1 //===- llvm/ADT/APFloat.h - Arbitrary Precision Floating Point ---*- C++ -*-==//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// \brief
11 /// This file declares a class to represent arbitrary precision floating point
12 /// values and provide a variety of arithmetic operations on them.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_ADT_APFLOAT_H
17 #define LLVM_ADT_APFLOAT_H
18 
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include <memory>
23 
24 #define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL)                             \
25   do {                                                                         \
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");                                  \
31   } while (false)
32 
33 namespace llvm {
34 
35 struct fltSemantics;
36 class APSInt;
37 class StringRef;
38 class APFloat;
39 class raw_ostream;
40 
41 template <typename T> class Expected;
42 template <typename T> class SmallVectorImpl;
43 
44 /// Enum that represents what fraction of the LSB truncated bits of an fp number
45 /// represent.
46 ///
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
53 };
54 
55 /// A self-contained host- and target-independent arbitrary-precision
56 /// floating-point software implementation.
57 ///
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.
61 ///
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.
68 ///
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.
74 ///
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
79 /// format.
80 ///
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.
87 ///
88 /// At present, underflow tininess is detected after rounding; it should be
89 /// straight forward to add support for the before-rounding case too.
90 ///
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
98 /// mode.
99 ///
100 /// It also reads decimal floating point numbers and correctly rounds according
101 /// to the specified rounding mode.
102 ///
103 /// Conversion to decimal text is not currently implemented.
104 ///
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.
118 ///
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
122 /// 0.
123 ///
124 /// TODO
125 /// ====
126 ///
127 /// Some features that may or may not be worth adding:
128 ///
129 /// Binary to decimal conversion (hard).
130 ///
131 /// Optional ability to detect underflow tininess before rounding.
132 ///
133 /// New formats: x87 in single and double precision mode (IEEE apart from
134 /// extended exponent range) (hard).
135 ///
136 /// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward.
137 ///
138 
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
141 // members.
142 struct APFloatBase {
143   typedef APInt::WordType integerPart;
144   static const unsigned integerPartWidth = APInt::APINT_BITS_PER_WORD;
145 
146   /// A signed type to represent a floating point numbers unbiased exponent.
147   typedef int32_t ExponentType;
148 
149   /// \name Floating Point Semantics.
150   /// @{
151   enum Semantics {
152     S_IEEEhalf,
153     S_IEEEsingle,
154     S_IEEEdouble,
155     S_x87DoubleExtended,
156     S_IEEEquad,
157     S_PPCDoubleDouble
158   };
159 
160   static const llvm::fltSemantics &EnumToSemantics(Semantics S);
161   static Semantics SemanticsToEnum(const llvm::fltSemantics &Sem);
162 
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;
169 
170   /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with
171   /// anything real.
172   static const fltSemantics &Bogus() LLVM_READNONE;
173 
174   /// @}
175 
176   /// IEEE-754R 5.11: Floating Point Comparison Relations.
177   enum cmpResult {
178     cmpLessThan,
179     cmpEqual,
180     cmpGreaterThan,
181     cmpUnordered
182   };
183 
184   /// IEEE-754R 4.3: Rounding-direction attributes.
185   enum roundingMode {
186     rmNearestTiesToEven,
187     rmTowardPositive,
188     rmTowardNegative,
189     rmTowardZero,
190     rmNearestTiesToAway
191   };
192 
193   /// IEEE-754R 7: Default exception handling.
194   ///
195   /// opUnderflow or opOverflow are always returned or-ed with opInexact.
196   ///
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."
201   enum opStatus {
202     opOK = 0x00,
203     opInvalidOp = 0x01,
204     opDivByZero = 0x02,
205     opOverflow = 0x04,
206     opUnderflow = 0x08,
207     opInexact = 0x10
208   };
209 
210   /// Category of internally-represented number.
211   enum fltCategory {
212     fcInfinity,
213     fcNaN,
214     fcNormal,
215     fcZero
216   };
217 
218   /// Convenience enum used to construct an uninitialized APFloat.
219   enum uninitializedTag {
220     uninitialized
221   };
222 
223   /// Enumeration of \c ilogb error results.
224   enum IlogbErrorKinds {
225     IEK_Zero = INT_MIN + 1,
226     IEK_NaN = INT_MIN,
227     IEK_Inf = INT_MAX
228   };
229 
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 &);
234 
235   /// Returns the size of the floating point number (in bits) in the given
236   /// semantics.
237   static unsigned getSizeInBits(const fltSemantics &Sem);
238 };
239 
240 namespace detail {
241 
242 class IEEEFloat final : public APFloatBase {
243 public:
244   /// \name Constructors
245   /// @{
246 
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 &&);
255   ~IEEEFloat();
256 
257   /// @}
258 
259   /// Returns whether this instance allocated memory.
260   bool needsCleanup() const { return partCount() > 1; }
261 
262   /// \name Convenience "constructors"
263   /// @{
264 
265   /// @}
266 
267   /// \name Arithmetic
268   /// @{
269 
270   opStatus add(const IEEEFloat &, roundingMode);
271   opStatus subtract(const IEEEFloat &, roundingMode);
272   opStatus multiply(const IEEEFloat &, roundingMode);
273   opStatus divide(const IEEEFloat &, roundingMode);
274   /// IEEE remainder.
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);
282 
283   /// @}
284 
285   /// \name Sign operations.
286   /// @{
287 
288   void changeSign();
289 
290   /// @}
291 
292   /// \name Conversions
293   /// @{
294 
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,
300                                           bool, roundingMode);
301   opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
302                                           bool, roundingMode);
303   Expected<opStatus> convertFromString(StringRef, roundingMode);
304   APInt bitcastToAPInt() const;
305   double convertToDouble() const;
306   float convertToFloat() const;
307 
308   /// @}
309 
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;
314 
315   /// IEEE comparison with another floating point number (NaNs compare
316   /// unordered, 0==-0).
317   cmpResult compare(const IEEEFloat &) const;
318 
319   /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
320   bool bitwiseIsEqual(const IEEEFloat &) const;
321 
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;
327 
328   /// \name IEEE-754R 5.7.2 General operations.
329   /// @{
330 
331   /// IEEE-754R isSignMinus: Returns true if and only if the current value is
332   /// negative.
333   ///
334   /// This applies to zeros and NaNs as well.
335   bool isNegative() const { return sign; }
336 
337   /// IEEE-754R isNormal: Returns true if and only if the current value is normal.
338   ///
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(); }
342 
343   /// Returns true if and only if the current value is zero, subnormal, or
344   /// normal.
345   ///
346   /// This means that the value is not infinite or NaN.
347   bool isFinite() const { return !isNaN() && !isInfinity(); }
348 
349   /// Returns true if and only if the float is plus or minus zero.
350   bool isZero() const { return category == fcZero; }
351 
352   /// IEEE-754R isSubnormal(): Returns true if and only if the float is a
353   /// denormal.
354   bool isDenormal() const;
355 
356   /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
357   bool isInfinity() const { return category == fcInfinity; }
358 
359   /// Returns true if and only if the float is a quiet or signaling NaN.
360   bool isNaN() const { return category == fcNaN; }
361 
362   /// Returns true if and only if the float is a signaling NaN.
363   bool isSignaling() const;
364 
365   /// @}
366 
367   /// \name Simple Queries
368   /// @{
369 
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(); }
376 
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;
380 
381   /// Returns true if and only if the number has the largest possible finite
382   /// magnitude in the current semantics.
383   bool isLargest() const;
384 
385   /// Returns true if and only if the number is an exact integer.
386   bool isInteger() const;
387 
388   /// @}
389 
390   IEEEFloat &operator=(const IEEEFloat &);
391   IEEEFloat &operator=(IEEEFloat &&);
392 
393   /// Overload to compute a hash code for an APFloat value.
394   ///
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);
403 
404   /// Converts this value into a decimal string.
405   ///
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.
415   ///
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.
421   ///
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;
432 
433   /// If this value has an exact multiplicative inverse, store it in inv and
434   /// return true.
435   bool getExactInverse(APFloat *inv) const;
436 
437   /// Returns the exponent of the internal representation of the APFloat.
438   ///
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:
441   ///
442   ///   NaN -> \c IEK_NaN
443   ///   0   -> \c IEK_Zero
444   ///   Inf -> \c IEK_Inf
445   ///
446   friend int ilogb(const IEEEFloat &Arg);
447 
448   /// Returns: X * 2^Exp for integral exponents.
449   friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode);
450 
451   friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode);
452 
453   /// \name Special value setters.
454   /// @{
455 
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);
462   void makeQuiet();
463 
464   /// Returns the smallest (by magnitude) normalized finite number in the given
465   /// semantics.
466   ///
467   /// \param Negative - True iff the number should be negative
468   void makeSmallestNormalized(bool Negative = false);
469 
470   /// @}
471 
472   cmpResult compareAbsoluteValue(const IEEEFloat &) const;
473 
474 private:
475   /// \name Simple Queries
476   /// @{
477 
478   integerPart *significandParts();
479   const integerPart *significandParts() const;
480   unsigned int partCount() const;
481 
482   /// @}
483 
484   /// \name Significand operations.
485   /// @{
486 
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;
504 
505   /// @}
506 
507   /// \name Arithmetic on special values.
508   /// @{
509 
510   opStatus addOrSubtractSpecials(const IEEEFloat &, bool subtract);
511   opStatus divideSpecials(const IEEEFloat &);
512   opStatus multiplySpecials(const IEEEFloat &);
513   opStatus modSpecials(const IEEEFloat &);
514 
515   /// @}
516 
517   /// \name Miscellany
518   /// @{
519 
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,
527                                         bool *) const;
528   opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
529                                     roundingMode);
530   Expected<opStatus> convertFromHexadecimalString(StringRef, roundingMode);
531   Expected<opStatus> convertFromDecimalString(StringRef, roundingMode);
532   char *convertNormalToHexString(char *, unsigned int, bool,
533                                  roundingMode) const;
534   opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
535                                         roundingMode);
536 
537   /// @}
538 
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);
552 
553   void assign(const IEEEFloat &);
554   void copySignificand(const IEEEFloat &);
555   void freeSignificand();
556 
557   /// Note: this must be the first data member.
558   /// The semantics that this value obeys.
559   const fltSemantics *semantics;
560 
561   /// A binary fraction with an explicit integer bit.
562   ///
563   /// The significand must be at least one bit wider than the target precision.
564   union Significand {
565     integerPart part;
566     integerPart *parts;
567   } significand;
568 
569   /// The signed unbiased exponent of the value.
570   ExponentType exponent;
571 
572   /// What kind of floating point number this is.
573   ///
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;
577 
578   /// Sign bit of the number.
579   unsigned int sign : 1;
580 };
581 
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);
586 
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;
595 
596   opStatus addImpl(const APFloat &a, const APFloat &aa, const APFloat &c,
597                    const APFloat &cc, roundingMode RM);
598 
599   opStatus addWithSpecial(const DoubleAPFloat &LHS, const DoubleAPFloat &RHS,
600                           DoubleAPFloat &Out, roundingMode RM);
601 
602 public:
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);
610 
611   DoubleAPFloat &operator=(const DoubleAPFloat &RHS);
612 
613   DoubleAPFloat &operator=(DoubleAPFloat &&RHS) {
614     if (this != &RHS) {
615       this->~DoubleAPFloat();
616       new (this) DoubleAPFloat(std::move(RHS));
617     }
618     return *this;
619   }
620 
621   bool needsCleanup() const { return Floats != nullptr; }
622 
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]; }
627 
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);
637   void changeSign();
638   cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const;
639 
640   fltCategory getCategory() const;
641   bool isNegative() const;
642 
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);
649 
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);
655 
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,
662                                           roundingMode RM);
663   opStatus convertFromZeroExtendedInteger(const integerPart *Input,
664                                           unsigned int InputSize, bool IsSigned,
665                                           roundingMode RM);
666   unsigned int convertToHexString(char *DST, unsigned int HexDigits,
667                                   bool UpperCase, roundingMode RM) const;
668 
669   bool isDenormal() const;
670   bool isSmallest() const;
671   bool isLargest() const;
672   bool isInteger() const;
673 
674   void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
675                 unsigned FormatMaxPadding, bool TruncateZero = true) const;
676 
677   bool getExactInverse(APFloat *inv) const;
678 
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);
683 };
684 
685 hash_code hash_value(const DoubleAPFloat &Arg);
686 
687 } // End detail namespace
688 
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;
694 
695   static_assert(std::is_standard_layout<IEEEFloat>::value, "");
696 
697   union Storage {
698     const fltSemantics *semantics;
699     IEEEFloat IEEE;
700     DoubleAPFloat Double;
701 
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());
706     }
707 
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)...);
712         return;
713       }
714       if (usesLayout<DoubleAPFloat>(Semantics)) {
715         new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
716         return;
717       }
718       llvm_unreachable("Unexpected semantics");
719     }
720 
721     ~Storage() {
722       if (usesLayout<IEEEFloat>(*semantics)) {
723         IEEE.~IEEEFloat();
724         return;
725       }
726       if (usesLayout<DoubleAPFloat>(*semantics)) {
727         Double.~DoubleAPFloat();
728         return;
729       }
730       llvm_unreachable("Unexpected semantics");
731     }
732 
733     Storage(const Storage &RHS) {
734       if (usesLayout<IEEEFloat>(*RHS.semantics)) {
735         new (this) IEEEFloat(RHS.IEEE);
736         return;
737       }
738       if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
739         new (this) DoubleAPFloat(RHS.Double);
740         return;
741       }
742       llvm_unreachable("Unexpected semantics");
743     }
744 
745     Storage(Storage &&RHS) {
746       if (usesLayout<IEEEFloat>(*RHS.semantics)) {
747         new (this) IEEEFloat(std::move(RHS.IEEE));
748         return;
749       }
750       if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
751         new (this) DoubleAPFloat(std::move(RHS.Double));
752         return;
753       }
754       llvm_unreachable("Unexpected semantics");
755     }
756 
757     Storage &operator=(const Storage &RHS) {
758       if (usesLayout<IEEEFloat>(*semantics) &&
759           usesLayout<IEEEFloat>(*RHS.semantics)) {
760         IEEE = RHS.IEEE;
761       } else if (usesLayout<DoubleAPFloat>(*semantics) &&
762                  usesLayout<DoubleAPFloat>(*RHS.semantics)) {
763         Double = RHS.Double;
764       } else if (this != &RHS) {
765         this->~Storage();
766         new (this) Storage(RHS);
767       }
768       return *this;
769     }
770 
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) {
779         this->~Storage();
780         new (this) Storage(std::move(RHS));
781       }
782       return *this;
783     }
784   } U;
785 
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();
791     }
792     return &Semantics != &PPCDoubleDouble();
793   }
794 
795   IEEEFloat &getIEEE() {
796     if (usesLayout<IEEEFloat>(*U.semantics))
797       return U.IEEE;
798     if (usesLayout<DoubleAPFloat>(*U.semantics))
799       return U.Double.getFirst().U.IEEE;
800     llvm_unreachable("Unexpected semantics");
801   }
802 
803   const IEEEFloat &getIEEE() const {
804     if (usesLayout<IEEEFloat>(*U.semantics))
805       return U.IEEE;
806     if (usesLayout<DoubleAPFloat>(*U.semantics))
807       return U.Double.getFirst().U.IEEE;
808     llvm_unreachable("Unexpected semantics");
809   }
810 
811   void makeZero(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeZero(Neg)); }
812 
813   void makeInf(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeInf(Neg)); }
814 
815   void makeNaN(bool SNaN, bool Neg, const APInt *fill) {
816     APFLOAT_DISPATCH_ON_SEMANTICS(makeNaN(SNaN, Neg, fill));
817   }
818 
819   void makeLargest(bool Neg) {
820     APFLOAT_DISPATCH_ON_SEMANTICS(makeLargest(Neg));
821   }
822 
823   void makeSmallest(bool Neg) {
824     APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallest(Neg));
825   }
826 
827   void makeSmallestNormalized(bool Neg) {
828     APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallestNormalized(Neg));
829   }
830 
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.");
836   }
837 
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) {}
841 
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");
850   }
851 
852 public:
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;
867 
868   ~APFloat() = default;
869 
870   bool needsCleanup() const { APFLOAT_DISPATCH_ON_SEMANTICS(needsCleanup()); }
871 
872   /// Factory for Positive and Negative Zero.
873   ///
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);
878     return Val;
879   }
880 
881   /// Factory for Positive and Negative Infinity.
882   ///
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);
887     return Val;
888   }
889 
890   /// Factory for NaN values.
891   ///
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) {
897     if (payload) {
898       APInt intPayload(64, payload);
899       return getQNaN(Sem, Negative, &intPayload);
900     } else {
901       return getQNaN(Sem, Negative, nullptr);
902     }
903   }
904 
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);
910     return Val;
911   }
912 
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);
918     return Val;
919   }
920 
921   /// Returns the largest finite number in the given semantics.
922   ///
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);
927     return Val;
928   }
929 
930   /// Returns the smallest (by magnitude) finite number in the given semantics.
931   /// Might be denormalized, which implies a relative loss of precision.
932   ///
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);
937     return Val;
938   }
939 
940   /// Returns the smallest (by magnitude) normalized finite number in the given
941   /// semantics.
942   ///
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);
948     return Val;
949   }
950 
951   /// Returns a float which is bitcasted from an all one value int.
952   ///
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);
956 
957   /// Used to insert APFloat objects, or objects that contain APFloat objects,
958   /// into FoldingSets.
959   void Profile(FoldingSetNodeID &NID) const;
960 
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");
969   }
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");
978   }
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");
987   }
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");
996   }
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");
1005   }
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");
1014   }
1015   opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend,
1016                             roundingMode RM) {
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,
1025                                        RM);
1026     llvm_unreachable("Unexpected semantics");
1027   }
1028   opStatus roundToIntegral(roundingMode RM) {
1029     APFLOAT_DISPATCH_ON_SEMANTICS(roundToIntegral(RM));
1030   }
1031 
1032   // TODO: bool parameters are not readable and a source of bugs.
1033   // Do something.
1034   opStatus next(bool nextDown) {
1035     APFLOAT_DISPATCH_ON_SEMANTICS(next(nextDown));
1036   }
1037 
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);
1043     return Result;
1044   }
1045 
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);
1051     return Result;
1052   }
1053 
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);
1059     return Result;
1060   }
1061 
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);
1067     return Result;
1068   }
1069 
1070   void changeSign() { APFLOAT_DISPATCH_ON_SEMANTICS(changeSign()); }
1071   void clearSign() {
1072     if (isNegative())
1073       changeSign();
1074   }
1075   void copySign(const APFloat &RHS) {
1076     if (isNegative() != RHS.isNegative())
1077       changeSign();
1078   }
1079 
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);
1084     return Value;
1085   }
1086 
1087   opStatus convert(const fltSemantics &ToSemantics, roundingMode RM,
1088                    bool *losesInfo);
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));
1094   }
1095   opStatus convertToInteger(APSInt &Result, roundingMode RM,
1096                             bool *IsExact) const;
1097   opStatus convertFromAPInt(const APInt &Input, bool IsSigned,
1098                             roundingMode RM) {
1099     APFLOAT_DISPATCH_ON_SEMANTICS(convertFromAPInt(Input, IsSigned, RM));
1100   }
1101   opStatus convertFromSignExtendedInteger(const integerPart *Input,
1102                                           unsigned int InputSize, bool IsSigned,
1103                                           roundingMode RM) {
1104     APFLOAT_DISPATCH_ON_SEMANTICS(
1105         convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM));
1106   }
1107   opStatus convertFromZeroExtendedInteger(const integerPart *Input,
1108                                           unsigned int InputSize, bool IsSigned,
1109                                           roundingMode RM) {
1110     APFLOAT_DISPATCH_ON_SEMANTICS(
1111         convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM));
1112   }
1113   Expected<opStatus> convertFromString(StringRef, roundingMode);
1114   APInt bitcastToAPInt() const {
1115     APFLOAT_DISPATCH_ON_SEMANTICS(bitcastToAPInt());
1116   }
1117   double convertToDouble() const { return getIEEE().convertToDouble(); }
1118   float convertToFloat() const { return getIEEE().convertToFloat(); }
1119 
1120   bool operator==(const APFloat &) const = delete;
1121 
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");
1130   }
1131 
1132   bool bitwiseIsEqual(const APFloat &RHS) const {
1133     if (&getSemantics() != &RHS.getSemantics())
1134       return false;
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");
1140   }
1141 
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.
1146   ///
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 {
1151     bool ignored;
1152     APFloat Tmp(V);
1153     Tmp.convert(getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
1154     return bitwiseIsEqual(Tmp);
1155   }
1156 
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));
1161   }
1162 
1163   bool isZero() const { return getCategory() == fcZero; }
1164   bool isInfinity() const { return getCategory() == fcInfinity; }
1165   bool isNaN() const { return getCategory() == fcNaN; }
1166 
1167   bool isNegative() const { return getIEEE().isNegative(); }
1168   bool isDenormal() const { APFLOAT_DISPATCH_ON_SEMANTICS(isDenormal()); }
1169   bool isSignaling() const { return getIEEE().isSignaling(); }
1170 
1171   bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
1172   bool isFinite() const { return !isNaN() && !isInfinity(); }
1173 
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()); }
1183 
1184   APFloat &operator=(const APFloat &RHS) = default;
1185   APFloat &operator=(APFloat &&RHS) = default;
1186 
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));
1191   }
1192 
1193   void print(raw_ostream &) const;
1194   void dump() const;
1195 
1196   bool getExactInverse(APFloat *inv) const {
1197     APFLOAT_DISPATCH_ON_SEMANTICS(getExactInverse(inv));
1198   }
1199 
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);
1204   friend IEEEFloat;
1205   friend DoubleAPFloat;
1206 };
1207 
1208 /// See friend declarations above.
1209 ///
1210 /// These additional declarations are required in order to compile LLVM with IBM
1211 /// xlC compiler.
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");
1219 }
1220 
1221 /// Equivalent of C standard library function.
1222 ///
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");
1231 }
1232 /// Returns the absolute value of the argument.
1233 inline APFloat abs(APFloat X) {
1234   X.clearSign();
1235   return X;
1236 }
1237 
1238 /// Returns the negated value of the argument.
1239 inline APFloat neg(APFloat X) {
1240   X.changeSign();
1241   return X;
1242 }
1243 
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.
1246 LLVM_READONLY
1247 inline APFloat minnum(const APFloat &A, const APFloat &B) {
1248   if (A.isNaN())
1249     return B;
1250   if (B.isNaN())
1251     return A;
1252   return (B.compare(A) == APFloat::cmpLessThan) ? B : A;
1253 }
1254 
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.
1257 LLVM_READONLY
1258 inline APFloat maxnum(const APFloat &A, const APFloat &B) {
1259   if (A.isNaN())
1260     return B;
1261   if (B.isNaN())
1262     return A;
1263   return (A.compare(B) == APFloat::cmpLessThan) ? B : A;
1264 }
1265 
1266 /// Implements IEEE 754-2018 minimum semantics. Returns the smaller of 2
1267 /// arguments, propagating NaNs and treating -0 as less than +0.
1268 LLVM_READONLY
1269 inline APFloat minimum(const APFloat &A, const APFloat &B) {
1270   if (A.isNaN())
1271     return A;
1272   if (B.isNaN())
1273     return 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;
1277 }
1278 
1279 /// Implements IEEE 754-2018 maximum semantics. Returns the larger of 2
1280 /// arguments, propagating NaNs and treating -0 as less than +0.
1281 LLVM_READONLY
1282 inline APFloat maximum(const APFloat &A, const APFloat &B) {
1283   if (A.isNaN())
1284     return A;
1285   if (B.isNaN())
1286     return 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;
1290 }
1291 
1292 } // namespace llvm
1293 
1294 #undef APFLOAT_DISPATCH_ON_SEMANTICS
1295 #endif // LLVM_ADT_APFLOAT_H
1296