Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Support/APFloat.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
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
// This file implements a class to represent arbitrary precision floating
10
// point values and provide a variety of arithmetic operations on them.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "llvm/ADT/APFloat.h"
15
#include "llvm/ADT/APSInt.h"
16
#include "llvm/ADT/ArrayRef.h"
17
#include "llvm/ADT/FoldingSet.h"
18
#include "llvm/ADT/Hashing.h"
19
#include "llvm/ADT/StringExtras.h"
20
#include "llvm/ADT/StringRef.h"
21
#include "llvm/Config/llvm-config.h"
22
#include "llvm/Support/Debug.h"
23
#include "llvm/Support/ErrorHandling.h"
24
#include "llvm/Support/MathExtras.h"
25
#include "llvm/Support/raw_ostream.h"
26
#include <cstring>
27
#include <limits.h>
28
29
#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL)                             \
30
351k
  do {                                                                         \
31
351k
    if (usesLayout<IEEEFloat>(getSemantics()))                                 \
32
351k
      
return U.IEEE.METHOD_CALL351k
; \
33
351k
    
if (42
usesLayout<DoubleAPFloat>(getSemantics())42
) \
34
42
      return U.Double.METHOD_CALL;                                             \
35
42
    
llvm_unreachable0
("Unexpected semantics"); \
36
42
  } while (
false0
)
37
38
using namespace llvm;
39
40
/// A macro used to combine two fcCategory enums into one key which can be used
41
/// in a switch statement to classify how the interaction of two APFloat's
42
/// categories affects an operation.
43
///
44
/// TODO: If clang source code is ever allowed to use constexpr in its own
45
/// codebase, change this into a static inline function.
46
276k
#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
47
48
/* Assumed in hexadecimal significand parsing, and conversion to
49
   hexadecimal strings.  */
50
static_assert(APFloatBase::integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
51
52
namespace llvm {
53
  /* Represents floating point arithmetic semantics.  */
54
  struct fltSemantics {
55
    /* The largest E such that 2^E is representable; this matches the
56
       definition of IEEE 754.  */
57
    APFloatBase::ExponentType maxExponent;
58
59
    /* The smallest E such that 2^E is a normalized number; this
60
       matches the definition of IEEE 754.  */
61
    APFloatBase::ExponentType minExponent;
62
63
    /* Number of bits in the significand.  This includes the integer
64
       bit.  */
65
    unsigned int precision;
66
67
    /* Number of bits actually used in the semantics. */
68
    unsigned int sizeInBits;
69
  };
70
71
  static const fltSemantics semIEEEhalf = {15, -14, 11, 16};
72
  static const fltSemantics semIEEEsingle = {127, -126, 24, 32};
73
  static const fltSemantics semIEEEdouble = {1023, -1022, 53, 64};
74
  static const fltSemantics semIEEEquad = {16383, -16382, 113, 128};
75
  static const fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80};
76
  static const fltSemantics semBogus = {0, 0, 0, 0};
77
78
  /* The IBM double-double semantics. Such a number consists of a pair of IEEE
79
     64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal,
80
     (double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo.
81
     Therefore it has two 53-bit mantissa parts that aren't necessarily adjacent
82
     to each other, and two 11-bit exponents.
83
84
     Note: we need to make the value different from semBogus as otherwise
85
     an unsafe optimization may collapse both values to a single address,
86
     and we heavily rely on them having distinct addresses.             */
87
  static const fltSemantics semPPCDoubleDouble = {-1, 0, 0, 0};
88
89
  /* These are legacy semantics for the fallback, inaccrurate implementation of
90
     IBM double-double, if the accurate semPPCDoubleDouble doesn't handle the
91
     operation. It's equivalent to having an IEEE number with consecutive 106
92
     bits of mantissa and 11 bits of exponent.
93
94
     It's not equivalent to IBM double-double. For example, a legit IBM
95
     double-double, 1 + epsilon:
96
97
       1 + epsilon = 1 + (1 >> 1076)
98
99
     is not representable by a consecutive 106 bits of mantissa.
100
101
     Currently, these semantics are used in the following way:
102
103
       semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) ->
104
       (64-bit APInt, 64-bit APInt) -> (128-bit APInt) ->
105
       semPPCDoubleDoubleLegacy -> IEEE operations
106
107
     We use bitcastToAPInt() to get the bit representation (in APInt) of the
108
     underlying IEEEdouble, then use the APInt constructor to construct the
109
     legacy IEEE float.
110
111
     TODO: Implement all operations in semPPCDoubleDouble, and delete these
112
     semantics.  */
113
  static const fltSemantics semPPCDoubleDoubleLegacy = {1023, -1022 + 53,
114
                                                        53 + 53, 128};
115
116
308k
  const llvm::fltSemantics &APFloatBase::EnumToSemantics(Semantics S) {
117
308k
    switch (S) {
118
308k
    case S_IEEEhalf:
119
406
      return IEEEhalf();
120
308k
    case S_IEEEsingle:
121
175k
      return IEEEsingle();
122
308k
    case S_IEEEdouble:
123
130k
      return IEEEdouble();
124
308k
    case S_x87DoubleExtended:
125
1.50k
      return x87DoubleExtended();
126
308k
    case S_IEEEquad:
127
251
      return IEEEquad();
128
308k
    case S_PPCDoubleDouble:
129
32
      return PPCDoubleDouble();
130
0
    }
131
0
    llvm_unreachable("Unrecognised floating semantics");
132
0
  }
133
134
  APFloatBase::Semantics
135
242k
  APFloatBase::SemanticsToEnum(const llvm::fltSemantics &Sem) {
136
242k
    if (&Sem == &llvm::APFloat::IEEEhalf())
137
128
      return S_IEEEhalf;
138
242k
    else if (&Sem == &llvm::APFloat::IEEEsingle())
139
164k
      return S_IEEEsingle;
140
77.5k
    else if (&Sem == &llvm::APFloat::IEEEdouble())
141
76.1k
      return S_IEEEdouble;
142
1.36k
    else if (&Sem == &llvm::APFloat::x87DoubleExtended())
143
1.15k
      return S_x87DoubleExtended;
144
205
    else if (&Sem == &llvm::APFloat::IEEEquad())
145
188
      return S_IEEEquad;
146
17
    else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
147
17
      return S_PPCDoubleDouble;
148
17
    else
149
17
      llvm_unreachable("Unknown floating semantics");
150
242k
  }
151
152
570k
  const fltSemantics &APFloatBase::IEEEhalf() {
153
570k
    return semIEEEhalf;
154
570k
  }
155
1.09M
  const fltSemantics &APFloatBase::IEEEsingle() {
156
1.09M
    return semIEEEsingle;
157
1.09M
  }
158
8.07M
  const fltSemantics &APFloatBase::IEEEdouble() {
159
8.07M
    return semIEEEdouble;
160
8.07M
  }
161
84.3k
  const fltSemantics &APFloatBase::IEEEquad() {
162
84.3k
    return semIEEEquad;
163
84.3k
  }
164
444k
  const fltSemantics &APFloatBase::x87DoubleExtended() {
165
444k
    return semX87DoubleExtended;
166
444k
  }
167
2.49M
  const fltSemantics &APFloatBase::Bogus() {
168
2.49M
    return semBogus;
169
2.49M
  }
170
25.3M
  const fltSemantics &APFloatBase::PPCDoubleDouble() {
171
25.3M
    return semPPCDoubleDouble;
172
25.3M
  }
173
174
  /* A tight upper bound on number of parts required to hold the value
175
     pow(5, power) is
176
177
       power * 815 / (351 * integerPartWidth) + 1
178
179
     However, whilst the result may require only this many parts,
180
     because we are multiplying two values to get it, the
181
     multiplication may require an extra part with the excess part
182
     being zero (consider the trivial case of 1 * 1, tcFullMultiply
183
     requires two parts to hold the single-part result).  So we add an
184
     extra one to guarantee enough space whilst multiplying.  */
185
  const unsigned int maxExponent = 16383;
186
  const unsigned int maxPrecision = 113;
187
  const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
188
  const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815) / (351 * APFloatBase::integerPartWidth));
189
190
103k
  unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
191
103k
    return semantics.precision;
192
103k
  }
193
  APFloatBase::ExponentType
194
2
  APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) {
195
2
    return semantics.maxExponent;
196
2
  }
197
  APFloatBase::ExponentType
198
2
  APFloatBase::semanticsMinExponent(const fltSemantics &semantics) {
199
2
    return semantics.minExponent;
200
2
  }
201
119
  unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
202
119
    return semantics.sizeInBits;
203
119
  }
204
205
472
  unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) {
206
472
    return Sem.sizeInBits;
207
472
}
208
209
/* A bunch of private, handy routines.  */
210
211
static inline unsigned int
212
partCountForBits(unsigned int bits)
213
92.6M
{
214
92.6M
  return ((bits) + APFloatBase::integerPartWidth - 1) / APFloatBase::integerPartWidth;
215
92.6M
}
216
217
/* Returns 0U-9U.  Return values >= 10U are not digits.  */
218
static inline unsigned int
219
decDigitValue(unsigned int c)
220
3.67M
{
221
3.67M
  return c - '0';
222
3.67M
}
223
224
/* Return the value of a decimal exponent of the form
225
   [+-]ddddddd.
226
227
   If the exponent overflows, returns a large exponent with the
228
   appropriate sign.  */
229
static int
230
readExponent(StringRef::iterator begin, StringRef::iterator end)
231
66.3k
{
232
66.3k
  bool isNegative;
233
66.3k
  unsigned int absExponent;
234
66.3k
  const unsigned int overlargeExponent = 24000;  /* FIXME.  */
235
66.3k
  StringRef::iterator p = begin;
236
66.3k
237
66.3k
  // Treat no exponent as 0 to match binutils
238
66.3k
  if (p == end || 
(66.3k
(66.3k
*p == '-'66.3k
||
*p == '+'47.9k
) &&
(p + 1) == end65.0k
)) {
239
36
    return 0;
240
36
  }
241
66.3k
242
66.3k
  isNegative = (*p == '-');
243
66.3k
  if (*p == '-' || 
*p == '+'47.9k
) {
244
65.0k
    p++;
245
65.0k
    assert(p != end && "Exponent has no digits");
246
65.0k
  }
247
66.3k
248
66.3k
  absExponent = decDigitValue(*p++);
249
66.3k
  assert(absExponent < 10U && "Invalid character in exponent");
250
66.3k
251
135k
  for (; p != end; 
++p69.5k
) {
252
69.5k
    unsigned int value;
253
69.5k
254
69.5k
    value = decDigitValue(*p);
255
69.5k
    assert(value < 10U && "Invalid character in exponent");
256
69.5k
257
69.5k
    value += absExponent * 10;
258
69.5k
    if (absExponent >= overlargeExponent) {
259
2
      absExponent = overlargeExponent;
260
2
      p = end;  /* outwit assert below */
261
2
      break;
262
2
    }
263
69.5k
    absExponent = value;
264
69.5k
  }
265
66.3k
266
66.3k
  assert(p == end && "Invalid exponent in exponent");
267
66.3k
268
66.3k
  if (isNegative)
269
18.4k
    return -(int) absExponent;
270
47.9k
  else
271
47.9k
    return (int) absExponent;
272
66.3k
}
273
274
/* This is ugly and needs cleaning up, but I don't immediately see
275
   how whilst remaining safe.  */
276
static int
277
totalExponent(StringRef::iterator p, StringRef::iterator end,
278
              int exponentAdjustment)
279
584
{
280
584
  int unsignedExponent;
281
584
  bool negative, overflow;
282
584
  int exponent = 0;
283
584
284
584
  assert(p != end && "Exponent has no digits");
285
584
286
584
  negative = *p == '-';
287
584
  if (*p == '-' || 
*p == '+'337
) {
288
541
    p++;
289
541
    assert(p != end && "Exponent has no digits");
290
541
  }
291
584
292
584
  unsignedExponent = 0;
293
584
  overflow = false;
294
1.95k
  for (; p != end; 
++p1.37k
) {
295
1.37k
    unsigned int value;
296
1.37k
297
1.37k
    value = decDigitValue(*p);
298
1.37k
    assert(value < 10U && "Invalid character in exponent");
299
1.37k
300
1.37k
    unsignedExponent = unsignedExponent * 10 + value;
301
1.37k
    if (unsignedExponent > 32767) {
302
2
      overflow = true;
303
2
      break;
304
2
    }
305
1.37k
  }
306
584
307
584
  if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
308
0
    overflow = true;
309
584
310
584
  if (!overflow) {
311
582
    exponent = unsignedExponent;
312
582
    if (negative)
313
247
      exponent = -exponent;
314
582
    exponent += exponentAdjustment;
315
582
    if (exponent > 32767 || exponent < -32768)
316
0
      overflow = true;
317
582
  }
318
584
319
584
  if (overflow)
320
2
    exponent = negative ? 
-327680
: 32767;
321
584
322
584
  return exponent;
323
584
}
324
325
static StringRef::iterator
326
skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
327
                           StringRef::iterator *dot)
328
350k
{
329
350k
  StringRef::iterator p = begin;
330
350k
  *dot = end;
331
531k
  while (p != end && 
*p == '0'531k
)
332
180k
    p++;
333
350k
334
350k
  if (p != end && 
*p == '.'350k
) {
335
181k
    *dot = p++;
336
181k
337
181k
    assert(end - begin != 1 && "Significand has no digits");
338
181k
339
376k
    while (p != end && 
*p == '0'346k
)
340
195k
      p++;
341
181k
  }
342
350k
343
350k
  return p;
344
350k
}
345
346
/* Given a normal decimal floating point number of the form
347
348
     dddd.dddd[eE][+-]ddd
349
350
   where the decimal point and exponent are optional, fill out the
351
   structure D.  Exponent is appropriate if the significand is
352
   treated as an integer, and normalizedExponent if the significand
353
   is taken to have the decimal point after a single leading
354
   non-zero digit.
355
356
   If the value is zero, V->firstSigDigit points to a non-digit, and
357
   the return exponent is zero.
358
*/
359
struct decimalInfo {
360
  const char *firstSigDigit;
361
  const char *lastSigDigit;
362
  int exponent;
363
  int normalizedExponent;
364
};
365
366
static void
367
interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
368
                 decimalInfo *D)
369
350k
{
370
350k
  StringRef::iterator dot = end;
371
350k
  StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
372
350k
373
350k
  D->firstSigDigit = p;
374
350k
  D->exponent = 0;
375
350k
  D->normalizedExponent = 0;
376
350k
377
1.95M
  for (; p != end; 
++p1.60M
) {
378
1.67M
    if (*p == '.') {
379
167k
      assert(dot == end && "String contains multiple dots");
380
167k
      dot = p++;
381
167k
      if (p == end)
382
5.01k
        break;
383
1.66M
    }
384
1.66M
    if (decDigitValue(*p) >= 10U)
385
66.3k
      break;
386
1.66M
  }
387
350k
388
350k
  if (p != end) {
389
66.3k
    assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
390
66.3k
    assert(p != begin && "Significand has no digits");
391
66.3k
    assert((dot == end || p - begin != 1) && "Significand has no digits");
392
66.3k
393
66.3k
    /* p points to the first non-digit in the string */
394
66.3k
    D->exponent = readExponent(p + 1, end);
395
66.3k
396
66.3k
    /* Implied decimal point?  */
397
66.3k
    if (dot == end)
398
1.13k
      dot = p;
399
66.3k
  }
400
350k
401
350k
  /* If number is all zeroes accept any exponent.  */
402
350k
  if (p != D->firstSigDigit) {
403
295k
    /* Drop insignificant trailing zeroes.  */
404
295k
    if (p != begin) {
405
295k
      do
406
370k
        do
407
568k
          p--;
408
568k
        while (p != begin && 
*p == '0'500k
);
409
370k
      while (p != begin && 
*p == '.'302k
);
410
295k
    }
411
295k
412
295k
    /* Adjust the exponents for any decimal point.  */
413
295k
    D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
414
295k
    D->normalizedExponent = (D->exponent +
415
295k
              static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
416
295k
                                      - (dot > D->firstSigDigit && 
dot < p169k
)));
417
295k
  }
418
350k
419
350k
  D->lastSigDigit = p;
420
350k
}
421
422
/* Return the trailing fraction of a hexadecimal number.
423
   DIGITVALUE is the first hex digit of the fraction, P points to
424
   the next digit.  */
425
static lostFraction
426
trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
427
                            unsigned int digitValue)
428
2
{
429
2
  unsigned int hexDigit;
430
2
431
2
  /* If the first trailing digit isn't 0 or 8 we can work out the
432
2
     fraction immediately.  */
433
2
  if (digitValue > 8)
434
0
    return lfMoreThanHalf;
435
2
  else if (digitValue < 8 && digitValue > 0)
436
0
    return lfLessThanHalf;
437
2
438
2
  // Otherwise we need to find the first non-zero digit.
439
7
  
while (2
p != end && (*p == '0' ||
*p == '.'3
))
440
5
    p++;
441
2
442
2
  assert(p != end && "Invalid trailing hexadecimal fraction!");
443
2
444
2
  hexDigit = hexDigitValue(*p);
445
2
446
2
  /* If we ran off the end it is exactly zero or one-half, otherwise
447
2
     a little more.  */
448
2
  if (hexDigit == -1U)
449
0
    return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
450
2
  else
451
2
    return digitValue == 0 ? lfLessThanHalf: 
lfMoreThanHalf0
;
452
2
}
453
454
/* Return the fraction lost were a bignum truncated losing the least
455
   significant BITS bits.  */
456
static lostFraction
457
lostFractionThroughTruncation(const APFloatBase::integerPart *parts,
458
                              unsigned int partCount,
459
                              unsigned int bits)
460
2.17M
{
461
2.17M
  unsigned int lsb;
462
2.17M
463
2.17M
  lsb = APInt::tcLSB(parts, partCount);
464
2.17M
465
2.17M
  /* Note this is guaranteed true if bits == 0, or LSB == -1U.  */
466
2.17M
  if (bits <= lsb)
467
574k
    return lfExactlyZero;
468
1.60M
  if (bits == lsb + 1)
469
1.33M
    return lfExactlyHalf;
470
270k
  if (bits <= partCount * APFloatBase::integerPartWidth &&
471
270k
      
APInt::tcExtractBit(parts, bits - 1)268k
)
472
117k
    return lfMoreThanHalf;
473
152k
474
152k
  return lfLessThanHalf;
475
152k
}
476
477
/* Shift DST right BITS bits noting lost fraction.  */
478
static lostFraction
479
shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
480
1.78M
{
481
1.78M
  lostFraction lost_fraction;
482
1.78M
483
1.78M
  lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
484
1.78M
485
1.78M
  APInt::tcShiftRight(dst, parts, bits);
486
1.78M
487
1.78M
  return lost_fraction;
488
1.78M
}
489
490
/* Combine the effect of two lost fractions.  */
491
static lostFraction
492
combineLostFractions(lostFraction moreSignificant,
493
                     lostFraction lessSignificant)
494
1.41M
{
495
1.41M
  if (lessSignificant != lfExactlyZero) {
496
655
    if (moreSignificant == lfExactlyZero)
497
81
      moreSignificant = lfLessThanHalf;
498
574
    else if (moreSignificant == lfExactlyHalf)
499
304
      moreSignificant = lfMoreThanHalf;
500
655
  }
501
1.41M
502
1.41M
  return moreSignificant;
503
1.41M
}
504
505
/* The error from the true value, in half-ulps, on multiplying two
506
   floating point numbers, which differ from the value they
507
   approximate by at most HUE1 and HUE2 half-ulps, is strictly less
508
   than the returned value.
509
510
   See "How to Read Floating Point Numbers Accurately" by William D
511
   Clinger.  */
512
static unsigned int
513
HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
514
295k
{
515
295k
  assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
516
295k
517
295k
  if (HUerr1 + HUerr2 == 0)
518
137k
    return inexactMultiply * 2;  /* <= inexactMultiply half-ulps.  */
519
157k
  else
520
157k
    return inexactMultiply + 2 * (HUerr1 + HUerr2);
521
295k
}
522
523
/* The number of ulps from the boundary (zero, or half if ISNEAREST)
524
   when the least significant BITS are truncated.  BITS cannot be
525
   zero.  */
526
static APFloatBase::integerPart
527
ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits,
528
295k
                 bool isNearest) {
529
295k
  unsigned int count, partBits;
530
295k
  APFloatBase::integerPart part, boundary;
531
295k
532
295k
  assert(bits != 0);
533
295k
534
295k
  bits--;
535
295k
  count = bits / APFloatBase::integerPartWidth;
536
295k
  partBits = bits % APFloatBase::integerPartWidth + 1;
537
295k
538
295k
  part = parts[count] & (~(APFloatBase::integerPart) 0 >> (APFloatBase::integerPartWidth - partBits));
539
295k
540
295k
  if (isNearest)
541
290k
    boundary = (APFloatBase::integerPart) 1 << (partBits - 1);
542
4.19k
  else
543
4.19k
    boundary = 0;
544
295k
545
295k
  if (count == 0) {
546
294k
    if (part - boundary <= boundary - part)
547
82.7k
      return part - boundary;
548
212k
    else
549
212k
      return boundary - part;
550
176
  }
551
176
552
176
  if (part == boundary) {
553
15
    while (--count)
554
0
      if (parts[count])
555
0
        return ~(APFloatBase::integerPart) 0; /* A lot.  */
556
15
557
15
    return parts[0];
558
161
  } else if (part == boundary - 1) {
559
1
    while (--count)
560
0
      if (~parts[count])
561
0
        return ~(APFloatBase::integerPart) 0; /* A lot.  */
562
1
563
1
    return -parts[0];
564
160
  }
565
160
566
160
  return ~(APFloatBase::integerPart) 0; /* A lot.  */
567
160
}
568
569
/* Place pow(5, power) in DST, and return the number of parts used.
570
   DST must be at least one part larger than size of the answer.  */
571
static unsigned int
572
295k
powerOf5(APFloatBase::integerPart *dst, unsigned int power) {
573
295k
  static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 };
574
295k
  APFloatBase::integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
575
295k
  pow5s[0] = 78125 * 5;
576
295k
577
295k
  unsigned int partsCount[16] = { 1 };
578
295k
  APFloatBase::integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
579
295k
  unsigned int result;
580
295k
  assert(power <= maxExponent);
581
295k
582
295k
  p1 = dst;
583
295k
  p2 = scratch;
584
295k
585
295k
  *p1 = firstEightPowers[power & 7];
586
295k
  power >>= 3;
587
295k
588
295k
  result = 1;
589
295k
  pow5 = pow5s;
590
295k
591
384k
  for (unsigned int n = 0; power; 
power >>= 1, n++89.6k
) {
592
89.6k
    unsigned int pc;
593
89.6k
594
89.6k
    pc = partsCount[n];
595
89.6k
596
89.6k
    /* Calculate pow(5,pow(2,n+3)) if we haven't yet.  */
597
89.6k
    if (pc == 0) {
598
56.8k
      pc = partsCount[n - 1];
599
56.8k
      APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
600
56.8k
      pc *= 2;
601
56.8k
      if (pow5[pc - 1] == 0)
602
36.0k
        pc--;
603
56.8k
      partsCount[n] = pc;
604
56.8k
    }
605
89.6k
606
89.6k
    if (power & 1) {
607
48.5k
      APFloatBase::integerPart *tmp;
608
48.5k
609
48.5k
      APInt::tcFullMultiply(p2, p1, pow5, result, pc);
610
48.5k
      result += pc;
611
48.5k
      if (p2[result - 1] == 0)
612
44.7k
        result--;
613
48.5k
614
48.5k
      /* Now result is in p1 with partsCount parts and p2 is scratch
615
48.5k
         space.  */
616
48.5k
      tmp = p1;
617
48.5k
      p1 = p2;
618
48.5k
      p2 = tmp;
619
48.5k
    }
620
89.6k
621
89.6k
    pow5 += pc;
622
89.6k
  }
623
295k
624
295k
  if (p1 != dst)
625
22.5k
    APInt::tcAssign(dst, p1, result);
626
295k
627
295k
  return result;
628
295k
}
629
630
/* Zero at the end to avoid modular arithmetic when adding one; used
631
   when rounding up during hexadecimal output.  */
632
static const char hexDigitsLower[] = "0123456789abcdef0";
633
static const char hexDigitsUpper[] = "0123456789ABCDEF0";
634
static const char infinityL[] = "infinity";
635
static const char infinityU[] = "INFINITY";
636
static const char NaNL[] = "nan";
637
static const char NaNU[] = "NAN";
638
639
/* Write out an integerPart in hexadecimal, starting with the most
640
   significant nibble.  Write out exactly COUNT hexdigits, return
641
   COUNT.  */
642
static unsigned int
643
partAsHex (char *dst, APFloatBase::integerPart part, unsigned int count,
644
           const char *hexDigitChars)
