Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/include/llvm/ADT/APFloat.h
Line
Count
Source (jump to first uncovered line)
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
1.88M
  do {                                                                         \
26
1.88M
    if (usesLayout<IEEEFloat>(getSemantics()))                                 \
27
1.88M
      
return U.IEEE.METHOD_CALL1.88M
; \
28
1.88M
    
if (298
usesLayout<DoubleAPFloat>(getSemantics())298
) \
29
299
      return U.Double.METHOD_CALL;                                             \
30
18.4E
    llvm_unreachable("Unexpected semantics");                                  \
31
298
  } while (
false0
)
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 {
142
  typedef APInt::WordType integerPart;
143
  static const unsigned integerPartWidth = APInt::APINT_BITS_PER_WORD;
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 {
151
    S_IEEEhalf,
152
    S_IEEEsingle,
153
    S_IEEEdouble,
154
    S_x87DoubleExtended,
155
    S_IEEEquad,
156
    S_PPCDoubleDouble
157
  };
158
159
  static const llvm::fltSemantics &EnumToSemantics(Semantics S);
160
  static Semantics SemanticsToEnum(const llvm::fltSemantics &Sem);
161
162
  static const fltSemantics &IEEEhalf() LLVM_READNONE;
163
  static const fltSemantics &IEEEsingle() 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 {
177
    cmpLessThan,
178
    cmpEqual,
179
    cmpGreaterThan,
180
    cmpUnordered
181
  };
182
183
  /// IEEE-754R 4.3: Rounding-direction attributes.
184
  enum roundingMode {
185
    rmNearestTiesToEven,
186
    rmTowardPositive,
187
    rmTowardNegative,
188
    rmTowardZero,
189
    rmNearestTiesToAway
190
  };
191
192
  /// IEEE-754R 7: Default exception handling.
193
  ///
194
  /// opUnderflow or opOverflow are always returned or-ed with opInexact.
195
  enum opStatus {
196
    opOK = 0x00,
197
    opInvalidOp = 0x01,
198
    opDivByZero = 0x02,
199
    opOverflow = 0x04,
200
    opUnderflow = 0x08,
201
    opInexact = 0x10
202
  };
203
204
  /// Category of internally-represented number.
205
  enum fltCategory {
206
    fcInfinity,
207
    fcNaN,
208
    fcNormal,
209
    fcZero
210
  };
211
212
  /// Convenience enum used to construct an uninitialized APFloat.
213
  enum uninitializedTag {
214
    uninitialized
215
  };
216
217
  /// Enumeration of \c ilogb error results.
218
  enum IlogbErrorKinds {
219
    IEK_Zero = INT_MIN + 1,
220
    IEK_NaN = INT_MIN,
221
    IEK_Inf = INT_MAX
222
  };
223
224
  static unsigned int semanticsPrecision(const fltSemantics &);
225
  static ExponentType semanticsMinExponent(const fltSemantics &);
226
  static ExponentType semanticsMaxExponent(const fltSemantics &);
227
  static unsigned int semanticsSizeInBits(const fltSemantics &);
228
229
  /// Returns the size of the floating point number (in bits) in the given
230
  /// semantics.
231
  static unsigned getSizeInBits(const fltSemantics &Sem);
232
};
233
234
namespace detail {
235
236
class IEEEFloat final : public APFloatBase {
237
public:
238
  /// \name Constructors
239
  /// @{
240
241
  IEEEFloat(const fltSemantics &); // Default construct to 0.0
242
  IEEEFloat(const fltSemantics &, integerPart);
243
  IEEEFloat(const fltSemantics &, uninitializedTag);
244
  IEEEFloat(const fltSemantics &, const APInt &);
245
  explicit IEEEFloat(double d);
246
  explicit IEEEFloat(float f);
247
  IEEEFloat(const IEEEFloat &);
248
  IEEEFloat(IEEEFloat &&);
249
  ~IEEEFloat();
250
251
  /// @}
252
253
  /// Returns whether this instance allocated memory.
254
27.2M
  bool needsCleanup() const { return partCount() > 1; }
255
256
  /// \name Convenience "constructors"
257
  /// @{
258
259
  /// @}
260
261
  /// \name Arithmetic
262
  /// @{
263
264
  opStatus add(const IEEEFloat &, roundingMode);
265
  opStatus subtract(const IEEEFloat &, roundingMode);
266
  opStatus multiply(const IEEEFloat &, roundingMode);
267
  opStatus divide(const IEEEFloat &, roundingMode);
268
  /// IEEE remainder.
269
  opStatus remainder(const IEEEFloat &);
270
  /// C fmod, or llvm frem.
271
  opStatus mod(const IEEEFloat &);
272
  opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode);
273
  opStatus roundToIntegral(roundingMode);
274
  /// IEEE-754R 5.3.1: nextUp/nextDown.
275
  opStatus next(bool nextDown);
276
277
  /// @}
278
279
  /// \name Sign operations.
280
  /// @{
281
282
  void changeSign();
283
284
  /// @}
285
286
  /// \name Conversions
287
  /// @{
288
289
  opStatus convert(const fltSemantics &, roundingMode, bool *);
290
  opStatus convertToInteger(MutableArrayRef<integerPart>, unsigned int, bool,
291
                            roundingMode, bool *) const;
292
  opStatus convertFromAPInt(const APInt &, bool, roundingMode);
293
  opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
294
                                          bool, roundingMode);
295
  opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
296
                                          bool, roundingMode);
297
  opStatus convertFromString(StringRef, roundingMode);
298
  APInt bitcastToAPInt() const;
299
  double convertToDouble() const;
300
  float convertToFloat() const;
301
302
  /// @}
303
304
  /// The definition of equality is not straightforward for floating point, so
305
  /// we won't use operator==.  Use one of the following, or write whatever it
306
  /// is you really mean.
307
  bool operator==(const IEEEFloat &) const = delete;
308
309
  /// IEEE comparison with another floating point number (NaNs compare
310
  /// unordered, 0==-0).
311
  cmpResult compare(const IEEEFloat &) const;
312
313
  /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
314
  bool bitwiseIsEqual(const IEEEFloat &) const;
315
316
  /// Write out a hexadecimal representation of the floating point value to DST,
317
  /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d.
318
  /// Return the number of characters written, excluding the terminating NUL.
319
  unsigned int convertToHexString(char *dst, unsigned int hexDigits,
320
                                  bool upperCase, roundingMode) const;
321
322
  /// \name IEEE-754R 5.7.2 General operations.
323
  /// @{
324
325
  /// IEEE-754R isSignMinus: Returns true if and only if the current value is
326
  /// negative.
327
  ///
328
  /// This applies to zeros and NaNs as well.
329
953k
  bool isNegative() const { return sign; }
330
331
  /// IEEE-754R isNormal: Returns true if and only if the current value is normal.
332
  ///
333
  /// This implies that the current value of the float is not zero, subnormal,
334
  /// infinite, or NaN following the definition of normality from IEEE-754R.
335
0
  bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
336
337
  /// Returns true if and only if the current value is zero, subnormal, or
