LLVM API Documentation

APFloat.cpp

Go to the documentation of this file.
00001 //===-- APFloat.cpp - Implement APFloat class -----------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements a class to represent arbitrary precision floating
00011 // point values and provide a variety of arithmetic operations on them.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/ADT/APFloat.h"
00016 #include "llvm/ADT/StringRef.h"
00017 #include "llvm/ADT/FoldingSet.h"
00018 #include "llvm/Support/ErrorHandling.h"
00019 #include "llvm/Support/MathExtras.h"
00020 #include <cstring>
00021 
00022 using namespace llvm;
00023 
00024 #define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
00025 
00026 /* Assumed in hexadecimal significand parsing, and conversion to
00027    hexadecimal strings.  */
00028 #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
00029 COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
00030 
00031 namespace llvm {
00032 
00033   /* Represents floating point arithmetic semantics.  */
00034   struct fltSemantics {
00035     /* The largest E such that 2^E is representable; this matches the
00036        definition of IEEE 754.  */
00037     exponent_t maxExponent;
00038 
00039     /* The smallest E such that 2^E is a normalized number; this
00040        matches the definition of IEEE 754.  */
00041     exponent_t minExponent;
00042 
00043     /* Number of bits in the significand.  This includes the integer
00044        bit.  */
00045     unsigned int precision;
00046 
00047     /* True if arithmetic is supported.  */
00048     unsigned int arithmeticOK;
00049   };
00050 
00051   const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
00052   const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
00053   const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
00054   const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
00055   const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
00056 
00057   // The PowerPC format consists of two doubles.  It does not map cleanly
00058   // onto the usual format above.  For now only storage of constants of
00059   // this type is supported, no arithmetic.
00060   const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
00061 
00062   /* A tight upper bound on number of parts required to hold the value
00063      pow(5, power) is
00064 
00065        power * 815 / (351 * integerPartWidth) + 1
00066        
00067      However, whilst the result may require only this many parts,
00068      because we are multiplying two values to get it, the
00069      multiplication may require an extra part with the excess part
00070      being zero (consider the trivial case of 1 * 1, tcFullMultiply
00071      requires two parts to hold the single-part result).  So we add an
00072      extra one to guarantee enough space whilst multiplying.  */
00073   const unsigned int maxExponent = 16383;
00074   const unsigned int maxPrecision = 113;
00075   const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
00076   const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
00077                                                 / (351 * integerPartWidth));
00078 }
00079 
00080 /* A bunch of private, handy routines.  */
00081 
00082 static inline unsigned int
00083 partCountForBits(unsigned int bits)
00084 {
00085   return ((bits) + integerPartWidth - 1) / integerPartWidth;
00086 }
00087 
00088 /* Returns 0U-9U.  Return values >= 10U are not digits.  */
00089 static inline unsigned int
00090 decDigitValue(unsigned int c)
00091 {
00092   return c - '0';
00093 }
00094 
00095 static unsigned int
00096 hexDigitValue(unsigned int c)
00097 {
00098   unsigned int r;
00099 
00100   r = c - '0';
00101   if(r <= 9)
00102     return r;
00103 
00104   r = c - 'A';
00105   if(r <= 5)
00106     return r + 10;
00107 
00108   r = c - 'a';
00109   if(r <= 5)
00110     return r + 10;
00111 
00112   return -1U;
00113 }
00114 
00115 static inline void
00116 assertArithmeticOK(const llvm::fltSemantics &semantics) {
00117   assert(semantics.arithmeticOK
00118          && "Compile-time arithmetic does not support these semantics");
00119 }
00120 
00121 /* Return the value of a decimal exponent of the form
00122    [+-]ddddddd.
00123 
00124    If the exponent overflows, returns a large exponent with the
00125    appropriate sign.  */
00126 static int
00127 readExponent(StringRef::iterator begin, StringRef::iterator end)
00128 {
00129   bool isNegative;
00130   unsigned int absExponent;
00131   const unsigned int overlargeExponent = 24000;  /* FIXME.  */
00132   StringRef::iterator p = begin;
00133 
00134   assert(p != end && "Exponent has no digits");
00135 
00136   isNegative = (*p == '-');
00137   if (*p == '-' || *p == '+') {
00138     p++;
00139     assert(p != end && "Exponent has no digits");
00140   }
00141 
00142   absExponent = decDigitValue(*p++);
00143   assert(absExponent < 10U && "Invalid character in exponent");
00144 
00145   for (; p != end; ++p) {
00146     unsigned int value;
00147 
00148     value = decDigitValue(*p);
00149     assert(value < 10U && "Invalid character in exponent");
00150 
00151     value += absExponent * 10;
00152     if (absExponent >= overlargeExponent) {
00153       absExponent = overlargeExponent;
00154       break;
00155     }
00156     absExponent = value;
00157   }
00158 
00159   assert(p == end && "Invalid exponent in exponent");
00160 
00161   if (isNegative)
00162     return -(int) absExponent;
00163   else
00164     return (int) absExponent;
00165 }
00166 
00167 /* This is ugly and needs cleaning up, but I don't immediately see
00168    how whilst remaining safe.  */
00169 static int
00170 totalExponent(StringRef::iterator p, StringRef::iterator end,
00171               int exponentAdjustment)
00172 {
00173   int unsignedExponent;
00174   bool negative, overflow;
00175   int exponent;
00176 
00177   assert(p != end && "Exponent has no digits");
00178 
00179   negative = *p == '-';
00180   if(*p == '-' || *p == '+') {
00181     p++;
00182     assert(p != end && "Exponent has no digits");
00183   }
00184 
00185   unsignedExponent = 0;
00186   overflow = false;
00187   for(; p != end; ++p) {
00188     unsigned int value;
00189 
00190     value = decDigitValue(*p);
00191     assert(value < 10U && "Invalid character in exponent");
00192 
00193     unsignedExponent = unsignedExponent * 10 + value;
00194     if(unsignedExponent > 65535)
00195       overflow = true;
00196   }
00197 
00198   if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
00199     overflow = true;
00200 
00201   if(!overflow) {
00202     exponent = unsignedExponent;
00203     if(negative)
00204       exponent = -exponent;
00205     exponent += exponentAdjustment;
00206     if(exponent > 65535 || exponent < -65536)
00207       overflow = true;
00208   }
00209 
00210   if(overflow)
00211     exponent = negative ? -65536: 65535;
00212 
00213   return exponent;
00214 }
00215 
00216 static StringRef::iterator
00217 skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
00218                            StringRef::iterator *dot)
00219 {
00220   StringRef::iterator p = begin;
00221   *dot = end;
00222   while(*p == '0' && p != end)
00223     p++;
00224 
00225   if(*p == '.') {
00226     *dot = p++;
00227 
00228     assert(end - begin != 1 && "Significand has no digits");
00229 
00230     while(*p == '0' && p != end)
00231       p++;
00232   }
00233 
00234   return p;
00235 }
00236 
00237 /* Given a normal decimal floating point number of the form
00238 
00239      dddd.dddd[eE][+-]ddd
00240 
00241    where the decimal point and exponent are optional, fill out the
00242    structure D.  Exponent is appropriate if the significand is
00243    treated as an integer, and normalizedExponent if the significand
00244    is taken to have the decimal point after a single leading
00245    non-zero digit.
00246 
00247    If the value is zero, V->firstSigDigit points to a non-digit, and
00248    the return exponent is zero.
00249 */
00250 struct decimalInfo {
00251   const char *firstSigDigit;
00252   const char *lastSigDigit;
00253   int exponent;
00254   int normalizedExponent;
00255 };
00256 
00257 static void
00258 interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
00259                  decimalInfo *D)
00260 {
00261   StringRef::iterator dot = end;
00262   StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
00263 
00264   D->firstSigDigit = p;
00265   D->exponent = 0;
00266   D->normalizedExponent = 0;
00267 
00268   for (; p != end; ++p) {
00269     if (*p == '.') {
00270       assert(dot == end && "String contains multiple dots");
00271       dot = p++;
00272       if (p == end)
00273         break;
00274     }
00275     if (decDigitValue(*p) >= 10U)
00276       break;
00277   }
00278 
00279   if (p != end) {
00280     assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
00281     assert(p != begin && "Significand has no digits");
00282     assert((dot == end || p - begin != 1) && "Significand has no digits");
00283 
00284     /* p points to the first non-digit in the string */
00285     D->exponent = readExponent(p + 1, end);
00286 
00287     /* Implied decimal point?  */
00288     if (dot == end)
00289       dot = p;
00290   }
00291 
00292   /* If number is all zeroes accept any exponent.  */
00293   if (p != D->firstSigDigit) {
00294     /* Drop insignificant trailing zeroes.  */
00295     if (p != begin) {
00296       do
00297         do
00298           p--;
00299         while (p != begin && *p == '0');
00300       while (p != begin && *p == '.');
00301     }
00302 
00303     /* Adjust the exponents for any decimal point.  */
00304     D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
00305     D->normalizedExponent = (D->exponent +
00306               static_cast<exponent_t>((p - D->firstSigDigit)
00307                                       - (dot > D->firstSigDigit && dot < p)));
00308   }
00309 
00310   D->lastSigDigit = p;
00311 }
00312 
00313 /* Return the trailing fraction of a hexadecimal number.
00314    DIGITVALUE is the first hex digit of the fraction, P points to
00315    the next digit.  */
00316 static lostFraction
00317 trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
00318                             unsigned int digitValue)
00319 {
00320   unsigned int hexDigit;
00321 
00322   /* If the first trailing digit isn't 0 or 8 we can work out the
00323      fraction immediately.  */
00324   if(digitValue > 8)
00325     return lfMoreThanHalf;
00326   else if(digitValue < 8 && digitValue > 0)
00327     return lfLessThanHalf;
00328 
00329   /* Otherwise we need to find the first non-zero digit.  */
00330   while(*p == '0')
00331     p++;
00332 
00333   assert(p != end && "Invalid trailing hexadecimal fraction!");
00334 
00335   hexDigit = hexDigitValue(*p);
00336 
00337   /* If we ran off the end it is exactly zero or one-half, otherwise
00338      a little more.  */
00339   if(hexDigit == -1U)
00340     return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
00341   else
00342     return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
00343 }
00344 
00345 /* Return the fraction lost were a bignum truncated losing the least
00346    significant BITS bits.  */
00347 static lostFraction
00348 lostFractionThroughTruncation(const integerPart *parts,
00349                               unsigned int partCount,
00350                               unsigned int bits)
00351 {
00352   unsigned int lsb;
00353 
00354   lsb = APInt::tcLSB(parts, partCount);
00355 
00356   /* Note this is guaranteed true if bits == 0, or LSB == -1U.  */
00357   if(bits <= lsb)
00358     return lfExactlyZero;
00359   if(bits == lsb + 1)
00360     return lfExactlyHalf;
00361   if(bits <= partCount * integerPartWidth
00362      && APInt::tcExtractBit(parts, bits - 1))
00363     return lfMoreThanHalf;
00364 
00365   return lfLessThanHalf;
00366 }
00367 
00368 /* Shift DST right BITS bits noting lost fraction.  */
00369 static lostFraction
00370 shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
00371 {
00372   lostFraction lost_fraction;
00373 
00374   lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
00375 
00376   APInt::tcShiftRight(dst, parts, bits);
00377 
00378   return lost_fraction;
00379 }
00380 
00381 /* Combine the effect of two lost fractions.  */
00382 static lostFraction
00383 combineLostFractions(lostFraction moreSignificant,
00384                      lostFraction lessSignificant)
00385 {
00386   if(lessSignificant != lfExactlyZero) {
00387     if(moreSignificant == lfExactlyZero)
00388       moreSignificant = lfLessThanHalf;
00389     else if(moreSignificant == lfExactlyHalf)
00390       moreSignificant = lfMoreThanHalf;
00391   }
00392 
00393   return moreSignificant;
00394 }
00395 
00396 /* The error from the true value, in half-ulps, on multiplying two
00397    floating point numbers, which differ from the value they
00398    approximate by at most HUE1 and HUE2 half-ulps, is strictly less
00399    than the returned value.
00400 
00401    See "How to Read Floating Point Numbers Accurately" by William D
00402    Clinger.  */
00403 static unsigned int
00404 HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
00405 {
00406   assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
00407 
00408   if (HUerr1 + HUerr2 == 0)
00409     return inexactMultiply * 2;  /* <= inexactMultiply half-ulps.  */
00410   else
00411     return inexactMultiply + 2 * (HUerr1 + HUerr2);
00412 }
00413 
00414 /* The number of ulps from the boundary (zero, or half if ISNEAREST)
00415    when the least significant BITS are truncated.  BITS cannot be
00416    zero.  */
00417 static integerPart
00418 ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
00419 {
00420   unsigned int count, partBits;
00421   integerPart part, boundary;
00422 
00423   assert (bits != 0);
00424 
00425   bits--;
00426   count = bits / integerPartWidth;
00427   partBits = bits % integerPartWidth + 1;
00428 
00429   part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
00430 
00431   if (isNearest)
00432     boundary = (integerPart) 1 << (partBits - 1);
00433   else
00434     boundary = 0;
00435 
00436   if (count == 0) {
00437     if (part - boundary <= boundary - part)
00438       return part - boundary;
00439     else
00440       return boundary - part;
00441   }
00442 
00443   if (part == boundary) {
00444     while (--count)
00445       if (parts[count])
00446         return ~(integerPart) 0; /* A lot.  */
00447 
00448     return parts[0];
00449   } else if (part == boundary - 1) {
00450     while (--count)
00451       if (~parts[count])
00452         return ~(integerPart) 0; /* A lot.  */
00453 
00454     return -parts[0];
00455   }
00456 
00457   return ~(integerPart) 0; /* A lot.  */
00458 }
00459 
00460 /* Place pow(5, power) in DST, and return the number of parts used.
00461    DST must be at least one part larger than size of the answer.  */
00462 static unsigned int
00463 powerOf5(integerPart *dst, unsigned int power)
00464 {
00465   static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
00466                                                   15625, 78125 };
00467   integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
00468   pow5s[0] = 78125 * 5;
00469   
00470   unsigned int partsCount[16] = { 1 };
00471   integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
00472   unsigned int result;
00473   assert(power <= maxExponent);
00474 
00475   p1 = dst;
00476   p2 = scratch;
00477 
00478   *p1 = firstEightPowers[power & 7];
00479   power >>= 3;
00480 
00481   result = 1;
00482   pow5 = pow5s;
00483 
00484   for (unsigned int n = 0; power; power >>= 1, n++) {
00485     unsigned int pc;
00486 
00487     pc = partsCount[n];
00488 
00489     /* Calculate pow(5,pow(2,n+3)) if we haven't yet.  */
00490     if (pc == 0) {
00491       pc = partsCount[n - 1];
00492       APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
00493       pc *= 2;
00494       if (pow5[pc - 1] == 0)
00495         pc--;
00496       partsCount[n] = pc;
00497     }
00498 
00499     if (power & 1) {
00500       integerPart *tmp;
00501 
00502       APInt::tcFullMultiply(p2, p1, pow5, result, pc);
00503       result += pc;
00504       if (p2[result - 1] == 0)
00505         result--;
00506 
00507       /* Now result is in p1 with partsCount parts and p2 is scratch
00508          space.  */
00509       tmp = p1, p1 = p2, p2 = tmp;
00510     }
00511 
00512     pow5 += pc;
00513   }
00514 
00515   if (p1 != dst)
00516     APInt::tcAssign(dst, p1, result);
00517 
00518   return result;
00519 }
00520 
00521 /* Zero at the end to avoid modular arithmetic when adding one; used
00522    when rounding up during hexadecimal output.  */
00523 static const char hexDigitsLower[] = "0123456789abcdef0";
00524 static const char hexDigitsUpper[] = "0123456789ABCDEF0";
00525 static const char infinityL[] = "infinity";
00526 static const char infinityU[] = "INFINITY";
00527 static const char NaNL[] = "nan";
00528 static const char NaNU[] = "NAN";
00529 
00530 /* Write out an integerPart in hexadecimal, starting with the most
00531    significant nibble.  Write out exactly COUNT hexdigits, return
00532    COUNT.  */
00533 static unsigned int
00534 partAsHex (char *dst, integerPart part, unsigned int count,
00535            const char *hexDigitChars)
00536 {
00537   unsigned int result = count;
00538 
00539   assert (count != 0 && count <= integerPartWidth / 4);
00540 
00541   part >>= (integerPartWidth - 4 * count);
00542   while (count--) {
00543     dst[count] = hexDigitChars[part & 0xf];
00544     part >>= 4;
00545   }
00546 
00547   return result;
00548 }
00549 
00550 /* Write out an unsigned decimal integer.  */
00551 static char *
00552 writeUnsignedDecimal (char *dst, unsigned int n)
00553 {
00554   char buff[40], *p;
00555 
00556   p = buff;
00557   do
00558     *p++ = '0' + n % 10;
00559   while (n /= 10);
00560 
00561   do
00562     *dst++ = *--p;
00563   while (p != buff);
00564 
00565   return dst;
00566 }
00567 
00568 /* Write out a signed decimal integer.  */
00569 static char *
00570 writeSignedDecimal (char *dst, int value)
00571 {
00572   if (value < 0) {
00573     *dst++ = '-';
00574     dst = writeUnsignedDecimal(dst, -(unsigned) value);
00575   } else
00576     dst = writeUnsignedDecimal(dst, value);
00577 
00578   return dst;
00579 }
00580 
00581 /* Constructors.  */
00582 void
00583 APFloat::initialize(const fltSemantics *ourSemantics)
00584 {
00585   unsigned int count;
00586 
00587   semantics = ourSemantics;
00588   count = partCount();
00589   if(count > 1)
00590     significand.parts = new integerPart[count];
00591 }
00592 
00593 void
00594 APFloat::freeSignificand()
00595 {
00596   if(partCount() > 1)
00597     delete [] significand.parts;
00598 }
00599 
00600 void
00601 APFloat::assign(const APFloat &rhs)
00602 {
00603   assert(semantics == rhs.semantics);
00604 
00605   sign = rhs.sign;
00606   category = rhs.category;
00607   exponent = rhs.exponent;
00608   sign2 = rhs.sign2;
00609   exponent2 = rhs.exponent2;
00610   if(category == fcNormal || category == fcNaN)
00611     copySignificand(rhs);
00612 }
00613 
00614 void
00615 APFloat::copySignificand(const APFloat &rhs)
00616 {
00617   assert(category == fcNormal || category == fcNaN);
00618   assert(rhs.partCount() >= partCount());
00619 
00620   APInt::tcAssign(significandParts(), rhs.significandParts(),
00621                   partCount());
00622 }
00623 
00624 /* Make this number a NaN, with an arbitrary but deterministic value
00625    for the significand.  If double or longer, this is a signalling NaN,
00626    which may not be ideal.  If float, this is QNaN(0).  */
00627 void
00628 APFloat::makeNaN(unsigned type)
00629 {
00630   category = fcNaN;
00631   // FIXME: Add double and long double support for QNaN(0).
00632   if (semantics->precision == 24 && semantics->maxExponent == 127) {
00633     type |=  0x7fc00000U;
00634     type &= ~0x80000000U;
00635   } else
00636     type = ~0U;
00637   APInt::tcSet(significandParts(), type, partCount());
00638 }
00639 
00640 APFloat &
00641 APFloat::operator=(const APFloat &rhs)
00642 {
00643   if(this != &rhs) {
00644     if(semantics != rhs.semantics) {
00645       freeSignificand();
00646       initialize(rhs.semantics);
00647     }
00648     assign(rhs);
00649   }
00650 
00651   return *this;
00652 }
00653 
00654 bool
00655 APFloat::bitwiseIsEqual(const APFloat &rhs) const {
00656   if (this == &rhs)
00657     return true;
00658   if (semantics != rhs.semantics ||
00659       category != rhs.category ||
00660       sign != rhs.sign)
00661     return false;
00662   if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
00663       sign2 != rhs.sign2)
00664     return false;
00665   if (category==fcZero || category==fcInfinity)
00666     return true;
00667   else if (category==fcNormal && exponent!=rhs.exponent)
00668     return false;
00669   else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
00670            exponent2!=rhs.exponent2)
00671     return false;
00672   else {
00673     int i= partCount();
00674     const integerPart* p=significandParts();
00675     const integerPart* q=rhs.significandParts();
00676     for (; i>0; i--, p++, q++) {
00677       if (*p != *q)
00678         return false;
00679     }
00680     return true;
00681   }
00682 }
00683 
00684 APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
00685 {
00686   assertArithmeticOK(ourSemantics);
00687   initialize(&ourSemantics);
00688   sign = 0;
00689   zeroSignificand();
00690   exponent = ourSemantics.precision - 1;
00691   significandParts()[0] = value;
00692   normalize(rmNearestTiesToEven, lfExactlyZero);
00693 }
00694 
00695 APFloat::APFloat(const fltSemantics &ourSemantics,
00696                  fltCategory ourCategory, bool negative, unsigned type)
00697 {
00698   assertArithmeticOK(ourSemantics);
00699   initialize(&ourSemantics);
00700   category = ourCategory;
00701   sign = negative;
00702   if (category == fcNormal)
00703     category = fcZero;
00704   else if (ourCategory == fcNaN)
00705     makeNaN(type);
00706 }
00707 
00708 APFloat::APFloat(const fltSemantics &ourSemantics, const StringRef& text)
00709 {
00710   assertArithmeticOK(ourSemantics);
00711   initialize(&ourSemantics);
00712   convertFromString(text, rmNearestTiesToEven);
00713 }
00714 
00715 APFloat::APFloat(const APFloat &rhs)
00716 {
00717   initialize(rhs.semantics);
00718   assign(rhs);
00719 }
00720 
00721 APFloat::~APFloat()
00722 {
00723   freeSignificand();
00724 }
00725 
00726 // Profile - This method 'profiles' an APFloat for use with FoldingSet.
00727 void APFloat::Profile(FoldingSetNodeID& ID) const {
00728   ID.Add(bitcastToAPInt());
00729 }
00730 
00731 unsigned int
00732 APFloat::partCount() const
00733 {
00734   return partCountForBits(semantics->precision + 1);
00735 }
00736 
00737 unsigned int
00738 APFloat::semanticsPrecision(const fltSemantics &semantics)
00739 {
00740   return semantics.precision;
00741 }
00742 
00743 const integerPart *
00744 APFloat::significandParts() const
00745 {
00746   return const_cast<APFloat *>(this)->significandParts();
00747 }
00748 
00749 integerPart *
00750 APFloat::significandParts()
00751 {
00752   assert(category == fcNormal || category == fcNaN);
00753 
00754   if(partCount() > 1)
00755     return significand.parts;
00756   else
00757     return &significand.part;
00758 }
00759 
00760 void
00761 APFloat::zeroSignificand()
00762 {
00763   category = fcNormal;
00764   APInt::tcSet(significandParts(), 0, partCount());
00765 }
00766 
00767 /* Increment an fcNormal floating point number's significand.  */
00768 void
00769 APFloat::incrementSignificand()
00770 {
00771   integerPart carry;
00772 
00773   carry = APInt::tcIncrement(significandParts(), partCount());
00774 
00775   /* Our callers should never cause us to overflow.  */
00776   assert(carry == 0);
00777 }
00778 
00779 /* Add the significand of the RHS.  Returns the carry flag.  */
00780 integerPart
00781 APFloat::addSignificand(const APFloat &rhs)
00782 {
00783   integerPart *parts;
00784 
00785   parts = significandParts();
00786 
00787   assert(semantics == rhs.semantics);
00788   assert(exponent == rhs.exponent);
00789 
00790   return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
00791 }
00792 
00793 /* Subtract the significand of the RHS with a borrow flag.  Returns
00794    the borrow flag.  */
00795 integerPart
00796 APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
00797 {
00798   integerPart *parts;
00799 
00800   parts = significandParts();
00801 
00802   assert(semantics == rhs.semantics);
00803   assert(exponent == rhs.exponent);
00804 
00805   return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
00806                            partCount());
00807 }
00808 
00809 /* Multiply the significand of the RHS.  If ADDEND is non-NULL, add it
00810    on to the full-precision result of the multiplication.  Returns the
00811    lost fraction.  */
00812 lostFraction
00813 APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
00814 {
00815   unsigned int omsb;        // One, not zero, based MSB.
00816   unsigned int partsCount, newPartsCount, precision;
00817   integerPart *lhsSignificand;
00818   integerPart scratch[4];
00819   integerPart *fullSignificand;
00820   lostFraction lost_fraction;
00821   bool ignored;
00822 
00823   assert(semantics == rhs.semantics);
00824 
00825   precision = semantics->precision;
00826   newPartsCount = partCountForBits(precision * 2);
00827 
00828   if(newPartsCount > 4)
00829     fullSignificand = new integerPart[newPartsCount];
00830   else
00831     fullSignificand = scratch;
00832 
00833   lhsSignificand = significandParts();
00834   partsCount = partCount();
00835 
00836   APInt::tcFullMultiply(fullSignificand, lhsSignificand,
00837                         rhs.significandParts(), partsCount, partsCount);
00838 
00839   lost_fraction = lfExactlyZero;
00840   omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
00841   exponent += rhs.exponent;
00842 
00843   if(addend) {
00844     Significand savedSignificand = significand;
00845     const fltSemantics *savedSemantics = semantics;
00846     fltSemantics extendedSemantics;
00847     opStatus status;
00848     unsigned int extendedPrecision;
00849 
00850     /* Normalize our MSB.  */
00851     extendedPrecision = precision + precision - 1;
00852     if(omsb != extendedPrecision)
00853       {
00854         APInt::tcShiftLeft(fullSignificand, newPartsCount,
00855                            extendedPrecision - omsb);
00856         exponent -= extendedPrecision - omsb;
00857       }
00858 
00859     /* Create new semantics.  */
00860     extendedSemantics = *semantics;
00861     extendedSemantics.precision = extendedPrecision;
00862 
00863     if(newPartsCount == 1)
00864       significand.part = fullSignificand[0];
00865     else
00866       significand.parts = fullSignificand;
00867     semantics = &extendedSemantics;
00868 
00869     APFloat extendedAddend(*addend);
00870     status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
00871     assert(status == opOK);
00872     lost_fraction = addOrSubtractSignificand(extendedAddend, false);
00873 
00874     /* Restore our state.  */
00875     if(newPartsCount == 1)
00876       fullSignificand[0] = significand.part;
00877     significand = savedSignificand;
00878     semantics = savedSemantics;
00879 
00880     omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
00881   }
00882 
00883   exponent -= (precision - 1);
00884 
00885   if(omsb > precision) {
00886     unsigned int bits, significantParts;
00887     lostFraction lf;
00888 
00889     bits = omsb - precision;
00890     significantParts = partCountForBits(omsb);
00891     lf = shiftRight(fullSignificand, significantParts, bits);
00892     lost_fraction = combineLostFractions(lf, lost_fraction);
00893     exponent += bits;
00894   }
00895 
00896   APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
00897 
00898   if(newPartsCount > 4)
00899     delete [] fullSignificand;
00900 
00901   return lost_fraction;
00902 }
00903 
00904 /* Multiply the significands of LHS and RHS to DST.  */
00905 lostFraction
00906 APFloat::divideSignificand(const APFloat &rhs)
00907 {
00908   unsigned int bit, i, partsCount;
00909   const integerPart *rhsSignificand;
00910   integerPart *lhsSignificand, *dividend, *divisor;
00911   integerPart scratch[4];
00912   lostFraction lost_fraction;
00913 
00914   assert(semantics == rhs.semantics);
00915 
00916   lhsSignificand = significandParts();
00917   rhsSignificand = rhs.significandParts();
00918   partsCount = partCount();
00919 
00920   if(partsCount > 2)
00921     dividend = new integerPart[partsCount * 2];
00922   else
00923     dividend = scratch;
00924 
00925   divisor = dividend + partsCount;
00926 
00927   /* Copy the dividend and divisor as they will be modified in-place.  */
00928   for(i = 0; i < partsCount; i++) {
00929     dividend[i] = lhsSignificand[i];
00930     divisor[i] = rhsSignificand[i];
00931     lhsSignificand[i] = 0;
00932   }
00933 
00934   exponent -= rhs.exponent;
00935 
00936   unsigned int precision = semantics->precision;
00937 
00938   /* Normalize the divisor.  */
00939   bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
00940   if(bit) {
00941     exponent += bit;
00942     APInt::tcShiftLeft(divisor, partsCount, bit);
00943   }
00944 
00945   /* Normalize the dividend.  */
00946   bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
00947   if(bit) {
00948     exponent -= bit;
00949     APInt::tcShiftLeft(dividend, partsCount, bit);
00950   }
00951 
00952   /* Ensure the dividend >= divisor initially for the loop below.
00953      Incidentally, this means that the division loop below is
00954      guaranteed to set the integer bit to one.  */
00955   if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
00956     exponent--;
00957     APInt::tcShiftLeft(dividend, partsCount, 1);
00958     assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
00959   }
00960 
00961   /* Long division.  */
00962   for(bit = precision; bit; bit -= 1) {
00963     if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
00964       APInt::tcSubtract(dividend, divisor, 0, partsCount);
00965       APInt::tcSetBit(lhsSignificand, bit - 1);
00966     }
00967 
00968     APInt::tcShiftLeft(dividend, partsCount, 1);
00969   }
00970 
00971   /* Figure out the lost fraction.  */
00972   int cmp = APInt::tcCompare(dividend, divisor, partsCount);
00973 
00974   if(cmp > 0)
00975     lost_fraction = lfMoreThanHalf;
00976   else if(cmp == 0)
00977     lost_fraction = lfExactlyHalf;
00978   else if(APInt::tcIsZero(dividend, partsCount))
00979     lost_fraction = lfExactlyZero;
00980   else
00981     lost_fraction = lfLessThanHalf;
00982 
00983   if(partsCount > 2)
00984     delete [] dividend;
00985 
00986   return lost_fraction;
00987 }
00988 
00989 unsigned int
00990 APFloat::significandMSB() const
00991 {
00992   return APInt::tcMSB(significandParts(), partCount());
00993 }
00994 
00995 unsigned int
00996 APFloat::significandLSB() const
00997 {
00998   return APInt::tcLSB(significandParts(), partCount());
00999 }
01000 
01001 /* Note that a zero result is NOT normalized to fcZero.  */
01002 lostFraction
01003 APFloat::shiftSignificandRight(unsigned int bits)
01004 {
01005   /* Our exponent should not overflow.  */
01006   assert((exponent_t) (exponent + bits) >= exponent);
01007 
01008   exponent += bits;
01009 
01010   return shiftRight(significandParts(), partCount(), bits);
01011 }
01012 
01013 /* Shift the significand left BITS bits, subtract BITS from its exponent.  */
01014 void
01015 APFloat::shiftSignificandLeft(unsigned int bits)
01016 {
01017   assert(bits < semantics->precision);
01018 
01019   if(bits) {
01020     unsigned int partsCount = partCount();
01021 
01022     APInt::tcShiftLeft(significandParts(), partsCount, bits);
01023     exponent -= bits;
01024 
01025     assert(!APInt::tcIsZero(significandParts(), partsCount));
01026   }
01027 }
01028 
01029 APFloat::cmpResult
01030 APFloat::compareAbsoluteValue(const APFloat &rhs) const
01031 {
01032   int compare;
01033 
01034   assert(semantics == rhs.semantics);
01035   assert(category == fcNormal);
01036   assert(rhs.category == fcNormal);
01037 
01038   compare = exponent - rhs.exponent;
01039 
01040   /* If exponents are equal, do an unsigned bignum comparison of the
01041      significands.  */
01042   if(compare == 0)
01043     compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
01044                                partCount());
01045 
01046   if(compare > 0)
01047     return cmpGreaterThan;
01048   else if(compare < 0)
01049     return cmpLessThan;
01050   else
01051     return cmpEqual;
01052 }
01053 
01054 /* Handle overflow.  Sign is preserved.  We either become infinity or
01055    the largest finite number.  */
01056 APFloat::opStatus
01057 APFloat::handleOverflow(roundingMode rounding_mode)
01058 {
01059   /* Infinity?  */
01060   if(rounding_mode == rmNearestTiesToEven
01061      || rounding_mode == rmNearestTiesToAway
01062      || (rounding_mode == rmTowardPositive && !sign)
01063      || (rounding_mode == rmTowardNegative && sign))
01064     {
01065       category = fcInfinity;
01066       return (opStatus) (opOverflow | opInexact);
01067     }
01068 
01069   /* Otherwise we become the largest finite number.  */
01070   category = fcNormal;
01071   exponent = semantics->maxExponent;
01072   APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
01073                                    semantics->precision);
01074 
01075   return opInexact;
01076 }
01077 
01078 /* Returns TRUE if, when truncating the current number, with BIT the
01079    new LSB, with the given lost fraction and rounding mode, the result
01080    would need to be rounded away from zero (i.e., by increasing the
01081    signficand).  This routine must work for fcZero of both signs, and
01082    fcNormal numbers.  */
01083 bool
01084 APFloat::roundAwayFromZero(roundingMode rounding_mode,
01085                            lostFraction lost_fraction,
01086                            unsigned int bit) const
01087 {
01088   /* NaNs and infinities should not have lost fractions.  */
01089   assert(category == fcNormal || category == fcZero);
01090 
01091   /* Current callers never pass this so we don't handle it.  */
01092   assert(lost_fraction != lfExactlyZero);
01093 
01094   switch (rounding_mode) {
01095   default:
01096     llvm_unreachable(0);
01097 
01098   case rmNearestTiesToAway:
01099     return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
01100 
01101   case rmNearestTiesToEven:
01102     if(lost_fraction == lfMoreThanHalf)
01103       return true;
01104 
01105     /* Our zeroes don't have a significand to test.  */
01106     if(lost_fraction == lfExactlyHalf && category != fcZero)
01107       return APInt::tcExtractBit(significandParts(), bit);
01108 
01109     return false;
01110 
01111   case rmTowardZero:
01112     return false;
01113 
01114   case rmTowardPositive:
01115     return sign == false;
01116 
01117   case rmTowardNegative:
01118     return sign == true;
01119   }
01120 }
01121 
01122 APFloat::opStatus
01123 APFloat::normalize(roundingMode rounding_mode,
01124                    lostFraction lost_fraction)
01125 {
01126   unsigned int omsb;                /* One, not zero, based MSB.  */
01127   int exponentChange;
01128 
01129   if(category != fcNormal)
01130     return opOK;
01131 
01132   /* Before rounding normalize the exponent of fcNormal numbers.  */
01133   omsb = significandMSB() + 1;
01134 
01135   if(omsb) {
01136     /* OMSB is numbered from 1.  We want to place it in the integer
01137        bit numbered PRECISON if possible, with a compensating change in
01138        the exponent.  */
01139     exponentChange = omsb - semantics->precision;
01140 
01141     /* If the resulting exponent is too high, overflow according to
01142        the rounding mode.  */
01143     if(exponent + exponentChange > semantics->maxExponent)
01144       return handleOverflow(rounding_mode);
01145 
01146     /* Subnormal numbers have exponent minExponent, and their MSB
01147        is forced based on that.  */
01148     if(exponent + exponentChange < semantics->minExponent)
01149       exponentChange = semantics->minExponent - exponent;
01150 
01151     /* Shifting left is easy as we don't lose precision.  */
01152     if(exponentChange < 0) {
01153       assert(lost_fraction == lfExactlyZero);
01154 
01155       shiftSignificandLeft(-exponentChange);
01156 
01157       return opOK;
01158     }
01159 
01160     if(exponentChange > 0) {
01161       lostFraction lf;
01162 
01163       /* Shift right and capture any new lost fraction.  */
01164       lf = shiftSignificandRight(exponentChange);
01165 
01166       lost_fraction = combineLostFractions(lf, lost_fraction);
01167 
01168       /* Keep OMSB up-to-date.  */
01169       if(omsb > (unsigned) exponentChange)
01170         omsb -= exponentChange;
01171       else
01172         omsb = 0;
01173     }
01174   }
01175 
01176   /* Now round the number according to rounding_mode given the lost
01177      fraction.  */
01178 
01179   /* As specified in IEEE 754, since we do not trap we do not report
01180      underflow for exact results.  */
01181   if(lost_fraction == lfExactlyZero) {
01182     /* Canonicalize zeroes.  */
01183     if(omsb == 0)
01184       category = fcZero;
01185 
01186     return opOK;
01187   }
01188 
01189   /* Increment the significand if we're rounding away from zero.  */
01190   if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
01191     if(omsb == 0)
01192       exponent = semantics->minExponent;
01193 
01194     incrementSignificand();
01195     omsb = significandMSB() + 1;
01196 
01197     /* Did the significand increment overflow?  */
01198     if(omsb == (unsigned) semantics->precision + 1) {
01199       /* Renormalize by incrementing the exponent and shifting our
01200          significand right one.  However if we already have the
01201          maximum exponent we overflow to infinity.  */
01202       if(exponent == semantics->maxExponent) {
01203         category = fcInfinity;
01204 
01205         return (opStatus) (opOverflow | opInexact);
01206       }
01207 
01208       shiftSignificandRight(1);
01209 
01210       return opInexact;
01211     }
01212   }
01213 
01214   /* The normal case - we were and are not denormal, and any
01215      significand increment above didn't overflow.  */
01216   if(omsb == semantics->precision)
01217     return opInexact;
01218 
01219   /* We have a non-zero denormal.  */
01220   assert(omsb < semantics->precision);
01221 
01222   /* Canonicalize zeroes.  */
01223   if(omsb == 0)
01224     category = fcZero;
01225 
01226   /* The fcZero case is a denormal that underflowed to zero.  */
01227   return (opStatus) (opUnderflow | opInexact);
01228 }
01229 
01230 APFloat::opStatus
01231 APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
01232 {
01233   switch (convolve(category, rhs.category)) {
01234   default:
01235     llvm_unreachable(0);
01236 
01237   case convolve(fcNaN, fcZero):
01238   case convolve(fcNaN, fcNormal):
01239   case convolve(fcNaN, fcInfinity):
01240   case convolve(fcNaN, fcNaN):
01241   case convolve(fcNormal, fcZero):
01242   case convolve(fcInfinity, fcNormal):
01243   case convolve(fcInfinity, fcZero):
01244     return opOK;
01245 
01246   case convolve(fcZero, fcNaN):
01247   case convolve(fcNormal, fcNaN):
01248   case convolve(fcInfinity, fcNaN):
01249     category = fcNaN;
01250     copySignificand(rhs);
01251     return opOK;
01252 
01253   case convolve(fcNormal, fcInfinity):
01254   case convolve(fcZero, fcInfinity):
01255     category = fcInfinity;
01256     sign = rhs.sign ^ subtract;
01257     return opOK;
01258 
01259   case convolve(fcZero, fcNormal):
01260     assign(rhs);
01261     sign = rhs.sign ^ subtract;
01262     return opOK;
01263 
01264   case convolve(fcZero, fcZero):
01265     /* Sign depends on rounding mode; handled by caller.  */
01266     return opOK;
01267 
01268   case convolve(fcInfinity, fcInfinity):
01269     /* Differently signed infinities can only be validly
01270        subtracted.  */
01271     if(((sign ^ rhs.sign)!=0) != subtract) {
01272       makeNaN();
01273       return opInvalidOp;
01274     }
01275 
01276     return opOK;
01277 
01278   case convolve(fcNormal, fcNormal):
01279     return opDivByZero;
01280   }
01281 }
01282 
01283 /* Add or subtract two normal numbers.  */
01284 lostFraction
01285 APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
01286 {
01287   integerPart carry;
01288   lostFraction lost_fraction;
01289   int bits;
01290 
01291   /* Determine if the operation on the absolute values is effectively
01292      an addition or subtraction.  */
01293   subtract ^= (sign ^ rhs.sign) ? true : false;
01294 
01295   /* Are we bigger exponent-wise than the RHS?  */
01296   bits = exponent - rhs.exponent;
01297 
01298   /* Subtraction is more subtle than one might naively expect.  */
01299   if(subtract) {
01300     APFloat temp_rhs(rhs);
01301     bool reverse;
01302 
01303     if (bits == 0) {
01304       reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
01305       lost_fraction = lfExactlyZero;
01306     } else if (bits > 0) {
01307       lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
01308       shiftSignificandLeft(1);
01309       reverse = false;
01310     } else {
01311       lost_fraction = shiftSignificandRight(-bits - 1);
01312       temp_rhs.shiftSignificandLeft(1);
01313       reverse = true;
01314     }
01315 
01316     if (reverse) {
01317       carry = temp_rhs.subtractSignificand
01318         (*this, lost_fraction != lfExactlyZero);
01319       copySignificand(temp_rhs);
01320       sign = !sign;
01321     } else {
01322       carry = subtractSignificand
01323         (temp_rhs, lost_fraction != lfExactlyZero);
01324     }
01325 
01326     /* Invert the lost fraction - it was on the RHS and
01327        subtracted.  */
01328     if(lost_fraction == lfLessThanHalf)
01329       lost_fraction = lfMoreThanHalf;
01330     else if(lost_fraction == lfMoreThanHalf)
01331       lost_fraction = lfLessThanHalf;
01332 
01333     /* The code above is intended to ensure that no borrow is
01334        necessary.  */
01335     assert(!carry);
01336   } else {
01337     if(bits > 0) {
01338       APFloat temp_rhs(rhs);
01339 
01340       lost_fraction = temp_rhs.shiftSignificandRight(bits);
01341       carry = addSignificand(temp_rhs);
01342     } else {
01343       lost_fraction = shiftSignificandRight(-bits);
01344       carry = addSignificand(rhs);
01345     }
01346 
01347     /* We have a guard bit; generating a carry cannot happen.  */
01348     assert(!carry);
01349   }
01350 
01351   return lost_fraction;
01352 }
01353 
01354 APFloat::opStatus
01355 APFloat::multiplySpecials(const APFloat &rhs)
01356 {
01357   switch (convolve(category, rhs.category)) {
01358   default:
01359     llvm_unreachable(0);
01360 
01361   case convolve(fcNaN, fcZero):
01362   case convolve(fcNaN, fcNormal):
01363   case convolve(fcNaN, fcInfinity):
01364   case convolve(fcNaN, fcNaN):
01365     return opOK;
01366 
01367   case convolve(fcZero, fcNaN):
01368   case convolve(fcNormal, fcNaN):
01369   case convolve(fcInfinity, fcNaN):
01370     category = fcNaN;
01371     copySignificand(rhs);
01372     return opOK;
01373 
01374   case convolve(fcNormal, fcInfinity):
01375   case convolve(fcInfinity, fcNormal):
01376   case convolve(fcInfinity, fcInfinity):
01377     category = fcInfinity;
01378     return opOK;
01379 
01380   case convolve(fcZero, fcNormal):
01381   case convolve(fcNormal, fcZero):
01382   case convolve(fcZero, fcZero):
01383     category = fcZero;
01384     return opOK;
01385 
01386   case convolve(fcZero, fcInfinity):
01387   case convolve(fcInfinity, fcZero):
01388     makeNaN();
01389     return opInvalidOp;
01390 
01391   case convolve(fcNormal, fcNormal):
01392     return opOK;
01393   }
01394 }
01395 
01396 APFloat::opStatus
01397 APFloat::divideSpecials(const APFloat &rhs)
01398 {
01399   switch (convolve(category, rhs.category)) {
01400   default:
01401     llvm_unreachable(0);
01402 
01403   case convolve(fcNaN, fcZero):
01404   case convolve(fcNaN, fcNormal):
01405   case convolve(fcNaN, fcInfinity):
01406   case convolve(fcNaN, fcNaN):
01407   case convolve(fcInfinity, fcZero):
01408   case convolve(fcInfinity, fcNormal):
01409   case convolve(fcZero, fcInfinity):
01410   case convolve(fcZero, fcNormal):
01411     return opOK;
01412 
01413   case convolve(fcZero, fcNaN):
01414   case convolve(fcNormal, fcNaN):
01415   case convolve(fcInfinity, fcNaN):
01416     category = fcNaN;
01417     copySignificand(rhs);
01418     return opOK;
01419 
01420   case convolve(fcNormal, fcInfinity):
01421     category = fcZero;
01422     return opOK;
01423 
01424   case convolve(fcNormal, fcZero):
01425     category = fcInfinity;
01426     return opDivByZero;
01427 
01428   case convolve(fcInfinity, fcInfinity):
01429   case convolve(fcZero, fcZero):
01430     makeNaN();
01431     return opInvalidOp;
01432 
01433   case convolve(fcNormal, fcNormal):
01434     return opOK;
01435   }
01436 }
01437 
01438 APFloat::opStatus
01439 APFloat::modSpecials(const APFloat &rhs)
01440 {
01441   switch (convolve(category, rhs.category)) {
01442   default:
01443     llvm_unreachable(0);
01444 
01445   case convolve(fcNaN, fcZero):
01446   case convolve(fcNaN, fcNormal):
01447   case convolve(fcNaN, fcInfinity):
01448   case convolve(fcNaN, fcNaN):
01449   case convolve(fcZero, fcInfinity):
01450   case convolve(fcZero, fcNormal):
01451   case convolve(fcNormal, fcInfinity):
01452     return opOK;
01453 
01454   case convolve(fcZero, fcNaN):
01455   case convolve(fcNormal, fcNaN):
01456   case convolve(fcInfinity, fcNaN):
01457     category = fcNaN;
01458     copySignificand(rhs);
01459     return opOK;
01460 
01461   case convolve(fcNormal, fcZero):
01462   case convolve(fcInfinity, fcZero):
01463   case convolve(fcInfinity, fcNormal):
01464   case convolve(fcInfinity, fcInfinity):
01465   case convolve(fcZero, fcZero):
01466     makeNaN();
01467     return opInvalidOp;
01468 
01469   case convolve(fcNormal, fcNormal):
01470     return opOK;
01471   }
01472 }
01473 
01474 /* Change sign.  */
01475 void
01476 APFloat::changeSign()
01477 {
01478   /* Look mummy, this one's easy.  */
01479   sign = !sign;
01480 }
01481 
01482 void
01483 APFloat::clearSign()
01484 {
01485   /* So is this one. */
01486   sign = 0;
01487 }
01488 
01489 void
01490 APFloat::copySign(const APFloat &rhs)
01491 {
01492   /* And this one. */
01493   sign = rhs.sign;
01494 }
01495 
01496 /* Normalized addition or subtraction.  */
01497 APFloat::opStatus
01498 APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
01499                        bool subtract)
01500 {
01501   opStatus fs;
01502 
01503   assertArithmeticOK(*semantics);
01504 
01505   fs = addOrSubtractSpecials(rhs, subtract);
01506 
01507   /* This return code means it was not a simple case.  */
01508   if(fs == opDivByZero) {
01509     lostFraction lost_fraction;
01510 
01511     lost_fraction = addOrSubtractSignificand(rhs, subtract);
01512     fs = normalize(rounding_mode, lost_fraction);
01513 
01514     /* Can only be zero if we lost no fraction.  */
01515     assert(category != fcZero || lost_fraction == lfExactlyZero);
01516   }
01517 
01518   /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
01519      positive zero unless rounding to minus infinity, except that
01520      adding two like-signed zeroes gives that zero.  */
01521   if(category == fcZero) {
01522     if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
01523       sign = (rounding_mode == rmTowardNegative);
01524   }
01525 
01526   return fs;
01527 }
01528 
01529 /* Normalized addition.  */
01530 APFloat::opStatus
01531 APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
01532 {
01533   return addOrSubtract(rhs, rounding_mode, false);
01534 }
01535 
01536 /* Normalized subtraction.  */
01537 APFloat::opStatus
01538 APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
01539 {
01540   return addOrSubtract(rhs, rounding_mode, true);
01541 }
01542 
01543 /* Normalized multiply.  */
01544 APFloat::opStatus
01545 APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
01546 {
01547   opStatus fs;
01548 
01549   assertArithmeticOK(*semantics);
01550   sign ^= rhs.sign;
01551   fs = multiplySpecials(rhs);
01552 
01553   if(category == fcNormal) {
01554     lostFraction lost_fraction = multiplySignificand(rhs, 0);
01555     fs = normalize(rounding_mode, lost_fraction);
01556     if(lost_fraction != lfExactlyZero)
01557       fs = (opStatus) (fs | opInexact);
01558   }
01559 
01560   return fs;
01561 }
01562 
01563 /* Normalized divide.  */
01564 APFloat::opStatus
01565 APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
01566 {
01567   opStatus fs;
01568 
01569   assertArithmeticOK(*semantics);
01570   sign ^= rhs.sign;
01571   fs = divideSpecials(rhs);
01572 
01573   if(category == fcNormal) {
01574     lostFraction lost_fraction = divideSignificand(rhs);
01575     fs = normalize(rounding_mode, lost_fraction);
01576     if(lost_fraction != lfExactlyZero)
01577       fs = (opStatus) (fs | opInexact);
01578   }
01579 
01580   return fs;
01581 }
01582 
01583 /* Normalized remainder.  This is not currently correct in all cases.  */
01584 APFloat::opStatus
01585 APFloat::remainder(const APFloat &rhs)
01586 {
01587   opStatus fs;
01588   APFloat V = *this;
01589   unsigned int origSign = sign;
01590 
01591   assertArithmeticOK(*semantics);
01592   fs = V.divide(rhs, rmNearestTiesToEven);
01593   if (fs == opDivByZero)
01594     return fs;
01595 
01596   int parts = partCount();
01597   integerPart *x = new integerPart[parts];
01598   bool ignored;
01599   fs = V.convertToInteger(x, parts * integerPartWidth, true,
01600                           rmNearestTiesToEven, &ignored);
01601   if (fs==opInvalidOp)
01602     return fs;
01603 
01604   fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
01605                                         rmNearestTiesToEven);
01606   assert(fs==opOK);   // should always work
01607 
01608   fs = V.multiply(rhs, rmNearestTiesToEven);
01609   assert(fs==opOK || fs==opInexact);   // should not overflow or underflow
01610 
01611   fs = subtract(V, rmNearestTiesToEven);
01612   assert(fs==opOK || fs==opInexact);   // likewise
01613 
01614   if (isZero())
01615     sign = origSign;    // IEEE754 requires this
01616   delete[] x;
01617   return fs;
01618 }
01619 
01620 /* Normalized llvm frem (C fmod).  
01621    This is not currently correct in all cases.  */
01622 APFloat::opStatus
01623 APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
01624 {
01625   opStatus fs;
01626   assertArithmeticOK(*semantics);
01627   fs = modSpecials(rhs);
01628 
01629   if (category == fcNormal && rhs.category == fcNormal) {
01630     APFloat V = *this;
01631     unsigned int origSign = sign;
01632 
01633     fs = V.divide(rhs, rmNearestTiesToEven);
01634     if (fs == opDivByZero)
01635       return fs;
01636 
01637     int parts = partCount();
01638     integerPart *x = new integerPart[parts];
01639     bool ignored;
01640     fs = V.convertToInteger(x, parts * integerPartWidth, true,
01641                             rmTowardZero, &ignored);
01642     if (fs==opInvalidOp)
01643       return fs;
01644 
01645     fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
01646                                           rmNearestTiesToEven);
01647     assert(fs==opOK);   // should always work
01648 
01649     fs = V.multiply(rhs, rounding_mode);
01650     assert(fs==opOK || fs==opInexact);   // should not overflow or underflow
01651 
01652     fs = subtract(V, rounding_mode);
01653     assert(fs==opOK || fs==opInexact);   // likewise
01654 
01655     if (isZero())
01656       sign = origSign;    // IEEE754 requires this
01657     delete[] x;
01658   }
01659   return fs;
01660 }
01661 
01662 /* Normalized fused-multiply-add.  */
01663 APFloat::opStatus
01664 APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
01665                           const APFloat &addend,
01666                           roundingMode rounding_mode)
01667 {
01668   opStatus fs;
01669 
01670   assertArithmeticOK(*semantics);
01671 
01672   /* Post-multiplication sign, before addition.  */
01673   sign ^= multiplicand.sign;
01674 
01675   /* If and only if all arguments are normal do we need to do an
01676      extended-precision calculation.  */
01677   if(category == fcNormal
01678      && multiplicand.category == fcNormal
01679      && addend.category == fcNormal) {
01680     lostFraction lost_fraction;
01681 
01682     lost_fraction = multiplySignificand(multiplicand, &addend);
01683     fs = normalize(rounding_mode, lost_fraction);
01684     if(lost_fraction != lfExactlyZero)
01685       fs = (opStatus) (fs | opInexact);
01686 
01687     /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
01688        positive zero unless rounding to minus infinity, except that
01689        adding two like-signed zeroes gives that zero.  */
01690     if(category == fcZero && sign != addend.sign)
01691       sign = (rounding_mode == rmTowardNegative);
01692   } else {
01693     fs = multiplySpecials(multiplicand);
01694 
01695     /* FS can only be opOK or opInvalidOp.  There is no more work
01696        to do in the latter case.  The IEEE-754R standard says it is
01697        implementation-defined in this case whether, if ADDEND is a
01698        quiet NaN, we raise invalid op; this implementation does so.
01699 
01700        If we need to do the addition we can do so with normal
01701        precision.  */
01702     if(fs == opOK)
01703       fs = addOrSubtract(addend, rounding_mode, false);
01704   }
01705 
01706   return fs;
01707 }
01708 
01709 /* Comparison requires normalized numbers.  */
01710 APFloat::cmpResult
01711 APFloat::compare(const APFloat &rhs) const
01712 {
01713   cmpResult result;
01714 
01715   assertArithmeticOK(*semantics);
01716   assert(semantics == rhs.semantics);
01717 
01718   switch (convolve(category, rhs.category)) {
01719   default:
01720     llvm_unreachable(0);
01721 
01722   case convolve(fcNaN, fcZero):
01723   case convolve(fcNaN, fcNormal):
01724   case convolve(fcNaN, fcInfinity):
01725   case convolve(fcNaN, fcNaN):
01726   case convolve(fcZero, fcNaN):
01727   case convolve(fcNormal, fcNaN):
01728   case convolve(fcInfinity, fcNaN):
01729     return cmpUnordered;
01730 
01731   case convolve(fcInfinity, fcNormal):
01732   case convolve(fcInfinity, fcZero):
01733   case convolve(fcNormal, fcZero):
01734     if(sign)
01735       return cmpLessThan;
01736     else
01737       return cmpGreaterThan;
01738 
01739   case convolve(fcNormal, fcInfinity):
01740   case convolve(fcZero, fcInfinity):
01741   case convolve(fcZero, fcNormal):
01742     if(rhs.sign)
01743       return cmpGreaterThan;
01744     else
01745       return cmpLessThan;
01746 
01747   case convolve(fcInfinity, fcInfinity):
01748     if(sign == rhs.sign)
01749       return cmpEqual;
01750     else if(sign)
01751       return cmpLessThan;
01752     else
01753       return cmpGreaterThan;
01754 
01755   case convolve(fcZero, fcZero):
01756     return cmpEqual;
01757 
01758   case convolve(fcNormal, fcNormal):
01759     break;
01760   }
01761 
01762   /* Two normal numbers.  Do they have the same sign?  */
01763   if(sign != rhs.sign) {
01764     if(sign)
01765       result = cmpLessThan;
01766     else
01767       result = cmpGreaterThan;
01768   } else {
01769     /* Compare absolute values; invert result if negative.  */
01770     result = compareAbsoluteValue(rhs);
01771 
01772     if(sign) {
01773       if(result == cmpLessThan)
01774         result = cmpGreaterThan;
01775       else if(result == cmpGreaterThan)
01776         result = cmpLessThan;
01777     }
01778   }
01779 
01780   return result;
01781 }
01782 
01783 /// APFloat::convert - convert a value of one floating point type to another.
01784 /// The return value corresponds to the IEEE754 exceptions.  *losesInfo
01785 /// records whether the transformation lost information, i.e. whether
01786 /// converting the result back to the original type will produce the
01787 /// original value (this is almost the same as return value==fsOK, but there
01788 /// are edge cases where this is not so).
01789 
01790 APFloat::opStatus
01791 APFloat::convert(const fltSemantics &toSemantics,
01792                  roundingMode rounding_mode, bool *losesInfo)
01793 {
01794   lostFraction lostFraction;
01795   unsigned int newPartCount, oldPartCount;
01796   opStatus fs;
01797 
01798   assertArithmeticOK(*semantics);
01799   assertArithmeticOK(toSemantics);
01800   lostFraction = lfExactlyZero;
01801   newPartCount = partCountForBits(toSemantics.precision + 1);
01802   oldPartCount = partCount();
01803 
01804   /* Handle storage complications.  If our new form is wider,
01805      re-allocate our bit pattern into wider storage.  If it is
01806      narrower, we ignore the excess parts, but if narrowing to a
01807      single part we need to free the old storage.
01808      Be careful not to reference significandParts for zeroes
01809      and infinities, since it aborts.  */
01810   if (newPartCount > oldPartCount) {
01811     integerPart *newParts;
01812     newParts = new integerPart[newPartCount];
01813     APInt::tcSet(newParts, 0, newPartCount);
01814     if (category==fcNormal || category==fcNaN)
01815       APInt::tcAssign(newParts, significandParts(), oldPartCount);
01816     freeSignificand();
01817     significand.parts = newParts;
01818   } else if (newPartCount < oldPartCount) {
01819     /* Capture any lost fraction through truncation of parts so we get
01820        correct rounding whilst normalizing.  */
01821     if (category==fcNormal)
01822       lostFraction = lostFractionThroughTruncation
01823         (significandParts(), oldPartCount, toSemantics.precision);
01824     if (newPartCount == 1) {
01825         integerPart newPart = 0;
01826         if (category==fcNormal || category==fcNaN)
01827           newPart = significandParts()[0];
01828         freeSignificand();
01829         significand.part = newPart;
01830     }
01831   }
01832 
01833   if(category == fcNormal) {
01834     /* Re-interpret our bit-pattern.  */
01835     exponent += toSemantics.precision - semantics->precision;
01836     semantics = &toSemantics;
01837     fs = normalize(rounding_mode, lostFraction);
01838     *losesInfo = (fs != opOK);
01839   } else if (category == fcNaN) {
01840     int shift = toSemantics.precision - semantics->precision;
01841     // Do this now so significandParts gets the right answer
01842     const fltSemantics *oldSemantics = semantics;
01843     semantics = &toSemantics;
01844     *losesInfo = false;
01845     // No normalization here, just truncate
01846     if (shift>0)
01847       APInt::tcShiftLeft(significandParts(), newPartCount, shift);
01848     else if (shift < 0) {
01849       unsigned ushift = -shift;
01850       // Figure out if we are losing information.  This happens
01851       // if are shifting out something other than 0s, or if the x87 long
01852       // double input did not have its integer bit set (pseudo-NaN), or if the
01853       // x87 long double input did not have its QNan bit set (because the x87
01854       // hardware sets this bit when converting a lower-precision NaN to
01855       // x87 long double).
01856       if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
01857         *losesInfo = true;
01858       if (oldSemantics == &APFloat::x87DoubleExtended && 
01859           (!(*significandParts() & 0x8000000000000000ULL) ||
01860            !(*significandParts() & 0x4000000000000000ULL)))
01861         *losesInfo = true;
01862       APInt::tcShiftRight(significandParts(), newPartCount, ushift);
01863     }
01864     // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
01865     // does not give you back the same bits.  This is dubious, and we
01866     // don't currently do it.  You're really supposed to get
01867     // an invalid operation signal at runtime, but nobody does that.
01868     fs = opOK;
01869   } else {
01870     semantics = &toSemantics;
01871     fs = opOK;
01872     *losesInfo = false;
01873   }
01874 
01875   return fs;
01876 }
01877 
01878 /* Convert a floating point number to an integer according to the
01879    rounding mode.  If the rounded integer value is out of range this
01880    returns an invalid operation exception and the contents of the
01881    destination parts are unspecified.  If the rounded value is in
01882    range but the floating point number is not the exact integer, the C
01883    standard doesn't require an inexact exception to be raised.  IEEE
01884    854 does require it so we do that.
01885 
01886    Note that for conversions to integer type the C standard requires
01887    round-to-zero to always be used.  */
01888 APFloat::opStatus
01889 APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
01890                                       bool isSigned,
01891                                       roundingMode rounding_mode,
01892                                       bool *isExact) const
01893 {
01894   lostFraction lost_fraction;
01895   const integerPart *src;
01896   unsigned int dstPartsCount, truncatedBits;
01897 
01898   assertArithmeticOK(*semantics);
01899 
01900   *isExact = false;
01901 
01902   /* Handle the three special cases first.  */
01903   if(category == fcInfinity || category == fcNaN)
01904     return opInvalidOp;
01905 
01906   dstPartsCount = partCountForBits(width);
01907 
01908   if(category == fcZero) {
01909     APInt::tcSet(parts, 0, dstPartsCount);
01910     // Negative zero can't be represented as an int.
01911     *isExact = !sign;
01912     return opOK;
01913   }
01914 
01915   src = significandParts();
01916 
01917   /* Step 1: place our absolute value, with any fraction truncated, in
01918      the destination.  */
01919   if (exponent < 0) {
01920     /* Our absolute value is less than one; truncate everything.  */
01921     APInt::tcSet(parts, 0, dstPartsCount);
01922     /* For exponent -1 the integer bit represents .5, look at that.
01923        For smaller exponents leftmost truncated bit is 0. */
01924     truncatedBits = semantics->precision -1U - exponent;
01925   } else {
01926     /* We want the most significant (exponent + 1) bits; the rest are
01927        truncated.  */
01928     unsigned int bits = exponent + 1U;
01929 
01930     /* Hopelessly large in magnitude?  */
01931     if (bits > width)
01932       return opInvalidOp;
01933 
01934     if (bits < semantics->precision) {
01935       /* We truncate (semantics->precision - bits) bits.  */
01936       truncatedBits = semantics->precision - bits;
01937       APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
01938     } else {
01939       /* We want at least as many bits as are available.  */
01940       APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
01941       APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
01942       truncatedBits = 0;
01943     }
01944   }
01945 
01946   /* Step 2: work out any lost fraction, and increment the absolute
01947      value if we would round away from zero.  */
01948   if (truncatedBits) {
01949     lost_fraction = lostFractionThroughTruncation(src, partCount(),
01950                                                   truncatedBits);
01951     if (lost_fraction != lfExactlyZero
01952         && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
01953       if (APInt::tcIncrement(parts, dstPartsCount))
01954         return opInvalidOp;     /* Overflow.  */
01955     }
01956   } else {
01957     lost_fraction = lfExactlyZero;
01958   }
01959 
01960   /* Step 3: check if we fit in the destination.  */
01961   unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
01962 
01963   if (sign) {
01964     if (!isSigned) {
01965       /* Negative numbers cannot be represented as unsigned.  */
01966       if (omsb != 0)
01967         return opInvalidOp;
01968     } else {
01969       /* It takes omsb bits to represent the unsigned integer value.
01970          We lose a bit for the sign, but care is needed as the
01971          maximally negative integer is a special case.  */
01972       if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
01973         return opInvalidOp;
01974 
01975       /* This case can happen because of rounding.  */
01976       if (omsb > width)
01977         return opInvalidOp;
01978     }
01979 
01980     APInt::tcNegate (parts, dstPartsCount);
01981   } else {
01982     if (omsb >= width + !isSigned)
01983       return opInvalidOp;
01984   }
01985 
01986   if (lost_fraction == lfExactlyZero) {
01987     *isExact = true;
01988     return opOK;
01989   } else
01990     return opInexact;
01991 }
01992 
01993 /* Same as convertToSignExtendedInteger, except we provide
01994    deterministic values in case of an invalid operation exception,
01995    namely zero for NaNs and the minimal or maximal value respectively
01996    for underflow or overflow.
01997    The *isExact output tells whether the result is exact, in the sense
01998    that converting it back to the original floating point type produces
01999    the original value.  This is almost equivalent to result==opOK,
02000    except for negative zeroes.
02001 */
02002 APFloat::opStatus
02003 APFloat::convertToInteger(integerPart *parts, unsigned int width,
02004                           bool isSigned,
02005                           roundingMode rounding_mode, bool *isExact) const
02006 {
02007   opStatus fs;
02008 
02009   fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode, 
02010                                     isExact);
02011 
02012   if (fs == opInvalidOp) {
02013     unsigned int bits, dstPartsCount;
02014 
02015     dstPartsCount = partCountForBits(width);
02016 
02017     if (category == fcNaN)
02018       bits = 0;
02019     else if (sign)
02020       bits = isSigned;
02021     else
02022       bits = width - isSigned;
02023 
02024     APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
02025     if (sign && isSigned)
02026       APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
02027   }
02028 
02029   return fs;
02030 }
02031 
02032 /* Convert an unsigned integer SRC to a floating point number,
02033    rounding according to ROUNDING_MODE.  The sign of the floating
02034    point number is not modified.  */
02035 APFloat::opStatus
02036 APFloat::convertFromUnsignedParts(const integerPart *src,
02037                                   unsigned int srcCount,
02038                                   roundingMode rounding_mode)
02039 {
02040   unsigned int omsb, precision, dstCount;
02041   integerPart *dst;
02042   lostFraction lost_fraction;
02043 
02044   assertArithmeticOK(*semantics);
02045   category = fcNormal;
02046   omsb = APInt::tcMSB(src, srcCount) + 1;
02047   dst = significandParts();
02048   dstCount = partCount();
02049   precision = semantics->precision;
02050 
02051   /* We want the most significant PRECISON bits of SRC.  There may not
02052      be that many; extract what we can.  */
02053   if (precision <= omsb) {
02054     exponent = omsb - 1;
02055     lost_fraction = lostFractionThroughTruncation(src, srcCount,
02056                                                   omsb - precision);
02057     APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
02058   } else {
02059     exponent = precision - 1;
02060     lost_fraction = lfExactlyZero;
02061     APInt::tcExtract(dst, dstCount, src, omsb, 0);
02062   }
02063 
02064   return normalize(rounding_mode, lost_fraction);
02065 }
02066 
02067 APFloat::opStatus
02068 APFloat::convertFromAPInt(const APInt &Val,
02069                           bool isSigned,
02070                           roundingMode rounding_mode)
02071 {
02072   unsigned int partCount = Val.getNumWords();
02073   APInt api = Val;
02074 
02075   sign = false;
02076   if (isSigned && api.isNegative()) {
02077     sign = true;
02078     api = -api;
02079   }
02080 
02081   return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
02082 }
02083 
02084 /* Convert a two's complement integer SRC to a floating point number,
02085    rounding according to ROUNDING_MODE.  ISSIGNED is true if the
02086    integer is signed, in which case it must be sign-extended.  */
02087 APFloat::opStatus
02088 APFloat::convertFromSignExtendedInteger(const integerPart *src,
02089                                         unsigned int srcCount,
02090                                         bool isSigned,
02091                                         roundingMode rounding_mode)
02092 {
02093   opStatus status;
02094 
02095   assertArithmeticOK(*semantics);
02096   if (isSigned
02097       && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
02098     integerPart *copy;
02099 
02100     /* If we're signed and negative negate a copy.  */
02101     sign = true;
02102     copy = new integerPart[srcCount];
02103     APInt::tcAssign(copy, src, srcCount);
02104     APInt::tcNegate(copy, srcCount);
02105     status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
02106     delete [] copy;
02107   } else {
02108     sign = false;
02109     status = convertFromUnsignedParts(src, srcCount, rounding_mode);
02110   }
02111 
02112   return status;
02113 }
02114 
02115 /* FIXME: should this just take a const APInt reference?  */
02116 APFloat::opStatus
02117 APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
02118                                         unsigned int width, bool isSigned,
02119                                         roundingMode rounding_mode)
02120 {
02121   unsigned int partCount = partCountForBits(width);
02122   APInt api = APInt(width, partCount, parts);
02123 
02124   sign = false;
02125   if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
02126     sign = true;
02127     api = -api;
02128   }
02129 
02130   return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
02131 }
02132 
02133 APFloat::opStatus
02134 APFloat::convertFromHexadecimalString(const StringRef &s,
02135                                       roundingMode rounding_mode)
02136 {
02137   lostFraction lost_fraction = lfExactlyZero;
02138   integerPart *significand;
02139   unsigned int bitPos, partsCount;
02140   StringRef::iterator dot, firstSignificantDigit;
02141 
02142   zeroSignificand();
02143   exponent = 0;
02144   category = fcNormal;
02145 
02146   significand = significandParts();
02147   partsCount = partCount();
02148   bitPos = partsCount * integerPartWidth;
02149 
02150   /* Skip leading zeroes and any (hexa)decimal point.  */
02151   StringRef::iterator begin = s.begin();
02152   StringRef::iterator end = s.end();
02153   StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
02154   firstSignificantDigit = p;
02155 
02156   for(; p != end;) {
02157     integerPart hex_value;
02158 
02159     if(*p == '.') {
02160       assert(dot == end && "String contains multiple dots");
02161       dot = p++;
02162       if (p == end) {
02163         break;
02164       }
02165     }
02166 
02167     hex_value = hexDigitValue(*p);
02168     if(hex_value == -1U) {
02169       break;
02170     }
02171 
02172     p++;
02173 
02174     if (p == end) {
02175       break;
02176     } else {
02177       /* Store the number whilst 4-bit nibbles remain.  */
02178       if(bitPos) {
02179         bitPos -= 4;
02180         hex_value <<= bitPos % integerPartWidth;
02181         significand[bitPos / integerPartWidth] |= hex_value;
02182       } else {
02183         lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
02184         while(p != end && hexDigitValue(*p) != -1U)
02185           p++;
02186         break;
02187       }
02188     }
02189   }
02190 
02191   /* Hex floats require an exponent but not a hexadecimal point.  */
02192   assert(p != end && "Hex strings require an exponent");
02193   assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
02194   assert(p != begin && "Significand has no digits");
02195   assert((dot == end || p - begin != 1) && "Significand has no digits");
02196 
02197   /* Ignore the exponent if we are zero.  */
02198   if(p != firstSignificantDigit) {
02199     int expAdjustment;
02200 
02201     /* Implicit hexadecimal point?  */
02202     if (dot == end)
02203       dot = p;
02204 
02205     /* Calculate the exponent adjustment implicit in the number of
02206        significant digits.  */
02207     expAdjustment = static_cast<int>(dot - firstSignificantDigit);
02208     if(expAdjustment < 0)
02209       expAdjustment++;
02210     expAdjustment = expAdjustment * 4 - 1;
02211 
02212     /* Adjust for writing the significand starting at the most
02213        significant nibble.  */
02214     expAdjustment += semantics->precision;
02215     expAdjustment -= partsCount * integerPartWidth;
02216 
02217     /* Adjust for the given exponent.  */
02218     exponent = totalExponent(p + 1, end, expAdjustment);
02219   }
02220 
02221   return normalize(rounding_mode, lost_fraction);
02222 }
02223 
02224 APFloat::opStatus
02225 APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
02226                                       unsigned sigPartCount, int exp,
02227                                       roundingMode rounding_mode)
02228 {
02229   unsigned int parts, pow5PartCount;
02230   fltSemantics calcSemantics = { 32767, -32767, 0, true };
02231   integerPart pow5Parts[maxPowerOfFiveParts];
02232   bool isNearest;
02233 
02234   isNearest = (rounding_mode == rmNearestTiesToEven
02235                || rounding_mode == rmNearestTiesToAway);
02236 
02237   parts = partCountForBits(semantics->precision + 11);
02238 
02239   /* Calculate pow(5, abs(exp)).  */
02240   pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
02241 
02242   for (;; parts *= 2) {
02243     opStatus sigStatus, powStatus;
02244     unsigned int excessPrecision, truncatedBits;
02245 
02246     calcSemantics.precision = parts * integerPartWidth - 1;
02247     excessPrecision = calcSemantics.precision - semantics->precision;
02248     truncatedBits = excessPrecision;
02249 
02250     APFloat decSig(calcSemantics, fcZero, sign);
02251     APFloat pow5(calcSemantics, fcZero, false);
02252 
02253     sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
02254                                                 rmNearestTiesToEven);
02255     powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
02256                                               rmNearestTiesToEven);
02257     /* Add exp, as 10^n = 5^n * 2^n.  */
02258     decSig.exponent += exp;
02259 
02260     lostFraction calcLostFraction;
02261     integerPart HUerr, HUdistance;
02262     unsigned int powHUerr;
02263 
02264     if (exp >= 0) {
02265       /* multiplySignificand leaves the precision-th bit set to 1.  */
02266       calcLostFraction = decSig.multiplySignificand(pow5, NULL);
02267       powHUerr = powStatus != opOK;
02268     } else {
02269       calcLostFraction = decSig.divideSignificand(pow5);
02270       /* Denormal numbers have less precision.  */
02271       if (decSig.exponent < semantics->minExponent) {
02272         excessPrecision += (semantics->minExponent - decSig.exponent);
02273         truncatedBits = excessPrecision;
02274         if (excessPrecision > calcSemantics.precision)
02275           excessPrecision = calcSemantics.precision;
02276       }
02277       /* Extra half-ulp lost in reciprocal of exponent.  */
02278       powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
02279     }
02280 
02281     /* Both multiplySignificand and divideSignificand return the
02282        result with the integer bit set.  */
02283     assert (APInt::tcExtractBit
02284             (decSig.significandParts(), calcSemantics.precision - 1) == 1);
02285 
02286     HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
02287                        powHUerr);
02288     HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
02289                                       excessPrecision, isNearest);
02290 
02291     /* Are we guaranteed to round correctly if we truncate?  */
02292     if (HUdistance >= HUerr) {
02293       APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
02294                        calcSemantics.precision - excessPrecision,
02295                        excessPrecision);
02296       /* Take the exponent of decSig.  If we tcExtract-ed less bits
02297          above we must adjust our exponent to compensate for the
02298          implicit right shift.  */
02299       exponent = (decSig.exponent + semantics->precision
02300                   - (calcSemantics.precision - excessPrecision));
02301       calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
02302                                                        decSig.partCount(),
02303                                                        truncatedBits);
02304       return normalize(rounding_mode, calcLostFraction);
02305     }
02306   }
02307 }
02308 
02309 APFloat::opStatus
02310 APFloat::convertFromDecimalString(const StringRef &str, roundingMode rounding_mode)
02311 {
02312   decimalInfo D;
02313   opStatus fs;
02314 
02315   /* Scan the text.  */
02316   StringRef::iterator p = str.begin();
02317   interpretDecimal(p, str.end(), &D);
02318 
02319   /* Handle the quick cases.  First the case of no significant digits,
02320      i.e. zero, and then exponents that are obviously too large or too
02321      small.  Writing L for log 10 / log 2, a number d.ddddd*10^exp
02322      definitely overflows if
02323 
02324            (exp - 1) * L >= maxExponent
02325 
02326      and definitely underflows to zero where
02327 
02328            (exp + 1) * L <= minExponent - precision
02329 
02330      With integer arithmetic the tightest bounds for L are
02331 
02332            93/28 < L < 196/59            [ numerator <= 256 ]
02333            42039/12655 < L < 28738/8651  [ numerator <= 65536 ]
02334   */
02335 
02336   if (decDigitValue(*D.firstSigDigit) >= 10U) {
02337     category = fcZero;
02338     fs = opOK;
02339   } else if ((D.normalizedExponent + 1) * 28738
02340              <= 8651 * (semantics->minExponent - (int) semantics->precision)) {
02341     /* Underflow to zero and round.  */
02342     zeroSignificand();
02343     fs = normalize(rounding_mode, lfLessThanHalf);
02344   } else if ((D.normalizedExponent - 1) * 42039
02345              >= 12655 * semantics->maxExponent) {
02346     /* Overflow and round.  */
02347     fs = handleOverflow(rounding_mode);
02348   } else {
02349     integerPart *decSignificand;
02350     unsigned int partCount;
02351 
02352     /* A tight upper bound on number of bits required to hold an
02353        N-digit decimal integer is N * 196 / 59.  Allocate enough space
02354        to hold the full significand, and an extra part required by
02355        tcMultiplyPart.  */
02356     partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
02357     partCount = partCountForBits(1 + 196 * partCount / 59);
02358     decSignificand = new integerPart[partCount + 1];
02359     partCount = 0;
02360 
02361     /* Convert to binary efficiently - we do almost all multiplication
02362        in an integerPart.  When this would overflow do we do a single
02363        bignum multiplication, and then revert again to multiplication
02364        in an integerPart.  */
02365     do {
02366       integerPart decValue, val, multiplier;
02367 
02368       val = 0;
02369       multiplier = 1;
02370 
02371       do {
02372         if (*p == '.') {
02373           p++;
02374           if (p == str.end()) {
02375             break;
02376           }
02377         }
02378         decValue = decDigitValue(*p++);
02379         assert(decValue < 10U && "Invalid character in significand");
02380         multiplier *= 10;
02381         val = val * 10 + decValue;
02382         /* The maximum number that can be multiplied by ten with any
02383            digit added without overflowing an integerPart.  */
02384       } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
02385 
02386       /* Multiply out the current part.  */
02387       APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
02388                             partCount, partCount + 1, false);
02389 
02390       /* If we used another part (likely but not guaranteed), increase
02391          the count.  */
02392       if (decSignificand[partCount])
02393         partCount++;
02394     } while (p <= D.lastSigDigit);
02395 
02396     category = fcNormal;
02397     fs = roundSignificandWithExponent(decSignificand, partCount,
02398                                       D.exponent, rounding_mode);
02399 
02400     delete [] decSignificand;
02401   }
02402 
02403   return fs;
02404 }
02405 
02406 APFloat::opStatus
02407 APFloat::convertFromString(const StringRef &str, roundingMode rounding_mode)
02408 {
02409   assertArithmeticOK(*semantics);
02410   assert(!str.empty() && "Invalid string length");
02411 
02412   /* Handle a leading minus sign.  */
02413   StringRef::iterator p = str.begin();
02414   size_t slen = str.size();
02415   sign = *p == '-' ? 1 : 0;
02416   if(*p == '-' || *p == '+') {
02417     p++;
02418     slen--;
02419     assert(slen && "String has no digits");
02420   }
02421 
02422   if(slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
02423     assert(slen - 2 && "Invalid string");
02424     return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
02425                                         rounding_mode);
02426   }
02427 
02428   return convertFromDecimalString(StringRef(p, slen), rounding_mode);
02429 }
02430 
02431 /* Write out a hexadecimal representation of the floating point value
02432    to DST, which must be of sufficient size, in the C99 form
02433    [-]0xh.hhhhp[+-]d.  Return the number of characters written,
02434    excluding the terminating NUL.
02435 
02436    If UPPERCASE, the output is in upper case, otherwise in lower case.
02437 
02438    HEXDIGITS digits appear altogether, rounding the value if
02439    necessary.  If HEXDIGITS is 0, the minimal precision to display the
02440    number precisely is used instead.  If nothing would appear after
02441    the decimal point it is suppressed.
02442 
02443    The decimal exponent is always printed and has at least one digit.
02444    Zero values display an exponent of zero.  Infinities and NaNs
02445    appear as "infinity" or "nan" respectively.
02446 
02447    The above rules are as specified by C99.  There is ambiguity about
02448    what the leading hexadecimal digit should be.  This implementation
02449    uses whatever is necessary so that the exponent is displayed as
02450    stored.  This implies the exponent will fall within the IEEE format
02451    range, and the leading hexadecimal digit will be 0 (for denormals),
02452    1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
02453    any other digits zero).
02454 */
02455 unsigned int
02456 APFloat::convertToHexString(char *dst, unsigned int hexDigits,
02457                             bool upperCase, roundingMode rounding_mode) const
02458 {
02459   char *p;
02460 
02461   assertArithmeticOK(*semantics);
02462 
02463   p = dst;
02464   if (sign)
02465     *dst++ = '-';
02466 
02467   switch (category) {
02468   case fcInfinity:
02469     memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
02470     dst += sizeof infinityL - 1;
02471     break;
02472 
02473   case fcNaN:
02474     memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
02475     dst += sizeof NaNU - 1;
02476     break;
02477 
02478   case fcZero:
02479     *dst++ = '0';
02480     *dst++ = upperCase ? 'X': 'x';
02481     *dst++ = '0';
02482     if (hexDigits > 1) {
02483       *dst++ = '.';
02484       memset (dst, '0', hexDigits - 1);
02485       dst += hexDigits - 1;
02486     }
02487     *dst++ = upperCase ? 'P': 'p';
02488     *dst++ = '0';
02489     break;
02490 
02491   case fcNormal:
02492     dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
02493     break;
02494   }
02495 
02496   *dst = 0;
02497 
02498   return static_cast<unsigned int>(dst - p);
02499 }
02500 
02501 /* Does the hard work of outputting the correctly rounded hexadecimal
02502    form of a normal floating point number with the specified number of
02503    hexadecimal digits.  If HEXDIGITS is zero the minimum number of
02504    digits necessary to print the value precisely is output.  */
02505 char *
02506 APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
02507                                   bool upperCase,
02508                                   roundingMode rounding_mode) const
02509 {
02510   unsigned int count, valueBits, shift, partsCount, outputDigits;
02511   const char *hexDigitChars;
02512   const integerPart *significand;
02513   char *p;
02514   bool roundUp;
02515 
02516   *dst++ = '0';
02517   *dst++ = upperCase ? 'X': 'x';
02518 
02519   roundUp = false;
02520   hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
02521 
02522   significand = significandParts();
02523   partsCount = partCount();
02524 
02525   /* +3 because the first digit only uses the single integer bit, so
02526      we have 3 virtual zero most-significant-bits.  */
02527   valueBits = semantics->precision + 3;
02528   shift = integerPartWidth - valueBits % integerPartWidth;
02529 
02530   /* The natural number of digits required ignoring trailing
02531      insignificant zeroes.  */
02532   outputDigits = (valueBits - significandLSB () + 3) / 4;
02533 
02534   /* hexDigits of zero means use the required number for the
02535      precision.  Otherwise, see if we are truncating.  If we are,
02536      find out if we need to round away from zero.  */
02537   if (hexDigits) {
02538     if (hexDigits < outputDigits) {
02539       /* We are dropping non-zero bits, so need to check how to round.
02540          "bits" is the number of dropped bits.  */
02541       unsigned int bits;
02542       lostFraction fraction;
02543 
02544       bits = valueBits - hexDigits * 4;
02545       fraction = lostFractionThroughTruncation (significand, partsCount, bits);
02546       roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
02547     }
02548     outputDigits = hexDigits;
02549   }
02550 
02551   /* Write the digits consecutively, and start writing in the location
02552      of the hexadecimal point.  We move the most significant digit
02553      left and add the hexadecimal point later.  */
02554   p = ++dst;
02555 
02556   count = (valueBits + integerPartWidth - 1) / integerPartWidth;
02557 
02558   while (outputDigits && count) {
02559     integerPart part;
02560 
02561     /* Put the most significant integerPartWidth bits in "part".  */
02562     if (--count == partsCount)
02563       part = 0;  /* An imaginary higher zero part.  */
02564     else
02565       part = significand[count] << shift;
02566 
02567     if (count && shift)
02568       part |= significand[count - 1] >> (integerPartWidth - shift);
02569 
02570     /* Convert as much of "part" to hexdigits as we can.  */
02571     unsigned int curDigits = integerPartWidth / 4;
02572 
02573     if (curDigits > outputDigits)
02574       curDigits = outputDigits;
02575     dst += partAsHex (dst, part, curDigits, hexDigitChars);
02576     outputDigits -= curDigits;
02577   }
02578 
02579   if (roundUp) {
02580     char *q = dst;
02581 
02582     /* Note that hexDigitChars has a trailing '0'.  */
02583     do {
02584       q--;
02585       *q = hexDigitChars[hexDigitValue (*q) + 1];
02586     } while (*q == '0');
02587     assert (q >= p);
02588   } else {
02589     /* Add trailing zeroes.  */
02590     memset (dst, '0', outputDigits);
02591     dst += outputDigits;
02592   }
02593 
02594   /* Move the most significant digit to before the point, and if there
02595      is something after the decimal point add it.  This must come
02596      after rounding above.  */
02597   p[-1] = p[0];
02598   if (dst -1 == p)
02599     dst--;
02600   else
02601     p[0] = '.';
02602 
02603   /* Finally output the exponent.  */
02604   *dst++ = upperCase ? 'P': 'p';
02605 
02606   return writeSignedDecimal (dst, exponent);
02607 }
02608 
02609 // For good performance it is desirable for different APFloats
02610 // to produce different integers.
02611 uint32_t
02612 APFloat::getHashValue() const
02613 {
02614   if (category==fcZero) return sign<<8 | semantics->precision ;
02615   else if (category==fcInfinity) return sign<<9 | semantics->precision;
02616   else if (category==fcNaN) return 1<<10 | semantics->precision;
02617   else {
02618     uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
02619     const integerPart* p = significandParts();
02620     for (int i=partCount(); i>0; i--, p++)
02621       hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
02622     return hash;
02623   }
02624 }
02625 
02626 // Conversion from APFloat to/from host float/double.  It may eventually be
02627 // possible to eliminate these and have everybody deal with APFloats, but that
02628 // will take a while.  This approach will not easily extend to long double.
02629 // Current implementation requires integerPartWidth==64, which is correct at
02630 // the moment but could be made more general.
02631 
02632 // Denormals have exponent minExponent in APFloat, but minExponent-1 in
02633 // the actual IEEE respresentations.  We compensate for that here.
02634 
02635 APInt
02636 APFloat::convertF80LongDoubleAPFloatToAPInt() const
02637 {
02638   assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
02639   assert (partCount()==2);
02640 
02641   uint64_t myexponent, mysignificand;
02642 
02643   if (category==fcNormal) {
02644     myexponent = exponent+16383; //bias
02645     mysignificand = significandParts()[0];
02646     if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
02647       myexponent = 0;   // denormal
02648   } else if (category==fcZero) {
02649     myexponent = 0;
02650     mysignificand = 0;
02651   } else if (category==fcInfinity) {
02652     myexponent = 0x7fff;
02653     mysignificand = 0x8000000000000000ULL;
02654   } else {
02655     assert(category == fcNaN && "Unknown category");
02656     myexponent = 0x7fff;
02657     mysignificand = significandParts()[0];
02658   }
02659 
02660   uint64_t words[2];
02661   words[0] = mysignificand;
02662   words[1] =  ((uint64_t)(sign & 1) << 15) |
02663               (myexponent & 0x7fffLL);
02664   return APInt(80, 2, words);
02665 }
02666 
02667 APInt
02668 APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
02669 {
02670   assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
02671   assert (partCount()==2);
02672 
02673   uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
02674 
02675   if (category==fcNormal) {
02676     myexponent = exponent + 1023; //bias
02677     myexponent2 = exponent2 + 1023;
02678     mysignificand = significandParts()[0];
02679     mysignificand2 = significandParts()[1];
02680     if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
02681       myexponent = 0;   // denormal
02682     if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
02683       myexponent2 = 0;   // denormal
02684   } else if (category==fcZero) {
02685     myexponent = 0;
02686     mysignificand = 0;
02687     myexponent2 = 0;
02688     mysignificand2 = 0;
02689   } else if (category==fcInfinity) {
02690     myexponent = 0x7ff;
02691     myexponent2 = 0;
02692     mysignificand = 0;
02693     mysignificand2 = 0;
02694   } else {
02695     assert(category == fcNaN && "Unknown category");
02696     myexponent = 0x7ff;
02697     mysignificand = significandParts()[0];
02698     myexponent2 = exponent2;
02699     mysignificand2 = significandParts()[1];
02700   }
02701 
02702   uint64_t words[2];
02703   words[0] =  ((uint64_t)(sign & 1) << 63) |
02704               ((myexponent & 0x7ff) <<  52) |
02705               (mysignificand & 0xfffffffffffffLL);
02706   words[1] =  ((uint64_t)(sign2 & 1) << 63) |
02707               ((myexponent2 & 0x7ff) <<  52) |
02708               (mysignificand2 & 0xfffffffffffffLL);
02709   return APInt(128, 2, words);
02710 }
02711 
02712 APInt
02713 APFloat::convertQuadrupleAPFloatToAPInt() const
02714 {
02715   assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
02716   assert (partCount()==2);
02717 
02718   uint64_t myexponent, mysignificand, mysignificand2;
02719 
02720   if (category==fcNormal) {
02721     myexponent = exponent+16383; //bias
02722     mysignificand = significandParts()[0];
02723     mysignificand2 = significandParts()[1];
02724     if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
02725       myexponent = 0;   // denormal
02726   } else if (category==fcZero) {
02727     myexponent = 0;
02728     mysignificand = mysignificand2 = 0;
02729   } else if (category==fcInfinity) {
02730     myexponent = 0x7fff;
02731     mysignificand = mysignificand2 = 0;
02732   } else {
02733     assert(category == fcNaN && "Unknown category!");
02734     myexponent = 0x7fff;
02735     mysignificand = significandParts()[0];
02736     mysignificand2 = significandParts()[1];
02737   }
02738 
02739   uint64_t words[2];
02740   words[0] = mysignificand;
02741   words[1] = ((uint64_t)(sign & 1) << 63) |
02742              ((myexponent & 0x7fff) << 48) |
02743              (mysignificand2 & 0xffffffffffffLL);
02744 
02745   return APInt(128, 2, words);
02746 }
02747 
02748 APInt
02749 APFloat::convertDoubleAPFloatToAPInt() const
02750 {
02751   assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
02752   assert (partCount()==1);
02753 
02754   uint64_t myexponent, mysignificand;
02755 
02756   if (category==fcNormal) {
02757     myexponent = exponent+1023; //bias
02758     mysignificand = *significandParts();
02759     if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
02760       myexponent = 0;   // denormal
02761   } else if (category==fcZero) {
02762     myexponent = 0;
02763     mysignificand = 0;
02764   } else if (category==fcInfinity) {
02765     myexponent = 0x7ff;
02766     mysignificand = 0;
02767   } else {
02768     assert(category == fcNaN && "Unknown category!");
02769     myexponent = 0x7ff;
02770     mysignificand = *significandParts();
02771   }
02772 
02773   return APInt(64, ((((uint64_t)(sign & 1) << 63) |
02774                      ((myexponent & 0x7ff) <<  52) |
02775                      (mysignificand & 0xfffffffffffffLL))));
02776 }
02777 
02778 APInt
02779 APFloat::convertFloatAPFloatToAPInt() const
02780 {
02781   assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
02782   assert (partCount()==1);
02783 
02784   uint32_t myexponent, mysignificand;
02785 
02786   if (category==fcNormal) {
02787     myexponent = exponent+127; //bias
02788     mysignificand = (uint32_t)*significandParts();
02789     if (myexponent == 1 && !(mysignificand & 0x800000))
02790       myexponent = 0;   // denormal
02791   } else if (category==fcZero) {
02792     myexponent = 0;
02793     mysignificand = 0;
02794   } else if (category==fcInfinity) {
02795     myexponent = 0xff;
02796     mysignificand = 0;
02797   } else {
02798     assert(category == fcNaN && "Unknown category!");
02799     myexponent = 0xff;
02800     mysignificand = (uint32_t)*significandParts();
02801   }
02802 
02803   return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
02804                     (mysignificand & 0x7fffff)));
02805 }
02806 
02807 // This function creates an APInt that is just a bit map of the floating
02808 // point constant as it would appear in memory.  It is not a conversion,
02809 // and treating the result as a normal integer is unlikely to be useful.
02810 
02811 APInt
02812 APFloat::bitcastToAPInt() const
02813 {
02814   if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
02815     return convertFloatAPFloatToAPInt();
02816 
02817   if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
02818     return convertDoubleAPFloatToAPInt();
02819 
02820   if (semantics == (const llvm::fltSemantics*)&IEEEquad)
02821     return convertQuadrupleAPFloatToAPInt();
02822 
02823   if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
02824     return convertPPCDoubleDoubleAPFloatToAPInt();
02825 
02826   assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
02827          "unknown format!");
02828   return convertF80LongDoubleAPFloatToAPInt();
02829 }
02830 
02831 float
02832 APFloat::convertToFloat() const
02833 {
02834   assert(semantics == (const llvm::fltSemantics*)&IEEEsingle && "Float semantics are not IEEEsingle");
02835   APInt api = bitcastToAPInt();
02836   return api.bitsToFloat();
02837 }
02838 
02839 double
02840 APFloat::convertToDouble() const
02841 {
02842   assert(semantics == (const llvm::fltSemantics*)&IEEEdouble && "Float semantics are not IEEEdouble");
02843   APInt api = bitcastToAPInt();
02844   return api.bitsToDouble();
02845 }
02846 
02847 /// Integer bit is explicit in this format.  Intel hardware (387 and later)
02848 /// does not support these bit patterns:
02849 ///  exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
02850 ///  exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
02851 ///  exponent = 0, integer bit 1 ("pseudodenormal")
02852 ///  exponent!=0 nor all 1's, integer bit 0 ("unnormal")
02853 /// At the moment, the first two are treated as NaNs, the second two as Normal.
02854 void
02855 APFloat::initFromF80LongDoubleAPInt(const APInt &api)
02856 {
02857   assert(api.getBitWidth()==80);
02858   uint64_t i1 = api.getRawData()[0];
02859   uint64_t i2 = api.getRawData()[1];
02860   uint64_t myexponent = (i2 & 0x7fff);
02861   uint64_t mysignificand = i1;
02862 
02863   initialize(&APFloat::x87DoubleExtended);
02864   assert(partCount()==2);
02865 
02866   sign = static_cast<unsigned int>(i2>>15);
02867   if (myexponent==0 && mysignificand==0) {
02868     // exponent, significand meaningless
02869     category = fcZero;
02870   } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
02871     // exponent, significand meaningless
02872     category = fcInfinity;
02873   } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
02874     // exponent meaningless
02875     category = fcNaN;
02876     significandParts()[0] = mysignificand;
02877     significandParts()[1] = 0;
02878   } else {
02879     category = fcNormal;
02880     exponent = myexponent - 16383;
02881     significandParts()[0] = mysignificand;
02882     significandParts()[1] = 0;
02883     if (myexponent==0)          // denormal
02884       exponent = -16382;
02885   }
02886 }
02887 
02888 void
02889 APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
02890 {
02891   assert(api.getBitWidth()==128);
02892   uint64_t i1 = api.getRawData()[0];
02893   uint64_t i2 = api.getRawData()[1];
02894   uint64_t myexponent = (i1 >> 52) & 0x7ff;
02895   uint64_t mysignificand = i1 & 0xfffffffffffffLL;
02896   uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
02897   uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
02898 
02899   initialize(&APFloat::PPCDoubleDouble);
02900   assert(partCount()==2);
02901 
02902   sign = static_cast<unsigned int>(i1>>63);
02903   sign2 = static_cast<unsigned int>(i2>>63);
02904   if (myexponent==0 && mysignificand==0) {
02905     // exponent, significand meaningless
02906     // exponent2 and significand2 are required to be 0; we don't check
02907     category = fcZero;
02908   } else if (myexponent==0x7ff && mysignificand==0) {
02909     // exponent, significand meaningless
02910     // exponent2 and significand2 are required to be 0; we don't check
02911     category = fcInfinity;
02912   } else if (myexponent==0x7ff && mysignificand!=0) {
02913     // exponent meaningless.  So is the whole second word, but keep it 
02914     // for determinism.
02915     category = fcNaN;
02916     exponent2 = myexponent2;
02917     significandParts()[0] = mysignificand;
02918     significandParts()[1] = mysignificand2;
02919   } else {
02920     category = fcNormal;
02921     // Note there is no category2; the second word is treated as if it is
02922     // fcNormal, although it might be something else considered by itself.
02923     exponent = myexponent - 1023;
02924     exponent2 = myexponent2 - 1023;
02925     significandParts()[0] = mysignificand;
02926     significandParts()[1] = mysignificand2;
02927     if (myexponent==0)          // denormal
02928       exponent = -1022;
02929     else
02930       significandParts()[0] |= 0x10000000000000LL;  // integer bit
02931     if (myexponent2==0) 
02932       exponent2 = -1022;
02933     else
02934       significandParts()[1] |= 0x10000000000000LL;  // integer bit
02935   }
02936 }
02937 
02938 void
02939 APFloat::initFromQuadrupleAPInt(const APInt &api)
02940 {
02941   assert(api.getBitWidth()==128);
02942   uint64_t i1 = api.getRawData()[0];
02943   uint64_t i2 = api.getRawData()[1];
02944   uint64_t myexponent = (i2 >> 48) & 0x7fff;
02945   uint64_t mysignificand  = i1;
02946   uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
02947 
02948   initialize(&APFloat::IEEEquad);
02949   assert(partCount()==2);
02950 
02951   sign = static_cast<unsigned int>(i2>>63);
02952   if (myexponent==0 &&
02953       (mysignificand==0 && mysignificand2==0)) {
02954     // exponent, significand meaningless
02955     category = fcZero;
02956   } else if (myexponent==0x7fff &&
02957              (mysignificand==0 && mysignificand2==0)) {
02958     // exponent, significand meaningless
02959     category = fcInfinity;
02960   } else if (myexponent==0x7fff &&
02961              (mysignificand!=0 || mysignificand2 !=0)) {
02962     // exponent meaningless
02963     category = fcNaN;
02964     significandParts()[0] = mysignificand;
02965     significandParts()[1] = mysignificand2;
02966   } else {
02967     category = fcNormal;
02968     exponent = myexponent - 16383;
02969     significandParts()[0] = mysignificand;
02970     significandParts()[1] = mysignificand2;
02971     if (myexponent==0)          // denormal
02972       exponent = -16382;
02973     else
02974       significandParts()[1] |= 0x1000000000000LL;  // integer bit
02975   }
02976 }
02977 
02978 void
02979 APFloat::initFromDoubleAPInt(const APInt &api)
02980 {
02981   assert(api.getBitWidth()==64);
02982   uint64_t i = *api.getRawData();
02983   uint64_t myexponent = (i >> 52) & 0x7ff;
02984   uint64_t mysignificand = i & 0xfffffffffffffLL;
02985 
02986   initialize(&APFloat::IEEEdouble);
02987   assert(partCount()==1);
02988 
02989   sign = static_cast<unsigned int>(i>>63);
02990   if (myexponent==0 && mysignificand==0) {
02991     // exponent, significand meaningless
02992     category = fcZero;
02993   } else if (myexponent==0x7ff && mysignificand==0) {
02994     // exponent, significand meaningless
02995     category = fcInfinity;
02996   } else if (myexponent==0x7ff && mysignificand!=0) {
02997     // exponent meaningless
02998     category = fcNaN;
02999     *significandParts() = mysignificand;
03000   } else {
03001     category = fcNormal;
03002     exponent = myexponent - 1023;
03003     *significandParts() = mysignificand;
03004     if (myexponent==0)          // denormal
03005       exponent = -1022;
03006     else
03007       *significandParts() |= 0x10000000000000LL;  // integer bit
03008   }
03009 }
03010 
03011 void
03012 APFloat::initFromFloatAPInt(const APInt & api)
03013 {
03014   assert(api.getBitWidth()==32);
03015   uint32_t i = (uint32_t)*api.getRawData();
03016   uint32_t myexponent = (i >> 23) & 0xff;
03017   uint32_t mysignificand = i & 0x7fffff;
03018 
03019   initialize(&APFloat::IEEEsingle);
03020   assert(partCount()==1);
03021 
03022   sign = i >> 31;
03023   if (myexponent==0 && mysignificand==0) {
03024     // exponent, significand meaningless
03025     category = fcZero;
03026   } else if (myexponent==0xff && mysignificand==0) {
03027     // exponent, significand meaningless
03028     category = fcInfinity;
03029   } else if (myexponent==0xff && mysignificand!=0) {
03030     // sign, exponent, significand meaningless
03031     category = fcNaN;
03032     *significandParts() = mysignificand;
03033   } else {
03034     category = fcNormal;
03035     exponent = myexponent - 127;  //bias
03036     *significandParts() = mysignificand;
03037     if (myexponent==0)    // denormal
03038       exponent = -126;
03039     else
03040       *significandParts() |= 0x800000; // integer bit
03041   }
03042 }
03043 
03044 /// Treat api as containing the bits of a floating point number.  Currently
03045 /// we infer the floating point type from the size of the APInt.  The
03046 /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
03047 /// when the size is anything else).
03048 void
03049 APFloat::initFromAPInt(const APInt& api, bool isIEEE)
03050 {
03051   if (api.getBitWidth() == 32)
03052     return initFromFloatAPInt(api);
03053   else if (api.getBitWidth()==64)
03054     return initFromDoubleAPInt(api);
03055   else if (api.getBitWidth()==80)
03056     return initFromF80LongDoubleAPInt(api);
03057   else if (api.getBitWidth()==128)
03058     return (isIEEE ?
03059             initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
03060   else
03061     llvm_unreachable(0);
03062 }
03063 
03064 APFloat::APFloat(const APInt& api, bool isIEEE)
03065 {
03066   initFromAPInt(api, isIEEE);
03067 }
03068 
03069 APFloat::APFloat(float f)
03070 {
03071   APInt api = APInt(32, 0);
03072   initFromAPInt(api.floatToBits(f));
03073 }
03074 
03075 APFloat::APFloat(double d)
03076 {
03077   APInt api = APInt(64, 0);
03078   initFromAPInt(api.doubleToBits(d));
03079 }