APFixedPoint.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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/SmallString.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. namespace llvm {
  26. class APFloat;
  27. struct fltSemantics;
  28. /// The fixed point semantics work similarly to fltSemantics. The width
  29. /// specifies the whole bit width of the underlying scaled integer (with padding
  30. /// if any). The scale represents the number of fractional bits in this type.
  31. /// When HasUnsignedPadding is true and this type is unsigned, the first bit
  32. /// in the value this represents is treated as padding.
  33. class FixedPointSemantics {
  34. public:
  35. FixedPointSemantics(unsigned Width, unsigned Scale, bool IsSigned,
  36. bool IsSaturated, bool HasUnsignedPadding)
  37. : Width(Width), Scale(Scale), IsSigned(IsSigned),
  38. IsSaturated(IsSaturated), HasUnsignedPadding(HasUnsignedPadding) {
  39. assert(Width >= Scale && "Not enough room for the scale");
  40. assert(!(IsSigned && HasUnsignedPadding) &&
  41. "Cannot have unsigned padding on a signed type.");
  42. }
  43. unsigned getWidth() const { return Width; }
  44. unsigned getScale() const { return Scale; }
  45. bool isSigned() const { return IsSigned; }
  46. bool isSaturated() const { return IsSaturated; }
  47. bool hasUnsignedPadding() const { return HasUnsignedPadding; }
  48. void setSaturated(bool Saturated) { IsSaturated = Saturated; }
  49. /// Return the number of integral bits represented by these semantics. These
  50. /// are separate from the fractional bits and do not include the sign or
  51. /// padding bit.
  52. unsigned getIntegralBits() const {
  53. if (IsSigned || (!IsSigned && HasUnsignedPadding))
  54. return Width - Scale - 1;
  55. else
  56. return Width - Scale;
  57. }
  58. /// Return the FixedPointSemantics that allows for calculating the full
  59. /// precision semantic that can precisely represent the precision and ranges
  60. /// of both input values. This does not compute the resulting semantics for a
  61. /// given binary operation.
  62. FixedPointSemantics
  63. getCommonSemantics(const FixedPointSemantics &Other) const;
  64. /// Returns true if this fixed-point semantic with its value bits interpreted
  65. /// as an integer can fit in the given floating point semantic without
  66. /// overflowing to infinity.
  67. /// For example, a signed 8-bit fixed-point semantic has a maximum and
  68. /// minimum integer representation of 127 and -128, respectively. If both of
  69. /// these values can be represented (possibly inexactly) in the floating
  70. /// point semantic without overflowing, this returns true.
  71. bool fitsInFloatSemantics(const fltSemantics &FloatSema) const;
  72. /// Return the FixedPointSemantics for an integer type.
  73. static FixedPointSemantics GetIntegerSemantics(unsigned Width,
  74. bool IsSigned) {
  75. return FixedPointSemantics(Width, /*Scale=*/0, IsSigned,
  76. /*IsSaturated=*/false,
  77. /*HasUnsignedPadding=*/false);
  78. }
  79. private:
  80. unsigned Width : 16;
  81. unsigned Scale : 13;
  82. unsigned IsSigned : 1;
  83. unsigned IsSaturated : 1;
  84. unsigned HasUnsignedPadding : 1;
  85. };
  86. /// The APFixedPoint class works similarly to APInt/APSInt in that it is a
  87. /// functional replacement for a scaled integer. It is meant to replicate the
  88. /// fixed point types proposed in ISO/IEC JTC1 SC22 WG14 N1169. The class carries
  89. /// info about the fixed point type's width, sign, scale, and saturation, and
  90. /// provides different operations that would normally be performed on fixed point
  91. /// types.
  92. class APFixedPoint {
  93. public:
  94. APFixedPoint(const APInt &Val, const FixedPointSemantics &Sema)
  95. : Val(Val, !Sema.isSigned()), Sema(Sema) {
  96. assert(Val.getBitWidth() == Sema.getWidth() &&
  97. "The value should have a bit width that matches the Sema width");
  98. }
  99. APFixedPoint(uint64_t Val, const FixedPointSemantics &Sema)
  100. : APFixedPoint(APInt(Sema.getWidth(), Val, Sema.isSigned()), Sema) {}
  101. // Zero initialization.
  102. APFixedPoint(const FixedPointSemantics &Sema) : APFixedPoint(0, Sema) {}
  103. APSInt getValue() const { return APSInt(Val, !Sema.isSigned()); }
  104. inline unsigned getWidth() const { return Sema.getWidth(); }
  105. inline unsigned getScale() const { return Sema.getScale(); }
  106. inline bool isSaturated() const { return Sema.isSaturated(); }
  107. inline bool isSigned() const { return Sema.isSigned(); }
  108. inline bool hasPadding() const { return Sema.hasUnsignedPadding(); }
  109. FixedPointSemantics getSemantics() const { return Sema; }
  110. bool getBoolValue() const { return Val.getBoolValue(); }
  111. // Convert this number to match the semantics provided. If the overflow
  112. // parameter is provided, set this value to true or false to indicate if this
  113. // operation results in an overflow.
  114. APFixedPoint convert(const FixedPointSemantics &DstSema,
  115. bool *Overflow = nullptr) const;
  116. // Perform binary operations on a fixed point type. The resulting fixed point
  117. // value will be in the common, full precision semantics that can represent
  118. // the precision and ranges of both input values. See convert() for an
  119. // explanation of the Overflow parameter.
  120. APFixedPoint add(const APFixedPoint &Other, bool *Overflow = nullptr) const;
  121. APFixedPoint sub(const APFixedPoint &Other, bool *Overflow = nullptr) const;
  122. APFixedPoint mul(const APFixedPoint &Other, bool *Overflow = nullptr) const;
  123. APFixedPoint div(const APFixedPoint &Other, bool *Overflow = nullptr) const;
  124. // Perform shift operations on a fixed point type. Unlike the other binary
  125. // operations, the resulting fixed point value will be in the original
  126. // semantic.
  127. APFixedPoint shl(unsigned Amt, bool *Overflow = nullptr) const;
  128. APFixedPoint shr(unsigned Amt, bool *Overflow = nullptr) const {
  129. // Right shift cannot overflow.
  130. if (Overflow)
  131. *Overflow = false;
  132. return APFixedPoint(Val >> Amt, Sema);
  133. }
  134. /// Perform a unary negation (-X) on this fixed point type, taking into
  135. /// account saturation if applicable.
  136. APFixedPoint negate(bool *Overflow = nullptr) const;
  137. /// Return the integral part of this fixed point number, rounded towards
  138. /// zero. (-2.5k -> -2)
  139. APSInt getIntPart() const {
  140. if (Val < 0 && Val != -Val) // Cover the case when we have the min val
  141. return -(-Val >> getScale());
  142. else
  143. return Val >> getScale();
  144. }
  145. /// Return the integral part of this fixed point number, rounded towards
  146. /// zero. The value is stored into an APSInt with the provided width and sign.
  147. /// If the overflow parameter is provided, and the integral value is not able
  148. /// to be fully stored in the provided width and sign, the overflow parameter
  149. /// is set to true.
  150. APSInt convertToInt(unsigned DstWidth, bool DstSign,
  151. bool *Overflow = nullptr) const;
  152. /// Convert this fixed point number to a floating point value with the
  153. /// provided semantics.
  154. APFloat convertToFloat(const fltSemantics &FloatSema) const;
  155. void toString(SmallVectorImpl<char> &Str) const;
  156. std::string toString() const {
  157. SmallString<40> S;
  158. toString(S);
  159. return std::string(S.str());
  160. }
  161. // If LHS > RHS, return 1. If LHS == RHS, return 0. If LHS < RHS, return -1.
  162. int compare(const APFixedPoint &Other) const;
  163. bool operator==(const APFixedPoint &Other) const {
  164. return compare(Other) == 0;
  165. }
  166. bool operator!=(const APFixedPoint &Other) const {
  167. return compare(Other) != 0;
  168. }
  169. bool operator>(const APFixedPoint &Other) const { return compare(Other) > 0; }
  170. bool operator<(const APFixedPoint &Other) const { return compare(Other) < 0; }
  171. bool operator>=(const APFixedPoint &Other) const {
  172. return compare(Other) >= 0;
  173. }
  174. bool operator<=(const APFixedPoint &Other) const {
  175. return compare(Other) <= 0;
  176. }
  177. static APFixedPoint getMax(const FixedPointSemantics &Sema);
  178. static APFixedPoint getMin(const FixedPointSemantics &Sema);
  179. /// Given a floating point semantic, return the next floating point semantic
  180. /// with a larger exponent and larger or equal mantissa.
  181. static const fltSemantics *promoteFloatSemantics(const fltSemantics *S);
  182. /// Create an APFixedPoint with a value equal to that of the provided integer,
  183. /// and in the same semantics as the provided target semantics. If the value
  184. /// is not able to fit in the specified fixed point semantics, and the
  185. /// overflow parameter is provided, it is set to true.
  186. static APFixedPoint getFromIntValue(const APSInt &Value,
  187. const FixedPointSemantics &DstFXSema,
  188. bool *Overflow = nullptr);
  189. /// Create an APFixedPoint with a value equal to that of the provided
  190. /// floating point value, in the provided target semantics. If the value is
  191. /// not able to fit in the specified fixed point semantics and the overflow
  192. /// parameter is specified, it is set to true.
  193. /// For NaN, the Overflow flag is always set. For +inf and -inf, if the
  194. /// semantic is saturating, the value saturates. Otherwise, the Overflow flag
  195. /// is set.
  196. static APFixedPoint getFromFloatValue(const APFloat &Value,
  197. const FixedPointSemantics &DstFXSema,
  198. bool *Overflow = nullptr);
  199. private:
  200. APSInt Val;
  201. FixedPointSemantics Sema;
  202. };
  203. inline raw_ostream &operator<<(raw_ostream &OS, const APFixedPoint &FX) {
  204. OS << FX.toString();
  205. return OS;
  206. }
  207. } // namespace llvm
  208. #endif
  209. #ifdef __GNUC__
  210. #pragma GCC diagnostic pop
  211. #endif