645
205
{
646
205
  unsigned int result = count;
647
205
648
205
  assert(count != 0 && count <= APFloatBase::integerPartWidth / 4);
649
205
650
205
  part >>= (APFloatBase::integerPartWidth - 4 * count);
651
830
  while (count--) {
652
625
    dst[count] = hexDigitChars[part & 0xf];
653
625
    part >>= 4;
654
625
  }
655
205
656
205
  return result;
657
205
}
658
659
/* Write out an unsigned decimal integer.  */
660
static char *
661
writeUnsignedDecimal (char *dst, unsigned int n)
662
205
{
663
205
  char buff[40], *p;
664
205
665
205
  p = buff;
666
205
  do
667
264
    *p++ = '0' + n % 10;
668
264
  while (n /= 10);
669
205
670
205
  do
671
264
    *dst++ = *--p;
672
264
  while (p != buff);
673
205
674
205
  return dst;
675
205
}
676
677
/* Write out a signed decimal integer.  */
678
static char *
679
writeSignedDecimal (char *dst, int value)
680
205
{
681
205
  if (value < 0) {
682
18
    *dst++ = '-';
683
18
    dst = writeUnsignedDecimal(dst, -(unsigned) value);
684
18
  } else
685
187
    dst = writeUnsignedDecimal(dst, value);
686
205
687
205
  return dst;
688
205
}
689
690
namespace detail {
691
/* Constructors.  */
692
13.4M
void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
693
13.4M
  unsigned int count;
694
13.4M
695
13.4M
  semantics = ourSemantics;
696
13.4M
  count = partCount();
697
13.4M
  if (count > 1)
698
119k
    significand.parts = new integerPart[count];
699
13.4M
}
700
701
27.2M
void IEEEFloat::freeSignificand() {
702
27.2M
  if (needsCleanup())
703
123k
    delete [] significand.parts;
704
27.2M
}
705
706
2.29M
void IEEEFloat::assign(const IEEEFloat &rhs) {
707
2.29M
  assert(semantics == rhs.semantics);
708
2.29M
709
2.29M
  sign = rhs.sign;
710
2.29M
  category = rhs.category;
711
2.29M
  exponent = rhs.exponent;
712
2.29M
  if (isFiniteNonZero() || 
category == fcNaN354k
)
713
1.96M
    copySignificand(rhs);
714
2.29M
}
715
716
1.96M
void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
717
1.96M
  assert(isFiniteNonZero() || category == fcNaN);
718
1.96M
  assert(rhs.partCount() >= partCount());
719
1.96M
720
1.96M
  APInt::tcAssign(significandParts(), rhs.significandParts(),
721
1.96M
                  partCount());
722
1.96M
}
723
724
/* Make this number a NaN, with an arbitrary but deterministic value
725
   for the significand.  If double or longer, this is a signalling NaN,
726
   which may not be ideal.  If float, this is QNaN(0).  */
727
7.75k
void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
728
7.75k
  category = fcNaN;
729
7.75k
  sign = Negative;
730
7.75k
731
7.75k
  integerPart *significand = significandParts();
732
7.75k
  unsigned numParts = partCount();
733
7.75k
734
7.75k
  // Set the significand bits to the fill.
735
7.75k
  if (!fill || 
fill->getNumWords() < numParts4.24k
)
736
3.82k
    APInt::tcSet(significand, 0, numParts);
737
7.75k
  if (fill) {
738
4.24k
    APInt::tcAssign(significand, fill->getRawData(),
739
4.24k
                    std::min(fill->getNumWords(), numParts));
740
4.24k
741
4.24k
    // Zero out the excess bits of the significand.
742
4.24k
    unsigned bitsToPreserve = semantics->precision - 1;
743
4.24k
    unsigned part = bitsToPreserve / 64;
744
4.24k
    bitsToPreserve %= 64;
745
4.24k
    significand[part] &= ((1ULL << bitsToPreserve) - 1);
746
4.56k
    for (part++; part != numParts; 
++part320
)
747
320
      significand[part] = 0;
748
4.24k
  }
749
7.75k
750
7.75k
  unsigned QNaNBit = semantics->precision - 2;
751
7.75k
752
7.75k
  if (SNaN) {
753
2.06k
    // We always have to clear the QNaN bit to make it an SNaN.
754
2.06k
    APInt::tcClearBit(significand, QNaNBit);
755
2.06k
756
2.06k
    // If there are no bits set in the payload, we have to set
757
2.06k
    // *something* to make it a NaN instead of an infinity;
758
2.06k
    // conventionally, this is the next bit down from the QNaN bit.
759
2.06k
    if (APInt::tcIsZero(significand, numParts))
760
2.04k
      APInt::tcSetBit(significand, QNaNBit - 1);
761
5.69k
  } else {
762
5.69k
    // We always have to set the QNaN bit to make it a QNaN.
763
5.69k
    APInt::tcSetBit(significand, QNaNBit);
764
5.69k
  }
765
7.75k
766
7.75k
  // For x87 extended precision, we want to make a NaN, not a
767
7.75k
  // pseudo-NaN.  Maybe we should expose the ability to make
768
7.75k
  // pseudo-NaNs?
769
7.75k
  if (semantics == &semX87DoubleExtended)
770
324
    APInt::tcSetBit(significand, QNaNBit + 1);
771
7.75k
}
772
773
252k
IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) {
774
252k
  if (this != &rhs) {
775
252k
    if (semantics != rhs.semantics) {
776
183k
      freeSignificand();
777
183k
      initialize(rhs.semantics);
778
183k
    }
779
252k
    assign(rhs);
780
252k
  }
781
252k
782
252k
  return *this;
783
252k
}
784
785
7.56M
IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
786
7.56M
  freeSignificand();
787
7.56M
788
7.56M
  semantics = rhs.semantics;
789
7.56M
  significand = rhs.significand;
790
7.56M
  exponent = rhs.exponent;
791
7.56M
  category = rhs.category;
792
7.56M
  sign = rhs.sign;
793
7.56M
794
7.56M
  rhs.semantics = &semBogus;
795
7.56M
  return *this;
796
7.56M
}
797
798
1.52k
bool IEEEFloat::isDenormal() const {
799
1.52k
  return isFiniteNonZero() && 
(exponent == semantics->minExponent)1.33k
&&
800
1.52k
         (APInt::tcExtractBit(significandParts(),
801
126
                              semantics->precision - 1) == 0);
802
1.52k
}
803
804
35
bool IEEEFloat::isSmallest() const {
805
35
  // The smallest number by magnitude in our format will be the smallest
806
35
  // denormal, i.e. the floating point number with exponent being minimum
807
35
  // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
808
35
  return isFiniteNonZero() && exponent == semantics->minExponent &&
809
35
    
significandMSB() == 018
;
810
35
}
811
812
15
bool IEEEFloat::isSignificandAllOnes() const {
813
15
  // Test if the significand excluding the integral bit is all ones. This allows
814
15
  // us to test for binade boundaries.
815
15
  const integerPart *Parts = significandParts();
816
15
  const unsigned PartCount = partCount();
817
23
  for (unsigned i = 0; i < PartCount - 1; 
i++8
)
818
12
    if (~Parts[i])
819
4
      return false;
820
15
821
15
  // Set the unused high bits to all ones when we compare.
822
15
  const unsigned NumHighBits =
823
11
    PartCount*integerPartWidth - semantics->precision + 1;
824
11
  assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
825
11
         "fill than integerPartWidth");
826
11
  const integerPart HighBitFill =
827
11
    ~integerPart(0) << (integerPartWidth - NumHighBits);
828
11
  if (~(Parts[PartCount - 1] | HighBitFill))
829
3
    return false;
830
8
831
8
  return true;
832
8
}
833
834
8
bool IEEEFloat::isSignificandAllZeros() const {
835
8
  // Test if the significand excluding the integral bit is all zeros. This
836
8
  // allows us to test for binade boundaries.
837
8
  const integerPart *Parts = significandParts();
838
8
  const unsigned PartCount = partCount();
839
8
840
12
  for (unsigned i = 0; i < PartCount - 1; 
i++4
)
841
8
    if (Parts[i])
842
4
      return false;
843
8
844
8
  const unsigned NumHighBits =
845
4
    PartCount*integerPartWidth - semantics->precision + 1;
846
4
  assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
847
4
         "clear than integerPartWidth");
848
4
  const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
849
4
850
4
  if (Parts[PartCount - 1] & HighBitMask)
851
0
    return false;
852
4
853
4
  return true;
854
4
}
855
856
33
bool IEEEFloat::isLargest() const {
857
33
  // The largest number by magnitude in our format will be the floating point
858
33
  // number with maximum exponent and with significand that is all ones.
859
33
  return isFiniteNonZero() && exponent == semantics->maxExponent
860
33
    && 
isSignificandAllOnes()4
;
861
33
}
862
863
502
bool IEEEFloat::isInteger() const {
864
502
  // This could be made more efficient; I'm going for obviously correct.
865
502
  if (!isFinite()) 
return false13
;
866
489
  IEEEFloat truncated = *this;
867
489
  truncated.roundToIntegral(rmTowardZero);
868
489
  return compare(truncated) == cmpEqual;
869
489
}
870
871
3.23M
bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
872
3.23M
  if (this == &rhs)
873
0
    return true;
874
3.23M
  if (semantics != rhs.semantics ||
875
3.23M
      category != rhs.category ||
876
3.23M
      
sign != rhs.sign3.14M
)
877
361k
    return false;
878
2.86M
  if (category==fcZero || 
category==fcInfinity2.74M
)
879
130k
    return true;
880
2.73M
881
2.73M
  if (isFiniteNonZero() && 
exponent != rhs.exponent2.72M
)
882
545k
    return false;
883
2.19M
884
2.19M
  return std::equal(significandParts(), significandParts() + partCount(),
885
2.19M
                    rhs.significandParts());
886
2.19M
}
887
888
2.52M
IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) {
889
2.52M
  initialize(&ourSemantics);
890
2.52M
  sign = 0;
891
2.52M
  category = fcNormal;
892
2.52M
  zeroSignificand();
893
2.52M
  exponent = ourSemantics.precision - 1;
894
2.52M
  significandParts()[0] = value;
895
2.52M
  normalize(rmNearestTiesToEven, lfExactlyZero);
896
2.52M
}
897
898
1.06M
IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) {
899
1.06M
  initialize(&ourSemantics);
900
1.06M
  category = fcZero;
901
1.06M
  sign = false;
902
1.06M
}
903
904
// Delegate to the previous constructor, because later copy constructor may
905
// actually inspects category, which can't be garbage.
906
IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
907
391k
    : IEEEFloat(ourSemantics) {}
Unexecuted instantiation: llvm::detail::IEEEFloat::IEEEFloat(llvm::fltSemantics const&, llvm::APFloatBase::uninitializedTag)
llvm::detail::IEEEFloat::IEEEFloat(llvm::fltSemantics const&, llvm::APFloatBase::uninitializedTag)
Line
Count
Source
907
391k
    : IEEEFloat(ourSemantics) {}
908
909
2.03M
IEEEFloat::IEEEFloat(const IEEEFloat &rhs) {
910
2.03M
  initialize(rhs.semantics);
911
2.03M
  assign(rhs);
912
2.03M
}
913
914
6.75M
IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) {
915
6.75M
  *this = std::move(rhs);
916
6.75M
}
917
918
19.5M
IEEEFloat::~IEEEFloat() { freeSignificand(); }
919
920
91.3M
unsigned int IEEEFloat::partCount() const {
921
91.3M
  return partCountForBits(semantics->precision + 1);
922
91.3M
}
923
924
18.1M
const IEEEFloat::integerPart *IEEEFloat::significandParts() const {
925
18.1M
  return const_cast<IEEEFloat *>(this)->significandParts();
926
18.1M
}
927
928
33.7M
IEEEFloat::integerPart *IEEEFloat::significandParts() {
929
33.7M
  if (partCount() > 1)
930
158k
    return significand.parts;
931
33.5M
  else
932
33.5M
    return &significand.part;
933
33.7M
}
934
935
2.52M
void IEEEFloat::zeroSignificand() {
936
2.52M
  APInt::tcSet(significandParts(), 0, partCount());
937
2.52M
}
938
939
/* Increment an fcNormal floating point number's significand.  */
940
116k
void IEEEFloat::incrementSignificand() {
941
116k
  integerPart carry;
942
116k
943
116k
  carry = APInt::tcIncrement(significandParts(), partCount());
944
116k
945
116k
  /* Our callers should never cause us to overflow.  */
946
116k
  assert(carry == 0);
947
116k
  (void)carry;
948
116k
}
949
950
/* Add the significand of the RHS.  Returns the carry flag.  */
951
23.1k
IEEEFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
952
23.1k
  integerPart *parts;
953
23.1k
954
23.1k
  parts = significandParts();
955
23.1k
956
23.1k
  assert(semantics == rhs.semantics);
957
23.1k
  assert(exponent == rhs.exponent);
958
23.1k
959
23.1k
  return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
960
23.1k
}
961
962
/* Subtract the significand of the RHS with a borrow flag.  Returns
963
   the borrow flag.  */
964
IEEEFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
965
22.6k
                                                      integerPart borrow) {
966
22.6k
  integerPart *parts;
967
22.6k
968
22.6k
  parts = significandParts();
969
22.6k
970
22.6k
  assert(semantics == rhs.semantics);
971
22.6k
  assert(exponent == rhs.exponent);
972
22.6k
973
22.6k
  return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
974
22.6k
                           partCount());
975
22.6k
}
976
977
/* Multiply the significand of the RHS.  If ADDEND is non-NULL, add it
978
   on to the full-precision result of the multiplication.  Returns the
979
   lost fraction.  */
980
lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
981
86.1k
                                            const IEEEFloat *addend) {
982
86.1k
  unsigned int omsb;        // One, not zero, based MSB.
983
86.1k
  unsigned int partsCount, newPartsCount, precision;
984
86.1k
  integerPart *lhsSignificand;
985
86.1k
  integerPart scratch[4];
986
86.1k
  integerPart *fullSignificand;
987
86.1k
  lostFraction lost_fraction;
988
86.1k
  bool ignored;
989
86.1k
990
86.1k
  assert(semantics == rhs.semantics);
991
86.1k
992
86.1k
  precision = semantics->precision;
993
86.1k
994
86.1k
  // Allocate space for twice as many bits as the original significand, plus one
995
86.1k
  // extra bit for the addition to overflow into.
996
86.1k
  newPartsCount = partCountForBits(precision * 2 + 1);
997
86.1k
998
86.1k
  if (newPartsCount > 4)
999
0
    fullSignificand = new integerPart[newPartsCount];
1000
86.1k
  else
1001
86.1k
    fullSignificand = scratch;
1002
86.1k
1003
86.1k
  lhsSignificand = significandParts();
1004
86.1k
  partsCount = partCount();
1005
86.1k
1006
86.1k
  APInt::tcFullMultiply(fullSignificand, lhsSignificand,
1007
86.1k
                        rhs.significandParts(), partsCount, partsCount);
1008
86.1k
1009
86.1k
  lost_fraction = lfExactlyZero;
1010
86.1k
  omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1011
86.1k
  exponent += rhs.exponent;
1012
86.1k
1013
86.1k
  // Assume the operands involved in the multiplication are single-precision
1014
86.1k
  // FP, and the two multiplicants are:
1015
86.1k
  //   *this = a23 . a22 ... a0 * 2^e1
1016
86.1k
  //     rhs = b23 . b22 ... b0 * 2^e2
1017
86.1k
  // the result of multiplication is:
1018
86.1k
  //   *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
1019
86.1k
  // Note that there are three significant bits at the left-hand side of the
1020
86.1k
  // radix point: two for the multiplication, and an overflow bit for the
1021
86.1k
  // addition (that will always be zero at this point). Move the radix point
1022
86.1k
  // toward left by two bits, and adjust exponent accordingly.
1023
86.1k
  exponent += 2;
1024
86.1k
1025
86.1k
  if (addend && 
addend->isNonZero()119
) {
1026
117
    // The intermediate result of the multiplication has "2 * precision"
1027
117
    // signicant bit; adjust the addend to be consistent with mul result.
1028
117
    //
1029
117
    Significand savedSignificand = significand;
1030
117
    const fltSemantics *savedSemantics = semantics;
1031
117
    fltSemantics extendedSemantics;
1032
117
    opStatus status;
1033
117
    unsigned int extendedPrecision;
1034
117
1035
117
    // Normalize our MSB to one below the top bit to allow for overflow.
1036
117
    extendedPrecision = 2 * precision + 1;
1037
117
    if (omsb != extendedPrecision - 1) {
1038
55
      assert(extendedPrecision > omsb);
1039
55
      APInt::tcShiftLeft(fullSignificand, newPartsCount,
1040
55
                         (extendedPrecision - 1) - omsb);
1041
55
      exponent -= (extendedPrecision - 1) - omsb;
1042
55
    }
1043
117
1044
117
    /* Create new semantics.  */
1045
117
    extendedSemantics = *semantics;
1046
117
    extendedSemantics.precision = extendedPrecision;
1047
117
1048
117
    if (newPartsCount == 1)
1049
68
      significand.part = fullSignificand[0];
1050
49
    else
1051
49
      significand.parts = fullSignificand;
1052
117
    semantics = &extendedSemantics;
1053
117
1054
117
    IEEEFloat extendedAddend(*addend);
1055
117
    status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
1056
117
    assert(status == opOK);
1057
117
    (void)status;
1058
117
1059
117
    // Shift the significand of the addend right by one bit. This guarantees
1060
117
    // that the high bit of the significand is zero (same as fullSignificand),
1061
117
    // so the addition will overflow (if it does overflow at all) into the top bit.
1062
117
    lost_fraction = extendedAddend.shiftSignificandRight(1);
1063
117
    assert(lost_fraction == lfExactlyZero &&
1064
117
           "Lost precision while shifting addend for fused-multiply-add.");
1065
117
1066
117
    lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1067
117
1068
117
    /* Restore our state.  */
1069
117
    if (newPartsCount == 1)
1070
68
      fullSignificand[0] = significand.part;
1071
117
    significand = savedSignificand;
1072
117
    semantics = savedSemantics;
1073
117
1074
117
    omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1075
117
  }
1076
86.1k
1077
86.1k
  // Convert the result having "2 * precision" significant-bits back to the one
1078
86.1k
  // having "precision" significant-bits. First, move the radix point from
1079
86.1k
  // poision "2*precision - 1" to "precision - 1". The exponent need to be
1080
86.1k
  // adjusted by "2*precision - 1" - "precision - 1" = "precision".
1081
86.1k
  exponent -= precision + 1;
1082
86.1k
1083
86.1k
  // In case MSB resides at the left-hand side of radix point, shift the
1084
86.1k
  // mantissa right by some amount to make sure the MSB reside right before
1085
86.1k
  // the radix point (i.e. "MSB . rest-significant-bits").
1086
86.1k
  //
1087
86.1k
  // Note that the result is not normalized when "omsb < precision". So, the
1088
86.1k
  // caller needs to call IEEEFloat::normalize() if normalized value is
1089
86.1k
  // expected.
1090
86.1k
  if (omsb > precision) {
1091
86.0k
    unsigned int bits, significantParts;
1092
86.0k
    lostFraction lf;
1093
86.0k
1094
86.0k
    bits = omsb - precision;
1095
86.0k
    significantParts = partCountForBits(omsb);
1096
86.0k
    lf = shiftRight(fullSignificand, significantParts, bits);
1097
86.0k
    lost_fraction = combineLostFractions(lf, lost_fraction);
1098
86.0k
    exponent += bits;
1099
86.0k
  }
1100
86.1k
1101
86.1k
  APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1102
86.1k
1103
86.1k
  if (newPartsCount > 4)
1104
0
    delete [] fullSignificand;
1105
86.1k
1106
86.1k
  return lost_fraction;
1107
86.1k
}
1108
1109
/* Multiply the significands of LHS and RHS to DST.  */
1110
233k
lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
1111
233k
  unsigned int bit, i, partsCount;
1112
233k
  const integerPart *rhsSignificand;
1113
233k
  integerPart *lhsSignificand, *dividend, *divisor;
1114
233k
  integerPart scratch[4];
1115
233k
  lostFraction lost_fraction;
1116
233k
1117
233k
  assert(semantics == rhs.semantics);
1118
233k
1119
233k
  lhsSignificand = significandParts();
1120
233k
  rhsSignificand = rhs.significandParts();
1121
233k
  partsCount = partCount();
1122
233k
1123
233k
  if (partsCount > 2)
1124
0
    dividend = new integerPart[partsCount * 2];
1125
233k
  else
1126
233k
    dividend = scratch;
1127
233k
1128
233k
  divisor = dividend + partsCount;
1129
233k
1130
233k
  /* Copy the dividend and divisor as they will be modified in-place.  */
1131
467k
  for (i = 0; i < partsCount; 
i++234k
) {
1132
234k
    dividend[i] = lhsSignificand[i];
1133
234k
    divisor[i] = rhsSignificand[i];
1134
234k
    lhsSignificand[i] = 0;
1135
234k
  }
1136
233k
1137
233k
  exponent -= rhs.exponent;
1138
233k
1139
233k
  unsigned int precision = semantics->precision;
1140
233k
1141
233k
  /* Normalize the divisor.  */
1142
233k
  bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
1143
233k
  if (bit) {
1144
20
    exponent += bit;
1145
20
    APInt::tcShiftLeft(divisor, partsCount, bit);
1146
20
  }
1147
233k
1148
233k
  /* Normalize the dividend.  */
1149
233k
  bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
1150
233k
  if (bit) {
1151
16
    exponent -= bit;
1152
16
    APInt::tcShiftLeft(dividend, partsCount, bit);
1153
16
  }
1154
233k
1155
233k
  /* Ensure the dividend >= divisor initially for the loop below.
1156
233k
     Incidentally, this means that the division loop below is
1157
233k
     guaranteed to set the integer bit to one.  */
1158
233k
  if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
1159
131k
    exponent--;
1160
131k
    APInt::tcShiftLeft(dividend, partsCount, 1);
1161
131k
    assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1162
131k
  }
1163
233k
1164
233k
  /* Long division.  */
1165
14.6M
  for (bit = precision; bit; 
bit -= 114.4M
) {
1166
14.4M
    if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
1167
5.01M
      APInt::tcSubtract(dividend, divisor, 0, partsCount);
1168
5.01M
      APInt::tcSetBit(lhsSignificand, bit - 1);
1169
5.01M
    }
1170
14.4M
1171
14.4M
    APInt::tcShiftLeft(dividend, partsCount, 1);
1172
14.4M
  }
1173
233k
1174
233k
  /* Figure out the lost fraction.  */
1175
233k
  int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1176
233k
1177
233k
  if (cmp > 0)
1178
81.9k
    lost_fraction = lfMoreThanHalf;
1179
151k
  else if (cmp == 0)
1180
0
    lost_fraction = lfExactlyHalf;
1181
151k
  else if (APInt::tcIsZero(dividend, partsCount))
1182
76.5k
    lost_fraction = lfExactlyZero;
1183
74.8k
  else
1184
74.8k
    lost_fraction = lfLessThanHalf;
1185
233k
1186
233k
  if (partsCount > 2)
1187
0
    delete [] dividend;
1188
233k
1189
233k
  return lost_fraction;
1190
233k
}
1191
1192
4.39M
unsigned int IEEEFloat::significandMSB() const {
1193
4.39M
  return APInt::tcMSB(significandParts(), partCount());
1194
4.39M
}
1195
1196
63.7k
unsigned int IEEEFloat::significandLSB() const {
1197
63.7k
  return APInt::tcLSB(significandParts(), partCount());
1198
63.7k
}
1199
1200
/* Note that a zero result is NOT normalized to fcZero.  */
1201
1.35M
lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
1202
1.35M
  /* Our exponent should not overflow.  */
1203
1.35M
  assert((ExponentType) (exponent + bits) >= exponent);
1204
1.35M
1205
1.35M
  exponent += bits;
1206
1.35M
1207
1.35M
  return shiftRight(significandParts(), partCount(), bits);
1208
1.35M
}
1209
1210
/* Shift the significand left BITS bits, subtract BITS from its exponent.  */
1211
666k
void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
1212
666k
  assert(bits < semantics->precision);
1213
666k
1214
666k
  if (bits) {
1215
666k
    unsigned int partsCount = partCount();
1216
666k
1217
666k
    APInt::tcShiftLeft(significandParts(), partsCount, bits);
1218
666k
    exponent -= bits;
1219
666k
1220
666k
    assert(!APInt::tcIsZero(significandParts(), partsCount));
1221
666k
  }
1222
666k
}
1223
1224
IEEEFloat::cmpResult
1225
39.5k
IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const {
1226
39.5k
  int compare;
1227
39.5k
1228
39.5k
  assert(semantics == rhs.semantics);
1229
39.5k
  assert(isFiniteNonZero());
1230
39.5k
  assert(rhs.isFiniteNonZero());
1231
39.5k
1232
39.5k
  compare = exponent - rhs.exponent;
1233
39.5k
1234
39.5k
  /* If exponents are equal, do an unsigned bignum comparison of the
1235
39.5k
     significands.  */
1236
39.5k
  if (compare == 0)
1237
33.7k
    compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
1238
33.7k
                               partCount());
