1//===-- APFloat.cpp - Implement APFloat class -----------------------------===// 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 7//===----------------------------------------------------------------------===// 9// This file implements a class to represent arbitrary precision floating 10// point values and provide a variety of arithmetic operations on them. 12//===----------------------------------------------------------------------===// 23#include "llvm/Config/llvm-config.h" 31#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \ 33 if (usesLayout<IEEEFloat>(getSemantics())) \ 34 return U.IEEE.METHOD_CALL; \ 35 if (usesLayout<DoubleAPFloat>(getSemantics())) \ 36 return U.Double.METHOD_CALL; \ 37 llvm_unreachable("Unexpected semantics"); \
42/// A macro used to combine two fcCategory enums into one key which can be used 43/// in a switch statement to classify how the interaction of two APFloat's 44/// categories affects an operation. 46/// TODO: If clang source code is ever allowed to use constexpr in its own 47/// codebase, change this into a static inline function. 48#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs)) 50/* Assumed in hexadecimal significand parsing, and conversion to 51 hexadecimal strings. */ 56// How the nonfinite values Inf and NaN are represented. 58// Represents standard IEEE 754 behavior. A value is nonfinite if the 59// exponent field is all 1s. In such cases, a value is Inf if the 60// significand bits are all zero, and NaN otherwise 63// This behavior is present in the Float8ExMyFN* types (Float8E4M3FN, 64// Float8E5M2FNUZ, Float8E4M3FNUZ, and Float8E4M3B11FNUZ). There is no 65// representation for Inf, and operations that would ordinarily produce Inf 66// produce NaN instead. 67// The details of the NaN representation(s) in this form are determined by the 68// `fltNanEncoding` enum. We treat all NaNs as quiet, as the available 69// encodings do not distinguish between signalling and quiet NaN. 72// This behavior is present in Float6E3M2FN, Float6E2M3FN, and 73// Float4E2M1FN types, which do not support Inf or NaN values. 77// How NaN values are represented. This is curently only used in combination 78// with fltNonfiniteBehavior::NanOnly, and using a variant other than IEEE 79// while having IEEE non-finite behavior is liable to lead to unexpected 82// Represents the standard IEEE behavior where a value is NaN if its 83// exponent is all 1s and the significand is non-zero. 86// Represents the behavior in the Float8E4M3FN floating point type where NaN 87// is represented by having the exponent and mantissa set to all 1s. 88// This behavior matches the FP8 E4M3 type described in 89// https://arxiv.org/abs/2209.05433. We treat both signed and unsigned NaNs 90// as non-signalling, although the paper does not state whether the NaN 91// values are signalling or not. 94// Represents the behavior in Float8E{5,4}E{2,3}FNUZ floating point types 95// where NaN is represented by a sign bit of 1 and all 0s in the exponent 96// and mantissa (i.e. the negative zero encoding in a IEEE float). Since 97// there is only one NaN value, it is treated as quiet NaN. This matches the 98// behavior described in https://arxiv.org/abs/2206.02915 . 102/* Represents floating point arithmetic semantics. */ 104/* The largest E such that 2^E is representable; this matches the 105 definition of IEEE 754. */ 108/* The smallest E such that 2^E is a normalized number; this 109 matches the definition of IEEE 754. */ 112/* Number of bits in the significand. This includes the integer 116/* Number of bits actually used in the semantics. */ 123/* Whether this semantics has an encoding for Zero */ 126/* Whether this semantics can represent signed values */ 287returnA.maxExponent <=
B.maxExponent &&
A.minExponent >=
B.minExponent &&
288A.precision <=
B.precision;
297/* A tight upper bound on number of parts required to hold the value 300 power * 815 / (351 * integerPartWidth) + 1 302 However, whilst the result may require only this many parts, 303 because we are multiplying two values to get it, the 304 multiplication may require an extra part with the excess part 305 being zero (consider the trivial case of 1 * 1, tcFullMultiply 306 requires two parts to hold the single-part result). So we add an 307 extra one to guarantee enough space whilst multiplying. */ 331// The max FP value is pow(2, MaxExponent) * (1 + MaxFraction), so we need 332// at least one more bit than the MaxExponent to hold the max FP value. 334// Extra sign bit needed. 358// Exponent range must be larger. 359if (Src.maxExponent >= Dst.maxExponent || Src.minExponent <= Dst.minExponent)
362// If the mantissa is long enough, the result value could still be denormal 363// with a larger exponent range. 365// FIXME: This condition is probably not accurate but also shouldn't be a 366// practical concern with existing types. 367return Dst.precision >= Src.precision;
395/* A bunch of private, handy routines. */ 406/* Returns 0U-9U. Return values >= 10U are not digits. */ 407staticinlineunsignedint 413/* Return the value of a decimal exponent of the form 416 If the exponent overflows, returns a large exponent with the 421unsignedint absExponent;
422constunsignedint overlargeExponent = 24000;
/* FIXME. */ 425// Treat no exponent as 0 to match binutils 426if (p == end || ((*p ==
'-' || *p ==
'+') && (p + 1) == end)) {
430 isNegative = (*p ==
'-');
431if (*p ==
'-' || *p ==
'+') {
438if (absExponent >= 10U)
441for (; p != end; ++p) {
448 absExponent = absExponent * 10U +
value;
449if (absExponent >= overlargeExponent) {
450 absExponent = overlargeExponent;
456return -(int) absExponent;
458return (
int) absExponent;
461/* This is ugly and needs cleaning up, but I don't immediately see 462 how whilst remaining safe. */ 465int exponentAdjustment) {
467bool negative, overflow;
474if (*p ==
'-' || *p ==
'+') {
480 unsignedExponent = 0;
482for (; p != end; ++p) {
489 unsignedExponent = unsignedExponent * 10 +
value;
490if (unsignedExponent > 32767) {
496if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
500 exponent = unsignedExponent;
502 exponent = -exponent;
503 exponent += exponentAdjustment;
504if (exponent > 32767 || exponent < -32768)
509 exponent = negative ? -32768: 32767;
519while (p != end && *p ==
'0')
522if (p != end && *p ==
'.') {
528while (p != end && *p ==
'0')
535/* Given a normal decimal floating point number of the form 539 where the decimal point and exponent are optional, fill out the 540 structure D. Exponent is appropriate if the significand is 541 treated as an integer, and normalizedExponent if the significand 542 is taken to have the decimal point after a single leading 545 If the value is zero, V->firstSigDigit points to a non-digit, and 546 the return exponent is zero. 561return PtrOrErr.takeError();
566D->normalizedExponent = 0;
568for (; p != end; ++p) {
581if (*p !=
'e' && *p !=
'E')
582returncreateError(
"Invalid character in significand");
585if (dot != end && p - begin == 1)
588/* p points to the first non-digit in the string */ 591return ExpOrErr.takeError();
592D->exponent = *ExpOrErr;
594/* Implied decimal point? */ 599/* If number is all zeroes accept any exponent. */ 600if (p !=
D->firstSigDigit) {
601/* Drop insignificant trailing zeroes. */ 606while (p != begin && *p ==
'0');
607while (p != begin && *p ==
'.');
610/* Adjust the exponents for any decimal point. */ 612D->normalizedExponent = (
D->exponent +
614 - (dot >
D->firstSigDigit && dot < p)));
621/* Return the trailing fraction of a hexadecimal number. 622 DIGITVALUE is the first hex digit of the fraction, P points to 626unsignedint digitValue) {
629/* If the first trailing digit isn't 0 or 8 we can work out the 630 fraction immediately. */ 633elseif (digitValue < 8 && digitValue > 0)
636// Otherwise we need to find the first non-zero digit. 637while (p != end && (*p ==
'0' || *p ==
'.'))
641returncreateError(
"Invalid trailing hexadecimal fraction!");
643 hexDigit = hexDigitValue(*p);
645/* If we ran off the end it is exactly zero or one-half, otherwise 647if (hexDigit == UINT_MAX)
653/* Return the fraction lost were a bignum truncated losing the least 654 significant BITS bits. */ 657unsignedint partCount,
664/* Note this is guaranteed true if bits == 0, or LSB == UINT_MAX. */ 676/* Shift DST right BITS bits noting lost fraction. */ 689/* Combine the effect of two lost fractions. */ 701return moreSignificant;
704/* The error from the true value, in half-ulps, on multiplying two 705 floating point numbers, which differ from the value they 706 approximate by at most HUE1 and HUE2 half-ulps, is strictly less 707 than the returned value. 709 See "How to Read Floating Point Numbers Accurately" by William D 712HUerrBound(
bool inexactMultiply,
unsignedint HUerr1,
unsignedint HUerr2)
714assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
716if (HUerr1 + HUerr2 == 0)
717return inexactMultiply * 2;
/* <= inexactMultiply half-ulps. */ 719return inexactMultiply + 2 * (HUerr1 + HUerr2);
722/* The number of ulps from the boundary (zero, or half if ISNEAREST) 723 when the least significant BITS are truncated. BITS cannot be 728unsignedintcount, partBits;
745if (part - boundary <= boundary - part)
746return part - boundary;
748return boundary - part;
751if (part == boundary) {
757 }
elseif (part == boundary - 1) {
768/* Place pow(5, power) in DST, and return the number of parts used. 769 DST must be at least one part larger than size of the answer. */ 774 pow5s[0] = 78125 * 5;
776unsignedint partsCount = 1;
784 *p1 = firstEightPowers[power & 7];
790for (
unsignedint n = 0; power; power >>= 1, n++) {
791/* Calculate pow(5,pow(2,n+3)) if we haven't yet. */ 794 partsCount, partsCount);
796if (pow5[partsCount - 1] == 0)
804 result += partsCount;
805if (p2[result - 1] == 0)
808/* Now result is in p1 with partsCount parts and p2 is scratch 824/* Zero at the end to avoid modular arithmetic when adding one; used 825 when rounding up during hexadecimal output. */ 833/* Write out an integerPart in hexadecimal, starting with the most 834 significant nibble. Write out exactly COUNT hexdigits, return 838constchar *hexDigitChars)
840unsignedint result =
count;
846 dst[
count] = hexDigitChars[part & 0xf];
853/* Write out an unsigned decimal integer. */ 871/* Write out a signed decimal integer. */ 886void IEEEFloat::initialize(
constfltSemantics *ourSemantics) {
889 semantics = ourSemantics;
895void IEEEFloat::freeSignificand() {
897delete [] significand.parts;
900void IEEEFloat::assign(
const IEEEFloat &rhs) {
901assert(semantics == rhs.semantics);
904 category = rhs.category;
905 exponent = rhs.exponent;
907 copySignificand(rhs);
910void IEEEFloat::copySignificand(
const IEEEFloat &rhs) {
912assert(rhs.partCount() >= partCount());
918/* Make this number a NaN, with an arbitrary but deterministic value 919 for the significand. If double or longer, this is a signalling NaN, 920 which may not be ideal. If float, this is QNaN(0). */ 927"This floating point format does not support signed values");
931 exponent = exponentNaN();
934unsigned numParts = partCount();
938// Finite-only types do not distinguish signalling and quiet NaN, so 939// make them all signalling. 947 fill = &fill_storage;
950// Set the significand bits to the fill. 957// Zero out the excess bits of the significand. 958unsigned bitsToPreserve = semantics->
precision - 1;
959unsigned part = bitsToPreserve / 64;
960 bitsToPreserve %= 64;
961 significand[part] &= ((1ULL << bitsToPreserve) - 1);
962for (part++; part != numParts; ++part)
963 significand[part] = 0;
970// We always have to clear the QNaN bit to make it an SNaN. 973// If there are no bits set in the payload, we have to set 974// *something* to make it a NaN instead of an infinity; 975// conventionally, this is the next bit down from the QNaN bit. 979// The only NaN is a quiet NaN, and it has no bits sets in the significand. 982// We always have to set the QNaN bit to make it a QNaN. 986// For x87 extended precision, we want to make a NaN, not a 987// pseudo-NaN. Maybe we should expose the ability to make 995if (semantics != rhs.semantics) {
997 initialize(rhs.semantics);
1008 semantics = rhs.semantics;
1009 significand = rhs.significand;
1010 exponent = rhs.exponent;
1011 category = rhs.category;
1025// The smallest number by magnitude in our format will be the smallest 1026// denormal, i.e. the floating point number with exponent being minimum 1027// exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0). 1029 significandMSB() == 0;
1034 isSignificandAllZerosExceptMSB();
1037unsignedint IEEEFloat::getNumHighBits()
const{
1041// Compute how many bits are used in the final word. 1042// When precision is just 1, it represents the 'Pth' 1043// Precision bit and not the actual significand bit. 1044constunsignedint NumHighBits = (semantics->
precision > 1)
1050bool IEEEFloat::isSignificandAllOnes()
const{
1051// Test if the significand excluding the integral bit is all ones. This allows 1052// us to test for binade boundaries. 1055for (
unsigned i = 0; i < PartCount - 1; i++)
1059// Set the unused high bits to all ones when we compare. 1060constunsigned NumHighBits = getNumHighBits();
1061assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1062"Can not have more high bits to fill than integerPartWidth");
1065if ((semantics->
precision <= 1) || (~(Parts[PartCount - 1] | HighBitFill)))
1071bool IEEEFloat::isSignificandAllOnesExceptLSB()
const{
1072// Test if the significand excluding the integral bit is all ones except for 1073// the least significant bit. 1080for (
unsigned i = 0; i < PartCount - 1; i++) {
1081if (~Parts[i] & ~
unsigned{!i})
1085// Set the unused high bits to all ones when we compare. 1086constunsigned NumHighBits = getNumHighBits();
1087assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1088"Can not have more high bits to fill than integerPartWidth");
1091if (~(Parts[PartCount - 1] | HighBitFill | 0x1))
1097bool IEEEFloat::isSignificandAllZeros()
const{
1098// Test if the significand excluding the integral bit is all zeros. This 1099// allows us to test for binade boundaries. 1103for (
unsigned i = 0; i < PartCount - 1; i++)
1107// Compute how many bits are used in the final word. 1108constunsigned NumHighBits = getNumHighBits();
1110"clear than integerPartWidth");
1111constintegerPart HighBitMask = ~integerPart(0) >> NumHighBits;
1113if ((semantics->
precision > 1) && (Parts[PartCount - 1] & HighBitMask))
1119bool IEEEFloat::isSignificandAllZerosExceptMSB()
const{
1123for (
unsigned i = 0; i < PartCount - 1; i++) {
1128constunsigned NumHighBits = getNumHighBits();
1131return ((semantics->
precision <= 1) || (Parts[PartCount - 1] == MSBMask));
1138// The largest number by magnitude in our format will be the floating point 1139// number with maximum exponent and with significand that is all ones except 1142 ? isSignificandAllOnesExceptLSB()
1145// The largest number by magnitude in our format will be the floating point 1146// number with maximum exponent and with significand that is all ones. 1147return IsMaxExp && isSignificandAllOnes();
1152// This could be made more efficient; I'm going for obviously correct. 1162if (semantics != rhs.semantics ||
1163 category != rhs.category ||
1172return std::equal(significandParts(), significandParts() + partCount(),
1173 rhs.significandParts());
1177 initialize(&ourSemantics);
1182 significandParts()[0] =
value;
1187 initialize(&ourSemantics);
1188// The Float8E8MOFNU format does not have a representation 1189// for zero. So, use the closest representation instead. 1190// Moreover, the all-zero encoding represents a valid 1191// normal value (which is the smallestNormalized here). 1192// Hence, we call makeSmallestNormalized (where category is 1193// 'fcNormal') instead of makeZero (where category is 'fcZero'). 1197// Delegate to the previous constructor, because later copy constructor may 1198// actually inspects category, which can't be garbage. 1203 initialize(rhs.semantics);
1208 *
this = std::move(rhs);
1213unsignedint IEEEFloat::partCount()
const{
1218returnconst_cast<IEEEFloat *
>(
this)->significandParts();
1223return significand.parts;
1225return &significand.part;
1228void IEEEFloat::zeroSignificand() {
1232/* Increment an fcNormal floating point number's significand. */ 1233void IEEEFloat::incrementSignificand() {
1238/* Our callers should never cause us to overflow. */ 1243/* Add the significand of the RHS. Returns the carry flag. */ 1247 parts = significandParts();
1249assert(semantics == rhs.semantics);
1250assert(exponent == rhs.exponent);
1252returnAPInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
1255/* Subtract the significand of the RHS with a borrow flag. Returns 1261 parts = significandParts();
1263assert(semantics == rhs.semantics);
1264assert(exponent == rhs.exponent);
1270/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it 1271 on to the full-precision result of the multiplication. Returns the 1273lostFraction IEEEFloat::multiplySignificand(
const IEEEFloat &rhs,
1276unsignedint omsb;
// One, not zero, based MSB. 1277unsignedint partsCount, newPartsCount, precision;
1284assert(semantics == rhs.semantics);
1288// Allocate space for twice as many bits as the original significand, plus one 1289// extra bit for the addition to overflow into. 1292if (newPartsCount > 4)
1295 fullSignificand = scratch;
1297 lhsSignificand = significandParts();
1298 partsCount = partCount();
1301 rhs.significandParts(), partsCount, partsCount);
1304 omsb =
APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1305 exponent += rhs.exponent;
1307// Assume the operands involved in the multiplication are single-precision 1308// FP, and the two multiplicants are: 1309// *this = a23 . a22 ... a0 * 2^e1 1310// rhs = b23 . b22 ... b0 * 2^e2 1311// the result of multiplication is: 1312// *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2) 1313// Note that there are three significant bits at the left-hand side of the 1314// radix point: two for the multiplication, and an overflow bit for the 1315// addition (that will always be zero at this point). Move the radix point 1316// toward left by two bits, and adjust exponent accordingly. 1319if (!ignoreAddend && addend.isNonZero()) {
1320// The intermediate result of the multiplication has "2 * precision" 1321// signicant bit; adjust the addend to be consistent with mul result. 1323 Significand savedSignificand = significand;
1327unsignedint extendedPrecision;
1329// Normalize our MSB to one below the top bit to allow for overflow. 1330 extendedPrecision = 2 * precision + 1;
1331if (omsb != extendedPrecision - 1) {
1332assert(extendedPrecision > omsb);
1334 (extendedPrecision - 1) - omsb);
1335 exponent -= (extendedPrecision - 1) - omsb;
1338/* Create new semantics. */ 1339 extendedSemantics = *semantics;
1340 extendedSemantics.
precision = extendedPrecision;
1342if (newPartsCount == 1)
1343 significand.part = fullSignificand[0];
1345 significand.parts = fullSignificand;
1346 semantics = &extendedSemantics;
1348// Make a copy so we can convert it to the extended semantics. 1349// Note that we cannot convert the addend directly, as the extendedSemantics 1350// is a local variable (which we take a reference to). 1357// Shift the significand of the addend right by one bit. This guarantees 1358// that the high bit of the significand is zero (same as fullSignificand), 1359// so the addition will overflow (if it does overflow at all) into the top bit. 1360 lost_fraction = extendedAddend.shiftSignificandRight(1);
1362"Lost precision while shifting addend for fused-multiply-add.");
1364 lost_fraction = addOrSubtractSignificand(extendedAddend,
false);
1366/* Restore our state. */ 1367if (newPartsCount == 1)
1368 fullSignificand[0] = significand.part;
1369 significand = savedSignificand;
1370 semantics = savedSemantics;
1372 omsb =
APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1375// Convert the result having "2 * precision" significant-bits back to the one 1376// having "precision" significant-bits. First, move the radix point from 1377// poision "2*precision - 1" to "precision - 1". The exponent need to be 1378// adjusted by "2*precision - 1" - "precision - 1" = "precision". 1379 exponent -= precision + 1;
1381// In case MSB resides at the left-hand side of radix point, shift the 1382// mantissa right by some amount to make sure the MSB reside right before 1383// the radix point (i.e. "MSB . rest-significant-bits"). 1385// Note that the result is not normalized when "omsb < precision". So, the 1386// caller needs to call IEEEFloat::normalize() if normalized value is 1388if (omsb > precision) {
1389unsignedint bits, significantParts;
1392 bits = omsb - precision;
1394 lf =
shiftRight(fullSignificand, significantParts, bits);
1401if (newPartsCount > 4)
1402delete [] fullSignificand;
1404return lost_fraction;
1407lostFraction IEEEFloat::multiplySignificand(
const IEEEFloat &rhs) {
1408// When the given semantics has zero, the addend here is a zero. 1409// i.e . it belongs to the 'fcZero' category. 1410// But when the semantics does not support zero, we need to 1411// explicitly convey that this addend should be ignored 1412// for multiplication. 1416/* Multiply the significands of LHS and RHS to DST. */ 1417lostFraction IEEEFloat::divideSignificand(
const IEEEFloat &rhs) {
1418unsignedint bit, i, partsCount;
1424assert(semantics == rhs.semantics);
1426 lhsSignificand = significandParts();
1427 rhsSignificand = rhs.significandParts();
1428 partsCount = partCount();
1435 divisor = dividend + partsCount;
1437/* Copy the dividend and divisor as they will be modified in-place. */ 1438for (i = 0; i < partsCount; i++) {
1439 dividend[i] = lhsSignificand[i];
1440 divisor[i] = rhsSignificand[i];
1441 lhsSignificand[i] = 0;
1444 exponent -= rhs.exponent;
1446unsignedint precision = semantics->
precision;
1448/* Normalize the divisor. */ 1449 bit = precision -
APInt::tcMSB(divisor, partsCount) - 1;
1455/* Normalize the dividend. */ 1456 bit = precision -
APInt::tcMSB(dividend, partsCount) - 1;
1462/* Ensure the dividend >= divisor initially for the loop below. 1463 Incidentally, this means that the division loop below is 1464 guaranteed to set the integer bit to one. */ 1472for (bit = precision; bit; bit -= 1) {
1481/* Figure out the lost fraction. */ 1496return lost_fraction;
1499unsignedint IEEEFloat::significandMSB()
const{
1503unsignedint IEEEFloat::significandLSB()
const{
1507/* Note that a zero result is NOT normalized to fcZero. */ 1508lostFraction IEEEFloat::shiftSignificandRight(
unsignedint bits) {
1509/* Our exponent should not overflow. */ 1514returnshiftRight(significandParts(), partCount(), bits);
1517/* Shift the significand left BITS bits, subtract BITS from its exponent. */ 1518void IEEEFloat::shiftSignificandLeft(
unsignedint bits) {
1519assert(bits < semantics->precision ||
1520 (semantics->
precision == 1 && bits <= 1));
1523unsignedint partsCount = partCount();
1535assert(semantics == rhs.semantics);
1539compare = exponent - rhs.exponent;
1541/* If exponents are equal, do an unsigned bignum comparison of the 1555/* Set the least significant BITS bits of a bignum, clear the 1572/* Handle overflow. Sign is preserved. We either become infinity or 1573 the largest finite number. */ 1589/* Otherwise we become the largest finite number. */ 1601/* Returns TRUE if, when truncating the current number, with BIT the 1602 new LSB, with the given lost fraction and rounding mode, the result 1603 would need to be rounded away from zero (i.e., by increasing the 1604 signficand). This routine must work for fcZero of both signs, and 1605 fcNormal numbers. */ 1606bool IEEEFloat::roundAwayFromZero(
roundingMode rounding_mode,
1608unsignedint bit)
const{
1609/* NaNs and infinities should not have lost fractions. */ 1612/* Current callers never pass this so we don't handle it. */ 1615switch (rounding_mode) {
1623/* Our zeroes don't have a significand to test. */ 1646unsignedint omsb;
/* One, not zero, based MSB. */ 1652/* Before rounding normalize the exponent of fcNormal numbers. */ 1653 omsb = significandMSB() + 1;
1656/* OMSB is numbered from 1. We want to place it in the integer 1657 bit numbered PRECISION if possible, with a compensating change in 1659 exponentChange = omsb - semantics->
precision;
1661/* If the resulting exponent is too high, overflow according to 1662 the rounding mode. */ 1663if (exponent + exponentChange > semantics->
maxExponent)
1664return handleOverflow(rounding_mode);
1666/* Subnormal numbers have exponent minExponent, and their MSB 1667 is forced based on that. */ 1668if (exponent + exponentChange < semantics->minExponent)
1669 exponentChange = semantics->
minExponent - exponent;
1671/* Shifting left is easy as we don't lose precision. */ 1672if (exponentChange < 0) {
1675 shiftSignificandLeft(-exponentChange);
1680if (exponentChange > 0) {
1683/* Shift right and capture any new lost fraction. */ 1684 lf = shiftSignificandRight(exponentChange);
1688/* Keep OMSB up-to-date. */ 1689if (omsb > (
unsigned) exponentChange)
1690 omsb -= exponentChange;
1696// The all-ones values is an overflow if NaN is all ones. If NaN is 1697// represented by negative zero, then it is a valid finite value. 1700 exponent == semantics->
maxExponent && isSignificandAllOnes())
1701return handleOverflow(rounding_mode);
1703/* Now round the number according to rounding_mode given the lost 1706/* As specified in IEEE 754, since we do not trap we do not report 1707 underflow for exact results. */ 1709/* Canonicalize zeroes. */ 1721/* Increment the significand if we're rounding away from zero. */ 1722if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1726 incrementSignificand();
1727 omsb = significandMSB() + 1;
1729/* Did the significand increment overflow? */ 1730if (omsb == (
unsigned) semantics->
precision + 1) {
1731/* Renormalize by incrementing the exponent and shifting our 1732 significand right one. However if we already have the 1733 maximum exponent we overflow to infinity. */ 1735// Invoke overflow handling with a rounding mode that will guarantee 1736// that the result gets turned into the correct infinity representation. 1737// This is needed instead of just setting the category to infinity to 1738// account for 8-bit floating point types that have no inf, only NaN. 1741 shiftSignificandRight(1);
1746// The all-ones values is an overflow if NaN is all ones. If NaN is 1747// represented by negative zero, then it is a valid finite value. 1750 exponent == semantics->
maxExponent && isSignificandAllOnes())
1751return handleOverflow(rounding_mode);
1754/* The normal case - we were and are not denormal, and any 1755 significand increment above didn't overflow. */ 1759/* We have a non-zero denormal. */ 1760assert(omsb < semantics->precision);
1762/* Canonicalize zeroes. */ 1767// This condition handles the case where the semantics 1768// does not have zero but uses the all-zero encoding 1769// to represent the smallest normal value. 1774/* The fcZero case is a denormal that underflowed to zero. */ 1816/* Sign depends on rounding mode; handled by caller. */ 1820/* Differently signed infinities can only be validly 1834/* Add or subtract two normal numbers. */ 1835lostFraction IEEEFloat::addOrSubtractSignificand(
const IEEEFloat &rhs,
1841/* Determine if the operation on the absolute values is effectively 1842 an addition or subtraction. */ 1843subtract ^=
static_cast<bool>(sign ^ rhs.sign);
1845/* Are we bigger exponent-wise than the RHS? */ 1846 bits = exponent - rhs.exponent;
1848/* Subtraction is more subtle than one might naively expect. */ 1852"This floating point format does not support signed values");
1859 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1860 shiftSignificandLeft(1);
1862 lost_fraction = shiftSignificandRight(-bits - 1);
1863 temp_rhs.shiftSignificandLeft(1);
1866// Should we reverse the subtraction. 1868 carry = temp_rhs.subtractSignificand
1870 copySignificand(temp_rhs);
1873 carry = subtractSignificand
1877/* Invert the lost fraction - it was on the RHS and 1884/* The code above is intended to ensure that no borrow is 1892 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1893 carry = addSignificand(temp_rhs);
1895 lost_fraction = shiftSignificandRight(-bits);
1896 carry = addSignificand(rhs);
1899/* We have a guard bit; generating a carry cannot happen. */ 1904return lost_fraction;
1922 sign ^= rhs.sign;
// restore the original sign 1966 sign ^= rhs.sign;
// restore the original sign 2072 return
opDivByZero;
// fake status, indicating this is not a special case 2078// With NaN-as-negative-zero, neither NaN or negative zero can change 2083/* Look mummy, this one's easy. */ 2087/* Normalized addition or subtraction. */ 2093 fs = addOrSubtractSpecials(rhs,
subtract);
2095/* This return code means it was not a simple case. */ 2099 lost_fraction = addOrSubtractSignificand(rhs,
subtract);
2100 fs = normalize(rounding_mode, lost_fraction);
2102/* Can only be zero if we lost no fraction. */ 2106/* If two numbers add (exactly) to zero, IEEE 754 decrees it is a 2107 positive zero unless rounding to minus infinity, except that 2108 adding two like-signed zeroes gives that zero. */ 2112// NaN-in-negative-zero means zeros need to be normalized to +0. 2120/* Normalized addition. */ 2123return addOrSubtract(rhs, rounding_mode,
false);
2126/* Normalized subtraction. */ 2129return addOrSubtract(rhs, rounding_mode,
true);
2132/* Normalized multiply. */ 2138 fs = multiplySpecials(rhs);
2144 fs = normalize(rounding_mode, lost_fraction);
2152/* Normalized divide. */ 2158 fs = divideSpecials(rhs);
2164 fs = normalize(rounding_mode, lost_fraction);
2172/* Normalized remainder. */ 2175unsignedint origSign = sign;
2177// First handle the special cases. 2178 fs = remainderSpecials(rhs);
2184// Make sure the current value is less than twice the denom. If the addition 2185// did not succeed (an overflow has happened), which means that the finite 2186// value we currently posses must be less than twice the denom (as we are 2187// using the same semantics). 2194// Lets work with absolute numbers. 2200// To calculate the remainder we use the following scheme. 2202// The remainder is defained as follows: 2204// remainder = numer - rquot * denom = x - r * p 2206// Where r is the result of: x/p, rounded toward the nearest integral value 2207// (with halfway cases rounded toward the even number). 2209// Currently, (after x mod 2p): 2210// r is the number of 2p's present inside x, which is inherently, an even 2213// We may split the remaining calculation into 4 options: 2214// - if x < 0.5p then we round to the nearest number with is 0, and are done. 2215// - if x == 0.5p then we round to the nearest even number which is 0, and we 2217// - if 0.5p < x < p then we round to nearest number which is 1, and we have 2218// to subtract 1p at least once. 2219// - if x >= p then we must subtract p at least once, as x must be a 2222// By now, we were done, or we added 1 to r, which in turn, now an odd number. 2224// We can now split the remaining calculation to the following 3 options: 2225// - if x < 0.5p then we round to the nearest number with is 0, and are done. 2226// - if x == 0.5p then we round to the nearest even number. As r is odd, we 2227// must round up to the next even number. so we must subtract p once more. 2228// - if x > 0.5p (and inherently x < p) then we must round r up to the next 2229// integral, and subtract p once more. 2232// Extend the semantics to prevent an overflow/underflow or inexact result. 2246// It is simpler to work with 2x instead of 0.5p, and we do not need to lose 2255// Make VEx = this.add(this), but because we have different semantics, we do 2256// not want to `convert` again, so we just subtract PEx twice (which equals 2257// to the desired value). 2271 sign = origSign;
// IEEE754 requires this 2273// But some 8-bit floats only have positive 0. 2282/* Normalized llvm frem (C fmod). */ 2285 fs = modSpecials(rhs);
2286unsignedint origSign = sign;
2292// V can overflow to NaN with fltNonfiniteBehavior::NanOnly, so explicitly 2300// When the semantics supports zero, this loop's 2301// exit-condition is handled by the 'isFiniteNonZero' 2302// category check above. However, when the semantics 2303// does not have 'fcZero' and we have reached the 2304// minimum possible value, (and any further subtract 2305// will underflow to the same value) explicitly 2306// provide an exit-path here. 2307if (!semantics->
hasZero && this->isSmallest())
2313 sign = origSign;
// fmod requires this 2320/* Normalized fused-multiply-add. */ 2326/* Post-multiplication sign, before addition. */ 2327 sign ^= multiplicand.sign;
2329/* If and only if all arguments are normal do we need to do an 2330 extended-precision calculation. */ 2336 lost_fraction = multiplySignificand(multiplicand, addend);
2337 fs = normalize(rounding_mode, lost_fraction);
2341/* If two numbers add (exactly) to zero, IEEE 754 decrees it is a 2342 positive zero unless rounding to minus infinity, except that 2343 adding two like-signed zeroes gives that zero. */ 2350 fs = multiplySpecials(multiplicand);
2352/* FS can only be opOK or opInvalidOp. There is no more work 2353 to do in the latter case. The IEEE-754R standard says it is 2354 implementation-defined in this case whether, if ADDEND is a 2355 quiet NaN, we raise invalid op; this implementation does so. 2357 If we need to do the addition we can do so with normal 2360 fs = addOrSubtract(addend, rounding_mode,
false);
2366/* Rounding-mode correct round to integral value. */ 2371// [IEEE Std 754-2008 6.1]: 2372// The behavior of infinity in floating-point arithmetic is derived from the 2373// limiting cases of real arithmetic with operands of arbitrarily 2374// large magnitude, when such a limit exists. 2376// Operations on infinite operands are usually exact and therefore signal no 2382// [IEEE Std 754-2008 6.2]: 2383// Under default exception handling, any operation signaling an invalid 2384// operation exception and for which a floating-point result is to be 2385// delivered shall deliver a quiet NaN. 2387// [IEEE Std 754-2008 6.2]: 2388// Signaling NaNs shall be reserved operands that, under default exception 2389// handling, signal the invalid operation exception(see 7.2) for every 2390// general-computational and signaling-computational operation except for 2391// the conversions described in 5.12. 2394// [IEEE Std 754-2008 6.2]: 2395// For an operation with quiet NaN inputs, other than maximum and minimum 2396// operations, if a floating-point result is to be delivered the result 2397// shall be a quiet NaN which should be one of the input NaNs. 2399// Every general-computational and quiet-computational operation involving 2400// one or more input NaNs, none of them signaling, shall signal no 2401// exception, except fusedMultiplyAdd might signal the invalid operation 2402// exception(see 7.2). 2408// [IEEE Std 754-2008 6.3]: 2409// ... the sign of the result of conversions, the quantize operation, the 2410// roundToIntegral operations, and the roundToIntegralExact(see 5.3.1) is 2411// the sign of the first or only operand. 2415// If the exponent is large enough, we know that this value is already 2416// integral, and the arithmetic below would potentially cause it to saturate 2417// to +/-Inf. Bail out early instead. 2421// The algorithm here is quite simple: we add 2^(p-1), where p is the 2422// precision of our format, and then subtract it back off again. The choice 2423// of rounding modes for the addition/subtraction determines the rounding mode 2424// for our integral rounding as well. 2425// NOTE: When the input value is negative, we do subtraction followed by 2434 MagicConstant.sign = sign;
2436// Preserve the input sign so that we can handle the case of zero result 2440 fs =
add(MagicConstant, rounding_mode);
2442// Current value and 'MagicConstant' are both integers, so the result of the 2443// subtraction is always exact according to Sterbenz' lemma. 2444subtract(MagicConstant, rounding_mode);
2446// Restore the input sign. 2453/* Comparison requires normalized numbers. */ 2457assert(semantics == rhs.semantics);
2489if (sign == rhs.sign)
2503/* Two normal numbers. Do they have the same sign? */ 2504if (sign != rhs.sign) {
2510/* Compare absolute values; invert result if negative. */ 2524/// IEEEFloat::convert - convert a value of one floating point type to another. 2525/// The return value corresponds to the IEEE754 exceptions. *losesInfo 2526/// records whether the transformation lost information, i.e. whether 2527/// converting the result back to the original type will produce the 2528/// original value (this is almost the same as return value==fsOK, but there 2529/// are edge cases where this is not so). 2535unsignedint newPartCount, oldPartCount;
2543 oldPartCount = partCount();
2546bool X86SpecialNan =
false;
2549 (!(*significandParts() & 0x8000000000000000ULL) ||
2550 !(*significandParts() & 0x4000000000000000ULL))) {
2551// x86 has some unusual NaNs which cannot be represented in any other 2552// format; note them here. 2553 X86SpecialNan =
true;
2556// If this is a truncation of a denormal number, and the target semantics 2557// has larger exponent range than the source semantics (this can happen 2558// when truncating from PowerPC double-double to double format), the 2559// right shift could lose result mantissa bits. Adjust exponent instead 2560// of performing excessive shift. 2561// Also do a similar trick in case shifting denormal would produce zero 2562// significand as this case isn't handled correctly by normalize. 2564int omsb = significandMSB() + 1;
2565int exponentChange = omsb - fromSemantics.
precision;
2566if (exponent + exponentChange < toSemantics.
minExponent)
2567 exponentChange = toSemantics.
minExponent - exponent;
2568if (exponentChange < shift)
2569 exponentChange = shift;
2570if (exponentChange < 0) {
2571 shift -= exponentChange;
2572 exponent += exponentChange;
2573 }
elseif (omsb <= -shift) {
2574 exponentChange = omsb + shift - 1;
// leave at least one bit set 2575 shift -= exponentChange;
2576 exponent += exponentChange;
2580// If this is a truncation, perform the shift before we narrow the storage. 2586// Fix the storage so it can hold to new value. 2587if (newPartCount > oldPartCount) {
2588// The new type requires more storage; make it available. 2595 significand.parts = newParts;
2596 }
elseif (newPartCount == 1 && oldPartCount != 1) {
2597// Switch to built-in storage for a single part. 2600 newPart = significandParts()[0];
2602 significand.part = newPart;
2605// Now that we have the right storage, switch the semantics. 2606 semantics = &toSemantics;
2608// If this is an extension, perform the shift now that the storage is 2615 *losesInfo = (fs !=
opOK);
2616 }
elseif (category ==
fcNaN) {
2624// If NaN is negative zero, we need to create a new NaN to avoid converting 2632// For x87 extended precision, we want to make a NaN, not a special NaN if 2633// the input wasn't special either. 2637// Convert of sNaN creates qNaN and raises an exception (invalid op). 2638// This also guarantees that a sNaN does not become Inf on a truncation 2639// that loses all payload bits. 2651 }
elseif (category ==
fcZero &&
2653// Negative zero loses info, but positive zero doesn't. 2657// NaN is negative zero means -0 -> +0, which can lose information 2669/* Convert a floating point number to an integer according to the 2670 rounding mode. If the rounded integer value is out of range this 2671 returns an invalid operation exception and the contents of the 2672 destination parts are unspecified. If the rounded value is in 2673 range but the floating point number is not the exact integer, the C 2674 standard doesn't require an inexact exception to be raised. IEEE 2675 854 does require it so we do that. 2677 Note that for conversions to integer type the C standard requires 2678 round-to-zero to always be used. */ 2684unsignedint dstPartsCount, truncatedBits;
2688/* Handle the three special cases first. */ 2693assert(dstPartsCount <= parts.
size() &&
"Integer too big");
2697// Negative zero can't be represented as an int. 2702 src = significandParts();
2704/* Step 1: place our absolute value, with any fraction truncated, in 2707/* Our absolute value is less than one; truncate everything. */ 2709/* For exponent -1 the integer bit represents .5, look at that. 2710 For smaller exponents leftmost truncated bit is 0. */ 2711 truncatedBits = semantics->
precision -1U - exponent;
2713/* We want the most significant (exponent + 1) bits; the rest are 2715unsignedint bits = exponent + 1U;
2717/* Hopelessly large in magnitude? */ 2721if (bits < semantics->precision) {
2722/* We truncate (semantics->precision - bits) bits. */ 2723 truncatedBits = semantics->
precision - bits;
2726/* We want at least as many bits as are available. */ 2735/* Step 2: work out any lost fraction, and increment the absolute 2736 value if we would round away from zero. */ 2741 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
2749/* Step 3: check if we fit in the destination. */ 2754/* Negative numbers cannot be represented as unsigned. */ 2758/* It takes omsb bits to represent the unsigned integer value. 2759 We lose a bit for the sign, but care is needed as the 2760 maximally negative integer is a special case. */ 2765/* This case can happen because of rounding. */ 2783/* Same as convertToSignExtendedInteger, except we provide 2784 deterministic values in case of an invalid operation exception, 2785 namely zero for NaNs and the minimal or maximal value respectively 2786 for underflow or overflow. 2787 The *isExact output tells whether the result is exact, in the sense 2788 that converting it back to the original floating point type produces 2789 the original value. This is almost equivalent to result==opOK, 2790 except for negative zeroes. 2798 fs = convertToSignExtendedInteger(parts, width,
isSigned, rounding_mode,
2802unsignedint bits, dstPartsCount;
2805assert(dstPartsCount <= parts.
size() &&
"Integer too big");
2807if (category ==
fcNaN)
2822/* Convert an unsigned integer SRC to a floating point number, 2823 rounding according to ROUNDING_MODE. The sign of the floating 2824 point number is not modified. */ 2827unsignedint omsb, precision, dstCount;
2833 dst = significandParts();
2834 dstCount = partCount();
2837/* We want the most significant PRECISION bits of SRC. There may not 2838 be that many; extract what we can. */ 2839if (precision <= omsb) {
2840 exponent = omsb - 1;
2845 exponent = precision - 1;
2850return normalize(rounding_mode, lost_fraction);
2864return convertFromUnsignedParts(api.
getRawData(), partCount, rounding_mode);
2867/* Convert a two's complement integer SRC to a floating point number, 2868 rounding according to ROUNDING_MODE. ISSIGNED is true if the 2869 integer is signed, in which case it must be sign-extended. */ 2880/* If we're signed and negative negate a copy. */ 2885 status = convertFromUnsignedParts(
copy, srcCount, rounding_mode);
2889 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2895/* FIXME: should this just take a const APInt reference? */ 2909return convertFromUnsignedParts(api.
getRawData(), partCount, rounding_mode);
2913IEEEFloat::convertFromHexadecimalString(
StringRef s,
2922unsigned partsCount = partCount();
2924bool computedTrailingFraction =
false;
2926// Skip leading zeroes and any (hexa)decimal point. 2932return PtrOrErr.takeError();
2941returncreateError(
"String contains multiple dots");
2946 hex_value = hexDigitValue(*p);
2947if (hex_value == UINT_MAX)
2952// Store the number while we have space. 2957 }
elseif (!computedTrailingFraction) {
2960return FractOrErr.takeError();
2961 lost_fraction = *FractOrErr;
2962 computedTrailingFraction =
true;
2966/* Hex floats require an exponent but not a hexadecimal point. */ 2968returncreateError(
"Hex strings require an exponent");
2969if (*p !=
'p' && *p !=
'P')
2970returncreateError(
"Invalid character in significand");
2973if (dot != end && p - begin == 1)
2976/* Ignore the exponent if we are zero. */ 2977if (p != firstSignificantDigit) {
2980/* Implicit hexadecimal point? */ 2984/* Calculate the exponent adjustment implicit in the number of 2985 significant digits. */ 2986 expAdjustment =
static_cast<int>(
dot - firstSignificantDigit);
2987if (expAdjustment < 0)
2989 expAdjustment = expAdjustment * 4 - 1;
2991/* Adjust for writing the significand starting at the most 2992 significant nibble. */ 2996/* Adjust for the given exponent. */ 2999return ExpOrErr.takeError();
3000 exponent = *ExpOrErr;
3003return normalize(rounding_mode, lost_fraction);
3007IEEEFloat::roundSignificandWithExponent(
constintegerPart *decSigParts,
3008unsigned sigPartCount,
int exp,
3010unsignedint parts, pow5PartCount;
3020/* Calculate pow(5, abs(exp)). */ 3021 pow5PartCount =
powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
3023for (;; parts *= 2) {
3025unsignedint excessPrecision, truncatedBits;
3029 truncatedBits = excessPrecision;
3032 decSig.makeZero(sign);
3035 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
3037 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
3039/* Add exp, as 10^n = 5^n * 2^n. */ 3040 decSig.exponent += exp;
3044unsignedint powHUerr;
3047/* multiplySignificand leaves the precision-th bit set to 1. */ 3048 calcLostFraction = decSig.multiplySignificand(pow5);
3049 powHUerr = powStatus !=
opOK;
3051 calcLostFraction = decSig.divideSignificand(pow5);
3052/* Denormal numbers have less precision. */ 3054 excessPrecision += (semantics->
minExponent - decSig.exponent);
3055 truncatedBits = excessPrecision;
3056if (excessPrecision > calcSemantics.
precision)
3057 excessPrecision = calcSemantics.
precision;
3059/* Extra half-ulp lost in reciprocal of exponent. */ 3063/* Both multiplySignificand and divideSignificand return the 3064 result with the integer bit set. */ 3066 (decSig.significandParts(), calcSemantics.
precision - 1) == 1);
3071 excessPrecision, isNearest);
3073/* Are we guaranteed to round correctly if we truncate? */ 3074if (HUdistance >= HUerr) {
3075APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
3076 calcSemantics.
precision - excessPrecision,
3078/* Take the exponent of decSig. If we tcExtract-ed less bits 3079 above we must adjust our exponent to compensate for the 3080 implicit right shift. */ 3081 exponent = (decSig.exponent + semantics->
precision 3082 - (calcSemantics.
precision - excessPrecision));
3086return normalize(rounding_mode, calcLostFraction);
3099return std::move(Err);
3101/* Handle the quick cases. First the case of no significant digits, 3102 i.e. zero, and then exponents that are obviously too large or too 3103 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp 3104 definitely overflows if 3106 (exp - 1) * L >= maxExponent 3108 and definitely underflows to zero where 3110 (exp + 1) * L <= minExponent - precision 3112 With integer arithmetic the tightest bounds for L are 3114 93/28 < L < 196/59 [ numerator <= 256 ] 3115 42039/12655 < L < 28738/8651 [ numerator <= 65536 ] 3118// Test if we have a zero number allowing for strings with no null terminators 3119// and zero decimals with non-zero exponents. 3121// We computed firstSigDigit by ignoring all zeros and dots. Thus if 3122// D->firstSigDigit equals str.end(), every digit must be a zero and there can 3123// be at most one dot. On the other hand, if we have a zero with a non-zero 3124// exponent, then we know that D.firstSigDigit will be non-numeric. 3133/* Check whether the normalized exponent is high enough to overflow 3134 max during the log-rebasing in the max-exponent check below. */ 3135 }
elseif (
D.normalizedExponent - 1 > INT_MAX / 42039) {
3136 fs = handleOverflow(rounding_mode);
3138/* If it wasn't, then it also wasn't high enough to overflow max 3139 during the log-rebasing in the min-exponent check. Check that it 3140 won't overflow min in either check, then perform the min-exponent 3142 }
elseif (
D.normalizedExponent - 1 < INT_MIN / 42039 ||
3143 (
D.normalizedExponent + 1) * 28738 <=
3145/* Underflow to zero and round. */ 3150/* We can finally safely perform the max-exponent check. */ 3151 }
elseif ((
D.normalizedExponent - 1) * 42039
3153/* Overflow and round. */ 3154 fs = handleOverflow(rounding_mode);
3157unsignedint partCount;
3159/* A tight upper bound on number of bits required to hold an 3160 N-digit decimal integer is N * 196 / 59. Allocate enough space 3161 to hold the full significand, and an extra part required by 3163 partCount =
static_cast<unsignedint>(
D.lastSigDigit -
D.firstSigDigit) + 1;
3168/* Convert to binary efficiently - we do almost all multiplication 3169 in an integerPart. When this would overflow do we do a single 3170 bignum multiplication, and then revert again to multiplication 3171 in an integerPart. */ 3181if (p == str.
end()) {
3186if (decValue >= 10U) {
3187delete[] decSignificand;
3188returncreateError(
"Invalid character in significand");
3191 val = val * 10 + decValue;
3192/* The maximum number that can be multiplied by ten with any 3193 digit added without overflowing an integerPart. */ 3194 }
while (p <=
D.lastSigDigit && multiplier <= (~ (
integerPart) 0 - 9) / 10);
3196/* Multiply out the current part. */ 3198 partCount, partCount + 1,
false);
3200/* If we used another part (likely but not guaranteed), increase 3202if (decSignificand[partCount])
3204 }
while (p <=
D.lastSigDigit);
3207 fs = roundSignificandWithExponent(decSignificand, partCount,
3208D.exponent, rounding_mode);
3210delete [] decSignificand;
3216bool IEEEFloat::convertFromStringSpecials(
StringRef str) {
3217constsize_t MIN_NAME_SIZE = 3;
3219if (str.
size() < MIN_NAME_SIZE)
3222if (str ==
"inf" || str ==
"INFINITY" || str ==
"+Inf") {
3227bool IsNegative = str.
front() ==
'-';
3230if (str.
size() < MIN_NAME_SIZE)
3233if (str ==
"inf" || str ==
"INFINITY" || str ==
"Inf") {
3239// If we have a 's' (or 'S') prefix, then this is a Signaling NaN. 3240bool IsSignaling = str.
front() ==
's' || str.
front() ==
'S';
3243if (str.
size() < MIN_NAME_SIZE)
3250// A NaN without payload. 3252makeNaN(IsSignaling, IsNegative);
3256// Allow the payload to be inside parentheses. 3257if (str.
front() ==
'(') {
3258// Parentheses should be balanced (and not empty). 3259if (str.
size() <= 2 || str.
back() !=
')')
3265// Determine the payload number's radix. 3268if (str.
size() > 1 && tolower(str[1]) ==
'x') {
3275// Parse the payload and make the NaN. 3278makeNaN(IsSignaling, IsNegative, &Payload);
3291// Handle special cases. 3292if (convertFromStringSpecials(str))
3295/* Handle a leading minus sign. */ 3297size_t slen = str.
size();
3298 sign = *p ==
'-' ? 1 : 0;
3301"This floating point format does not support signed values");
3303if (*p ==
'-' || *p ==
'+') {
3310if (slen >= 2 && p[0] ==
'0' && (p[1] ==
'x' || p[1] ==
'X')) {
3313return convertFromHexadecimalString(
StringRef(p + 2, slen - 2),
3317return convertFromDecimalString(
StringRef(p, slen), rounding_mode);
3320/* Write out a hexadecimal representation of the floating point value 3321 to DST, which must be of sufficient size, in the C99 form 3322 [-]0xh.hhhhp[+-]d. Return the number of characters written, 3323 excluding the terminating NUL. 3325 If UPPERCASE, the output is in upper case, otherwise in lower case. 3327 HEXDIGITS digits appear altogether, rounding the value if 3328 necessary. If HEXDIGITS is 0, the minimal precision to display the 3329 number precisely is used instead. If nothing would appear after 3330 the decimal point it is suppressed. 3332 The decimal exponent is always printed and has at least one digit. 3333 Zero values display an exponent of zero. Infinities and NaNs 3334 appear as "infinity" or "nan" respectively. 3336 The above rules are as specified by C99. There is ambiguity about 3337 what the leading hexadecimal digit should be. This implementation 3338 uses whatever is necessary so that the exponent is displayed as 3339 stored. This implies the exponent will fall within the IEEE format 3340 range, and the leading hexadecimal digit will be 0 (for denormals), 3341 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with 3342 any other digits zero). 3361 dst +=
sizeofNaNU - 1;
3366 *dst++ = upperCase ?
'X':
'x';
3370 memset (dst,
'0', hexDigits - 1);
3371 dst += hexDigits - 1;
3373 *dst++ = upperCase ?
'P':
'p';
3378 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
3384returnstatic_cast<unsignedint>(dst - p);
3387/* Does the hard work of outputting the correctly rounded hexadecimal 3388 form of a normal floating point number with the specified number of 3389 hexadecimal digits. If HEXDIGITS is zero the minimum number of 3390 digits necessary to print the value precisely is output. */ 3391char *IEEEFloat::convertNormalToHexString(
char *dst,
unsignedint hexDigits,
3394unsignedintcount, valueBits, shift, partsCount, outputDigits;
3395constchar *hexDigitChars;
3401 *dst++ = upperCase ?
'X':
'x';
3406 significand = significandParts();
3407 partsCount = partCount();
3409/* +3 because the first digit only uses the single integer bit, so 3410 we have 3 virtual zero most-significant-bits. */ 3414/* The natural number of digits required ignoring trailing 3415 insignificant zeroes. */ 3416 outputDigits = (valueBits - significandLSB () + 3) / 4;
3418/* hexDigits of zero means use the required number for the 3419 precision. Otherwise, see if we are truncating. If we are, 3420 find out if we need to round away from zero. */ 3422if (hexDigits < outputDigits) {
3423/* We are dropping non-zero bits, so need to check how to round. 3424 "bits" is the number of dropped bits. */ 3428 bits = valueBits - hexDigits * 4;
3430 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
3432 outputDigits = hexDigits;
3435/* Write the digits consecutively, and start writing in the location 3436 of the hexadecimal point. We move the most significant digit 3437 left and add the hexadecimal point later. */ 3442while (outputDigits &&
count) {
3445/* Put the most significant integerPartWidth bits in "part". */ 3446if (--
count == partsCount)
3447 part = 0;
/* An imaginary higher zero part. */ 3449 part = significand[
count] << shift;
3454/* Convert as much of "part" to hexdigits as we can. */ 3457if (curDigits > outputDigits)
3458 curDigits = outputDigits;
3459 dst +=
partAsHex (dst, part, curDigits, hexDigitChars);
3460 outputDigits -= curDigits;
3466/* Note that hexDigitChars has a trailing '0'. */ 3469 *
q = hexDigitChars[hexDigitValue (*q) + 1];
3473/* Add trailing zeroes. */ 3474 memset (dst,
'0', outputDigits);
3475 dst += outputDigits;
3478/* Move the most significant digit to before the point, and if there 3479 is something after the decimal point add it. This must come 3480 after rounding above. */ 3487/* Finally output the exponent. */ 3488 *dst++ = upperCase ?
'P':
'p';
3496// NaN has no sign, fix it at zero. 3500// Normal floats need their exponent and significand hashed. 3504 Arg.significandParts(),
3505 Arg.significandParts() + Arg.partCount()));
3508// Conversion from APFloat to/from host float/double. It may eventually be 3509// possible to eliminate these and have everybody deal with APFloats, but that 3510// will take a while. This approach will not easily extend to long double. 3511// Current implementation requires integerPartWidth==64, which is correct at 3512// the moment but could be made more general. 3514// Denormals have exponent minExponent in APFloat, but minExponent-1 in 3515// the actual IEEE respresentations. We compensate for that here. 3517APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt()
const{
3524 myexponent = exponent+16383;
//bias 3525 mysignificand = significandParts()[0];
3526if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
3527 myexponent = 0;
// denormal 3528 }
elseif (category==
fcZero) {
3532 myexponent = 0x7fff;
3533 mysignificand = 0x8000000000000000ULL;
3536 myexponent = 0x7fff;
3537 mysignificand = significandParts()[0];
3541 words[0] = mysignificand;
3542 words[1] = ((
uint64_t)(sign & 1) << 15) |
3543 (myexponent & 0x7fffLL);
3544returnAPInt(80, words);
3547APInt IEEEFloat::convertPPCDoubleDoubleLegacyAPFloatToAPInt()
const{
3555// Convert number to double. To avoid spurious underflows, we re- 3556// normalize against the "double" minExponent first, and only *then* 3557// truncate the mantissa. The result of that second conversion 3558// may be inexact, but should never underflow. 3559// Declare fltSemantics before APFloat that uses it (and 3560// saves pointer to it) to ensure correct destruction order. 3572 words[0] = *
u.convertDoubleAPFloatToAPInt().getRawData();
3574// If conversion was exact or resulted in a special case, we're done; 3575// just set the second double to zero. Otherwise, re-convert back to 3576// the extended format and compute the difference. This now should 3577// convert exactly to double. 3578if (
u.isFiniteNonZero() && losesInfo) {
3588 words[1] = *
v.convertDoubleAPFloatToAPInt().getRawData();
3593returnAPInt(128, words);
3596template <const fltSemantics &S>
3597APInt IEEEFloat::convertIEEEFloatToAPInt()
const{
3601constexprunsignedint trailing_significand_bits = S.precision - 1;
3602constexprint integer_bit_part = trailing_significand_bits /
integerPartWidth;
3605constexpruint64_t significand_mask = integer_bit - 1;
3606constexprunsignedint exponent_bits =
3607 trailing_significand_bits ? (S.sizeInBits - 1 - trailing_significand_bits)
3609static_assert(exponent_bits < 64);
3617 myexponent = exponent + bias;
3618 std::copy_n(significandParts(), mysignificand.size(),
3619 mysignificand.begin());
3620if (myexponent == 1 &&
3621 !(significandParts()[integer_bit_part] & integer_bit))
3622 myexponent = 0;
// denormal 3623 }
elseif (category ==
fcZero) {
3626 myexponent = ::exponentZero(S) + bias;
3627 mysignificand.fill(0);
3632 myexponent = ::exponentInf(S) + bias;
3633 mysignificand.fill(0);
3638 myexponent = ::exponentNaN(S) + bias;
3639 std::copy_n(significandParts(), mysignificand.size(),
3640 mysignificand.begin());
3642 std::array<
uint64_t, (S.sizeInBits + 63) / 64> words;
3644 std::copy_n(mysignificand.begin(), mysignificand.size(), words.begin());
3645ifconstexpr (significand_mask != 0 || trailing_significand_bits == 0) {
3646// Clear the integer bit. 3647 words[mysignificand.size() - 1] &= significand_mask;
3649 std::fill(words_iter, words.end(),
uint64_t{0});
3650constexprsize_t last_word = words.size() - 1;
3652 << ((S.sizeInBits - 1) % 64);
3653 words[last_word] |= shifted_sign;
3654uint64_t shifted_exponent = (myexponent & exponent_mask)
3655 << (trailing_significand_bits % 64);
3656 words[last_word] |= shifted_exponent;
3657ifconstexpr (last_word == 0) {
3658returnAPInt(S.sizeInBits, words[0]);
3660returnAPInt(S.sizeInBits, words);
3663APInt IEEEFloat::convertQuadrupleAPFloatToAPInt()
const{
3665return convertIEEEFloatToAPInt<semIEEEquad>();
3668APInt IEEEFloat::convertDoubleAPFloatToAPInt()
const{
3670return convertIEEEFloatToAPInt<semIEEEdouble>();
3673APInt IEEEFloat::convertFloatAPFloatToAPInt()
const{
3675return convertIEEEFloatToAPInt<semIEEEsingle>();
3678APInt IEEEFloat::convertBFloatAPFloatToAPInt()
const{
3680return convertIEEEFloatToAPInt<semBFloat>();
3683APInt IEEEFloat::convertHalfAPFloatToAPInt()
const{
3685return convertIEEEFloatToAPInt<semIEEEhalf>();
3688APInt IEEEFloat::convertFloat8E5M2APFloatToAPInt()
const{
3690return convertIEEEFloatToAPInt<semFloat8E5M2>();
3693APInt IEEEFloat::convertFloat8E5M2FNUZAPFloatToAPInt()
const{
3695return convertIEEEFloatToAPInt<semFloat8E5M2FNUZ>();
3698APInt IEEEFloat::convertFloat8E4M3APFloatToAPInt()
const{
3700return convertIEEEFloatToAPInt<semFloat8E4M3>();
3703APInt IEEEFloat::convertFloat8E4M3FNAPFloatToAPInt()
const{
3705return convertIEEEFloatToAPInt<semFloat8E4M3FN>();
3708APInt IEEEFloat::convertFloat8E4M3FNUZAPFloatToAPInt()
const{
3710return convertIEEEFloatToAPInt<semFloat8E4M3FNUZ>();
3713APInt IEEEFloat::convertFloat8E4M3B11FNUZAPFloatToAPInt()
const{
3715return convertIEEEFloatToAPInt<semFloat8E4M3B11FNUZ>();
3718APInt IEEEFloat::convertFloat8E3M4APFloatToAPInt()
const{
3720return convertIEEEFloatToAPInt<semFloat8E3M4>();
3723APInt IEEEFloat::convertFloatTF32APFloatToAPInt()
const{
3725return convertIEEEFloatToAPInt<semFloatTF32>();
3728APInt IEEEFloat::convertFloat8E8M0FNUAPFloatToAPInt()
const{
3730return convertIEEEFloatToAPInt<semFloat8E8M0FNU>();
3733APInt IEEEFloat::convertFloat6E3M2FNAPFloatToAPInt()
const{
3735return convertIEEEFloatToAPInt<semFloat6E3M2FN>();
3738APInt IEEEFloat::convertFloat6E2M3FNAPFloatToAPInt()
const{
3740return convertIEEEFloatToAPInt<semFloat6E2M3FN>();
3743APInt IEEEFloat::convertFloat4E2M1FNAPFloatToAPInt()
const{
3745return convertIEEEFloatToAPInt<semFloat4E2M1FN>();
3748// This function creates an APInt that is just a bit map of the floating 3749// point constant as it would appear in memory. It is not a conversion, 3750// and treating the result as a normal integer is unlikely to be useful. 3754return convertHalfAPFloatToAPInt();
3757return convertBFloatAPFloatToAPInt();
3760return convertFloatAPFloatToAPInt();
3763return convertDoubleAPFloatToAPInt();
3766return convertQuadrupleAPFloatToAPInt();
3769return convertPPCDoubleDoubleLegacyAPFloatToAPInt();
3772return convertFloat8E5M2APFloatToAPInt();
3775return convertFloat8E5M2FNUZAPFloatToAPInt();
3778return convertFloat8E4M3APFloatToAPInt();
3781return convertFloat8E4M3FNAPFloatToAPInt();
3784return convertFloat8E4M3FNUZAPFloatToAPInt();
3787return convertFloat8E4M3B11FNUZAPFloatToAPInt();
3790return convertFloat8E3M4APFloatToAPInt();
3793return convertFloatTF32APFloatToAPInt();
3796return convertFloat8E8M0FNUAPFloatToAPInt();
3799return convertFloat6E3M2FNAPFloatToAPInt();
3802return convertFloat6E2M3FNAPFloatToAPInt();
3805return convertFloat4E2M1FNAPFloatToAPInt();
3809return convertF80LongDoubleAPFloatToAPInt();
3814"Float semantics are not IEEEsingle");
3821"Float semantics are not IEEEdouble");
3826#ifdef HAS_IEE754_FLOAT128 3827float128 IEEEFloat::convertToQuad()
const{
3829"Float semantics are not IEEEquads");
3831return api.bitsToQuad();
3835/// Integer bit is explicit in this format. Intel hardware (387 and later) 3836/// does not support these bit patterns: 3837/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity") 3838/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN") 3839/// exponent!=0 nor all 1's, integer bit 0 ("unnormal") 3840/// exponent = 0, integer bit 1 ("pseudodenormal") 3841/// At the moment, the first three are treated as NaNs, the last one as Normal. 3842void IEEEFloat::initFromF80LongDoubleAPInt(
constAPInt &api) {
3845uint64_t myexponent = (i2 & 0x7fff);
3847uint8_t myintegerbit = mysignificand >> 63;
3852 sign =
static_cast<unsignedint>(i2>>15);
3853if (myexponent == 0 && mysignificand == 0) {
3855 }
elseif (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3857 }
elseif ((myexponent == 0x7fff && mysignificand != 0x8000000000000000ULL) ||
3858 (myexponent != 0x7fff && myexponent != 0 && myintegerbit == 0)) {
3860 exponent = exponentNaN();
3861 significandParts()[0] = mysignificand;
3862 significandParts()[1] = 0;
3865 exponent = myexponent - 16383;
3866 significandParts()[0] = mysignificand;
3867 significandParts()[1] = 0;
3868if (myexponent==0)
// denormal 3873void IEEEFloat::initFromPPCDoubleDoubleLegacyAPInt(
constAPInt &api) {
3879// Get the first double and convert to our format. 3880 initFromDoubleAPInt(
APInt(64, i1));
3885// Unless we have a special case, add in second double. 3896// The E8M0 format has the following characteristics: 3897// It is an 8-bit unsigned format with only exponents (no actual significand). 3898// No encodings for {zero, infinities or denorms}. 3899// NaN is represented by all 1's. 3901void IEEEFloat::initFromFloat8E8M0FNUAPInt(
constAPInt &api) {
3904uint64_t myexponent = (val & exponent_mask);
3909// This format has unsigned representation only 3912// Set the significand 3913// This format does not have any significand but the 'Pth' precision bit is 3914// always set to 1 for consistency in APFloat's internal representation. 3916 significandParts()[0] = mysignificand;
3918// This format can either have a NaN or fcNormal 3919// All 1's i.e. 255 is a NaN 3920if (val == exponent_mask) {
3922 exponent = exponentNaN();
3925// Handle fcNormal... 3927 exponent = myexponent - 127;
// 127 is bias 3929template <const fltSemantics &S>
3930void IEEEFloat::initFromIEEEAPInt(
constAPInt &api) {
3934constexpruint64_t significand_mask = integer_bit - 1;
3935constexprunsignedint trailing_significand_bits = S.precision - 1;
3936constexprunsignedint stored_significand_parts =
3938constexprunsignedint exponent_bits =
3939 S.sizeInBits - 1 - trailing_significand_bits;
3940static_assert(exponent_bits < 64);
3942constexprint bias = -(S.minExponent - 1);
3944// Copy the bits of the significand. We need to clear out the exponent and 3945// sign bit in the last word. 3946 std::array<integerPart, stored_significand_parts> mysignificand;
3947 std::copy_n(api.
getRawData(), mysignificand.size(), mysignificand.begin());
3948ifconstexpr (significand_mask != 0) {
3949 mysignificand[mysignificand.size() - 1] &= significand_mask;
3952// We assume the last word holds the sign bit, the exponent, and potentially 3953// some of the trailing significand field. 3956 (last_word >> (trailing_significand_bits % 64)) & exponent_mask;
3959assert(partCount() == mysignificand.size());
3961 sign =
static_cast<unsignedint>(last_word >> ((S.sizeInBits - 1) % 64));
3963bool all_zero_significand =
3966boolis_zero = myexponent == 0 && all_zero_significand;
3969if (myexponent - bias == ::exponentInf(S) && all_zero_significand) {
3978is_nan = myexponent - bias == ::exponentNaN(S) && !all_zero_significand;
3980bool all_ones_significand =
3981 std::all_of(mysignificand.begin(), mysignificand.end() - 1,
3982 [](
integerPart bits) { return bits == ~integerPart{0}; }) &&
3983 (!significand_mask ||
3984 mysignificand[mysignificand.size() - 1] == significand_mask);
3985is_nan = myexponent - bias == ::exponentNaN(S) && all_ones_significand;
3993 std::copy_n(mysignificand.begin(), mysignificand.size(),
3994 significandParts());
4004 exponent = myexponent - bias;
4005 std::copy_n(mysignificand.begin(), mysignificand.size(), significandParts());
4006if (myexponent == 0)
// denormal 4007 exponent = S.minExponent;
4009 significandParts()[mysignificand.size()-1] |= integer_bit;
// integer bit 4012void IEEEFloat::initFromQuadrupleAPInt(
constAPInt &api) {
4013 initFromIEEEAPInt<semIEEEquad>(api);
4016void IEEEFloat::initFromDoubleAPInt(
constAPInt &api) {
4017 initFromIEEEAPInt<semIEEEdouble>(api);
4020void IEEEFloat::initFromFloatAPInt(
constAPInt &api) {
4021 initFromIEEEAPInt<semIEEEsingle>(api);
4024void IEEEFloat::initFromBFloatAPInt(
constAPInt &api) {
4025 initFromIEEEAPInt<semBFloat>(api);
4028void IEEEFloat::initFromHalfAPInt(
constAPInt &api) {
4029 initFromIEEEAPInt<semIEEEhalf>(api);
4032void IEEEFloat::initFromFloat8E5M2APInt(
constAPInt &api) {
4033 initFromIEEEAPInt<semFloat8E5M2>(api);
4036void IEEEFloat::initFromFloat8E5M2FNUZAPInt(
constAPInt &api) {
4037 initFromIEEEAPInt<semFloat8E5M2FNUZ>(api);
4040void IEEEFloat::initFromFloat8E4M3APInt(
constAPInt &api) {
4041 initFromIEEEAPInt<semFloat8E4M3>(api);
4044void IEEEFloat::initFromFloat8E4M3FNAPInt(
constAPInt &api) {
4045 initFromIEEEAPInt<semFloat8E4M3FN>(api);
4048void IEEEFloat::initFromFloat8E4M3FNUZAPInt(
constAPInt &api) {
4049 initFromIEEEAPInt<semFloat8E4M3FNUZ>(api);
4052void IEEEFloat::initFromFloat8E4M3B11FNUZAPInt(
constAPInt &api) {
4053 initFromIEEEAPInt<semFloat8E4M3B11FNUZ>(api);
4056void IEEEFloat::initFromFloat8E3M4APInt(
constAPInt &api) {
4057 initFromIEEEAPInt<semFloat8E3M4>(api);
4060void IEEEFloat::initFromFloatTF32APInt(
constAPInt &api) {
4061 initFromIEEEAPInt<semFloatTF32>(api);
4064void IEEEFloat::initFromFloat6E3M2FNAPInt(
constAPInt &api) {
4065 initFromIEEEAPInt<semFloat6E3M2FN>(api);
4068void IEEEFloat::initFromFloat6E2M3FNAPInt(
constAPInt &api) {
4069 initFromIEEEAPInt<semFloat6E2M3FN>(api);
4072void IEEEFloat::initFromFloat4E2M1FNAPInt(
constAPInt &api) {
4073 initFromIEEEAPInt<semFloat4E2M1FN>(api);
4076/// Treat api as containing the bits of a floating point number. 4080return initFromHalfAPInt(api);
4082return initFromBFloatAPInt(api);
4084return initFromFloatAPInt(api);
4086return initFromDoubleAPInt(api);
4088return initFromF80LongDoubleAPInt(api);
4090return initFromQuadrupleAPInt(api);
4092return initFromPPCDoubleDoubleLegacyAPInt(api);
4094return initFromFloat8E5M2APInt(api);
4096return initFromFloat8E5M2FNUZAPInt(api);
4098return initFromFloat8E4M3APInt(api);
4100return initFromFloat8E4M3FNAPInt(api);
4102return initFromFloat8E4M3FNUZAPInt(api);
4104return initFromFloat8E4M3B11FNUZAPInt(api);
4106return initFromFloat8E3M4APInt(api);
4108return initFromFloatTF32APInt(api);
4110return initFromFloat8E8M0FNUAPInt(api);
4112return initFromFloat6E3M2FNAPInt(api);
4114return initFromFloat6E2M3FNAPInt(api);
4116return initFromFloat4E2M1FNAPInt(api);
4121/// Make this number the largest magnitude normal number in the given 4123void IEEEFloat::makeLargest(
bool Negative) {
4124if (Negative && !semantics->hasSignedRepr)
4126"This floating point format does not support signed values");
4127// We want (in interchange format): 4130// significand = 1..1 4133 exponent = semantics->maxExponent;
4135// Use memset to set all but the highest integerPart to all ones. 4137unsigned PartCount = partCount();
4138 memset(significand, 0xFF,
sizeof(
integerPart)*(PartCount - 1));
4140// Set the high integerPart especially setting all unused top bits for 4141// internal consistency. 4142constunsigned NumUnusedHighBits =
4143 PartCount*integerPartWidth - semantics->precision;
4144 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
4149 (semantics->precision > 1))
4153/// Make this number the smallest magnitude denormal number in the given 4155void IEEEFloat::makeSmallest(
bool Negative) {
4156if (Negative && !semantics->hasSignedRepr)
4158"This floating point format does not support signed values");
4159// We want (in interchange format): 4162// significand = 0..01 4165 exponent = semantics->minExponent;
4169void IEEEFloat::makeSmallestNormalized(
bool Negative) {
4170if (Negative && !semantics->hasSignedRepr)
4172"This floating point format does not support signed values");
4173// We want (in interchange format): 4176// significand = 10..0 4181 exponent = semantics->minExponent;
4186 initFromAPInt(&Sem, API);
4189IEEEFloat::IEEEFloat(
float f) {
4193IEEEFloat::IEEEFloat(
double d) {
4199 Buffer.
append(Str.begin(), Str.end());
4202 /// Removes data from the given significand until it is no more 4203 /// precise than is required for the desired precision. 4204void AdjustToPrecision(
APInt &significand,
4205int &exp,
unsigned FormatPrecision) {
4208// 196/59 is a very slight overestimate of lg_2(10). 4209unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
4211if (bits <= bitsRequired)
return;
4213unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
4214if (!tensRemovable)
return;
4216 exp += tensRemovable;
4221if (tensRemovable & 1)
4223 tensRemovable >>= 1;
4224if (!tensRemovable)
break;
4228 significand = significand.
udiv(divisor);
4230// Truncate the significand down to its active bit count. 4236int &exp,
unsigned FormatPrecision) {
4237unsignedN = buffer.
size();
4238if (
N <= FormatPrecision)
return;
4240// The most significant figures are the last ones in the buffer. 4241unsigned FirstSignificant =
N - FormatPrecision;
4244// FIXME: this probably shouldn't use 'round half up'. 4246// Rounding down is just a truncation, except we also want to drop 4247// trailing zeros from the new result. 4248if (buffer[FirstSignificant - 1] <
'5') {
4249while (FirstSignificant <
N && buffer[FirstSignificant] ==
'0')
4252 exp += FirstSignificant;
4253 buffer.
erase(&buffer[0], &buffer[FirstSignificant]);
4257// Rounding up requires a decimal add-with-carry. If we continue 4258// the carry, the newly-introduced zeros will just be truncated. 4259for (
unsignedI = FirstSignificant;
I !=
N; ++
I) {
4260if (buffer[
I] ==
'9') {
4268// If we carried through, we have exactly one digit of precision. 4269if (FirstSignificant ==
N) {
4270 exp += FirstSignificant;
4276 exp += FirstSignificant;
4277 buffer.
erase(&buffer[0], &buffer[FirstSignificant]);
4281APInt significand,
unsigned FormatPrecision,
4282unsigned FormatMaxPadding,
bool TruncateZero) {
4283constint semanticsPrecision = significand.
getBitWidth();
4288// Set FormatPrecision if zero. We want to do this before we 4289// truncate trailing zeros, as those are part of the precision. 4290if (!FormatPrecision) {
4291// We use enough digits so the number can be round-tripped back to an 4292// APFloat. The formula comes from "How to Print Floating-Point Numbers 4293// Accurately" by Steele and White. 4294// FIXME: Using a formula based purely on the precision is conservative; 4295// we can print fewer digits depending on the actual value being printed. 4297// FormatPrecision = 2 + floor(significandBits / lg_2(10)) 4298 FormatPrecision = 2 + semanticsPrecision * 59 / 196;
4301// Ignore trailing binary zeros. 4303 exp += trailingZeros;
4306// Change the exponent from 2^e to 10^e. 4311 significand = significand.
zext(semanticsPrecision + exp);
4312 significand <<= exp;
4314 }
else {
/* exp < 0 */ 4317// We transform this using the identity: 4318// (N)(2^-e) == (N)(5^e)(10^-e) 4319// This means we have to multiply N (the significand) by 5^e. 4320// To avoid overflow, we have to operate on numbers large 4321// enough to store N * 5^e: 4322// log2(N * 5^e) == log2(N) + e * log2(5) 4323// <= semantics->precision + e * 137 / 59 4324// (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59) 4326unsigned precision = semanticsPrecision + (137 * texp + 136) / 59;
4328// Multiply significand by 5^e. 4329// N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8) 4330 significand = significand.
zext(precision);
4331APInt five_to_the_i(precision, 5);
4334 significand *= five_to_the_i;
4339 five_to_the_i *= five_to_the_i;
4343 AdjustToPrecision(significand, exp, FormatPrecision);
4348unsigned precision = significand.getBitWidth();
4350// We need enough precision to store the value 10. 4352 significand = significand.zext(precision);
4354APInt ten(precision, 10);
4355APInt digit(precision, 0);
4358while (significand != 0) {
4359// digit <- significand % 10 4360// significand <- significand / 10 4363unsigned d = digit.getZExtValue();
4365// Drop trailing zeros. 4374assert(!buffer.
empty() &&
"no characters in buffer!");
4376// Drop down to FormatPrecision. 4377// TODO: don't do more precise calculations above than are required. 4378 AdjustToPrecision(buffer, exp, FormatPrecision);
4380unsigned NDigits = buffer.
size();
4382// Check whether we should use scientific notation. 4383bool FormatScientific;
4384if (!FormatMaxPadding)
4385 FormatScientific =
true;
4390// But we shouldn't make the number look more precise than it is. 4391 FormatScientific = ((
unsigned) exp > FormatMaxPadding ||
4392 NDigits + (
unsigned) exp > FormatPrecision);
4394// Power of the most significant digit. 4395int MSD = exp + (int) (NDigits - 1);
4398 FormatScientific =
false;
4402 FormatScientific = ((
unsigned) -MSD) > FormatMaxPadding;
4407// Scientific formatting is pretty straightforward. 4408if (FormatScientific) {
4409 exp += (NDigits - 1);
4411 Str.push_back(buffer[NDigits-1]);
4413if (NDigits == 1 && TruncateZero)
4416for (
unsignedI = 1;
I != NDigits; ++
I)
4417 Str.push_back(buffer[NDigits-1-
I]);
4418// Fill with zeros up to FormatPrecision. 4419if (!TruncateZero && FormatPrecision > NDigits - 1)
4420 Str.append(FormatPrecision - NDigits + 1,
'0');
4421// For !TruncateZero we use lower 'e'. 4422 Str.push_back(TruncateZero ?
'E' :
'e');
4424 Str.push_back(exp >= 0 ?
'+' :
'-');
4429 expbuf.
push_back((
char) (
'0' + (exp % 10)));
4432// Exponent always at least two digits if we do not truncate zeros. 4433if (!TruncateZero && expbuf.
size() < 2)
4435for (
unsignedI = 0, E = expbuf.
size();
I != E; ++
I)
4436 Str.push_back(expbuf[E-1-
I]);
4440// Non-scientific, positive exponents. 4442for (
unsignedI = 0;
I != NDigits; ++
I)
4443 Str.push_back(buffer[NDigits-1-
I]);
4449// Non-scientific, negative exponents. 4451// The number of digits to the left of the decimal point. 4452int NWholeDigits = exp + (int) NDigits;
4455if (NWholeDigits > 0) {
4457 Str.push_back(buffer[NDigits-
I-1]);
4460unsigned NZeros = 1 + (
unsigned) -NWholeDigits;
4464for (
unsigned Z = 1;
Z != NZeros; ++
Z)
4468for (;
I != NDigits; ++
I)
4469 Str.push_back(buffer[NDigits-
I-1]);
4475unsigned FormatMaxPadding,
bool TruncateZero)
const{
4479return append(Str,
"-Inf");
4481return append(Str,
"+Inf");
4483case fcNaN:
return append(Str,
"NaN");
4489if (!FormatMaxPadding) {
4491 append(Str,
"0.0E+0");
4494if (FormatPrecision > 1)
4495 Str.append(FormatPrecision - 1,
'0');
4506// Decompose the number into an APInt and an exponent. 4507int exp = exponent - ((int) semantics->precision - 1);
4509 semantics->precision,
4512 toStringImpl(Str, isNegative(), exp, significand, FormatPrecision,
4513 FormatMaxPadding, TruncateZero);
4517bool IEEEFloat::getExactInverse(
APFloat *inv)
const{
4518// Special floats and denormals have no exact inverse. 4519if (!isFiniteNonZero())
4522// Check that the number is a power of two by making sure that only the 4523// integer bit is set in the significand. 4524if (significandLSB() != semantics->precision - 1)
4529if (reciprocal.
divide(*
this, rmNearestTiesToEven) != opOK)
4532// Avoid multiplication with a denormal, it is not safe on all platforms and 4533// may be slower than a normal division. 4538 reciprocal.significandLSB() == reciprocal.semantics->
precision - 1);
4541 *inv =
APFloat(reciprocal, *semantics);
4546int IEEEFloat::getExactLog2Abs()
const{
4554for (
int i = 0; i < PartCount; ++i) {
4560if (exponent != semantics->minExponent)
4564for (
int i = 0; i < PartCount;
4567return exponent - semantics->precision + CountrParts +
4575bool IEEEFloat::isSignaling()
const{
4582// IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the 4583// first bit of the trailing significand being 0. 4587/// IEEE-754R 2008 5.3.1: nextUp/nextDown. 4589/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with 4590/// appropriate sign switching before/after the computation. 4592// If we are performing nextDown, swap sign so we have -x. 4599// Handle each float category separately. 4602// nextUp(+inf) = +inf 4605// nextUp(-inf) = -getLargest() 4609// IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag. 4610// IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not 4611// change the payload. 4613 result = opInvalidOp;
4614// For consistency, propagate the sign of the sNaN to the qNaN. 4615 makeNaN(
false, isNegative(),
nullptr);
4619// nextUp(pm 0) = +getSmallest() 4620 makeSmallest(
false);
4623// nextUp(-getSmallest()) = -0 4624if (isSmallest() && isNegative()) {
4630if (!semantics->hasZero)
4631 makeSmallestNormalized(
false);
4635if (isLargest() && !isNegative()) {
4637// nextUp(getLargest()) == NAN 4640 }
elseif (semantics->nonFiniteBehavior ==
4642// nextUp(getLargest()) == getLargest() 4645// nextUp(getLargest()) == INFINITY 4647 category = fcInfinity;
4648 exponent = semantics->maxExponent + 1;
4653// nextUp(normal) == normal + inc. 4655// If we are negative, we need to decrement the significand. 4657// We only cross a binade boundary that requires adjusting the exponent 4659// 1. exponent != semantics->minExponent. This implies we are not in the 4660// smallest binade or are dealing with denormals. 4661// 2. Our significand excluding the integral bit is all zeros. 4662bool WillCrossBinadeBoundary =
4663 exponent != semantics->minExponent && isSignificandAllZeros();
4665// Decrement the significand. 4667// We always do this since: 4668// 1. If we are dealing with a non-binade decrement, by definition we 4669// just decrement the significand. 4670// 2. If we are dealing with a normal -> normal binade decrement, since 4671// we have an explicit integral bit the fact that all bits but the 4672// integral bit are zero implies that subtracting one will yield a 4673// significand with 0 integral bit and 1 in all other spots. Thus we 4674// must just adjust the exponent and set the integral bit to 1. 4675// 3. If we are dealing with a normal -> denormal binade decrement, 4676// since we set the integral bit to 0 when we represent denormals, we 4677// just decrement the significand. 4681if (WillCrossBinadeBoundary) {
4682// Our result is a normal number. Do the following: 4683// 1. Set the integral bit to 1. 4684// 2. Decrement the exponent. 4689// If we are positive, we need to increment the significand. 4691// We only cross a binade boundary that requires adjusting the exponent if 4692// the input is not a denormal and all of said input's significand bits 4693// are set. If all of said conditions are true: clear the significand, set 4694// the integral bit to 1, and increment the exponent. If we have a 4695// denormal always increment since moving denormals and the numbers in the 4696// smallest normal binade have the same exponent in our representation. 4697// If there are only exponents, any increment always crosses the 4700 (!isDenormal() && isSignificandAllOnes());
4702if (WillCrossBinadeBoundary) {
4706assert(exponent != semantics->maxExponent &&
4707"We can not increment an exponent beyond the maxExponent allowed" 4708" by the given floating point semantics.");
4711 incrementSignificand();
4717// If we are performing nextDown, swap sign so we have -nextUp(-x) 4725 return ::exponentNaN(*semantics);
4729 return ::exponentInf(*semantics);
4733 return ::exponentZero(*semantics);
4736void IEEEFloat::makeInf(
bool Negative) {
4741// There is no Inf, so make NaN instead. 4742 makeNaN(
false, Negative);
4745 category = fcInfinity;
4751void IEEEFloat::makeZero(
bool Negative) {
4752if (!semantics->hasZero)
4758// Merge negative zero to positive because 0b10000...000 is used for NaN 4765void IEEEFloat::makeQuiet() {
4784 Normalized.exponent += SignificandBits;
4786return Normalized.exponent - SignificandBits;
4790auto MaxExp =
X.getSemantics().maxExponent;
4791auto MinExp =
X.getSemantics().minExponent;
4793// If Exp is wildly out-of-scale, simply adding it to X.exponent will 4794// overflow; clamp it to a safe range before adding, but ensure that the range 4795// is large enough that the clamp does not change the result. The range we 4796// need to support is the difference between the largest possible exponent and 4797// the normalized exponent of half the smallest denormal. 4799int SignificandBits =
X.getSemantics().precision - 1;
4800int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
4802// Clamp to one past the range ends to let normalize handle overlflow. 4803X.exponent += std::clamp(Exp, -MaxIncrement - 1, MaxIncrement);
4813// Quiet signalling nans. 4823// 1 is added because frexp is defined to return a normalized fraction in 4824// +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0). 4826returnscalbn(Val, -Exp, RM);
4859 Floats(new
APFloat[2]{std::move(
First), std::move(Second)}) {
4866 : Semantics(
RHS.Semantics),
4880if (Semantics ==
RHS.Semantics &&
RHS.Floats) {
4881 Floats[0] =
RHS.Floats[0];
4882 Floats[1] =
RHS.Floats[1];
4883 }
elseif (
this != &
RHS) {
4890// Implement addition, subtraction, multiplication and division based on: 4891// "Software for Doubled-Precision Floating-Point Computations", 4892// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283. 4901 Floats[0] = std::move(z);
4902 Floats[1].makeZero(
/* Neg = */false);
4906auto AComparedToC = a.compareAbsoluteValue(c);
4910// z = cc + aa + c + a; 4914// z = cc + aa + a + c; 4919 Floats[0] = std::move(z);
4920 Floats[1].makeZero(
/* Neg = */false);
4927// Floats[1] = a - z + c + zz; 4929Status |= Floats[1].subtract(z, RM);
4930Status |= Floats[1].add(c, RM);
4931Status |= Floats[1].add(zz, RM);
4933// Floats[1] = c - z + a + zz; 4935Status |= Floats[1].subtract(z, RM);
4936Status |= Floats[1].add(a, RM);
4937Status |= Floats[1].add(zz, RM);
4944// zz = q + c + (a - (q + z)) + aa + cc; 4945// Compute a - (q + z) as -((q + z) - a) to avoid temporary copies. 4955 Floats[0] = std::move(z);
4956 Floats[1].makeZero(
/* Neg = */false);
4960Status |= Floats[0].add(zz, RM);
4962 Floats[1].makeZero(
/* Neg = */false);
4965 Floats[1] = std::move(z);
4966Status |= Floats[1].subtract(Floats[0], RM);
4967Status |= Floats[1].add(zz, RM);
4973const DoubleAPFloat &RHS,
4993LHS.isNegative() !=
RHS.isNegative()) {
4994 Out.makeNaN(
false, Out.isNegative(),
nullptr);
5015return Out.addImpl(
A, AA,
C,
CC, RM);
5020return addWithSpecial(*
this,
RHS, *
this, RM);
5033constauto &
LHS = *
this;
5035/* Interesting observation: For special categories, finding the lowest 5036 common ancestor of the following layered graph gives the correct 5045 e.g. NaN * NaN = NaN 5047 Normal * Zero = Zero 5060 Out.makeNaN(
false,
false,
nullptr);
5072"Special cases not handled exhaustively");
5079if (!
T.isFiniteNonZero()) {
5081 Floats[1].makeZero(
/* Neg = */false);
5085// tau = fmsub(a, c, t), that is -fmadd(-a, c, t). 5107 Floats[1].makeZero(
/* Neg = */false);
5109// Floats[1] = (t - u) + tau 5166 Floats[0].changeSign();
5167 Floats[1].changeSign();
5172auto Result = Floats[0].compareAbsoluteValue(
RHS.Floats[0]);
5175 Result = Floats[1].compareAbsoluteValue(
RHS.Floats[1]);
5177auto Against = Floats[0].isNegative() ^ Floats[1].isNegative();
5178auto RHSAgainst =
RHS.Floats[0].isNegative() ^
RHS.Floats[1].isNegative();
5179if (Against && !RHSAgainst)
5181if (!Against && RHSAgainst)
5183if (!Against && !RHSAgainst)
5185if (Against && RHSAgainst)
5192return Floats[0].getCategory();
5198 Floats[0].makeInf(Neg);
5199 Floats[1].makeZero(
/* Neg = */false);
5203 Floats[0].makeZero(Neg);
5204 Floats[1].makeZero(
/* Neg = */false);
5217 Floats[0].makeSmallest(Neg);
5218 Floats[1].makeZero(
/* Neg = */false);
5225 Floats[0].changeSign();
5226 Floats[1].makeZero(
/* Neg = */false);
5230 Floats[0].makeNaN(SNaN, Neg, fill);
5231 Floats[1].makeZero(
/* Neg = */false);
5235auto Result = Floats[0].compare(
RHS.Floats[0]);
5236// |Float[0]| > |Float[1]| 5238return Floats[1].compare(
RHS.Floats[1]);
5243return Floats[0].bitwiseIsEqual(
RHS.Floats[0]) &&
5244 Floats[1].bitwiseIsEqual(
RHS.Floats[1]);
5256 Floats[0].bitcastToAPInt().getRawData()[0],
5257 Floats[1].bitcastToAPInt().getRawData()[0],
5274auto Ret = Tmp.
next(nextDown);
5281unsignedint Width,
bool IsSigned,
5300unsignedint InputSize,
5311unsignedint InputSize,
5321unsignedint HexDigits,
5331 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
5332// (double)(Hi + Lo) == Hi defines a normal number. 5333 Floats[0] != Floats[0] + Floats[1]);
5363return Floats[0].isInteger() && Floats[1].isInteger();
5367unsigned FormatPrecision,
5368unsigned FormatMaxPadding,
5369bool TruncateZero)
const{
5372 .
toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
5387// TODO: Implement me 5392// TODO: Implement me 5400scalbn(Arg.Floats[1], Exp, RM));
5407APFloat Second = Arg.Floats[1];
5409 Second =
scalbn(Second, -Exp, RM);
5415APFloat::Storage::Storage(IEEEFloat
F,
constfltSemantics &Semantics) {
5416if (usesLayout<IEEEFloat>(Semantics)) {
5417new (&
IEEE) IEEEFloat(std::move(
F));
5420if (usesLayout<DoubleAPFloat>(Semantics)) {
5423 DoubleAPFloat(Semantics,
APFloat(std::move(
F), S),
5436if (APFloat::usesLayout<detail::IEEEFloat>(Arg.
getSemantics()))
5438if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.
getSemantics()))
5446assert(StatusOrErr &&
"Invalid floating point representation");
5470 usesLayout<IEEEFloat>(ToSemantics))
5471return U.IEEE.convert(ToSemantics, RM, losesInfo);
5473 usesLayout<DoubleAPFloat>(ToSemantics)) {
5476 *
this =
APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
5480 usesLayout<IEEEFloat>(ToSemantics)) {
5481auto Ret = getIEEE().
convert(ToSemantics, RM, losesInfo);
5482 *
this =
APFloat(std::move(getIEEE()), ToSemantics);
5498#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 5509/* Same as convertToInteger(integerPart*, ...), except the result is returned in 5510 an APSInt, whose initial bit-width and signed-ness are used to determine the 5511 precision of the conversion. 5515bool *isExact)
const{
5519 rounding_mode, isExact);
5520// Keeps the original signed-ness. 5521 result =
APInt(bitWidth, parts);
5529"Float semantics is not representable by IEEEdouble");
5538#ifdef HAS_IEE754_FLOAT128 5539float128 APFloat::convertToQuad()
const{
5541return getIEEE().convertToQuad();
5543"Float semantics is not representable by IEEEquad");
5549return Temp.getIEEE().convertToQuad();
5557"Float semantics is not representable by IEEEsingle");
5568#undef APFLOAT_DISPATCH_ON_SEMANTICS #define PackCategoriesIntoKey(_lhs, _rhs)
A macro used to combine two fcCategory enums into one key which can be used in a switch statement to ...
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...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#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.
Looks at all the uses of the given value Returns the Liveness deduced from the uses of this value Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses If the result is MaybeLiveUses might be modified but its content should be ignored(since it might not be complete). DeadArgumentEliminationPass
Given that RA is a live value
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static bool isSigned(unsigned int 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)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file contains some functions that are useful when dealing with strings.
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 getExactInverse(APFloat *inv) const
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
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 APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
const fltSemantics & getSemantics() const
opStatus convertFromSignExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
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
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
opStatus next(bool nextDown)
FPClassTest classify() const
Return the FPClassTest which will return true for the value.
opStatus mod(const APFloat &RHS)
Expected< opStatus > convertFromString(StringRef, roundingMode)
void print(raw_ostream &) const
opStatus roundToIntegral(roundingMode RM)
static bool hasSignificand(const fltSemantics &Sem)
Returns true if the given semantics has actual significand.
opStatus convertFromZeroExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
Class for arbitrary precision integers.
APInt udiv(const APInt &RHS) const
Unsigned division operation.
static 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 void tcSet(WordType *, WordType, unsigned)
Sets the least significant part of a bignum to the input value, and zeroes out higher parts.
static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
static int tcExtractBit(const WordType *, unsigned bit)
Extract the given bit of a bignum; returns 0 or 1. Zero-based.
APInt zext(unsigned width) const
Zero extend to a new width.
static WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned)
DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
static 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.
APInt trunc(unsigned width) const
Truncate to new width.
static int tcCompare(const WordType *, const WordType *, unsigned)
Comparison (unsigned) of two bignums.
static APInt floatToBits(float V)
Converts a float to APInt bits.
static void tcAssign(WordType *, const WordType *, unsigned)
Assign one bignum to another.
unsigned getBitWidth() const
Return the number of bits in the APInt.
static void tcShiftRight(WordType *, unsigned Words, unsigned Count)
Shift a bignum right Count bits.
static 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 void tcClearBit(WordType *, unsigned bit)
Clear the given bit of a bignum. Zero-based.
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 unsigned tcLSB(const WordType *, unsigned n)
Returns the bit number of the least or most significant set bit of a number.
static void tcShiftLeft(WordType *, unsigned Words, unsigned Count)
Shift a bignum left Count bits.
static bool tcIsZero(const WordType *, unsigned)
Returns true if a bignum is zero, false otherwise.
static 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 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 WordType tcSubtract(WordType *, const WordType *, WordType carry, unsigned)
DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
static 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.
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - 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.
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
empty - 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
back - 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
size - Get the string size.
char front() const
front - Get the first character in the string.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
void makeSmallestNormalized(bool Neg)
DoubleAPFloat & operator=(const DoubleAPFloat &RHS)
LLVM_READONLY int getExactLog2() const
opStatus remainder(const DoubleAPFloat &RHS)
opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM)
fltCategory getCategory() const
bool bitwiseIsEqual(const DoubleAPFloat &RHS) const
LLVM_READONLY int getExactLog2Abs() const
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
opStatus convertFromZeroExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
APInt bitcastToAPInt() const
bool getExactInverse(APFloat *inv) const
Expected< opStatus > convertFromString(StringRef, roundingMode)
opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM)
cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
void makeSmallest(bool Neg)
opStatus next(bool nextDown)
opStatus divide(const DoubleAPFloat &RHS, roundingMode RM)
bool isSmallestNormalized() const
opStatus mod(const DoubleAPFloat &RHS)
DoubleAPFloat(const fltSemantics &S)
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision, unsigned FormatMaxPadding, bool TruncateZero=true) const
void makeLargest(bool Neg)
cmpResult compare(const DoubleAPFloat &RHS) const
opStatus roundToIntegral(roundingMode RM)
opStatus convertFromSignExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, const DoubleAPFloat &Addend, roundingMode RM)
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
opStatus add(const DoubleAPFloat &RHS, roundingMode RM)
void makeNaN(bool SNaN, bool Neg, const APInt *fill)
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...
cmpResult compareAbsoluteValue(const IEEEFloat &) const
opStatus mod(const IEEEFloat &)
C fmod, or llvm frem.
fltCategory getCategory() const
opStatus convertFromAPInt(const APInt &, bool, roundingMode)
bool isFiniteNonZero() const
bool needsCleanup() const
Returns whether this instance allocated memory.
APInt bitcastToAPInt() const
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.
opStatus divide(const IEEEFloat &, roundingMode)
bool isNaN() const
Returns true if and only if the float is a quiet or signaling NaN.
opStatus remainder(const IEEEFloat &)
IEEE remainder.
double convertToDouble() const
opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int, bool, roundingMode)
float convertToFloat() const
opStatus subtract(const IEEEFloat &, roundingMode)
void makeInf(bool Neg=false)
opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int, bool, roundingMode)
bool isSmallestNormalized() const
Returns true if this is the smallest (by magnitude) normalized finite number in the given semantics.
bool isLargest() const
Returns true if and only if the number has the largest possible finite magnitude in the current seman...
opStatus add(const IEEEFloat &, roundingMode)
bool isFinite() const
Returns true if and only if the current value is zero, subnormal, or normal.
Expected< opStatus > convertFromString(StringRef, roundingMode)
void makeNaN(bool SNaN=false, bool Neg=false, const APInt *fill=nullptr)
friend int ilogb(const IEEEFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
opStatus multiply(const IEEEFloat &, roundingMode)
opStatus roundToIntegral(roundingMode)
IEEEFloat & operator=(const IEEEFloat &)
friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Returns: X * 2^Exp for integral exponents.
bool bitwiseIsEqual(const IEEEFloat &) const
Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
void makeSmallestNormalized(bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
bool isInteger() const
Returns true if and only if the number is an exact integer.
IEEEFloat(const fltSemantics &)
opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode)
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.
bool isSignaling() const
Returns true if and only if the float is a signaling NaN.
void makeZero(bool Neg=false)
opStatus convert(const fltSemantics &, roundingMode, bool *)
IEEEFloat::convert - convert a value of one floating point type to another.
bool isDenormal() const
IEEE-754R isSubnormal(): Returns true if and only if the float is a denormal.
opStatus convertToInteger(MutableArrayRef< integerPart >, unsigned int, bool, roundingMode, bool *) const
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.
@ C
The default llvm calling convention, compatible with C.
static constexpr opStatus opInexact
APFloatBase::roundingMode roundingMode
static constexpr fltCategory fcNaN
static constexpr opStatus opDivByZero
static constexpr opStatus opOverflow
static constexpr cmpResult cmpLessThan
static void tcSetLeastSignificantBits(APInt::WordType *dst, unsigned parts, unsigned bits)
APFloatBase::opStatus opStatus
static constexpr roundingMode rmTowardPositive
static constexpr uninitializedTag uninitialized
static constexpr fltCategory fcZero
static constexpr opStatus opOK
static constexpr cmpResult cmpGreaterThan
static constexpr unsigned integerPartWidth
APFloatBase::ExponentType ExponentType
hash_code hash_value(const IEEEFloat &Arg)
static constexpr fltCategory fcNormal
static constexpr opStatus opInvalidOp
IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM)
APFloatBase::integerPart integerPart
static constexpr cmpResult cmpUnordered
static constexpr roundingMode rmTowardNegative
static constexpr fltCategory fcInfinity
static constexpr roundingMode rmNearestTiesToAway
static constexpr roundingMode rmTowardZero
static constexpr opStatus opUnderflow
static constexpr roundingMode rmNearestTiesToEven
int ilogb(const IEEEFloat &Arg)
static constexpr cmpResult cmpEqual
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)
static constexpr fltSemantics semBogus
static const char infinityL[]
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
hash_code hash_value(const FixedPointSemantics &Val)
int popcount(T Value) noexcept
Count the number of set bits in a value.
static constexpr unsigned int partCountForBits(unsigned int bits)
static constexpr fltSemantics semFloat8E8M0FNU
static unsigned int HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
static unsigned int powerOf5(APFloatBase::integerPart *dst, unsigned int power)
static constexpr fltSemantics semFloat6E2M3FN
static constexpr APFloatBase::ExponentType exponentZero(const fltSemantics &semantics)
static Expected< int > totalExponent(StringRef::iterator p, StringRef::iterator end, int exponentAdjustment)
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
static constexpr fltSemantics semIEEEquad
const unsigned int maxPowerOfFiveExponent
static constexpr fltSemantics semFloat6E3M2FN
static char * writeUnsignedDecimal(char *dst, unsigned int n)
static constexpr fltSemantics semFloat8E4M3FNUZ
const unsigned int maxPrecision
static constexpr fltSemantics semIEEEdouble
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 constexpr fltSemantics semFloat8E4M3FN
static const char infinityU[]
lostFraction
Enum that represents what fraction of the LSB truncated bits of an fp number represent.
static constexpr fltSemantics semPPCDoubleDouble
static Error interpretDecimal(StringRef::iterator begin, StringRef::iterator end, decimalInfo *D)
static constexpr fltSemantics semFloat8E5M2FNUZ
bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
const unsigned int maxPowerOfFiveParts
static constexpr fltSemantics semIEEEsingle
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
static constexpr fltSemantics semFloat4E2M1FN
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static constexpr APFloatBase::ExponentType exponentNaN(const fltSemantics &semantics)
static Error createError(const Twine &Err)
static constexpr fltSemantics semIEEEhalf
static constexpr fltSemantics semPPCDoubleDoubleLegacy
static lostFraction shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
static constexpr fltSemantics semFloat8E5M2
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
static const char hexDigitsUpper[]
const unsigned int maxExponent
static unsigned int decDigitValue(unsigned int c)
static constexpr fltSemantics semFloat8E4M3B11FNUZ
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.
OutputIt copy(R &&Range, OutputIt Out)
static constexpr fltSemantics semX87DoubleExtended
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
static constexpr fltSemantics semFloatTF32
static constexpr APFloatBase::ExponentType exponentInf(const fltSemantics &semantics)
static lostFraction lostFractionThroughTruncation(const APFloatBase::integerPart *parts, unsigned int partCount, unsigned int bits)
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 constexpr fltSemantics semBFloat
static Expected< lostFraction > trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, unsigned int digitValue)
void consumeError(Error Err)
Consume a Error without doing anything.
static constexpr fltSemantics semFloat8E3M4
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.
static constexpr fltSemantics semFloat8E4M3
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[]
Implement std::hash so that hash_code can be used in STL containers.
static const llvm::fltSemantics & EnumToSemantics(Semantics S)
static const fltSemantics & IEEEsingle() LLVM_READNONE
static bool semanticsHasInf(const fltSemantics &)
static const fltSemantics & Float6E3M2FN() LLVM_READNONE
static constexpr roundingMode rmNearestTiesToAway
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
static const fltSemantics & PPCDoubleDoubleLegacy() LLVM_READNONE
static constexpr roundingMode rmTowardNegative
static ExponentType semanticsMinExponent(const fltSemantics &)
static constexpr roundingMode rmNearestTiesToEven
static unsigned int semanticsSizeInBits(const fltSemantics &)
static bool semanticsHasSignedRepr(const fltSemantics &)
static const fltSemantics & Float8E4M3() LLVM_READNONE
static unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
static const fltSemantics & Float8E4M3FN() LLVM_READNONE
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
static constexpr roundingMode rmTowardZero
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
uninitializedTag
Convenience enum used to construct an uninitialized APFloat.
static const fltSemantics & IEEEquad() LLVM_READNONE
static const fltSemantics & Float4E2M1FN() LLVM_READNONE
static const fltSemantics & Float8E8M0FNU() LLVM_READNONE
static const fltSemantics & Float8E4M3B11FNUZ() LLVM_READNONE
static const fltSemantics & Bogus() LLVM_READNONE
A Pseudo fltsemantic used to construct APFloats that cannot conflict with anything real.
static ExponentType semanticsMaxExponent(const fltSemantics &)
static unsigned int semanticsPrecision(const fltSemantics &)
static const fltSemantics & IEEEdouble() LLVM_READNONE
static bool semanticsHasNaN(const fltSemantics &)
static const fltSemantics & Float8E5M2() LLVM_READNONE
static Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
static constexpr unsigned integerPartWidth
static const fltSemantics & IEEEhalf() LLVM_READNONE
APInt::WordType integerPart
static constexpr roundingMode rmTowardPositive
static bool semanticsHasZero(const fltSemantics &)
static bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
static const fltSemantics & Float8E4M3FNUZ() LLVM_READNONE
static const fltSemantics & BFloat() LLVM_READNONE
static const fltSemantics & FloatTF32() LLVM_READNONE
static bool isRepresentableBy(const fltSemantics &A, const fltSemantics &B)
static const fltSemantics & Float8E5M2FNUZ() LLVM_READNONE
static const fltSemantics & Float6E2M3FN() LLVM_READNONE
fltCategory
Category of internally-represented number.
@ S_PPCDoubleDoubleLegacy
static const fltSemantics & Float8E3M4() LLVM_READNONE
opStatus
IEEE-754R 7: Default exception handling.
int32_t ExponentType
A signed type to represent a floating point numbers unbiased exponent.
static unsigned int semanticsIntSizeInBits(const fltSemantics &, bool)
const char * lastSigDigit
const char * firstSigDigit
APFloatBase::ExponentType maxExponent
fltNonfiniteBehavior nonFiniteBehavior
APFloatBase::ExponentType minExponent
fltNanEncoding nanEncoding