338
  /// normal.
339
  ///
340
  /// This means that the value is not infinite or NaN.
341
13.0M
  bool isFinite() const { return !isNaN() && 
!isInfinity()12.9M
; }
342
343
  /// Returns true if and only if the float is plus or minus zero.
344
12.9M
  bool isZero() const { return category == fcZero; }
345
346
  /// IEEE-754R isSubnormal(): Returns true if and only if the float is a
347
  /// denormal.
348
  bool isDenormal() const;
349
350
  /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
351
12.9M
  bool isInfinity() const { return category == fcInfinity; }
352
353
  /// Returns true if and only if the float is a quiet or signaling NaN.
354
13.2M
  bool isNaN() const { return category == fcNaN; }
355
356
  /// Returns true if and only if the float is a signaling NaN.
357
  bool isSignaling() const;
358
359
  /// @}
360
361
  /// \name Simple Queries
362
  /// @{
363
364
4.99M
  fltCategory getCategory() const { return category; }
365
956
  const fltSemantics &getSemantics() const { return *semantics; }
366
119
  bool isNonZero() const { return category != fcZero; }
367
13.0M
  bool isFiniteNonZero() const { return isFinite() && 
!isZero()12.9M
; }
368
0
  bool isPosZero() const { return isZero() && !isNegative(); }
369
0
  bool isNegZero() const { return isZero() && isNegative(); }
370
371
  /// Returns true if and only if the number has the smallest possible non-zero
372
  /// magnitude in the current semantics.
373
  bool isSmallest() const;
374
375
  /// Returns true if and only if the number has the largest possible finite
376
  /// magnitude in the current semantics.
377
  bool isLargest() const;
378
379
  /// Returns true if and only if the number is an exact integer.
380
  bool isInteger() const;
381
382
  /// @}
383
384
  IEEEFloat &operator=(const IEEEFloat &);
385
  IEEEFloat &operator=(IEEEFloat &&);
386
387
  /// Overload to compute a hash code for an APFloat value.
388
  ///
389
  /// Note that the use of hash codes for floating point values is in general
390
  /// frought with peril. Equality is hard to define for these values. For
391
  /// example, should negative and positive zero hash to different codes? Are
392
  /// they equal or not? This hash value implementation specifically
393
  /// emphasizes producing different codes for different inputs in order to
394
  /// be used in canonicalization and memoization. As such, equality is
395
  /// bitwiseIsEqual, and 0 != -0.
396
  friend hash_code hash_value(const IEEEFloat &Arg);
397
398
  /// Converts this value into a decimal string.
399
  ///
400
  /// \param FormatPrecision The maximum number of digits of
401
  ///   precision to output.  If there are fewer digits available,
402
  ///   zero padding will not be used unless the value is
403
  ///   integral and small enough to be expressed in
404
  ///   FormatPrecision digits.  0 means to use the natural
405
  ///   precision of the number.
406
  /// \param FormatMaxPadding The maximum number of zeros to
407
  ///   consider inserting before falling back to scientific
408
  ///   notation.  0 means to always use scientific notation.
409
  ///
410
  /// \param TruncateZero Indicate whether to remove the trailing zero in
411
  ///   fraction part or not. Also setting this parameter to false forcing
412
  ///   producing of output more similar to default printf behavior.
413
  ///   Specifically the lower e is used as exponent delimiter and exponent
414
  ///   always contains no less than two digits.
415
  ///
416
  /// Number       Precision    MaxPadding      Result
417
  /// ------       ---------    ----------      ------
418
  /// 1.01E+4              5             2       10100
419
  /// 1.01E+4              4             2       1.01E+4
420
  /// 1.01E+4              5             1       1.01E+4
421
  /// 1.01E-2              5             2       0.0101
422
  /// 1.01E-2              4             2       0.0101
423
  /// 1.01E-2              4             1       1.01E-2
424
  void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
425
                unsigned FormatMaxPadding = 3, bool TruncateZero = true) const;
426
427
  /// If this value has an exact multiplicative inverse, store it in inv and
428
  /// return true.
429
  bool getExactInverse(APFloat *inv) const;
430
431
  /// Returns the exponent of the internal representation of the APFloat.
432
  ///
433
  /// Because the radix of APFloat is 2, this is equivalent to floor(log2(x)).
434
  /// For special APFloat values, this returns special error codes:
435
  ///
436
  ///   NaN -> \c IEK_NaN
437
  ///   0   -> \c IEK_Zero
438
  ///   Inf -> \c IEK_Inf
439
  ///
440
  friend int ilogb(const IEEEFloat &Arg);
441
442
  /// Returns: X * 2^Exp for integral exponents.
443
  friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode);
444
445
  friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode);
446
447
  /// \name Special value setters.
448
  /// @{
449
450
  void makeLargest(bool Neg = false);
451
  void makeSmallest(bool Neg = false);
452
  void makeNaN(bool SNaN = false, bool Neg = false,
453
               const APInt *fill = nullptr);
454
  void makeInf(bool Neg = false);
455
  void makeZero(bool Neg = false);
456
  void makeQuiet();
457
458
  /// Returns the smallest (by magnitude) normalized finite number in the given
459
  /// semantics.
460
  ///
461
  /// \param Negative - True iff the number should be negative
462
  void makeSmallestNormalized(bool Negative = false);
463
464
  /// @}
465
466
  cmpResult compareAbsoluteValue(const IEEEFloat &) const;
467
468
private:
469
  /// \name Simple Queries
470
  /// @{
471
472
  integerPart *significandParts();
473
  const integerPart *significandParts() const;
474
  unsigned int partCount() const;
475
476
  /// @}
477
478
  /// \name Significand operations.
479
  /// @{
480
481
  integerPart addSignificand(const IEEEFloat &);
482
  integerPart subtractSignificand(const IEEEFloat &, integerPart);
483
  lostFraction addOrSubtractSignificand(const IEEEFloat &, bool subtract);
484
  lostFraction multiplySignificand(const IEEEFloat &, const IEEEFloat *);
485
  lostFraction divideSignificand(const IEEEFloat &);
486
  void incrementSignificand();
487
  void initialize(const fltSemantics *);
488
  void shiftSignificandLeft(unsigned int);
489
  lostFraction shiftSignificandRight(unsigned int);
490
  unsigned int significandLSB() const;
491
  unsigned int significandMSB() const;
492
  void zeroSignificand();
493
  /// Return true if the significand excluding the integral bit is all ones.
494
  bool isSignificandAllOnes() const;
495
  /// Return true if the significand excluding the integral bit is all zeros.
496
  bool isSignificandAllZeros() const;
497
498
  /// @}
499
500
  /// \name Arithmetic on special values.
501
  /// @{
502
503
  opStatus addOrSubtractSpecials(const IEEEFloat &, bool subtract);
504
  opStatus divideSpecials(const IEEEFloat &);
505
  opStatus multiplySpecials(const IEEEFloat &);
506
  opStatus modSpecials(const IEEEFloat &);
507
508
  /// @}
509
510
  /// \name Miscellany
