1 //===-- APFloat.cpp - Implement APFloat class -----------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements a class to represent arbitrary precision floating 11 // point values and provide a variety of arithmetic operations on them. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APSInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/FoldingSet.h" 19 #include "llvm/ADT/Hashing.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/Support/ErrorHandling.h" 23 #include "llvm/Support/MathExtras.h" 24 #include <cstring> 25 #include <limits.h> 26 27 using namespace llvm; 28 29 /// A macro used to combine two fcCategory enums into one key which can be used 30 /// in a switch statement to classify how the interaction of two APFloat's 31 /// categories affects an operation. 32 /// 33 /// TODO: If clang source code is ever allowed to use constexpr in its own 34 /// codebase, change this into a static inline function. 35 #define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs)) 36 37 /* Assumed in hexadecimal significand parsing, and conversion to 38 hexadecimal strings. */ 39 static_assert(integerPartWidth % 4 == 0, "Part width must be divisible by 4!"); 40 41 namespace llvm { 42 /* Represents floating point arithmetic semantics. */ 43 struct fltSemantics { 44 /* The largest E such that 2^E is representable; this matches the 45 definition of IEEE 754. */ 46 APFloatBase::ExponentType maxExponent; 47 48 /* The smallest E such that 2^E is a normalized number; this 49 matches the definition of IEEE 754. */ 50 APFloatBase::ExponentType minExponent; 51 52 /* Number of bits in the significand. This includes the integer 53 bit. */ 54 unsigned int precision; 55 56 /* Number of bits actually used in the semantics. */ 57 unsigned int sizeInBits; 58 }; 59 60 const fltSemantics APFloatBase::IEEEhalf = {15, -14, 11, 16}; 61 const fltSemantics APFloatBase::IEEEsingle = {127, -126, 24, 32}; 62 const fltSemantics APFloatBase::IEEEdouble = {1023, -1022, 53, 64}; 63 const fltSemantics APFloatBase::IEEEquad = {16383, -16382, 113, 128}; 64 const fltSemantics APFloatBase::x87DoubleExtended = {16383, -16382, 64, 80}; 65 const fltSemantics APFloatBase::Bogus = {0, 0, 0, 0}; 66 67 /* The PowerPC format consists of two doubles. It does not map cleanly 68 onto the usual format above. It is approximated using twice the 69 mantissa bits. Note that for exponents near the double minimum, 70 we no longer can represent the full 106 mantissa bits, so those 71 will be treated as denormal numbers. 72 73 FIXME: While this approximation is equivalent to what GCC uses for 74 compile-time arithmetic on PPC double-double numbers, it is not able 75 to represent all possible values held by a PPC double-double number, 76 for example: (long double) 1.0 + (long double) 0x1p-106 77 Should this be replaced by a full emulation of PPC double-double? */ 78 const fltSemantics APFloatBase::PPCDoubleDouble = {0, 0, 0, 0}; 79 80 /* There are temporary semantics for the real PPCDoubleDouble implementation. 81 Currently, APFloat of PPCDoubleDouble holds one PPCDoubleDoubleImpl as the 82 high part of double double, and one IEEEdouble as the low part, so that 83 the old operations operate on PPCDoubleDoubleImpl, while the newly added 84 operations also populate the IEEEdouble. 85 86 TODO: Once all functions support DoubleAPFloat mode, we'll change all 87 PPCDoubleDoubleImpl to IEEEdouble and remove PPCDoubleDoubleImpl. */ 88 static const fltSemantics PPCDoubleDoubleImpl = {1023, -1022 + 53, 53 + 53, 89 128}; 90 91 /* A tight upper bound on number of parts required to hold the value 92 pow(5, power) is 93 94 power * 815 / (351 * integerPartWidth) + 1 95 96 However, whilst the result may require only this many parts, 97 because we are multiplying two values to get it, the 98 multiplication may require an extra part with the excess part 99 being zero (consider the trivial case of 1 * 1, tcFullMultiply 100 requires two parts to hold the single-part result). So we add an 101 extra one to guarantee enough space whilst multiplying. */ 102 const unsigned int maxExponent = 16383; 103 const unsigned int maxPrecision = 113; 104 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1; 105 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815) 106 / (351 * integerPartWidth)); 107 108 unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) { 109 return semantics.precision; 110 } 111 APFloatBase::ExponentType 112 APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) { 113 return semantics.maxExponent; 114 } 115 APFloatBase::ExponentType 116 APFloatBase::semanticsMinExponent(const fltSemantics &semantics) { 117 return semantics.minExponent; 118 } 119 unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) { 120 return semantics.sizeInBits; 121 } 122 123 unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) { 124 return Sem.sizeInBits; 125 } 126 127 /* A bunch of private, handy routines. */ 128 129 static inline unsigned int 130 partCountForBits(unsigned int bits) 131 { 132 return ((bits) + integerPartWidth - 1) / integerPartWidth; 133 } 134 135 /* Returns 0U-9U. Return values >= 10U are not digits. */ 136 static inline unsigned int 137 decDigitValue(unsigned int c) 138 { 139 return c - '0'; 140 } 141 142 /* Return the value of a decimal exponent of the form 143 [+-]ddddddd. 144 145 If the exponent overflows, returns a large exponent with the 146 appropriate sign. */ 147 static int 148 readExponent(StringRef::iterator begin, StringRef::iterator end) 149 { 150 bool isNegative; 151 unsigned int absExponent; 152 const unsigned int overlargeExponent = 24000; /* FIXME. */ 153 StringRef::iterator p = begin; 154 155 assert(p != end && "Exponent has no digits"); 156 157 isNegative = (*p == '-'); 158 if (*p == '-' || *p == '+') { 159 p++; 160 assert(p != end && "Exponent has no digits"); 161 } 162 163 absExponent = decDigitValue(*p++); 164 assert(absExponent < 10U && "Invalid character in exponent"); 165 166 for (; p != end; ++p) { 167 unsigned int value; 168 169 value = decDigitValue(*p); 170 assert(value < 10U && "Invalid character in exponent"); 171 172 value += absExponent * 10; 173 if (absExponent >= overlargeExponent) { 174 absExponent = overlargeExponent; 175 p = end; /* outwit assert below */ 176 break; 177 } 178 absExponent = value; 179 } 180 181 assert(p == end && "Invalid exponent in exponent"); 182 183 if (isNegative) 184 return -(int) absExponent; 185 else 186 return (int) absExponent; 187 } 188 189 /* This is ugly and needs cleaning up, but I don't immediately see 190 how whilst remaining safe. */ 191 static int 192 totalExponent(StringRef::iterator p, StringRef::iterator end, 193 int exponentAdjustment) 194 { 195 int unsignedExponent; 196 bool negative, overflow; 197 int exponent = 0; 198 199 assert(p != end && "Exponent has no digits"); 200 201 negative = *p == '-'; 202 if (*p == '-' || *p == '+') { 203 p++; 204 assert(p != end && "Exponent has no digits"); 205 } 206 207 unsignedExponent = 0; 208 overflow = false; 209 for (; p != end; ++p) { 210 unsigned int value; 211 212 value = decDigitValue(*p); 213 assert(value < 10U && "Invalid character in exponent"); 214 215 unsignedExponent = unsignedExponent * 10 + value; 216 if (unsignedExponent > 32767) { 217 overflow = true; 218 break; 219 } 220 } 221 222 if (exponentAdjustment > 32767 || exponentAdjustment < -32768) 223 overflow = true; 224 225 if (!overflow) { 226 exponent = unsignedExponent; 227 if (negative) 228 exponent = -exponent; 229 exponent += exponentAdjustment; 230 if (exponent > 32767 || exponent < -32768) 231 overflow = true; 232 } 233 234 if (overflow) 235 exponent = negative ? -32768: 32767; 236 237 return exponent; 238 } 239 240 static StringRef::iterator 241 skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end, 242 StringRef::iterator *dot) 243 { 244 StringRef::iterator p = begin; 245 *dot = end; 246 while (p != end && *p == '0') 247 p++; 248 249 if (p != end && *p == '.') { 250 *dot = p++; 251 252 assert(end - begin != 1 && "Significand has no digits"); 253 254 while (p != end && *p == '0') 255 p++; 256 } 257 258 return p; 259 } 260 261 /* Given a normal decimal floating point number of the form 262 263 dddd.dddd[eE][+-]ddd 264 265 where the decimal point and exponent are optional, fill out the 266 structure D. Exponent is appropriate if the significand is 267 treated as an integer, and normalizedExponent if the significand 268 is taken to have the decimal point after a single leading 269 non-zero digit. 270 271 If the value is zero, V->firstSigDigit points to a non-digit, and 272 the return exponent is zero. 273 */ 274 struct decimalInfo { 275 const char *firstSigDigit; 276 const char *lastSigDigit; 277 int exponent; 278 int normalizedExponent; 279 }; 280 281 static void 282 interpretDecimal(StringRef::iterator begin, StringRef::iterator end, 283 decimalInfo *D) 284 { 285 StringRef::iterator dot = end; 286 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot); 287 288 D->firstSigDigit = p; 289 D->exponent = 0; 290 D->normalizedExponent = 0; 291 292 for (; p != end; ++p) { 293 if (*p == '.') { 294 assert(dot == end && "String contains multiple dots"); 295 dot = p++; 296 if (p == end) 297 break; 298 } 299 if (decDigitValue(*p) >= 10U) 300 break; 301 } 302 303 if (p != end) { 304 assert((*p == 'e' || *p == 'E') && "Invalid character in significand"); 305 assert(p != begin && "Significand has no digits"); 306 assert((dot == end || p - begin != 1) && "Significand has no digits"); 307 308 /* p points to the first non-digit in the string */ 309 D->exponent = readExponent(p + 1, end); 310 311 /* Implied decimal point? */ 312 if (dot == end) 313 dot = p; 314 } 315 316 /* If number is all zeroes accept any exponent. */ 317 if (p != D->firstSigDigit) { 318 /* Drop insignificant trailing zeroes. */ 319 if (p != begin) { 320 do 321 do 322 p--; 323 while (p != begin && *p == '0'); 324 while (p != begin && *p == '.'); 325 } 326 327 /* Adjust the exponents for any decimal point. */ 328 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p)); 329 D->normalizedExponent = (D->exponent + 330 static_cast<APFloat::ExponentType>((p - D->firstSigDigit) 331 - (dot > D->firstSigDigit && dot < p))); 332 } 333 334 D->lastSigDigit = p; 335 } 336 337 /* Return the trailing fraction of a hexadecimal number. 338 DIGITVALUE is the first hex digit of the fraction, P points to 339 the next digit. */ 340 static lostFraction 341 trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, 342 unsigned int digitValue) 343 { 344 unsigned int hexDigit; 345 346 /* If the first trailing digit isn't 0 or 8 we can work out the 347 fraction immediately. */ 348 if (digitValue > 8) 349 return lfMoreThanHalf; 350 else if (digitValue < 8 && digitValue > 0) 351 return lfLessThanHalf; 352 353 // Otherwise we need to find the first non-zero digit. 354 while (p != end && (*p == '0' || *p == '.')) 355 p++; 356 357 assert(p != end && "Invalid trailing hexadecimal fraction!"); 358 359 hexDigit = hexDigitValue(*p); 360 361 /* If we ran off the end it is exactly zero or one-half, otherwise 362 a little more. */ 363 if (hexDigit == -1U) 364 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf; 365 else 366 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf; 367 } 368 369 /* Return the fraction lost were a bignum truncated losing the least 370 significant BITS bits. */ 371 static lostFraction 372 lostFractionThroughTruncation(const integerPart *parts, 373 unsigned int partCount, 374 unsigned int bits) 375 { 376 unsigned int lsb; 377 378 lsb = APInt::tcLSB(parts, partCount); 379 380 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */ 381 if (bits <= lsb) 382 return lfExactlyZero; 383 if (bits == lsb + 1) 384 return lfExactlyHalf; 385 if (bits <= partCount * integerPartWidth && 386 APInt::tcExtractBit(parts, bits - 1)) 387 return lfMoreThanHalf; 388 389 return lfLessThanHalf; 390 } 391 392 /* Shift DST right BITS bits noting lost fraction. */ 393 static lostFraction 394 shiftRight(integerPart *dst, unsigned int parts, unsigned int bits) 395 { 396 lostFraction lost_fraction; 397 398 lost_fraction = lostFractionThroughTruncation(dst, parts, bits); 399 400 APInt::tcShiftRight(dst, parts, bits); 401 402 return lost_fraction; 403 } 404 405 /* Combine the effect of two lost fractions. */ 406 static lostFraction 407 combineLostFractions(lostFraction moreSignificant, 408 lostFraction lessSignificant) 409 { 410 if (lessSignificant != lfExactlyZero) { 411 if (moreSignificant == lfExactlyZero) 412 moreSignificant = lfLessThanHalf; 413 else if (moreSignificant == lfExactlyHalf) 414 moreSignificant = lfMoreThanHalf; 415 } 416 417 return moreSignificant; 418 } 419 420 /* The error from the true value, in half-ulps, on multiplying two 421 floating point numbers, which differ from the value they 422 approximate by at most HUE1 and HUE2 half-ulps, is strictly less 423 than the returned value. 424 425 See "How to Read Floating Point Numbers Accurately" by William D 426 Clinger. */ 427 static unsigned int 428 HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2) 429 { 430 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8)); 431 432 if (HUerr1 + HUerr2 == 0) 433 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */ 434 else 435 return inexactMultiply + 2 * (HUerr1 + HUerr2); 436 } 437 438 /* The number of ulps from the boundary (zero, or half if ISNEAREST) 439 when the least significant BITS are truncated. BITS cannot be 440 zero. */ 441 static integerPart 442 ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest) 443 { 444 unsigned int count, partBits; 445 integerPart part, boundary; 446 447 assert(bits != 0); 448 449 bits--; 450 count = bits / integerPartWidth; 451 partBits = bits % integerPartWidth + 1; 452 453 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits)); 454 455 if (isNearest) 456 boundary = (integerPart) 1 << (partBits - 1); 457 else 458 boundary = 0; 459 460 if (count == 0) { 461 if (part - boundary <= boundary - part) 462 return part - boundary; 463 else 464 return boundary - part; 465 } 466 467 if (part == boundary) { 468 while (--count) 469 if (parts[count]) 470 return ~(integerPart) 0; /* A lot. */ 471 472 return parts[0]; 473 } else if (part == boundary - 1) { 474 while (--count) 475 if (~parts[count]) 476 return ~(integerPart) 0; /* A lot. */ 477 478 return -parts[0]; 479 } 480 481 return ~(integerPart) 0; /* A lot. */ 482 } 483 484 /* Place pow(5, power) in DST, and return the number of parts used. 485 DST must be at least one part larger than size of the answer. */ 486 static unsigned int 487 powerOf5(integerPart *dst, unsigned int power) 488 { 489 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 490 15625, 78125 }; 491 integerPart pow5s[maxPowerOfFiveParts * 2 + 5]; 492 pow5s[0] = 78125 * 5; 493 494 unsigned int partsCount[16] = { 1 }; 495 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5; 496 unsigned int result; 497 assert(power <= maxExponent); 498 499 p1 = dst; 500 p2 = scratch; 501 502 *p1 = firstEightPowers[power & 7]; 503 power >>= 3; 504 505 result = 1; 506 pow5 = pow5s; 507 508 for (unsigned int n = 0; power; power >>= 1, n++) { 509 unsigned int pc; 510 511 pc = partsCount[n]; 512 513 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */ 514 if (pc == 0) { 515 pc = partsCount[n - 1]; 516 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc); 517 pc *= 2; 518 if (pow5[pc - 1] == 0) 519 pc--; 520 partsCount[n] = pc; 521 } 522 523 if (power & 1) { 524 integerPart *tmp; 525 526 APInt::tcFullMultiply(p2, p1, pow5, result, pc); 527 result += pc; 528 if (p2[result - 1] == 0) 529 result--; 530 531 /* Now result is in p1 with partsCount parts and p2 is scratch 532 space. */ 533 tmp = p1; 534 p1 = p2; 535 p2 = tmp; 536 } 537 538 pow5 += pc; 539 } 540 541 if (p1 != dst) 542 APInt::tcAssign(dst, p1, result); 543 544 return result; 545 } 546 547 /* Zero at the end to avoid modular arithmetic when adding one; used 548 when rounding up during hexadecimal output. */ 549 static const char hexDigitsLower[] = "0123456789abcdef0"; 550 static const char hexDigitsUpper[] = "0123456789ABCDEF0"; 551 static const char infinityL[] = "infinity"; 552 static const char infinityU[] = "INFINITY"; 553 static const char NaNL[] = "nan"; 554 static const char NaNU[] = "NAN"; 555 556 /* Write out an integerPart in hexadecimal, starting with the most 557 significant nibble. Write out exactly COUNT hexdigits, return 558 COUNT. */ 559 static unsigned int 560 partAsHex (char *dst, integerPart part, unsigned int count, 561 const char *hexDigitChars) 562 { 563 unsigned int result = count; 564 565 assert(count != 0 && count <= integerPartWidth / 4); 566 567 part >>= (integerPartWidth - 4 * count); 568 while (count--) { 569 dst[count] = hexDigitChars[part & 0xf]; 570 part >>= 4; 571 } 572 573 return result; 574 } 575 576 /* Write out an unsigned decimal integer. */ 577 static char * 578 writeUnsignedDecimal (char *dst, unsigned int n) 579 { 580 char buff[40], *p; 581 582 p = buff; 583 do 584 *p++ = '0' + n % 10; 585 while (n /= 10); 586 587 do 588 *dst++ = *--p; 589 while (p != buff); 590 591 return dst; 592 } 593 594 /* Write out a signed decimal integer. */ 595 static char * 596 writeSignedDecimal (char *dst, int value) 597 { 598 if (value < 0) { 599 *dst++ = '-'; 600 dst = writeUnsignedDecimal(dst, -(unsigned) value); 601 } else 602 dst = writeUnsignedDecimal(dst, value); 603 604 return dst; 605 } 606 607 namespace detail { 608 /* Constructors. */ 609 void IEEEFloat::initialize(const fltSemantics *ourSemantics) { 610 unsigned int count; 611 612 semantics = ourSemantics; 613 count = partCount(); 614 if (count > 1) 615 significand.parts = new integerPart[count]; 616 } 617 618 void IEEEFloat::freeSignificand() { 619 if (needsCleanup()) 620 delete [] significand.parts; 621 } 622 623 void IEEEFloat::assign(const IEEEFloat &rhs) { 624 assert(semantics == rhs.semantics); 625 626 sign = rhs.sign; 627 category = rhs.category; 628 exponent = rhs.exponent; 629 if (isFiniteNonZero() || category == fcNaN) 630 copySignificand(rhs); 631 } 632 633 void IEEEFloat::copySignificand(const IEEEFloat &rhs) { 634 assert(isFiniteNonZero() || category == fcNaN); 635 assert(rhs.partCount() >= partCount()); 636 637 APInt::tcAssign(significandParts(), rhs.significandParts(), 638 partCount()); 639 } 640 641 /* Make this number a NaN, with an arbitrary but deterministic value 642 for the significand. If double or longer, this is a signalling NaN, 643 which may not be ideal. If float, this is QNaN(0). */ 644 void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) { 645 category = fcNaN; 646 sign = Negative; 647 648 integerPart *significand = significandParts(); 649 unsigned numParts = partCount(); 650 651 // Set the significand bits to the fill. 652 if (!fill || fill->getNumWords() < numParts) 653 APInt::tcSet(significand, 0, numParts); 654 if (fill) { 655 APInt::tcAssign(significand, fill->getRawData(), 656 std::min(fill->getNumWords(), numParts)); 657 658 // Zero out the excess bits of the significand. 659 unsigned bitsToPreserve = semantics->precision - 1; 660 unsigned part = bitsToPreserve / 64; 661 bitsToPreserve %= 64; 662 significand[part] &= ((1ULL << bitsToPreserve) - 1); 663 for (part++; part != numParts; ++part) 664 significand[part] = 0; 665 } 666 667 unsigned QNaNBit = semantics->precision - 2; 668 669 if (SNaN) { 670 // We always have to clear the QNaN bit to make it an SNaN. 671 APInt::tcClearBit(significand, QNaNBit); 672 673 // If there are no bits set in the payload, we have to set 674 // *something* to make it a NaN instead of an infinity; 675 // conventionally, this is the next bit down from the QNaN bit. 676 if (APInt::tcIsZero(significand, numParts)) 677 APInt::tcSetBit(significand, QNaNBit - 1); 678 } else { 679 // We always have to set the QNaN bit to make it a QNaN. 680 APInt::tcSetBit(significand, QNaNBit); 681 } 682 683 // For x87 extended precision, we want to make a NaN, not a 684 // pseudo-NaN. Maybe we should expose the ability to make 685 // pseudo-NaNs? 686 if (semantics == &APFloat::x87DoubleExtended) 687 APInt::tcSetBit(significand, QNaNBit + 1); 688 } 689 690 IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) { 691 if (this != &rhs) { 692 if (semantics != rhs.semantics) { 693 freeSignificand(); 694 initialize(rhs.semantics); 695 } 696 assign(rhs); 697 } 698 699 return *this; 700 } 701 702 IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) { 703 freeSignificand(); 704 705 semantics = rhs.semantics; 706 significand = rhs.significand; 707 exponent = rhs.exponent; 708 category = rhs.category; 709 sign = rhs.sign; 710 711 rhs.semantics = &Bogus; 712 return *this; 713 } 714 715 bool IEEEFloat::isDenormal() const { 716 return isFiniteNonZero() && (exponent == semantics->minExponent) && 717 (APInt::tcExtractBit(significandParts(), 718 semantics->precision - 1) == 0); 719 } 720 721 bool IEEEFloat::isSmallest() const { 722 // The smallest number by magnitude in our format will be the smallest 723 // denormal, i.e. the floating point number with exponent being minimum 724 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0). 725 return isFiniteNonZero() && exponent == semantics->minExponent && 726 significandMSB() == 0; 727 } 728 729 bool IEEEFloat::isSignificandAllOnes() const { 730 // Test if the significand excluding the integral bit is all ones. This allows 731 // us to test for binade boundaries. 732 const integerPart *Parts = significandParts(); 733 const unsigned PartCount = partCount(); 734 for (unsigned i = 0; i < PartCount - 1; i++) 735 if (~Parts[i]) 736 return false; 737 738 // Set the unused high bits to all ones when we compare. 739 const unsigned NumHighBits = 740 PartCount*integerPartWidth - semantics->precision + 1; 741 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to " 742 "fill than integerPartWidth"); 743 const integerPart HighBitFill = 744 ~integerPart(0) << (integerPartWidth - NumHighBits); 745 if (~(Parts[PartCount - 1] | HighBitFill)) 746 return false; 747 748 return true; 749 } 750 751 bool IEEEFloat::isSignificandAllZeros() const { 752 // Test if the significand excluding the integral bit is all zeros. This 753 // allows us to test for binade boundaries. 754 const integerPart *Parts = significandParts(); 755 const unsigned PartCount = partCount(); 756 757 for (unsigned i = 0; i < PartCount - 1; i++) 758 if (Parts[i]) 759 return false; 760 761 const unsigned NumHighBits = 762 PartCount*integerPartWidth - semantics->precision + 1; 763 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to " 764 "clear than integerPartWidth"); 765 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits; 766 767 if (Parts[PartCount - 1] & HighBitMask) 768 return false; 769 770 return true; 771 } 772 773 bool IEEEFloat::isLargest() const { 774 // The largest number by magnitude in our format will be the floating point 775 // number with maximum exponent and with significand that is all ones. 776 return isFiniteNonZero() && exponent == semantics->maxExponent 777 && isSignificandAllOnes(); 778 } 779 780 bool IEEEFloat::isInteger() const { 781 // This could be made more efficient; I'm going for obviously correct. 782 if (!isFinite()) return false; 783 IEEEFloat truncated = *this; 784 truncated.roundToIntegral(rmTowardZero); 785 return compare(truncated) == cmpEqual; 786 } 787 788 bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const { 789 if (this == &rhs) 790 return true; 791 if (semantics != rhs.semantics || 792 category != rhs.category || 793 sign != rhs.sign) 794 return false; 795 if (category==fcZero || category==fcInfinity) 796 return true; 797 798 if (isFiniteNonZero() && exponent != rhs.exponent) 799 return false; 800 801 return std::equal(significandParts(), significandParts() + partCount(), 802 rhs.significandParts()); 803 } 804 805 IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) { 806 initialize(&ourSemantics); 807 sign = 0; 808 category = fcNormal; 809 zeroSignificand(); 810 exponent = ourSemantics.precision - 1; 811 significandParts()[0] = value; 812 normalize(rmNearestTiesToEven, lfExactlyZero); 813 } 814 815 IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) { 816 initialize(&ourSemantics); 817 category = fcZero; 818 sign = false; 819 } 820 821 // Delegate to the previous constructor, because later copy constructor may 822 // actually inspects category, which can't be garbage. 823 IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag) 824 : IEEEFloat(ourSemantics) {} 825 826 IEEEFloat::IEEEFloat(const IEEEFloat &rhs) { 827 initialize(rhs.semantics); 828 assign(rhs); 829 } 830 831 IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&Bogus) { 832 *this = std::move(rhs); 833 } 834 835 IEEEFloat::~IEEEFloat() { freeSignificand(); } 836 837 // Profile - This method 'profiles' an APFloat for use with FoldingSet. 838 void IEEEFloat::Profile(FoldingSetNodeID &ID) const { 839 ID.Add(bitcastToAPInt()); 840 } 841 842 unsigned int IEEEFloat::partCount() const { 843 return partCountForBits(semantics->precision + 1); 844 } 845 846 const integerPart *IEEEFloat::significandParts() const { 847 return const_cast<IEEEFloat *>(this)->significandParts(); 848 } 849 850 integerPart *IEEEFloat::significandParts() { 851 if (partCount() > 1) 852 return significand.parts; 853 else 854 return &significand.part; 855 } 856 857 void IEEEFloat::zeroSignificand() { 858 APInt::tcSet(significandParts(), 0, partCount()); 859 } 860 861 /* Increment an fcNormal floating point number's significand. */ 862 void IEEEFloat::incrementSignificand() { 863 integerPart carry; 864 865 carry = APInt::tcIncrement(significandParts(), partCount()); 866 867 /* Our callers should never cause us to overflow. */ 868 assert(carry == 0); 869 (void)carry; 870 } 871 872 /* Add the significand of the RHS. Returns the carry flag. */ 873 integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) { 874 integerPart *parts; 875 876 parts = significandParts(); 877 878 assert(semantics == rhs.semantics); 879 assert(exponent == rhs.exponent); 880 881 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount()); 882 } 883 884 /* Subtract the significand of the RHS with a borrow flag. Returns 885 the borrow flag. */ 886 integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs, 887 integerPart borrow) { 888 integerPart *parts; 889 890 parts = significandParts(); 891 892 assert(semantics == rhs.semantics); 893 assert(exponent == rhs.exponent); 894 895 return APInt::tcSubtract(parts, rhs.significandParts(), borrow, 896 partCount()); 897 } 898 899 /* Multiply the significand of the RHS. If ADDEND is non-NULL, add it 900 on to the full-precision result of the multiplication. Returns the 901 lost fraction. */ 902 lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs, 903 const IEEEFloat *addend) { 904 unsigned int omsb; // One, not zero, based MSB. 905 unsigned int partsCount, newPartsCount, precision; 906 integerPart *lhsSignificand; 907 integerPart scratch[4]; 908 integerPart *fullSignificand; 909 lostFraction lost_fraction; 910 bool ignored; 911 912 assert(semantics == rhs.semantics); 913 914 precision = semantics->precision; 915 916 // Allocate space for twice as many bits as the original significand, plus one 917 // extra bit for the addition to overflow into. 918 newPartsCount = partCountForBits(precision * 2 + 1); 919 920 if (newPartsCount > 4) 921 fullSignificand = new integerPart[newPartsCount]; 922 else 923 fullSignificand = scratch; 924 925 lhsSignificand = significandParts(); 926 partsCount = partCount(); 927 928 APInt::tcFullMultiply(fullSignificand, lhsSignificand, 929 rhs.significandParts(), partsCount, partsCount); 930 931 lost_fraction = lfExactlyZero; 932 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1; 933 exponent += rhs.exponent; 934 935 // Assume the operands involved in the multiplication are single-precision 936 // FP, and the two multiplicants are: 937 // *this = a23 . a22 ... a0 * 2^e1 938 // rhs = b23 . b22 ... b0 * 2^e2 939 // the result of multiplication is: 940 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2) 941 // Note that there are three significant bits at the left-hand side of the 942 // radix point: two for the multiplication, and an overflow bit for the 943 // addition (that will always be zero at this point). Move the radix point 944 // toward left by two bits, and adjust exponent accordingly. 945 exponent += 2; 946 947 if (addend && addend->isNonZero()) { 948 // The intermediate result of the multiplication has "2 * precision" 949 // signicant bit; adjust the addend to be consistent with mul result. 950 // 951 Significand savedSignificand = significand; 952 const fltSemantics *savedSemantics = semantics; 953 fltSemantics extendedSemantics; 954 opStatus status; 955 unsigned int extendedPrecision; 956 957 // Normalize our MSB to one below the top bit to allow for overflow. 958 extendedPrecision = 2 * precision + 1; 959 if (omsb != extendedPrecision - 1) { 960 assert(extendedPrecision > omsb); 961 APInt::tcShiftLeft(fullSignificand, newPartsCount, 962 (extendedPrecision - 1) - omsb); 963 exponent -= (extendedPrecision - 1) - omsb; 964 } 965 966 /* Create new semantics. */ 967 extendedSemantics = *semantics; 968 extendedSemantics.precision = extendedPrecision; 969 970 if (newPartsCount == 1) 971 significand.part = fullSignificand[0]; 972 else 973 significand.parts = fullSignificand; 974 semantics = &extendedSemantics; 975 976 IEEEFloat extendedAddend(*addend); 977 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored); 978 assert(status == opOK); 979 (void)status; 980 981 // Shift the significand of the addend right by one bit. This guarantees 982 // that the high bit of the significand is zero (same as fullSignificand), 983 // so the addition will overflow (if it does overflow at all) into the top bit. 984 lost_fraction = extendedAddend.shiftSignificandRight(1); 985 assert(lost_fraction == lfExactlyZero && 986 "Lost precision while shifting addend for fused-multiply-add."); 987 988 lost_fraction = addOrSubtractSignificand(extendedAddend, false); 989 990 /* Restore our state. */ 991 if (newPartsCount == 1) 992 fullSignificand[0] = significand.part; 993 significand = savedSignificand; 994 semantics = savedSemantics; 995 996 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1; 997 } 998 999 // Convert the result having "2 * precision" significant-bits back to the one 1000 // having "precision" significant-bits. First, move the radix point from 1001 // poision "2*precision - 1" to "precision - 1". The exponent need to be 1002 // adjusted by "2*precision - 1" - "precision - 1" = "precision". 1003 exponent -= precision + 1; 1004 1005 // In case MSB resides at the left-hand side of radix point, shift the 1006 // mantissa right by some amount to make sure the MSB reside right before 1007 // the radix point (i.e. "MSB . rest-significant-bits"). 1008 // 1009 // Note that the result is not normalized when "omsb < precision". So, the 1010 // caller needs to call IEEEFloat::normalize() if normalized value is 1011 // expected. 1012 if (omsb > precision) { 1013 unsigned int bits, significantParts; 1014 lostFraction lf; 1015 1016 bits = omsb - precision; 1017 significantParts = partCountForBits(omsb); 1018 lf = shiftRight(fullSignificand, significantParts, bits); 1019 lost_fraction = combineLostFractions(lf, lost_fraction); 1020 exponent += bits; 1021 } 1022 1023 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount); 1024 1025 if (newPartsCount > 4) 1026 delete [] fullSignificand; 1027 1028 return lost_fraction; 1029 } 1030 1031 /* Multiply the significands of LHS and RHS to DST. */ 1032 lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) { 1033 unsigned int bit, i, partsCount; 1034 const integerPart *rhsSignificand; 1035 integerPart *lhsSignificand, *dividend, *divisor; 1036 integerPart scratch[4]; 1037 lostFraction lost_fraction; 1038 1039 assert(semantics == rhs.semantics); 1040 1041 lhsSignificand = significandParts(); 1042 rhsSignificand = rhs.significandParts(); 1043 partsCount = partCount(); 1044 1045 if (partsCount > 2) 1046 dividend = new integerPart[partsCount * 2]; 1047 else 1048 dividend = scratch; 1049 1050 divisor = dividend + partsCount; 1051 1052 /* Copy the dividend and divisor as they will be modified in-place. */ 1053 for (i = 0; i < partsCount; i++) { 1054 dividend[i] = lhsSignificand[i]; 1055 divisor[i] = rhsSignificand[i]; 1056 lhsSignificand[i] = 0; 1057 } 1058 1059 exponent -= rhs.exponent; 1060 1061 unsigned int precision = semantics->precision; 1062 1063 /* Normalize the divisor. */ 1064 bit = precision - APInt::tcMSB(divisor, partsCount) - 1; 1065 if (bit) { 1066 exponent += bit; 1067 APInt::tcShiftLeft(divisor, partsCount, bit); 1068 } 1069 1070 /* Normalize the dividend. */ 1071 bit = precision - APInt::tcMSB(dividend, partsCount) - 1; 1072 if (bit) { 1073 exponent -= bit; 1074 APInt::tcShiftLeft(dividend, partsCount, bit); 1075 } 1076 1077 /* Ensure the dividend >= divisor initially for the loop below. 1078 Incidentally, this means that the division loop below is 1079 guaranteed to set the integer bit to one. */ 1080 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) { 1081 exponent--; 1082 APInt::tcShiftLeft(dividend, partsCount, 1); 1083 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0); 1084 } 1085 1086 /* Long division. */ 1087 for (bit = precision; bit; bit -= 1) { 1088 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) { 1089 APInt::tcSubtract(dividend, divisor, 0, partsCount); 1090 APInt::tcSetBit(lhsSignificand, bit - 1); 1091 } 1092 1093 APInt::tcShiftLeft(dividend, partsCount, 1); 1094 } 1095 1096 /* Figure out the lost fraction. */ 1097 int cmp = APInt::tcCompare(dividend, divisor, partsCount); 1098 1099 if (cmp > 0) 1100 lost_fraction = lfMoreThanHalf; 1101 else if (cmp == 0) 1102 lost_fraction = lfExactlyHalf; 1103 else if (APInt::tcIsZero(dividend, partsCount)) 1104 lost_fraction = lfExactlyZero; 1105 else 1106 lost_fraction = lfLessThanHalf; 1107 1108 if (partsCount > 2) 1109 delete [] dividend; 1110 1111 return lost_fraction; 1112 } 1113 1114 unsigned int IEEEFloat::significandMSB() const { 1115 return APInt::tcMSB(significandParts(), partCount()); 1116 } 1117 1118 unsigned int IEEEFloat::significandLSB() const { 1119 return APInt::tcLSB(significandParts(), partCount()); 1120 } 1121 1122 /* Note that a zero result is NOT normalized to fcZero. */ 1123 lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) { 1124 /* Our exponent should not overflow. */ 1125 assert((ExponentType) (exponent + bits) >= exponent); 1126 1127 exponent += bits; 1128 1129 return shiftRight(significandParts(), partCount(), bits); 1130 } 1131 1132 /* Shift the significand left BITS bits, subtract BITS from its exponent. */ 1133 void IEEEFloat::shiftSignificandLeft(unsigned int bits) { 1134 assert(bits < semantics->precision); 1135 1136 if (bits) { 1137 unsigned int partsCount = partCount(); 1138 1139 APInt::tcShiftLeft(significandParts(), partsCount, bits); 1140 exponent -= bits; 1141 1142 assert(!APInt::tcIsZero(significandParts(), partsCount)); 1143 } 1144 } 1145 1146 IEEEFloat::cmpResult 1147 IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const { 1148 int compare; 1149 1150 assert(semantics == rhs.semantics); 1151 assert(isFiniteNonZero()); 1152 assert(rhs.isFiniteNonZero()); 1153 1154 compare = exponent - rhs.exponent; 1155 1156 /* If exponents are equal, do an unsigned bignum comparison of the 1157 significands. */ 1158 if (compare == 0) 1159 compare = APInt::tcCompare(significandParts(), rhs.significandParts(), 1160 partCount()); 1161 1162 if (compare > 0) 1163 return cmpGreaterThan; 1164 else if (compare < 0) 1165 return cmpLessThan; 1166 else 1167 return cmpEqual; 1168 } 1169 1170 /* Handle overflow. Sign is preserved. We either become infinity or 1171 the largest finite number. */ 1172 IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) { 1173 /* Infinity? */ 1174 if (rounding_mode == rmNearestTiesToEven || 1175 rounding_mode == rmNearestTiesToAway || 1176 (rounding_mode == rmTowardPositive && !sign) || 1177 (rounding_mode == rmTowardNegative && sign)) { 1178 category = fcInfinity; 1179 return (opStatus) (opOverflow | opInexact); 1180 } 1181 1182 /* Otherwise we become the largest finite number. */ 1183 category = fcNormal; 1184 exponent = semantics->maxExponent; 1185 APInt::tcSetLeastSignificantBits(significandParts(), partCount(), 1186 semantics->precision); 1187 1188 return opInexact; 1189 } 1190 1191 /* Returns TRUE if, when truncating the current number, with BIT the 1192 new LSB, with the given lost fraction and rounding mode, the result 1193 would need to be rounded away from zero (i.e., by increasing the 1194 signficand). This routine must work for fcZero of both signs, and 1195 fcNormal numbers. */ 1196 bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode, 1197 lostFraction lost_fraction, 1198 unsigned int bit) const { 1199 /* NaNs and infinities should not have lost fractions. */ 1200 assert(isFiniteNonZero() || category == fcZero); 1201 1202 /* Current callers never pass this so we don't handle it. */ 1203 assert(lost_fraction != lfExactlyZero); 1204 1205 switch (rounding_mode) { 1206 case rmNearestTiesToAway: 1207 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf; 1208 1209 case rmNearestTiesToEven: 1210 if (lost_fraction == lfMoreThanHalf) 1211 return true; 1212 1213 /* Our zeroes don't have a significand to test. */ 1214 if (lost_fraction == lfExactlyHalf && category != fcZero) 1215 return APInt::tcExtractBit(significandParts(), bit); 1216 1217 return false; 1218 1219 case rmTowardZero: 1220 return false; 1221 1222 case rmTowardPositive: 1223 return !sign; 1224 1225 case rmTowardNegative: 1226 return sign; 1227 } 1228 llvm_unreachable("Invalid rounding mode found"); 1229 } 1230 1231 IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode, 1232 lostFraction lost_fraction) { 1233 unsigned int omsb; /* One, not zero, based MSB. */ 1234 int exponentChange; 1235 1236 if (!isFiniteNonZero()) 1237 return opOK; 1238 1239 /* Before rounding normalize the exponent of fcNormal numbers. */ 1240 omsb = significandMSB() + 1; 1241 1242 if (omsb) { 1243 /* OMSB is numbered from 1. We want to place it in the integer 1244 bit numbered PRECISION if possible, with a compensating change in 1245 the exponent. */ 1246 exponentChange = omsb - semantics->precision; 1247 1248 /* If the resulting exponent is too high, overflow according to 1249 the rounding mode. */ 1250 if (exponent + exponentChange > semantics->maxExponent) 1251 return handleOverflow(rounding_mode); 1252 1253 /* Subnormal numbers have exponent minExponent, and their MSB 1254 is forced based on that. */ 1255 if (exponent + exponentChange < semantics->minExponent) 1256 exponentChange = semantics->minExponent - exponent; 1257 1258 /* Shifting left is easy as we don't lose precision. */ 1259 if (exponentChange < 0) { 1260 assert(lost_fraction == lfExactlyZero); 1261 1262 shiftSignificandLeft(-exponentChange); 1263 1264 return opOK; 1265 } 1266 1267 if (exponentChange > 0) { 1268 lostFraction lf; 1269 1270 /* Shift right and capture any new lost fraction. */ 1271 lf = shiftSignificandRight(exponentChange); 1272 1273 lost_fraction = combineLostFractions(lf, lost_fraction); 1274 1275 /* Keep OMSB up-to-date. */ 1276 if (omsb > (unsigned) exponentChange) 1277 omsb -= exponentChange; 1278 else 1279 omsb = 0; 1280 } 1281 } 1282 1283 /* Now round the number according to rounding_mode given the lost 1284 fraction. */ 1285 1286 /* As specified in IEEE 754, since we do not trap we do not report 1287 underflow for exact results. */ 1288 if (lost_fraction == lfExactlyZero) { 1289 /* Canonicalize zeroes. */ 1290 if (omsb == 0) 1291 category = fcZero; 1292 1293 return opOK; 1294 } 1295 1296 /* Increment the significand if we're rounding away from zero. */ 1297 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) { 1298 if (omsb == 0) 1299 exponent = semantics->minExponent; 1300 1301 incrementSignificand(); 1302 omsb = significandMSB() + 1; 1303 1304 /* Did the significand increment overflow? */ 1305 if (omsb == (unsigned) semantics->precision + 1) { 1306 /* Renormalize by incrementing the exponent and shifting our 1307 significand right one. However if we already have the 1308 maximum exponent we overflow to infinity. */ 1309 if (exponent == semantics->maxExponent) { 1310 category = fcInfinity; 1311 1312 return (opStatus) (opOverflow | opInexact); 1313 } 1314 1315 shiftSignificandRight(1); 1316 1317 return opInexact; 1318 } 1319 } 1320 1321 /* The normal case - we were and are not denormal, and any 1322 significand increment above didn't overflow. */ 1323 if (omsb == semantics->precision) 1324 return opInexact; 1325 1326 /* We have a non-zero denormal. */ 1327 assert(omsb < semantics->precision); 1328 1329 /* Canonicalize zeroes. */ 1330 if (omsb == 0) 1331 category = fcZero; 1332 1333 /* The fcZero case is a denormal that underflowed to zero. */ 1334 return (opStatus) (opUnderflow | opInexact); 1335 } 1336 1337 IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs, 1338 bool subtract) { 1339 switch (PackCategoriesIntoKey(category, rhs.category)) { 1340 default: 1341 llvm_unreachable(nullptr); 1342 1343 case PackCategoriesIntoKey(fcNaN, fcZero): 1344 case PackCategoriesIntoKey(fcNaN, fcNormal): 1345 case PackCategoriesIntoKey(fcNaN, fcInfinity): 1346 case PackCategoriesIntoKey(fcNaN, fcNaN): 1347 case PackCategoriesIntoKey(fcNormal, fcZero): 1348 case PackCategoriesIntoKey(fcInfinity, fcNormal): 1349 case PackCategoriesIntoKey(fcInfinity, fcZero): 1350 return opOK; 1351 1352 case PackCategoriesIntoKey(fcZero, fcNaN): 1353 case PackCategoriesIntoKey(fcNormal, fcNaN): 1354 case PackCategoriesIntoKey(fcInfinity, fcNaN): 1355 // We need to be sure to flip the sign here for subtraction because we 1356 // don't have a separate negate operation so -NaN becomes 0 - NaN here. 1357 sign = rhs.sign ^ subtract; 1358 category = fcNaN; 1359 copySignificand(rhs); 1360 return opOK; 1361 1362 case PackCategoriesIntoKey(fcNormal, fcInfinity): 1363 case PackCategoriesIntoKey(fcZero, fcInfinity): 1364 category = fcInfinity; 1365 sign = rhs.sign ^ subtract; 1366 return opOK; 1367 1368 case PackCategoriesIntoKey(fcZero, fcNormal): 1369 assign(rhs); 1370 sign = rhs.sign ^ subtract; 1371 return opOK; 1372 1373 case PackCategoriesIntoKey(fcZero, fcZero): 1374 /* Sign depends on rounding mode; handled by caller. */ 1375 return opOK; 1376 1377 case PackCategoriesIntoKey(fcInfinity, fcInfinity): 1378 /* Differently signed infinities can only be validly 1379 subtracted. */ 1380 if (((sign ^ rhs.sign)!=0) != subtract) { 1381 makeNaN(); 1382 return opInvalidOp; 1383 } 1384 1385 return opOK; 1386 1387 case PackCategoriesIntoKey(fcNormal, fcNormal): 1388 return opDivByZero; 1389 } 1390 } 1391 1392 /* Add or subtract two normal numbers. */ 1393 lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs, 1394 bool subtract) { 1395 integerPart carry; 1396 lostFraction lost_fraction; 1397 int bits; 1398 1399 /* Determine if the operation on the absolute values is effectively 1400 an addition or subtraction. */ 1401 subtract ^= static_cast<bool>(sign ^ rhs.sign); 1402 1403 /* Are we bigger exponent-wise than the RHS? */ 1404 bits = exponent - rhs.exponent; 1405 1406 /* Subtraction is more subtle than one might naively expect. */ 1407 if (subtract) { 1408 IEEEFloat temp_rhs(rhs); 1409 bool reverse; 1410 1411 if (bits == 0) { 1412 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan; 1413 lost_fraction = lfExactlyZero; 1414 } else if (bits > 0) { 1415 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1); 1416 shiftSignificandLeft(1); 1417 reverse = false; 1418 } else { 1419 lost_fraction = shiftSignificandRight(-bits - 1); 1420 temp_rhs.shiftSignificandLeft(1); 1421 reverse = true; 1422 } 1423 1424 if (reverse) { 1425 carry = temp_rhs.subtractSignificand 1426 (*this, lost_fraction != lfExactlyZero); 1427 copySignificand(temp_rhs); 1428 sign = !sign; 1429 } else { 1430 carry = subtractSignificand 1431 (temp_rhs, lost_fraction != lfExactlyZero); 1432 } 1433 1434 /* Invert the lost fraction - it was on the RHS and 1435 subtracted. */ 1436 if (lost_fraction == lfLessThanHalf) 1437 lost_fraction = lfMoreThanHalf; 1438 else if (lost_fraction == lfMoreThanHalf) 1439 lost_fraction = lfLessThanHalf; 1440 1441 /* The code above is intended to ensure that no borrow is 1442 necessary. */ 1443 assert(!carry); 1444 (void)carry; 1445 } else { 1446 if (bits > 0) { 1447 IEEEFloat temp_rhs(rhs); 1448 1449 lost_fraction = temp_rhs.shiftSignificandRight(bits); 1450 carry = addSignificand(temp_rhs); 1451 } else { 1452 lost_fraction = shiftSignificandRight(-bits); 1453 carry = addSignificand(rhs); 1454 } 1455 1456 /* We have a guard bit; generating a carry cannot happen. */ 1457 assert(!carry); 1458 (void)carry; 1459 } 1460 1461 return lost_fraction; 1462 } 1463 1464 IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) { 1465 switch (PackCategoriesIntoKey(category, rhs.category)) { 1466 default: 1467 llvm_unreachable(nullptr); 1468 1469 case PackCategoriesIntoKey(fcNaN, fcZero): 1470 case PackCategoriesIntoKey(fcNaN, fcNormal): 1471 case PackCategoriesIntoKey(fcNaN, fcInfinity): 1472 case PackCategoriesIntoKey(fcNaN, fcNaN): 1473 sign = false; 1474 return opOK; 1475 1476 case PackCategoriesIntoKey(fcZero, fcNaN): 1477 case PackCategoriesIntoKey(fcNormal, fcNaN): 1478 case PackCategoriesIntoKey(fcInfinity, fcNaN): 1479 sign = false; 1480 category = fcNaN; 1481 copySignificand(rhs); 1482 return opOK; 1483 1484 case PackCategoriesIntoKey(fcNormal, fcInfinity): 1485 case PackCategoriesIntoKey(fcInfinity, fcNormal): 1486 case PackCategoriesIntoKey(fcInfinity, fcInfinity): 1487 category = fcInfinity; 1488 return opOK; 1489 1490 case PackCategoriesIntoKey(fcZero, fcNormal): 1491 case PackCategoriesIntoKey(fcNormal, fcZero): 1492 case PackCategoriesIntoKey(fcZero, fcZero): 1493 category = fcZero; 1494 return opOK; 1495 1496 case PackCategoriesIntoKey(fcZero, fcInfinity): 1497 case PackCategoriesIntoKey(fcInfinity, fcZero): 1498 makeNaN(); 1499 return opInvalidOp; 1500 1501 case PackCategoriesIntoKey(fcNormal, fcNormal): 1502 return opOK; 1503 } 1504 } 1505 1506 IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) { 1507 switch (PackCategoriesIntoKey(category, rhs.category)) { 1508 default: 1509 llvm_unreachable(nullptr); 1510 1511 case PackCategoriesIntoKey(fcZero, fcNaN): 1512 case PackCategoriesIntoKey(fcNormal, fcNaN): 1513 case PackCategoriesIntoKey(fcInfinity, fcNaN): 1514 category = fcNaN; 1515 copySignificand(rhs); 1516 case PackCategoriesIntoKey(fcNaN, fcZero): 1517 case PackCategoriesIntoKey(fcNaN, fcNormal): 1518 case PackCategoriesIntoKey(fcNaN, fcInfinity): 1519 case PackCategoriesIntoKey(fcNaN, fcNaN): 1520 sign = false; 1521 case PackCategoriesIntoKey(fcInfinity, fcZero): 1522 case PackCategoriesIntoKey(fcInfinity, fcNormal): 1523 case PackCategoriesIntoKey(fcZero, fcInfinity): 1524 case PackCategoriesIntoKey(fcZero, fcNormal): 1525 return opOK; 1526 1527 case PackCategoriesIntoKey(fcNormal, fcInfinity): 1528 category = fcZero; 1529 return opOK; 1530 1531 case PackCategoriesIntoKey(fcNormal, fcZero): 1532 category = fcInfinity; 1533 return opDivByZero; 1534 1535 case PackCategoriesIntoKey(fcInfinity, fcInfinity): 1536 case PackCategoriesIntoKey(fcZero, fcZero): 1537 makeNaN(); 1538 return opInvalidOp; 1539 1540 case PackCategoriesIntoKey(fcNormal, fcNormal): 1541 return opOK; 1542 } 1543 } 1544 1545 IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) { 1546 switch (PackCategoriesIntoKey(category, rhs.category)) { 1547 default: 1548 llvm_unreachable(nullptr); 1549 1550 case PackCategoriesIntoKey(fcNaN, fcZero): 1551 case PackCategoriesIntoKey(fcNaN, fcNormal): 1552 case PackCategoriesIntoKey(fcNaN, fcInfinity): 1553 case PackCategoriesIntoKey(fcNaN, fcNaN): 1554 case PackCategoriesIntoKey(fcZero, fcInfinity): 1555 case PackCategoriesIntoKey(fcZero, fcNormal): 1556 case PackCategoriesIntoKey(fcNormal, fcInfinity): 1557 return opOK; 1558 1559 case PackCategoriesIntoKey(fcZero, fcNaN): 1560 case PackCategoriesIntoKey(fcNormal, fcNaN): 1561 case PackCategoriesIntoKey(fcInfinity, fcNaN): 1562 sign = false; 1563 category = fcNaN; 1564 copySignificand(rhs); 1565 return opOK; 1566 1567 case PackCategoriesIntoKey(fcNormal, fcZero): 1568 case PackCategoriesIntoKey(fcInfinity, fcZero): 1569 case PackCategoriesIntoKey(fcInfinity, fcNormal): 1570 case PackCategoriesIntoKey(fcInfinity, fcInfinity): 1571 case PackCategoriesIntoKey(fcZero, fcZero): 1572 makeNaN(); 1573 return opInvalidOp; 1574 1575 case PackCategoriesIntoKey(fcNormal, fcNormal): 1576 return opOK; 1577 } 1578 } 1579 1580 /* Change sign. */ 1581 void IEEEFloat::changeSign() { 1582 /* Look mummy, this one's easy. */ 1583 sign = !sign; 1584 } 1585 1586 void IEEEFloat::clearSign() { 1587 /* So is this one. */ 1588 sign = 0; 1589 } 1590 1591 void IEEEFloat::copySign(const IEEEFloat &rhs) { 1592 /* And this one. */ 1593 sign = rhs.sign; 1594 } 1595 1596 /* Normalized addition or subtraction. */ 1597 IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs, 1598 roundingMode rounding_mode, 1599 bool subtract) { 1600 opStatus fs; 1601 1602 fs = addOrSubtractSpecials(rhs, subtract); 1603 1604 /* This return code means it was not a simple case. */ 1605 if (fs == opDivByZero) { 1606 lostFraction lost_fraction; 1607 1608 lost_fraction = addOrSubtractSignificand(rhs, subtract); 1609 fs = normalize(rounding_mode, lost_fraction); 1610 1611 /* Can only be zero if we lost no fraction. */ 1612 assert(category != fcZero || lost_fraction == lfExactlyZero); 1613 } 1614 1615 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a 1616 positive zero unless rounding to minus infinity, except that 1617 adding two like-signed zeroes gives that zero. */ 1618 if (category == fcZero) { 1619 if (rhs.category != fcZero || (sign == rhs.sign) == subtract) 1620 sign = (rounding_mode == rmTowardNegative); 1621 } 1622 1623 return fs; 1624 } 1625 1626 /* Normalized addition. */ 1627 IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs, 1628 roundingMode rounding_mode) { 1629 return addOrSubtract(rhs, rounding_mode, false); 1630 } 1631 1632 /* Normalized subtraction. */ 1633 IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs, 1634 roundingMode rounding_mode) { 1635 return addOrSubtract(rhs, rounding_mode, true); 1636 } 1637 1638 /* Normalized multiply. */ 1639 IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs, 1640 roundingMode rounding_mode) { 1641 opStatus fs; 1642 1643 sign ^= rhs.sign; 1644 fs = multiplySpecials(rhs); 1645 1646 if (isFiniteNonZero()) { 1647 lostFraction lost_fraction = multiplySignificand(rhs, nullptr); 1648 fs = normalize(rounding_mode, lost_fraction); 1649 if (lost_fraction != lfExactlyZero) 1650 fs = (opStatus) (fs | opInexact); 1651 } 1652 1653 return fs; 1654 } 1655 1656 /* Normalized divide. */ 1657 IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs, 1658 roundingMode rounding_mode) { 1659 opStatus fs; 1660 1661 sign ^= rhs.sign; 1662 fs = divideSpecials(rhs); 1663 1664 if (isFiniteNonZero()) { 1665 lostFraction lost_fraction = divideSignificand(rhs); 1666 fs = normalize(rounding_mode, lost_fraction); 1667 if (lost_fraction != lfExactlyZero) 1668 fs = (opStatus) (fs | opInexact); 1669 } 1670 1671 return fs; 1672 } 1673 1674 /* Normalized remainder. This is not currently correct in all cases. */ 1675 IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) { 1676 opStatus fs; 1677 IEEEFloat V = *this; 1678 unsigned int origSign = sign; 1679 1680 fs = V.divide(rhs, rmNearestTiesToEven); 1681 if (fs == opDivByZero) 1682 return fs; 1683 1684 int parts = partCount(); 1685 integerPart *x = new integerPart[parts]; 1686 bool ignored; 1687 fs = V.convertToInteger(x, parts * integerPartWidth, true, 1688 rmNearestTiesToEven, &ignored); 1689 if (fs==opInvalidOp) 1690 return fs; 1691 1692 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true, 1693 rmNearestTiesToEven); 1694 assert(fs==opOK); // should always work 1695 1696 fs = V.multiply(rhs, rmNearestTiesToEven); 1697 assert(fs==opOK || fs==opInexact); // should not overflow or underflow 1698 1699 fs = subtract(V, rmNearestTiesToEven); 1700 assert(fs==opOK || fs==opInexact); // likewise 1701 1702 if (isZero()) 1703 sign = origSign; // IEEE754 requires this 1704 delete[] x; 1705 return fs; 1706 } 1707 1708 /* Normalized llvm frem (C fmod). 1709 This is not currently correct in all cases. */ 1710 IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) { 1711 opStatus fs; 1712 fs = modSpecials(rhs); 1713 1714 if (isFiniteNonZero() && rhs.isFiniteNonZero()) { 1715 IEEEFloat V = *this; 1716 unsigned int origSign = sign; 1717 1718 fs = V.divide(rhs, rmNearestTiesToEven); 1719 if (fs == opDivByZero) 1720 return fs; 1721 1722 int parts = partCount(); 1723 integerPart *x = new integerPart[parts]; 1724 bool ignored; 1725 fs = V.convertToInteger(x, parts * integerPartWidth, true, 1726 rmTowardZero, &ignored); 1727 if (fs==opInvalidOp) 1728 return fs; 1729 1730 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true, 1731 rmNearestTiesToEven); 1732 assert(fs==opOK); // should always work 1733 1734 fs = V.multiply(rhs, rmNearestTiesToEven); 1735 assert(fs==opOK || fs==opInexact); // should not overflow or underflow 1736 1737 fs = subtract(V, rmNearestTiesToEven); 1738 assert(fs==opOK || fs==opInexact); // likewise 1739 1740 if (isZero()) 1741 sign = origSign; // IEEE754 requires this 1742 delete[] x; 1743 } 1744 return fs; 1745 } 1746 1747 /* Normalized fused-multiply-add. */ 1748 IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand, 1749 const IEEEFloat &addend, 1750 roundingMode rounding_mode) { 1751 opStatus fs; 1752 1753 /* Post-multiplication sign, before addition. */ 1754 sign ^= multiplicand.sign; 1755 1756 /* If and only if all arguments are normal do we need to do an 1757 extended-precision calculation. */ 1758 if (isFiniteNonZero() && 1759 multiplicand.isFiniteNonZero() && 1760 addend.isFinite()) { 1761 lostFraction lost_fraction; 1762 1763 lost_fraction = multiplySignificand(multiplicand, &addend); 1764 fs = normalize(rounding_mode, lost_fraction); 1765 if (lost_fraction != lfExactlyZero) 1766 fs = (opStatus) (fs | opInexact); 1767 1768 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a 1769 positive zero unless rounding to minus infinity, except that 1770 adding two like-signed zeroes gives that zero. */ 1771 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign) 1772 sign = (rounding_mode == rmTowardNegative); 1773 } else { 1774 fs = multiplySpecials(multiplicand); 1775 1776 /* FS can only be opOK or opInvalidOp. There is no more work 1777 to do in the latter case. The IEEE-754R standard says it is 1778 implementation-defined in this case whether, if ADDEND is a 1779 quiet NaN, we raise invalid op; this implementation does so. 1780 1781 If we need to do the addition we can do so with normal 1782 precision. */ 1783 if (fs == opOK) 1784 fs = addOrSubtract(addend, rounding_mode, false); 1785 } 1786 1787 return fs; 1788 } 1789 1790 /* Rounding-mode corrrect round to integral value. */ 1791 IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) { 1792 opStatus fs; 1793 1794 // If the exponent is large enough, we know that this value is already 1795 // integral, and the arithmetic below would potentially cause it to saturate 1796 // to +/-Inf. Bail out early instead. 1797 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics)) 1798 return opOK; 1799 1800 // The algorithm here is quite simple: we add 2^(p-1), where p is the 1801 // precision of our format, and then subtract it back off again. The choice 1802 // of rounding modes for the addition/subtraction determines the rounding mode 1803 // for our integral rounding as well. 1804 // NOTE: When the input value is negative, we do subtraction followed by 1805 // addition instead. 1806 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1); 1807 IntegerConstant <<= semanticsPrecision(*semantics)-1; 1808 IEEEFloat MagicConstant(*semantics); 1809 fs = MagicConstant.convertFromAPInt(IntegerConstant, false, 1810 rmNearestTiesToEven); 1811 MagicConstant.copySign(*this); 1812 1813 if (fs != opOK) 1814 return fs; 1815 1816 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly. 1817 bool inputSign = isNegative(); 1818 1819 fs = add(MagicConstant, rounding_mode); 1820 if (fs != opOK && fs != opInexact) 1821 return fs; 1822 1823 fs = subtract(MagicConstant, rounding_mode); 1824 1825 // Restore the input sign. 1826 if (inputSign != isNegative()) 1827 changeSign(); 1828 1829 return fs; 1830 } 1831 1832 1833 /* Comparison requires normalized numbers. */ 1834 IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const { 1835 cmpResult result; 1836 1837 assert(semantics == rhs.semantics); 1838 1839 switch (PackCategoriesIntoKey(category, rhs.category)) { 1840 default: 1841 llvm_unreachable(nullptr); 1842 1843 case PackCategoriesIntoKey(fcNaN, fcZero): 1844 case PackCategoriesIntoKey(fcNaN, fcNormal): 1845 case PackCategoriesIntoKey(fcNaN, fcInfinity): 1846 case PackCategoriesIntoKey(fcNaN, fcNaN): 1847 case PackCategoriesIntoKey(fcZero, fcNaN): 1848 case PackCategoriesIntoKey(fcNormal, fcNaN): 1849 case PackCategoriesIntoKey(fcInfinity, fcNaN): 1850 return cmpUnordered; 1851 1852 case PackCategoriesIntoKey(fcInfinity, fcNormal): 1853 case PackCategoriesIntoKey(fcInfinity, fcZero): 1854 case PackCategoriesIntoKey(fcNormal, fcZero): 1855 if (sign) 1856 return cmpLessThan; 1857 else 1858 return cmpGreaterThan; 1859 1860 case PackCategoriesIntoKey(fcNormal, fcInfinity): 1861 case PackCategoriesIntoKey(fcZero, fcInfinity): 1862 case PackCategoriesIntoKey(fcZero, fcNormal): 1863 if (rhs.sign) 1864 return cmpGreaterThan; 1865 else 1866 return cmpLessThan; 1867 1868 case PackCategoriesIntoKey(fcInfinity, fcInfinity): 1869 if (sign == rhs.sign) 1870 return cmpEqual; 1871 else if (sign) 1872 return cmpLessThan; 1873 else 1874 return cmpGreaterThan; 1875 1876 case PackCategoriesIntoKey(fcZero, fcZero): 1877 return cmpEqual; 1878 1879 case PackCategoriesIntoKey(fcNormal, fcNormal): 1880 break; 1881 } 1882 1883 /* Two normal numbers. Do they have the same sign? */ 1884 if (sign != rhs.sign) { 1885 if (sign) 1886 result = cmpLessThan; 1887 else 1888 result = cmpGreaterThan; 1889 } else { 1890 /* Compare absolute values; invert result if negative. */ 1891 result = compareAbsoluteValue(rhs); 1892 1893 if (sign) { 1894 if (result == cmpLessThan) 1895 result = cmpGreaterThan; 1896 else if (result == cmpGreaterThan) 1897 result = cmpLessThan; 1898 } 1899 } 1900 1901 return result; 1902 } 1903 1904 /// IEEEFloat::convert - convert a value of one floating point type to another. 1905 /// The return value corresponds to the IEEE754 exceptions. *losesInfo 1906 /// records whether the transformation lost information, i.e. whether 1907 /// converting the result back to the original type will produce the 1908 /// original value (this is almost the same as return value==fsOK, but there 1909 /// are edge cases where this is not so). 1910 1911 IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics, 1912 roundingMode rounding_mode, 1913 bool *losesInfo) { 1914 lostFraction lostFraction; 1915 unsigned int newPartCount, oldPartCount; 1916 opStatus fs; 1917 int shift; 1918 const fltSemantics &fromSemantics = *semantics; 1919 1920 lostFraction = lfExactlyZero; 1921 newPartCount = partCountForBits(toSemantics.precision + 1); 1922 oldPartCount = partCount(); 1923 shift = toSemantics.precision - fromSemantics.precision; 1924 1925 bool X86SpecialNan = false; 1926 if (&fromSemantics == &IEEEFloat::x87DoubleExtended && 1927 &toSemantics != &IEEEFloat::x87DoubleExtended && category == fcNaN && 1928 (!(*significandParts() & 0x8000000000000000ULL) || 1929 !(*significandParts() & 0x4000000000000000ULL))) { 1930 // x86 has some unusual NaNs which cannot be represented in any other 1931 // format; note them here. 1932 X86SpecialNan = true; 1933 } 1934 1935 // If this is a truncation of a denormal number, and the target semantics 1936 // has larger exponent range than the source semantics (this can happen 1937 // when truncating from PowerPC double-double to double format), the 1938 // right shift could lose result mantissa bits. Adjust exponent instead 1939 // of performing excessive shift. 1940 if (shift < 0 && isFiniteNonZero()) { 1941 int exponentChange = significandMSB() + 1 - fromSemantics.precision; 1942 if (exponent + exponentChange < toSemantics.minExponent) 1943 exponentChange = toSemantics.minExponent - exponent; 1944 if (exponentChange < shift) 1945 exponentChange = shift; 1946 if (exponentChange < 0) { 1947 shift -= exponentChange; 1948 exponent += exponentChange; 1949 } 1950 } 1951 1952 // If this is a truncation, perform the shift before we narrow the storage. 1953 if (shift < 0 && (isFiniteNonZero() || category==fcNaN)) 1954 lostFraction = shiftRight(significandParts(), oldPartCount, -shift); 1955 1956 // Fix the storage so it can hold to new value. 1957 if (newPartCount > oldPartCount) { 1958 // The new type requires more storage; make it available. 1959 integerPart *newParts; 1960 newParts = new integerPart[newPartCount]; 1961 APInt::tcSet(newParts, 0, newPartCount); 1962 if (isFiniteNonZero() || category==fcNaN) 1963 APInt::tcAssign(newParts, significandParts(), oldPartCount); 1964 freeSignificand(); 1965 significand.parts = newParts; 1966 } else if (newPartCount == 1 && oldPartCount != 1) { 1967 // Switch to built-in storage for a single part. 1968 integerPart newPart = 0; 1969 if (isFiniteNonZero() || category==fcNaN) 1970 newPart = significandParts()[0]; 1971 freeSignificand(); 1972 significand.part = newPart; 1973 } 1974 1975 // Now that we have the right storage, switch the semantics. 1976 semantics = &toSemantics; 1977 1978 // If this is an extension, perform the shift now that the storage is 1979 // available. 1980 if (shift > 0 && (isFiniteNonZero() || category==fcNaN)) 1981 APInt::tcShiftLeft(significandParts(), newPartCount, shift); 1982 1983 if (isFiniteNonZero()) { 1984 fs = normalize(rounding_mode, lostFraction); 1985 *losesInfo = (fs != opOK); 1986 } else if (category == fcNaN) { 1987 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan; 1988 1989 // For x87 extended precision, we want to make a NaN, not a special NaN if 1990 // the input wasn't special either. 1991 if (!X86SpecialNan && semantics == &IEEEFloat::x87DoubleExtended) 1992 APInt::tcSetBit(significandParts(), semantics->precision - 1); 1993 1994 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan) 1995 // does not give you back the same bits. This is dubious, and we 1996 // don't currently do it. You're really supposed to get 1997 // an invalid operation signal at runtime, but nobody does that. 1998 fs = opOK; 1999 } else { 2000 *losesInfo = false; 2001 fs = opOK; 2002 } 2003 2004 return fs; 2005 } 2006 2007 /* Convert a floating point number to an integer according to the 2008 rounding mode. If the rounded integer value is out of range this 2009 returns an invalid operation exception and the contents of the 2010 destination parts are unspecified. If the rounded value is in 2011 range but the floating point number is not the exact integer, the C 2012 standard doesn't require an inexact exception to be raised. IEEE 2013 854 does require it so we do that. 2014 2015 Note that for conversions to integer type the C standard requires 2016 round-to-zero to always be used. */ 2017 IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger( 2018 integerPart *parts, unsigned int width, bool isSigned, 2019 roundingMode rounding_mode, bool *isExact) const { 2020 lostFraction lost_fraction; 2021 const integerPart *src; 2022 unsigned int dstPartsCount, truncatedBits; 2023 2024 *isExact = false; 2025 2026 /* Handle the three special cases first. */ 2027 if (category == fcInfinity || category == fcNaN) 2028 return opInvalidOp; 2029 2030 dstPartsCount = partCountForBits(width); 2031 2032 if (category == fcZero) { 2033 APInt::tcSet(parts, 0, dstPartsCount); 2034 // Negative zero can't be represented as an int. 2035 *isExact = !sign; 2036 return opOK; 2037 } 2038 2039 src = significandParts(); 2040 2041 /* Step 1: place our absolute value, with any fraction truncated, in 2042 the destination. */ 2043 if (exponent < 0) { 2044 /* Our absolute value is less than one; truncate everything. */ 2045 APInt::tcSet(parts, 0, dstPartsCount); 2046 /* For exponent -1 the integer bit represents .5, look at that. 2047 For smaller exponents leftmost truncated bit is 0. */ 2048 truncatedBits = semantics->precision -1U - exponent; 2049 } else { 2050 /* We want the most significant (exponent + 1) bits; the rest are 2051 truncated. */ 2052 unsigned int bits = exponent + 1U; 2053 2054 /* Hopelessly large in magnitude? */ 2055 if (bits > width) 2056 return opInvalidOp; 2057 2058 if (bits < semantics->precision) { 2059 /* We truncate (semantics->precision - bits) bits. */ 2060 truncatedBits = semantics->precision - bits; 2061 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits); 2062 } else { 2063 /* We want at least as many bits as are available. */ 2064 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0); 2065 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision); 2066 truncatedBits = 0; 2067 } 2068 } 2069 2070 /* Step 2: work out any lost fraction, and increment the absolute 2071 value if we would round away from zero. */ 2072 if (truncatedBits) { 2073 lost_fraction = lostFractionThroughTruncation(src, partCount(), 2074 truncatedBits); 2075 if (lost_fraction != lfExactlyZero && 2076 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) { 2077 if (APInt::tcIncrement(parts, dstPartsCount)) 2078 return opInvalidOp; /* Overflow. */ 2079 } 2080 } else { 2081 lost_fraction = lfExactlyZero; 2082 } 2083 2084 /* Step 3: check if we fit in the destination. */ 2085 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1; 2086 2087 if (sign) { 2088 if (!isSigned) { 2089 /* Negative numbers cannot be represented as unsigned. */ 2090 if (omsb != 0) 2091 return opInvalidOp; 2092 } else { 2093 /* It takes omsb bits to represent the unsigned integer value. 2094 We lose a bit for the sign, but care is needed as the 2095 maximally negative integer is a special case. */ 2096 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb) 2097 return opInvalidOp; 2098 2099 /* This case can happen because of rounding. */ 2100 if (omsb > width) 2101 return opInvalidOp; 2102 } 2103 2104 APInt::tcNegate (parts, dstPartsCount); 2105 } else { 2106 if (omsb >= width + !isSigned) 2107 return opInvalidOp; 2108 } 2109 2110 if (lost_fraction == lfExactlyZero) { 2111 *isExact = true; 2112 return opOK; 2113 } else 2114 return opInexact; 2115 } 2116 2117 /* Same as convertToSignExtendedInteger, except we provide 2118 deterministic values in case of an invalid operation exception, 2119 namely zero for NaNs and the minimal or maximal value respectively 2120 for underflow or overflow. 2121 The *isExact output tells whether the result is exact, in the sense 2122 that converting it back to the original floating point type produces 2123 the original value. This is almost equivalent to result==opOK, 2124 except for negative zeroes. 2125 */ 2126 IEEEFloat::opStatus IEEEFloat::convertToInteger(integerPart *parts, 2127 unsigned int width, 2128 bool isSigned, 2129 roundingMode rounding_mode, 2130 bool *isExact) const { 2131 opStatus fs; 2132 2133 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode, 2134 isExact); 2135 2136 if (fs == opInvalidOp) { 2137 unsigned int bits, dstPartsCount; 2138 2139 dstPartsCount = partCountForBits(width); 2140 2141 if (category == fcNaN) 2142 bits = 0; 2143 else if (sign) 2144 bits = isSigned; 2145 else 2146 bits = width - isSigned; 2147 2148 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits); 2149 if (sign && isSigned) 2150 APInt::tcShiftLeft(parts, dstPartsCount, width - 1); 2151 } 2152 2153 return fs; 2154 } 2155 2156 /* Same as convertToInteger(integerPart*, ...), except the result is returned in 2157 an APSInt, whose initial bit-width and signed-ness are used to determine the 2158 precision of the conversion. 2159 */ 2160 IEEEFloat::opStatus IEEEFloat::convertToInteger(APSInt &result, 2161 roundingMode rounding_mode, 2162 bool *isExact) const { 2163 unsigned bitWidth = result.getBitWidth(); 2164 SmallVector<uint64_t, 4> parts(result.getNumWords()); 2165 opStatus status = convertToInteger( 2166 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact); 2167 // Keeps the original signed-ness. 2168 result = APInt(bitWidth, parts); 2169 return status; 2170 } 2171 2172 /* Convert an unsigned integer SRC to a floating point number, 2173 rounding according to ROUNDING_MODE. The sign of the floating 2174 point number is not modified. */ 2175 IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts( 2176 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) { 2177 unsigned int omsb, precision, dstCount; 2178 integerPart *dst; 2179 lostFraction lost_fraction; 2180 2181 category = fcNormal; 2182 omsb = APInt::tcMSB(src, srcCount) + 1; 2183 dst = significandParts(); 2184 dstCount = partCount(); 2185 precision = semantics->precision; 2186 2187 /* We want the most significant PRECISION bits of SRC. There may not 2188 be that many; extract what we can. */ 2189 if (precision <= omsb) { 2190 exponent = omsb - 1; 2191 lost_fraction = lostFractionThroughTruncation(src, srcCount, 2192 omsb - precision); 2193 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision); 2194 } else { 2195 exponent = precision - 1; 2196 lost_fraction = lfExactlyZero; 2197 APInt::tcExtract(dst, dstCount, src, omsb, 0); 2198 } 2199 2200 return normalize(rounding_mode, lost_fraction); 2201 } 2202 2203 IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned, 2204 roundingMode rounding_mode) { 2205 unsigned int partCount = Val.getNumWords(); 2206 APInt api = Val; 2207 2208 sign = false; 2209 if (isSigned && api.isNegative()) { 2210 sign = true; 2211 api = -api; 2212 } 2213 2214 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode); 2215 } 2216 2217 /* Convert a two's complement integer SRC to a floating point number, 2218 rounding according to ROUNDING_MODE. ISSIGNED is true if the 2219 integer is signed, in which case it must be sign-extended. */ 2220 IEEEFloat::opStatus 2221 IEEEFloat::convertFromSignExtendedInteger(const integerPart *src, 2222 unsigned int srcCount, bool isSigned, 2223 roundingMode rounding_mode) { 2224 opStatus status; 2225 2226 if (isSigned && 2227 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) { 2228 integerPart *copy; 2229 2230 /* If we're signed and negative negate a copy. */ 2231 sign = true; 2232 copy = new integerPart[srcCount]; 2233 APInt::tcAssign(copy, src, srcCount); 2234 APInt::tcNegate(copy, srcCount); 2235 status = convertFromUnsignedParts(copy, srcCount, rounding_mode); 2236 delete [] copy; 2237 } else { 2238 sign = false; 2239 status = convertFromUnsignedParts(src, srcCount, rounding_mode); 2240 } 2241 2242 return status; 2243 } 2244 2245 /* FIXME: should this just take a const APInt reference? */ 2246 IEEEFloat::opStatus 2247 IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts, 2248 unsigned int width, bool isSigned, 2249 roundingMode rounding_mode) { 2250 unsigned int partCount = partCountForBits(width); 2251 APInt api = APInt(width, makeArrayRef(parts, partCount)); 2252 2253 sign = false; 2254 if (isSigned && APInt::tcExtractBit(parts, width - 1)) { 2255 sign = true; 2256 api = -api; 2257 } 2258 2259 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode); 2260 } 2261 2262 IEEEFloat::opStatus 2263 IEEEFloat::convertFromHexadecimalString(StringRef s, 2264 roundingMode rounding_mode) { 2265 lostFraction lost_fraction = lfExactlyZero; 2266 2267 category = fcNormal; 2268 zeroSignificand(); 2269 exponent = 0; 2270 2271 integerPart *significand = significandParts(); 2272 unsigned partsCount = partCount(); 2273 unsigned bitPos = partsCount * integerPartWidth; 2274 bool computedTrailingFraction = false; 2275 2276 // Skip leading zeroes and any (hexa)decimal point. 2277 StringRef::iterator begin = s.begin(); 2278 StringRef::iterator end = s.end(); 2279 StringRef::iterator dot; 2280 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot); 2281 StringRef::iterator firstSignificantDigit = p; 2282 2283 while (p != end) { 2284 integerPart hex_value; 2285 2286 if (*p == '.') { 2287 assert(dot == end && "String contains multiple dots"); 2288 dot = p++; 2289 continue; 2290 } 2291 2292 hex_value = hexDigitValue(*p); 2293 if (hex_value == -1U) 2294 break; 2295 2296 p++; 2297 2298 // Store the number while we have space. 2299 if (bitPos) { 2300 bitPos -= 4; 2301 hex_value <<= bitPos % integerPartWidth; 2302 significand[bitPos / integerPartWidth] |= hex_value; 2303 } else if (!computedTrailingFraction) { 2304 lost_fraction = trailingHexadecimalFraction(p, end, hex_value); 2305 computedTrailingFraction = true; 2306 } 2307 } 2308 2309 /* Hex floats require an exponent but not a hexadecimal point. */ 2310 assert(p != end && "Hex strings require an exponent"); 2311 assert((*p == 'p' || *p == 'P') && "Invalid character in significand"); 2312 assert(p != begin && "Significand has no digits"); 2313 assert((dot == end || p - begin != 1) && "Significand has no digits"); 2314 2315 /* Ignore the exponent if we are zero. */ 2316 if (p != firstSignificantDigit) { 2317 int expAdjustment; 2318 2319 /* Implicit hexadecimal point? */ 2320 if (dot == end) 2321 dot = p; 2322 2323 /* Calculate the exponent adjustment implicit in the number of 2324 significant digits. */ 2325 expAdjustment = static_cast<int>(dot - firstSignificantDigit); 2326 if (expAdjustment < 0) 2327 expAdjustment++; 2328 expAdjustment = expAdjustment * 4 - 1; 2329 2330 /* Adjust for writing the significand starting at the most 2331 significant nibble. */ 2332 expAdjustment += semantics->precision; 2333 expAdjustment -= partsCount * integerPartWidth; 2334 2335 /* Adjust for the given exponent. */ 2336 exponent = totalExponent(p + 1, end, expAdjustment); 2337 } 2338 2339 return normalize(rounding_mode, lost_fraction); 2340 } 2341 2342 IEEEFloat::opStatus 2343 IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts, 2344 unsigned sigPartCount, int exp, 2345 roundingMode rounding_mode) { 2346 unsigned int parts, pow5PartCount; 2347 fltSemantics calcSemantics = { 32767, -32767, 0, 0 }; 2348 integerPart pow5Parts[maxPowerOfFiveParts]; 2349 bool isNearest; 2350 2351 isNearest = (rounding_mode == rmNearestTiesToEven || 2352 rounding_mode == rmNearestTiesToAway); 2353 2354 parts = partCountForBits(semantics->precision + 11); 2355 2356 /* Calculate pow(5, abs(exp)). */ 2357 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp); 2358 2359 for (;; parts *= 2) { 2360 opStatus sigStatus, powStatus; 2361 unsigned int excessPrecision, truncatedBits; 2362 2363 calcSemantics.precision = parts * integerPartWidth - 1; 2364 excessPrecision = calcSemantics.precision - semantics->precision; 2365 truncatedBits = excessPrecision; 2366 2367 IEEEFloat decSig(calcSemantics, uninitialized); 2368 decSig.makeZero(sign); 2369 IEEEFloat pow5(calcSemantics); 2370 2371 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount, 2372 rmNearestTiesToEven); 2373 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount, 2374 rmNearestTiesToEven); 2375 /* Add exp, as 10^n = 5^n * 2^n. */ 2376 decSig.exponent += exp; 2377 2378 lostFraction calcLostFraction; 2379 integerPart HUerr, HUdistance; 2380 unsigned int powHUerr; 2381 2382 if (exp >= 0) { 2383 /* multiplySignificand leaves the precision-th bit set to 1. */ 2384 calcLostFraction = decSig.multiplySignificand(pow5, nullptr); 2385 powHUerr = powStatus != opOK; 2386 } else { 2387 calcLostFraction = decSig.divideSignificand(pow5); 2388 /* Denormal numbers have less precision. */ 2389 if (decSig.exponent < semantics->minExponent) { 2390 excessPrecision += (semantics->minExponent - decSig.exponent); 2391 truncatedBits = excessPrecision; 2392 if (excessPrecision > calcSemantics.precision) 2393 excessPrecision = calcSemantics.precision; 2394 } 2395 /* Extra half-ulp lost in reciprocal of exponent. */ 2396 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2; 2397 } 2398 2399 /* Both multiplySignificand and divideSignificand return the 2400 result with the integer bit set. */ 2401 assert(APInt::tcExtractBit 2402 (decSig.significandParts(), calcSemantics.precision - 1) == 1); 2403 2404 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK, 2405 powHUerr); 2406 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(), 2407 excessPrecision, isNearest); 2408 2409 /* Are we guaranteed to round correctly if we truncate? */ 2410 if (HUdistance >= HUerr) { 2411 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(), 2412 calcSemantics.precision - excessPrecision, 2413 excessPrecision); 2414 /* Take the exponent of decSig. If we tcExtract-ed less bits 2415 above we must adjust our exponent to compensate for the 2416 implicit right shift. */ 2417 exponent = (decSig.exponent + semantics->precision 2418 - (calcSemantics.precision - excessPrecision)); 2419 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(), 2420 decSig.partCount(), 2421 truncatedBits); 2422 return normalize(rounding_mode, calcLostFraction); 2423 } 2424 } 2425 } 2426 2427 IEEEFloat::opStatus 2428 IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) { 2429 decimalInfo D; 2430 opStatus fs; 2431 2432 /* Scan the text. */ 2433 StringRef::iterator p = str.begin(); 2434 interpretDecimal(p, str.end(), &D); 2435 2436 /* Handle the quick cases. First the case of no significant digits, 2437 i.e. zero, and then exponents that are obviously too large or too 2438 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp 2439 definitely overflows if 2440 2441 (exp - 1) * L >= maxExponent 2442 2443 and definitely underflows to zero where 2444 2445 (exp + 1) * L <= minExponent - precision 2446 2447 With integer arithmetic the tightest bounds for L are 2448 2449 93/28 < L < 196/59 [ numerator <= 256 ] 2450 42039/12655 < L < 28738/8651 [ numerator <= 65536 ] 2451 */ 2452 2453 // Test if we have a zero number allowing for strings with no null terminators 2454 // and zero decimals with non-zero exponents. 2455 // 2456 // We computed firstSigDigit by ignoring all zeros and dots. Thus if 2457 // D->firstSigDigit equals str.end(), every digit must be a zero and there can 2458 // be at most one dot. On the other hand, if we have a zero with a non-zero 2459 // exponent, then we know that D.firstSigDigit will be non-numeric. 2460 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) { 2461 category = fcZero; 2462 fs = opOK; 2463 2464 /* Check whether the normalized exponent is high enough to overflow 2465 max during the log-rebasing in the max-exponent check below. */ 2466 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) { 2467 fs = handleOverflow(rounding_mode); 2468 2469 /* If it wasn't, then it also wasn't high enough to overflow max 2470 during the log-rebasing in the min-exponent check. Check that it 2471 won't overflow min in either check, then perform the min-exponent 2472 check. */ 2473 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 || 2474 (D.normalizedExponent + 1) * 28738 <= 2475 8651 * (semantics->minExponent - (int) semantics->precision)) { 2476 /* Underflow to zero and round. */ 2477 category = fcNormal; 2478 zeroSignificand(); 2479 fs = normalize(rounding_mode, lfLessThanHalf); 2480 2481 /* We can finally safely perform the max-exponent check. */ 2482 } else if ((D.normalizedExponent - 1) * 42039 2483 >= 12655 * semantics->maxExponent) { 2484 /* Overflow and round. */ 2485 fs = handleOverflow(rounding_mode); 2486 } else { 2487 integerPart *decSignificand; 2488 unsigned int partCount; 2489 2490 /* A tight upper bound on number of bits required to hold an 2491 N-digit decimal integer is N * 196 / 59. Allocate enough space 2492 to hold the full significand, and an extra part required by 2493 tcMultiplyPart. */ 2494 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1; 2495 partCount = partCountForBits(1 + 196 * partCount / 59); 2496 decSignificand = new integerPart[partCount + 1]; 2497 partCount = 0; 2498 2499 /* Convert to binary efficiently - we do almost all multiplication 2500 in an integerPart. When this would overflow do we do a single 2501 bignum multiplication, and then revert again to multiplication 2502 in an integerPart. */ 2503 do { 2504 integerPart decValue, val, multiplier; 2505 2506 val = 0; 2507 multiplier = 1; 2508 2509 do { 2510 if (*p == '.') { 2511 p++; 2512 if (p == str.end()) { 2513 break; 2514 } 2515 } 2516 decValue = decDigitValue(*p++); 2517 assert(decValue < 10U && "Invalid character in significand"); 2518 multiplier *= 10; 2519 val = val * 10 + decValue; 2520 /* The maximum number that can be multiplied by ten with any 2521 digit added without overflowing an integerPart. */ 2522 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10); 2523 2524 /* Multiply out the current part. */ 2525 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val, 2526 partCount, partCount + 1, false); 2527 2528 /* If we used another part (likely but not guaranteed), increase 2529 the count. */ 2530 if (decSignificand[partCount]) 2531 partCount++; 2532 } while (p <= D.lastSigDigit); 2533 2534 category = fcNormal; 2535 fs = roundSignificandWithExponent(decSignificand, partCount, 2536 D.exponent, rounding_mode); 2537 2538 delete [] decSignificand; 2539 } 2540 2541 return fs; 2542 } 2543 2544 bool IEEEFloat::convertFromStringSpecials(StringRef str) { 2545 if (str.equals("inf") || str.equals("INFINITY")) { 2546 makeInf(false); 2547 return true; 2548 } 2549 2550 if (str.equals("-inf") || str.equals("-INFINITY")) { 2551 makeInf(true); 2552 return true; 2553 } 2554 2555 if (str.equals("nan") || str.equals("NaN")) { 2556 makeNaN(false, false); 2557 return true; 2558 } 2559 2560 if (str.equals("-nan") || str.equals("-NaN")) { 2561 makeNaN(false, true); 2562 return true; 2563 } 2564 2565 return false; 2566 } 2567 2568 IEEEFloat::opStatus IEEEFloat::convertFromString(StringRef str, 2569 roundingMode rounding_mode) { 2570 assert(!str.empty() && "Invalid string length"); 2571 2572 // Handle special cases. 2573 if (convertFromStringSpecials(str)) 2574 return opOK; 2575 2576 /* Handle a leading minus sign. */ 2577 StringRef::iterator p = str.begin(); 2578 size_t slen = str.size(); 2579 sign = *p == '-' ? 1 : 0; 2580 if (*p == '-' || *p == '+') { 2581 p++; 2582 slen--; 2583 assert(slen && "String has no digits"); 2584 } 2585 2586 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) { 2587 assert(slen - 2 && "Invalid string"); 2588 return convertFromHexadecimalString(StringRef(p + 2, slen - 2), 2589 rounding_mode); 2590 } 2591 2592 return convertFromDecimalString(StringRef(p, slen), rounding_mode); 2593 } 2594 2595 /* Write out a hexadecimal representation of the floating point value 2596 to DST, which must be of sufficient size, in the C99 form 2597 [-]0xh.hhhhp[+-]d. Return the number of characters written, 2598 excluding the terminating NUL. 2599 2600 If UPPERCASE, the output is in upper case, otherwise in lower case. 2601 2602 HEXDIGITS digits appear altogether, rounding the value if 2603 necessary. If HEXDIGITS is 0, the minimal precision to display the 2604 number precisely is used instead. If nothing would appear after 2605 the decimal point it is suppressed. 2606 2607 The decimal exponent is always printed and has at least one digit. 2608 Zero values display an exponent of zero. Infinities and NaNs 2609 appear as "infinity" or "nan" respectively. 2610 2611 The above rules are as specified by C99. There is ambiguity about 2612 what the leading hexadecimal digit should be. This implementation 2613 uses whatever is necessary so that the exponent is displayed as 2614 stored. This implies the exponent will fall within the IEEE format 2615 range, and the leading hexadecimal digit will be 0 (for denormals), 2616 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with 2617 any other digits zero). 2618 */ 2619 unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits, 2620 bool upperCase, 2621 roundingMode rounding_mode) const { 2622 char *p; 2623 2624 p = dst; 2625 if (sign) 2626 *dst++ = '-'; 2627 2628 switch (category) { 2629 case fcInfinity: 2630 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1); 2631 dst += sizeof infinityL - 1; 2632 break; 2633 2634 case fcNaN: 2635 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1); 2636 dst += sizeof NaNU - 1; 2637 break; 2638 2639 case fcZero: 2640 *dst++ = '0'; 2641 *dst++ = upperCase ? 'X': 'x'; 2642 *dst++ = '0'; 2643 if (hexDigits > 1) { 2644 *dst++ = '.'; 2645 memset (dst, '0', hexDigits - 1); 2646 dst += hexDigits - 1; 2647 } 2648 *dst++ = upperCase ? 'P': 'p'; 2649 *dst++ = '0'; 2650 break; 2651 2652 case fcNormal: 2653 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode); 2654 break; 2655 } 2656 2657 *dst = 0; 2658 2659 return static_cast<unsigned int>(dst - p); 2660 } 2661 2662 /* Does the hard work of outputting the correctly rounded hexadecimal 2663 form of a normal floating point number with the specified number of 2664 hexadecimal digits. If HEXDIGITS is zero the minimum number of 2665 digits necessary to print the value precisely is output. */ 2666 char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits, 2667 bool upperCase, 2668 roundingMode rounding_mode) const { 2669 unsigned int count, valueBits, shift, partsCount, outputDigits; 2670 const char *hexDigitChars; 2671 const integerPart *significand; 2672 char *p; 2673 bool roundUp; 2674 2675 *dst++ = '0'; 2676 *dst++ = upperCase ? 'X': 'x'; 2677 2678 roundUp = false; 2679 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower; 2680 2681 significand = significandParts(); 2682 partsCount = partCount(); 2683 2684 /* +3 because the first digit only uses the single integer bit, so 2685 we have 3 virtual zero most-significant-bits. */ 2686 valueBits = semantics->precision + 3; 2687 shift = integerPartWidth - valueBits % integerPartWidth; 2688 2689 /* The natural number of digits required ignoring trailing 2690 insignificant zeroes. */ 2691 outputDigits = (valueBits - significandLSB () + 3) / 4; 2692 2693 /* hexDigits of zero means use the required number for the 2694 precision. Otherwise, see if we are truncating. If we are, 2695 find out if we need to round away from zero. */ 2696 if (hexDigits) { 2697 if (hexDigits < outputDigits) { 2698 /* We are dropping non-zero bits, so need to check how to round. 2699 "bits" is the number of dropped bits. */ 2700 unsigned int bits; 2701 lostFraction fraction; 2702 2703 bits = valueBits - hexDigits * 4; 2704 fraction = lostFractionThroughTruncation (significand, partsCount, bits); 2705 roundUp = roundAwayFromZero(rounding_mode, fraction, bits); 2706 } 2707 outputDigits = hexDigits; 2708 } 2709 2710 /* Write the digits consecutively, and start writing in the location 2711 of the hexadecimal point. We move the most significant digit 2712 left and add the hexadecimal point later. */ 2713 p = ++dst; 2714 2715 count = (valueBits + integerPartWidth - 1) / integerPartWidth; 2716 2717 while (outputDigits && count) { 2718 integerPart part; 2719 2720 /* Put the most significant integerPartWidth bits in "part". */ 2721 if (--count == partsCount) 2722 part = 0; /* An imaginary higher zero part. */ 2723 else 2724 part = significand[count] << shift; 2725 2726 if (count && shift) 2727 part |= significand[count - 1] >> (integerPartWidth - shift); 2728 2729 /* Convert as much of "part" to hexdigits as we can. */ 2730 unsigned int curDigits = integerPartWidth / 4; 2731 2732 if (curDigits > outputDigits) 2733 curDigits = outputDigits; 2734 dst += partAsHex (dst, part, curDigits, hexDigitChars); 2735 outputDigits -= curDigits; 2736 } 2737 2738 if (roundUp) { 2739 char *q = dst; 2740 2741 /* Note that hexDigitChars has a trailing '0'. */ 2742 do { 2743 q--; 2744 *q = hexDigitChars[hexDigitValue (*q) + 1]; 2745 } while (*q == '0'); 2746 assert(q >= p); 2747 } else { 2748 /* Add trailing zeroes. */ 2749 memset (dst, '0', outputDigits); 2750 dst += outputDigits; 2751 } 2752 2753 /* Move the most significant digit to before the point, and if there 2754 is something after the decimal point add it. This must come 2755 after rounding above. */ 2756 p[-1] = p[0]; 2757 if (dst -1 == p) 2758 dst--; 2759 else 2760 p[0] = '.'; 2761 2762 /* Finally output the exponent. */ 2763 *dst++ = upperCase ? 'P': 'p'; 2764 2765 return writeSignedDecimal (dst, exponent); 2766 } 2767 2768 hash_code hash_value(const IEEEFloat &Arg) { 2769 if (!Arg.isFiniteNonZero()) 2770 return hash_combine((uint8_t)Arg.category, 2771 // NaN has no sign, fix it at zero. 2772 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign, 2773 Arg.semantics->precision); 2774 2775 // Normal floats need their exponent and significand hashed. 2776 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign, 2777 Arg.semantics->precision, Arg.exponent, 2778 hash_combine_range( 2779 Arg.significandParts(), 2780 Arg.significandParts() + Arg.partCount())); 2781 } 2782 2783 // Conversion from APFloat to/from host float/double. It may eventually be 2784 // possible to eliminate these and have everybody deal with APFloats, but that 2785 // will take a while. This approach will not easily extend to long double. 2786 // Current implementation requires integerPartWidth==64, which is correct at 2787 // the moment but could be made more general. 2788 2789 // Denormals have exponent minExponent in APFloat, but minExponent-1 in 2790 // the actual IEEE respresentations. We compensate for that here. 2791 2792 APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const { 2793 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended); 2794 assert(partCount()==2); 2795 2796 uint64_t myexponent, mysignificand; 2797 2798 if (isFiniteNonZero()) { 2799 myexponent = exponent+16383; //bias 2800 mysignificand = significandParts()[0]; 2801 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL)) 2802 myexponent = 0; // denormal 2803 } else if (category==fcZero) { 2804 myexponent = 0; 2805 mysignificand = 0; 2806 } else if (category==fcInfinity) { 2807 myexponent = 0x7fff; 2808 mysignificand = 0x8000000000000000ULL; 2809 } else { 2810 assert(category == fcNaN && "Unknown category"); 2811 myexponent = 0x7fff; 2812 mysignificand = significandParts()[0]; 2813 } 2814 2815 uint64_t words[2]; 2816 words[0] = mysignificand; 2817 words[1] = ((uint64_t)(sign & 1) << 15) | 2818 (myexponent & 0x7fffLL); 2819 return APInt(80, words); 2820 } 2821 2822 APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const { 2823 assert(semantics == (const llvm::fltSemantics *)&PPCDoubleDoubleImpl); 2824 assert(partCount()==2); 2825 2826 uint64_t words[2]; 2827 opStatus fs; 2828 bool losesInfo; 2829 2830 // Convert number to double. To avoid spurious underflows, we re- 2831 // normalize against the "double" minExponent first, and only *then* 2832 // truncate the mantissa. The result of that second conversion 2833 // may be inexact, but should never underflow. 2834 // Declare fltSemantics before APFloat that uses it (and 2835 // saves pointer to it) to ensure correct destruction order. 2836 fltSemantics extendedSemantics = *semantics; 2837 extendedSemantics.minExponent = IEEEdouble.minExponent; 2838 IEEEFloat extended(*this); 2839 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo); 2840 assert(fs == opOK && !losesInfo); 2841 (void)fs; 2842 2843 IEEEFloat u(extended); 2844 fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo); 2845 assert(fs == opOK || fs == opInexact); 2846 (void)fs; 2847 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData(); 2848 2849 // If conversion was exact or resulted in a special case, we're done; 2850 // just set the second double to zero. Otherwise, re-convert back to 2851 // the extended format and compute the difference. This now should 2852 // convert exactly to double. 2853 if (u.isFiniteNonZero() && losesInfo) { 2854 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo); 2855 assert(fs == opOK && !losesInfo); 2856 (void)fs; 2857 2858 IEEEFloat v(extended); 2859 v.subtract(u, rmNearestTiesToEven); 2860 fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo); 2861 assert(fs == opOK && !losesInfo); 2862 (void)fs; 2863 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData(); 2864 } else { 2865 words[1] = 0; 2866 } 2867 2868 return APInt(128, words); 2869 } 2870 2871 APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const { 2872 assert(semantics == (const llvm::fltSemantics*)&IEEEquad); 2873 assert(partCount()==2); 2874 2875 uint64_t myexponent, mysignificand, mysignificand2; 2876 2877 if (isFiniteNonZero()) { 2878 myexponent = exponent+16383; //bias 2879 mysignificand = significandParts()[0]; 2880 mysignificand2 = significandParts()[1]; 2881 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL)) 2882 myexponent = 0; // denormal 2883 } else if (category==fcZero) { 2884 myexponent = 0; 2885 mysignificand = mysignificand2 = 0; 2886 } else if (category==fcInfinity) { 2887 myexponent = 0x7fff; 2888 mysignificand = mysignificand2 = 0; 2889 } else { 2890 assert(category == fcNaN && "Unknown category!"); 2891 myexponent = 0x7fff; 2892 mysignificand = significandParts()[0]; 2893 mysignificand2 = significandParts()[1]; 2894 } 2895 2896 uint64_t words[2]; 2897 words[0] = mysignificand; 2898 words[1] = ((uint64_t)(sign & 1) << 63) | 2899 ((myexponent & 0x7fff) << 48) | 2900 (mysignificand2 & 0xffffffffffffLL); 2901 2902 return APInt(128, words); 2903 } 2904 2905 APInt IEEEFloat::convertDoubleAPFloatToAPInt() const { 2906 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble); 2907 assert(partCount()==1); 2908 2909 uint64_t myexponent, mysignificand; 2910 2911 if (isFiniteNonZero()) { 2912 myexponent = exponent+1023; //bias 2913 mysignificand = *significandParts(); 2914 if (myexponent==1 && !(mysignificand & 0x10000000000000LL)) 2915 myexponent = 0; // denormal 2916 } else if (category==fcZero) { 2917 myexponent = 0; 2918 mysignificand = 0; 2919 } else if (category==fcInfinity) { 2920 myexponent = 0x7ff; 2921 mysignificand = 0; 2922 } else { 2923 assert(category == fcNaN && "Unknown category!"); 2924 myexponent = 0x7ff; 2925 mysignificand = *significandParts(); 2926 } 2927 2928 return APInt(64, ((((uint64_t)(sign & 1) << 63) | 2929 ((myexponent & 0x7ff) << 52) | 2930 (mysignificand & 0xfffffffffffffLL)))); 2931 } 2932 2933 APInt IEEEFloat::convertFloatAPFloatToAPInt() const { 2934 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle); 2935 assert(partCount()==1); 2936 2937 uint32_t myexponent, mysignificand; 2938 2939 if (isFiniteNonZero()) { 2940 myexponent = exponent+127; //bias 2941 mysignificand = (uint32_t)*significandParts(); 2942 if (myexponent == 1 && !(mysignificand & 0x800000)) 2943 myexponent = 0; // denormal 2944 } else if (category==fcZero) { 2945 myexponent = 0; 2946 mysignificand = 0; 2947 } else if (category==fcInfinity) { 2948 myexponent = 0xff; 2949 mysignificand = 0; 2950 } else { 2951 assert(category == fcNaN && "Unknown category!"); 2952 myexponent = 0xff; 2953 mysignificand = (uint32_t)*significandParts(); 2954 } 2955 2956 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) | 2957 (mysignificand & 0x7fffff))); 2958 } 2959 2960 APInt IEEEFloat::convertHalfAPFloatToAPInt() const { 2961 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf); 2962 assert(partCount()==1); 2963 2964 uint32_t myexponent, mysignificand; 2965 2966 if (isFiniteNonZero()) { 2967 myexponent = exponent+15; //bias 2968 mysignificand = (uint32_t)*significandParts(); 2969 if (myexponent == 1 && !(mysignificand & 0x400)) 2970 myexponent = 0; // denormal 2971 } else if (category==fcZero) { 2972 myexponent = 0; 2973 mysignificand = 0; 2974 } else if (category==fcInfinity) { 2975 myexponent = 0x1f; 2976 mysignificand = 0; 2977 } else { 2978 assert(category == fcNaN && "Unknown category!"); 2979 myexponent = 0x1f; 2980 mysignificand = (uint32_t)*significandParts(); 2981 } 2982 2983 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) | 2984 (mysignificand & 0x3ff))); 2985 } 2986 2987 // This function creates an APInt that is just a bit map of the floating 2988 // point constant as it would appear in memory. It is not a conversion, 2989 // and treating the result as a normal integer is unlikely to be useful. 2990 2991 APInt IEEEFloat::bitcastToAPInt() const { 2992 if (semantics == (const llvm::fltSemantics*)&IEEEhalf) 2993 return convertHalfAPFloatToAPInt(); 2994 2995 if (semantics == (const llvm::fltSemantics*)&IEEEsingle) 2996 return convertFloatAPFloatToAPInt(); 2997 2998 if (semantics == (const llvm::fltSemantics*)&IEEEdouble) 2999 return convertDoubleAPFloatToAPInt(); 3000 3001 if (semantics == (const llvm::fltSemantics*)&IEEEquad) 3002 return convertQuadrupleAPFloatToAPInt(); 3003 3004 if (semantics == (const llvm::fltSemantics *)&PPCDoubleDoubleImpl) 3005 return convertPPCDoubleDoubleAPFloatToAPInt(); 3006 3007 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended && 3008 "unknown format!"); 3009 return convertF80LongDoubleAPFloatToAPInt(); 3010 } 3011 3012 float IEEEFloat::convertToFloat() const { 3013 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle && 3014 "Float semantics are not IEEEsingle"); 3015 APInt api = bitcastToAPInt(); 3016 return api.bitsToFloat(); 3017 } 3018 3019 double IEEEFloat::convertToDouble() const { 3020 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble && 3021 "Float semantics are not IEEEdouble"); 3022 APInt api = bitcastToAPInt(); 3023 return api.bitsToDouble(); 3024 } 3025 3026 /// Integer bit is explicit in this format. Intel hardware (387 and later) 3027 /// does not support these bit patterns: 3028 /// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity") 3029 /// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN") 3030 /// exponent = 0, integer bit 1 ("pseudodenormal") 3031 /// exponent!=0 nor all 1's, integer bit 0 ("unnormal") 3032 /// At the moment, the first two are treated as NaNs, the second two as Normal. 3033 void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) { 3034 assert(api.getBitWidth()==80); 3035 uint64_t i1 = api.getRawData()[0]; 3036 uint64_t i2 = api.getRawData()[1]; 3037 uint64_t myexponent = (i2 & 0x7fff); 3038 uint64_t mysignificand = i1; 3039 3040 initialize(&IEEEFloat::x87DoubleExtended); 3041 assert(partCount()==2); 3042 3043 sign = static_cast<unsigned int>(i2>>15); 3044 if (myexponent==0 && mysignificand==0) { 3045 // exponent, significand meaningless 3046 category = fcZero; 3047 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) { 3048 // exponent, significand meaningless 3049 category = fcInfinity; 3050 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) { 3051 // exponent meaningless 3052 category = fcNaN; 3053 significandParts()[0] = mysignificand; 3054 significandParts()[1] = 0; 3055 } else { 3056 category = fcNormal; 3057 exponent = myexponent - 16383; 3058 significandParts()[0] = mysignificand; 3059 significandParts()[1] = 0; 3060 if (myexponent==0) // denormal 3061 exponent = -16382; 3062 } 3063 } 3064 3065 void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) { 3066 assert(api.getBitWidth()==128); 3067 uint64_t i1 = api.getRawData()[0]; 3068 uint64_t i2 = api.getRawData()[1]; 3069 opStatus fs; 3070 bool losesInfo; 3071 3072 // Get the first double and convert to our format. 3073 initFromDoubleAPInt(APInt(64, i1)); 3074 fs = convert(PPCDoubleDoubleImpl, rmNearestTiesToEven, &losesInfo); 3075 assert(fs == opOK && !losesInfo); 3076 (void)fs; 3077 3078 // Unless we have a special case, add in second double. 3079 if (isFiniteNonZero()) { 3080 IEEEFloat v(IEEEdouble, APInt(64, i2)); 3081 fs = v.convert(PPCDoubleDoubleImpl, rmNearestTiesToEven, &losesInfo); 3082 assert(fs == opOK && !losesInfo); 3083 (void)fs; 3084 3085 add(v, rmNearestTiesToEven); 3086 } 3087 } 3088 3089 void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) { 3090 assert(api.getBitWidth()==128); 3091 uint64_t i1 = api.getRawData()[0]; 3092 uint64_t i2 = api.getRawData()[1]; 3093 uint64_t myexponent = (i2 >> 48) & 0x7fff; 3094 uint64_t mysignificand = i1; 3095 uint64_t mysignificand2 = i2 & 0xffffffffffffLL; 3096 3097 initialize(&IEEEFloat::IEEEquad); 3098 assert(partCount()==2); 3099 3100 sign = static_cast<unsigned int>(i2>>63); 3101 if (myexponent==0 && 3102 (mysignificand==0 && mysignificand2==0)) { 3103 // exponent, significand meaningless 3104 category = fcZero; 3105 } else if (myexponent==0x7fff && 3106 (mysignificand==0 && mysignificand2==0)) { 3107 // exponent, significand meaningless 3108 category = fcInfinity; 3109 } else if (myexponent==0x7fff && 3110 (mysignificand!=0 || mysignificand2 !=0)) { 3111 // exponent meaningless 3112 category = fcNaN; 3113 significandParts()[0] = mysignificand; 3114 significandParts()[1] = mysignificand2; 3115 } else { 3116 category = fcNormal; 3117 exponent = myexponent - 16383; 3118 significandParts()[0] = mysignificand; 3119 significandParts()[1] = mysignificand2; 3120 if (myexponent==0) // denormal 3121 exponent = -16382; 3122 else 3123 significandParts()[1] |= 0x1000000000000LL; // integer bit 3124 } 3125 } 3126 3127 void IEEEFloat::initFromDoubleAPInt(const APInt &api) { 3128 assert(api.getBitWidth()==64); 3129 uint64_t i = *api.getRawData(); 3130 uint64_t myexponent = (i >> 52) & 0x7ff; 3131 uint64_t mysignificand = i & 0xfffffffffffffLL; 3132 3133 initialize(&IEEEFloat::IEEEdouble); 3134 assert(partCount()==1); 3135 3136 sign = static_cast<unsigned int>(i>>63); 3137 if (myexponent==0 && mysignificand==0) { 3138 // exponent, significand meaningless 3139 category = fcZero; 3140 } else if (myexponent==0x7ff && mysignificand==0) { 3141 // exponent, significand meaningless 3142 category = fcInfinity; 3143 } else if (myexponent==0x7ff && mysignificand!=0) { 3144 // exponent meaningless 3145 category = fcNaN; 3146 *significandParts() = mysignificand; 3147 } else { 3148 category = fcNormal; 3149 exponent = myexponent - 1023; 3150 *significandParts() = mysignificand; 3151 if (myexponent==0) // denormal 3152 exponent = -1022; 3153 else 3154 *significandParts() |= 0x10000000000000LL; // integer bit 3155 } 3156 } 3157 3158 void IEEEFloat::initFromFloatAPInt(const APInt &api) { 3159 assert(api.getBitWidth()==32); 3160 uint32_t i = (uint32_t)*api.getRawData(); 3161 uint32_t myexponent = (i >> 23) & 0xff; 3162 uint32_t mysignificand = i & 0x7fffff; 3163 3164 initialize(&IEEEFloat::IEEEsingle); 3165 assert(partCount()==1); 3166 3167 sign = i >> 31; 3168 if (myexponent==0 && mysignificand==0) { 3169 // exponent, significand meaningless 3170 category = fcZero; 3171 } else if (myexponent==0xff && mysignificand==0) { 3172 // exponent, significand meaningless 3173 category = fcInfinity; 3174 } else if (myexponent==0xff && mysignificand!=0) { 3175 // sign, exponent, significand meaningless 3176 category = fcNaN; 3177 *significandParts() = mysignificand; 3178 } else { 3179 category = fcNormal; 3180 exponent = myexponent - 127; //bias 3181 *significandParts() = mysignificand; 3182 if (myexponent==0) // denormal 3183 exponent = -126; 3184 else 3185 *significandParts() |= 0x800000; // integer bit 3186 } 3187 } 3188 3189 void IEEEFloat::initFromHalfAPInt(const APInt &api) { 3190 assert(api.getBitWidth()==16); 3191 uint32_t i = (uint32_t)*api.getRawData(); 3192 uint32_t myexponent = (i >> 10) & 0x1f; 3193 uint32_t mysignificand = i & 0x3ff; 3194 3195 initialize(&IEEEFloat::IEEEhalf); 3196 assert(partCount()==1); 3197 3198 sign = i >> 15; 3199 if (myexponent==0 && mysignificand==0) { 3200 // exponent, significand meaningless 3201 category = fcZero; 3202 } else if (myexponent==0x1f && mysignificand==0) { 3203 // exponent, significand meaningless 3204 category = fcInfinity; 3205 } else if (myexponent==0x1f && mysignificand!=0) { 3206 // sign, exponent, significand meaningless 3207 category = fcNaN; 3208 *significandParts() = mysignificand; 3209 } else { 3210 category = fcNormal; 3211 exponent = myexponent - 15; //bias 3212 *significandParts() = mysignificand; 3213 if (myexponent==0) // denormal 3214 exponent = -14; 3215 else 3216 *significandParts() |= 0x400; // integer bit 3217 } 3218 } 3219 3220 /// Treat api as containing the bits of a floating point number. Currently 3221 /// we infer the floating point type from the size of the APInt. The 3222 /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful 3223 /// when the size is anything else). 3224 void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) { 3225 if (Sem == &IEEEhalf) 3226 return initFromHalfAPInt(api); 3227 if (Sem == &IEEEsingle) 3228 return initFromFloatAPInt(api); 3229 if (Sem == &IEEEdouble) 3230 return initFromDoubleAPInt(api); 3231 if (Sem == &x87DoubleExtended) 3232 return initFromF80LongDoubleAPInt(api); 3233 if (Sem == &IEEEquad) 3234 return initFromQuadrupleAPInt(api); 3235 if (Sem == &PPCDoubleDoubleImpl) 3236 return initFromPPCDoubleDoubleAPInt(api); 3237 3238 llvm_unreachable(nullptr); 3239 } 3240 3241 IEEEFloat IEEEFloat::getAllOnesValue(unsigned BitWidth) { 3242 switch (BitWidth) { 3243 case 16: 3244 return IEEEFloat(IEEEhalf, APInt::getAllOnesValue(BitWidth)); 3245 case 32: 3246 return IEEEFloat(IEEEsingle, APInt::getAllOnesValue(BitWidth)); 3247 case 64: 3248 return IEEEFloat(IEEEdouble, APInt::getAllOnesValue(BitWidth)); 3249 case 80: 3250 return IEEEFloat(x87DoubleExtended, APInt::getAllOnesValue(BitWidth)); 3251 case 128: 3252 return IEEEFloat(IEEEquad, APInt::getAllOnesValue(BitWidth)); 3253 default: 3254 llvm_unreachable("Unknown floating bit width"); 3255 } 3256 } 3257 3258 /// Make this number the largest magnitude normal number in the given 3259 /// semantics. 3260 void IEEEFloat::makeLargest(bool Negative) { 3261 // We want (in interchange format): 3262 // sign = {Negative} 3263 // exponent = 1..10 3264 // significand = 1..1 3265 category = fcNormal; 3266 sign = Negative; 3267 exponent = semantics->maxExponent; 3268 3269 // Use memset to set all but the highest integerPart to all ones. 3270 integerPart *significand = significandParts(); 3271 unsigned PartCount = partCount(); 3272 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1)); 3273 3274 // Set the high integerPart especially setting all unused top bits for 3275 // internal consistency. 3276 const unsigned NumUnusedHighBits = 3277 PartCount*integerPartWidth - semantics->precision; 3278 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth) 3279 ? (~integerPart(0) >> NumUnusedHighBits) 3280 : 0; 3281 } 3282 3283 /// Make this number the smallest magnitude denormal number in the given 3284 /// semantics. 3285 void IEEEFloat::makeSmallest(bool Negative) { 3286 // We want (in interchange format): 3287 // sign = {Negative} 3288 // exponent = 0..0 3289 // significand = 0..01 3290 category = fcNormal; 3291 sign = Negative; 3292 exponent = semantics->minExponent; 3293 APInt::tcSet(significandParts(), 1, partCount()); 3294 } 3295 3296 void IEEEFloat::makeSmallestNormalized(bool Negative) { 3297 // We want (in interchange format): 3298 // sign = {Negative} 3299 // exponent = 0..0 3300 // significand = 10..0 3301 3302 category = fcNormal; 3303 zeroSignificand(); 3304 sign = Negative; 3305 exponent = semantics->minExponent; 3306 significandParts()[partCountForBits(semantics->precision) - 1] |= 3307 (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth)); 3308 } 3309 3310 IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) { 3311 initFromAPInt(&Sem, API); 3312 } 3313 3314 IEEEFloat::IEEEFloat(float f) { 3315 initFromAPInt(&IEEEsingle, APInt::floatToBits(f)); 3316 } 3317 3318 IEEEFloat::IEEEFloat(double d) { 3319 initFromAPInt(&IEEEdouble, APInt::doubleToBits(d)); 3320 } 3321 3322 namespace { 3323 void append(SmallVectorImpl<char> &Buffer, StringRef Str) { 3324 Buffer.append(Str.begin(), Str.end()); 3325 } 3326 3327 /// Removes data from the given significand until it is no more 3328 /// precise than is required for the desired precision. 3329 void AdjustToPrecision(APInt &significand, 3330 int &exp, unsigned FormatPrecision) { 3331 unsigned bits = significand.getActiveBits(); 3332 3333 // 196/59 is a very slight overestimate of lg_2(10). 3334 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59; 3335 3336 if (bits <= bitsRequired) return; 3337 3338 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196; 3339 if (!tensRemovable) return; 3340 3341 exp += tensRemovable; 3342 3343 APInt divisor(significand.getBitWidth(), 1); 3344 APInt powten(significand.getBitWidth(), 10); 3345 while (true) { 3346 if (tensRemovable & 1) 3347 divisor *= powten; 3348 tensRemovable >>= 1; 3349 if (!tensRemovable) break; 3350 powten *= powten; 3351 } 3352 3353 significand = significand.udiv(divisor); 3354 3355 // Truncate the significand down to its active bit count. 3356 significand = significand.trunc(significand.getActiveBits()); 3357 } 3358 3359 3360 void AdjustToPrecision(SmallVectorImpl<char> &buffer, 3361 int &exp, unsigned FormatPrecision) { 3362 unsigned N = buffer.size(); 3363 if (N <= FormatPrecision) return; 3364 3365 // The most significant figures are the last ones in the buffer. 3366 unsigned FirstSignificant = N - FormatPrecision; 3367 3368 // Round. 3369 // FIXME: this probably shouldn't use 'round half up'. 3370 3371 // Rounding down is just a truncation, except we also want to drop 3372 // trailing zeros from the new result. 3373 if (buffer[FirstSignificant - 1] < '5') { 3374 while (FirstSignificant < N && buffer[FirstSignificant] == '0') 3375 FirstSignificant++; 3376 3377 exp += FirstSignificant; 3378 buffer.erase(&buffer[0], &buffer[FirstSignificant]); 3379 return; 3380 } 3381 3382 // Rounding up requires a decimal add-with-carry. If we continue 3383 // the carry, the newly-introduced zeros will just be truncated. 3384 for (unsigned I = FirstSignificant; I != N; ++I) { 3385 if (buffer[I] == '9') { 3386 FirstSignificant++; 3387 } else { 3388 buffer[I]++; 3389 break; 3390 } 3391 } 3392 3393 // If we carried through, we have exactly one digit of precision. 3394 if (FirstSignificant == N) { 3395 exp += FirstSignificant; 3396 buffer.clear(); 3397 buffer.push_back('1'); 3398 return; 3399 } 3400 3401 exp += FirstSignificant; 3402 buffer.erase(&buffer[0], &buffer[FirstSignificant]); 3403 } 3404 } 3405 3406 void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision, 3407 unsigned FormatMaxPadding) const { 3408 switch (category) { 3409 case fcInfinity: 3410 if (isNegative()) 3411 return append(Str, "-Inf"); 3412 else 3413 return append(Str, "+Inf"); 3414 3415 case fcNaN: return append(Str, "NaN"); 3416 3417 case fcZero: 3418 if (isNegative()) 3419 Str.push_back('-'); 3420 3421 if (!FormatMaxPadding) 3422 append(Str, "0.0E+0"); 3423 else 3424 Str.push_back('0'); 3425 return; 3426 3427 case fcNormal: 3428 break; 3429 } 3430 3431 if (isNegative()) 3432 Str.push_back('-'); 3433 3434 // Decompose the number into an APInt and an exponent. 3435 int exp = exponent - ((int) semantics->precision - 1); 3436 APInt significand(semantics->precision, 3437 makeArrayRef(significandParts(), 3438 partCountForBits(semantics->precision))); 3439 3440 // Set FormatPrecision if zero. We want to do this before we 3441 // truncate trailing zeros, as those are part of the precision. 3442 if (!FormatPrecision) { 3443 // We use enough digits so the number can be round-tripped back to an 3444 // APFloat. The formula comes from "How to Print Floating-Point Numbers 3445 // Accurately" by Steele and White. 3446 // FIXME: Using a formula based purely on the precision is conservative; 3447 // we can print fewer digits depending on the actual value being printed. 3448 3449 // FormatPrecision = 2 + floor(significandBits / lg_2(10)) 3450 FormatPrecision = 2 + semantics->precision * 59 / 196; 3451 } 3452 3453 // Ignore trailing binary zeros. 3454 int trailingZeros = significand.countTrailingZeros(); 3455 exp += trailingZeros; 3456 significand = significand.lshr(trailingZeros); 3457 3458 // Change the exponent from 2^e to 10^e. 3459 if (exp == 0) { 3460 // Nothing to do. 3461 } else if (exp > 0) { 3462 // Just shift left. 3463 significand = significand.zext(semantics->precision + exp); 3464 significand <<= exp; 3465 exp = 0; 3466 } else { /* exp < 0 */ 3467 int texp = -exp; 3468 3469 // We transform this using the identity: 3470 // (N)(2^-e) == (N)(5^e)(10^-e) 3471 // This means we have to multiply N (the significand) by 5^e. 3472 // To avoid overflow, we have to operate on numbers large 3473 // enough to store N * 5^e: 3474 // log2(N * 5^e) == log2(N) + e * log2(5) 3475 // <= semantics->precision + e * 137 / 59 3476 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59) 3477 3478 unsigned precision = semantics->precision + (137 * texp + 136) / 59; 3479 3480 // Multiply significand by 5^e. 3481 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8) 3482 significand = significand.zext(precision); 3483 APInt five_to_the_i(precision, 5); 3484 while (true) { 3485 if (texp & 1) significand *= five_to_the_i; 3486 3487 texp >>= 1; 3488 if (!texp) break; 3489 five_to_the_i *= five_to_the_i; 3490 } 3491 } 3492 3493 AdjustToPrecision(significand, exp, FormatPrecision); 3494 3495 SmallVector<char, 256> buffer; 3496 3497 // Fill the buffer. 3498 unsigned precision = significand.getBitWidth(); 3499 APInt ten(precision, 10); 3500 APInt digit(precision, 0); 3501 3502 bool inTrail = true; 3503 while (significand != 0) { 3504 // digit <- significand % 10 3505 // significand <- significand / 10 3506 APInt::udivrem(significand, ten, significand, digit); 3507 3508 unsigned d = digit.getZExtValue(); 3509 3510 // Drop trailing zeros. 3511 if (inTrail && !d) exp++; 3512 else { 3513 buffer.push_back((char) ('0' + d)); 3514 inTrail = false; 3515 } 3516 } 3517 3518 assert(!buffer.empty() && "no characters in buffer!"); 3519 3520 // Drop down to FormatPrecision. 3521 // TODO: don't do more precise calculations above than are required. 3522 AdjustToPrecision(buffer, exp, FormatPrecision); 3523 3524 unsigned NDigits = buffer.size(); 3525 3526 // Check whether we should use scientific notation. 3527 bool FormatScientific; 3528 if (!FormatMaxPadding) 3529 FormatScientific = true; 3530 else { 3531 if (exp >= 0) { 3532 // 765e3 --> 765000 3533 // ^^^ 3534 // But we shouldn't make the number look more precise than it is. 3535 FormatScientific = ((unsigned) exp > FormatMaxPadding || 3536 NDigits + (unsigned) exp > FormatPrecision); 3537 } else { 3538 // Power of the most significant digit. 3539 int MSD = exp + (int) (NDigits - 1); 3540 if (MSD >= 0) { 3541 // 765e-2 == 7.65 3542 FormatScientific = false; 3543 } else { 3544 // 765e-5 == 0.00765 3545 // ^ ^^ 3546 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding; 3547 } 3548 } 3549 } 3550 3551 // Scientific formatting is pretty straightforward. 3552 if (FormatScientific) { 3553 exp += (NDigits - 1); 3554 3555 Str.push_back(buffer[NDigits-1]); 3556 Str.push_back('.'); 3557 if (NDigits == 1) 3558 Str.push_back('0'); 3559 else 3560 for (unsigned I = 1; I != NDigits; ++I) 3561 Str.push_back(buffer[NDigits-1-I]); 3562 Str.push_back('E'); 3563 3564 Str.push_back(exp >= 0 ? '+' : '-'); 3565 if (exp < 0) exp = -exp; 3566 SmallVector<char, 6> expbuf; 3567 do { 3568 expbuf.push_back((char) ('0' + (exp % 10))); 3569 exp /= 10; 3570 } while (exp); 3571 for (unsigned I = 0, E = expbuf.size(); I != E; ++I) 3572 Str.push_back(expbuf[E-1-I]); 3573 return; 3574 } 3575 3576 // Non-scientific, positive exponents. 3577 if (exp >= 0) { 3578 for (unsigned I = 0; I != NDigits; ++I) 3579 Str.push_back(buffer[NDigits-1-I]); 3580 for (unsigned I = 0; I != (unsigned) exp; ++I) 3581 Str.push_back('0'); 3582 return; 3583 } 3584 3585 // Non-scientific, negative exponents. 3586 3587 // The number of digits to the left of the decimal point. 3588 int NWholeDigits = exp + (int) NDigits; 3589 3590 unsigned I = 0; 3591 if (NWholeDigits > 0) { 3592 for (; I != (unsigned) NWholeDigits; ++I) 3593 Str.push_back(buffer[NDigits-I-1]); 3594 Str.push_back('.'); 3595 } else { 3596 unsigned NZeros = 1 + (unsigned) -NWholeDigits; 3597 3598 Str.push_back('0'); 3599 Str.push_back('.'); 3600 for (unsigned Z = 1; Z != NZeros; ++Z) 3601 Str.push_back('0'); 3602 } 3603 3604 for (; I != NDigits; ++I) 3605 Str.push_back(buffer[NDigits-I-1]); 3606 } 3607 3608 bool IEEEFloat::getExactInverse(IEEEFloat *inv) const { 3609 // Special floats and denormals have no exact inverse. 3610 if (!isFiniteNonZero()) 3611 return false; 3612 3613 // Check that the number is a power of two by making sure that only the 3614 // integer bit is set in the significand. 3615 if (significandLSB() != semantics->precision - 1) 3616 return false; 3617 3618 // Get the inverse. 3619 IEEEFloat reciprocal(*semantics, 1ULL); 3620 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK) 3621 return false; 3622 3623 // Avoid multiplication with a denormal, it is not safe on all platforms and 3624 // may be slower than a normal division. 3625 if (reciprocal.isDenormal()) 3626 return false; 3627 3628 assert(reciprocal.isFiniteNonZero() && 3629 reciprocal.significandLSB() == reciprocal.semantics->precision - 1); 3630 3631 if (inv) 3632 *inv = reciprocal; 3633 3634 return true; 3635 } 3636 3637 bool IEEEFloat::isSignaling() const { 3638 if (!isNaN()) 3639 return false; 3640 3641 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the 3642 // first bit of the trailing significand being 0. 3643 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2); 3644 } 3645 3646 /// IEEE-754R 2008 5.3.1: nextUp/nextDown. 3647 /// 3648 /// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with 3649 /// appropriate sign switching before/after the computation. 3650 IEEEFloat::opStatus IEEEFloat::next(bool nextDown) { 3651 // If we are performing nextDown, swap sign so we have -x. 3652 if (nextDown) 3653 changeSign(); 3654 3655 // Compute nextUp(x) 3656 opStatus result = opOK; 3657 3658 // Handle each float category separately. 3659 switch (category) { 3660 case fcInfinity: 3661 // nextUp(+inf) = +inf 3662 if (!isNegative()) 3663 break; 3664 // nextUp(-inf) = -getLargest() 3665 makeLargest(true); 3666 break; 3667 case fcNaN: 3668 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag. 3669 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not 3670 // change the payload. 3671 if (isSignaling()) { 3672 result = opInvalidOp; 3673 // For consistency, propagate the sign of the sNaN to the qNaN. 3674 makeNaN(false, isNegative(), nullptr); 3675 } 3676 break; 3677 case fcZero: 3678 // nextUp(pm 0) = +getSmallest() 3679 makeSmallest(false); 3680 break; 3681 case fcNormal: 3682 // nextUp(-getSmallest()) = -0 3683 if (isSmallest() && isNegative()) { 3684 APInt::tcSet(significandParts(), 0, partCount()); 3685 category = fcZero; 3686 exponent = 0; 3687 break; 3688 } 3689 3690 // nextUp(getLargest()) == INFINITY 3691 if (isLargest() && !isNegative()) { 3692 APInt::tcSet(significandParts(), 0, partCount()); 3693 category = fcInfinity; 3694 exponent = semantics->maxExponent + 1; 3695 break; 3696 } 3697 3698 // nextUp(normal) == normal + inc. 3699 if (isNegative()) { 3700 // If we are negative, we need to decrement the significand. 3701 3702 // We only cross a binade boundary that requires adjusting the exponent 3703 // if: 3704 // 1. exponent != semantics->minExponent. This implies we are not in the 3705 // smallest binade or are dealing with denormals. 3706 // 2. Our significand excluding the integral bit is all zeros. 3707 bool WillCrossBinadeBoundary = 3708 exponent != semantics->minExponent && isSignificandAllZeros(); 3709 3710 // Decrement the significand. 3711 // 3712 // We always do this since: 3713 // 1. If we are dealing with a non-binade decrement, by definition we 3714 // just decrement the significand. 3715 // 2. If we are dealing with a normal -> normal binade decrement, since 3716 // we have an explicit integral bit the fact that all bits but the 3717 // integral bit are zero implies that subtracting one will yield a 3718 // significand with 0 integral bit and 1 in all other spots. Thus we 3719 // must just adjust the exponent and set the integral bit to 1. 3720 // 3. If we are dealing with a normal -> denormal binade decrement, 3721 // since we set the integral bit to 0 when we represent denormals, we 3722 // just decrement the significand. 3723 integerPart *Parts = significandParts(); 3724 APInt::tcDecrement(Parts, partCount()); 3725 3726 if (WillCrossBinadeBoundary) { 3727 // Our result is a normal number. Do the following: 3728 // 1. Set the integral bit to 1. 3729 // 2. Decrement the exponent. 3730 APInt::tcSetBit(Parts, semantics->precision - 1); 3731 exponent--; 3732 } 3733 } else { 3734 // If we are positive, we need to increment the significand. 3735 3736 // We only cross a binade boundary that requires adjusting the exponent if 3737 // the input is not a denormal and all of said input's significand bits 3738 // are set. If all of said conditions are true: clear the significand, set 3739 // the integral bit to 1, and increment the exponent. If we have a 3740 // denormal always increment since moving denormals and the numbers in the 3741 // smallest normal binade have the same exponent in our representation. 3742 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes(); 3743 3744 if (WillCrossBinadeBoundary) { 3745 integerPart *Parts = significandParts(); 3746 APInt::tcSet(Parts, 0, partCount()); 3747 APInt::tcSetBit(Parts, semantics->precision - 1); 3748 assert(exponent != semantics->maxExponent && 3749 "We can not increment an exponent beyond the maxExponent allowed" 3750 " by the given floating point semantics."); 3751 exponent++; 3752 } else { 3753 incrementSignificand(); 3754 } 3755 } 3756 break; 3757 } 3758 3759 // If we are performing nextDown, swap sign so we have -nextUp(-x) 3760 if (nextDown) 3761 changeSign(); 3762 3763 return result; 3764 } 3765 3766 void IEEEFloat::makeInf(bool Negative) { 3767 category = fcInfinity; 3768 sign = Negative; 3769 exponent = semantics->maxExponent + 1; 3770 APInt::tcSet(significandParts(), 0, partCount()); 3771 } 3772 3773 void IEEEFloat::makeZero(bool Negative) { 3774 category = fcZero; 3775 sign = Negative; 3776 exponent = semantics->minExponent-1; 3777 APInt::tcSet(significandParts(), 0, partCount()); 3778 } 3779 3780 void IEEEFloat::makeQuiet() { 3781 assert(isNaN()); 3782 APInt::tcSetBit(significandParts(), semantics->precision - 2); 3783 } 3784 3785 int ilogb(const IEEEFloat &Arg) { 3786 if (Arg.isNaN()) 3787 return IEEEFloat::IEK_NaN; 3788 if (Arg.isZero()) 3789 return IEEEFloat::IEK_Zero; 3790 if (Arg.isInfinity()) 3791 return IEEEFloat::IEK_Inf; 3792 if (!Arg.isDenormal()) 3793 return Arg.exponent; 3794 3795 IEEEFloat Normalized(Arg); 3796 int SignificandBits = Arg.getSemantics().precision - 1; 3797 3798 Normalized.exponent += SignificandBits; 3799 Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero); 3800 return Normalized.exponent - SignificandBits; 3801 } 3802 3803 IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) { 3804 auto MaxExp = X.getSemantics().maxExponent; 3805 auto MinExp = X.getSemantics().minExponent; 3806 3807 // If Exp is wildly out-of-scale, simply adding it to X.exponent will 3808 // overflow; clamp it to a safe range before adding, but ensure that the range 3809 // is large enough that the clamp does not change the result. The range we 3810 // need to support is the difference between the largest possible exponent and 3811 // the normalized exponent of half the smallest denormal. 3812 3813 int SignificandBits = X.getSemantics().precision - 1; 3814 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1; 3815 3816 // Clamp to one past the range ends to let normalize handle overlflow. 3817 X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement); 3818 X.normalize(RoundingMode, lfExactlyZero); 3819 if (X.isNaN()) 3820 X.makeQuiet(); 3821 return X; 3822 } 3823 3824 IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) { 3825 Exp = ilogb(Val); 3826 3827 // Quiet signalling nans. 3828 if (Exp == IEEEFloat::IEK_NaN) { 3829 IEEEFloat Quiet(Val); 3830 Quiet.makeQuiet(); 3831 return Quiet; 3832 } 3833 3834 if (Exp == IEEEFloat::IEK_Inf) 3835 return Val; 3836 3837 // 1 is added because frexp is defined to return a normalized fraction in 3838 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0). 3839 Exp = Exp == IEEEFloat::IEK_Zero ? 0 : Exp + 1; 3840 return scalbn(Val, -Exp, RM); 3841 } 3842 3843 DoubleAPFloat::DoubleAPFloat(const fltSemantics &S) 3844 : Semantics(&S), Floats(new APFloat[2]{APFloat(PPCDoubleDoubleImpl), 3845 APFloat(IEEEdouble)}) { 3846 assert(Semantics == &PPCDoubleDouble); 3847 } 3848 3849 DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag) 3850 : Semantics(&S), 3851 Floats(new APFloat[2]{APFloat(PPCDoubleDoubleImpl, uninitialized), 3852 APFloat(IEEEdouble, uninitialized)}) { 3853 assert(Semantics == &PPCDoubleDouble); 3854 } 3855 3856 DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I) 3857 : Semantics(&S), Floats(new APFloat[2]{APFloat(PPCDoubleDoubleImpl, I), 3858 APFloat(IEEEdouble)}) { 3859 assert(Semantics == &PPCDoubleDouble); 3860 } 3861 3862 DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I) 3863 : Semantics(&S), Floats(new APFloat[2]{APFloat(PPCDoubleDoubleImpl, I), 3864 APFloat(IEEEdouble)}) { 3865 assert(Semantics == &PPCDoubleDouble); 3866 } 3867 3868 DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First, 3869 APFloat &&Second) 3870 : Semantics(&S), 3871 Floats(new APFloat[2]{std::move(First), std::move(Second)}) { 3872 assert(Semantics == &PPCDoubleDouble); 3873 // TODO Check for First == &IEEEdouble once the transition is done. 3874 assert(&Floats[0].getSemantics() == &PPCDoubleDoubleImpl); 3875 assert(&Floats[1].getSemantics() == &IEEEdouble); 3876 } 3877 3878 DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS) 3879 : Semantics(RHS.Semantics), 3880 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]), 3881 APFloat(RHS.Floats[1])} 3882 : nullptr) { 3883 assert(Semantics == &PPCDoubleDouble); 3884 } 3885 3886 DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS) 3887 : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) { 3888 RHS.Semantics = &Bogus; 3889 assert(Semantics == &PPCDoubleDouble); 3890 } 3891 3892 DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) { 3893 if (Semantics == RHS.Semantics && RHS.Floats) { 3894 Floats[0] = RHS.Floats[0]; 3895 Floats[1] = RHS.Floats[1]; 3896 } else if (this != &RHS) { 3897 this->~DoubleAPFloat(); 3898 new (this) DoubleAPFloat(RHS); 3899 } 3900 return *this; 3901 } 3902 3903 } // End detail namespace 3904 3905 APFloat::opStatus APFloat::convertFromString(StringRef Str, roundingMode RM) { 3906 return getIEEE().convertFromString(Str, RM); 3907 } 3908 3909 hash_code hash_value(const APFloat &Arg) { return hash_value(Arg.getIEEE()); } 3910 3911 APFloat::APFloat(const fltSemantics &Semantics, StringRef S) 3912 : APFloat(Semantics) { 3913 convertFromString(S, rmNearestTiesToEven); 3914 } 3915 3916 APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics, 3917 roundingMode RM, bool *losesInfo) { 3918 if (&getSemantics() == &ToSemantics) 3919 return opOK; 3920 if (usesLayout<IEEEFloat>(getSemantics()) && 3921 usesLayout<IEEEFloat>(ToSemantics)) { 3922 return U.IEEE.convert(ToSemantics, RM, losesInfo); 3923 } else if (usesLayout<IEEEFloat>(getSemantics()) && 3924 usesLayout<DoubleAPFloat>(ToSemantics)) { 3925 assert(&ToSemantics == &PPCDoubleDouble); 3926 auto Ret = U.IEEE.convert(PPCDoubleDoubleImpl, RM, losesInfo); 3927 *this = APFloat( 3928 DoubleAPFloat(PPCDoubleDouble, std::move(*this), APFloat(IEEEdouble))); 3929 return Ret; 3930 } else if (usesLayout<DoubleAPFloat>(getSemantics()) && 3931 usesLayout<IEEEFloat>(ToSemantics)) { 3932 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo); 3933 *this = APFloat(std::move(getIEEE())); 3934 return Ret; 3935 } else { 3936 llvm_unreachable("Unexpected semantics"); 3937 } 3938 } 3939 3940 } // End llvm namespace 3941