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 // If the source has no significand, there are no payload bits to carry
2561 // over, and an all-zero significand would encode an Inf. Create a new NaN.
2562 if (!APFloat::hasSignificand(fromSemantics))
2563 makeNaN(false, sign);
2564
2565 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
2566
2567 // For x87 extended precision, we want to make a NaN, not a special NaN if
2568 // the input wasn't special either.
2569 if (!X86SpecialNan && semantics == &APFloatBase::semX87DoubleExtended)
2570 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2571
2572 // Convert of sNaN creates qNaN and raises an exception (invalid op).
2573 // This also guarantees that a sNaN does not become Inf on a truncation
2574 // that loses all payload bits.
2575 if (is_signaling) {
2576 makeQuiet();
2577 fs = opInvalidOp;
2578 } else {
2579 fs = opOK;
2580 }
2581 } else if (category == fcInfinity &&
2582 semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
2583 makeNaN(false, sign);
2584 *losesInfo = true;
2585 fs = opInexact;
2586 } else if (category == fcZero &&
2587 semantics->nanEncoding == fltNanEncoding::NegativeZero) {
2588 // Negative zero loses info, but positive zero doesn't.
2589 *losesInfo =
2590 fromSemantics.nanEncoding != fltNanEncoding::NegativeZero && sign;
2591 fs = *losesInfo ? opInexact : opOK;
2592 // NaN is negative zero means -0 -> +0, which can lose information
2593 sign = false;
2594 } else {
2595 *losesInfo = false;
2596 fs = opOK;
2597 }
2598
2599 if (category == fcZero && !semantics->hasZero)
2601 return fs;
2602}
2603
2604/* Convert a floating point number to an integer according to the
2605 rounding mode. If the rounded integer value is out of range this
2606 returns an invalid operation exception and the contents of the
2607 destination parts are unspecified. If the rounded value is in
2608 range but the floating point number is not the exact integer, the C
2609 standard doesn't require an inexact exception to be raised. IEEE
2610 854 does require it so we do that.
2611
2612 Note that for conversions to integer type the C standard requires
2613 round-to-zero to always be used. */
2614APFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
2615 MutableArrayRef<integerPart> parts, unsigned int width, bool isSigned,
2616 roundingMode rounding_mode, bool *isExact) const {
2617 *isExact = false;
2618
2619 /* Handle the three special cases first. */
2620 if (category == fcInfinity || category == fcNaN)
2621 return opInvalidOp;
2622
2623 unsigned dstPartsCount = partCountForBits(width);
2624 assert(dstPartsCount <= parts.size() && "Integer too big");
2625
2626 if (category == fcZero) {
2627 APInt::tcSet(parts.data(), 0, dstPartsCount);
2628 // Negative zero can't be represented as an int.
2629 *isExact = !sign;
2630 return opOK;
2631 }
2632
2633 const integerPart *src = significandParts();
2634
2635 unsigned truncatedBits;
2636 /* Step 1: place our absolute value, with any fraction truncated, in
2637 the destination. */
2638 if (exponent < 0) {
2639 /* Our absolute value is less than one; truncate everything. */
2640 APInt::tcSet(parts.data(), 0, dstPartsCount);
2641 /* For exponent -1 the integer bit represents .5, look at that.
2642 For smaller exponents leftmost truncated bit is 0. */
2643 truncatedBits = semantics->precision -1U - exponent;
2644 } else {
2645 /* We want the most significant (exponent + 1) bits; the rest are
2646 truncated. */
2647 unsigned int bits = exponent + 1U;
2648
2649 /* Hopelessly large in magnitude? */
2650 if (bits > width)
2651 return opInvalidOp;
2652
2653 if (bits < semantics->precision) {
2654 /* We truncate (semantics->precision - bits) bits. */
2655 truncatedBits = semantics->precision - bits;
2656 APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits);
2657 } else {
2658 /* We want at least as many bits as are available. */
2659 APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision,
2660 0);
2661 APInt::tcShiftLeft(parts.data(), dstPartsCount,
2662 bits - semantics->precision);
2663 truncatedBits = 0;
2664 }
2665 }
2666
2667 /* Step 2: work out any lost fraction, and increment the absolute
2668 value if we would round away from zero. */
2669 lostFraction lost_fraction;
2670 if (truncatedBits) {
2671 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2672 truncatedBits);
2673 if (lost_fraction != lfExactlyZero &&
2674 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
2675 if (APInt::tcIncrement(parts.data(), dstPartsCount))
2676 return opInvalidOp; /* Overflow. */
2677 }
2678 } else {
2679 lost_fraction = lfExactlyZero;
2680 }
2681
2682 /* Step 3: check if we fit in the destination. */
2683 unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1;
2684
2685 if (sign) {
2686 if (!isSigned) {
2687 /* Negative numbers cannot be represented as unsigned. */
2688 if (omsb != 0)
2689 return opInvalidOp;
2690 } else {
2691 /* It takes omsb bits to represent the unsigned integer value.
2692 We lose a bit for the sign, but care is needed as the
2693 maximally negative integer is a special case. */
2694 if (omsb == width &&
2695 APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb)
2696 return opInvalidOp;
2697
2698 /* This case can happen because of rounding. */
2699 if (omsb > width)
2700 return opInvalidOp;
2701 }
2702
2703 APInt::tcNegate (parts.data(), dstPartsCount);
2704 } else {
2705 if (omsb >= width + !isSigned)
2706 return opInvalidOp;
2707 }
2708
2709 if (lost_fraction == lfExactlyZero) {
2710 *isExact = true;
2711 return opOK;
2712 }
2713 return opInexact;
2714}
2715
2716/* Same as convertToSignExtendedInteger, except we provide
2717 deterministic values in case of an invalid operation exception,
2718 namely zero for NaNs and the minimal or maximal value respectively
2719 for underflow or overflow.
2720 The *isExact output tells whether the result is exact, in the sense
2721 that converting it back to the original floating point type produces
2722 the original value. This is almost equivalent to result==opOK,
2723 except for negative zeroes.
2724*/
2727 unsigned int width, bool isSigned,
2728 roundingMode rounding_mode, bool *isExact) const {
2729 opStatus fs = convertToSignExtendedInteger(parts, width, isSigned,
2730 rounding_mode, isExact);
2731
2732 if (fs == opInvalidOp) {
2733 unsigned int bits, dstPartsCount;
2734
2735 dstPartsCount = partCountForBits(width);
2736 assert(dstPartsCount <= parts.size() && "Integer too big");
2737
2738 if (category == fcNaN)
2739 bits = 0;
2740 else if (sign)
2741 bits = isSigned;
2742 else
2743 bits = width - isSigned;
2744
2745 tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits);
2746 if (sign && isSigned)
2747 APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1);
2748 }
2749
2750 return fs;
2751}
2752
2753/* Convert an unsigned integer SRC to a floating point number,
2754 rounding according to ROUNDING_MODE. The sign of the floating
2755 point number is not modified. */
2756APFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2757 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
2758 category = fcNormal;
2759 unsigned omsb = APInt::tcMSB(src, srcCount) + 1;
2760 integerPart *dst = significandParts();
2761 unsigned dstCount = partCount();
2762 unsigned precision = semantics->precision;
2763
2764 /* We want the most significant PRECISION bits of SRC. There may not
2765 be that many; extract what we can. */
2766 lostFraction lost_fraction;
2767 if (precision <= omsb) {
2768 exponent = omsb - 1;
2769 lost_fraction = lostFractionThroughTruncation(src, srcCount,
2770 omsb - precision);
2771 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2772 } else {
2773 exponent = precision - 1;
2774 lost_fraction = lfExactlyZero;
2775 APInt::tcExtract(dst, dstCount, src, omsb, 0);
2776 }
2777
2778 return normalize(rounding_mode, lost_fraction);
2779}
2780
2782 roundingMode rounding_mode) {
2783 unsigned int partCount = Val.getNumWords();
2784 APInt api = Val;
2785
2786 sign = false;
2787 if (isSigned && api.isNegative()) {
2788 sign = true;
2789 api = -api;
2790 }
2791
2792 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2793}
2794
2796IEEEFloat::convertFromHexadecimalString(StringRef s,
2797 roundingMode rounding_mode) {
2798 lostFraction lost_fraction = lfExactlyZero;
2799
2800 category = fcNormal;
2801 zeroSignificand();
2802 exponent = 0;
2803
2804 integerPart *significand = significandParts();
2805 unsigned partsCount = partCount();
2806 unsigned bitPos = partsCount * integerPartWidth;
2807 bool computedTrailingFraction = false;
2808
2809 // Skip leading zeroes and any (hexa)decimal point.
2810 StringRef::iterator begin = s.begin();
2811 StringRef::iterator end = s.end();
2813 auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot);
2814 if (!PtrOrErr)
2815 return PtrOrErr.takeError();
2816 StringRef::iterator p = *PtrOrErr;
2817 StringRef::iterator firstSignificantDigit = p;
2818
2819 while (p != end) {
2820 integerPart hex_value;
2821
2822 if (*p == '.') {
2823 if (dot != end)
2824 return createError("String contains multiple dots");
2825 dot = p++;
2826 continue;
2827 }
2828
2829 hex_value = hexDigitValue(*p);
2830 if (hex_value == UINT_MAX)
2831 break;
2832
2833 p++;
2834
2835 // Store the number while we have space.
2836 if (bitPos) {
2837 bitPos -= 4;
2838 hex_value <<= bitPos % integerPartWidth;
2839 significand[bitPos / integerPartWidth] |= hex_value;
2840 } else if (!computedTrailingFraction) {
2841 auto FractOrErr = trailingHexadecimalFraction(p, end, hex_value);
2842 if (!FractOrErr)
2843 return FractOrErr.takeError();
2844 lost_fraction = *FractOrErr;
2845 computedTrailingFraction = true;
2846 }
2847 }
2848
2849 /* Hex floats require an exponent but not a hexadecimal point. */
2850 if (p == end)
2851 return createError("Hex strings require an exponent");
2852 if (*p != 'p' && *p != 'P')
2853 return createError("Invalid character in significand");
2854 if (p == begin)
2855 return createError("Significand has no digits");
2856 if (dot != end && p - begin == 1)
2857 return createError("Significand has no digits");
2858
2859 /* Ignore the exponent if we are zero. */
2860 if (p != firstSignificantDigit) {
2861 int expAdjustment;
2862
2863 /* Implicit hexadecimal point? */
2864 if (dot == end)
2865 dot = p;
2866
2867 /* Calculate the exponent adjustment implicit in the number of
2868 significant digits. */
2869 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
2870 if (expAdjustment < 0)
2871 expAdjustment++;
2872 expAdjustment = expAdjustment * 4 - 1;
2873
2874 /* Adjust for writing the significand starting at the most
2875 significant nibble. */
2876 expAdjustment += semantics->precision;
2877 expAdjustment -= partsCount * integerPartWidth;
2878
2879 /* Adjust for the given exponent. */
2880 auto ExpOrErr = totalExponent(p + 1, end, expAdjustment);
2881 if (!ExpOrErr)
2882 return ExpOrErr.takeError();
2883 exponent = *ExpOrErr;
2884 }
2885
2886 return normalize(rounding_mode, lost_fraction);
2887}
2888
2890IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2891 unsigned sigPartCount, int exp,
2892 roundingMode rounding_mode) {
2893 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
2895
2896 bool isNearest = rounding_mode == rmNearestTiesToEven ||
2897 rounding_mode == rmNearestTiesToAway;
2898
2899 unsigned parts = partCountForBits(semantics->precision + 11);
2900
2901 /* Calculate pow(5, abs(exp)). */
2902 unsigned pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp : -exp);
2903
2904 for (;; parts *= 2) {
2905 unsigned int excessPrecision, truncatedBits;
2906
2907 calcSemantics.precision = parts * integerPartWidth - 1;
2908 excessPrecision = calcSemantics.precision - semantics->precision;
2909 truncatedBits = excessPrecision;
2910
2911 IEEEFloat decSig(calcSemantics, uninitialized);
2912 decSig.makeZero(sign);
2913 IEEEFloat pow5(calcSemantics);
2914
2915 opStatus sigStatus = decSig.convertFromUnsignedParts(
2916 decSigParts, sigPartCount, rmNearestTiesToEven);
2917 opStatus powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2919 /* Add exp, as 10^n = 5^n * 2^n. */
2920 decSig.exponent += exp;
2921
2922 lostFraction calcLostFraction;
2923 integerPart HUerr, HUdistance;
2924 unsigned int powHUerr;
2925
2926 if (exp >= 0) {
2927 /* multiplySignificand leaves the precision-th bit set to 1. */
2928 calcLostFraction = decSig.multiplySignificand(pow5);
2929 powHUerr = powStatus != opOK;
2930 } else {
2931 calcLostFraction = decSig.divideSignificand(pow5);
2932 /* Denormal numbers have less precision. */
2933 if (decSig.exponent < semantics->minExponent) {
2934 excessPrecision += (semantics->minExponent - decSig.exponent);
2935 truncatedBits = excessPrecision;
2936 excessPrecision = std::min(excessPrecision, calcSemantics.precision);
2937 }
2938 /* Extra half-ulp lost in reciprocal of exponent. */
2939 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
2940 }
2941
2942 /* Both multiplySignificand and divideSignificand return the
2943 result with the integer bit set. */
2945 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
2946
2947 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2948 powHUerr);
2949 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2950 excessPrecision, isNearest);
2951
2952 /* Are we guaranteed to round correctly if we truncate? */
2953 if (HUdistance >= HUerr) {
2954 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2955 calcSemantics.precision - excessPrecision,
2956 excessPrecision);
2957 /* Take the exponent of decSig. If we tcExtract-ed less bits
2958 above we must adjust our exponent to compensate for the
2959 implicit right shift. */
2960 exponent = (decSig.exponent + semantics->precision
2961 - (calcSemantics.precision - excessPrecision));
2962 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2963 decSig.partCount(),
2964 truncatedBits);
2965 return static_cast<opStatus>(normalize(rounding_mode, calcLostFraction) |
2966 ((sigStatus | powStatus) & opInexact));
2967 }
2968 }
2969}
2970
2971Expected<APFloat::opStatus>
2972IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
2973 decimalInfo D;
2974 opStatus fs;
2975
2976 /* Scan the text. */
2977 StringRef::iterator p = str.begin();
2978 if (Error Err = interpretDecimal(p, str.end(), &D))
2979 return std::move(Err);
2980
2981 /* Handle the quick cases. First the case of no significant digits,
2982 i.e. zero, and then exponents that are obviously too large or too
2983 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2984 definitely overflows if
2985
2986 (exp - 1) * L >= maxExponent
2987
2988 and definitely underflows to zero where
2989
2990 (exp + 1) * L <= minExponent - precision
2991
2992 With integer arithmetic the tightest bounds for L are
2993
2994 93/28 < L < 196/59 [ numerator <= 256 ]
2995 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2996 */
2997
2998 // Test if we have a zero number allowing for strings with no null terminators
2999 // and zero decimals with non-zero exponents.
3000 //
3001 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
3002 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
3003 // be at most one dot. On the other hand, if we have a zero with a non-zero
3004 // exponent, then we know that D.firstSigDigit will be non-numeric.
3005 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
3006 category = fcZero;
3007 fs = opOK;
3008 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
3009 sign = false;
3010 if (!semantics->hasZero)
3012
3013 /* Check whether the normalized exponent is high enough to overflow
3014 max during the log-rebasing in the max-exponent check below. */
3015 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
3016 fs = handleOverflow(rounding_mode);
3017
3018 /* If it wasn't, then it also wasn't high enough to overflow max
3019 during the log-rebasing in the min-exponent check. Check that it
3020 won't overflow min in either check, then perform the min-exponent
3021 check. */
3022 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
3023 (D.normalizedExponent + 1) * 28738 <=
3024 8651 * (semantics->minExponent - (int) semantics->precision)) {
3025 /* Underflow to zero and round. */
3026 category = fcNormal;
3027 zeroSignificand();
3028 fs = normalize(rounding_mode, lfLessThanHalf);
3029
3030 /* We can finally safely perform the max-exponent check. */
3031 } else if ((D.normalizedExponent - 1) * 42039
3032 >= 12655 * semantics->maxExponent) {
3033 /* Overflow and round. */
3034 fs = handleOverflow(rounding_mode);
3035 } else {
3036 integerPart *decSignificand;
3037 unsigned int partCount;
3038
3039 /* A tight upper bound on number of bits required to hold an
3040 N-digit decimal integer is N * 196 / 59. Allocate enough space
3041 to hold the full significand, and an extra part required by
3042 tcMultiplyPart. */
3043 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
3044 partCount = partCountForBits(1 + 196 * partCount / 59);
3045 decSignificand = new integerPart[partCount + 1];
3046 partCount = 0;
3047
3048 /* Convert to binary efficiently - we do almost all multiplication
3049 in an integerPart. When this would overflow do we do a single
3050 bignum multiplication, and then revert again to multiplication
3051 in an integerPart. */
3052 do {
3053 integerPart decValue, val, multiplier;
3054
3055 val = 0;
3056 multiplier = 1;
3057
3058 do {
3059 if (*p == '.') {
3060 p++;
3061 if (p == str.end()) {
3062 break;
3063 }
3064 }
3065 decValue = decDigitValue(*p++);
3066 if (decValue >= 10U) {
3067 delete[] decSignificand;
3068 return createError("Invalid character in significand");
3069 }
3070 multiplier *= 10;
3071 val = val * 10 + decValue;
3072 /* The maximum number that can be multiplied by ten with any
3073 digit added without overflowing an integerPart. */
3074 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
3075
3076 /* Multiply out the current part. */
3077 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
3078 partCount, partCount + 1, false);
3079
3080 /* If we used another part (likely but not guaranteed), increase
3081 the count. */
3082 if (decSignificand[partCount])
3083 partCount++;
3084 } while (p <= D.lastSigDigit);
3085
3086 category = fcNormal;
3087 fs = roundSignificandWithExponent(decSignificand, partCount,
3088 D.exponent, rounding_mode);
3089
3090 delete [] decSignificand;
3091 }
3092
3093 return fs;
3094}
3095
3096bool IEEEFloat::convertFromStringSpecials(StringRef str) {
3097 const size_t MIN_NAME_SIZE = 3;
3098
3099 if (str.size() < MIN_NAME_SIZE)
3100 return false;
3101
3102 if (str == "inf" || str == "INFINITY" || str == "+Inf" || str == "+inf") {
3103 makeInf(false);
3104 return true;
3105 }
3106
3107 bool IsNegative = str.consume_front("-");
3108 if (IsNegative) {
3109 if (str.size() < MIN_NAME_SIZE)
3110 return false;
3111
3112 if (str == "inf" || str == "INFINITY" || str == "Inf") {
3113 makeInf(true);
3114 return true;
3115 }
3116 }
3117
3118 // If we have a 's' (or 'S') prefix, then this is a Signaling NaN.
3119 bool IsSignaling = str.consume_front_insensitive("s");
3120 if (IsSignaling) {
3121 if (str.size() < MIN_NAME_SIZE)
3122 return false;
3123 }
3124
3125 if (str.consume_front("nan") || str.consume_front("NaN")) {
3126 // A NaN without payload.
3127 if (str.empty()) {
3128 makeNaN(IsSignaling, IsNegative);
3129 return true;
3130 }
3131
3132 // Allow the payload to be inside parentheses.
3133 if (str.front() == '(') {
3134 // Parentheses should be balanced (and not empty).
3135 if (str.size() <= 2 || str.back() != ')')
3136 return false;
3137
3138 str = str.slice(1, str.size() - 1);
3139 }
3140
3141 // Determine the payload number's radix.
3142 unsigned Radix = 10;
3143 if (str[0] == '0') {
3144 if (str.size() > 1 && tolower(str[1]) == 'x') {
3145 str = str.drop_front(2);
3146 Radix = 16;
3147 } else {
3148 Radix = 8;
3149 }
3150 }
3151
3152 // Parse the payload and make the NaN.
3153 APInt Payload;
3154 if (!str.getAsInteger(Radix, Payload)) {
3155 makeNaN(IsSignaling, IsNegative, &Payload);
3156 return true;
3157 }
3158 }
3159
3160 return false;
3161}
3162
3163Expected<APFloat::opStatus>
3165 if (str.empty())
3166 return createError("Invalid string length");
3167
3168 // Handle special cases.
3169 if (convertFromStringSpecials(str))
3170 return opOK;
3171
3172 /* Handle a leading minus sign. */
3173 StringRef::iterator p = str.begin();
3174 size_t slen = str.size();
3175 sign = *p == '-' ? 1 : 0;
3176 if (sign && !semantics->hasSignedRepr)
3178 "This floating point format does not support signed values");
3179
3180 if (*p == '-' || *p == '+') {
3181 p++;
3182 slen--;
3183 if (!slen)
3184 return createError("String has no digits");
3185 }
3186
3187 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3188 if (slen == 2)
3189 return createError("Invalid string");
3190 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
3191 rounding_mode);
3192 }
3193
3194 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
3195}
3196
3197/* Write out a hexadecimal representation of the floating point value
3198 to DST, which must be of sufficient size, in the C99 form
3199 [-]0xh.hhhhp[+-]d. Return the number of characters written,
3200 excluding the terminating NUL.
3201
3202 If UPPERCASE, the output is in upper case, otherwise in lower case.
3203
3204 HEXDIGITS digits appear altogether, rounding the value if
3205 necessary. If HEXDIGITS is 0, the minimal precision to display the
3206 number precisely is used instead. If nothing would appear after
3207 the decimal point it is suppressed.
3208
3209 The decimal exponent is always printed and has at least one digit.
3210 Zero values display an exponent of zero. Infinities and NaNs
3211 appear as "infinity" or "nan" respectively.
3212
3213 The above rules are as specified by C99. There is ambiguity about
3214 what the leading hexadecimal digit should be. This implementation
3215 uses whatever is necessary so that the exponent is displayed as
3216 stored. This implies the exponent will fall within the IEEE format
3217 range, and the leading hexadecimal digit will be 0 (for denormals),
3218 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
3219 any other digits zero).
3220*/
3221unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
3222 bool upperCase,
3223 roundingMode rounding_mode) const {
3224 char *p = dst;
3225 if (sign)
3226 *dst++ = '-';
3227
3228 switch (category) {
3229 case fcInfinity:
3230 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
3231 dst += sizeof infinityL - 1;
3232 break;
3233
3234 case fcNaN:
3235 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
3236 dst += sizeof NaNU - 1;
3237 break;
3238
3239 case fcZero:
3240 *dst++ = '0';
3241 *dst++ = upperCase ? 'X': 'x';
3242 *dst++ = '0';
3243 if (hexDigits > 1) {
3244 *dst++ = '.';
3245 memset (dst, '0', hexDigits - 1);
3246 dst += hexDigits - 1;
3247 }
3248 *dst++ = upperCase ? 'P': 'p';
3249 *dst++ = '0';
3250 break;
3251
3252 case fcNormal:
3253 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
3254 break;
3255 }
3256
3257 *dst = 0;
3258
3259 return static_cast<unsigned int>(dst - p);
3260}
3261
3262/* Does the hard work of outputting the correctly rounded hexadecimal
3263 form of a normal floating point number with the specified number of
3264 hexadecimal digits. If HEXDIGITS is zero the minimum number of
3265 digits necessary to print the value precisely is output. */
3266char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
3267 bool upperCase,
3268 roundingMode rounding_mode) const {
3269 *dst++ = '0';
3270 *dst++ = upperCase ? 'X': 'x';
3271
3272 bool roundUp = false;
3273 const char *hexDigitChars = upperCase ? hexDigitsUpper : hexDigitsLower;
3274
3275 const integerPart *significand = significandParts();
3276 unsigned partsCount = partCount();
3277
3278 /* +3 because the first digit only uses the single integer bit, so
3279 we have 3 virtual zero most-significant-bits. */
3280 unsigned valueBits = semantics->precision + 3;
3281 unsigned shift = integerPartWidth - valueBits % integerPartWidth;
3282
3283 /* The natural number of digits required ignoring trailing
3284 insignificant zeroes. */
3285 unsigned outputDigits = (valueBits - significandLSB() + 3) / 4;
3286
3287 /* hexDigits of zero means use the required number for the
3288 precision. Otherwise, see if we are truncating. If we are,
3289 find out if we need to round away from zero. */
3290 if (hexDigits) {
3291 if (hexDigits < outputDigits) {
3292 /* We are dropping non-zero bits, so need to check how to round.
3293 "bits" is the number of dropped bits. */
3294 unsigned int bits;
3295 lostFraction fraction;
3296
3297 bits = valueBits - hexDigits * 4;
3298 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
3299 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
3300 }
3301 outputDigits = hexDigits;
3302 }
3303
3304 /* Write the digits consecutively, and start writing in the location
3305 of the hexadecimal point. We move the most significant digit
3306 left and add the hexadecimal point later. */
3307 char *p = ++dst;
3308
3309 unsigned count = (valueBits + integerPartWidth - 1) / integerPartWidth;
3310
3311 while (outputDigits && count) {
3312 integerPart part;
3313
3314 /* Put the most significant integerPartWidth bits in "part". */
3315 if (--count == partsCount)
3316 part = 0; /* An imaginary higher zero part. */
3317 else
3318 part = significand[count] << shift;
3319
3320 if (count && shift)
3321 part |= significand[count - 1] >> (integerPartWidth - shift);
3322
3323 /* Convert as much of "part" to hexdigits as we can. */
3324 unsigned int curDigits = integerPartWidth / 4;
3325
3326 curDigits = std::min(curDigits, outputDigits);
3327 dst += partAsHex (dst, part, curDigits, hexDigitChars);
3328 outputDigits -= curDigits;
3329 }
3330
3331 if (roundUp) {
3332 char *q = dst;
3333
3334 /* Note that hexDigitChars has a trailing '0'. */
3335 do {
3336 q--;
3337 *q = hexDigitChars[hexDigitValue (*q) + 1];
3338 } while (*q == '0');
3339 assert(q >= p);
3340 } else {
3341 /* Add trailing zeroes. */
3342 memset (dst, '0', outputDigits);
3343 dst += outputDigits;
3344 }
3345
3346 /* Move the most significant digit to before the point, and if there
3347 is something after the decimal point add it. This must come
3348 after rounding above. */
3349 p[-1] = p[0];
3350 if (dst -1 == p)
3351 dst--;
3352 else
3353 p[0] = '.';
3354
3355 /* Finally output the exponent. */
3356 *dst++ = upperCase ? 'P': 'p';
3357
3358 return writeSignedDecimal (dst, exponent);
3359}
3360
3362 if (!Arg.isFiniteNonZero())
3363 return hash_combine((uint8_t)Arg.category,
3364 // NaN has no sign, fix it at zero.
3365 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
3366 Arg.semantics->precision);
3367
3368 // Normal floats need their exponent and significand hashed.
3369 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
3370 Arg.semantics->precision, Arg.exponent,
3372 Arg.significandParts(),
3373 Arg.significandParts() + Arg.partCount()));
3374}
3375
3376// Conversion from APFloat to/from host float/double. It may eventually be
3377// possible to eliminate these and have everybody deal with APFloats, but that
3378// will take a while. This approach will not easily extend to long double.
3379// Current implementation requires integerPartWidth==64, which is correct at
3380// the moment but could be made more general.
3381
3382// Denormals have exponent minExponent in APFloat, but minExponent-1 in
3383// the actual IEEE respresentations. We compensate for that here.
3384
3385APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
3386 assert(partCount() == 2);
3387 return convertIEEEFloatToAPInt<APFloatBase::semX87DoubleExtended>();
3388}
3389
3390APInt IEEEFloat::convertPPCDoubleDoubleLegacyAPFloatToAPInt() const {
3391 assert(semantics ==
3392 (const llvm::fltSemantics *)&APFloatBase::semPPCDoubleDoubleLegacy);
3393 assert(partCount()==2);
3394
3395 uint64_t words[2];
3396 bool losesInfo;
3397
3398 // Convert number to double. To avoid spurious underflows, we re-
3399 // normalize against the "double" minExponent first, and only *then*
3400 // truncate the mantissa. The result of that second conversion
3401 // may be inexact, but should never underflow.
3402 // Declare fltSemantics before APFloat that uses it (and
3403 // saves pointer to it) to ensure correct destruction order.
3404 fltSemantics extendedSemantics = *semantics;
3405 extendedSemantics.minExponent = APFloatBase::semIEEEdouble.minExponent;
3406 IEEEFloat extended(*this);
3407 [[maybe_unused]] opStatus fs =
3408 extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
3409 assert(fs == opOK && !losesInfo);
3410
3411 IEEEFloat u(extended);
3412 fs = u.convert(APFloatBase::semIEEEdouble, rmNearestTiesToEven, &losesInfo);
3413 assert(fs == opOK || fs == opInexact);
3414 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
3415
3416 // If conversion was exact or resulted in a special case, we're done;
3417 // just set the second double to zero. Otherwise, re-convert back to
3418 // the extended format and compute the difference. This now should
3419 // convert exactly to double.
3420 if (u.isFiniteNonZero() && losesInfo) {
3421 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
3422 assert(fs == opOK && !losesInfo);
3423
3424 IEEEFloat v(extended);
3425 v.subtract(u, rmNearestTiesToEven);
3426 fs = v.convert(APFloatBase::semIEEEdouble, rmNearestTiesToEven, &losesInfo);
3427 assert(fs == opOK && !losesInfo);
3428 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
3429 } else {
3430 words[1] = 0;
3431 }
3432
3433 return APInt(128, words);
3434}
3435
3436template <const fltSemantics &S>
3437APInt IEEEFloat::convertIEEEFloatToAPInt() const {
3438 assert(semantics == &S);
3439 constexpr unsigned int trailing_significand_bits =
3440 S.precision - 1 + S.hasExplicitIntegerBit;
3441 constexpr int integer_bit_part = (S.precision - 1) / integerPartWidth;
3442 constexpr integerPart integer_bit = integerPart{1}
3443 << ((S.precision - 1) % integerPartWidth);
3444 constexpr uint64_t significand_mask = integer_bit - 1;
3445 constexpr unsigned int exponent_bits =
3446 S.sizeInBits - (S.hasSignedRepr ? 1 : 0) - trailing_significand_bits;
3447 static_assert(exponent_bits < 64);
3448 constexpr uint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1;
3449 constexpr bool is_zero_exp_reserved = S.hasDenormals || S.hasZero;
3450 constexpr int bias = -(S.minExponent - (is_zero_exp_reserved ? 1 : 0));
3451
3452 uint64_t myexponent;
3453 std::array<integerPart, partCountForBits(trailing_significand_bits)>
3454 mysignificand;
3455
3456 if (isFiniteNonZero()) {
3457 myexponent = exponent + bias;
3458 std::copy_n(significandParts(), mysignificand.size(),
3459 mysignificand.begin());
3460 if (myexponent == 1 &&
3461 !(significandParts()[integer_bit_part] & integer_bit))
3462 myexponent = 0; // denormal
3463 } else if (category == fcZero) {
3464 if (!S.hasZero)
3465 llvm_unreachable("semantics does not support zero!");
3466 myexponent = ::exponentZero(S) + bias;
3467 mysignificand.fill(0);
3468 } else if (category == fcInfinity) {
3469 if (S.nonFiniteBehavior == fltNonfiniteBehavior::NanOnly ||
3470 S.nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
3471 llvm_unreachable("semantics don't support inf!");
3472 myexponent = ::exponentInf(S) + bias;
3473 mysignificand.fill(0);
3474 if constexpr (S.hasExplicitIntegerBit) {
3475 mysignificand[0] = integerPart{1} << (trailing_significand_bits - 1);
3476 }
3477 } else {
3478 assert(category == fcNaN && "Unknown category!");
3479 if (S.nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
3480 llvm_unreachable("semantics don't support NaN!");
3481 myexponent = ::exponentNaN(S) + bias;
3482 std::copy_n(significandParts(), mysignificand.size(),
3483 mysignificand.begin());
3484 }
3485 std::array<uint64_t, (S.sizeInBits + 63) / 64> words;
3486 auto words_iter =
3487 std::copy_n(mysignificand.begin(), mysignificand.size(), words.begin());
3488 if constexpr (!S.hasExplicitIntegerBit) {
3489 if constexpr (significand_mask != 0 || trailing_significand_bits == 0) {
3490 // Clear the integer bit.
3491 words[mysignificand.size() - 1] &= significand_mask;
3492 }
3493 }
3494 std::fill(words_iter, words.end(), uint64_t{0});
3495 constexpr size_t last_word = words.size() - 1;
3496 uint64_t shifted_sign = static_cast<uint64_t>(sign & 1)
3497 << ((S.sizeInBits - 1) % 64);
3498 words[last_word] |= shifted_sign;
3499 uint64_t shifted_exponent = (myexponent & exponent_mask)
3500 << (trailing_significand_bits % 64);
3501 words[last_word] |= shifted_exponent;
3502 if constexpr (last_word == 0) {
3503 return APInt(S.sizeInBits, words[0]);
3504 }
3505 return APInt(S.sizeInBits, words);
3506}
3507
3508APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
3509 assert(partCount() == 2);
3510 return convertIEEEFloatToAPInt<APFloatBase::semIEEEquad>();
3511}
3512
3513APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
3514 assert(partCount()==1);
3515 return convertIEEEFloatToAPInt<APFloatBase::semIEEEdouble>();
3516}
3517
3518APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
3519 assert(partCount()==1);
3520 return convertIEEEFloatToAPInt<APFloatBase::semIEEEsingle>();
3521}
3522
3523APInt IEEEFloat::convertBFloatAPFloatToAPInt() const {
3524 assert(partCount() == 1);
3525 return convertIEEEFloatToAPInt<APFloatBase::semBFloat>();
3526}
3527
3528APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
3529 assert(partCount()==1);
3530 return convertIEEEFloatToAPInt<APFloatBase::APFloatBase::semIEEEhalf>();
3531}
3532
3533APInt IEEEFloat::convertFloat8E5M2APFloatToAPInt() const {
3534 assert(partCount() == 1);
3535 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M2>();
3536}
3537
3538APInt IEEEFloat::convertFloat8E5M2FNUZAPFloatToAPInt() const {
3539 assert(partCount() == 1);
3540 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M2FNUZ>();
3541}
3542
3543APInt IEEEFloat::convertFloat8E4M3APFloatToAPInt() const {
3544 assert(partCount() == 1);
3545 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3>();
3546}
3547
3548APInt IEEEFloat::convertFloat8E4M3FNAPFloatToAPInt() const {
3549 assert(partCount() == 1);
3550 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3FN>();
3551}
3552
3553APInt IEEEFloat::convertFloat8E4M3FNUZAPFloatToAPInt() const {
3554 assert(partCount() == 1);
3555 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3FNUZ>();
3556}
3557
3558APInt IEEEFloat::convertFloat8E4M3B11FNUZAPFloatToAPInt() const {
3559 assert(partCount() == 1);
3560 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3B11FNUZ>();
3561}
3562
3563APInt IEEEFloat::convertFloat8E3M4APFloatToAPInt() const {
3564 assert(partCount() == 1);
3565 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E3M4>();
3566}
3567
3568APInt IEEEFloat::convertFloatTF32APFloatToAPInt() const {
3569 assert(partCount() == 1);
3570 return convertIEEEFloatToAPInt<APFloatBase::semFloatTF32>();
3571}
3572
3573APInt IEEEFloat::convertFloat8E8M0FNUAPFloatToAPInt() const {
3574 assert(partCount() == 1);
3575 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E8M0FNU>();
3576}
3577
3578APInt IEEEFloat::convertFloat8E5M3FNUAPFloatToAPInt() const {
3579 assert(partCount() == 1);
3580 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M3FNU>();
3581}
3582
3583APInt IEEEFloat::convertFloat6E3M2FNAPFloatToAPInt() const {
3584 assert(partCount() == 1);
3585 return convertIEEEFloatToAPInt<APFloatBase::semFloat6E3M2FN>();
3586}
3587
3588APInt IEEEFloat::convertFloat6E2M3FNAPFloatToAPInt() const {
3589 assert(partCount() == 1);
3590 return convertIEEEFloatToAPInt<APFloatBase::semFloat6E2M3FN>();
3591}
3592
3593APInt IEEEFloat::convertFloat4E2M1FNAPFloatToAPInt() const {
3594 assert(partCount() == 1);
3595 return convertIEEEFloatToAPInt<APFloatBase::semFloat4E2M1FN>();
3596}
3597
3598// This function creates an APInt that is just a bit map of the floating
3599// point constant as it would appear in memory. It is not a conversion,
3600// and treating the result as a normal integer is unlikely to be useful.
3601
3603 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEhalf)
3604 return convertHalfAPFloatToAPInt();
3605
3606 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semBFloat)
3607 return convertBFloatAPFloatToAPInt();
3608
3609 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEsingle)
3610 return convertFloatAPFloatToAPInt();
3611
3612 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEdouble)
3613 return convertDoubleAPFloatToAPInt();
3614
3615 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEquad)
3616 return convertQuadrupleAPFloatToAPInt();
3617
3618 if (semantics ==
3619 (const llvm::fltSemantics *)&APFloatBase::semPPCDoubleDoubleLegacy)
3620 return convertPPCDoubleDoubleLegacyAPFloatToAPInt();
3621
3622 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M2)
3623 return convertFloat8E5M2APFloatToAPInt();
3624
3625 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M2FNUZ)
3626 return convertFloat8E5M2FNUZAPFloatToAPInt();
3627
3628 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3)
3629 return convertFloat8E4M3APFloatToAPInt();
3630
3631 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3FN)
3632 return convertFloat8E4M3FNAPFloatToAPInt();
3633
3634 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3FNUZ)
3635 return convertFloat8E4M3FNUZAPFloatToAPInt();
3636
3637 if (semantics ==
3638 (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3B11FNUZ)
3639 return convertFloat8E4M3B11FNUZAPFloatToAPInt();
3640
3641 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E3M4)
3642 return convertFloat8E3M4APFloatToAPInt();
3643
3644 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloatTF32)
3645 return convertFloatTF32APFloatToAPInt();
3646
3647 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E8M0FNU)
3648 return convertFloat8E8M0FNUAPFloatToAPInt();
3649
3650 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M3FNU)
3651 return convertFloat8E5M3FNUAPFloatToAPInt();
3652
3653 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat6E3M2FN)
3654 return convertFloat6E3M2FNAPFloatToAPInt();
3655
3656 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat6E2M3FN)
3657 return convertFloat6E2M3FNAPFloatToAPInt();
3658
3659 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat4E2M1FN)
3660 return convertFloat4E2M1FNAPFloatToAPInt();
3661
3662 assert(semantics ==
3663 (const llvm::fltSemantics *)&APFloatBase::semX87DoubleExtended &&
3664 "unknown format!");
3665 return convertF80LongDoubleAPFloatToAPInt();
3666}
3667
3669 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEsingle &&
3670 "Float semantics are not IEEEsingle");
3671 APInt api = bitcastToAPInt();
3672 return api.bitsToFloat();
3673}
3674
3676 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEdouble &&
3677 "Float semantics are not IEEEdouble");
3678 APInt api = bitcastToAPInt();
3679 return api.bitsToDouble();
3680}
3681
3682#ifdef HAS_IEE754_FLOAT128
3683float128 IEEEFloat::convertToQuad() const {
3684 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEquad &&
3685 "Float semantics are not IEEEquads");
3686 APInt api = bitcastToAPInt();
3687 return api.bitsToQuad();
3688}
3689#endif
3690
3691void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
3692 return initFromIEEEAPInt<APFloatBase::semX87DoubleExtended>(api);
3693}
3694
3695void IEEEFloat::initFromPPCDoubleDoubleLegacyAPInt(const APInt &api) {
3696 uint64_t i1 = api.getRawData()[0];
3697 uint64_t i2 = api.getRawData()[1];
3698 bool losesInfo;
3699
3700 // Get the first double and convert to our format.
3701 initFromDoubleAPInt(APInt(64, i1));
3702 [[maybe_unused]] opStatus fs = convert(APFloatBase::semPPCDoubleDoubleLegacy,
3703 rmNearestTiesToEven, &losesInfo);
3704 // (convert may return opInvalidOp if i1 is an sNaN).
3705 assert((fs == opOK || fs == opInvalidOp) && !losesInfo);
3706
3707 // Unless we have a special case, add in second double.
3708 if (isFiniteNonZero()) {
3709 IEEEFloat v(APFloatBase::semIEEEdouble, APInt(64, i2));
3710 fs = v.convert(APFloatBase::semPPCDoubleDoubleLegacy, rmNearestTiesToEven,
3711 &losesInfo);
3712 assert(fs == opOK && !losesInfo);
3713
3715 }
3716}
3717
3718// The E8M0 format has the following characteristics:
3719// It is an 8-bit unsigned format with only exponents (no actual significand).
3720// No encodings for {zero, infinities or denorms}.
3721// NaN is represented by all 1's.
3722// Bias is 127.
3723void IEEEFloat::initFromFloat8E8M0FNUAPInt(const APInt &api) {
3724 initFromIEEEAPInt<APFloatBase::semFloat8E8M0FNU>(api);
3725}
3726
3727void IEEEFloat::initFromFloat8E5M3FNUAPInt(const APInt &api) {
3728 initFromIEEEAPInt<APFloatBase::semFloat8E5M3FNU>(api);
3729}
3730
3731template <const fltSemantics &S>
3732void IEEEFloat::initFromIEEEAPInt(const APInt &api) {
3733 assert(api.getBitWidth() == S.sizeInBits);
3734
3735 constexpr unsigned int trailing_significand_bits =
3736 S.precision - 1 + S.hasExplicitIntegerBit;
3737 constexpr integerPart integer_bit =
3738 integerPart{1} << (trailing_significand_bits % integerPartWidth);
3739 constexpr uint64_t significand_mask = integer_bit - 1;
3740 constexpr unsigned int exponent_bits =
3741 S.sizeInBits - (S.hasSignedRepr ? 1 : 0) - trailing_significand_bits;
3742 static_assert(exponent_bits < 64);
3743 constexpr unsigned int stored_significand_parts =
3744 partCountForBits(trailing_significand_bits + 1);
3745 constexpr uint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1;
3746 constexpr bool is_zero_exp_reserved = S.hasDenormals || S.hasZero;
3747 constexpr int bias = -(S.minExponent - (is_zero_exp_reserved ? 1 : 0));
3748 constexpr bool has_significand = trailing_significand_bits > 0;
3749
3750 // Copy the bits of the significand. We need to clear out the exponent and
3751 // sign bit in the last word.
3752 std::array<integerPart, stored_significand_parts> mysignificand;
3753 if constexpr (has_significand) {
3754 std::copy_n(api.getRawData(), mysignificand.size(), mysignificand.begin());
3755 if constexpr (significand_mask != 0 || S.precision >= integerPartWidth) {
3756 mysignificand[mysignificand.size() - 1] &= significand_mask;
3757 }
3758 } else {
3759 std::fill_n(mysignificand.begin(), mysignificand.size(), 0);
3760 // Always set integer bit to 1 for consistency in APFloat's internal
3761 // representation.
3762 mysignificand[0] = 1;
3763 }
3764
3765 // We assume the last word holds the sign bit, the exponent, and potentially
3766 // some of the trailing significand field.
3767 uint64_t last_word = api.getRawData()[api.getNumWords() - 1];
3768 uint64_t myexponent =
3769 (last_word >> (trailing_significand_bits % 64)) & exponent_mask;
3770
3771 initialize(&S);
3772 assert(partCount() == mysignificand.size());
3773
3774 sign = S.hasSignedRepr
3775 ? static_cast<unsigned int>(last_word >> ((S.sizeInBits - 1) % 64))
3776 : 0;
3777
3778 bool all_zero_significand =
3779 has_significand && llvm::all_of(mysignificand, equal_to(0));
3780
3781 bool is_zero = myexponent == 0 && all_zero_significand && S.hasZero;
3782
3783 if constexpr (S.nonFiniteBehavior == fltNonfiniteBehavior::IEEE754) {
3784 bool is_inf = false;
3785
3786 if constexpr (S.hasExplicitIntegerBit) {
3787 // This is only used and tested for x87DoubleExtended
3788 static_assert(S.precision == 64);
3789 constexpr integerPart significand_mask_no_int_bit =
3790 (uint64_t{1} << (trailing_significand_bits - 1)) - 1;
3791 const integerPart myintegerbit =
3792 mysignificand[0] >> (trailing_significand_bits - 1);
3793
3794 is_inf = myexponent - bias == ::exponentInf(S) && myintegerbit == 1 &&
3795 (mysignificand[0] & significand_mask_no_int_bit) == 0;
3796 } else {
3797 is_inf = myexponent - bias == ::exponentInf(S) && all_zero_significand;
3798 }
3799
3800 if (is_inf) {
3801 makeInf(sign);
3802 return;
3803 }
3804 }
3805
3806 bool is_nan = false;
3807
3808 if constexpr (S.nanEncoding == fltNanEncoding::IEEE) {
3809 if constexpr (S.hasExplicitIntegerBit) {
3810 // This is only used and tested for x87DoubleExtended
3811 static_assert(S.precision == 64);
3812 const integerPart myintegerbit =
3813 mysignificand[0] >> (trailing_significand_bits - 1);
3814 constexpr integerPart significand_mask_no_int_bit =
3815 (uint64_t{1} << (trailing_significand_bits - 1)) - 1;
3816
3817 if (myexponent - bias == ::exponentNaN(S) &&
3818 (mysignificand[0] & significand_mask_no_int_bit) != 0) {
3819 // regular NaN and pseudoNaN
3820 is_nan = true;
3821 } else if (myexponent - bias == ::exponentNaN(S) &&
3822 (mysignificand[0] & significand_mask_no_int_bit) == 0) {
3823 // pseudoinfinity
3824 is_nan = true;
3825 } else if (myexponent - bias != ::exponentNaN(S) && myexponent != 0 &&
3826 myintegerbit == 0) {
3827 // unnormal
3828 is_nan = true;
3829 }
3830 } else {
3831 is_nan = myexponent - bias == ::exponentNaN(S) && !all_zero_significand;
3832 }
3833 } else if constexpr (S.nanEncoding == fltNanEncoding::AllOnes) {
3834 bool all_ones_significand =
3835 std::all_of(mysignificand.begin(), mysignificand.end() - 1,
3836 [](integerPart bits) { return bits == ~integerPart{0}; }) &&
3837 (!significand_mask ||
3838 mysignificand[mysignificand.size() - 1] == significand_mask);
3839 is_nan = myexponent - bias == ::exponentNaN(S) && all_ones_significand;
3840 } else if constexpr (S.nanEncoding == fltNanEncoding::NegativeZero) {
3841 is_nan = is_zero && sign;
3842 }
3843
3844 if (is_nan) {
3845 category = fcNaN;
3846 exponent = ::exponentNaN(S);
3847 std::copy_n(mysignificand.begin(), mysignificand.size(),
3848 significandParts());
3849 return;
3850 }
3851
3852 if (is_zero) {
3853 makeZero(sign);
3854 return;
3855 }
3856
3857 category = fcNormal;
3858 exponent = myexponent - bias;
3859 std::copy_n(mysignificand.begin(), mysignificand.size(), significandParts());
3860 if (myexponent == 0 && S.hasDenormals) // denormal
3861 exponent = S.minExponent;
3862 else {
3863 if constexpr (!S.hasExplicitIntegerBit) {
3864 significandParts()[mysignificand.size() - 1] |= integer_bit;
3865 }
3866 }
3867}
3868
3869void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
3870 initFromIEEEAPInt<APFloatBase::semIEEEquad>(api);
3871}
3872
3873void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
3874 initFromIEEEAPInt<APFloatBase::semIEEEdouble>(api);
3875}
3876
3877void IEEEFloat::initFromFloatAPInt(const APInt &api) {
3878 initFromIEEEAPInt<APFloatBase::semIEEEsingle>(api);
3879}
3880
3881void IEEEFloat::initFromBFloatAPInt(const APInt &api) {
3882 initFromIEEEAPInt<APFloatBase::semBFloat>(api);
3883}
3884
3885void IEEEFloat::initFromHalfAPInt(const APInt &api) {
3886 initFromIEEEAPInt<APFloatBase::semIEEEhalf>(api);
3887}
3888
3889void IEEEFloat::initFromFloat8E5M2APInt(const APInt &api) {
3890 initFromIEEEAPInt<APFloatBase::semFloat8E5M2>(api);
3891}
3892
3893void IEEEFloat::initFromFloat8E5M2FNUZAPInt(const APInt &api) {
3894 initFromIEEEAPInt<APFloatBase::semFloat8E5M2FNUZ>(api);
3895}
3896
3897void IEEEFloat::initFromFloat8E4M3APInt(const APInt &api) {
3898 initFromIEEEAPInt<APFloatBase::semFloat8E4M3>(api);
3899}
3900
3901void IEEEFloat::initFromFloat8E4M3FNAPInt(const APInt &api) {
3902 initFromIEEEAPInt<APFloatBase::semFloat8E4M3FN>(api);
3903}
3904
3905void IEEEFloat::initFromFloat8E4M3FNUZAPInt(const APInt &api) {
3906 initFromIEEEAPInt<APFloatBase::semFloat8E4M3FNUZ>(api);
3907}
3908
3909void IEEEFloat::initFromFloat8E4M3B11FNUZAPInt(const APInt &api) {
3910 initFromIEEEAPInt<APFloatBase::semFloat8E4M3B11FNUZ>(api);
3911}
3912
3913void IEEEFloat::initFromFloat8E3M4APInt(const APInt &api) {
3914 initFromIEEEAPInt<APFloatBase::semFloat8E3M4>(api);
3915}
3916
3917void IEEEFloat::initFromFloatTF32APInt(const APInt &api) {
3918 initFromIEEEAPInt<APFloatBase::semFloatTF32>(api);
3919}
3920
3921void IEEEFloat::initFromFloat6E3M2FNAPInt(const APInt &api) {
3922 initFromIEEEAPInt<APFloatBase::semFloat6E3M2FN>(api);
3923}
3924
3925void IEEEFloat::initFromFloat6E2M3FNAPInt(const APInt &api) {
3926 initFromIEEEAPInt<APFloatBase::semFloat6E2M3FN>(api);
3927}
3928
3929void IEEEFloat::initFromFloat4E2M1FNAPInt(const APInt &api) {
3930 initFromIEEEAPInt<APFloatBase::semFloat4E2M1FN>(api);
3931}
3932
3933/// Treat api as containing the bits of a floating point number.
3934void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
3935 assert(api.getBitWidth() == Sem->sizeInBits);
3936 if (Sem == &APFloatBase::semIEEEhalf)
3937 return initFromHalfAPInt(api);
3938 if (Sem == &APFloatBase::semBFloat)
3939 return initFromBFloatAPInt(api);
3940 if (Sem == &APFloatBase::semIEEEsingle)
3941 return initFromFloatAPInt(api);
3942 if (Sem == &APFloatBase::semIEEEdouble)
3943 return initFromDoubleAPInt(api);
3944 if (Sem == &APFloatBase::semX87DoubleExtended)
3945 return initFromF80LongDoubleAPInt(api);
3946 if (Sem == &APFloatBase::semIEEEquad)
3947 return initFromQuadrupleAPInt(api);
3948 if (Sem == &APFloatBase::semPPCDoubleDoubleLegacy)
3949 return initFromPPCDoubleDoubleLegacyAPInt(api);
3950 if (Sem == &APFloatBase::semFloat8E5M2)
3951 return initFromFloat8E5M2APInt(api);
3952 if (Sem == &APFloatBase::semFloat8E5M2FNUZ)
3953 return initFromFloat8E5M2FNUZAPInt(api);
3954 if (Sem == &APFloatBase::semFloat8E4M3)
3955 return initFromFloat8E4M3APInt(api);
3956 if (Sem == &APFloatBase::semFloat8E4M3FN)
3957 return initFromFloat8E4M3FNAPInt(api);
3958 if (Sem == &APFloatBase::semFloat8E4M3FNUZ)
3959 return initFromFloat8E4M3FNUZAPInt(api);
3960 if (Sem == &APFloatBase::semFloat8E4M3B11FNUZ)
3961 return initFromFloat8E4M3B11FNUZAPInt(api);
3962 if (Sem == &APFloatBase::semFloat8E3M4)
3963 return initFromFloat8E3M4APInt(api);
3964 if (Sem == &APFloatBase::semFloatTF32)
3965 return initFromFloatTF32APInt(api);
3966 if (Sem == &APFloatBase::semFloat8E8M0FNU)
3967 return initFromFloat8E8M0FNUAPInt(api);
3968 if (Sem == &APFloatBase::semFloat8E5M3FNU)
3969 return initFromFloat8E5M3FNUAPInt(api);
3970 if (Sem == &APFloatBase::semFloat6E3M2FN)
3971 return initFromFloat6E3M2FNAPInt(api);
3972 if (Sem == &APFloatBase::semFloat6E2M3FN)
3973 return initFromFloat6E2M3FNAPInt(api);
3974 if (Sem == &APFloatBase::semFloat4E2M1FN)
3975 return initFromFloat4E2M1FNAPInt(api);
3976
3977 llvm_unreachable("unsupported semantics");
3978}
3979
3980/// Make this number the largest magnitude normal number in the given
3981/// semantics.
3982void IEEEFloat::makeLargest(bool Negative) {
3983 if (Negative && !semantics->hasSignedRepr)
3985 "This floating point format does not support signed values");
3986 // We want (in interchange format):
3987 // sign = {Negative}
3988 // exponent = 1..10
3989 // significand = 1..1
3990 category = fcNormal;
3991 sign = Negative;
3992 exponent = semantics->maxExponent;
3993
3994 // Use memset to set all but the highest integerPart to all ones.
3995 integerPart *significand = significandParts();
3996 unsigned PartCount = partCount();
3997 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
3998
3999 // Set the high integerPart especially setting all unused top bits for
4000 // internal consistency.
4001 const unsigned NumUnusedHighBits =
4002 PartCount*integerPartWidth - semantics->precision;
4003 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
4004 ? (~integerPart(0) >> NumUnusedHighBits)
4005 : 0;
4006 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
4007 semantics->nanEncoding == fltNanEncoding::AllOnes &&
4008 (semantics->precision > 1))
4009 significand[0] &= ~integerPart(1);
4010}
4011
4012/// Make this number the smallest magnitude denormal number in the given
4013/// semantics.
4014void IEEEFloat::makeSmallest(bool Negative) {
4015 if (Negative && !semantics->hasSignedRepr)
4017 "This floating point format does not support signed values");
4018 // We want (in interchange format):
4019 // sign = {Negative}
4020 // exponent = 0..0
4021 // significand = 0..01
4022 category = fcNormal;
4023 sign = Negative;
4024 exponent = semantics->minExponent;
4025 APInt::tcSet(significandParts(), 1, partCount());
4026}
4027
4029 if (Negative && !semantics->hasSignedRepr)
4031 "This floating point format does not support signed values");
4032 // We want (in interchange format):
4033 // sign = {Negative}
4034 // exponent = 0..0
4035 // significand = 10..0
4036
4037 category = fcNormal;
4038 zeroSignificand();
4039 sign = Negative;
4040 exponent = semantics->minExponent;
4041 APInt::tcSetBit(significandParts(), semantics->precision - 1);
4042}
4043
4044IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
4045 initFromAPInt(&Sem, API);
4046}
4047
4049 initFromAPInt(&APFloatBase::semIEEEsingle, APInt::floatToBits(f));
4050}
4051
4053 initFromAPInt(&APFloatBase::semIEEEdouble, APInt::doubleToBits(d));
4054}
4055
4056namespace {
4057 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
4058 Buffer.append(Str.begin(), Str.end());
4059 }
4060
4061 /// Removes data from the given significand until it is no more
4062 /// precise than is required for the desired precision.
4063 void AdjustToPrecision(APInt &significand,
4064 int &exp, unsigned FormatPrecision) {
4065 unsigned bits = significand.getActiveBits();
4066
4067 // 196/59 is a very slight overestimate of lg_2(10).
4068 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
4069
4070 if (bits <= bitsRequired) return;
4071
4072 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
4073 if (!tensRemovable) return;
4074
4075 exp += tensRemovable;
4076
4077 APInt divisor(significand.getBitWidth(), 1);
4078 APInt powten(significand.getBitWidth(), 10);
4079 while (true) {
4080 if (tensRemovable & 1)
4081 divisor *= powten;
4082 tensRemovable >>= 1;
4083 if (!tensRemovable) break;
4084 powten *= powten;
4085 }
4086
4087 significand = significand.udiv(divisor);
4088
4089 // Truncate the significand down to its active bit count.
4090 significand = significand.trunc(significand.getActiveBits());
4091 }
4092
4093
4094 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
4095 int &exp, unsigned FormatPrecision) {
4096 unsigned N = buffer.size();
4097 if (N <= FormatPrecision) return;
4098
4099 // The most significant figures are the last ones in the buffer.
4100 unsigned FirstSignificant = N - FormatPrecision;
4101
4102 // Round.
4103 // FIXME: this probably shouldn't use 'round half up'.
4104
4105 // Rounding down is just a truncation, except we also want to drop
4106 // trailing zeros from the new result.
4107 if (buffer[FirstSignificant - 1] < '5') {
4108 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
4109 FirstSignificant++;
4110
4111 exp += FirstSignificant;
4112 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4113 return;
4114 }
4115
4116 // Rounding up requires a decimal add-with-carry. If we continue
4117 // the carry, the newly-introduced zeros will just be truncated.
4118 for (unsigned I = FirstSignificant; I != N; ++I) {
4119 if (buffer[I] == '9') {
4120 FirstSignificant++;
4121 } else {
4122 buffer[I]++;
4123 break;
4124 }
4125 }
4126
4127 // If we carried through, we have exactly one digit of precision.
4128 if (FirstSignificant == N) {
4129 exp += FirstSignificant;
4130 buffer.clear();
4131 buffer.push_back('1');
4132 return;
4133 }
4134
4135 exp += FirstSignificant;
4136 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4137 }
4138
4139 void toStringImpl(SmallVectorImpl<char> &Str, const bool isNeg, int exp,
4140 APInt significand, unsigned FormatPrecision,
4141 unsigned FormatMaxPadding, bool TruncateZero) {
4142 const int semanticsPrecision = significand.getBitWidth();
4143
4144 if (isNeg)
4145 Str.push_back('-');
4146
4147 // Set FormatPrecision if zero. We want to do this before we
4148 // truncate trailing zeros, as those are part of the precision.
4149 if (!FormatPrecision) {
4150 // We use enough digits so the number can be round-tripped back to an
4151 // APFloat. The formula comes from "How to Print Floating-Point Numbers
4152 // Accurately" by Steele and White.
4153 // FIXME: Using a formula based purely on the precision is conservative;
4154 // we can print fewer digits depending on the actual value being printed.
4155
4156 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
4157 FormatPrecision = 2 + semanticsPrecision * 59 / 196;
4158 }
4159
4160 // Ignore trailing binary zeros.
4161 int trailingZeros = significand.countr_zero();
4162 exp += trailingZeros;
4163 significand.lshrInPlace(trailingZeros);
4164
4165 // Change the exponent from 2^e to 10^e.
4166 if (exp == 0) {
4167 // Nothing to do.
4168 } else if (exp > 0) {
4169 // Just shift left.
4170 significand = significand.zext(semanticsPrecision + exp);
4171 significand <<= exp;
4172 exp = 0;
4173 } else { /* exp < 0 */
4174 int texp = -exp;
4175
4176 // We transform this using the identity:
4177 // (N)(2^-e) == (N)(5^e)(10^-e)
4178 // This means we have to multiply N (the significand) by 5^e.
4179 // To avoid overflow, we have to operate on numbers large
4180 // enough to store N * 5^e:
4181 // log2(N * 5^e) == log2(N) + e * log2(5)
4182 // <= semantics->precision + e * 137 / 59
4183 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
4184
4185 unsigned precision = semanticsPrecision + (137 * texp + 136) / 59;
4186
4187 // Multiply significand by 5^e.
4188 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
4189 significand = significand.zext(precision);
4190 APInt five_to_the_i(precision, 5);
4191 while (true) {
4192 if (texp & 1)
4193 significand *= five_to_the_i;
4194
4195 texp >>= 1;
4196 if (!texp)
4197 break;
4198 five_to_the_i *= five_to_the_i;
4199 }
4200 }
4201
4202 AdjustToPrecision(significand, exp, FormatPrecision);
4203
4205
4206 // Fill the buffer.
4207 unsigned precision = significand.getBitWidth();
4208 if (precision < 4) {
4209 // We need enough precision to store the value 10.
4210 precision = 4;
4211 significand = significand.zext(precision);
4212 }
4213 APInt ten(precision, 10);
4214 APInt digit(precision, 0);
4215
4216 bool inTrail = true;
4217 while (significand != 0) {
4218 // digit <- significand % 10
4219 // significand <- significand / 10
4220 APInt::udivrem(significand, ten, significand, digit);
4221
4222 unsigned d = digit.getZExtValue();
4223
4224 // Drop trailing zeros.
4225 if (inTrail && !d)
4226 exp++;
4227 else {
4228 buffer.push_back((char) ('0' + d));
4229 inTrail = false;
4230 }
4231 }
4232
4233 assert(!buffer.empty() && "no characters in buffer!");
4234
4235 // Drop down to FormatPrecision.
4236 // TODO: don't do more precise calculations above than are required.
4237 AdjustToPrecision(buffer, exp, FormatPrecision);
4238
4239 unsigned NDigits = buffer.size();
4240
4241 // Check whether we should use scientific notation.
4242 bool FormatScientific;
4243 if (!FormatMaxPadding) {
4244 FormatScientific = true;
4245 } else {
4246 if (exp >= 0) {
4247 // 765e3 --> 765000
4248 // ^^^
4249 // But we shouldn't make the number look more precise than it is.
4250 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
4251 NDigits + (unsigned) exp > FormatPrecision);
4252 } else {
4253 // Power of the most significant digit.
4254 int MSD = exp + (int) (NDigits - 1);
4255 if (MSD >= 0) {
4256 // 765e-2 == 7.65
4257 FormatScientific = false;
4258 } else {
4259 // 765e-5 == 0.00765
4260 // ^ ^^
4261 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
4262 }
4263 }
4264 }
4265
4266 // Scientific formatting is pretty straightforward.
4267 if (FormatScientific) {
4268 exp += (NDigits - 1);
4269
4270 Str.push_back(buffer[NDigits-1]);
4271 Str.push_back('.');
4272 if (NDigits == 1 && TruncateZero)
4273 Str.push_back('0');
4274 else
4275 for (unsigned I = 1; I != NDigits; ++I)
4276 Str.push_back(buffer[NDigits-1-I]);
4277 // Fill with zeros up to FormatPrecision.
4278 if (!TruncateZero && FormatPrecision > NDigits - 1)
4279 Str.append(FormatPrecision - NDigits + 1, '0');
4280 // For !TruncateZero we use lower 'e'.
4281 Str.push_back(TruncateZero ? 'E' : 'e');
4282
4283 Str.push_back(exp >= 0 ? '+' : '-');
4284 if (exp < 0)
4285 exp = -exp;
4286 SmallVector<char, 6> expbuf;
4287 do {
4288 expbuf.push_back((char) ('0' + (exp % 10)));
4289 exp /= 10;
4290 } while (exp);
4291 // Exponent always at least two digits if we do not truncate zeros.
4292 if (!TruncateZero && expbuf.size() < 2)
4293 expbuf.push_back('0');
4294 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
4295 Str.push_back(expbuf[E-1-I]);
4296 return;
4297 }
4298
4299 // Non-scientific, positive exponents.
4300 if (exp >= 0) {
4301 for (unsigned I = 0; I != NDigits; ++I)
4302 Str.push_back(buffer[NDigits-1-I]);
4303 for (unsigned I = 0; I != (unsigned) exp; ++I)
4304 Str.push_back('0');
4305 return;
4306 }
4307
4308 // Non-scientific, negative exponents.
4309
4310 // The number of digits to the left of the decimal point.
4311 int NWholeDigits = exp + (int) NDigits;
4312
4313 unsigned I = 0;
4314 if (NWholeDigits > 0) {
4315 for (; I != (unsigned) NWholeDigits; ++I)
4316 Str.push_back(buffer[NDigits-I-1]);
4317 Str.push_back('.');
4318 } else {
4319 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
4320
4321 Str.push_back('0');
4322 Str.push_back('.');
4323 for (unsigned Z = 1; Z != NZeros; ++Z)
4324 Str.push_back('0');
4325 }
4326
4327 for (; I != NDigits; ++I)
4328 Str.push_back(buffer[NDigits-I-1]);
4329
4330 }
4331} // namespace
4332
4333void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
4334 unsigned FormatMaxPadding, bool TruncateZero) const {
4335 switch (category) {
4336 case fcInfinity:
4337 if (isNegative())
4338 return append(Str, "-Inf");
4339 else
4340 return append(Str, "+Inf");
4341
4342 case fcNaN: return append(Str, "NaN");
4343
4344 case fcZero:
4345 if (isNegative())
4346 Str.push_back('-');
4347
4348 if (!FormatMaxPadding) {
4349 if (TruncateZero)
4350 append(Str, "0.0E+0");
4351 else {
4352 append(Str, "0.0");
4353 if (FormatPrecision > 1)
4354 Str.append(FormatPrecision - 1, '0');
4355 append(Str, "e+00");
4356 }
4357 } else {
4358 Str.push_back('0');
4359 }
4360 return;
4361
4362 case fcNormal:
4363 break;
4364 }
4365
4366 // Decompose the number into an APInt and an exponent.
4367 int exp = exponent - ((int) semantics->precision - 1);
4368 APInt significand(
4369 semantics->precision,
4370 ArrayRef(significandParts(), partCountForBits(semantics->precision)));
4371
4372 toStringImpl(Str, isNegative(), exp, significand, FormatPrecision,
4373 FormatMaxPadding, TruncateZero);
4374
4375}
4376
4378 if (!isFinite() || isZero())
4379 return INT_MIN;
4380
4381 const integerPart *Parts = significandParts();
4382 const int PartCount = partCountForBits(semantics->precision);
4383
4384 int PopCount = 0;
4385 for (int i = 0; i < PartCount; ++i) {
4386 PopCount += llvm::popcount(Parts[i]);
4387 if (PopCount > 1)
4388 return INT_MIN;
4389 }
4390
4391 if (exponent != semantics->minExponent)
4392 return exponent;
4393
4394 int CountrParts = 0;
4395 for (int i = 0; i < PartCount;
4396 ++i, CountrParts += APInt::APINT_BITS_PER_WORD) {
4397 if (Parts[i] != 0) {
4398 return exponent - semantics->precision + CountrParts +
4399 llvm::countr_zero(Parts[i]) + 1;
4400 }
4401 }
4402
4403 llvm_unreachable("didn't find the set bit");
4404}
4405
4407 if (!isNaN())
4408 return false;
4409 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly ||
4410 semantics->nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
4411 return false;
4412
4413 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
4414 // first bit of the trailing significand being 0.
4415 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
4416}
4417
4418/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
4419///
4420/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
4421/// appropriate sign switching before/after the computation.
4423 // If we are performing nextDown, swap sign so we have -x.
4424 if (nextDown)
4425 changeSign();
4426
4427 // Compute nextUp(x)
4428 opStatus result = opOK;
4429
4430 // Handle each float category separately.
4431 switch (category) {
4432 case fcInfinity:
4433 // nextUp(+inf) = +inf
4434 if (!isNegative())
4435 break;
4436 // nextUp(-inf) = -getLargest()
4437 makeLargest(true);
4438 break;
4439 case fcNaN:
4440 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
4441 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
4442 // change the payload.
4443 if (isSignaling()) {
4444 result = opInvalidOp;
4445 // For consistency, propagate the sign of the sNaN to the qNaN.
4446 makeNaN(false, isNegative(), nullptr);
4447 }
4448 break;
4449 case fcZero:
4450 // nextUp(pm 0) = +getSmallest()
4451 makeSmallest(false);
4452 break;
4453 case fcNormal:
4454 // nextUp(-getSmallest()) = -0
4455 if (isSmallest() && isNegative()) {
4456 APInt::tcSet(significandParts(), 0, partCount());
4457 category = fcZero;
4458 exponent = 0;
4459 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
4460 sign = false;
4461 if (!semantics->hasZero)
4463 break;
4464 }
4465
4466 if (isLargest() && !isNegative()) {
4467 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
4468 // nextUp(getLargest()) == NAN
4469 makeNaN();
4470 break;
4471 } else if (semantics->nonFiniteBehavior ==
4473 // nextUp(getLargest()) == getLargest()
4474 break;
4475 } else {
4476 // nextUp(getLargest()) == INFINITY
4477 APInt::tcSet(significandParts(), 0, partCount());
4478 category = fcInfinity;
4479 exponent = semantics->maxExponent + 1;
4480 break;
4481 }
4482 }
4483
4484 // nextUp(normal) == normal + inc.
4485 if (isNegative()) {
4486 // If we are negative, we need to decrement the significand.
4487
4488 // We only cross a binade boundary that requires adjusting the exponent
4489 // if:
4490 // 1. exponent != semantics->minExponent. This implies we are not in the
4491 // smallest binade or are dealing with denormals.
4492 // 2. Our significand excluding the integral bit is all zeros.
4493 bool WillCrossBinadeBoundary =
4494 exponent != semantics->minExponent && isSignificandAllZeros();
4495
4496 // Decrement the significand.
4497 //
4498 // We always do this since:
4499 // 1. If we are dealing with a non-binade decrement, by definition we
4500 // just decrement the significand.
4501 // 2. If we are dealing with a normal -> normal binade decrement, since
4502 // we have an explicit integral bit the fact that all bits but the
4503 // integral bit are zero implies that subtracting one will yield a
4504 // significand with 0 integral bit and 1 in all other spots. Thus we
4505 // must just adjust the exponent and set the integral bit to 1.
4506 // 3. If we are dealing with a normal -> denormal binade decrement,
4507 // since we set the integral bit to 0 when we represent denormals, we
4508 // just decrement the significand.
4509 integerPart *Parts = significandParts();
4510 APInt::tcDecrement(Parts, partCount());
4511
4512 if (WillCrossBinadeBoundary) {
4513 // Our result is a normal number. Do the following:
4514 // 1. Set the integral bit to 1.
4515 // 2. Decrement the exponent.
4516 APInt::tcSetBit(Parts, semantics->precision - 1);
4517 exponent--;
4518 }
4519 } else {
4520 // If we are positive, we need to increment the significand.
4521
4522 // We only cross a binade boundary that requires adjusting the exponent if
4523 // the input is not a denormal and all of said input's significand bits
4524 // are set. If all of said conditions are true: clear the significand, set
4525 // the integral bit to 1, and increment the exponent. If we have a
4526 // denormal always increment since moving denormals and the numbers in the
4527 // smallest normal binade have the same exponent in our representation.
4528 // If there are only exponents, any increment always crosses the
4529 // BinadeBoundary.
4530 bool WillCrossBinadeBoundary = !APFloat::hasSignificand(*semantics) ||
4531 (!isDenormal() && isSignificandAllOnes());
4532
4533 if (WillCrossBinadeBoundary) {
4534 integerPart *Parts = significandParts();
4535 APInt::tcSet(Parts, 0, partCount());
4536 APInt::tcSetBit(Parts, semantics->precision - 1);
4537 assert(exponent != semantics->maxExponent &&
4538 "We can not increment an exponent beyond the maxExponent allowed"
4539 " by the given floating point semantics.");
4540 exponent++;
4541 } else {
4542 incrementSignificand();
4543 }
4544 }
4545 break;
4546 }
4547
4548 // If we are performing nextDown, swap sign so we have -nextUp(-x)
4549 if (nextDown)
4550 changeSign();
4551
4552 return result;
4553}
4554
4556 assert(isNaN() && "Can only be called on NaN values");
4557 // Number of bits in the payload, excluding the (maybe implied) integer bit.
4558 unsigned Bits = semantics->precision - 1;
4559 return APInt(Bits, ArrayRef(significandParts(), partCountForBits(Bits)));
4560}
4561
4562APFloatBase::ExponentType IEEEFloat::exponentNaN() const {
4563 return ::exponentNaN(*semantics);
4564}
4565
4566APFloatBase::ExponentType IEEEFloat::exponentInf() const {
4567 return ::exponentInf(*semantics);
4568}
4569
4570APFloatBase::ExponentType IEEEFloat::exponentZero() const {
4571 return ::exponentZero(*semantics);
4572}
4573
4574void IEEEFloat::makeInf(bool Negative) {
4575 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
4576 llvm_unreachable("This floating point format does not support Inf");
4577
4578 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
4579 // There is no Inf, so make NaN instead.
4580 makeNaN(false, Negative);
4581 return;
4582 }
4583 category = fcInfinity;
4584 sign = Negative;
4585 exponent = exponentInf();
4586 APInt::tcSet(significandParts(), 0, partCount());
4587}
4588
4589void IEEEFloat::makeZero(bool Negative) {
4590 if (!semantics->hasZero)
4591 llvm_unreachable("This floating point format does not support Zero");
4592
4593 category = fcZero;
4594 sign = Negative;
4595 if (semantics->nanEncoding == fltNanEncoding::NegativeZero) {
4596 // Merge negative zero to positive because 0b10000...000 is used for NaN
4597 sign = false;
4598 }
4599 exponent = exponentZero();
4600 APInt::tcSet(significandParts(), 0, partCount());
4601}
4602
4604 assert(isNaN());
4605 if (semantics->nonFiniteBehavior != fltNonfiniteBehavior::NanOnly)
4606 APInt::tcSetBit(significandParts(), semantics->precision - 2);
4607}
4608
4609int ilogb(const IEEEFloat &Arg) {
4610 if (Arg.isNaN())
4611 return APFloat::IEK_NaN;
4612 if (Arg.isZero())
4613 return APFloat::IEK_Zero;
4614 if (Arg.isInfinity())
4615 return APFloat::IEK_Inf;
4616 if (!Arg.isDenormal())
4617 return Arg.exponent;
4618
4619 IEEEFloat Normalized(Arg);
4620 int SignificandBits = Arg.getSemantics().precision - 1;
4621
4622 Normalized.exponent += SignificandBits;
4623 Normalized.normalize(APFloat::rmNearestTiesToEven, lfExactlyZero);
4624 return Normalized.exponent - SignificandBits;
4625}
4626
4628 auto MaxExp = X.getSemantics().maxExponent;
4629 auto MinExp = X.getSemantics().minExponent;
4630
4631 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
4632 // overflow; clamp it to a safe range before adding, but ensure that the range
4633 // is large enough that the clamp does not change the result. The range we
4634 // need to support is the difference between the largest possible exponent and
4635 // the normalized exponent of half the smallest denormal.
4636
4637 int SignificandBits = X.getSemantics().precision - 1;
4638 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
4639
4640 // Clamp to one past the range ends to let normalize handle overlflow.
4641 X.exponent += std::clamp(Exp, -MaxIncrement - 1, MaxIncrement);
4642 X.normalize(RoundingMode, lfExactlyZero);
4643 if (X.isNaN())
4644 X.makeQuiet();
4645 return X;
4646}
4647
4648IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM) {
4649 Exp = ilogb(Val);
4650
4651 // Quiet signalling nans.
4652 if (Exp == APFloat::IEK_NaN) {
4653 IEEEFloat Quiet(Val);
4654 Quiet.makeQuiet();
4655 return Quiet;
4656 }
4657
4658 if (Exp == APFloat::IEK_Inf)
4659 return Val;
4660
4661 // 1 is added because frexp is defined to return a normalized fraction in
4662 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
4663 Exp = Exp == APFloat::IEK_Zero ? 0 : Exp + 1;
4664 return scalbn(Val, -Exp, RM);
4665}
4666
4668 : Semantics(&S),
4669 Floats(new APFloat[2]{APFloat(APFloatBase::semIEEEdouble),
4670 APFloat(APFloatBase::semIEEEdouble)}) {
4671 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4672}
4673
4675 : Semantics(&S), Floats(new APFloat[2]{
4676 APFloat(APFloatBase::semIEEEdouble, uninitialized),
4677 APFloat(APFloatBase::semIEEEdouble, uninitialized)}) {
4678 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4679}
4680
4682 : Semantics(&S),
4683 Floats(new APFloat[2]{APFloat(APFloatBase::semIEEEdouble, I),
4684 APFloat(APFloatBase::semIEEEdouble)}) {
4685 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4686}
4687
4689 : Semantics(&S),
4690 Floats(new APFloat[2]{
4691 APFloat(APFloatBase::semIEEEdouble, APInt(64, I.getRawData()[0])),
4692 APFloat(APFloatBase::semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
4693 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4694}
4695
4697 APFloat &&Second)
4698 : Semantics(&S),
4699 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
4700 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4701 assert(&Floats[0].getSemantics() == &APFloatBase::semIEEEdouble);
4702 assert(&Floats[1].getSemantics() == &APFloatBase::semIEEEdouble);
4703}
4704
4706 : Semantics(RHS.Semantics),
4707 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
4708 APFloat(RHS.Floats[1])}
4709 : nullptr) {
4710 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4711}
4712
4714 : Semantics(RHS.Semantics), Floats(RHS.Floats) {
4715 RHS.Semantics = &APFloatBase::semBogus;
4716 RHS.Floats = nullptr;
4717 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4718}
4719
4721 if (Semantics == RHS.Semantics && RHS.Floats) {
4722 Floats[0] = RHS.Floats[0];
4723 Floats[1] = RHS.Floats[1];
4724 } else if (this != &RHS) {
4725 this->~DoubleAPFloat();
4726 new (this) DoubleAPFloat(RHS);
4727 }
4728 return *this;
4729}
4730
4731// Returns a result such that:
4732// 1. abs(Lo) <= ulp(Hi)/2
4733// 2. Hi == RTNE(Hi + Lo)
4734// 3. Hi + Lo == X + Y
4735//
4736// Requires that log2(X) >= log2(Y).
4737static std::pair<APFloat, APFloat> fastTwoSum(APFloat X, APFloat Y) {
4738 if (!X.isFinite())
4739 return {X, APFloat::getZero(X.getSemantics(), /*Negative=*/false)};
4740 APFloat Hi = X + Y;
4741 APFloat Delta = Hi - X;
4742 APFloat Lo = Y - Delta;
4743 return {Hi, Lo};
4744}
4745
4746// Implement addition, subtraction, multiplication and division based on:
4747// "Software for Doubled-Precision Floating-Point Computations",
4748// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
4749APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
4750 const APFloat &c, const APFloat &cc,
4751 roundingMode RM) {
4752 int Status = opOK;
4753 APFloat z = a;
4754 Status |= z.add(c, RM);
4755 if (!z.isFinite()) {
4756 if (!z.isInfinity()) {
4757 Floats[0] = std::move(z);
4758 Floats[1].makeZero(/* Neg = */ false);
4759 return (opStatus)Status;
4760 }
4761 Status = opOK;
4762 auto AComparedToC = a.compareAbsoluteValue(c);
4763 z = cc;
4764 Status |= z.add(aa, RM);
4765 if (AComparedToC == APFloat::cmpGreaterThan) {
4766 // z = cc + aa + c + a;
4767 Status |= z.add(c, RM);
4768 Status |= z.add(a, RM);
4769 } else {
4770 // z = cc + aa + a + c;
4771 Status |= z.add(a, RM);
4772 Status |= z.add(c, RM);
4773 }
4774 if (!z.isFinite()) {
4775 Floats[0] = std::move(z);
4776 Floats[1].makeZero(/* Neg = */ false);
4777 return (opStatus)Status;
4778 }
4779 Floats[0] = z;
4780 APFloat zz = aa;
4781 Status |= zz.add(cc, RM);
4782 if (AComparedToC == APFloat::cmpGreaterThan) {
4783 // Floats[1] = a - z + c + zz;
4784 Floats[1] = a;
4785 Status |= Floats[1].subtract(z, RM);
4786 Status |= Floats[1].add(c, RM);
4787 Status |= Floats[1].add(zz, RM);
4788 } else {
4789 // Floats[1] = c - z + a + zz;
4790 Floats[1] = c;
4791 Status |= Floats[1].subtract(z, RM);
4792 Status |= Floats[1].add(a, RM);
4793 Status |= Floats[1].add(zz, RM);
4794 }
4795 } else {
4796 // q = a - z;
4797 APFloat q = a;
4798 Status |= q.subtract(z, RM);
4799
4800 // zz = q + c + (a - (q + z)) + aa + cc;
4801 // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
4802 auto zz = q;
4803 Status |= zz.add(c, RM);
4804 Status |= q.add(z, RM);
4805 Status |= q.subtract(a, RM);
4806 q.changeSign();
4807 Status |= zz.add(q, RM);
4808 Status |= zz.add(aa, RM);
4809 Status |= zz.add(cc, RM);
4810 if (zz.isZero() && !zz.isNegative()) {
4811 Floats[0] = std::move(z);
4812 Floats[1].makeZero(/* Neg = */ false);
4813 return opOK;
4814 }
4815 Floats[0] = z;
4816 Status |= Floats[0].add(zz, RM);
4817 if (!Floats[0].isFinite()) {
4818 Floats[1].makeZero(/* Neg = */ false);
4819 return (opStatus)Status;
4820 }
4821 Floats[1] = std::move(z);
4822 Status |= Floats[1].subtract(Floats[0], RM);
4823 Status |= Floats[1].add(zz, RM);
4824 }
4825 return (opStatus)Status;
4826}
4827
4828APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
4829 const DoubleAPFloat &RHS,
4830 DoubleAPFloat &Out,
4831 roundingMode RM) {
4832 if (LHS.getCategory() == fcNaN) {
4833 Out = LHS;
4834 return opOK;
4835 }
4836 if (RHS.getCategory() == fcNaN) {
4837 Out = RHS;
4838 return opOK;
4839 }
4840 if (LHS.getCategory() == fcZero) {
4841 Out = RHS;
4842 return opOK;
4843 }
4844 if (RHS.getCategory() == fcZero) {
4845 Out = LHS;
4846 return opOK;
4847 }
4848 if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity &&
4849 LHS.isNegative() != RHS.isNegative()) {
4850 Out.makeNaN(false, Out.isNegative(), nullptr);
4851 return opInvalidOp;
4852 }
4853 if (LHS.getCategory() == fcInfinity) {
4854 Out = LHS;
4855 return opOK;
4856 }
4857 if (RHS.getCategory() == fcInfinity) {
4858 Out = RHS;
4859 return opOK;
4860 }
4861 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
4862
4863 APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
4864 CC(RHS.Floats[1]);
4865 assert(&A.getSemantics() == &APFloatBase::semIEEEdouble);
4866 assert(&AA.getSemantics() == &APFloatBase::semIEEEdouble);
4867 assert(&C.getSemantics() == &APFloatBase::semIEEEdouble);
4868 assert(&CC.getSemantics() == &APFloatBase::semIEEEdouble);
4869 assert(&Out.Floats[0].getSemantics() == &APFloatBase::semIEEEdouble);
4870 assert(&Out.Floats[1].getSemantics() == &APFloatBase::semIEEEdouble);
4871 return Out.addImpl(A, AA, C, CC, RM);
4872}
4873
4875 roundingMode RM) {
4876 return addWithSpecial(*this, RHS, *this, RM);
4877}
4878
4880 roundingMode RM) {
4881 changeSign();
4882 auto Ret = add(RHS, RM);
4883 changeSign();
4884 return Ret;
4885}
4886
4889 const auto &LHS = *this;
4890 auto &Out = *this;
4891 /* Interesting observation: For special categories, finding the lowest
4892 common ancestor of the following layered graph gives the correct
4893 return category:
4894
4895 NaN
4896 / \
4897 Zero Inf
4898 \ /
4899 Normal
4900
4901 e.g. NaN * NaN = NaN
4902 Zero * Inf = NaN
4903 Normal * Zero = Zero
4904 Normal * Inf = Inf
4905 */
4906 if (LHS.getCategory() == fcNaN) {
4907 Out = LHS;
4908 return opOK;
4909 }
4910 if (RHS.getCategory() == fcNaN) {
4911 Out = RHS;
4912 return opOK;
4913 }
4914 if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) ||
4915 (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) {
4916 Out.makeNaN(false, false, nullptr);
4917 return opOK;
4918 }
4919 if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) {
4920 Out = LHS;
4921 return opOK;
4922 }
4923 if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) {
4924 Out = RHS;
4925 return opOK;
4926 }
4927 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
4928 "Special cases not handled exhaustively");
4929
4930 int Status = opOK;
4931 APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
4932 // t = a * c
4933 APFloat T = A;
4934 Status |= T.multiply(C, RM);
4935 if (!T.isFiniteNonZero()) {
4936 Floats[0] = std::move(T);
4937 Floats[1].makeZero(/* Neg = */ false);
4938 return (opStatus)Status;
4939 }
4940
4941 // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
4942 APFloat Tau = A;
4943 T.changeSign();
4944 Status |= Tau.fusedMultiplyAdd(C, T, RM);
4945 T.changeSign();
4946 {
4947 // v = a * d
4948 APFloat V = A;
4949 Status |= V.multiply(D, RM);
4950 // w = b * c
4951 APFloat W = B;
4952 Status |= W.multiply(C, RM);
4953 Status |= V.add(W, RM);
4954 // tau += v + w
4955 Status |= Tau.add(V, RM);
4956 }
4957 // u = t + tau
4958 APFloat U = T;
4959 Status |= U.add(Tau, RM);
4960
4961 Floats[0] = U;
4962 if (!U.isFinite()) {
4963 Floats[1].makeZero(/* Neg = */ false);
4964 } else {
4965 // Floats[1] = (t - u) + tau
4966 Status |= T.subtract(U, RM);
4967 Status |= T.add(Tau, RM);
4968 Floats[1] = std::move(T);
4969 }
4970 return (opStatus)Status;
4971}
4972
4975 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
4976 "Unexpected Semantics");
4977 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
4978 auto Ret = Tmp.divide(
4979 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
4980 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
4981 return Ret;
4982}
4983
4985 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
4986 "Unexpected Semantics");
4987 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
4988 auto Ret = Tmp.remainder(
4989 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4990 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
4991 return Ret;
4992}
4993
4995 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
4996 "Unexpected Semantics");
4997 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
4998 auto Ret = Tmp.mod(
4999 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
5000 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5001 return Ret;
5002}
5003
5006 const DoubleAPFloat &Addend,
5008 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5009 "Unexpected Semantics");
5010 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
5011 auto Ret = Tmp.fusedMultiplyAdd(
5012 APFloat(APFloatBase::semPPCDoubleDoubleLegacy,
5013 Multiplicand.bitcastToAPInt()),
5014 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()),
5015 RM);
5016 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5017 return Ret;
5018}
5019
5021 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5022 "Unexpected Semantics");
5023 const APFloat &Hi = getFirst();
5024 const APFloat &Lo = getSecond();
5025
5026 APFloat RoundedHi = Hi;
5027 const opStatus HiStatus = RoundedHi.roundToIntegral(RM);
5028
5029 // We can reduce the problem to just the high part if the input:
5030 // 1. Represents a non-finite value.
5031 // 2. Has a component which is zero.
5032 if (!Hi.isFiniteNonZero() || Lo.isZero()) {
5033 Floats[0] = std::move(RoundedHi);
5034 Floats[1].makeZero(/*Neg=*/false);
5035 return HiStatus;
5036 }
5037
5038 // Adjust `Rounded` in the direction of `TieBreaker` if `ToRound` was at a
5039 // halfway point.
5040 auto RoundToNearestHelper = [](APFloat ToRound, APFloat Rounded,
5041 APFloat TieBreaker) {
5042 // RoundingError tells us which direction we rounded:
5043 // - RoundingError > 0: we rounded up.
5044 // - RoundingError < 0: we rounded down.
5045 // Sterbenz' lemma ensures that RoundingError is exact.
5046 const APFloat RoundingError = Rounded - ToRound;
5047 if (TieBreaker.isNonZero() &&
5048 TieBreaker.isNegative() != RoundingError.isNegative() &&
5049 abs(RoundingError).isExactlyValue(0.5))
5050 Rounded.add(
5051 APFloat::getOne(Rounded.getSemantics(), TieBreaker.isNegative()),
5053 return Rounded;
5054 };
5055
5056 // Case 1: Hi is not an integer.
5057 // Special cases are for rounding modes that are sensitive to ties.
5058 if (RoundedHi != Hi) {
5059 // We need to consider the case where Hi was between two integers and the
5060 // rounding mode broke the tie when, in fact, Lo may have had a different
5061 // sign than Hi.
5062 if (RM == rmNearestTiesToAway || RM == rmNearestTiesToEven)
5063 RoundedHi = RoundToNearestHelper(Hi, RoundedHi, Lo);
5064
5065 Floats[0] = std::move(RoundedHi);
5066 Floats[1].makeZero(/*Neg=*/false);
5067 return HiStatus;
5068 }
5069
5070 // Case 2: Hi is an integer.
5071 // Special cases are for rounding modes which are rounding towards or away from zero.
5072 RoundingMode LoRoundingMode;
5073 if (RM == rmTowardZero)
5074 // When our input is positive, we want the Lo component rounded toward
5075 // negative infinity to get the smallest result magnitude. Likewise,
5076 // negative inputs want the Lo component rounded toward positive infinity.
5077 LoRoundingMode = isNegative() ? rmTowardPositive : rmTowardNegative;
5078 else
5079 LoRoundingMode = RM;
5080
5081 APFloat RoundedLo = Lo;
5082 const opStatus LoStatus = RoundedLo.roundToIntegral(LoRoundingMode);
5083 if (LoRoundingMode == rmNearestTiesToAway)
5084 // We need to consider the case where Lo was between two integers and the
5085 // rounding mode broke the tie when, in fact, Hi may have had a different
5086 // sign than Lo.
5087 RoundedLo = RoundToNearestHelper(Lo, RoundedLo, Hi);
5088
5089 // We must ensure that the final result has no overlap between the two APFloat values.
5090 std::tie(RoundedHi, RoundedLo) = fastTwoSum(RoundedHi, RoundedLo);
5091
5092 Floats[0] = std::move(RoundedHi);
5093 Floats[1] = std::move(RoundedLo);
5094 return LoStatus;
5095}
5096
5098 Floats[0].changeSign();
5099 Floats[1].changeSign();
5100}
5101
5104 // Compare absolute values of the high parts.
5105 const cmpResult HiPartCmp = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
5106 if (HiPartCmp != cmpEqual)
5107 return HiPartCmp;
5108
5109 // Zero, regardless of sign, is equal.
5110 if (Floats[1].isZero() && RHS.Floats[1].isZero())
5111 return cmpEqual;
5112
5113 // At this point, |this->Hi| == |RHS.Hi|.
5114 // The magnitude is |Hi+Lo| which is Hi+|Lo| if signs of Hi and Lo are the
5115 // same, and Hi-|Lo| if signs are different.
5116 const bool ThisIsSubtractive =
5117 Floats[0].isNegative() != Floats[1].isNegative();
5118 const bool RHSIsSubtractive =
5119 RHS.Floats[0].isNegative() != RHS.Floats[1].isNegative();
5120
5121 // Case 1: The low part of 'this' is zero.
5122 if (Floats[1].isZero())
5123 // We are comparing |Hi| vs. |Hi| ± |RHS.Lo|.
5124 // If RHS is subtractive, its magnitude is smaller.
5125 // If RHS is additive, its magnitude is larger.
5126 return RHSIsSubtractive ? cmpGreaterThan : cmpLessThan;
5127
5128 // Case 2: The low part of 'RHS' is zero (and we know 'this' is not).
5129 if (RHS.Floats[1].isZero())
5130 // We are comparing |Hi| ± |This.Lo| vs. |Hi|.
5131 // If 'this' is subtractive, its magnitude is smaller.
5132 // If 'this' is additive, its magnitude is larger.
5133 return ThisIsSubtractive ? cmpLessThan : cmpGreaterThan;
5134
5135 // If their natures differ, the additive one is larger.
5136 if (ThisIsSubtractive != RHSIsSubtractive)
5137 return ThisIsSubtractive ? cmpLessThan : cmpGreaterThan;
5138
5139 // Case 3: Both are additive (Hi+|Lo|) or both are subtractive (Hi-|Lo|).
5140 // The comparison now depends on the magnitude of the low parts.
5141 const cmpResult LoPartCmp = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
5142
5143 if (ThisIsSubtractive) {
5144 // Both are subtractive (Hi-|Lo|), so the comparison of |Lo| is inverted.
5145 if (LoPartCmp == cmpLessThan)
5146 return cmpGreaterThan;
5147 if (LoPartCmp == cmpGreaterThan)
5148 return cmpLessThan;
5149 }
5150
5151 // If additive, the comparison of |Lo| is direct.
5152 // If equal, they are equal.
5153 return LoPartCmp;
5154}
5155
5157 return Floats[0].getCategory();
5158}
5159
5160bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
5161
5163 Floats[0].makeInf(Neg);
5164 Floats[1].makeZero(/* Neg = */ false);
5165}
5166
5168 Floats[0].makeZero(Neg);
5169 Floats[1].makeZero(/* Neg = */ false);
5170}
5171
5173 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5174 "Unexpected Semantics");
5175 Floats[0] =
5176 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
5177 Floats[1] =
5178 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
5179 if (Neg)
5180 changeSign();
5181}
5182
5184 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5185 "Unexpected Semantics");
5186 Floats[0].makeSmallest(Neg);
5187 Floats[1].makeZero(/* Neg = */ false);
5188}
5189
5191 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5192 "Unexpected Semantics");
5193 Floats[0] =
5194 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x0360000000000000ull));
5195 if (Neg)
5196 Floats[0].changeSign();
5197 Floats[1].makeZero(/* Neg = */ false);
5198}
5199
5200void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
5201 Floats[0].makeNaN(SNaN, Neg, fill);
5202 Floats[1].makeZero(/* Neg = */ false);
5203}
5204
5206 auto Result = Floats[0].compare(RHS.Floats[0]);
5207 // |Float[0]| > |Float[1]|
5208 if (Result == APFloat::cmpEqual)
5209 return Floats[1].compare(RHS.Floats[1]);
5210 return Result;
5211}
5212
5214 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
5215 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
5216}
5217
5219 if (Arg.Floats)
5220 return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
5221 return hash_combine(Arg.Semantics);
5222}
5223
5225 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5226 "Unexpected Semantics");
5227 uint64_t Data[] = {
5228 Floats[0].bitcastToAPInt().getRawData()[0],
5229 Floats[1].bitcastToAPInt().getRawData()[0],
5230 };
5231 return APInt(128, Data);
5232}
5233
5235 roundingMode RM) {
5236 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5237 "Unexpected Semantics");
5238 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy);
5239 auto Ret = Tmp.convertFromString(S, RM);
5240 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5241 return Ret;
5242}
5243
5244// The double-double lattice of values corresponds to numbers which obey:
5245// - abs(lo) <= 1/2 * ulp(hi)
5246// - roundTiesToEven(hi + lo) == hi
5247//
5248// nextUp must choose the smallest output > input that follows these rules.
5249// nexDown must choose the largest output < input that follows these rules.
5251 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5252 "Unexpected Semantics");
5253 // nextDown(x) = -nextUp(-x)
5254 if (nextDown) {
5255 changeSign();
5256 APFloat::opStatus Result = next(/*nextDown=*/false);
5257 changeSign();
5258 return Result;
5259 }
5260 switch (getCategory()) {
5261 case fcInfinity:
5262 // nextUp(+inf) = +inf
5263 // nextUp(-inf) = -getLargest()
5264 if (isNegative())
5265 makeLargest(true);
5266 return opOK;
5267
5268 case fcNaN:
5269 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
5270 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
5271 // change the payload.
5272 if (getFirst().isSignaling()) {
5273 // For consistency, propagate the sign of the sNaN to the qNaN.
5274 makeNaN(false, isNegative(), nullptr);
5275 return opInvalidOp;
5276 }
5277 return opOK;
5278
5279 case fcZero:
5280 // nextUp(pm 0) = +getSmallest()
5281 makeSmallest(false);
5282 return opOK;
5283
5284 case fcNormal:
5285 break;
5286 }
5287
5288 const APFloat &HiOld = getFirst();
5289 const APFloat &LoOld = getSecond();
5290
5291 APFloat NextLo = LoOld;
5292 NextLo.next(/*nextDown=*/false);
5293
5294 // We want to admit values where:
5295 // 1. abs(Lo) <= ulp(Hi)/2
5296 // 2. Hi == RTNE(Hi + lo)
5297 auto InLattice = [](const APFloat &Hi, const APFloat &Lo) {
5298 return Hi + Lo == Hi;
5299 };
5300
5301 // Check if (HiOld, nextUp(LoOld) is in the lattice.
5302 if (InLattice(HiOld, NextLo)) {
5303 // Yes, the result is (HiOld, nextUp(LoOld)).
5304 Floats[1] = std::move(NextLo);
5305
5306 // TODO: Because we currently rely on semPPCDoubleDoubleLegacy, our maximum
5307 // value is defined to have exactly 106 bits of precision. This limitation
5308 // results in semPPCDoubleDouble being unable to reach its maximum canonical
5309 // value.
5310 DoubleAPFloat Largest{*Semantics, uninitialized};
5311 Largest.makeLargest(/*Neg=*/false);
5312 if (compare(Largest) == cmpGreaterThan)
5313 makeInf(/*Neg=*/false);
5314
5315 return opOK;
5316 }
5317
5318 // Now we need to handle the cases where (HiOld, nextUp(LoOld)) is not the
5319 // correct result. We know the new hi component will be nextUp(HiOld) but our
5320 // lattice rules make it a little ambiguous what the correct NextLo must be.
5321 APFloat NextHi = HiOld;
5322 NextHi.next(/*nextDown=*/false);
5323
5324 // nextUp(getLargest()) == INFINITY
5325 if (NextHi.isInfinity()) {
5326 makeInf(/*Neg=*/false);
5327 return opOK;
5328 }
5329
5330 // IEEE 754-2019 5.3.1:
5331 // "If x is the negative number of least magnitude in x's format, nextUp(x) is
5332 // -0."
5333 if (NextHi.isZero()) {
5334 makeZero(/*Neg=*/true);
5335 return opOK;
5336 }
5337
5338 // abs(NextLo) must be <= ulp(NextHi)/2. We want NextLo to be as close to
5339 // negative infinity as possible.
5340 NextLo = neg(scalbn(harrisonUlp(NextHi), -1, rmTowardZero));
5341 if (!InLattice(NextHi, NextLo))
5342 // RTNE may mean that Lo must be < ulp(NextHi) / 2 so we bump NextLo.
5343 NextLo.next(/*nextDown=*/false);
5344
5345 Floats[0] = std::move(NextHi);
5346 Floats[1] = std::move(NextLo);
5347
5348 return opOK;
5349}
5350
5351APFloat::opStatus DoubleAPFloat::convertToSignExtendedInteger(
5352 MutableArrayRef<integerPart> Input, unsigned int Width, bool IsSigned,
5353 roundingMode RM, bool *IsExact) const {
5354 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5355 "Unexpected Semantics");
5356
5357 // If Hi is not finite, or Lo is zero, the value is entirely represented
5358 // by Hi. Delegate to the simpler single-APFloat conversion.
5359 if (!getFirst().isFiniteNonZero() || getSecond().isZero())
5360 return getFirst().convertToInteger(Input, Width, IsSigned, RM, IsExact);
5361
5362 // First, round the full double-double value to an integral value. This
5363 // simplifies the rest of the function, as we no longer need to consider
5364 // fractional parts.
5365 *IsExact = false;
5366 DoubleAPFloat Integral = *this;
5367 const opStatus RoundStatus = Integral.roundToIntegral(RM);
5368 if (RoundStatus == opInvalidOp)
5369 return opInvalidOp;
5370 const APFloat &IntegralHi = Integral.getFirst();
5371 const APFloat &IntegralLo = Integral.getSecond();
5372
5373 // If rounding results in either component being zero, the sum is trivial.
5374 // Delegate to the simpler single-APFloat conversion.
5375 bool HiIsExact;
5376 if (IntegralHi.isZero() || IntegralLo.isZero()) {
5377 const opStatus HiStatus =
5378 IntegralHi.convertToInteger(Input, Width, IsSigned, RM, &HiIsExact);
5379 // The conversion from an integer-valued float to an APInt may fail if the
5380 // result would be out of range. Regardless, taking this path is only
5381 // possible if rounding occurred during the initial `roundToIntegral`.
5382 return HiStatus == opOK ? opInexact : HiStatus;
5383 }
5384
5385 // A negative number cannot be represented by an unsigned integer.
5386 // Since a double-double is canonical, if Hi is negative, the sum is negative.
5387 if (!IsSigned && IntegralHi.isNegative())
5388 return opInvalidOp;
5389
5390 // Handle the special boundary case where |Hi| is exactly the power of two
5391 // that marks the edge of the integer's range (e.g., 2^63 for int64_t). In
5392 // this situation, Hi itself won't fit, but the sum Hi + Lo might.
5393 // `PositiveOverflowWidth` is the bit number for this boundary (N-1 for
5394 // signed, N for unsigned).
5395 bool LoIsExact;
5396 const int HiExactLog2 = IntegralHi.getExactLog2Abs();
5397 const unsigned PositiveOverflowWidth = IsSigned ? Width - 1 : Width;
5398 if (HiExactLog2 >= 0 &&
5399 static_cast<unsigned>(HiExactLog2) == PositiveOverflowWidth) {
5400 // If Hi and Lo have the same sign, |Hi + Lo| > |Hi|, so the sum is
5401 // guaranteed to overflow. E.g., for uint128_t, (2^128, 1) overflows.
5402 if (IntegralHi.isNegative() == IntegralLo.isNegative())
5403 return opInvalidOp;
5404
5405 // If the signs differ, the sum will fit. We can compute the result using
5406 // properties of two's complement arithmetic without a wide intermediate
5407 // integer. E.g., for uint128_t, (2^128, -1) should be 2^128 - 1.
5408 const opStatus LoStatus = IntegralLo.convertToInteger(
5409 Input, Width, /*IsSigned=*/true, RM, &LoIsExact);
5410 if (LoStatus == opInvalidOp)
5411 return opInvalidOp;
5412
5413 // Adjust the bit pattern of Lo to account for Hi's value:
5414 // - For unsigned (Hi=2^Width): `2^Width + Lo` in `Width`-bit
5415 // arithmetic is equivalent to just `Lo`. The conversion of `Lo` above
5416 // already produced the correct final bit pattern.
5417 // - For signed (Hi=2^(Width-1)): The sum `2^(Width-1) + Lo` (where Lo<0)
5418 // can be computed by taking the two's complement pattern for `Lo` and
5419 // clearing the sign bit.
5420 if (IsSigned && !IntegralHi.isNegative())
5421 APInt::tcClearBit(Input.data(), PositiveOverflowWidth);
5422 *IsExact = RoundStatus == opOK;
5423 return RoundStatus;
5424 }
5425
5426 // Convert Hi into an integer. This may not fit but that is OK: we know that
5427 // Hi + Lo would not fit either in this situation.
5428 const opStatus HiStatus = IntegralHi.convertToInteger(
5429 Input, Width, IsSigned, rmTowardZero, &HiIsExact);
5430 if (HiStatus == opInvalidOp)
5431 return HiStatus;
5432
5433 // Convert Lo into a temporary integer of the same width.
5434 APSInt LoResult{Width, /*isUnsigned=*/!IsSigned};
5435 const opStatus LoStatus =
5436 IntegralLo.convertToInteger(LoResult, rmTowardZero, &LoIsExact);
5437 if (LoStatus == opInvalidOp)
5438 return LoStatus;
5439
5440 // Add Lo to Hi. This addition is guaranteed not to overflow because of the
5441 // double-double canonicalization rule (`|Lo| <= ulp(Hi)/2`). The only case
5442 // where the sum could cross the integer type's boundary is when Hi is a
5443 // power of two, which is handled by the special case block above.
5444 APInt::tcAdd(Input.data(), LoResult.getRawData(), /*carry=*/0, Input.size());
5445
5446 *IsExact = RoundStatus == opOK;
5447 return RoundStatus;
5448}
5449
5452 unsigned int Width, bool IsSigned,
5453 roundingMode RM, bool *IsExact) const {
5454 opStatus FS =
5455 convertToSignExtendedInteger(Input, Width, IsSigned, RM, IsExact);
5456
5457 if (FS == opInvalidOp) {
5458 const unsigned DstPartsCount = partCountForBits(Width);
5459 assert(DstPartsCount <= Input.size() && "Integer too big");
5460
5461 unsigned Bits;
5462 if (getCategory() == fcNaN)
5463 Bits = 0;
5464 else if (isNegative())
5465 Bits = IsSigned;
5466 else
5467 Bits = Width - IsSigned;
5468
5469 tcSetLeastSignificantBits(Input.data(), DstPartsCount, Bits);
5470 if (isNegative() && IsSigned)
5471 APInt::tcShiftLeft(Input.data(), DstPartsCount, Width - 1);
5472 }
5473
5474 return FS;
5475}
5476
5477APFloat::opStatus DoubleAPFloat::handleOverflow(roundingMode RM) {
5478 switch (RM) {
5480 makeLargest(/*Neg=*/isNegative());
5481 break;
5483 if (isNegative())
5484 makeInf(/*Neg=*/true);
5485 else
5486 makeLargest(/*Neg=*/false);
5487 break;
5489 if (isNegative())
5490 makeLargest(/*Neg=*/true);
5491 else
5492 makeInf(/*Neg=*/false);
5493 break;
5496 makeInf(/*Neg=*/isNegative());
5497 break;
5498 default:
5499 llvm_unreachable("Invalid rounding mode found");
5500 }
5501 opStatus S = opInexact;
5502 if (!getFirst().isFinite())
5503 S = static_cast<opStatus>(S | opOverflow);
5504 return S;
5505}
5506
5507APFloat::opStatus DoubleAPFloat::convertFromUnsignedParts(
5508 const integerPart *Src, unsigned int SrcCount, roundingMode RM) {
5509 // Find the most significant bit of the source integer. APInt::tcMSB returns
5510 // UINT_MAX for a zero value.
5511 const unsigned SrcMSB = APInt::tcMSB(Src, SrcCount);
5512 if (SrcMSB == UINT_MAX) {
5513 // The source integer is 0.
5514 makeZero(/*Neg=*/false);
5515 return opOK;
5516 }
5517
5518 // Create a minimally-sized APInt to represent the source value.
5519 const unsigned SrcBitWidth = SrcMSB + 1;
5520 APSInt SrcInt{APInt{/*numBits=*/SrcBitWidth, ArrayRef(Src, SrcCount)},
5521 /*isUnsigned=*/true};
5522
5523 // Stage 1: Initial Approximation.
5524 // Convert the source integer SrcInt to the Hi part of the DoubleAPFloat.
5525 // We use round-to-nearest because it minimizes the initial error, which is
5526 // crucial for the subsequent steps.
5528 Hi.convertFromAPInt(SrcInt, /*IsSigned=*/false, rmNearestTiesToEven);
5529
5530 // If the first approximation already overflows, the number is too large.
5531 // NOTE: The underlying semantics are *more* conservative when choosing to
5532 // overflow because their notion of ULP is much larger. As such, it is always
5533 // safe to overflow at the DoubleAPFloat level if the APFloat overflows.
5534 if (!Hi.isFinite())
5535 return handleOverflow(RM);
5536
5537 // Stage 2: Exact Error Calculation.
5538 // Calculate the exact error of the first approximation: Error = SrcInt - Hi.
5539 // This is done by converting Hi back to an integer and subtracting it from
5540 // the original source.
5541 bool HiAsIntIsExact;
5542 // Create an integer representation of Hi. Its width is determined by the
5543 // exponent of Hi, ensuring it's just large enough. This width can exceed
5544 // SrcBitWidth if the conversion to Hi rounded up to a power of two.
5545 // accurately when converted back to an integer.
5546 APSInt HiAsInt{static_cast<uint32_t>(ilogb(Hi) + 1), /*isUnsigned=*/true};
5547 Hi.convertToInteger(HiAsInt, rmNearestTiesToEven, &HiAsIntIsExact);
5548 const APInt Error = SrcInt.zext(HiAsInt.getBitWidth()) - HiAsInt;
5549
5550 // Stage 3: Error Approximation and Rounding.
5551 // Convert the integer error into the Lo part of the DoubleAPFloat. This step
5552 // captures the remainder of the original number. The rounding mode for this
5553 // conversion (LoRM) may need to be adjusted from the user-requested RM to
5554 // ensure the final sum (Hi + Lo) rounds correctly.
5555 roundingMode LoRM = RM;
5556 // Adjustments are only necessary when the initial approximation Hi was an
5557 // overestimate, making the Error negative.
5558 if (Error.isNegative()) {
5559 if (RM == rmNearestTiesToAway) {
5560 // For rmNearestTiesToAway, a tie should round away from zero. Since
5561 // SrcInt is positive, this means rounding toward +infinity.
5562 // A standard conversion of a negative Error would round ties toward
5563 // -infinity, causing the final sum Hi + Lo to be smaller. To
5564 // counteract this, we detect the tie case and override the rounding
5565 // mode for Lo to rmTowardPositive.
5566 const unsigned ErrorActiveBits = Error.getSignificantBits() - 1;
5567 const unsigned LoPrecision = getSecond().getSemantics().precision;
5568 if (ErrorActiveBits > LoPrecision) {
5569 const unsigned RoundingBoundary = ErrorActiveBits - LoPrecision;
5570 // A tie occurs when the bits to be truncated are of the form 100...0.
5571 // This is detected by checking if the number of trailing zeros is
5572 // exactly one less than the number of bits being truncated.
5573 if (Error.countTrailingZeros() == RoundingBoundary - 1)
5574 LoRM = rmTowardPositive;
5575 }
5576 } else if (RM == rmTowardZero) {
5577 // For rmTowardZero, the final positive result must be truncated (rounded
5578 // down). When Hi is an overestimate, Error is negative. A standard
5579 // rmTowardZero conversion of Error would make it *less* negative,
5580 // effectively rounding the final sum Hi + Lo *up*. To ensure the sum
5581 // rounds down correctly, we force Lo to round toward -infinity.
5582 LoRM = rmTowardNegative;
5583 }
5584 }
5585
5587 opStatus Status = Lo.convertFromAPInt(Error, /*IsSigned=*/true, LoRM);
5588
5589 // Renormalize the pair (Hi, Lo) into a canonical DoubleAPFloat form where the
5590 // components do not overlap. fastTwoSum performs this operation.
5591 std::tie(Hi, Lo) = fastTwoSum(Hi, Lo);
5592 Floats[0] = std::move(Hi);
5593 Floats[1] = std::move(Lo);
5594
5595 // A final check for overflow is needed because fastTwoSum can cause a
5596 // carry-out from Lo that pushes Hi to infinity.
5597 if (!getFirst().isFinite())
5598 return handleOverflow(RM);
5599
5600 // The largest DoubleAPFloat must be canonical. Values which are larger are
5601 // not canonical and are equivalent to overflow.
5602 if (getFirst().isFiniteNonZero() && Floats[0].isLargest()) {
5603 DoubleAPFloat Largest{*Semantics};
5604 Largest.makeLargest(/*Neg=*/false);
5605 if (compare(Largest) == APFloat::cmpGreaterThan)
5606 return handleOverflow(RM);
5607 }
5608
5609 // The final status of the operation is determined by the conversion of the
5610 // error term. If Lo could represent Error exactly, the entire conversion
5611 // is exact. Otherwise, it's inexact.
5612 return Status;
5613}
5614
5616 bool IsSigned,
5617 roundingMode RM) {
5618 const bool NegateInput = IsSigned && Input.isNegative();
5619 APInt API = Input;
5620 if (NegateInput)
5621 API.negate();
5622
5624 convertFromUnsignedParts(API.getRawData(), API.getNumWords(), RM);
5625 if (NegateInput)
5626 changeSign();
5627 return Status;
5628}
5629
5631 unsigned int HexDigits,
5632 bool UpperCase,
5633 roundingMode RM) const {
5634 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5635 "Unexpected Semantics");
5636 return APFloat(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt())
5637 .convertToHexString(DST, HexDigits, UpperCase, RM);
5638}
5639
5641 return getCategory() == fcNormal &&
5642 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
5643 // (double)(Hi + Lo) == Hi defines a normal number.
5644 Floats[0] != Floats[0] + Floats[1]);
5645}
5646
5648 if (getCategory() != fcNormal)
5649 return false;
5650 DoubleAPFloat Tmp(*this);
5651 Tmp.makeSmallest(this->isNegative());
5652 return Tmp.compare(*this) == cmpEqual;
5653}
5654
5656 if (getCategory() != fcNormal)
5657 return false;
5658
5659 DoubleAPFloat Tmp(*this);
5661 return Tmp.compare(*this) == cmpEqual;
5662}
5663
5665 if (getCategory() != fcNormal)
5666 return false;
5667 DoubleAPFloat Tmp(*this);
5668 Tmp.makeLargest(this->isNegative());
5669 return Tmp.compare(*this) == cmpEqual;
5670}
5671
5673 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5674 "Unexpected Semantics");
5675 return Floats[0].isInteger() && Floats[1].isInteger();
5676}
5677
5679 unsigned FormatPrecision,
5680 unsigned FormatMaxPadding,
5681 bool TruncateZero) const {
5682 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5683 "Unexpected Semantics");
5684 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt())
5685 .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
5686}
5687
5689 // In order for Hi + Lo to be a power of two, the following must be true:
5690 // 1. Hi must be a power of two.
5691 // 2. Lo must be zero.
5692 if (getSecond().isNonZero())
5693 return INT_MIN;
5694 return getFirst().getExactLog2Abs();
5695}
5696
5697int ilogb(const DoubleAPFloat &Arg) {
5698 const APFloat &Hi = Arg.getFirst();
5699 const APFloat &Lo = Arg.getSecond();
5700 int IlogbResult = ilogb(Hi);
5701 // Zero and non-finite values can delegate to ilogb(Hi).
5702 if (Arg.getCategory() != fcNormal)
5703 return IlogbResult;
5704 // If Lo can't change the binade, we can delegate to ilogb(Hi).
5705 if (Lo.isZero() || Hi.isNegative() == Lo.isNegative())
5706 return IlogbResult;
5707 if (Hi.getExactLog2Abs() == INT_MIN)
5708 return IlogbResult;
5709 // Numbers of the form 2^a - 2^b or -2^a + 2^b are almost powers of two but
5710 // get nudged out of the binade by the low component.
5711 return IlogbResult - 1;
5712}
5713
5716 assert(Arg.Semantics == &APFloatBase::PPCDoubleDouble() &&
5717 "Unexpected Semantics");
5719 scalbn(Arg.Floats[0], Exp, RM),
5720 scalbn(Arg.Floats[1], Exp, RM));
5721}
5722
5723DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
5725 assert(Arg.Semantics == &APFloatBase::PPCDoubleDouble() &&
5726 "Unexpected Semantics");
5727
5728 // Get the unbiased exponent e of the number, where |Arg| = m * 2^e for m in
5729 // [1.0, 2.0).
5730 Exp = ilogb(Arg);
5731
5732 // For NaNs, quiet any signaling NaN and return the result, as per standard
5733 // practice.
5734 if (Exp == APFloat::IEK_NaN) {
5735 DoubleAPFloat Quiet{Arg};
5736 Quiet.getFirst() = Quiet.getFirst().makeQuiet();
5737 return Quiet;
5738 }
5739
5740 // For infinity, return it unchanged. The exponent remains IEK_Inf.
5741 if (Exp == APFloat::IEK_Inf)
5742 return Arg;
5743
5744 // For zero, the fraction is zero and the standard requires the exponent be 0.
5745 if (Exp == APFloat::IEK_Zero) {
5746 Exp = 0;
5747 return Arg;
5748 }
5749
5750 const APFloat &Hi = Arg.getFirst();
5751 const APFloat &Lo = Arg.getSecond();
5752
5753 // frexp requires the fraction's absolute value to be in [0.5, 1.0).
5754 // ilogb provides an exponent for an absolute value in [1.0, 2.0).
5755 // Increment the exponent to ensure the fraction is in the correct range.
5756 ++Exp;
5757
5758 const bool SignsDisagree = Hi.isNegative() != Lo.isNegative();
5759 APFloat Second = Lo;
5760 if (Arg.getCategory() == APFloat::fcNormal && Lo.isFiniteNonZero()) {
5761 roundingMode LoRoundingMode;
5762 // The interpretation of rmTowardZero depends on the sign of the combined
5763 // Arg rather than the sign of the component.
5764 if (RM == rmTowardZero)
5765 LoRoundingMode = Arg.isNegative() ? rmTowardPositive : rmTowardNegative;
5766 // For rmNearestTiesToAway, we face a similar problem. If signs disagree,
5767 // Lo is a correction *toward* zero relative to Hi. Rounding Lo
5768 // "away from zero" based on its own sign would move the value in the
5769 // wrong direction. As a safe proxy, we use rmNearestTiesToEven, which is
5770 // direction-agnostic. We only need to bother with this if Lo is scaled
5771 // down.
5772 else if (RM == rmNearestTiesToAway && SignsDisagree && Exp > 0)
5773 LoRoundingMode = rmNearestTiesToEven;
5774 else
5775 LoRoundingMode = RM;
5776 Second = scalbn(Lo, -Exp, LoRoundingMode);
5777 // The rmNearestTiesToEven proxy is correct most of the time, but it
5778 // differs from rmNearestTiesToAway when the scaled value of Lo is an
5779 // exact midpoint.
5780 // NOTE: This is morally equivalent to roundTiesTowardZero.
5781 if (RM == rmNearestTiesToAway && LoRoundingMode == rmNearestTiesToEven) {
5782 // Re-scale the result back to check if rounding occurred.
5783 const APFloat RecomposedLo = scalbn(Second, Exp, rmNearestTiesToEven);
5784 if (RecomposedLo != Lo) {
5785 // RoundingError tells us which direction we rounded:
5786 // - RoundingError > 0: we rounded up.
5787 // - RoundingError < 0: we down up.
5788 const APFloat RoundingError = RecomposedLo - Lo;
5789 // Determine if scalbn(Lo, -Exp) landed exactly on a midpoint.
5790 // We do this by checking if the absolute rounding error is exactly
5791 // half a ULP of the result.
5792 const APFloat UlpOfSecond = harrisonUlp(Second);
5793 const APFloat ScaledUlpOfSecond =
5794 scalbn(UlpOfSecond, Exp - 1, rmNearestTiesToEven);
5795 const bool IsMidpoint = abs(RoundingError) == ScaledUlpOfSecond;
5796 const bool RoundedLoAway =
5797 Second.isNegative() == RoundingError.isNegative();
5798 // The sign of Hi and Lo disagree and we rounded Lo away: we must
5799 // decrease the magnitude of Second to increase the magnitude
5800 // First+Second.
5801 if (IsMidpoint && RoundedLoAway)
5802 Second.next(/*nextDown=*/!Second.isNegative());
5803 }
5804 }
5805 // Handle a tricky edge case where Arg is slightly less than a power of two
5806 // (e.g., Arg = 2^k - epsilon). In this situation:
5807 // 1. Hi is 2^k, and Lo is a small negative value -epsilon.
5808 // 2. ilogb(Arg) correctly returns k-1.
5809 // 3. Our initial Exp becomes (k-1) + 1 = k.
5810 // 4. Scaling Hi (2^k) by 2^-k would yield a magnitude of 1.0 and
5811 // scaling Lo by 2^-k would yield zero. This would make the result 1.0
5812 // which is an invalid fraction, as the required interval is [0.5, 1.0).
5813 // We detect this specific case by checking if Hi is a power of two and if
5814 // the scaled Lo underflowed to zero. The fix: Increment Exp to k+1. This
5815 // adjusts the scale factor, causing Hi to be scaled to 0.5, which is a
5816 // valid fraction.
5817 if (Second.isZero() && SignsDisagree && Hi.getExactLog2Abs() != INT_MIN)
5818 ++Exp;
5819 }
5820
5821 APFloat First = scalbn(Hi, -Exp, RM);
5823 std::move(Second));
5824}
5825
5826APInt DoubleAPFloat::getNaNPayload() const { return Floats[0].getNaNPayload(); }
5827} // namespace detail
5828
5829APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
5830 if (usesLayout<IEEEFloat>(Semantics)) {
5831 new (&IEEE) IEEEFloat(std::move(F));
5832 return;
5833 }
5834 if (usesLayout<DoubleAPFloat>(Semantics)) {
5835 const fltSemantics& S = F.getSemantics();
5836 new (&Double) DoubleAPFloat(Semantics, APFloat(std::move(F), S),
5838 return;
5839 }
5840 llvm_unreachable("Unexpected semantics");
5841}
5842
5847
5848hash_code hash_value(const APFloat &Arg) {
5849 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
5850 return hash_value(Arg.U.IEEE);
5851 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
5852 return hash_value(Arg.U.Double);
5853 llvm_unreachable("Unexpected semantics");
5854}
5855
5857 : APFloat(Semantics) {
5858 auto StatusOrErr = convertFromString(S, rmNearestTiesToEven);
5859 assert(StatusOrErr && "Invalid floating point representation");
5860 consumeError(StatusOrErr.takeError());
5861}
5862
5864 if (isZero())
5865 return isNegative() ? fcNegZero : fcPosZero;
5866 if (isNormal())
5867 return isNegative() ? fcNegNormal : fcPosNormal;
5868 if (isDenormal())
5870 if (isInfinity())
5871 return isNegative() ? fcNegInf : fcPosInf;
5872 assert(isNaN() && "Other class of FP constant");
5873 return isSignaling() ? fcSNan : fcQNan;
5874}
5875
5876bool APFloat::getExactInverse(APFloat *Inv) const {
5877 // Only finite, non-zero numbers can have a useful, representable inverse.
5878 // This check filters out +/- zero, +/- infinity, and NaN.
5879 if (!isFiniteNonZero())
5880 return false;
5881
5882 // Historically, this function rejects subnormal inputs. One reason why this
5883 // might be important is that subnormals may behave differently under FTZ/DAZ
5884 // runtime behavior.
5885 if (isDenormal())
5886 return false;
5887
5888 // A number has an exact, representable inverse if and only if it is a power
5889 // of two.
5890 //
5891 // Mathematical Rationale:
5892 // 1. A binary floating-point number x is a dyadic rational, meaning it can
5893 // be written as x = M / 2^k for integers M (the significand) and k.
5894 // 2. The inverse is 1/x = 2^k / M.
5895 // 3. For 1/x to also be a dyadic rational (and thus exactly representable
5896 // in binary), its denominator M must also be a power of two.
5897 // Let's say M = 2^m.
5898 // 4. Substituting this back into the formula for x, we get
5899 // x = (2^m) / (2^k) = 2^(m-k).
5900 //
5901 // This proves that x must be a power of two.
5902
5903 // getExactLog2Abs() returns the integer exponent if the number is a power of
5904 // two or INT_MIN if it is not.
5905 const int Exp = getExactLog2Abs();
5906 if (Exp == INT_MIN)
5907 return false;
5908
5909 // The inverse of +/- 2^Exp is +/- 2^(-Exp). We can compute this by
5910 // scaling 1.0 by the negated exponent.
5911 APFloat Reciprocal =
5912 scalbn(APFloat::getOne(getSemantics(), /*Negative=*/isNegative()), -Exp,
5913 rmTowardZero);
5914
5915 // scalbn might round if the resulting exponent -Exp is outside the
5916 // representable range, causing overflow (to infinity) or underflow. We
5917 // must verify that the result is still the exact power of two we expect.
5918 if (Reciprocal.getExactLog2Abs() != -Exp)
5919 return false;
5920
5921 // Avoid multiplication with a subnormal, it is not safe on all platforms and
5922 // may be slower than a normal division.
5923 if (Reciprocal.isDenormal())
5924 return false;
5925
5926 assert(Reciprocal.isFiniteNonZero());
5927
5928 if (Inv)
5929 *Inv = std::move(Reciprocal);
5930
5931 return true;
5932}
5933
5935 roundingMode RM, bool *losesInfo) {
5936 if (&getSemantics() == &ToSemantics) {
5937 *losesInfo = false;
5938 return opOK;
5939 }
5940 if (usesLayout<IEEEFloat>(getSemantics()) &&
5941 usesLayout<IEEEFloat>(ToSemantics))
5942 return U.IEEE.convert(ToSemantics, RM, losesInfo);
5943 if (usesLayout<IEEEFloat>(getSemantics()) &&
5944 usesLayout<DoubleAPFloat>(ToSemantics)) {
5945 assert(&ToSemantics == &APFloatBase::semPPCDoubleDouble);
5946 auto Ret =
5947 U.IEEE.convert(APFloatBase::semPPCDoubleDoubleLegacy, RM, losesInfo);
5948 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
5949 return Ret;
5950 }
5951 if (usesLayout<DoubleAPFloat>(getSemantics()) &&
5952 usesLayout<IEEEFloat>(ToSemantics)) {
5953 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
5954 *this = APFloat(std::move(getIEEE()), ToSemantics);
5955 return Ret;
5956 }
5957 llvm_unreachable("Unexpected semantics");
5958}
5959
5963
5965 SmallVector<char, 16> Buffer;
5966 toString(Buffer);
5967 OS << Buffer;
5968}
5969
5970#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5972 print(dbgs());
5973 dbgs() << '\n';
5974}
5975#endif
5976
5978 NID.Add(bitcastToAPInt());
5979}
5980
5982 roundingMode rounding_mode,
5983 bool *isExact) const {
5984 unsigned bitWidth = result.getBitWidth();
5985 SmallVector<uint64_t, 4> parts(result.getNumWords());
5986 opStatus status = convertToInteger(parts, bitWidth, result.isSigned(),
5987 rounding_mode, isExact);
5988 // Keeps the original signed-ness.
5989 result = APInt(bitWidth, parts);
5990 return status;
5991}
5992
5994 if (&getSemantics() == &APFloatBase::semIEEEdouble)
5995 return getIEEE().convertToDouble();
5996 assert(isRepresentableBy(getSemantics(), semIEEEdouble) &&
5997 "Float semantics is not representable by IEEEdouble");
5998 APFloat Temp = *this;
5999 bool LosesInfo;
6000 [[maybe_unused]] opStatus St =
6001 Temp.convert(APFloatBase::semIEEEdouble, rmNearestTiesToEven, &LosesInfo);
6002 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
6003 return Temp.getIEEE().convertToDouble();
6004}
6005
6006#ifdef HAS_IEE754_FLOAT128
6007float128 APFloat::convertToQuad() const {
6008 if (&getSemantics() == &APFloatBase::semIEEEquad)
6009 return getIEEE().convertToQuad();
6010 assert(isRepresentableBy(getSemantics(), semIEEEquad) &&
6011 "Float semantics is not representable by IEEEquad");
6012 APFloat Temp = *this;
6013 bool LosesInfo;
6014 [[maybe_unused]] opStatus St =
6015 Temp.convert(APFloatBase::semIEEEquad, rmNearestTiesToEven, &LosesInfo);
6016 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
6017 return Temp.getIEEE().convertToQuad();
6018}
6019#endif
6020
6022 if (&getSemantics() == &APFloatBase::semIEEEsingle)
6023 return getIEEE().convertToFloat();
6024 assert(isRepresentableBy(getSemantics(), semIEEEsingle) &&
6025 "Float semantics is not representable by IEEEsingle");
6026 APFloat Temp = *this;
6027 bool LosesInfo;
6028 [[maybe_unused]] opStatus St =
6029 Temp.convert(APFloatBase::semIEEEsingle, rmNearestTiesToEven, &LosesInfo);
6030 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
6031 return Temp.getIEEE().convertToFloat();
6032}
6033
6036 .Case("Float8E5M2", getSizeInBits(semFloat8E5M2))
6037 .Case("Float8E5M2FNUZ", getSizeInBits(semFloat8E5M2FNUZ))
6038 .Case("Float8E4M3", getSizeInBits(semFloat8E4M3))
6039 .Case("Float8E4M3FN", getSizeInBits(semFloat8E4M3FN))
6040 .Case("Float8E4M3FNUZ", getSizeInBits(semFloat8E4M3FNUZ))
6041 .Case("Float8E4M3B11FNUZ", getSizeInBits(semFloat8E4M3B11FNUZ))
6042 .Case("Float8E3M4", getSizeInBits(semFloat8E3M4))
6043 .Case("Float8E8M0FNU", getSizeInBits(semFloat8E8M0FNU))
6044 .Case("Float6E3M2FN", getSizeInBits(semFloat6E3M2FN))
6045 .Case("Float6E2M3FN", getSizeInBits(semFloat6E2M3FN))
6046 .Case("Float4E2M1FN", getSizeInBits(semFloat4E2M1FN))
6047 .Case("Float8E5M3FNU", getSizeInBits(semFloat8E5M3FNU))
6048 .Default(0);
6049}
6050
6054
6056 // TODO: extend to remaining arbitrary FP types: Float8E4M3, Float8E3M4,
6057 // Float8E5M2FNUZ, Float8E4M3FNUZ, Float8E4M3B11FNUZ, Float8E8M0FNU,
6058 // Float8E5M3FNU.
6060 .Case("Float8E5M2", &semFloat8E5M2)
6061 .Case("Float8E4M3FN", &semFloat8E4M3FN)
6062 .Case("Float4E2M1FN", &semFloat4E2M1FN)
6063 .Case("Float6E3M2FN", &semFloat6E3M2FN)
6064 .Case("Float6E2M3FN", &semFloat6E2M3FN)
6065 .Default(nullptr);
6066}
6067
6068APFloat::Storage::~Storage() {
6069 if (usesLayout<IEEEFloat>(*semantics)) {
6070 IEEE.~IEEEFloat();
6071 return;
6072 }
6073 if (usesLayout<DoubleAPFloat>(*semantics)) {
6074 Double.~DoubleAPFloat();
6075 return;
6076 }
6077 llvm_unreachable("Unexpected semantics");
6078}
6079
6080APFloat::Storage::Storage(const APFloat::Storage &RHS) {
6081 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
6082 new (this) IEEEFloat(RHS.IEEE);
6083 return;
6084 }
6085 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6086 new (this) DoubleAPFloat(RHS.Double);
6087 return;
6088 }
6089 llvm_unreachable("Unexpected semantics");
6090}
6091
6092APFloat::Storage::Storage(APFloat::Storage &&RHS) {
6093 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
6094 new (this) IEEEFloat(std::move(RHS.IEEE));
6095 return;
6096 }
6097 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6098 new (this) DoubleAPFloat(std::move(RHS.Double));
6099 return;
6100 }
6101 llvm_unreachable("Unexpected semantics");
6102}
6103
6104APFloat::Storage &APFloat::Storage::operator=(const APFloat::Storage &RHS) {
6105 if (usesLayout<IEEEFloat>(*semantics) &&
6106 usesLayout<IEEEFloat>(*RHS.semantics)) {
6107 IEEE = RHS.IEEE;
6108 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
6109 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6110 Double = RHS.Double;
6111 } else if (this != &RHS) {
6112 this->~Storage();
6113 new (this) Storage(RHS);
6114 }
6115 return *this;
6116}
6117
6118APFloat::Storage &APFloat::Storage::operator=(APFloat::Storage &&RHS) {
6119 if (usesLayout<IEEEFloat>(*semantics) &&
6120 usesLayout<IEEEFloat>(*RHS.semantics)) {
6121 IEEE = std::move(RHS.IEEE);
6122 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
6123 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6124 Double = std::move(RHS.Double);
6125 } else if (this != &RHS) {
6126 this->~Storage();
6127 new (this) Storage(std::move(RHS));
6128 }
6129 return *this;
6130}
6131
6132namespace {
6133
6134APFloat::opStatus getOpStatusFromLibc(int libc_exceptions) {
6136 if (libc_exceptions & FE_INVALID)
6138 if (libc_exceptions & FE_DIVBYZERO)
6140 if (libc_exceptions & FE_OVERFLOW)
6142 if (libc_exceptions & FE_UNDERFLOW)
6144 if (libc_exceptions & FE_INEXACT)
6146 return status;
6147}
6148
6149} // namespace
6150
6151// TODO: Support other rounding modes when LLVM libc math implement static
6152// roundings.
6153std::optional<APFloat> exp(const APFloat &x, RoundingMode rounding_mode,
6154 APFloat::opStatus *status) {
6155
6156 if (rounding_mode == APFloatBase::rmNearestTiesToEven) {
6157 if (APFloat::SemanticsToEnum(x.getSemantics()) ==
6159 float x_val = x.convertToFloat();
6160 int exc =
6161 LIBC_NAMESPACE::shared::check::exp_exceptions(x_val, FE_TONEAREST);
6162 if (status) {
6163 *status = getOpStatusFromLibc(exc);
6164 if (x.isSignaling()) {
6165 // 32-bit x86 will silence sNaN when loading floats, so we explicitly
6166 // add the INVALID exception here.
6167 *status =
6168 static_cast<APFloat::opStatus>(*status | APFloat::opInvalidOp);
6169 }
6170 }
6171 float result = LIBC_NAMESPACE::shared::expf(x_val);
6172 return APFloat(result);
6173 }
6174 if (APFloat::SemanticsToEnum(x.getSemantics()) ==
6176 double x_val = x.convertToDouble();
6177 int exc =
6178 LIBC_NAMESPACE::shared::check::exp_exceptions(x_val, FE_TONEAREST);
6179 if (status) {
6180 *status = getOpStatusFromLibc(exc);
6181 if (x.isSignaling()) {
6182 // 32-bit x86 will silence sNaN when loading floats, so we explicitly
6183 // add the INVALID exception here.
6184 *status =
6185 static_cast<APFloat::opStatus>(*status | APFloat::opInvalidOp);
6186 }
6187 }
6188 double result = LIBC_NAMESPACE::shared::exp(x_val);
6189 return APFloat(result);
6190 }
6191 }
6192 return std::nullopt;
6193}
6194
6195} // namespace llvm
6196
6197#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:6051
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:6034
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:6055
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:5977
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:5934
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:5876
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:5993
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:5960
LLVM_ABI friend hash_code hash_value(const APFloat &Arg)
See friend declarations above.
Definition APFloat.cpp:5848
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:6021
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:5863
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:5843
friend IEEEFloat
Definition APFloat.h:1662
LLVM_DUMP_METHOD void dump() const
Definition APFloat.cpp:5971
LLVM_ABI void print(raw_ostream &) const
Definition APFloat.cpp:5964
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:5190
LLVM_ABI DoubleAPFloat & operator=(const DoubleAPFloat &RHS)
Definition APFloat.cpp:4720
LLVM_ABI void changeSign()
Definition APFloat.cpp:5097
LLVM_ABI bool isLargest() const
Definition APFloat.cpp:5664
LLVM_ABI opStatus remainder(const DoubleAPFloat &RHS)
Definition APFloat.cpp:4984
LLVM_ABI opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4887
LLVM_ABI fltCategory getCategory() const
Definition APFloat.cpp:5156
LLVM_ABI bool bitwiseIsEqual(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5213
LLVM_ABI LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.cpp:5688
LLVM_ABI opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.cpp:5615
LLVM_ABI APInt bitcastToAPInt() const
Definition APFloat.cpp:5224
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
Definition APFloat.cpp:5234
LLVM_ABI bool isSmallest() const
Definition APFloat.cpp:5647
LLVM_ABI opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4879
LLVM_ABI friend hash_code hash_value(const DoubleAPFloat &Arg)
Definition APFloat.cpp:5218
LLVM_ABI cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5103
LLVM_ABI bool isDenormal() const
Definition APFloat.cpp:5640
LLVM_ABI opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.cpp:5451
LLVM_ABI void makeSmallest(bool Neg)
Definition APFloat.cpp:5183
LLVM_ABI friend int ilogb(const DoubleAPFloat &X)
Definition APFloat.cpp:5697
LLVM_ABI opStatus next(bool nextDown)
Definition APFloat.cpp:5250
LLVM_ABI void makeInf(bool Neg)
Definition APFloat.cpp:5162
LLVM_ABI bool isInteger() const
Definition APFloat.cpp:5672
LLVM_ABI void makeZero(bool Neg)
Definition APFloat.cpp:5167
LLVM_ABI opStatus divide(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4973
LLVM_ABI bool isSmallestNormalized() const
Definition APFloat.cpp:5655
LLVM_ABI opStatus mod(const DoubleAPFloat &RHS)
Definition APFloat.cpp:4994
LLVM_ABI DoubleAPFloat(const fltSemantics &S)
Definition APFloat.cpp:4667
LLVM_ABI void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision, unsigned FormatMaxPadding, bool TruncateZero=true) const
Definition APFloat.cpp:5678
LLVM_ABI void makeLargest(bool Neg)
Definition APFloat.cpp:5172
LLVM_ABI cmpResult compare(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5205
LLVM_ABI friend DoubleAPFloat scalbn(const DoubleAPFloat &X, int Exp, roundingMode)
LLVM_ABI opStatus roundToIntegral(roundingMode RM)
Definition APFloat.cpp:5020
LLVM_ABI opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, const DoubleAPFloat &Addend, roundingMode RM)
Definition APFloat.cpp:5005
LLVM_ABI APInt getNaNPayload() const
Definition APFloat.cpp:5826
LLVM_ABI unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
Definition APFloat.cpp:5630
LLVM_ABI bool isNegative() const
Definition APFloat.cpp:5160
LLVM_ABI opStatus add(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4874
LLVM_ABI void makeNaN(bool SNaN, bool Neg, const APInt *fill)
Definition APFloat.cpp:5200
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:3221
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:2781
LLVM_ABI APInt getNaNPayload() const
Definition APFloat.cpp:4555
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:3982
LLVM_ABI LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.cpp:4377
LLVM_ABI APInt bitcastToAPInt() const
Definition APFloat.cpp:3602
LLVM_ABI friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Definition APFloat.cpp:4627
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:3675
LLVM_ABI float convertToFloat() const
Definition APFloat.cpp:3668
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:4333
LLVM_ABI void makeSmallest(bool Neg=false)
Make this number the smallest magnitude denormal number in the given semantics.
Definition APFloat.cpp:4014
LLVM_ABI void makeInf(bool Neg=false)
Definition APFloat.cpp:4574
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:4603
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:3164
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:4028
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:4609
LLVM_ABI opStatus next(bool nextDown)
IEEE-754R 5.3.1: nextUp/nextDown.
Definition APFloat.cpp:4422
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:4406
LLVM_ABI void makeZero(bool Neg=false)
Definition APFloat.cpp:4589
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:2726
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:3361
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:4648
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:4609
static constexpr cmpResult cmpEqual
Definition APFloat.h:454
LLVM_ABI IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Definition APFloat.cpp:4627
static std::pair< APFloat, APFloat > fastTwoSum(APFloat X, APFloat Y)
Definition APFloat.cpp:4737
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:6153
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