1239
39.5k
1240
39.5k
  if (compare > 0)
1241
15.4k
    return cmpGreaterThan;
1242
24.0k
  else if (compare < 0)
1243
4.22k
    return cmpLessThan;
1244
19.8k
  else
1245
19.8k
    return cmpEqual;
1246
39.5k
}
1247
1248
/* Handle overflow.  Sign is preserved.  We either become infinity or
1249
   the largest finite number.  */
1250
1.16M
IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
1251
1.16M
  /* Infinity?  */
1252
1.16M
  if (rounding_mode == rmNearestTiesToEven ||
1253
1.16M
      
rounding_mode == rmNearestTiesToAway0
||
1254
1.16M
      
(0
rounding_mode == rmTowardPositive0
&&
!sign0
) ||
1255
1.16M
      
(0
rounding_mode == rmTowardNegative0
&&
sign0
)) {
1256
1.16M
    category = fcInfinity;
1257
1.16M
    return (opStatus) (opOverflow | opInexact);
1258
1.16M
  }
1259
0
1260
0
  /* Otherwise we become the largest finite number.  */
1261
0
  category = fcNormal;
1262
0
  exponent = semantics->maxExponent;
1263
0
  APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
1264
0
                                   semantics->precision);
1265
0
1266
0
  return opInexact;
1267
0
}
1268
1269
/* Returns TRUE if, when truncating the current number, with BIT the
1270
   new LSB, with the given lost fraction and rounding mode, the result
1271
   would need to be rounded away from zero (i.e., by increasing the
1272
   signficand).  This routine must work for fcZero of both signs, and
1273
   fcNormal numbers.  */
1274
bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1275
                                  lostFraction lost_fraction,
1276
1.60M
                                  unsigned int bit) const {
1277
1.60M
  /* NaNs and infinities should not have lost fractions.  */
1278
1.60M
  assert(isFiniteNonZero() || category == fcZero);
1279
1.60M
1280
1.60M
  /* Current callers never pass this so we don't handle it.  */
1281
1.60M
  assert(lost_fraction != lfExactlyZero);
1282
1.60M
1283
1.60M
  switch (rounding_mode) {
1284
1.60M
  case rmNearestTiesToAway:
1285
30
    return lost_fraction == lfExactlyHalf || 
lost_fraction == lfMoreThanHalf26
;
1286
1.60M
1287
1.60M
  case rmNearestTiesToEven:
1288
1.55M
    if (lost_fraction == lfMoreThanHalf)
1289
115k
      return true;
1290
1.44M
1291
1.44M
    /* Our zeroes don't have a significand to test.  */
1292
1.44M
    if (lost_fraction == lfExactlyHalf && 
category != fcZero1.33M
)
1293
1.33M
      return APInt::tcExtractBit(significandParts(), bit);
1294
110k
1295
110k
    return false;
1296
110k
1297
110k
  case rmTowardZero:
1298
43.9k
    return false;
1299
110k
1300
110k
  case rmTowardPositive:
1301
49
    return !sign;
1302
110k
1303
110k
  case rmTowardNegative:
1304
49
    return sign;
1305
0
  }
1306
0
  llvm_unreachable("Invalid rounding mode found");
1307
0
}
1308
1309
IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1310
3.93M
                                         lostFraction lost_fraction) {
1311
3.93M
  unsigned int omsb;                /* One, not zero, based MSB.  */
1312
3.93M
  int exponentChange;
1313
3.93M
1314
3.93M
  if (!isFiniteNonZero())
1315
71
    return opOK;
1316
3.93M
1317
3.93M
  /* Before rounding normalize the exponent of fcNormal numbers.  */
1318
3.93M
  omsb = significandMSB() + 1;
1319
3.93M
1320
3.93M
  if (omsb) {
1321
3.91M
    /* OMSB is numbered from 1.  We want to place it in the integer
1322
3.91M
       bit numbered PRECISION if possible, with a compensating change in
1323
3.91M
       the exponent.  */
1324
3.91M
    exponentChange = omsb - semantics->precision;
1325
3.91M
1326
3.91M
    /* If the resulting exponent is too high, overflow according to
1327
3.91M
       the rounding mode.  */
1328
3.91M
    if (exponent + exponentChange > semantics->maxExponent)
1329
1.16M
      return handleOverflow(rounding_mode);
1330
2.75M
1331
2.75M
    /* Subnormal numbers have exponent minExponent, and their MSB
1332
2.75M
       is forced based on that.  */
1333
2.75M
    if (exponent + exponentChange < semantics->minExponent)
1334
3.28k
      exponentChange = semantics->minExponent - exponent;
1335
2.75M
1336
2.75M
    /* Shifting left is easy as we don't lose precision.  */
1337
2.75M
    if (exponentChange < 0) {
1338
665k
      assert(lost_fraction == lfExactlyZero);
1339
665k
1340
665k
      shiftSignificandLeft(-exponentChange);
1341
665k
1342
665k
      return opOK;
1343
665k
    }
1344
2.08M
1345
2.08M
    if (exponentChange > 0) {
1346
1.33M
      lostFraction lf;
1347
1.33M
1348
1.33M
      /* Shift right and capture any new lost fraction.  */
1349
1.33M
      lf = shiftSignificandRight(exponentChange);
1350
1.33M
1351
1.33M
      lost_fraction = combineLostFractions(lf, lost_fraction);
1352
1.33M
1353
1.33M
      /* Keep OMSB up-to-date.  */
1354
1.33M
      if (omsb > (unsigned) exponentChange)
1355
2.15k
        omsb -= exponentChange;
1356
1.32M
      else
1357
1.32M
        omsb = 0;
1358
1.33M
    }
1359
2.08M
  }
1360
3.93M
1361
3.93M
  /* Now round the number according to rounding_mode given the lost
1362
3.93M
     fraction.  */
1363
3.93M
1364
3.93M
  /* As specified in IEEE 754, since we do not trap we do not report
1365
3.93M
     underflow for exact results.  */
1366
3.93M
  
if (2.10M
lost_fraction == lfExactlyZero2.10M
) {
1367
545k
    /* Canonicalize zeroes.  */
1368
545k
    if (omsb == 0)
1369
16.3k
      category = fcZero;
1370
545k
1371
545k
    return opOK;
1372
545k
  }
1373
1.55M
1374
1.55M
  /* Increment the significand if we're rounding away from zero.  */
1375
1.55M
  if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1376
116k
    if (omsb == 0)
1377
2.19k
      exponent = semantics->minExponent;
1378
116k
1379
116k
    incrementSignificand();
1380
116k
    omsb = significandMSB() + 1;
1381
116k
1382
116k
    /* Did the significand increment overflow?  */
1383
116k
    if (omsb == (unsigned) semantics->precision + 1) {
1384
253
      /* Renormalize by incrementing the exponent and shifting our
1385
253
         significand right one.  However if we already have the
1386
253
         maximum exponent we overflow to infinity.  */
1387
253
      if (exponent == semantics->maxExponent) {
1388
10
        category = fcInfinity;
1389
10
1390
10
        return (opStatus) (opOverflow | opInexact);
1391
10
      }
1392
243
1393
243
      shiftSignificandRight(1);
1394
243
1395
243
      return opInexact;
1396
243
    }
1397
116k
  }
1398
1.55M
1399
1.55M
  /* The normal case - we were and are not denormal, and any
1400
1.55M
     significand increment above didn't overflow.  */
1401
1.55M
  if (omsb == semantics->precision)
1402
1.55M
    return opInexact;
1403
2.71k
1404
2.71k
  /* We have a non-zero denormal.  */
1405
2.71k
  assert(omsb < semantics->precision);
1406
2.71k
1407
2.71k
  /* Canonicalize zeroes.  */
1408
2.71k
  if (omsb == 0)
1409
310
    category = fcZero;
1410
2.71k
1411
2.71k
  /* The fcZero case is a denormal that underflowed to zero.  */
1412
2.71k
  return (opStatus) (opUnderflow | opInexact);
1413
2.71k
}
1414
1415
IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1416
61.1k
                                                     bool subtract) {
1417
61.1k
  switch (PackCategoriesIntoKey(category, rhs.category)) {
1418
61.1k
  default:
1419
0
    llvm_unreachable(nullptr);
1420
61.1k
1421
61.1k
  
case 945
PackCategoriesIntoKey945
(fcNaN, fcZero):
1422
945
  case PackCategoriesIntoKey(fcNaN, fcNormal):
1423
945
  case PackCategoriesIntoKey(fcNaN, fcInfinity):
1424
945
  case PackCategoriesIntoKey(fcNaN, fcNaN):
1425
945
  case PackCategoriesIntoKey(fcNormal, fcZero):
1426
945
  case PackCategoriesIntoKey(fcInfinity, fcNormal):
1427
945
  case PackCategoriesIntoKey(fcInfinity, fcZero):
1428
945
    return opOK;
1429
945
1430
945
  
case 118
PackCategoriesIntoKey118
(fcZero, fcNaN):
1431
118
  case PackCategoriesIntoKey(fcNormal, fcNaN):
1432
118
  case PackCategoriesIntoKey(fcInfinity, fcNaN):
1433
118
    // We need to be sure to flip the sign here for subtraction because we
1434
118
    // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1435
118
    sign = rhs.sign ^ subtract;
1436
118
    category = fcNaN;
1437
118
    copySignificand(rhs);
1438
118
    return opOK;
1439
118
1440
118
  
case 58
PackCategoriesIntoKey58
(fcNormal, fcInfinity):
1441
58
  case PackCategoriesIntoKey(fcZero, fcInfinity):
1442
58
    category = fcInfinity;
1443
58
    sign = rhs.sign ^ subtract;
1444
58
    return opOK;
1445
58
1446
13.5k
  case PackCategoriesIntoKey(fcZero, fcNormal):
1447
13.5k
    assign(rhs);
1448
13.5k
    sign = rhs.sign ^ subtract;
1449
13.5k
    return opOK;
1450
58
1451
814
  case PackCategoriesIntoKey(fcZero, fcZero):
1452
814
    /* Sign depends on rounding mode; handled by caller.  */
1453
814
    return opOK;
1454
58
1455
58
  
case 14
PackCategoriesIntoKey14
(fcInfinity, fcInfinity):
1456
14
    /* Differently signed infinities can only be validly
1457
14
       subtracted.  */
1458
14
    if (((sign ^ rhs.sign)!=0) != subtract) {
1459
8
      makeNaN();
1460
8
      return opInvalidOp;
1461
8
    }
1462
6
1463
6
    return opOK;
1464
6
1465
45.6k
  case PackCategoriesIntoKey(fcNormal, fcNormal):
1466
45.6k
    return opDivByZero;
1467
61.1k
  }
1468
61.1k
}
1469
1470
/* Add or subtract two normal numbers.  */
1471
lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1472
45.7k
                                                 bool subtract) {
1473
45.7k
  integerPart carry;
1474
45.7k
  lostFraction lost_fraction;
1475
45.7k
  int bits;
1476
45.7k
1477
45.7k
  /* Determine if the operation on the absolute values is effectively
1478
45.7k
     an addition or subtraction.  */
1479
45.7k
  subtract ^= static_cast<bool>(sign ^ rhs.sign);
1480
45.7k
1481
45.7k
  /* Are we bigger exponent-wise than the RHS?  */
1482
45.7k
  bits = exponent - rhs.exponent;
1483
45.7k
1484
45.7k
  /* Subtraction is more subtle than one might naively expect.  */
1485
45.7k
  if (subtract) {
1486
22.6k
    IEEEFloat temp_rhs(rhs);
1487
22.6k
    bool reverse;
1488
22.6k
1489
22.6k
    if (bits == 0) {
1490
21.5k
      reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1491
21.5k
      lost_fraction = lfExactlyZero;
1492
21.5k
    } else 
if (1.08k
bits > 01.08k
) {
1493
854
      lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1494
854
      shiftSignificandLeft(1);
1495
854
      reverse = false;
1496
854
    } else {
1497
232
      lost_fraction = shiftSignificandRight(-bits - 1);
1498
232
      temp_rhs.shiftSignificandLeft(1);
1499
232
      reverse = true;
1500
232
    }
1501
22.6k
1502
22.6k
    if (reverse) {
1503
289
      carry = temp_rhs.subtractSignificand
1504
289
        (*this, lost_fraction != lfExactlyZero);
1505
289
      copySignificand(temp_rhs);
1506
289
      sign = !sign;
1507
22.3k
    } else {
1508
22.3k
      carry = subtractSignificand
1509
22.3k
        (temp_rhs, lost_fraction != lfExactlyZero);
1510
22.3k
    }
1511
22.6k
1512
22.6k
    /* Invert the lost fraction - it was on the RHS and
1513
22.6k
       subtracted.  */
1514
22.6k
    if (lost_fraction == lfLessThanHalf)
1515
293
      lost_fraction = lfMoreThanHalf;
1516
22.3k
    else if (lost_fraction == lfMoreThanHalf)
1517
18
      lost_fraction = lfLessThanHalf;
1518
22.6k
1519
22.6k
    /* The code above is intended to ensure that no borrow is
1520
22.6k
       necessary.  */
1521
22.6k
    assert(!carry);
1522
22.6k
    (void)carry;
1523
23.1k
  } else {
1524
23.1k
    if (bits > 0) {
1525
3.96k
      IEEEFloat temp_rhs(rhs);
1526
3.96k
1527
3.96k
      lost_fraction = temp_rhs.shiftSignificandRight(bits);
1528
3.96k
      carry = addSignificand(temp_rhs);
1529
19.1k
    } else {
1530
19.1k
      lost_fraction = shiftSignificandRight(-bits);
1531
19.1k
      carry = addSignificand(rhs);
1532
19.1k
    }
1533
23.1k
1534
23.1k
    /* We have a guard bit; generating a carry cannot happen.  */
1535
23.1k
    assert(!carry);
1536
23.1k
    (void)carry;
1537
23.1k
  }
1538
45.7k
1539
45.7k
  return lost_fraction;
1540
45.7k
}
1541
1542
11.6k
IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
1543
11.6k
  switch (PackCategoriesIntoKey(category, rhs.category)) {
1544
11.6k
  default:
1545
0
    llvm_unreachable(nullptr);
1546
11.6k
1547
11.6k
  
case 132
PackCategoriesIntoKey132
(fcNaN, fcZero):
1548
132
  case PackCategoriesIntoKey(fcNaN, fcNormal):
1549
132
  case PackCategoriesIntoKey(fcNaN, fcInfinity):
1550
132
  case PackCategoriesIntoKey(fcNaN, fcNaN):
1551
132
    sign = false;
1552
132
    return opOK;
1553
132
1554
132
  
case 53
PackCategoriesIntoKey53
(fcZero, fcNaN):
1555
53
  case PackCategoriesIntoKey(fcNormal, fcNaN):
1556
53
  case PackCategoriesIntoKey(fcInfinity, fcNaN):
1557
53
    sign = false;
1558
53
    category = fcNaN;
1559
53
    copySignificand(rhs);
1560
53
    return opOK;
1561
53
1562
193
  case PackCategoriesIntoKey(fcNormal, fcInfinity):
1563
193
  case PackCategoriesIntoKey(fcInfinity, fcNormal):
1564
193
  case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1565
193
    category = fcInfinity;
1566
193
    return opOK;
1567
193
1568
1.70k
  case PackCategoriesIntoKey(fcZero, fcNormal):
1569
1.70k
  case PackCategoriesIntoKey(fcNormal, fcZero):
1570
1.70k
  case PackCategoriesIntoKey(fcZero, fcZero):
1571
1.70k
    category = fcZero;
1572
1.70k
    return opOK;
1573
1.70k
1574
1.70k
  
case 72
PackCategoriesIntoKey72
(fcZero, fcInfinity):
1575
72
  case PackCategoriesIntoKey(fcInfinity, fcZero):
1576
72
    makeNaN();
1577
72
    return opInvalidOp;
1578
72
1579
9.46k
  case PackCategoriesIntoKey(fcNormal, fcNormal):
1580
9.46k
    return opOK;
1581
11.6k
  }
1582
11.6k
}
1583
1584
15.6k
IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
1585
15.6k
  switch (PackCategoriesIntoKey(category, rhs.category)) {
1586
15.6k
  default:
1587
0
    llvm_unreachable(nullptr);
1588
15.6k
1589
15.6k
  
case 17
PackCategoriesIntoKey17
(fcZero, fcNaN):
1590
17
  case PackCategoriesIntoKey(fcNormal, fcNaN):
1591
17
  case PackCategoriesIntoKey(fcInfinity, fcNaN):
1592
17
    category = fcNaN;
1593
17
    copySignificand(rhs);
1594
17
    LLVM_FALLTHROUGH;
1595
66
  case PackCategoriesIntoKey(fcNaN, fcZero):
1596
66
  case PackCategoriesIntoKey(fcNaN, fcNormal):
1597
66
  case PackCategoriesIntoKey(fcNaN, fcInfinity):
1598
66
  case PackCategoriesIntoKey(fcNaN, fcNaN):
1599
66
    sign = false;
1600
66
    LLVM_FALLTHROUGH;
1601
611
  case PackCategoriesIntoKey(fcInfinity, fcZero):
1602
611
  case PackCategoriesIntoKey(fcInfinity, fcNormal):
1603
611
  case PackCategoriesIntoKey(fcZero, fcInfinity):
1604
611
  case PackCategoriesIntoKey(fcZero, fcNormal):
1605
611
    return opOK;
1606
611
1607
611
  
case 28
PackCategoriesIntoKey28
(fcNormal, fcInfinity):
1608
28
    category = fcZero;
1609
28
    return opOK;
1610
611
1611
611
  
case 80
PackCategoriesIntoKey80
(fcNormal, fcZero):
1612
80
    category = fcInfinity;
1613
80
    return opDivByZero;
1614
611
1615
611
  
case 185
PackCategoriesIntoKey185
(fcInfinity, fcInfinity):
1616
185
  case PackCategoriesIntoKey(fcZero, fcZero):
1617
185
    makeNaN();
1618
185
    return opInvalidOp;
1619
185
1620
14.7k
  case PackCategoriesIntoKey(fcNormal, fcNormal):
1621
14.7k
    return opOK;
1622
15.6k
  }
1623
15.6k
}
1624
1625
136
IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
1626
136
  switch (PackCategoriesIntoKey(category, rhs.category)) {
1627
136
  default:
1628
0
    llvm_unreachable(nullptr);
1629
136
1630
136
  
case 34
PackCategoriesIntoKey34
(fcNaN, fcZero):
1631
34
  case PackCategoriesIntoKey(fcNaN, fcNormal):
1632
34
  case PackCategoriesIntoKey(fcNaN, fcInfinity):
1633
34
  case PackCategoriesIntoKey(fcNaN, fcNaN):
1634
34
  case PackCategoriesIntoKey(fcZero, fcInfinity):
1635
34
  case PackCategoriesIntoKey(fcZero, fcNormal):
1636
34
  case PackCategoriesIntoKey(fcNormal, fcInfinity):
1637
34
    return opOK;
1638
34
1639
34
  
case 9
PackCategoriesIntoKey9
(fcZero, fcNaN):
1640
9
  case PackCategoriesIntoKey(fcNormal, fcNaN):
1641
9
  case PackCategoriesIntoKey(fcInfinity, fcNaN):
1642
9
    sign = false;
1643
9
    category = fcNaN;
1644
9
    copySignificand(rhs);
1645
9
    return opOK;
1646
9
1647
24
  case PackCategoriesIntoKey(fcNormal, fcZero):
1648
24
  case PackCategoriesIntoKey(fcInfinity, fcZero):
1649
24
  case PackCategoriesIntoKey(fcInfinity, fcNormal):
1650
24
  case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1651
24
  case PackCategoriesIntoKey(fcZero, fcZero):
1652
24
    makeNaN();
1653
24
    return opInvalidOp;
1654
24
1655
69
  case PackCategoriesIntoKey(fcNormal, fcNormal):
1656
69
    return opOK;
1657
136
  }
1658
136
}
1659
1660
/* Change sign.  */
1661
103k
void IEEEFloat::changeSign() {
1662
103k
  /* Look mummy, this one's easy.  */
1663
103k
  sign = !sign;
1664
103k
}
1665
1666
/* Normalized addition or subtraction.  */
1667
IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
1668
                                             roundingMode rounding_mode,
1669
61.1k
                                             bool subtract) {
1670
61.1k
  opStatus fs;
1671
61.1k
1672
61.1k
  fs = addOrSubtractSpecials(rhs, subtract);
1673
61.1k
1674
61.1k
  /* This return code means it was not a simple case.  */
1675
61.1k
  if (fs == opDivByZero) {
1676
45.6k
    lostFraction lost_fraction;
1677
45.6k
1678
45.6k
    lost_fraction = addOrSubtractSignificand(rhs, subtract);
1679
45.6k
    fs = normalize(rounding_mode, lost_fraction);
1680
45.6k
1681
45.6k
    /* Can only be zero if we lost no fraction.  */
1682
45.6k
    assert(category != fcZero || lost_fraction == lfExactlyZero);
1683
45.6k
  }
1684
61.1k
1685
61.1k
  /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1686
61.1k
     positive zero unless rounding to minus infinity, except that
1687
61.1k
     adding two like-signed zeroes gives that zero.  */
1688
61.1k
  if (category == fcZero) {
1689
10.2k
    if (rhs.category != fcZero || 
(sign == rhs.sign) == subtract814
)
1690
9.63k
      sign = (rounding_mode == rmTowardNegative);
1691
10.2k
  }
1692
61.1k
1693
61.1k
  return fs;
1694
61.1k
}
1695
1696
/* Normalized addition.  */
1697
IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs,
1698
31.8k
                                   roundingMode rounding_mode) {
1699
31.8k
  return addOrSubtract(rhs, rounding_mode, false);
1700
31.8k
}
1701
1702
/* Normalized subtraction.  */
1703
IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs,
1704
29.2k
                                        roundingMode rounding_mode) {
1705
29.2k
  return addOrSubtract(rhs, rounding_mode, true);
1706
29.2k
}
1707
1708
/* Normalized multiply.  */
1709
IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs,
1710
11.6k
                                        roundingMode rounding_mode) {
1711
11.6k
  opStatus fs;
1712
11.6k
1713
11.6k
  sign ^= rhs.sign;
1714
11.6k
  fs = multiplySpecials(rhs);
1715
11.6k
1716
11.6k
  if (isFiniteNonZero()) {
1717
9.46k
    lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
1718
9.46k
    fs = normalize(rounding_mode, lost_fraction);
1719
9.46k
    if (lost_fraction != lfExactlyZero)
1720
1.90k
      fs = (opStatus) (fs | opInexact);
1721
9.46k
  }
1722
11.6k
1723
11.6k
  return fs;
1724
11.6k
}
1725
1726
/* Normalized divide.  */
1727
IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs,
1728
15.6k
                                      roundingMode rounding_mode) {
1729
15.6k
  opStatus fs;
1730
15.6k
1731
15.6k
  sign ^= rhs.sign;
1732
15.6k
  fs = divideSpecials(rhs);
1733
15.6k
1734
15.6k
  if (isFiniteNonZero()) {
1735
14.7k
    lostFraction lost_fraction = divideSignificand(rhs);
1736
14.7k
    fs = normalize(rounding_mode, lost_fraction);
1737
14.7k
    if (lost_fraction != lfExactlyZero)
1738
1.62k
      fs = (opStatus) (fs | opInexact);
1739
14.7k
  }
1740
15.6k
1741
15.6k
  return fs;
1742
15.6k
}
1743
1744
/* Normalized remainder.  This is not currently correct in all cases.  */
1745
2
IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) {
1746
2
  opStatus fs;
1747
2
  IEEEFloat V = *this;
1748
2
  unsigned int origSign = sign;
1749
2
1750
2
  fs = V.divide(rhs, rmNearestTiesToEven);
1751
2
  if (fs == opDivByZero)
1752
0
    return fs;
1753
2
1754
2
  int parts = partCount();
1755
2
  integerPart *x = new integerPart[parts];
1756
2
  bool ignored;
1757
2
  fs = V.convertToInteger(makeMutableArrayRef(x, parts),
1758
2
                          parts * integerPartWidth, true, rmNearestTiesToEven,
1759
2
                          &ignored);
1760
2
  if (fs == opInvalidOp) {
1761
0
    delete[] x;
1762
0
    return fs;
1763
0
  }
1764
2
1765
2
  fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1766
2
                                        rmNearestTiesToEven);
1767
2
  assert(fs==opOK);   // should always work
1768
2
1769
2
  fs = V.multiply(rhs, rmNearestTiesToEven);
1770
2
  assert(fs==opOK || fs==opInexact);   // should not overflow or underflow
1771
2
1772
2
  fs = subtract(V, rmNearestTiesToEven);
1773
2
  assert(fs==opOK || fs==opInexact);   // likewise
1774
2
1775
2
  if (isZero())
1776
0
    sign = origSign;    // IEEE754 requires this
1777
2
  delete[] x;
1778
2
  return fs;
