xref: /freebsd/contrib/llvm-project/llvm/include/llvm/ADT/APFixedPoint.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- APFixedPoint.h - Fixed point constant handling -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// Defines the fixed point number interface.
11 /// This is a class for abstracting various operations performed on fixed point
12 /// types.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_ADT_APFIXEDPOINT_H
17 #define LLVM_ADT_APFIXEDPOINT_H
18 
19 #include "llvm/ADT/APSInt.h"
20 #include "llvm/ADT/Hashing.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/raw_ostream.h"
24 
25 namespace llvm {
26 
27 class APFloat;
28 struct fltSemantics;
29 
30 /// The fixed point semantics work similarly to fltSemantics. The width
31 /// specifies the whole bit width of the underlying scaled integer (with padding
32 /// if any). The scale represents the number of fractional bits in this type.
33 /// When HasUnsignedPadding is true and this type is unsigned, the first bit
34 /// in the value this represents is treated as padding.
35 class FixedPointSemantics {
36 public:
37   static constexpr unsigned WidthBitWidth = 16;
38   static constexpr unsigned LsbWeightBitWidth = 13;
39   /// Used to differentiate between constructors with Width and Lsb from the
40   /// default Width and scale
41   struct Lsb {
42     int LsbWeight;
43   };
FixedPointSemantics(unsigned Width,unsigned Scale,bool IsSigned,bool IsSaturated,bool HasUnsignedPadding)44   FixedPointSemantics(unsigned Width, unsigned Scale, bool IsSigned,
45                       bool IsSaturated, bool HasUnsignedPadding)
46       : FixedPointSemantics(Width, Lsb{-static_cast<int>(Scale)}, IsSigned,
47                             IsSaturated, HasUnsignedPadding) {}
FixedPointSemantics(unsigned Width,Lsb Weight,bool IsSigned,bool IsSaturated,bool HasUnsignedPadding)48   FixedPointSemantics(unsigned Width, Lsb Weight, bool IsSigned,
49                       bool IsSaturated, bool HasUnsignedPadding)
50       : Width(Width), LsbWeight(Weight.LsbWeight), IsSigned(IsSigned),
51         IsSaturated(IsSaturated), HasUnsignedPadding(HasUnsignedPadding) {
52     assert(isUInt<WidthBitWidth>(Width) && isInt<LsbWeightBitWidth>(Weight.LsbWeight));
53     assert(!(IsSigned && HasUnsignedPadding) &&
54            "Cannot have unsigned padding on a signed type.");
55   }
56 
57   /// Check if the Semantic follow the requirements of an older more limited
58   /// version of this class
isValidLegacySema()59   bool isValidLegacySema() const {
60     return LsbWeight <= 0 && static_cast<int>(Width) >= -LsbWeight;
61   }
getWidth()62   unsigned getWidth() const { return Width; }
getScale()63   unsigned getScale() const { assert(isValidLegacySema()); return -LsbWeight; }
getLsbWeight()64   int getLsbWeight() const { return LsbWeight; }
getMsbWeight()65   int getMsbWeight() const {
66     return LsbWeight + Width - 1 /*Both lsb and msb are both part of width*/;
67   }
isSigned()68   bool isSigned() const { return IsSigned; }
isSaturated()69   bool isSaturated() const { return IsSaturated; }
hasUnsignedPadding()70   bool hasUnsignedPadding() const { return HasUnsignedPadding; }
71 
setSaturated(bool Saturated)72   void setSaturated(bool Saturated) { IsSaturated = Saturated; }
73 
74   /// return true if the first bit doesn't have a strictly positive weight
hasSignOrPaddingBit()75   bool hasSignOrPaddingBit() const { return IsSigned || HasUnsignedPadding; }
76 
77   /// Return the number of integral bits represented by these semantics. These
78   /// are separate from the fractional bits and do not include the sign or
79   /// padding bit.
getIntegralBits()80   unsigned getIntegralBits() const {
81     return std::max(getMsbWeight() + 1 - hasSignOrPaddingBit(), 0);
82   }
83 
84   /// Return the FixedPointSemantics that allows for calculating the full
85   /// precision semantic that can precisely represent the precision and ranges
86   /// of both input values. This does not compute the resulting semantics for a
87   /// given binary operation.
88   LLVM_ABI FixedPointSemantics
89   getCommonSemantics(const FixedPointSemantics &Other) const;
90 
91   /// Print semantics for debug purposes
92   LLVM_ABI void print(llvm::raw_ostream &OS) const;
93 
94   /// Returns true if this fixed-point semantic with its value bits interpreted
95   /// as an integer can fit in the given floating point semantic without
96   /// overflowing to infinity.
97   /// For example, a signed 8-bit fixed-point semantic has a maximum and
98   /// minimum integer representation of 127 and -128, respectively. If both of
99   /// these values can be represented (possibly inexactly) in the floating
100   /// point semantic without overflowing, this returns true.
101   LLVM_ABI bool fitsInFloatSemantics(const fltSemantics &FloatSema) const;
102 
103   /// Return the FixedPointSemantics for an integer type.
GetIntegerSemantics(unsigned Width,bool IsSigned)104   static FixedPointSemantics GetIntegerSemantics(unsigned Width,
105                                                  bool IsSigned) {
106     return FixedPointSemantics(Width, /*Scale=*/0, IsSigned,
107                                /*IsSaturated=*/false,
108                                /*HasUnsignedPadding=*/false);
109   }
110 
111   bool operator==(FixedPointSemantics Other) const {
112     return Width == Other.Width && LsbWeight == Other.LsbWeight &&
113            IsSigned == Other.IsSigned && IsSaturated == Other.IsSaturated &&
114            HasUnsignedPadding == Other.HasUnsignedPadding;
115   }
116   bool operator!=(FixedPointSemantics Other) const { return !(*this == Other); }
117 
118   /// Convert the semantics to a 32-bit unsigned integer.
119   /// The result is dependent on the host endianness and not stable across LLVM
120   /// versions. See getFromOpaqueInt() to convert it back to a
121   /// FixedPointSemantics object.
122   LLVM_ABI uint32_t toOpaqueInt() const;
123   /// Create a FixedPointSemantics object from an integer created via
124   /// toOpaqueInt().
125   LLVM_ABI static FixedPointSemantics getFromOpaqueInt(uint32_t);
126 
127 private:
128   unsigned Width          : WidthBitWidth;
129   signed int LsbWeight    : LsbWeightBitWidth;
130   unsigned IsSigned       : 1;
131   unsigned IsSaturated    : 1;
132   unsigned HasUnsignedPadding : 1;
133 };
134 
135 static_assert(sizeof(FixedPointSemantics) == 4, "");
136 
hash_value(const FixedPointSemantics & Val)137 inline hash_code hash_value(const FixedPointSemantics &Val) {
138   return hash_value(bit_cast<uint32_t>(Val));
139 }
140 
141 template <> struct DenseMapInfo<FixedPointSemantics> {
142   static inline FixedPointSemantics getEmptyKey() {
143     return FixedPointSemantics(0, 0, false, false, false);
144   }
145 
146   static inline FixedPointSemantics getTombstoneKey() {
147     return FixedPointSemantics(0, 1, false, false, false);
148   }
149 
150   static unsigned getHashValue(const FixedPointSemantics &Val) {
151     return hash_value(Val);
152   }
153 
154   static bool isEqual(const char &LHS, const char &RHS) { return LHS == RHS; }
155 };
156 
157 /// The APFixedPoint class works similarly to APInt/APSInt in that it is a
158 /// functional replacement for a scaled integer. It supports a wide range of
159 /// semantics including the one used by fixed point types proposed in ISO/IEC
160 /// JTC1 SC22 WG14 N1169. The class carries the value and semantics of
161 /// a fixed point, and provides different operations that would normally be
162 /// performed on fixed point types.
163 class APFixedPoint {
164 public:
165   APFixedPoint(const APInt &Val, const FixedPointSemantics &Sema)
166       : Val(Val, !Sema.isSigned()), Sema(Sema) {
167     assert(Val.getBitWidth() == Sema.getWidth() &&
168            "The value should have a bit width that matches the Sema width");
169   }
170 
171   APFixedPoint(uint64_t Val, const FixedPointSemantics &Sema)
172       : APFixedPoint(APInt(Sema.getWidth(), Val, Sema.isSigned(),
173                            /*implicitTrunc=*/true),
174                      Sema) {}
175 
176   // Zero initialization.
177   APFixedPoint(const FixedPointSemantics &Sema) : APFixedPoint(0, Sema) {}
178 
179   APSInt getValue() const { return APSInt(Val, !Sema.isSigned()); }
180   inline unsigned getWidth() const { return Sema.getWidth(); }
181   inline unsigned getScale() const { return Sema.getScale(); }
182   int getLsbWeight() const { return Sema.getLsbWeight(); }
183   int getMsbWeight() const { return Sema.getMsbWeight(); }
184   inline bool isSaturated() const { return Sema.isSaturated(); }
185   inline bool isSigned() const { return Sema.isSigned(); }
186   inline bool hasPadding() const { return Sema.hasUnsignedPadding(); }
187   FixedPointSemantics getSemantics() const { return Sema; }
188 
189   bool getBoolValue() const { return Val.getBoolValue(); }
190 
191   // Convert this number to match the semantics provided. If the overflow
192   // parameter is provided, set this value to true or false to indicate if this
193   // operation results in an overflow.
194   LLVM_ABI APFixedPoint convert(const FixedPointSemantics &DstSema,
195                                 bool *Overflow = nullptr) const;
196 
197   // Perform binary operations on a fixed point type. The resulting fixed point
198   // value will be in the common, full precision semantics that can represent
199   // the precision and ranges of both input values. See convert() for an
200   // explanation of the Overflow parameter.
201   LLVM_ABI APFixedPoint add(const APFixedPoint &Other,
202                             bool *Overflow = nullptr) const;
203   LLVM_ABI APFixedPoint sub(const APFixedPoint &Other,
204                             bool *Overflow = nullptr) const;
205   LLVM_ABI APFixedPoint mul(const APFixedPoint &Other,
206                             bool *Overflow = nullptr) const;
207   LLVM_ABI APFixedPoint div(const APFixedPoint &Other,
208                             bool *Overflow = nullptr) const;
209 
210   // Perform shift operations on a fixed point type. Unlike the other binary
211   // operations, the resulting fixed point value will be in the original
212   // semantic.
213   LLVM_ABI APFixedPoint shl(unsigned Amt, bool *Overflow = nullptr) const;
214   APFixedPoint shr(unsigned Amt, bool *Overflow = nullptr) const {
215     // Right shift cannot overflow.
216     if (Overflow)
217       *Overflow = false;
218     return APFixedPoint(Val >> Amt, Sema);
219   }
220 
221   /// Perform a unary negation (-X) on this fixed point type, taking into
222   /// account saturation if applicable.
223   LLVM_ABI APFixedPoint negate(bool *Overflow = nullptr) const;
224 
225   /// Return the integral part of this fixed point number, rounded towards
226   /// zero. (-2.5k -> -2)
227   APSInt getIntPart() const {
228     if (getMsbWeight() < 0)
229       return APSInt(APInt::getZero(getWidth()), Val.isUnsigned());
230     APSInt ExtVal =
231         (getLsbWeight() > 0) ? Val.extend(getWidth() + getLsbWeight()) : Val;
232     if (Val < 0 && Val != -Val) // Cover the case when we have the min val
233       return -((-ExtVal).relativeShl(getLsbWeight()));
234     return ExtVal.relativeShl(getLsbWeight());
235   }
236 
237   /// Return the integral part of this fixed point number, rounded towards
238   /// zero. The value is stored into an APSInt with the provided width and sign.
239   /// If the overflow parameter is provided, and the integral value is not able
240   /// to be fully stored in the provided width and sign, the overflow parameter
241   /// is set to true.
242   LLVM_ABI APSInt convertToInt(unsigned DstWidth, bool DstSign,
243                                bool *Overflow = nullptr) const;
244 
245   /// Convert this fixed point number to a floating point value with the
246   /// provided semantics.
247   LLVM_ABI APFloat convertToFloat(const fltSemantics &FloatSema) const;
248 
249   LLVM_ABI void toString(SmallVectorImpl<char> &Str) const;
250   std::string toString() const {
251     SmallString<40> S;
252     toString(S);
253     return std::string(S);
254   }
255 
256   LLVM_ABI void print(raw_ostream &) const;
257 
258 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
259   LLVM_DUMP_METHOD void dump() const;
260 #endif
261 
262   // If LHS > RHS, return 1. If LHS == RHS, return 0. If LHS < RHS, return -1.
263   LLVM_ABI int compare(const APFixedPoint &Other) const;
264   bool operator==(const APFixedPoint &Other) const {
265     return compare(Other) == 0;
266   }
267   bool operator!=(const APFixedPoint &Other) const {
268     return compare(Other) != 0;
269   }
270   bool operator>(const APFixedPoint &Other) const { return compare(Other) > 0; }
271   bool operator<(const APFixedPoint &Other) const { return compare(Other) < 0; }
272   bool operator>=(const APFixedPoint &Other) const {
273     return compare(Other) >= 0;
274   }
275   bool operator<=(const APFixedPoint &Other) const {
276     return compare(Other) <= 0;
277   }
278 
279   LLVM_ABI static APFixedPoint getMax(const FixedPointSemantics &Sema);
280   LLVM_ABI static APFixedPoint getMin(const FixedPointSemantics &Sema);
281   LLVM_ABI static APFixedPoint getEpsilon(const FixedPointSemantics &Sema);
282 
283   /// Given a floating point semantic, return the next floating point semantic
284   /// with a larger exponent and larger or equal mantissa.
285   LLVM_ABI static const fltSemantics *
286   promoteFloatSemantics(const fltSemantics *S);
287 
288   /// Create an APFixedPoint with a value equal to that of the provided integer,
289   /// and in the same semantics as the provided target semantics. If the value
290   /// is not able to fit in the specified fixed point semantics, and the
291   /// overflow parameter is provided, it is set to true.
292   LLVM_ABI static APFixedPoint
293   getFromIntValue(const APSInt &Value, const FixedPointSemantics &DstFXSema,
294                   bool *Overflow = nullptr);
295 
296   /// Create an APFixedPoint with a value equal to that of the provided
297   /// floating point value, in the provided target semantics. If the value is
298   /// not able to fit in the specified fixed point semantics and the overflow
299   /// parameter is specified, it is set to true.
300   /// For NaN, the Overflow flag is always set. For +inf and -inf, if the
301   /// semantic is saturating, the value saturates. Otherwise, the Overflow flag
302   /// is set.
303   LLVM_ABI static APFixedPoint
304   getFromFloatValue(const APFloat &Value, const FixedPointSemantics &DstFXSema,
305                     bool *Overflow = nullptr);
306 
307 private:
308   APSInt Val;
309   FixedPointSemantics Sema;
310 };
311 
312 inline raw_ostream &operator<<(raw_ostream &OS, const APFixedPoint &FX) {
313   OS << FX.toString();
314   return OS;
315 }
316 
317 inline hash_code hash_value(const APFixedPoint &Val) {
318   return hash_combine(Val.getSemantics(), Val.getValue());
319 }
320 
321 template <> struct DenseMapInfo<APFixedPoint> {
322   static inline APFixedPoint getEmptyKey() {
323     return APFixedPoint(DenseMapInfo<FixedPointSemantics>::getEmptyKey());
324   }
325 
326   static inline APFixedPoint getTombstoneKey() {
327     return APFixedPoint(DenseMapInfo<FixedPointSemantics>::getTombstoneKey());
328   }
329 
330   static unsigned getHashValue(const APFixedPoint &Val) {
331     return hash_value(Val);
332   }
333 
334   static bool isEqual(const APFixedPoint &LHS, const APFixedPoint &RHS) {
335     return LHS.getSemantics() == RHS.getSemantics() &&
336            LHS.getValue() == RHS.getValue();
337   }
338 };
339 
340 } // namespace llvm
341 
342 #endif
343