1 //===-- APFloat.cpp - Implement APFloat class -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Neil Booth and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a class to represent arbitrary precision floating
11 // point values and provide a variety of arithmetic operations on them.
13 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/Support/MathExtras.h"
22 #define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
24 /* Assumed in hexadecimal significand parsing, and conversion to
25 hexadecimal strings. */
26 COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
30 /* Represents floating point arithmetic semantics. */
32 /* The largest E such that 2^E is representable; this matches the
33 definition of IEEE 754. */
34 exponent_t maxExponent;
36 /* The smallest E such that 2^E is a normalized number; this
37 matches the definition of IEEE 754. */
38 exponent_t minExponent;
40 /* Number of bits in the significand. This includes the integer
42 unsigned char precision;
44 /* If the target format has an implicit integer bit. */
45 bool implicitIntegerBit;
48 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
49 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
50 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
51 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, false };
52 const fltSemantics APFloat::Bogus = { 0, 0, 0, false };
54 // The PowerPC format consists of two doubles. It does not map cleanly
55 // onto the usual format above. For now only storage of constants of
56 // this type is supported, no arithmetic.
57 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, true };
60 /* Put a bunch of private, handy routines in an anonymous namespace. */
64 partCountForBits(unsigned int bits)
66 return ((bits) + integerPartWidth - 1) / integerPartWidth;
70 digitValue(unsigned int c)
82 hexDigitValue (unsigned int c)
101 /* This is ugly and needs cleaning up, but I don't immediately see
102 how whilst remaining safe. */
104 totalExponent(const char *p, int exponentAdjustment)
106 integerPart unsignedExponent;
107 bool negative, overflow;
110 /* Move past the exponent letter and sign to the digits. */
112 negative = *p == '-';
113 if(*p == '-' || *p == '+')
116 unsignedExponent = 0;
121 value = digitValue(*p);
126 unsignedExponent = unsignedExponent * 10 + value;
127 if(unsignedExponent > 65535)
131 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
135 exponent = unsignedExponent;
137 exponent = -exponent;
138 exponent += exponentAdjustment;
139 if(exponent > 65535 || exponent < -65536)
144 exponent = negative ? -65536: 65535;
150 skipLeadingZeroesAndAnyDot(const char *p, const char **dot)
165 /* Return the trailing fraction of a hexadecimal number.
166 DIGITVALUE is the first hex digit of the fraction, P points to
169 trailingHexadecimalFraction(const char *p, unsigned int digitValue)
171 unsigned int hexDigit;
173 /* If the first trailing digit isn't 0 or 8 we can work out the
174 fraction immediately. */
176 return lfMoreThanHalf;
177 else if(digitValue < 8 && digitValue > 0)
178 return lfLessThanHalf;
180 /* Otherwise we need to find the first non-zero digit. */
184 hexDigit = hexDigitValue(*p);
186 /* If we ran off the end it is exactly zero or one-half, otherwise
189 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
191 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
194 /* Return the fraction lost were a bignum truncated losing the least
195 significant BITS bits. */
197 lostFractionThroughTruncation(const integerPart *parts,
198 unsigned int partCount,
203 lsb = APInt::tcLSB(parts, partCount);
205 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
207 return lfExactlyZero;
209 return lfExactlyHalf;
210 if(bits <= partCount * integerPartWidth
211 && APInt::tcExtractBit(parts, bits - 1))
212 return lfMoreThanHalf;
214 return lfLessThanHalf;
217 /* Shift DST right BITS bits noting lost fraction. */
219 shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
221 lostFraction lost_fraction;
223 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
225 APInt::tcShiftRight(dst, parts, bits);
227 return lost_fraction;
230 /* Combine the effect of two lost fractions. */
232 combineLostFractions(lostFraction moreSignificant,
233 lostFraction lessSignificant)
235 if(lessSignificant != lfExactlyZero) {
236 if(moreSignificant == lfExactlyZero)
237 moreSignificant = lfLessThanHalf;
238 else if(moreSignificant == lfExactlyHalf)
239 moreSignificant = lfMoreThanHalf;
242 return moreSignificant;
245 /* Zero at the end to avoid modular arithmetic when adding one; used
246 when rounding up during hexadecimal output. */
247 static const char hexDigitsLower[] = "0123456789abcdef0";
248 static const char hexDigitsUpper[] = "0123456789ABCDEF0";
249 static const char infinityL[] = "infinity";
250 static const char infinityU[] = "INFINITY";
251 static const char NaNL[] = "nan";
252 static const char NaNU[] = "NAN";
254 /* Write out an integerPart in hexadecimal, starting with the most
255 significant nibble. Write out exactly COUNT hexdigits, return
258 partAsHex (char *dst, integerPart part, unsigned int count,
259 const char *hexDigitChars)
261 unsigned int result = count;
263 assert (count != 0 && count <= integerPartWidth / 4);
265 part >>= (integerPartWidth - 4 * count);
267 dst[count] = hexDigitChars[part & 0xf];
274 /* Write out an unsigned decimal integer. */
276 writeUnsignedDecimal (char *dst, unsigned int n)
292 /* Write out a signed decimal integer. */
294 writeSignedDecimal (char *dst, int value)
298 dst = writeUnsignedDecimal(dst, -(unsigned) value);
300 dst = writeUnsignedDecimal(dst, value);
308 APFloat::initialize(const fltSemantics *ourSemantics)
312 semantics = ourSemantics;
315 significand.parts = new integerPart[count];
319 APFloat::freeSignificand()
322 delete [] significand.parts;
326 APFloat::assign(const APFloat &rhs)
328 assert(semantics == rhs.semantics);
331 category = rhs.category;
332 exponent = rhs.exponent;
334 exponent2 = rhs.exponent2;
335 if(category == fcNormal || category == fcNaN)
336 copySignificand(rhs);
340 APFloat::copySignificand(const APFloat &rhs)
342 assert(category == fcNormal || category == fcNaN);
343 assert(rhs.partCount() >= partCount());
345 APInt::tcAssign(significandParts(), rhs.significandParts(),
350 APFloat::operator=(const APFloat &rhs)
353 if(semantics != rhs.semantics) {
355 initialize(rhs.semantics);
364 APFloat::bitwiseIsEqual(const APFloat &rhs) const {
367 if (semantics != rhs.semantics ||
368 category != rhs.category ||
371 if (semantics==(const llvm::fltSemantics* const)&PPCDoubleDouble &&
374 if (category==fcZero || category==fcInfinity)
376 else if (category==fcNormal && exponent!=rhs.exponent)
378 else if (semantics==(const llvm::fltSemantics* const)&PPCDoubleDouble &&
379 exponent2!=rhs.exponent2)
383 const integerPart* p=significandParts();
384 const integerPart* q=rhs.significandParts();
385 for (; i>0; i--, p++, q++) {
393 APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
395 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
396 "Compile-time arithmetic on PPC long double not supported yet");
397 initialize(&ourSemantics);
400 exponent = ourSemantics.precision - 1;
401 significandParts()[0] = value;
402 normalize(rmNearestTiesToEven, lfExactlyZero);
405 APFloat::APFloat(const fltSemantics &ourSemantics,
406 fltCategory ourCategory, bool negative)
408 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
409 "Compile-time arithmetic on PPC long double not supported yet");
410 initialize(&ourSemantics);
411 category = ourCategory;
413 if(category == fcNormal)
417 APFloat::APFloat(const fltSemantics &ourSemantics, const char *text)
419 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
420 "Compile-time arithmetic on PPC long double not supported yet");
421 initialize(&ourSemantics);
422 convertFromString(text, rmNearestTiesToEven);
425 APFloat::APFloat(const APFloat &rhs)
427 initialize(rhs.semantics);
437 APFloat::partCount() const
439 return partCountForBits(semantics->precision + 1);
443 APFloat::semanticsPrecision(const fltSemantics &semantics)
445 return semantics.precision;
449 APFloat::significandParts() const
451 return const_cast<APFloat *>(this)->significandParts();
455 APFloat::significandParts()
457 assert(category == fcNormal || category == fcNaN);
460 return significand.parts;
462 return &significand.part;
466 APFloat::zeroSignificand()
469 APInt::tcSet(significandParts(), 0, partCount());
472 /* Increment an fcNormal floating point number's significand. */
474 APFloat::incrementSignificand()
478 carry = APInt::tcIncrement(significandParts(), partCount());
480 /* Our callers should never cause us to overflow. */
484 /* Add the significand of the RHS. Returns the carry flag. */
486 APFloat::addSignificand(const APFloat &rhs)
490 parts = significandParts();
492 assert(semantics == rhs.semantics);
493 assert(exponent == rhs.exponent);
495 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
498 /* Subtract the significand of the RHS with a borrow flag. Returns
501 APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
505 parts = significandParts();
507 assert(semantics == rhs.semantics);
508 assert(exponent == rhs.exponent);
510 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
514 /* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
515 on to the full-precision result of the multiplication. Returns the
518 APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
520 unsigned int omsb; // One, not zero, based MSB.
521 unsigned int partsCount, newPartsCount, precision;
522 integerPart *lhsSignificand;
523 integerPart scratch[4];
524 integerPart *fullSignificand;
525 lostFraction lost_fraction;
527 assert(semantics == rhs.semantics);
529 precision = semantics->precision;
530 newPartsCount = partCountForBits(precision * 2);
532 if(newPartsCount > 4)
533 fullSignificand = new integerPart[newPartsCount];
535 fullSignificand = scratch;
537 lhsSignificand = significandParts();
538 partsCount = partCount();
540 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
541 rhs.significandParts(), partsCount, partsCount);
543 lost_fraction = lfExactlyZero;
544 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
545 exponent += rhs.exponent;
548 Significand savedSignificand = significand;
549 const fltSemantics *savedSemantics = semantics;
550 fltSemantics extendedSemantics;
552 unsigned int extendedPrecision;
554 /* Normalize our MSB. */
555 extendedPrecision = precision + precision - 1;
556 if(omsb != extendedPrecision)
558 APInt::tcShiftLeft(fullSignificand, newPartsCount,
559 extendedPrecision - omsb);
560 exponent -= extendedPrecision - omsb;
563 /* Create new semantics. */
564 extendedSemantics = *semantics;
565 extendedSemantics.precision = extendedPrecision;
567 if(newPartsCount == 1)
568 significand.part = fullSignificand[0];
570 significand.parts = fullSignificand;
571 semantics = &extendedSemantics;
573 APFloat extendedAddend(*addend);
574 status = extendedAddend.convert(extendedSemantics, rmTowardZero);
575 assert(status == opOK);
576 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
578 /* Restore our state. */
579 if(newPartsCount == 1)
580 fullSignificand[0] = significand.part;
581 significand = savedSignificand;
582 semantics = savedSemantics;
584 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
587 exponent -= (precision - 1);
589 if(omsb > precision) {
590 unsigned int bits, significantParts;
593 bits = omsb - precision;
594 significantParts = partCountForBits(omsb);
595 lf = shiftRight(fullSignificand, significantParts, bits);
596 lost_fraction = combineLostFractions(lf, lost_fraction);
600 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
602 if(newPartsCount > 4)
603 delete [] fullSignificand;
605 return lost_fraction;
608 /* Multiply the significands of LHS and RHS to DST. */
610 APFloat::divideSignificand(const APFloat &rhs)
612 unsigned int bit, i, partsCount;
613 const integerPart *rhsSignificand;
614 integerPart *lhsSignificand, *dividend, *divisor;
615 integerPart scratch[4];
616 lostFraction lost_fraction;
618 assert(semantics == rhs.semantics);
620 lhsSignificand = significandParts();
621 rhsSignificand = rhs.significandParts();
622 partsCount = partCount();
625 dividend = new integerPart[partsCount * 2];
629 divisor = dividend + partsCount;
631 /* Copy the dividend and divisor as they will be modified in-place. */
632 for(i = 0; i < partsCount; i++) {
633 dividend[i] = lhsSignificand[i];
634 divisor[i] = rhsSignificand[i];
635 lhsSignificand[i] = 0;
638 exponent -= rhs.exponent;
640 unsigned int precision = semantics->precision;
642 /* Normalize the divisor. */
643 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
646 APInt::tcShiftLeft(divisor, partsCount, bit);
649 /* Normalize the dividend. */
650 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
653 APInt::tcShiftLeft(dividend, partsCount, bit);
656 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
658 APInt::tcShiftLeft(dividend, partsCount, 1);
659 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
663 for(bit = precision; bit; bit -= 1) {
664 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
665 APInt::tcSubtract(dividend, divisor, 0, partsCount);
666 APInt::tcSetBit(lhsSignificand, bit - 1);
669 APInt::tcShiftLeft(dividend, partsCount, 1);
672 /* Figure out the lost fraction. */
673 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
676 lost_fraction = lfMoreThanHalf;
678 lost_fraction = lfExactlyHalf;
679 else if(APInt::tcIsZero(dividend, partsCount))
680 lost_fraction = lfExactlyZero;
682 lost_fraction = lfLessThanHalf;
687 return lost_fraction;
691 APFloat::significandMSB() const
693 return APInt::tcMSB(significandParts(), partCount());
697 APFloat::significandLSB() const
699 return APInt::tcLSB(significandParts(), partCount());
702 /* Note that a zero result is NOT normalized to fcZero. */
704 APFloat::shiftSignificandRight(unsigned int bits)
706 /* Our exponent should not overflow. */
707 assert((exponent_t) (exponent + bits) >= exponent);
711 return shiftRight(significandParts(), partCount(), bits);
714 /* Shift the significand left BITS bits, subtract BITS from its exponent. */
716 APFloat::shiftSignificandLeft(unsigned int bits)
718 assert(bits < semantics->precision);
721 unsigned int partsCount = partCount();
723 APInt::tcShiftLeft(significandParts(), partsCount, bits);
726 assert(!APInt::tcIsZero(significandParts(), partsCount));
731 APFloat::compareAbsoluteValue(const APFloat &rhs) const
735 assert(semantics == rhs.semantics);
736 assert(category == fcNormal);
737 assert(rhs.category == fcNormal);
739 compare = exponent - rhs.exponent;
741 /* If exponents are equal, do an unsigned bignum comparison of the
744 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
748 return cmpGreaterThan;
755 /* Handle overflow. Sign is preserved. We either become infinity or
756 the largest finite number. */
758 APFloat::handleOverflow(roundingMode rounding_mode)
761 if(rounding_mode == rmNearestTiesToEven
762 || rounding_mode == rmNearestTiesToAway
763 || (rounding_mode == rmTowardPositive && !sign)
764 || (rounding_mode == rmTowardNegative && sign))
766 category = fcInfinity;
767 return (opStatus) (opOverflow | opInexact);
770 /* Otherwise we become the largest finite number. */
772 exponent = semantics->maxExponent;
773 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
774 semantics->precision);
779 /* Returns TRUE if, when truncating the current number, with BIT the
780 new LSB, with the given lost fraction and rounding mode, the result
781 would need to be rounded away from zero (i.e., by increasing the
782 signficand). This routine must work for fcZero of both signs, and
785 APFloat::roundAwayFromZero(roundingMode rounding_mode,
786 lostFraction lost_fraction,
787 unsigned int bit) const
789 /* NaNs and infinities should not have lost fractions. */
790 assert(category == fcNormal || category == fcZero);
792 /* Current callers never pass this so we don't handle it. */
793 assert(lost_fraction != lfExactlyZero);
795 switch(rounding_mode) {
799 case rmNearestTiesToAway:
800 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
802 case rmNearestTiesToEven:
803 if(lost_fraction == lfMoreThanHalf)
806 /* Our zeroes don't have a significand to test. */
807 if(lost_fraction == lfExactlyHalf && category != fcZero)
808 return APInt::tcExtractBit(significandParts(), bit);
815 case rmTowardPositive:
816 return sign == false;
818 case rmTowardNegative:
824 APFloat::normalize(roundingMode rounding_mode,
825 lostFraction lost_fraction)
827 unsigned int omsb; /* One, not zero, based MSB. */
830 if(category != fcNormal)
833 /* Before rounding normalize the exponent of fcNormal numbers. */
834 omsb = significandMSB() + 1;
837 /* OMSB is numbered from 1. We want to place it in the integer
838 bit numbered PRECISON if possible, with a compensating change in
840 exponentChange = omsb - semantics->precision;
842 /* If the resulting exponent is too high, overflow according to
843 the rounding mode. */
844 if(exponent + exponentChange > semantics->maxExponent)
845 return handleOverflow(rounding_mode);
847 /* Subnormal numbers have exponent minExponent, and their MSB
848 is forced based on that. */
849 if(exponent + exponentChange < semantics->minExponent)
850 exponentChange = semantics->minExponent - exponent;
852 /* Shifting left is easy as we don't lose precision. */
853 if(exponentChange < 0) {
854 assert(lost_fraction == lfExactlyZero);
856 shiftSignificandLeft(-exponentChange);
861 if(exponentChange > 0) {
864 /* Shift right and capture any new lost fraction. */
865 lf = shiftSignificandRight(exponentChange);
867 lost_fraction = combineLostFractions(lf, lost_fraction);
869 /* Keep OMSB up-to-date. */
870 if(omsb > (unsigned) exponentChange)
871 omsb -= (unsigned) exponentChange;
877 /* Now round the number according to rounding_mode given the lost
880 /* As specified in IEEE 754, since we do not trap we do not report
881 underflow for exact results. */
882 if(lost_fraction == lfExactlyZero) {
883 /* Canonicalize zeroes. */
890 /* Increment the significand if we're rounding away from zero. */
891 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
893 exponent = semantics->minExponent;
895 incrementSignificand();
896 omsb = significandMSB() + 1;
898 /* Did the significand increment overflow? */
899 if(omsb == (unsigned) semantics->precision + 1) {
900 /* Renormalize by incrementing the exponent and shifting our
901 significand right one. However if we already have the
902 maximum exponent we overflow to infinity. */
903 if(exponent == semantics->maxExponent) {
904 category = fcInfinity;
906 return (opStatus) (opOverflow | opInexact);
909 shiftSignificandRight(1);
915 /* The normal case - we were and are not denormal, and any
916 significand increment above didn't overflow. */
917 if(omsb == semantics->precision)
920 /* We have a non-zero denormal. */
921 assert(omsb < semantics->precision);
922 assert(exponent == semantics->minExponent);
924 /* Canonicalize zeroes. */
928 /* The fcZero case is a denormal that underflowed to zero. */
929 return (opStatus) (opUnderflow | opInexact);
933 APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
935 switch(convolve(category, rhs.category)) {
939 case convolve(fcNaN, fcZero):
940 case convolve(fcNaN, fcNormal):
941 case convolve(fcNaN, fcInfinity):
942 case convolve(fcNaN, fcNaN):
943 case convolve(fcNormal, fcZero):
944 case convolve(fcInfinity, fcNormal):
945 case convolve(fcInfinity, fcZero):
948 case convolve(fcZero, fcNaN):
949 case convolve(fcNormal, fcNaN):
950 case convolve(fcInfinity, fcNaN):
952 copySignificand(rhs);
955 case convolve(fcNormal, fcInfinity):
956 case convolve(fcZero, fcInfinity):
957 category = fcInfinity;
958 sign = rhs.sign ^ subtract;
961 case convolve(fcZero, fcNormal):
963 sign = rhs.sign ^ subtract;
966 case convolve(fcZero, fcZero):
967 /* Sign depends on rounding mode; handled by caller. */
970 case convolve(fcInfinity, fcInfinity):
971 /* Differently signed infinities can only be validly
973 if(sign ^ rhs.sign != subtract) {
975 // Arbitrary but deterministic value for significand
976 APInt::tcSet(significandParts(), ~0U, partCount());
982 case convolve(fcNormal, fcNormal):
987 /* Add or subtract two normal numbers. */
989 APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
992 lostFraction lost_fraction;
995 /* Determine if the operation on the absolute values is effectively
996 an addition or subtraction. */
997 subtract ^= (sign ^ rhs.sign);
999 /* Are we bigger exponent-wise than the RHS? */
1000 bits = exponent - rhs.exponent;
1002 /* Subtraction is more subtle than one might naively expect. */
1004 APFloat temp_rhs(rhs);
1008 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1009 lost_fraction = lfExactlyZero;
1010 } else if (bits > 0) {
1011 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1012 shiftSignificandLeft(1);
1015 lost_fraction = shiftSignificandRight(-bits - 1);
1016 temp_rhs.shiftSignificandLeft(1);
1021 carry = temp_rhs.subtractSignificand
1022 (*this, lost_fraction != lfExactlyZero);
1023 copySignificand(temp_rhs);
1026 carry = subtractSignificand
1027 (temp_rhs, lost_fraction != lfExactlyZero);
1030 /* Invert the lost fraction - it was on the RHS and
1032 if(lost_fraction == lfLessThanHalf)
1033 lost_fraction = lfMoreThanHalf;
1034 else if(lost_fraction == lfMoreThanHalf)
1035 lost_fraction = lfLessThanHalf;
1037 /* The code above is intended to ensure that no borrow is
1042 APFloat temp_rhs(rhs);
1044 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1045 carry = addSignificand(temp_rhs);
1047 lost_fraction = shiftSignificandRight(-bits);
1048 carry = addSignificand(rhs);
1051 /* We have a guard bit; generating a carry cannot happen. */
1055 return lost_fraction;
1059 APFloat::multiplySpecials(const APFloat &rhs)
1061 switch(convolve(category, rhs.category)) {
1065 case convolve(fcNaN, fcZero):
1066 case convolve(fcNaN, fcNormal):
1067 case convolve(fcNaN, fcInfinity):
1068 case convolve(fcNaN, fcNaN):
1071 case convolve(fcZero, fcNaN):
1072 case convolve(fcNormal, fcNaN):
1073 case convolve(fcInfinity, fcNaN):
1075 copySignificand(rhs);
1078 case convolve(fcNormal, fcInfinity):
1079 case convolve(fcInfinity, fcNormal):
1080 case convolve(fcInfinity, fcInfinity):
1081 category = fcInfinity;
1084 case convolve(fcZero, fcNormal):
1085 case convolve(fcNormal, fcZero):
1086 case convolve(fcZero, fcZero):
1090 case convolve(fcZero, fcInfinity):
1091 case convolve(fcInfinity, fcZero):
1093 // Arbitrary but deterministic value for significand
1094 APInt::tcSet(significandParts(), ~0U, partCount());
1097 case convolve(fcNormal, fcNormal):
1103 APFloat::divideSpecials(const APFloat &rhs)
1105 switch(convolve(category, rhs.category)) {
1109 case convolve(fcNaN, fcZero):
1110 case convolve(fcNaN, fcNormal):
1111 case convolve(fcNaN, fcInfinity):
1112 case convolve(fcNaN, fcNaN):
1113 case convolve(fcInfinity, fcZero):
1114 case convolve(fcInfinity, fcNormal):
1115 case convolve(fcZero, fcInfinity):
1116 case convolve(fcZero, fcNormal):
1119 case convolve(fcZero, fcNaN):
1120 case convolve(fcNormal, fcNaN):
1121 case convolve(fcInfinity, fcNaN):
1123 copySignificand(rhs);
1126 case convolve(fcNormal, fcInfinity):
1130 case convolve(fcNormal, fcZero):
1131 category = fcInfinity;
1134 case convolve(fcInfinity, fcInfinity):
1135 case convolve(fcZero, fcZero):
1137 // Arbitrary but deterministic value for significand
1138 APInt::tcSet(significandParts(), ~0U, partCount());
1141 case convolve(fcNormal, fcNormal):
1148 APFloat::changeSign()
1150 /* Look mummy, this one's easy. */
1155 APFloat::clearSign()
1157 /* So is this one. */
1162 APFloat::copySign(const APFloat &rhs)
1168 /* Normalized addition or subtraction. */
1170 APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
1175 fs = addOrSubtractSpecials(rhs, subtract);
1177 /* This return code means it was not a simple case. */
1178 if(fs == opDivByZero) {
1179 lostFraction lost_fraction;
1181 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1182 fs = normalize(rounding_mode, lost_fraction);
1184 /* Can only be zero if we lost no fraction. */
1185 assert(category != fcZero || lost_fraction == lfExactlyZero);
1188 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1189 positive zero unless rounding to minus infinity, except that
1190 adding two like-signed zeroes gives that zero. */
1191 if(category == fcZero) {
1192 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1193 sign = (rounding_mode == rmTowardNegative);
1199 /* Normalized addition. */
1201 APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1203 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1204 "Compile-time arithmetic on PPC long double not supported yet");
1205 return addOrSubtract(rhs, rounding_mode, false);
1208 /* Normalized subtraction. */
1210 APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1212 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1213 "Compile-time arithmetic on PPC long double not supported yet");
1214 return addOrSubtract(rhs, rounding_mode, true);
1217 /* Normalized multiply. */
1219 APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1221 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1222 "Compile-time arithmetic on PPC long double not supported yet");
1226 fs = multiplySpecials(rhs);
1228 if(category == fcNormal) {
1229 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1230 fs = normalize(rounding_mode, lost_fraction);
1231 if(lost_fraction != lfExactlyZero)
1232 fs = (opStatus) (fs | opInexact);
1238 /* Normalized divide. */
1240 APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1242 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1243 "Compile-time arithmetic on PPC long double not supported yet");
1247 fs = divideSpecials(rhs);
1249 if(category == fcNormal) {
1250 lostFraction lost_fraction = divideSignificand(rhs);
1251 fs = normalize(rounding_mode, lost_fraction);
1252 if(lost_fraction != lfExactlyZero)
1253 fs = (opStatus) (fs | opInexact);
1259 /* Normalized remainder. This is not currently doing TRT. */
1261 APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1263 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1264 "Compile-time arithmetic on PPC long double not supported yet");
1267 unsigned int origSign = sign;
1268 fs = V.divide(rhs, rmNearestTiesToEven);
1269 if (fs == opDivByZero)
1272 int parts = partCount();
1273 integerPart *x = new integerPart[parts];
1274 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1275 rmNearestTiesToEven);
1276 if (fs==opInvalidOp)
1279 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1280 rmNearestTiesToEven);
1281 assert(fs==opOK); // should always work
1283 fs = V.multiply(rhs, rounding_mode);
1284 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1286 fs = subtract(V, rounding_mode);
1287 assert(fs==opOK || fs==opInexact); // likewise
1290 sign = origSign; // IEEE754 requires this
1295 /* Normalized fused-multiply-add. */
1297 APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
1298 const APFloat &addend,
1299 roundingMode rounding_mode)
1301 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1302 "Compile-time arithmetic on PPC long double not supported yet");
1305 /* Post-multiplication sign, before addition. */
1306 sign ^= multiplicand.sign;
1308 /* If and only if all arguments are normal do we need to do an
1309 extended-precision calculation. */
1310 if(category == fcNormal
1311 && multiplicand.category == fcNormal
1312 && addend.category == fcNormal) {
1313 lostFraction lost_fraction;
1315 lost_fraction = multiplySignificand(multiplicand, &addend);
1316 fs = normalize(rounding_mode, lost_fraction);
1317 if(lost_fraction != lfExactlyZero)
1318 fs = (opStatus) (fs | opInexact);
1320 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1321 positive zero unless rounding to minus infinity, except that
1322 adding two like-signed zeroes gives that zero. */
1323 if(category == fcZero && sign != addend.sign)
1324 sign = (rounding_mode == rmTowardNegative);
1326 fs = multiplySpecials(multiplicand);
1328 /* FS can only be opOK or opInvalidOp. There is no more work
1329 to do in the latter case. The IEEE-754R standard says it is
1330 implementation-defined in this case whether, if ADDEND is a
1331 quiet NaN, we raise invalid op; this implementation does so.
1333 If we need to do the addition we can do so with normal
1336 fs = addOrSubtract(addend, rounding_mode, false);
1342 /* Comparison requires normalized numbers. */
1344 APFloat::compare(const APFloat &rhs) const
1346 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1347 "Compile-time arithmetic on PPC long double not supported yet");
1350 assert(semantics == rhs.semantics);
1352 switch(convolve(category, rhs.category)) {
1356 case convolve(fcNaN, fcZero):
1357 case convolve(fcNaN, fcNormal):
1358 case convolve(fcNaN, fcInfinity):
1359 case convolve(fcNaN, fcNaN):
1360 case convolve(fcZero, fcNaN):
1361 case convolve(fcNormal, fcNaN):
1362 case convolve(fcInfinity, fcNaN):
1363 return cmpUnordered;
1365 case convolve(fcInfinity, fcNormal):
1366 case convolve(fcInfinity, fcZero):
1367 case convolve(fcNormal, fcZero):
1371 return cmpGreaterThan;
1373 case convolve(fcNormal, fcInfinity):
1374 case convolve(fcZero, fcInfinity):
1375 case convolve(fcZero, fcNormal):
1377 return cmpGreaterThan;
1381 case convolve(fcInfinity, fcInfinity):
1382 if(sign == rhs.sign)
1387 return cmpGreaterThan;
1389 case convolve(fcZero, fcZero):
1392 case convolve(fcNormal, fcNormal):
1396 /* Two normal numbers. Do they have the same sign? */
1397 if(sign != rhs.sign) {
1399 result = cmpLessThan;
1401 result = cmpGreaterThan;
1403 /* Compare absolute values; invert result if negative. */
1404 result = compareAbsoluteValue(rhs);
1407 if(result == cmpLessThan)
1408 result = cmpGreaterThan;
1409 else if(result == cmpGreaterThan)
1410 result = cmpLessThan;
1418 APFloat::convert(const fltSemantics &toSemantics,
1419 roundingMode rounding_mode)
1421 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1422 "Compile-time arithmetic on PPC long double not supported yet");
1423 lostFraction lostFraction;
1424 unsigned int newPartCount, oldPartCount;
1427 lostFraction = lfExactlyZero;
1428 newPartCount = partCountForBits(toSemantics.precision + 1);
1429 oldPartCount = partCount();
1431 /* Handle storage complications. If our new form is wider,
1432 re-allocate our bit pattern into wider storage. If it is
1433 narrower, we ignore the excess parts, but if narrowing to a
1434 single part we need to free the old storage.
1435 Be careful not to reference significandParts for zeroes
1436 and infinities, since it aborts. */
1437 if (newPartCount > oldPartCount) {
1438 integerPart *newParts;
1439 newParts = new integerPart[newPartCount];
1440 APInt::tcSet(newParts, 0, newPartCount);
1441 if (category==fcNormal || category==fcNaN)
1442 APInt::tcAssign(newParts, significandParts(), oldPartCount);
1444 significand.parts = newParts;
1445 } else if (newPartCount < oldPartCount) {
1446 /* Capture any lost fraction through truncation of parts so we get
1447 correct rounding whilst normalizing. */
1448 if (category==fcNormal)
1449 lostFraction = lostFractionThroughTruncation
1450 (significandParts(), oldPartCount, toSemantics.precision);
1451 if (newPartCount == 1) {
1452 integerPart newPart = 0;
1453 if (category==fcNormal || category==fcNaN)
1454 newPart = significandParts()[0];
1456 significand.part = newPart;
1460 if(category == fcNormal) {
1461 /* Re-interpret our bit-pattern. */
1462 exponent += toSemantics.precision - semantics->precision;
1463 semantics = &toSemantics;
1464 fs = normalize(rounding_mode, lostFraction);
1465 } else if (category == fcNaN) {
1466 int shift = toSemantics.precision - semantics->precision;
1467 // No normalization here, just truncate
1469 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1471 APInt::tcShiftRight(significandParts(), newPartCount, -shift);
1472 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1473 // does not give you back the same bits. This is dubious, and we
1474 // don't currently do it. You're really supposed to get
1475 // an invalid operation signal at runtime, but nobody does that.
1476 semantics = &toSemantics;
1479 semantics = &toSemantics;
1486 /* Convert a floating point number to an integer according to the
1487 rounding mode. If the rounded integer value is out of range this
1488 returns an invalid operation exception. If the rounded value is in
1489 range but the floating point number is not the exact integer, the C
1490 standard doesn't require an inexact exception to be raised. IEEE
1491 854 does require it so we do that.
1493 Note that for conversions to integer type the C standard requires
1494 round-to-zero to always be used. */
1496 APFloat::convertToInteger(integerPart *parts, unsigned int width,
1498 roundingMode rounding_mode) const
1500 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1501 "Compile-time arithmetic on PPC long double not supported yet");
1502 lostFraction lost_fraction;
1503 unsigned int msb, partsCount;
1506 partsCount = partCountForBits(width);
1508 /* Handle the three special cases first. We produce
1509 a deterministic result even for the Invalid cases. */
1510 if (category == fcNaN) {
1511 // Neither sign nor isSigned affects this.
1512 APInt::tcSet(parts, 0, partsCount);
1515 if (category == fcInfinity) {
1516 if (!sign && isSigned)
1517 APInt::tcSetLeastSignificantBits(parts, partsCount, width-1);
1518 else if (!sign && !isSigned)
1519 APInt::tcSetLeastSignificantBits(parts, partsCount, width);
1520 else if (sign && isSigned) {
1521 APInt::tcSetLeastSignificantBits(parts, partsCount, 1);
1522 APInt::tcShiftLeft(parts, partsCount, width-1);
1523 } else // sign && !isSigned
1524 APInt::tcSet(parts, 0, partsCount);
1527 if (category == fcZero) {
1528 APInt::tcSet(parts, 0, partsCount);
1532 /* Shift the bit pattern so the fraction is lost. */
1535 bits = (int) semantics->precision - 1 - exponent;
1538 lost_fraction = tmp.shiftSignificandRight(bits);
1540 if (-bits >= semantics->precision) {
1541 // Unrepresentably large.
1542 if (!sign && isSigned)
1543 APInt::tcSetLeastSignificantBits(parts, partsCount, width-1);
1544 else if (!sign && !isSigned)
1545 APInt::tcSetLeastSignificantBits(parts, partsCount, width);
1546 else if (sign && isSigned) {
1547 APInt::tcSetLeastSignificantBits(parts, partsCount, 1);
1548 APInt::tcShiftLeft(parts, partsCount, width-1);
1549 } else // sign && !isSigned
1550 APInt::tcSet(parts, 0, partsCount);
1551 return (opStatus)(opOverflow | opInexact);
1553 tmp.shiftSignificandLeft(-bits);
1554 lost_fraction = lfExactlyZero;
1557 if(lost_fraction != lfExactlyZero
1558 && tmp.roundAwayFromZero(rounding_mode, lost_fraction, 0))
1559 tmp.incrementSignificand();
1561 msb = tmp.significandMSB();
1563 /* Negative numbers cannot be represented as unsigned. */
1564 if(!isSigned && tmp.sign && msb != -1U)
1567 /* It takes exponent + 1 bits to represent the truncated floating
1568 point number without its sign. We lose a bit for the sign, but
1569 the maximally negative integer is a special case. */
1570 if(msb + 1 > width) /* !! Not same as msb >= width !! */
1573 if(isSigned && msb + 1 == width
1574 && (!tmp.sign || tmp.significandLSB() != msb))
1577 APInt::tcAssign(parts, tmp.significandParts(), partsCount);
1580 APInt::tcNegate(parts, partsCount);
1582 if(lost_fraction == lfExactlyZero)
1588 /* Convert an unsigned integer SRC to a floating point number,
1589 rounding according to ROUNDING_MODE. The sign of the floating
1590 point number is not modified. */
1592 APFloat::convertFromUnsignedParts(const integerPart *src,
1593 unsigned int srcCount,
1594 roundingMode rounding_mode)
1596 unsigned int omsb, precision, dstCount;
1598 lostFraction lost_fraction;
1600 category = fcNormal;
1601 omsb = APInt::tcMSB(src, srcCount) + 1;
1602 dst = significandParts();
1603 dstCount = partCount();
1604 precision = semantics->precision;
1606 /* We want the most significant PRECISON bits of SRC. There may not
1607 be that many; extract what we can. */
1608 if (precision <= omsb) {
1609 exponent = omsb - 1;
1610 lost_fraction = lostFractionThroughTruncation(src, srcCount,
1612 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
1614 exponent = precision - 1;
1615 lost_fraction = lfExactlyZero;
1616 APInt::tcExtract(dst, dstCount, src, omsb, 0);
1619 return normalize(rounding_mode, lost_fraction);
1622 /* Convert a two's complement integer SRC to a floating point number,
1623 rounding according to ROUNDING_MODE. ISSIGNED is true if the
1624 integer is signed, in which case it must be sign-extended. */
1626 APFloat::convertFromSignExtendedInteger(const integerPart *src,
1627 unsigned int srcCount,
1629 roundingMode rounding_mode)
1631 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1632 "Compile-time arithmetic on PPC long double not supported yet");
1636 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
1639 /* If we're signed and negative negate a copy. */
1641 copy = new integerPart[srcCount];
1642 APInt::tcAssign(copy, src, srcCount);
1643 APInt::tcNegate(copy, srcCount);
1644 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
1648 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
1654 /* FIXME: should this just take a const APInt reference? */
1656 APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
1657 unsigned int width, bool isSigned,
1658 roundingMode rounding_mode)
1660 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1661 "Compile-time arithmetic on PPC long double not supported yet");
1662 unsigned int partCount = partCountForBits(width);
1663 APInt api = APInt(width, partCount, parts);
1666 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
1671 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
1675 APFloat::convertFromHexadecimalString(const char *p,
1676 roundingMode rounding_mode)
1678 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1679 "Compile-time arithmetic on PPC long double not supported yet");
1680 lostFraction lost_fraction;
1681 integerPart *significand;
1682 unsigned int bitPos, partsCount;
1683 const char *dot, *firstSignificantDigit;
1687 category = fcNormal;
1689 significand = significandParts();
1690 partsCount = partCount();
1691 bitPos = partsCount * integerPartWidth;
1693 /* Skip leading zeroes and any (hexa)decimal point. */
1694 p = skipLeadingZeroesAndAnyDot(p, &dot);
1695 firstSignificantDigit = p;
1698 integerPart hex_value;
1705 hex_value = hexDigitValue(*p);
1706 if(hex_value == -1U) {
1707 lost_fraction = lfExactlyZero;
1713 /* Store the number whilst 4-bit nibbles remain. */
1716 hex_value <<= bitPos % integerPartWidth;
1717 significand[bitPos / integerPartWidth] |= hex_value;
1719 lost_fraction = trailingHexadecimalFraction(p, hex_value);
1720 while(hexDigitValue(*p) != -1U)
1726 /* Hex floats require an exponent but not a hexadecimal point. */
1727 assert(*p == 'p' || *p == 'P');
1729 /* Ignore the exponent if we are zero. */
1730 if(p != firstSignificantDigit) {
1733 /* Implicit hexadecimal point? */
1737 /* Calculate the exponent adjustment implicit in the number of
1738 significant digits. */
1739 expAdjustment = dot - firstSignificantDigit;
1740 if(expAdjustment < 0)
1742 expAdjustment = expAdjustment * 4 - 1;
1744 /* Adjust for writing the significand starting at the most
1745 significant nibble. */
1746 expAdjustment += semantics->precision;
1747 expAdjustment -= partsCount * integerPartWidth;
1749 /* Adjust for the given exponent. */
1750 exponent = totalExponent(p, expAdjustment);
1753 return normalize(rounding_mode, lost_fraction);
1757 APFloat::convertFromString(const char *p, roundingMode rounding_mode)
1759 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1760 "Compile-time arithmetic on PPC long double not supported yet");
1761 /* Handle a leading minus sign. */
1767 if(p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
1768 return convertFromHexadecimalString(p + 2, rounding_mode);
1770 assert(0 && "Decimal to binary conversions not yet implemented");
1774 /* Write out a hexadecimal representation of the floating point value
1775 to DST, which must be of sufficient size, in the C99 form
1776 [-]0xh.hhhhp[+-]d. Return the number of characters written,
1777 excluding the terminating NUL.
1779 If UPPERCASE, the output is in upper case, otherwise in lower case.
1781 HEXDIGITS digits appear altogether, rounding the value if
1782 necessary. If HEXDIGITS is 0, the minimal precision to display the
1783 number precisely is used instead. If nothing would appear after
1784 the decimal point it is suppressed.
1786 The decimal exponent is always printed and has at least one digit.
1787 Zero values display an exponent of zero. Infinities and NaNs
1788 appear as "infinity" or "nan" respectively.
1790 The above rules are as specified by C99. There is ambiguity about
1791 what the leading hexadecimal digit should be. This implementation
1792 uses whatever is necessary so that the exponent is displayed as
1793 stored. This implies the exponent will fall within the IEEE format
1794 range, and the leading hexadecimal digit will be 0 (for denormals),
1795 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
1796 any other digits zero).
1799 APFloat::convertToHexString(char *dst, unsigned int hexDigits,
1800 bool upperCase, roundingMode rounding_mode) const
1802 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1803 "Compile-time arithmetic on PPC long double not supported yet");
1812 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
1813 dst += sizeof infinityL - 1;
1817 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
1818 dst += sizeof NaNU - 1;
1823 *dst++ = upperCase ? 'X': 'x';
1825 if (hexDigits > 1) {
1827 memset (dst, '0', hexDigits - 1);
1828 dst += hexDigits - 1;
1830 *dst++ = upperCase ? 'P': 'p';
1835 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
1844 /* Does the hard work of outputting the correctly rounded hexadecimal
1845 form of a normal floating point number with the specified number of
1846 hexadecimal digits. If HEXDIGITS is zero the minimum number of
1847 digits necessary to print the value precisely is output. */
1849 APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
1851 roundingMode rounding_mode) const
1853 unsigned int count, valueBits, shift, partsCount, outputDigits;
1854 const char *hexDigitChars;
1855 const integerPart *significand;
1860 *dst++ = upperCase ? 'X': 'x';
1863 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
1865 significand = significandParts();
1866 partsCount = partCount();
1868 /* +3 because the first digit only uses the single integer bit, so
1869 we have 3 virtual zero most-significant-bits. */
1870 valueBits = semantics->precision + 3;
1871 shift = integerPartWidth - valueBits % integerPartWidth;
1873 /* The natural number of digits required ignoring trailing
1874 insignificant zeroes. */
1875 outputDigits = (valueBits - significandLSB () + 3) / 4;
1877 /* hexDigits of zero means use the required number for the
1878 precision. Otherwise, see if we are truncating. If we are,
1879 find out if we need to round away from zero. */
1881 if (hexDigits < outputDigits) {
1882 /* We are dropping non-zero bits, so need to check how to round.
1883 "bits" is the number of dropped bits. */
1885 lostFraction fraction;
1887 bits = valueBits - hexDigits * 4;
1888 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
1889 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
1891 outputDigits = hexDigits;
1894 /* Write the digits consecutively, and start writing in the location
1895 of the hexadecimal point. We move the most significant digit
1896 left and add the hexadecimal point later. */
1899 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
1901 while (outputDigits && count) {
1904 /* Put the most significant integerPartWidth bits in "part". */
1905 if (--count == partsCount)
1906 part = 0; /* An imaginary higher zero part. */
1908 part = significand[count] << shift;
1911 part |= significand[count - 1] >> (integerPartWidth - shift);
1913 /* Convert as much of "part" to hexdigits as we can. */
1914 unsigned int curDigits = integerPartWidth / 4;
1916 if (curDigits > outputDigits)
1917 curDigits = outputDigits;
1918 dst += partAsHex (dst, part, curDigits, hexDigitChars);
1919 outputDigits -= curDigits;
1925 /* Note that hexDigitChars has a trailing '0'. */
1928 *q = hexDigitChars[hexDigitValue (*q) + 1];
1929 } while (*q == '0');
1932 /* Add trailing zeroes. */
1933 memset (dst, '0', outputDigits);
1934 dst += outputDigits;
1937 /* Move the most significant digit to before the point, and if there
1938 is something after the decimal point add it. This must come
1939 after rounding above. */
1946 /* Finally output the exponent. */
1947 *dst++ = upperCase ? 'P': 'p';
1949 return writeSignedDecimal (dst, exponent);
1952 // For good performance it is desirable for different APFloats
1953 // to produce different integers.
1955 APFloat::getHashValue() const
1957 if (category==fcZero) return sign<<8 | semantics->precision ;
1958 else if (category==fcInfinity) return sign<<9 | semantics->precision;
1959 else if (category==fcNaN) return 1<<10 | semantics->precision;
1961 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
1962 const integerPart* p = significandParts();
1963 for (int i=partCount(); i>0; i--, p++)
1964 hash ^= ((uint32_t)*p) ^ (*p)>>32;
1969 // Conversion from APFloat to/from host float/double. It may eventually be
1970 // possible to eliminate these and have everybody deal with APFloats, but that
1971 // will take a while. This approach will not easily extend to long double.
1972 // Current implementation requires integerPartWidth==64, which is correct at
1973 // the moment but could be made more general.
1975 // Denormals have exponent minExponent in APFloat, but minExponent-1 in
1976 // the actual IEEE respresentations. We compensate for that here.
1979 APFloat::convertF80LongDoubleAPFloatToAPInt() const
1981 assert(semantics == (const llvm::fltSemantics* const)&x87DoubleExtended);
1982 assert (partCount()==2);
1984 uint64_t myexponent, mysignificand;
1986 if (category==fcNormal) {
1987 myexponent = exponent+16383; //bias
1988 mysignificand = significandParts()[0];
1989 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
1990 myexponent = 0; // denormal
1991 } else if (category==fcZero) {
1994 } else if (category==fcInfinity) {
1995 myexponent = 0x7fff;
1996 mysignificand = 0x8000000000000000ULL;
1998 assert(category == fcNaN && "Unknown category");
1999 myexponent = 0x7fff;
2000 mysignificand = significandParts()[0];
2004 words[0] = (((uint64_t)sign & 1) << 63) |
2005 ((myexponent & 0x7fff) << 48) |
2006 ((mysignificand >>16) & 0xffffffffffffLL);
2007 words[1] = mysignificand & 0xffff;
2008 return APInt(80, 2, words);
2012 APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2014 assert(semantics == (const llvm::fltSemantics* const)&PPCDoubleDouble);
2015 assert (partCount()==2);
2017 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2019 if (category==fcNormal) {
2020 myexponent = exponent + 1023; //bias
2021 myexponent2 = exponent2 + 1023;
2022 mysignificand = significandParts()[0];
2023 mysignificand2 = significandParts()[1];
2024 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2025 myexponent = 0; // denormal
2026 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2027 myexponent2 = 0; // denormal
2028 } else if (category==fcZero) {
2033 } else if (category==fcInfinity) {
2039 assert(category == fcNaN && "Unknown category");
2041 mysignificand = significandParts()[0];
2042 myexponent2 = exponent2;
2043 mysignificand2 = significandParts()[1];
2047 words[0] = (((uint64_t)sign & 1) << 63) |
2048 ((myexponent & 0x7ff) << 52) |
2049 (mysignificand & 0xfffffffffffffLL);
2050 words[1] = (((uint64_t)sign2 & 1) << 63) |
2051 ((myexponent2 & 0x7ff) << 52) |
2052 (mysignificand2 & 0xfffffffffffffLL);
2053 return APInt(128, 2, words);
2057 APFloat::convertDoubleAPFloatToAPInt() const
2059 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
2060 assert (partCount()==1);
2062 uint64_t myexponent, mysignificand;
2064 if (category==fcNormal) {
2065 myexponent = exponent+1023; //bias
2066 mysignificand = *significandParts();
2067 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2068 myexponent = 0; // denormal
2069 } else if (category==fcZero) {
2072 } else if (category==fcInfinity) {
2076 assert(category == fcNaN && "Unknown category!");
2078 mysignificand = *significandParts();
2081 return APInt(64, (((((uint64_t)sign & 1) << 63) |
2082 ((myexponent & 0x7ff) << 52) |
2083 (mysignificand & 0xfffffffffffffLL))));
2087 APFloat::convertFloatAPFloatToAPInt() const
2089 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
2090 assert (partCount()==1);
2092 uint32_t myexponent, mysignificand;
2094 if (category==fcNormal) {
2095 myexponent = exponent+127; //bias
2096 mysignificand = *significandParts();
2097 if (myexponent == 1 && !(mysignificand & 0x400000))
2098 myexponent = 0; // denormal
2099 } else if (category==fcZero) {
2102 } else if (category==fcInfinity) {
2106 assert(category == fcNaN && "Unknown category!");
2108 mysignificand = *significandParts();
2111 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2112 (mysignificand & 0x7fffff)));
2115 // This function creates an APInt that is just a bit map of the floating
2116 // point constant as it would appear in memory. It is not a conversion,
2117 // and treating the result as a normal integer is unlikely to be useful.
2120 APFloat::convertToAPInt() const
2122 if (semantics == (const llvm::fltSemantics* const)&IEEEsingle)
2123 return convertFloatAPFloatToAPInt();
2125 if (semantics == (const llvm::fltSemantics* const)&IEEEdouble)
2126 return convertDoubleAPFloatToAPInt();
2128 if (semantics == (const llvm::fltSemantics* const)&PPCDoubleDouble)
2129 return convertPPCDoubleDoubleAPFloatToAPInt();
2131 assert(semantics == (const llvm::fltSemantics* const)&x87DoubleExtended &&
2133 return convertF80LongDoubleAPFloatToAPInt();
2137 APFloat::convertToFloat() const
2139 assert(semantics == (const llvm::fltSemantics* const)&IEEEsingle);
2140 APInt api = convertToAPInt();
2141 return api.bitsToFloat();
2145 APFloat::convertToDouble() const
2147 assert(semantics == (const llvm::fltSemantics* const)&IEEEdouble);
2148 APInt api = convertToAPInt();
2149 return api.bitsToDouble();
2152 /// Integer bit is explicit in this format. Current Intel book does not
2153 /// define meaning of:
2154 /// exponent = all 1's, integer bit not set.
2155 /// exponent = 0, integer bit set. (formerly "psuedodenormals")
2156 /// exponent!=0 nor all 1's, integer bit not set. (formerly "unnormals")
2158 APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2160 assert(api.getBitWidth()==80);
2161 uint64_t i1 = api.getRawData()[0];
2162 uint64_t i2 = api.getRawData()[1];
2163 uint64_t myexponent = (i1 >> 48) & 0x7fff;
2164 uint64_t mysignificand = ((i1 << 16) & 0xffffffffffff0000ULL) |
2167 initialize(&APFloat::x87DoubleExtended);
2168 assert(partCount()==2);
2171 if (myexponent==0 && mysignificand==0) {
2172 // exponent, significand meaningless
2174 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2175 // exponent, significand meaningless
2176 category = fcInfinity;
2177 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2178 // exponent meaningless
2180 significandParts()[0] = mysignificand;
2181 significandParts()[1] = 0;
2183 category = fcNormal;
2184 exponent = myexponent - 16383;
2185 significandParts()[0] = mysignificand;
2186 significandParts()[1] = 0;
2187 if (myexponent==0) // denormal
2193 APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2195 assert(api.getBitWidth()==128);
2196 uint64_t i1 = api.getRawData()[0];
2197 uint64_t i2 = api.getRawData()[1];
2198 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2199 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2200 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2201 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2203 initialize(&APFloat::PPCDoubleDouble);
2204 assert(partCount()==2);
2208 if (myexponent==0 && mysignificand==0) {
2209 // exponent, significand meaningless
2210 // exponent2 and significand2 are required to be 0; we don't check
2212 } else if (myexponent==0x7ff && mysignificand==0) {
2213 // exponent, significand meaningless
2214 // exponent2 and significand2 are required to be 0; we don't check
2215 category = fcInfinity;
2216 } else if (myexponent==0x7ff && mysignificand!=0) {
2217 // exponent meaningless. So is the whole second word, but keep it
2220 exponent2 = myexponent2;
2221 significandParts()[0] = mysignificand;
2222 significandParts()[1] = mysignificand2;
2224 category = fcNormal;
2225 // Note there is no category2; the second word is treated as if it is
2226 // fcNormal, although it might be something else considered by itself.
2227 exponent = myexponent - 1023;
2228 exponent2 = myexponent2 - 1023;
2229 significandParts()[0] = mysignificand;
2230 significandParts()[1] = mysignificand2;
2231 if (myexponent==0) // denormal
2234 significandParts()[0] |= 0x10000000000000LL; // integer bit
2238 significandParts()[1] |= 0x10000000000000LL; // integer bit
2243 APFloat::initFromDoubleAPInt(const APInt &api)
2245 assert(api.getBitWidth()==64);
2246 uint64_t i = *api.getRawData();
2247 uint64_t myexponent = (i >> 52) & 0x7ff;
2248 uint64_t mysignificand = i & 0xfffffffffffffLL;
2250 initialize(&APFloat::IEEEdouble);
2251 assert(partCount()==1);
2254 if (myexponent==0 && mysignificand==0) {
2255 // exponent, significand meaningless
2257 } else if (myexponent==0x7ff && mysignificand==0) {
2258 // exponent, significand meaningless
2259 category = fcInfinity;
2260 } else if (myexponent==0x7ff && mysignificand!=0) {
2261 // exponent meaningless
2263 *significandParts() = mysignificand;
2265 category = fcNormal;
2266 exponent = myexponent - 1023;
2267 *significandParts() = mysignificand;
2268 if (myexponent==0) // denormal
2271 *significandParts() |= 0x10000000000000LL; // integer bit
2276 APFloat::initFromFloatAPInt(const APInt & api)
2278 assert(api.getBitWidth()==32);
2279 uint32_t i = (uint32_t)*api.getRawData();
2280 uint32_t myexponent = (i >> 23) & 0xff;
2281 uint32_t mysignificand = i & 0x7fffff;
2283 initialize(&APFloat::IEEEsingle);
2284 assert(partCount()==1);
2287 if (myexponent==0 && mysignificand==0) {
2288 // exponent, significand meaningless
2290 } else if (myexponent==0xff && mysignificand==0) {
2291 // exponent, significand meaningless
2292 category = fcInfinity;
2293 } else if (myexponent==0xff && mysignificand!=0) {
2294 // sign, exponent, significand meaningless
2296 *significandParts() = mysignificand;
2298 category = fcNormal;
2299 exponent = myexponent - 127; //bias
2300 *significandParts() = mysignificand;
2301 if (myexponent==0) // denormal
2304 *significandParts() |= 0x800000; // integer bit
2308 /// Treat api as containing the bits of a floating point number. Currently
2309 /// we infer the floating point type from the size of the APInt. The
2310 /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
2311 /// when the size is anything else).
2313 APFloat::initFromAPInt(const APInt& api, bool isIEEE)
2315 if (api.getBitWidth() == 32)
2316 return initFromFloatAPInt(api);
2317 else if (api.getBitWidth()==64)
2318 return initFromDoubleAPInt(api);
2319 else if (api.getBitWidth()==80)
2320 return initFromF80LongDoubleAPInt(api);
2321 else if (api.getBitWidth()==128 && !isIEEE)
2322 return initFromPPCDoubleDoubleAPInt(api);
2327 APFloat::APFloat(const APInt& api, bool isIEEE)
2329 initFromAPInt(api, isIEEE);
2332 APFloat::APFloat(float f)
2334 APInt api = APInt(32, 0);
2335 initFromAPInt(api.floatToBits(f));
2338 APFloat::APFloat(double d)
2340 APInt api = APInt(64, 0);
2341 initFromAPInt(api.doubleToBits(d));