1779
2
}
1780
1781
/* Normalized llvm frem (C fmod). */
1782
136
IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) {
1783
136
  opStatus fs;
1784
136
  fs = modSpecials(rhs);
1785
136
  unsigned int origSign = sign;
1786
136
1787
217
  while (isFiniteNonZero() && 
rhs.isFiniteNonZero()144
&&
1788
217
         
compareAbsoluteValue(rhs) != cmpLessThan141
) {
1789
81
    IEEEFloat V = scalbn(rhs, ilogb(*this) - ilogb(rhs), rmNearestTiesToEven);
1790
81
    if (compareAbsoluteValue(V) == cmpLessThan)
1791
49
      V = scalbn(V, -1, rmNearestTiesToEven);
1792
81
    V.sign = sign;
1793
81
1794
81
    fs = subtract(V, rmNearestTiesToEven);
1795
81
    assert(fs==opOK);
1796
81
  }
1797
136
  if (isZero())
1798
28
    sign = origSign; // fmod requires this
1799
136
  return fs;
1800
136
}
1801
1802
/* Normalized fused-multiply-add.  */
1803
IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand,
1804
                                                const IEEEFloat &addend,
1805
133
                                                roundingMode rounding_mode) {
1806
133
  opStatus fs;
1807
133
1808
133
  /* Post-multiplication sign, before addition.  */
1809
133
  sign ^= multiplicand.sign;
1810
133
1811
133
  /* If and only if all arguments are normal do we need to do an
1812
133
     extended-precision calculation.  */
1813
133
  if (isFiniteNonZero() &&
1814
133
      
multiplicand.isFiniteNonZero()127
&&
1815
133
      
addend.isFinite()123
) {
1816
119
    lostFraction lost_fraction;
1817
119
1818
119
    lost_fraction = multiplySignificand(multiplicand, &addend);
1819
119
    fs = normalize(rounding_mode, lost_fraction);
1820
119
    if (lost_fraction != lfExactlyZero)
1821
75
      fs = (opStatus) (fs | opInexact);
1822
119
1823
119
    /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1824
119
       positive zero unless rounding to minus infinity, except that
1825
119
       adding two like-signed zeroes gives that zero.  */
1826
119
    if (category == fcZero && 
!(fs & opUnderflow)20
&&
sign != addend.sign19
)
1827
19
      sign = (rounding_mode == rmTowardNegative);
1828
119
  } else {
1829
14
    fs = multiplySpecials(multiplicand);
1830
14
1831
14
    /* FS can only be opOK or opInvalidOp.  There is no more work
1832
14
       to do in the latter case.  The IEEE-754R standard says it is
1833
14
       implementation-defined in this case whether, if ADDEND is a
1834
14
       quiet NaN, we raise invalid op; this implementation does so.
1835
14
1836
14
       If we need to do the addition we can do so with normal
1837
14
       precision.  */
1838
14
    if (fs == opOK)
1839
13
      fs = addOrSubtract(addend, rounding_mode, false);
1840
14
  }
1841
133
1842
133
  return fs;
1843
133
}
1844
1845
/* Rounding-mode corrrect round to integral value.  */
1846
20.6k
IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) {
1847
20.6k
  opStatus fs;
1848
20.6k
1849
20.6k
  // If the exponent is large enough, we know that this value is already
1850
20.6k
  // integral, and the arithmetic below would potentially cause it to saturate
1851
20.6k
  // to +/-Inf.  Bail out early instead.
1852
20.6k
  if (isFiniteNonZero() && 
exponent+1 >= (int)semanticsPrecision(*semantics)18.4k
)
1853
124
    return opOK;
1854
20.5k
1855
20.5k
  // The algorithm here is quite simple: we add 2^(p-1), where p is the
1856
20.5k
  // precision of our format, and then subtract it back off again.  The choice
1857
20.5k
  // of rounding modes for the addition/subtraction determines the rounding mode
1858
20.5k
  // for our integral rounding as well.
1859
20.5k
  // NOTE: When the input value is negative, we do subtraction followed by
1860
20.5k
  // addition instead.
1861
20.5k
  APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1862
20.5k
  IntegerConstant <<= semanticsPrecision(*semantics)-1;
1863
20.5k
  IEEEFloat MagicConstant(*semantics);
1864
20.5k
  fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1865
20.5k
                                      rmNearestTiesToEven);
1866
20.5k
  MagicConstant.sign = sign;
1867
20.5k
1868
20.5k
  if (fs != opOK)
1869
0
    return fs;
1870
20.5k
1871
20.5k
  // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1872
20.5k
  bool inputSign = isNegative();
1873
20.5k
1874
20.5k
  fs = add(MagicConstant, rounding_mode);
1875
20.5k
  if (fs != opOK && 
fs != opInexact8.52k
)
1876
0
    return fs;
1877
20.5k
1878
20.5k
  fs = subtract(MagicConstant, rounding_mode);
1879
20.5k
1880
20.5k
  // Restore the input sign.
1881
20.5k
  if (inputSign != isNegative())
1882
780
    changeSign();
1883
20.5k
1884
20.5k
  return fs;
1885
20.5k
}
1886
1887
1888
/* Comparison requires normalized numbers.  */
1889
32.4k
IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const {
1890
32.4k
  cmpResult result;
1891
32.4k
1892
32.4k
  assert(semantics == rhs.semantics);
1893
32.4k
1894
32.4k
  switch (PackCategoriesIntoKey(category, rhs.category)) {
1895
32.4k
  default:
1896
0
    llvm_unreachable(nullptr);
1897
32.4k
1898
32.4k
  
case 181
PackCategoriesIntoKey181
(fcNaN, fcZero):
1899
181
  case PackCategoriesIntoKey(fcNaN, fcNormal):
1900
181
  case PackCategoriesIntoKey(fcNaN, fcInfinity):
1901
181
  case PackCategoriesIntoKey(fcNaN, fcNaN):
1902
181
  case PackCategoriesIntoKey(fcZero, fcNaN):
1903
181
  case PackCategoriesIntoKey(fcNormal, fcNaN):
1904
181
  case PackCategoriesIntoKey(fcInfinity, fcNaN):
1905
181
    return cmpUnordered;
1906
181
1907
1.68k
  case PackCategoriesIntoKey(fcInfinity, fcNormal):
1908
1.68k
  case PackCategoriesIntoKey(fcInfinity, fcZero):
1909
1.68k
  case PackCategoriesIntoKey(fcNormal, fcZero):
1910
1.68k
    if (sign)
1911
281
      return cmpLessThan;
1912
1.40k
    else
1913
1.40k
      return cmpGreaterThan;
1914
0
1915
8.51k
  case PackCategoriesIntoKey(fcNormal, fcInfinity):
1916
8.51k
  case PackCategoriesIntoKey(fcZero, fcInfinity):
1917
8.51k
  case PackCategoriesIntoKey(fcZero, fcNormal):
1918
8.51k
    if (rhs.sign)
1919
1.42k
      return cmpGreaterThan;
1920
7.08k
    else
1921
7.08k
      return cmpLessThan;
1922
0
1923
93
  case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1924
93
    if (sign == rhs.sign)
1925
93
      return cmpEqual;
1926
0
    else if (sign)
1927
0
      return cmpLessThan;
1928
0
    else
1929
0
      return cmpGreaterThan;
1930
0
1931
3.49k
  case PackCategoriesIntoKey(fcZero, fcZero):
1932
3.49k
    return cmpEqual;
1933
0
1934
18.5k
  case PackCategoriesIntoKey(fcNormal, fcNormal):
1935
18.5k
    break;
1936
18.5k
  }
1937
18.5k
1938
18.5k
  /* Two normal numbers.  Do they have the same sign?  */
1939
18.5k
  if (sign != rhs.sign) {
1940
775
    if (sign)
1941
556
      result = cmpLessThan;
1942
219
    else
1943
219
      result = cmpGreaterThan;
1944
17.7k
  } else {
1945
17.7k
    /* Compare absolute values; invert result if negative.  */
1946
17.7k
    result = compareAbsoluteValue(rhs);
1947
17.7k
1948
17.7k
    if (sign) {
1949
366
      if (result == cmpLessThan)
1950
69
        result = cmpGreaterThan;
1951
297
      else if (result == cmpGreaterThan)
1952
17
        result = cmpLessThan;
1953
366
    }
1954
17.7k
  }
1955
18.5k
1956
18.5k
  return result;
1957
18.5k
}
1958
1959
/// IEEEFloat::convert - convert a value of one floating point type to another.
1960
/// The return value corresponds to the IEEE754 exceptions.  *losesInfo
1961
/// records whether the transformation lost information, i.e. whether
1962
/// converting the result back to the original type will produce the
1963
/// original value (this is almost the same as return value==fsOK, but there
1964
/// are edge cases where this is not so).
1965
1966
IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics,
1967
                                       roundingMode rounding_mode,
1968
456k
                                       bool *losesInfo) {
1969
456k
  lostFraction lostFraction;
1970
456k
  unsigned int newPartCount, oldPartCount;
1971
456k
  opStatus fs;
1972
456k
  int shift;
1973
456k
  const fltSemantics &fromSemantics = *semantics;
1974
456k
1975
456k
  lostFraction = lfExactlyZero;
1976
456k
  newPartCount = partCountForBits(toSemantics.precision + 1);
1977
456k
  oldPartCount = partCount();
1978
456k
  shift = toSemantics.precision - fromSemantics.precision;
1979
456k
1980
456k
  bool X86SpecialNan = false;
1981
456k
  if (&fromSemantics == &semX87DoubleExtended &&
1982
456k
      
&toSemantics != &semX87DoubleExtended1.07k
&&
category == fcNaN1.07k
&&
1983
456k
      
(13
!(*significandParts() & 0x8000000000000000ULL)13
||
1984
13
       !(*significandParts() & 0x4000000000000000ULL))) {
1985
0
    // x86 has some unusual NaNs which cannot be represented in any other
1986
0
    // format; note them here.
1987
0
    X86SpecialNan = true;
1988
0
  }
1989
456k
1990
456k
  // If this is a truncation of a denormal number, and the target semantics
1991
456k
  // has larger exponent range than the source semantics (this can happen
1992
456k
  // when truncating from PowerPC double-double to double format), the
1993
456k
  // right shift could lose result mantissa bits.  Adjust exponent instead
1994
456k
  // of performing excessive shift.
1995
456k
  if (shift < 0 && 
isFiniteNonZero()417k
) {
1996
344k
    int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1997
344k
    if (exponent + exponentChange < toSemantics.minExponent)
1998
466
      exponentChange = toSemantics.minExponent - exponent;
1999
344k
    if (exponentChange < shift)
2000
0
      exponentChange = shift;
2001
344k
    if (exponentChange < 0) {
2002
0
      shift -= exponentChange;
2003
0
      exponent += exponentChange;
2004
0
    }
2005
344k
  }
2006
456k
2007
456k
  // If this is a truncation, perform the shift before we narrow the storage.
2008
456k
  if (shift < 0 && 
(417k
isFiniteNonZero()417k
||
category==fcNaN72.5k
))
2009
346k
    lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
2010
456k
2011
456k
  // Fix the storage so it can hold to new value.
2012
456k
  if (newPartCount > oldPartCount) {
2013
18.7k
    // The new type requires more storage; make it available.
2014
18.7k
    integerPart *newParts;
2015
18.7k
    newParts = new integerPart[newPartCount];
2016
18.7k
    APInt::tcSet(newParts, 0, newPartCount);
2017
18.7k
    if (isFiniteNonZero() || 
category==fcNaN645
)
2018
18.1k
      APInt::tcAssign(newParts, significandParts(), oldPartCount);
2019
18.7k
    freeSignificand();
2020
18.7k
    significand.parts = newParts;
2021
437k
  } else if (newPartCount == 1 && 
oldPartCount != 1437k
) {
2022
1.41k
    // Switch to built-in storage for a single part.
2023
1.41k
    integerPart newPart = 0;
2024
1.41k
    if (isFiniteNonZero() || 
category==fcNaN860
)
2025
607
      newPart = significandParts()[0];
2026
1.41k
    freeSignificand();
2027
1.41k
    significand.part = newPart;
2028
1.41k
  }
2029
456k
2030
456k
  // Now that we have the right storage, switch the semantics.
2031
456k
  semantics = &toSemantics;
2032
456k
2033
456k
  // If this is an extension, perform the shift now that the storage is
2034
456k
  // available.
2035
456k
  if (shift > 0 && 
(38.5k
isFiniteNonZero()38.5k
||
category==fcNaN6.16k
))
2036
32.7k
    APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2037
456k
2038
456k
  if (isFiniteNonZero()) {
2039
377k
    fs = normalize(rounding_mode, lostFraction);
2040
377k
    *losesInfo = (fs != opOK);
2041
377k
  } else 
if (78.7k
category == fcNaN78.7k
) {
2042
2.21k
    *losesInfo = lostFraction != lfExactlyZero || 
X86SpecialNan2.13k
;
2043
2.21k
2044
2.21k
    // For x87 extended precision, we want to make a NaN, not a special NaN if
2045
2.21k
    // the input wasn't special either.
2046
2.21k
    if (!X86SpecialNan && semantics == &semX87DoubleExtended)
2047
28
      APInt::tcSetBit(significandParts(), semantics->precision - 1);
2048
2.21k
2049
2.21k
    // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2050
2.21k
    // does not give you back the same bits.  This is dubious, and we
2051
2.21k
    // don't currently do it.  You're really supposed to get
2052
2.21k
    // an invalid operation signal at runtime, but nobody does that.
2053
2.21k
    fs = opOK;
2054
76.5k
  } else {
2055
76.5k
    *losesInfo = false;
2056
76.5k
    fs = opOK;
2057
76.5k
  }
2058
456k
2059
456k
  return fs;
2060
456k
}
2061
2062
/* Convert a floating point number to an integer according to the
2063
   rounding mode.  If the rounded integer value is out of range this
2064
   returns an invalid operation exception and the contents of the
2065
   destination parts are unspecified.  If the rounded value is in
2066
   range but the floating point number is not the exact integer, the C
2067
   standard doesn't require an inexact exception to be raised.  IEEE
2068
   854 does require it so we do that.
2069
2070
   Note that for conversions to integer type the C standard requires
2071
   round-to-zero to always be used.  */
2072
IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
2073
    MutableArrayRef<integerPart> parts, unsigned int width, bool isSigned,
2074
63.7k
    roundingMode rounding_mode, bool *isExact) const {
2075
63.7k
  lostFraction lost_fraction;
2076
63.7k
  const integerPart *src;
2077
63.7k
  unsigned int dstPartsCount, truncatedBits;
2078
63.7k
2079
63.7k
  *isExact = false;
2080
63.7k
2081
63.7k
  /* Handle the three special cases first.  */
2082
63.7k
  if (category == fcInfinity || 
category == fcNaN63.7k
)
2083
85
    return opInvalidOp;
2084
63.7k
2085
63.7k
  dstPartsCount = partCountForBits(width);
2086
63.7k
  assert(dstPartsCount <= parts.size() && "Integer too big");
2087
63.7k
2088
63.7k
  if (category == fcZero) {
2089
5.74k
    APInt::tcSet(parts.data(), 0, dstPartsCount);
2090
5.74k
    // Negative zero can't be represented as an int.
2091
5.74k
    *isExact = !sign;
2092
5.74k
    return opOK;
2093
5.74k
  }
2094
57.9k
2095
57.9k
  src = significandParts();
2096
57.9k
2097
57.9k
  /* Step 1: place our absolute value, with any fraction truncated, in
2098
57.9k
     the destination.  */
2099
57.9k
  if (exponent < 0) {
2100
960
    /* Our absolute value is less than one; truncate everything.  */
2101
960
    APInt::tcSet(parts.data(), 0, dstPartsCount);
2102
960
    /* For exponent -1 the integer bit represents .5, look at that.
2103
960
       For smaller exponents leftmost truncated bit is 0. */
2104
960
    truncatedBits = semantics->precision -1U - exponent;
2105
57.0k
  } else {
2106
57.0k
    /* We want the most significant (exponent + 1) bits; the rest are
2107
57.0k
       truncated.  */
2108
57.0k
    unsigned int bits = exponent + 1U;
2109
57.0k
2110
57.0k
    /* Hopelessly large in magnitude?  */
2111
57.0k
    if (bits > width)
2112
144
      return opInvalidOp;
2113
56.8k
2114
56.8k
    if (bits < semantics->precision) {
2115
56.7k
      /* We truncate (semantics->precision - bits) bits.  */
2116
56.7k
      truncatedBits = semantics->precision - bits;
2117
56.7k
      APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits);
2118
56.7k
    } else {
2119
147
      /* We want at least as many bits as are available.  */
2120
147
      APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision,
2121
147
                       0);
2122
147
      APInt::tcShiftLeft(parts.data(), dstPartsCount,
2123
147
                         bits - semantics->precision);
2124
147
      truncatedBits = 0;
2125
147
    }
2126
56.8k
  }
2127
57.9k
2128
57.9k
  /* Step 2: work out any lost fraction, and increment the absolute
2129
57.9k
     value if we would round away from zero.  */
2130
57.9k
  
if (57.8k
truncatedBits57.8k
) {
2131
57.6k
    lost_fraction = lostFractionThroughTruncation(src, partCount(),
2132
57.6k
                                                  truncatedBits);
2133
57.6k
    if (lost_fraction != lfExactlyZero &&
2134
57.6k
        
roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)43.5k
) {
2135
13
      if (APInt::tcIncrement(parts.data(), dstPartsCount))
2136
0
        return opInvalidOp;     /* Overflow.  */
2137
147
    }
2138
147
  } else {
2139
147
    lost_fraction = lfExactlyZero;
2140
147
  }
2141
57.8k
2142
57.8k
  /* Step 3: check if we fit in the destination.  */
2143
57.8k
  unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1;
2144
57.8k
2145
57.8k
  if (sign) {
2146
1.18k
    if (!isSigned) {
2147
20
      /* Negative numbers cannot be represented as unsigned.  */
2148
20
      if (omsb != 0)
2149
18
        return opInvalidOp;
2150
1.16k
    } else {
2151
1.16k
      /* It takes omsb bits to represent the unsigned integer value.
2152
1.16k
         We lose a bit for the sign, but care is needed as the
2153
1.16k
         maximally negative integer is a special case.  */
2154
1.16k
      if (omsb == width &&
2155
1.16k
          
APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb5
)
2156
3
        return opInvalidOp;
2157
1.16k
2158
1.16k
      /* This case can happen because of rounding.  */
2159
1.16k
      if (omsb > width)
2160
0
        return opInvalidOp;
2161
1.16k
    }
2162
1.16k
2163
1.16k
    APInt::tcNegate (parts.data(), dstPartsCount);
2164
56.6k
  } else {
2165
56.6k
    if (omsb >= width + !isSigned)
2166
5
      return opInvalidOp;
2167
57.7k
  }
2168
57.7k
2169
57.7k
  if (lost_fraction == lfExactlyZero) {
2170
14.2k
    *isExact = true;
2171
14.2k
    return opOK;
2172
14.2k
  } else
2173
43.5k
    return opInexact;
2174
57.7k
}
2175
2176
/* Same as convertToSignExtendedInteger, except we provide
2177
   deterministic values in case of an invalid operation exception,
2178
   namely zero for NaNs and the minimal or maximal value respectively
2179
   for underflow or overflow.
2180
   The *isExact output tells whether the result is exact, in the sense
2181
   that converting it back to the original floating point type produces
2182
   the original value.  This is almost equivalent to result==opOK,
2183
   except for negative zeroes.
2184
*/
2185
IEEEFloat::opStatus
2186
IEEEFloat::convertToInteger(MutableArrayRef<integerPart> parts,
2187
                            unsigned int width, bool isSigned,
2188
63.7k
                            roundingMode rounding_mode, bool *isExact) const {
2189
63.7k
  opStatus fs;
2190
63.7k
2191
63.7k
  fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
2192
63.7k
                                    isExact);
2193
63.7k
2194
63.7k
  if (fs == opInvalidOp) {
2195
255
    unsigned int bits, dstPartsCount;
2196
255
2197
255
    dstPartsCount = partCountForBits(width);
2198
255
    assert(dstPartsCount <= parts.size() && "Integer too big");
2199
255
2200
255
    if (category == fcNaN)
2201
52
      bits = 0;
2202
203
    else if (sign)
2203
57
      bits = isSigned;
2204
146
    else
2205
146
      bits = width - isSigned;
2206
255
2207
255
    APInt::tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits);
2208
255
    if (sign && 
isSigned57
)
2209
26
      APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1);
2210
255
  }
2211
63.7k
2212
63.7k
  return fs;
2213
63.7k
}
2214
2215
/* Convert an unsigned integer SRC to a floating point number,
2216
   rounding according to ROUNDING_MODE.  The sign of the floating
2217
   point number is not modified.  */
2218
IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2219
663k
    const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
2220
663k
  unsigned int omsb, precision, dstCount;
2221
663k
  integerPart *dst;
2222
663k
  lostFraction lost_fraction;
2223
663k
2224
663k
  category = fcNormal;
2225
663k
  omsb = APInt::tcMSB(src, srcCount) + 1;
2226
663k
  dst = significandParts();
2227
663k
  dstCount = partCount();
2228
663k
  precision = semantics->precision;
2229
663k
2230
663k
  /* We want the most significant PRECISION bits of SRC.  There may not
2231
663k
     be that many; extract what we can.  */
2232
663k
  if (precision <= omsb) {
2233
38.0k
    exponent = omsb - 1;
2234
38.0k
    lost_fraction = lostFractionThroughTruncation(src, srcCount,
2235
38.0k
                                                  omsb - precision);
2236
38.0k
    APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2237
625k
  } else {
2238
625k
    exponent = precision - 1;
2239
625k
    lost_fraction = lfExactlyZero;
2240
625k
    APInt::tcExtract(dst, dstCount, src, omsb, 0);
2241
625k
  }
2242
663k
2243
663k
  return normalize(rounding_mode, lost_fraction);
2244
663k
}
2245
2246
IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned,
2247
73.6k
                                                roundingMode rounding_mode) {
2248
73.6k
  unsigned int partCount = Val.getNumWords();
2249
73.6k
  APInt api = Val;
2250
73.6k
2251
73.6k
  sign = false;
2252
73.6k
  if (isSigned && 
api.isNegative()52.1k
) {
2253
14.2k
    sign = true;
2254
14.2k
    api = -api;
2255
14.2k
  }
2256
73.6k
2257
73.6k
  return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2258
73.6k
}
2259
2260
/* Convert a two's complement integer SRC to a floating point number,
2261
   rounding according to ROUNDING_MODE.  ISSIGNED is true if the
2262
   integer is signed, in which case it must be sign-extended.  */
2263
IEEEFloat::opStatus
2264
IEEEFloat::convertFromSignExtendedInteger(const integerPart *src,
2265
                                          unsigned int srcCount, bool isSigned,
2266
0
                                          roundingMode rounding_mode) {
2267
0
  opStatus status;
2268
0
2269
0
  if (isSigned &&
2270
0
      APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
2271
0
    integerPart *copy;
2272
0
2273
0
    /* If we're signed and negative negate a copy.  */
2274
0
    sign = true;
2275
0
    copy = new integerPart[srcCount];
2276
0
    APInt::tcAssign(copy, src, srcCount);
2277
0
    APInt::tcNegate(copy, srcCount);
2278
0
    status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2279
0
    delete [] copy;
2280
0
  } else {
2281
0
    sign = false;
2282
0
    status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2283
0
  }
2284
0
2285
0
  return status;
2286
0
}
2287
2288
/* FIXME: should this just take a const APInt reference?  */
2289
IEEEFloat::opStatus
2290
IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2291
                                          unsigned int width, bool isSigned,
2292
2
                                          roundingMode rounding_mode) {
2293
2
  unsigned int partCount = partCountForBits(width);
2294
2
  APInt api = APInt(width, makeArrayRef(parts, partCount));
2295
2
2296
2
  sign = false;
2297
2
  if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
2298
0
    sign = true;
2299
0
    api = -api;
2300
0
  }
2301
2
2302
2
  return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2303