511
  /// @{
512
513
  bool convertFromStringSpecials(StringRef str);
514
  opStatus normalize(roundingMode, lostFraction);
515
  opStatus addOrSubtract(const IEEEFloat &, roundingMode, bool subtract);
516
  opStatus handleOverflow(roundingMode);
517
  bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
518
  opStatus convertToSignExtendedInteger(MutableArrayRef<integerPart>,
519
                                        unsigned int, bool, roundingMode,
520
                                        bool *) const;
521
  opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
522
                                    roundingMode);
523
  opStatus convertFromHexadecimalString(StringRef, roundingMode);
524
  opStatus convertFromDecimalString(StringRef, roundingMode);
525
  char *convertNormalToHexString(char *, unsigned int, bool,
526
                                 roundingMode) const;
527
  opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
528
                                        roundingMode);
529
530
  /// @}
531
532
  APInt convertHalfAPFloatToAPInt() const;
533
  APInt convertFloatAPFloatToAPInt() const;
534
  APInt convertDoubleAPFloatToAPInt() const;
535
  APInt convertQuadrupleAPFloatToAPInt() const;
536
  APInt convertF80LongDoubleAPFloatToAPInt() const;
537
  APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
538
  void initFromAPInt(const fltSemantics *Sem, const APInt &api);
539
  void initFromHalfAPInt(const APInt &api);
540
  void initFromFloatAPInt(const APInt &api);
541
  void initFromDoubleAPInt(const APInt &api);
542
  void initFromQuadrupleAPInt(const APInt &api);
543
  void initFromF80LongDoubleAPInt(const APInt &api);
544
  void initFromPPCDoubleDoubleAPInt(const APInt &api);
545
546
  void assign(const IEEEFloat &);
547
  void copySignificand(const IEEEFloat &);
548
  void freeSignificand();
549
550
  /// Note: this must be the first data member.
551
  /// The semantics that this value obeys.
552
  const fltSemantics *semantics;
553
554
  /// A binary fraction with an explicit integer bit.
555
  ///
556
  /// The significand must be at least one bit wider than the target precision.
557
  union Significand {
558
    integerPart part;
559
    integerPart *parts;
560
  } significand;
561
562
  /// The signed unbiased exponent of the value.
563
  ExponentType exponent;
564
565
  /// What kind of floating point number this is.
566
  ///
567
  /// Only 2 bits are required, but VisualStudio incorrectly sign extends it.
568
  /// Using the extra bit keeps it from failing under VisualStudio.
569
  fltCategory category : 3;
570
571
  /// Sign bit of the number.
572
  unsigned int sign : 1;
573
};
574
575
hash_code hash_value(const IEEEFloat &Arg);
576
int ilogb(const IEEEFloat &Arg);
577
IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode);
578
IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM);
579
580
// This mode implements more precise float in terms of two APFloats.
581
// The interface and layout is designed for arbitray underlying semantics,
582
// though currently only PPCDoubleDouble semantics are supported, whose
583
// corresponding underlying semantics are IEEEdouble.
584
class DoubleAPFloat final : public APFloatBase {
585
  // Note: this must be the first data member.
586
  const fltSemantics *Semantics;
587
  std::unique_ptr<APFloat[]> Floats;
588
589
  opStatus addImpl(const APFloat &a, const APFloat &aa, const APFloat &c,
590
                   const APFloat &cc, roundingMode RM);
591
592
  opStatus addWithSpecial(const DoubleAPFloat &LHS, const DoubleAPFloat &RHS,
593
                          DoubleAPFloat &Out, roundingMode RM);
594
595
public:
596
  DoubleAPFloat(const fltSemantics &S);
597
  DoubleAPFloat(const fltSemantics &S, uninitializedTag);
598
  DoubleAPFloat(const fltSemantics &S, integerPart);
599
  DoubleAPFloat(const fltSemantics &S, const APInt &I);
600
  DoubleAPFloat(const fltSemantics &S, APFloat &&First, APFloat &&Second);
601
  DoubleAPFloat(const DoubleAPFloat &RHS);
602
  DoubleAPFloat(DoubleAPFloat &&RHS);
603
604
  DoubleAPFloat &operator=(const DoubleAPFloat &RHS);
605
606
99
  DoubleAPFloat &operator=(DoubleAPFloat &&RHS) {
607
99
    if (this != &RHS) {
608
99
      this->~DoubleAPFloat();
609
99
      new (this) DoubleAPFloat(std::move(RHS));
610
99
    }
611
99
    return *this;
612
99
  }
613
614
5
  bool needsCleanup() const { return Floats != nullptr; }
615
616
4
  APFloat &getFirst() { return Floats[0]; }
617
544
  const APFloat &getFirst() const { return Floats[0]; }
618
0
  APFloat &getSecond() { return Floats[1]; }
619
0
  const APFloat &getSecond() const { return Floats[1]; }
620
621
  opStatus add(const DoubleAPFloat &RHS, roundingMode RM);
622
  opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM);
623
  opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM);
624
  opStatus divide(const DoubleAPFloat &RHS, roundingMode RM);
625
  opStatus remainder(const DoubleAPFloat &RHS);
626
  opStatus mod(const DoubleAPFloat &RHS);
627
  opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
628
                            const DoubleAPFloat &Addend, roundingMode RM);
629
  opStatus roundToIntegral(roundingMode RM);
630
  void changeSign();
631
  cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const;
632
633
  fltCategory getCategory() const;
634
  bool isNegative() const;
635
636
  void makeInf(bool Neg);
637
  void makeZero(bool Neg);
638
  void makeLargest(bool Neg);
639
  void makeSmallest(bool Neg);
640
  void makeSmallestNormalized(bool Neg);
641
  void makeNaN(bool SNaN, bool Neg, const APInt *fill);
642
643
  cmpResult compare(const DoubleAPFloat &RHS) const;
644
  bool bitwiseIsEqual(const DoubleAPFloat &RHS) const;
645
  APInt bitcastToAPInt() const;
646
  opStatus convertFromString(StringRef, roundingMode);
647
  opStatus next(bool nextDown);
648
649
  opStatus convertToInteger(MutableArrayRef<integerPart> Input,
650
                            unsigned int Width, bool IsSigned, roundingMode RM,
651
                            bool *IsExact) const;
652
  opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM);
653
  opStatus convertFromSignExtendedInteger(const integerPart *Input,
654
                                          unsigned int InputSize, bool IsSigned,
655
                                          roundingMode RM);
656
  opStatus convertFromZeroExtendedInteger(const integerPart *Input,
657
                                          unsigned int InputSize, bool IsSigned,
658
                                          roundingMode RM);
659
  unsigned int convertToHexString(char *DST, unsigned int HexDigits,
660
                                  bool UpperCase, roundingMode RM) const;
661
662
  bool isDenormal() const;
663
  bool isSmallest() const;
664
  bool isLargest() const;
665
  bool isInteger() const;
666
667
  void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
668
                unsigned FormatMaxPadding, bool TruncateZero = true) const;
