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