2
}
2304
2305
IEEEFloat::opStatus
2306
IEEEFloat::convertFromHexadecimalString(StringRef s,
2307
763
                                        roundingMode rounding_mode) {
2308
763
  lostFraction lost_fraction = lfExactlyZero;
2309
763
2310
763
  category = fcNormal;
2311
763
  zeroSignificand();
2312
763
  exponent = 0;
2313
763
2314
763
  integerPart *significand = significandParts();
2315
763
  unsigned partsCount = partCount();
2316
763
  unsigned bitPos = partsCount * integerPartWidth;
2317
763
  bool computedTrailingFraction = false;
2318
763
2319
763
  // Skip leading zeroes and any (hexa)decimal point.
2320
763
  StringRef::iterator begin = s.begin();
2321
763
  StringRef::iterator end = s.end();
2322
763
  StringRef::iterator dot;
2323
763
  StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
2324
763
  StringRef::iterator firstSignificantDigit = p;
2325
763
2326
4.46k
  while (p != end) {
2327
4.46k
    integerPart hex_value;
2328
4.46k
2329
4.46k
    if (*p == '.') {
2330
259
      assert(dot == end && "String contains multiple dots");
2331
259
      dot = p++;
2332
259
      continue;
2333
259
    }
2334
4.20k
2335
4.20k
    hex_value = hexDigitValue(*p);
2336
4.20k
    if (hex_value == -1U)
2337
763
      break;
2338
3.44k
2339
3.44k
    p++;
2340
3.44k
2341
3.44k
    // Store the number while we have space.
2342
3.44k
    if (bitPos) {
2343
3.43k
      bitPos -= 4;
2344
3.43k
      hex_value <<= bitPos % integerPartWidth;
2345
3.43k
      significand[bitPos / integerPartWidth] |= hex_value;
2346
3.43k
    } else 
if (9
!computedTrailingFraction9
) {
2347
2
      lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2348
2
      computedTrailingFraction = true;
2349
2
    }
2350
3.44k
  }
2351
763
2352
763
  /* Hex floats require an exponent but not a hexadecimal point.  */
2353
763
  assert(p != end && "Hex strings require an exponent");
2354
763
  assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2355
763
  assert(p != begin && "Significand has no digits");
2356
763
  assert((dot == end || p - begin != 1) && "Significand has no digits");
2357
763
2358
763
  /* Ignore the exponent if we are zero.  */
2359
763
  if (p != firstSignificantDigit) {
2360
584
    int expAdjustment;
2361
584
2362
584
    /* Implicit hexadecimal point?  */
2363
584
    if (dot == end)
2364
286
      dot = p;
2365
584
2366
584
    /* Calculate the exponent adjustment implicit in the number of
2367
584
       significant digits.  */
2368
584
    expAdjustment = static_cast<int>(dot - firstSignificantDigit);
2369
584
    if (expAdjustment < 0)
2370
39
      expAdjustment++;
2371
584
    expAdjustment = expAdjustment * 4 - 1;
2372
584
2373
584
    /* Adjust for writing the significand starting at the most
2374
584
       significant nibble.  */
2375
584
    expAdjustment += semantics->precision;
2376
584
    expAdjustment -= partsCount * integerPartWidth;
2377
584
2378
584
    /* Adjust for the given exponent.  */
2379
584
    exponent = totalExponent(p + 1, end, expAdjustment);
2380
584
  }
2381
763
2382
763
  return normalize(rounding_mode, lost_fraction);
2383
763
}
2384
2385
IEEEFloat::opStatus
2386
IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2387
                                        unsigned sigPartCount, int exp,
2388
295k
                                        roundingMode rounding_mode) {
2389
295k
  unsigned int parts, pow5PartCount;
2390
295k
  fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
2391
295k
  integerPart pow5Parts[maxPowerOfFiveParts];
2392
295k
  bool isNearest;
2393
295k
2394
295k
  isNearest = (rounding_mode == rmNearestTiesToEven ||
2395
295k
               
rounding_mode == rmNearestTiesToAway4.17k
);
2396
295k
2397
295k
  parts = partCountForBits(semantics->precision + 11);
2398
295k
2399
295k
  /* Calculate pow(5, abs(exp)).  */
2400
295k
  pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? 
exp76.5k
:
-exp218k
);
2401
295k
2402
295k
  for (;; 
parts *= 229
) {
2403
295k
    opStatus sigStatus, powStatus;
2404
295k
    unsigned int excessPrecision, truncatedBits;
2405
295k
2406
295k
    calcSemantics.precision = parts * integerPartWidth - 1;
2407
295k
    excessPrecision = calcSemantics.precision - semantics->precision;
2408
295k
    truncatedBits = excessPrecision;
2409
295k
2410
295k
    IEEEFloat decSig(calcSemantics, uninitialized);
2411
295k
    decSig.makeZero(sign);
2412
295k
    IEEEFloat pow5(calcSemantics);
2413
295k
2414
295k
    sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2415
295k
                                                rmNearestTiesToEven);
2416
295k
    powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2417
295k
                                              rmNearestTiesToEven);
2418
295k
    /* Add exp, as 10^n = 5^n * 2^n.  */
2419
295k
    decSig.exponent += exp;
2420
295k
2421
295k
    lostFraction calcLostFraction;
2422
295k
    integerPart HUerr, HUdistance;
2423
295k
    unsigned int powHUerr;
2424
295k
2425
295k
    if (exp >= 0) {
2426
76.5k
      /* multiplySignificand leaves the precision-th bit set to 1.  */
2427
76.5k
      calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
2428
76.5k
      powHUerr = powStatus != opOK;
2429
218k
    } else {
2430
218k
      calcLostFraction = decSig.divideSignificand(pow5);
2431
218k
      /* Denormal numbers have less precision.  */
2432
218k
      if (decSig.exponent < semantics->minExponent) {
2433
4.80k
        excessPrecision += (semantics->minExponent - decSig.exponent);
2434
4.80k
        truncatedBits = excessPrecision;
2435
4.80k
        if (excessPrecision > calcSemantics.precision)
2436
0
          excessPrecision = calcSemantics.precision;
2437
4.80k
      }
2438
218k
      /* Extra half-ulp lost in reciprocal of exponent.  */
2439
218k
      powHUerr = (powStatus == opOK && 
calcLostFraction == lfExactlyZero207k
) ?
063.4k
:
2155k
;
2440
218k
    }
2441
295k
2442
295k
    /* Both multiplySignificand and divideSignificand return the
2443
295k
       result with the integer bit set.  */
2444
295k
    assert(APInt::tcExtractBit
2445
295k
           (decSig.significandParts(), calcSemantics.precision - 1) == 1);
2446
295k
2447
295k
    HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2448
295k
                       powHUerr);
2449
295k
    HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2450
295k
                                      excessPrecision, isNearest);
2451
295k
2452
295k
    /* Are we guaranteed to round correctly if we truncate?  */
2453
295k
    if (HUdistance >= HUerr) {
2454
295k
      APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2455
295k
                       calcSemantics.precision - excessPrecision,
2456
295k
                       excessPrecision);
2457
295k
      /* Take the exponent of decSig.  If we tcExtract-ed less bits
2458
295k
         above we must adjust our exponent to compensate for the
2459
295k
         implicit right shift.  */
2460
295k
      exponent = (decSig.exponent + semantics->precision
2461
295k
                  - (calcSemantics.precision - excessPrecision));
2462
295k
      calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2463
295k
                                                       decSig.partCount(),
2464
295k
                                                       truncatedBits);
2465
295k
      return normalize(rounding_mode, calcLostFraction);
2466
295k
    }
2467
295k
  }
2468
295k
}
2469
2470
IEEEFloat::opStatus
2471
350k
IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
2472
350k
  decimalInfo D;
2473
350k
  opStatus fs;
2474
350k
2475
350k
  /* Scan the text.  */
2476
350k
  StringRef::iterator p = str.begin();
2477
350k
  interpretDecimal(p, str.end(), &D);
2478
350k
2479
350k
  /* Handle the quick cases.  First the case of no significant digits,
2480
350k
     i.e. zero, and then exponents that are obviously too large or too
2481
350k
     small.  Writing L for log 10 / log 2, a number d.ddddd*10^exp
2482
350k
     definitely overflows if
2483
350k
2484
350k
           (exp - 1) * L >= maxExponent
2485
350k
2486
350k
     and definitely underflows to zero where
2487
350k
2488
350k
           (exp + 1) * L <= minExponent - precision
2489
350k
2490
350k
     With integer arithmetic the tightest bounds for L are
2491
350k
2492
350k
           93/28 < L < 196/59            [ numerator <= 256 ]
2493
350k
           42039/12655 < L < 28738/8651  [ numerator <= 65536 ]
2494
350k
  */
2495
350k
2496
350k
  // Test if we have a zero number allowing for strings with no null terminators
2497
350k
  // and zero decimals with non-zero exponents.
2498
350k
  //
2499
350k
  // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2500
350k
  // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2501
350k
  // be at most one dot. On the other hand, if we have a zero with a non-zero
2502
350k
  // exponent, then we know that D.firstSigDigit will be non-numeric.
2503
350k
  if (D.firstSigDigit == str.end() || 
decDigitValue(*D.firstSigDigit) >= 10U320k
) {
2504
55.0k
    category = fcZero;
2505
55.0k
    fs = opOK;
2506
55.0k
2507
55.0k
  /* Check whether the normalized exponent is high enough to overflow
2508
55.0k
     max during the log-rebasing in the max-exponent check below. */
2509
295k
  } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2510
2
    fs = handleOverflow(rounding_mode);
2511
2
2512
2
  /* If it wasn't, then it also wasn't high enough to overflow max
2513
2
     during the log-rebasing in the min-exponent check.  Check that it
2514
2
     won't overflow min in either check, then perform the min-exponent
2515
2
     check. */
2516
295k
  } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2517
295k
             (D.normalizedExponent + 1) * 28738 <=
2518
295k
               8651 * (semantics->minExponent - (int) semantics->precision)) {
2519
6
    /* Underflow to zero and round.  */
2520
6
    category = fcNormal;
2521
6
    zeroSignificand();
2522
6
    fs = normalize(rounding_mode, lfLessThanHalf);
2523
6
2524
6
  /* We can finally safely perform the max-exponent check. */
2525
295k
  } else if ((D.normalizedExponent - 1) * 42039
2526
295k
             >= 12655 * semantics->maxExponent) {
2527
6
    /* Overflow and round.  */
2528
6
    fs = handleOverflow(rounding_mode);
2529
295k
  } else {
2530
295k
    integerPart *decSignificand;
2531
295k
    unsigned int partCount;
2532
295k
2533
295k
    /* A tight upper bound on number of bits required to hold an
2534
295k
       N-digit decimal integer is N * 196 / 59.  Allocate enough space
2535
295k
       to hold the full significand, and an extra part required by
2536
295k
       tcMultiplyPart.  */
2537
295k
    partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
2538
295k
    partCount = partCountForBits(1 + 196 * partCount / 59);
2539
295k
    decSignificand = new integerPart[partCount + 1];
2540
295k
    partCount = 0;
2541
295k
2542
295k
    /* Convert to binary efficiently - we do almost all multiplication
2543
295k
       in an integerPart.  When this would overflow do we do a single
2544
295k
       bignum multiplication, and then revert again to multiplication
2545
295k
       in an integerPart.  */
2546
296k
    do {
2547
296k
      integerPart decValue, val, multiplier;
2548
296k
2549
296k
      val = 0;
2550
296k
      multiplier = 1;
2551
296k
2552
1.54M
      do {
2553
1.54M
        if (*p == '.') {
2554
217k
          p++;
2555
217k
          if (p == str.end()) {
2556
0
            break;
2557
0
          }
2558
1.54M
        }
2559
1.54M
        decValue = decDigitValue(*p++);
2560
1.54M
        assert(decValue < 10U && "Invalid character in significand");
2561
1.54M
        multiplier *= 10;
2562
1.54M
        val = val * 10 + decValue;
2563
1.54M
        /* The maximum number that can be multiplied by ten with any
2564
1.54M
           digit added without overflowing an integerPart.  */
2565
1.54M
      } while (p <= D.lastSigDigit && 
multiplier <= (~ (integerPart) 0 - 9) / 101.25M
);
2566
296k
2567
296k
      /* Multiply out the current part.  */
2568
296k
      APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2569
296k
                            partCount, partCount + 1, false);
2570
296k
2571
296k
      /* If we used another part (likely but not guaranteed), increase
2572
296k
         the count.  */
2573
296k
      if (decSignificand[partCount])
2574
296k
        partCount++;
2575
296k
    } while (p <= D.lastSigDigit);
2576
295k
2577
295k
    category = fcNormal;
2578
295k
    fs = roundSignificandWithExponent(decSignificand, partCount,
2579
295k
                                      D.exponent, rounding_mode);
2580
295k
2581
295k
    delete [] decSignificand;
2582
295k
  }
2583
350k
2584
350k
  return fs;
2585
350k
}
2586
2587
351k
bool IEEEFloat::convertFromStringSpecials(StringRef str) {
2588
351k
  if (str.equals("inf") || 
str.equals("INFINITY")351k
||
str.equals("+Inf")351k
) {
2589
91
    makeInf(false);
2590
91
    return true;
2591
91
  }
2592
351k
2593
351k
  if (str.equals("-inf") || 
str.equals("-INFINITY")351k
||
str.equals("-Inf")351k
) {
2594
91
    makeInf(true);
2595
91
    return true;
2596
91
  }
2597
351k
2598
351k
  if (str.equals("nan") || 
str.equals("NaN")350k
) {
2599
110
    makeNaN(false, false);
2600
110
    return true;
2601
110
  }
2602
350k
2603
350k
  if (str.equals("-nan") || 
str.equals("-NaN")350k
) {
2604
14
    makeNaN(false, true);
2605
14
    return true;
2606
14
  }
2607
350k
2608
350k
  return false;
2609
350k
}
2610
2611
IEEEFloat::opStatus IEEEFloat::convertFromString(StringRef str,
2612
351k
                                                 roundingMode rounding_mode) {
2613
351k
  assert(!str.empty() && "Invalid string length");
2614
351k
2615
351k
  // Handle special cases.
2616
351k
  if (convertFromStringSpecials(str))
2617
306
    return opOK;
2618
350k
2619
350k
  /* Handle a leading minus sign.  */
2620
350k
  StringRef::iterator p = str.begin();
2621
350k
  size_t slen = str.size();
2622
350k
  sign = *p == '-' ? 
122.8k
:
0328k
;
2623
350k
  if (*p == '-' || 
*p == '+'328k
) {
2624
22.9k
    p++;
2625
22.9k
    slen--;
2626
22.9k
    assert(slen && "String has no digits");
2627
22.9k
  }
2628
350k
2629
350k
  if (slen >= 2 && 
p[0] == '0'350k
&&
(180k
p[1] == 'x'180k
||
p[1] == 'X'179k
)) {
2630
763
    assert(slen - 2 && "Invalid string");
2631
763
    return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
2632
763
                                        rounding_mode);
2633
763
  }
2634
350k
2635
350k
  return convertFromDecimalString(StringRef(p, slen), rounding_mode);
2636
350k
}
2637
2638
/* Write out a hexadecimal representation of the floating point value
2639
   to DST, which must be of sufficient size, in the C99 form
2640
   [-]0xh.hhhhp[+-]d.  Return the number of characters written,
2641
   excluding the terminating NUL.
2642
2643
   If UPPERCASE, the output is in upper case, otherwise in lower case.
2644
2645
   HEXDIGITS digits appear altogether, rounding the value if
2646
   necessary.  If HEXDIGITS is 0, the minimal precision to display the
2647
   number precisely is used instead.  If nothing would appear after
2648
   the decimal point it is suppressed.
2649
2650
   The decimal exponent is always printed and has at least one digit.
2651
   Zero values display an exponent of zero.  Infinities and NaNs
2652
   appear as "infinity" or "nan" respectively.
2653
2654
   The above rules are as specified by C99.  There is ambiguity about
2655
   what the leading hexadecimal digit should be.  This implementation
2656
   uses whatever is necessary so that the exponent is displayed as
2657
   stored.  This implies the exponent will fall within the IEEE format
2658
   range, and the leading hexadecimal digit will be 0 (for denormals),
2659
   1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2660
   any other digits zero).
2661
*/
2662
unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
2663
                                           bool upperCase,
2664
254
                                           roundingMode rounding_mode) const {
2665
254
  char *p;
2666
254
2667
254
  p = dst;
2668
254
  if (sign)
2669
16
    *dst++ = '-';
2670
254
2671
254
  switch (category) {
2672
254
  case fcInfinity:
2673
5
    memcpy (dst, upperCase ? 
infinityU0
: infinityL, sizeof infinityU - 1);
2674
5
    dst += sizeof infinityL - 1;
2675
5
    break;
2676
254
2677
254
  case fcNaN:
2678
5
    memcpy (dst, upperCase ? 
NaNU0
: NaNL, sizeof NaNU - 1);
2679
5
    dst += sizeof NaNU - 1;
2680
5
    break;
2681
254
2682
254
  case fcZero:
2683
39
    *dst++ = '0';
2684
39
    *dst++ = upperCase ? 
'X'0
: 'x';
2685
39
    *dst++ = '0';
2686
39
    if (hexDigits > 1) {
2687
0
      *dst++ = '.';
2688
0
      memset (dst, '0', hexDigits - 1);
2689
0
      dst += hexDigits - 1;
2690
0
    }
2691
39
    *dst++ = upperCase ? 
'P'0
: 'p';
2692
39
    *dst++ = '0';
2693
39
    break;
2694
254
2695
254
  case fcNormal:
2696
205
    dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2697
205
    break;
2698
254
  }
2699
254
2700
254
  *dst = 0;
2701
254
2702
254
  return static_cast<unsigned int>(dst - p);
2703
254
}
2704
2705
/* Does the hard work of outputting the correctly rounded hexadecimal
2706
   form of a normal floating point number with the specified number of
2707
   hexadecimal digits.  If HEXDIGITS is zero the minimum number of
2708
   digits necessary to print the value precisely is output.  */
2709
char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2710
                                          bool upperCase,
2711
205
                                          roundingMode rounding_mode) const {
2712
205
  unsigned int count, valueBits, shift, partsCount, outputDigits;
2713
205
  const char *hexDigitChars;
2714
205
  const integerPart *significand;
2715
205
  char *p;
2716
205
  bool roundUp;
2717
205
2718
205
  *dst++ = '0';
2719
205
  *dst++ = upperCase ? 
'X'0
: 'x';
2720
205
2721
205
  roundUp = false;
2722
205
  hexDigitChars = upperCase ? 
hexDigitsUpper0
: hexDigitsLower;
2723
205
2724
205
  significand = significandParts();
2725
205
  partsCount = partCount();
2726
205
2727
205
  /* +3 because the first digit only uses the single integer bit, so
2728
205
     we have 3 virtual zero most-significant-bits.  */
2729
205
  valueBits = semantics->precision + 3;
2730
205
  shift = integerPartWidth - valueBits % integerPartWidth;
2731
205
2732
205
  /* The natural number of digits required ignoring trailing
2733
205
     insignificant zeroes.  */
2734
205
  outputDigits = (valueBits - significandLSB () + 3) / 4;
2735
205
2736
205
  /* hexDigits of zero means use the required number for the
2737
205
     precision.  Otherwise, see if we are truncating.  If we are,
2738
205
     find out if we need to round away from zero.  */
2739
205
  if (hexDigits) {
2740
0
    if (hexDigits < outputDigits) {
2741
0
      /* We are dropping non-zero bits, so need to check how to round.
2742
0
         "bits" is the number of dropped bits.  */
2743
0
      unsigned int bits;
2744
0
      lostFraction fraction;
2745
0
2746
0
      bits = valueBits - hexDigits * 4;
2747
0
      fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2748
0
      roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2749
0
    }
2750
0
    outputDigits = hexDigits;
2751
0
  }
2752
205
2753
205
  /* Write the digits consecutively, and start writing in the location
2754
205
     of the hexadecimal point.  We move the most significant digit
2755
205
     left and add the hexadecimal point later.  */
2756
205
  p = ++dst;
2757
205
2758
205
  count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2759
205
2760
410
  while (outputDigits && 
count205
) {
2761
205
    integerPart part;
2762
205
2763
205
    /* Put the most significant integerPartWidth bits in "part".  */
2764
205
    if (--count == partsCount)
2765
0
      part = 0;  /* An imaginary higher zero part.  */
2766
205
    else
2767
205
      part = significand[count] << shift;
2768
205
2769
205
    if (count && 
shift0
)
2770
0
      part |= significand[count - 1] >> (integerPartWidth - shift);
2771
205
2772
205
    /* Convert as much of "part" to hexdigits as we can.  */
2773
205
    unsigned int curDigits = integerPartWidth / 4;
2774
205
2775
205
    if (curDigits > outputDigits)
2776
205
      curDigits = outputDigits;
2777
205
    dst += partAsHex (dst, part, curDigits, hexDigitChars);
2778
205
    outputDigits -= curDigits;
2779
205
  }
2780
205
2781
205
  if (roundUp) {
2782
0
    char *q = dst;
2783
0
2784
0
    /* Note that hexDigitChars has a trailing '0'.  */
2785
0
    do {
2786
0
      q--;
2787
0
      *q = hexDigitChars[hexDigitValue (*q) + 1];
2788
0
    } while (*q == '0');
2789
0
    assert(q >= p);
2790
205
  } else {
2791
205
    /* Add trailing zeroes.  */
2792
205
    memset (dst, '0', outputDigits);
2793
205
    dst += outputDigits;
2794
205
  }
2795
205
2796
205
  /* Move the most significant digit to before the point, and if there
2797
205
     is something after the decimal point add it.  This must come
2798
205
     after rounding above.  */
2799
205
  p[-1] = p[0];
2800
205
  if (dst -1 == p)
2801
42
    dst--;
2802
163
  else
2803
163
    p[0] = '.';
2804
205
2805
205
  /* Finally output the exponent.  */
2806
205
  *dst++ = upperCase ? 
'P'0
: 'p';
2807
205
2808
205
  return writeSignedDecimal (dst, exponent);
2809
205
}
2810
2811
1.15M
hash_code hash_value(const IEEEFloat &Arg) {
2812
1.15M
  if (!Arg.isFiniteNonZero())
2813
150k
    return hash_combine((uint8_t)Arg.category,
2814
150k
                        // NaN has no sign, fix it at zero.
2815
150k
                        Arg.isNaN() ? 
(uint8_t)017.0k
:
(uint8_t)Arg.sign133k
,
2816
150k
                        Arg.semantics->precision);
2817
999k
2818
999k
  // Normal floats need their exponent and significand hashed.
2819
999k
  return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2820
999k
                      Arg.semantics->precision, Arg.exponent,
2821
999k
                      hash_combine_range(
2822
999k
                        Arg.significandParts(),
2823
999k
                        Arg.significandParts() + Arg.partCount()));
2824
999k
}
2825
2826
// Conversion from APFloat to/from host float/double.  It may eventually be
2827
// possible to eliminate these and have everybody deal with APFloats, but that
2828
// will take a while.  This approach will not easily extend to long double.
2829
// Current implementation requires integerPartWidth==64, which is correct at
2830
// the moment but could be made more general.
2831
2832
// Denormals have exponent minExponent in APFloat, but minExponent-1 in
2833
// the actual IEEE respresentations.  We compensate for that here.
2834
2835
1.56k
APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
2836
1.56k
  assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended);
2837
1.56k
  assert(partCount()==2);
2838
1.56k
2839
1.56k
  uint64_t myexponent, mysignificand;
2840
1.56k
2841
1.56k
  if (isFiniteNonZero()) {
2842
1.22k
    myexponent = exponent+16383; //bias
2843
1.22k
    mysignificand = significandParts()[0];
2844
1.22k
    if (myexponent==1 && 
!(mysignificand & 0x8000000000000000ULL)442
)
2845
150
      myexponent = 0;   // denormal
2846
1.22k
  } else 
if (347
category==fcZero347
) {
2847
315
    myexponent = 0;
2848
315
    mysignificand = 0;
2849
315
  } else 
if (32
category==fcInfinity32
) {
2850
15
    myexponent = 0x7fff;
2851
15
    mysignificand = 0x8000000000000000ULL;
2852
17
  } else {
2853
17
    assert(category == fcNaN && "Unknown category");
2854
17
    myexponent = 0x7fff;
2855
17
    mysignificand = significandParts()[0];
2856
17
  }
2857
1.56k
2858
1.56k
  uint64_t words[2];
2859
1.56k
  words[0] = mysignificand;
2860
1.56k
  words[1] =  ((uint64_t)(sign & 1) << 15) |
2861
1.56k
              (myexponent & 0x7fffLL);
2862
1.56k
  return APInt(80, words);
2863
1.56k
}
2864
2865
81
APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const {
2866
81
  assert(semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy);
2867
81
  assert(partCount()==2);
2868
81
2869
81
  uint64_t words[2];
2870
81
  opStatus fs;
2871
81
  bool losesInfo;
2872
81
2873
81
  // Convert number to double.  To avoid spurious underflows, we re-
2874
81
  // normalize against the "double" minExponent first, and only *then*
2875
81
  // truncate the mantissa.  The result of that second conversion
2876
81
  // may be inexact, but should never underflow.
2877
81
  // Declare fltSemantics before APFloat that uses it (and
2878
81
  // saves pointer to it) to ensure correct destruction order.
2879
81
  fltSemantics extendedSemantics = *semantics;
2880
81
  extendedSemantics.minExponent = semIEEEdouble.minExponent;
2881
81
  IEEEFloat extended(*this);
2882
81
  fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2883
81
  assert(fs == opOK && !losesInfo);
2884
81
  (void)fs;
2885
81
2886
81
  IEEEFloat u(extended);
2887
81
  fs = u.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
2888
81
  assert(fs == opOK || fs == opInexact);
2889
81
  (void)fs;
2890
81
  words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2891
81
2892
81
  // If conversion was exact or resulted in a special case, we're done;
2893
81
  // just set the second double to zero.  Otherwise, re-convert back to
2894
81
  // the extended format and compute the difference.  This now should
2895
81
  // convert exactly to double.
2896
81
  if (u.isFiniteNonZero() && 
losesInfo73
) {
2897
6
    fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2898
6
    assert(fs == opOK && !losesInfo);
2899
6
    (void)fs;
2900
6
2901
6
    IEEEFloat v(extended);
2902
6
    v.subtract(u, rmNearestTiesToEven);
2903
6
    fs = v.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
2904
6
    assert(fs == opOK && !losesInfo);
2905
6
    (void)fs;
2906
6
    words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
2907
75
  } else {
2908
75
    words[1] = 0;
2909
75
  }
2910
81
2911
81
  return APInt(128, words);
2912
81
}
2913
2914
739
APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
2915
739
  assert(semantics == (const llvm::fltSemantics*)&semIEEEquad);