669
670
  bool getExactInverse(APFloat *inv) const;
671
672
  friend int ilogb(const DoubleAPFloat &Arg);
673
  friend DoubleAPFloat scalbn(DoubleAPFloat X, int Exp, roundingMode);
674
  friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp, roundingMode);
675
  friend hash_code hash_value(const DoubleAPFloat &Arg);
676
};
677
678
hash_code hash_value(const DoubleAPFloat &Arg);
679
680
} // End detail namespace
681
682
// This is a interface class that is currently forwarding functionalities from
683
// detail::IEEEFloat.
684
class APFloat : public APFloatBase {
685
  typedef detail::IEEEFloat IEEEFloat;
686
  typedef detail::DoubleAPFloat DoubleAPFloat;
687
688
  static_assert(std::is_standard_layout<IEEEFloat>::value, "");
689
690
  union Storage {
691
    const fltSemantics *semantics;
692
    IEEEFloat IEEE;
693
    DoubleAPFloat Double;
694
695
    explicit Storage(IEEEFloat F, const fltSemantics &S);
696
    explicit Storage(DoubleAPFloat F, const fltSemantics &S)
697
4
        : Double(std::move(F)) {
698
4
      assert(&S == &PPCDoubleDouble());
699
4
    }
700
701
    template <typename... ArgTypes>
702
4.15M
    Storage(const fltSemantics &Semantics, ArgTypes &&... Args) {
703
4.15M
      if (usesLayout<IEEEFloat>(Semantics)) {
704
4.15M
        new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...);
705
4.15M
        return;
706
4.15M
      }
707
396
      
if (391
usesLayout<DoubleAPFloat>(Semantics)391
) {
708
396
        new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
709
396
        return;
710
396
      }
711
18.4E
      llvm_unreachable("Unexpected semantics");
712
18.4E
    }
llvm::APFloat::Storage::Storage<llvm::APInt const&>(llvm::fltSemantics const&, llvm::APInt const&&&)
Line
Count
Source
702
1.17M
    Storage(const fltSemantics &Semantics, ArgTypes &&... Args) {
703
1.17M
      if (usesLayout<IEEEFloat>(Semantics)) {
704
1.17M
        new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...);
705
1.17M
        return;
706
1.17M
      }
707
312
      if (usesLayout<DoubleAPFloat>(Semantics)) {
708
312
        new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
709
312
        return;
710
312
      }
711
0
      llvm_unreachable("Unexpected semantics");
712
0
    }
llvm::APFloat::Storage::Storage<>(llvm::fltSemantics const&)
Line
Count
Source
702
360k
    Storage(const fltSemantics &Semantics, ArgTypes &&... Args) {
703
360k
      if (usesLayout<IEEEFloat>(Semantics)) {
704
360k
        new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...);
705
360k
        return;
706
360k
      }
707
46
      if (usesLayout<DoubleAPFloat>(Semantics)) {
708
46
        new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
709
46
        return;
710
46
      }
711
0
      llvm_unreachable("Unexpected semantics");
712
0
    }
llvm::APFloat::Storage::Storage<llvm::APFloatBase::uninitializedTag>(llvm::fltSemantics const&, llvm::APFloatBase::uninitializedTag&&)
Line
Count
Source
702
96.6k
    Storage(const fltSemantics &Semantics, ArgTypes &&... Args) {
703
96.6k
      if (usesLayout<IEEEFloat>(Semantics)) {
704
96.6k
        new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...);
705
96.6k
        return;
706
96.6k
      }
707
34
      
if (29
usesLayout<DoubleAPFloat>(Semantics)29
) {
708
34
        new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
709
34
        return;
710
34
      }
711
18.4E
      llvm_unreachable("Unexpected semantics");
712
18.4E
    }
llvm::APFloat::Storage::Storage<unsigned long long&>(llvm::fltSemantics const&, unsigned long long&&&)
Line
Count
Source
702
2.52M
    Storage(const fltSemantics &Semantics, ArgTypes &&... Args) {
703
2.52M
      if (usesLayout<IEEEFloat>(Semantics)) {
704
2.52M
        new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...);
705
2.52M
        return;
706
2.52M
      }
707
4
      if (usesLayout<DoubleAPFloat>(Semantics)) {
708
4
        new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
709
4
        return;
710
4
      }
711
0
      llvm_unreachable("Unexpected semantics");
712
0
    }
713
714
12.3M
    ~Storage() {
715
12.3M
      if (usesLayout<IEEEFloat>(*semantics)) {
716
12.3M
        IEEE.~IEEEFloat();
717
12.3M
        return;
718
12.3M
      }
719
745
      
if (740
usesLayout<DoubleAPFloat>(*semantics)740
) {
720
745
        Double.~DoubleAPFloat();
721
745
        return;
722
745
      }
723
18.4E
      llvm_unreachable("Unexpected semantics");
724
18.4E
    }
725
726
2.00M
    Storage(const Storage &RHS) {
727
2.00M
      if (usesLayout<IEEEFloat>(*RHS.semantics)) {
728
2.00M
        new (this) IEEEFloat(RHS.IEEE);
729
2.00M
        return;
730
2.00M
      }
731
399
      
if (394
usesLayout<DoubleAPFloat>(*RHS.semantics)394
) {
732
399
        new (this) DoubleAPFloat(RHS.Double);
733
399
        return;
734
399
      }
735
18.4E
      llvm_unreachable("Unexpected semantics");
736
18.4E
    }
737
738
246k
    Storage(Storage &&RHS) {
739
246k
      if (usesLayout<IEEEFloat>(*RHS.semantics)) {
740
246k
        new (this) IEEEFloat(std::move(RHS.IEEE));
741
246k
        return;
742
246k
      }
743
145
      if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
744
145
        new (this) DoubleAPFloat(std::move(RHS.Double));
745
145
        return;
746
145
      }
747
0
      llvm_unreachable("Unexpected semantics");
748
0
    }
749
750
252k
    Storage &operator=(const Storage &RHS) {
751
252k
      if (usesLayout<IEEEFloat>(*semantics) &&
752
252k
          
usesLayout<IEEEFloat>(*RHS.semantics)252k
) {
753
252k
        IEEE = RHS.IEEE;
754
252k
      } else 
if (243
usesLayout<DoubleAPFloat>(*semantics)243
&&
755
243
                 
usesLayout<DoubleAPFloat>(*RHS.semantics)85
) {
756
2
        Double = RHS.Double;
757
241
      } else if (this != &RHS) {
758
241
        this->~Storage();
759
241
        new (this) Storage(RHS);
760
241
      }
761
252k
      return *this;
762
252k
    }
763
764
804k
    Storage &operator=(Storage &&RHS) {
765
804k
      if (usesLayout<IEEEFloat>(*semantics) &&
766
804k
          
usesLayout<IEEEFloat>(*RHS.semantics)804k
) {
767
804k
        IEEE = std::move(RHS.IEEE);
768
804k
      } else 
if (169
usesLayout<DoubleAPFloat>(*semantics)169
&&
769
169
                 
usesLayout<DoubleAPFloat>(*RHS.semantics)50
) {
770
39
        Double = std::move(RHS.Double);
771
130
      } else if (this != &RHS) {
772
130
        this->~Storage();
773
130
        new (this) Storage(std::move(RHS));
774
130
      }
775
804k
      return *this;
776
804k
    }
