APFixedPoint.h 13 KB

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