2916
739
  assert(partCount()==2);
2917
739
2918
739
  uint64_t myexponent, mysignificand, mysignificand2;
2919
739
2920
739
  if (isFiniteNonZero()) {
2921
545
    myexponent = exponent+16383; //bias
2922
545
    mysignificand = significandParts()[0];
2923
545
    mysignificand2 = significandParts()[1];
2924
545
    if (myexponent==1 && 
!(mysignificand2 & 0x1000000000000LL)3
)
2925
3
      myexponent = 0;   // denormal
2926
545
  } else 
if (194
category==fcZero194
) {
2927
150
    myexponent = 0;
2928
150
    mysignificand = mysignificand2 = 0;
2929
150
  } else 
if (44
category==fcInfinity44
) {
2930
26
    myexponent = 0x7fff;
2931
26
    mysignificand = mysignificand2 = 0;
2932
26
  } else {
2933
18
    assert(category == fcNaN && "Unknown category!");
2934
18
    myexponent = 0x7fff;
2935
18
    mysignificand = significandParts()[0];
2936
18
    mysignificand2 = significandParts()[1];
2937
18
  }
2938
739
2939
739
  uint64_t words[2];
2940
739
  words[0] = mysignificand;
2941
739
  words[1] = ((uint64_t)(sign & 1) << 63) |
2942
739
             ((myexponent & 0x7fff) << 48) |
2943
739
             (mysignificand2 & 0xffffffffffffLL);
2944
739
2945
739
  return APInt(128, words);
2946
739
}
2947
2948
488k
APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
2949
488k
  assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble);
2950
488k
  assert(partCount()==1);
2951
488k
2952
488k
  uint64_t myexponent, mysignificand;
2953
488k
2954
488k
  if (isFiniteNonZero()) {
2955
404k
    myexponent = exponent+1023; //bias
2956
404k
    mysignificand = *significandParts();
2957
404k
    if (myexponent==1 && 
!(mysignificand & 0x10000000000000LL)6.17k
)
2958
2.17k
      myexponent = 0;   // denormal
2959
404k
  } else 
if (84.2k
category==fcZero84.2k
) {
2960
75.3k
    myexponent = 0;
2961
75.3k
    mysignificand = 0;
2962
75.3k
  } else 
if (8.89k
category==fcInfinity8.89k
) {
2963
2.22k
    myexponent = 0x7ff;
2964
2.22k
    mysignificand = 0;
2965
6.66k
  } else {
2966
6.66k
    assert(category == fcNaN && "Unknown category!");
2967
6.66k
    myexponent = 0x7ff;
2968
6.66k
    mysignificand = *significandParts();
2969
6.66k
  }
2970
488k
2971
488k
  return APInt(64, ((((uint64_t)(sign & 1) << 63) |
2972
488k
                     ((myexponent & 0x7ff) <<  52) |
2973
488k
                     (mysignificand & 0xfffffffffffffLL))));
2974
488k
}
2975
2976
974k
APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
2977
974k
  assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle);
2978
974k
  assert(partCount()==1);
2979
974k
2980
974k
  uint32_t myexponent, mysignificand;
2981
974k
2982
974k
  if (isFiniteNonZero()) {
2983
854k
    myexponent = exponent+127; //bias
2984
854k
    mysignificand = (uint32_t)*significandParts();
2985
854k
    if (myexponent == 1 && 
!(mysignificand & 0x800000)4.30k
)
2986
2.00k
      myexponent = 0;   // denormal
2987
854k
  } else 
if (120k
category==fcZero120k
) {
2988
108k
    myexponent = 0;
2989
108k
    mysignificand = 0;
2990
108k
  } else 
if (12.2k
category==fcInfinity12.2k
) {
2991
1.25k
    myexponent = 0xff;
2992
1.25k
    mysignificand = 0;
2993
11.0k
  } else {
2994
11.0k
    assert(category == fcNaN && "Unknown category!");
2995
11.0k
    myexponent = 0xff;
2996
11.0k
    mysignificand = (uint32_t)*significandParts();
2997
11.0k
  }
2998
974k
2999
974k
  return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
3000
974k
                    (mysignificand & 0x7fffff)));
3001
974k
}
3002
3003
19.5k
APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
3004
19.5k
  assert(semantics == (const llvm::fltSemantics*)&semIEEEhalf);
3005
19.5k
  assert(partCount()==1);
3006
19.5k
3007
19.5k
  uint32_t myexponent, mysignificand;
3008
19.5k
3009
19.5k
  if (isFiniteNonZero()) {
3010
17.9k
    myexponent = exponent+15; //bias
3011
17.9k
    mysignificand = (uint32_t)*significandParts();
3012
17.9k
    if (myexponent == 1 && 
!(mysignificand & 0x400)772
)
3013
767
      myexponent = 0;   // denormal
3014
17.9k
  } else 
if (1.53k
category==fcZero1.53k
) {
3015
1.28k
    myexponent = 0;
3016
1.28k
    mysignificand = 0;
3017
1.28k
  } else 
if (245
category==fcInfinity245
) {
3018
77
    myexponent = 0x1f;
3019
77
    mysignificand = 0;
3020
168
  } else {
3021
168
    assert(category == fcNaN && "Unknown category!");
3022
168
    myexponent = 0x1f;
3023
168
    mysignificand = (uint32_t)*significandParts();
3024
168
  }
3025
19.5k
3026
19.5k
  return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
3027
19.5k
                    (mysignificand & 0x3ff)));
3028
19.5k
}
3029
3030
// This function creates an APInt that is just a bit map of the floating
3031
// point constant as it would appear in memory.  It is not a conversion,
3032
// and treating the result as a normal integer is unlikely to be useful.
3033
3034
1.48M
APInt IEEEFloat::bitcastToAPInt() const {
3035
1.48M
  if (semantics == (const llvm::fltSemantics*)&semIEEEhalf)
3036
19.5k
    return convertHalfAPFloatToAPInt();
3037
1.46M
3038
1.46M
  if (semantics == (const llvm::fltSemantics*)&semIEEEsingle)
3039
974k
    return convertFloatAPFloatToAPInt();
3040
491k
3041
491k
  if (semantics == (const llvm::fltSemantics*)&semIEEEdouble)
3042
488k
    return convertDoubleAPFloatToAPInt();
3043
2.38k
3044
2.38k
  if (semantics == (const llvm::fltSemantics*)&semIEEEquad)
3045
739
    return convertQuadrupleAPFloatToAPInt();
3046
1.64k
3047
1.64k
  if (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy)
3048
81
    return convertPPCDoubleDoubleAPFloatToAPInt();
3049
1.56k
3050
1.56k
  assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended &&
3051
1.56k
         "unknown format!");
3052
1.56k
  return convertF80LongDoubleAPFloatToAPInt();
3053
1.56k
}
3054
3055
13.7k
float IEEEFloat::convertToFloat() const {
3056
13.7k
  assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle &&
3057
13.7k
         "Float semantics are not IEEEsingle");
3058
13.7k
  APInt api = bitcastToAPInt();
3059
13.7k
  return api.bitsToFloat();
3060
13.7k
}
3061
3062
30.0k
double IEEEFloat::convertToDouble() const {
3063
30.0k
  assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble &&
3064
30.0k
         "Float semantics are not IEEEdouble");
3065
30.0k
  APInt api = bitcastToAPInt();
3066
30.0k
  return api.bitsToDouble();
3067
30.0k
}
3068
3069
/// Integer bit is explicit in this format.  Intel hardware (387 and later)
3070
/// does not support these bit patterns:
3071
///  exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3072
///  exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3073
///  exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3074
///  exponent = 0, integer bit 1 ("pseudodenormal")
3075
/// At the moment, the first three are treated as NaNs, the last one as Normal.
3076
1.70k
void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
3077
1.70k
  assert(api.getBitWidth()==80);
3078
1.70k
  uint64_t i1 = api.getRawData()[0];
3079
1.70k
  uint64_t i2 = api.getRawData()[1];
3080
1.70k
  uint64_t myexponent = (i2 & 0x7fff);
3081
1.70k
  uint64_t mysignificand = i1;
3082
1.70k
  uint8_t myintegerbit = mysignificand >> 63;
3083
1.70k
3084
1.70k
  initialize(&semX87DoubleExtended);
3085
1.70k
  assert(partCount()==2);
3086
1.70k
3087
1.70k
  sign = static_cast<unsigned int>(i2>>15);
3088
1.70k
  if (myexponent == 0 && 
mysignificand == 0314
) {
3089
164
    // exponent, significand meaningless
3090
164
    category = fcZero;
3091
1.54k
  } else if (myexponent==0x7fff && 
mysignificand==0x8000000000000000ULL5
) {
3092
1
    // exponent, significand meaningless
3093
1
    category = fcInfinity;
3094
1.53k
  } else if ((myexponent == 0x7fff && 
mysignificand != 0x8000000000000000ULL4
) ||
3095
1.53k
             
(1.53k
myexponent != 0x7fff1.53k
&&
myexponent != 01.53k
&&
myintegerbit == 01.38k
)) {
3096
6
    // exponent meaningless
3097
6
    category = fcNaN;
3098
6
    significandParts()[0] = mysignificand;
3099
6
    significandParts()[1] = 0;
3100
1.53k
  } else {
3101
1.53k
    category = fcNormal;
3102
1.53k
    exponent = myexponent - 16383;
3103
1.53k
    significandParts()[0] = mysignificand;
3104
1.53k
    significandParts()[1] = 0;
3105
1.53k
    if (myexponent==0)          // denormal
3106
150
      exponent = -16382;
3107
1.53k
  }
3108
1.70k
}
3109
3110
25
void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) {
3111
25
  assert(api.getBitWidth()==128);
3112
25
  uint64_t i1 = api.getRawData()[0];
3113
25
  uint64_t i2 = api.getRawData()[1];
3114
25
  opStatus fs;
3115
25
  bool losesInfo;
3116
25
3117
25
  // Get the first double and convert to our format.
3118
25
  initFromDoubleAPInt(APInt(64, i1));
3119
25
  fs = convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
3120
25
  assert(fs == opOK && !losesInfo);
3121
25
  (void)fs;
3122
25
3123
25
  // Unless we have a special case, add in second double.
3124
25
  if (isFiniteNonZero()) {
3125
20
    IEEEFloat v(semIEEEdouble, APInt(64, i2));
3126
20
    fs = v.convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
3127
20
    assert(fs == opOK && !losesInfo);
3128
20
    (void)fs;
3129
20
3130
20
    add(v, rmNearestTiesToEven);
3131
20
  }
3132
25
}
3133
3134
561
void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
3135
561
  assert(api.getBitWidth()==128);
3136
561
  uint64_t i1 = api.getRawData()[0];
3137
561
  uint64_t i2 = api.getRawData()[1];
3138
561
  uint64_t myexponent = (i2 >> 48) & 0x7fff;
3139
561
  uint64_t mysignificand  = i1;
3140
561
  uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3141
561
3142
561
  initialize(&semIEEEquad);
3143
561
  assert(partCount()==2);
3144
561
3145
561
  sign = static_cast<unsigned int>(i2>>63);
3146
561
  if (myexponent==0 &&
3147
561
      
(201
mysignificand==0201
&&
mysignificand2==0200
)) {
3148
198
    // exponent, significand meaningless
3149
198
    category = fcZero;
3150
363
  } else if (myexponent==0x7fff &&
3151
363
             
(48
mysignificand==048
&&
mysignificand2==028
)) {
3152
24
    // exponent, significand meaningless
3153
24
    category = fcInfinity;
3154
339
  } else if (myexponent==0x7fff &&
3155
339
             
(24
mysignificand!=024
||
mysignificand2 !=04
)) {
3156
24
    // exponent meaningless
3157
24
    category = fcNaN;
3158
24
    significandParts()[0] = mysignificand;
3159
24
    significandParts()[1] = mysignificand2;
3160
315
  } else {
3161
315
    category = fcNormal;
3162
315
    exponent = myexponent - 16383;
3163
315
    significandParts()[0] = mysignificand;
3164
315
    significandParts()[1] = mysignificand2;
3165
315
    if (myexponent==0)          // denormal
3166
3
      exponent = -16382;
3167
312
    else
3168
312
      significandParts()[1] |= 0x1000000000000LL;  // integer bit
3169
315
  }
3170
561
}
3171
3172
6.96M
void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
3173
6.96M
  assert(api.getBitWidth()==64);
3174
6.96M
  uint64_t i = *api.getRawData();
3175
6.96M
  uint64_t myexponent = (i >> 52) & 0x7ff;
3176
6.96M
  uint64_t mysignificand = i & 0xfffffffffffffLL;
3177
6.96M
3178
6.96M
  initialize(&semIEEEdouble);
3179
6.96M
  assert(partCount()==1);
3180
6.96M
3181
6.96M
  sign = static_cast<unsigned int>(i>>63);
3182
6.96M
  if (myexponent==0 && 
mysignificand==05.89M
) {
3183
5.89M
    // exponent, significand meaningless
3184
5.89M
    category = fcZero;
3185
5.89M
  } else 
if (1.06M
myexponent==0x7ff1.06M
&&
mysignificand==010.2k
) {
3186
3.85k
    // exponent, significand meaningless
3187
3.85k
    category = fcInfinity;
3188
1.06M
  } else if (myexponent==0x7ff && 
mysignificand!=06.36k
) {
3189
6.36k
    // exponent meaningless
3190
6.36k
    category = fcNaN;
3191
6.36k
    *significandParts() = mysignificand;
3192
1.05M
  } else {
3193
1.05M
    category = fcNormal;
3194
1.05M
    exponent = myexponent - 1023;
3195
1.05M
    *significandParts() = mysignificand;
3196
1.05M
    if (myexponent==0)          // denormal
3197
1.63k
      exponent = -1022;
3198
1.05M
    else
3199
1.05M
      *significandParts() |= 0x10000000000000LL;  // integer bit
3200
1.05M
  }
3201
6.96M
}
3202
3203
708k
void IEEEFloat::initFromFloatAPInt(const APInt &api) {
3204
708k
  assert(api.getBitWidth()==32);
3205
708k
  uint32_t i = (uint32_t)*api.getRawData();
3206
708k
  uint32_t myexponent = (i >> 23) & 0xff;
3207
708k
  uint32_t mysignificand = i & 0x7fffff;
3208
708k
3209
708k
  initialize(&semIEEEsingle);
3210
708k
  assert(partCount()==1);
3211
708k
3212
708k
  sign = i >> 31;
3213
708k
  if (myexponent==0 && 
mysignificand==049.5k
) {
3214
48.2k
    // exponent, significand meaningless
3215
48.2k
    category = fcZero;
3216
660k
  } else if (myexponent==0xff && 
mysignificand==010.6k
) {
3217
3.22k
    // exponent, significand meaningless
3218
3.22k
    category = fcInfinity;
3219
656k
  } else if (myexponent==0xff && 
mysignificand!=07.40k
) {
3220
7.40k
    // sign, exponent, significand meaningless
3221
7.40k
    category = fcNaN;
3222
7.40k
    *significandParts() = mysignificand;
3223
649k
  } else {
3224
649k
    category = fcNormal;
3225
649k
    exponent = myexponent - 127;  //bias
3226
649k
    *significandParts() = mysignificand;
3227
649k
    if (myexponent==0)    // denormal
3228
1.30k
      exponent = -126;
3229
648k
    else
3230
648k
      *significandParts() |= 0x800000; // integer bit
3231
649k
  }
3232
708k
}
3233
3234
6.48k
void IEEEFloat::initFromHalfAPInt(const APInt &api) {
3235
6.48k
  assert(api.getBitWidth()==16);
3236
6.48k
  uint32_t i = (uint32_t)*api.getRawData();
3237
6.48k
  uint32_t myexponent = (i >> 10) & 0x1f;
3238
6.48k
  uint32_t mysignificand = i & 0x3ff;
3239
6.48k
3240
6.48k
  initialize(&semIEEEhalf);
3241
6.48k
  assert(partCount()==1);
3242
6.48k
3243
6.48k
  sign = i >> 15;
3244
6.48k
  if (myexponent==0 && 
mysignificand==02.09k
) {
3245
1.09k
    // exponent, significand meaningless
3246
1.09k
    category = fcZero;
3247
5.39k
  } else if (myexponent==0x1f && 
mysignificand==0183
) {
3248
70
    // exponent, significand meaningless
3249
70
    category = fcInfinity;
3250
5.32k
  } else if (myexponent==0x1f && 
mysignificand!=0113
) {
3251
113
    // sign, exponent, significand meaningless
3252
113
    category = fcNaN;
3253
113
    *significandParts() = mysignificand;
3254
5.20k
  } else {
3255
5.20k
    category = fcNormal;
3256
5.20k
    exponent = myexponent - 15;  //bias
3257
5.20k
    *significandParts() = mysignificand;
3258
5.20k
    if (myexponent==0)    // denormal
3259
995
      exponent = -14;
3260
4.21k
    else
3261
4.21k
      *significandParts() |= 0x400; // integer bit
3262
5.20k
  }
3263
6.48k
}
3264
3265
/// Treat api as containing the bits of a floating point number.  Currently
3266
/// we infer the floating point type from the size of the APInt.  The
3267
/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3268
/// when the size is anything else).
3269
7.68M
void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
3270
7.68M
  if (Sem == &semIEEEhalf)
3271
6.48k
    return initFromHalfAPInt(api);
3272
7.67M
  if (Sem == &semIEEEsingle)
3273
708k
    return initFromFloatAPInt(api);
3274
6.96M
  if (Sem == &semIEEEdouble)
3275
6.96M
    return initFromDoubleAPInt(api);
3276
2.29k
  if (Sem == &semX87DoubleExtended)
3277
1.70k
    return initFromF80LongDoubleAPInt(api);
3278
586
  if (Sem == &semIEEEquad)
3279
561
    return initFromQuadrupleAPInt(api);
3280
25
  if (Sem == &semPPCDoubleDoubleLegacy)
3281
25
    return initFromPPCDoubleDoubleAPInt(api);
3282
0
3283
0
  llvm_unreachable(nullptr);
3284
0
}
3285
3286
/// Make this number the largest magnitude normal number in the given
3287
/// semantics.
3288
287
void IEEEFloat::makeLargest(bool Negative) {
3289
287
  // We want (in interchange format):
3290
287
  //   sign = {Negative}
3291
287
  //   exponent = 1..10
3292
287
  //   significand = 1..1
3293
287
  category = fcNormal;
3294
287
  sign = Negative;
3295
287
  exponent = semantics->maxExponent;
3296
287
3297
287
  // Use memset to set all but the highest integerPart to all ones.
3298
287
  integerPart *significand = significandParts();
3299
287
  unsigned PartCount = partCount();
3300
287
  memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
3301
287
3302
287
  // Set the high integerPart especially setting all unused top bits for
3303
287
  // internal consistency.
3304
287
  const unsigned NumUnusedHighBits =
3305
287
    PartCount*integerPartWidth - semantics->precision;
3306
287
  significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3307
287
                                   ? 
(~integerPart(0) >> NumUnusedHighBits)286
3308
287
                                   : 
01
;
3309
287
}
3310
3311
/// Make this number the smallest magnitude denormal number in the given
3312
/// semantics.
3313
50
void IEEEFloat::makeSmallest(bool Negative) {
3314
50
  // We want (in interchange format):
3315
50
  //   sign = {Negative}
3316
50
  //   exponent = 0..0
3317
50
  //   significand = 0..01
3318
50
  category = fcNormal;
3319
50
  sign = Negative;
3320
50
  exponent = semantics->minExponent;
3321
50
  APInt::tcSet(significandParts(), 1, partCount());
3322
50
}
3323
3324
304
void IEEEFloat::makeSmallestNormalized(bool Negative) {
3325
304
  // We want (in interchange format):
3326
304
  //   sign = {Negative}
3327
304
  //   exponent = 0..0
3328
304
  //   significand = 10..0
3329
304
3330
304
  category = fcNormal;
3331
304
  zeroSignificand();
3332
304
  sign = Negative;
3333
304
  exponent = semantics->minExponent;
3334
304
  significandParts()[partCountForBits(semantics->precision) - 1] |=
3335
304
      (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth));
3336
304
}
3337
3338
1.17M
IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
3339
1.17M
  initFromAPInt(&Sem, API);
3340
1.17M
}
3341
3342
26.5k
IEEEFloat::IEEEFloat(float f) {
3343
26.5k
  initFromAPInt(&semIEEEsingle, APInt::floatToBits(f));
3344
26.5k
}
3345
3346
6.48M
IEEEFloat::IEEEFloat(double d) {
3347
6.48M
  initFromAPInt(&semIEEEdouble, APInt::doubleToBits(d));
3348
6.48M
}
3349
3350
namespace {
3351
15.9k
  void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3352
15.9k
    Buffer.append(Str.begin(), Str.end());
3353
15.9k
  }
3354
3355
  /// Removes data from the given significand until it is no more
3356
  /// precise than is required for the desired precision.
3357
  void AdjustToPrecision(APInt &significand,
3358
30.8k
                         int &exp, unsigned FormatPrecision) {
3359
30.8k
    unsigned bits = significand.getActiveBits();
3360
30.8k
3361
30.8k
    // 196/59 is a very slight overestimate of lg_2(10).
3362
30.8k
    unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3363
30.8k
3364
30.8k
    if (bits <= bitsRequired) 
return24.7k
;
3365
6.06k
3366
6.06k
    unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3367
6.06k
    if (!tensRemovable) 
return254
;
3368
5.80k
3369
5.80k
    exp += tensRemovable;
3370
5.80k
3371
5.80k
    APInt divisor(significand.getBitWidth(), 1);
3372
5.80k
    APInt powten(significand.getBitWidth(), 10);
3373
29.1k
    while (true) {
3374
29.1k
      if (tensRemovable & 1)
3375
16.8k
        divisor *= powten;
3376
29.1k
      tensRemovable >>= 1;
3377
29.1k
      if (!tensRemovable) 
break5.80k
;
3378
23.3k
      powten *= powten;
3379
23.3k
    }
3380
5.80k
3381
5.80k
    significand = significand.udiv(divisor);
3382
5.80k
3383
5.80k
    // Truncate the significand down to its active bit count.
3384
5.80k
    significand = significand.trunc(significand.getActiveBits());
3385
5.80k
  }
3386
3387
3388
  void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3389
30.8k
                         int &exp, unsigned FormatPrecision) {
3390
30.8k
    unsigned N = buffer.size();
3391
30.8k
    if (N <= FormatPrecision) 
return26.3k
;
3392
4.51k
3393
4.51k
    // The most significant figures are the last ones in the buffer.
3394
4.51k
    unsigned FirstSignificant = N - FormatPrecision;
3395
4.51k
3396
4.51k
    // Round.
3397
4.51k
    // FIXME: this probably shouldn't use 'round half up'.
3398
4.51k
3399
4.51k
    // Rounding down is just a truncation, except we also want to drop
3400
4.51k
    // trailing zeros from the new result.
3401
4.51k
    if (buffer[FirstSignificant - 1] < '5') {
3402
3.15k
      while (FirstSignificant < N && buffer[FirstSignificant] == '0')
3403
938
        FirstSignificant++;
3404
2.22k
3405
2.22k
      exp += FirstSignificant;
3406
2.22k
      buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3407
2.22k
      return;
3408
2.22k
    }
3409
2.29k
3410
2.29k
    // Rounding up requires a decimal add-with-carry.  If we continue
3411
2.29k
    // the carry, the newly-introduced zeros will just be truncated.
3412
4.72k
    
for (unsigned I = FirstSignificant; 2.29k
I != N;
++I2.42k
) {
3413
4.72k
      if (buffer[I] == '9') {
3414
2.42k
        FirstSignificant++;
3415
2.42k
      } else {
3416
2.29k
        buffer[I]++;
3417
2.29k
        break;
3418
2.29k
      }
3419
4.72k
    }
3420
2.29k
3421
2.29k
    // If we carried through, we have exactly one digit of precision.
3422
2.29k
    if (FirstSignificant == N) {
3423
0
      exp += FirstSignificant;
3424
0
      buffer.clear();
3425
0
      buffer.push_back('1');
3426
0
      return;
3427
0
    }
3428
2.29k
3429
2.29k
    exp += FirstSignificant;
3430
2.29k
    buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3431
2.29k
  }