777
  } U;
778
779
40.9M
  template <typename T> static bool usesLayout(const fltSemantics &Semantics) {
780
40.9M
    static_assert(std::is_same<T, IEEEFloat>::value ||
781
40.9M
                  std::is_same<T, DoubleAPFloat>::value, "");
782
40.9M
    if (std::is_same<T, DoubleAPFloat>::value) {
783
3.45k
      return &Semantics == &PPCDoubleDouble();
784
3.45k
    }
785
40.9M
    return &Semantics != &PPCDoubleDouble();
786
40.9M
  }
bool llvm::APFloat::usesLayout<llvm::detail::IEEEFloat>(llvm::fltSemantics const&)
Line
Count
Source
779
40.9M
  template <typename T> static bool usesLayout(const fltSemantics &Semantics) {
780
40.9M
    static_assert(std::is_same<T, IEEEFloat>::value ||
781
40.9M
                  std::is_same<T, DoubleAPFloat>::value, "");
782
40.9M
    if (std::is_same<T, DoubleAPFloat>::value) {
783
0
      return &Semantics == &PPCDoubleDouble();
784
0
    }
785
40.9M
    return &Semantics != &PPCDoubleDouble();
786
40.9M
  }
bool llvm::APFloat::usesLayout<llvm::detail::DoubleAPFloat>(llvm::fltSemantics const&)
Line
Count
Source
779
3.45k
  template <typename T> static bool usesLayout(const fltSemantics &Semantics) {
780
3.45k
    static_assert(std::is_same<T, IEEEFloat>::value ||
781
3.45k
                  std::is_same<T, DoubleAPFloat>::value, "");
782
3.45k
    if (std::is_same<T, DoubleAPFloat>::value) {
783
3.45k
      return &Semantics == &PPCDoubleDouble();
784
3.45k
    }
785
0
    return &Semantics != &PPCDoubleDouble();
786
0
  }
787
788
4
  IEEEFloat &getIEEE() {
789
4
    if (usesLayout<IEEEFloat>(*U.semantics))
790
0
      return U.IEEE;
791
4
    if (usesLayout<DoubleAPFloat>(*U.semantics))
792
4
      return U.Double.getFirst().U.IEEE;
793
0
    llvm_unreachable("Unexpected semantics");
794
0
  }
795
796
5.92M
  const IEEEFloat &getIEEE() const {
797
5.92M
    if (usesLayout<IEEEFloat>(*U.semantics))
798
5.92M
      return U.IEEE;
799
544
    if (usesLayout<DoubleAPFloat>(*U.semantics))
800
544
      return U.Double.getFirst().U.IEEE;
801
0
    llvm_unreachable("Unexpected semantics");
802
0
  }
803
804
69.3k
  void makeZero(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeZero(Neg)); }
805
806
19.3k
  void makeInf(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeInf(Neg)); }
807
808
7.34k
  void makeNaN(bool SNaN, bool Neg, const APInt *fill) {
809
7.34k
    APFLOAT_DISPATCH_ON_SEMANTICS(makeNaN(SNaN, Neg, fill));
810
7.34k
  }
811
812
289
  void makeLargest(bool Neg) {
813
289
    APFLOAT_DISPATCH_ON_SEMANTICS(makeLargest(Neg));
814
289
  }
815
816
50
  void makeSmallest(bool Neg) {
817
50
    APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallest(Neg));
818
50
  }
819
820
307
  void makeSmallestNormalized(bool Neg) {
821
307
    APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallestNormalized(Neg));
822
307
  }
823
824
  // FIXME: This is due to clang 3.3 (or older version) always checks for the
825
  // default constructor in an array aggregate initialization, even if no
826
  // elements in the array is default initialized.
827
0
  APFloat() : U(IEEEdouble()) {
828
0
    llvm_unreachable("This is a workaround for old clang.");
829
0
  }
830
831
209
  explicit APFloat(IEEEFloat F, const fltSemantics &S) : U(std::move(F), S) {}
832
  explicit APFloat(DoubleAPFloat F, const fltSemantics &S)
833
4
      : U(std::move(F), S) {}
834
835
6
  cmpResult compareAbsoluteValue(const APFloat &RHS) const {
836
6
    assert(&getSemantics() == &RHS.getSemantics() &&
837
6
           "Should only compare APFloats with the same semantics");
838
6
    if (usesLayout<IEEEFloat>(getSemantics()))
839
6
      return U.IEEE.compareAbsoluteValue(RHS.U.IEEE);
840
0
    if (usesLayout<DoubleAPFloat>(getSemantics()))
841
0
      return U.Double.compareAbsoluteValue(RHS.U.Double);
842
0
    llvm_unreachable("Unexpected semantics");
843
0
  }
844
845
public:
846
360k
  APFloat(const fltSemantics &Semantics) : U(Semantics) {}
847
  APFloat(const fltSemantics &Semantics, StringRef S);
848
2.52M
  APFloat(const fltSemantics &Semantics, integerPart I) : U(Semantics, I) {}
849
  // TODO: Remove this constructor. This isn't faster than the first one.
850
  APFloat(const fltSemantics &Semantics, uninitializedTag)
851
96.6k
      : U(Semantics, uninitialized) {}
852
1.17M
  APFloat(const fltSemantics &Semantics, const APInt &I) : U(Semantics, I) {}
853
6.48M
  explicit APFloat(double d) : U(IEEEFloat(d), IEEEdouble()) {}
854
26.5k
  explicit APFloat(float f) : U(IEEEFloat(f), IEEEsingle()) {}
855
2.00M
  APFloat(const APFloat &RHS) = default;
856
246k
  APFloat(APFloat &&RHS) = default;
857
858
12.3M
  ~APFloat() = default;
859
860
1.00k
  bool needsCleanup() const { APFLOAT_DISPATCH_ON_SEMANTICS(needsCleanup()); }
861
862
  /// Factory for Positive and Negative Zero.
863
  ///
864
  /// \param Negative True iff the number should be negative.
865
69.2k
  static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
866
69.2k
    APFloat Val(Sem, uninitialized);
867
69.2k
    Val.makeZero(Negative);
868
69.2k
    return Val;
869
69.2k
  }
870
871
  /// Factory for Positive and Negative Infinity.
872
  ///
873
  /// \param Negative True iff the number should be negative.
874
19.3k
  static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
875
19.3k
    APFloat Val(Sem, uninitialized);
876
19.3k
    Val.makeInf(Negative);
877
19.3k
    return Val;
878
19.3k
  }
879
880
  /// Factory for NaN values.
881
  ///
882
  /// \param Negative - True iff the NaN generated should be negative.
883
  /// \param payload - The unspecified fill bits for creating the NaN, 0 by
884
  /// default.  The value is truncated as necessary.
885
  static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
