LLVM API Documentation

APInt.cpp

Go to the documentation of this file.
00001 //===-- APInt.cpp - Implement APInt 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 integer
00011 // constant values and provide a variety of arithmetic operations on them.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "apint"
00016 #include "llvm/ADT/APInt.h"
00017 #include "llvm/ADT/FoldingSet.h"
00018 #include "llvm/ADT/SmallString.h"
00019 #include "llvm/Support/Debug.h"
00020 #include "llvm/Support/MathExtras.h"
00021 #include "llvm/Support/raw_ostream.h"
00022 #include <cmath>
00023 #include <limits>
00024 #include <cstring>
00025 #include <cstdlib>
00026 using namespace llvm;
00027 
00028 /// A utility function for allocating memory, checking for allocation failures,
00029 /// and ensuring the contents are zeroed.
00030 inline static uint64_t* getClearedMemory(unsigned numWords) {
00031   uint64_t * result = new uint64_t[numWords];
00032   assert(result && "APInt memory allocation fails!");
00033   memset(result, 0, numWords * sizeof(uint64_t));
00034   return result;
00035 }
00036 
00037 /// A utility function for allocating memory and checking for allocation 
00038 /// failure.  The content is not zeroed.
00039 inline static uint64_t* getMemory(unsigned numWords) {
00040   uint64_t * result = new uint64_t[numWords];
00041   assert(result && "APInt memory allocation fails!");
00042   return result;
00043 }
00044 
00045 void APInt::initSlowCase(unsigned numBits, uint64_t val, bool isSigned) {
00046   pVal = getClearedMemory(getNumWords());
00047   pVal[0] = val;
00048   if (isSigned && int64_t(val) < 0) 
00049     for (unsigned i = 1; i < getNumWords(); ++i)
00050       pVal[i] = -1ULL;
00051 }
00052 
00053 void APInt::initSlowCase(const APInt& that) {
00054   pVal = getMemory(getNumWords());
00055   memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
00056 }
00057 
00058 
00059 APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
00060   : BitWidth(numBits), VAL(0) {
00061   assert(BitWidth && "bitwidth too small");
00062   assert(bigVal && "Null pointer detected!");
00063   if (isSingleWord())
00064     VAL = bigVal[0];
00065   else {
00066     // Get memory, cleared to 0
00067     pVal = getClearedMemory(getNumWords());
00068     // Calculate the number of words to copy
00069     unsigned words = std::min<unsigned>(numWords, getNumWords());
00070     // Copy the words from bigVal to pVal
00071     memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
00072   }
00073   // Make sure unused high bits are cleared
00074   clearUnusedBits();
00075 }
00076 
00077 APInt::APInt(unsigned numbits, const char StrStart[], unsigned slen,
00078              uint8_t radix) 
00079   : BitWidth(numbits), VAL(0) {
00080   assert(BitWidth && "bitwidth too small");
00081   fromString(numbits, StrStart, slen, radix);
00082 }
00083 
00084 APInt& APInt::AssignSlowCase(const APInt& RHS) {
00085   // Don't do anything for X = X
00086   if (this == &RHS)
00087     return *this;
00088 
00089   if (BitWidth == RHS.getBitWidth()) {
00090     // assume same bit-width single-word case is already handled
00091     assert(!isSingleWord());
00092     memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
00093     return *this;
00094   }
00095 
00096   if (isSingleWord()) {
00097     // assume case where both are single words is already handled
00098     assert(!RHS.isSingleWord());
00099     VAL = 0;
00100     pVal = getMemory(RHS.getNumWords());
00101     memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
00102   } else if (getNumWords() == RHS.getNumWords()) 
00103     memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
00104   else if (RHS.isSingleWord()) {
00105     delete [] pVal;
00106     VAL = RHS.VAL;
00107   } else {
00108     delete [] pVal;
00109     pVal = getMemory(RHS.getNumWords());
00110     memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
00111   }
00112   BitWidth = RHS.BitWidth;
00113   return clearUnusedBits();
00114 }
00115 
00116 APInt& APInt::operator=(uint64_t RHS) {
00117   if (isSingleWord()) 
00118     VAL = RHS;
00119   else {
00120     pVal[0] = RHS;
00121     memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
00122   }
00123   return clearUnusedBits();
00124 }
00125 
00126 /// Profile - This method 'profiles' an APInt for use with FoldingSet.
00127 void APInt::Profile(FoldingSetNodeID& ID) const {
00128   ID.AddInteger(BitWidth);
00129   
00130   if (isSingleWord()) {
00131     ID.AddInteger(VAL);
00132     return;
00133   }
00134 
00135   unsigned NumWords = getNumWords();
00136   for (unsigned i = 0; i < NumWords; ++i)
00137     ID.AddInteger(pVal[i]);
00138 }
00139 
00140 /// add_1 - This function adds a single "digit" integer, y, to the multiple 
00141 /// "digit" integer array,  x[]. x[] is modified to reflect the addition and
00142 /// 1 is returned if there is a carry out, otherwise 0 is returned.
00143 /// @returns the carry of the addition.
00144 static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
00145   for (unsigned i = 0; i < len; ++i) {
00146     dest[i] = y + x[i];
00147     if (dest[i] < y)
00148       y = 1; // Carry one to next digit.
00149     else {
00150       y = 0; // No need to carry so exit early
00151       break;
00152     }
00153   }
00154   return y;
00155 }
00156 
00157 /// @brief Prefix increment operator. Increments the APInt by one.
00158 APInt& APInt::operator++() {
00159   if (isSingleWord()) 
00160     ++VAL;
00161   else
00162     add_1(pVal, pVal, getNumWords(), 1);
00163   return clearUnusedBits();
00164 }
00165 
00166 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from 
00167 /// the multi-digit integer array, x[], propagating the borrowed 1 value until 
00168 /// no further borrowing is neeeded or it runs out of "digits" in x.  The result
00169 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
00170 /// In other words, if y > x then this function returns 1, otherwise 0.
00171 /// @returns the borrow out of the subtraction
00172 static bool sub_1(uint64_t x[], unsigned len, uint64_t y) {
00173   for (unsigned i = 0; i < len; ++i) {
00174     uint64_t X = x[i];
00175     x[i] -= y;
00176     if (y > X) 
00177       y = 1;  // We have to "borrow 1" from next "digit"
00178     else {
00179       y = 0;  // No need to borrow
00180       break;  // Remaining digits are unchanged so exit early
00181     }
00182   }
00183   return bool(y);
00184 }
00185 
00186 /// @brief Prefix decrement operator. Decrements the APInt by one.
00187 APInt& APInt::operator--() {
00188   if (isSingleWord()) 
00189     --VAL;
00190   else
00191     sub_1(pVal, getNumWords(), 1);
00192   return clearUnusedBits();
00193 }
00194 
00195 /// add - This function adds the integer array x to the integer array Y and
00196 /// places the result in dest. 
00197 /// @returns the carry out from the addition
00198 /// @brief General addition of 64-bit integer arrays
00199 static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y, 
00200                 unsigned len) {
00201   bool carry = false;
00202   for (unsigned i = 0; i< len; ++i) {
00203     uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
00204     dest[i] = x[i] + y[i] + carry;
00205     carry = dest[i] < limit || (carry && dest[i] == limit);
00206   }
00207   return carry;
00208 }
00209 
00210 /// Adds the RHS APint to this APInt.
00211 /// @returns this, after addition of RHS.
00212 /// @brief Addition assignment operator. 
00213 APInt& APInt::operator+=(const APInt& RHS) {
00214   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00215   if (isSingleWord()) 
00216     VAL += RHS.VAL;
00217   else {
00218     add(pVal, pVal, RHS.pVal, getNumWords());
00219   }
00220   return clearUnusedBits();
00221 }
00222 
00223 /// Subtracts the integer array y from the integer array x 
00224 /// @returns returns the borrow out.
00225 /// @brief Generalized subtraction of 64-bit integer arrays.
00226 static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y, 
00227                 unsigned len) {
00228   bool borrow = false;
00229   for (unsigned i = 0; i < len; ++i) {
00230     uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
00231     borrow = y[i] > x_tmp || (borrow && x[i] == 0);
00232     dest[i] = x_tmp - y[i];
00233   }
00234   return borrow;
00235 }
00236 
00237 /// Subtracts the RHS APInt from this APInt
00238 /// @returns this, after subtraction
00239 /// @brief Subtraction assignment operator. 
00240 APInt& APInt::operator-=(const APInt& RHS) {
00241   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00242   if (isSingleWord()) 
00243     VAL -= RHS.VAL;
00244   else
00245     sub(pVal, pVal, RHS.pVal, getNumWords());
00246   return clearUnusedBits();
00247 }
00248 
00249 /// Multiplies an integer array, x by a a uint64_t integer and places the result
00250 /// into dest. 
00251 /// @returns the carry out of the multiplication.
00252 /// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
00253 static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
00254   // Split y into high 32-bit part (hy)  and low 32-bit part (ly)
00255   uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
00256   uint64_t carry = 0;
00257 
00258   // For each digit of x.
00259   for (unsigned i = 0; i < len; ++i) {
00260     // Split x into high and low words
00261     uint64_t lx = x[i] & 0xffffffffULL;
00262     uint64_t hx = x[i] >> 32;
00263     // hasCarry - A flag to indicate if there is a carry to the next digit.
00264     // hasCarry == 0, no carry
00265     // hasCarry == 1, has carry
00266     // hasCarry == 2, no carry and the calculation result == 0.
00267     uint8_t hasCarry = 0;
00268     dest[i] = carry + lx * ly;
00269     // Determine if the add above introduces carry.
00270     hasCarry = (dest[i] < carry) ? 1 : 0;
00271     carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
00272     // The upper limit of carry can be (2^32 - 1)(2^32 - 1) + 
00273     // (2^32 - 1) + 2^32 = 2^64.
00274     hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
00275 
00276     carry += (lx * hy) & 0xffffffffULL;
00277     dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
00278     carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) + 
00279             (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
00280   }
00281   return carry;
00282 }
00283 
00284 /// Multiplies integer array x by integer array y and stores the result into 
00285 /// the integer array dest. Note that dest's size must be >= xlen + ylen.
00286 /// @brief Generalized multiplicate of integer arrays.
00287 static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
00288                 unsigned ylen) {
00289   dest[xlen] = mul_1(dest, x, xlen, y[0]);
00290   for (unsigned i = 1; i < ylen; ++i) {
00291     uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
00292     uint64_t carry = 0, lx = 0, hx = 0;
00293     for (unsigned j = 0; j < xlen; ++j) {
00294       lx = x[j] & 0xffffffffULL;
00295       hx = x[j] >> 32;
00296       // hasCarry - A flag to indicate if has carry.
00297       // hasCarry == 0, no carry
00298       // hasCarry == 1, has carry
00299       // hasCarry == 2, no carry and the calculation result == 0.
00300       uint8_t hasCarry = 0;
00301       uint64_t resul = carry + lx * ly;
00302       hasCarry = (resul < carry) ? 1 : 0;
00303       carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
00304       hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
00305 
00306       carry += (lx * hy) & 0xffffffffULL;
00307       resul = (carry << 32) | (resul & 0xffffffffULL);
00308       dest[i+j] += resul;
00309       carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
00310               (carry >> 32) + (dest[i+j] < resul ? 1 : 0) + 
00311               ((lx * hy) >> 32) + hx * hy;
00312     }
00313     dest[i+xlen] = carry;
00314   }
00315 }
00316 
00317 APInt& APInt::operator*=(const APInt& RHS) {
00318   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00319   if (isSingleWord()) {
00320     VAL *= RHS.VAL;
00321     clearUnusedBits();
00322     return *this;
00323   }
00324 
00325   // Get some bit facts about LHS and check for zero
00326   unsigned lhsBits = getActiveBits();
00327   unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
00328   if (!lhsWords) 
00329     // 0 * X ===> 0
00330     return *this;
00331 
00332   // Get some bit facts about RHS and check for zero
00333   unsigned rhsBits = RHS.getActiveBits();
00334   unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
00335   if (!rhsWords) {
00336     // X * 0 ===> 0
00337     clear();
00338     return *this;
00339   }
00340 
00341   // Allocate space for the result
00342   unsigned destWords = rhsWords + lhsWords;
00343   uint64_t *dest = getMemory(destWords);
00344 
00345   // Perform the long multiply
00346   mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
00347 
00348   // Copy result back into *this
00349   clear();
00350   unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
00351   memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
00352 
00353   // delete dest array and return
00354   delete[] dest;
00355   return *this;
00356 }
00357 
00358 APInt& APInt::operator&=(const APInt& RHS) {
00359   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00360   if (isSingleWord()) {
00361     VAL &= RHS.VAL;
00362     return *this;
00363   }
00364   unsigned numWords = getNumWords();
00365   for (unsigned i = 0; i < numWords; ++i)
00366     pVal[i] &= RHS.pVal[i];
00367   return *this;
00368 }
00369 
00370 APInt& APInt::operator|=(const APInt& RHS) {
00371   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00372   if (isSingleWord()) {
00373     VAL |= RHS.VAL;
00374     return *this;
00375   }
00376   unsigned numWords = getNumWords();
00377   for (unsigned i = 0; i < numWords; ++i)
00378     pVal[i] |= RHS.pVal[i];
00379   return *this;
00380 }
00381 
00382 APInt& APInt::operator^=(const APInt& RHS) {
00383   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00384   if (isSingleWord()) {
00385     VAL ^= RHS.VAL;
00386     this->clearUnusedBits();
00387     return *this;
00388   } 
00389   unsigned numWords = getNumWords();
00390   for (unsigned i = 0; i < numWords; ++i)
00391     pVal[i] ^= RHS.pVal[i];
00392   return clearUnusedBits();
00393 }
00394 
00395 APInt APInt::AndSlowCase(const APInt& RHS) const {
00396   unsigned numWords = getNumWords();
00397   uint64_t* val = getMemory(numWords);
00398   for (unsigned i = 0; i < numWords; ++i)
00399     val[i] = pVal[i] & RHS.pVal[i];
00400   return APInt(val, getBitWidth());
00401 }
00402 
00403 APInt APInt::OrSlowCase(const APInt& RHS) const {
00404   unsigned numWords = getNumWords();
00405   uint64_t *val = getMemory(numWords);
00406   for (unsigned i = 0; i < numWords; ++i)
00407     val[i] = pVal[i] | RHS.pVal[i];
00408   return APInt(val, getBitWidth());
00409 }
00410 
00411 APInt APInt::XorSlowCase(const APInt& RHS) const {
00412   unsigned numWords = getNumWords();
00413   uint64_t *val = getMemory(numWords);
00414   for (unsigned i = 0; i < numWords; ++i)
00415     val[i] = pVal[i] ^ RHS.pVal[i];
00416 
00417   // 0^0==1 so clear the high bits in case they got set.
00418   return APInt(val, getBitWidth()).clearUnusedBits();
00419 }
00420 
00421 bool APInt::operator !() const {
00422   if (isSingleWord())
00423     return !VAL;
00424 
00425   for (unsigned i = 0; i < getNumWords(); ++i)
00426     if (pVal[i]) 
00427       return false;
00428   return true;
00429 }
00430 
00431 APInt APInt::operator*(const APInt& RHS) const {
00432   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00433   if (isSingleWord())
00434     return APInt(BitWidth, VAL * RHS.VAL);
00435   APInt Result(*this);
00436   Result *= RHS;
00437   return Result.clearUnusedBits();
00438 }
00439 
00440 APInt APInt::operator+(const APInt& RHS) const {
00441   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00442   if (isSingleWord())
00443     return APInt(BitWidth, VAL + RHS.VAL);
00444   APInt Result(BitWidth, 0);
00445   add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
00446   return Result.clearUnusedBits();
00447 }
00448 
00449 APInt APInt::operator-(const APInt& RHS) const {
00450   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00451   if (isSingleWord())
00452     return APInt(BitWidth, VAL - RHS.VAL);
00453   APInt Result(BitWidth, 0);
00454   sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
00455   return Result.clearUnusedBits();
00456 }
00457 
00458 bool APInt::operator[](unsigned bitPosition) const {
00459   return (maskBit(bitPosition) & 
00460           (isSingleWord() ?  VAL : pVal[whichWord(bitPosition)])) != 0;
00461 }
00462 
00463 bool APInt::EqualSlowCase(const APInt& RHS) const {
00464   // Get some facts about the number of bits used in the two operands.
00465   unsigned n1 = getActiveBits();
00466   unsigned n2 = RHS.getActiveBits();
00467 
00468   // If the number of bits isn't the same, they aren't equal
00469   if (n1 != n2) 
00470     return false;
00471 
00472   // If the number of bits fits in a word, we only need to compare the low word.
00473   if (n1 <= APINT_BITS_PER_WORD)
00474     return pVal[0] == RHS.pVal[0];
00475 
00476   // Otherwise, compare everything
00477   for (int i = whichWord(n1 - 1); i >= 0; --i)
00478     if (pVal[i] != RHS.pVal[i]) 
00479       return false;
00480   return true;
00481 }
00482 
00483 bool APInt::EqualSlowCase(uint64_t Val) const {
00484   unsigned n = getActiveBits();
00485   if (n <= APINT_BITS_PER_WORD)
00486     return pVal[0] == Val;
00487   else
00488     return false;
00489 }
00490 
00491 bool APInt::ult(const APInt& RHS) const {
00492   assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
00493   if (isSingleWord())
00494     return VAL < RHS.VAL;
00495 
00496   // Get active bit length of both operands
00497   unsigned n1 = getActiveBits();
00498   unsigned n2 = RHS.getActiveBits();
00499 
00500   // If magnitude of LHS is less than RHS, return true.
00501   if (n1 < n2)
00502     return true;
00503 
00504   // If magnitude of RHS is greather than LHS, return false.
00505   if (n2 < n1)
00506     return false;
00507 
00508   // If they bot fit in a word, just compare the low order word
00509   if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
00510     return pVal[0] < RHS.pVal[0];
00511 
00512   // Otherwise, compare all words
00513   unsigned topWord = whichWord(std::max(n1,n2)-1);
00514   for (int i = topWord; i >= 0; --i) {
00515     if (pVal[i] > RHS.pVal[i]) 
00516       return false;
00517     if (pVal[i] < RHS.pVal[i]) 
00518       return true;
00519   }
00520   return false;
00521 }
00522 
00523 bool APInt::slt(const APInt& RHS) const {
00524   assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
00525   if (isSingleWord()) {
00526     int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
00527     int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
00528     return lhsSext < rhsSext;
00529   }
00530 
00531   APInt lhs(*this);
00532   APInt rhs(RHS);
00533   bool lhsNeg = isNegative();
00534   bool rhsNeg = rhs.isNegative();
00535   if (lhsNeg) {
00536     // Sign bit is set so perform two's complement to make it positive
00537     lhs.flip();
00538     lhs++;
00539   }
00540   if (rhsNeg) {
00541     // Sign bit is set so perform two's complement to make it positive
00542     rhs.flip();
00543     rhs++;
00544   }
00545 
00546   // Now we have unsigned values to compare so do the comparison if necessary
00547   // based on the negativeness of the values.
00548   if (lhsNeg)
00549     if (rhsNeg)
00550       return lhs.ugt(rhs);
00551     else
00552       return true;
00553   else if (rhsNeg)
00554     return false;
00555   else 
00556     return lhs.ult(rhs);
00557 }
00558 
00559 APInt& APInt::set(unsigned bitPosition) {
00560   if (isSingleWord()) 
00561     VAL |= maskBit(bitPosition);
00562   else 
00563     pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
00564   return *this;
00565 }
00566 
00567 /// Set the given bit to 0 whose position is given as "bitPosition".
00568 /// @brief Set a given bit to 0.
00569 APInt& APInt::clear(unsigned bitPosition) {
00570   if (isSingleWord()) 
00571     VAL &= ~maskBit(bitPosition);
00572   else 
00573     pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
00574   return *this;
00575 }
00576 
00577 /// @brief Toggle every bit to its opposite value.
00578 
00579 /// Toggle a given bit to its opposite value whose position is given 
00580 /// as "bitPosition".
00581 /// @brief Toggles a given bit to its opposite value.
00582 APInt& APInt::flip(unsigned bitPosition) {
00583   assert(bitPosition < BitWidth && "Out of the bit-width range!");
00584   if ((*this)[bitPosition]) clear(bitPosition);
00585   else set(bitPosition);
00586   return *this;
00587 }
00588 
00589 unsigned APInt::getBitsNeeded(const char* str, unsigned slen, uint8_t radix) {
00590   assert(str != 0 && "Invalid value string");
00591   assert(slen > 0 && "Invalid string length");
00592 
00593   // Each computation below needs to know if its negative
00594   unsigned isNegative = str[0] == '-';
00595   if (isNegative) {
00596     slen--;
00597     str++;
00598   }
00599   // For radixes of power-of-two values, the bits required is accurately and
00600   // easily computed
00601   if (radix == 2)
00602     return slen + isNegative;
00603   if (radix == 8)
00604     return slen * 3 + isNegative;
00605   if (radix == 16)
00606     return slen * 4 + isNegative;
00607 
00608   // Otherwise it must be radix == 10, the hard case
00609   assert(radix == 10 && "Invalid radix");
00610 
00611   // This is grossly inefficient but accurate. We could probably do something
00612   // with a computation of roughly slen*64/20 and then adjust by the value of
00613   // the first few digits. But, I'm not sure how accurate that could be.
00614 
00615   // Compute a sufficient number of bits that is always large enough but might
00616   // be too large. This avoids the assertion in the constructor.
00617   unsigned sufficient = slen*64/18;
00618 
00619   // Convert to the actual binary value.
00620   APInt tmp(sufficient, str, slen, radix);
00621 
00622   // Compute how many bits are required.
00623   return isNegative + tmp.logBase2() + 1;
00624 }
00625 
00626 uint64_t APInt::getHashValue() const {
00627   // Put the bit width into the low order bits.
00628   uint64_t hash = BitWidth;
00629 
00630   // Add the sum of the words to the hash.
00631   if (isSingleWord())
00632     hash += VAL << 6; // clear separation of up to 64 bits
00633   else
00634     for (unsigned i = 0; i < getNumWords(); ++i)
00635       hash += pVal[i] << 6; // clear sepration of up to 64 bits
00636   return hash;
00637 }
00638 
00639 /// HiBits - This function returns the high "numBits" bits of this APInt.
00640 APInt APInt::getHiBits(unsigned numBits) const {
00641   return APIntOps::lshr(*this, BitWidth - numBits);
00642 }
00643 
00644 /// LoBits - This function returns the low "numBits" bits of this APInt.
00645 APInt APInt::getLoBits(unsigned numBits) const {
00646   return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits), 
00647                         BitWidth - numBits);
00648 }
00649 
00650 bool APInt::isPowerOf2() const {
00651   return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
00652 }
00653 
00654 unsigned APInt::countLeadingZerosSlowCase() const {
00655   unsigned Count = 0;
00656   for (unsigned i = getNumWords(); i > 0u; --i) {
00657     if (pVal[i-1] == 0)
00658       Count += APINT_BITS_PER_WORD;
00659     else {
00660       Count += CountLeadingZeros_64(pVal[i-1]);
00661       break;
00662     }
00663   }
00664   unsigned remainder = BitWidth % APINT_BITS_PER_WORD;
00665   if (remainder)
00666     Count -= APINT_BITS_PER_WORD - remainder;
00667   return std::min(Count, BitWidth);
00668 }
00669 
00670 static unsigned countLeadingOnes_64(uint64_t V, unsigned skip) {
00671   unsigned Count = 0;
00672   if (skip)
00673     V <<= skip;
00674   while (V && (V & (1ULL << 63))) {
00675     Count++;
00676     V <<= 1;
00677   }
00678   return Count;
00679 }
00680 
00681 unsigned APInt::countLeadingOnes() const {
00682   if (isSingleWord())
00683     return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth);
00684 
00685   unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
00686   unsigned shift;
00687   if (!highWordBits) {
00688     highWordBits = APINT_BITS_PER_WORD;
00689     shift = 0;
00690   } else {
00691     shift = APINT_BITS_PER_WORD - highWordBits;
00692   }
00693   int i = getNumWords() - 1;
00694   unsigned Count = countLeadingOnes_64(pVal[i], shift);
00695   if (Count == highWordBits) {
00696     for (i--; i >= 0; --i) {
00697       if (pVal[i] == -1ULL)
00698         Count += APINT_BITS_PER_WORD;
00699       else {
00700         Count += countLeadingOnes_64(pVal[i], 0);
00701         break;
00702       }
00703     }
00704   }
00705   return Count;
00706 }
00707 
00708 unsigned APInt::countTrailingZeros() const {
00709   if (isSingleWord())
00710     return std::min(unsigned(CountTrailingZeros_64(VAL)), BitWidth);
00711   unsigned Count = 0;
00712   unsigned i = 0;
00713   for (; i < getNumWords() && pVal[i] == 0; ++i)
00714     Count += APINT_BITS_PER_WORD;
00715   if (i < getNumWords())
00716     Count += CountTrailingZeros_64(pVal[i]);
00717   return std::min(Count, BitWidth);
00718 }
00719 
00720 unsigned APInt::countTrailingOnesSlowCase() const {
00721   unsigned Count = 0;
00722   unsigned i = 0;
00723   for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
00724     Count += APINT_BITS_PER_WORD;
00725   if (i < getNumWords())
00726     Count += CountTrailingOnes_64(pVal[i]);
00727   return std::min(Count, BitWidth);
00728 }
00729 
00730 unsigned APInt::countPopulationSlowCase() const {
00731   unsigned Count = 0;
00732   for (unsigned i = 0; i < getNumWords(); ++i)
00733     Count += CountPopulation_64(pVal[i]);
00734   return Count;
00735 }
00736 
00737 APInt APInt::byteSwap() const {
00738   assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
00739   if (BitWidth == 16)
00740     return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
00741   else if (BitWidth == 32)
00742     return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
00743   else if (BitWidth == 48) {
00744     unsigned Tmp1 = unsigned(VAL >> 16);
00745     Tmp1 = ByteSwap_32(Tmp1);
00746     uint16_t Tmp2 = uint16_t(VAL);
00747     Tmp2 = ByteSwap_16(Tmp2);
00748     return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
00749   } else if (BitWidth == 64)
00750     return APInt(BitWidth, ByteSwap_64(VAL));
00751   else {
00752     APInt Result(BitWidth, 0);
00753     char *pByte = (char*)Result.pVal;
00754     for (unsigned i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
00755       char Tmp = pByte[i];
00756       pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
00757       pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
00758     }
00759     return Result;
00760   }
00761 }
00762 
00763 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1, 
00764                                             const APInt& API2) {
00765   APInt A = API1, B = API2;
00766   while (!!B) {
00767     APInt T = B;
00768     B = APIntOps::urem(A, B);
00769     A = T;
00770   }
00771   return A;
00772 }
00773 
00774 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
00775   union {
00776     double D;
00777     uint64_t I;
00778   } T;
00779   T.D = Double;
00780 
00781   // Get the sign bit from the highest order bit
00782   bool isNeg = T.I >> 63;
00783 
00784   // Get the 11-bit exponent and adjust for the 1023 bit bias
00785   int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
00786 
00787   // If the exponent is negative, the value is < 0 so just return 0.
00788   if (exp < 0)
00789     return APInt(width, 0u);
00790 
00791   // Extract the mantissa by clearing the top 12 bits (sign + exponent).
00792   uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
00793 
00794   // If the exponent doesn't shift all bits out of the mantissa
00795   if (exp < 52)
00796     return isNeg ? -APInt(width, mantissa >> (52 - exp)) : 
00797                     APInt(width, mantissa >> (52 - exp));
00798 
00799   // If the client didn't provide enough bits for us to shift the mantissa into
00800   // then the result is undefined, just return 0
00801   if (width <= exp - 52)
00802     return APInt(width, 0);
00803 
00804   // Otherwise, we have to shift the mantissa bits up to the right location
00805   APInt Tmp(width, mantissa);
00806   Tmp = Tmp.shl((unsigned)exp - 52);
00807   return isNeg ? -Tmp : Tmp;
00808 }
00809 
00810 /// RoundToDouble - This function convert this APInt to a double.
00811 /// The layout for double is as following (IEEE Standard 754):
00812 ///  --------------------------------------
00813 /// |  Sign    Exponent    Fraction    Bias |
00814 /// |-------------------------------------- |
00815 /// |  1[63]   11[62-52]   52[51-00]   1023 |
00816 ///  -------------------------------------- 
00817 double APInt::roundToDouble(bool isSigned) const {
00818 
00819   // Handle the simple case where the value is contained in one uint64_t.
00820   if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
00821     if (isSigned) {
00822       int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
00823       return double(sext);
00824     } else
00825       return double(VAL);
00826   }
00827 
00828   // Determine if the value is negative.
00829   bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
00830 
00831   // Construct the absolute value if we're negative.
00832   APInt Tmp(isNeg ? -(*this) : (*this));
00833 
00834   // Figure out how many bits we're using.
00835   unsigned n = Tmp.getActiveBits();
00836 
00837   // The exponent (without bias normalization) is just the number of bits
00838   // we are using. Note that the sign bit is gone since we constructed the
00839   // absolute value.
00840   uint64_t exp = n;
00841 
00842   // Return infinity for exponent overflow
00843   if (exp > 1023) {
00844     if (!isSigned || !isNeg)
00845       return std::numeric_limits<double>::infinity();
00846     else 
00847       return -std::numeric_limits<double>::infinity();
00848   }
00849   exp += 1023; // Increment for 1023 bias
00850 
00851   // Number of bits in mantissa is 52. To obtain the mantissa value, we must
00852   // extract the high 52 bits from the correct words in pVal.
00853   uint64_t mantissa;
00854   unsigned hiWord = whichWord(n-1);
00855   if (hiWord == 0) {
00856     mantissa = Tmp.pVal[0];
00857     if (n > 52)
00858       mantissa >>= n - 52; // shift down, we want the top 52 bits.
00859   } else {
00860     assert(hiWord > 0 && "huh?");
00861     uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
00862     uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
00863     mantissa = hibits | lobits;
00864   }
00865 
00866   // The leading bit of mantissa is implicit, so get rid of it.
00867   uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
00868   union {
00869     double D;
00870     uint64_t I;
00871   } T;
00872   T.I = sign | (exp << 52) | mantissa;
00873   return T.D;
00874 }
00875 
00876 // Truncate to new width.
00877 APInt &APInt::trunc(unsigned width) {
00878   assert(width < BitWidth && "Invalid APInt Truncate request");
00879   assert(width && "Can't truncate to 0 bits");
00880   unsigned wordsBefore = getNumWords();
00881   BitWidth = width;
00882   unsigned wordsAfter = getNumWords();
00883   if (wordsBefore != wordsAfter) {
00884     if (wordsAfter == 1) {
00885       uint64_t *tmp = pVal;
00886       VAL = pVal[0];
00887       delete [] tmp;
00888     } else {
00889       uint64_t *newVal = getClearedMemory(wordsAfter);
00890       for (unsigned i = 0; i < wordsAfter; ++i)
00891         newVal[i] = pVal[i];
00892       delete [] pVal;
00893       pVal = newVal;
00894     }
00895   }
00896   return clearUnusedBits();
00897 }
00898 
00899 // Sign extend to a new width.
00900 APInt &APInt::sext(unsigned width) {
00901   assert(width > BitWidth && "Invalid APInt SignExtend request");
00902   // If the sign bit isn't set, this is the same as zext.
00903   if (!isNegative()) {
00904     zext(width);
00905     return *this;
00906   }
00907 
00908   // The sign bit is set. First, get some facts
00909   unsigned wordsBefore = getNumWords();
00910   unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
00911   BitWidth = width;
00912   unsigned wordsAfter = getNumWords();
00913 
00914   // Mask the high order word appropriately
00915   if (wordsBefore == wordsAfter) {
00916     unsigned newWordBits = width % APINT_BITS_PER_WORD;
00917     // The extension is contained to the wordsBefore-1th word.
00918     uint64_t mask = ~0ULL;
00919     if (newWordBits)
00920       mask >>= APINT_BITS_PER_WORD - newWordBits;
00921     mask <<= wordBits;
00922     if (wordsBefore == 1)
00923       VAL |= mask;
00924     else
00925       pVal[wordsBefore-1] |= mask;
00926     return clearUnusedBits();
00927   }
00928 
00929   uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
00930   uint64_t *newVal = getMemory(wordsAfter);
00931   if (wordsBefore == 1)
00932     newVal[0] = VAL | mask;
00933   else {
00934     for (unsigned i = 0; i < wordsBefore; ++i)
00935       newVal[i] = pVal[i];
00936     newVal[wordsBefore-1] |= mask;
00937   }
00938   for (unsigned i = wordsBefore; i < wordsAfter; i++)
00939     newVal[i] = -1ULL;
00940   if (wordsBefore != 1)
00941     delete [] pVal;
00942   pVal = newVal;
00943   return clearUnusedBits();
00944 }
00945 
00946 //  Zero extend to a new width.
00947 APInt &APInt::zext(unsigned width) {
00948   assert(width > BitWidth && "Invalid APInt ZeroExtend request");
00949   unsigned wordsBefore = getNumWords();
00950   BitWidth = width;
00951   unsigned wordsAfter = getNumWords();
00952   if (wordsBefore != wordsAfter) {
00953     uint64_t *newVal = getClearedMemory(wordsAfter);
00954     if (wordsBefore == 1)
00955       newVal[0] = VAL;
00956     else 
00957       for (unsigned i = 0; i < wordsBefore; ++i)
00958         newVal[i] = pVal[i];
00959     if (wordsBefore != 1)
00960       delete [] pVal;
00961     pVal = newVal;
00962   }
00963   return *this;
00964 }
00965 
00966 APInt &APInt::zextOrTrunc(unsigned width) {
00967   if (BitWidth < width)
00968     return zext(width);
00969   if (BitWidth > width)
00970     return trunc(width);
00971   return *this;
00972 }
00973 
00974 APInt &APInt::sextOrTrunc(unsigned width) {
00975   if (BitWidth < width)
00976     return sext(width);
00977   if (BitWidth > width)
00978     return trunc(width);
00979   return *this;
00980 }
00981 
00982 /// Arithmetic right-shift this APInt by shiftAmt.
00983 /// @brief Arithmetic right-shift function.
00984 APInt APInt::ashr(const APInt &shiftAmt) const {
00985   return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
00986 }
00987 
00988 /// Arithmetic right-shift this APInt by shiftAmt.
00989 /// @brief Arithmetic right-shift function.
00990 APInt APInt::ashr(unsigned shiftAmt) const {
00991   assert(shiftAmt <= BitWidth && "Invalid shift amount");
00992   // Handle a degenerate case
00993   if (shiftAmt == 0)
00994     return *this;
00995 
00996   // Handle single word shifts with built-in ashr
00997   if (isSingleWord()) {
00998     if (shiftAmt == BitWidth)
00999       return APInt(BitWidth, 0); // undefined
01000     else {
01001       unsigned SignBit = APINT_BITS_PER_WORD - BitWidth;
01002       return APInt(BitWidth, 
01003         (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
01004     }
01005   }
01006 
01007   // If all the bits were shifted out, the result is, technically, undefined.
01008   // We return -1 if it was negative, 0 otherwise. We check this early to avoid
01009   // issues in the algorithm below.
01010   if (shiftAmt == BitWidth) {
01011     if (isNegative())
01012       return APInt(BitWidth, -1ULL, true);
01013     else
01014       return APInt(BitWidth, 0);
01015   }
01016 
01017   // Create some space for the result.
01018   uint64_t * val = new uint64_t[getNumWords()];
01019 
01020   // Compute some values needed by the following shift algorithms
01021   unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
01022   unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
01023   unsigned breakWord = getNumWords() - 1 - offset; // last word affected
01024   unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
01025   if (bitsInWord == 0)
01026     bitsInWord = APINT_BITS_PER_WORD;
01027 
01028   // If we are shifting whole words, just move whole words
01029   if (wordShift == 0) {
01030     // Move the words containing significant bits
01031     for (unsigned i = 0; i <= breakWord; ++i)
01032       val[i] = pVal[i+offset]; // move whole word
01033 
01034     // Adjust the top significant word for sign bit fill, if negative
01035     if (isNegative())
01036       if (bitsInWord < APINT_BITS_PER_WORD)
01037         val[breakWord] |= ~0ULL << bitsInWord; // set high bits
01038   } else {
01039     // Shift the low order words 
01040     for (unsigned i = 0; i < breakWord; ++i) {
01041       // This combines the shifted corresponding word with the low bits from
01042       // the next word (shifted into this word's high bits).
01043       val[i] = (pVal[i+offset] >> wordShift) | 
01044                (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
01045     }
01046 
01047     // Shift the break word. In this case there are no bits from the next word
01048     // to include in this word.
01049     val[breakWord] = pVal[breakWord+offset] >> wordShift;
01050 
01051     // Deal with sign extenstion in the break word, and possibly the word before
01052     // it.
01053     if (isNegative()) {
01054       if (wordShift > bitsInWord) {
01055         if (breakWord > 0)
01056           val[breakWord-1] |= 
01057             ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
01058         val[breakWord] |= ~0ULL;
01059       } else 
01060         val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
01061     }
01062   }
01063 
01064   // Remaining words are 0 or -1, just assign them.
01065   uint64_t fillValue = (isNegative() ? -1ULL : 0);
01066   for (unsigned i = breakWord+1; i < getNumWords(); ++i)
01067     val[i] = fillValue;
01068   return APInt(val, BitWidth).clearUnusedBits();
01069 }
01070 
01071 /// Logical right-shift this APInt by shiftAmt.
01072 /// @brief Logical right-shift function.
01073 APInt APInt::lshr(const APInt &shiftAmt) const {
01074   return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
01075 }
01076 
01077 /// Logical right-shift this APInt by shiftAmt.
01078 /// @brief Logical right-shift function.
01079 APInt APInt::lshr(unsigned shiftAmt) const {
01080   if (isSingleWord()) {
01081     if (shiftAmt == BitWidth)
01082       return APInt(BitWidth, 0);
01083     else 
01084       return APInt(BitWidth, this->VAL >> shiftAmt);
01085   }
01086 
01087   // If all the bits were shifted out, the result is 0. This avoids issues
01088   // with shifting by the size of the integer type, which produces undefined
01089   // results. We define these "undefined results" to always be 0.
01090   if (shiftAmt == BitWidth)
01091     return APInt(BitWidth, 0);
01092 
01093   // If none of the bits are shifted out, the result is *this. This avoids
01094   // issues with shifting by the size of the integer type, which produces 
01095   // undefined results in the code below. This is also an optimization.
01096   if (shiftAmt == 0)
01097     return *this;
01098 
01099   // Create some space for the result.
01100   uint64_t * val = new uint64_t[getNumWords()];
01101 
01102   // If we are shifting less than a word, compute the shift with a simple carry
01103   if (shiftAmt < APINT_BITS_PER_WORD) {
01104     uint64_t carry = 0;
01105     for (int i = getNumWords()-1; i >= 0; --i) {
01106       val[i] = (pVal[i] >> shiftAmt) | carry;
01107       carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
01108     }
01109     return APInt(val, BitWidth).clearUnusedBits();
01110   }
01111 
01112   // Compute some values needed by the remaining shift algorithms
01113   unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
01114   unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
01115 
01116   // If we are shifting whole words, just move whole words
01117   if (wordShift == 0) {
01118     for (unsigned i = 0; i < getNumWords() - offset; ++i)
01119       val[i] = pVal[i+offset];
01120     for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
01121       val[i] = 0;
01122     return APInt(val,BitWidth).clearUnusedBits();
01123   }
01124 
01125   // Shift the low order words 
01126   unsigned breakWord = getNumWords() - offset -1;
01127   for (unsigned i = 0; i < breakWord; ++i)
01128     val[i] = (pVal[i+offset] >> wordShift) |
01129              (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
01130   // Shift the break word.
01131   val[breakWord] = pVal[breakWord+offset] >> wordShift;
01132 
01133   // Remaining words are 0
01134   for (unsigned i = breakWord+1; i < getNumWords(); ++i)
01135     val[i] = 0;
01136   return APInt(val, BitWidth).clearUnusedBits();
01137 }
01138 
01139 /// Left-shift this APInt by shiftAmt.
01140 /// @brief Left-shift function.
01141 APInt APInt::shl(const APInt &shiftAmt) const {
01142   // It's undefined behavior in C to shift by BitWidth or greater.
01143   return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
01144 }
01145 
01146 APInt APInt::shlSlowCase(unsigned shiftAmt) const {
01147   // If all the bits were shifted out, the result is 0. This avoids issues
01148   // with shifting by the size of the integer type, which produces undefined
01149   // results. We define these "undefined results" to always be 0.
01150   if (shiftAmt == BitWidth)
01151     return APInt(BitWidth, 0);
01152 
01153   // If none of the bits are shifted out, the result is *this. This avoids a
01154   // lshr by the words size in the loop below which can produce incorrect
01155   // results. It also avoids the expensive computation below for a common case.
01156   if (shiftAmt == 0)
01157     return *this;
01158 
01159   // Create some space for the result.
01160   uint64_t * val = new uint64_t[getNumWords()];
01161 
01162   // If we are shifting less than a word, do it the easy way
01163   if (shiftAmt < APINT_BITS_PER_WORD) {
01164     uint64_t carry = 0;
01165     for (unsigned i = 0; i < getNumWords(); i++) {
01166       val[i] = pVal[i] << shiftAmt | carry;
01167       carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
01168     }
01169     return APInt(val, BitWidth).clearUnusedBits();
01170   }
01171 
01172   // Compute some values needed by the remaining shift algorithms
01173   unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
01174   unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
01175 
01176   // If we are shifting whole words, just move whole words
01177   if (wordShift == 0) {
01178     for (unsigned i = 0; i < offset; i++)
01179       val[i] = 0;
01180     for (unsigned i = offset; i < getNumWords(); i++)
01181       val[i] = pVal[i-offset];
01182     return APInt(val,BitWidth).clearUnusedBits();
01183   }
01184 
01185   // Copy whole words from this to Result.
01186   unsigned i = getNumWords() - 1;
01187   for (; i > offset; --i)
01188     val[i] = pVal[i-offset] << wordShift |
01189              pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
01190   val[offset] = pVal[0] << wordShift;
01191   for (i = 0; i < offset; ++i)
01192     val[i] = 0;
01193   return APInt(val, BitWidth).clearUnusedBits();
01194 }
01195 
01196 APInt APInt::rotl(const APInt &rotateAmt) const {
01197   return rotl((unsigned)rotateAmt.getLimitedValue(BitWidth));
01198 }
01199 
01200 APInt APInt::rotl(unsigned rotateAmt) const {
01201   if (rotateAmt == 0)
01202     return *this;
01203   // Don't get too fancy, just use existing shift/or facilities
01204   APInt hi(*this);
01205   APInt lo(*this);
01206   hi.shl(rotateAmt);
01207   lo.lshr(BitWidth - rotateAmt);
01208   return hi | lo;
01209 }
01210 
01211 APInt APInt::rotr(const APInt &rotateAmt) const {
01212   return rotr((unsigned)rotateAmt.getLimitedValue(BitWidth));
01213 }
01214 
01215 APInt APInt::rotr(unsigned rotateAmt) const {
01216   if (rotateAmt == 0)
01217     return *this;
01218   // Don't get too fancy, just use existing shift/or facilities
01219   APInt hi(*this);
01220   APInt lo(*this);
01221   lo.lshr(rotateAmt);
01222   hi.shl(BitWidth - rotateAmt);
01223   return hi | lo;
01224 }
01225 
01226 // Square Root - this method computes and returns the square root of "this".
01227 // Three mechanisms are used for computation. For small values (<= 5 bits),
01228 // a table lookup is done. This gets some performance for common cases. For
01229 // values using less than 52 bits, the value is converted to double and then
01230 // the libc sqrt function is called. The result is rounded and then converted
01231 // back to a uint64_t which is then used to construct the result. Finally,
01232 // the Babylonian method for computing square roots is used. 
01233 APInt APInt::sqrt() const {
01234 
01235   // Determine the magnitude of the value.
01236   unsigned magnitude = getActiveBits();
01237 
01238   // Use a fast table for some small values. This also gets rid of some
01239   // rounding errors in libc sqrt for small values.
01240   if (magnitude <= 5) {
01241     static const uint8_t results[32] = {
01242       /*     0 */ 0,
01243       /*  1- 2 */ 1, 1,
01244       /*  3- 6 */ 2, 2, 2, 2, 
01245       /*  7-12 */ 3, 3, 3, 3, 3, 3,
01246       /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
01247       /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
01248       /*    31 */ 6
01249     };
01250     return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
01251   }
01252 
01253   // If the magnitude of the value fits in less than 52 bits (the precision of
01254   // an IEEE double precision floating point value), then we can use the
01255   // libc sqrt function which will probably use a hardware sqrt computation.
01256   // This should be faster than the algorithm below.
01257   if (magnitude < 52) {
01258 #ifdef _MSC_VER
01259     // Amazingly, VC++ doesn't have round().
01260     return APInt(BitWidth, 
01261                  uint64_t(::sqrt(double(isSingleWord()?VAL:pVal[0]))) + 0.5);
01262 #else
01263     return APInt(BitWidth, 
01264                  uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
01265 #endif
01266   }
01267 
01268   // Okay, all the short cuts are exhausted. We must compute it. The following
01269   // is a classical Babylonian method for computing the square root. This code
01270   // was adapted to APINt from a wikipedia article on such computations.
01271   // See http://www.wikipedia.org/ and go to the page named
01272   // Calculate_an_integer_square_root. 
01273   unsigned nbits = BitWidth, i = 4;
01274   APInt testy(BitWidth, 16);
01275   APInt x_old(BitWidth, 1);
01276   APInt x_new(BitWidth, 0);
01277   APInt two(BitWidth, 2);
01278 
01279   // Select a good starting value using binary logarithms.
01280   for (;; i += 2, testy = testy.shl(2)) 
01281     if (i >= nbits || this->ule(testy)) {
01282       x_old = x_old.shl(i / 2);
01283       break;
01284     }
01285 
01286   // Use the Babylonian method to arrive at the integer square root: 
01287   for (;;) {
01288     x_new = (this->udiv(x_old) + x_old).udiv(two);
01289     if (x_old.ule(x_new))
01290       break;
01291     x_old = x_new;
01292   }
01293 
01294   // Make sure we return the closest approximation
01295   // NOTE: The rounding calculation below is correct. It will produce an 
01296   // off-by-one discrepancy with results from pari/gp. That discrepancy has been
01297   // determined to be a rounding issue with pari/gp as it begins to use a 
01298   // floating point representation after 192 bits. There are no discrepancies
01299   // between this algorithm and pari/gp for bit widths < 192 bits.
01300   APInt square(x_old * x_old);
01301   APInt nextSquare((x_old + 1) * (x_old +1));
01302   if (this->ult(square))
01303     return x_old;
01304   else if (this->ule(nextSquare)) {
01305     APInt midpoint((nextSquare - square).udiv(two));
01306     APInt offset(*this - square);
01307     if (offset.ult(midpoint))
01308       return x_old;
01309     else
01310       return x_old + 1;
01311   } else
01312     assert(0 && "Error in APInt::sqrt computation");
01313   return x_old + 1;
01314 }
01315 
01316 /// Computes the multiplicative inverse of this APInt for a given modulo. The
01317 /// iterative extended Euclidean algorithm is used to solve for this value,
01318 /// however we simplify it to speed up calculating only the inverse, and take
01319 /// advantage of div+rem calculations. We also use some tricks to avoid copying
01320 /// (potentially large) APInts around.
01321 APInt APInt::multiplicativeInverse(const APInt& modulo) const {
01322   assert(ult(modulo) && "This APInt must be smaller than the modulo");
01323 
01324   // Using the properties listed at the following web page (accessed 06/21/08):
01325   //   http://www.numbertheory.org/php/euclid.html
01326   // (especially the properties numbered 3, 4 and 9) it can be proved that
01327   // BitWidth bits suffice for all the computations in the algorithm implemented
01328   // below. More precisely, this number of bits suffice if the multiplicative
01329   // inverse exists, but may not suffice for the general extended Euclidean
01330   // algorithm.
01331 
01332   APInt r[2] = { modulo, *this };
01333   APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
01334   APInt q(BitWidth, 0);
01335   
01336   unsigned i;
01337   for (i = 0; r[i^1] != 0; i ^= 1) {
01338     // An overview of the math without the confusing bit-flipping:
01339     // q = r[i-2] / r[i-1]
01340     // r[i] = r[i-2] % r[i-1]
01341     // t[i] = t[i-2] - t[i-1] * q
01342     udivrem(r[i], r[i^1], q, r[i]);
01343     t[i] -= t[i^1] * q;
01344   }
01345 
01346   // If this APInt and the modulo are not coprime, there is no multiplicative
01347   // inverse, so return 0. We check this by looking at the next-to-last
01348   // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
01349   // algorithm.
01350   if (r[i] != 1)
01351     return APInt(BitWidth, 0);
01352 
01353   // The next-to-last t is the multiplicative inverse.  However, we are
01354   // interested in a positive inverse. Calcuate a positive one from a negative
01355   // one if necessary. A simple addition of the modulo suffices because
01356   // abs(t[i]) is known to be less than *this/2 (see the link above).
01357   return t[i].isNegative() ? t[i] + modulo : t[i];
01358 }
01359 
01360 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
01361 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
01362 /// variables here have the same names as in the algorithm. Comments explain
01363 /// the algorithm and any deviation from it.
01364 static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
01365                      unsigned m, unsigned n) {
01366   assert(u && "Must provide dividend");
01367   assert(v && "Must provide divisor");
01368   assert(q && "Must provide quotient");
01369   assert(u != v && u != q && v != q && "Must us different memory");
01370   assert(n>1 && "n must be > 1");
01371 
01372   // Knuth uses the value b as the base of the number system. In our case b
01373   // is 2^31 so we just set it to -1u.
01374   uint64_t b = uint64_t(1) << 32;
01375 
01376 #if 0
01377   DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
01378   DEBUG(cerr << "KnuthDiv: original:");
01379   DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
01380   DEBUG(cerr << " by");
01381   DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
01382   DEBUG(cerr << '\n');
01383 #endif
01384   // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of 
01385   // u and v by d. Note that we have taken Knuth's advice here to use a power 
01386   // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of 
01387   // 2 allows us to shift instead of multiply and it is easy to determine the 
01388   // shift amount from the leading zeros.  We are basically normalizing the u
01389   // and v so that its high bits are shifted to the top of v's range without
01390   // overflow. Note that this can require an extra word in u so that u must
01391   // be of length m+n+1.
01392   unsigned shift = CountLeadingZeros_32(v[n-1]);
01393   unsigned v_carry = 0;
01394   unsigned u_carry = 0;
01395   if (shift) {
01396     for (unsigned i = 0; i < m+n; ++i) {
01397       unsigned u_tmp = u[i] >> (32 - shift);
01398       u[i] = (u[i] << shift) | u_carry;
01399       u_carry = u_tmp;
01400     }
01401     for (unsigned i = 0; i < n; ++i) {
01402       unsigned v_tmp = v[i] >> (32 - shift);
01403       v[i] = (v[i] << shift) | v_carry;
01404       v_carry = v_tmp;
01405     }
01406   }
01407   u[m+n] = u_carry;
01408 #if 0
01409   DEBUG(cerr << "KnuthDiv:   normal:");
01410   DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
01411   DEBUG(cerr << " by");
01412   DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
01413   DEBUG(cerr << '\n');
01414 #endif
01415 
01416   // D2. [Initialize j.]  Set j to m. This is the loop counter over the places.
01417   int j = m;
01418   do {
01419     DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
01420     // D3. [Calculate q'.]. 
01421     //     Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
01422     //     Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
01423     // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
01424     // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
01425     // on v[n-2] determines at high speed most of the cases in which the trial
01426     // value qp is one too large, and it eliminates all cases where qp is two 
01427     // too large. 
01428     uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
01429     DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
01430     uint64_t qp = dividend / v[n-1];
01431     uint64_t rp = dividend % v[n-1];
01432     if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
01433       qp--;
01434       rp += v[n-1];
01435       if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
01436         qp--;
01437     }
01438     DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
01439 
01440     // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
01441     // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
01442     // consists of a simple multiplication by a one-place number, combined with
01443     // a subtraction. 
01444     bool isNeg = false;
01445     for (unsigned i = 0; i < n; ++i) {
01446       uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
01447       uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
01448       bool borrow = subtrahend > u_tmp;
01449       DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp 
01450                  << ", subtrahend == " << subtrahend
01451                  << ", borrow = " << borrow << '\n');
01452 
01453       uint64_t result = u_tmp - subtrahend;
01454       unsigned k = j + i;
01455       u[k++] = (unsigned)(result & (b-1)); // subtract low word
01456       u[k++] = (unsigned)(result >> 32);   // subtract high word
01457       while (borrow && k <= m+n) { // deal with borrow to the left
01458         borrow = u[k] == 0;
01459         u[k]--;
01460         k++;
01461       }
01462       isNeg |= borrow;
01463       DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ",  u[j+i+1] == " << 
01464                     u[j+i+1] << '\n'); 
01465     }
01466     DEBUG(cerr << "KnuthDiv: after subtraction:");
01467     DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
01468     DEBUG(cerr << '\n');
01469     // The digits (u[j+n]...u[j]) should be kept positive; if the result of 
01470     // this step is actually negative, (u[j+n]...u[j]) should be left as the 
01471     // true value plus b**(n+1), namely as the b's complement of
01472     // the true value, and a "borrow" to the left should be remembered.
01473     //
01474     if (isNeg) {
01475       bool carry = true;  // true because b's complement is "complement + 1"
01476       for (unsigned i = 0; i <= m+n; ++i) {
01477         u[i] = ~u[i] + carry; // b's complement
01478         carry = carry && u[i] == 0;
01479       }
01480     }
01481     DEBUG(cerr << "KnuthDiv: after complement:");
01482     DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
01483     DEBUG(cerr << '\n');
01484 
01485     // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was 
01486     // negative, go to step D6; otherwise go on to step D7.
01487     q[j] = (unsigned)qp;
01488     if (isNeg) {
01489       // D6. [Add back]. The probability that this step is necessary is very 
01490       // small, on the order of only 2/b. Make sure that test data accounts for
01491       // this possibility. Decrease q[j] by 1 
01492       q[j]--;
01493       // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]). 
01494       // A carry will occur to the left of u[j+n], and it should be ignored 
01495       // since it cancels with the borrow that occurred in D4.
01496       bool carry = false;
01497       for (unsigned i = 0; i < n; i++) {
01498         unsigned limit = std::min(u[j+i],v[i]);
01499         u[j+i] += v[i] + carry;
01500         carry = u[j+i] < limit || (carry && u[j+i] == limit);
01501       }
01502       u[j+n] += carry;
01503     }
01504     DEBUG(cerr << "KnuthDiv: after correction:");
01505     DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
01506     DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
01507 
01508   // D7. [Loop on j.]  Decrease j by one. Now if j >= 0, go back to D3.
01509   } while (--j >= 0);
01510 
01511   DEBUG(cerr << "KnuthDiv: quotient:");
01512   DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
01513   DEBUG(cerr << '\n');
01514 
01515   // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
01516   // remainder may be obtained by dividing u[...] by d. If r is non-null we
01517   // compute the remainder (urem uses this).
01518   if (r) {
01519     // The value d is expressed by the "shift" value above since we avoided
01520     // multiplication by d by using a shift left. So, all we have to do is
01521     // shift right here. In order to mak
01522     if (shift) {
01523       unsigned carry = 0;
01524       DEBUG(cerr << "KnuthDiv: remainder:");
01525       for (int i = n-1; i >= 0; i--) {
01526         r[i] = (u[i] >> shift) | carry;
01527         carry = u[i] << (32 - shift);
01528         DEBUG(cerr << " " << r[i]);
01529       }
01530     } else {
01531       for (int i = n-1; i >= 0; i--) {
01532         r[i] = u[i];
01533         DEBUG(cerr << " " << r[i]);
01534       }
01535     }
01536     DEBUG(cerr << '\n');
01537   }
01538 #if 0
01539   DEBUG(cerr << std::setbase(10) << '\n');
01540 #endif
01541 }
01542 
01543 void APInt::divide(const APInt LHS, unsigned lhsWords,
01544                    const APInt &RHS, unsigned rhsWords,
01545                    APInt *Quotient, APInt *Remainder)
01546 {
01547   assert(lhsWords >= rhsWords && "Fractional result");
01548 
01549   // First, compose the values into an array of 32-bit words instead of 
01550   // 64-bit words. This is a necessity of both the "short division" algorithm
01551   // and the the Knuth "classical algorithm" which requires there to be native 
01552   // operations for +, -, and * on an m bit value with an m*2 bit result. We 
01553   // can't use 64-bit operands here because we don't have native results of 
01554   // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't 
01555   // work on large-endian machines.
01556   uint64_t mask = ~0ull >> (sizeof(unsigned)*8);
01557   unsigned n = rhsWords * 2;
01558   unsigned m = (lhsWords * 2) - n;
01559 
01560   // Allocate space for the temporary values we need either on the stack, if
01561   // it will fit, or on the heap if it won't.
01562   unsigned SPACE[128];
01563   unsigned *U = 0;
01564   unsigned *V = 0;
01565   unsigned *Q = 0;
01566   unsigned *R = 0;
01567   if ((Remainder?4:3)*n+2*m+1 <= 128) {
01568     U = &SPACE[0];
01569     V = &SPACE[m+n+1];
01570     Q = &SPACE[(m+n+1) + n];
01571     if (Remainder)
01572       R = &SPACE[(m+n+1) + n + (m+n)];
01573   } else {
01574     U = new unsigned[m + n + 1];
01575     V = new unsigned[n];
01576     Q = new unsigned[m+n];
01577     if (Remainder)
01578       R = new unsigned[n];
01579   }
01580 
01581   // Initialize the dividend
01582   memset(U, 0, (m+n+1)*sizeof(unsigned));
01583   for (unsigned i = 0; i < lhsWords; ++i) {
01584     uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
01585     U[i * 2] = (unsigned)(tmp & mask);
01586     U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*8));
01587   }
01588   U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
01589 
01590   // Initialize the divisor
01591   memset(V, 0, (n)*sizeof(unsigned));
01592   for (unsigned i = 0; i < rhsWords; ++i) {
01593     uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
01594     V[i * 2] = (unsigned)(tmp & mask);
01595     V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*8));
01596   }
01597 
01598   // initialize the quotient and remainder
01599   memset(Q, 0, (m+n) * sizeof(unsigned));
01600   if (Remainder)
01601     memset(R, 0, n * sizeof(unsigned));
01602 
01603   // Now, adjust m and n for the Knuth division. n is the number of words in 
01604   // the divisor. m is the number of words by which the dividend exceeds the
01605   // divisor (i.e. m+n is the length of the dividend). These sizes must not 
01606   // contain any zero words or the Knuth algorithm fails.
01607   for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
01608     n--;
01609     m++;
01610   }
01611   for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
01612     m--;
01613 
01614   // If we're left with only a single word for the divisor, Knuth doesn't work
01615   // so we implement the short division algorithm here. This is much simpler
01616   // and faster because we are certain that we can divide a 64-bit quantity
01617   // by a 32-bit quantity at hardware speed and short division is simply a
01618   // series of such operations. This is just like doing short division but we
01619   // are using base 2^32 instead of base 10.
01620   assert(n != 0 && "Divide by zero?");
01621   if (n == 1) {
01622     unsigned divisor = V[0];
01623     unsigned remainder = 0;
01624     for (int i = m+n-1; i >= 0; i--) {
01625       uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
01626       if (partial_dividend == 0) {
01627         Q[i] = 0;
01628         remainder = 0;
01629       } else if (partial_dividend < divisor) {
01630         Q[i] = 0;
01631         remainder = (unsigned)partial_dividend;
01632       } else if (partial_dividend == divisor) {
01633         Q[i] = 1;
01634         remainder = 0;
01635       } else {
01636         Q[i] = (unsigned)(partial_dividend / divisor);
01637         remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
01638       }
01639     }
01640     if (R)
01641       R[0] = remainder;
01642   } else {
01643     // Now we're ready to invoke the Knuth classical divide algorithm. In this
01644     // case n > 1.
01645     KnuthDiv(U, V, Q, R, m, n);
01646   }
01647 
01648   // If the caller wants the quotient
01649   if (Quotient) {
01650     // Set up the Quotient value's memory.
01651     if (Quotient->BitWidth != LHS.BitWidth) {
01652       if (Quotient->isSingleWord())
01653         Quotient->VAL = 0;
01654       else
01655         delete [] Quotient->pVal;
01656       Quotient->BitWidth = LHS.BitWidth;
01657       if (!Quotient->isSingleWord())
01658         Quotient->pVal = getClearedMemory(Quotient->getNumWords());
01659     } else
01660       Quotient->clear();
01661 
01662     // The quotient is in Q. Reconstitute the quotient into Quotient's low 
01663     // order words.
01664     if (lhsWords == 1) {
01665       uint64_t tmp = 
01666         uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
01667       if (Quotient->isSingleWord())
01668         Quotient->VAL = tmp;
01669       else
01670         Quotient->pVal[0] = tmp;
01671     } else {
01672       assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
01673       for (unsigned i = 0; i < lhsWords; ++i)
01674         Quotient->pVal[i] = 
01675           uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
01676     }
01677   }
01678 
01679   // If the caller wants the remainder
01680   if (Remainder) {
01681     // Set up the Remainder value's memory.
01682     if (Remainder->BitWidth != RHS.BitWidth) {
01683       if (Remainder->isSingleWord())
01684         Remainder->VAL = 0;
01685       else
01686         delete [] Remainder->pVal;
01687       Remainder->BitWidth = RHS.BitWidth;
01688       if (!Remainder->isSingleWord())
01689         Remainder->pVal = getClearedMemory(Remainder->getNumWords());
01690     } else
01691       Remainder->clear();
01692 
01693     // The remainder is in R. Reconstitute the remainder into Remainder's low
01694     // order words.
01695     if (rhsWords == 1) {
01696       uint64_t tmp = 
01697         uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
01698       if (Remainder->isSingleWord())
01699         Remainder->VAL = tmp;
01700       else
01701         Remainder->pVal[0] = tmp;
01702     } else {
01703       assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
01704       for (unsigned i = 0; i < rhsWords; ++i)
01705         Remainder->pVal[i] = 
01706           uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
01707     }
01708   }
01709 
01710   // Clean up the memory we allocated.
01711   if (U != &SPACE[0]) {
01712     delete [] U;
01713     delete [] V;
01714     delete [] Q;
01715     delete [] R;
01716   }
01717 }
01718 
01719 APInt APInt::udiv(const APInt& RHS) const {
01720   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
01721 
01722   // First, deal with the easy case
01723   if (isSingleWord()) {
01724     assert(RHS.VAL != 0 && "Divide by zero?");
01725     return APInt(BitWidth, VAL / RHS.VAL);
01726   }
01727 
01728   // Get some facts about the LHS and RHS number of bits and words
01729   unsigned rhsBits = RHS.getActiveBits();
01730   unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
01731   assert(rhsWords && "Divided by zero???");
01732   unsigned lhsBits = this->getActiveBits();
01733   unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
01734 
01735   // Deal with some degenerate cases
01736   if (!lhsWords) 
01737     // 0 / X ===> 0
01738     return APInt(BitWidth, 0); 
01739   else if (lhsWords < rhsWords || this->ult(RHS)) {
01740     // X / Y ===> 0, iff X < Y
01741     return APInt(BitWidth, 0);
01742   } else if (*this == RHS) {
01743     // X / X ===> 1
01744     return APInt(BitWidth, 1);
01745   } else if (lhsWords == 1 && rhsWords == 1) {
01746     // All high words are zero, just use native divide
01747     return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
01748   }
01749 
01750   // We have to compute it the hard way. Invoke the Knuth divide algorithm.
01751   APInt Quotient(1,0); // to hold result.
01752   divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
01753   return Quotient;
01754 }
01755 
01756 APInt APInt::urem(const APInt& RHS) const {
01757   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
01758   if (isSingleWord()) {
01759     assert(RHS.VAL != 0 && "Remainder by zero?");
01760     return APInt(BitWidth, VAL % RHS.VAL);
01761   }
01762 
01763   // Get some facts about the LHS
01764   unsigned lhsBits = getActiveBits();
01765   unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
01766 
01767   // Get some facts about the RHS
01768   unsigned rhsBits = RHS.getActiveBits();
01769   unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
01770   assert(rhsWords && "Performing remainder operation by zero ???");
01771 
01772   // Check the degenerate cases
01773   if (lhsWords == 0) {
01774     // 0 % Y ===> 0
01775     return APInt(BitWidth, 0);
01776   } else if (lhsWords < rhsWords || this->ult(RHS)) {
01777     // X % Y ===> X, iff X < Y
01778     return *this;
01779   } else if (*this == RHS) {
01780     // X % X == 0;
01781     return APInt(BitWidth, 0);
01782   } else if (lhsWords == 1) {
01783     // All high words are zero, just use native remainder
01784     return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
01785   }
01786 
01787   // We have to compute it the hard way. Invoke the Knuth divide algorithm.
01788   APInt Remainder(1,0);
01789   divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
01790   return Remainder;
01791 }
01792 
01793 void APInt::udivrem(const APInt &LHS, const APInt &RHS, 
01794                     APInt &Quotient, APInt &Remainder) {
01795   // Get some size facts about the dividend and divisor
01796   unsigned lhsBits  = LHS.getActiveBits();
01797   unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
01798   unsigned rhsBits  = RHS.getActiveBits();
01799   unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
01800 
01801   // Check the degenerate cases
01802   if (lhsWords == 0) {              
01803     Quotient = 0;                // 0 / Y ===> 0
01804     Remainder = 0;               // 0 % Y ===> 0
01805     return;
01806   } 
01807   
01808   if (lhsWords < rhsWords || LHS.ult(RHS)) { 
01809     Quotient = 0;               // X / Y ===> 0, iff X < Y
01810     Remainder = LHS;            // X % Y ===> X, iff X < Y
01811     return;
01812   } 
01813   
01814   if (LHS == RHS) {
01815     Quotient  = 1;              // X / X ===> 1
01816     Remainder = 0;              // X % X ===> 0;
01817     return;
01818   } 
01819   
01820   if (lhsWords == 1 && rhsWords == 1) {
01821     // There is only one word to consider so use the native versions.
01822     uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
01823     uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
01824     Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
01825     Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
01826     return;
01827   }
01828 
01829   // Okay, lets do it the long way
01830   divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
01831 }
01832 
01833 void APInt::fromString(unsigned numbits, const char *str, unsigned slen,
01834                        uint8_t radix) {
01835   // Check our assumptions here
01836   assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
01837          "Radix should be 2, 8, 10, or 16!");
01838   assert(str && "String is null?");
01839   bool isNeg = str[0] == '-';
01840   if (isNeg)
01841     str++, slen--;
01842   assert((slen <= numbits || radix != 2) && "Insufficient bit width");
01843   assert((slen*3 <= numbits || radix != 8) && "Insufficient bit width");
01844   assert((slen*4 <= numbits || radix != 16) && "Insufficient bit width");
01845   assert(((slen*64)/22 <= numbits || radix != 10) && "Insufficient bit width");
01846 
01847   // Allocate memory
01848   if (!isSingleWord())
01849     pVal = getClearedMemory(getNumWords());
01850 
01851   // Figure out if we can shift instead of multiply
01852   unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
01853 
01854   // Set up an APInt for the digit to add outside the loop so we don't
01855   // constantly construct/destruct it.
01856   APInt apdigit(getBitWidth(), 0);
01857   APInt apradix(getBitWidth(), radix);
01858 
01859   // Enter digit traversal loop
01860   for (unsigned i = 0; i < slen; i++) {
01861     // Get a digit
01862     unsigned digit = 0;
01863     char cdigit = str[i];
01864     if (radix == 16) {
01865       if (!isxdigit(cdigit))
01866         assert(0 && "Invalid hex digit in string");
01867       if (isdigit(cdigit))
01868         digit = cdigit - '0';
01869       else if (cdigit >= 'a')
01870         digit = cdigit - 'a' + 10;
01871       else if (cdigit >= 'A')
01872         digit = cdigit - 'A' + 10;
01873       else
01874         assert(0 && "huh? we shouldn't get here");
01875     } else if (isdigit(cdigit)) {
01876       digit = cdigit - '0';
01877       assert((radix == 10 ||
01878               (radix == 8 && digit != 8 && digit != 9) ||
01879               (radix == 2 && (digit == 0 || digit == 1))) &&
01880              "Invalid digit in string for given radix");
01881     } else {
01882       assert(0 && "Invalid character in digit string");
01883     }
01884 
01885     // Shift or multiply the value by the radix
01886     if (shift)
01887       *this <<= shift;
01888     else
01889       *this *= apradix;
01890 
01891     // Add in the digit we just interpreted
01892     if (apdigit.isSingleWord())
01893       apdigit.VAL = digit;
01894     else
01895       apdigit.pVal[0] = digit;
01896     *this += apdigit;
01897   }
01898   // If its negative, put it in two's complement form
01899   if (isNeg) {
01900     (*this)--;
01901     this->flip();
01902   }
01903 }
01904 
01905 void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
01906                      bool Signed) const {
01907   assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2) &&
01908          "Radix should be 2, 8, 10, or 16!");
01909   
01910   // First, check for a zero value and just short circuit the logic below.
01911   if (*this == 0) {
01912     Str.push_back('0');
01913     return;
01914   }
01915   
01916   static const char Digits[] = "0123456789ABCDEF";
01917   
01918   if (isSingleWord()) {
01919     char Buffer[65];
01920     char *BufPtr = Buffer+65;
01921     
01922     uint64_t N;
01923     if (Signed) {
01924       int64_t I = getSExtValue();
01925       if (I < 0) {
01926         Str.push_back('-');
01927         I = -I;
01928       }
01929       N = I;
01930     } else {
01931       N = getZExtValue();
01932     }
01933     
01934     while (N) {
01935       *--BufPtr = Digits[N % Radix];
01936       N /= Radix;
01937     }
01938     Str.append(BufPtr, Buffer+65);
01939     return;
01940   }
01941 
01942   APInt Tmp(*this);
01943   
01944   if (Signed && isNegative()) {
01945     // They want to print the signed version and it is a negative value
01946     // Flip the bits and add one to turn it into the equivalent positive
01947     // value and put a '-' in the result.
01948     Tmp.flip();
01949     Tmp++;
01950     Str.push_back('-');
01951   }
01952   
01953   // We insert the digits backward, then reverse them to get the right order.
01954   unsigned StartDig = Str.size();
01955   
01956   // For the 2, 8 and 16 bit cases, we can just shift instead of divide 
01957   // because the number of bits per digit (1, 3 and 4 respectively) divides 
01958   // equaly.  We just shift until the value is zero.
01959   if (Radix != 10) {
01960     // Just shift tmp right for each digit width until it becomes zero
01961     unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
01962     unsigned MaskAmt = Radix - 1;
01963     
01964     while (Tmp != 0) {
01965       unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
01966       Str.push_back(Digits[Digit]);
01967       Tmp = Tmp.lshr(ShiftAmt);
01968     }
01969   } else {
01970     APInt divisor(4, 10);
01971     while (Tmp != 0) {
01972       APInt APdigit(1, 0);
01973       APInt tmp2(Tmp.getBitWidth(), 0);
01974       divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2, 
01975              &APdigit);
01976       unsigned Digit = (unsigned)APdigit.getZExtValue();
01977       assert(Digit < Radix && "divide failed");
01978       Str.push_back(Digits[Digit]);
01979       Tmp = tmp2;
01980     }
01981   }
01982   
01983   // Reverse the digits before returning.
01984   std::reverse(Str.begin()+StartDig, Str.end());
01985 }
01986 
01987 /// toString - This returns the APInt as a std::string.  Note that this is an
01988 /// inefficient method.  It is better to pass in a SmallVector/SmallString
01989 /// to the methods above.
01990 std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
01991   SmallString<40> S;
01992   toString(S, Radix, Signed);
01993   return S.c_str();
01994 }
01995 
01996 
01997 void APInt::dump() const {
01998   SmallString<40> S, U;
01999   this->toStringUnsigned(U);
02000   this->toStringSigned(S);
02001   fprintf(stderr, "APInt(%db, %su %ss)", BitWidth, U.c_str(), S.c_str());
02002 }
02003 
02004 void APInt::print(raw_ostream &OS, bool isSigned) const {
02005   SmallString<40> S;
02006   this->toString(S, 10, isSigned);
02007   OS << S.c_str();
02008 }
02009 
02010 // This implements a variety of operations on a representation of
02011 // arbitrary precision, two's-complement, bignum integer values.
02012 
02013 /* Assumed by lowHalf, highHalf, partMSB and partLSB.  A fairly safe
02014    and unrestricting assumption.  */
02015 #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
02016 COMPILE_TIME_ASSERT(integerPartWidth % 2 == 0);
02017 
02018 /* Some handy functions local to this file.  */
02019 namespace {
02020 
02021   /* Returns the integer part with the least significant BITS set.
02022      BITS cannot be zero.  */
02023   static inline integerPart
02024   lowBitMask(unsigned int bits)
02025   {
02026     assert (bits != 0 && bits <= integerPartWidth);
02027 
02028     return ~(integerPart) 0 >> (integerPartWidth - bits);
02029   }
02030 
02031   /* Returns the value of the lower half of PART.  */
02032   static inline integerPart
02033   lowHalf(integerPart part)
02034   {
02035     return part & lowBitMask(integerPartWidth / 2);
02036   }
02037 
02038   /* Returns the value of the upper half of PART.  */
02039   static inline integerPart
02040   highHalf(integerPart part)
02041   {
02042     return part >> (integerPartWidth / 2);
02043   }
02044 
02045   /* Returns the bit number of the most significant set bit of a part.
02046      If the input number has no bits set -1U is returned.  */
02047   static unsigned int
02048   partMSB(integerPart value)
02049   {
02050     unsigned int n, msb;
02051 
02052     if (value == 0)
02053       return -1U;
02054 
02055     n = integerPartWidth / 2;
02056 
02057     msb = 0;
02058     do {
02059       if (value >> n) {
02060         value >>= n;
02061         msb += n;
02062       }
02063 
02064       n >>= 1;
02065     } while (n);
02066 
02067     return msb;
02068   }
02069 
02070   /* Returns the bit number of the least significant set bit of a
02071      part.  If the input number has no bits set -1U is returned.  */
02072   static unsigned int
02073   partLSB(integerPart value)
02074   {
02075     unsigned int n, lsb;
02076 
02077     if (value == 0)
02078       return -1U;
02079 
02080     lsb = integerPartWidth - 1;
02081     n = integerPartWidth / 2;
02082 
02083     do {
02084       if (value << n) {
02085         value <<= n;
02086         lsb -= n;
02087       }
02088 
02089       n >>= 1;
02090     } while (n);
02091 
02092     return lsb;
02093   }
02094 }
02095 
02096 /* Sets the least significant part of a bignum to the input value, and
02097    zeroes out higher parts.  */
02098 void
02099 APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts)
02100 {
02101   unsigned int i;
02102 
02103   assert (parts > 0);
02104 
02105   dst[0] = part;
02106   for(i = 1; i < parts; i++)
02107     dst[i] = 0;
02108 }
02109 
02110 /* Assign one bignum to another.  */
02111 void
02112 APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts)
02113 {
02114   unsigned int i;
02115 
02116   for(i = 0; i < parts; i++)
02117     dst[i] = src[i];
02118 }
02119 
02120 /* Returns true if a bignum is zero, false otherwise.  */
02121 bool
02122 APInt::tcIsZero(const integerPart *src, unsigned int parts)
02123 {
02124   unsigned int i;
02125 
02126   for(i = 0; i < parts; i++)
02127     if (src[i])
02128       return false;
02129 
02130   return true;
02131 }
02132 
02133 /* Extract the given bit of a bignum; returns 0 or 1.  */
02134 int
02135 APInt::tcExtractBit(const integerPart *parts, unsigned int bit)
02136 {
02137   return(parts[bit / integerPartWidth]
02138          & ((integerPart) 1 << bit % integerPartWidth)) != 0;
02139 }
02140 
02141 /* Set the given bit of a bignum.  */
02142 void
02143 APInt::tcSetBit(integerPart *parts, unsigned int bit)
02144 {
02145   parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
02146 }
02147 
02148 /* Returns the bit number of the least significant set bit of a
02149    number.  If the input number has no bits set -1U is returned.  */
02150 unsigned int
02151 APInt::tcLSB(const integerPart *parts, unsigned int n)
02152 {
02153   unsigned int i, lsb;
02154 
02155   for(i = 0; i < n; i++) {
02156       if (parts[i] != 0) {
02157           lsb = partLSB(parts[i]);
02158 
02159           return lsb + i * integerPartWidth;
02160       }
02161   }
02162 
02163   return -1U;
02164 }
02165 
02166 /* Returns the bit number of the most significant set bit of a number.
02167    If the input number has no bits set -1U is returned.  */
02168 unsigned int
02169 APInt::tcMSB(const integerPart *parts, unsigned int n)
02170 {
02171   unsigned int msb;
02172 
02173   do {
02174       --n;
02175 
02176       if (parts[n] != 0) {
02177           msb = partMSB(parts[n]);
02178 
02179           return msb + n * integerPartWidth;
02180       }
02181   } while (n);
02182 
02183   return -1U;
02184 }
02185 
02186 /* Copy the bit vector of width srcBITS from SRC, starting at bit
02187    srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
02188    the least significant bit of DST.  All high bits above srcBITS in
02189    DST are zero-filled.  */
02190 void
02191 APInt::tcExtract(integerPart *dst, unsigned int dstCount, const integerPart *src,
02192                  unsigned int srcBits, unsigned int srcLSB)
02193 {
02194   unsigned int firstSrcPart, dstParts, shift, n;
02195 
02196   dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
02197   assert (dstParts <= dstCount);
02198 
02199   firstSrcPart = srcLSB / integerPartWidth;
02200   tcAssign (dst, src + firstSrcPart, dstParts);
02201 
02202   shift = srcLSB % integerPartWidth;
02203   tcShiftRight (dst, dstParts, shift);
02204 
02205   /* We now have (dstParts * integerPartWidth - shift) bits from SRC
02206      in DST.  If this is less that srcBits, append the rest, else
02207      clear the high bits.  */
02208   n = dstParts * integerPartWidth - shift;
02209   if (n < srcBits) {
02210     integerPart mask = lowBitMask (srcBits - n);
02211     dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
02212                           << n % integerPartWidth);
02213   } else if (n > srcBits) {
02214     if (srcBits % integerPartWidth)
02215       dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
02216   }
02217 
02218   /* Clear high parts.  */
02219   while (dstParts < dstCount)
02220     dst[dstParts++] = 0;
02221 }
02222 
02223 /* DST += RHS + C where C is zero or one.  Returns the carry flag.  */
02224 integerPart
02225 APInt::tcAdd(integerPart *dst, const integerPart *rhs,
02226              integerPart c, unsigned int parts)
02227 {
02228   unsigned int i;
02229 
02230   assert(c <= 1);
02231 
02232   for(i = 0; i < parts; i++) {
02233     integerPart l;
02234 
02235     l = dst[i];
02236     if (c) {
02237       dst[i] += rhs[i] + 1;
02238       c = (dst[i] <= l);
02239     } else {
02240       dst[i] += rhs[i];
02241       c = (dst[i] < l);
02242     }
02243   }
02244 
02245   return c;
02246 }
02247 
02248 /* DST -= RHS + C where C is zero or one.  Returns the carry flag.  */
02249 integerPart
02250 APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
02251                   integerPart c, unsigned int parts)
02252 {
02253   unsigned int i;
02254 
02255   assert(c <= 1);
02256 
02257   for(i = 0; i < parts; i++) {
02258     integerPart l;
02259 
02260     l = dst[i];
02261     if (c) {
02262       dst[i] -= rhs[i] + 1;
02263       c = (dst[i] >= l);
02264     } else {
02265       dst[i] -= rhs[i];
02266       c = (dst[i] > l);
02267     }
02268   }
02269 
02270   return c;
02271 }
02272 
02273 /* Negate a bignum in-place.  */
02274 void
02275 APInt::tcNegate(integerPart *dst, unsigned int parts)
02276 {
02277   tcComplement(dst, parts);
02278   tcIncrement(dst, parts);
02279 }
02280 
02281 /*  DST += SRC * MULTIPLIER + CARRY   if add is true
02282     DST  = SRC * MULTIPLIER + CARRY   if add is false
02283 
02284     Requires 0 <= DSTPARTS <= SRCPARTS + 1.  If DST overlaps SRC
02285     they must start at the same point, i.e. DST == SRC.
02286 
02287     If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
02288     returned.  Otherwise DST is filled with the least significant
02289     DSTPARTS parts of the result, and if all of the omitted higher
02290     parts were zero return zero, otherwise overflow occurred and
02291     return one.  */
02292 int
02293 APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
02294                       integerPart multiplier, integerPart carry,
02295                       unsigned int srcParts, unsigned int dstParts,
02296                       bool add)
02297 {
02298   unsigned int i, n;
02299 
02300   /* Otherwise our writes of DST kill our later reads of SRC.  */
02301   assert(dst <= src || dst >= src + srcParts);
02302   assert(dstParts <= srcParts + 1);
02303 
02304   /* N loops; minimum of dstParts and srcParts.  */
02305   n = dstParts < srcParts ? dstParts: srcParts;
02306 
02307   for(i = 0; i < n; i++) {
02308     integerPart low, mid, high, srcPart;
02309 
02310       /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
02311 
02312          This cannot overflow, because
02313 
02314          (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
02315 
02316          which is less than n^2.  */
02317 
02318     srcPart = src[i];
02319 
02320     if (multiplier == 0 || srcPart == 0)        {
02321       low = carry;
02322       high = 0;
02323     } else {
02324       low = lowHalf(srcPart) * lowHalf(multiplier);
02325       high = highHalf(srcPart) * highHalf(multiplier);
02326 
02327       mid = lowHalf(srcPart) * highHalf(multiplier);
02328       high += highHalf(mid);
02329       mid <<= integerPartWidth / 2;
02330       if (low + mid < low)
02331         high++;
02332       low += mid;
02333 
02334       mid = highHalf(srcPart) * lowHalf(multiplier);
02335       high += highHalf(mid);
02336       mid <<= integerPartWidth / 2;
02337       if (low + mid < low)
02338         high++;
02339       low += mid;
02340 
02341       /* Now add carry.  */
02342       if (low + carry < low)
02343         high++;
02344       low += carry;
02345     }
02346 
02347     if (add) {
02348       /* And now DST[i], and store the new low part there.  */
02349       if (low + dst[i] < low)
02350         high++;
02351       dst[i] += low;
02352     } else
02353       dst[i] = low;
02354 
02355     carry = high;
02356   }
02357 
02358   if (i < dstParts) {
02359     /* Full multiplication, there is no overflow.  */
02360     assert(i + 1 == dstParts);
02361     dst[i] = carry;
02362     return 0;
02363   } else {
02364     /* We overflowed if there is carry.  */
02365     if (carry)
02366       return 1;
02367 
02368     /* We would overflow if any significant unwritten parts would be
02369        non-zero.  This is true if any remaining src parts are non-zero
02370        and the multiplier is non-zero.  */
02371     if (multiplier)
02372       for(; i < srcParts; i++)
02373         if (src[i])
02374           return 1;
02375 
02376     /* We fitted in the narrow destination.  */
02377     return 0;
02378   }
02379 }
02380 
02381 /* DST = LHS * RHS, where DST has the same width as the operands and
02382    is filled with the least significant parts of the result.  Returns
02383    one if overflow occurred, otherwise zero.  DST must be disjoint
02384    from both operands.  */
02385 int
02386 APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
02387                   const integerPart *rhs, unsigned int parts)
02388 {
02389   unsigned int i;
02390   int overflow;
02391 
02392   assert(dst != lhs && dst != rhs);
02393 
02394   overflow = 0;
02395   tcSet(dst, 0, parts);
02396 
02397   for(i = 0; i < parts; i++)
02398     overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
02399                                parts - i, true);
02400 
02401   return overflow;
02402 }
02403 
02404 /* DST = LHS * RHS, where DST has width the sum of the widths of the
02405    operands.  No overflow occurs.  DST must be disjoint from both
02406    operands.  Returns the number of parts required to hold the
02407    result.  */
02408 unsigned int
02409 APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
02410                       const integerPart *rhs, unsigned int lhsParts,
02411                       unsigned int rhsParts)
02412 {
02413   /* Put the narrower number on the LHS for less loops below.  */
02414   if (lhsParts > rhsParts) {
02415     return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
02416   } else {
02417     unsigned int n;
02418 
02419     assert(dst != lhs && dst != rhs);
02420 
02421     tcSet(dst, 0, rhsParts);
02422 
02423     for(n = 0; n < lhsParts; n++)
02424       tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true);
02425 
02426     n = lhsParts + rhsParts;
02427 
02428     return n - (dst[n - 1] == 0);
02429   }
02430 }
02431 
02432 /* If RHS is zero LHS and REMAINDER are left unchanged, return one.
02433    Otherwise set LHS to LHS / RHS with the fractional part discarded,
02434    set REMAINDER to the remainder, return zero.  i.e.
02435 
02436    OLD_LHS = RHS * LHS + REMAINDER
02437 
02438    SCRATCH is a bignum of the same size as the operands and result for
02439    use by the routine; its contents need not be initialized and are
02440    destroyed.  LHS, REMAINDER and SCRATCH must be distinct.
02441 */
02442 int
02443 APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
02444                 integerPart *remainder, integerPart *srhs,
02445                 unsigned int parts)
02446 {
02447   unsigned int n, shiftCount;
02448   integerPart mask;
02449 
02450   assert(lhs != remainder && lhs != srhs && remainder != srhs);
02451 
02452   shiftCount = tcMSB(rhs, parts) + 1;
02453   if (shiftCount == 0)
02454     return true;
02455 
02456   shiftCount = parts * integerPartWidth - shiftCount;
02457   n = shiftCount / integerPartWidth;
02458   mask = (integerPart) 1 << (shiftCount % integerPartWidth);
02459 
02460   tcAssign(srhs, rhs, parts);
02461   tcShiftLeft(srhs, parts, shiftCount);
02462   tcAssign(remainder, lhs, parts);
02463   tcSet(lhs, 0, parts);
02464 
02465   /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
02466      the total.  */
02467   for(;;) {
02468       int compare;
02469 
02470       compare = tcCompare(remainder, srhs, parts);
02471       if (compare >= 0) {
02472         tcSubtract(remainder, srhs, 0, parts);
02473         lhs[n] |= mask;
02474       }
02475 
02476       if (shiftCount == 0)
02477         break;
02478       shiftCount--;
02479       tcShiftRight(srhs, parts, 1);
02480       if ((mask >>= 1) == 0)
02481         mask = (integerPart) 1 << (integerPartWidth - 1), n--;
02482   }
02483 
02484   return false;
02485 }
02486 
02487 /* Shift a bignum left COUNT bits in-place.  Shifted in bits are zero.
02488    There are no restrictions on COUNT.  */
02489 void
02490 APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count)
02491 {
02492   if (count) {
02493     unsigned int jump, shift;
02494 
02495     /* Jump is the inter-part jump; shift is is intra-part shift.  */
02496     jump = count / integerPartWidth;
02497     shift = count % integerPartWidth;
02498 
02499     while (parts > jump) {
02500       integerPart part;
02501 
02502       parts--;
02503 
02504       /* dst[i] comes from the two parts src[i - jump] and, if we have
02505          an intra-part shift, src[i - jump - 1].  */
02506       part = dst[parts - jump];
02507       if (shift) {
02508         part <<= shift;
02509         if (parts >= jump + 1)
02510           part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
02511       }
02512 
02513       dst[parts] = part;
02514     }
02515 
02516     while (parts > 0)
02517       dst[--parts] = 0;
02518   }
02519 }
02520 
02521 /* Shift a bignum right COUNT bits in-place.  Shifted in bits are
02522    zero.  There are no restrictions on COUNT.  */
02523 void
02524 APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count)
02525 {
02526   if (count) {
02527     unsigned int i, jump, shift;
02528 
02529     /* Jump is the inter-part jump; shift is is intra-part shift.  */
02530     jump = count / integerPartWidth;
02531     shift = count % integerPartWidth;
02532 
02533     /* Perform the shift.  This leaves the most significant COUNT bits
02534        of the result at zero.  */
02535     for(i = 0; i < parts; i++) {
02536       integerPart part;
02537 
02538       if (i + jump >= parts) {
02539         part = 0;
02540       } else {
02541         part = dst[i + jump];
02542         if (shift) {
02543           part >>= shift;
02544           if (i + jump + 1 < parts)
02545             part |= dst[i + jump + 1] << (integerPartWidth - shift);
02546         }
02547       }
02548 
02549       dst[i] = part;
02550     }
02551   }
02552 }
02553 
02554 /* Bitwise and of two bignums.  */
02555 void
02556 APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts)
02557 {
02558   unsigned int i;
02559 
02560   for(i = 0; i < parts; i++)
02561     dst[i] &= rhs[i];
02562 }
02563 
02564 /* Bitwise inclusive or of two bignums.  */
02565 void
02566 APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts)
02567 {
02568   unsigned int i;
02569 
02570   for(i = 0; i < parts; i++)
02571     dst[i] |= rhs[i];
02572 }
02573 
02574 /* Bitwise exclusive or of two bignums.  */
02575 void
02576 APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts)
02577 {
02578   unsigned int i;
02579 
02580   for(i = 0; i < parts; i++)
02581     dst[i] ^= rhs[i];
02582 }
02583 
02584 /* Complement a bignum in-place.  */
02585 void
02586 APInt::tcComplement(integerPart *dst, unsigned int parts)
02587 {
02588   unsigned int i;
02589 
02590   for(i = 0; i < parts; i++)
02591     dst[i] = ~dst[i];
02592 }
02593 
02594 /* Comparison (unsigned) of two bignums.  */
02595 int
02596 APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
02597                  unsigned int parts)
02598 {
02599   while (parts) {
02600       parts--;
02601       if (lhs[parts] == rhs[parts])
02602         continue;
02603 
02604       if (lhs[parts] > rhs[parts])
02605         return 1;
02606       else
02607         return -1;
02608     }
02609 
02610   return 0;
02611 }
02612 
02613 /* Increment a bignum in-place, return the carry flag.  */
02614 integerPart
02615 APInt::tcIncrement(integerPart *dst, unsigned int parts)
02616 {
02617   unsigned int i;
02618 
02619   for(i = 0; i < parts; i++)
02620     if (++dst[i] != 0)
02621       break;
02622 
02623   return i == parts;
02624 }
02625 
02626 /* Set the least significant BITS bits of a bignum, clear the
02627    rest.  */
02628 void
02629 APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts,
02630                                  unsigned int bits)
02631 {
02632   unsigned int i;
02633 
02634   i = 0;
02635   while (bits > integerPartWidth) {
02636     dst[i++] = ~(integerPart) 0;
02637     bits -= integerPartWidth;
02638   }
02639 
02640   if (bits)
02641     dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
02642 
02643   while (i < parts)
02644     dst[i++] = 0;
02645 }