3432
}
3433
3434
void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
3435
41.0k
                         unsigned FormatMaxPadding, bool TruncateZero) const {
3436
41.0k
  switch (category) {
3437
41.0k
  case fcInfinity:
3438
166
    if (isNegative())
3439
61
      return append(Str, "-Inf");
3440
105
    else
3441
105
      return append(Str, "+Inf");
3442
0
3443
981
  case fcNaN: return append(Str, "NaN");
3444
0
3445
9.11k
  case fcZero:
3446
9.11k
    if (isNegative())
3447
5.16k
      Str.push_back('-');
3448
9.11k
3449
9.11k
    if (!FormatMaxPadding) {
3450
7.54k
      if (TruncateZero)
3451
312
        append(Str, "0.0E+0");
3452
7.23k
      else {
3453
7.23k
        append(Str, "0.0");
3454
7.23k
        if (FormatPrecision > 1)
3455
7.23k
          Str.append(FormatPrecision - 1, '0');
3456
7.23k
        append(Str, "e+00");
3457
7.23k
      }
3458
7.54k
    } else
3459
1.56k
      Str.push_back('0');
3460
9.11k
    return;
3461
0
3462
30.8k
  case fcNormal:
3463
30.8k
    break;
3464
30.8k
  }
3465
30.8k
3466
30.8k
  if (isNegative())
3467
2.77k
    Str.push_back('-');
3468
30.8k
3469
30.8k
  // Decompose the number into an APInt and an exponent.
3470
30.8k
  int exp = exponent - ((int) semantics->precision - 1);
3471
30.8k
  APInt significand(semantics->precision,
3472
30.8k
                    makeArrayRef(significandParts(),
3473
30.8k
                                 partCountForBits(semantics->precision)));
3474
30.8k
3475
30.8k
  // Set FormatPrecision if zero.  We want to do this before we
3476
30.8k
  // truncate trailing zeros, as those are part of the precision.
3477
30.8k
  if (!FormatPrecision) {
3478
18.0k
    // We use enough digits so the number can be round-tripped back to an
3479
18.0k
    // APFloat. The formula comes from "How to Print Floating-Point Numbers
3480
18.0k
    // Accurately" by Steele and White.
3481
18.0k
    // FIXME: Using a formula based purely on the precision is conservative;
3482
18.0k
    // we can print fewer digits depending on the actual value being printed.
3483
18.0k
3484
18.0k
    // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3485
18.0k
    FormatPrecision = 2 + semantics->precision * 59 / 196;
3486
18.0k
  }
3487
30.8k
3488
30.8k
  // Ignore trailing binary zeros.
3489
30.8k
  int trailingZeros = significand.countTrailingZeros();
3490
30.8k
  exp += trailingZeros;
3491
30.8k
  significand.lshrInPlace(trailingZeros);
3492
30.8k
3493
30.8k
  // Change the exponent from 2^e to 10^e.
3494
30.8k
  if (exp == 0) {
3495
13.9k
    // Nothing to do.
3496
16.9k
  } else if (exp > 0) {
3497
9.08k
    // Just shift left.
3498
9.08k
    significand = significand.zext(semantics->precision + exp);
3499
9.08k
    significand <<= exp;
3500
9.08k
    exp = 0;
3501
9.08k
  } else { /* exp < 0 */
3502
7.82k
    int texp = -exp;
3503
7.82k
3504
7.82k
    // We transform this using the identity:
3505
7.82k
    //   (N)(2^-e) == (N)(5^e)(10^-e)
3506
7.82k
    // This means we have to multiply N (the significand) by 5^e.
3507
7.82k
    // To avoid overflow, we have to operate on numbers large
3508
7.82k
    // enough to store N * 5^e:
3509
7.82k
    //   log2(N * 5^e) == log2(N) + e * log2(5)
3510
7.82k
    //                 <= semantics->precision + e * 137 / 59
3511
7.82k
    //   (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
3512
7.82k
3513
7.82k
    unsigned precision = semantics->precision + (137 * texp + 136) / 59;
3514
7.82k
3515
7.82k
    // Multiply significand by 5^e.
3516
7.82k
    //   N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
3517
7.82k
    significand = significand.zext(precision);
3518
7.82k
    APInt five_to_the_i(precision, 5);
3519
30.5k
    while (true) {
3520
30.5k
      if (texp & 1) 
significand *= five_to_the_i19.3k
;
3521
30.5k
3522
30.5k
      texp >>= 1;
3523
30.5k
      if (!texp) 
break7.82k
;
3524
22.7k
      five_to_the_i *= five_to_the_i;
3525
22.7k
    }
3526
7.82k
  }
3527
30.8k
3528
30.8k
  AdjustToPrecision(significand, exp, FormatPrecision);
3529
30.8k
3530
30.8k
  SmallVector<char, 256> buffer;
3531
30.8k
3532
30.8k
  // Fill the buffer.
3533
30.8k
  unsigned precision = significand.getBitWidth();
3534
30.8k
  APInt ten(precision, 10);
3535
30.8k
  APInt digit(precision, 0);
3536
30.8k
3537
30.8k
  bool inTrail = true;
3538
141k
  while (significand != 0) {
3539
110k
    // digit <- significand % 10
3540
110k
    // significand <- significand / 10
3541
110k
    APInt::udivrem(significand, ten, significand, digit);
3542
110k
3543
110k
    unsigned d = digit.getZExtValue();
3544
110k
3545
110k
    // Drop trailing zeros.
3546
110k
    if (inTrail && 
!d34.3k
)
exp++3.48k
;
3547
107k
    else {
3548
107k
      buffer.push_back((char) ('0' + d));
3549
107k
      inTrail = false;
3550
107k
    }
3551
110k
  }
3552
30.8k
3553
30.8k
  assert(!buffer.empty() && "no characters in buffer!");
3554
30.8k
3555
30.8k
  // Drop down to FormatPrecision.
3556
30.8k
  // TODO: don't do more precise calculations above than are required.
3557
30.8k
  AdjustToPrecision(buffer, exp, FormatPrecision);
3558
30.8k
3559
30.8k
  unsigned NDigits = buffer.size();
3560
30.8k
3561
30.8k
  // Check whether we should use scientific notation.
3562
30.8k
  bool FormatScientific;
3563
30.8k
  if (!FormatMaxPadding)
3564
16.6k
    FormatScientific = true;
3565
14.1k
  else {
3566
14.1k
    if (exp >= 0) {
3567
10.0k
      // 765e3 --> 765000
3568
10.0k
      //              ^^^
3569
10.0k
      // But we shouldn't make the number look more precise than it is.
3570
10.0k
      FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3571
10.0k
                          
NDigits + (unsigned) exp > FormatPrecision9.51k
);
3572
10.0k
    } else {
3573
4.10k
      // Power of the most significant digit.
3574
4.10k
      int MSD = exp + (int) (NDigits - 1);
3575
4.10k
      if (MSD >= 0) {
3576
2.92k
        // 765e-2 == 7.65
3577
2.92k
        FormatScientific = false;
3578
2.92k
      } else {
3579
1.18k
        // 765e-5 == 0.00765
3580
1.18k
        //           ^ ^^
3581
1.18k
        FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
3582
1.18k
      }
3583
4.10k
    }
3584
14.1k
  }
3585
30.8k
3586
30.8k
  // Scientific formatting is pretty straightforward.
3587
30.8k
  if (FormatScientific) {
3588
18.2k
    exp += (NDigits - 1);
3589
18.2k
3590
18.2k
    Str.push_back(buffer[NDigits-1]);
3591
18.2k
    Str.push_back('.');
3592
18.2k
    if (NDigits == 1 && 
TruncateZero13.3k
)
3593
2.84k
      Str.push_back('0');
3594
15.3k
    else
3595
47.5k
      
for (unsigned I = 1; 15.3k
I != NDigits;
++I32.2k
)
3596
32.2k
        Str.push_back(buffer[NDigits-1-I]);
3597
18.2k
    // Fill with zeros up to FormatPrecision.
3598
18.2k
    if (!TruncateZero && 
FormatPrecision > NDigits - 112.6k
)
3599
12.6k
      Str.append(FormatPrecision - NDigits + 1, '0');
3600
18.2k
    // For !TruncateZero we use lower 'e'.
3601
18.2k
    Str.push_back(TruncateZero ? 
'E'5.55k
:
'e'12.6k
);
3602
18.2k
3603
18.2k
    Str.push_back(exp >= 0 ? 
'+'15.0k
:
'-'3.18k
);
3604
18.2k
    if (exp < 0) 
exp = -exp3.18k
;
3605
18.2k
    SmallVector<char, 6> expbuf;
3606
20.6k
    do {
3607
20.6k
      expbuf.push_back((char) ('0' + (exp % 10)));
3608
20.6k
      exp /= 10;
3609
20.6k
    } while (exp);
3610
18.2k
    // Exponent always at least two digits if we do not truncate zeros.
3611
18.2k
    if (!TruncateZero && 
expbuf.size() < 212.6k
)
3612
12.5k
      expbuf.push_back('0');
3613
51.4k
    for (unsigned I = 0, E = expbuf.size(); I != E; 
++I33.1k
)
3614
33.1k
      Str.push_back(expbuf[E-1-I]);
3615
18.2k
    return;
3616
18.2k
  }
3617
12.5k
3618
12.5k
  // Non-scientific, positive exponents.
3619
12.5k
  if (exp >= 0) {
3620
24.1k
    for (unsigned I = 0; I != NDigits; 
++I14.9k
)
3621
14.9k
      Str.push_back(buffer[NDigits-1-I]);
3622
9.69k
    for (unsigned I = 0; I != (unsigned) exp; 
++I579
)
3623
579
      Str.push_back('0');
3624
9.11k
    return;
3625
9.11k
  }
3626
3.48k
3627
3.48k
  // Non-scientific, negative exponents.
3628
3.48k
3629
3.48k
  // The number of digits to the left of the decimal point.
3630
3.48k
  int NWholeDigits = exp + (int) NDigits;
3631
3.48k
3632
3.48k
  unsigned I = 0;
3633
3.48k
  if (NWholeDigits > 0) {
3634
8.29k
    for (; I != (unsigned) NWholeDigits; 
++I5.37k
)
3635
5.37k
      Str.push_back(buffer[NDigits-I-1]);
3636
2.92k
    Str.push_back('.');
3637
2.92k
  } else {
3638
560
    unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3639
560
3640
560
    Str.push_back('0');
3641
560
    Str.push_back('.');
3642
723
    for (unsigned Z = 1; Z != NZeros; 
++Z163
)
3643
163
      Str.push_back('0');
3644
560
  }
3645
3.48k
3646
32.1k
  for (; I != NDigits; 
++I28.6k
)
3647
28.6k
    Str.push_back(buffer[NDigits-I-1]);
3648
3.48k
}
3649
3650
63.5k
bool IEEEFloat::getExactInverse(APFloat *inv) const {
3651
63.5k
  // Special floats and denormals have no exact inverse.
3652
63.5k
  if (!isFiniteNonZero())
3653
47
    return false;
3654
63.5k
3655
63.5k
  // Check that the number is a power of two by making sure that only the
3656
63.5k
  // integer bit is set in the significand.
3657
63.5k
  if (significandLSB() != semantics->precision - 1)
3658
63.1k
    return false;
3659
392
3660
392
  // Get the inverse.
3661
392
  IEEEFloat reciprocal(*semantics, 1ULL);
3662
392
  if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3663
0
    return false;
3664
392
3665
392
  // Avoid multiplication with a denormal, it is not safe on all platforms and
3666
392
  // may be slower than a normal division.
3667
392
  if (reciprocal.isDenormal())
3668
2
    return false;
3669
390
3670
390
  assert(reciprocal.isFiniteNonZero() &&
3671
390
         reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3672
390
3673
390
  if (inv)
3674
6
    *inv = APFloat(reciprocal, *semantics);
3675
390
3676
390
  return true;
3677
390
}
3678
3679
12.5k
bool IEEEFloat::isSignaling() const {
3680
12.5k
  if (!isNaN())
3681
11.9k
    return false;
3682
542
3683
542
  // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3684
542
  // first bit of the trailing significand being 0.
3685
542
  return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3686
542
}
3687
3688
/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3689
///
3690
/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3691
/// appropriate sign switching before/after the computation.
3692
47
IEEEFloat::opStatus IEEEFloat::next(bool nextDown) {
3693
47
  // If we are performing nextDown, swap sign so we have -x.
3694
47
  if (nextDown)
3695
22
    changeSign();
3696
47
3697
47
  // Compute nextUp(x)
3698
47
  opStatus result = opOK;
3699
47
3700
47
  // Handle each float category separately.
3701
47
  switch (category) {
3702
47
  case fcInfinity:
3703
4
    // nextUp(+inf) = +inf
3704
4
    if (!isNegative())
3705
2
      break;
3706
2
    // nextUp(-inf) = -getLargest()
3707
2
    makeLargest(true);
3708
2
    break;
3709
4
  case fcNaN:
3710
4
    // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3711
4
    // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3712
4
    //                     change the payload.
3713
4
    if (isSignaling()) {
3714
2
      result = opInvalidOp;
3715
2
      // For consistency, propagate the sign of the sNaN to the qNaN.
3716
2
      makeNaN(false, isNegative(), nullptr);
3717
2
    }
3718
4
    break;
3719
4
  case fcZero:
3720
4
    // nextUp(pm 0) = +getSmallest()
3721
4
    makeSmallest(false);
3722
4
    break;
3723
35
  case fcNormal:
3724
35
    // nextUp(-getSmallest()) = -0
3725
35
    if (isSmallest() && 
isNegative()4
) {
3726
2
      APInt::tcSet(significandParts(), 0, partCount());
3727
2
      category = fcZero;
3728
2
      exponent = 0;
3729
2
      break;
3730
2
    }
3731
33
3732
33
    // nextUp(getLargest()) == INFINITY
3733
33
    if (isLargest() && 
!isNegative()4
) {
3734
2
      APInt::tcSet(significandParts(), 0, partCount());
3735
2
      category = fcInfinity;
3736
2
      exponent = semantics->maxExponent + 1;
3737
2
      break;
3738
2
    }
3739
31
3740
31
    // nextUp(normal) == normal + inc.
3741
31
    if (isNegative()) {
3742
14
      // If we are negative, we need to decrement the significand.
3743
14
3744
14
      // We only cross a binade boundary that requires adjusting the exponent
3745
14
      // if:
3746
14
      //   1. exponent != semantics->minExponent. This implies we are not in the
3747
14
      //   smallest binade or are dealing with denormals.
3748
14
      //   2. Our significand excluding the integral bit is all zeros.
3749
14
      bool WillCrossBinadeBoundary =
3750
14
        exponent != semantics->minExponent && 
isSignificandAllZeros()8
;
3751
14
3752
14
      // Decrement the significand.
3753
14
      //
3754
14
      // We always do this since:
3755
14
      //   1. If we are dealing with a non-binade decrement, by definition we
3756
14
      //   just decrement the significand.
3757
14
      //   2. If we are dealing with a normal -> normal binade decrement, since
3758
14
      //   we have an explicit integral bit the fact that all bits but the
3759
14
      //   integral bit are zero implies that subtracting one will yield a
3760
14
      //   significand with 0 integral bit and 1 in all other spots. Thus we
3761
14
      //   must just adjust the exponent and set the integral bit to 1.
3762
14
      //   3. If we are dealing with a normal -> denormal binade decrement,
3763
14
      //   since we set the integral bit to 0 when we represent denormals, we
3764
14
      //   just decrement the significand.
3765
14
      integerPart *Parts = significandParts();
3766
14
      APInt::tcDecrement(Parts, partCount());
3767
14
3768
14
      if (WillCrossBinadeBoundary) {
3769
4
        // Our result is a normal number. Do the following:
3770
4
        // 1. Set the integral bit to 1.
3771
4
        // 2. Decrement the exponent.
3772
4
        APInt::tcSetBit(Parts, semantics->precision - 1);
3773
4
        exponent--;
3774
4
      }
3775
17
    } else {
3776
17
      // If we are positive, we need to increment the significand.
3777
17
3778
17
      // We only cross a binade boundary that requires adjusting the exponent if
3779
17
      // the input is not a denormal and all of said input's significand bits
3780
17
      // are set. If all of said conditions are true: clear the significand, set
3781
17
      // the integral bit to 1, and increment the exponent. If we have a
3782
17
      // denormal always increment since moving denormals and the numbers in the
3783
17
      // smallest normal binade have the same exponent in our representation.
3784
17
      bool WillCrossBinadeBoundary = !isDenormal() && 
isSignificandAllOnes()11
;
3785
17
3786
17
      if (WillCrossBinadeBoundary) {
3787
4
        integerPart *Parts = significandParts();
3788
4
        APInt::tcSet(Parts, 0, partCount());
3789
4
        APInt::tcSetBit(Parts, semantics->precision - 1);
3790
4
        assert(exponent != semantics->maxExponent &&
3791
4
               "We can not increment an exponent beyond the maxExponent allowed"
3792
4
               " by the given floating point semantics.");
3793
4
        exponent++;
3794
13
      } else {
3795
13
        incrementSignificand();
3796
13
      }
3797
17
    }
3798
31
    break;
3799
47
  }
3800
47
3801
47
  // If we are performing nextDown, swap sign so we have -nextUp(-x)
3802
47
  if (nextDown)
3803
22
    changeSign();
3804
47
3805
47
  return result;
3806
47
}
3807
3808
19.5k
void IEEEFloat::makeInf(bool Negative) {
3809
19.5k
  category = fcInfinity;
3810
19.5k
  sign = Negative;
3811
19.5k
  exponent = semantics->maxExponent + 1;
3812
19.5k
  APInt::tcSet(significandParts(), 0, partCount());
3813
19.5k
}
3814
3815
364k
void IEEEFloat::makeZero(bool Negative) {
3816
364k
  category = fcZero;
3817
364k
  sign = Negative;
3818
364k
  exponent = semantics->minExponent-1;
3819
364k
  APInt::tcSet(significandParts(), 0, partCount());
3820
364k
}
3821
3822
43
void IEEEFloat::makeQuiet() {
3823
43
  assert(isNaN());
3824
43
  APInt::tcSetBit(significandParts(), semantics->precision - 2);
3825
43
}
3826
3827
329
int ilogb(const IEEEFloat &Arg) {
3828
329
  if (Arg.isNaN())
3829
10
    return IEEEFloat::IEK_NaN;
3830
319
  if (Arg.isZero())
3831
65
    return IEEEFloat::IEK_Zero;
3832
254
  if (Arg.isInfinity())
3833
15
    return IEEEFloat::IEK_Inf;
3834
239
  if (!Arg.isDenormal())
3835
222
    return Arg.exponent;
3836
17
3837
17
  IEEEFloat Normalized(Arg);
3838
17
  int SignificandBits = Arg.getSemantics().precision - 1;
3839
17
3840
17
  Normalized.exponent += SignificandBits;
3841
17
  Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero);
3842
17
  return Normalized.exponent - SignificandBits;
3843
17
}
3844
3845
313
IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) {
3846
313
  auto MaxExp = X.getSemantics().maxExponent;
3847
313
  auto MinExp = X.getSemantics().minExponent;
3848
313
3849
313
  // If Exp is wildly out-of-scale, simply adding it to X.exponent will
3850
313
  // overflow; clamp it to a safe range before adding, but ensure that the range
3851
313
  // is large enough that the clamp does not change the result. The range we
3852
313
  // need to support is the difference between the largest possible exponent and
3853
313
  // the normalized exponent of half the smallest denormal.
3854
313
3855
313
  int SignificandBits = X.getSemantics().precision - 1;
3856
313
  int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
3857
313
3858
313
  // Clamp to one past the range ends to let normalize handle overlflow.
3859
313
  X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement);
3860
313
  X.normalize(RoundingMode, lfExactlyZero);
3861
313
  if (X.isNaN())
3862
35
    X.makeQuiet();
3863
313
  return X;
3864
313
}
3865
3866
59
IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) {
3867
59
  Exp = ilogb(Val);
3868
59
3869
59
  // Quiet signalling nans.
3870
59
  if (Exp == IEEEFloat::IEK_NaN) {
3871
8
    IEEEFloat Quiet(Val);
3872
8
    Quiet.makeQuiet();
3873
8
    return Quiet;
3874
8
  }
3875
51
3876
51
  if (Exp == IEEEFloat::IEK_Inf)
3877
10
    return Val;
3878
41
3879
41
  // 1 is added because frexp is defined to return a normalized fraction in
3880
41
  // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
3881
41
  Exp = Exp == IEEEFloat::IEK_Zero ? 
010
:
Exp + 131
;
3882
41
  return scalbn(Val, -Exp, RM);
3883
41
}
3884
3885
DoubleAPFloat::DoubleAPFloat(const fltSemantics &S)
3886
    : Semantics(&S),
3887
46
      Floats(new APFloat[2]{APFloat(semIEEEdouble), APFloat(semIEEEdouble)}) {
3888
46
  assert(Semantics == &semPPCDoubleDouble);
3889
46
}
3890
3891
DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag)
3892
    : Semantics(&S),
3893
      Floats(new APFloat[2]{APFloat(semIEEEdouble, uninitialized),
3894
34
                            APFloat(semIEEEdouble, uninitialized)}) {
3895
34
  assert(Semantics == &semPPCDoubleDouble);
3896
34
}
3897
3898
DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I)
3899
    : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble, I),
3900
4
                                           APFloat(semIEEEdouble)}) {
3901
4
  assert(Semantics == &semPPCDoubleDouble);
3902
4
}
3903
3904
DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I)
3905
    : Semantics(&S),
3906
      Floats(new APFloat[2]{
3907
          APFloat(semIEEEdouble, APInt(64, I.getRawData()[0])),
3908
372
          APFloat(semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
3909
372
  assert(Semantics == &semPPCDoubleDouble);
3910
372
}
3911
3912
DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First,
3913
                             APFloat &&Second)
3914
    : Semantics(&S),
3915
7
      Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
3916
7
  assert(Semantics == &semPPCDoubleDouble);
3917
7
  assert(&Floats[0].getSemantics() == &semIEEEdouble);
3918
7
  assert(&Floats[1].getSemantics() == &semIEEEdouble);
3919
7
}
3920
3921
DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS)
3922
    : Semantics(RHS.Semantics),
3923
      Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
3924
                                         APFloat(RHS.Floats[1])}
3925
403
                        : nullptr) {
3926
403
  assert(Semantics == &semPPCDoubleDouble);
3927
403
}
3928
3929
DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS)
3930
252
    : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) {
3931
252
  RHS.Semantics = &semBogus;
3932
252
  assert(Semantics == &semPPCDoubleDouble);
3933
252
}
3934
3935
28
DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) {
3936
28
  if (Semantics == RHS.Semantics && RHS.Floats) {
3937
28
    Floats[0] = RHS.Floats[0];
3938
28
    Floats[1] = RHS.Floats[1];
3939
28
  } else 
if (0
this != &RHS0
) {
3940
0
    this->~DoubleAPFloat();
3941
0
    new (this) DoubleAPFloat(RHS);
3942
0
  }
3943
28
  return *this;
3944
28
}
3945
3946
// Implement addition, subtraction, multiplication and division based on:
3947
// "Software for Doubled-Precision Floating-Point Computations",
3948
// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
3949
APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
3950
                                         const APFloat &c, const APFloat &cc,
