Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

466 lines
19 KiB

  1. //== llvm/Support/APFloat.h - Arbitrary Precision Floating Point -*- C++ -*-==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file declares a class to represent arbitrary precision floating
  11. // point values and provide a variety of arithmetic operations on them.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. /* A self-contained host- and target-independent arbitrary-precision
  15. floating-point software implementation. It uses bignum integer
  16. arithmetic as provided by static functions in the APInt class.
  17. The library will work with bignum integers whose parts are any
  18. unsigned type at least 16 bits wide, but 64 bits is recommended.
  19. Written for clarity rather than speed, in particular with a view
  20. to use in the front-end of a cross compiler so that target
  21. arithmetic can be correctly performed on the host. Performance
  22. should nonetheless be reasonable, particularly for its intended
  23. use. It may be useful as a base implementation for a run-time
  24. library during development of a faster target-specific one.
  25. All 5 rounding modes in the IEEE-754R draft are handled correctly
  26. for all implemented operations. Currently implemented operations
  27. are add, subtract, multiply, divide, fused-multiply-add,
  28. conversion-to-float, conversion-to-integer and
  29. conversion-from-integer. New rounding modes (e.g. away from zero)
  30. can be added with three or four lines of code.
  31. Four formats are built-in: IEEE single precision, double
  32. precision, quadruple precision, and x87 80-bit extended double
  33. (when operating with full extended precision). Adding a new
  34. format that obeys IEEE semantics only requires adding two lines of
  35. code: a declaration and definition of the format.
  36. All operations return the status of that operation as an exception
  37. bit-mask, so multiple operations can be done consecutively with
  38. their results or-ed together. The returned status can be useful
  39. for compiler diagnostics; e.g., inexact, underflow and overflow
  40. can be easily diagnosed on constant folding, and compiler
  41. optimizers can determine what exceptions would be raised by
  42. folding operations and optimize, or perhaps not optimize,
  43. accordingly.
  44. At present, underflow tininess is detected after rounding; it
  45. should be straight forward to add support for the before-rounding
  46. case too.
  47. The library reads hexadecimal floating point numbers as per C99,
  48. and correctly rounds if necessary according to the specified
  49. rounding mode. Syntax is required to have been validated by the
  50. caller. It also converts floating point numbers to hexadecimal
  51. text as per the C99 %a and %A conversions. The output precision
  52. (or alternatively the natural minimal precision) can be specified;
  53. if the requested precision is less than the natural precision the
  54. output is correctly rounded for the specified rounding mode.
  55. It also reads decimal floating point numbers and correctly rounds
  56. according to the specified rounding mode.
  57. Conversion to decimal text is not currently implemented.
  58. Non-zero finite numbers are represented internally as a sign bit,
  59. a 16-bit signed exponent, and the significand as an array of
  60. integer parts. After normalization of a number of precision P the
  61. exponent is within the range of the format, and if the number is
  62. not denormal the P-th bit of the significand is set as an explicit
  63. integer bit. For denormals the most significant bit is shifted
  64. right so that the exponent is maintained at the format's minimum,
  65. so that the smallest denormal has just the least significant bit
  66. of the significand set. The sign of zeroes and infinities is
  67. significant; the exponent and significand of such numbers is not
  68. stored, but has a known implicit (deterministic) value: 0 for the
  69. significands, 0 for zero exponent, all 1 bits for infinity
  70. exponent. For NaNs the sign and significand are deterministic,
  71. although not really meaningful, and preserved in non-conversion
  72. operations. The exponent is implicitly all 1 bits.
  73. TODO
  74. ====
  75. Some features that may or may not be worth adding:
  76. Binary to decimal conversion (hard).
  77. Optional ability to detect underflow tininess before rounding.
  78. New formats: x87 in single and double precision mode (IEEE apart
  79. from extended exponent range) (hard).
  80. New operations: sqrt, IEEE remainder, C90 fmod, nextafter,
  81. nexttoward.
  82. */
  83. #ifndef LLVM_ADT_APFLOAT_H
  84. #define LLVM_ADT_APFLOAT_H
  85. // APInt contains static functions implementing bignum arithmetic.
  86. #include "llvm/ADT/APInt.h"
  87. namespace llvm {
  88. /* Exponents are stored as signed numbers. */
  89. typedef signed short exponent_t;
  90. struct fltSemantics;
  91. class APSInt;
  92. class StringRef;
  93. /* When bits of a floating point number are truncated, this enum is
  94. used to indicate what fraction of the LSB those bits represented.
  95. It essentially combines the roles of guard and sticky bits. */
  96. enum lostFraction { // Example of truncated bits:
  97. lfExactlyZero, // 000000
  98. lfLessThanHalf, // 0xxxxx x's not all zero
  99. lfExactlyHalf, // 100000
  100. lfMoreThanHalf // 1xxxxx x's not all zero
  101. };
  102. class APFloat {
  103. public:
  104. /* We support the following floating point semantics. */
  105. static const fltSemantics IEEEhalf;
  106. static const fltSemantics IEEEsingle;
  107. static const fltSemantics IEEEdouble;
  108. static const fltSemantics IEEEquad;
  109. static const fltSemantics PPCDoubleDouble;
  110. static const fltSemantics x87DoubleExtended;
  111. /* And this pseudo, used to construct APFloats that cannot
  112. conflict with anything real. */
  113. static const fltSemantics Bogus;
  114. static unsigned int semanticsPrecision(const fltSemantics &);
  115. /* Floating point numbers have a four-state comparison relation. */
  116. enum cmpResult {
  117. cmpLessThan,
  118. cmpEqual,
  119. cmpGreaterThan,
  120. cmpUnordered
  121. };
  122. /* IEEE-754R gives five rounding modes. */
  123. enum roundingMode {
  124. rmNearestTiesToEven,
  125. rmTowardPositive,
  126. rmTowardNegative,
  127. rmTowardZero,
  128. rmNearestTiesToAway
  129. };
  130. // Operation status. opUnderflow or opOverflow are always returned
  131. // or-ed with opInexact.
  132. enum opStatus {
  133. opOK = 0x00,
  134. opInvalidOp = 0x01,
  135. opDivByZero = 0x02,
  136. opOverflow = 0x04,
  137. opUnderflow = 0x08,
  138. opInexact = 0x10
  139. };
  140. // Category of internally-represented number.
  141. enum fltCategory {
  142. fcInfinity,
  143. fcNaN,
  144. fcNormal,
  145. fcZero
  146. };
  147. enum uninitializedTag {
  148. uninitialized
  149. };
  150. // Constructors.
  151. APFloat(const fltSemantics &); // Default construct to 0.0
  152. APFloat(const fltSemantics &, StringRef);
  153. APFloat(const fltSemantics &, integerPart);
  154. APFloat(const fltSemantics &, fltCategory, bool negative);
  155. APFloat(const fltSemantics &, uninitializedTag);
  156. APFloat(const fltSemantics &, const APInt &);
  157. explicit APFloat(double d);
  158. explicit APFloat(float f);
  159. APFloat(const APFloat &);
  160. ~APFloat();
  161. // Convenience "constructors"
  162. static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
  163. return APFloat(Sem, fcZero, Negative);
  164. }
  165. static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
  166. return APFloat(Sem, fcInfinity, Negative);
  167. }
  168. /// getNaN - Factory for QNaN values.
  169. ///
  170. /// \param Negative - True iff the NaN generated should be negative.
  171. /// \param type - The unspecified fill bits for creating the NaN, 0 by
  172. /// default. The value is truncated as necessary.
  173. static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
  174. unsigned type = 0) {
  175. if (type) {
  176. APInt fill(64, type);
  177. return getQNaN(Sem, Negative, &fill);
  178. } else {
  179. return getQNaN(Sem, Negative, 0);
  180. }
  181. }
  182. /// getQNan - Factory for QNaN values.
  183. static APFloat getQNaN(const fltSemantics &Sem,
  184. bool Negative = false,
  185. const APInt *payload = 0) {
  186. return makeNaN(Sem, false, Negative, payload);
  187. }
  188. /// getSNan - Factory for SNaN values.
  189. static APFloat getSNaN(const fltSemantics &Sem,
  190. bool Negative = false,
  191. const APInt *payload = 0) {
  192. return makeNaN(Sem, true, Negative, payload);
  193. }
  194. /// getLargest - Returns the largest finite number in the given
  195. /// semantics.
  196. ///
  197. /// \param Negative - True iff the number should be negative
  198. static APFloat getLargest(const fltSemantics &Sem, bool Negative = false);
  199. /// getSmallest - Returns the smallest (by magnitude) finite number
  200. /// in the given semantics. Might be denormalized, which implies a
  201. /// relative loss of precision.
  202. ///
  203. /// \param Negative - True iff the number should be negative
  204. static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false);
  205. /// getSmallestNormalized - Returns the smallest (by magnitude)
  206. /// normalized finite number in the given semantics.
  207. ///
  208. /// \param Negative - True iff the number should be negative
  209. static APFloat getSmallestNormalized(const fltSemantics &Sem,
  210. bool Negative = false);
  211. /// getAllOnesValue - Returns a float which is bitcasted from
  212. /// an all one value int.
  213. ///
  214. /// \param BitWidth - Select float type
  215. /// \param isIEEE - If 128 bit number, select between PPC and IEEE
  216. static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false);
  217. /// Profile - Used to insert APFloat objects, or objects that contain
  218. /// APFloat objects, into FoldingSets.
  219. void Profile(FoldingSetNodeID& NID) const;
  220. /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
  221. void Emit(Serializer& S) const;
  222. /// @brief Used by the Bitcode deserializer to deserialize APInts.
  223. static APFloat ReadVal(Deserializer& D);
  224. /* Arithmetic. */
  225. opStatus add(const APFloat &, roundingMode);
  226. opStatus subtract(const APFloat &, roundingMode);
  227. opStatus multiply(const APFloat &, roundingMode);
  228. opStatus divide(const APFloat &, roundingMode);
  229. /* IEEE remainder. */
  230. opStatus remainder(const APFloat &);
  231. /* C fmod, or llvm frem. */
  232. opStatus mod(const APFloat &, roundingMode);
  233. opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
  234. opStatus roundToIntegral(roundingMode);
  235. /* Sign operations. */
  236. void changeSign();
  237. void clearSign();
  238. void copySign(const APFloat &);
  239. /* Conversions. */
  240. opStatus convert(const fltSemantics &, roundingMode, bool *);
  241. opStatus convertToInteger(integerPart *, unsigned int, bool,
  242. roundingMode, bool *) const;
  243. opStatus convertToInteger(APSInt&, roundingMode, bool *) const;
  244. opStatus convertFromAPInt(const APInt &,
  245. bool, roundingMode);
  246. opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
  247. bool, roundingMode);
  248. opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
  249. bool, roundingMode);
  250. opStatus convertFromString(StringRef, roundingMode);
  251. APInt bitcastToAPInt() const;
  252. double convertToDouble() const;
  253. float convertToFloat() const;
  254. /* The definition of equality is not straightforward for floating point,
  255. so we won't use operator==. Use one of the following, or write
  256. whatever it is you really mean. */
  257. bool operator==(const APFloat &) const LLVM_DELETED_FUNCTION;
  258. /* IEEE comparison with another floating point number (NaNs
  259. compare unordered, 0==-0). */
  260. cmpResult compare(const APFloat &) const;
  261. /* Bitwise comparison for equality (QNaNs compare equal, 0!=-0). */
  262. bool bitwiseIsEqual(const APFloat &) const;
  263. /* Write out a hexadecimal representation of the floating point
  264. value to DST, which must be of sufficient size, in the C99 form
  265. [-]0xh.hhhhp[+-]d. Return the number of characters written,
  266. excluding the terminating NUL. */
  267. unsigned int convertToHexString(char *dst, unsigned int hexDigits,
  268. bool upperCase, roundingMode) const;
  269. /* Simple queries. */
  270. fltCategory getCategory() const { return category; }
  271. const fltSemantics &getSemantics() const { return *semantics; }
  272. bool isZero() const { return category == fcZero; }
  273. bool isNonZero() const { return category != fcZero; }
  274. bool isNormal() const { return category == fcNormal; }
  275. bool isNaN() const { return category == fcNaN; }
  276. bool isInfinity() const { return category == fcInfinity; }
  277. bool isNegative() const { return sign; }
  278. bool isPosZero() const { return isZero() && !isNegative(); }
  279. bool isNegZero() const { return isZero() && isNegative(); }
  280. bool isDenormal() const;
  281. APFloat& operator=(const APFloat &);
  282. /// \brief Overload to compute a hash code for an APFloat value.
  283. ///
  284. /// Note that the use of hash codes for floating point values is in general
  285. /// frought with peril. Equality is hard to define for these values. For
  286. /// example, should negative and positive zero hash to different codes? Are
  287. /// they equal or not? This hash value implementation specifically
  288. /// emphasizes producing different codes for different inputs in order to
  289. /// be used in canonicalization and memoization. As such, equality is
  290. /// bitwiseIsEqual, and 0 != -0.
  291. friend hash_code hash_value(const APFloat &Arg);
  292. /// Converts this value into a decimal string.
  293. ///
  294. /// \param FormatPrecision The maximum number of digits of
  295. /// precision to output. If there are fewer digits available,
  296. /// zero padding will not be used unless the value is
  297. /// integral and small enough to be expressed in
  298. /// FormatPrecision digits. 0 means to use the natural
  299. /// precision of the number.
  300. /// \param FormatMaxPadding The maximum number of zeros to
  301. /// consider inserting before falling back to scientific
  302. /// notation. 0 means to always use scientific notation.
  303. ///
  304. /// Number Precision MaxPadding Result
  305. /// ------ --------- ---------- ------
  306. /// 1.01E+4 5 2 10100
  307. /// 1.01E+4 4 2 1.01E+4
  308. /// 1.01E+4 5 1 1.01E+4
  309. /// 1.01E-2 5 2 0.0101
  310. /// 1.01E-2 4 2 0.0101
  311. /// 1.01E-2 4 1 1.01E-2
  312. void toString(SmallVectorImpl<char> &Str,
  313. unsigned FormatPrecision = 0,
  314. unsigned FormatMaxPadding = 3) const;
  315. /// getExactInverse - If this value has an exact multiplicative inverse,
  316. /// store it in inv and return true.
  317. bool getExactInverse(APFloat *inv) const;
  318. private:
  319. /* Trivial queries. */
  320. integerPart *significandParts();
  321. const integerPart *significandParts() const;
  322. unsigned int partCount() const;
  323. /* Significand operations. */
  324. integerPart addSignificand(const APFloat &);
  325. integerPart subtractSignificand(const APFloat &, integerPart);
  326. lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
  327. lostFraction multiplySignificand(const APFloat &, const APFloat *);
  328. lostFraction divideSignificand(const APFloat &);
  329. void incrementSignificand();
  330. void initialize(const fltSemantics *);
  331. void shiftSignificandLeft(unsigned int);
  332. lostFraction shiftSignificandRight(unsigned int);
  333. unsigned int significandLSB() const;
  334. unsigned int significandMSB() const;
  335. void zeroSignificand();
  336. /* Arithmetic on special values. */
  337. opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
  338. opStatus divideSpecials(const APFloat &);
  339. opStatus multiplySpecials(const APFloat &);
  340. opStatus modSpecials(const APFloat &);
  341. /* Miscellany. */
  342. static APFloat makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
  343. const APInt *fill);
  344. void makeNaN(bool SNaN = false, bool Neg = false, const APInt *fill = 0);
  345. opStatus normalize(roundingMode, lostFraction);
  346. opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
  347. cmpResult compareAbsoluteValue(const APFloat &) const;
  348. opStatus handleOverflow(roundingMode);
  349. bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
  350. opStatus convertToSignExtendedInteger(integerPart *, unsigned int, bool,
  351. roundingMode, bool *) const;
  352. opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
  353. roundingMode);
  354. opStatus convertFromHexadecimalString(StringRef, roundingMode);
  355. opStatus convertFromDecimalString(StringRef, roundingMode);
  356. char *convertNormalToHexString(char *, unsigned int, bool,
  357. roundingMode) const;
  358. opStatus roundSignificandWithExponent(const integerPart *, unsigned int,
  359. int, roundingMode);
  360. APInt convertHalfAPFloatToAPInt() const;
  361. APInt convertFloatAPFloatToAPInt() const;
  362. APInt convertDoubleAPFloatToAPInt() const;
  363. APInt convertQuadrupleAPFloatToAPInt() const;
  364. APInt convertF80LongDoubleAPFloatToAPInt() const;
  365. APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
  366. void initFromAPInt(const fltSemantics *Sem, const APInt& api);
  367. void initFromHalfAPInt(const APInt& api);
  368. void initFromFloatAPInt(const APInt& api);
  369. void initFromDoubleAPInt(const APInt& api);
  370. void initFromQuadrupleAPInt(const APInt &api);
  371. void initFromF80LongDoubleAPInt(const APInt& api);
  372. void initFromPPCDoubleDoubleAPInt(const APInt& api);
  373. void assign(const APFloat &);
  374. void copySignificand(const APFloat &);
  375. void freeSignificand();
  376. /* What kind of semantics does this value obey? */
  377. const fltSemantics *semantics;
  378. /* Significand - the fraction with an explicit integer bit. Must be
  379. at least one bit wider than the target precision. */
  380. union Significand
  381. {
  382. integerPart part;
  383. integerPart *parts;
  384. } significand;
  385. /* The exponent - a signed number. */
  386. exponent_t exponent;
  387. /* What kind of floating point number this is. */
  388. /* Only 2 bits are required, but VisualStudio incorrectly sign extends
  389. it. Using the extra bit keeps it from failing under VisualStudio */
  390. fltCategory category: 3;
  391. /* The sign bit of this number. */
  392. unsigned int sign: 1;
  393. };
  394. // See friend declaration above. This additional declaration is required in
  395. // order to compile LLVM with IBM xlC compiler.
  396. hash_code hash_value(const APFloat &Arg);
  397. } /* namespace llvm */
  398. #endif /* LLVM_ADT_APFLOAT_H */