1 //===- llvm/ADT/APFloat.h - Arbitrary Precision Floating Point ---*- C++ -*-==//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
11 /// This file declares a class to represent arbitrary precision floating point
12 /// values and provide a variety of arithmetic operations on them.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_ADT_APFLOAT_H
17 #define LLVM_ADT_APFLOAT_H
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/Support/ErrorHandling.h"
24 #define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
26 if (usesLayout<IEEEFloat>(getSemantics())) \
27 return U.IEEE.METHOD_CALL; \
28 if (usesLayout<DoubleAPFloat>(getSemantics())) \
29 return U.Double.METHOD_CALL; \
30 llvm_unreachable("Unexpected semantics"); \
41 template <typename T> class Expected;
42 template <typename T> class SmallVectorImpl;
44 /// Enum that represents what fraction of the LSB truncated bits of an fp number
47 /// This essentially combines the roles of guard and sticky bits.
48 enum lostFraction { // Example of truncated bits:
49 lfExactlyZero, // 000000
50 lfLessThanHalf, // 0xxxxx x's not all zero
51 lfExactlyHalf, // 100000
52 lfMoreThanHalf // 1xxxxx x's not all zero
55 /// A self-contained host- and target-independent arbitrary-precision
56 /// floating-point software implementation.
58 /// APFloat uses bignum integer arithmetic as provided by static functions in
59 /// the APInt class. The library will work with bignum integers whose parts are
60 /// any unsigned type at least 16 bits wide, but 64 bits is recommended.
62 /// Written for clarity rather than speed, in particular with a view to use in
63 /// the front-end of a cross compiler so that target arithmetic can be correctly
64 /// performed on the host. Performance should nonetheless be reasonable,
65 /// particularly for its intended use. It may be useful as a base
66 /// implementation for a run-time library during development of a faster
67 /// target-specific one.
69 /// All 5 rounding modes in the IEEE-754R draft are handled correctly for all
70 /// implemented operations. Currently implemented operations are add, subtract,
71 /// multiply, divide, fused-multiply-add, conversion-to-float,
72 /// conversion-to-integer and conversion-from-integer. New rounding modes
73 /// (e.g. away from zero) can be added with three or four lines of code.
75 /// Four formats are built-in: IEEE single precision, double precision,
76 /// quadruple precision, and x87 80-bit extended double (when operating with
77 /// full extended precision). Adding a new format that obeys IEEE semantics
78 /// only requires adding two lines of code: a declaration and definition of the
81 /// All operations return the status of that operation as an exception bit-mask,
82 /// so multiple operations can be done consecutively with their results or-ed
83 /// together. The returned status can be useful for compiler diagnostics; e.g.,
84 /// inexact, underflow and overflow can be easily diagnosed on constant folding,
85 /// and compiler optimizers can determine what exceptions would be raised by
86 /// folding operations and optimize, or perhaps not optimize, accordingly.
88 /// At present, underflow tininess is detected after rounding; it should be
89 /// straight forward to add support for the before-rounding case too.
91 /// The library reads hexadecimal floating point numbers as per C99, and
92 /// correctly rounds if necessary according to the specified rounding mode.
93 /// Syntax is required to have been validated by the caller. It also converts
94 /// floating point numbers to hexadecimal text as per the C99 %a and %A
95 /// conversions. The output precision (or alternatively the natural minimal
96 /// precision) can be specified; if the requested precision is less than the
97 /// natural precision the output is correctly rounded for the specified rounding
100 /// It also reads decimal floating point numbers and correctly rounds according
101 /// to the specified rounding mode.
103 /// Conversion to decimal text is not currently implemented.
105 /// Non-zero finite numbers are represented internally as a sign bit, a 16-bit
106 /// signed exponent, and the significand as an array of integer parts. After
107 /// normalization of a number of precision P the exponent is within the range of
108 /// the format, and if the number is not denormal the P-th bit of the
109 /// significand is set as an explicit integer bit. For denormals the most
110 /// significant bit is shifted right so that the exponent is maintained at the
111 /// format's minimum, so that the smallest denormal has just the least
112 /// significant bit of the significand set. The sign of zeroes and infinities
113 /// is significant; the exponent and significand of such numbers is not stored,
114 /// but has a known implicit (deterministic) value: 0 for the significands, 0
115 /// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and
116 /// significand are deterministic, although not really meaningful, and preserved
117 /// in non-conversion operations. The exponent is implicitly all 1 bits.
119 /// APFloat does not provide any exception handling beyond default exception
120 /// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause
121 /// by encoding Signaling NaNs with the first bit of its trailing significand as
127 /// Some features that may or may not be worth adding:
129 /// Binary to decimal conversion (hard).
131 /// Optional ability to detect underflow tininess before rounding.
133 /// New formats: x87 in single and double precision mode (IEEE apart from
134 /// extended exponent range) (hard).
136 /// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward.
139 // This is the common type definitions shared by APFloat and its internal
140 // implementation classes. This struct should not define any non-static data
143 typedef APInt::WordType integerPart;
144 static const unsigned integerPartWidth = APInt::APINT_BITS_PER_WORD;
146 /// A signed type to represent a floating point numbers unbiased exponent.
147 typedef int32_t ExponentType;
149 /// \name Floating Point Semantics.
160 static const llvm::fltSemantics &EnumToSemantics(Semantics S);
161 static Semantics SemanticsToEnum(const llvm::fltSemantics &Sem);
163 static const fltSemantics &IEEEhalf() LLVM_READNONE;
164 static const fltSemantics &IEEEsingle() LLVM_READNONE;
165 static const fltSemantics &IEEEdouble() LLVM_READNONE;
166 static const fltSemantics &IEEEquad() LLVM_READNONE;
167 static const fltSemantics &PPCDoubleDouble() LLVM_READNONE;
168 static const fltSemantics &x87DoubleExtended() LLVM_READNONE;
170 /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with
172 static const fltSemantics &Bogus() LLVM_READNONE;
176 /// IEEE-754R 5.11: Floating Point Comparison Relations.
184 /// IEEE-754R 4.3: Rounding-direction attributes.
193 /// IEEE-754R 7: Default exception handling.
195 /// opUnderflow or opOverflow are always returned or-ed with opInexact.
197 /// APFloat models this behavior specified by IEEE-754:
198 /// "For operations producing results in floating-point format, the default
199 /// result of an operation that signals the invalid operation exception
200 /// shall be a quiet NaN."
210 /// Category of internally-represented number.
218 /// Convenience enum used to construct an uninitialized APFloat.
219 enum uninitializedTag {
223 /// Enumeration of \c ilogb error results.
224 enum IlogbErrorKinds {
225 IEK_Zero = INT_MIN + 1,
230 static unsigned int semanticsPrecision(const fltSemantics &);
231 static ExponentType semanticsMinExponent(const fltSemantics &);
232 static ExponentType semanticsMaxExponent(const fltSemantics &);
233 static unsigned int semanticsSizeInBits(const fltSemantics &);
235 /// Returns the size of the floating point number (in bits) in the given
237 static unsigned getSizeInBits(const fltSemantics &Sem);
242 class IEEEFloat final : public APFloatBase {
244 /// \name Constructors
247 IEEEFloat(const fltSemantics &); // Default construct to 0.0
248 IEEEFloat(const fltSemantics &, integerPart);
249 IEEEFloat(const fltSemantics &, uninitializedTag);
250 IEEEFloat(const fltSemantics &, const APInt &);
251 explicit IEEEFloat(double d);
252 explicit IEEEFloat(float f);
253 IEEEFloat(const IEEEFloat &);
254 IEEEFloat(IEEEFloat &&);
259 /// Returns whether this instance allocated memory.
260 bool needsCleanup() const { return partCount() > 1; }
262 /// \name Convenience "constructors"
270 opStatus add(const IEEEFloat &, roundingMode);
271 opStatus subtract(const IEEEFloat &, roundingMode);
272 opStatus multiply(const IEEEFloat &, roundingMode);
273 opStatus divide(const IEEEFloat &, roundingMode);
275 opStatus remainder(const IEEEFloat &);
276 /// C fmod, or llvm frem.
277 opStatus mod(const IEEEFloat &);
278 opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode);
279 opStatus roundToIntegral(roundingMode);
280 /// IEEE-754R 5.3.1: nextUp/nextDown.
281 opStatus next(bool nextDown);
285 /// \name Sign operations.
292 /// \name Conversions
295 opStatus convert(const fltSemantics &, roundingMode, bool *);
296 opStatus convertToInteger(MutableArrayRef<integerPart>, unsigned int, bool,
297 roundingMode, bool *) const;
298 opStatus convertFromAPInt(const APInt &, bool, roundingMode);
299 opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
301 opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
303 Expected<opStatus> convertFromString(StringRef, roundingMode);
304 APInt bitcastToAPInt() const;
305 double convertToDouble() const;
306 float convertToFloat() const;
310 /// The definition of equality is not straightforward for floating point, so
311 /// we won't use operator==. Use one of the following, or write whatever it
312 /// is you really mean.
313 bool operator==(const IEEEFloat &) const = delete;
315 /// IEEE comparison with another floating point number (NaNs compare
316 /// unordered, 0==-0).
317 cmpResult compare(const IEEEFloat &) const;
319 /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
320 bool bitwiseIsEqual(const IEEEFloat &) const;
322 /// Write out a hexadecimal representation of the floating point value to DST,
323 /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d.
324 /// Return the number of characters written, excluding the terminating NUL.
325 unsigned int convertToHexString(char *dst, unsigned int hexDigits,
326 bool upperCase, roundingMode) const;
328 /// \name IEEE-754R 5.7.2 General operations.
331 /// IEEE-754R isSignMinus: Returns true if and only if the current value is
334 /// This applies to zeros and NaNs as well.
335 bool isNegative() const { return sign; }
337 /// IEEE-754R isNormal: Returns true if and only if the current value is normal.
339 /// This implies that the current value of the float is not zero, subnormal,
340 /// infinite, or NaN following the definition of normality from IEEE-754R.
341 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
343 /// Returns true if and only if the current value is zero, subnormal, or
346 /// This means that the value is not infinite or NaN.
347 bool isFinite() const { return !isNaN() && !isInfinity(); }
349 /// Returns true if and only if the float is plus or minus zero.
350 bool isZero() const { return category == fcZero; }
352 /// IEEE-754R isSubnormal(): Returns true if and only if the float is a
354 bool isDenormal() const;
356 /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
357 bool isInfinity() const { return category == fcInfinity; }
359 /// Returns true if and only if the float is a quiet or signaling NaN.
360 bool isNaN() const { return category == fcNaN; }
362 /// Returns true if and only if the float is a signaling NaN.
363 bool isSignaling() const;
367 /// \name Simple Queries
370 fltCategory getCategory() const { return category; }
371 const fltSemantics &getSemantics() const { return *semantics; }
372 bool isNonZero() const { return category != fcZero; }
373 bool isFiniteNonZero() const { return isFinite() && !isZero(); }
374 bool isPosZero() const { return isZero() && !isNegative(); }
375 bool isNegZero() const { return isZero() && isNegative(); }
377 /// Returns true if and only if the number has the smallest possible non-zero
378 /// magnitude in the current semantics.
379 bool isSmallest() const;
381 /// Returns true if and only if the number has the largest possible finite
382 /// magnitude in the current semantics.
383 bool isLargest() const;
385 /// Returns true if and only if the number is an exact integer.
386 bool isInteger() const;
390 IEEEFloat &operator=(const IEEEFloat &);
391 IEEEFloat &operator=(IEEEFloat &&);
393 /// Overload to compute a hash code for an APFloat value.
395 /// Note that the use of hash codes for floating point values is in general
396 /// frought with peril. Equality is hard to define for these values. For
397 /// example, should negative and positive zero hash to different codes? Are
398 /// they equal or not? This hash value implementation specifically
399 /// emphasizes producing different codes for different inputs in order to
400 /// be used in canonicalization and memoization. As such, equality is
401 /// bitwiseIsEqual, and 0 != -0.
402 friend hash_code hash_value(const IEEEFloat &Arg);
404 /// Converts this value into a decimal string.
406 /// \param FormatPrecision The maximum number of digits of
407 /// precision to output. If there are fewer digits available,
408 /// zero padding will not be used unless the value is
409 /// integral and small enough to be expressed in
410 /// FormatPrecision digits. 0 means to use the natural
411 /// precision of the number.
412 /// \param FormatMaxPadding The maximum number of zeros to
413 /// consider inserting before falling back to scientific
414 /// notation. 0 means to always use scientific notation.
416 /// \param TruncateZero Indicate whether to remove the trailing zero in
417 /// fraction part or not. Also setting this parameter to false forcing
418 /// producing of output more similar to default printf behavior.
419 /// Specifically the lower e is used as exponent delimiter and exponent
420 /// always contains no less than two digits.
422 /// Number Precision MaxPadding Result
423 /// ------ --------- ---------- ------
424 /// 1.01E+4 5 2 10100
425 /// 1.01E+4 4 2 1.01E+4
426 /// 1.01E+4 5 1 1.01E+4
427 /// 1.01E-2 5 2 0.0101
428 /// 1.01E-2 4 2 0.0101
429 /// 1.01E-2 4 1 1.01E-2
430 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
431 unsigned FormatMaxPadding = 3, bool TruncateZero = true) const;
433 /// If this value has an exact multiplicative inverse, store it in inv and
435 bool getExactInverse(APFloat *inv) const;
437 /// Returns the exponent of the internal representation of the APFloat.
439 /// Because the radix of APFloat is 2, this is equivalent to floor(log2(x)).
440 /// For special APFloat values, this returns special error codes:
442 /// NaN -> \c IEK_NaN
444 /// Inf -> \c IEK_Inf
446 friend int ilogb(const IEEEFloat &Arg);
448 /// Returns: X * 2^Exp for integral exponents.
449 friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode);
451 friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode);
453 /// \name Special value setters.
456 void makeLargest(bool Neg = false);
457 void makeSmallest(bool Neg = false);
458 void makeNaN(bool SNaN = false, bool Neg = false,
459 const APInt *fill = nullptr);
460 void makeInf(bool Neg = false);
461 void makeZero(bool Neg = false);
464 /// Returns the smallest (by magnitude) normalized finite number in the given
467 /// \param Negative - True iff the number should be negative
468 void makeSmallestNormalized(bool Negative = false);
472 cmpResult compareAbsoluteValue(const IEEEFloat &) const;
475 /// \name Simple Queries
478 integerPart *significandParts();
479 const integerPart *significandParts() const;
480 unsigned int partCount() const;
484 /// \name Significand operations.
487 integerPart addSignificand(const IEEEFloat &);
488 integerPart subtractSignificand(const IEEEFloat &, integerPart);
489 lostFraction addOrSubtractSignificand(const IEEEFloat &, bool subtract);
490 lostFraction multiplySignificand(const IEEEFloat &, IEEEFloat);
491 lostFraction multiplySignificand(const IEEEFloat&);
492 lostFraction divideSignificand(const IEEEFloat &);
493 void incrementSignificand();
494 void initialize(const fltSemantics *);
495 void shiftSignificandLeft(unsigned int);
496 lostFraction shiftSignificandRight(unsigned int);
497 unsigned int significandLSB() const;
498 unsigned int significandMSB() const;
499 void zeroSignificand();
500 /// Return true if the significand excluding the integral bit is all ones.
501 bool isSignificandAllOnes() const;
502 /// Return true if the significand excluding the integral bit is all zeros.
503 bool isSignificandAllZeros() const;
507 /// \name Arithmetic on special values.
510 opStatus addOrSubtractSpecials(const IEEEFloat &, bool subtract);
511 opStatus divideSpecials(const IEEEFloat &);
512 opStatus multiplySpecials(const IEEEFloat &);
513 opStatus modSpecials(const IEEEFloat &);
520 bool convertFromStringSpecials(StringRef str);
521 opStatus normalize(roundingMode, lostFraction);
522 opStatus addOrSubtract(const IEEEFloat &, roundingMode, bool subtract);
523 opStatus handleOverflow(roundingMode);
524 bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
525 opStatus convertToSignExtendedInteger(MutableArrayRef<integerPart>,
526 unsigned int, bool, roundingMode,
528 opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
530 Expected<opStatus> convertFromHexadecimalString(StringRef, roundingMode);
531 Expected<opStatus> convertFromDecimalString(StringRef, roundingMode);
532 char *convertNormalToHexString(char *, unsigned int, bool,
534 opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
539 APInt convertHalfAPFloatToAPInt() const;
540 APInt convertFloatAPFloatToAPInt() const;
541 APInt convertDoubleAPFloatToAPInt() const;
542 APInt convertQuadrupleAPFloatToAPInt() const;
543 APInt convertF80LongDoubleAPFloatToAPInt() const;
544 APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
545 void initFromAPInt(const fltSemantics *Sem, const APInt &api);
546 void initFromHalfAPInt(const APInt &api);
547 void initFromFloatAPInt(const APInt &api);
548 void initFromDoubleAPInt(const APInt &api);
549 void initFromQuadrupleAPInt(const APInt &api);
550 void initFromF80LongDoubleAPInt(const APInt &api);
551 void initFromPPCDoubleDoubleAPInt(const APInt &api);
553 void assign(const IEEEFloat &);
554 void copySignificand(const IEEEFloat &);
555 void freeSignificand();
557 /// Note: this must be the first data member.
558 /// The semantics that this value obeys.
559 const fltSemantics *semantics;
561 /// A binary fraction with an explicit integer bit.
563 /// The significand must be at least one bit wider than the target precision.
569 /// The signed unbiased exponent of the value.
570 ExponentType exponent;
572 /// What kind of floating point number this is.
574 /// Only 2 bits are required, but VisualStudio incorrectly sign extends it.
575 /// Using the extra bit keeps it from failing under VisualStudio.
576 fltCategory category : 3;
578 /// Sign bit of the number.
579 unsigned int sign : 1;
582 hash_code hash_value(const IEEEFloat &Arg);
583 int ilogb(const IEEEFloat &Arg);
584 IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode);
585 IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM);
587 // This mode implements more precise float in terms of two APFloats.
588 // The interface and layout is designed for arbitray underlying semantics,
589 // though currently only PPCDoubleDouble semantics are supported, whose
590 // corresponding underlying semantics are IEEEdouble.
591 class DoubleAPFloat final : public APFloatBase {
592 // Note: this must be the first data member.
593 const fltSemantics *Semantics;
594 std::unique_ptr<APFloat[]> Floats;
596 opStatus addImpl(const APFloat &a, const APFloat &aa, const APFloat &c,
597 const APFloat &cc, roundingMode RM);
599 opStatus addWithSpecial(const DoubleAPFloat &LHS, const DoubleAPFloat &RHS,
600 DoubleAPFloat &Out, roundingMode RM);
603 DoubleAPFloat(const fltSemantics &S);
604 DoubleAPFloat(const fltSemantics &S, uninitializedTag);
605 DoubleAPFloat(const fltSemantics &S, integerPart);
606 DoubleAPFloat(const fltSemantics &S, const APInt &I);
607 DoubleAPFloat(const fltSemantics &S, APFloat &&First, APFloat &&Second);
608 DoubleAPFloat(const DoubleAPFloat &RHS);
609 DoubleAPFloat(DoubleAPFloat &&RHS);
611 DoubleAPFloat &operator=(const DoubleAPFloat &RHS);
613 DoubleAPFloat &operator=(DoubleAPFloat &&RHS) {
615 this->~DoubleAPFloat();
616 new (this) DoubleAPFloat(std::move(RHS));
621 bool needsCleanup() const { return Floats != nullptr; }
623 APFloat &getFirst() { return Floats[0]; }
624 const APFloat &getFirst() const { return Floats[0]; }
625 APFloat &getSecond() { return Floats[1]; }
626 const APFloat &getSecond() const { return Floats[1]; }
628 opStatus add(const DoubleAPFloat &RHS, roundingMode RM);
629 opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM);
630 opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM);
631 opStatus divide(const DoubleAPFloat &RHS, roundingMode RM);
632 opStatus remainder(const DoubleAPFloat &RHS);
633 opStatus mod(const DoubleAPFloat &RHS);
634 opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
635 const DoubleAPFloat &Addend, roundingMode RM);
636 opStatus roundToIntegral(roundingMode RM);
638 cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const;
640 fltCategory getCategory() const;
641 bool isNegative() const;
643 void makeInf(bool Neg);
644 void makeZero(bool Neg);
645 void makeLargest(bool Neg);
646 void makeSmallest(bool Neg);
647 void makeSmallestNormalized(bool Neg);
648 void makeNaN(bool SNaN, bool Neg, const APInt *fill);
650 cmpResult compare(const DoubleAPFloat &RHS) const;
651 bool bitwiseIsEqual(const DoubleAPFloat &RHS) const;
652 APInt bitcastToAPInt() const;
653 Expected<opStatus> convertFromString(StringRef, roundingMode);
654 opStatus next(bool nextDown);
656 opStatus convertToInteger(MutableArrayRef<integerPart> Input,
657 unsigned int Width, bool IsSigned, roundingMode RM,
658 bool *IsExact) const;
659 opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM);
660 opStatus convertFromSignExtendedInteger(const integerPart *Input,
661 unsigned int InputSize, bool IsSigned,
663 opStatus convertFromZeroExtendedInteger(const integerPart *Input,
664 unsigned int InputSize, bool IsSigned,
666 unsigned int convertToHexString(char *DST, unsigned int HexDigits,
667 bool UpperCase, roundingMode RM) const;
669 bool isDenormal() const;
670 bool isSmallest() const;
671 bool isLargest() const;
672 bool isInteger() const;
674 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
675 unsigned FormatMaxPadding, bool TruncateZero = true) const;
677 bool getExactInverse(APFloat *inv) const;
679 friend int ilogb(const DoubleAPFloat &Arg);
680 friend DoubleAPFloat scalbn(DoubleAPFloat X, int Exp, roundingMode);
681 friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp, roundingMode);
682 friend hash_code hash_value(const DoubleAPFloat &Arg);
685 hash_code hash_value(const DoubleAPFloat &Arg);
687 } // End detail namespace
689 // This is a interface class that is currently forwarding functionalities from
690 // detail::IEEEFloat.
691 class APFloat : public APFloatBase {
692 typedef detail::IEEEFloat IEEEFloat;
693 typedef detail::DoubleAPFloat DoubleAPFloat;
695 static_assert(std::is_standard_layout<IEEEFloat>::value, "");
698 const fltSemantics *semantics;
700 DoubleAPFloat Double;
702 explicit Storage(IEEEFloat F, const fltSemantics &S);
703 explicit Storage(DoubleAPFloat F, const fltSemantics &S)
704 : Double(std::move(F)) {
705 assert(&S == &PPCDoubleDouble());
708 template <typename... ArgTypes>
709 Storage(const fltSemantics &Semantics, ArgTypes &&... Args) {
710 if (usesLayout<IEEEFloat>(Semantics)) {
711 new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...);
714 if (usesLayout<DoubleAPFloat>(Semantics)) {
715 new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
718 llvm_unreachable("Unexpected semantics");
722 if (usesLayout<IEEEFloat>(*semantics)) {
726 if (usesLayout<DoubleAPFloat>(*semantics)) {
727 Double.~DoubleAPFloat();
730 llvm_unreachable("Unexpected semantics");
733 Storage(const Storage &RHS) {
734 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
735 new (this) IEEEFloat(RHS.IEEE);
738 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
739 new (this) DoubleAPFloat(RHS.Double);
742 llvm_unreachable("Unexpected semantics");
745 Storage(Storage &&RHS) {
746 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
747 new (this) IEEEFloat(std::move(RHS.IEEE));
750 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
751 new (this) DoubleAPFloat(std::move(RHS.Double));
754 llvm_unreachable("Unexpected semantics");
757 Storage &operator=(const Storage &RHS) {
758 if (usesLayout<IEEEFloat>(*semantics) &&
759 usesLayout<IEEEFloat>(*RHS.semantics)) {
761 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
762 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
764 } else if (this != &RHS) {
766 new (this) Storage(RHS);
771 Storage &operator=(Storage &&RHS) {
772 if (usesLayout<IEEEFloat>(*semantics) &&
773 usesLayout<IEEEFloat>(*RHS.semantics)) {
774 IEEE = std::move(RHS.IEEE);
775 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
776 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
777 Double = std::move(RHS.Double);
778 } else if (this != &RHS) {
780 new (this) Storage(std::move(RHS));
786 template <typename T> static bool usesLayout(const fltSemantics &Semantics) {
787 static_assert(std::is_same<T, IEEEFloat>::value ||
788 std::is_same<T, DoubleAPFloat>::value, "");
789 if (std::is_same<T, DoubleAPFloat>::value) {
790 return &Semantics == &PPCDoubleDouble();
792 return &Semantics != &PPCDoubleDouble();
795 IEEEFloat &getIEEE() {
796 if (usesLayout<IEEEFloat>(*U.semantics))
798 if (usesLayout<DoubleAPFloat>(*U.semantics))
799 return U.Double.getFirst().U.IEEE;
800 llvm_unreachable("Unexpected semantics");
803 const IEEEFloat &getIEEE() const {
804 if (usesLayout<IEEEFloat>(*U.semantics))
806 if (usesLayout<DoubleAPFloat>(*U.semantics))
807 return U.Double.getFirst().U.IEEE;
808 llvm_unreachable("Unexpected semantics");
811 void makeZero(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeZero(Neg)); }
813 void makeInf(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeInf(Neg)); }
815 void makeNaN(bool SNaN, bool Neg, const APInt *fill) {
816 APFLOAT_DISPATCH_ON_SEMANTICS(makeNaN(SNaN, Neg, fill));
819 void makeLargest(bool Neg) {
820 APFLOAT_DISPATCH_ON_SEMANTICS(makeLargest(Neg));
823 void makeSmallest(bool Neg) {
824 APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallest(Neg));
827 void makeSmallestNormalized(bool Neg) {
828 APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallestNormalized(Neg));
831 // FIXME: This is due to clang 3.3 (or older version) always checks for the
832 // default constructor in an array aggregate initialization, even if no
833 // elements in the array is default initialized.
834 APFloat() : U(IEEEdouble()) {
835 llvm_unreachable("This is a workaround for old clang.");
838 explicit APFloat(IEEEFloat F, const fltSemantics &S) : U(std::move(F), S) {}
839 explicit APFloat(DoubleAPFloat F, const fltSemantics &S)
840 : U(std::move(F), S) {}
842 cmpResult compareAbsoluteValue(const APFloat &RHS) const {
843 assert(&getSemantics() == &RHS.getSemantics() &&
844 "Should only compare APFloats with the same semantics");
845 if (usesLayout<IEEEFloat>(getSemantics()))
846 return U.IEEE.compareAbsoluteValue(RHS.U.IEEE);
847 if (usesLayout<DoubleAPFloat>(getSemantics()))
848 return U.Double.compareAbsoluteValue(RHS.U.Double);
849 llvm_unreachable("Unexpected semantics");
853 APFloat(const fltSemantics &Semantics) : U(Semantics) {}
854 APFloat(const fltSemantics &Semantics, StringRef S);
855 APFloat(const fltSemantics &Semantics, integerPart I) : U(Semantics, I) {}
856 template <typename T, typename = typename std::enable_if<
857 std::is_floating_point<T>::value>::type>
858 APFloat(const fltSemantics &Semantics, T V) = delete;
859 // TODO: Remove this constructor. This isn't faster than the first one.
860 APFloat(const fltSemantics &Semantics, uninitializedTag)
861 : U(Semantics, uninitialized) {}
862 APFloat(const fltSemantics &Semantics, const APInt &I) : U(Semantics, I) {}
863 explicit APFloat(double d) : U(IEEEFloat(d), IEEEdouble()) {}
864 explicit APFloat(float f) : U(IEEEFloat(f), IEEEsingle()) {}
865 APFloat(const APFloat &RHS) = default;
866 APFloat(APFloat &&RHS) = default;
868 ~APFloat() = default;
870 bool needsCleanup() const { APFLOAT_DISPATCH_ON_SEMANTICS(needsCleanup()); }
872 /// Factory for Positive and Negative Zero.
874 /// \param Negative True iff the number should be negative.
875 static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
876 APFloat Val(Sem, uninitialized);
877 Val.makeZero(Negative);
881 /// Factory for Positive and Negative Infinity.
883 /// \param Negative True iff the number should be negative.
884 static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
885 APFloat Val(Sem, uninitialized);
886 Val.makeInf(Negative);
890 /// Factory for NaN values.
892 /// \param Negative - True iff the NaN generated should be negative.
893 /// \param payload - The unspecified fill bits for creating the NaN, 0 by
894 /// default. The value is truncated as necessary.
895 static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
896 uint64_t payload = 0) {
898 APInt intPayload(64, payload);
899 return getQNaN(Sem, Negative, &intPayload);
901 return getQNaN(Sem, Negative, nullptr);
905 /// Factory for QNaN values.
906 static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false,
907 const APInt *payload = nullptr) {
908 APFloat Val(Sem, uninitialized);
909 Val.makeNaN(false, Negative, payload);
913 /// Factory for SNaN values.
914 static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false,
915 const APInt *payload = nullptr) {
916 APFloat Val(Sem, uninitialized);
917 Val.makeNaN(true, Negative, payload);
921 /// Returns the largest finite number in the given semantics.
923 /// \param Negative - True iff the number should be negative
924 static APFloat getLargest(const fltSemantics &Sem, bool Negative = false) {
925 APFloat Val(Sem, uninitialized);
926 Val.makeLargest(Negative);
930 /// Returns the smallest (by magnitude) finite number in the given semantics.
931 /// Might be denormalized, which implies a relative loss of precision.
933 /// \param Negative - True iff the number should be negative
934 static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false) {
935 APFloat Val(Sem, uninitialized);
936 Val.makeSmallest(Negative);
940 /// Returns the smallest (by magnitude) normalized finite number in the given
943 /// \param Negative - True iff the number should be negative
944 static APFloat getSmallestNormalized(const fltSemantics &Sem,
945 bool Negative = false) {
946 APFloat Val(Sem, uninitialized);
947 Val.makeSmallestNormalized(Negative);
951 /// Returns a float which is bitcasted from an all one value int.
953 /// \param BitWidth - Select float type
954 /// \param isIEEE - If 128 bit number, select between PPC and IEEE
955 static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false);
957 /// Used to insert APFloat objects, or objects that contain APFloat objects,
958 /// into FoldingSets.
959 void Profile(FoldingSetNodeID &NID) const;
961 opStatus add(const APFloat &RHS, roundingMode RM) {
962 assert(&getSemantics() == &RHS.getSemantics() &&
963 "Should only call on two APFloats with the same semantics");
964 if (usesLayout<IEEEFloat>(getSemantics()))
965 return U.IEEE.add(RHS.U.IEEE, RM);
966 if (usesLayout<DoubleAPFloat>(getSemantics()))
967 return U.Double.add(RHS.U.Double, RM);
968 llvm_unreachable("Unexpected semantics");
970 opStatus subtract(const APFloat &RHS, roundingMode RM) {
971 assert(&getSemantics() == &RHS.getSemantics() &&
972 "Should only call on two APFloats with the same semantics");
973 if (usesLayout<IEEEFloat>(getSemantics()))
974 return U.IEEE.subtract(RHS.U.IEEE, RM);
975 if (usesLayout<DoubleAPFloat>(getSemantics()))
976 return U.Double.subtract(RHS.U.Double, RM);
977 llvm_unreachable("Unexpected semantics");
979 opStatus multiply(const APFloat &RHS, roundingMode RM) {
980 assert(&getSemantics() == &RHS.getSemantics() &&
981 "Should only call on two APFloats with the same semantics");
982 if (usesLayout<IEEEFloat>(getSemantics()))
983 return U.IEEE.multiply(RHS.U.IEEE, RM);
984 if (usesLayout<DoubleAPFloat>(getSemantics()))
985 return U.Double.multiply(RHS.U.Double, RM);
986 llvm_unreachable("Unexpected semantics");
988 opStatus divide(const APFloat &RHS, roundingMode RM) {
989 assert(&getSemantics() == &RHS.getSemantics() &&
990 "Should only call on two APFloats with the same semantics");
991 if (usesLayout<IEEEFloat>(getSemantics()))
992 return U.IEEE.divide(RHS.U.IEEE, RM);
993 if (usesLayout<DoubleAPFloat>(getSemantics()))
994 return U.Double.divide(RHS.U.Double, RM);
995 llvm_unreachable("Unexpected semantics");
997 opStatus remainder(const APFloat &RHS) {
998 assert(&getSemantics() == &RHS.getSemantics() &&
999 "Should only call on two APFloats with the same semantics");
1000 if (usesLayout<IEEEFloat>(getSemantics()))
1001 return U.IEEE.remainder(RHS.U.IEEE);
1002 if (usesLayout<DoubleAPFloat>(getSemantics()))
1003 return U.Double.remainder(RHS.U.Double);
1004 llvm_unreachable("Unexpected semantics");
1006 opStatus mod(const APFloat &RHS) {
1007 assert(&getSemantics() == &RHS.getSemantics() &&
1008 "Should only call on two APFloats with the same semantics");
1009 if (usesLayout<IEEEFloat>(getSemantics()))
1010 return U.IEEE.mod(RHS.U.IEEE);
1011 if (usesLayout<DoubleAPFloat>(getSemantics()))
1012 return U.Double.mod(RHS.U.Double);
1013 llvm_unreachable("Unexpected semantics");
1015 opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend,
1017 assert(&getSemantics() == &Multiplicand.getSemantics() &&
1018 "Should only call on APFloats with the same semantics");
1019 assert(&getSemantics() == &Addend.getSemantics() &&
1020 "Should only call on APFloats with the same semantics");
1021 if (usesLayout<IEEEFloat>(getSemantics()))
1022 return U.IEEE.fusedMultiplyAdd(Multiplicand.U.IEEE, Addend.U.IEEE, RM);
1023 if (usesLayout<DoubleAPFloat>(getSemantics()))
1024 return U.Double.fusedMultiplyAdd(Multiplicand.U.Double, Addend.U.Double,
1026 llvm_unreachable("Unexpected semantics");
1028 opStatus roundToIntegral(roundingMode RM) {
1029 APFLOAT_DISPATCH_ON_SEMANTICS(roundToIntegral(RM));
1032 // TODO: bool parameters are not readable and a source of bugs.
1034 opStatus next(bool nextDown) {
1035 APFLOAT_DISPATCH_ON_SEMANTICS(next(nextDown));
1038 /// Add two APFloats, rounding ties to the nearest even.
1039 /// No error checking.
1040 APFloat operator+(const APFloat &RHS) const {
1041 APFloat Result(*this);
1042 (void)Result.add(RHS, rmNearestTiesToEven);
1046 /// Subtract two APFloats, rounding ties to the nearest even.
1047 /// No error checking.
1048 APFloat operator-(const APFloat &RHS) const {
1049 APFloat Result(*this);
1050 (void)Result.subtract(RHS, rmNearestTiesToEven);
1054 /// Multiply two APFloats, rounding ties to the nearest even.
1055 /// No error checking.
1056 APFloat operator*(const APFloat &RHS) const {
1057 APFloat Result(*this);
1058 (void)Result.multiply(RHS, rmNearestTiesToEven);
1062 /// Divide the first APFloat by the second, rounding ties to the nearest even.
1063 /// No error checking.
1064 APFloat operator/(const APFloat &RHS) const {
1065 APFloat Result(*this);
1066 (void)Result.divide(RHS, rmNearestTiesToEven);
1070 void changeSign() { APFLOAT_DISPATCH_ON_SEMANTICS(changeSign()); }
1075 void copySign(const APFloat &RHS) {
1076 if (isNegative() != RHS.isNegative())
1080 /// A static helper to produce a copy of an APFloat value with its sign
1081 /// copied from some other APFloat.
1082 static APFloat copySign(APFloat Value, const APFloat &Sign) {
1083 Value.copySign(Sign);
1087 opStatus convert(const fltSemantics &ToSemantics, roundingMode RM,
1089 opStatus convertToInteger(MutableArrayRef<integerPart> Input,
1090 unsigned int Width, bool IsSigned, roundingMode RM,
1091 bool *IsExact) const {
1092 APFLOAT_DISPATCH_ON_SEMANTICS(
1093 convertToInteger(Input, Width, IsSigned, RM, IsExact));
1095 opStatus convertToInteger(APSInt &Result, roundingMode RM,
1096 bool *IsExact) const;
1097 opStatus convertFromAPInt(const APInt &Input, bool IsSigned,
1099 APFLOAT_DISPATCH_ON_SEMANTICS(convertFromAPInt(Input, IsSigned, RM));
1101 opStatus convertFromSignExtendedInteger(const integerPart *Input,
1102 unsigned int InputSize, bool IsSigned,
1104 APFLOAT_DISPATCH_ON_SEMANTICS(
1105 convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM));
1107 opStatus convertFromZeroExtendedInteger(const integerPart *Input,
1108 unsigned int InputSize, bool IsSigned,
1110 APFLOAT_DISPATCH_ON_SEMANTICS(
1111 convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM));
1113 Expected<opStatus> convertFromString(StringRef, roundingMode);
1114 APInt bitcastToAPInt() const {
1115 APFLOAT_DISPATCH_ON_SEMANTICS(bitcastToAPInt());
1117 double convertToDouble() const { return getIEEE().convertToDouble(); }
1118 float convertToFloat() const { return getIEEE().convertToFloat(); }
1120 bool operator==(const APFloat &) const = delete;
1122 cmpResult compare(const APFloat &RHS) const {
1123 assert(&getSemantics() == &RHS.getSemantics() &&
1124 "Should only compare APFloats with the same semantics");
1125 if (usesLayout<IEEEFloat>(getSemantics()))
1126 return U.IEEE.compare(RHS.U.IEEE);
1127 if (usesLayout<DoubleAPFloat>(getSemantics()))
1128 return U.Double.compare(RHS.U.Double);
1129 llvm_unreachable("Unexpected semantics");
1132 bool bitwiseIsEqual(const APFloat &RHS) const {
1133 if (&getSemantics() != &RHS.getSemantics())
1135 if (usesLayout<IEEEFloat>(getSemantics()))
1136 return U.IEEE.bitwiseIsEqual(RHS.U.IEEE);
1137 if (usesLayout<DoubleAPFloat>(getSemantics()))
1138 return U.Double.bitwiseIsEqual(RHS.U.Double);
1139 llvm_unreachable("Unexpected semantics");
1142 /// We don't rely on operator== working on double values, as
1143 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1144 /// As such, this method can be used to do an exact bit-for-bit comparison of
1145 /// two floating point values.
1147 /// We leave the version with the double argument here because it's just so
1148 /// convenient to write "2.0" and the like. Without this function we'd
1149 /// have to duplicate its logic everywhere it's called.
1150 bool isExactlyValue(double V) const {
1153 Tmp.convert(getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
1154 return bitwiseIsEqual(Tmp);
1157 unsigned int convertToHexString(char *DST, unsigned int HexDigits,
1158 bool UpperCase, roundingMode RM) const {
1159 APFLOAT_DISPATCH_ON_SEMANTICS(
1160 convertToHexString(DST, HexDigits, UpperCase, RM));
1163 bool isZero() const { return getCategory() == fcZero; }
1164 bool isInfinity() const { return getCategory() == fcInfinity; }
1165 bool isNaN() const { return getCategory() == fcNaN; }
1167 bool isNegative() const { return getIEEE().isNegative(); }
1168 bool isDenormal() const { APFLOAT_DISPATCH_ON_SEMANTICS(isDenormal()); }
1169 bool isSignaling() const { return getIEEE().isSignaling(); }
1171 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
1172 bool isFinite() const { return !isNaN() && !isInfinity(); }
1174 fltCategory getCategory() const { return getIEEE().getCategory(); }
1175 const fltSemantics &getSemantics() const { return *U.semantics; }
1176 bool isNonZero() const { return !isZero(); }
1177 bool isFiniteNonZero() const { return isFinite() && !isZero(); }
1178 bool isPosZero() const { return isZero() && !isNegative(); }
1179 bool isNegZero() const { return isZero() && isNegative(); }
1180 bool isSmallest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isSmallest()); }
1181 bool isLargest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isLargest()); }
1182 bool isInteger() const { APFLOAT_DISPATCH_ON_SEMANTICS(isInteger()); }
1184 APFloat &operator=(const APFloat &RHS) = default;
1185 APFloat &operator=(APFloat &&RHS) = default;
1187 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
1188 unsigned FormatMaxPadding = 3, bool TruncateZero = true) const {
1189 APFLOAT_DISPATCH_ON_SEMANTICS(
1190 toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero));
1193 void print(raw_ostream &) const;
1196 bool getExactInverse(APFloat *inv) const {
1197 APFLOAT_DISPATCH_ON_SEMANTICS(getExactInverse(inv));
1200 friend hash_code hash_value(const APFloat &Arg);
1201 friend int ilogb(const APFloat &Arg) { return ilogb(Arg.getIEEE()); }
1202 friend APFloat scalbn(APFloat X, int Exp, roundingMode RM);
1203 friend APFloat frexp(const APFloat &X, int &Exp, roundingMode RM);
1205 friend DoubleAPFloat;
1208 /// See friend declarations above.
1210 /// These additional declarations are required in order to compile LLVM with IBM
1212 hash_code hash_value(const APFloat &Arg);
1213 inline APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM) {
1214 if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
1215 return APFloat(scalbn(X.U.IEEE, Exp, RM), X.getSemantics());
1216 if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
1217 return APFloat(scalbn(X.U.Double, Exp, RM), X.getSemantics());
1218 llvm_unreachable("Unexpected semantics");
1221 /// Equivalent of C standard library function.
1223 /// While the C standard says Exp is an unspecified value for infinity and nan,
1224 /// this returns INT_MAX for infinities, and INT_MIN for NaNs.
1225 inline APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM) {
1226 if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
1227 return APFloat(frexp(X.U.IEEE, Exp, RM), X.getSemantics());
1228 if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
1229 return APFloat(frexp(X.U.Double, Exp, RM), X.getSemantics());
1230 llvm_unreachable("Unexpected semantics");
1232 /// Returns the absolute value of the argument.
1233 inline APFloat abs(APFloat X) {
1238 /// Returns the negated value of the argument.
1239 inline APFloat neg(APFloat X) {
1244 /// Implements IEEE minNum semantics. Returns the smaller of the 2 arguments if
1245 /// both are not NaN. If either argument is a NaN, returns the other argument.
1247 inline APFloat minnum(const APFloat &A, const APFloat &B) {
1252 return (B.compare(A) == APFloat::cmpLessThan) ? B : A;
1255 /// Implements IEEE maxNum semantics. Returns the larger of the 2 arguments if
1256 /// both are not NaN. If either argument is a NaN, returns the other argument.
1258 inline APFloat maxnum(const APFloat &A, const APFloat &B) {
1263 return (A.compare(B) == APFloat::cmpLessThan) ? B : A;
1266 /// Implements IEEE 754-2018 minimum semantics. Returns the smaller of 2
1267 /// arguments, propagating NaNs and treating -0 as less than +0.
1269 inline APFloat minimum(const APFloat &A, const APFloat &B) {
1274 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1275 return A.isNegative() ? A : B;
1276 return (B.compare(A) == APFloat::cmpLessThan) ? B : A;
1279 /// Implements IEEE 754-2018 maximum semantics. Returns the larger of 2
1280 /// arguments, propagating NaNs and treating -0 as less than +0.
1282 inline APFloat maximum(const APFloat &A, const APFloat &B) {
1287 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1288 return A.isNegative() ? B : A;
1289 return (A.compare(B) == APFloat::cmpLessThan) ? B : A;
1294 #undef APFLOAT_DISPATCH_ON_SEMANTICS
1295 #endif // LLVM_ADT_APFLOAT_H