3951
24
                                         roundingMode RM) {
3952
24
  int Status = opOK;
3953
24
  APFloat z = a;
3954
24
  Status |= z.add(c, RM);
3955
24
  if (!z.isFinite()) {
3956
6
    if (!z.isInfinity()) {
3957
0
      Floats[0] = std::move(z);
3958
0
      Floats[1].makeZero(/* Neg = */ false);
3959
0
      return (opStatus)Status;
3960
0
    }
3961
6
    Status = opOK;
3962
6
    auto AComparedToC = a.compareAbsoluteValue(c);
3963
6
    z = cc;
3964
6
    Status |= z.add(aa, RM);
3965
6
    if (AComparedToC == APFloat::cmpGreaterThan) {
3966
2
      // z = cc + aa + c + a;
3967
2
      Status |= z.add(c, RM);
3968
2
      Status |= z.add(a, RM);
3969
4
    } else {
3970
4
      // z = cc + aa + a + c;
3971
4
      Status |= z.add(a, RM);
3972
4
      Status |= z.add(c, RM);
3973
4
    }
3974
6
    if (!z.isFinite()) {
3975
2
      Floats[0] = std::move(z);
3976
2
      Floats[1].makeZero(/* Neg = */ false);
3977
2
      return (opStatus)Status;
3978
2
    }
3979
4
    Floats[0] = z;
3980
4
    APFloat zz = aa;
3981
4
    Status |= zz.add(cc, RM);
3982
4
    if (AComparedToC == APFloat::cmpGreaterThan) {
3983
2
      // Floats[1] = a - z + c + zz;
3984
2
      Floats[1] = a;
3985
2
      Status |= Floats[1].subtract(z, RM);
3986
2
      Status |= Floats[1].add(c, RM);
3987
2
      Status |= Floats[1].add(zz, RM);
3988
2
    } else {
3989
2
      // Floats[1] = c - z + a + zz;
3990
2
      Floats[1] = c;
3991
2
      Status |= Floats[1].subtract(z, RM);
3992
2
      Status |= Floats[1].add(a, RM);
3993
2
      Status |= Floats[1].add(zz, RM);
3994
2
    }
3995
18
  } else {
3996
18
    // q = a - z;
3997
18
    APFloat q = a;
3998
18
    Status |= q.subtract(z, RM);
3999
18
4000
18
    // zz = q + c + (a - (q + z)) + aa + cc;
4001
18
    // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
4002
18
    auto zz = q;
4003
18
    Status |= zz.add(c, RM);
4004
18
    Status |= q.add(z, RM);
4005
18
    Status |= q.subtract(a, RM);
4006
18
    q.changeSign();
4007
18
    Status |= zz.add(q, RM);
4008
18
    Status |= zz.add(aa, RM);
4009
18
    Status |= zz.add(cc, RM);
4010
18
    if (zz.isZero() && 
!zz.isNegative()4
) {
4011
4
      Floats[0] = std::move(z);
4012
4
      Floats[1].makeZero(/* Neg = */ false);
4013
4
      return opOK;
4014
4
    }
4015
14
    Floats[0] = z;
4016
14
    Status |= Floats[0].add(zz, RM);
4017
14
    if (!Floats[0].isFinite()) {
4018
2
      Floats[1].makeZero(/* Neg = */ false);
4019
2
      return (opStatus)Status;
4020
2
    }
4021
12
    Floats[1] = std::move(z);
4022
12
    Status |= Floats[1].subtract(Floats[0], RM);
4023
12
    Status |= Floats[1].add(zz, RM);
4024
12
  }
4025
24
  
return (opStatus)Status16
;
4026
24
}
4027
4028
APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
4029
                                                const DoubleAPFloat &RHS,
4030
                                                DoubleAPFloat &Out,
4031
31
                                                roundingMode RM) {
4032
31
  if (LHS.getCategory() == fcNaN) {
4033
1
    Out = LHS;
4034
1
    return opOK;
4035
1
  }
4036
30
  if (RHS.getCategory() == fcNaN) {
4037
1
    Out = RHS;
4038
1
    return opOK;
4039
1
  }
4040
29
  if (LHS.getCategory() == fcZero) {
4041
1
    Out = RHS;
4042
1
    return opOK;
4043
1
  }
4044
28
  if (RHS.getCategory() == fcZero) {
4045
4
    Out = LHS;
4046
4
    return opOK;
4047
4
  }
4048
24
  if (LHS.getCategory() == fcInfinity && 
RHS.getCategory() == fcInfinity0
&&
4049
24
      
LHS.isNegative() != RHS.isNegative()0
) {
4050
0
    Out.makeNaN(false, Out.isNegative(), nullptr);
4051
0
    return opInvalidOp;
4052
0
  }
4053
24
  if (LHS.getCategory() == fcInfinity) {
4054
0
    Out = LHS;
4055
0
    return opOK;
4056
0
  }
4057
24
  if (RHS.getCategory() == fcInfinity) {
4058
0
    Out = RHS;
4059
0
    return opOK;
4060
0
  }
4061
24
  assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
4062
24
4063
24
  APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
4064
24
      CC(RHS.Floats[1]);
4065
24
  assert(&A.getSemantics() == &semIEEEdouble);
4066
24
  assert(&AA.getSemantics() == &semIEEEdouble);
4067
24
  assert(&C.getSemantics() == &semIEEEdouble);
4068
24
  assert(&CC.getSemantics() == &semIEEEdouble);
4069
24
  assert(&Out.Floats[0].getSemantics() == &semIEEEdouble);
4070
24
  assert(&Out.Floats[1].getSemantics() == &semIEEEdouble);
4071
24
  return Out.addImpl(A, AA, C, CC, RM);
4072
24
}
4073
4074
APFloat::opStatus DoubleAPFloat::add(const DoubleAPFloat &RHS,
4075
31
                                     roundingMode RM) {
4076
31
  return addWithSpecial(*this, RHS, *this, RM);
4077
31
}
4078
4079
APFloat::opStatus DoubleAPFloat::subtract(const DoubleAPFloat &RHS,
4080
8
                                          roundingMode RM) {
4081
8
  changeSign();
4082
8
  auto Ret = add(RHS, RM);
4083
8
  changeSign();
4084
8
  return Ret;
4085
8
}
4086
4087
APFloat::opStatus DoubleAPFloat::multiply(const DoubleAPFloat &RHS,
4088
40
                                          APFloat::roundingMode RM) {
4089
40
  const auto &LHS = *this;
4090
40
  auto &Out = *this;
4091
40
  /* Interesting observation: For special categories, finding the lowest
4092
40
     common ancestor of the following layered graph gives the correct
4093
40
     return category:
4094
40
4095
40
        NaN
4096
40
       /   \
4097
40
     Zero  Inf
4098
40
       \   /
4099
40
       Normal
4100
40
4101
40
     e.g. NaN * NaN = NaN
4102
40
          Zero * Inf = NaN
4103
40
          Normal * Zero = Zero
4104
40
          Normal * Inf = Inf
4105
40
  */
4106
40
  if (LHS.getCategory() == fcNaN) {
4107
5
    Out = LHS;
4108
5
    return opOK;
4109
5
  }
4110
35
  if (RHS.getCategory() == fcNaN) {
4111
3
    Out = RHS;
4112
3
    return opOK;
4113
3
  }
4114
32
  if ((LHS.getCategory() == fcZero && 
RHS.getCategory() == fcInfinity7
) ||
4115
32
      
(31
LHS.getCategory() == fcInfinity31
&&
RHS.getCategory() == fcZero4
)) {
4116
2
    Out.makeNaN(false, false, nullptr);
4117
2
    return opOK;
4118
2
  }
4119
30
  if (LHS.getCategory() == fcZero || 
LHS.getCategory() == fcInfinity24
) {
4120
9
    Out = LHS;
4121
9
    return opOK;
4122
9
  }
4123
21
  if (RHS.getCategory() == fcZero || 
RHS.getCategory() == fcInfinity20
) {
4124
2
    Out = RHS;
4125
2
    return opOK;
4126
2
  }
4127
19
  assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
4128
19
         "Special cases not handled exhaustively");
4129
19
4130
19
  int Status = opOK;
4131
19
  APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
4132
19
  // t = a * c
4133
19
  APFloat T = A;
4134
19
  Status |= T.multiply(C, RM);
4135
19
  if (!T.isFiniteNonZero()) {
4136
0
    Floats[0] = T;
4137
0
    Floats[1].makeZero(/* Neg = */ false);
4138
0
    return (opStatus)Status;
4139
0
  }
4140
19
4141
19
  // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
4142
19
  APFloat Tau = A;
4143
19
  T.changeSign();
4144
19
  Status |= Tau.fusedMultiplyAdd(C, T, RM);
4145
19
  T.changeSign();
4146
19
  {
4147
19
    // v = a * d
4148
19
    APFloat V = A;
4149
19
    Status |= V.multiply(D, RM);
4150
19
    // w = b * c
4151
19
    APFloat W = B;
4152
19
    Status |= W.multiply(C, RM);
4153
19
    Status |= V.add(W, RM);
4154
19
    // tau += v + w
4155
19
    Status |= Tau.add(V, RM);
4156
19
  }
4157
19
  // u = t + tau
4158
19
  APFloat U = T;
4159
19
  Status |= U.add(Tau, RM);
4160
19
4161
19
  Floats[0] = U;
4162
19
  if (!U.isFinite()) {
4163
2
    Floats[1].makeZero(/* Neg = */ false);
4164
17
  } else {
4165
17
    // Floats[1] = (t - u) + tau
4166
17
    Status |= T.subtract(U, RM);
4167
17
    Status |= T.add(Tau, RM);
4168
17
    Floats[1] = T;
4169
17
  }
4170
19
  return (opStatus)Status;
4171
19
}
4172
4173
APFloat::opStatus DoubleAPFloat::divide(const DoubleAPFloat &RHS,
4174
2
                                        APFloat::roundingMode RM) {
4175
2
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4176
2
  APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4177
2
  auto Ret =
4178
2
      Tmp.divide(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
4179
2
  *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4180
2
  return Ret;
4181
2
}
4182
4183
2
APFloat::opStatus DoubleAPFloat::remainder(const DoubleAPFloat &RHS) {
4184
2
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4185
2
  APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4186
2
  auto Ret =
4187
2
      Tmp.remainder(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4188
2
  *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4189
2
  return Ret;
4190
2
}
4191
4192
2
APFloat::opStatus DoubleAPFloat::mod(const DoubleAPFloat &RHS) {
4193
2
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4194
2
  APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4195
2
  auto Ret = Tmp.mod(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4196
2
  *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4197
2
  return Ret;
4198
2
}
4199
4200
APFloat::opStatus
4201
DoubleAPFloat::fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
4202
                                const DoubleAPFloat &Addend,
4203
1
                                APFloat::roundingMode RM) {
4204
1
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4205
1
  APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4206
1
  auto Ret = Tmp.fusedMultiplyAdd(
4207
1
      APFloat(semPPCDoubleDoubleLegacy, Multiplicand.bitcastToAPInt()),
4208
1
      APFloat(semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()), RM);
4209
1
  *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4210
1
  return Ret;
4211
1
}
4212
4213
2
APFloat::opStatus DoubleAPFloat::roundToIntegral(APFloat::roundingMode RM) {
4214
2
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4215
2
  APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4216
2
  auto Ret = Tmp.roundToIntegral(RM);
4217
2
  *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4218
2
  return Ret;
4219
2
}
4220
4221
25
void DoubleAPFloat::changeSign() {
4222
25
  Floats[0].changeSign();
4223
25
  Floats[1].changeSign();
4224
25
}
4225
4226
APFloat::cmpResult
4227
0
DoubleAPFloat::compareAbsoluteValue(const DoubleAPFloat &RHS) const {
4228
0
  auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
4229
0
  if (Result != cmpEqual)
4230
0
    return Result;
4231
0
  Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
4232
0
  if (Result == cmpLessThan || Result == cmpGreaterThan) {
4233
0
    auto Against = Floats[0].isNegative() ^ Floats[1].isNegative();
4234
0
    auto RHSAgainst = RHS.Floats[0].isNegative() ^ RHS.Floats[1].isNegative();
4235
0
    if (Against && !RHSAgainst)
4236
0
      return cmpLessThan;
4237
0
    if (!Against && RHSAgainst)
4238
0
      return cmpGreaterThan;
4239
0
    if (!Against && !RHSAgainst)
4240
0
      return Result;
4241
0
    if (Against && RHSAgainst)
4242
0
      return (cmpResult)(cmpLessThan + cmpGreaterThan - Result);
4243
0
  }
4244
0
  return Result;
4245
0
}
4246
4247
442
APFloat::fltCategory DoubleAPFloat::getCategory() const {
4248
442
  return Floats[0].getCategory();
4249
442
}
4250
4251
2
bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
4252
4253
0
void DoubleAPFloat::makeInf(bool Neg) {
4254
0
  Floats[0].makeInf(Neg);
4255
0
  Floats[1].makeZero(/* Neg = */ false);
4256
0
}
4257
4258
23
void DoubleAPFloat::makeZero(bool Neg) {
4259
23
  Floats[0].makeZero(Neg);
4260
23
  Floats[1].makeZero(/* Neg = */ false);
4261
23
}
4262
4263
5
void DoubleAPFloat::makeLargest(bool Neg) {
4264
5
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4265
5
  Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
4266
5
  Floats[1] = APFloat(semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
4267
5
  if (Neg)
4268
1
    changeSign();
4269
5
}
4270
4271
5
void DoubleAPFloat::makeSmallest(bool Neg) {
4272
5
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4273
5
  Floats[0].makeSmallest(Neg);
4274
5
  Floats[1].makeZero(/* Neg = */ false);
4275
5
}
4276
4277
3
void DoubleAPFloat::makeSmallestNormalized(bool Neg) {
4278
3
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4279
3
  Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x0360000000000000ull));
4280
3
  if (Neg)
4281
1
    Floats[0].changeSign();
4282
3
  Floats[1].makeZero(/* Neg = */ false);
4283
3
}
4284
4285
2
void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
4286
2
  Floats[0].makeNaN(SNaN, Neg, fill);
4287
2
  Floats[1].makeZero(/* Neg = */ false);
4288
2
}
4289
4290
14
APFloat::cmpResult DoubleAPFloat::compare(const DoubleAPFloat &RHS) const {
4291
14
  auto Result = Floats[0].compare(RHS.Floats[0]);
4292
14
  // |Float[0]| > |Float[1]|
4293
14
  if (Result == APFloat::cmpEqual)
4294
9
    return Floats[1].compare(RHS.Floats[1]);
4295
5
  return Result;
4296
5
}
4297
4298
78
bool DoubleAPFloat::bitwiseIsEqual(const DoubleAPFloat &RHS) const {
4299
78
  return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
4300
78
         
Floats[1].bitwiseIsEqual(RHS.Floats[1])53
;
4301
78
}
4302
4303
136
hash_code hash_value(const DoubleAPFloat &Arg) {
4304
136
  if (Arg.Floats)
4305
136
    return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
4306
0
  return hash_combine(Arg.Semantics);
4307
0
}
4308
4309
254
APInt DoubleAPFloat::bitcastToAPInt() const {
4310
254
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4311
254
  uint64_t Data[] = {
4312
254
      Floats[0].bitcastToAPInt().getRawData()[0],
4313
254
      Floats[1].bitcastToAPInt().getRawData()[0],
4314
254
  };
4315
254
  return APInt(128, 2, Data);
4316
254
}
4317
4318
APFloat::opStatus DoubleAPFloat::convertFromString(StringRef S,
4319
42
                                                   roundingMode RM) {
4320
42
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4321
42
  APFloat Tmp(semPPCDoubleDoubleLegacy);
4322
42
  auto Ret = Tmp.convertFromString(S, RM);
4323
42
  *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4324
42
  return Ret;
4325
42
}
4326
4327
0
APFloat::opStatus DoubleAPFloat::next(bool nextDown) {
4328
0
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4329
0
  APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4330
0
  auto Ret = Tmp.next(nextDown);
4331
0
  *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4332
0
  return Ret;
4333
0
}
4334
4335
APFloat::opStatus
4336
DoubleAPFloat::convertToInteger(MutableArrayRef<integerPart> Input,
4337
                                unsigned int Width, bool IsSigned,
4338
2
                                roundingMode RM, bool *IsExact) const {
4339
2
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4340
2
  return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4341
2
      .convertToInteger(Input, Width, IsSigned, RM, IsExact);
4342
2
}
4343
4344
APFloat::opStatus DoubleAPFloat::convertFromAPInt(const APInt &Input,
4345
                                                  bool IsSigned,
4346
9
                                                  roundingMode RM) {
4347
9
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4348
9
  APFloat Tmp(semPPCDoubleDoubleLegacy);
4349
9
  auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM);
4350
9
  *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4351
9
  return Ret;
4352
9
}
4353
4354
APFloat::opStatus
4355
DoubleAPFloat::convertFromSignExtendedInteger(const integerPart *Input,
4356
                                              unsigned int InputSize,
4357
0
                                              bool IsSigned, roundingMode RM) {
4358
0
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4359
0
  APFloat Tmp(semPPCDoubleDoubleLegacy);
4360
0
  auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM);
4361
0
  *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4362
0
  return Ret;
4363
0
}
4364
4365
APFloat::opStatus
4366
DoubleAPFloat::convertFromZeroExtendedInteger(const integerPart *Input,
4367
                                              unsigned int InputSize,
4368
0
                                              bool IsSigned, roundingMode RM) {
4369
0
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4370
0
  APFloat Tmp(semPPCDoubleDoubleLegacy);
4371
0
  auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM);
4372
0
  *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4373
0
  return Ret;
4374
0
}
4375
4376
unsigned int DoubleAPFloat::convertToHexString(char *DST,
4377
                                               unsigned int HexDigits,
4378
                                               bool UpperCase,
4379
0
                                               roundingMode RM) const {
4380
0
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4381
0
  return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4382
0
      .convertToHexString(DST, HexDigits, UpperCase, RM);
4383
0
}
4384
4385
4
bool DoubleAPFloat::isDenormal() const {
4386
4
  return getCategory() == fcNormal &&
4387
4
         (Floats[0].isDenormal() || 
Floats[1].isDenormal()3
||
4388
4
          // (double)(Hi + Lo) == Hi defines a normal number.
4389
4
          
Floats[0].compare(Floats[0] + Floats[1]) != cmpEqual3
);
4390
4
}
4391
4392
1
bool DoubleAPFloat::isSmallest() const {
4393
1
  if (getCategory() != fcNormal)
4394
0
    return false;
4395
1
  DoubleAPFloat Tmp(*this);
4396
1
  Tmp.makeSmallest(this->isNegative());
4397
1
  return Tmp.compare(*this) == cmpEqual;
4398
1
}
4399
4400
1
bool DoubleAPFloat::isLargest() const {
4401
1
  if (getCategory() != fcNormal)
4402
0
    return false;
4403
1
  DoubleAPFloat Tmp(*this);
4404
1
  Tmp.makeLargest(this->isNegative());
4405
1
  return Tmp.compare(*this) == cmpEqual;
4406
1
}
4407
4408
3
bool DoubleAPFloat::isInteger() const {
4409
3
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4410
3
  return Floats[0].isInteger() && 
Floats[1].isInteger()2
;
4411
3
}
4412
4413
void DoubleAPFloat::toString(SmallVectorImpl<char> &Str,
4414
                             unsigned FormatPrecision,
4415
                             unsigned FormatMaxPadding,
4416
5
                             bool TruncateZero) const {
4417
5
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4418
5
  APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4419
5
      .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
4420
5
}
4421
4422
1
bool DoubleAPFloat::getExactInverse(APFloat *inv) const {
4423
1
  assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4424
1
  APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4425
1
  if (!inv)
4426
0
    return Tmp.getExactInverse(nullptr);
4427
1
  APFloat Inv(semPPCDoubleDoubleLegacy);
4428
1
  auto Ret = Tmp.getExactInverse(&Inv);
4429
1
  *inv = APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt());
4430
1
  return Ret;
4431
1
}
4432
4433
2
DoubleAPFloat scalbn(DoubleAPFloat Arg, int Exp, APFloat::roundingMode RM) {
4434
2
  assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4435
2
  return DoubleAPFloat(semPPCDoubleDouble, scalbn(Arg.Floats[0], Exp, RM),
4436
2
                       scalbn(Arg.Floats[1], Exp, RM));
4437
2
}
4438
4439
DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
4440
2
                    APFloat::roundingMode RM) {
4441
2
  assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4442
2
  APFloat First = frexp(Arg.Floats[0], Exp, RM);
4443
2
  APFloat Second = Arg.Floats[1];
4444
2
  if (Arg.getCategory() == APFloat::fcNormal)
4445
2
    Second = scalbn(Second, -Exp, RM);
4446
2
  return DoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second));
4447
2
}
4448
4449
} // End detail namespace
4450
4451
6.51M
APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
4452
6.51M
  if (
usesLayout<IEEEFloat>(Semantics)6.51M
) {
4453
6.51M
    new (&IEEE) IEEEFloat(std::move(F));
4454
6.51M
    return;
4455
6.51M
  }
4456
18.4E
  if (usesLayout<DoubleAPFloat>(Semantics)) {
4457
0
    const fltSemantics& S = F.getSemantics();
4458
0
    new (&Double)
4459
0
        DoubleAPFloat(Semantics, APFloat(std::move(F), S),
4460
0
                      APFloat(semIEEEdouble));
4461
0
    return;
4462
0
  }
4463
18.4E
  llvm_unreachable("Unexpected semantics");
4464
18.4E
}
4465
4466
351k
APFloat::opStatus APFloat::convertFromString(StringRef Str, roundingMode RM) {
4467
351k
  APFLOAT_DISPATCH_ON_SEMANTICS(convertFromString(Str, RM));
4468
351k
}
4469
4470
1.15M
hash_code hash_value(const APFloat &Arg) {
4471
1.15M
  if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
4472
1.15M
    return hash_value(Arg.U.IEEE);
4473
136
  if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
4474
136
    return hash_value(Arg.U.Double);
4475
0
  llvm_unreachable("Unexpected semantics");
4476
0
}
4477
4478
APFloat::APFloat(const fltSemantics &Semantics, StringRef S)
4479
78.5k
    : APFloat(Semantics) {
4480
78.5k
  convertFromString(S, rmNearestTiesToEven);
4481
78.5k
}
Unexecuted instantiation: llvm::APFloat::APFloat(llvm::fltSemantics const&, llvm::StringRef)
llvm::APFloat::APFloat(llvm::fltSemantics const&, llvm::StringRef)
Line
Count
Source
4479
78.5k
    : APFloat(Semantics) {
4480
78.5k
  convertFromString(S, rmNearestTiesToEven);
4481
78.5k
}
4482
4483
APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics,
4484
930k
                                   roundingMode RM, bool *losesInfo) {
4485
930k
  if (&getSemantics() == &ToSemantics) {
4486
474k
    *losesInfo = false;
4487
474k
    return opOK;
4488
474k
  }
4489
455k
  if (usesLayout<IEEEFloat>(getSemantics()) &&
4490
455k
      
usesLayout<IEEEFloat>(ToSemantics)455k
)
4491
455k
    return U.IEEE.convert(ToSemantics, RM, losesInfo);
4492
18
  if (usesLayout<IEEEFloat>(getSemantics()) &&
4493
20
      usesLayout<DoubleAPFloat>(ToSemantics)) {
4494
20
    assert(&ToSemantics == &semPPCDoubleDouble);
4495
20
    auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo);
4496
20
    *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
4497
20
    return Ret;
4498
20
  }
4499
18.4E
  if (usesLayout<DoubleAPFloat>(getSemantics()) &&
4500
18.4E
      
usesLayout<IEEEFloat>(ToSemantics)2
) {
4501
2
    auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
4502
2
    *this = APFloat(std::move(getIEEE()), ToSemantics);
4503
2
    return Ret;
4504
2
  }
4505
18.4E
  llvm_unreachable("Unexpected semantics");
4506
18.4E
}
4507
4508
251
APFloat APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE) {
4509
251
  if (isIEEE) {
4510
251
    switch (BitWidth) {
4511
251
    case 16:
4512
3
      return APFloat(semIEEEhalf, APInt::getAllOnesValue(BitWidth));
4513
251
    case 32:
4514
227
      return APFloat(semIEEEsingle, APInt::getAllOnesValue(BitWidth));
4515
251
    case 64:
4516
21
      return APFloat(semIEEEdouble, APInt::getAllOnesValue(BitWidth));
4517
251
    case 80:
4518
0
      return APFloat(semX87DoubleExtended, APInt::getAllOnesValue(BitWidth));
4519
251
    case 128:
4520
0
      return APFloat(semIEEEquad, APInt::getAllOnesValue(BitWidth));
4521
251
    default:
4522
0
      llvm_unreachable("Unknown floating bit width");
4523
0
    }
4524
0
  } else {
4525
0
    assert(BitWidth == 128);
4526
0
    return APFloat(semPPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
4527
0
  }
4528
251
}
4529
4530
0
void APFloat::print(raw_ostream &OS) const {
4531
0
  SmallVector<char, 16> Buffer;
4532
0
  toString(Buffer);
4533
0
  OS << Buffer << "\n";
4534
0
}
4535
4536
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4537
LLVM_DUMP_METHOD void APFloat::dump() const { print(dbgs()); }
4538
#endif
4539
4540
424
void APFloat::Profile(FoldingSetNodeID &NID) const {
4541
424
  NID.Add(bitcastToAPInt());
4542
424
}
4543
4544
/* Same as convertToInteger(integerPart*, ...), except the result is returned in
4545
   an APSInt, whose initial bit-width and signed-ness are used to determine the
4546
   precision of the conversion.
4547
 */
4548
APFloat::opStatus APFloat::convertToInteger(APSInt &result,
4549
                                            roundingMode rounding_mode,
4550
60.4k
                                            bool *isExact) const {
4551
60.4k
  unsigned bitWidth = result.getBitWidth();
4552
60.4k
  SmallVector<uint64_t, 4> parts(result.getNumWords());
4553
60.4k
  opStatus status = convertToInteger(parts, bitWidth, result.isSigned(),
4554
60.4k
                                     rounding_mode, isExact);
4555
60.4k
  // Keeps the original signed-ness.
4556
60.4k
  result = APInt(bitWidth, parts);
4557
60.4k
  return status;
4558
60.4k
}
4559
4560
} // End llvm namespace
4561
4562
#undef APFLOAT_DISPATCH_ON_SEMANTICS