APFloat.h 50 KB

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