886
2.95k
                        uint64_t payload = 0) {
887
2.95k
    if (payload) {
888
4
      APInt intPayload(64, payload);
889
4
      return getQNaN(Sem, Negative, &intPayload);
890
2.95k
    } else {
891
2.95k
      return getQNaN(Sem, Negative, nullptr);
892
2.95k
    }
893
2.95k
  }
894
895
  /// Factory for QNaN values.
896
  static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false,
897
5.27k
                         const APInt *payload = nullptr) {
898
5.27k
    APFloat Val(Sem, uninitialized);
899
5.27k
    Val.makeNaN(false, Negative, payload);
900
5.27k
    return Val;
901
5.27k
  }
902
903
  /// Factory for SNaN values.
904
  static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false,
905
2.06k
                         const APInt *payload = nullptr) {
906
2.06k
    APFloat Val(Sem, uninitialized);
907
2.06k
    Val.makeNaN(true, Negative, payload);
908
2.06k
    return Val;
909
2.06k
  }
910
911
  /// Returns the largest finite number in the given semantics.
912
  ///
913
  /// \param Negative - True iff the number should be negative
914
289
  static APFloat getLargest(const fltSemantics &Sem, bool Negative = false) {
915
289
    APFloat Val(Sem, uninitialized);
916
289
    Val.makeLargest(Negative);
917
289
    return Val;
918
289
  }
919
920
  /// Returns the smallest (by magnitude) finite number in the given semantics.
921
  /// Might be denormalized, which implies a relative loss of precision.
922
  ///
923
  /// \param Negative - True iff the number should be negative
924
45
  static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false) {
925
45
    APFloat Val(Sem, uninitialized);
926
45
    Val.makeSmallest(Negative);
927
45
    return Val;
928
45
  }
929
930
  /// Returns the smallest (by magnitude) normalized finite number in the given
931
  /// semantics.
932
  ///
933
  /// \param Negative - True iff the number should be negative
934
  static APFloat getSmallestNormalized(const fltSemantics &Sem,
935
307
                                       bool Negative = false) {
936
307
    APFloat Val(Sem, uninitialized);
937
307
    Val.makeSmallestNormalized(Negative);
938
307
    return Val;
939
307
  }
940
941
  /// Returns a float which is bitcasted from an all one value int.
942
  ///
943
  /// \param BitWidth - Select float type
944
  /// \param isIEEE   - If 128 bit number, select between PPC and IEEE
945
  static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false);
946
947
  /// Used to insert APFloat objects, or objects that contain APFloat objects,
948
  /// into FoldingSets.
949
  void Profile(FoldingSetNodeID &NID) const;
950
951
11.2k
  opStatus add(const APFloat &RHS, roundingMode RM) {
952
11.2k
    assert(&getSemantics() == &RHS.getSemantics() &&
953
11.2k
           "Should only call on two APFloats with the same semantics");
954
11.2k
    if (usesLayout<IEEEFloat>(getSemantics()))
955
11.2k
      return U.IEEE.add(RHS.U.IEEE, RM);
956
23
    if (usesLayout<DoubleAPFloat>(getSemantics()))
957
23
      return U.Double.add(RHS.U.Double, RM);
958
0
    llvm_unreachable("Unexpected semantics");
959
0
  }
960
8.65k
  opStatus subtract(const APFloat &RHS, roundingMode RM) {
961
8.65k
    assert(&getSemantics() == &RHS.getSemantics() &&
962
8.65k
           "Should only call on two APFloats with the same semantics");
963
8.65k
    if (usesLayout<IEEEFloat>(getSemantics()))
964
8.64k
      return U.IEEE.subtract(RHS.U.IEEE, RM);
965
8
    if (usesLayout<DoubleAPFloat>(getSemantics()))
966
8
      return U.Double.subtract(RHS.U.Double, RM);
967
0
    llvm_unreachable("Unexpected semantics");
968
0
  }
969
11.6k
  opStatus multiply(const APFloat &RHS, roundingMode RM) {
970
11.6k
    assert(&getSemantics() == &RHS.getSemantics() &&
971
11.6k
           "Should only call on two APFloats with the same semantics");
972
11.6k
    if (usesLayout<IEEEFloat>(getSemantics()))
973
11.6k
      return U.IEEE.multiply(RHS.U.IEEE, RM);
974
40
    if (usesLayout<DoubleAPFloat>(getSemantics()))
975
40
      return U.Double.multiply(RHS.U.Double, RM);
976
0
    llvm_unreachable("Unexpected semantics");
977
0
  }
978
15.2k
  opStatus divide(const APFloat &RHS, roundingMode RM) {
979
15.2k
    assert(&getSemantics() == &RHS.getSemantics() &&
980
15.2k
           "Should only call on two APFloats with the same semantics");
981
15.2k
    if (usesLayout<IEEEFloat>(getSemantics()))
982
15.2k
      return U.IEEE.divide(RHS.U.IEEE, RM);
983
2
    if (usesLayout<DoubleAPFloat>(getSemantics()))
984
2
      return U.Double.divide(RHS.U.Double, RM);
985
0
    llvm_unreachable("Unexpected semantics");
986
0
  }
987
4
  opStatus remainder(const APFloat &RHS) {
988
4
    assert(&getSemantics() == &RHS.getSemantics() &&
989
4
           "Should only call on two APFloats with the same semantics");
990
4
    if (usesLayout<IEEEFloat>(getSemantics()))
991
2
      return U.IEEE.remainder(RHS.U.IEEE);
992
2
    if (usesLayout<DoubleAPFloat>(getSemantics()))
993
2
      return U.Double.remainder(RHS.U.Double);
994
0
    llvm_unreachable("Unexpected semantics");
995
0
  }
996
138
  opStatus mod(const APFloat &RHS) {
997
138
    assert(&getSemantics() == &RHS.getSemantics() &&
998
138
           "Should only call on two APFloats with the same semantics");
999
138
    if (usesLayout<IEEEFloat>(getSemantics()))
1000
136
      return U.IEEE.mod(RHS.U.IEEE);
1001
2
    if (usesLayout<DoubleAPFloat>(getSemantics()))
1002
2
      return U.Double.mod(RHS.U.Double);
1003
0
    llvm_unreachable("Unexpected semantics");
1004
0
  }
1005
  opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend,
1006
134
                            roundingMode RM) {
1007
134
    assert(&getSemantics() == &Multiplicand.getSemantics() &&
1008
134
           "Should only call on APFloats with the same semantics");
1009
134
    assert(&getSemantics() == &Addend.getSemantics() &&
1010
134
           "Should only call on APFloats with the same semantics");
1011
134
    if (usesLayout<IEEEFloat>(getSemantics()))
1012
133
      return U.IEEE.fusedMultiplyAdd(Multiplicand.U.IEEE, Addend.U.IEEE, RM);
1013
1
    if (usesLayout<DoubleAPFloat>(getSemantics()))
1014
1
      return U.Double.fusedMultiplyAdd(Multiplicand.U.Double, Addend.U.Double,
1015
1
                                       RM);
1016
0
    llvm_unreachable("Unexpected semantics");
1017
0
  }
