LLVM 24.0.0git
APFloat.cpp
Go to the documentation of this file.
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"
18#include "llvm/ADT/FoldingSet.h"
19#include "llvm/ADT/Hashing.h"
20#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringRef.h"
24#include "llvm/Config/llvm-config.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Error.h"
29#include <cstring>
30#include <limits.h>
31
32/// Shared headers from LLVM libc
33/// Make sure to add ${LLVM_SOURCE_DIR}/../libc to include directories.
34///
35/// Notes: So far it looks like APFloat does not check errnos or floating-point
36/// exceptions after calling the math functions, so we will configure LLVM libc
37/// math functions to skip setting errnos and floating-point exceptions
38/// explicitly. We also put them in a separate namespace so that the symbols
39/// do not clash with other libc math builds just in case.
40#define LIBC_NAMESPACE __llvm_libc_apfloat
41#define LIBC_MATH (LIBC_MATH_NO_ERRNO | LIBC_MATH_NO_EXCEPT)
42
43#include "shared/math.h"
44#include "shared/math_check_exceptions.h"
45
46#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
47 do { \
48 if (usesLayout<IEEEFloat>(getSemantics())) \
49 return U.IEEE.METHOD_CALL; \
50 if (usesLayout<DoubleAPFloat>(getSemantics())) \
51 return U.Double.METHOD_CALL; \
52 llvm_unreachable("Unexpected semantics"); \
53 } while (false)
54
55using namespace llvm;
56
57/// A macro used to combine two fcCategory enums into one key which can be used
58/// in a switch statement to classify how the interaction of two APFloat's
59/// categories affects an operation.
60///
61/// TODO: If clang source code is ever allowed to use constexpr in its own
62/// codebase, change this into a static inline function.
63#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
64
65/* Assumed in hexadecimal significand parsing, and conversion to
66 hexadecimal strings. */
67static_assert(APFloatBase::integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
68
69namespace llvm {
70
71constexpr fltSemantics APFloatBase::semIEEEhalf = {15, -14, 11, 16};
72constexpr fltSemantics APFloatBase::semBFloat = {127, -126, 8, 16};
73constexpr fltSemantics APFloatBase::semIEEEsingle = {127, -126, 24, 32};
74constexpr fltSemantics APFloatBase::semIEEEdouble = {1023, -1022, 53, 64};
75constexpr fltSemantics APFloatBase::semIEEEquad = {16383, -16382, 113, 128};
76constexpr fltSemantics APFloatBase::semFloat8E5M2 = {15, -14, 3, 8};
77constexpr fltSemantics APFloatBase::semFloat8E5M2FNUZ = {
79constexpr fltSemantics APFloatBase::semFloat8E4M3 = {7, -6, 4, 8};
80constexpr fltSemantics APFloatBase::semFloat8E4M3FN = {
82constexpr fltSemantics APFloatBase::semFloat8E4M3FNUZ = {
84constexpr fltSemantics APFloatBase::semFloat8E4M3B11FNUZ = {
86constexpr fltSemantics APFloatBase::semFloat8E3M4 = {3, -2, 5, 8};
87constexpr fltSemantics APFloatBase::semFloatTF32 = {127, -126, 11, 19};
88constexpr fltSemantics APFloatBase::semFloat8E8M0FNU = {
89 127,
90 -127,
91 1,
92 8,
95 false,
96 false,
97 false,
98 false};
99
100constexpr fltSemantics APFloatBase::semFloat8E5M3FNU = {
101 16,
102 -14,
103 4,
104 8,
107 true,
108 false,
109 false};
110
111constexpr fltSemantics APFloatBase::semFloat6E3M2FN = {
113constexpr fltSemantics APFloatBase::semFloat6E2M3FN = {
115constexpr fltSemantics APFloatBase::semFloat4E2M1FN = {
117constexpr fltSemantics APFloatBase::semX87DoubleExtended = {
118 16383,
119 -16382,
120 64,
121 80,
124 true,
125 true,
126 true,
127 true,
128 true};
129constexpr fltSemantics APFloatBase::semBogus = {0, 0, 0, 0};
130constexpr fltSemantics APFloatBase::semPPCDoubleDouble = {-1, 0, 0, 128};
131constexpr fltSemantics APFloatBase::semPPCDoubleDoubleLegacy = {
132 1023, -1022 + 53, 53 + 53, 128};
133
135 switch (S) {
136 case S_IEEEhalf:
137 return IEEEhalf();
138 case S_BFloat:
139 return BFloat();
140 case S_IEEEsingle:
141 return IEEEsingle();
142 case S_IEEEdouble:
143 return IEEEdouble();
144 case S_IEEEquad:
145 return IEEEquad();
147 return PPCDoubleDouble();
149 return PPCDoubleDoubleLegacy();
150 case S_Float8E5M2:
151 return Float8E5M2();
152 case S_Float8E5M2FNUZ:
153 return Float8E5M2FNUZ();
154 case S_Float8E4M3:
155 return Float8E4M3();
156 case S_Float8E4M3FN:
157 return Float8E4M3FN();
158 case S_Float8E4M3FNUZ:
159 return Float8E4M3FNUZ();
161 return Float8E4M3B11FNUZ();
162 case S_Float8E3M4:
163 return Float8E3M4();
164 case S_FloatTF32:
165 return FloatTF32();
166 case S_Float8E8M0FNU:
167 return Float8E8M0FNU();
168 case S_Float8E5M3FNU:
169 return Float8E5M3FNU();
170 case S_Float6E3M2FN:
171 return Float6E3M2FN();
172 case S_Float6E2M3FN:
173 return Float6E2M3FN();
174 case S_Float4E2M1FN:
175 return Float4E2M1FN();
177 return x87DoubleExtended();
178 }
179 llvm_unreachable("Unrecognised floating semantics");
180}
181
184 if (&Sem == &llvm::APFloat::IEEEhalf())
185 return S_IEEEhalf;
186 else if (&Sem == &llvm::APFloat::BFloat())
187 return S_BFloat;
188 else if (&Sem == &llvm::APFloat::IEEEsingle())
189 return S_IEEEsingle;
190 else if (&Sem == &llvm::APFloat::IEEEdouble())
191 return S_IEEEdouble;
192 else if (&Sem == &llvm::APFloat::IEEEquad())
193 return S_IEEEquad;
194 else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
195 return S_PPCDoubleDouble;
196 else if (&Sem == &llvm::APFloat::PPCDoubleDoubleLegacy())
198 else if (&Sem == &llvm::APFloat::Float8E5M2())
199 return S_Float8E5M2;
200 else if (&Sem == &llvm::APFloat::Float8E5M2FNUZ())
201 return S_Float8E5M2FNUZ;
202 else if (&Sem == &llvm::APFloat::Float8E4M3())
203 return S_Float8E4M3;
204 else if (&Sem == &llvm::APFloat::Float8E4M3FN())
205 return S_Float8E4M3FN;
206 else if (&Sem == &llvm::APFloat::Float8E4M3FNUZ())
207 return S_Float8E4M3FNUZ;
208 else if (&Sem == &llvm::APFloat::Float8E4M3B11FNUZ())
209 return S_Float8E4M3B11FNUZ;
210 else if (&Sem == &llvm::APFloat::Float8E3M4())
211 return S_Float8E3M4;
212 else if (&Sem == &llvm::APFloat::FloatTF32())
213 return S_FloatTF32;
214 else if (&Sem == &llvm::APFloat::Float8E8M0FNU())
215 return S_Float8E8M0FNU;
216 else if (&Sem == &llvm::APFloat::Float8E5M3FNU())
217 return S_Float8E5M3FNU;
218 else if (&Sem == &llvm::APFloat::Float6E3M2FN())
219 return S_Float6E3M2FN;
220 else if (&Sem == &llvm::APFloat::Float6E2M3FN())
221 return S_Float6E2M3FN;
222 else if (&Sem == &llvm::APFloat::Float4E2M1FN())
223 return S_Float4E2M1FN;
224 else if (&Sem == &llvm::APFloat::x87DoubleExtended())
225 return S_x87DoubleExtended;
226 else
227 llvm_unreachable("Unknown floating semantics");
228}
229
231 const fltSemantics &B) {
232 return A.maxExponent <= B.maxExponent && A.minExponent >= B.minExponent &&
233 A.precision <= B.precision;
234}
235
236/* A tight upper bound on number of parts required to hold the value
237 pow(5, power) is
238
239 power * 815 / (351 * integerPartWidth) + 1
240
241 However, whilst the result may require only this many parts,
242 because we are multiplying two values to get it, the
243 multiplication may require an extra part with the excess part
244 being zero (consider the trivial case of 1 * 1, tcFullMultiply
245 requires two parts to hold the single-part result). So we add an
246 extra one to guarantee enough space whilst multiplying. */
247const unsigned int maxExponent = 16383;
248const unsigned int maxPrecision = 113;
250const unsigned int maxPowerOfFiveParts =
251 2 +
253
254unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
255 return semantics.precision;
256}
259 return semantics.maxExponent;
260}
263 return semantics.minExponent;
264}
265unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
266 return semantics.sizeInBits;
267}
269 bool isSigned) {
270 // The max FP value is pow(2, MaxExponent) * (1 + MaxFraction), so we need
271 // at least one more bit than the MaxExponent to hold the max FP value.
272 unsigned int MinBitWidth = semanticsMaxExponent(semantics) + 1;
273 // Extra sign bit needed.
274 if (isSigned)
275 ++MinBitWidth;
276 return MinBitWidth;
277}
278
280 return semantics.hasZero;
281}
282
284 return semantics.hasSignedRepr;
285}
286
290
294
296 // Keep in sync with Type::isIEEELikeFPTy
297 return SemanticsToEnum(semantics) <= S_IEEEquad;
298}
299
301 return semantics.hasSignBitInMSB;
302}
303
305 const fltSemantics &Dst) {
306 // Exponent range must be larger.
307 if (Src.maxExponent >= Dst.maxExponent || Src.minExponent <= Dst.minExponent)
308 return false;
309
310 // If the mantissa is long enough, the result value could still be denormal
311 // with a larger exponent range.
312 //
313 // FIXME: This condition is probably not accurate but also shouldn't be a
314 // practical concern with existing types.
315 return Dst.precision >= Src.precision;
316}
317
319 return Sem.sizeInBits;
320}
321
322static constexpr APFloatBase::ExponentType
323exponentZero(const fltSemantics &semantics) {
324 return semantics.minExponent - 1;
325}
326
327static constexpr APFloatBase::ExponentType
328exponentInf(const fltSemantics &semantics) {
329 return semantics.maxExponent + 1;
330}
331
332static constexpr APFloatBase::ExponentType
333exponentNaN(const fltSemantics &semantics) {
336 return exponentZero(semantics);
337 if (semantics.hasSignedRepr || semantics.precision > 1)
338 return semantics.maxExponent;
339 }
340 return semantics.maxExponent + 1;
341}
342
343/* A bunch of private, handy routines. */
344
345static inline Error createError(const Twine &Err) {
347}
348
349static constexpr inline unsigned int partCountForBits(unsigned int bits) {
350 return std::max(1u, (bits + APFloatBase::integerPartWidth - 1) /
352}
353
354/* Returns 0U-9U. Return values >= 10U are not digits. */
355static inline unsigned int
356decDigitValue(unsigned int c)
357{
358 return c - '0';
359}
360
361/* Return the value of a decimal exponent of the form
362 [+-]ddddddd.
363
364 If the exponent overflows, returns a large exponent with the
365 appropriate sign. */
368 const unsigned int overlargeExponent = 24000; /* FIXME. */
369 StringRef::iterator p = begin;
370
371 // Treat no exponent as 0 to match binutils
372 if (p == end || ((*p == '-' || *p == '+') && (p + 1) == end))
373 return 0;
374
375 bool isNegative = *p == '-';
376 if (*p == '-' || *p == '+') {
377 p++;
378 if (p == end)
379 return createError("Exponent has no digits");
380 }
381
382 unsigned absExponent = decDigitValue(*p++);
383 if (absExponent >= 10U)
384 return createError("Invalid character in exponent");
385
386 for (; p != end; ++p) {
387 unsigned value = decDigitValue(*p);
388 if (value >= 10U)
389 return createError("Invalid character in exponent");
390
391 absExponent = absExponent * 10U + value;
392 if (absExponent >= overlargeExponent) {
393 absExponent = overlargeExponent;
394 break;
395 }
396 }
397
398 if (isNegative)
399 return -(int) absExponent;
400 else
401 return (int) absExponent;
402}
403
404/* This is ugly and needs cleaning up, but I don't immediately see
405 how whilst remaining safe. */
408 int exponentAdjustment) {
409 int exponent = 0;
410
411 if (p == end)
412 return createError("Exponent has no digits");
413
414 bool negative = *p == '-';
415 if (*p == '-' || *p == '+') {
416 p++;
417 if (p == end)
418 return createError("Exponent has no digits");
419 }
420
421 int unsignedExponent = 0;
422 bool overflow = false;
423 for (; p != end; ++p) {
424 unsigned int value;
425
426 value = decDigitValue(*p);
427 if (value >= 10U)
428 return createError("Invalid character in exponent");
429
430 unsignedExponent = unsignedExponent * 10 + value;
431 if (unsignedExponent > 32767) {
432 overflow = true;
433 break;
434 }
435 }
436
437 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
438 overflow = true;
439
440 if (!overflow) {
441 exponent = unsignedExponent;
442 if (negative)
443 exponent = -exponent;
444 exponent += exponentAdjustment;
445 if (exponent > 32767 || exponent < -32768)
446 overflow = true;
447 }
448
449 if (overflow)
450 exponent = negative ? -32768: 32767;
451
452 return exponent;
453}
454
457 StringRef::iterator *dot) {
458 StringRef::iterator p = begin;
459 *dot = end;
460 while (p != end && *p == '0')
461 p++;
462
463 if (p != end && *p == '.') {
464 *dot = p++;
465
466 if (end - begin == 1)
467 return createError("Significand has no digits");
468
469 while (p != end && *p == '0')
470 p++;
471 }
472
473 return p;
474}
475
476/* Given a normal decimal floating point number of the form
477
478 dddd.dddd[eE][+-]ddd
479
480 where the decimal point and exponent are optional, fill out the
481 structure D. Exponent is appropriate if the significand is
482 treated as an integer, and normalizedExponent if the significand
483 is taken to have the decimal point after a single leading
484 non-zero digit.
485
486 If the value is zero, V->firstSigDigit points to a non-digit, and
487 the return exponent is zero.
488*/
490 const char *firstSigDigit;
491 const char *lastSigDigit;
494};
495
498 StringRef::iterator dot = end;
499
500 auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot);
501 if (!PtrOrErr)
502 return PtrOrErr.takeError();
503 StringRef::iterator p = *PtrOrErr;
504
505 D->firstSigDigit = p;
506 D->exponent = 0;
507 D->normalizedExponent = 0;
508
509 for (; p != end; ++p) {
510 if (*p == '.') {
511 if (dot != end)
512 return createError("String contains multiple dots");
513 dot = p++;
514 if (p == end)
515 break;
516 }
517 if (decDigitValue(*p) >= 10U)
518 break;
519 }
520
521 if (p != end) {
522 if (*p != 'e' && *p != 'E')
523 return createError("Invalid character in significand");
524 if (p == begin)
525 return createError("Significand has no digits");
526 if (dot != end && p - begin == 1)
527 return createError("Significand has no digits");
528
529 /* p points to the first non-digit in the string */
530 auto ExpOrErr = readExponent(p + 1, end);
531 if (!ExpOrErr)
532 return ExpOrErr.takeError();
533 D->exponent = *ExpOrErr;
534
535 /* Implied decimal point? */
536 if (dot == end)
537 dot = p;
538 }
539
540 /* If number is all zeroes accept any exponent. */
541 if (p != D->firstSigDigit) {
542 /* Drop insignificant trailing zeroes. */
543 if (p != begin) {
544 do
545 do
546 p--;
547 while (p != begin && *p == '0');
548 while (p != begin && *p == '.');
549 }
550
551 /* Adjust the exponents for any decimal point. */
552 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
553 D->normalizedExponent = (D->exponent +
554 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
555 - (dot > D->firstSigDigit && dot < p)));
556 }
557
558 D->lastSigDigit = p;
559 return Error::success();
560}
561
562/* Return the trailing fraction of a hexadecimal number.
563 DIGITVALUE is the first hex digit of the fraction, P points to
564 the next digit. */
567 unsigned int digitValue) {
568 /* If the first trailing digit isn't 0 or 8 we can work out the
569 fraction immediately. */
570 if (digitValue > 8)
571 return lfMoreThanHalf;
572 else if (digitValue < 8 && digitValue > 0)
573 return lfLessThanHalf;
574
575 // Otherwise we need to find the first non-zero digit.
576 while (p != end && (*p == '0' || *p == '.'))
577 p++;
578
579 if (p == end)
580 return createError("Invalid trailing hexadecimal fraction!");
581
582 unsigned hexDigit = hexDigitValue(*p);
583
584 /* If we ran off the end it is exactly zero or one-half, otherwise
585 a little more. */
586 if (hexDigit == UINT_MAX)
587 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
588 else
589 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
590}
591
592/* Return the fraction lost were a bignum truncated losing the least
593 significant BITS bits. */
594static lostFraction
596 unsigned int partCount,
597 unsigned int bits)
598{
599 unsigned lsb = APInt::tcLSB(parts, partCount);
600
601 /* Note this is guaranteed true if bits == 0, or LSB == UINT_MAX. */
602 if (bits <= lsb)
603 return lfExactlyZero;
604 if (bits == lsb + 1)
605 return lfExactlyHalf;
606 if (bits <= partCount * APFloatBase::integerPartWidth &&
607 APInt::tcExtractBit(parts, bits - 1))
608 return lfMoreThanHalf;
609
610 return lfLessThanHalf;
611}
612
613/* Shift DST right BITS bits noting lost fraction. */
614static lostFraction
615shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
616{
617 lostFraction lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
618
619 APInt::tcShiftRight(dst, parts, bits);
620
621 return lost_fraction;
622}
623
624/* Combine the effect of two lost fractions. */
625static lostFraction
627 lostFraction lessSignificant)
628{
629 if (lessSignificant != lfExactlyZero) {
630 if (moreSignificant == lfExactlyZero)
631 moreSignificant = lfLessThanHalf;
632 else if (moreSignificant == lfExactlyHalf)
633 moreSignificant = lfMoreThanHalf;
634 }
635
636 return moreSignificant;
637}
638
639/* The error from the true value, in half-ulps, on multiplying two
640 floating point numbers, which differ from the value they
641 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
642 than the returned value.
643
644 See "How to Read Floating Point Numbers Accurately" by William D
645 Clinger. */
646static unsigned int
647HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
648{
649 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
650
651 if (HUerr1 + HUerr2 == 0)
652 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
653 else
654 return inexactMultiply + 2 * (HUerr1 + HUerr2);
655}
656
657/* The number of ulps from the boundary (zero, or half if ISNEAREST)
658 when the least significant BITS are truncated. BITS cannot be
659 zero. */
661ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits,
662 bool isNearest) {
663 assert(bits != 0);
664
665 bits--;
666 unsigned count = bits / APFloatBase::integerPartWidth;
667 unsigned partBits = bits % APFloatBase::integerPartWidth + 1;
668
670 parts[count] & (~(APFloatBase::integerPart)0 >>
671 (APFloatBase::integerPartWidth - partBits));
672
674 if (isNearest)
675 boundary = (APFloatBase::integerPart) 1 << (partBits - 1);
676 else
677 boundary = 0;
678
679 if (count == 0) {
680 if (part - boundary <= boundary - part)
681 return part - boundary;
682 else
683 return boundary - part;
684 }
685
686 if (part == boundary) {
687 while (--count)
688 if (parts[count])
689 return ~(APFloatBase::integerPart) 0; /* A lot. */
690
691 return parts[0];
692 } else if (part == boundary - 1) {
693 while (--count)
694 if (~parts[count])
695 return ~(APFloatBase::integerPart) 0; /* A lot. */
696
697 return -parts[0];
698 }
699
700 return ~(APFloatBase::integerPart) 0; /* A lot. */
701}
702
703/* Place pow(5, power) in DST, and return the number of parts used.
704 DST must be at least one part larger than size of the answer. */
705static unsigned int
706powerOf5(APFloatBase::integerPart *dst, unsigned int power) {
707 static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 };
709 pow5s[0] = 78125 * 5;
710
711 unsigned int partsCount = 1;
712 APFloatBase::integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
713 assert(power <= maxExponent);
714
715 p1 = dst;
716 p2 = scratch;
717
718 *p1 = firstEightPowers[power & 7];
719 power >>= 3;
720
721 unsigned result = 1;
722 pow5 = pow5s;
723
724 for (unsigned int n = 0; power; power >>= 1, n++) {
725 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
726 if (n != 0) {
727 APInt::tcFullMultiply(pow5, pow5 - partsCount, pow5 - partsCount,
728 partsCount, partsCount);
729 partsCount *= 2;
730 if (pow5[partsCount - 1] == 0)
731 partsCount--;
732 }
733
734 if (power & 1) {
736
737 APInt::tcFullMultiply(p2, p1, pow5, result, partsCount);
738 result += partsCount;
739 if (p2[result - 1] == 0)
740 result--;
741
742 /* Now result is in p1 with partsCount parts and p2 is scratch
743 space. */
744 tmp = p1;
745 p1 = p2;
746 p2 = tmp;
747 }
748
749 pow5 += partsCount;
750 }
751
752 if (p1 != dst)
753 APInt::tcAssign(dst, p1, result);
754
755 return result;
756}
757
758/* Zero at the end to avoid modular arithmetic when adding one; used
759 when rounding up during hexadecimal output. */
760static const char hexDigitsLower[] = "0123456789abcdef0";
761static const char hexDigitsUpper[] = "0123456789ABCDEF0";
762static const char infinityL[] = "infinity";
763static const char infinityU[] = "INFINITY";
764static const char NaNL[] = "nan";
765static const char NaNU[] = "NAN";
766
767/* Write out an integerPart in hexadecimal, starting with the most
768 significant nibble. Write out exactly COUNT hexdigits, return
769 COUNT. */
770static unsigned int
771partAsHex (char *dst, APFloatBase::integerPart part, unsigned int count,
772 const char *hexDigitChars)
773{
774 unsigned int result = count;
775
777
778 part >>= (APFloatBase::integerPartWidth - 4 * count);
779 while (count--) {
780 dst[count] = hexDigitChars[part & 0xf];
781 part >>= 4;
782 }
783
784 return result;
785}
786
787/* Write out an unsigned decimal integer. */
788static char *writeUnsignedDecimal(char *dst, unsigned int n) {
789 char buff[40], *p;
790
791 p = buff;
792 do
793 *p++ = '0' + n % 10;
794 while (n /= 10);
795
796 do
797 *dst++ = *--p;
798 while (p != buff);
799
800 return dst;
801}
802
803/* Write out a signed decimal integer. */
804static char *writeSignedDecimal(char *dst, int value) {
805 if (value < 0) {
806 *dst++ = '-';
807 dst = writeUnsignedDecimal(dst, -(unsigned) value);
808 } else {
809 dst = writeUnsignedDecimal(dst, value);
810 }
811
812 return dst;
813}
814
815// Compute the ULP of the input using a definition from:
816// Jean-Michel Muller. On the definition of ulp(x). [Research Report] RR-5504,
817// LIP RR-2005-09, INRIA, LIP. 2005, pp.16. inria-00070503
818static APFloat harrisonUlp(const APFloat &X) {
819 const fltSemantics &Sem = X.getSemantics();
820 switch (X.getCategory()) {
821 case APFloat::fcNaN:
822 return APFloat::getQNaN(Sem);
824 return APFloat::getInf(Sem);
825 case APFloat::fcZero:
826 return APFloat::getSmallest(Sem);
828 break;
829 }
830 if (X.isDenormal() || X.isSmallestNormalized())
831 return APFloat::getSmallest(Sem);
832 int Exp = ilogb(X);
833 if (X.getExactLog2() != INT_MIN)
834 Exp -= 1;
835 return scalbn(APFloat::getOne(Sem), Exp - (Sem.precision - 1),
837}
838
839namespace detail {
840/* Constructors. */
841void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
842 semantics = ourSemantics;
843 unsigned count = partCount();
844 if (count > 1)
845 significand.parts = new integerPart[count];
846}
847
848void IEEEFloat::freeSignificand() {
849 if (needsCleanup())
850 delete [] significand.parts;
851}
852
853void IEEEFloat::assign(const IEEEFloat &rhs) {
854 assert(semantics == rhs.semantics);
855
856 sign = rhs.sign;
857 category = rhs.category;
858 exponent = rhs.exponent;
859 if (isFiniteNonZero() || category == fcNaN)
860 copySignificand(rhs);
861}
862
863void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
864 assert(isFiniteNonZero() || category == fcNaN);
865 assert(rhs.partCount() >= partCount());
866
867 APInt::tcAssign(significandParts(), rhs.significandParts(),
868 partCount());
869}
870
871/* Make this number a NaN, with an arbitrary but deterministic value
872 for the significand. If double or longer, this is a signalling NaN,
873 which may not be ideal. If float, this is QNaN(0). */
874void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
875 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
876 llvm_unreachable("This floating point format does not support NaN");
877
878 if (Negative && !semantics->hasSignedRepr)
880 "This floating point format does not support signed values");
881
882 category = fcNaN;
883 sign = Negative;
884 exponent = exponentNaN();
885
886 integerPart *significand = significandParts();
887 unsigned numParts = partCount();
888
889 APInt fill_storage;
890 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
891 // Finite-only types do not distinguish signalling and quiet NaN, so
892 // make them all signalling.
893 SNaN = false;
894 if (semantics->nanEncoding == fltNanEncoding::NegativeZero) {
895 sign = true;
896 fill_storage = APInt::getZero(semantics->precision - 1);
897 } else {
898 fill_storage = APInt::getAllOnes(semantics->precision - 1);
899 }
900 fill = &fill_storage;
901 }
902
903 // Set the significand bits to the fill.
904 if (!fill || fill->getNumWords() < numParts)
905 APInt::tcSet(significand, 0, numParts);
906 if (fill) {
907 APInt::tcAssign(significand, fill->getRawData(),
908 std::min(fill->getNumWords(), numParts));
909
910 // Zero out the excess bits of the significand.
911 unsigned bitsToPreserve = semantics->precision - 1;
912 unsigned part = bitsToPreserve / 64;
913 bitsToPreserve %= 64;
914 significand[part] &= ((1ULL << bitsToPreserve) - 1);
915 for (part++; part != numParts; ++part)
916 significand[part] = 0;
917 }
918
919 unsigned QNaNBit =
920 (semantics->precision >= 2) ? (semantics->precision - 2) : 0;
921
922 if (SNaN) {
923 // We always have to clear the QNaN bit to make it an SNaN.
924 APInt::tcClearBit(significand, QNaNBit);
925
926 // If there are no bits set in the payload, we have to set
927 // *something* to make it a NaN instead of an infinity;
928 // conventionally, this is the next bit down from the QNaN bit.
929 if (APInt::tcIsZero(significand, numParts))
930 APInt::tcSetBit(significand, QNaNBit - 1);
931 } else if (semantics->nanEncoding == fltNanEncoding::NegativeZero) {
932 // The only NaN is a quiet NaN, and it has no bits sets in the significand.
933 // Do nothing.
934 } else {
935 // We always have to set the QNaN bit to make it a QNaN.
936 APInt::tcSetBit(significand, QNaNBit);
937 }
938
939 // For x87 extended precision, we want to make a NaN, not a
940 // pseudo-NaN. Maybe we should expose the ability to make
941 // pseudo-NaNs?
942 if (semantics == &APFloatBase::semX87DoubleExtended)
943 APInt::tcSetBit(significand, QNaNBit + 1);
944}
945
947 if (this != &rhs) {
948 if (semantics != rhs.semantics) {
949 freeSignificand();
950 initialize(rhs.semantics);
951 }
952 assign(rhs);
953 }
954
955 return *this;
956}
957
959 freeSignificand();
960
961 semantics = rhs.semantics;
962 significand = rhs.significand;
963 exponent = rhs.exponent;
964 category = rhs.category;
965 sign = rhs.sign;
966
967 rhs.semantics = &APFloatBase::semBogus;
968 return *this;
969}
970
973 (exponent == semantics->minExponent) &&
974 (APInt::tcExtractBit(significandParts(), semantics->precision - 1) ==
975 0);
976}
977
979 // The smallest number by magnitude in our format will be the smallest
980 // denormal, i.e. the floating point number with exponent being minimum
981 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
982 return isFiniteNonZero() && exponent == semantics->minExponent &&
983 significandMSB() == 0;
984}
985
987 return getCategory() == fcNormal && exponent == semantics->minExponent &&
988 isSignificandAllZerosExceptMSB();
989}
990
991unsigned int IEEEFloat::getNumHighBits() const {
992 const unsigned int PartCount = partCountForBits(semantics->precision);
993 const unsigned int Bits = PartCount * integerPartWidth;
994
995 // Compute how many bits are used in the final word.
996 // When precision is just 1, it represents the 'Pth'
997 // Precision bit and not the actual significand bit.
998 const unsigned int NumHighBits = (semantics->precision > 1)
999 ? (Bits - semantics->precision + 1)
1000 : (Bits - semantics->precision);
1001 return NumHighBits;
1002}
1003
1004bool IEEEFloat::isSignificandAllOnes() const {
1005 // Test if the significand excluding the integral bit is all ones. This allows
1006 // us to test for binade boundaries.
1007 const integerPart *Parts = significandParts();
1008 const unsigned PartCount = partCountForBits(semantics->precision);
1009 for (unsigned i = 0; i < PartCount - 1; i++)
1010 if (~Parts[i])
1011 return false;
1012
1013 // Set the unused high bits to all ones when we compare.
1014 const unsigned NumHighBits = getNumHighBits();
1015 assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1016 "Can not have more high bits to fill than integerPartWidth");
1017 const integerPart HighBitFill =
1018 ~integerPart(0) << (integerPartWidth - NumHighBits);
1019 if ((semantics->precision <= 1) || (~(Parts[PartCount - 1] | HighBitFill)))
1020 return false;
1021
1022 return true;
1023}
1024
1025bool IEEEFloat::isSignificandAllOnesExceptLSB() const {
1026 // Test if the significand excluding the integral bit is all ones except for
1027 // the least significant bit.
1028 const integerPart *Parts = significandParts();
1029
1030 if (Parts[0] & 1)
1031 return false;
1032
1033 const unsigned PartCount = partCountForBits(semantics->precision);
1034 for (unsigned i = 0; i < PartCount - 1; i++) {
1035 if (~Parts[i] & ~unsigned{!i})
1036 return false;
1037 }
1038
1039 // Set the unused high bits to all ones when we compare.
1040 const unsigned NumHighBits = getNumHighBits();
1041 assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1042 "Can not have more high bits to fill than integerPartWidth");
1043 const integerPart HighBitFill = ~integerPart(0)
1044 << (integerPartWidth - NumHighBits);
1045 if (~(Parts[PartCount - 1] | HighBitFill | 0x1))
1046 return false;
1047
1048 return true;
1049}
1050
1051bool IEEEFloat::isSignificandAllZeros() const {
1052 // Test if the significand excluding the integral bit is all zeros. This
1053 // allows us to test for binade boundaries.
1054 const integerPart *Parts = significandParts();
1055 const unsigned PartCount = partCountForBits(semantics->precision);
1056
1057 for (unsigned i = 0; i < PartCount - 1; i++)
1058 if (Parts[i])
1059 return false;
1060
1061 // Compute how many bits are used in the final word.
1062 const unsigned NumHighBits = getNumHighBits();
1063 assert(NumHighBits < integerPartWidth && "Can not have more high bits to "
1064 "clear than integerPartWidth");
1065 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
1066
1067 if ((semantics->precision > 1) && (Parts[PartCount - 1] & HighBitMask))
1068 return false;
1069
1070 return true;
1071}
1072
1073bool IEEEFloat::isSignificandAllZerosExceptMSB() const {
1074 const integerPart *Parts = significandParts();
1075 const unsigned PartCount = partCountForBits(semantics->precision);
1076
1077 for (unsigned i = 0; i < PartCount - 1; i++) {
1078 if (Parts[i])
1079 return false;
1080 }
1081
1082 const unsigned NumHighBits = getNumHighBits();
1083 const integerPart MSBMask = integerPart(1)
1084 << (integerPartWidth - NumHighBits);
1085 return ((semantics->precision <= 1) || (Parts[PartCount - 1] == MSBMask));
1086}
1087
1089 bool IsMaxExp = isFiniteNonZero() && exponent == semantics->maxExponent;
1090 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
1091 semantics->nanEncoding == fltNanEncoding::AllOnes) {
1092 // The largest number by magnitude in our format will be the floating point
1093 // number with maximum exponent and with significand that is all ones except
1094 // the LSB.
1095 return (IsMaxExp && APFloat::hasSignificand(*semantics))
1096 ? isSignificandAllOnesExceptLSB()
1097 : IsMaxExp;
1098 } else {
1099 // The largest number by magnitude in our format will be the floating point
1100 // number with maximum exponent and with significand that is all ones.
1101 return IsMaxExp && isSignificandAllOnes();
1102 }
1103}
1104
1106 // This could be made more efficient; I'm going for obviously correct.
1107 if (!isFinite()) return false;
1108 IEEEFloat truncated = *this;
1109 truncated.roundToIntegral(rmTowardZero);
1110 return compare(truncated) == cmpEqual;
1111}
1112
1113bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
1114 if (this == &rhs)
1115 return true;
1116 if (semantics != rhs.semantics ||
1117 category != rhs.category ||
1118 sign != rhs.sign)
1119 return false;
1120 if (category==fcZero || category==fcInfinity)
1121 return true;
1122
1123 if (isFiniteNonZero() && exponent != rhs.exponent)
1124 return false;
1125
1126 return std::equal(significandParts(), significandParts() + partCount(),
1127 rhs.significandParts());
1128}
1129
1131 initialize(&ourSemantics);
1132 sign = 0;
1133 category = fcNormal;
1134 zeroSignificand();
1135 exponent = ourSemantics.precision - 1;
1136 significandParts()[0] = value;
1138}
1139
1141 initialize(&ourSemantics);
1142 // The Float8E8MOFNU format does not have a representation
1143 // for zero. So, use the closest representation instead.
1144 // Moreover, the all-zero encoding represents a valid
1145 // normal value (which is the smallestNormalized here).
1146 // Hence, we call makeSmallestNormalized (where category is
1147 // 'fcNormal') instead of makeZero (where category is 'fcZero').
1148 ourSemantics.hasZero ? makeZero(false) : makeSmallestNormalized(false);
1149}
1150
1151// Delegate to the previous constructor, because later copy constructor may
1152// actually inspects category, which can't be garbage.
1154 : IEEEFloat(ourSemantics) {}
1155
1157 initialize(rhs.semantics);
1158 assign(rhs);
1159}
1160
1161IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&APFloatBase::semBogus) {
1162 *this = std::move(rhs);
1163}
1164
1165IEEEFloat::~IEEEFloat() { freeSignificand(); }
1166
1167unsigned int IEEEFloat::partCount() const {
1168 return partCountForBits(semantics->precision + 1);
1169}
1170
1171const APFloat::integerPart *IEEEFloat::significandParts() const {
1172 return const_cast<IEEEFloat *>(this)->significandParts();
1173}
1174
1175APFloat::integerPart *IEEEFloat::significandParts() {
1176 if (partCount() > 1)
1177 return significand.parts;
1178 else
1179 return &significand.part;
1180}
1181
1182void IEEEFloat::zeroSignificand() {
1183 APInt::tcSet(significandParts(), 0, partCount());
1184}
1185
1186/* Increment an fcNormal floating point number's significand. */
1187void IEEEFloat::incrementSignificand() {
1188 [[maybe_unused]] integerPart carry =
1189 APInt::tcIncrement(significandParts(), partCount());
1190
1191 /* Our callers should never cause us to overflow. */
1192 assert(carry == 0);
1193}
1194
1195/* Add the significand of the RHS. Returns the carry flag. */
1196APFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
1197 integerPart *parts = significandParts();
1198
1199 assert(semantics == rhs.semantics);
1200 assert(exponent == rhs.exponent);
1201
1202 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
1203}
1204
1205/* Subtract the significand of the RHS with a borrow flag. Returns
1206 the borrow flag. */
1207APFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
1208 integerPart borrow) {
1209 integerPart *parts = significandParts();
1210
1211 assert(semantics == rhs.semantics);
1212 assert(exponent == rhs.exponent);
1213
1214 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
1215 partCount());
1216}
1217
1218/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
1219 on to the full-precision result of the multiplication. Returns the
1220 lost fraction. */
1221lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
1222 IEEEFloat addend,
1223 bool ignoreAddend) {
1224 integerPart scratch[4];
1225 bool ignored;
1226
1227 assert(semantics == rhs.semantics);
1228
1229 unsigned precision = semantics->precision;
1230
1231 // Allocate space for twice as many bits as the original significand, plus one
1232 // extra bit for the addition to overflow into.
1233 unsigned newPartsCount = partCountForBits(precision * 2 + 1);
1234
1235 // FIXME: Replace with SmallVector<4>.
1236 integerPart *fullSignificand =
1237 newPartsCount > 4 ? new integerPart[newPartsCount] : scratch;
1238
1239 integerPart *lhsSignificand = significandParts();
1240 unsigned partsCount = partCount();
1241
1242 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
1243 rhs.significandParts(), partsCount, partsCount);
1244
1245 lostFraction lost_fraction = lfExactlyZero;
1246 // One, not zero, based MSB.
1247 unsigned omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1248 exponent += rhs.exponent;
1249
1250 // Assume the operands involved in the multiplication are single-precision
1251 // FP, and the two multiplicants are:
1252 // *this = a23 . a22 ... a0 * 2^e1
1253 // rhs = b23 . b22 ... b0 * 2^e2
1254 // the result of multiplication is:
1255 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
1256 // Note that there are three significant bits at the left-hand side of the
1257 // radix point: two for the multiplication, and an overflow bit for the
1258 // addition (that will always be zero at this point). Move the radix point
1259 // toward left by two bits, and adjust exponent accordingly.
1260 exponent += 2;
1261
1262 if (!ignoreAddend && addend.isNonZero()) {
1263 // The intermediate result of the multiplication has "2 * precision"
1264 // signicant bit; adjust the addend to be consistent with mul result.
1265 //
1266 Significand savedSignificand = significand;
1267 const fltSemantics *savedSemantics = semantics;
1268
1269 // Normalize our MSB to one below the top bit to allow for overflow.
1270 unsigned extendedPrecision = 2 * precision + 1;
1271 if (omsb != extendedPrecision - 1) {
1272 assert(extendedPrecision > omsb);
1273 APInt::tcShiftLeft(fullSignificand, newPartsCount,
1274 (extendedPrecision - 1) - omsb);
1275 exponent -= (extendedPrecision - 1) - omsb;
1276 }
1277
1278 /* Create new semantics. */
1279 fltSemantics extendedSemantics = *semantics;
1280 extendedSemantics.precision = extendedPrecision;
1281
1282 if (newPartsCount == 1)
1283 significand.part = fullSignificand[0];
1284 else
1285 significand.parts = fullSignificand;
1286 semantics = &extendedSemantics;
1287
1288 // Make a copy so we can convert it to the extended semantics.
1289 // Note that we cannot convert the addend directly, as the extendedSemantics
1290 // is a local variable (which we take a reference to).
1291 IEEEFloat extendedAddend(addend);
1292 [[maybe_unused]] opStatus status = extendedAddend.convert(
1293 extendedSemantics, APFloat::rmTowardZero, &ignored);
1294 assert(status == APFloat::opOK);
1295
1296 // Shift the significand of the addend right by one bit. This guarantees
1297 // that the high bit of the significand is zero (same as fullSignificand),
1298 // so the addition will overflow (if it does overflow at all) into the top bit.
1299 lost_fraction = extendedAddend.shiftSignificandRight(1);
1300 assert(lost_fraction == lfExactlyZero &&
1301 "Lost precision while shifting addend for fused-multiply-add.");
1302
1303 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1304
1305 /* Restore our state. */
1306 if (newPartsCount == 1)
1307 fullSignificand[0] = significand.part;
1308 significand = savedSignificand;
1309 semantics = savedSemantics;
1310
1311 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1312 }
1313
1314 // Convert the result having "2 * precision" significant-bits back to the one
1315 // having "precision" significant-bits. First, move the radix point from
1316 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1317 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
1318 exponent -= precision + 1;
1319
1320 // In case MSB resides at the left-hand side of radix point, shift the
1321 // mantissa right by some amount to make sure the MSB reside right before
1322 // the radix point (i.e. "MSB . rest-significant-bits").
1323 //
1324 // Note that the result is not normalized when "omsb < precision". So, the
1325 // caller needs to call IEEEFloat::normalize() if normalized value is
1326 // expected.
1327 if (omsb > precision) {
1328 unsigned int bits, significantParts;
1329 lostFraction lf;
1330
1331 bits = omsb - precision;
1332 significantParts = partCountForBits(omsb);
1333 lf = shiftRight(fullSignificand, significantParts, bits);
1334 lost_fraction = combineLostFractions(lf, lost_fraction);
1335 exponent += bits;
1336 }
1337
1338 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1339
1340 if (newPartsCount > 4)
1341 delete [] fullSignificand;
1342
1343 return lost_fraction;
1344}
1345
1346lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs) {
1347 // When the given semantics has zero, the addend here is a zero.
1348 // i.e . it belongs to the 'fcZero' category.
1349 // But when the semantics does not support zero, we need to
1350 // explicitly convey that this addend should be ignored
1351 // for multiplication.
1352 return multiplySignificand(rhs, IEEEFloat(*semantics), !semantics->hasZero);
1353}
1354
1355/* Multiply the significands of LHS and RHS to DST. */
1356lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
1357 integerPart scratch[4];
1358
1359 assert(semantics == rhs.semantics);
1360
1361 integerPart *lhsSignificand = significandParts();
1362 const integerPart *rhsSignificand = rhs.significandParts();
1363 unsigned partsCount = partCount();
1364
1365 integerPart *dividend =
1366 partsCount > 2 ? new integerPart[partsCount * 2] : scratch;
1367 integerPart *divisor = dividend + partsCount;
1368
1369 /* Copy the dividend and divisor as they will be modified in-place. */
1370 for (unsigned i = 0; i < partsCount; i++) {
1371 dividend[i] = lhsSignificand[i];
1372 divisor[i] = rhsSignificand[i];
1373 lhsSignificand[i] = 0;
1374 }
1375
1376 exponent -= rhs.exponent;
1377
1378 unsigned int precision = semantics->precision;
1379
1380 /* Normalize the divisor. */
1381 unsigned bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
1382 if (bit) {
1383 exponent += bit;
1384 APInt::tcShiftLeft(divisor, partsCount, bit);
1385 }
1386
1387 /* Normalize the dividend. */
1388 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
1389 if (bit) {
1390 exponent -= bit;
1391 APInt::tcShiftLeft(dividend, partsCount, bit);
1392 }
1393
1394 /* Ensure the dividend >= divisor initially for the loop below.
1395 Incidentally, this means that the division loop below is
1396 guaranteed to set the integer bit to one. */
1397 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
1398 exponent--;
1399 APInt::tcShiftLeft(dividend, partsCount, 1);
1400 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1401 }
1402
1403 /* Long division. */
1404 for (bit = precision; bit; bit -= 1) {
1405 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
1406 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1407 APInt::tcSetBit(lhsSignificand, bit - 1);
1408 }
1409
1410 APInt::tcShiftLeft(dividend, partsCount, 1);
1411 }
1412
1413 /* Figure out the lost fraction. */
1414 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1415
1416 lostFraction lost_fraction;
1417 if (cmp > 0)
1418 lost_fraction = lfMoreThanHalf;
1419 else if (cmp == 0)
1420 lost_fraction = lfExactlyHalf;
1421 else if (APInt::tcIsZero(dividend, partsCount))
1422 lost_fraction = lfExactlyZero;
1423 else
1424 lost_fraction = lfLessThanHalf;
1425
1426 if (partsCount > 2)
1427 delete [] dividend;
1428
1429 return lost_fraction;
1430}
1431
1432unsigned int IEEEFloat::significandMSB() const {
1433 return APInt::tcMSB(significandParts(), partCount());
1434}
1435
1436unsigned int IEEEFloat::significandLSB() const {
1437 return APInt::tcLSB(significandParts(), partCount());
1438}
1439
1440/* Note that a zero result is NOT normalized to fcZero. */
1441lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
1442 /* Our exponent should not overflow. */
1443 assert((ExponentType) (exponent + bits) >= exponent);
1444
1445 exponent += bits;
1446
1447 return shiftRight(significandParts(), partCount(), bits);
1448}
1449
1450/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1451void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
1452 assert(bits < semantics->precision ||
1453 (semantics->precision == 1 && bits <= 1));
1454
1455 if (bits) {
1456 unsigned int partsCount = partCount();
1457
1458 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1459 exponent -= bits;
1460
1461 assert(!APInt::tcIsZero(significandParts(), partsCount));
1462 }
1463}
1464
1466 assert(semantics == rhs.semantics);
1468 assert(rhs.isFiniteNonZero());
1469
1470 int compare = exponent - rhs.exponent;
1471
1472 /* If exponents are equal, do an unsigned bignum comparison of the
1473 significands. */
1474 if (compare == 0)
1475 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
1476 partCount());
1477
1478 if (compare > 0)
1479 return cmpGreaterThan;
1480 else if (compare < 0)
1481 return cmpLessThan;
1482 else
1483 return cmpEqual;
1484}
1485
1486/* Set the least significant BITS bits of a bignum, clear the
1487 rest. */
1488static void tcSetLeastSignificantBits(APInt::WordType *dst, unsigned parts,
1489 unsigned bits) {
1490 unsigned i = 0;
1491 while (bits > APInt::APINT_BITS_PER_WORD) {
1492 dst[i++] = ~(APInt::WordType)0;
1494 }
1495
1496 if (bits)
1497 dst[i++] = ~(APInt::WordType)0 >> (APInt::APINT_BITS_PER_WORD - bits);
1498
1499 while (i < parts)
1500 dst[i++] = 0;
1501}
1502
1503/* Handle overflow. Sign is preserved. We either become infinity or
1504 the largest finite number. */
1505APFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
1507 /* Infinity? */
1508 if (rounding_mode == rmNearestTiesToEven ||
1509 rounding_mode == rmNearestTiesToAway ||
1510 (rounding_mode == rmTowardPositive && !sign) ||
1511 (rounding_mode == rmTowardNegative && sign)) {
1513 makeNaN(false, sign);
1514 else
1515 category = fcInfinity;
1516 return static_cast<opStatus>(opOverflow | opInexact);
1517 }
1518 }
1519
1520 /* Otherwise we become the largest finite number. */
1521 category = fcNormal;
1522 exponent = semantics->maxExponent;
1523 tcSetLeastSignificantBits(significandParts(), partCount(),
1524 semantics->precision);
1525 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
1526 semantics->nanEncoding == fltNanEncoding::AllOnes)
1527 APInt::tcClearBit(significandParts(), 0);
1528
1529 return opInexact;
1530}
1531
1532/* Returns TRUE if, when truncating the current number, with BIT the
1533 new LSB, with the given lost fraction and rounding mode, the result
1534 would need to be rounded away from zero (i.e., by increasing the
1535 signficand). This routine must work for fcZero of both signs, and
1536 fcNormal numbers. */
1537bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1538 lostFraction lost_fraction,
1539 unsigned int bit) const {
1540 /* NaNs and infinities should not have lost fractions. */
1541 assert(isFiniteNonZero() || category == fcZero);
1542
1543 /* Current callers never pass this so we don't handle it. */
1544 assert(lost_fraction != lfExactlyZero);
1545
1546 switch (rounding_mode) {
1548 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1549
1551 if (lost_fraction == lfMoreThanHalf)
1552 return true;
1553
1554 /* Our zeroes don't have a significand to test. */
1555 if (lost_fraction == lfExactlyHalf && category != fcZero)
1556 return APInt::tcExtractBit(significandParts(), bit);
1557
1558 return false;
1559
1560 case rmTowardZero:
1561 return false;
1562
1563 case rmTowardPositive:
1564 return !sign;
1565
1566 case rmTowardNegative:
1567 return sign;
1568
1569 default:
1570 break;
1571 }
1572 llvm_unreachable("Invalid rounding mode found");
1573}
1574
1575APFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1576 lostFraction lost_fraction) {
1577 if (!isFiniteNonZero())
1578 return opOK;
1579
1580 /* Before rounding normalize the exponent of fcNormal numbers. */
1581 /* One, not zero, based MSB. */
1582 unsigned omsb = significandMSB() + 1;
1583
1584 // Only skip this `if` if the value is exactly zero.
1585 if (omsb || lost_fraction != lfExactlyZero) {
1586 /* OMSB is numbered from 1. We want to place it in the integer
1587 bit numbered PRECISION if possible, with a compensating change in
1588 the exponent. */
1589 int exponentChange = omsb - semantics->precision;
1590
1591 /* If the resulting exponent is too high, overflow according to
1592 the rounding mode. */
1593 if (exponent + exponentChange > semantics->maxExponent)
1594 return handleOverflow(rounding_mode);
1595
1596 /* Subnormal numbers have exponent minExponent, and their MSB
1597 is forced based on that. */
1598 if (exponent + exponentChange < semantics->minExponent)
1599 exponentChange = semantics->minExponent - exponent;
1600
1601 /* Shifting left is easy as we don't lose precision. */
1602 if (exponentChange < 0) {
1603 assert(lost_fraction == lfExactlyZero);
1604
1605 shiftSignificandLeft(-exponentChange);
1606
1607 return opOK;
1608 }
1609
1610 if (exponentChange > 0) {
1611 lostFraction lf;
1612
1613 /* Shift right and capture any new lost fraction. */
1614 lf = shiftSignificandRight(exponentChange);
1615
1616 lost_fraction = combineLostFractions(lf, lost_fraction);
1617
1618 /* Keep OMSB up-to-date. */
1619 if (omsb > (unsigned) exponentChange)
1620 omsb -= exponentChange;
1621 else
1622 omsb = 0;
1623 }
1624 }
1625
1626 // The all-ones values is an overflow if NaN is all ones. If NaN is
1627 // represented by negative zero, then it is a valid finite value.
1628 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
1629 semantics->nanEncoding == fltNanEncoding::AllOnes &&
1630 exponent == semantics->maxExponent && isSignificandAllOnes())
1631 return handleOverflow(rounding_mode);
1632
1633 /* Now round the number according to rounding_mode given the lost
1634 fraction. */
1635
1636 /* As specified in IEEE 754, since we do not trap we do not report
1637 underflow for exact results. */
1638 if (lost_fraction == lfExactlyZero) {
1639 /* Canonicalize zeroes. */
1640 if (omsb == 0) {
1641 category = fcZero;
1642 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
1643 sign = false;
1644 if (!semantics->hasZero)
1646 }
1647
1648 return opOK;
1649 }
1650
1651 /* Increment the significand if we're rounding away from zero. */
1652 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1653 if (omsb == 0)
1654 exponent = semantics->minExponent;
1655
1656 incrementSignificand();
1657 omsb = significandMSB() + 1;
1658
1659 /* Did the significand increment overflow? */
1660 if (omsb == (unsigned) semantics->precision + 1) {
1661 /* Renormalize by incrementing the exponent and shifting our
1662 significand right one. However if we already have the
1663 maximum exponent we overflow to infinity. */
1664 if (exponent == semantics->maxExponent)
1665 // Invoke overflow handling with a rounding mode that will guarantee
1666 // that the result gets turned into the correct infinity representation.
1667 // This is needed instead of just setting the category to infinity to
1668 // account for 8-bit floating point types that have no inf, only NaN.
1669 return handleOverflow(sign ? rmTowardNegative : rmTowardPositive);
1670
1671 shiftSignificandRight(1);
1672
1673 return opInexact;
1674 }
1675
1676 // The all-ones values is an overflow if NaN is all ones. If NaN is
1677 // represented by negative zero, then it is a valid finite value.
1678 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
1679 semantics->nanEncoding == fltNanEncoding::AllOnes &&
1680 exponent == semantics->maxExponent && isSignificandAllOnes())
1681 return handleOverflow(rounding_mode);
1682 }
1683
1684 /* The normal case - we were and are not denormal, and any
1685 significand increment above didn't overflow. */
1686 if (omsb == semantics->precision)
1687 return opInexact;
1688
1689 /* We have a non-zero denormal. */
1690 assert(omsb < semantics->precision);
1691
1692 /* Canonicalize zeroes. */
1693 if (omsb == 0) {
1694 category = fcZero;
1695 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
1696 sign = false;
1697 // This condition handles the case where the semantics
1698 // does not have zero but uses the all-zero encoding
1699 // to represent the smallest normal value.
1700 if (!semantics->hasZero)
1702 }
1703
1704 /* The fcZero case is a denormal that underflowed to zero. */
1705 return (opStatus) (opUnderflow | opInexact);
1706}
1707
1708APFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1709 bool subtract) {
1710 switch (PackCategoriesIntoKey(category, rhs.category)) {
1711 default:
1712 llvm_unreachable(nullptr);
1713
1717 assign(rhs);
1718 [[fallthrough]];
1723 if (isSignaling()) {
1724 makeQuiet();
1725 return opInvalidOp;
1726 }
1727 return rhs.isSignaling() ? opInvalidOp : opOK;
1728
1732 return opOK;
1733
1736 category = fcInfinity;
1737 sign = rhs.sign ^ subtract;
1738 return opOK;
1739
1741 assign(rhs);
1742 sign = rhs.sign ^ subtract;
1743 return opOK;
1744
1746 /* Sign depends on rounding mode; handled by caller. */
1747 return opOK;
1748
1750 /* Differently signed infinities can only be validly
1751 subtracted. */
1752 if (((sign ^ rhs.sign)!=0) != subtract) {
1753 makeNaN();
1754 return opInvalidOp;
1755 }
1756
1757 return opOK;
1758
1760 return opDivByZero;
1761 }
1762}
1763
1764/* Add or subtract two normal numbers. */
1765lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1766 bool subtract) {
1767 [[maybe_unused]] integerPart carry = 0;
1768 lostFraction lost_fraction;
1769
1770 /* Determine if the operation on the absolute values is effectively
1771 an addition or subtraction. */
1772 subtract ^= static_cast<bool>(sign ^ rhs.sign);
1773
1774 /* Are we bigger exponent-wise than the RHS? */
1775 int bits = exponent - rhs.exponent;
1776
1777 /* Subtraction is more subtle than one might naively expect. */
1778 if (subtract) {
1779 if ((bits < 0) && !semantics->hasSignedRepr)
1781 "This floating point format does not support signed values");
1782
1783 IEEEFloat temp_rhs(rhs);
1784 bool lost_fraction_is_from_rhs = false;
1785
1786 if (bits == 0)
1787 lost_fraction = lfExactlyZero;
1788 else if (bits > 0) {
1789 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1790 lost_fraction_is_from_rhs = true;
1791 shiftSignificandLeft(1);
1792 } else {
1793 lost_fraction = shiftSignificandRight(-bits - 1);
1794 temp_rhs.shiftSignificandLeft(1);
1795 }
1796
1797 // Should we reverse the subtraction.
1798 cmpResult cmp_result = compareAbsoluteValue(temp_rhs);
1799 if (cmp_result == cmpLessThan) {
1800 bool borrow =
1801 lost_fraction != lfExactlyZero && !lost_fraction_is_from_rhs;
1802 if (borrow) {
1803 // The lost fraction is being subtracted, borrow from the significand
1804 // and invert `lost_fraction`.
1805 if (lost_fraction == lfLessThanHalf)
1806 lost_fraction = lfMoreThanHalf;
1807 else if (lost_fraction == lfMoreThanHalf)
1808 lost_fraction = lfLessThanHalf;
1809 }
1810 carry = temp_rhs.subtractSignificand(*this, borrow);
1811 copySignificand(temp_rhs);
1812 sign = !sign;
1813 } else if (cmp_result == cmpGreaterThan) {
1814 bool borrow = lost_fraction != lfExactlyZero && lost_fraction_is_from_rhs;
1815 if (borrow) {
1816 // The lost fraction is being subtracted, borrow from the significand
1817 // and invert `lost_fraction`.
1818 if (lost_fraction == lfLessThanHalf)
1819 lost_fraction = lfMoreThanHalf;
1820 else if (lost_fraction == lfMoreThanHalf)
1821 lost_fraction = lfLessThanHalf;
1822 }
1823 carry = subtractSignificand(temp_rhs, borrow);
1824 } else { // cmpEqual
1825 zeroSignificand();
1826 if (lost_fraction != lfExactlyZero && lost_fraction_is_from_rhs) {
1827 // rhs is slightly larger due to the lost fraction, flip the sign.
1828 sign = !sign;
1829 }
1830 }
1831
1832 /* The code above is intended to ensure that no borrow is
1833 necessary. */
1834 assert(!carry);
1835 } else {
1836 if (bits > 0) {
1837 IEEEFloat temp_rhs(rhs);
1838
1839 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1840 carry = addSignificand(temp_rhs);
1841 } else {
1842 lost_fraction = shiftSignificandRight(-bits);
1843 carry = addSignificand(rhs);
1844 }
1845
1846 /* We have a guard bit; generating a carry cannot happen. */
1847 assert(!carry);
1848 }
1849
1850 return lost_fraction;
1851}
1852
1853APFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
1854 switch (PackCategoriesIntoKey(category, rhs.category)) {
1855 default:
1856 llvm_unreachable(nullptr);
1857
1861 assign(rhs);
1862 sign = false;
1863 [[fallthrough]];
1868 sign ^= rhs.sign; // restore the original sign
1869 if (isSignaling()) {
1870 makeQuiet();
1871 return opInvalidOp;
1872 }
1873 return rhs.isSignaling() ? opInvalidOp : opOK;
1874
1878 category = fcInfinity;
1879 return opOK;
1880
1884 category = fcZero;
1885 return opOK;
1886
1889 makeNaN();
1890 return opInvalidOp;
1891
1893 return opOK;
1894 }
1895}
1896
1897APFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
1898 switch (PackCategoriesIntoKey(category, rhs.category)) {
1899 default:
1900 llvm_unreachable(nullptr);
1901
1905 assign(rhs);
1906 sign = false;
1907 [[fallthrough]];
1912 sign ^= rhs.sign; // restore the original sign
1913 if (isSignaling()) {
1914 makeQuiet();
1915 return opInvalidOp;
1916 }
1917 return rhs.isSignaling() ? opInvalidOp : opOK;
1918
1923 return opOK;
1924
1926 category = fcZero;
1927 return opOK;
1928
1930 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly)
1931 makeNaN(false, sign);
1932 else
1933 category = fcInfinity;
1934 return opDivByZero;
1935
1938 makeNaN();
1939 return opInvalidOp;
1940
1942 return opOK;
1943 }
1944}
1945
1946APFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
1947 switch (PackCategoriesIntoKey(category, rhs.category)) {
1948 default:
1949 llvm_unreachable(nullptr);
1950
1954 assign(rhs);
1955 [[fallthrough]];
1960 if (isSignaling()) {
1961 makeQuiet();
1962 return opInvalidOp;
1963 }
1964 return rhs.isSignaling() ? opInvalidOp : opOK;
1965
1969 return opOK;
1970
1976 makeNaN();
1977 return opInvalidOp;
1978
1980 return opOK;
1981 }
1982}
1983
1984APFloat::opStatus IEEEFloat::remainderSpecials(const IEEEFloat &rhs) {
1985 switch (PackCategoriesIntoKey(category, rhs.category)) {
1986 default:
1987 llvm_unreachable(nullptr);
1988
1992 assign(rhs);
1993 [[fallthrough]];
1998 if (isSignaling()) {
1999 makeQuiet();
2000 return opInvalidOp;
2001 }
2002 return rhs.isSignaling() ? opInvalidOp : opOK;
2003
2007 return opOK;
2008
2014 makeNaN();
2015 return opInvalidOp;
2016
2018 return opDivByZero; // fake status, indicating this is not a special case
2019 }
2020}
2021
2022/* Change sign. */
2024 // With NaN-as-negative-zero, neither NaN or negative zero can change
2025 // their signs.
2026 if (semantics->nanEncoding == fltNanEncoding::NegativeZero &&
2027 (isZero() || isNaN()))
2028 return;
2029 /* Look mummy, this one's easy. */
2030 sign = !sign;
2031}
2032
2033/* Normalized addition or subtraction. */
2034APFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
2035 roundingMode rounding_mode,
2036 bool subtract) {
2037 opStatus fs = addOrSubtractSpecials(rhs, subtract);
2038
2039 /* This return code means it was not a simple case. */
2040 if (fs == opDivByZero) {
2041 lostFraction lost_fraction;
2042
2043 lost_fraction = addOrSubtractSignificand(rhs, subtract);
2044 fs = normalize(rounding_mode, lost_fraction);
2045
2046 /* Can only be zero if we lost no fraction. */
2047 assert(category != fcZero || lost_fraction == lfExactlyZero);
2048 }
2049
2050 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
2051 positive zero unless rounding to minus infinity, except that
2052 adding two like-signed zeroes gives that zero. */
2053 if (category == fcZero) {
2054 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
2055 sign = (rounding_mode == rmTowardNegative);
2056 // NaN-in-negative-zero means zeros need to be normalized to +0.
2057 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
2058 sign = false;
2059 }
2060
2061 return fs;
2062}
2063
2064/* Normalized addition. */
2066 roundingMode rounding_mode) {
2067 return addOrSubtract(rhs, rounding_mode, false);
2068}
2069
2070/* Normalized subtraction. */
2072 roundingMode rounding_mode) {
2073 return addOrSubtract(rhs, rounding_mode, true);
2074}
2075
2076/* Normalized multiply. */
2078 roundingMode rounding_mode) {
2079 sign ^= rhs.sign;
2080 opStatus fs = multiplySpecials(rhs);
2081
2082 if (isZero() && semantics->nanEncoding == fltNanEncoding::NegativeZero)
2083 sign = false;
2084 if (isFiniteNonZero()) {
2085 lostFraction lost_fraction = multiplySignificand(rhs);
2086 fs = normalize(rounding_mode, lost_fraction);
2087 if (lost_fraction != lfExactlyZero)
2088 fs = (opStatus) (fs | opInexact);
2089 }
2090
2091 return fs;
2092}
2093
2094/* Normalized divide. */
2096 roundingMode rounding_mode) {
2097 sign ^= rhs.sign;
2098 opStatus fs = divideSpecials(rhs);
2099
2100 if (isZero() && semantics->nanEncoding == fltNanEncoding::NegativeZero)
2101 sign = false;
2102 if (isFiniteNonZero()) {
2103 lostFraction lost_fraction = divideSignificand(rhs);
2104 fs = normalize(rounding_mode, lost_fraction);
2105 if (lost_fraction != lfExactlyZero)
2106 fs = (opStatus) (fs | opInexact);
2107 }
2108
2109 return fs;
2110}
2111
2112/* Normalized remainder. */
2114 unsigned int origSign = sign;
2115
2116 // First handle the special cases.
2117 opStatus fs = remainderSpecials(rhs);
2118 if (fs != opDivByZero)
2119 return fs;
2120
2121 fs = opOK;
2122
2123 // Make sure the current value is less than twice the denom. If the addition
2124 // did not succeed (an overflow has happened), which means that the finite
2125 // value we currently posses must be less than twice the denom (as we are
2126 // using the same semantics).
2127 IEEEFloat P2 = rhs;
2128 if (P2.add(rhs, rmNearestTiesToEven) == opOK) {
2129 fs = mod(P2);
2130 assert(fs == opOK);
2131 }
2132
2133 // Lets work with absolute numbers.
2134 IEEEFloat P = rhs;
2135 P.sign = false;
2136 sign = false;
2137
2138 //
2139 // To calculate the remainder we use the following scheme.
2140 //
2141 // The remainder is defained as follows:
2142 //
2143 // remainder = numer - rquot * denom = x - r * p
2144 //
2145 // Where r is the result of: x/p, rounded toward the nearest integral value
2146 // (with halfway cases rounded toward the even number).
2147 //
2148 // Currently, (after x mod 2p):
2149 // r is the number of 2p's present inside x, which is inherently, an even
2150 // number of p's.
2151 //
2152 // We may split the remaining calculation into 4 options:
2153 // - if x < 0.5p then we round to the nearest number with is 0, and are done.
2154 // - if x == 0.5p then we round to the nearest even number which is 0, and we
2155 // are done as well.
2156 // - if 0.5p < x < p then we round to nearest number which is 1, and we have
2157 // to subtract 1p at least once.
2158 // - if x >= p then we must subtract p at least once, as x must be a
2159 // remainder.
2160 //
2161 // By now, we were done, or we added 1 to r, which in turn, now an odd number.
2162 //
2163 // We can now split the remaining calculation to the following 3 options:
2164 // - if x < 0.5p then we round to the nearest number with is 0, and are done.
2165 // - if x == 0.5p then we round to the nearest even number. As r is odd, we
2166 // must round up to the next even number. so we must subtract p once more.
2167 // - if x > 0.5p (and inherently x < p) then we must round r up to the next
2168 // integral, and subtract p once more.
2169 //
2170
2171 // Extend the semantics to prevent an overflow/underflow or inexact result.
2172 bool losesInfo;
2173 fltSemantics extendedSemantics = *semantics;
2174 extendedSemantics.maxExponent++;
2175 extendedSemantics.minExponent--;
2176 extendedSemantics.precision += 2;
2177
2178 IEEEFloat VEx = *this;
2179 fs = VEx.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2180 assert(fs == opOK && !losesInfo);
2181 IEEEFloat PEx = P;
2182 fs = PEx.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2183 assert(fs == opOK && !losesInfo);
2184
2185 // It is simpler to work with 2x instead of 0.5p, and we do not need to lose
2186 // any fraction.
2187 fs = VEx.add(VEx, rmNearestTiesToEven);
2188 assert(fs == opOK);
2189
2190 if (VEx.compare(PEx) == cmpGreaterThan) {
2192 assert(fs == opOK);
2193
2194 // Make VEx = this.add(this), but because we have different semantics, we do
2195 // not want to `convert` again, so we just subtract PEx twice (which equals
2196 // to the desired value).
2197 fs = VEx.subtract(PEx, rmNearestTiesToEven);
2198 assert(fs == opOK);
2199 fs = VEx.subtract(PEx, rmNearestTiesToEven);
2200 assert(fs == opOK);
2201
2202 cmpResult result = VEx.compare(PEx);
2203 if (result == cmpGreaterThan || result == cmpEqual) {
2205 assert(fs == opOK);
2206 }
2207 }
2208
2209 if (isZero()) {
2210 sign = origSign; // IEEE754 requires this
2211 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
2212 // But some 8-bit floats only have positive 0.
2213 sign = false;
2214 } else {
2215 sign ^= origSign;
2216 }
2217 return fs;
2218}
2219
2220/* Normalized llvm frem (C fmod). */
2222 opStatus fs = modSpecials(rhs);
2223 unsigned int origSign = sign;
2224
2225 while (isFiniteNonZero() && rhs.isFiniteNonZero() &&
2227 int Exp = ilogb(*this) - ilogb(rhs);
2228 IEEEFloat V = scalbn(rhs, Exp, rmNearestTiesToEven);
2229 // V can overflow to NaN with fltNonfiniteBehavior::NanOnly, so explicitly
2230 // check for it.
2231 if (V.isNaN() || compareAbsoluteValue(V) == cmpLessThan)
2232 V = scalbn(rhs, Exp - 1, rmNearestTiesToEven);
2233 V.sign = sign;
2234
2236
2237 // When the semantics supports zero, this loop's
2238 // exit-condition is handled by the 'isFiniteNonZero'
2239 // category check above. However, when the semantics
2240 // does not have 'fcZero' and we have reached the
2241 // minimum possible value, (and any further subtract
2242 // will underflow to the same value) explicitly
2243 // provide an exit-path here.
2244 if (!semantics->hasZero && this->isSmallest())
2245 break;
2246
2247 assert(fs==opOK);
2248 }
2249 if (isZero()) {
2250 sign = origSign; // fmod requires this
2251 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
2252 sign = false;
2253 }
2254 return fs;
2255}
2256
2257/* Normalized fused-multiply-add. */
2259 const IEEEFloat &addend,
2260 roundingMode rounding_mode) {
2261 opStatus fs;
2262
2263 /* Post-multiplication sign, before addition. */
2264 sign ^= multiplicand.sign;
2265
2266 /* If and only if all arguments are normal do we need to do an
2267 extended-precision calculation. */
2268 if (isFiniteNonZero() &&
2269 multiplicand.isFiniteNonZero() &&
2270 addend.isFinite()) {
2271 lostFraction lost_fraction;
2272
2273 lost_fraction = multiplySignificand(multiplicand, addend);
2274 fs = normalize(rounding_mode, lost_fraction);
2275 if (lost_fraction != lfExactlyZero)
2276 fs = (opStatus) (fs | opInexact);
2277
2278 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
2279 positive zero unless rounding to minus infinity, except that
2280 adding two like-signed zeroes gives that zero. */
2281 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign) {
2282 sign = (rounding_mode == rmTowardNegative);
2283 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
2284 sign = false;
2285 }
2286 } else {
2287 fs = multiplySpecials(multiplicand);
2288
2289 /* FS can only be opOK or opInvalidOp. There is no more work
2290 to do in the latter case. The IEEE-754R standard says it is
2291 implementation-defined in this case whether, if ADDEND is a
2292 quiet NaN, we raise invalid op; this implementation does so.
2293
2294 If we need to do the addition we can do so with normal
2295 precision. */
2296 if (fs == opOK)
2297 fs = addOrSubtract(addend, rounding_mode, false);
2298 }
2299
2300 return fs;
2301}
2302
2303/* Rounding-mode correct round to integral value. */
2305 if (isInfinity())
2306 // [IEEE Std 754-2008 6.1]:
2307 // The behavior of infinity in floating-point arithmetic is derived from the
2308 // limiting cases of real arithmetic with operands of arbitrarily
2309 // large magnitude, when such a limit exists.
2310 // ...
2311 // Operations on infinite operands are usually exact and therefore signal no
2312 // exceptions ...
2313 return opOK;
2314
2315 if (isNaN()) {
2316 if (isSignaling()) {
2317 // [IEEE Std 754-2008 6.2]:
2318 // Under default exception handling, any operation signaling an invalid
2319 // operation exception and for which a floating-point result is to be
2320 // delivered shall deliver a quiet NaN.
2321 makeQuiet();
2322 // [IEEE Std 754-2008 6.2]:
2323 // Signaling NaNs shall be reserved operands that, under default exception
2324 // handling, signal the invalid operation exception(see 7.2) for every
2325 // general-computational and signaling-computational operation except for
2326 // the conversions described in 5.12.
2327 return opInvalidOp;
2328 } else {
2329 // [IEEE Std 754-2008 6.2]:
2330 // For an operation with quiet NaN inputs, other than maximum and minimum
2331 // operations, if a floating-point result is to be delivered the result
2332 // shall be a quiet NaN which should be one of the input NaNs.
2333 // ...
2334 // Every general-computational and quiet-computational operation involving
2335 // one or more input NaNs, none of them signaling, shall signal no
2336 // exception, except fusedMultiplyAdd might signal the invalid operation
2337 // exception(see 7.2).
2338 return opOK;
2339 }
2340 }
2341
2342 if (isZero()) {
2343 // [IEEE Std 754-2008 6.3]:
2344 // ... the sign of the result of conversions, the quantize operation, the
2345 // roundToIntegral operations, and the roundToIntegralExact(see 5.3.1) is
2346 // the sign of the first or only operand.
2347 return opOK;
2348 }
2349
2350 // If the exponent is large enough, we know that this value is already
2351 // integral, and the arithmetic below would potentially cause it to saturate
2352 // to +/-Inf. Bail out early instead.
2353 if (exponent + 1 >= (int)APFloat::semanticsPrecision(*semantics))
2354 return opOK;
2355
2356 // The algorithm here is quite simple: we add 2^(p-1), where p is the
2357 // precision of our format, and then subtract it back off again. The choice
2358 // of rounding modes for the addition/subtraction determines the rounding mode
2359 // for our integral rounding as well.
2360 // NOTE: When the input value is negative, we do subtraction followed by
2361 // addition instead.
2362 APInt IntegerConstant(NextPowerOf2(APFloat::semanticsPrecision(*semantics)),
2363 1);
2364 IntegerConstant <<= APFloat::semanticsPrecision(*semantics) - 1;
2365 IEEEFloat MagicConstant(*semantics);
2366 opStatus fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
2368 assert(fs == opOK);
2369 MagicConstant.sign = sign;
2370
2371 // Preserve the input sign so that we can handle the case of zero result
2372 // correctly.
2373 bool inputSign = isNegative();
2374
2375 fs = add(MagicConstant, rounding_mode);
2376
2377 // Current value and 'MagicConstant' are both integers, so the result of the
2378 // subtraction is always exact according to Sterbenz' lemma.
2379 subtract(MagicConstant, rounding_mode);
2380
2381 // Restore the input sign.
2382 if (inputSign != isNegative())
2383 changeSign();
2384
2385 return fs;
2386}
2387
2388/* Comparison requires normalized numbers. */
2390 assert(semantics == rhs.semantics);
2391
2392 switch (PackCategoriesIntoKey(category, rhs.category)) {
2393 default:
2394 llvm_unreachable(nullptr);
2395
2403 return cmpUnordered;
2404
2408 if (sign)
2409 return cmpLessThan;
2410 else
2411 return cmpGreaterThan;
2412
2416 if (rhs.sign)
2417 return cmpGreaterThan;
2418 else
2419 return cmpLessThan;
2420
2422 if (sign == rhs.sign)
2423 return cmpEqual;
2424 else if (sign)
2425 return cmpLessThan;
2426 else
2427 return cmpGreaterThan;
2428
2430 return cmpEqual;
2431
2433 break;
2434 }
2435
2436 cmpResult result;
2437 /* Two normal numbers. Do they have the same sign? */
2438 if (sign != rhs.sign) {
2439 if (sign)
2440 result = cmpLessThan;
2441 else
2442 result = cmpGreaterThan;
2443 } else {
2444 /* Compare absolute values; invert result if negative. */
2445 result = compareAbsoluteValue(rhs);
2446
2447 if (sign) {
2448 if (result == cmpLessThan)
2449 result = cmpGreaterThan;
2450 else if (result == cmpGreaterThan)
2451 result = cmpLessThan;
2452 }
2453 }
2454
2455 return result;
2456}
2457
2458/// IEEEFloat::convert - convert a value of one floating point type to another.
2459/// The return value corresponds to the IEEE754 exceptions. *losesInfo
2460/// records whether the transformation lost information, i.e. whether
2461/// converting the result back to the original type will produce the
2462/// original value (this is almost the same as return value==fsOK, but there
2463/// are edge cases where this is not so).
2464
2466 roundingMode rounding_mode,
2467 bool *losesInfo) {
2468 opStatus fs;
2469 const fltSemantics &fromSemantics = *semantics;
2470 bool is_signaling = isSignaling();
2471
2473 unsigned newPartCount = partCountForBits(toSemantics.precision + 1);
2474 unsigned oldPartCount = partCount();
2475 int shift = toSemantics.precision - fromSemantics.precision;
2476
2477 bool X86SpecialNan = false;
2478 if (&fromSemantics == &APFloatBase::semX87DoubleExtended &&
2479 &toSemantics != &APFloatBase::semX87DoubleExtended && category == fcNaN &&
2480 (!(*significandParts() & 0x8000000000000000ULL) ||
2481 !(*significandParts() & 0x4000000000000000ULL))) {
2482 // x86 has some unusual NaNs which cannot be represented in any other
2483 // format; note them here.
2484 X86SpecialNan = true;
2485 }
2486
2487 // If this is a truncation of a denormal number, and the target semantics
2488 // has larger exponent range than the source semantics (this can happen
2489 // when truncating from PowerPC double-double to double format), the
2490 // right shift could lose result mantissa bits. Adjust exponent instead
2491 // of performing excessive shift.
2492 // Also do a similar trick in case shifting denormal would produce zero
2493 // significand as this case isn't handled correctly by normalize.
2494 if (shift < 0 && isFiniteNonZero()) {
2495 int omsb = significandMSB() + 1;
2496 int exponentChange = omsb - fromSemantics.precision;
2497 if (exponent + exponentChange < toSemantics.minExponent)
2498 exponentChange = toSemantics.minExponent - exponent;
2499 exponentChange = std::max(exponentChange, shift);
2500 if (exponentChange < 0) {
2501 shift -= exponentChange;
2502 exponent += exponentChange;
2503 } else if (omsb <= -shift) {
2504 exponentChange = omsb + shift - 1; // leave at least one bit set
2505 shift -= exponentChange;
2506 exponent += exponentChange;
2507 }
2508 }
2509
2510 // If this is a truncation, perform the shift before we narrow the storage.
2511 if (shift < 0 && (isFiniteNonZero() ||
2512 (category == fcNaN && semantics->nonFiniteBehavior !=
2514 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
2515
2516 // Fix the storage so it can hold to new value.
2517 if (newPartCount > oldPartCount) {
2518 // The new type requires more storage; make it available.
2519 integerPart *newParts;
2520 newParts = new integerPart[newPartCount];
2521 APInt::tcSet(newParts, 0, newPartCount);
2522 if (isFiniteNonZero() || category==fcNaN)
2523 APInt::tcAssign(newParts, significandParts(), oldPartCount);
2524 freeSignificand();
2525 significand.parts = newParts;
2526 } else if (newPartCount == 1 && oldPartCount != 1) {
2527 // Switch to built-in storage for a single part.
2528 integerPart newPart = 0;
2529 if (isFiniteNonZero() || category==fcNaN)
2530 newPart = significandParts()[0];
2531 freeSignificand();
2532 significand.part = newPart;
2533 }
2534
2535 // Now that we have the right storage, switch the semantics.
2536 semantics = &toSemantics;
2537
2538 // If this is an extension, perform the shift now that the storage is
2539 // available.
2540 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
2541 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2542
2543 if (isFiniteNonZero()) {
2544 fs = normalize(rounding_mode, lostFraction);
2545 *losesInfo = (fs != opOK);
2546 } else if (category == fcNaN) {
2547 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
2548 *losesInfo =
2550 makeNaN(false, sign);
2551 return is_signaling ? opInvalidOp : opOK;
2552 }
2553
2554 // If NaN is negative zero, we need to create a new NaN to avoid converting
2555 // NaN to -Inf.
2556 if (fromSemantics.nanEncoding == fltNanEncoding::NegativeZero &&
2557 semantics->nanEncoding != fltNanEncoding::NegativeZero)
2558 makeNaN(false, false);
2559
2560 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
2561
2562 // For x87 extended precision, we want to make a NaN, not a special NaN if
2563 // the input wasn't special either.
2564 if (!X86SpecialNan && semantics == &APFloatBase::semX87DoubleExtended)
2565 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2566
2567 // Convert of sNaN creates qNaN and raises an exception (invalid op).
2568 // This also guarantees that a sNaN does not become Inf on a truncation
2569 // that loses all payload bits.
2570 if (is_signaling) {
2571 makeQuiet();
2572 fs = opInvalidOp;
2573 } else {
2574 fs = opOK;
2575 }
2576 } else if (category == fcInfinity &&
2577 semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
2578 makeNaN(false, sign);
2579 *losesInfo = true;
2580 fs = opInexact;
2581 } else if (category == fcZero &&
2582 semantics->nanEncoding == fltNanEncoding::NegativeZero) {
2583 // Negative zero loses info, but positive zero doesn't.
2584 *losesInfo =
2585 fromSemantics.nanEncoding != fltNanEncoding::NegativeZero && sign;
2586 fs = *losesInfo ? opInexact : opOK;
2587 // NaN is negative zero means -0 -> +0, which can lose information
2588 sign = false;
2589 } else {
2590 *losesInfo = false;
2591 fs = opOK;
2592 }
2593
2594 if (category == fcZero && !semantics->hasZero)
2596 return fs;
2597}
2598
2599/* Convert a floating point number to an integer according to the
2600 rounding mode. If the rounded integer value is out of range this
2601 returns an invalid operation exception and the contents of the
2602 destination parts are unspecified. If the rounded value is in
2603 range but the floating point number is not the exact integer, the C
2604 standard doesn't require an inexact exception to be raised. IEEE
2605 854 does require it so we do that.
2606
2607 Note that for conversions to integer type the C standard requires
2608 round-to-zero to always be used. */
2609APFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
2610 MutableArrayRef<integerPart> parts, unsigned int width, bool isSigned,
2611 roundingMode rounding_mode, bool *isExact) const {
2612 *isExact = false;
2613
2614 /* Handle the three special cases first. */
2615 if (category == fcInfinity || category == fcNaN)
2616 return opInvalidOp;
2617
2618 unsigned dstPartsCount = partCountForBits(width);
2619 assert(dstPartsCount <= parts.size() && "Integer too big");
2620
2621 if (category == fcZero) {
2622 APInt::tcSet(parts.data(), 0, dstPartsCount);
2623 // Negative zero can't be represented as an int.
2624 *isExact = !sign;
2625 return opOK;
2626 }
2627
2628 const integerPart *src = significandParts();
2629
2630 unsigned truncatedBits;
2631 /* Step 1: place our absolute value, with any fraction truncated, in
2632 the destination. */
2633 if (exponent < 0) {
2634 /* Our absolute value is less than one; truncate everything. */
2635 APInt::tcSet(parts.data(), 0, dstPartsCount);
2636 /* For exponent -1 the integer bit represents .5, look at that.
2637 For smaller exponents leftmost truncated bit is 0. */
2638 truncatedBits = semantics->precision -1U - exponent;
2639 } else {
2640 /* We want the most significant (exponent + 1) bits; the rest are
2641 truncated. */
2642 unsigned int bits = exponent + 1U;
2643
2644 /* Hopelessly large in magnitude? */
2645 if (bits > width)
2646 return opInvalidOp;
2647
2648 if (bits < semantics->precision) {
2649 /* We truncate (semantics->precision - bits) bits. */
2650 truncatedBits = semantics->precision - bits;
2651 APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits);
2652 } else {
2653 /* We want at least as many bits as are available. */
2654 APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision,
2655 0);
2656 APInt::tcShiftLeft(parts.data(), dstPartsCount,
2657 bits - semantics->precision);
2658 truncatedBits = 0;
2659 }
2660 }
2661
2662 /* Step 2: work out any lost fraction, and increment the absolute
2663 value if we would round away from zero. */
2664 lostFraction lost_fraction;
2665 if (truncatedBits) {
2666 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2667 truncatedBits);
2668 if (lost_fraction != lfExactlyZero &&
2669 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
2670 if (APInt::tcIncrement(parts.data(), dstPartsCount))
2671 return opInvalidOp; /* Overflow. */
2672 }
2673 } else {
2674 lost_fraction = lfExactlyZero;
2675 }
2676
2677 /* Step 3: check if we fit in the destination. */
2678 unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1;
2679
2680 if (sign) {
2681 if (!isSigned) {
2682 /* Negative numbers cannot be represented as unsigned. */
2683 if (omsb != 0)
2684 return opInvalidOp;
2685 } else {
2686 /* It takes omsb bits to represent the unsigned integer value.
2687 We lose a bit for the sign, but care is needed as the
2688 maximally negative integer is a special case. */
2689 if (omsb == width &&
2690 APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb)
2691 return opInvalidOp;
2692
2693 /* This case can happen because of rounding. */
2694 if (omsb > width)
2695 return opInvalidOp;
2696 }
2697
2698 APInt::tcNegate (parts.data(), dstPartsCount);
2699 } else {
2700 if (omsb >= width + !isSigned)
2701 return opInvalidOp;
2702 }
2703
2704 if (lost_fraction == lfExactlyZero) {
2705 *isExact = true;
2706 return opOK;
2707 }
2708 return opInexact;
2709}
2710
2711/* Same as convertToSignExtendedInteger, except we provide
2712 deterministic values in case of an invalid operation exception,
2713 namely zero for NaNs and the minimal or maximal value respectively
2714 for underflow or overflow.
2715 The *isExact output tells whether the result is exact, in the sense
2716 that converting it back to the original floating point type produces
2717 the original value. This is almost equivalent to result==opOK,
2718 except for negative zeroes.
2719*/
2722 unsigned int width, bool isSigned,
2723 roundingMode rounding_mode, bool *isExact) const {
2724 opStatus fs = convertToSignExtendedInteger(parts, width, isSigned,
2725 rounding_mode, isExact);
2726
2727 if (fs == opInvalidOp) {
2728 unsigned int bits, dstPartsCount;
2729
2730 dstPartsCount = partCountForBits(width);
2731 assert(dstPartsCount <= parts.size() && "Integer too big");
2732
2733 if (category == fcNaN)
2734 bits = 0;
2735 else if (sign)
2736 bits = isSigned;
2737 else
2738 bits = width - isSigned;
2739
2740 tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits);
2741 if (sign && isSigned)
2742 APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1);
2743 }
2744
2745 return fs;
2746}
2747
2748/* Convert an unsigned integer SRC to a floating point number,
2749 rounding according to ROUNDING_MODE. The sign of the floating
2750 point number is not modified. */
2751APFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2752 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
2753 category = fcNormal;
2754 unsigned omsb = APInt::tcMSB(src, srcCount) + 1;
2755 integerPart *dst = significandParts();
2756 unsigned dstCount = partCount();
2757 unsigned precision = semantics->precision;
2758
2759 /* We want the most significant PRECISION bits of SRC. There may not
2760 be that many; extract what we can. */
2761 lostFraction lost_fraction;
2762 if (precision <= omsb) {
2763 exponent = omsb - 1;
2764 lost_fraction = lostFractionThroughTruncation(src, srcCount,
2765 omsb - precision);
2766 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2767 } else {
2768 exponent = precision - 1;
2769 lost_fraction = lfExactlyZero;
2770 APInt::tcExtract(dst, dstCount, src, omsb, 0);
2771 }
2772
2773 return normalize(rounding_mode, lost_fraction);
2774}
2775
2777 roundingMode rounding_mode) {
2778 unsigned int partCount = Val.getNumWords();
2779 APInt api = Val;
2780
2781 sign = false;
2782 if (isSigned && api.isNegative()) {
2783 sign = true;
2784 api = -api;
2785 }
2786
2787 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2788}
2789
2791IEEEFloat::convertFromHexadecimalString(StringRef s,
2792 roundingMode rounding_mode) {
2793 lostFraction lost_fraction = lfExactlyZero;
2794
2795 category = fcNormal;
2796 zeroSignificand();
2797 exponent = 0;
2798
2799 integerPart *significand = significandParts();
2800 unsigned partsCount = partCount();
2801 unsigned bitPos = partsCount * integerPartWidth;
2802 bool computedTrailingFraction = false;
2803
2804 // Skip leading zeroes and any (hexa)decimal point.
2805 StringRef::iterator begin = s.begin();
2806 StringRef::iterator end = s.end();
2808 auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot);
2809 if (!PtrOrErr)
2810 return PtrOrErr.takeError();
2811 StringRef::iterator p = *PtrOrErr;
2812 StringRef::iterator firstSignificantDigit = p;
2813
2814 while (p != end) {
2815 integerPart hex_value;
2816
2817 if (*p == '.') {
2818 if (dot != end)
2819 return createError("String contains multiple dots");
2820 dot = p++;
2821 continue;
2822 }
2823
2824 hex_value = hexDigitValue(*p);
2825 if (hex_value == UINT_MAX)
2826 break;
2827
2828 p++;
2829
2830 // Store the number while we have space.
2831 if (bitPos) {
2832 bitPos -= 4;
2833 hex_value <<= bitPos % integerPartWidth;
2834 significand[bitPos / integerPartWidth] |= hex_value;
2835 } else if (!computedTrailingFraction) {
2836 auto FractOrErr = trailingHexadecimalFraction(p, end, hex_value);
2837 if (!FractOrErr)
2838 return FractOrErr.takeError();
2839 lost_fraction = *FractOrErr;
2840 computedTrailingFraction = true;
2841 }
2842 }
2843
2844 /* Hex floats require an exponent but not a hexadecimal point. */
2845 if (p == end)
2846 return createError("Hex strings require an exponent");
2847 if (*p != 'p' && *p != 'P')
2848 return createError("Invalid character in significand");
2849 if (p == begin)
2850 return createError("Significand has no digits");
2851 if (dot != end && p - begin == 1)
2852 return createError("Significand has no digits");
2853
2854 /* Ignore the exponent if we are zero. */
2855 if (p != firstSignificantDigit) {
2856 int expAdjustment;
2857
2858 /* Implicit hexadecimal point? */
2859 if (dot == end)
2860 dot = p;
2861
2862 /* Calculate the exponent adjustment implicit in the number of
2863 significant digits. */
2864 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
2865 if (expAdjustment < 0)
2866 expAdjustment++;
2867 expAdjustment = expAdjustment * 4 - 1;
2868
2869 /* Adjust for writing the significand starting at the most
2870 significant nibble. */
2871 expAdjustment += semantics->precision;
2872 expAdjustment -= partsCount * integerPartWidth;
2873
2874 /* Adjust for the given exponent. */
2875 auto ExpOrErr = totalExponent(p + 1, end, expAdjustment);
2876 if (!ExpOrErr)
2877 return ExpOrErr.takeError();
2878 exponent = *ExpOrErr;
2879 }
2880
2881 return normalize(rounding_mode, lost_fraction);
2882}
2883
2885IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2886 unsigned sigPartCount, int exp,
2887 roundingMode rounding_mode) {
2888 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
2890
2891 bool isNearest = rounding_mode == rmNearestTiesToEven ||
2892 rounding_mode == rmNearestTiesToAway;
2893
2894 unsigned parts = partCountForBits(semantics->precision + 11);
2895
2896 /* Calculate pow(5, abs(exp)). */
2897 unsigned pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp : -exp);
2898
2899 for (;; parts *= 2) {
2900 unsigned int excessPrecision, truncatedBits;
2901
2902 calcSemantics.precision = parts * integerPartWidth - 1;
2903 excessPrecision = calcSemantics.precision - semantics->precision;
2904 truncatedBits = excessPrecision;
2905
2906 IEEEFloat decSig(calcSemantics, uninitialized);
2907 decSig.makeZero(sign);
2908 IEEEFloat pow5(calcSemantics);
2909
2910 opStatus sigStatus = decSig.convertFromUnsignedParts(
2911 decSigParts, sigPartCount, rmNearestTiesToEven);
2912 opStatus powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2914 /* Add exp, as 10^n = 5^n * 2^n. */
2915 decSig.exponent += exp;
2916
2917 lostFraction calcLostFraction;
2918 integerPart HUerr, HUdistance;
2919 unsigned int powHUerr;
2920
2921 if (exp >= 0) {
2922 /* multiplySignificand leaves the precision-th bit set to 1. */
2923 calcLostFraction = decSig.multiplySignificand(pow5);
2924 powHUerr = powStatus != opOK;
2925 } else {
2926 calcLostFraction = decSig.divideSignificand(pow5);
2927 /* Denormal numbers have less precision. */
2928 if (decSig.exponent < semantics->minExponent) {
2929 excessPrecision += (semantics->minExponent - decSig.exponent);
2930 truncatedBits = excessPrecision;
2931 excessPrecision = std::min(excessPrecision, calcSemantics.precision);
2932 }
2933 /* Extra half-ulp lost in reciprocal of exponent. */
2934 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
2935 }
2936
2937 /* Both multiplySignificand and divideSignificand return the
2938 result with the integer bit set. */
2940 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
2941
2942 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2943 powHUerr);
2944 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2945 excessPrecision, isNearest);
2946
2947 /* Are we guaranteed to round correctly if we truncate? */
2948 if (HUdistance >= HUerr) {
2949 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2950 calcSemantics.precision - excessPrecision,
2951 excessPrecision);
2952 /* Take the exponent of decSig. If we tcExtract-ed less bits
2953 above we must adjust our exponent to compensate for the
2954 implicit right shift. */
2955 exponent = (decSig.exponent + semantics->precision
2956 - (calcSemantics.precision - excessPrecision));
2957 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2958 decSig.partCount(),
2959 truncatedBits);
2960 return static_cast<opStatus>(normalize(rounding_mode, calcLostFraction) |
2961 ((sigStatus | powStatus) & opInexact));
2962 }
2963 }
2964}
2965
2966Expected<APFloat::opStatus>
2967IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
2968 decimalInfo D;
2969 opStatus fs;
2970
2971 /* Scan the text. */
2972 StringRef::iterator p = str.begin();
2973 if (Error Err = interpretDecimal(p, str.end(), &D))
2974 return std::move(Err);
2975
2976 /* Handle the quick cases. First the case of no significant digits,
2977 i.e. zero, and then exponents that are obviously too large or too
2978 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2979 definitely overflows if
2980
2981 (exp - 1) * L >= maxExponent
2982
2983 and definitely underflows to zero where
2984
2985 (exp + 1) * L <= minExponent - precision
2986
2987 With integer arithmetic the tightest bounds for L are
2988
2989 93/28 < L < 196/59 [ numerator <= 256 ]
2990 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2991 */
2992
2993 // Test if we have a zero number allowing for strings with no null terminators
2994 // and zero decimals with non-zero exponents.
2995 //
2996 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2997 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2998 // be at most one dot. On the other hand, if we have a zero with a non-zero
2999 // exponent, then we know that D.firstSigDigit will be non-numeric.
3000 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
3001 category = fcZero;
3002 fs = opOK;
3003 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
3004 sign = false;
3005 if (!semantics->hasZero)
3007
3008 /* Check whether the normalized exponent is high enough to overflow
3009 max during the log-rebasing in the max-exponent check below. */
3010 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
3011 fs = handleOverflow(rounding_mode);
3012
3013 /* If it wasn't, then it also wasn't high enough to overflow max
3014 during the log-rebasing in the min-exponent check. Check that it
3015 won't overflow min in either check, then perform the min-exponent
3016 check. */
3017 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
3018 (D.normalizedExponent + 1) * 28738 <=
3019 8651 * (semantics->minExponent - (int) semantics->precision)) {
3020 /* Underflow to zero and round. */
3021 category = fcNormal;
3022 zeroSignificand();
3023 fs = normalize(rounding_mode, lfLessThanHalf);
3024
3025 /* We can finally safely perform the max-exponent check. */
3026 } else if ((D.normalizedExponent - 1) * 42039
3027 >= 12655 * semantics->maxExponent) {
3028 /* Overflow and round. */
3029 fs = handleOverflow(rounding_mode);
3030 } else {
3031 integerPart *decSignificand;
3032 unsigned int partCount;
3033
3034 /* A tight upper bound on number of bits required to hold an
3035 N-digit decimal integer is N * 196 / 59. Allocate enough space
3036 to hold the full significand, and an extra part required by
3037 tcMultiplyPart. */
3038 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
3039 partCount = partCountForBits(1 + 196 * partCount / 59);
3040 decSignificand = new integerPart[partCount + 1];
3041 partCount = 0;
3042
3043 /* Convert to binary efficiently - we do almost all multiplication
3044 in an integerPart. When this would overflow do we do a single
3045 bignum multiplication, and then revert again to multiplication
3046 in an integerPart. */
3047 do {
3048 integerPart decValue, val, multiplier;
3049
3050 val = 0;
3051 multiplier = 1;
3052
3053 do {
3054 if (*p == '.') {
3055 p++;
3056 if (p == str.end()) {
3057 break;
3058 }
3059 }
3060 decValue = decDigitValue(*p++);
3061 if (decValue >= 10U) {
3062 delete[] decSignificand;
3063 return createError("Invalid character in significand");
3064 }
3065 multiplier *= 10;
3066 val = val * 10 + decValue;
3067 /* The maximum number that can be multiplied by ten with any
3068 digit added without overflowing an integerPart. */
3069 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
3070
3071 /* Multiply out the current part. */
3072 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
3073 partCount, partCount + 1, false);
3074
3075 /* If we used another part (likely but not guaranteed), increase
3076 the count. */
3077 if (decSignificand[partCount])
3078 partCount++;
3079 } while (p <= D.lastSigDigit);
3080
3081 category = fcNormal;
3082 fs = roundSignificandWithExponent(decSignificand, partCount,
3083 D.exponent, rounding_mode);
3084
3085 delete [] decSignificand;
3086 }
3087
3088 return fs;
3089}
3090
3091bool IEEEFloat::convertFromStringSpecials(StringRef str) {
3092 const size_t MIN_NAME_SIZE = 3;
3093
3094 if (str.size() < MIN_NAME_SIZE)
3095 return false;
3096
3097 if (str == "inf" || str == "INFINITY" || str == "+Inf" || str == "+inf") {
3098 makeInf(false);
3099 return true;
3100 }
3101
3102 bool IsNegative = str.consume_front("-");
3103 if (IsNegative) {
3104 if (str.size() < MIN_NAME_SIZE)
3105 return false;
3106
3107 if (str == "inf" || str == "INFINITY" || str == "Inf") {
3108 makeInf(true);
3109 return true;
3110 }
3111 }
3112
3113 // If we have a 's' (or 'S') prefix, then this is a Signaling NaN.
3114 bool IsSignaling = str.consume_front_insensitive("s");
3115 if (IsSignaling) {
3116 if (str.size() < MIN_NAME_SIZE)
3117 return false;
3118 }
3119
3120 if (str.consume_front("nan") || str.consume_front("NaN")) {
3121 // A NaN without payload.
3122 if (str.empty()) {
3123 makeNaN(IsSignaling, IsNegative);
3124 return true;
3125 }
3126
3127 // Allow the payload to be inside parentheses.
3128 if (str.front() == '(') {
3129 // Parentheses should be balanced (and not empty).
3130 if (str.size() <= 2 || str.back() != ')')
3131 return false;
3132
3133 str = str.slice(1, str.size() - 1);
3134 }
3135
3136 // Determine the payload number's radix.
3137 unsigned Radix = 10;
3138 if (str[0] == '0') {
3139 if (str.size() > 1 && tolower(str[1]) == 'x') {
3140 str = str.drop_front(2);
3141 Radix = 16;
3142 } else {
3143 Radix = 8;
3144 }
3145 }
3146
3147 // Parse the payload and make the NaN.
3148 APInt Payload;
3149 if (!str.getAsInteger(Radix, Payload)) {
3150 makeNaN(IsSignaling, IsNegative, &Payload);
3151 return true;
3152 }
3153 }
3154
3155 return false;
3156}
3157
3158Expected<APFloat::opStatus>
3160 if (str.empty())
3161 return createError("Invalid string length");
3162
3163 // Handle special cases.
3164 if (convertFromStringSpecials(str))
3165 return opOK;
3166
3167 /* Handle a leading minus sign. */
3168 StringRef::iterator p = str.begin();
3169 size_t slen = str.size();
3170 sign = *p == '-' ? 1 : 0;
3171 if (sign && !semantics->hasSignedRepr)
3173 "This floating point format does not support signed values");
3174
3175 if (*p == '-' || *p == '+') {
3176 p++;
3177 slen--;
3178 if (!slen)
3179 return createError("String has no digits");
3180 }
3181
3182 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3183 if (slen == 2)
3184 return createError("Invalid string");
3185 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
3186 rounding_mode);
3187 }
3188
3189 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
3190}
3191
3192/* Write out a hexadecimal representation of the floating point value
3193 to DST, which must be of sufficient size, in the C99 form
3194 [-]0xh.hhhhp[+-]d. Return the number of characters written,
3195 excluding the terminating NUL.
3196
3197 If UPPERCASE, the output is in upper case, otherwise in lower case.
3198
3199 HEXDIGITS digits appear altogether, rounding the value if
3200 necessary. If HEXDIGITS is 0, the minimal precision to display the
3201 number precisely is used instead. If nothing would appear after
3202 the decimal point it is suppressed.
3203
3204 The decimal exponent is always printed and has at least one digit.
3205 Zero values display an exponent of zero. Infinities and NaNs
3206 appear as "infinity" or "nan" respectively.
3207
3208 The above rules are as specified by C99. There is ambiguity about
3209 what the leading hexadecimal digit should be. This implementation
3210 uses whatever is necessary so that the exponent is displayed as
3211 stored. This implies the exponent will fall within the IEEE format
3212 range, and the leading hexadecimal digit will be 0 (for denormals),
3213 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
3214 any other digits zero).
3215*/
3216unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
3217 bool upperCase,
3218 roundingMode rounding_mode) const {
3219 char *p = dst;
3220 if (sign)
3221 *dst++ = '-';
3222
3223 switch (category) {
3224 case fcInfinity:
3225 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
3226 dst += sizeof infinityL - 1;
3227 break;
3228
3229 case fcNaN:
3230 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
3231 dst += sizeof NaNU - 1;
3232 break;
3233
3234 case fcZero:
3235 *dst++ = '0';
3236 *dst++ = upperCase ? 'X': 'x';
3237 *dst++ = '0';
3238 if (hexDigits > 1) {
3239 *dst++ = '.';
3240 memset (dst, '0', hexDigits - 1);
3241 dst += hexDigits - 1;
3242 }
3243 *dst++ = upperCase ? 'P': 'p';
3244 *dst++ = '0';
3245 break;
3246
3247 case fcNormal:
3248 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
3249 break;
3250 }
3251
3252 *dst = 0;
3253
3254 return static_cast<unsigned int>(dst - p);
3255}
3256
3257/* Does the hard work of outputting the correctly rounded hexadecimal
3258 form of a normal floating point number with the specified number of
3259 hexadecimal digits. If HEXDIGITS is zero the minimum number of
3260 digits necessary to print the value precisely is output. */
3261char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
3262 bool upperCase,
3263 roundingMode rounding_mode) const {
3264 *dst++ = '0';
3265 *dst++ = upperCase ? 'X': 'x';
3266
3267 bool roundUp = false;
3268 const char *hexDigitChars = upperCase ? hexDigitsUpper : hexDigitsLower;
3269
3270 const integerPart *significand = significandParts();
3271 unsigned partsCount = partCount();
3272
3273 /* +3 because the first digit only uses the single integer bit, so
3274 we have 3 virtual zero most-significant-bits. */
3275 unsigned valueBits = semantics->precision + 3;
3276 unsigned shift = integerPartWidth - valueBits % integerPartWidth;
3277
3278 /* The natural number of digits required ignoring trailing
3279 insignificant zeroes. */
3280 unsigned outputDigits = (valueBits - significandLSB() + 3) / 4;
3281
3282 /* hexDigits of zero means use the required number for the
3283 precision. Otherwise, see if we are truncating. If we are,
3284 find out if we need to round away from zero. */
3285 if (hexDigits) {
3286 if (hexDigits < outputDigits) {
3287 /* We are dropping non-zero bits, so need to check how to round.
3288 "bits" is the number of dropped bits. */
3289 unsigned int bits;
3290 lostFraction fraction;
3291
3292 bits = valueBits - hexDigits * 4;
3293 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
3294 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
3295 }
3296 outputDigits = hexDigits;
3297 }
3298
3299 /* Write the digits consecutively, and start writing in the location
3300 of the hexadecimal point. We move the most significant digit
3301 left and add the hexadecimal point later. */
3302 char *p = ++dst;
3303
3304 unsigned count = (valueBits + integerPartWidth - 1) / integerPartWidth;
3305
3306 while (outputDigits && count) {
3307 integerPart part;
3308
3309 /* Put the most significant integerPartWidth bits in "part". */
3310 if (--count == partsCount)
3311 part = 0; /* An imaginary higher zero part. */
3312 else
3313 part = significand[count] << shift;
3314
3315 if (count && shift)
3316 part |= significand[count - 1] >> (integerPartWidth - shift);
3317
3318 /* Convert as much of "part" to hexdigits as we can. */
3319 unsigned int curDigits = integerPartWidth / 4;
3320
3321 curDigits = std::min(curDigits, outputDigits);
3322 dst += partAsHex (dst, part, curDigits, hexDigitChars);
3323 outputDigits -= curDigits;
3324 }
3325
3326 if (roundUp) {
3327 char *q = dst;
3328
3329 /* Note that hexDigitChars has a trailing '0'. */
3330 do {
3331 q--;
3332 *q = hexDigitChars[hexDigitValue (*q) + 1];
3333 } while (*q == '0');
3334 assert(q >= p);
3335 } else {
3336 /* Add trailing zeroes. */
3337 memset (dst, '0', outputDigits);
3338 dst += outputDigits;
3339 }
3340
3341 /* Move the most significant digit to before the point, and if there
3342 is something after the decimal point add it. This must come
3343 after rounding above. */
3344 p[-1] = p[0];
3345 if (dst -1 == p)
3346 dst--;
3347 else
3348 p[0] = '.';
3349
3350 /* Finally output the exponent. */
3351 *dst++ = upperCase ? 'P': 'p';
3352
3353 return writeSignedDecimal (dst, exponent);
3354}
3355
3357 if (!Arg.isFiniteNonZero())
3358 return hash_combine((uint8_t)Arg.category,
3359 // NaN has no sign, fix it at zero.
3360 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
3361 Arg.semantics->precision);
3362
3363 // Normal floats need their exponent and significand hashed.
3364 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
3365 Arg.semantics->precision, Arg.exponent,
3367 Arg.significandParts(),
3368 Arg.significandParts() + Arg.partCount()));
3369}
3370
3371// Conversion from APFloat to/from host float/double. It may eventually be
3372// possible to eliminate these and have everybody deal with APFloats, but that
3373// will take a while. This approach will not easily extend to long double.
3374// Current implementation requires integerPartWidth==64, which is correct at
3375// the moment but could be made more general.
3376
3377// Denormals have exponent minExponent in APFloat, but minExponent-1 in
3378// the actual IEEE respresentations. We compensate for that here.
3379
3380APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
3381 assert(partCount() == 2);
3382 return convertIEEEFloatToAPInt<APFloatBase::semX87DoubleExtended>();
3383}
3384
3385APInt IEEEFloat::convertPPCDoubleDoubleLegacyAPFloatToAPInt() const {
3386 assert(semantics ==
3387 (const llvm::fltSemantics *)&APFloatBase::semPPCDoubleDoubleLegacy);
3388 assert(partCount()==2);
3389
3390 uint64_t words[2];
3391 bool losesInfo;
3392
3393 // Convert number to double. To avoid spurious underflows, we re-
3394 // normalize against the "double" minExponent first, and only *then*
3395 // truncate the mantissa. The result of that second conversion
3396 // may be inexact, but should never underflow.
3397 // Declare fltSemantics before APFloat that uses it (and
3398 // saves pointer to it) to ensure correct destruction order.
3399 fltSemantics extendedSemantics = *semantics;
3400 extendedSemantics.minExponent = APFloatBase::semIEEEdouble.minExponent;
3401 IEEEFloat extended(*this);
3402 [[maybe_unused]] opStatus fs =
3403 extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
3404 assert(fs == opOK && !losesInfo);
3405
3406 IEEEFloat u(extended);
3407 fs = u.convert(APFloatBase::semIEEEdouble, rmNearestTiesToEven, &losesInfo);
3408 assert(fs == opOK || fs == opInexact);
3409 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
3410
3411 // If conversion was exact or resulted in a special case, we're done;
3412 // just set the second double to zero. Otherwise, re-convert back to
3413 // the extended format and compute the difference. This now should
3414 // convert exactly to double.
3415 if (u.isFiniteNonZero() && losesInfo) {
3416 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
3417 assert(fs == opOK && !losesInfo);
3418
3419 IEEEFloat v(extended);
3420 v.subtract(u, rmNearestTiesToEven);
3421 fs = v.convert(APFloatBase::semIEEEdouble, rmNearestTiesToEven, &losesInfo);
3422 assert(fs == opOK && !losesInfo);
3423 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
3424 } else {
3425 words[1] = 0;
3426 }
3427
3428 return APInt(128, words);
3429}
3430
3431template <const fltSemantics &S>
3432APInt IEEEFloat::convertIEEEFloatToAPInt() const {
3433 assert(semantics == &S);
3434 constexpr unsigned int trailing_significand_bits =
3435 S.precision - 1 + S.hasExplicitIntegerBit;
3436 constexpr int integer_bit_part = (S.precision - 1) / integerPartWidth;
3437 constexpr integerPart integer_bit = integerPart{1}
3438 << ((S.precision - 1) % integerPartWidth);
3439 constexpr uint64_t significand_mask = integer_bit - 1;
3440 constexpr unsigned int exponent_bits =
3441 S.sizeInBits - (S.hasSignedRepr ? 1 : 0) - trailing_significand_bits;
3442 static_assert(exponent_bits < 64);
3443 constexpr uint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1;
3444 constexpr bool is_zero_exp_reserved = S.hasDenormals || S.hasZero;
3445 constexpr int bias = -(S.minExponent - (is_zero_exp_reserved ? 1 : 0));
3446
3447 uint64_t myexponent;
3448 std::array<integerPart, partCountForBits(trailing_significand_bits)>
3449 mysignificand;
3450
3451 if (isFiniteNonZero()) {
3452 myexponent = exponent + bias;
3453 std::copy_n(significandParts(), mysignificand.size(),
3454 mysignificand.begin());
3455 if (myexponent == 1 &&
3456 !(significandParts()[integer_bit_part] & integer_bit))
3457 myexponent = 0; // denormal
3458 } else if (category == fcZero) {
3459 if (!S.hasZero)
3460 llvm_unreachable("semantics does not support zero!");
3461 myexponent = ::exponentZero(S) + bias;
3462 mysignificand.fill(0);
3463 } else if (category == fcInfinity) {
3464 if (S.nonFiniteBehavior == fltNonfiniteBehavior::NanOnly ||
3465 S.nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
3466 llvm_unreachable("semantics don't support inf!");
3467 myexponent = ::exponentInf(S) + bias;
3468 mysignificand.fill(0);
3469 if constexpr (S.hasExplicitIntegerBit) {
3470 mysignificand[0] = integerPart{1} << (trailing_significand_bits - 1);
3471 }
3472 } else {
3473 assert(category == fcNaN && "Unknown category!");
3474 if (S.nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
3475 llvm_unreachable("semantics don't support NaN!");
3476 myexponent = ::exponentNaN(S) + bias;
3477 std::copy_n(significandParts(), mysignificand.size(),
3478 mysignificand.begin());
3479 }
3480 std::array<uint64_t, (S.sizeInBits + 63) / 64> words;
3481 auto words_iter =
3482 std::copy_n(mysignificand.begin(), mysignificand.size(), words.begin());
3483 if constexpr (!S.hasExplicitIntegerBit) {
3484 if constexpr (significand_mask != 0 || trailing_significand_bits == 0) {
3485 // Clear the integer bit.
3486 words[mysignificand.size() - 1] &= significand_mask;
3487 }
3488 }
3489 std::fill(words_iter, words.end(), uint64_t{0});
3490 constexpr size_t last_word = words.size() - 1;
3491 uint64_t shifted_sign = static_cast<uint64_t>(sign & 1)
3492 << ((S.sizeInBits - 1) % 64);
3493 words[last_word] |= shifted_sign;
3494 uint64_t shifted_exponent = (myexponent & exponent_mask)
3495 << (trailing_significand_bits % 64);
3496 words[last_word] |= shifted_exponent;
3497 if constexpr (last_word == 0) {
3498 return APInt(S.sizeInBits, words[0]);
3499 }
3500 return APInt(S.sizeInBits, words);
3501}
3502
3503APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
3504 assert(partCount() == 2);
3505 return convertIEEEFloatToAPInt<APFloatBase::semIEEEquad>();
3506}
3507
3508APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
3509 assert(partCount()==1);
3510 return convertIEEEFloatToAPInt<APFloatBase::semIEEEdouble>();
3511}
3512
3513APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
3514 assert(partCount()==1);
3515 return convertIEEEFloatToAPInt<APFloatBase::semIEEEsingle>();
3516}
3517
3518APInt IEEEFloat::convertBFloatAPFloatToAPInt() const {
3519 assert(partCount() == 1);
3520 return convertIEEEFloatToAPInt<APFloatBase::semBFloat>();
3521}
3522
3523APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
3524 assert(partCount()==1);
3525 return convertIEEEFloatToAPInt<APFloatBase::APFloatBase::semIEEEhalf>();
3526}
3527
3528APInt IEEEFloat::convertFloat8E5M2APFloatToAPInt() const {
3529 assert(partCount() == 1);
3530 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M2>();
3531}
3532
3533APInt IEEEFloat::convertFloat8E5M2FNUZAPFloatToAPInt() const {
3534 assert(partCount() == 1);
3535 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M2FNUZ>();
3536}
3537
3538APInt IEEEFloat::convertFloat8E4M3APFloatToAPInt() const {
3539 assert(partCount() == 1);
3540 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3>();
3541}
3542
3543APInt IEEEFloat::convertFloat8E4M3FNAPFloatToAPInt() const {
3544 assert(partCount() == 1);
3545 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3FN>();
3546}
3547
3548APInt IEEEFloat::convertFloat8E4M3FNUZAPFloatToAPInt() const {
3549 assert(partCount() == 1);
3550 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3FNUZ>();
3551}
3552
3553APInt IEEEFloat::convertFloat8E4M3B11FNUZAPFloatToAPInt() const {
3554 assert(partCount() == 1);
3555 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3B11FNUZ>();
3556}
3557
3558APInt IEEEFloat::convertFloat8E3M4APFloatToAPInt() const {
3559 assert(partCount() == 1);
3560 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E3M4>();
3561}
3562
3563APInt IEEEFloat::convertFloatTF32APFloatToAPInt() const {
3564 assert(partCount() == 1);
3565 return convertIEEEFloatToAPInt<APFloatBase::semFloatTF32>();
3566}
3567
3568APInt IEEEFloat::convertFloat8E8M0FNUAPFloatToAPInt() const {
3569 assert(partCount() == 1);
3570 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E8M0FNU>();
3571}
3572
3573APInt IEEEFloat::convertFloat8E5M3FNUAPFloatToAPInt() const {
3574 assert(partCount() == 1);
3575 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M3FNU>();
3576}
3577
3578APInt IEEEFloat::convertFloat6E3M2FNAPFloatToAPInt() const {
3579 assert(partCount() == 1);
3580 return convertIEEEFloatToAPInt<APFloatBase::semFloat6E3M2FN>();
3581}
3582
3583APInt IEEEFloat::convertFloat6E2M3FNAPFloatToAPInt() const {
3584 assert(partCount() == 1);
3585 return convertIEEEFloatToAPInt<APFloatBase::semFloat6E2M3FN>();
3586}
3587
3588APInt IEEEFloat::convertFloat4E2M1FNAPFloatToAPInt() const {
3589 assert(partCount() == 1);
3590 return convertIEEEFloatToAPInt<APFloatBase::semFloat4E2M1FN>();
3591}
3592
3593// This function creates an APInt that is just a bit map of the floating
3594// point constant as it would appear in memory. It is not a conversion,
3595// and treating the result as a normal integer is unlikely to be useful.
3596
3598 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEhalf)
3599 return convertHalfAPFloatToAPInt();
3600
3601 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semBFloat)
3602 return convertBFloatAPFloatToAPInt();
3603
3604 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEsingle)
3605 return convertFloatAPFloatToAPInt();
3606
3607 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEdouble)
3608 return convertDoubleAPFloatToAPInt();
3609
3610 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEquad)
3611 return convertQuadrupleAPFloatToAPInt();
3612
3613 if (semantics ==
3614 (const llvm::fltSemantics *)&APFloatBase::semPPCDoubleDoubleLegacy)
3615 return convertPPCDoubleDoubleLegacyAPFloatToAPInt();
3616
3617 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M2)
3618 return convertFloat8E5M2APFloatToAPInt();
3619
3620 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M2FNUZ)
3621 return convertFloat8E5M2FNUZAPFloatToAPInt();
3622
3623 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3)
3624 return convertFloat8E4M3APFloatToAPInt();
3625
3626 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3FN)
3627 return convertFloat8E4M3FNAPFloatToAPInt();
3628
3629 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3FNUZ)
3630 return convertFloat8E4M3FNUZAPFloatToAPInt();
3631
3632 if (semantics ==
3633 (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3B11FNUZ)
3634 return convertFloat8E4M3B11FNUZAPFloatToAPInt();
3635
3636 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E3M4)
3637 return convertFloat8E3M4APFloatToAPInt();
3638
3639 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloatTF32)
3640 return convertFloatTF32APFloatToAPInt();
3641
3642 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E8M0FNU)
3643 return convertFloat8E8M0FNUAPFloatToAPInt();
3644
3645 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M3FNU)
3646 return convertFloat8E5M3FNUAPFloatToAPInt();
3647
3648 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat6E3M2FN)
3649 return convertFloat6E3M2FNAPFloatToAPInt();
3650
3651 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat6E2M3FN)
3652 return convertFloat6E2M3FNAPFloatToAPInt();
3653
3654 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat4E2M1FN)
3655 return convertFloat4E2M1FNAPFloatToAPInt();
3656
3657 assert(semantics ==
3658 (const llvm::fltSemantics *)&APFloatBase::semX87DoubleExtended &&
3659 "unknown format!");
3660 return convertF80LongDoubleAPFloatToAPInt();
3661}
3662
3664 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEsingle &&
3665 "Float semantics are not IEEEsingle");
3666 APInt api = bitcastToAPInt();
3667 return api.bitsToFloat();
3668}
3669
3671 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEdouble &&
3672 "Float semantics are not IEEEdouble");
3673 APInt api = bitcastToAPInt();
3674 return api.bitsToDouble();
3675}
3676
3677#ifdef HAS_IEE754_FLOAT128
3678float128 IEEEFloat::convertToQuad() const {
3679 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEquad &&
3680 "Float semantics are not IEEEquads");
3681 APInt api = bitcastToAPInt();
3682 return api.bitsToQuad();
3683}
3684#endif
3685
3686void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
3687 return initFromIEEEAPInt<APFloatBase::semX87DoubleExtended>(api);
3688}
3689
3690void IEEEFloat::initFromPPCDoubleDoubleLegacyAPInt(const APInt &api) {
3691 uint64_t i1 = api.getRawData()[0];
3692 uint64_t i2 = api.getRawData()[1];
3693 bool losesInfo;
3694
3695 // Get the first double and convert to our format.
3696 initFromDoubleAPInt(APInt(64, i1));
3697 [[maybe_unused]] opStatus fs = convert(APFloatBase::semPPCDoubleDoubleLegacy,
3698 rmNearestTiesToEven, &losesInfo);
3699 // (convert may return opInvalidOp if i1 is an sNaN).
3700 assert((fs == opOK || fs == opInvalidOp) && !losesInfo);
3701
3702 // Unless we have a special case, add in second double.
3703 if (isFiniteNonZero()) {
3704 IEEEFloat v(APFloatBase::semIEEEdouble, APInt(64, i2));
3705 fs = v.convert(APFloatBase::semPPCDoubleDoubleLegacy, rmNearestTiesToEven,
3706 &losesInfo);
3707 assert(fs == opOK && !losesInfo);
3708
3710 }
3711}
3712
3713// The E8M0 format has the following characteristics:
3714// It is an 8-bit unsigned format with only exponents (no actual significand).
3715// No encodings for {zero, infinities or denorms}.
3716// NaN is represented by all 1's.
3717// Bias is 127.
3718void IEEEFloat::initFromFloat8E8M0FNUAPInt(const APInt &api) {
3719 initFromIEEEAPInt<APFloatBase::semFloat8E8M0FNU>(api);
3720}
3721
3722void IEEEFloat::initFromFloat8E5M3FNUAPInt(const APInt &api) {
3723 initFromIEEEAPInt<APFloatBase::semFloat8E5M3FNU>(api);
3724}
3725
3726template <const fltSemantics &S>
3727void IEEEFloat::initFromIEEEAPInt(const APInt &api) {
3728 assert(api.getBitWidth() == S.sizeInBits);
3729
3730 constexpr unsigned int trailing_significand_bits =
3731 S.precision - 1 + S.hasExplicitIntegerBit;
3732 constexpr integerPart integer_bit =
3733 integerPart{1} << (trailing_significand_bits % integerPartWidth);
3734 constexpr uint64_t significand_mask = integer_bit - 1;
3735 constexpr unsigned int exponent_bits =
3736 S.sizeInBits - (S.hasSignedRepr ? 1 : 0) - trailing_significand_bits;
3737 static_assert(exponent_bits < 64);
3738 constexpr unsigned int stored_significand_parts =
3739 partCountForBits(trailing_significand_bits + 1);
3740 constexpr uint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1;
3741 constexpr bool is_zero_exp_reserved = S.hasDenormals || S.hasZero;
3742 constexpr int bias = -(S.minExponent - (is_zero_exp_reserved ? 1 : 0));
3743 constexpr bool has_significand = trailing_significand_bits > 0;
3744
3745 // Copy the bits of the significand. We need to clear out the exponent and
3746 // sign bit in the last word.
3747 std::array<integerPart, stored_significand_parts> mysignificand;
3748 if constexpr (has_significand) {
3749 std::copy_n(api.getRawData(), mysignificand.size(), mysignificand.begin());
3750 if constexpr (significand_mask != 0 || S.precision >= integerPartWidth) {
3751 mysignificand[mysignificand.size() - 1] &= significand_mask;
3752 }
3753 } else {
3754 std::fill_n(mysignificand.begin(), mysignificand.size(), 0);
3755 // Always set integer bit to 1 for consistency in APFloat's internal
3756 // representation.
3757 mysignificand[0] = 1;
3758 }
3759
3760 // We assume the last word holds the sign bit, the exponent, and potentially
3761 // some of the trailing significand field.
3762 uint64_t last_word = api.getRawData()[api.getNumWords() - 1];
3763 uint64_t myexponent =
3764 (last_word >> (trailing_significand_bits % 64)) & exponent_mask;
3765
3766 initialize(&S);
3767 assert(partCount() == mysignificand.size());
3768
3769 sign = S.hasSignedRepr
3770 ? static_cast<unsigned int>(last_word >> ((S.sizeInBits - 1) % 64))
3771 : 0;
3772
3773 bool all_zero_significand =
3774 has_significand && llvm::all_of(mysignificand, equal_to(0));
3775
3776 bool is_zero = myexponent == 0 && all_zero_significand && S.hasZero;
3777
3778 if constexpr (S.nonFiniteBehavior == fltNonfiniteBehavior::IEEE754) {
3779 bool is_inf = false;
3780
3781 if constexpr (S.hasExplicitIntegerBit) {
3782 // This is only used and tested for x87DoubleExtended
3783 static_assert(S.precision == 64);
3784 constexpr integerPart significand_mask_no_int_bit =
3785 (uint64_t{1} << (trailing_significand_bits - 1)) - 1;
3786 const integerPart myintegerbit =
3787 mysignificand[0] >> (trailing_significand_bits - 1);
3788
3789 is_inf = myexponent - bias == ::exponentInf(S) && myintegerbit == 1 &&
3790 (mysignificand[0] & significand_mask_no_int_bit) == 0;
3791 } else {
3792 is_inf = myexponent - bias == ::exponentInf(S) && all_zero_significand;
3793 }
3794
3795 if (is_inf) {
3796 makeInf(sign);
3797 return;
3798 }
3799 }
3800
3801 bool is_nan = false;
3802
3803 if constexpr (S.nanEncoding == fltNanEncoding::IEEE) {
3804 if constexpr (S.hasExplicitIntegerBit) {
3805 // This is only used and tested for x87DoubleExtended
3806 static_assert(S.precision == 64);
3807 const integerPart myintegerbit =
3808 mysignificand[0] >> (trailing_significand_bits - 1);
3809 constexpr integerPart significand_mask_no_int_bit =
3810 (uint64_t{1} << (trailing_significand_bits - 1)) - 1;
3811
3812 if (myexponent - bias == ::exponentNaN(S) &&
3813 (mysignificand[0] & significand_mask_no_int_bit) != 0) {
3814 // regular NaN and pseudoNaN
3815 is_nan = true;
3816 } else if (myexponent - bias == ::exponentNaN(S) &&
3817 (mysignificand[0] & significand_mask_no_int_bit) == 0) {
3818 // pseudoinfinity
3819 is_nan = true;
3820 } else if (myexponent - bias != ::exponentNaN(S) && myexponent != 0 &&
3821 myintegerbit == 0) {
3822 // unnormal
3823 is_nan = true;
3824 }
3825 } else {
3826 is_nan = myexponent - bias == ::exponentNaN(S) && !all_zero_significand;
3827 }
3828 } else if constexpr (S.nanEncoding == fltNanEncoding::AllOnes) {
3829 bool all_ones_significand =
3830 std::all_of(mysignificand.begin(), mysignificand.end() - 1,
3831 [](integerPart bits) { return bits == ~integerPart{0}; }) &&
3832 (!significand_mask ||
3833 mysignificand[mysignificand.size() - 1] == significand_mask);
3834 is_nan = myexponent - bias == ::exponentNaN(S) && all_ones_significand;
3835 } else if constexpr (S.nanEncoding == fltNanEncoding::NegativeZero) {
3836 is_nan = is_zero && sign;
3837 }
3838
3839 if (is_nan) {
3840 category = fcNaN;
3841 exponent = ::exponentNaN(S);
3842 std::copy_n(mysignificand.begin(), mysignificand.size(),
3843 significandParts());
3844 return;
3845 }
3846
3847 if (is_zero) {
3848 makeZero(sign);
3849 return;
3850 }
3851
3852 category = fcNormal;
3853 exponent = myexponent - bias;
3854 std::copy_n(mysignificand.begin(), mysignificand.size(), significandParts());
3855 if (myexponent == 0 && S.hasDenormals) // denormal
3856 exponent = S.minExponent;
3857 else {
3858 if constexpr (!S.hasExplicitIntegerBit) {
3859 significandParts()[mysignificand.size() - 1] |= integer_bit;
3860 }
3861 }
3862}
3863
3864void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
3865 initFromIEEEAPInt<APFloatBase::semIEEEquad>(api);
3866}
3867
3868void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
3869 initFromIEEEAPInt<APFloatBase::semIEEEdouble>(api);
3870}
3871
3872void IEEEFloat::initFromFloatAPInt(const APInt &api) {
3873 initFromIEEEAPInt<APFloatBase::semIEEEsingle>(api);
3874}
3875
3876void IEEEFloat::initFromBFloatAPInt(const APInt &api) {
3877 initFromIEEEAPInt<APFloatBase::semBFloat>(api);
3878}
3879
3880void IEEEFloat::initFromHalfAPInt(const APInt &api) {
3881 initFromIEEEAPInt<APFloatBase::semIEEEhalf>(api);
3882}
3883
3884void IEEEFloat::initFromFloat8E5M2APInt(const APInt &api) {
3885 initFromIEEEAPInt<APFloatBase::semFloat8E5M2>(api);
3886}
3887
3888void IEEEFloat::initFromFloat8E5M2FNUZAPInt(const APInt &api) {
3889 initFromIEEEAPInt<APFloatBase::semFloat8E5M2FNUZ>(api);
3890}
3891
3892void IEEEFloat::initFromFloat8E4M3APInt(const APInt &api) {
3893 initFromIEEEAPInt<APFloatBase::semFloat8E4M3>(api);
3894}
3895
3896void IEEEFloat::initFromFloat8E4M3FNAPInt(const APInt &api) {
3897 initFromIEEEAPInt<APFloatBase::semFloat8E4M3FN>(api);
3898}
3899
3900void IEEEFloat::initFromFloat8E4M3FNUZAPInt(const APInt &api) {
3901 initFromIEEEAPInt<APFloatBase::semFloat8E4M3FNUZ>(api);
3902}
3903
3904void IEEEFloat::initFromFloat8E4M3B11FNUZAPInt(const APInt &api) {
3905 initFromIEEEAPInt<APFloatBase::semFloat8E4M3B11FNUZ>(api);
3906}
3907
3908void IEEEFloat::initFromFloat8E3M4APInt(const APInt &api) {
3909 initFromIEEEAPInt<APFloatBase::semFloat8E3M4>(api);
3910}
3911
3912void IEEEFloat::initFromFloatTF32APInt(const APInt &api) {
3913 initFromIEEEAPInt<APFloatBase::semFloatTF32>(api);
3914}
3915
3916void IEEEFloat::initFromFloat6E3M2FNAPInt(const APInt &api) {
3917 initFromIEEEAPInt<APFloatBase::semFloat6E3M2FN>(api);
3918}
3919
3920void IEEEFloat::initFromFloat6E2M3FNAPInt(const APInt &api) {
3921 initFromIEEEAPInt<APFloatBase::semFloat6E2M3FN>(api);
3922}
3923
3924void IEEEFloat::initFromFloat4E2M1FNAPInt(const APInt &api) {
3925 initFromIEEEAPInt<APFloatBase::semFloat4E2M1FN>(api);
3926}
3927
3928/// Treat api as containing the bits of a floating point number.
3929void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
3930 assert(api.getBitWidth() == Sem->sizeInBits);
3931 if (Sem == &APFloatBase::semIEEEhalf)
3932 return initFromHalfAPInt(api);
3933 if (Sem == &APFloatBase::semBFloat)
3934 return initFromBFloatAPInt(api);
3935 if (Sem == &APFloatBase::semIEEEsingle)
3936 return initFromFloatAPInt(api);
3937 if (Sem == &APFloatBase::semIEEEdouble)
3938 return initFromDoubleAPInt(api);
3939 if (Sem == &APFloatBase::semX87DoubleExtended)
3940 return initFromF80LongDoubleAPInt(api);
3941 if (Sem == &APFloatBase::semIEEEquad)
3942 return initFromQuadrupleAPInt(api);
3943 if (Sem == &APFloatBase::semPPCDoubleDoubleLegacy)
3944 return initFromPPCDoubleDoubleLegacyAPInt(api);
3945 if (Sem == &APFloatBase::semFloat8E5M2)
3946 return initFromFloat8E5M2APInt(api);
3947 if (Sem == &APFloatBase::semFloat8E5M2FNUZ)
3948 return initFromFloat8E5M2FNUZAPInt(api);
3949 if (Sem == &APFloatBase::semFloat8E4M3)
3950 return initFromFloat8E4M3APInt(api);
3951 if (Sem == &APFloatBase::semFloat8E4M3FN)
3952 return initFromFloat8E4M3FNAPInt(api);
3953 if (Sem == &APFloatBase::semFloat8E4M3FNUZ)
3954 return initFromFloat8E4M3FNUZAPInt(api);
3955 if (Sem == &APFloatBase::semFloat8E4M3B11FNUZ)
3956 return initFromFloat8E4M3B11FNUZAPInt(api);
3957 if (Sem == &APFloatBase::semFloat8E3M4)
3958 return initFromFloat8E3M4APInt(api);
3959 if (Sem == &APFloatBase::semFloatTF32)
3960 return initFromFloatTF32APInt(api);
3961 if (Sem == &APFloatBase::semFloat8E8M0FNU)
3962 return initFromFloat8E8M0FNUAPInt(api);
3963 if (Sem == &APFloatBase::semFloat8E5M3FNU)
3964 return initFromFloat8E5M3FNUAPInt(api);
3965 if (Sem == &APFloatBase::semFloat6E3M2FN)
3966 return initFromFloat6E3M2FNAPInt(api);
3967 if (Sem == &APFloatBase::semFloat6E2M3FN)
3968 return initFromFloat6E2M3FNAPInt(api);
3969 if (Sem == &APFloatBase::semFloat4E2M1FN)
3970 return initFromFloat4E2M1FNAPInt(api);
3971
3972 llvm_unreachable("unsupported semantics");
3973}
3974
3975/// Make this number the largest magnitude normal number in the given
3976/// semantics.
3977void IEEEFloat::makeLargest(bool Negative) {
3978 if (Negative && !semantics->hasSignedRepr)
3980 "This floating point format does not support signed values");
3981 // We want (in interchange format):
3982 // sign = {Negative}
3983 // exponent = 1..10
3984 // significand = 1..1
3985 category = fcNormal;
3986 sign = Negative;
3987 exponent = semantics->maxExponent;
3988
3989 // Use memset to set all but the highest integerPart to all ones.
3990 integerPart *significand = significandParts();
3991 unsigned PartCount = partCount();
3992 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
3993
3994 // Set the high integerPart especially setting all unused top bits for
3995 // internal consistency.
3996 const unsigned NumUnusedHighBits =
3997 PartCount*integerPartWidth - semantics->precision;
3998 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3999 ? (~integerPart(0) >> NumUnusedHighBits)
4000 : 0;
4001 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
4002 semantics->nanEncoding == fltNanEncoding::AllOnes &&
4003 (semantics->precision > 1))
4004 significand[0] &= ~integerPart(1);
4005}
4006
4007/// Make this number the smallest magnitude denormal number in the given
4008/// semantics.
4009void IEEEFloat::makeSmallest(bool Negative) {
4010 if (Negative && !semantics->hasSignedRepr)
4012 "This floating point format does not support signed values");
4013 // We want (in interchange format):
4014 // sign = {Negative}
4015 // exponent = 0..0
4016 // significand = 0..01
4017 category = fcNormal;
4018 sign = Negative;
4019 exponent = semantics->minExponent;
4020 APInt::tcSet(significandParts(), 1, partCount());
4021}
4022
4024 if (Negative && !semantics->hasSignedRepr)
4026 "This floating point format does not support signed values");
4027 // We want (in interchange format):
4028 // sign = {Negative}
4029 // exponent = 0..0
4030 // significand = 10..0
4031
4032 category = fcNormal;
4033 zeroSignificand();
4034 sign = Negative;
4035 exponent = semantics->minExponent;
4036 APInt::tcSetBit(significandParts(), semantics->precision - 1);
4037}
4038
4039IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
4040 initFromAPInt(&Sem, API);
4041}
4042
4044 initFromAPInt(&APFloatBase::semIEEEsingle, APInt::floatToBits(f));
4045}
4046
4048 initFromAPInt(&APFloatBase::semIEEEdouble, APInt::doubleToBits(d));
4049}
4050
4051namespace {
4052 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
4053 Buffer.append(Str.begin(), Str.end());
4054 }
4055
4056 /// Removes data from the given significand until it is no more
4057 /// precise than is required for the desired precision.
4058 void AdjustToPrecision(APInt &significand,
4059 int &exp, unsigned FormatPrecision) {
4060 unsigned bits = significand.getActiveBits();
4061
4062 // 196/59 is a very slight overestimate of lg_2(10).
4063 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
4064
4065 if (bits <= bitsRequired) return;
4066
4067 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
4068 if (!tensRemovable) return;
4069
4070 exp += tensRemovable;
4071
4072 APInt divisor(significand.getBitWidth(), 1);
4073 APInt powten(significand.getBitWidth(), 10);
4074 while (true) {
4075 if (tensRemovable & 1)
4076 divisor *= powten;
4077 tensRemovable >>= 1;
4078 if (!tensRemovable) break;
4079 powten *= powten;
4080 }
4081
4082 significand = significand.udiv(divisor);
4083
4084 // Truncate the significand down to its active bit count.
4085 significand = significand.trunc(significand.getActiveBits());
4086 }
4087
4088
4089 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
4090 int &exp, unsigned FormatPrecision) {
4091 unsigned N = buffer.size();
4092 if (N <= FormatPrecision) return;
4093
4094 // The most significant figures are the last ones in the buffer.
4095 unsigned FirstSignificant = N - FormatPrecision;
4096
4097 // Round.
4098 // FIXME: this probably shouldn't use 'round half up'.
4099
4100 // Rounding down is just a truncation, except we also want to drop
4101 // trailing zeros from the new result.
4102 if (buffer[FirstSignificant - 1] < '5') {
4103 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
4104 FirstSignificant++;
4105
4106 exp += FirstSignificant;
4107 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4108 return;
4109 }
4110
4111 // Rounding up requires a decimal add-with-carry. If we continue
4112 // the carry, the newly-introduced zeros will just be truncated.
4113 for (unsigned I = FirstSignificant; I != N; ++I) {
4114 if (buffer[I] == '9') {
4115 FirstSignificant++;
4116 } else {
4117 buffer[I]++;
4118 break;
4119 }
4120 }
4121
4122 // If we carried through, we have exactly one digit of precision.
4123 if (FirstSignificant == N) {
4124 exp += FirstSignificant;
4125 buffer.clear();
4126 buffer.push_back('1');
4127 return;
4128 }
4129
4130 exp += FirstSignificant;
4131 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4132 }
4133
4134 void toStringImpl(SmallVectorImpl<char> &Str, const bool isNeg, int exp,
4135 APInt significand, unsigned FormatPrecision,
4136 unsigned FormatMaxPadding, bool TruncateZero) {
4137 const int semanticsPrecision = significand.getBitWidth();
4138
4139 if (isNeg)
4140 Str.push_back('-');
4141
4142 // Set FormatPrecision if zero. We want to do this before we
4143 // truncate trailing zeros, as those are part of the precision.
4144 if (!FormatPrecision) {
4145 // We use enough digits so the number can be round-tripped back to an
4146 // APFloat. The formula comes from "How to Print Floating-Point Numbers
4147 // Accurately" by Steele and White.
4148 // FIXME: Using a formula based purely on the precision is conservative;
4149 // we can print fewer digits depending on the actual value being printed.
4150
4151 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
4152 FormatPrecision = 2 + semanticsPrecision * 59 / 196;
4153 }
4154
4155 // Ignore trailing binary zeros.
4156 int trailingZeros = significand.countr_zero();
4157 exp += trailingZeros;
4158 significand.lshrInPlace(trailingZeros);
4159
4160 // Change the exponent from 2^e to 10^e.
4161 if (exp == 0) {
4162 // Nothing to do.
4163 } else if (exp > 0) {
4164 // Just shift left.
4165 significand = significand.zext(semanticsPrecision + exp);
4166 significand <<= exp;
4167 exp = 0;
4168 } else { /* exp < 0 */
4169 int texp = -exp;
4170
4171 // We transform this using the identity:
4172 // (N)(2^-e) == (N)(5^e)(10^-e)
4173 // This means we have to multiply N (the significand) by 5^e.
4174 // To avoid overflow, we have to operate on numbers large
4175 // enough to store N * 5^e:
4176 // log2(N * 5^e) == log2(N) + e * log2(5)
4177 // <= semantics->precision + e * 137 / 59
4178 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
4179
4180 unsigned precision = semanticsPrecision + (137 * texp + 136) / 59;
4181
4182 // Multiply significand by 5^e.
4183 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
4184 significand = significand.zext(precision);
4185 APInt five_to_the_i(precision, 5);
4186 while (true) {
4187 if (texp & 1)
4188 significand *= five_to_the_i;
4189
4190 texp >>= 1;
4191 if (!texp)
4192 break;
4193 five_to_the_i *= five_to_the_i;
4194 }
4195 }
4196
4197 AdjustToPrecision(significand, exp, FormatPrecision);
4198
4200
4201 // Fill the buffer.
4202 unsigned precision = significand.getBitWidth();
4203 if (precision < 4) {
4204 // We need enough precision to store the value 10.
4205 precision = 4;
4206 significand = significand.zext(precision);
4207 }
4208 APInt ten(precision, 10);
4209 APInt digit(precision, 0);
4210
4211 bool inTrail = true;
4212 while (significand != 0) {
4213 // digit <- significand % 10
4214 // significand <- significand / 10
4215 APInt::udivrem(significand, ten, significand, digit);
4216
4217 unsigned d = digit.getZExtValue();
4218
4219 // Drop trailing zeros.
4220 if (inTrail && !d)
4221 exp++;
4222 else {
4223 buffer.push_back((char) ('0' + d));
4224 inTrail = false;
4225 }
4226 }
4227
4228 assert(!buffer.empty() && "no characters in buffer!");
4229
4230 // Drop down to FormatPrecision.
4231 // TODO: don't do more precise calculations above than are required.
4232 AdjustToPrecision(buffer, exp, FormatPrecision);
4233
4234 unsigned NDigits = buffer.size();
4235
4236 // Check whether we should use scientific notation.
4237 bool FormatScientific;
4238 if (!FormatMaxPadding) {
4239 FormatScientific = true;
4240 } else {
4241 if (exp >= 0) {
4242 // 765e3 --> 765000
4243 // ^^^
4244 // But we shouldn't make the number look more precise than it is.
4245 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
4246 NDigits + (unsigned) exp > FormatPrecision);
4247 } else {
4248 // Power of the most significant digit.
4249 int MSD = exp + (int) (NDigits - 1);
4250 if (MSD >= 0) {
4251 // 765e-2 == 7.65
4252 FormatScientific = false;
4253 } else {
4254 // 765e-5 == 0.00765
4255 // ^ ^^
4256 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
4257 }
4258 }
4259 }
4260
4261 // Scientific formatting is pretty straightforward.
4262 if (FormatScientific) {
4263 exp += (NDigits - 1);
4264
4265 Str.push_back(buffer[NDigits-1]);
4266 Str.push_back('.');
4267 if (NDigits == 1 && TruncateZero)
4268 Str.push_back('0');
4269 else
4270 for (unsigned I = 1; I != NDigits; ++I)
4271 Str.push_back(buffer[NDigits-1-I]);
4272 // Fill with zeros up to FormatPrecision.
4273 if (!TruncateZero && FormatPrecision > NDigits - 1)
4274 Str.append(FormatPrecision - NDigits + 1, '0');
4275 // For !TruncateZero we use lower 'e'.
4276 Str.push_back(TruncateZero ? 'E' : 'e');
4277
4278 Str.push_back(exp >= 0 ? '+' : '-');
4279 if (exp < 0)
4280 exp = -exp;
4281 SmallVector<char, 6> expbuf;
4282 do {
4283 expbuf.push_back((char) ('0' + (exp % 10)));
4284 exp /= 10;
4285 } while (exp);
4286 // Exponent always at least two digits if we do not truncate zeros.
4287 if (!TruncateZero && expbuf.size() < 2)
4288 expbuf.push_back('0');
4289 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
4290 Str.push_back(expbuf[E-1-I]);
4291 return;
4292 }
4293
4294 // Non-scientific, positive exponents.
4295 if (exp >= 0) {
4296 for (unsigned I = 0; I != NDigits; ++I)
4297 Str.push_back(buffer[NDigits-1-I]);
4298 for (unsigned I = 0; I != (unsigned) exp; ++I)
4299 Str.push_back('0');
4300 return;
4301 }
4302
4303 // Non-scientific, negative exponents.
4304
4305 // The number of digits to the left of the decimal point.
4306 int NWholeDigits = exp + (int) NDigits;
4307
4308 unsigned I = 0;
4309 if (NWholeDigits > 0) {
4310 for (; I != (unsigned) NWholeDigits; ++I)
4311 Str.push_back(buffer[NDigits-I-1]);
4312 Str.push_back('.');
4313 } else {
4314 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
4315
4316 Str.push_back('0');
4317 Str.push_back('.');
4318 for (unsigned Z = 1; Z != NZeros; ++Z)
4319 Str.push_back('0');
4320 }
4321
4322 for (; I != NDigits; ++I)
4323 Str.push_back(buffer[NDigits-I-1]);
4324
4325 }
4326} // namespace
4327
4328void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
4329 unsigned FormatMaxPadding, bool TruncateZero) const {
4330 switch (category) {
4331 case fcInfinity:
4332 if (isNegative())
4333 return append(Str, "-Inf");
4334 else
4335 return append(Str, "+Inf");
4336
4337 case fcNaN: return append(Str, "NaN");
4338
4339 case fcZero:
4340 if (isNegative())
4341 Str.push_back('-');
4342
4343 if (!FormatMaxPadding) {
4344 if (TruncateZero)
4345 append(Str, "0.0E+0");
4346 else {
4347 append(Str, "0.0");
4348 if (FormatPrecision > 1)
4349 Str.append(FormatPrecision - 1, '0');
4350 append(Str, "e+00");
4351 }
4352 } else {
4353 Str.push_back('0');
4354 }
4355 return;
4356
4357 case fcNormal:
4358 break;
4359 }
4360
4361 // Decompose the number into an APInt and an exponent.
4362 int exp = exponent - ((int) semantics->precision - 1);
4363 APInt significand(
4364 semantics->precision,
4365 ArrayRef(significandParts(), partCountForBits(semantics->precision)));
4366
4367 toStringImpl(Str, isNegative(), exp, significand, FormatPrecision,
4368 FormatMaxPadding, TruncateZero);
4369
4370}
4371
4373 if (!isFinite() || isZero())
4374 return INT_MIN;
4375
4376 const integerPart *Parts = significandParts();
4377 const int PartCount = partCountForBits(semantics->precision);
4378
4379 int PopCount = 0;
4380 for (int i = 0; i < PartCount; ++i) {
4381 PopCount += llvm::popcount(Parts[i]);
4382 if (PopCount > 1)
4383 return INT_MIN;
4384 }
4385
4386 if (exponent != semantics->minExponent)
4387 return exponent;
4388
4389 int CountrParts = 0;
4390 for (int i = 0; i < PartCount;
4391 ++i, CountrParts += APInt::APINT_BITS_PER_WORD) {
4392 if (Parts[i] != 0) {
4393 return exponent - semantics->precision + CountrParts +
4394 llvm::countr_zero(Parts[i]) + 1;
4395 }
4396 }
4397
4398 llvm_unreachable("didn't find the set bit");
4399}
4400
4402 if (!isNaN())
4403 return false;
4404 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly ||
4405 semantics->nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
4406 return false;
4407
4408 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
4409 // first bit of the trailing significand being 0.
4410 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
4411}
4412
4413/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
4414///
4415/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
4416/// appropriate sign switching before/after the computation.
4418 // If we are performing nextDown, swap sign so we have -x.
4419 if (nextDown)
4420 changeSign();
4421
4422 // Compute nextUp(x)
4423 opStatus result = opOK;
4424
4425 // Handle each float category separately.
4426 switch (category) {
4427 case fcInfinity:
4428 // nextUp(+inf) = +inf
4429 if (!isNegative())
4430 break;
4431 // nextUp(-inf) = -getLargest()
4432 makeLargest(true);
4433 break;
4434 case fcNaN:
4435 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
4436 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
4437 // change the payload.
4438 if (isSignaling()) {
4439 result = opInvalidOp;
4440 // For consistency, propagate the sign of the sNaN to the qNaN.
4441 makeNaN(false, isNegative(), nullptr);
4442 }
4443 break;
4444 case fcZero:
4445 // nextUp(pm 0) = +getSmallest()
4446 makeSmallest(false);
4447 break;
4448 case fcNormal:
4449 // nextUp(-getSmallest()) = -0
4450 if (isSmallest() && isNegative()) {
4451 APInt::tcSet(significandParts(), 0, partCount());
4452 category = fcZero;
4453 exponent = 0;
4454 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
4455 sign = false;
4456 if (!semantics->hasZero)
4458 break;
4459 }
4460
4461 if (isLargest() && !isNegative()) {
4462 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
4463 // nextUp(getLargest()) == NAN
4464 makeNaN();
4465 break;
4466 } else if (semantics->nonFiniteBehavior ==
4468 // nextUp(getLargest()) == getLargest()
4469 break;
4470 } else {
4471 // nextUp(getLargest()) == INFINITY
4472 APInt::tcSet(significandParts(), 0, partCount());
4473 category = fcInfinity;
4474 exponent = semantics->maxExponent + 1;
4475 break;
4476 }
4477 }
4478
4479 // nextUp(normal) == normal + inc.
4480 if (isNegative()) {
4481 // If we are negative, we need to decrement the significand.
4482
4483 // We only cross a binade boundary that requires adjusting the exponent
4484 // if:
4485 // 1. exponent != semantics->minExponent. This implies we are not in the
4486 // smallest binade or are dealing with denormals.
4487 // 2. Our significand excluding the integral bit is all zeros.
4488 bool WillCrossBinadeBoundary =
4489 exponent != semantics->minExponent && isSignificandAllZeros();
4490
4491 // Decrement the significand.
4492 //
4493 // We always do this since:
4494 // 1. If we are dealing with a non-binade decrement, by definition we
4495 // just decrement the significand.
4496 // 2. If we are dealing with a normal -> normal binade decrement, since
4497 // we have an explicit integral bit the fact that all bits but the
4498 // integral bit are zero implies that subtracting one will yield a
4499 // significand with 0 integral bit and 1 in all other spots. Thus we
4500 // must just adjust the exponent and set the integral bit to 1.
4501 // 3. If we are dealing with a normal -> denormal binade decrement,
4502 // since we set the integral bit to 0 when we represent denormals, we
4503 // just decrement the significand.
4504 integerPart *Parts = significandParts();
4505 APInt::tcDecrement(Parts, partCount());
4506
4507 if (WillCrossBinadeBoundary) {
4508 // Our result is a normal number. Do the following:
4509 // 1. Set the integral bit to 1.
4510 // 2. Decrement the exponent.
4511 APInt::tcSetBit(Parts, semantics->precision - 1);
4512 exponent--;
4513 }
4514 } else {
4515 // If we are positive, we need to increment the significand.
4516
4517 // We only cross a binade boundary that requires adjusting the exponent if
4518 // the input is not a denormal and all of said input's significand bits
4519 // are set. If all of said conditions are true: clear the significand, set
4520 // the integral bit to 1, and increment the exponent. If we have a
4521 // denormal always increment since moving denormals and the numbers in the
4522 // smallest normal binade have the same exponent in our representation.
4523 // If there are only exponents, any increment always crosses the
4524 // BinadeBoundary.
4525 bool WillCrossBinadeBoundary = !APFloat::hasSignificand(*semantics) ||
4526 (!isDenormal() && isSignificandAllOnes());
4527
4528 if (WillCrossBinadeBoundary) {
4529 integerPart *Parts = significandParts();
4530 APInt::tcSet(Parts, 0, partCount());
4531 APInt::tcSetBit(Parts, semantics->precision - 1);
4532 assert(exponent != semantics->maxExponent &&
4533 "We can not increment an exponent beyond the maxExponent allowed"
4534 " by the given floating point semantics.");
4535 exponent++;
4536 } else {
4537 incrementSignificand();
4538 }
4539 }
4540 break;
4541 }
4542
4543 // If we are performing nextDown, swap sign so we have -nextUp(-x)
4544 if (nextDown)
4545 changeSign();
4546
4547 return result;
4548}
4549
4551 assert(isNaN() && "Can only be called on NaN values");
4552 // Number of bits in the payload, excluding the (maybe implied) integer bit.
4553 unsigned Bits = semantics->precision - 1;
4554 return APInt(Bits, ArrayRef(significandParts(), partCountForBits(Bits)));
4555}
4556
4557APFloatBase::ExponentType IEEEFloat::exponentNaN() const {
4558 return ::exponentNaN(*semantics);
4559}
4560
4561APFloatBase::ExponentType IEEEFloat::exponentInf() const {
4562 return ::exponentInf(*semantics);
4563}
4564
4565APFloatBase::ExponentType IEEEFloat::exponentZero() const {
4566 return ::exponentZero(*semantics);
4567}
4568
4569void IEEEFloat::makeInf(bool Negative) {
4570 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
4571 llvm_unreachable("This floating point format does not support Inf");
4572
4573 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
4574 // There is no Inf, so make NaN instead.
4575 makeNaN(false, Negative);
4576 return;
4577 }
4578 category = fcInfinity;
4579 sign = Negative;
4580 exponent = exponentInf();
4581 APInt::tcSet(significandParts(), 0, partCount());
4582}
4583
4584void IEEEFloat::makeZero(bool Negative) {
4585 if (!semantics->hasZero)
4586 llvm_unreachable("This floating point format does not support Zero");
4587
4588 category = fcZero;
4589 sign = Negative;
4590 if (semantics->nanEncoding == fltNanEncoding::NegativeZero) {
4591 // Merge negative zero to positive because 0b10000...000 is used for NaN
4592 sign = false;
4593 }
4594 exponent = exponentZero();
4595 APInt::tcSet(significandParts(), 0, partCount());
4596}
4597
4599 assert(isNaN());
4600 if (semantics->nonFiniteBehavior != fltNonfiniteBehavior::NanOnly)
4601 APInt::tcSetBit(significandParts(), semantics->precision - 2);
4602}
4603
4604int ilogb(const IEEEFloat &Arg) {
4605 if (Arg.isNaN())
4606 return APFloat::IEK_NaN;
4607 if (Arg.isZero())
4608 return APFloat::IEK_Zero;
4609 if (Arg.isInfinity())
4610 return APFloat::IEK_Inf;
4611 if (!Arg.isDenormal())
4612 return Arg.exponent;
4613
4614 IEEEFloat Normalized(Arg);
4615 int SignificandBits = Arg.getSemantics().precision - 1;
4616
4617 Normalized.exponent += SignificandBits;
4618 Normalized.normalize(APFloat::rmNearestTiesToEven, lfExactlyZero);
4619 return Normalized.exponent - SignificandBits;
4620}
4621
4623 auto MaxExp = X.getSemantics().maxExponent;
4624 auto MinExp = X.getSemantics().minExponent;
4625
4626 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
4627 // overflow; clamp it to a safe range before adding, but ensure that the range
4628 // is large enough that the clamp does not change the result. The range we
4629 // need to support is the difference between the largest possible exponent and
4630 // the normalized exponent of half the smallest denormal.
4631
4632 int SignificandBits = X.getSemantics().precision - 1;
4633 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
4634
4635 // Clamp to one past the range ends to let normalize handle overlflow.
4636 X.exponent += std::clamp(Exp, -MaxIncrement - 1, MaxIncrement);
4637 X.normalize(RoundingMode, lfExactlyZero);
4638 if (X.isNaN())
4639 X.makeQuiet();
4640 return X;
4641}
4642
4643IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM) {
4644 Exp = ilogb(Val);
4645
4646 // Quiet signalling nans.
4647 if (Exp == APFloat::IEK_NaN) {
4648 IEEEFloat Quiet(Val);
4649 Quiet.makeQuiet();
4650 return Quiet;
4651 }
4652
4653 if (Exp == APFloat::IEK_Inf)
4654 return Val;
4655
4656 // 1 is added because frexp is defined to return a normalized fraction in
4657 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
4658 Exp = Exp == APFloat::IEK_Zero ? 0 : Exp + 1;
4659 return scalbn(Val, -Exp, RM);
4660}
4661
4663 : Semantics(&S),
4664 Floats(new APFloat[2]{APFloat(APFloatBase::semIEEEdouble),
4665 APFloat(APFloatBase::semIEEEdouble)}) {
4666 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4667}
4668
4670 : Semantics(&S), Floats(new APFloat[2]{
4671 APFloat(APFloatBase::semIEEEdouble, uninitialized),
4672 APFloat(APFloatBase::semIEEEdouble, uninitialized)}) {
4673 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4674}
4675
4677 : Semantics(&S),
4678 Floats(new APFloat[2]{APFloat(APFloatBase::semIEEEdouble, I),
4679 APFloat(APFloatBase::semIEEEdouble)}) {
4680 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4681}
4682
4684 : Semantics(&S),
4685 Floats(new APFloat[2]{
4686 APFloat(APFloatBase::semIEEEdouble, APInt(64, I.getRawData()[0])),
4687 APFloat(APFloatBase::semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
4688 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4689}
4690
4692 APFloat &&Second)
4693 : Semantics(&S),
4694 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
4695 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4696 assert(&Floats[0].getSemantics() == &APFloatBase::semIEEEdouble);
4697 assert(&Floats[1].getSemantics() == &APFloatBase::semIEEEdouble);
4698}
4699
4701 : Semantics(RHS.Semantics),
4702 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
4703 APFloat(RHS.Floats[1])}
4704 : nullptr) {
4705 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4706}
4707
4709 : Semantics(RHS.Semantics), Floats(RHS.Floats) {
4710 RHS.Semantics = &APFloatBase::semBogus;
4711 RHS.Floats = nullptr;
4712 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4713}
4714
4716 if (Semantics == RHS.Semantics && RHS.Floats) {
4717 Floats[0] = RHS.Floats[0];
4718 Floats[1] = RHS.Floats[1];
4719 } else if (this != &RHS) {
4720 this->~DoubleAPFloat();
4721 new (this) DoubleAPFloat(RHS);
4722 }
4723 return *this;
4724}
4725
4726// Returns a result such that:
4727// 1. abs(Lo) <= ulp(Hi)/2
4728// 2. Hi == RTNE(Hi + Lo)
4729// 3. Hi + Lo == X + Y
4730//
4731// Requires that log2(X) >= log2(Y).
4732static std::pair<APFloat, APFloat> fastTwoSum(APFloat X, APFloat Y) {
4733 if (!X.isFinite())
4734 return {X, APFloat::getZero(X.getSemantics(), /*Negative=*/false)};
4735 APFloat Hi = X + Y;
4736 APFloat Delta = Hi - X;
4737 APFloat Lo = Y - Delta;
4738 return {Hi, Lo};
4739}
4740
4741// Implement addition, subtraction, multiplication and division based on:
4742// "Software for Doubled-Precision Floating-Point Computations",
4743// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
4744APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
4745 const APFloat &c, const APFloat &cc,
4746 roundingMode RM) {
4747 int Status = opOK;
4748 APFloat z = a;
4749 Status |= z.add(c, RM);
4750 if (!z.isFinite()) {
4751 if (!z.isInfinity()) {
4752 Floats[0] = std::move(z);
4753 Floats[1].makeZero(/* Neg = */ false);
4754 return (opStatus)Status;
4755 }
4756 Status = opOK;
4757 auto AComparedToC = a.compareAbsoluteValue(c);
4758 z = cc;
4759 Status |= z.add(aa, RM);
4760 if (AComparedToC == APFloat::cmpGreaterThan) {
4761 // z = cc + aa + c + a;
4762 Status |= z.add(c, RM);
4763 Status |= z.add(a, RM);
4764 } else {
4765 // z = cc + aa + a + c;
4766 Status |= z.add(a, RM);
4767 Status |= z.add(c, RM);
4768 }
4769 if (!z.isFinite()) {
4770 Floats[0] = std::move(z);
4771 Floats[1].makeZero(/* Neg = */ false);
4772 return (opStatus)Status;
4773 }
4774 Floats[0] = z;
4775 APFloat zz = aa;
4776 Status |= zz.add(cc, RM);
4777 if (AComparedToC == APFloat::cmpGreaterThan) {
4778 // Floats[1] = a - z + c + zz;
4779 Floats[1] = a;
4780 Status |= Floats[1].subtract(z, RM);
4781 Status |= Floats[1].add(c, RM);
4782 Status |= Floats[1].add(zz, RM);
4783 } else {
4784 // Floats[1] = c - z + a + zz;
4785 Floats[1] = c;
4786 Status |= Floats[1].subtract(z, RM);
4787 Status |= Floats[1].add(a, RM);
4788 Status |= Floats[1].add(zz, RM);
4789 }
4790 } else {
4791 // q = a - z;
4792 APFloat q = a;
4793 Status |= q.subtract(z, RM);
4794
4795 // zz = q + c + (a - (q + z)) + aa + cc;
4796 // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
4797 auto zz = q;
4798 Status |= zz.add(c, RM);
4799 Status |= q.add(z, RM);
4800 Status |= q.subtract(a, RM);
4801 q.changeSign();
4802 Status |= zz.add(q, RM);
4803 Status |= zz.add(aa, RM);
4804 Status |= zz.add(cc, RM);
4805 if (zz.isZero() && !zz.isNegative()) {
4806 Floats[0] = std::move(z);
4807 Floats[1].makeZero(/* Neg = */ false);
4808 return opOK;
4809 }
4810 Floats[0] = z;
4811 Status |= Floats[0].add(zz, RM);
4812 if (!Floats[0].isFinite()) {
4813 Floats[1].makeZero(/* Neg = */ false);
4814 return (opStatus)Status;
4815 }
4816 Floats[1] = std::move(z);
4817 Status |= Floats[1].subtract(Floats[0], RM);
4818 Status |= Floats[1].add(zz, RM);
4819 }
4820 return (opStatus)Status;
4821}
4822
4823APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
4824 const DoubleAPFloat &RHS,
4825 DoubleAPFloat &Out,
4826 roundingMode RM) {
4827 if (LHS.getCategory() == fcNaN) {
4828 Out = LHS;
4829 return opOK;
4830 }
4831 if (RHS.getCategory() == fcNaN) {
4832 Out = RHS;
4833 return opOK;
4834 }
4835 if (LHS.getCategory() == fcZero) {
4836 Out = RHS;
4837 return opOK;
4838 }
4839 if (RHS.getCategory() == fcZero) {
4840 Out = LHS;
4841 return opOK;
4842 }
4843 if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity &&
4844 LHS.isNegative() != RHS.isNegative()) {
4845 Out.makeNaN(false, Out.isNegative(), nullptr);
4846 return opInvalidOp;
4847 }
4848 if (LHS.getCategory() == fcInfinity) {
4849 Out = LHS;
4850 return opOK;
4851 }
4852 if (RHS.getCategory() == fcInfinity) {
4853 Out = RHS;
4854 return opOK;
4855 }
4856 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
4857
4858 APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
4859 CC(RHS.Floats[1]);
4860 assert(&A.getSemantics() == &APFloatBase::semIEEEdouble);
4861 assert(&AA.getSemantics() == &APFloatBase::semIEEEdouble);
4862 assert(&C.getSemantics() == &APFloatBase::semIEEEdouble);
4863 assert(&CC.getSemantics() == &APFloatBase::semIEEEdouble);
4864 assert(&Out.Floats[0].getSemantics() == &APFloatBase::semIEEEdouble);
4865 assert(&Out.Floats[1].getSemantics() == &APFloatBase::semIEEEdouble);
4866 return Out.addImpl(A, AA, C, CC, RM);
4867}
4868
4870 roundingMode RM) {
4871 return addWithSpecial(*this, RHS, *this, RM);
4872}
4873
4875 roundingMode RM) {
4876 changeSign();
4877 auto Ret = add(RHS, RM);
4878 changeSign();
4879 return Ret;
4880}
4881
4884 const auto &LHS = *this;
4885 auto &Out = *this;
4886 /* Interesting observation: For special categories, finding the lowest
4887 common ancestor of the following layered graph gives the correct
4888 return category:
4889
4890 NaN
4891 / \
4892 Zero Inf
4893 \ /
4894 Normal
4895
4896 e.g. NaN * NaN = NaN
4897 Zero * Inf = NaN
4898 Normal * Zero = Zero
4899 Normal * Inf = Inf
4900 */
4901 if (LHS.getCategory() == fcNaN) {
4902 Out = LHS;
4903 return opOK;
4904 }
4905 if (RHS.getCategory() == fcNaN) {
4906 Out = RHS;
4907 return opOK;
4908 }
4909 if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) ||
4910 (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) {
4911 Out.makeNaN(false, false, nullptr);
4912 return opOK;
4913 }
4914 if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) {
4915 Out = LHS;
4916 return opOK;
4917 }
4918 if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) {
4919 Out = RHS;
4920 return opOK;
4921 }
4922 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
4923 "Special cases not handled exhaustively");
4924
4925 int Status = opOK;
4926 APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
4927 // t = a * c
4928 APFloat T = A;
4929 Status |= T.multiply(C, RM);
4930 if (!T.isFiniteNonZero()) {
4931 Floats[0] = std::move(T);
4932 Floats[1].makeZero(/* Neg = */ false);
4933 return (opStatus)Status;
4934 }
4935
4936 // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
4937 APFloat Tau = A;
4938 T.changeSign();
4939 Status |= Tau.fusedMultiplyAdd(C, T, RM);
4940 T.changeSign();
4941 {
4942 // v = a * d
4943 APFloat V = A;
4944 Status |= V.multiply(D, RM);
4945 // w = b * c
4946 APFloat W = B;
4947 Status |= W.multiply(C, RM);
4948 Status |= V.add(W, RM);
4949 // tau += v + w
4950 Status |= Tau.add(V, RM);
4951 }
4952 // u = t + tau
4953 APFloat U = T;
4954 Status |= U.add(Tau, RM);
4955
4956 Floats[0] = U;
4957 if (!U.isFinite()) {
4958 Floats[1].makeZero(/* Neg = */ false);
4959 } else {
4960 // Floats[1] = (t - u) + tau
4961 Status |= T.subtract(U, RM);
4962 Status |= T.add(Tau, RM);
4963 Floats[1] = std::move(T);
4964 }
4965 return (opStatus)Status;
4966}
4967
4970 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
4971 "Unexpected Semantics");
4972 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
4973 auto Ret = Tmp.divide(
4974 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
4975 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
4976 return Ret;
4977}
4978
4980 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
4981 "Unexpected Semantics");
4982 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
4983 auto Ret = Tmp.remainder(
4984 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4985 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
4986 return Ret;
4987}
4988
4990 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
4991 "Unexpected Semantics");
4992 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
4993 auto Ret = Tmp.mod(
4994 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4995 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
4996 return Ret;
4997}
4998
5001 const DoubleAPFloat &Addend,
5003 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5004 "Unexpected Semantics");
5005 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
5006 auto Ret = Tmp.fusedMultiplyAdd(
5007 APFloat(APFloatBase::semPPCDoubleDoubleLegacy,
5008 Multiplicand.bitcastToAPInt()),
5009 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()),
5010 RM);
5011 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5012 return Ret;
5013}
5014
5016 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5017 "Unexpected Semantics");
5018 const APFloat &Hi = getFirst();
5019 const APFloat &Lo = getSecond();
5020
5021 APFloat RoundedHi = Hi;
5022 const opStatus HiStatus = RoundedHi.roundToIntegral(RM);
5023
5024 // We can reduce the problem to just the high part if the input:
5025 // 1. Represents a non-finite value.
5026 // 2. Has a component which is zero.
5027 if (!Hi.isFiniteNonZero() || Lo.isZero()) {
5028 Floats[0] = std::move(RoundedHi);
5029 Floats[1].makeZero(/*Neg=*/false);
5030 return HiStatus;
5031 }
5032
5033 // Adjust `Rounded` in the direction of `TieBreaker` if `ToRound` was at a
5034 // halfway point.
5035 auto RoundToNearestHelper = [](APFloat ToRound, APFloat Rounded,
5036 APFloat TieBreaker) {
5037 // RoundingError tells us which direction we rounded:
5038 // - RoundingError > 0: we rounded up.
5039 // - RoundingError < 0: we rounded down.
5040 // Sterbenz' lemma ensures that RoundingError is exact.
5041 const APFloat RoundingError = Rounded - ToRound;
5042 if (TieBreaker.isNonZero() &&
5043 TieBreaker.isNegative() != RoundingError.isNegative() &&
5044 abs(RoundingError).isExactlyValue(0.5))
5045 Rounded.add(
5046 APFloat::getOne(Rounded.getSemantics(), TieBreaker.isNegative()),
5048 return Rounded;
5049 };
5050
5051 // Case 1: Hi is not an integer.
5052 // Special cases are for rounding modes that are sensitive to ties.
5053 if (RoundedHi != Hi) {
5054 // We need to consider the case where Hi was between two integers and the
5055 // rounding mode broke the tie when, in fact, Lo may have had a different
5056 // sign than Hi.
5057 if (RM == rmNearestTiesToAway || RM == rmNearestTiesToEven)
5058 RoundedHi = RoundToNearestHelper(Hi, RoundedHi, Lo);
5059
5060 Floats[0] = std::move(RoundedHi);
5061 Floats[1].makeZero(/*Neg=*/false);
5062 return HiStatus;
5063 }
5064
5065 // Case 2: Hi is an integer.
5066 // Special cases are for rounding modes which are rounding towards or away from zero.
5067 RoundingMode LoRoundingMode;
5068 if (RM == rmTowardZero)
5069 // When our input is positive, we want the Lo component rounded toward
5070 // negative infinity to get the smallest result magnitude. Likewise,
5071 // negative inputs want the Lo component rounded toward positive infinity.
5072 LoRoundingMode = isNegative() ? rmTowardPositive : rmTowardNegative;
5073 else
5074 LoRoundingMode = RM;
5075
5076 APFloat RoundedLo = Lo;
5077 const opStatus LoStatus = RoundedLo.roundToIntegral(LoRoundingMode);
5078 if (LoRoundingMode == rmNearestTiesToAway)
5079 // We need to consider the case where Lo was between two integers and the
5080 // rounding mode broke the tie when, in fact, Hi may have had a different
5081 // sign than Lo.
5082 RoundedLo = RoundToNearestHelper(Lo, RoundedLo, Hi);
5083
5084 // We must ensure that the final result has no overlap between the two APFloat values.
5085 std::tie(RoundedHi, RoundedLo) = fastTwoSum(RoundedHi, RoundedLo);
5086
5087 Floats[0] = std::move(RoundedHi);
5088 Floats[1] = std::move(RoundedLo);
5089 return LoStatus;
5090}
5091
5093 Floats[0].changeSign();
5094 Floats[1].changeSign();
5095}
5096
5099 // Compare absolute values of the high parts.
5100 const cmpResult HiPartCmp = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
5101 if (HiPartCmp != cmpEqual)
5102 return HiPartCmp;
5103
5104 // Zero, regardless of sign, is equal.
5105 if (Floats[1].isZero() && RHS.Floats[1].isZero())
5106 return cmpEqual;
5107
5108 // At this point, |this->Hi| == |RHS.Hi|.
5109 // The magnitude is |Hi+Lo| which is Hi+|Lo| if signs of Hi and Lo are the
5110 // same, and Hi-|Lo| if signs are different.
5111 const bool ThisIsSubtractive =
5112 Floats[0].isNegative() != Floats[1].isNegative();
5113 const bool RHSIsSubtractive =
5114 RHS.Floats[0].isNegative() != RHS.Floats[1].isNegative();
5115
5116 // Case 1: The low part of 'this' is zero.
5117 if (Floats[1].isZero())
5118 // We are comparing |Hi| vs. |Hi| ± |RHS.Lo|.
5119 // If RHS is subtractive, its magnitude is smaller.
5120 // If RHS is additive, its magnitude is larger.
5121 return RHSIsSubtractive ? cmpGreaterThan : cmpLessThan;
5122
5123 // Case 2: The low part of 'RHS' is zero (and we know 'this' is not).
5124 if (RHS.Floats[1].isZero())
5125 // We are comparing |Hi| ± |This.Lo| vs. |Hi|.
5126 // If 'this' is subtractive, its magnitude is smaller.
5127 // If 'this' is additive, its magnitude is larger.
5128 return ThisIsSubtractive ? cmpLessThan : cmpGreaterThan;
5129
5130 // If their natures differ, the additive one is larger.
5131 if (ThisIsSubtractive != RHSIsSubtractive)
5132 return ThisIsSubtractive ? cmpLessThan : cmpGreaterThan;
5133
5134 // Case 3: Both are additive (Hi+|Lo|) or both are subtractive (Hi-|Lo|).
5135 // The comparison now depends on the magnitude of the low parts.
5136 const cmpResult LoPartCmp = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
5137
5138 if (ThisIsSubtractive) {
5139 // Both are subtractive (Hi-|Lo|), so the comparison of |Lo| is inverted.
5140 if (LoPartCmp == cmpLessThan)
5141 return cmpGreaterThan;
5142 if (LoPartCmp == cmpGreaterThan)
5143 return cmpLessThan;
5144 }
5145
5146 // If additive, the comparison of |Lo| is direct.
5147 // If equal, they are equal.
5148 return LoPartCmp;
5149}
5150
5152 return Floats[0].getCategory();
5153}
5154
5155bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
5156
5158 Floats[0].makeInf(Neg);
5159 Floats[1].makeZero(/* Neg = */ false);
5160}
5161
5163 Floats[0].makeZero(Neg);
5164 Floats[1].makeZero(/* Neg = */ false);
5165}
5166
5168 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5169 "Unexpected Semantics");
5170 Floats[0] =
5171 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
5172 Floats[1] =
5173 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
5174 if (Neg)
5175 changeSign();
5176}
5177
5179 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5180 "Unexpected Semantics");
5181 Floats[0].makeSmallest(Neg);
5182 Floats[1].makeZero(/* Neg = */ false);
5183}
5184
5186 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5187 "Unexpected Semantics");
5188 Floats[0] =
5189 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x0360000000000000ull));
5190 if (Neg)
5191 Floats[0].changeSign();
5192 Floats[1].makeZero(/* Neg = */ false);
5193}
5194
5195void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
5196 Floats[0].makeNaN(SNaN, Neg, fill);
5197 Floats[1].makeZero(/* Neg = */ false);
5198}
5199
5201 auto Result = Floats[0].compare(RHS.Floats[0]);
5202 // |Float[0]| > |Float[1]|
5203 if (Result == APFloat::cmpEqual)
5204 return Floats[1].compare(RHS.Floats[1]);
5205 return Result;
5206}
5207
5209 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
5210 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
5211}
5212
5214 if (Arg.Floats)
5215 return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
5216 return hash_combine(Arg.Semantics);
5217}
5218
5220 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5221 "Unexpected Semantics");
5222 uint64_t Data[] = {
5223 Floats[0].bitcastToAPInt().getRawData()[0],
5224 Floats[1].bitcastToAPInt().getRawData()[0],
5225 };
5226 return APInt(128, Data);
5227}
5228
5230 roundingMode RM) {
5231 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5232 "Unexpected Semantics");
5233 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy);
5234 auto Ret = Tmp.convertFromString(S, RM);
5235 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5236 return Ret;
5237}
5238
5239// The double-double lattice of values corresponds to numbers which obey:
5240// - abs(lo) <= 1/2 * ulp(hi)
5241// - roundTiesToEven(hi + lo) == hi
5242//
5243// nextUp must choose the smallest output > input that follows these rules.
5244// nexDown must choose the largest output < input that follows these rules.
5246 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5247 "Unexpected Semantics");
5248 // nextDown(x) = -nextUp(-x)
5249 if (nextDown) {
5250 changeSign();
5251 APFloat::opStatus Result = next(/*nextDown=*/false);
5252 changeSign();
5253 return Result;
5254 }
5255 switch (getCategory()) {
5256 case fcInfinity:
5257 // nextUp(+inf) = +inf
5258 // nextUp(-inf) = -getLargest()
5259 if (isNegative())
5260 makeLargest(true);
5261 return opOK;
5262
5263 case fcNaN:
5264 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
5265 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
5266 // change the payload.
5267 if (getFirst().isSignaling()) {
5268 // For consistency, propagate the sign of the sNaN to the qNaN.
5269 makeNaN(false, isNegative(), nullptr);
5270 return opInvalidOp;
5271 }
5272 return opOK;
5273
5274 case fcZero:
5275 // nextUp(pm 0) = +getSmallest()
5276 makeSmallest(false);
5277 return opOK;
5278
5279 case fcNormal:
5280 break;
5281 }
5282
5283 const APFloat &HiOld = getFirst();
5284 const APFloat &LoOld = getSecond();
5285
5286 APFloat NextLo = LoOld;
5287 NextLo.next(/*nextDown=*/false);
5288
5289 // We want to admit values where:
5290 // 1. abs(Lo) <= ulp(Hi)/2
5291 // 2. Hi == RTNE(Hi + lo)
5292 auto InLattice = [](const APFloat &Hi, const APFloat &Lo) {
5293 return Hi + Lo == Hi;
5294 };
5295
5296 // Check if (HiOld, nextUp(LoOld) is in the lattice.
5297 if (InLattice(HiOld, NextLo)) {
5298 // Yes, the result is (HiOld, nextUp(LoOld)).
5299 Floats[1] = std::move(NextLo);
5300
5301 // TODO: Because we currently rely on semPPCDoubleDoubleLegacy, our maximum
5302 // value is defined to have exactly 106 bits of precision. This limitation
5303 // results in semPPCDoubleDouble being unable to reach its maximum canonical
5304 // value.
5305 DoubleAPFloat Largest{*Semantics, uninitialized};
5306 Largest.makeLargest(/*Neg=*/false);
5307 if (compare(Largest) == cmpGreaterThan)
5308 makeInf(/*Neg=*/false);
5309
5310 return opOK;
5311 }
5312
5313 // Now we need to handle the cases where (HiOld, nextUp(LoOld)) is not the
5314 // correct result. We know the new hi component will be nextUp(HiOld) but our
5315 // lattice rules make it a little ambiguous what the correct NextLo must be.
5316 APFloat NextHi = HiOld;
5317 NextHi.next(/*nextDown=*/false);
5318
5319 // nextUp(getLargest()) == INFINITY
5320 if (NextHi.isInfinity()) {
5321 makeInf(/*Neg=*/false);
5322 return opOK;
5323 }
5324
5325 // IEEE 754-2019 5.3.1:
5326 // "If x is the negative number of least magnitude in x's format, nextUp(x) is
5327 // -0."
5328 if (NextHi.isZero()) {
5329 makeZero(/*Neg=*/true);
5330 return opOK;
5331 }
5332
5333 // abs(NextLo) must be <= ulp(NextHi)/2. We want NextLo to be as close to
5334 // negative infinity as possible.
5335 NextLo = neg(scalbn(harrisonUlp(NextHi), -1, rmTowardZero));
5336 if (!InLattice(NextHi, NextLo))
5337 // RTNE may mean that Lo must be < ulp(NextHi) / 2 so we bump NextLo.
5338 NextLo.next(/*nextDown=*/false);
5339
5340 Floats[0] = std::move(NextHi);
5341 Floats[1] = std::move(NextLo);
5342
5343 return opOK;
5344}
5345
5346APFloat::opStatus DoubleAPFloat::convertToSignExtendedInteger(
5347 MutableArrayRef<integerPart> Input, unsigned int Width, bool IsSigned,
5348 roundingMode RM, bool *IsExact) const {
5349 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5350 "Unexpected Semantics");
5351
5352 // If Hi is not finite, or Lo is zero, the value is entirely represented
5353 // by Hi. Delegate to the simpler single-APFloat conversion.
5354 if (!getFirst().isFiniteNonZero() || getSecond().isZero())
5355 return getFirst().convertToInteger(Input, Width, IsSigned, RM, IsExact);
5356
5357 // First, round the full double-double value to an integral value. This
5358 // simplifies the rest of the function, as we no longer need to consider
5359 // fractional parts.
5360 *IsExact = false;
5361 DoubleAPFloat Integral = *this;
5362 const opStatus RoundStatus = Integral.roundToIntegral(RM);
5363 if (RoundStatus == opInvalidOp)
5364 return opInvalidOp;
5365 const APFloat &IntegralHi = Integral.getFirst();
5366 const APFloat &IntegralLo = Integral.getSecond();
5367
5368 // If rounding results in either component being zero, the sum is trivial.
5369 // Delegate to the simpler single-APFloat conversion.
5370 bool HiIsExact;
5371 if (IntegralHi.isZero() || IntegralLo.isZero()) {
5372 const opStatus HiStatus =
5373 IntegralHi.convertToInteger(Input, Width, IsSigned, RM, &HiIsExact);
5374 // The conversion from an integer-valued float to an APInt may fail if the
5375 // result would be out of range. Regardless, taking this path is only
5376 // possible if rounding occurred during the initial `roundToIntegral`.
5377 return HiStatus == opOK ? opInexact : HiStatus;
5378 }
5379
5380 // A negative number cannot be represented by an unsigned integer.
5381 // Since a double-double is canonical, if Hi is negative, the sum is negative.
5382 if (!IsSigned && IntegralHi.isNegative())
5383 return opInvalidOp;
5384
5385 // Handle the special boundary case where |Hi| is exactly the power of two
5386 // that marks the edge of the integer's range (e.g., 2^63 for int64_t). In
5387 // this situation, Hi itself won't fit, but the sum Hi + Lo might.
5388 // `PositiveOverflowWidth` is the bit number for this boundary (N-1 for
5389 // signed, N for unsigned).
5390 bool LoIsExact;
5391 const int HiExactLog2 = IntegralHi.getExactLog2Abs();
5392 const unsigned PositiveOverflowWidth = IsSigned ? Width - 1 : Width;
5393 if (HiExactLog2 >= 0 &&
5394 static_cast<unsigned>(HiExactLog2) == PositiveOverflowWidth) {
5395 // If Hi and Lo have the same sign, |Hi + Lo| > |Hi|, so the sum is
5396 // guaranteed to overflow. E.g., for uint128_t, (2^128, 1) overflows.
5397 if (IntegralHi.isNegative() == IntegralLo.isNegative())
5398 return opInvalidOp;
5399
5400 // If the signs differ, the sum will fit. We can compute the result using
5401 // properties of two's complement arithmetic without a wide intermediate
5402 // integer. E.g., for uint128_t, (2^128, -1) should be 2^128 - 1.
5403 const opStatus LoStatus = IntegralLo.convertToInteger(
5404 Input, Width, /*IsSigned=*/true, RM, &LoIsExact);
5405 if (LoStatus == opInvalidOp)
5406 return opInvalidOp;
5407
5408 // Adjust the bit pattern of Lo to account for Hi's value:
5409 // - For unsigned (Hi=2^Width): `2^Width + Lo` in `Width`-bit
5410 // arithmetic is equivalent to just `Lo`. The conversion of `Lo` above
5411 // already produced the correct final bit pattern.
5412 // - For signed (Hi=2^(Width-1)): The sum `2^(Width-1) + Lo` (where Lo<0)
5413 // can be computed by taking the two's complement pattern for `Lo` and
5414 // clearing the sign bit.
5415 if (IsSigned && !IntegralHi.isNegative())
5416 APInt::tcClearBit(Input.data(), PositiveOverflowWidth);
5417 *IsExact = RoundStatus == opOK;
5418 return RoundStatus;
5419 }
5420
5421 // Convert Hi into an integer. This may not fit but that is OK: we know that
5422 // Hi + Lo would not fit either in this situation.
5423 const opStatus HiStatus = IntegralHi.convertToInteger(
5424 Input, Width, IsSigned, rmTowardZero, &HiIsExact);
5425 if (HiStatus == opInvalidOp)
5426 return HiStatus;
5427
5428 // Convert Lo into a temporary integer of the same width.
5429 APSInt LoResult{Width, /*isUnsigned=*/!IsSigned};
5430 const opStatus LoStatus =
5431 IntegralLo.convertToInteger(LoResult, rmTowardZero, &LoIsExact);
5432 if (LoStatus == opInvalidOp)
5433 return LoStatus;
5434
5435 // Add Lo to Hi. This addition is guaranteed not to overflow because of the
5436 // double-double canonicalization rule (`|Lo| <= ulp(Hi)/2`). The only case
5437 // where the sum could cross the integer type's boundary is when Hi is a
5438 // power of two, which is handled by the special case block above.
5439 APInt::tcAdd(Input.data(), LoResult.getRawData(), /*carry=*/0, Input.size());
5440
5441 *IsExact = RoundStatus == opOK;
5442 return RoundStatus;
5443}
5444
5447 unsigned int Width, bool IsSigned,
5448 roundingMode RM, bool *IsExact) const {
5449 opStatus FS =
5450 convertToSignExtendedInteger(Input, Width, IsSigned, RM, IsExact);
5451
5452 if (FS == opInvalidOp) {
5453 const unsigned DstPartsCount = partCountForBits(Width);
5454 assert(DstPartsCount <= Input.size() && "Integer too big");
5455
5456 unsigned Bits;
5457 if (getCategory() == fcNaN)
5458 Bits = 0;
5459 else if (isNegative())
5460 Bits = IsSigned;
5461 else
5462 Bits = Width - IsSigned;
5463
5464 tcSetLeastSignificantBits(Input.data(), DstPartsCount, Bits);
5465 if (isNegative() && IsSigned)
5466 APInt::tcShiftLeft(Input.data(), DstPartsCount, Width - 1);
5467 }
5468
5469 return FS;
5470}
5471
5472APFloat::opStatus DoubleAPFloat::handleOverflow(roundingMode RM) {
5473 switch (RM) {
5475 makeLargest(/*Neg=*/isNegative());
5476 break;
5478 if (isNegative())
5479 makeInf(/*Neg=*/true);
5480 else
5481 makeLargest(/*Neg=*/false);
5482 break;
5484 if (isNegative())
5485 makeLargest(/*Neg=*/true);
5486 else
5487 makeInf(/*Neg=*/false);
5488 break;
5491 makeInf(/*Neg=*/isNegative());
5492 break;
5493 default:
5494 llvm_unreachable("Invalid rounding mode found");
5495 }
5496 opStatus S = opInexact;
5497 if (!getFirst().isFinite())
5498 S = static_cast<opStatus>(S | opOverflow);
5499 return S;
5500}
5501
5502APFloat::opStatus DoubleAPFloat::convertFromUnsignedParts(
5503 const integerPart *Src, unsigned int SrcCount, roundingMode RM) {
5504 // Find the most significant bit of the source integer. APInt::tcMSB returns
5505 // UINT_MAX for a zero value.
5506 const unsigned SrcMSB = APInt::tcMSB(Src, SrcCount);
5507 if (SrcMSB == UINT_MAX) {
5508 // The source integer is 0.
5509 makeZero(/*Neg=*/false);
5510 return opOK;
5511 }
5512
5513 // Create a minimally-sized APInt to represent the source value.
5514 const unsigned SrcBitWidth = SrcMSB + 1;
5515 APSInt SrcInt{APInt{/*numBits=*/SrcBitWidth, ArrayRef(Src, SrcCount)},
5516 /*isUnsigned=*/true};
5517
5518 // Stage 1: Initial Approximation.
5519 // Convert the source integer SrcInt to the Hi part of the DoubleAPFloat.
5520 // We use round-to-nearest because it minimizes the initial error, which is
5521 // crucial for the subsequent steps.
5523 Hi.convertFromAPInt(SrcInt, /*IsSigned=*/false, rmNearestTiesToEven);
5524
5525 // If the first approximation already overflows, the number is too large.
5526 // NOTE: The underlying semantics are *more* conservative when choosing to
5527 // overflow because their notion of ULP is much larger. As such, it is always
5528 // safe to overflow at the DoubleAPFloat level if the APFloat overflows.
5529 if (!Hi.isFinite())
5530 return handleOverflow(RM);
5531
5532 // Stage 2: Exact Error Calculation.
5533 // Calculate the exact error of the first approximation: Error = SrcInt - Hi.
5534 // This is done by converting Hi back to an integer and subtracting it from
5535 // the original source.
5536 bool HiAsIntIsExact;
5537 // Create an integer representation of Hi. Its width is determined by the
5538 // exponent of Hi, ensuring it's just large enough. This width can exceed
5539 // SrcBitWidth if the conversion to Hi rounded up to a power of two.
5540 // accurately when converted back to an integer.
5541 APSInt HiAsInt{static_cast<uint32_t>(ilogb(Hi) + 1), /*isUnsigned=*/true};
5542 Hi.convertToInteger(HiAsInt, rmNearestTiesToEven, &HiAsIntIsExact);
5543 const APInt Error = SrcInt.zext(HiAsInt.getBitWidth()) - HiAsInt;
5544
5545 // Stage 3: Error Approximation and Rounding.
5546 // Convert the integer error into the Lo part of the DoubleAPFloat. This step
5547 // captures the remainder of the original number. The rounding mode for this
5548 // conversion (LoRM) may need to be adjusted from the user-requested RM to
5549 // ensure the final sum (Hi + Lo) rounds correctly.
5550 roundingMode LoRM = RM;
5551 // Adjustments are only necessary when the initial approximation Hi was an
5552 // overestimate, making the Error negative.
5553 if (Error.isNegative()) {
5554 if (RM == rmNearestTiesToAway) {
5555 // For rmNearestTiesToAway, a tie should round away from zero. Since
5556 // SrcInt is positive, this means rounding toward +infinity.
5557 // A standard conversion of a negative Error would round ties toward
5558 // -infinity, causing the final sum Hi + Lo to be smaller. To
5559 // counteract this, we detect the tie case and override the rounding
5560 // mode for Lo to rmTowardPositive.
5561 const unsigned ErrorActiveBits = Error.getSignificantBits() - 1;
5562 const unsigned LoPrecision = getSecond().getSemantics().precision;
5563 if (ErrorActiveBits > LoPrecision) {
5564 const unsigned RoundingBoundary = ErrorActiveBits - LoPrecision;
5565 // A tie occurs when the bits to be truncated are of the form 100...0.
5566 // This is detected by checking if the number of trailing zeros is
5567 // exactly one less than the number of bits being truncated.
5568 if (Error.countTrailingZeros() == RoundingBoundary - 1)
5569 LoRM = rmTowardPositive;
5570 }
5571 } else if (RM == rmTowardZero) {
5572 // For rmTowardZero, the final positive result must be truncated (rounded
5573 // down). When Hi is an overestimate, Error is negative. A standard
5574 // rmTowardZero conversion of Error would make it *less* negative,
5575 // effectively rounding the final sum Hi + Lo *up*. To ensure the sum
5576 // rounds down correctly, we force Lo to round toward -infinity.
5577 LoRM = rmTowardNegative;
5578 }
5579 }
5580
5582 opStatus Status = Lo.convertFromAPInt(Error, /*IsSigned=*/true, LoRM);
5583
5584 // Renormalize the pair (Hi, Lo) into a canonical DoubleAPFloat form where the
5585 // components do not overlap. fastTwoSum performs this operation.
5586 std::tie(Hi, Lo) = fastTwoSum(Hi, Lo);
5587 Floats[0] = std::move(Hi);
5588 Floats[1] = std::move(Lo);
5589
5590 // A final check for overflow is needed because fastTwoSum can cause a
5591 // carry-out from Lo that pushes Hi to infinity.
5592 if (!getFirst().isFinite())
5593 return handleOverflow(RM);
5594
5595 // The largest DoubleAPFloat must be canonical. Values which are larger are
5596 // not canonical and are equivalent to overflow.
5597 if (getFirst().isFiniteNonZero() && Floats[0].isLargest()) {
5598 DoubleAPFloat Largest{*Semantics};
5599 Largest.makeLargest(/*Neg=*/false);
5600 if (compare(Largest) == APFloat::cmpGreaterThan)
5601 return handleOverflow(RM);
5602 }
5603
5604 // The final status of the operation is determined by the conversion of the
5605 // error term. If Lo could represent Error exactly, the entire conversion
5606 // is exact. Otherwise, it's inexact.
5607 return Status;
5608}
5609
5611 bool IsSigned,
5612 roundingMode RM) {
5613 const bool NegateInput = IsSigned && Input.isNegative();
5614 APInt API = Input;
5615 if (NegateInput)
5616 API.negate();
5617
5619 convertFromUnsignedParts(API.getRawData(), API.getNumWords(), RM);
5620 if (NegateInput)
5621 changeSign();
5622 return Status;
5623}
5624
5626 unsigned int HexDigits,
5627 bool UpperCase,
5628 roundingMode RM) const {
5629 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5630 "Unexpected Semantics");
5631 return APFloat(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt())
5632 .convertToHexString(DST, HexDigits, UpperCase, RM);
5633}
5634
5636 return getCategory() == fcNormal &&
5637 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
5638 // (double)(Hi + Lo) == Hi defines a normal number.
5639 Floats[0] != Floats[0] + Floats[1]);
5640}
5641
5643 if (getCategory() != fcNormal)
5644 return false;
5645 DoubleAPFloat Tmp(*this);
5646 Tmp.makeSmallest(this->isNegative());
5647 return Tmp.compare(*this) == cmpEqual;
5648}
5649
5651 if (getCategory() != fcNormal)
5652 return false;
5653
5654 DoubleAPFloat Tmp(*this);
5656 return Tmp.compare(*this) == cmpEqual;
5657}
5658
5660 if (getCategory() != fcNormal)
5661 return false;
5662 DoubleAPFloat Tmp(*this);
5663 Tmp.makeLargest(this->isNegative());
5664 return Tmp.compare(*this) == cmpEqual;
5665}
5666
5668 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5669 "Unexpected Semantics");
5670 return Floats[0].isInteger() && Floats[1].isInteger();
5671}
5672
5674 unsigned FormatPrecision,
5675 unsigned FormatMaxPadding,
5676 bool TruncateZero) const {
5677 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5678 "Unexpected Semantics");
5679 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt())
5680 .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
5681}
5682
5684 // In order for Hi + Lo to be a power of two, the following must be true:
5685 // 1. Hi must be a power of two.
5686 // 2. Lo must be zero.
5687 if (getSecond().isNonZero())
5688 return INT_MIN;
5689 return getFirst().getExactLog2Abs();
5690}
5691
5692int ilogb(const DoubleAPFloat &Arg) {
5693 const APFloat &Hi = Arg.getFirst();
5694 const APFloat &Lo = Arg.getSecond();
5695 int IlogbResult = ilogb(Hi);
5696 // Zero and non-finite values can delegate to ilogb(Hi).
5697 if (Arg.getCategory() != fcNormal)
5698 return IlogbResult;
5699 // If Lo can't change the binade, we can delegate to ilogb(Hi).
5700 if (Lo.isZero() || Hi.isNegative() == Lo.isNegative())
5701 return IlogbResult;
5702 if (Hi.getExactLog2Abs() == INT_MIN)
5703 return IlogbResult;
5704 // Numbers of the form 2^a - 2^b or -2^a + 2^b are almost powers of two but
5705 // get nudged out of the binade by the low component.
5706 return IlogbResult - 1;
5707}
5708
5711 assert(Arg.Semantics == &APFloatBase::PPCDoubleDouble() &&
5712 "Unexpected Semantics");
5714 scalbn(Arg.Floats[0], Exp, RM),
5715 scalbn(Arg.Floats[1], Exp, RM));
5716}
5717
5718DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
5720 assert(Arg.Semantics == &APFloatBase::PPCDoubleDouble() &&
5721 "Unexpected Semantics");
5722
5723 // Get the unbiased exponent e of the number, where |Arg| = m * 2^e for m in
5724 // [1.0, 2.0).
5725 Exp = ilogb(Arg);
5726
5727 // For NaNs, quiet any signaling NaN and return the result, as per standard
5728 // practice.
5729 if (Exp == APFloat::IEK_NaN) {
5730 DoubleAPFloat Quiet{Arg};
5731 Quiet.getFirst() = Quiet.getFirst().makeQuiet();
5732 return Quiet;
5733 }
5734
5735 // For infinity, return it unchanged. The exponent remains IEK_Inf.
5736 if (Exp == APFloat::IEK_Inf)
5737 return Arg;
5738
5739 // For zero, the fraction is zero and the standard requires the exponent be 0.
5740 if (Exp == APFloat::IEK_Zero) {
5741 Exp = 0;
5742 return Arg;
5743 }
5744
5745 const APFloat &Hi = Arg.getFirst();
5746 const APFloat &Lo = Arg.getSecond();
5747
5748 // frexp requires the fraction's absolute value to be in [0.5, 1.0).
5749 // ilogb provides an exponent for an absolute value in [1.0, 2.0).
5750 // Increment the exponent to ensure the fraction is in the correct range.
5751 ++Exp;
5752
5753 const bool SignsDisagree = Hi.isNegative() != Lo.isNegative();
5754 APFloat Second = Lo;
5755 if (Arg.getCategory() == APFloat::fcNormal && Lo.isFiniteNonZero()) {
5756 roundingMode LoRoundingMode;
5757 // The interpretation of rmTowardZero depends on the sign of the combined
5758 // Arg rather than the sign of the component.
5759 if (RM == rmTowardZero)
5760 LoRoundingMode = Arg.isNegative() ? rmTowardPositive : rmTowardNegative;
5761 // For rmNearestTiesToAway, we face a similar problem. If signs disagree,
5762 // Lo is a correction *toward* zero relative to Hi. Rounding Lo
5763 // "away from zero" based on its own sign would move the value in the
5764 // wrong direction. As a safe proxy, we use rmNearestTiesToEven, which is
5765 // direction-agnostic. We only need to bother with this if Lo is scaled
5766 // down.
5767 else if (RM == rmNearestTiesToAway && SignsDisagree && Exp > 0)
5768 LoRoundingMode = rmNearestTiesToEven;
5769 else
5770 LoRoundingMode = RM;
5771 Second = scalbn(Lo, -Exp, LoRoundingMode);
5772 // The rmNearestTiesToEven proxy is correct most of the time, but it
5773 // differs from rmNearestTiesToAway when the scaled value of Lo is an
5774 // exact midpoint.
5775 // NOTE: This is morally equivalent to roundTiesTowardZero.
5776 if (RM == rmNearestTiesToAway && LoRoundingMode == rmNearestTiesToEven) {
5777 // Re-scale the result back to check if rounding occurred.
5778 const APFloat RecomposedLo = scalbn(Second, Exp, rmNearestTiesToEven);
5779 if (RecomposedLo != Lo) {
5780 // RoundingError tells us which direction we rounded:
5781 // - RoundingError > 0: we rounded up.
5782 // - RoundingError < 0: we down up.
5783 const APFloat RoundingError = RecomposedLo - Lo;
5784 // Determine if scalbn(Lo, -Exp) landed exactly on a midpoint.
5785 // We do this by checking if the absolute rounding error is exactly
5786 // half a ULP of the result.
5787 const APFloat UlpOfSecond = harrisonUlp(Second);
5788 const APFloat ScaledUlpOfSecond =
5789 scalbn(UlpOfSecond, Exp - 1, rmNearestTiesToEven);
5790 const bool IsMidpoint = abs(RoundingError) == ScaledUlpOfSecond;
5791 const bool RoundedLoAway =
5792 Second.isNegative() == RoundingError.isNegative();
5793 // The sign of Hi and Lo disagree and we rounded Lo away: we must
5794 // decrease the magnitude of Second to increase the magnitude
5795 // First+Second.
5796 if (IsMidpoint && RoundedLoAway)
5797 Second.next(/*nextDown=*/!Second.isNegative());
5798 }
5799 }
5800 // Handle a tricky edge case where Arg is slightly less than a power of two
5801 // (e.g., Arg = 2^k - epsilon). In this situation:
5802 // 1. Hi is 2^k, and Lo is a small negative value -epsilon.
5803 // 2. ilogb(Arg) correctly returns k-1.
5804 // 3. Our initial Exp becomes (k-1) + 1 = k.
5805 // 4. Scaling Hi (2^k) by 2^-k would yield a magnitude of 1.0 and
5806 // scaling Lo by 2^-k would yield zero. This would make the result 1.0
5807 // which is an invalid fraction, as the required interval is [0.5, 1.0).
5808 // We detect this specific case by checking if Hi is a power of two and if
5809 // the scaled Lo underflowed to zero. The fix: Increment Exp to k+1. This
5810 // adjusts the scale factor, causing Hi to be scaled to 0.5, which is a
5811 // valid fraction.
5812 if (Second.isZero() && SignsDisagree && Hi.getExactLog2Abs() != INT_MIN)
5813 ++Exp;
5814 }
5815
5816 APFloat First = scalbn(Hi, -Exp, RM);
5818 std::move(Second));
5819}
5820
5821APInt DoubleAPFloat::getNaNPayload() const { return Floats[0].getNaNPayload(); }
5822} // namespace detail
5823
5824APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
5825 if (usesLayout<IEEEFloat>(Semantics)) {
5826 new (&IEEE) IEEEFloat(std::move(F));
5827 return;
5828 }
5829 if (usesLayout<DoubleAPFloat>(Semantics)) {
5830 const fltSemantics& S = F.getSemantics();
5831 new (&Double) DoubleAPFloat(Semantics, APFloat(std::move(F), S),
5833 return;
5834 }
5835 llvm_unreachable("Unexpected semantics");
5836}
5837
5842
5843hash_code hash_value(const APFloat &Arg) {
5844 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
5845 return hash_value(Arg.U.IEEE);
5846 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
5847 return hash_value(Arg.U.Double);
5848 llvm_unreachable("Unexpected semantics");
5849}
5850
5852 : APFloat(Semantics) {
5853 auto StatusOrErr = convertFromString(S, rmNearestTiesToEven);
5854 assert(StatusOrErr && "Invalid floating point representation");
5855 consumeError(StatusOrErr.takeError());
5856}
5857
5859 if (isZero())
5860 return isNegative() ? fcNegZero : fcPosZero;
5861 if (isNormal())
5862 return isNegative() ? fcNegNormal : fcPosNormal;
5863 if (isDenormal())
5865 if (isInfinity())
5866 return isNegative() ? fcNegInf : fcPosInf;
5867 assert(isNaN() && "Other class of FP constant");
5868 return isSignaling() ? fcSNan : fcQNan;
5869}
5870
5871bool APFloat::getExactInverse(APFloat *Inv) const {
5872 // Only finite, non-zero numbers can have a useful, representable inverse.
5873 // This check filters out +/- zero, +/- infinity, and NaN.
5874 if (!isFiniteNonZero())
5875 return false;
5876
5877 // Historically, this function rejects subnormal inputs. One reason why this
5878 // might be important is that subnormals may behave differently under FTZ/DAZ
5879 // runtime behavior.
5880 if (isDenormal())
5881 return false;
5882
5883 // A number has an exact, representable inverse if and only if it is a power
5884 // of two.
5885 //
5886 // Mathematical Rationale:
5887 // 1. A binary floating-point number x is a dyadic rational, meaning it can
5888 // be written as x = M / 2^k for integers M (the significand) and k.
5889 // 2. The inverse is 1/x = 2^k / M.
5890 // 3. For 1/x to also be a dyadic rational (and thus exactly representable
5891 // in binary), its denominator M must also be a power of two.
5892 // Let's say M = 2^m.
5893 // 4. Substituting this back into the formula for x, we get
5894 // x = (2^m) / (2^k) = 2^(m-k).
5895 //
5896 // This proves that x must be a power of two.
5897
5898 // getExactLog2Abs() returns the integer exponent if the number is a power of
5899 // two or INT_MIN if it is not.
5900 const int Exp = getExactLog2Abs();
5901 if (Exp == INT_MIN)
5902 return false;
5903
5904 // The inverse of +/- 2^Exp is +/- 2^(-Exp). We can compute this by
5905 // scaling 1.0 by the negated exponent.
5906 APFloat Reciprocal =
5907 scalbn(APFloat::getOne(getSemantics(), /*Negative=*/isNegative()), -Exp,
5908 rmTowardZero);
5909
5910 // scalbn might round if the resulting exponent -Exp is outside the
5911 // representable range, causing overflow (to infinity) or underflow. We
5912 // must verify that the result is still the exact power of two we expect.
5913 if (Reciprocal.getExactLog2Abs() != -Exp)
5914 return false;
5915
5916 // Avoid multiplication with a subnormal, it is not safe on all platforms and
5917 // may be slower than a normal division.
5918 if (Reciprocal.isDenormal())
5919 return false;
5920
5921 assert(Reciprocal.isFiniteNonZero());
5922
5923 if (Inv)
5924 *Inv = std::move(Reciprocal);
5925
5926 return true;
5927}
5928
5930 roundingMode RM, bool *losesInfo) {
5931 if (&getSemantics() == &ToSemantics) {
5932 *losesInfo = false;
5933 return opOK;
5934 }
5935 if (usesLayout<IEEEFloat>(getSemantics()) &&
5936 usesLayout<IEEEFloat>(ToSemantics))
5937 return U.IEEE.convert(ToSemantics, RM, losesInfo);
5938 if (usesLayout<IEEEFloat>(getSemantics()) &&
5939 usesLayout<DoubleAPFloat>(ToSemantics)) {
5940 assert(&ToSemantics == &APFloatBase::semPPCDoubleDouble);
5941 auto Ret =
5942 U.IEEE.convert(APFloatBase::semPPCDoubleDoubleLegacy, RM, losesInfo);
5943 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
5944 return Ret;
5945 }
5946 if (usesLayout<DoubleAPFloat>(getSemantics()) &&
5947 usesLayout<IEEEFloat>(ToSemantics)) {
5948 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
5949 *this = APFloat(std::move(getIEEE()), ToSemantics);
5950 return Ret;
5951 }
5952 llvm_unreachable("Unexpected semantics");
5953}
5954
5958
5960 SmallVector<char, 16> Buffer;
5961 toString(Buffer);
5962 OS << Buffer;
5963}
5964
5965#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5967 print(dbgs());
5968 dbgs() << '\n';
5969}
5970#endif
5971
5973 NID.Add(bitcastToAPInt());
5974}
5975
5977 roundingMode rounding_mode,
5978 bool *isExact) const {
5979 unsigned bitWidth = result.getBitWidth();
5980 SmallVector<uint64_t, 4> parts(result.getNumWords());
5981 opStatus status = convertToInteger(parts, bitWidth, result.isSigned(),
5982 rounding_mode, isExact);
5983 // Keeps the original signed-ness.
5984 result = APInt(bitWidth, parts);
5985 return status;
5986}
5987
5989 if (&getSemantics() == &APFloatBase::semIEEEdouble)
5990 return getIEEE().convertToDouble();
5991 assert(isRepresentableBy(getSemantics(), semIEEEdouble) &&
5992 "Float semantics is not representable by IEEEdouble");
5993 APFloat Temp = *this;
5994 bool LosesInfo;
5995 [[maybe_unused]] opStatus St =
5996 Temp.convert(APFloatBase::semIEEEdouble, rmNearestTiesToEven, &LosesInfo);
5997 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
5998 return Temp.getIEEE().convertToDouble();
5999}
6000
6001#ifdef HAS_IEE754_FLOAT128
6002float128 APFloat::convertToQuad() const {
6003 if (&getSemantics() == &APFloatBase::semIEEEquad)
6004 return getIEEE().convertToQuad();
6005 assert(isRepresentableBy(getSemantics(), semIEEEquad) &&
6006 "Float semantics is not representable by IEEEquad");
6007 APFloat Temp = *this;
6008 bool LosesInfo;
6009 [[maybe_unused]] opStatus St =
6010 Temp.convert(APFloatBase::semIEEEquad, rmNearestTiesToEven, &LosesInfo);
6011 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
6012 return Temp.getIEEE().convertToQuad();
6013}
6014#endif
6015
6017 if (&getSemantics() == &APFloatBase::semIEEEsingle)
6018 return getIEEE().convertToFloat();
6019 assert(isRepresentableBy(getSemantics(), semIEEEsingle) &&
6020 "Float semantics is not representable by IEEEsingle");
6021 APFloat Temp = *this;
6022 bool LosesInfo;
6023 [[maybe_unused]] opStatus St =
6024 Temp.convert(APFloatBase::semIEEEsingle, rmNearestTiesToEven, &LosesInfo);
6025 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
6026 return Temp.getIEEE().convertToFloat();
6027}
6028
6031 .Case("Float8E5M2", getSizeInBits(semFloat8E5M2))
6032 .Case("Float8E5M2FNUZ", getSizeInBits(semFloat8E5M2FNUZ))
6033 .Case("Float8E4M3", getSizeInBits(semFloat8E4M3))
6034 .Case("Float8E4M3FN", getSizeInBits(semFloat8E4M3FN))
6035 .Case("Float8E4M3FNUZ", getSizeInBits(semFloat8E4M3FNUZ))
6036 .Case("Float8E4M3B11FNUZ", getSizeInBits(semFloat8E4M3B11FNUZ))
6037 .Case("Float8E3M4", getSizeInBits(semFloat8E3M4))
6038 .Case("Float8E8M0FNU", getSizeInBits(semFloat8E8M0FNU))
6039 .Case("Float6E3M2FN", getSizeInBits(semFloat6E3M2FN))
6040 .Case("Float6E2M3FN", getSizeInBits(semFloat6E2M3FN))
6041 .Case("Float4E2M1FN", getSizeInBits(semFloat4E2M1FN))
6042 .Case("Float8E5M3FNU", getSizeInBits(semFloat8E5M3FNU))
6043 .Default(0);
6044}
6045
6049
6051 // TODO: extend to remaining arbitrary FP types: Float8E4M3, Float8E3M4,
6052 // Float8E5M2FNUZ, Float8E4M3FNUZ, Float8E4M3B11FNUZ, Float8E8M0FNU,
6053 // Float8E5M3FNU.
6055 .Case("Float8E5M2", &semFloat8E5M2)
6056 .Case("Float8E4M3FN", &semFloat8E4M3FN)
6057 .Case("Float4E2M1FN", &semFloat4E2M1FN)
6058 .Case("Float6E3M2FN", &semFloat6E3M2FN)
6059 .Case("Float6E2M3FN", &semFloat6E2M3FN)
6060 .Default(nullptr);
6061}
6062
6063APFloat::Storage::~Storage() {
6064 if (usesLayout<IEEEFloat>(*semantics)) {
6065 IEEE.~IEEEFloat();
6066 return;
6067 }
6068 if (usesLayout<DoubleAPFloat>(*semantics)) {
6069 Double.~DoubleAPFloat();
6070 return;
6071 }
6072 llvm_unreachable("Unexpected semantics");
6073}
6074
6075APFloat::Storage::Storage(const APFloat::Storage &RHS) {
6076 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
6077 new (this) IEEEFloat(RHS.IEEE);
6078 return;
6079 }
6080 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6081 new (this) DoubleAPFloat(RHS.Double);
6082 return;
6083 }
6084 llvm_unreachable("Unexpected semantics");
6085}
6086
6087APFloat::Storage::Storage(APFloat::Storage &&RHS) {
6088 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
6089 new (this) IEEEFloat(std::move(RHS.IEEE));
6090 return;
6091 }
6092 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6093 new (this) DoubleAPFloat(std::move(RHS.Double));
6094 return;
6095 }
6096 llvm_unreachable("Unexpected semantics");
6097}
6098
6099APFloat::Storage &APFloat::Storage::operator=(const APFloat::Storage &RHS) {
6100 if (usesLayout<IEEEFloat>(*semantics) &&
6101 usesLayout<IEEEFloat>(*RHS.semantics)) {
6102 IEEE = RHS.IEEE;
6103 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
6104 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6105 Double = RHS.Double;
6106 } else if (this != &RHS) {
6107 this->~Storage();
6108 new (this) Storage(RHS);
6109 }
6110 return *this;
6111}
6112
6113APFloat::Storage &APFloat::Storage::operator=(APFloat::Storage &&RHS) {
6114 if (usesLayout<IEEEFloat>(*semantics) &&
6115 usesLayout<IEEEFloat>(*RHS.semantics)) {
6116 IEEE = std::move(RHS.IEEE);
6117 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
6118 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6119 Double = std::move(RHS.Double);
6120 } else if (this != &RHS) {
6121 this->~Storage();
6122 new (this) Storage(std::move(RHS));
6123 }
6124 return *this;
6125}
6126
6127namespace {
6128
6129APFloat::opStatus getOpStatusFromLibc(int libc_exceptions) {
6131 if (libc_exceptions & FE_INVALID)
6133 if (libc_exceptions & FE_DIVBYZERO)
6135 if (libc_exceptions & FE_OVERFLOW)
6137 if (libc_exceptions & FE_UNDERFLOW)
6139 if (libc_exceptions & FE_INEXACT)
6141 return status;
6142}
6143
6144} // namespace
6145
6146// TODO: Support other rounding modes when LLVM libc math implement static
6147// roundings.
6148std::optional<APFloat> exp(const APFloat &x, RoundingMode rounding_mode,
6149 APFloat::opStatus *status) {
6150
6151 if (rounding_mode == APFloatBase::rmNearestTiesToEven) {
6152 if (APFloat::SemanticsToEnum(x.getSemantics()) ==
6154 float x_val = x.convertToFloat();
6155 int exc =
6156 LIBC_NAMESPACE::shared::check::exp_exceptions(x_val, FE_TONEAREST);
6157 if (status) {
6158 *status = getOpStatusFromLibc(exc);
6159 if (x.isSignaling()) {
6160 // 32-bit x86 will silence sNaN when loading floats, so we explicitly
6161 // add the INVALID exception here.
6162 *status =
6163 static_cast<APFloat::opStatus>(*status | APFloat::opInvalidOp);
6164 }
6165 }
6166 float result = LIBC_NAMESPACE::shared::expf(x_val);
6167 return APFloat(result);
6168 }
6169 if (APFloat::SemanticsToEnum(x.getSemantics()) ==
6171 double x_val = x.convertToDouble();
6172 int exc =
6173 LIBC_NAMESPACE::shared::check::exp_exceptions(x_val, FE_TONEAREST);
6174 if (status) {
6175 *status = getOpStatusFromLibc(exc);
6176 if (x.isSignaling()) {
6177 // 32-bit x86 will silence sNaN when loading floats, so we explicitly
6178 // add the INVALID exception here.
6179 *status =
6180 static_cast<APFloat::opStatus>(*status | APFloat::opInvalidOp);
6181 }
6182 }
6183 double result = LIBC_NAMESPACE::shared::exp(x_val);
6184 return APFloat(result);
6185 }
6186 }
6187 return std::nullopt;
6188}
6189
6190} // namespace llvm
6191
6192#undef APFLOAT_DISPATCH_ON_SEMANTICS
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define PackCategoriesIntoKey(_lhs, _rhs)
A macro used to combine two fcCategory enums into one key which can be used in a switch statement to ...
Definition APFloat.cpp:63
This file declares a class to represent arbitrary precision floating point values and provide a varie...
#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL)
Definition APFloat.h:27
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
static bool isNeg(Value *V)
Returns true if the operation is a negation of V, and it works for both integers and floats.
static bool isSigned(unsigned Opcode)
Utilities for dealing with flags related to floating point properties and mode controls.
This file defines a hash set that can be used to remove duplication of nodes in a graph.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define P(N)
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
This file contains some functions that are useful when dealing with strings.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static const fltSemantics & Float8E4M3FN()
Definition APFloat.h:314
static LLVM_ABI const llvm::fltSemantics & EnumToSemantics(Semantics S)
Definition APFloat.cpp:134
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
Definition APFloat.cpp:287
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:343
static constexpr roundingMode rmTowardZero
Definition APFloat.h:357
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:262
llvm::RoundingMode roundingMode
IEEE-754R 4.3: Rounding-direction attributes.
Definition APFloat.h:351
static const fltSemantics & BFloat()
Definition APFloat.h:303
static const fltSemantics & IEEEquad()
Definition APFloat.h:306
static LLVM_ABI unsigned int semanticsSizeInBits(const fltSemantics &)
Definition APFloat.cpp:265
static const fltSemantics & Float8E8M0FNU()
Definition APFloat.h:321
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:283
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition APFloat.cpp:318
static const fltSemantics & x87DoubleExtended()
Definition APFloat.h:326
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:356
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:353
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
Definition APFloat.cpp:6046
static LLVM_ABI bool hasSignBitInMSB(const fltSemantics &)
Definition APFloat.cpp:300
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:258
friend class APFloat
Definition APFloat.h:299
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:254
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:291
static LLVM_ABI Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
Definition APFloat.cpp:183
int32_t ExponentType
A signed type to represent a floating point numbers unbiased exponent.
Definition APFloat.h:156
static constexpr unsigned integerPartWidth
Definition APFloat.h:153
static const fltSemantics & PPCDoubleDoubleLegacy()
Definition APFloat.h:308
APInt::WordType integerPart
Definition APFloat.h:152
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:279
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:304
static const fltSemantics & Float8E5M2FNUZ()
Definition APFloat.h:312
static const fltSemantics & Float8E4M3FNUZ()
Definition APFloat.h:315
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:355
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
static const fltSemantics & Float4E2M1FN()
Definition APFloat.h:325
static const fltSemantics & Float6E2M3FN()
Definition APFloat.h:324
static const fltSemantics & Float8E4M3()
Definition APFloat.h:313
static const fltSemantics & Float8E4M3B11FNUZ()
Definition APFloat.h:316
static LLVM_ABI bool isRepresentableBy(const fltSemantics &A, const fltSemantics &B)
Definition APFloat.cpp:230
static const fltSemantics & Float8E3M4()
Definition APFloat.h:319
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:295
static const fltSemantics & Float8E5M2()
Definition APFloat.h:311
fltCategory
Category of internally-represented number.
Definition APFloat.h:379
static constexpr roundingMode rmNearestTiesToAway
Definition APFloat.h:358
static const fltSemantics & PPCDoubleDouble()
Definition APFloat.h:307
static const fltSemantics & Float6E3M2FN()
Definition APFloat.h:323
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:369
static const fltSemantics & Float8E5M3FNU()
Definition APFloat.h:322
static LLVM_ABI unsigned getArbitraryFPFormatSizeInBits(StringRef Format)
Returns the size in bits of a valid arbitrary floating-point format string, or 0 if the string is not...
Definition APFloat.cpp:6029
static LLVM_ABI const fltSemantics * getArbitraryFPSemantics(StringRef Format)
Returns the fltSemantics for a given arbitrary FP format string, or nullptr if invalid.
Definition APFloat.cpp:6050
static const fltSemantics & FloatTF32()
Definition APFloat.h:320
static LLVM_ABI unsigned int semanticsIntSizeInBits(const fltSemantics &, bool)
Definition APFloat.cpp:268
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1216
LLVM_ABI void Profile(FoldingSetNodeID &NID) const
Used to insert APFloat objects, or objects that contain APFloat objects, into FoldingSets.
Definition APFloat.cpp:5972
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1304
bool isFiniteNonZero() const
Definition APFloat.h:1585
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5929
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1631
bool isNegative() const
Definition APFloat.h:1575
LLVM_ABI bool getExactInverse(APFloat *Inv) const
If this value is normal and has an exact, normal, multiplicative inverse, store it in inv and return ...
Definition APFloat.cpp:5871
cmpResult compareAbsoluteValue(const APFloat &RHS) const
Definition APFloat.h:1530
friend DoubleAPFloat
Definition APFloat.h:1663
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:5988
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition APFloat.h:1612
bool isNormal() const
Definition APFloat.h:1579
bool isDenormal() const
Definition APFloat.h:1576
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1277
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition APFloat.cpp:5955
LLVM_ABI friend hash_code hash_value(const APFloat &Arg)
See friend declarations above.
Definition APFloat.cpp:5843
const fltSemantics & getSemantics() const
Definition APFloat.h:1583
bool isFinite() const
Definition APFloat.h:1580
bool isNaN() const
Definition APFloat.h:1573
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1184
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
Definition APFloat.h:1565
LLVM_ABI float convertToFloat() const
Converts this APFloat to host float value.
Definition APFloat.cpp:6016
bool isSignaling() const
Definition APFloat.h:1577
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
Definition APFloat.h:1331
opStatus remainder(const APFloat &RHS)
Definition APFloat.h:1313
bool isZero() const
Definition APFloat.h:1571
APInt bitcastToAPInt() const
Definition APFloat.h:1467
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1428
opStatus next(bool nextDown)
Definition APFloat.h:1350
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1194
friend APFloat scalbn(APFloat X, int Exp, roundingMode RM)
static APFloat getSmallest(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) finite number in the given semantics.
Definition APFloat.h:1244
LLVM_ABI FPClassTest classify() const
Return the FPClassTest which will return true for the value.
Definition APFloat.cpp:5858
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1322
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
Fill this APFloat with the result of a string conversion.
Definition APFloat.cpp:5838
friend IEEEFloat
Definition APFloat.h:1662
LLVM_DUMP_METHOD void dump() const
Definition APFloat.cpp:5966
LLVM_ABI void print(raw_ostream &) const
Definition APFloat.cpp:5959
opStatus roundToIntegral(roundingMode RM)
Definition APFloat.h:1344
static bool hasSignificand(const fltSemantics &Sem)
Returns true if the given semantics has actual significand.
Definition APFloat.h:1269
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1175
bool isInfinity() const
Definition APFloat.h:1572
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1599
static LLVM_ABI void tcSetBit(WordType *, unsigned bit)
Set the given bit of a bignum. Zero-based.
Definition APInt.cpp:2403
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
static LLVM_ABI void tcSet(WordType *, WordType, unsigned)
Sets the least significant part of a bignum to the input value, and zeroes out higher parts.
Definition APInt.cpp:2375
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1793
static LLVM_ABI int tcExtractBit(const WordType *, unsigned bit)
Extract the given bit of a bignum; returns 0 or 1. Zero-based.
Definition APInt.cpp:2398
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
static LLVM_ABI WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned)
DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
Definition APInt.cpp:2477
static LLVM_ABI void tcExtract(WordType *, unsigned dstCount, const WordType *, unsigned srcBits, unsigned srcLSB)
Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to DST, of dstCOUNT parts,...
Definition APInt.cpp:2447
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:968
static LLVM_ABI int tcCompare(const WordType *, const WordType *, unsigned)
Comparison (unsigned) of two bignums.
Definition APInt.cpp:2787
static APInt floatToBits(float V)
Converts a float to APInt bits.
Definition APInt.h:1777
uint64_t WordType
Definition APInt.h:80
static LLVM_ABI void tcAssign(WordType *, const WordType *, unsigned)
Assign one bignum to another.
Definition APInt.cpp:2383
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
static LLVM_ABI void tcShiftRight(WordType *, unsigned Words, unsigned Count)
Shift a bignum right Count bits.
Definition APInt.cpp:2761
static LLVM_ABI void tcFullMultiply(WordType *, const WordType *, const WordType *, unsigned, unsigned)
DST = LHS * RHS, where DST has width the sum of the widths of the operands.
Definition APInt.cpp:2667
unsigned getNumWords() const
Get the number of words.
Definition APInt.h:1520
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
static LLVM_ABI void tcClearBit(WordType *, unsigned bit)
Clear the given bit of a bignum. Zero-based.
Definition APInt.cpp:2408
void negate()
Negate this APInt in place.
Definition APInt.h:1493
static WordType tcDecrement(WordType *dst, unsigned parts)
Decrement a bignum in-place. Return the borrow flag.
Definition APInt.h:1943
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1664
static LLVM_ABI unsigned tcLSB(const WordType *, unsigned n)
Returns the bit number of the least or most significant set bit of a number.
Definition APInt.cpp:2414
static LLVM_ABI void tcShiftLeft(WordType *, unsigned Words, unsigned Count)
Shift a bignum left Count bits.
Definition APInt.cpp:2734
static LLVM_ABI bool tcIsZero(const WordType *, unsigned)
Returns true if a bignum is zero, false otherwise.
Definition APInt.cpp:2389
static LLVM_ABI unsigned tcMSB(const WordType *parts, unsigned n)
Returns the bit number of the most significant set bit of a number.
Definition APInt.cpp:2427
float bitsToFloat() const
Converts APInt bits to a float.
Definition APInt.h:1761
static LLVM_ABI int tcMultiplyPart(WordType *dst, const WordType *src, WordType multiplier, WordType carry, unsigned srcParts, unsigned dstParts, bool add)
DST += SRC * MULTIPLIER + PART if add is true DST = SRC * MULTIPLIER + PART if add is false.
Definition APInt.cpp:2565
static constexpr unsigned APINT_BITS_PER_WORD
Bits in a word.
Definition APInt.h:86
static LLVM_ABI WordType tcSubtract(WordType *, const WordType *, WordType carry, unsigned)
DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
Definition APInt.cpp:2512
static LLVM_ABI void tcNegate(WordType *, unsigned)
Negate a bignum in-place.
Definition APInt.cpp:2551
static APInt doubleToBits(double V)
Converts a double to APInt bits.
Definition APInt.h:1769
static WordType tcIncrement(WordType *dst, unsigned parts)
Increment a bignum in-place. Return the carry flag.
Definition APInt.h:1938
double bitsToDouble() const
Converts APInt bits to a double.
Definition APInt.h:1747
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition APInt.h:576
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:865
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
bool isSigned() const
Definition APSInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:208
void Add(const T &x)
Definition FoldingSet.h:248
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
const char * iterator
Definition StringRef.h:60
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:635
iterator begin() const
Definition StringRef.h:114
char back() const
Get the last character in the string.
Definition StringRef.h:153
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:720
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
char front() const
Get the first character in the string.
Definition StringRef.h:147
iterator end() const
Definition StringRef.h:116
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:661
bool consume_front_insensitive(StringRef Prefix)
Returns true if this StringRef has the given prefix, ignoring case, and removes that prefix.
Definition StringRef.h:681
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI void makeSmallestNormalized(bool Neg)
Definition APFloat.cpp:5185
LLVM_ABI DoubleAPFloat & operator=(const DoubleAPFloat &RHS)
Definition APFloat.cpp:4715
LLVM_ABI void changeSign()
Definition APFloat.cpp:5092
LLVM_ABI bool isLargest() const
Definition APFloat.cpp:5659
LLVM_ABI opStatus remainder(const DoubleAPFloat &RHS)
Definition APFloat.cpp:4979
LLVM_ABI opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4882
LLVM_ABI fltCategory getCategory() const
Definition APFloat.cpp:5151
LLVM_ABI bool bitwiseIsEqual(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5208
LLVM_ABI LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.cpp:5683
LLVM_ABI opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.cpp:5610
LLVM_ABI APInt bitcastToAPInt() const
Definition APFloat.cpp:5219
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
Definition APFloat.cpp:5229
LLVM_ABI bool isSmallest() const
Definition APFloat.cpp:5642
LLVM_ABI opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4874
LLVM_ABI friend hash_code hash_value(const DoubleAPFloat &Arg)
Definition APFloat.cpp:5213
LLVM_ABI cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5098
LLVM_ABI bool isDenormal() const
Definition APFloat.cpp:5635
LLVM_ABI opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.cpp:5446
LLVM_ABI void makeSmallest(bool Neg)
Definition APFloat.cpp:5178
LLVM_ABI friend int ilogb(const DoubleAPFloat &X)
Definition APFloat.cpp:5692
LLVM_ABI opStatus next(bool nextDown)
Definition APFloat.cpp:5245
LLVM_ABI void makeInf(bool Neg)
Definition APFloat.cpp:5157
LLVM_ABI bool isInteger() const
Definition APFloat.cpp:5667
LLVM_ABI void makeZero(bool Neg)
Definition APFloat.cpp:5162
LLVM_ABI opStatus divide(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4968
LLVM_ABI bool isSmallestNormalized() const
Definition APFloat.cpp:5650
LLVM_ABI opStatus mod(const DoubleAPFloat &RHS)
Definition APFloat.cpp:4989
LLVM_ABI DoubleAPFloat(const fltSemantics &S)
Definition APFloat.cpp:4662
LLVM_ABI void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision, unsigned FormatMaxPadding, bool TruncateZero=true) const
Definition APFloat.cpp:5673
LLVM_ABI void makeLargest(bool Neg)
Definition APFloat.cpp:5167
LLVM_ABI cmpResult compare(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5200
LLVM_ABI friend DoubleAPFloat scalbn(const DoubleAPFloat &X, int Exp, roundingMode)
LLVM_ABI opStatus roundToIntegral(roundingMode RM)
Definition APFloat.cpp:5015
LLVM_ABI opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, const DoubleAPFloat &Addend, roundingMode RM)
Definition APFloat.cpp:5000
LLVM_ABI APInt getNaNPayload() const
Definition APFloat.cpp:5821
LLVM_ABI unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
Definition APFloat.cpp:5625
LLVM_ABI bool isNegative() const
Definition APFloat.cpp:5155
LLVM_ABI opStatus add(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4869
LLVM_ABI void makeNaN(bool SNaN, bool Neg, const APInt *fill)
Definition APFloat.cpp:5195
LLVM_ABI unsigned int convertToHexString(char *dst, unsigned int hexDigits, bool upperCase, roundingMode) const
Write out a hexadecimal representation of the floating point value to DST, which must be of sufficien...
Definition APFloat.cpp:3216
LLVM_ABI cmpResult compareAbsoluteValue(const IEEEFloat &) const
Definition APFloat.cpp:1465
LLVM_ABI opStatus mod(const IEEEFloat &)
C fmod, or llvm frem.
Definition APFloat.cpp:2221
fltCategory getCategory() const
Definition APFloat.h:597
LLVM_ABI opStatus convertFromAPInt(const APInt &, bool, roundingMode)
Definition APFloat.cpp:2776
LLVM_ABI APInt getNaNPayload() const
Definition APFloat.cpp:4550
bool isFiniteNonZero() const
Definition APFloat.h:600
bool needsCleanup() const
Returns whether this instance allocated memory.
Definition APFloat.h:487
LLVM_ABI void makeLargest(bool Neg=false)
Make this number the largest magnitude normal number in the given semantics.
Definition APFloat.cpp:3977
LLVM_ABI LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.cpp:4372
LLVM_ABI APInt bitcastToAPInt() const
Definition APFloat.cpp:3597
LLVM_ABI friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Definition APFloat.cpp:4622
LLVM_ABI cmpResult compare(const IEEEFloat &) const
IEEE comparison with another floating point number (NaNs compare unordered, 0==-0).
Definition APFloat.cpp:2389
bool isNegative() const
IEEE-754R isSignMinus: Returns true if and only if the current value is negative.
Definition APFloat.h:562
LLVM_ABI opStatus divide(const IEEEFloat &, roundingMode)
Definition APFloat.cpp:2095
bool isNaN() const
Returns true if and only if the float is a quiet or signaling NaN.
Definition APFloat.h:587
LLVM_ABI opStatus remainder(const IEEEFloat &)
IEEE remainder.
Definition APFloat.cpp:2113
LLVM_ABI double convertToDouble() const
Definition APFloat.cpp:3670
LLVM_ABI float convertToFloat() const
Definition APFloat.cpp:3663
LLVM_ABI opStatus subtract(const IEEEFloat &, roundingMode)
Definition APFloat.cpp:2071
LLVM_ABI void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Converts this value into a decimal string.
Definition APFloat.cpp:4328
LLVM_ABI void makeSmallest(bool Neg=false)
Make this number the smallest magnitude denormal number in the given semantics.
Definition APFloat.cpp:4009
LLVM_ABI void makeInf(bool Neg=false)
Definition APFloat.cpp:4569
LLVM_ABI bool isSmallestNormalized() const
Returns true if this is the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.cpp:986
LLVM_ABI void makeQuiet()
Definition APFloat.cpp:4598
LLVM_ABI bool isLargest() const
Returns true if and only if the number has the largest possible finite magnitude in the current seman...
Definition APFloat.cpp:1088
LLVM_ABI opStatus add(const IEEEFloat &, roundingMode)
Definition APFloat.cpp:2065
bool isFinite() const
Returns true if and only if the current value is zero, subnormal, or normal.
Definition APFloat.h:574
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
Definition APFloat.cpp:3159
LLVM_ABI void makeNaN(bool SNaN=false, bool Neg=false, const APInt *fill=nullptr)
Definition APFloat.cpp:874
LLVM_ABI opStatus multiply(const IEEEFloat &, roundingMode)
Definition APFloat.cpp:2077
LLVM_ABI opStatus roundToIntegral(roundingMode)
Definition APFloat.cpp:2304
LLVM_ABI IEEEFloat & operator=(const IEEEFloat &)
Definition APFloat.cpp:946
LLVM_ABI bool bitwiseIsEqual(const IEEEFloat &) const
Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
Definition APFloat.cpp:1113
LLVM_ABI void makeSmallestNormalized(bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.cpp:4023
LLVM_ABI bool isInteger() const
Returns true if and only if the number is an exact integer.
Definition APFloat.cpp:1105
LLVM_ABI IEEEFloat(const fltSemantics &)
Definition APFloat.cpp:1140
LLVM_ABI opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode)
Definition APFloat.cpp:2258
LLVM_ABI friend int ilogb(const IEEEFloat &Arg)
Definition APFloat.cpp:4604
LLVM_ABI opStatus next(bool nextDown)
IEEE-754R 5.3.1: nextUp/nextDown.
Definition APFloat.cpp:4417
bool isInfinity() const
IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
Definition APFloat.h:584
const fltSemantics & getSemantics() const
Definition APFloat.h:598
bool isZero() const
Returns true if and only if the float is plus or minus zero.
Definition APFloat.h:577
LLVM_ABI bool isSignaling() const
Returns true if and only if the float is a signaling NaN.
Definition APFloat.cpp:4401
LLVM_ABI void makeZero(bool Neg=false)
Definition APFloat.cpp:4584
LLVM_ABI opStatus convert(const fltSemantics &, roundingMode, bool *)
IEEEFloat::convert - convert a value of one floating point type to another.
Definition APFloat.cpp:2465
LLVM_ABI void changeSign()
Definition APFloat.cpp:2023
LLVM_ABI bool isDenormal() const
IEEE-754R isSubnormal(): Returns true if and only if the float is a denormal.
Definition APFloat.cpp:971
LLVM_ABI opStatus convertToInteger(MutableArrayRef< integerPart >, unsigned int, bool, roundingMode, bool *) const
Definition APFloat.cpp:2721
LLVM_ABI bool isSmallest() const
Returns true if and only if the number has the smallest possible non-zero magnitude in the current se...
Definition APFloat.cpp:978
An opaque object representing a hash code.
Definition Hashing.h:77
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static constexpr opStatus opInexact
Definition APFloat.h:463
LLVM_ABI SlowDynamicAPInt abs(const SlowDynamicAPInt &X)
Redeclarations of friend declarations above to make it discoverable by lookups.
static constexpr fltCategory fcNaN
Definition APFloat.h:465
static constexpr opStatus opDivByZero
Definition APFloat.h:460
static constexpr opStatus opOverflow
Definition APFloat.h:461
static constexpr cmpResult cmpLessThan
Definition APFloat.h:455
const char unit< Period >::value[]
Definition Chrono.h:104
static void tcSetLeastSignificantBits(APInt::WordType *dst, unsigned parts, unsigned bits)
Definition APFloat.cpp:1488
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:451
static constexpr uninitializedTag uninitialized
Definition APFloat.h:445
static constexpr fltCategory fcZero
Definition APFloat.h:467
static constexpr opStatus opOK
Definition APFloat.h:458
static constexpr cmpResult cmpGreaterThan
Definition APFloat.h:456
static constexpr unsigned integerPartWidth
Definition APFloat.h:453
LLVM_ABI hash_code hash_value(const IEEEFloat &Arg)
Definition APFloat.cpp:3356
APFloatBase::ExponentType ExponentType
Definition APFloat.h:444
static constexpr fltCategory fcNormal
Definition APFloat.h:466
static constexpr opStatus opInvalidOp
Definition APFloat.h:459
APFloatBase::opStatus opStatus
Definition APFloat.h:441
LLVM_ABI IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM)
Definition APFloat.cpp:4643
APFloatBase::uninitializedTag uninitializedTag
Definition APFloat.h:439
static constexpr cmpResult cmpUnordered
Definition APFloat.h:457
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:450
APFloatBase::roundingMode roundingMode
Definition APFloat.h:440
APFloatBase::cmpResult cmpResult
Definition APFloat.h:442
static constexpr fltCategory fcInfinity
Definition APFloat.h:464
static constexpr roundingMode rmNearestTiesToAway
Definition APFloat.h:448
static constexpr roundingMode rmTowardZero
Definition APFloat.h:452
static constexpr opStatus opUnderflow
Definition APFloat.h:462
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:446
LLVM_ABI int ilogb(const IEEEFloat &Arg)
Definition APFloat.cpp:4604
static constexpr cmpResult cmpEqual
Definition APFloat.h:454
LLVM_ABI IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Definition APFloat.cpp:4622
static std::pair< APFloat, APFloat > fastTwoSum(APFloat X, APFloat Y)
Definition APFloat.cpp:4732
APFloatBase::integerPart integerPart
Definition APFloat.h:438
FormattedNumber decValue(uint64_t N, unsigned Width=DEC_WIDTH)
Definition LVSupport.h:123
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
This is an optimization pass for GlobalISel generic memory operations.
static unsigned int partAsHex(char *dst, APFloatBase::integerPart part, unsigned int count, const char *hexDigitChars)
Definition APFloat.cpp:771
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1759
static const char infinityL[]
Definition APFloat.cpp:762
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
static constexpr unsigned int partCountForBits(unsigned int bits)
Definition APFloat.cpp:349
static const char NaNU[]
Definition APFloat.cpp:765
static unsigned int HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
Definition APFloat.cpp:647
static unsigned int powerOf5(APFloatBase::integerPart *dst, unsigned int power)
Definition APFloat.cpp:706
unsigned hexDigitValue(char C)
Interpret the given character C as a hexadecimal digit and return its value.
static APFloat harrisonUlp(const APFloat &X)
Definition APFloat.cpp:818
static constexpr APFloatBase::ExponentType exponentZero(const fltSemantics &semantics)
Definition APFloat.cpp:323
static Expected< int > totalExponent(StringRef::iterator p, StringRef::iterator end, int exponentAdjustment)
Definition APFloat.cpp:406
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
const unsigned int maxPowerOfFiveExponent
Definition APFloat.cpp:249
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1684
static char * writeUnsignedDecimal(char *dst, unsigned int n)
Definition APFloat.cpp:788
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2173
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
const unsigned int maxPrecision
Definition APFloat.cpp:248
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition APFloat.h:1705
static const char NaNL[]
Definition APFloat.cpp:764
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
static const char infinityU[]
Definition APFloat.cpp:763
lostFraction
Enum that represents what fraction of the LSB truncated bits of an fp number represent.
Definition APFloat.h:51
@ lfMoreThanHalf
Definition APFloat.h:55
@ lfLessThanHalf
Definition APFloat.h:53
@ lfExactlyHalf
Definition APFloat.h:54
@ lfExactlyZero
Definition APFloat.h:52
static Error interpretDecimal(StringRef::iterator begin, StringRef::iterator end, decimalInfo *D)
Definition APFloat.cpp:496
LLVM_READONLY LLVM_ABI std::optional< APFloat > exp(const APFloat &X, RoundingMode RM=APFloat::rmNearestTiesToEven, APFloat::opStatus *Status=nullptr)
Implement IEEE 754-2019 exp functions.
Definition APFloat.cpp:6148
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
const unsigned int maxPowerOfFiveParts
Definition APFloat.cpp:250
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
Definition APFloat.h:1693
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
static constexpr APFloatBase::ExponentType exponentNaN(const fltSemantics &semantics)
Definition APFloat.cpp:333
static Error createError(const Twine &Err)
Definition APFloat.cpp:345
static lostFraction shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
Definition APFloat.cpp:615
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
static const char hexDigitsUpper[]
Definition APFloat.cpp:761
const unsigned int maxExponent
Definition APFloat.cpp:247
static unsigned int decDigitValue(unsigned int c)
Definition APFloat.cpp:356
fltNonfiniteBehavior
Definition APFloat.h:969
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2012
static lostFraction combineLostFractions(lostFraction moreSignificant, lostFraction lessSignificant)
Definition APFloat.cpp:626
static Expected< StringRef::iterator > skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end, StringRef::iterator *dot)
Definition APFloat.cpp:456
RoundingMode
Rounding mode.
ArrayRef(const T &OneElt) -> ArrayRef< T >
static constexpr APFloatBase::ExponentType exponentInf(const fltSemantics &semantics)
Definition APFloat.cpp:328
static lostFraction lostFractionThroughTruncation(const APFloatBase::integerPart *parts, unsigned int partCount, unsigned int bits)
Definition APFloat.cpp:595
APFloat neg(APFloat X)
Returns the negated value of the argument.
Definition APFloat.h:1719
static APFloatBase::integerPart ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits, bool isNearest)
Definition APFloat.cpp:661
static char * writeSignedDecimal(char *dst, int value)
Definition APFloat.cpp:804
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:305
static Expected< lostFraction > trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, unsigned int digitValue)
Definition APFloat.cpp:566
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
static Expected< int > readExponent(StringRef::iterator begin, StringRef::iterator end)
Definition APFloat.cpp:366
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:285
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:374
static const char hexDigitsLower[]
Definition APFloat.cpp:760
#define N
const char * lastSigDigit
Definition APFloat.cpp:491
const char * firstSigDigit
Definition APFloat.cpp:490
APFloatBase::ExponentType maxExponent
Definition APFloat.h:1018
fltNonfiniteBehavior nonFiniteBehavior
Definition APFloat.h:1031
APFloatBase::ExponentType minExponent
Definition APFloat.h:1022
unsigned int sizeInBits
Definition APFloat.h:1029
unsigned int precision
Definition APFloat.h:1026
fltNanEncoding nanEncoding
Definition APFloat.h:1033