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