APFloat.h 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/APFloat.h - Arbitrary Precision Floating Point ---*- 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. /// \brief
  16. /// This file declares a class to represent arbitrary precision floating point
  17. /// values and provide a variety of arithmetic operations on them.
  18. ///
  19. //===----------------------------------------------------------------------===//
  20. #ifndef LLVM_ADT_APFLOAT_H
  21. #define LLVM_ADT_APFLOAT_H
  22. #include "llvm/ADT/APInt.h"
  23. #include "llvm/ADT/ArrayRef.h"
  24. #include "llvm/ADT/FloatingPointMode.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include <memory>
  27. #define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
  28. do { \
  29. if (usesLayout<IEEEFloat>(getSemantics())) \
  30. return U.IEEE.METHOD_CALL; \
  31. if (usesLayout<DoubleAPFloat>(getSemantics())) \
  32. return U.Double.METHOD_CALL; \
  33. llvm_unreachable("Unexpected semantics"); \
  34. } while (false)
  35. namespace llvm {
  36. struct fltSemantics;
  37. class APSInt;
  38. class StringRef;
  39. class APFloat;
  40. class raw_ostream;
  41. template <typename T> class Expected;
  42. template <typename T> class SmallVectorImpl;
  43. /// Enum that represents what fraction of the LSB truncated bits of an fp number
  44. /// represent.
  45. ///
  46. /// This essentially combines the roles of guard and sticky bits.
  47. enum lostFraction { // Example of truncated bits:
  48. lfExactlyZero, // 000000
  49. lfLessThanHalf, // 0xxxxx x's not all zero
  50. lfExactlyHalf, // 100000
  51. lfMoreThanHalf // 1xxxxx x's not all zero
  52. };
  53. /// A self-contained host- and target-independent arbitrary-precision
  54. /// floating-point software implementation.
  55. ///
  56. /// APFloat uses bignum integer arithmetic as provided by static functions in
  57. /// the APInt class. The library will work with bignum integers whose parts are
  58. /// any unsigned type at least 16 bits wide, but 64 bits is recommended.
  59. ///
  60. /// Written for clarity rather than speed, in particular with a view to use in
  61. /// the front-end of a cross compiler so that target arithmetic can be correctly
  62. /// performed on the host. Performance should nonetheless be reasonable,
  63. /// particularly for its intended use. It may be useful as a base
  64. /// implementation for a run-time library during development of a faster
  65. /// target-specific one.
  66. ///
  67. /// All 5 rounding modes in the IEEE-754R draft are handled correctly for all
  68. /// implemented operations. Currently implemented operations are add, subtract,
  69. /// multiply, divide, fused-multiply-add, conversion-to-float,
  70. /// conversion-to-integer and conversion-from-integer. New rounding modes
  71. /// (e.g. away from zero) can be added with three or four lines of code.
  72. ///
  73. /// Four formats are built-in: IEEE single precision, double precision,
  74. /// quadruple precision, and x87 80-bit extended double (when operating with
  75. /// full extended precision). Adding a new format that obeys IEEE semantics
  76. /// only requires adding two lines of code: a declaration and definition of the
  77. /// format.
  78. ///
  79. /// All operations return the status of that operation as an exception bit-mask,
  80. /// so multiple operations can be done consecutively with their results or-ed
  81. /// together. The returned status can be useful for compiler diagnostics; e.g.,
  82. /// inexact, underflow and overflow can be easily diagnosed on constant folding,
  83. /// and compiler optimizers can determine what exceptions would be raised by
  84. /// folding operations and optimize, or perhaps not optimize, accordingly.
  85. ///
  86. /// At present, underflow tininess is detected after rounding; it should be
  87. /// straight forward to add support for the before-rounding case too.
  88. ///
  89. /// The library reads hexadecimal floating point numbers as per C99, and
  90. /// correctly rounds if necessary according to the specified rounding mode.
  91. /// Syntax is required to have been validated by the caller. It also converts
  92. /// floating point numbers to hexadecimal text as per the C99 %a and %A
  93. /// conversions. The output precision (or alternatively the natural minimal
  94. /// precision) can be specified; if the requested precision is less than the
  95. /// natural precision the output is correctly rounded for the specified rounding
  96. /// mode.
  97. ///
  98. /// It also reads decimal floating point numbers and correctly rounds according
  99. /// to the specified rounding mode.
  100. ///
  101. /// Conversion to decimal text is not currently implemented.
  102. ///
  103. /// Non-zero finite numbers are represented internally as a sign bit, a 16-bit
  104. /// signed exponent, and the significand as an array of integer parts. After
  105. /// normalization of a number of precision P the exponent is within the range of
  106. /// the format, and if the number is not denormal the P-th bit of the
  107. /// significand is set as an explicit integer bit. For denormals the most
  108. /// significant bit is shifted right so that the exponent is maintained at the
  109. /// format's minimum, so that the smallest denormal has just the least
  110. /// significant bit of the significand set. The sign of zeroes and infinities
  111. /// is significant; the exponent and significand of such numbers is not stored,
  112. /// but has a known implicit (deterministic) value: 0 for the significands, 0
  113. /// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and
  114. /// significand are deterministic, although not really meaningful, and preserved
  115. /// in non-conversion operations. The exponent is implicitly all 1 bits.
  116. ///
  117. /// APFloat does not provide any exception handling beyond default exception
  118. /// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause
  119. /// by encoding Signaling NaNs with the first bit of its trailing significand as
  120. /// 0.
  121. ///
  122. /// TODO
  123. /// ====
  124. ///
  125. /// Some features that may or may not be worth adding:
  126. ///
  127. /// Binary to decimal conversion (hard).
  128. ///
  129. /// Optional ability to detect underflow tininess before rounding.
  130. ///
  131. /// New formats: x87 in single and double precision mode (IEEE apart from
  132. /// extended exponent range) (hard).
  133. ///
  134. /// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward.
  135. ///
  136. // This is the common type definitions shared by APFloat and its internal
  137. // implementation classes. This struct should not define any non-static data
  138. // members.
  139. struct APFloatBase {
  140. typedef APInt::WordType integerPart;
  141. static constexpr unsigned integerPartWidth = APInt::APINT_BITS_PER_WORD;
  142. /// A signed type to represent a floating point numbers unbiased exponent.
  143. typedef int32_t ExponentType;
  144. /// \name Floating Point Semantics.
  145. /// @{
  146. enum Semantics {
  147. S_IEEEhalf,
  148. S_BFloat,
  149. S_IEEEsingle,
  150. S_IEEEdouble,
  151. S_x87DoubleExtended,
  152. S_IEEEquad,
  153. S_PPCDoubleDouble
  154. };
  155. static const llvm::fltSemantics &EnumToSemantics(Semantics S);
  156. static Semantics SemanticsToEnum(const llvm::fltSemantics &Sem);
  157. static const fltSemantics &IEEEhalf() LLVM_READNONE;
  158. static const fltSemantics &BFloat() LLVM_READNONE;
  159. static const fltSemantics &IEEEsingle() LLVM_READNONE;
  160. static const fltSemantics &IEEEdouble() LLVM_READNONE;
  161. static const fltSemantics &IEEEquad() LLVM_READNONE;
  162. static const fltSemantics &PPCDoubleDouble() LLVM_READNONE;
  163. static const fltSemantics &x87DoubleExtended() LLVM_READNONE;
  164. /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with
  165. /// anything real.
  166. static const fltSemantics &Bogus() LLVM_READNONE;
  167. /// @}
  168. /// IEEE-754R 5.11: Floating Point Comparison Relations.
  169. enum cmpResult {
  170. cmpLessThan,
  171. cmpEqual,
  172. cmpGreaterThan,
  173. cmpUnordered
  174. };
  175. /// IEEE-754R 4.3: Rounding-direction attributes.
  176. using roundingMode = llvm::RoundingMode;
  177. static constexpr roundingMode rmNearestTiesToEven =
  178. RoundingMode::NearestTiesToEven;
  179. static constexpr roundingMode rmTowardPositive = RoundingMode::TowardPositive;
  180. static constexpr roundingMode rmTowardNegative = RoundingMode::TowardNegative;
  181. static constexpr roundingMode rmTowardZero = RoundingMode::TowardZero;
  182. static constexpr roundingMode rmNearestTiesToAway =
  183. RoundingMode::NearestTiesToAway;
  184. /// IEEE-754R 7: Default exception handling.
  185. ///
  186. /// opUnderflow or opOverflow are always returned or-ed with opInexact.
  187. ///
  188. /// APFloat models this behavior specified by IEEE-754:
  189. /// "For operations producing results in floating-point format, the default
  190. /// result of an operation that signals the invalid operation exception
  191. /// shall be a quiet NaN."
  192. enum opStatus {
  193. opOK = 0x00,
  194. opInvalidOp = 0x01,
  195. opDivByZero = 0x02,
  196. opOverflow = 0x04,
  197. opUnderflow = 0x08,
  198. opInexact = 0x10
  199. };
  200. /// Category of internally-represented number.
  201. enum fltCategory {
  202. fcInfinity,
  203. fcNaN,
  204. fcNormal,
  205. fcZero
  206. };
  207. /// Convenience enum used to construct an uninitialized APFloat.
  208. enum uninitializedTag {
  209. uninitialized
  210. };
  211. /// Enumeration of \c ilogb error results.
  212. enum IlogbErrorKinds {
  213. IEK_Zero = INT_MIN + 1,
  214. IEK_NaN = INT_MIN,
  215. IEK_Inf = INT_MAX
  216. };
  217. static unsigned int semanticsPrecision(const fltSemantics &);
  218. static ExponentType semanticsMinExponent(const fltSemantics &);
  219. static ExponentType semanticsMaxExponent(const fltSemantics &);
  220. static unsigned int semanticsSizeInBits(const fltSemantics &);
  221. /// Returns the size of the floating point number (in bits) in the given
  222. /// semantics.
  223. static unsigned getSizeInBits(const fltSemantics &Sem);
  224. };
  225. namespace detail {
  226. class IEEEFloat final : public APFloatBase {
  227. public:
  228. /// \name Constructors
  229. /// @{
  230. IEEEFloat(const fltSemantics &); // Default construct to +0.0
  231. IEEEFloat(const fltSemantics &, integerPart);
  232. IEEEFloat(const fltSemantics &, uninitializedTag);
  233. IEEEFloat(const fltSemantics &, const APInt &);
  234. explicit IEEEFloat(double d);
  235. explicit IEEEFloat(float f);
  236. IEEEFloat(const IEEEFloat &);
  237. IEEEFloat(IEEEFloat &&);
  238. ~IEEEFloat();
  239. /// @}
  240. /// Returns whether this instance allocated memory.
  241. bool needsCleanup() const { return partCount() > 1; }
  242. /// \name Convenience "constructors"
  243. /// @{
  244. /// @}
  245. /// \name Arithmetic
  246. /// @{
  247. opStatus add(const IEEEFloat &, roundingMode);
  248. opStatus subtract(const IEEEFloat &, roundingMode);
  249. opStatus multiply(const IEEEFloat &, roundingMode);
  250. opStatus divide(const IEEEFloat &, roundingMode);
  251. /// IEEE remainder.
  252. opStatus remainder(const IEEEFloat &);
  253. /// C fmod, or llvm frem.
  254. opStatus mod(const IEEEFloat &);
  255. opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode);
  256. opStatus roundToIntegral(roundingMode);
  257. /// IEEE-754R 5.3.1: nextUp/nextDown.
  258. opStatus next(bool nextDown);
  259. /// @}
  260. /// \name Sign operations.
  261. /// @{
  262. void changeSign();
  263. /// @}
  264. /// \name Conversions
  265. /// @{
  266. opStatus convert(const fltSemantics &, roundingMode, bool *);
  267. opStatus convertToInteger(MutableArrayRef<integerPart>, unsigned int, bool,
  268. roundingMode, bool *) const;
  269. opStatus convertFromAPInt(const APInt &, bool, roundingMode);
  270. opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
  271. bool, roundingMode);
  272. opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
  273. bool, roundingMode);
  274. Expected<opStatus> convertFromString(StringRef, roundingMode);
  275. APInt bitcastToAPInt() const;
  276. double convertToDouble() const;
  277. float convertToFloat() const;
  278. /// @}
  279. /// The definition of equality is not straightforward for floating point, so
  280. /// we won't use operator==. Use one of the following, or write whatever it
  281. /// is you really mean.
  282. bool operator==(const IEEEFloat &) const = delete;
  283. /// IEEE comparison with another floating point number (NaNs compare
  284. /// unordered, 0==-0).
  285. cmpResult compare(const IEEEFloat &) const;
  286. /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
  287. bool bitwiseIsEqual(const IEEEFloat &) const;
  288. /// Write out a hexadecimal representation of the floating point value to DST,
  289. /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d.
  290. /// Return the number of characters written, excluding the terminating NUL.
  291. unsigned int convertToHexString(char *dst, unsigned int hexDigits,
  292. bool upperCase, roundingMode) const;
  293. /// \name IEEE-754R 5.7.2 General operations.
  294. /// @{
  295. /// IEEE-754R isSignMinus: Returns true if and only if the current value is
  296. /// negative.
  297. ///
  298. /// This applies to zeros and NaNs as well.
  299. bool isNegative() const { return sign; }
  300. /// IEEE-754R isNormal: Returns true if and only if the current value is normal.
  301. ///
  302. /// This implies that the current value of the float is not zero, subnormal,
  303. /// infinite, or NaN following the definition of normality from IEEE-754R.
  304. bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
  305. /// Returns true if and only if the current value is zero, subnormal, or
  306. /// normal.
  307. ///
  308. /// This means that the value is not infinite or NaN.
  309. bool isFinite() const { return !isNaN() && !isInfinity(); }
  310. /// Returns true if and only if the float is plus or minus zero.
  311. bool isZero() const { return category == fcZero; }
  312. /// IEEE-754R isSubnormal(): Returns true if and only if the float is a
  313. /// denormal.
  314. bool isDenormal() const;
  315. /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
  316. bool isInfinity() const { return category == fcInfinity; }
  317. /// Returns true if and only if the float is a quiet or signaling NaN.
  318. bool isNaN() const { return category == fcNaN; }
  319. /// Returns true if and only if the float is a signaling NaN.
  320. bool isSignaling() const;
  321. /// @}
  322. /// \name Simple Queries
  323. /// @{
  324. fltCategory getCategory() const { return category; }
  325. const fltSemantics &getSemantics() const { return *semantics; }
  326. bool isNonZero() const { return category != fcZero; }
  327. bool isFiniteNonZero() const { return isFinite() && !isZero(); }
  328. bool isPosZero() const { return isZero() && !isNegative(); }
  329. bool isNegZero() const { return isZero() && isNegative(); }
  330. /// Returns true if and only if the number has the smallest possible non-zero
  331. /// magnitude in the current semantics.
  332. bool isSmallest() const;
  333. /// Returns true if and only if the number has the largest possible finite
  334. /// magnitude in the current semantics.
  335. bool isLargest() const;
  336. /// Returns true if and only if the number is an exact integer.
  337. bool isInteger() const;
  338. /// @}
  339. IEEEFloat &operator=(const IEEEFloat &);
  340. IEEEFloat &operator=(IEEEFloat &&);
  341. /// Overload to compute a hash code for an APFloat value.
  342. ///
  343. /// Note that the use of hash codes for floating point values is in general
  344. /// frought with peril. Equality is hard to define for these values. For
  345. /// example, should negative and positive zero hash to different codes? Are
  346. /// they equal or not? This hash value implementation specifically
  347. /// emphasizes producing different codes for different inputs in order to
  348. /// be used in canonicalization and memoization. As such, equality is
  349. /// bitwiseIsEqual, and 0 != -0.
  350. friend hash_code hash_value(const IEEEFloat &Arg);
  351. /// Converts this value into a decimal string.
  352. ///
  353. /// \param FormatPrecision The maximum number of digits of
  354. /// precision to output. If there are fewer digits available,
  355. /// zero padding will not be used unless the value is
  356. /// integral and small enough to be expressed in
  357. /// FormatPrecision digits. 0 means to use the natural
  358. /// precision of the number.
  359. /// \param FormatMaxPadding The maximum number of zeros to
  360. /// consider inserting before falling back to scientific
  361. /// notation. 0 means to always use scientific notation.
  362. ///
  363. /// \param TruncateZero Indicate whether to remove the trailing zero in
  364. /// fraction part or not. Also setting this parameter to false forcing
  365. /// producing of output more similar to default printf behavior.
  366. /// Specifically the lower e is used as exponent delimiter and exponent
  367. /// always contains no less than two digits.
  368. ///
  369. /// Number Precision MaxPadding Result
  370. /// ------ --------- ---------- ------
  371. /// 1.01E+4 5 2 10100
  372. /// 1.01E+4 4 2 1.01E+4
  373. /// 1.01E+4 5 1 1.01E+4
  374. /// 1.01E-2 5 2 0.0101
  375. /// 1.01E-2 4 2 0.0101
  376. /// 1.01E-2 4 1 1.01E-2
  377. void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
  378. unsigned FormatMaxPadding = 3, bool TruncateZero = true) const;
  379. /// If this value has an exact multiplicative inverse, store it in inv and
  380. /// return true.
  381. bool getExactInverse(APFloat *inv) const;
  382. /// Returns the exponent of the internal representation of the APFloat.
  383. ///
  384. /// Because the radix of APFloat is 2, this is equivalent to floor(log2(x)).
  385. /// For special APFloat values, this returns special error codes:
  386. ///
  387. /// NaN -> \c IEK_NaN
  388. /// 0 -> \c IEK_Zero
  389. /// Inf -> \c IEK_Inf
  390. ///
  391. friend int ilogb(const IEEEFloat &Arg);
  392. /// Returns: X * 2^Exp for integral exponents.
  393. friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode);
  394. friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode);
  395. /// \name Special value setters.
  396. /// @{
  397. void makeLargest(bool Neg = false);
  398. void makeSmallest(bool Neg = false);
  399. void makeNaN(bool SNaN = false, bool Neg = false,
  400. const APInt *fill = nullptr);
  401. void makeInf(bool Neg = false);
  402. void makeZero(bool Neg = false);
  403. void makeQuiet();
  404. /// Returns the smallest (by magnitude) normalized finite number in the given
  405. /// semantics.
  406. ///
  407. /// \param Negative - True iff the number should be negative
  408. void makeSmallestNormalized(bool Negative = false);
  409. /// @}
  410. cmpResult compareAbsoluteValue(const IEEEFloat &) const;
  411. private:
  412. /// \name Simple Queries
  413. /// @{
  414. integerPart *significandParts();
  415. const integerPart *significandParts() const;
  416. unsigned int partCount() const;
  417. /// @}
  418. /// \name Significand operations.
  419. /// @{
  420. integerPart addSignificand(const IEEEFloat &);
  421. integerPart subtractSignificand(const IEEEFloat &, integerPart);
  422. lostFraction addOrSubtractSignificand(const IEEEFloat &, bool subtract);
  423. lostFraction multiplySignificand(const IEEEFloat &, IEEEFloat);
  424. lostFraction multiplySignificand(const IEEEFloat&);
  425. lostFraction divideSignificand(const IEEEFloat &);
  426. void incrementSignificand();
  427. void initialize(const fltSemantics *);
  428. void shiftSignificandLeft(unsigned int);
  429. lostFraction shiftSignificandRight(unsigned int);
  430. unsigned int significandLSB() const;
  431. unsigned int significandMSB() const;
  432. void zeroSignificand();
  433. /// Return true if the significand excluding the integral bit is all ones.
  434. bool isSignificandAllOnes() const;
  435. /// Return true if the significand excluding the integral bit is all zeros.
  436. bool isSignificandAllZeros() const;
  437. /// @}
  438. /// \name Arithmetic on special values.
  439. /// @{
  440. opStatus addOrSubtractSpecials(const IEEEFloat &, bool subtract);
  441. opStatus divideSpecials(const IEEEFloat &);
  442. opStatus multiplySpecials(const IEEEFloat &);
  443. opStatus modSpecials(const IEEEFloat &);
  444. opStatus remainderSpecials(const IEEEFloat&);
  445. /// @}
  446. /// \name Miscellany
  447. /// @{
  448. bool convertFromStringSpecials(StringRef str);
  449. opStatus normalize(roundingMode, lostFraction);
  450. opStatus addOrSubtract(const IEEEFloat &, roundingMode, bool subtract);
  451. opStatus handleOverflow(roundingMode);
  452. bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
  453. opStatus convertToSignExtendedInteger(MutableArrayRef<integerPart>,
  454. unsigned int, bool, roundingMode,
  455. bool *) const;
  456. opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
  457. roundingMode);
  458. Expected<opStatus> convertFromHexadecimalString(StringRef, roundingMode);
  459. Expected<opStatus> convertFromDecimalString(StringRef, roundingMode);
  460. char *convertNormalToHexString(char *, unsigned int, bool,
  461. roundingMode) const;
  462. opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
  463. roundingMode);
  464. ExponentType exponentNaN() const;
  465. ExponentType exponentInf() const;
  466. ExponentType exponentZero() const;
  467. /// @}
  468. APInt convertHalfAPFloatToAPInt() const;
  469. APInt convertBFloatAPFloatToAPInt() const;
  470. APInt convertFloatAPFloatToAPInt() const;
  471. APInt convertDoubleAPFloatToAPInt() const;
  472. APInt convertQuadrupleAPFloatToAPInt() const;
  473. APInt convertF80LongDoubleAPFloatToAPInt() const;
  474. APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
  475. void initFromAPInt(const fltSemantics *Sem, const APInt &api);
  476. void initFromHalfAPInt(const APInt &api);
  477. void initFromBFloatAPInt(const APInt &api);
  478. void initFromFloatAPInt(const APInt &api);
  479. void initFromDoubleAPInt(const APInt &api);
  480. void initFromQuadrupleAPInt(const APInt &api);
  481. void initFromF80LongDoubleAPInt(const APInt &api);
  482. void initFromPPCDoubleDoubleAPInt(const APInt &api);
  483. void assign(const IEEEFloat &);
  484. void copySignificand(const IEEEFloat &);
  485. void freeSignificand();
  486. /// Note: this must be the first data member.
  487. /// The semantics that this value obeys.
  488. const fltSemantics *semantics;
  489. /// A binary fraction with an explicit integer bit.
  490. ///
  491. /// The significand must be at least one bit wider than the target precision.
  492. union Significand {
  493. integerPart part;
  494. integerPart *parts;
  495. } significand;
  496. /// The signed unbiased exponent of the value.
  497. ExponentType exponent;
  498. /// What kind of floating point number this is.
  499. ///
  500. /// Only 2 bits are required, but VisualStudio incorrectly sign extends it.
  501. /// Using the extra bit keeps it from failing under VisualStudio.
  502. fltCategory category : 3;
  503. /// Sign bit of the number.
  504. unsigned int sign : 1;
  505. };
  506. hash_code hash_value(const IEEEFloat &Arg);
  507. int ilogb(const IEEEFloat &Arg);
  508. IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode);
  509. IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM);
  510. // This mode implements more precise float in terms of two APFloats.
  511. // The interface and layout is designed for arbitrary underlying semantics,
  512. // though currently only PPCDoubleDouble semantics are supported, whose
  513. // corresponding underlying semantics are IEEEdouble.
  514. class DoubleAPFloat final : public APFloatBase {
  515. // Note: this must be the first data member.
  516. const fltSemantics *Semantics;
  517. std::unique_ptr<APFloat[]> Floats;
  518. opStatus addImpl(const APFloat &a, const APFloat &aa, const APFloat &c,
  519. const APFloat &cc, roundingMode RM);
  520. opStatus addWithSpecial(const DoubleAPFloat &LHS, const DoubleAPFloat &RHS,
  521. DoubleAPFloat &Out, roundingMode RM);
  522. public:
  523. DoubleAPFloat(const fltSemantics &S);
  524. DoubleAPFloat(const fltSemantics &S, uninitializedTag);
  525. DoubleAPFloat(const fltSemantics &S, integerPart);
  526. DoubleAPFloat(const fltSemantics &S, const APInt &I);
  527. DoubleAPFloat(const fltSemantics &S, APFloat &&First, APFloat &&Second);
  528. DoubleAPFloat(const DoubleAPFloat &RHS);
  529. DoubleAPFloat(DoubleAPFloat &&RHS);
  530. DoubleAPFloat &operator=(const DoubleAPFloat &RHS);
  531. DoubleAPFloat &operator=(DoubleAPFloat &&RHS) {
  532. if (this != &RHS) {
  533. this->~DoubleAPFloat();
  534. new (this) DoubleAPFloat(std::move(RHS));
  535. }
  536. return *this;
  537. }
  538. bool needsCleanup() const { return Floats != nullptr; }
  539. APFloat &getFirst() { return Floats[0]; }
  540. const APFloat &getFirst() const { return Floats[0]; }
  541. APFloat &getSecond() { return Floats[1]; }
  542. const APFloat &getSecond() const { return Floats[1]; }
  543. opStatus add(const DoubleAPFloat &RHS, roundingMode RM);
  544. opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM);
  545. opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM);
  546. opStatus divide(const DoubleAPFloat &RHS, roundingMode RM);
  547. opStatus remainder(const DoubleAPFloat &RHS);
  548. opStatus mod(const DoubleAPFloat &RHS);
  549. opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
  550. const DoubleAPFloat &Addend, roundingMode RM);
  551. opStatus roundToIntegral(roundingMode RM);
  552. void changeSign();
  553. cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const;
  554. fltCategory getCategory() const;
  555. bool isNegative() const;
  556. void makeInf(bool Neg);
  557. void makeZero(bool Neg);
  558. void makeLargest(bool Neg);
  559. void makeSmallest(bool Neg);
  560. void makeSmallestNormalized(bool Neg);
  561. void makeNaN(bool SNaN, bool Neg, const APInt *fill);
  562. cmpResult compare(const DoubleAPFloat &RHS) const;
  563. bool bitwiseIsEqual(const DoubleAPFloat &RHS) const;
  564. APInt bitcastToAPInt() const;
  565. Expected<opStatus> convertFromString(StringRef, roundingMode);
  566. opStatus next(bool nextDown);
  567. opStatus convertToInteger(MutableArrayRef<integerPart> Input,
  568. unsigned int Width, bool IsSigned, roundingMode RM,
  569. bool *IsExact) const;
  570. opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM);
  571. opStatus convertFromSignExtendedInteger(const integerPart *Input,
  572. unsigned int InputSize, bool IsSigned,
  573. roundingMode RM);
  574. opStatus convertFromZeroExtendedInteger(const integerPart *Input,
  575. unsigned int InputSize, bool IsSigned,
  576. roundingMode RM);
  577. unsigned int convertToHexString(char *DST, unsigned int HexDigits,
  578. bool UpperCase, roundingMode RM) const;
  579. bool isDenormal() const;
  580. bool isSmallest() const;
  581. bool isLargest() const;
  582. bool isInteger() const;
  583. void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
  584. unsigned FormatMaxPadding, bool TruncateZero = true) const;
  585. bool getExactInverse(APFloat *inv) const;
  586. friend int ilogb(const DoubleAPFloat &Arg);
  587. friend DoubleAPFloat scalbn(DoubleAPFloat X, int Exp, roundingMode);
  588. friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp, roundingMode);
  589. friend hash_code hash_value(const DoubleAPFloat &Arg);
  590. };
  591. hash_code hash_value(const DoubleAPFloat &Arg);
  592. } // End detail namespace
  593. // This is a interface class that is currently forwarding functionalities from
  594. // detail::IEEEFloat.
  595. class APFloat : public APFloatBase {
  596. typedef detail::IEEEFloat IEEEFloat;
  597. typedef detail::DoubleAPFloat DoubleAPFloat;
  598. static_assert(std::is_standard_layout<IEEEFloat>::value, "");
  599. union Storage {
  600. const fltSemantics *semantics;
  601. IEEEFloat IEEE;
  602. DoubleAPFloat Double;
  603. explicit Storage(IEEEFloat F, const fltSemantics &S);
  604. explicit Storage(DoubleAPFloat F, const fltSemantics &S)
  605. : Double(std::move(F)) {
  606. assert(&S == &PPCDoubleDouble());
  607. }
  608. template <typename... ArgTypes>
  609. Storage(const fltSemantics &Semantics, ArgTypes &&... Args) {
  610. if (usesLayout<IEEEFloat>(Semantics)) {
  611. new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...);
  612. return;
  613. }
  614. if (usesLayout<DoubleAPFloat>(Semantics)) {
  615. new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
  616. return;
  617. }
  618. llvm_unreachable("Unexpected semantics");
  619. }
  620. ~Storage() {
  621. if (usesLayout<IEEEFloat>(*semantics)) {
  622. IEEE.~IEEEFloat();
  623. return;
  624. }
  625. if (usesLayout<DoubleAPFloat>(*semantics)) {
  626. Double.~DoubleAPFloat();
  627. return;
  628. }
  629. llvm_unreachable("Unexpected semantics");
  630. }
  631. Storage(const Storage &RHS) {
  632. if (usesLayout<IEEEFloat>(*RHS.semantics)) {
  633. new (this) IEEEFloat(RHS.IEEE);
  634. return;
  635. }
  636. if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
  637. new (this) DoubleAPFloat(RHS.Double);
  638. return;
  639. }
  640. llvm_unreachable("Unexpected semantics");
  641. }
  642. Storage(Storage &&RHS) {
  643. if (usesLayout<IEEEFloat>(*RHS.semantics)) {
  644. new (this) IEEEFloat(std::move(RHS.IEEE));
  645. return;
  646. }
  647. if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
  648. new (this) DoubleAPFloat(std::move(RHS.Double));
  649. return;
  650. }
  651. llvm_unreachable("Unexpected semantics");
  652. }
  653. Storage &operator=(const Storage &RHS) {
  654. if (usesLayout<IEEEFloat>(*semantics) &&
  655. usesLayout<IEEEFloat>(*RHS.semantics)) {
  656. IEEE = RHS.IEEE;
  657. } else if (usesLayout<DoubleAPFloat>(*semantics) &&
  658. usesLayout<DoubleAPFloat>(*RHS.semantics)) {
  659. Double = RHS.Double;
  660. } else if (this != &RHS) {
  661. this->~Storage();
  662. new (this) Storage(RHS);
  663. }
  664. return *this;
  665. }
  666. Storage &operator=(Storage &&RHS) {
  667. if (usesLayout<IEEEFloat>(*semantics) &&
  668. usesLayout<IEEEFloat>(*RHS.semantics)) {
  669. IEEE = std::move(RHS.IEEE);
  670. } else if (usesLayout<DoubleAPFloat>(*semantics) &&
  671. usesLayout<DoubleAPFloat>(*RHS.semantics)) {
  672. Double = std::move(RHS.Double);
  673. } else if (this != &RHS) {
  674. this->~Storage();
  675. new (this) Storage(std::move(RHS));
  676. }
  677. return *this;
  678. }
  679. } U;
  680. template <typename T> static bool usesLayout(const fltSemantics &Semantics) {
  681. static_assert(std::is_same<T, IEEEFloat>::value ||
  682. std::is_same<T, DoubleAPFloat>::value, "");
  683. if (std::is_same<T, DoubleAPFloat>::value) {
  684. return &Semantics == &PPCDoubleDouble();
  685. }
  686. return &Semantics != &PPCDoubleDouble();
  687. }
  688. IEEEFloat &getIEEE() {
  689. if (usesLayout<IEEEFloat>(*U.semantics))
  690. return U.IEEE;
  691. if (usesLayout<DoubleAPFloat>(*U.semantics))
  692. return U.Double.getFirst().U.IEEE;
  693. llvm_unreachable("Unexpected semantics");
  694. }
  695. const IEEEFloat &getIEEE() const {
  696. if (usesLayout<IEEEFloat>(*U.semantics))
  697. return U.IEEE;
  698. if (usesLayout<DoubleAPFloat>(*U.semantics))
  699. return U.Double.getFirst().U.IEEE;
  700. llvm_unreachable("Unexpected semantics");
  701. }
  702. void makeZero(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeZero(Neg)); }
  703. void makeInf(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeInf(Neg)); }
  704. void makeNaN(bool SNaN, bool Neg, const APInt *fill) {
  705. APFLOAT_DISPATCH_ON_SEMANTICS(makeNaN(SNaN, Neg, fill));
  706. }
  707. void makeLargest(bool Neg) {
  708. APFLOAT_DISPATCH_ON_SEMANTICS(makeLargest(Neg));
  709. }
  710. void makeSmallest(bool Neg) {
  711. APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallest(Neg));
  712. }
  713. void makeSmallestNormalized(bool Neg) {
  714. APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallestNormalized(Neg));
  715. }
  716. // FIXME: This is due to clang 3.3 (or older version) always checks for the
  717. // default constructor in an array aggregate initialization, even if no
  718. // elements in the array is default initialized.
  719. APFloat() : U(IEEEdouble()) {
  720. llvm_unreachable("This is a workaround for old clang.");
  721. }
  722. explicit APFloat(IEEEFloat F, const fltSemantics &S) : U(std::move(F), S) {}
  723. explicit APFloat(DoubleAPFloat F, const fltSemantics &S)
  724. : U(std::move(F), S) {}
  725. cmpResult compareAbsoluteValue(const APFloat &RHS) const {
  726. assert(&getSemantics() == &RHS.getSemantics() &&
  727. "Should only compare APFloats with the same semantics");
  728. if (usesLayout<IEEEFloat>(getSemantics()))
  729. return U.IEEE.compareAbsoluteValue(RHS.U.IEEE);
  730. if (usesLayout<DoubleAPFloat>(getSemantics()))
  731. return U.Double.compareAbsoluteValue(RHS.U.Double);
  732. llvm_unreachable("Unexpected semantics");
  733. }
  734. public:
  735. APFloat(const fltSemantics &Semantics) : U(Semantics) {}
  736. APFloat(const fltSemantics &Semantics, StringRef S);
  737. APFloat(const fltSemantics &Semantics, integerPart I) : U(Semantics, I) {}
  738. template <typename T,
  739. typename = std::enable_if_t<std::is_floating_point<T>::value>>
  740. APFloat(const fltSemantics &Semantics, T V) = delete;
  741. // TODO: Remove this constructor. This isn't faster than the first one.
  742. APFloat(const fltSemantics &Semantics, uninitializedTag)
  743. : U(Semantics, uninitialized) {}
  744. APFloat(const fltSemantics &Semantics, const APInt &I) : U(Semantics, I) {}
  745. explicit APFloat(double d) : U(IEEEFloat(d), IEEEdouble()) {}
  746. explicit APFloat(float f) : U(IEEEFloat(f), IEEEsingle()) {}
  747. APFloat(const APFloat &RHS) = default;
  748. APFloat(APFloat &&RHS) = default;
  749. ~APFloat() = default;
  750. bool needsCleanup() const { APFLOAT_DISPATCH_ON_SEMANTICS(needsCleanup()); }
  751. /// Factory for Positive and Negative Zero.
  752. ///
  753. /// \param Negative True iff the number should be negative.
  754. static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
  755. APFloat Val(Sem, uninitialized);
  756. Val.makeZero(Negative);
  757. return Val;
  758. }
  759. /// Factory for Positive and Negative Infinity.
  760. ///
  761. /// \param Negative True iff the number should be negative.
  762. static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
  763. APFloat Val(Sem, uninitialized);
  764. Val.makeInf(Negative);
  765. return Val;
  766. }
  767. /// Factory for NaN values.
  768. ///
  769. /// \param Negative - True iff the NaN generated should be negative.
  770. /// \param payload - The unspecified fill bits for creating the NaN, 0 by
  771. /// default. The value is truncated as necessary.
  772. static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
  773. uint64_t payload = 0) {
  774. if (payload) {
  775. APInt intPayload(64, payload);
  776. return getQNaN(Sem, Negative, &intPayload);
  777. } else {
  778. return getQNaN(Sem, Negative, nullptr);
  779. }
  780. }
  781. /// Factory for QNaN values.
  782. static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false,
  783. const APInt *payload = nullptr) {
  784. APFloat Val(Sem, uninitialized);
  785. Val.makeNaN(false, Negative, payload);
  786. return Val;
  787. }
  788. /// Factory for SNaN values.
  789. static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false,
  790. const APInt *payload = nullptr) {
  791. APFloat Val(Sem, uninitialized);
  792. Val.makeNaN(true, Negative, payload);
  793. return Val;
  794. }
  795. /// Returns the largest finite number in the given semantics.
  796. ///
  797. /// \param Negative - True iff the number should be negative
  798. static APFloat getLargest(const fltSemantics &Sem, bool Negative = false) {
  799. APFloat Val(Sem, uninitialized);
  800. Val.makeLargest(Negative);
  801. return Val;
  802. }
  803. /// Returns the smallest (by magnitude) finite number in the given semantics.
  804. /// Might be denormalized, which implies a relative loss of precision.
  805. ///
  806. /// \param Negative - True iff the number should be negative
  807. static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false) {
  808. APFloat Val(Sem, uninitialized);
  809. Val.makeSmallest(Negative);
  810. return Val;
  811. }
  812. /// Returns the smallest (by magnitude) normalized finite number in the given
  813. /// semantics.
  814. ///
  815. /// \param Negative - True iff the number should be negative
  816. static APFloat getSmallestNormalized(const fltSemantics &Sem,
  817. bool Negative = false) {
  818. APFloat Val(Sem, uninitialized);
  819. Val.makeSmallestNormalized(Negative);
  820. return Val;
  821. }
  822. /// Returns a float which is bitcasted from an all one value int.
  823. ///
  824. /// \param Semantics - type float semantics
  825. /// \param BitWidth - Select float type
  826. static APFloat getAllOnesValue(const fltSemantics &Semantics,
  827. unsigned BitWidth);
  828. /// Used to insert APFloat objects, or objects that contain APFloat objects,
  829. /// into FoldingSets.
  830. void Profile(FoldingSetNodeID &NID) const;
  831. opStatus add(const APFloat &RHS, roundingMode RM) {
  832. assert(&getSemantics() == &RHS.getSemantics() &&
  833. "Should only call on two APFloats with the same semantics");
  834. if (usesLayout<IEEEFloat>(getSemantics()))
  835. return U.IEEE.add(RHS.U.IEEE, RM);
  836. if (usesLayout<DoubleAPFloat>(getSemantics()))
  837. return U.Double.add(RHS.U.Double, RM);
  838. llvm_unreachable("Unexpected semantics");
  839. }
  840. opStatus subtract(const APFloat &RHS, roundingMode RM) {
  841. assert(&getSemantics() == &RHS.getSemantics() &&
  842. "Should only call on two APFloats with the same semantics");
  843. if (usesLayout<IEEEFloat>(getSemantics()))
  844. return U.IEEE.subtract(RHS.U.IEEE, RM);
  845. if (usesLayout<DoubleAPFloat>(getSemantics()))
  846. return U.Double.subtract(RHS.U.Double, RM);
  847. llvm_unreachable("Unexpected semantics");
  848. }
  849. opStatus multiply(const APFloat &RHS, roundingMode RM) {
  850. assert(&getSemantics() == &RHS.getSemantics() &&
  851. "Should only call on two APFloats with the same semantics");
  852. if (usesLayout<IEEEFloat>(getSemantics()))
  853. return U.IEEE.multiply(RHS.U.IEEE, RM);
  854. if (usesLayout<DoubleAPFloat>(getSemantics()))
  855. return U.Double.multiply(RHS.U.Double, RM);
  856. llvm_unreachable("Unexpected semantics");
  857. }
  858. opStatus divide(const APFloat &RHS, roundingMode RM) {
  859. assert(&getSemantics() == &RHS.getSemantics() &&
  860. "Should only call on two APFloats with the same semantics");
  861. if (usesLayout<IEEEFloat>(getSemantics()))
  862. return U.IEEE.divide(RHS.U.IEEE, RM);
  863. if (usesLayout<DoubleAPFloat>(getSemantics()))
  864. return U.Double.divide(RHS.U.Double, RM);
  865. llvm_unreachable("Unexpected semantics");
  866. }
  867. opStatus remainder(const APFloat &RHS) {
  868. assert(&getSemantics() == &RHS.getSemantics() &&
  869. "Should only call on two APFloats with the same semantics");
  870. if (usesLayout<IEEEFloat>(getSemantics()))
  871. return U.IEEE.remainder(RHS.U.IEEE);
  872. if (usesLayout<DoubleAPFloat>(getSemantics()))
  873. return U.Double.remainder(RHS.U.Double);
  874. llvm_unreachable("Unexpected semantics");
  875. }
  876. opStatus mod(const APFloat &RHS) {
  877. assert(&getSemantics() == &RHS.getSemantics() &&
  878. "Should only call on two APFloats with the same semantics");
  879. if (usesLayout<IEEEFloat>(getSemantics()))
  880. return U.IEEE.mod(RHS.U.IEEE);
  881. if (usesLayout<DoubleAPFloat>(getSemantics()))
  882. return U.Double.mod(RHS.U.Double);
  883. llvm_unreachable("Unexpected semantics");
  884. }
  885. opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend,
  886. roundingMode RM) {
  887. assert(&getSemantics() == &Multiplicand.getSemantics() &&
  888. "Should only call on APFloats with the same semantics");
  889. assert(&getSemantics() == &Addend.getSemantics() &&
  890. "Should only call on APFloats with the same semantics");
  891. if (usesLayout<IEEEFloat>(getSemantics()))
  892. return U.IEEE.fusedMultiplyAdd(Multiplicand.U.IEEE, Addend.U.IEEE, RM);
  893. if (usesLayout<DoubleAPFloat>(getSemantics()))
  894. return U.Double.fusedMultiplyAdd(Multiplicand.U.Double, Addend.U.Double,
  895. RM);
  896. llvm_unreachable("Unexpected semantics");
  897. }
  898. opStatus roundToIntegral(roundingMode RM) {
  899. APFLOAT_DISPATCH_ON_SEMANTICS(roundToIntegral(RM));
  900. }
  901. // TODO: bool parameters are not readable and a source of bugs.
  902. // Do something.
  903. opStatus next(bool nextDown) {
  904. APFLOAT_DISPATCH_ON_SEMANTICS(next(nextDown));
  905. }
  906. /// Negate an APFloat.
  907. APFloat operator-() const {
  908. APFloat Result(*this);
  909. Result.changeSign();
  910. return Result;
  911. }
  912. /// Add two APFloats, rounding ties to the nearest even.
  913. /// No error checking.
  914. APFloat operator+(const APFloat &RHS) const {
  915. APFloat Result(*this);
  916. (void)Result.add(RHS, rmNearestTiesToEven);
  917. return Result;
  918. }
  919. /// Subtract two APFloats, rounding ties to the nearest even.
  920. /// No error checking.
  921. APFloat operator-(const APFloat &RHS) const {
  922. APFloat Result(*this);
  923. (void)Result.subtract(RHS, rmNearestTiesToEven);
  924. return Result;
  925. }
  926. /// Multiply two APFloats, rounding ties to the nearest even.
  927. /// No error checking.
  928. APFloat operator*(const APFloat &RHS) const {
  929. APFloat Result(*this);
  930. (void)Result.multiply(RHS, rmNearestTiesToEven);
  931. return Result;
  932. }
  933. /// Divide the first APFloat by the second, rounding ties to the nearest even.
  934. /// No error checking.
  935. APFloat operator/(const APFloat &RHS) const {
  936. APFloat Result(*this);
  937. (void)Result.divide(RHS, rmNearestTiesToEven);
  938. return Result;
  939. }
  940. void changeSign() { APFLOAT_DISPATCH_ON_SEMANTICS(changeSign()); }
  941. void clearSign() {
  942. if (isNegative())
  943. changeSign();
  944. }
  945. void copySign(const APFloat &RHS) {
  946. if (isNegative() != RHS.isNegative())
  947. changeSign();
  948. }
  949. /// A static helper to produce a copy of an APFloat value with its sign
  950. /// copied from some other APFloat.
  951. static APFloat copySign(APFloat Value, const APFloat &Sign) {
  952. Value.copySign(Sign);
  953. return Value;
  954. }
  955. opStatus convert(const fltSemantics &ToSemantics, roundingMode RM,
  956. bool *losesInfo);
  957. opStatus convertToInteger(MutableArrayRef<integerPart> Input,
  958. unsigned int Width, bool IsSigned, roundingMode RM,
  959. bool *IsExact) const {
  960. APFLOAT_DISPATCH_ON_SEMANTICS(
  961. convertToInteger(Input, Width, IsSigned, RM, IsExact));
  962. }
  963. opStatus convertToInteger(APSInt &Result, roundingMode RM,
  964. bool *IsExact) const;
  965. opStatus convertFromAPInt(const APInt &Input, bool IsSigned,
  966. roundingMode RM) {
  967. APFLOAT_DISPATCH_ON_SEMANTICS(convertFromAPInt(Input, IsSigned, RM));
  968. }
  969. opStatus convertFromSignExtendedInteger(const integerPart *Input,
  970. unsigned int InputSize, bool IsSigned,
  971. roundingMode RM) {
  972. APFLOAT_DISPATCH_ON_SEMANTICS(
  973. convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM));
  974. }
  975. opStatus convertFromZeroExtendedInteger(const integerPart *Input,
  976. unsigned int InputSize, bool IsSigned,
  977. roundingMode RM) {
  978. APFLOAT_DISPATCH_ON_SEMANTICS(
  979. convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM));
  980. }
  981. Expected<opStatus> convertFromString(StringRef, roundingMode);
  982. APInt bitcastToAPInt() const {
  983. APFLOAT_DISPATCH_ON_SEMANTICS(bitcastToAPInt());
  984. }
  985. double convertToDouble() const { return getIEEE().convertToDouble(); }
  986. float convertToFloat() const { return getIEEE().convertToFloat(); }
  987. bool operator==(const APFloat &RHS) const { return compare(RHS) == cmpEqual; }
  988. bool operator!=(const APFloat &RHS) const { return compare(RHS) != cmpEqual; }
  989. bool operator<(const APFloat &RHS) const {
  990. return compare(RHS) == cmpLessThan;
  991. }
  992. bool operator>(const APFloat &RHS) const {
  993. return compare(RHS) == cmpGreaterThan;
  994. }
  995. bool operator<=(const APFloat &RHS) const {
  996. cmpResult Res = compare(RHS);
  997. return Res == cmpLessThan || Res == cmpEqual;
  998. }
  999. bool operator>=(const APFloat &RHS) const {
  1000. cmpResult Res = compare(RHS);
  1001. return Res == cmpGreaterThan || Res == cmpEqual;
  1002. }
  1003. cmpResult compare(const APFloat &RHS) const {
  1004. assert(&getSemantics() == &RHS.getSemantics() &&
  1005. "Should only compare APFloats with the same semantics");
  1006. if (usesLayout<IEEEFloat>(getSemantics()))
  1007. return U.IEEE.compare(RHS.U.IEEE);
  1008. if (usesLayout<DoubleAPFloat>(getSemantics()))
  1009. return U.Double.compare(RHS.U.Double);
  1010. llvm_unreachable("Unexpected semantics");
  1011. }
  1012. bool bitwiseIsEqual(const APFloat &RHS) const {
  1013. if (&getSemantics() != &RHS.getSemantics())
  1014. return false;
  1015. if (usesLayout<IEEEFloat>(getSemantics()))
  1016. return U.IEEE.bitwiseIsEqual(RHS.U.IEEE);
  1017. if (usesLayout<DoubleAPFloat>(getSemantics()))
  1018. return U.Double.bitwiseIsEqual(RHS.U.Double);
  1019. llvm_unreachable("Unexpected semantics");
  1020. }
  1021. /// We don't rely on operator== working on double values, as
  1022. /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
  1023. /// As such, this method can be used to do an exact bit-for-bit comparison of
  1024. /// two floating point values.
  1025. ///
  1026. /// We leave the version with the double argument here because it's just so
  1027. /// convenient to write "2.0" and the like. Without this function we'd
  1028. /// have to duplicate its logic everywhere it's called.
  1029. bool isExactlyValue(double V) const {
  1030. bool ignored;
  1031. APFloat Tmp(V);
  1032. Tmp.convert(getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
  1033. return bitwiseIsEqual(Tmp);
  1034. }
  1035. unsigned int convertToHexString(char *DST, unsigned int HexDigits,
  1036. bool UpperCase, roundingMode RM) const {
  1037. APFLOAT_DISPATCH_ON_SEMANTICS(
  1038. convertToHexString(DST, HexDigits, UpperCase, RM));
  1039. }
  1040. bool isZero() const { return getCategory() == fcZero; }
  1041. bool isInfinity() const { return getCategory() == fcInfinity; }
  1042. bool isNaN() const { return getCategory() == fcNaN; }
  1043. bool isNegative() const { return getIEEE().isNegative(); }
  1044. bool isDenormal() const { APFLOAT_DISPATCH_ON_SEMANTICS(isDenormal()); }
  1045. bool isSignaling() const { return getIEEE().isSignaling(); }
  1046. bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
  1047. bool isFinite() const { return !isNaN() && !isInfinity(); }
  1048. fltCategory getCategory() const { return getIEEE().getCategory(); }
  1049. const fltSemantics &getSemantics() const { return *U.semantics; }
  1050. bool isNonZero() const { return !isZero(); }
  1051. bool isFiniteNonZero() const { return isFinite() && !isZero(); }
  1052. bool isPosZero() const { return isZero() && !isNegative(); }
  1053. bool isNegZero() const { return isZero() && isNegative(); }
  1054. bool isSmallest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isSmallest()); }
  1055. bool isLargest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isLargest()); }
  1056. bool isInteger() const { APFLOAT_DISPATCH_ON_SEMANTICS(isInteger()); }
  1057. APFloat &operator=(const APFloat &RHS) = default;
  1058. APFloat &operator=(APFloat &&RHS) = default;
  1059. void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
  1060. unsigned FormatMaxPadding = 3, bool TruncateZero = true) const {
  1061. APFLOAT_DISPATCH_ON_SEMANTICS(
  1062. toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero));
  1063. }
  1064. void print(raw_ostream &) const;
  1065. void dump() const;
  1066. bool getExactInverse(APFloat *inv) const {
  1067. APFLOAT_DISPATCH_ON_SEMANTICS(getExactInverse(inv));
  1068. }
  1069. friend hash_code hash_value(const APFloat &Arg);
  1070. friend int ilogb(const APFloat &Arg) { return ilogb(Arg.getIEEE()); }
  1071. friend APFloat scalbn(APFloat X, int Exp, roundingMode RM);
  1072. friend APFloat frexp(const APFloat &X, int &Exp, roundingMode RM);
  1073. friend IEEEFloat;
  1074. friend DoubleAPFloat;
  1075. };
  1076. /// See friend declarations above.
  1077. ///
  1078. /// These additional declarations are required in order to compile LLVM with IBM
  1079. /// xlC compiler.
  1080. hash_code hash_value(const APFloat &Arg);
  1081. inline APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM) {
  1082. if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
  1083. return APFloat(scalbn(X.U.IEEE, Exp, RM), X.getSemantics());
  1084. if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
  1085. return APFloat(scalbn(X.U.Double, Exp, RM), X.getSemantics());
  1086. llvm_unreachable("Unexpected semantics");
  1087. }
  1088. /// Equivalent of C standard library function.
  1089. ///
  1090. /// While the C standard says Exp is an unspecified value for infinity and nan,
  1091. /// this returns INT_MAX for infinities, and INT_MIN for NaNs.
  1092. inline APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM) {
  1093. if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
  1094. return APFloat(frexp(X.U.IEEE, Exp, RM), X.getSemantics());
  1095. if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
  1096. return APFloat(frexp(X.U.Double, Exp, RM), X.getSemantics());
  1097. llvm_unreachable("Unexpected semantics");
  1098. }
  1099. /// Returns the absolute value of the argument.
  1100. inline APFloat abs(APFloat X) {
  1101. X.clearSign();
  1102. return X;
  1103. }
  1104. /// Returns the negated value of the argument.
  1105. inline APFloat neg(APFloat X) {
  1106. X.changeSign();
  1107. return X;
  1108. }
  1109. /// Implements IEEE minNum semantics. Returns the smaller of the 2 arguments if
  1110. /// both are not NaN. If either argument is a NaN, returns the other argument.
  1111. LLVM_READONLY
  1112. inline APFloat minnum(const APFloat &A, const APFloat &B) {
  1113. if (A.isNaN())
  1114. return B;
  1115. if (B.isNaN())
  1116. return A;
  1117. return B < A ? B : A;
  1118. }
  1119. /// Implements IEEE maxNum semantics. Returns the larger of the 2 arguments if
  1120. /// both are not NaN. If either argument is a NaN, returns the other argument.
  1121. LLVM_READONLY
  1122. inline APFloat maxnum(const APFloat &A, const APFloat &B) {
  1123. if (A.isNaN())
  1124. return B;
  1125. if (B.isNaN())
  1126. return A;
  1127. return A < B ? B : A;
  1128. }
  1129. /// Implements IEEE 754-2018 minimum semantics. Returns the smaller of 2
  1130. /// arguments, propagating NaNs and treating -0 as less than +0.
  1131. LLVM_READONLY
  1132. inline APFloat minimum(const APFloat &A, const APFloat &B) {
  1133. if (A.isNaN())
  1134. return A;
  1135. if (B.isNaN())
  1136. return B;
  1137. if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
  1138. return A.isNegative() ? A : B;
  1139. return B < A ? B : A;
  1140. }
  1141. /// Implements IEEE 754-2018 maximum semantics. Returns the larger of 2
  1142. /// arguments, propagating NaNs and treating -0 as less than +0.
  1143. LLVM_READONLY
  1144. inline APFloat maximum(const APFloat &A, const APFloat &B) {
  1145. if (A.isNaN())
  1146. return A;
  1147. if (B.isNaN())
  1148. return B;
  1149. if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
  1150. return A.isNegative() ? B : A;
  1151. return A < B ? B : A;
  1152. }
  1153. } // namespace llvm
  1154. #undef APFLOAT_DISPATCH_ON_SEMANTICS
  1155. #endif // LLVM_ADT_APFLOAT_H
  1156. #ifdef __GNUC__
  1157. #pragma GCC diagnostic pop
  1158. #endif