1018
20.1k
  opStatus roundToIntegral(roundingMode RM) {
1019
20.1k
    APFLOAT_DISPATCH_ON_SEMANTICS(roundToIntegral(RM));
1020
20.1k
  }
1021
1022
  // TODO: bool parameters are not readable and a source of bugs.
1023
  // Do something.
1024
47
  opStatus next(bool nextDown) {
1025
47
    APFLOAT_DISPATCH_ON_SEMANTICS(next(nextDown));
1026
47
  }
1027
1028
  /// Add two APFloats, rounding ties to the nearest even.
1029
  /// No error checking.
1030
93
  APFloat operator+(const APFloat &RHS) const {
1031
93
    APFloat Result(*this);
1032
93
    (void)Result.add(RHS, rmNearestTiesToEven);
1033
93
    return Result;
1034
93
  }
1035
1036
  /// Subtract two APFloats, rounding ties to the nearest even.
1037
  /// No error checking.
1038
70
  APFloat operator-(const APFloat &RHS) const {
1039
70
    APFloat Result(*this);
1040
70
    (void)Result.subtract(RHS, rmNearestTiesToEven);
1041
70
    return Result;
1042
70
  }
1043
1044
  /// Multiply two APFloats, rounding ties to the nearest even.
1045
  /// No error checking.
1046
502
  APFloat operator*(const APFloat &RHS) const {
1047
502
    APFloat Result(*this);
1048
502
    (void)Result.multiply(RHS, rmNearestTiesToEven);
1049
502
    return Result;
1050
502
  }
1051
1052
  /// Divide the first APFloat by the second, rounding ties to the nearest even.
1053
  /// No error checking.
1054
296
  APFloat operator/(const APFloat &RHS) const {
1055
296
    APFloat Result(*this);
1056
296
    (void)Result.divide(RHS, rmNearestTiesToEven);
1057
296
    return Result;
1058
296
  }
1059
1060
103k
  void changeSign() { APFLOAT_DISPATCH_ON_SEMANTICS(changeSign()); }
1061
2.41k
  void clearSign() {
1062
2.41k
    if (isNegative())
1063
124
      changeSign();
1064
2.41k
  }
1065
70
  void copySign(const APFloat &RHS) {
1066
70
    if (isNegative() != RHS.isNegative())
1067
15
      changeSign();
1068
70
  }
1069
1070
  /// A static helper to produce a copy of an APFloat value with its sign
1071
  /// copied from some other APFloat.
1072
56
  static APFloat copySign(APFloat Value, const APFloat &Sign) {
1073
56
    Value.copySign(Sign);
1074
56
    return Value;
1075
56
  }
1076
1077
  opStatus convert(const fltSemantics &ToSemantics, roundingMode RM,
1078
                   bool *losesInfo);
1079
  opStatus convertToInteger(MutableArrayRef<integerPart> Input,
1080
                            unsigned int Width, bool IsSigned, roundingMode RM,
1081
63.7k
                            bool *IsExact) const {
1082
63.7k
    APFLOAT_DISPATCH_ON_SEMANTICS(
1083
63.7k
        convertToInteger(Input, Width, IsSigned, RM, IsExact));
1084
63.7k
  }
1085
  opStatus convertToInteger(APSInt &Result, roundingMode RM,
1086
                            bool *IsExact) const;
1087
  opStatus convertFromAPInt(const APInt &Input, bool IsSigned,
1088
53.0k
                            roundingMode RM) {
1089
53.0k
    APFLOAT_DISPATCH_ON_SEMANTICS(convertFromAPInt(Input, IsSigned, RM));
1090
53.0k
  }
1091
  opStatus convertFromSignExtendedInteger(const integerPart *Input,
1092
                                          unsigned int InputSize, bool IsSigned,
1093
0
                                          roundingMode RM) {
1094
0
    APFLOAT_DISPATCH_ON_SEMANTICS(
1095
0
        convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM));
1096
0
  }
1097
  opStatus convertFromZeroExtendedInteger(const integerPart *Input,
1098
                                          unsigned int InputSize, bool IsSigned,
1099
0
                                          roundingMode RM) {
1100
0
    APFLOAT_DISPATCH_ON_SEMANTICS(
1101
0
        convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM));
1102
0
  }
1103
  opStatus convertFromString(StringRef, roundingMode);
1104
1.44M
  APInt bitcastToAPInt() const {
1105
1.44M
    APFLOAT_DISPATCH_ON_SEMANTICS(bitcastToAPInt());
1106
1.44M
  }
1107
30.0k
  double convertToDouble() const { return getIEEE().convertToDouble(); }
1108
13.7k
  float convertToFloat() const { return getIEEE().convertToFloat(); }
1109
1110
  bool operator==(const APFloat &) const = delete;
1111
1112
31.9k
  cmpResult compare(const APFloat &RHS) const {
1113
31.9k
    assert(&getSemantics() == &RHS.getSemantics() &&
1114
31.9k
           "Should only compare APFloats with the same semantics");
1115
31.9k
    if (usesLayout<IEEEFloat>(getSemantics()))
1116
31.9k
      return U.IEEE.compare(RHS.U.IEEE);
1117
12
    if (usesLayout<DoubleAPFloat>(getSemantics()))
1118
12
      return U.Double.compare(RHS.U.Double);
1119
0
    llvm_unreachable("Unexpected semantics");
1120
0
  }
1121
1122
4.77M
  bool bitwiseIsEqual(const APFloat &RHS) const {
1123
4.77M
    if (&getSemantics() != &RHS.getSemantics())
1124
1.54M
      return false;
1125
3.23M
    if (usesLayout<IEEEFloat>(getSemantics()))
1126
3.23M
      return U.IEEE.bitwiseIsEqual(RHS.U.IEEE);
1127
78
    if (usesLayout<DoubleAPFloat>(getSemantics()))
1128
78
      return U.Double.bitwiseIsEqual(RHS.U.Double);
1129
0
    llvm_unreachable("Unexpected semantics");
1130
0
  }
1131
1132
  /// We don't rely on operator== working on double values, as
1133
  /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1134
  /// As such, this method can be used to do an exact bit-for-bit comparison of
1135
  /// two floating point values.
1136
  ///
1137
  /// We leave the version with the double argument here because it's just so
1138
  /// convenient to write "2.0" and the like.  Without this function we'd
1139
  /// have to duplicate its logic everywhere it's called.
