26#include "llvm/Config/llvm-config.h"
43#define LIBC_NAMESPACE __llvm_libc_apfloat
44#define LIBC_MATH (LIBC_MATH_NO_ERRNO | LIBC_MATH_NO_EXCEPT)
46#include "shared/math.h"
47#include "shared/math_check_exceptions.h"
49#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
51 if (usesLayout<IEEEFloat>(getSemantics())) \
52 return U.IEEE.METHOD_CALL; \
53 if (usesLayout<DoubleAPFloat>(getSemantics())) \
54 return U.Double.METHOD_CALL; \
55 llvm_unreachable("Unexpected semantics"); \
93 const IEEEFloat &f{IEEEFloat::fromRepr(R)};
94 assert(f.partCount() == IEEEFloat::partCountForSemantic(E));
95 return f.convertIEEEFloatToAPInt<E>();
98template <APFloatBase::Semantics E>
100 IEEEFloat::fromRepr(R).initFromIEEEAPInt<E>(api);
174constexpr fltSemantics APFloatBase::semX87DoubleExtended = {
188constexpr fltSemantics APFloatBase::semPPCDoubleDouble = {
202constexpr fltSemantics APFloatBase::semPPCDoubleDoubleLegacy = {
230constexpr fltSemantics APFloatBase::semFloat8E5M2FNUZ = {
272constexpr fltSemantics APFloatBase::semFloat8E4M3FNUZ = {
286constexpr fltSemantics APFloatBase::semFloat8E4M3B11FNUZ = {
400constexpr fltSemantics APFloatBase::semBogus = {0, 0, 0, 0};
454 assert(&Sem != &semBogus);
508 return A.maxExponent <=
B.maxExponent &&
A.minExponent >=
B.minExponent &&
509 A.precision <=
B.precision;
515 if (&From == &InitialTo)
521 if (&From == &semPPCDoubleDouble)
528 &InitialTo == &semPPCDoubleDouble ? semIEEEdouble : InitialTo;
543 if (FromHasSignedZero && !ToHasSignedZero)
550 bool LosesInfo =
false;
662 if (Src.maxExponent >= Dst.maxExponent || Src.minExponent <= Dst.minExponent)
670 return Dst.precision >= Src.precision;
710static inline unsigned int
723 const unsigned int overlargeExponent = 24000;
727 if (p == end || ((*p ==
'-' || *p ==
'+') && (p + 1) == end))
730 bool isNegative = *p ==
'-';
731 if (*p ==
'-' || *p ==
'+') {
738 if (absExponent >= 10U)
739 return createError(
"Invalid character in exponent");
741 for (; p != end; ++p) {
744 return createError(
"Invalid character in exponent");
746 absExponent = absExponent * 10U + value;
747 if (absExponent >= overlargeExponent) {
748 absExponent = overlargeExponent;
754 return -(int) absExponent;
756 return (
int) absExponent;
763 int exponentAdjustment) {
769 bool negative = *p ==
'-';
770 if (*p ==
'-' || *p ==
'+') {
776 int unsignedExponent = 0;
777 bool overflow =
false;
778 for (; p != end; ++p) {
783 return createError(
"Invalid character in exponent");
785 unsignedExponent = unsignedExponent * 10 + value;
786 if (unsignedExponent > 32767) {
792 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
796 exponent = unsignedExponent;
798 exponent = -exponent;
799 exponent += exponentAdjustment;
800 if (exponent > 32767 || exponent < -32768)
805 exponent = negative ? -32768: 32767;
815 while (p != end && *p ==
'0')
818 if (p != end && *p ==
'.') {
821 if (end - begin == 1)
824 while (p != end && *p ==
'0')
857 return PtrOrErr.takeError();
860 D->firstSigDigit = p;
862 D->normalizedExponent = 0;
864 for (; p != end; ++p) {
867 return createError(
"String contains multiple dots");
877 if (*p !=
'e' && *p !=
'E')
878 return createError(
"Invalid character in significand");
881 if (dot != end && p - begin == 1)
887 return ExpOrErr.takeError();
888 D->exponent = *ExpOrErr;
896 if (p !=
D->firstSigDigit) {
902 while (p != begin && *p ==
'0');
903 while (p != begin && *p ==
'.');
908 D->normalizedExponent = (
D->exponent +
910 - (dot >
D->firstSigDigit && dot < p)));
922 unsigned int digitValue) {
927 else if (digitValue < 8 && digitValue > 0)
931 while (p != end && (*p ==
'0' || *p ==
'.'))
935 return createError(
"Invalid trailing hexadecimal fraction!");
941 if (hexDigit == UINT_MAX)
951 unsigned int partCount,
976 return lost_fraction;
991 return moreSignificant;
1002HUerrBound(
bool inexactMultiply,
unsigned int HUerr1,
unsigned int HUerr2)
1004 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
1006 if (HUerr1 + HUerr2 == 0)
1007 return inexactMultiply * 2;
1009 return inexactMultiply + 2 * (HUerr1 + HUerr2);
1035 if (part - boundary <= boundary - part)
1036 return part - boundary;
1038 return boundary - part;
1041 if (part == boundary) {
1047 }
else if (part == boundary - 1) {
1059 19, 38, 75, 149, 298};
1077 1, 5, 25, 125, 625, 3125, 15625, 78125};
1086 p2 = scratch.
data();
1088 *p1 = firstEightPowers[power & 7];
1091 unsigned result = 1;
1094 for (
unsigned int n = 0; power; power >>= 1, n++) {
1101 result += partsCount;
1102 if (p2[result - 1] == 0)
1135 const char *hexDigitChars)
1137 unsigned int result =
count;
1143 dst[
count] = hexDigitChars[part & 0xf];
1156 *p++ =
'0' + n % 10;
1183 switch (
X.getCategory()) {
1193 if (
X.isDenormal() ||
X.isSmallestNormalized())
1196 if (
X.getExactLog2() != INT_MIN)
1204void IEEEFloat::initialize(
const fltSemantics *ourSemantics) {
1205 semantics = ourSemantics;
1206 unsigned count = partCount();
1211void IEEEFloat::freeSignificand() {
1213 delete [] significand.parts;
1216void IEEEFloat::assign(
const IEEEFloat &rhs) {
1217 assert(semantics == rhs.semantics);
1220 category = rhs.category;
1221 exponent = rhs.exponent;
1223 copySignificand(rhs);
1226void IEEEFloat::copySignificand(
const IEEEFloat &rhs) {
1228 assert(rhs.partCount() >= partCount());
1241 if (Negative && !semantics->hasSignedRepr)
1243 "This floating point format does not support signed values");
1247 exponent = exponentNaN();
1250 unsigned numParts = partCount();
1263 fill = &fill_storage;
1267 if (!
fill ||
fill->getNumWords() < numParts)
1271 std::min(
fill->getNumWords(), numParts));
1274 unsigned bitsToPreserve = semantics->precision - 1;
1275 unsigned part = bitsToPreserve / 64;
1276 bitsToPreserve %= 64;
1277 significand[part] &= ((1ULL << bitsToPreserve) - 1);
1278 for (part++; part != numParts; ++part)
1279 significand[part] = 0;
1283 (semantics->precision >= 2) ? (semantics->precision - 2) : 0;
1305 if (semantics == &APFloatBase::semX87DoubleExtended)
1311 if (semantics != rhs.semantics) {
1313 initialize(rhs.semantics);
1324 semantics = rhs.semantics;
1325 significand = rhs.significand;
1326 exponent = rhs.exponent;
1327 category = rhs.category;
1330 rhs.semantics = &APFloatBase::semBogus;
1336 (exponent == semantics->minExponent) &&
1346 significandMSB() == 0;
1351 isSignificandAllZerosExceptMSB();
1354unsigned int IEEEFloat::getNumHighBits()
const {
1361 const unsigned int NumHighBits = (semantics->
precision > 1)
1367bool IEEEFloat::isSignificandAllOnes()
const {
1372 for (
unsigned i = 0; i < PartCount - 1; i++)
1377 const unsigned NumHighBits = getNumHighBits();
1378 assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1379 "Can not have more high bits to fill than integerPartWidth");
1382 if ((semantics->
precision <= 1) || (~(Parts[PartCount - 1] | HighBitFill)))
1388bool IEEEFloat::isSignificandAllOnesExceptLSB()
const {
1397 for (
unsigned i = 0; i < PartCount - 1; i++) {
1398 if (~Parts[i] & ~
unsigned{!i})
1403 const unsigned NumHighBits = getNumHighBits();
1404 assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1405 "Can not have more high bits to fill than integerPartWidth");
1408 if (~(Parts[PartCount - 1] | HighBitFill | 0x1))
1414bool IEEEFloat::isSignificandAllZeros()
const {
1420 for (
unsigned i = 0; i < PartCount - 1; i++)
1425 const unsigned NumHighBits = getNumHighBits();
1427 "clear than integerPartWidth");
1428 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
1430 if ((semantics->precision > 1) && (Parts[PartCount - 1] & HighBitMask))
1436bool IEEEFloat::isSignificandAllZerosExceptMSB()
const {
1440 for (
unsigned i = 0; i < PartCount - 1; i++) {
1445 const unsigned NumHighBits = getNumHighBits();
1448 return ((semantics->precision <= 1) || (Parts[PartCount - 1] == MSBMask));
1452 bool IsMaxExp =
isFiniteNonZero() && exponent == semantics->maxExponent;
1459 ? isSignificandAllOnesExceptLSB()
1464 return IsMaxExp && isSignificandAllOnes();
1479 if (semantics != rhs.semantics ||
1480 category != rhs.category ||
1489 return std::equal(significandParts(), significandParts() + partCount(),
1490 rhs.significandParts());
1494 initialize(&ourSemantics);
1499 significandParts()[0] =
value;
1504 initialize(&ourSemantics);
1520 initialize(rhs.semantics);
1525 *
this = std::move(rhs);
1530unsigned int IEEEFloat::partCount()
const {
1535 return const_cast<IEEEFloat *
>(
this)->significandParts();
1539 if (partCount() > 1)
1540 return significand.parts;
1542 return &significand.part;
1545void IEEEFloat::zeroSignificand() {
1550void IEEEFloat::incrementSignificand() {
1562 assert(semantics == rhs.semantics);
1563 assert(exponent == rhs.exponent);
1565 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
1574 assert(semantics == rhs.semantics);
1575 assert(exponent == rhs.exponent);
1586 bool ignoreAddend) {
1590 assert(semantics == rhs.semantics);
1592 unsigned precision = semantics->precision;
1600 newPartsCount > 4 ?
new integerPart[newPartsCount] : scratch;
1603 unsigned partsCount = partCount();
1606 rhs.significandParts(), partsCount, partsCount);
1610 unsigned omsb =
APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1611 exponent += rhs.exponent;
1625 if (!ignoreAddend && addend.isNonZero()) {
1629 Significand savedSignificand = significand;
1630 const fltSemantics *savedSemantics = semantics;
1633 unsigned extendedPrecision = 2 * precision + 1;
1634 if (omsb != extendedPrecision - 1) {
1635 assert(extendedPrecision > omsb);
1637 (extendedPrecision - 1) - omsb);
1638 exponent -= (extendedPrecision - 1) - omsb;
1642 fltSemantics extendedSemantics = *semantics;
1643 extendedSemantics.
precision = extendedPrecision;
1645 if (newPartsCount == 1)
1646 significand.part = fullSignificand[0];
1648 significand.parts = fullSignificand;
1649 semantics = &extendedSemantics;
1662 lost_fraction = extendedAddend.shiftSignificandRight(1);
1664 "Lost precision while shifting addend for fused-multiply-add.");
1666 lost_fraction = addOrSubtractSignificand(extendedAddend,
false);
1669 if (newPartsCount == 1)
1670 fullSignificand[0] = significand.part;
1671 significand = savedSignificand;
1672 semantics = savedSemantics;
1674 omsb =
APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1681 exponent -= precision + 1;
1690 if (omsb > precision) {
1691 unsigned int bits, significantParts;
1694 bits = omsb - precision;
1696 lf =
shiftRight(fullSignificand, significantParts, bits);
1703 if (newPartsCount > 4)
1704 delete [] fullSignificand;
1706 return lost_fraction;
1715 return multiplySignificand(rhs,
IEEEFloat(*semantics), !semantics->hasZero);
1722 assert(semantics == rhs.semantics);
1725 const integerPart *rhsSignificand = rhs.significandParts();
1726 unsigned partsCount = partCount();
1729 partsCount > 2 ?
new integerPart[partsCount * 2] : scratch;
1733 for (
unsigned i = 0; i < partsCount; i++) {
1734 dividend[i] = lhsSignificand[i];
1735 divisor[i] = rhsSignificand[i];
1736 lhsSignificand[i] = 0;
1739 exponent -= rhs.exponent;
1741 unsigned int precision = semantics->precision;
1744 unsigned bit = precision -
APInt::tcMSB(divisor, partsCount) - 1;
1751 bit = precision -
APInt::tcMSB(dividend, partsCount) - 1;
1767 for (bit = precision; bit; bit -= 1) {
1792 return lost_fraction;
1795unsigned int IEEEFloat::significandMSB()
const {
1799unsigned int IEEEFloat::significandLSB()
const {
1804lostFraction IEEEFloat::shiftSignificandRight(
unsigned int bits) {
1810 return shiftRight(significandParts(), partCount(), bits);
1814void IEEEFloat::shiftSignificandLeft(
unsigned int bits) {
1815 assert(bits < semantics->precision ||
1816 (semantics->precision == 1 && bits <= 1));
1819 unsigned int partsCount = partCount();
1829 assert(semantics == rhs.semantics);
1833 int compare = exponent - rhs.exponent;
1885 exponent = semantics->maxExponent;
1887 semantics->precision);
1900bool IEEEFloat::roundAwayFromZero(
roundingMode rounding_mode,
1902 unsigned int bit)
const {
1909 switch (rounding_mode) {
1945 unsigned omsb = significandMSB() + 1;
1952 int exponentChange = omsb - semantics->precision;
1956 if (exponent + exponentChange > semantics->maxExponent)
1957 return handleOverflow(rounding_mode);
1961 if (exponent + exponentChange < semantics->minExponent)
1962 exponentChange = semantics->minExponent - exponent;
1965 if (exponentChange < 0) {
1968 shiftSignificandLeft(-exponentChange);
1973 if (exponentChange > 0) {
1977 lf = shiftSignificandRight(exponentChange);
1982 if (omsb > (
unsigned) exponentChange)
1983 omsb -= exponentChange;
1993 exponent == semantics->maxExponent && isSignificandAllOnes())
1994 return handleOverflow(rounding_mode);
2007 if (!semantics->hasZero)
2015 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
2017 exponent = semantics->minExponent;
2019 incrementSignificand();
2020 omsb = significandMSB() + 1;
2023 if (omsb == (
unsigned) semantics->precision + 1) {
2027 if (exponent == semantics->maxExponent)
2034 shiftSignificandRight(1);
2043 exponent == semantics->maxExponent && isSignificandAllOnes())
2044 return handleOverflow(rounding_mode);
2049 if (omsb == semantics->precision)
2053 assert(omsb < semantics->precision);
2063 if (!semantics->hasZero)
2135 subtract ^=
static_cast<bool>(sign ^ rhs.sign);
2138 int bits = exponent - rhs.exponent;
2142 if ((bits < 0) && !semantics->hasSignedRepr)
2144 "This floating point format does not support signed values");
2147 bool lost_fraction_is_from_rhs =
false;
2151 else if (bits > 0) {
2152 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
2153 lost_fraction_is_from_rhs =
true;
2154 shiftSignificandLeft(1);
2156 lost_fraction = shiftSignificandRight(-bits - 1);
2157 temp_rhs.shiftSignificandLeft(1);
2164 lost_fraction !=
lfExactlyZero && !lost_fraction_is_from_rhs;
2173 carry = temp_rhs.subtractSignificand(*
this, borrow);
2174 copySignificand(temp_rhs);
2177 bool borrow = lost_fraction !=
lfExactlyZero && lost_fraction_is_from_rhs;
2186 carry = subtractSignificand(temp_rhs, borrow);
2189 if (lost_fraction !=
lfExactlyZero && lost_fraction_is_from_rhs) {
2202 lost_fraction = temp_rhs.shiftSignificandRight(bits);
2203 carry = addSignificand(temp_rhs);
2205 lost_fraction = shiftSignificandRight(-bits);
2206 carry = addSignificand(rhs);
2213 return lost_fraction;
2406 lost_fraction = addOrSubtractSignificand(rhs,
subtract);
2407 fs = normalize(rounding_mode, lost_fraction);
2416 if (category ==
fcZero) {
2430 return addOrSubtract(rhs, rounding_mode,
false);
2436 return addOrSubtract(rhs, rounding_mode,
true);
2449 fs = normalize(rounding_mode, lost_fraction);
2467 fs = normalize(rounding_mode, lost_fraction);
2477 unsigned int origSign = sign;
2586 unsigned int origSign = sign;
2607 if (!semantics->hasZero && this->isSmallest())
2627 sign ^= multiplicand.sign;
2636 lost_fraction = multiplySignificand(multiplicand, addend);
2637 fs = normalize(rounding_mode, lost_fraction);
2650 fs = multiplySpecials(multiplicand);
2660 fs = addOrSubtract(addend, rounding_mode,
false);
2732 MagicConstant.sign = sign;
2738 fs =
add(MagicConstant, rounding_mode);
2742 subtract(MagicConstant, rounding_mode);
2753 assert(semantics == rhs.semantics);
2785 if (sign == rhs.sign)
2801 if (sign != rhs.sign) {
2837 unsigned oldPartCount = partCount();
2840 bool X86SpecialNan =
false;
2841 if (&fromSemantics == &APFloatBase::semX87DoubleExtended &&
2842 &toSemantics != &APFloatBase::semX87DoubleExtended && category ==
fcNaN &&
2843 (!(*significandParts() & 0x8000000000000000ULL) ||
2844 !(*significandParts() & 0x4000000000000000ULL))) {
2847 X86SpecialNan =
true;
2858 int omsb = significandMSB() + 1;
2859 int exponentChange = omsb - fromSemantics.
precision;
2860 if (exponent + exponentChange < toSemantics.
minExponent)
2861 exponentChange = toSemantics.
minExponent - exponent;
2862 exponentChange = std::max(exponentChange, shift);
2863 if (exponentChange < 0) {
2864 shift -= exponentChange;
2865 exponent += exponentChange;
2866 }
else if (omsb <= -shift) {
2867 exponentChange = omsb + shift - 1;
2868 shift -= exponentChange;
2869 exponent += exponentChange;
2875 (category ==
fcNaN && semantics->nonFiniteBehavior !=
2880 if (newPartCount > oldPartCount) {
2888 significand.parts = newParts;
2889 }
else if (newPartCount == 1 && oldPartCount != 1) {
2893 newPart = significandParts()[0];
2895 significand.part = newPart;
2899 semantics = &toSemantics;
2908 *losesInfo = (
fs !=
opOK);
2909 }
else if (category ==
fcNaN) {
2932 if (!X86SpecialNan && semantics == &APFloatBase::semX87DoubleExtended)
2950 }
else if (category ==
fcZero &&
2967 if ((sign && !semantics->hasSignedRepr) ||
2968 (category ==
fcZero && !semantics->hasZero)) {
2974 if (category ==
fcZero && !semantics->hasZero)
2999 assert(dstPartsCount <= parts.
size() &&
"Integer too big");
3001 if (category ==
fcZero) {
3010 unsigned truncatedBits;
3018 truncatedBits = semantics->
precision -1U - exponent;
3022 unsigned int bits = exponent + 1U;
3028 if (bits < semantics->precision) {
3030 truncatedBits = semantics->
precision - bits;
3037 bits - semantics->precision);
3045 if (truncatedBits) {
3049 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
3069 if (omsb == width &&
3105 rounding_mode, isExact);
3108 unsigned int bits, dstPartsCount;
3111 assert(dstPartsCount <= parts.
size() &&
"Integer too big");
3113 if (category ==
fcNaN)
3136 unsigned dstCount = partCount();
3137 unsigned precision = semantics->
precision;
3142 if (precision <= omsb) {
3143 exponent = omsb - 1;
3148 exponent = precision - 1;
3153 return normalize(rounding_mode, lost_fraction);
3167 return convertFromUnsignedParts(api.
getRawData(), partCount, rounding_mode);
3171IEEEFloat::convertFromHexadecimalString(
StringRef s,
3180 unsigned partsCount = partCount();
3182 bool computedTrailingFraction =
false;
3190 return PtrOrErr.takeError();
3199 return createError(
"String contains multiple dots");
3205 if (hex_value == UINT_MAX)
3215 }
else if (!computedTrailingFraction) {
3218 return FractOrErr.takeError();
3219 lost_fraction = *FractOrErr;
3220 computedTrailingFraction =
true;
3226 return createError(
"Hex strings require an exponent");
3227 if (*p !=
'p' && *p !=
'P')
3228 return createError(
"Invalid character in significand");
3231 if (dot != end && p - begin == 1)
3235 if (p != firstSignificantDigit) {
3244 expAdjustment =
static_cast<int>(
dot - firstSignificantDigit);
3245 if (expAdjustment < 0)
3247 expAdjustment = expAdjustment * 4 - 1;
3251 expAdjustment += semantics->precision;
3257 return ExpOrErr.takeError();
3258 exponent = *ExpOrErr;
3261 return normalize(rounding_mode, lost_fraction);
3265IEEEFloat::roundSignificandWithExponent(
const integerPart *decSigParts,
3266 unsigned sigPartCount,
int exp,
3268 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
3269 unsigned int power =
exp >= 0 ?
exp : -
exp;
3280 unsigned pow5PartCount =
powerOf5(pow5Parts.
data(), power);
3282 for (;; parts *= 2) {
3283 unsigned int excessPrecision, truncatedBits;
3286 excessPrecision = calcSemantics.
precision - semantics->precision;
3287 truncatedBits = excessPrecision;
3290 decSig.makeZero(sign);
3293 opStatus sigStatus = decSig.convertFromUnsignedParts(
3295 opStatus powStatus = pow5.convertFromUnsignedParts(
3298 decSig.exponent +=
exp;
3302 unsigned int powHUerr;
3306 calcLostFraction = decSig.multiplySignificand(pow5);
3307 powHUerr = powStatus !=
opOK;
3309 calcLostFraction = decSig.divideSignificand(pow5);
3311 if (decSig.exponent < semantics->minExponent) {
3312 excessPrecision += (semantics->minExponent - decSig.exponent);
3313 truncatedBits = excessPrecision;
3314 excessPrecision = std::min(excessPrecision, calcSemantics.
precision);
3323 (decSig.significandParts(), calcSemantics.
precision - 1) == 1);
3328 excessPrecision, isNearest);
3331 if (HUdistance >= HUerr) {
3332 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
3333 calcSemantics.
precision - excessPrecision,
3338 exponent = (decSig.exponent + semantics->precision
3339 - (calcSemantics.
precision - excessPrecision));
3343 return static_cast<opStatus>(normalize(rounding_mode, calcLostFraction) |
3349Expected<APFloat::opStatus>
3350IEEEFloat::convertFromDecimalString(StringRef str,
roundingMode rounding_mode) {
3357 return std::move(Err);
3388 if (!semantics->hasZero)
3393 }
else if (
D.normalizedExponent - 1 > INT_MAX / 42039) {
3394 fs = handleOverflow(rounding_mode);
3400 }
else if (
D.normalizedExponent - 1 < INT_MIN / 42039 ||
3401 (
D.normalizedExponent + 1) * 28738 <=
3402 8651 * (semantics->minExponent - (
int) semantics->precision)) {
3409 }
else if ((
D.normalizedExponent - 1) * 42039
3410 >= 12655 * semantics->maxExponent) {
3412 fs = handleOverflow(rounding_mode);
3415 unsigned int partCount;
3421 partCount =
static_cast<unsigned int>(
D.lastSigDigit -
D.firstSigDigit) + 1;
3439 if (p == str.
end()) {
3444 if (decValue >= 10U) {
3445 delete[] decSignificand;
3446 return createError(
"Invalid character in significand");
3452 }
while (p <=
D.lastSigDigit && multiplier <= (~ (
integerPart) 0 - 9) / 10);
3456 partCount, partCount + 1,
false);
3460 if (decSignificand[partCount])
3462 }
while (p <=
D.lastSigDigit);
3465 fs = roundSignificandWithExponent(decSignificand, partCount,
3466 D.exponent, rounding_mode);
3468 delete [] decSignificand;
3474bool IEEEFloat::convertFromStringSpecials(StringRef str) {
3475 const size_t MIN_NAME_SIZE = 3;
3477 if (str.
size() < MIN_NAME_SIZE)
3480 if (str ==
"inf" || str ==
"INFINITY" || str ==
"+Inf" || str ==
"+inf") {
3487 if (str.
size() < MIN_NAME_SIZE)
3490 if (str ==
"inf" || str ==
"INFINITY" || str ==
"Inf") {
3499 if (str.
size() < MIN_NAME_SIZE)
3506 makeNaN(IsSignaling, IsNegative);
3511 if (str.
front() ==
'(') {
3513 if (str.
size() <= 2 || str.
back() !=
')')
3520 unsigned Radix = 10;
3521 if (str[0] ==
'0') {
3522 if (str.
size() > 1 && tolower(str[1]) ==
'x') {
3533 makeNaN(IsSignaling, IsNegative, &Payload);
3541Expected<APFloat::opStatus>
3547 if (convertFromStringSpecials(str))
3552 size_t slen = str.
size();
3553 sign = *p ==
'-' ? 1 : 0;
3554 if (sign && !semantics->hasSignedRepr)
3556 "This floating point format does not support signed values");
3558 if (*p ==
'-' || *p ==
'+') {
3565 if (slen >= 2 && p[0] ==
'0' && (p[1] ==
'x' || p[1] ==
'X')) {
3568 return convertFromHexadecimalString(
StringRef(p + 2, slen - 2),
3572 return convertFromDecimalString(
StringRef(p, slen), rounding_mode);
3614 dst +=
sizeof NaNU - 1;
3619 *dst++ = upperCase ?
'X':
'x';
3621 if (hexDigits > 1) {
3623 memset (dst,
'0', hexDigits - 1);
3624 dst += hexDigits - 1;
3626 *dst++ = upperCase ?
'P':
'p';
3631 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
3637 return static_cast<unsigned int>(dst - p);
3644char *IEEEFloat::convertNormalToHexString(
char *dst,
unsigned int hexDigits,
3648 *dst++ = upperCase ?
'X':
'x';
3650 bool roundUp =
false;
3653 const integerPart *significand = significandParts();
3654 unsigned partsCount = partCount();
3658 unsigned valueBits = semantics->
precision + 3;
3663 unsigned outputDigits = (valueBits - significandLSB() + 3) / 4;
3669 if (hexDigits < outputDigits) {
3675 bits = valueBits - hexDigits * 4;
3677 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
3679 outputDigits = hexDigits;
3689 while (outputDigits &&
count) {
3693 if (--
count == partsCount)
3696 part = significand[
count] << shift;
3704 curDigits = std::min(curDigits, outputDigits);
3705 dst +=
partAsHex (dst, part, curDigits, hexDigitChars);
3706 outputDigits -= curDigits;
3716 }
while (*q ==
'0');
3720 memset (dst,
'0', outputDigits);
3721 dst += outputDigits;
3734 *dst++ = upperCase ?
'P':
'p';
3750 Arg.significandParts(),
3751 Arg.significandParts() + Arg.partCount()));
3764APInt IEEEFloat::convertIEEEFloatToAPInt<APFloatBase::S_PPCDoubleDoubleLegacy>()
3780 extendedSemantics.
minExponent = APFloatBase::semIEEEdouble.minExponent;
3796 if (u.isFiniteNonZero() && losesInfo) {
3810 return APInt(128, words);
3813template <APFloatBase::Semantics E>
3814APInt IEEEFloat::convertIEEEFloatToAPInt()
const {
3817 constexpr unsigned int trailing_significand_bits =
3822 constexpr uint64_t significand_mask = integer_bit - 1;
3823 constexpr unsigned int exponent_bits =
3825 static_assert(exponent_bits < 64);
3828 constexpr int bias = -(S.
minExponent - (is_zero_exp_reserved ? 1 : 0));
3835 myexponent = exponent + bias;
3836 std::copy_n(significandParts(), mysignificand.size(),
3837 mysignificand.begin());
3838 if (myexponent == 1 &&
3839 !(significandParts()[integer_bit_part] & integer_bit))
3841 }
else if (category ==
fcZero) {
3844 myexponent = ::exponentZero(S) + bias;
3845 mysignificand.fill(0);
3850 myexponent = ::exponentInf(S) + bias;
3851 mysignificand.fill(0);
3853 mysignificand[0] =
integerPart{1} << (trailing_significand_bits - 1);
3859 myexponent = ::exponentNaN(S) + bias;
3860 std::copy_n(significandParts(), mysignificand.size(),
3861 mysignificand.begin());
3865 std::copy_n(mysignificand.begin(), mysignificand.size(), words.begin());
3867 if constexpr (significand_mask != 0 || trailing_significand_bits == 0) {
3869 words[mysignificand.size() - 1] &= significand_mask;
3872 std::fill(words_iter, words.end(),
uint64_t{0});
3873 constexpr size_t last_word = words.size() - 1;
3877 words[last_word] |= shifted_sign;
3879 uint64_t shifted_exponent = (myexponent & exponent_mask)
3880 << (trailing_significand_bits % 64);
3881 words[last_word] |= shifted_exponent;
3882 if constexpr (last_word == 0) {
3893 assert(semantics->bitcastToAPInt !=
nullptr &&
3894 "semantics must have bitcastToAPInt defined");
3896 return semantics->bitcastToAPInt(R);
3901 "Float semantics are not IEEEsingle");
3908 "Float semantics are not IEEEdouble");
3913#ifdef HAS_IEE754_FLOAT128
3914float128 IEEEFloat::convertToQuad()
const {
3916 "Float semantics are not IEEEquads");
3918 return api.bitsToQuad();
3923void IEEEFloat::initFromIEEEAPInt<APFloatBase::S_PPCDoubleDoubleLegacy>(
3930 initFromIEEEAPInt<APFloatBase::S_IEEEdouble>(
APInt(64, i1));
3931 [[maybe_unused]]
opStatus fs = convert(APFloatBase::semPPCDoubleDoubleLegacy,
3937 if (isFiniteNonZero()) {
3951template <APFloatBase::Semantics E>
3952void IEEEFloat::initFromIEEEAPInt(
const APInt &api) {
3956 constexpr unsigned int trailing_significand_bits =
3960 constexpr uint64_t significand_mask = integer_bit - 1;
3961 constexpr unsigned int exponent_bits =
3963 static_assert(exponent_bits < 64);
3964 constexpr unsigned int stored_significand_parts =
3968 constexpr int bias = -(S.
minExponent - (is_zero_exp_reserved ? 1 : 0));
3969 constexpr bool has_significand = trailing_significand_bits > 0;
3973 std::array<integerPart, stored_significand_parts> mysignificand;
3974 if constexpr (has_significand) {
3975 std::copy_n(api.
getRawData(), mysignificand.size(), mysignificand.begin());
3977 mysignificand[mysignificand.size() - 1] &= significand_mask;
3980 std::fill_n(mysignificand.begin(), mysignificand.size(), 0);
3983 mysignificand[0] = 1;
3990 (last_word >> (trailing_significand_bits % 64)) & exponent_mask;
3993 assert(partCount() == mysignificand.size());
3996 ?
static_cast<unsigned int>(last_word >> ((S.
sizeInBits - 1) % 64))
3999 bool all_zero_significand =
4002 bool is_zero = myexponent == 0 && all_zero_significand && S.
hasZero;
4005 bool is_inf =
false;
4010 constexpr integerPart significand_mask_no_int_bit =
4011 (
uint64_t{1} << (trailing_significand_bits - 1)) - 1;
4013 mysignificand[0] >> (trailing_significand_bits - 1);
4015 is_inf = myexponent - bias == ::exponentInf(S) && myintegerbit == 1 &&
4016 (mysignificand[0] & significand_mask_no_int_bit) == 0;
4018 is_inf = myexponent - bias == ::exponentInf(S) && all_zero_significand;
4027 bool is_nan =
false;
4034 mysignificand[0] >> (trailing_significand_bits - 1);
4035 constexpr integerPart significand_mask_no_int_bit =
4036 (
uint64_t{1} << (trailing_significand_bits - 1)) - 1;
4038 if (myexponent - bias == ::exponentNaN(S) &&
4039 (mysignificand[0] & significand_mask_no_int_bit) != 0) {
4042 }
else if (myexponent - bias == ::exponentNaN(S) &&
4043 (mysignificand[0] & significand_mask_no_int_bit) == 0) {
4046 }
else if (myexponent - bias != ::exponentNaN(S) && myexponent != 0 &&
4047 myintegerbit == 0) {
4052 is_nan = myexponent - bias == ::exponentNaN(S) && !all_zero_significand;
4055 bool all_ones_significand =
4056 std::all_of(mysignificand.begin(), mysignificand.end() - 1,
4057 [](
integerPart bits) { return bits == ~integerPart{0}; }) &&
4058 (!significand_mask ||
4059 mysignificand[mysignificand.size() - 1] == significand_mask);
4060 is_nan = myexponent - bias == ::exponentNaN(S) && all_ones_significand;
4062 is_nan = is_zero && sign;
4068 std::copy_n(mysignificand.begin(), mysignificand.size(),
4069 significandParts());
4079 exponent = myexponent - bias;
4080 std::copy_n(mysignificand.begin(), mysignificand.size(), significandParts());
4085 significandParts()[mysignificand.size() - 1] |= integer_bit;
4094 "semantics must have initFromAPInt defined");
4102 if (Negative && !semantics->hasSignedRepr)
4104 "This floating point format does not support signed values");
4111 exponent = semantics->maxExponent;
4115 unsigned PartCount = partCount();
4116 memset(significand, 0xFF,
sizeof(
integerPart)*(PartCount - 1));
4120 const unsigned NumUnusedHighBits =
4127 (semantics->precision > 1))
4134 if (Negative && !semantics->hasSignedRepr)
4136 "This floating point format does not support signed values");
4143 exponent = semantics->minExponent;
4148 if (Negative && !semantics->hasSignedRepr)
4150 "This floating point format does not support signed values");
4159 exponent = semantics->minExponent;
4164 initFromAPInt(&Sem, API);
4177 Buffer.
append(Str.begin(), Str.end());
4182 void AdjustToPrecision(
APInt &significand,
4183 int &
exp,
unsigned FormatPrecision) {
4187 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
4189 if (bits <= bitsRequired)
return;
4191 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
4192 if (!tensRemovable)
return;
4194 exp += tensRemovable;
4199 if (tensRemovable & 1)
4201 tensRemovable >>= 1;
4202 if (!tensRemovable)
break;
4206 significand = significand.
udiv(divisor);
4214 int &
exp,
unsigned FormatPrecision) {
4215 unsigned N = buffer.
size();
4216 if (
N <= FormatPrecision)
return;
4219 unsigned FirstSignificant =
N - FormatPrecision;
4226 if (buffer[FirstSignificant - 1] <
'5') {
4227 while (FirstSignificant <
N && buffer[FirstSignificant] ==
'0')
4230 exp += FirstSignificant;
4231 buffer.
erase(&buffer[0], &buffer[FirstSignificant]);
4237 for (
unsigned I = FirstSignificant;
I !=
N; ++
I) {
4238 if (buffer[
I] ==
'9') {
4247 if (FirstSignificant ==
N) {
4248 exp += FirstSignificant;
4254 exp += FirstSignificant;
4255 buffer.
erase(&buffer[0], &buffer[FirstSignificant]);
4259 APInt significand,
unsigned FormatPrecision,
4260 unsigned FormatMaxPadding,
bool TruncateZero) {
4261 const int semanticsPrecision = significand.
getBitWidth();
4268 if (!FormatPrecision) {
4276 FormatPrecision = 2 + semanticsPrecision * 59 / 196;
4281 exp += trailingZeros;
4287 }
else if (
exp > 0) {
4289 significand = significand.
zext(semanticsPrecision +
exp);
4290 significand <<=
exp;
4304 unsigned precision = semanticsPrecision + (137 * texp + 136) / 59;
4308 significand = significand.
zext(precision);
4309 APInt five_to_the_i(precision, 5);
4312 significand *= five_to_the_i;
4317 five_to_the_i *= five_to_the_i;
4321 AdjustToPrecision(significand,
exp, FormatPrecision);
4326 unsigned precision = significand.getBitWidth();
4327 if (precision < 4) {
4330 significand = significand.zext(precision);
4332 APInt ten(precision, 10);
4333 APInt digit(precision, 0);
4335 bool inTrail =
true;
4336 while (significand != 0) {
4341 unsigned d = digit.getZExtValue();
4352 assert(!buffer.
empty() &&
"no characters in buffer!");
4356 AdjustToPrecision(buffer,
exp, FormatPrecision);
4358 unsigned NDigits = buffer.
size();
4361 bool FormatScientific;
4362 if (!FormatMaxPadding) {
4363 FormatScientific =
true;
4369 FormatScientific = ((unsigned)
exp > FormatMaxPadding ||
4370 NDigits + (unsigned)
exp > FormatPrecision);
4373 int MSD =
exp + (int) (NDigits - 1);
4376 FormatScientific =
false;
4380 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
4386 if (FormatScientific) {
4387 exp += (NDigits - 1);
4389 Str.push_back(buffer[NDigits-1]);
4391 if (NDigits == 1 && TruncateZero)
4394 for (
unsigned I = 1;
I != NDigits; ++
I)
4395 Str.push_back(buffer[NDigits-1-
I]);
4397 if (!TruncateZero && FormatPrecision > NDigits - 1)
4398 Str.append(FormatPrecision - NDigits + 1,
'0');
4400 Str.push_back(TruncateZero ?
'E' :
'e');
4402 Str.push_back(
exp >= 0 ?
'+' :
'-');
4411 if (!TruncateZero && expbuf.
size() < 2)
4413 for (
unsigned I = 0,
E = expbuf.
size();
I !=
E; ++
I)
4414 Str.push_back(expbuf[
E-1-
I]);
4420 for (
unsigned I = 0;
I != NDigits; ++
I)
4421 Str.push_back(buffer[NDigits-1-
I]);
4422 for (
unsigned I = 0;
I != (unsigned)
exp; ++
I)
4430 int NWholeDigits =
exp + (int) NDigits;
4433 if (NWholeDigits > 0) {
4434 for (;
I != (unsigned) NWholeDigits; ++
I)
4435 Str.push_back(buffer[NDigits-
I-1]);
4438 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
4442 for (
unsigned Z = 1;
Z != NZeros; ++
Z)
4446 for (;
I != NDigits; ++
I)
4447 Str.push_back(buffer[NDigits-
I-1]);
4453 unsigned FormatMaxPadding,
bool TruncateZero)
const {
4457 return append(Str,
"-Inf");
4459 return append(Str,
"+Inf");
4467 if (!FormatMaxPadding) {
4472 if (FormatPrecision > 1)
4473 Str.append(FormatPrecision - 1,
'0');
4486 int exp = exponent - ((int) semantics->precision - 1);
4488 semantics->precision,
4491 toStringImpl(Str,
isNegative(),
exp, significand, FormatPrecision,
4492 FormatMaxPadding, TruncateZero);
4504 for (
int i = 0; i < PartCount; ++i) {
4510 if (exponent != semantics->minExponent)
4513 int CountrParts = 0;
4514 for (
int i = 0; i < PartCount;
4516 if (Parts[i] != 0) {
4517 return exponent - semantics->precision + CountrParts +
4580 if (!semantics->hasZero)
4590 }
else if (semantics->nonFiniteBehavior ==
4598 exponent = semantics->maxExponent + 1;
4612 bool WillCrossBinadeBoundary =
4613 exponent != semantics->minExponent && isSignificandAllZeros();
4631 if (WillCrossBinadeBoundary) {
4652 if (WillCrossBinadeBoundary) {
4656 assert(exponent != semantics->maxExponent &&
4657 "We can not increment an exponent beyond the maxExponent allowed"
4658 " by the given floating point semantics.");
4661 incrementSignificand();
4675 assert(
isNaN() &&
"Can only be called on NaN values");
4677 unsigned Bits = semantics->precision - 1;
4682 return ::exponentNaN(*semantics);
4686 return ::exponentInf(*semantics);
4690 return ::exponentZero(*semantics);
4709 if (!semantics->hasZero)
4736 return Arg.exponent;
4741 Normalized.exponent += SignificandBits;
4743 return Normalized.exponent - SignificandBits;
4747 auto MaxExp =
X.getSemantics().maxExponent;
4748 auto MinExp =
X.getSemantics().minExponent;
4756 int SignificandBits =
X.getSemantics().precision - 1;
4757 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
4760 X.exponent += std::clamp(Exp, -MaxIncrement - 1, MaxIncrement);
4783 return scalbn(Val, -Exp, RM);
4789 APFloat(APFloatBase::semIEEEdouble)}) {
4790 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4794 : Semantics(&S), Floats(new
APFloat[2]{
4797 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4803 APFloat(APFloatBase::semIEEEdouble)}) {
4804 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4810 APFloat(APFloatBase::semIEEEdouble,
APInt(64,
I.getRawData()[0])),
4811 APFloat(APFloatBase::semIEEEdouble,
APInt(64,
I.getRawData()[1]))}) {
4812 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4818 Floats(new
APFloat[2]{std::move(
First), std::move(Second)}) {
4819 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4820 assert(&Floats[0].getSemantics() == &APFloatBase::semIEEEdouble);
4821 assert(&Floats[1].getSemantics() == &APFloatBase::semIEEEdouble);
4825 : Semantics(RHS.Semantics),
4829 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4833 : Semantics(RHS.Semantics), Floats(RHS.Floats) {
4834 RHS.Semantics = &APFloatBase::semBogus;
4835 RHS.Floats =
nullptr;
4836 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4840 if (Semantics == RHS.Semantics && RHS.Floats) {
4841 Floats[0] = RHS.Floats[0];
4842 Floats[1] = RHS.Floats[1];
4843 }
else if (
this != &RHS) {
4876 Floats[0] = std::move(z);
4877 Floats[1].makeZero(
false);
4890 Status |= z.
add(a, RM);
4891 Status |= z.
add(c, RM);
4894 Floats[0] = std::move(z);
4895 Floats[1].makeZero(
false);
4900 Status |= zz.
add(cc, RM);
4904 Status |= Floats[1].subtract(z, RM);
4905 Status |= Floats[1].add(c, RM);
4906 Status |= Floats[1].add(zz, RM);
4910 Status |= Floats[1].subtract(z, RM);
4911 Status |= Floats[1].add(a, RM);
4912 Status |= Floats[1].add(zz, RM);
4917 Status |=
q.subtract(z, RM);
4922 Status |= zz.
add(c, RM);
4923 Status |=
q.add(z, RM);
4924 Status |=
q.subtract(a, RM);
4926 Status |= zz.
add(q, RM);
4927 Status |= zz.
add(
aa, RM);
4928 Status |= zz.
add(cc, RM);
4930 Floats[0] = std::move(z);
4931 Floats[1].makeZero(
false);
4935 Status |= Floats[0].add(zz, RM);
4937 Floats[1].makeZero(
false);
4940 Floats[1] = std::move(z);
4941 Status |= Floats[1].subtract(Floats[0], RM);
4942 Status |= Floats[1].add(zz, RM);
4968 LHS.isNegative() !=
RHS.isNegative()) {
4969 Out.makeNaN(
false,
Out.isNegative(),
nullptr);
4984 assert(&
A.getSemantics() == &APFloatBase::semIEEEdouble);
4985 assert(&AA.getSemantics() == &APFloatBase::semIEEEdouble);
4986 assert(&
C.getSemantics() == &APFloatBase::semIEEEdouble);
4987 assert(&
CC.getSemantics() == &APFloatBase::semIEEEdouble);
4988 assert(&
Out.Floats[0].getSemantics() == &APFloatBase::semIEEEdouble);
4989 assert(&
Out.Floats[1].getSemantics() == &APFloatBase::semIEEEdouble);
4990 return Out.addImpl(
A, AA,
C,
CC, RM);
4995 return addWithSpecial(*
this, RHS, *
this, RM);
5001 auto Ret =
add(RHS, RM);
5008 const auto &LHS = *
this;
5025 if (LHS.getCategory() ==
fcNaN) {
5029 if (RHS.getCategory() ==
fcNaN) {
5035 Out.makeNaN(
false,
false,
nullptr);
5047 "Special cases not handled exhaustively");
5050 APFloat A = Floats[0],
B = Floats[1],
C = RHS.Floats[0],
D = RHS.Floats[1];
5054 if (!
T.isFiniteNonZero()) {
5055 Floats[0] = std::move(
T);
5056 Floats[1].makeZero(
false);
5078 Status |= U.add(Tau, RM);
5081 if (!U.isFinite()) {
5082 Floats[1].makeZero(
false);
5087 Floats[1] = std::move(
T);
5094 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5095 "Unexpected Semantics");
5098 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
5104 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5105 "Unexpected Semantics");
5108 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
5114 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5115 "Unexpected Semantics");
5118 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
5127 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5128 "Unexpected Semantics");
5131 APFloat(APFloatBase::semPPCDoubleDoubleLegacy,
5140 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5141 "Unexpected Semantics");
5151 if (!
Hi.isFiniteNonZero() ||
Lo.isZero()) {
5152 Floats[0] = std::move(RoundedHi);
5153 Floats[1].makeZero(
false);
5165 const APFloat RoundingError = Rounded - ToRound;
5166 if (TieBreaker.isNonZero() &&
5167 TieBreaker.isNegative() != RoundingError.
isNegative() &&
5168 abs(RoundingError).isExactlyValue(0.5))
5177 if (RoundedHi !=
Hi) {
5182 RoundedHi = RoundToNearestHelper(
Hi, RoundedHi,
Lo);
5184 Floats[0] = std::move(RoundedHi);
5185 Floats[1].makeZero(
false);
5198 LoRoundingMode = RM;
5206 RoundedLo = RoundToNearestHelper(
Lo, RoundedLo,
Hi);
5209 std::tie(RoundedHi, RoundedLo) =
fastTwoSum(RoundedHi, RoundedLo);
5211 Floats[0] = std::move(RoundedHi);
5212 Floats[1] = std::move(RoundedLo);
5217 Floats[0].changeSign();
5218 Floats[1].changeSign();
5224 const cmpResult HiPartCmp = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
5229 if (Floats[1].
isZero() && RHS.Floats[1].isZero())
5235 const bool ThisIsSubtractive =
5236 Floats[0].isNegative() != Floats[1].isNegative();
5237 const bool RHSIsSubtractive =
5238 RHS.Floats[0].isNegative() != RHS.Floats[1].isNegative();
5248 if (RHS.Floats[1].isZero())
5255 if (ThisIsSubtractive != RHSIsSubtractive)
5260 const cmpResult LoPartCmp = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
5262 if (ThisIsSubtractive) {
5276 return Floats[0].getCategory();
5282 Floats[0].makeInf(Neg);
5283 Floats[1].makeZero(
false);
5287 Floats[0].makeZero(Neg);
5288 Floats[1].makeZero(
false);
5292 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5293 "Unexpected Semantics");
5295 APFloat(APFloatBase::semIEEEdouble,
APInt(64, 0x7fefffffffffffffull));
5297 APFloat(APFloatBase::semIEEEdouble,
APInt(64, 0x7c8ffffffffffffeull));
5303 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5304 "Unexpected Semantics");
5305 Floats[0].makeSmallest(Neg);
5306 Floats[1].makeZero(
false);
5310 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5311 "Unexpected Semantics");
5313 APFloat(APFloatBase::semIEEEdouble,
APInt(64, 0x0360000000000000ull));
5315 Floats[0].changeSign();
5316 Floats[1].makeZero(
false);
5320 Floats[0].makeNaN(SNaN, Neg,
fill);
5321 Floats[1].makeZero(
false);
5325 auto Result = Floats[0].compare(RHS.Floats[0]);
5328 return Floats[1].compare(RHS.Floats[1]);
5333 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
5334 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
5344 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5345 "Unexpected Semantics");
5347 Floats[0].bitcastToAPInt().getRawData()[0],
5348 Floats[1].bitcastToAPInt().getRawData()[0],
5355 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5356 "Unexpected Semantics");
5357 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy);
5370 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5371 "Unexpected Semantics");
5421 if (InLattice(HiOld, NextLo)) {
5423 Floats[1] = std::move(NextLo);
5460 if (!InLattice(NextHi, NextLo))
5464 Floats[0] = std::move(NextHi);
5465 Floats[1] = std::move(NextLo);
5473 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5474 "Unexpected Semantics");
5516 const unsigned PositiveOverflowWidth = IsSigned ? Width - 1 : Width;
5517 if (HiExactLog2 >= 0 &&
5518 static_cast<unsigned>(HiExactLog2) == PositiveOverflowWidth) {
5528 Input, Width,
true, RM, &LoIsExact);
5541 *IsExact = RoundStatus ==
opOK;
5553 APSInt LoResult{Width, !IsSigned};
5565 *IsExact = RoundStatus ==
opOK;
5571 unsigned int Width,
bool IsSigned,
5574 convertToSignExtendedInteger(
Input, Width, IsSigned, RM, IsExact);
5578 assert(DstPartsCount <=
Input.size() &&
"Integer too big");
5586 Bits = Width - IsSigned;
5631 if (SrcMSB == UINT_MAX) {
5638 const unsigned SrcBitWidth = SrcMSB + 1;
5654 return handleOverflow(RM);
5660 bool HiAsIntIsExact;
5677 if (
Error.isNegative()) {
5685 const unsigned ErrorActiveBits =
Error.getSignificantBits() - 1;
5687 if (ErrorActiveBits > LoPrecision) {
5688 const unsigned RoundingBoundary = ErrorActiveBits - LoPrecision;
5692 if (
Error.countTrailingZeros() == RoundingBoundary - 1)
5711 Floats[0] = std::move(
Hi);
5712 Floats[1] = std::move(
Lo);
5717 return handleOverflow(RM);
5723 Largest.makeLargest(
false);
5725 return handleOverflow(RM);
5737 const bool NegateInput = IsSigned &&
Input.isNegative();
5750 unsigned int HexDigits,
5753 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5754 "Unexpected Semantics");
5761 (Floats[0].isDenormal() || Floats[1].
isDenormal() ||
5763 Floats[0] != Floats[0] + Floats[1]);
5792 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5793 "Unexpected Semantics");
5794 return Floats[0].isInteger() && Floats[1].isInteger();
5798 unsigned FormatPrecision,
5799 unsigned FormatMaxPadding,
5800 bool TruncateZero)
const {
5801 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5802 "Unexpected Semantics");
5804 .
toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
5824 if (
Lo.isZero() ||
Hi.isNegative() ==
Lo.isNegative())
5826 if (
Hi.getExactLog2Abs() == INT_MIN)
5830 return IlogbResult - 1;
5836 "Unexpected Semantics");
5838 scalbn(Arg.Floats[0], Exp, RM),
5839 scalbn(Arg.Floats[1], Exp, RM));
5841 if (Result.getFirst().isInfinity())
5842 Result.makeInf(Result.getFirst().isNegative());
5850 "Unexpected Semantics");
5860 Quiet.getFirst() =
Quiet.getFirst().makeQuiet();
5882 const bool SignsDisagree =
Hi.isNegative() !=
Lo.isNegative();
5899 LoRoundingMode = RM;
5900 Second =
scalbn(
Lo, -Exp, LoRoundingMode);
5908 if (RecomposedLo !=
Lo) {
5912 const APFloat RoundingError = RecomposedLo -
Lo;
5917 const APFloat ScaledUlpOfSecond =
5919 const bool IsMidpoint =
abs(RoundingError) == ScaledUlpOfSecond;
5920 const bool RoundedLoAway =
5925 if (IsMidpoint && RoundedLoAway)
5941 if (Second.
isZero() && SignsDisagree &&
Hi.getExactLog2Abs() != INT_MIN)
5960 return Repr->category;
5966 return Repr->exponent;
5970 return APInt(Repr->semantics->precision,
5971 ArrayRef(Repr->significandParts(), Repr->partCount()));
5975 Repr->category = Category;
5979 assert((!Negative || Repr->semantics->hasSignedRepr) &&
5980 "This floating point format does not support signed values");
5981 Repr->sign = Negative;
5990 "significand must be precision bits wide");
5992 unsigned PartCount = Repr->partCount();
5995 std::min(PartCount, Significand.
getNumWords()), Parts);
5998APFloat::Storage::Storage(IEEEFloat
F,
const fltSemantics &Semantics) {
5999 if (usesLayout<IEEEFloat>(Semantics)) {
6000 new (&
IEEE) IEEEFloat(std::move(
F));
6003 if (usesLayout<DoubleAPFloat>(Semantics)) {
6005 new (&Double) DoubleAPFloat(Semantics,
APFloat(std::move(
F), S),
6018 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.
getSemantics()))
6020 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.
getSemantics()))
6028 assert(StatusOrErr &&
"Invalid floating point representation");
6080 APFloat Reciprocal =
6098 *Inv = std::move(Reciprocal);
6110 usesLayout<IEEEFloat>(ToSemantics))
6111 return U.IEEE.convert(ToSemantics, RM, losesInfo);
6113 usesLayout<DoubleAPFloat>(ToSemantics)) {
6114 assert(&ToSemantics == &APFloatBase::semPPCDoubleDouble);
6116 U.IEEE.convert(APFloatBase::semPPCDoubleDoubleLegacy, RM, losesInfo);
6121 usesLayout<IEEEFloat>(ToSemantics)) {
6122 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
6123 *
this =
APFloat(std::move(getIEEE()), ToSemantics);
6134 unsigned FormatPrecision,
6135 unsigned FormatMaxPadding,
6136 bool TruncateZero)
const {
6138 toString(Buf, FormatPrecision, FormatMaxPadding, TruncateZero);
6139 Str.append(Buf.
begin(), Buf.
end());
6154 APInt Result(Width, 1);
6155 for (; Exp >= 27; Exp -= 27)
6156 Result *= UINT64_C(7450580596923828125);
6184 const int Q = std::max(
ilogb(AbsVal), MinExp) - int(Prec - 1);
6189 bool LosesInfo =
false;
6192 assert(!LosesInfo &&
"widening conversion is exact");
6194 bool IsExact =
false;
6195 APSInt M(Prec + 2,
true);
6198 assert(IsExact &&
"significand extraction is exact");
6204 const bool HalfBelow = M.isPowerOf2() &&
ilogb(AbsVal) > MinExp;
6205 const bool Inclusive = !M[0];
6206 const int E2 = Q - (HalfBelow ? 2 : 1);
6211 const unsigned ScaleBits =
6213 const unsigned Width = Prec + 2 + ScaleBits + 4;
6215 APInt Low = HalfBelow ? (MW << 2) - 1 : (MW << 1) - 1;
6216 APInt High = HalfBelow ? (MW << 2) + 2 : (MW << 1) + 1;
6236 while ((P10 * 10).ule(IntervalWidth)) {
6243 APInt CMin(Width, 0), CMax(Width, 0);
6244 auto FindCandidates = [&]() {
6245 APInt Quo(Width, 0), Rem(Width, 0);
6247 CMin = (Inclusive && Rem.
isZero()) ? Quo : Quo + 1;
6249 CMax = (!Inclusive && Rem.
isZero()) ? Quo - 1 : Quo;
6252 while (CMin.ugt(CMax)) {
6261 if ((CMax10 * 10).ult(CMin))
6263 CMin = (CMin + 9).udiv(10);
6266 unsigned Digits = 0;
6267 for (; !CMin.isZero(); ++Digits)
6268 CMin = CMin.udiv(10);
6273 unsigned FormatMaxPadding,
6274 bool TruncateZero)
const {
6276 toString(Best, 0, FormatMaxPadding, TruncateZero);
6279 const bool KeepIntegerDigits =
6292 unsigned Precision =
6294 for (
unsigned MaxPrecision = Best.
size(); Precision < MaxPrecision;
6304 Str.append(Best.
begin(), Best.
end());
6313#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
6326 bool *isExact)
const {
6330 rounding_mode, isExact);
6332 result =
APInt(bitWidth, parts);
6338 return getIEEE().convertToDouble();
6340 "Float semantics is not representable by IEEEdouble");
6341 APFloat Temp = *
this;
6349#ifdef HAS_IEE754_FLOAT128
6350float128 APFloat::convertToQuad()
const {
6352 return getIEEE().convertToQuad();
6354 "Float semantics is not representable by IEEEquad");
6357 [[maybe_unused]] opStatus St =
6360 return Temp.getIEEE().convertToQuad();
6366 return getIEEE().convertToFloat();
6368 "Float semantics is not representable by IEEEsingle");
6369 APFloat Temp = *
this;
6402 .
Case(
"Float8E5M2", &semFloat8E5M2)
6403 .
Case(
"Float8E4M3FN", &semFloat8E4M3FN)
6404 .
Case(
"Float8E5M3FNU", &semFloat8E5M3FNU)
6405 .
Case(
"Float4E2M1FN", &semFloat4E2M1FN)
6406 .
Case(
"Float6E3M2FN", &semFloat6E3M2FN)
6407 .
Case(
"Float6E2M3FN", &semFloat6E2M3FN)
6411APFloat::Storage::~Storage() {
6412 if (usesLayout<IEEEFloat>(*semantics)) {
6416 if (usesLayout<DoubleAPFloat>(*semantics)) {
6423APFloat::Storage::Storage(
const APFloat::Storage &
RHS) {
6424 if (usesLayout<IEEEFloat>(*
RHS.semantics)) {
6428 if (usesLayout<DoubleAPFloat>(*
RHS.semantics)) {
6435APFloat::Storage::Storage(APFloat::Storage &&
RHS) {
6436 if (usesLayout<IEEEFloat>(*
RHS.semantics)) {
6440 if (usesLayout<DoubleAPFloat>(*
RHS.semantics)) {
6447APFloat::Storage &APFloat::Storage::operator=(
const APFloat::Storage &
RHS) {
6448 if (usesLayout<IEEEFloat>(*semantics) &&
6449 usesLayout<IEEEFloat>(*
RHS.semantics)) {
6451 }
else if (usesLayout<DoubleAPFloat>(*semantics) &&
6452 usesLayout<DoubleAPFloat>(*
RHS.semantics)) {
6454 }
else if (
this != &
RHS) {
6456 new (
this) Storage(
RHS);
6461APFloat::Storage &APFloat::Storage::operator=(APFloat::Storage &&
RHS) {
6462 if (usesLayout<IEEEFloat>(*semantics) &&
6463 usesLayout<IEEEFloat>(*
RHS.semantics)) {
6465 }
else if (usesLayout<DoubleAPFloat>(*semantics) &&
6466 usesLayout<DoubleAPFloat>(*
RHS.semantics)) {
6468 }
else if (
this != &
RHS) {
6470 new (
this) Storage(std::move(
RHS));
6479 if (libc_exceptions & FE_INVALID)
6481 if (libc_exceptions & FE_DIVBYZERO)
6483 if (libc_exceptions & FE_OVERFLOW)
6485 if (libc_exceptions & FE_UNDERFLOW)
6487 if (libc_exceptions & FE_INEXACT)
6502 float x_val = x.convertToFloat();
6504 LIBC_NAMESPACE::shared::check::exp_exceptions(x_val, FE_TONEAREST);
6506 *status = getOpStatusFromLibc(exc);
6507 if (x.isSignaling()) {
6514 float result = LIBC_NAMESPACE::shared::expf(x_val);
6519 double x_val = x.convertToDouble();
6521 LIBC_NAMESPACE::shared::check::exp_exceptions(x_val, FE_TONEAREST);
6523 *status = getOpStatusFromLibc(exc);
6524 if (x.isSignaling()) {
6531 double result = LIBC_NAMESPACE::shared::exp(x_val);
6535 return std::nullopt;
6540#undef APFLOAT_DISPATCH_ON_SEMANTICS
Ops append({Chain, DAG.getConstant(SVEStores[NumParts - 2], DL, MVT::i32)})
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static constexpr int packCategoriesIntoKey(int LHS, int RHS)
A function used to combine two fcCategory enums into one key which can be used in a switch statement ...
This file declares a class to represent arbitrary precision floating point values and provide a varie...
#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL)
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
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.
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)
if(!TBB||Cond.size()< 1) return false
This file defines the SmallString class.
This file defines the SmallVector class.
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")
static constexpr const fltSemantics & Float8E4M3()
static LLVM_ABI const llvm::fltSemantics & EnumToSemantics(Semantics S)
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
static constexpr const fltSemantics & Float8E5M2FNUZ()
static constexpr roundingMode rmTowardZero
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
llvm::RoundingMode roundingMode
IEEE-754R 4.3: Rounding-direction attributes.
static constexpr const fltSemantics & Float8E3M4()
static constexpr const fltSemantics & PPCDoubleDouble()
static LLVM_ABI unsigned int semanticsSizeInBits(const fltSemantics &)
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
static constexpr const fltSemantics & Float8E8M0FNU()
static constexpr const fltSemantics & Float8E4M3FNUZ()
static constexpr roundingMode rmTowardNegative
static constexpr const fltSemantics & FloatTF32()
static constexpr roundingMode rmNearestTiesToEven
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
static LLVM_ABI bool hasSignBitInMSB(const fltSemantics &)
static constexpr const fltSemantics & IEEEhalf()
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
static constexpr const fltSemantics & Bogus()
A Pseudo fltsemantic used to construct APFloats that cannot conflict with anything real.
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
static constexpr const fltSemantics & IEEEsingle()
static LLVM_ABI Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
int32_t ExponentType
A signed type to represent a floating point numbers unbiased exponent.
static constexpr const fltSemantics & Float6E2M3FN()
static constexpr unsigned integerPartWidth
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.
APInt::WordType integerPart
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
static constexpr roundingMode rmTowardPositive
static constexpr const fltSemantics & PPCDoubleDoubleLegacy()
static constexpr const fltSemantics & BFloat()
static constexpr const fltSemantics & Float6E3M2FN()
static constexpr const fltSemantics & IEEEdouble()
static LLVM_ABI bool isRepresentableBy(const fltSemantics &A, const fltSemantics &B)
static constexpr const fltSemantics & Float8E5M2()
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
fltCategory
Category of internally-represented number.
static constexpr const fltSemantics & Float8E5M3FNU()
static constexpr roundingMode rmNearestTiesToAway
@ S_PPCDoubleDoubleLegacy
static constexpr const fltSemantics & IEEEquad()
static constexpr const fltSemantics & Float4E2M1FN()
opStatus
IEEE-754R 7: Default exception handling.
static constexpr const fltSemantics & Float8E4M3B11FNUZ()
static constexpr const fltSemantics & Float8E4M3FN()
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...
static LLVM_ABI const fltSemantics * getArbitraryFPSemantics(StringRef Format)
Returns the fltSemantics for a given arbitrary FP format string, or nullptr if invalid.
static constexpr const fltSemantics & x87DoubleExtended()
static LLVM_ABI unsigned int semanticsIntSizeInBits(const fltSemantics &, bool)
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
LLVM_ABI void Profile(FoldingSetNodeID &NID) const
Used to insert APFloat objects, or objects that contain APFloat objects, into FoldingSets.
opStatus divide(const APFloat &RHS, roundingMode RM)
bool isFiniteNonZero() const
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
LLVM_READONLY int getExactLog2Abs() const
bool bitwiseIsEqual(const APFloat &RHS) const
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 ...
cmpResult compareAbsoluteValue(const APFloat &RHS) const
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
opStatus add(const APFloat &RHS, roundingMode RM)
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
const fltSemantics & getSemantics() const
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
LLVM_ABI float convertToFloat() const
Converts this APFloat to host float value.
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
opStatus remainder(const APFloat &RHS)
APInt bitcastToAPInt() const
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
opStatus next(bool nextDown)
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
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.
LLVM_ABI FPClassTest classify() const
Return the FPClassTest which will return true for the value.
opStatus mod(const APFloat &RHS)
LLVM_ABI void toStringShortest(SmallVectorImpl< char > &Str, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Like toString, but picks the smallest FormatPrecision whose output parses back bitwise equal: "3....
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
Fill this APFloat with the result of a string conversion.
LLVM_DUMP_METHOD void dump() const
LLVM_ABI bool toStringRoundTrip(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Format the value as toString does and return true if the string parses back bitwise equal.
LLVM_ABI void print(raw_ostream &) const
opStatus roundToIntegral(roundingMode RM)
static bool hasSignificand(const fltSemantics &Sem)
Returns true if the given semantics has actual significand.
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Class for arbitrary precision integers.
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
static LLVM_ABI void tcSetBit(WordType *, unsigned bit)
Set the given bit of a bignum. Zero-based.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
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.
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
static LLVM_ABI int tcExtractBit(const WordType *, unsigned bit)
Extract the given bit of a bignum; returns 0 or 1. Zero-based.
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
static LLVM_ABI WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned)
DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
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,...
unsigned getActiveBits() const
Compute the number of active bits in the value.
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
static LLVM_ABI int tcCompare(const WordType *, const WordType *, unsigned)
Comparison (unsigned) of two bignums.
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
static APInt floatToBits(float V)
Converts a float to APInt bits.
static LLVM_ABI void tcAssign(WordType *, const WordType *, unsigned)
Assign one bignum to another.
unsigned getBitWidth() const
Return the number of bits in the APInt.
static LLVM_ABI void tcShiftRight(WordType *, unsigned Words, unsigned Count)
Shift a bignum right Count bits.
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.
unsigned getNumWords() const
Get the number of words.
bool isNegative() const
Determine sign of this APInt.
static LLVM_ABI void tcClearBit(WordType *, unsigned bit)
Clear the given bit of a bignum. Zero-based.
void negate()
Negate this APInt in place.
static WordType tcDecrement(WordType *dst, unsigned parts)
Decrement a bignum in-place. Return the borrow flag.
unsigned countr_zero() const
Count the number of trailing zero bits.
static LLVM_ABI unsigned tcLSB(const WordType *, unsigned n)
Returns the bit number of the least or most significant set bit of a number.
static LLVM_ABI void tcShiftLeft(WordType *, unsigned Words, unsigned Count)
Shift a bignum left Count bits.
static LLVM_ABI bool tcIsZero(const WordType *, unsigned)
Returns true if a bignum is zero, false otherwise.
static LLVM_ABI unsigned tcMSB(const WordType *parts, unsigned n)
Returns the bit number of the most significant set bit of a number.
float bitsToFloat() const
Converts APInt bits to a float.
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.
static constexpr unsigned APINT_BITS_PER_WORD
Bits in a word.
static LLVM_ABI WordType tcSubtract(WordType *, const WordType *, WordType carry, unsigned)
DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
static LLVM_ABI void tcNegate(WordType *, unsigned)
Negate a bignum in-place.
static APInt doubleToBits(double V)
Converts a double to APInt bits.
static WordType tcIncrement(WordType *dst, unsigned parts)
Increment a bignum in-place. Return the carry flag.
APInt shl(unsigned shiftAmt) const
Left-shift function.
double bitsToDouble() const
Converts APInt bits to a double.
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
An arbitrary precision integer that knows its signedness.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Interface for fltSemantics callbacks to access the internal data of APFloat/IEEEFloat.
LLVM_ABI void setNegative(bool Negative)
LLVM_ABI bool isNegative() const
LLVM_ABI void initialize(const fltSemantics &Sem)
Set the semantics and allocate storage for the significand.
LLVM_ABI APFloatBase::fltCategory getCategory() const
LLVM_ABI void setExponent(APFloatBase::ExponentType Exponent)
LLVM_ABI APInt getSignificand() const
LLVM_ABI const fltSemantics & getSemantics() const
LLVM_ABI void setCategory(APFloatBase::fltCategory Category)
Exponent and significand are only meaningful for fcNormal and fcNaN.
LLVM_ABI void setSignificand(const APInt &Significand)
The significand is precision bits wide and includes the integer bit.
LLVM_ABI APFloatBase::ExponentType getExponent() const
This class is used to gather all the unique data bits of a node.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
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().
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
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.
static constexpr size_t npos
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
constexpr bool empty() const
Check if the string is empty.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
char back() const
Get the last character in the string.
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
constexpr size_t size() const
Get the string size.
char front() const
Get the first character in the string.
size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
bool consume_front_insensitive(StringRef Prefix)
Returns true if this StringRef has the given prefix, ignoring case, and removes that prefix.
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...
LLVM_ABI void makeSmallestNormalized(bool Neg)
LLVM_ABI DoubleAPFloat & operator=(const DoubleAPFloat &RHS)
LLVM_ABI void changeSign()
LLVM_ABI bool isLargest() const
LLVM_ABI opStatus remainder(const DoubleAPFloat &RHS)
LLVM_ABI opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM)
LLVM_ABI fltCategory getCategory() const
LLVM_ABI bool bitwiseIsEqual(const DoubleAPFloat &RHS) const
LLVM_ABI LLVM_READONLY int getExactLog2Abs() const
LLVM_ABI opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
LLVM_ABI APInt bitcastToAPInt() const
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
LLVM_ABI bool isSmallest() const
LLVM_ABI opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM)
LLVM_ABI friend hash_code hash_value(const DoubleAPFloat &Arg)
LLVM_ABI cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const
LLVM_ABI bool isDenormal() const
LLVM_ABI opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
LLVM_ABI void makeSmallest(bool Neg)
LLVM_ABI friend int ilogb(const DoubleAPFloat &X)
LLVM_ABI opStatus next(bool nextDown)
LLVM_ABI void makeInf(bool Neg)
LLVM_ABI bool isInteger() const
LLVM_ABI void makeZero(bool Neg)
LLVM_ABI opStatus divide(const DoubleAPFloat &RHS, roundingMode RM)
LLVM_ABI bool isSmallestNormalized() const
LLVM_ABI opStatus mod(const DoubleAPFloat &RHS)
LLVM_ABI DoubleAPFloat(const fltSemantics &S)
LLVM_ABI void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision, unsigned FormatMaxPadding, bool TruncateZero=true) const
LLVM_ABI void makeLargest(bool Neg)
LLVM_ABI cmpResult compare(const DoubleAPFloat &RHS) const
LLVM_ABI friend DoubleAPFloat scalbn(const DoubleAPFloat &X, int Exp, roundingMode)
LLVM_ABI opStatus roundToIntegral(roundingMode RM)
LLVM_ABI opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, const DoubleAPFloat &Addend, roundingMode RM)
LLVM_ABI APInt getNaNPayload() const
LLVM_ABI unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
LLVM_ABI bool isNegative() const
LLVM_ABI opStatus add(const DoubleAPFloat &RHS, roundingMode RM)
LLVM_ABI void makeNaN(bool SNaN, bool Neg, const APInt *fill)
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...
LLVM_ABI cmpResult compareAbsoluteValue(const IEEEFloat &) const
LLVM_ABI opStatus mod(const IEEEFloat &)
C fmod, or llvm frem.
fltCategory getCategory() const
LLVM_ABI opStatus convertFromAPInt(const APInt &, bool, roundingMode)
LLVM_ABI APInt getNaNPayload() const
bool isFiniteNonZero() const
bool needsCleanup() const
Returns whether this instance allocated memory.
LLVM_ABI void makeLargest(bool Neg=false)
Make this number the largest magnitude normal number in the given semantics.
LLVM_ABI LLVM_READONLY int getExactLog2Abs() const
LLVM_ABI APInt bitcastToAPInt() const
LLVM_ABI friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
LLVM_ABI cmpResult compare(const IEEEFloat &) const
IEEE comparison with another floating point number (NaNs compare unordered, 0==-0).
bool isNegative() const
IEEE-754R isSignMinus: Returns true if and only if the current value is negative.
LLVM_ABI opStatus divide(const IEEEFloat &, roundingMode)
bool isNaN() const
Returns true if and only if the float is a quiet or signaling NaN.
LLVM_ABI opStatus remainder(const IEEEFloat &)
IEEE remainder.
LLVM_ABI double convertToDouble() const
LLVM_ABI float convertToFloat() const
LLVM_ABI opStatus subtract(const IEEEFloat &, roundingMode)
LLVM_ABI void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Converts this value into a decimal string.
LLVM_ABI void makeSmallest(bool Neg=false)
Make this number the smallest magnitude denormal number in the given semantics.
LLVM_ABI void makeInf(bool Neg=false)
LLVM_ABI bool isSmallestNormalized() const
Returns true if this is the smallest (by magnitude) normalized finite number in the given semantics.
LLVM_ABI void makeQuiet()
LLVM_ABI bool isLargest() const
Returns true if and only if the number has the largest possible finite magnitude in the current seman...
LLVM_ABI opStatus add(const IEEEFloat &, roundingMode)
bool isFinite() const
Returns true if and only if the current value is zero, subnormal, or normal.
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
LLVM_ABI void makeNaN(bool SNaN=false, bool Neg=false, const APInt *fill=nullptr)
LLVM_ABI opStatus multiply(const IEEEFloat &, roundingMode)
LLVM_ABI opStatus roundToIntegral(roundingMode)
LLVM_ABI IEEEFloat & operator=(const IEEEFloat &)
LLVM_ABI bool bitwiseIsEqual(const IEEEFloat &) const
Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
LLVM_ABI void makeSmallestNormalized(bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
LLVM_ABI bool isInteger() const
Returns true if and only if the number is an exact integer.
friend class llvm::FloatRepr
LLVM_ABI IEEEFloat(const fltSemantics &)
LLVM_ABI opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode)
LLVM_ABI friend int ilogb(const IEEEFloat &Arg)
LLVM_ABI opStatus next(bool nextDown)
IEEE-754R 5.3.1: nextUp/nextDown.
bool isInfinity() const
IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
const fltSemantics & getSemantics() const
bool isZero() const
Returns true if and only if the float is plus or minus zero.
LLVM_ABI bool isSignaling() const
Returns true if and only if the float is a signaling NaN.
LLVM_ABI void makeZero(bool Neg=false)
LLVM_ABI opStatus convert(const fltSemantics &, roundingMode, bool *)
IEEEFloat::convert - convert a value of one floating point type to another.
LLVM_ABI void changeSign()
LLVM_ABI bool isDenormal() const
IEEE-754R isSubnormal(): Returns true if and only if the float is a denormal.
LLVM_ABI opStatus convertToInteger(MutableArrayRef< integerPart >, unsigned int, bool, roundingMode, bool *) const
LLVM_ABI bool isSmallest() const
Returns true if and only if the number has the smallest possible non-zero magnitude in the current se...
An opaque object representing a hash code.
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
A self-contained host- and target-independent arbitrary-precision floating-point software implementat...
static constexpr opStatus opInexact
LLVM_ABI SlowDynamicAPInt abs(const SlowDynamicAPInt &X)
Redeclarations of friend declarations above to make it discoverable by lookups.
static constexpr fltCategory fcNaN
static constexpr opStatus opDivByZero
constexpr const llvm::fltSemantics & EnumToSemanticsCE(APFloatBase::Semantics S)
static constexpr opStatus opOverflow
static constexpr cmpResult cmpLessThan
const char unit< Period >::value[]
static void tcSetLeastSignificantBits(APInt::WordType *dst, unsigned parts, unsigned bits)
static constexpr roundingMode rmTowardPositive
static constexpr uninitializedTag uninitialized
static constexpr fltCategory fcZero
static constexpr opStatus opOK
void initFromAPIntForSemantics(FloatRepr R, const APInt &api)
static constexpr cmpResult cmpGreaterThan
static constexpr unsigned integerPartWidth
LLVM_ABI hash_code hash_value(const IEEEFloat &Arg)
APFloatBase::ExponentType ExponentType
static constexpr fltCategory fcNormal
APInt bitcastForSemantics(FloatRepr R)
static constexpr opStatus opInvalidOp
APFloatBase::opStatus opStatus
LLVM_ABI IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM)
APFloatBase::uninitializedTag uninitializedTag
static constexpr cmpResult cmpUnordered
static constexpr roundingMode rmTowardNegative
APFloatBase::roundingMode roundingMode
APFloatBase::cmpResult cmpResult
static constexpr fltCategory fcInfinity
static constexpr roundingMode rmNearestTiesToAway
static constexpr roundingMode rmTowardZero
static constexpr opStatus opUnderflow
static constexpr roundingMode rmNearestTiesToEven
LLVM_ABI int ilogb(const IEEEFloat &Arg)
static constexpr cmpResult cmpEqual
LLVM_ABI IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
static std::pair< APFloat, APFloat > fastTwoSum(APFloat X, APFloat Y)
APFloatBase::integerPart integerPart
FormattedNumber decValue(uint64_t N, unsigned Width=DEC_WIDTH)
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)
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
static const char infinityL[]
static constexpr APFloatBase::integerPart PowerOfFiveParts[]
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
static constexpr unsigned int partCountForBits(unsigned int bits)
static unsigned int HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
static unsigned int powerOf5(APFloatBase::integerPart *dst, unsigned int power)
unsigned hexDigitValue(char C)
Interpret the given character C as a hexadecimal digit and return its value.
static APFloat harrisonUlp(const APFloat &X)
static constexpr APFloatBase::ExponentType exponentZero(const fltSemantics &semantics)
APFloat abs(APFloat X)
Returns the absolute value of the argument.
static Expected< int > totalExponent(StringRef::iterator p, StringRef::iterator end, int exponentAdjustment)
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
static char * writeUnsignedDecimal(char *dst, unsigned int n)
constexpr unsigned maxExponent
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
static constexpr unsigned NumPow5PartsOnStack
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
static const char infinityU[]
static constexpr unsigned PowerOfFivePartCounts[]
lostFraction
Enum that represents what fraction of the LSB truncated bits of an fp number represent.
static Error interpretDecimal(StringRef::iterator begin, StringRef::iterator end, decimalInfo *D)
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.
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.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static unsigned int powerOfFivePartsForExponent(unsigned int power)
static constexpr APFloatBase::ExponentType exponentNaN(const fltSemantics &semantics)
static Error createError(const Twine &Err)
static APInt pow5AsAPInt(unsigned Exp, unsigned Width)
5^Exp zero-extended to Width bits.
static lostFraction shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
static unsigned shortestDigitCount(const APFloat &Val)
Minimum number of significant decimal digits a string needs to parse back (round-to-nearest-even) to ...
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
static const char hexDigitsUpper[]
static unsigned int decDigitValue(unsigned int c)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
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...
static lostFraction combineLostFractions(lostFraction moreSignificant, lostFraction lessSignificant)
static Expected< StringRef::iterator > skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end, StringRef::iterator *dot)
RoundingMode
Rounding mode.
ArrayRef(const T &OneElt) -> ArrayRef< T >
static constexpr APFloatBase::ExponentType exponentInf(const fltSemantics &semantics)
static lostFraction lostFractionThroughTruncation(const APFloatBase::integerPart *parts, unsigned int partCount, unsigned int bits)
APFloat neg(APFloat X)
Returns the negated value of the argument.
static APFloatBase::integerPart ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits, bool isNearest)
static char * writeSignedDecimal(char *dst, int value)
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
static Expected< lostFraction > trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, unsigned int digitValue)
void consumeError(Error Err)
Consume a Error without doing anything.
static Expected< int > readExponent(StringRef::iterator begin, StringRef::iterator end)
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
static const char hexDigitsLower[]
const char * lastSigDigit
const char * firstSigDigit
void(* initFromAPInt)(FloatRepr, const APInt &)
APFloatBase::ExponentType maxExponent
fltNonfiniteBehavior nonFiniteBehavior
APFloatBase::ExponentType minExponent
fltNanEncoding nanEncoding
bool hasExplicitIntegerBit
APInt(* bitcastToAPInt)(FloatRepr)