1140
93.8k
  bool isExactlyValue(double V) const {
1141
93.8k
    bool ignored;
1142
93.8k
    APFloat Tmp(V);
1143
93.8k
    Tmp.convert(getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
1144
93.8k
    return bitwiseIsEqual(Tmp);
1145
93.8k
  }
1146
1147
  unsigned int convertToHexString(char *DST, unsigned int HexDigits,
1148
254
                                  bool UpperCase, roundingMode RM) const {
1149
254
    APFLOAT_DISPATCH_ON_SEMANTICS(
1150
254
        convertToHexString(DST, HexDigits, UpperCase, RM));
1151
254
  }
1152
1153
2.95M
  bool isZero() const { return getCategory() == fcZero; }
1154
386k
  bool isInfinity() const { return getCategory() == fcInfinity; }
1155
1.65M
  bool isNaN() const { return getCategory() == fcNaN; }
1156
1157
872k
  bool isNegative() const { return getIEEE().isNegative(); }
1158
879
  bool isDenormal() const { APFLOAT_DISPATCH_ON_SEMANTICS(isDenormal()); }
1159
12.5k
  bool isSignaling() const { return getIEEE().isSignaling(); }
1160
1161
514
  bool isNormal() const { return !isDenormal() && 
isFiniteNonZero()494
; }
1162
23.3k
  bool isFinite() const { return !isNaN() && 
!isInfinity()23.3k
; }
1163
1164
4.99M
  fltCategory getCategory() const { return getIEEE().getCategory(); }
1165
19.2M
  const fltSemantics &getSemantics() const { return *U.semantics; }
1166
7.11k
  bool isNonZero() const { return !isZero(); }
1167
1.74k
  bool isFiniteNonZero() const { return isFinite() && 
!isZero()1.71k
; }
1168
594k
  bool isPosZero() const { return isZero() && 
!isNegative()65.3k
; }
1169
934k
  bool isNegZero() const { return isZero() && 
isNegative()282k
; }
1170
  bool isSmallest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isSmallest()); }
1171
  bool isLargest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isLargest()); }
1172
502
  bool isInteger() const { APFLOAT_DISPATCH_ON_SEMANTICS(isInteger()); }
1173
1174
252k
  APFloat &operator=(const APFloat &RHS) = default;
1175
804k
  APFloat &operator=(APFloat &&RHS) = default;
1176
1177
  void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
1178
41.0k
                unsigned FormatMaxPadding = 3, bool TruncateZero = true) const {
1179
41.0k
    APFLOAT_DISPATCH_ON_SEMANTICS(
1180
41.0k
        toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero));
1181
41.0k
  }
1182
1183
  void print(raw_ostream &) const;
1184
  void dump() const;
1185
1186
63.5k
  bool getExactInverse(APFloat *inv) const {
1187
63.5k
    APFLOAT_DISPATCH_ON_SEMANTICS(getExactInverse(inv));
1188
63.5k
  }
1189
1190
  friend hash_code hash_value(const APFloat &Arg);
1191
108
  friend int ilogb(const APFloat &Arg) { return ilogb(Arg.getIEEE()); }
1192
  friend APFloat scalbn(APFloat X, int Exp, roundingMode RM);
1193
  friend APFloat frexp(const APFloat &X, int &Exp, roundingMode RM);
1194
  friend IEEEFloat;
1195
  friend DoubleAPFloat;
1196
};
1197
1198
/// See friend declarations above.
1199
///
1200
/// These additional declarations are required in order to compile LLVM with IBM
1201
/// xlC compiler.
1202
hash_code hash_value(const APFloat &Arg);
1203
144
inline APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM) {
1204
144
  if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
1205
142
    return APFloat(scalbn(X.U.IEEE, Exp, RM), X.getSemantics());
1206
2
  if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
1207
2
    return APFloat(scalbn(X.U.Double, Exp, RM), X.getSemantics());
1208
0
  llvm_unreachable("Unexpected semantics");
1209
0
}
1210
1211
/// Equivalent of C standard library function.
1212
///
1213
/// While the C standard says Exp is an unspecified value for infinity and nan,
1214
/// this returns INT_MAX for infinities, and INT_MIN for NaNs.
1215
61
inline APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM) {
1216
61
  if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
1217
59
    return APFloat(frexp(X.U.IEEE, Exp, RM), X.getSemantics());
1218
2
  if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
1219
2
    return APFloat(frexp(X.U.Double, Exp, RM), X.getSemantics());
1220
0
  llvm_unreachable("Unexpected semantics");
1221
0
}
1222
/// Returns the absolute value of the argument.
1223
87
inline APFloat abs(APFloat X) {
1224
87
  X.clearSign();
1225
87
  return X;
1226
87
}
1227
1228
/// Returns the negated value of the argument.
1229
3.02k
inline APFloat neg(APFloat X) {
1230
3.02k
  X.changeSign();
1231
3.02k
  return X;
1232
3.02k
}
1233
1234
/// Implements IEEE minNum semantics. Returns the smaller of the 2 arguments if
1235
/// both are not NaN. If either argument is a NaN, returns the other argument.
1236
LLVM_READONLY
1237
51
inline APFloat minnum(const APFloat &A, const APFloat &B) {
1238
51
  if (A.isNaN())
1239
8
    return B;
1240
43
  if (B.isNaN())
1241
4
    return A;
1242
39
  return (B.compare(A) == APFloat::cmpLessThan) ? 
B11
:
A28
;
1243
39
}
1244
1245
/// Implements IEEE maxNum semantics. Returns the larger of the 2 arguments if
1246
/// both are not NaN. If either argument is a NaN, returns the other argument.
1247
LLVM_READONLY
1248
86
inline APFloat maxnum(const APFloat &A, const APFloat &B) {
1249
86
  if (A.isNaN())
1250
9
    return B;
1251
77
  if (B.isNaN())
1252
4
    return A;
1253
73
  return (A.compare(B) == APFloat::cmpLessThan) ? 
B23
:
A50
;
1254
73
}
1255
1256
/// Implements IEEE 754-2018 minimum semantics. Returns the smaller of 2
1257
/// arguments, propagating NaNs and treating -0 as less than +0.
1258
LLVM_READONLY
1259
55
inline APFloat minimum(const APFloat &A, const APFloat &B) {
1260
55
  if (A.isNaN())
1261
7
    return A;
1262
48
  if (B.isNaN())
1263
4
    return B;
1264
44
  if (A.isZero() && 
B.isZero()11
&&
(A.isNegative() != B.isNegative())11
)
1265
7
    return A.isNegative() ? 
A3
:
B4
;
1266
37
  return (B.compare(A) == APFloat::cmpLessThan) ? 
B26
:
A11
;
1267
37
}
1268
1269
/// Implements IEEE 754-2018 maximum semantics. Returns the larger of 2
1270
/// arguments, propagating NaNs and treating -0 as less than +0.
1271
LLVM_READONLY
1272
55
inline APFloat maximum(const APFloat &A, const APFloat &B) {
1273
55
  if (A.isNaN())
1274
7
    return A;
1275
48
  if (B.isNaN())
1276
4
    return B;
1277
44
  if (A.isZero() && 
B.isZero()11
&&
(A.isNegative() != B.isNegative())11
)
1278
7
    return A.isNegative() ? 
B3
:
A4
;
1279
37
  return (A.compare(B) == APFloat::cmpLessThan) ? 
B7
:
A30
;
1280
37
}
1281
1282
} // namespace llvm
1283
1284
#undef APFLOAT_DISPATCH_ON_SEMANTICS
1285
#endif // LLVM_ADT_APFLOAT_H