Combine two lines that can be.
[oota-llvm.git] / lib / Support / APInt.cpp
1 //===-- APInt.cpp - Implement APInt class ---------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Sheng Zhou and is distributed under the 
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a class to represent arbitrary precision integer
11 // constant values and provide a variety of arithmetic operations on them.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "apint"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/MathExtras.h"
20 #include <cstring>
21 #include <cstdlib>
22 #ifndef NDEBUG
23 #include <iomanip>
24 #endif
25
26 using namespace llvm;
27
28 /// A utility function for allocating memory, checking for allocation failures,
29 /// and ensuring the contents are zeroed.
30 inline static uint64_t* getClearedMemory(uint32_t numWords) {
31   uint64_t * result = new uint64_t[numWords];
32   assert(result && "APInt memory allocation fails!");
33   memset(result, 0, numWords * sizeof(uint64_t));
34   return result;
35 }
36
37 /// A utility function for allocating memory and checking for allocation 
38 /// failure.  The content is not zeroed.
39 inline static uint64_t* getMemory(uint32_t numWords) {
40   uint64_t * result = new uint64_t[numWords];
41   assert(result && "APInt memory allocation fails!");
42   return result;
43 }
44
45 APInt::APInt(uint32_t numBits, uint64_t val) : BitWidth(numBits), VAL(0) {
46   assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
47   assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
48   if (isSingleWord())
49     VAL = val;
50   else {
51     pVal = getClearedMemory(getNumWords());
52     pVal[0] = val;
53   }
54   clearUnusedBits();
55 }
56
57 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
58   : BitWidth(numBits), VAL(0)  {
59   assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
60   assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
61   assert(bigVal && "Null pointer detected!");
62   if (isSingleWord())
63     VAL = bigVal[0];
64   else {
65     // Get memory, cleared to 0
66     pVal = getClearedMemory(getNumWords());
67     // Calculate the number of words to copy
68     uint32_t words = std::min<uint32_t>(numWords, getNumWords());
69     // Copy the words from bigVal to pVal
70     memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
71   }
72   // Make sure unused high bits are cleared
73   clearUnusedBits();
74 }
75
76 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen, 
77              uint8_t radix) 
78   : BitWidth(numbits), VAL(0) {
79   fromString(numbits, StrStart, slen, radix);
80 }
81
82 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
83   : BitWidth(numbits), VAL(0) {
84   assert(!Val.empty() && "String empty?");
85   fromString(numbits, Val.c_str(), Val.size(), radix);
86 }
87
88 APInt::APInt(const APInt& that)
89   : BitWidth(that.BitWidth), VAL(0) {
90   if (isSingleWord()) 
91     VAL = that.VAL;
92   else {
93     pVal = getMemory(getNumWords());
94     memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
95   }
96 }
97
98 APInt::~APInt() {
99   if (!isSingleWord() && pVal) 
100     delete [] pVal;
101 }
102
103 APInt& APInt::operator=(const APInt& RHS) {
104   // Don't do anything for X = X
105   if (this == &RHS)
106     return *this;
107
108   // If the bitwidths are the same, we can avoid mucking with memory
109   if (BitWidth == RHS.getBitWidth()) {
110     if (isSingleWord()) 
111       VAL = RHS.VAL;
112     else
113       memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
114     return *this;
115   }
116
117   if (isSingleWord())
118     if (RHS.isSingleWord())
119       VAL = RHS.VAL;
120     else {
121       VAL = 0;
122       pVal = getMemory(RHS.getNumWords());
123       memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
124     }
125   else if (getNumWords() == RHS.getNumWords()) 
126     memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
127   else if (RHS.isSingleWord()) {
128     delete [] pVal;
129     VAL = RHS.VAL;
130   } else {
131     delete [] pVal;
132     pVal = getMemory(RHS.getNumWords());
133     memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
134   }
135   BitWidth = RHS.BitWidth;
136   return clearUnusedBits();
137 }
138
139 APInt& APInt::operator=(uint64_t RHS) {
140   if (isSingleWord()) 
141     VAL = RHS;
142   else {
143     pVal[0] = RHS;
144     memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
145   }
146   return clearUnusedBits();
147 }
148
149 /// add_1 - This function adds a single "digit" integer, y, to the multiple 
150 /// "digit" integer array,  x[]. x[] is modified to reflect the addition and
151 /// 1 is returned if there is a carry out, otherwise 0 is returned.
152 /// @returns the carry of the addition.
153 static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
154   for (uint32_t i = 0; i < len; ++i) {
155     dest[i] = y + x[i];
156     if (dest[i] < y)
157       y = 1; // Carry one to next digit.
158     else {
159       y = 0; // No need to carry so exit early
160       break;
161     }
162   }
163   return y;
164 }
165
166 /// @brief Prefix increment operator. Increments the APInt by one.
167 APInt& APInt::operator++() {
168   if (isSingleWord()) 
169     ++VAL;
170   else
171     add_1(pVal, pVal, getNumWords(), 1);
172   return clearUnusedBits();
173 }
174
175 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from 
176 /// the multi-digit integer array, x[], propagating the borrowed 1 value until 
177 /// no further borrowing is neeeded or it runs out of "digits" in x.  The result
178 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
179 /// In other words, if y > x then this function returns 1, otherwise 0.
180 /// @returns the borrow out of the subtraction
181 static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
182   for (uint32_t i = 0; i < len; ++i) {
183     uint64_t X = x[i];
184     x[i] -= y;
185     if (y > X) 
186       y = 1;  // We have to "borrow 1" from next "digit"
187     else {
188       y = 0;  // No need to borrow
189       break;  // Remaining digits are unchanged so exit early
190     }
191   }
192   return bool(y);
193 }
194
195 /// @brief Prefix decrement operator. Decrements the APInt by one.
196 APInt& APInt::operator--() {
197   if (isSingleWord()) 
198     --VAL;
199   else
200     sub_1(pVal, getNumWords(), 1);
201   return clearUnusedBits();
202 }
203
204 /// add - This function adds the integer array x to the integer array Y and
205 /// places the result in dest. 
206 /// @returns the carry out from the addition
207 /// @brief General addition of 64-bit integer arrays
208 static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y, 
209                 uint32_t len) {
210   bool carry = false;
211   for (uint32_t i = 0; i< len; ++i) {
212     uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
213     dest[i] = x[i] + y[i] + carry;
214     carry = dest[i] < limit || (carry && dest[i] == limit);
215   }
216   return carry;
217 }
218
219 /// Adds the RHS APint to this APInt.
220 /// @returns this, after addition of RHS.
221 /// @brief Addition assignment operator. 
222 APInt& APInt::operator+=(const APInt& RHS) {
223   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
224   if (isSingleWord()) 
225     VAL += RHS.VAL;
226   else {
227     add(pVal, pVal, RHS.pVal, getNumWords());
228   }
229   return clearUnusedBits();
230 }
231
232 /// Subtracts the integer array y from the integer array x 
233 /// @returns returns the borrow out.
234 /// @brief Generalized subtraction of 64-bit integer arrays.
235 static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y, 
236                 uint32_t len) {
237   bool borrow = false;
238   for (uint32_t i = 0; i < len; ++i) {
239     uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
240     borrow = y[i] > x_tmp || (borrow && x[i] == 0);
241     dest[i] = x_tmp - y[i];
242   }
243   return borrow;
244 }
245
246 /// Subtracts the RHS APInt from this APInt
247 /// @returns this, after subtraction
248 /// @brief Subtraction assignment operator. 
249 APInt& APInt::operator-=(const APInt& RHS) {
250   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
251   if (isSingleWord()) 
252     VAL -= RHS.VAL;
253   else
254     sub(pVal, pVal, RHS.pVal, getNumWords());
255   return clearUnusedBits();
256 }
257
258 /// Multiplies an integer array, x by a a uint64_t integer and places the result
259 /// into dest. 
260 /// @returns the carry out of the multiplication.
261 /// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
262 static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
263   // Split y into high 32-bit part (hy)  and low 32-bit part (ly)
264   uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
265   uint64_t carry = 0;
266
267   // For each digit of x.
268   for (uint32_t i = 0; i < len; ++i) {
269     // Split x into high and low words
270     uint64_t lx = x[i] & 0xffffffffULL;
271     uint64_t hx = x[i] >> 32;
272     // hasCarry - A flag to indicate if there is a carry to the next digit.
273     // hasCarry == 0, no carry
274     // hasCarry == 1, has carry
275     // hasCarry == 2, no carry and the calculation result == 0.
276     uint8_t hasCarry = 0;
277     dest[i] = carry + lx * ly;
278     // Determine if the add above introduces carry.
279     hasCarry = (dest[i] < carry) ? 1 : 0;
280     carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
281     // The upper limit of carry can be (2^32 - 1)(2^32 - 1) + 
282     // (2^32 - 1) + 2^32 = 2^64.
283     hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
284
285     carry += (lx * hy) & 0xffffffffULL;
286     dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
287     carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) + 
288             (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
289   }
290   return carry;
291 }
292
293 /// Multiplies integer array x by integer array y and stores the result into 
294 /// the integer array dest. Note that dest's size must be >= xlen + ylen.
295 /// @brief Generalized multiplicate of integer arrays.
296 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[], 
297                 uint32_t ylen) {
298   dest[xlen] = mul_1(dest, x, xlen, y[0]);
299   for (uint32_t i = 1; i < ylen; ++i) {
300     uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
301     uint64_t carry = 0, lx = 0, hx = 0;
302     for (uint32_t j = 0; j < xlen; ++j) {
303       lx = x[j] & 0xffffffffULL;
304       hx = x[j] >> 32;
305       // hasCarry - A flag to indicate if has carry.
306       // hasCarry == 0, no carry
307       // hasCarry == 1, has carry
308       // hasCarry == 2, no carry and the calculation result == 0.
309       uint8_t hasCarry = 0;
310       uint64_t resul = carry + lx * ly;
311       hasCarry = (resul < carry) ? 1 : 0;
312       carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
313       hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
314
315       carry += (lx * hy) & 0xffffffffULL;
316       resul = (carry << 32) | (resul & 0xffffffffULL);
317       dest[i+j] += resul;
318       carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
319               (carry >> 32) + (dest[i+j] < resul ? 1 : 0) + 
320               ((lx * hy) >> 32) + hx * hy;
321     }
322     dest[i+xlen] = carry;
323   }
324 }
325
326 APInt& APInt::operator*=(const APInt& RHS) {
327   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
328   if (isSingleWord()) {
329     VAL *= RHS.VAL;
330     clearUnusedBits();
331     return *this;
332   }
333
334   // Get some bit facts about LHS and check for zero
335   uint32_t lhsBits = getActiveBits();
336   uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
337   if (!lhsWords) 
338     // 0 * X ===> 0
339     return *this;
340
341   // Get some bit facts about RHS and check for zero
342   uint32_t rhsBits = RHS.getActiveBits();
343   uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
344   if (!rhsWords) {
345     // X * 0 ===> 0
346     clear();
347     return *this;
348   }
349
350   // Allocate space for the result
351   uint32_t destWords = rhsWords + lhsWords;
352   uint64_t *dest = getMemory(destWords);
353
354   // Perform the long multiply
355   mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
356
357   // Copy result back into *this
358   clear();
359   uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
360   memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
361
362   // delete dest array and return
363   delete[] dest;
364   return *this;
365 }
366
367 APInt& APInt::operator&=(const APInt& RHS) {
368   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
369   if (isSingleWord()) {
370     VAL &= RHS.VAL;
371     return *this;
372   }
373   uint32_t numWords = getNumWords();
374   for (uint32_t i = 0; i < numWords; ++i)
375     pVal[i] &= RHS.pVal[i];
376   return *this;
377 }
378
379 APInt& APInt::operator|=(const APInt& RHS) {
380   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
381   if (isSingleWord()) {
382     VAL |= RHS.VAL;
383     return *this;
384   }
385   uint32_t numWords = getNumWords();
386   for (uint32_t i = 0; i < numWords; ++i)
387     pVal[i] |= RHS.pVal[i];
388   return *this;
389 }
390
391 APInt& APInt::operator^=(const APInt& RHS) {
392   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
393   if (isSingleWord()) {
394     VAL ^= RHS.VAL;
395     this->clearUnusedBits();
396     return *this;
397   } 
398   uint32_t numWords = getNumWords();
399   for (uint32_t i = 0; i < numWords; ++i)
400     pVal[i] ^= RHS.pVal[i];
401   return clearUnusedBits();
402 }
403
404 APInt APInt::operator&(const APInt& RHS) const {
405   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
406   if (isSingleWord())
407     return APInt(getBitWidth(), VAL & RHS.VAL);
408
409   uint32_t numWords = getNumWords();
410   uint64_t* val = getMemory(numWords);
411   for (uint32_t i = 0; i < numWords; ++i)
412     val[i] = pVal[i] & RHS.pVal[i];
413   return APInt(val, getBitWidth());
414 }
415
416 APInt APInt::operator|(const APInt& RHS) const {
417   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
418   if (isSingleWord())
419     return APInt(getBitWidth(), VAL | RHS.VAL);
420
421   uint32_t numWords = getNumWords();
422   uint64_t *val = getMemory(numWords);
423   for (uint32_t i = 0; i < numWords; ++i)
424     val[i] = pVal[i] | RHS.pVal[i];
425   return APInt(val, getBitWidth());
426 }
427
428 APInt APInt::operator^(const APInt& RHS) const {
429   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
430   if (isSingleWord())
431     return APInt(BitWidth, VAL ^ RHS.VAL);
432
433   uint32_t numWords = getNumWords();
434   uint64_t *val = getMemory(numWords);
435   for (uint32_t i = 0; i < numWords; ++i)
436     val[i] = pVal[i] ^ RHS.pVal[i];
437
438   // 0^0==1 so clear the high bits in case they got set.
439   return APInt(val, getBitWidth()).clearUnusedBits();
440 }
441
442 bool APInt::operator !() const {
443   if (isSingleWord())
444     return !VAL;
445
446   for (uint32_t i = 0; i < getNumWords(); ++i)
447     if (pVal[i]) 
448       return false;
449   return true;
450 }
451
452 APInt APInt::operator*(const APInt& RHS) const {
453   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
454   if (isSingleWord())
455     return APInt(BitWidth, VAL * RHS.VAL);
456   APInt Result(*this);
457   Result *= RHS;
458   return Result.clearUnusedBits();
459 }
460
461 APInt APInt::operator+(const APInt& RHS) const {
462   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
463   if (isSingleWord())
464     return APInt(BitWidth, VAL + RHS.VAL);
465   APInt Result(BitWidth, 0);
466   add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
467   return Result.clearUnusedBits();
468 }
469
470 APInt APInt::operator-(const APInt& RHS) const {
471   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
472   if (isSingleWord())
473     return APInt(BitWidth, VAL - RHS.VAL);
474   APInt Result(BitWidth, 0);
475   sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
476   return Result.clearUnusedBits();
477 }
478
479 bool APInt::operator[](uint32_t bitPosition) const {
480   return (maskBit(bitPosition) & 
481           (isSingleWord() ?  VAL : pVal[whichWord(bitPosition)])) != 0;
482 }
483
484 bool APInt::operator==(const APInt& RHS) const {
485   assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
486   if (isSingleWord())
487     return VAL == RHS.VAL;
488
489   // Get some facts about the number of bits used in the two operands.
490   uint32_t n1 = getActiveBits();
491   uint32_t n2 = RHS.getActiveBits();
492
493   // If the number of bits isn't the same, they aren't equal
494   if (n1 != n2) 
495     return false;
496
497   // If the number of bits fits in a word, we only need to compare the low word.
498   if (n1 <= APINT_BITS_PER_WORD)
499     return pVal[0] == RHS.pVal[0];
500
501   // Otherwise, compare everything
502   for (int i = whichWord(n1 - 1); i >= 0; --i)
503     if (pVal[i] != RHS.pVal[i]) 
504       return false;
505   return true;
506 }
507
508 bool APInt::operator==(uint64_t Val) const {
509   if (isSingleWord())
510     return VAL == Val;
511
512   uint32_t n = getActiveBits(); 
513   if (n <= APINT_BITS_PER_WORD)
514     return pVal[0] == Val;
515   else
516     return false;
517 }
518
519 bool APInt::ult(const APInt& RHS) const {
520   assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
521   if (isSingleWord())
522     return VAL < RHS.VAL;
523
524   // Get active bit length of both operands
525   uint32_t n1 = getActiveBits();
526   uint32_t n2 = RHS.getActiveBits();
527
528   // If magnitude of LHS is less than RHS, return true.
529   if (n1 < n2)
530     return true;
531
532   // If magnitude of RHS is greather than LHS, return false.
533   if (n2 < n1)
534     return false;
535
536   // If they bot fit in a word, just compare the low order word
537   if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
538     return pVal[0] < RHS.pVal[0];
539
540   // Otherwise, compare all words
541   uint32_t topWord = whichWord(std::max(n1,n2)-1);
542   for (int i = topWord; i >= 0; --i) {
543     if (pVal[i] > RHS.pVal[i]) 
544       return false;
545     if (pVal[i] < RHS.pVal[i]) 
546       return true;
547   }
548   return false;
549 }
550
551 bool APInt::slt(const APInt& RHS) const {
552   assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
553   if (isSingleWord()) {
554     int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
555     int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
556     return lhsSext < rhsSext;
557   }
558
559   APInt lhs(*this);
560   APInt rhs(RHS);
561   bool lhsNeg = isNegative();
562   bool rhsNeg = rhs.isNegative();
563   if (lhsNeg) {
564     // Sign bit is set so perform two's complement to make it positive
565     lhs.flip();
566     lhs++;
567   }
568   if (rhsNeg) {
569     // Sign bit is set so perform two's complement to make it positive
570     rhs.flip();
571     rhs++;
572   }
573
574   // Now we have unsigned values to compare so do the comparison if necessary
575   // based on the negativeness of the values.
576   if (lhsNeg)
577     if (rhsNeg)
578       return lhs.ugt(rhs);
579     else
580       return true;
581   else if (rhsNeg)
582     return false;
583   else 
584     return lhs.ult(rhs);
585 }
586
587 APInt& APInt::set(uint32_t bitPosition) {
588   if (isSingleWord()) 
589     VAL |= maskBit(bitPosition);
590   else 
591     pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
592   return *this;
593 }
594
595 APInt& APInt::set() {
596   if (isSingleWord()) {
597     VAL = -1ULL;
598     return clearUnusedBits();
599   }
600
601   // Set all the bits in all the words.
602   for (uint32_t i = 0; i < getNumWords() - 1; ++i)
603     pVal[i] = -1ULL;
604   // Clear the unused ones
605   return clearUnusedBits();
606 }
607
608 /// Set the given bit to 0 whose position is given as "bitPosition".
609 /// @brief Set a given bit to 0.
610 APInt& APInt::clear(uint32_t bitPosition) {
611   if (isSingleWord()) 
612     VAL &= ~maskBit(bitPosition);
613   else 
614     pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
615   return *this;
616 }
617
618 /// @brief Set every bit to 0.
619 APInt& APInt::clear() {
620   if (isSingleWord()) 
621     VAL = 0;
622   else 
623     memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
624   return *this;
625 }
626
627 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
628 /// this APInt.
629 APInt APInt::operator~() const {
630   APInt Result(*this);
631   Result.flip();
632   return Result;
633 }
634
635 /// @brief Toggle every bit to its opposite value.
636 APInt& APInt::flip() {
637   if (isSingleWord()) {
638     VAL ^= -1ULL;
639     return clearUnusedBits();
640   }
641   for (uint32_t i = 0; i < getNumWords(); ++i)
642     pVal[i] ^= -1ULL;
643   return clearUnusedBits();
644 }
645
646 /// Toggle a given bit to its opposite value whose position is given 
647 /// as "bitPosition".
648 /// @brief Toggles a given bit to its opposite value.
649 APInt& APInt::flip(uint32_t bitPosition) {
650   assert(bitPosition < BitWidth && "Out of the bit-width range!");
651   if ((*this)[bitPosition]) clear(bitPosition);
652   else set(bitPosition);
653   return *this;
654 }
655
656 uint64_t APInt::getHashValue() const {
657   // Put the bit width into the low order bits.
658   uint64_t hash = BitWidth;
659
660   // Add the sum of the words to the hash.
661   if (isSingleWord())
662     hash += VAL << 6; // clear separation of up to 64 bits
663   else
664     for (uint32_t i = 0; i < getNumWords(); ++i)
665       hash += pVal[i] << 6; // clear sepration of up to 64 bits
666   return hash;
667 }
668
669 /// HiBits - This function returns the high "numBits" bits of this APInt.
670 APInt APInt::getHiBits(uint32_t numBits) const {
671   return APIntOps::lshr(*this, BitWidth - numBits);
672 }
673
674 /// LoBits - This function returns the low "numBits" bits of this APInt.
675 APInt APInt::getLoBits(uint32_t numBits) const {
676   return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits), 
677                         BitWidth - numBits);
678 }
679
680 bool APInt::isPowerOf2() const {
681   return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
682 }
683
684 uint32_t APInt::countLeadingZeros() const {
685   uint32_t Count = 0;
686   if (isSingleWord())
687     Count = CountLeadingZeros_64(VAL);
688   else {
689     for (uint32_t i = getNumWords(); i > 0u; --i) {
690       if (pVal[i-1] == 0)
691         Count += APINT_BITS_PER_WORD;
692       else {
693         Count += CountLeadingZeros_64(pVal[i-1]);
694         break;
695       }
696     }
697   }
698   uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
699   if (remainder)
700     Count -= APINT_BITS_PER_WORD - remainder;
701   return Count;
702 }
703
704 static uint32_t countLeadingOnes_64(uint64_t V, uint32_t skip) {
705   uint32_t Count = 0;
706   if (skip)
707     V <<= skip;
708   while (V && (V & (1ULL << 63))) {
709     Count++;
710     V <<= 1;
711   }
712   return Count;
713 }
714
715 uint32_t APInt::countLeadingOnes() const {
716   if (isSingleWord())
717     return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth);
718
719   uint32_t highWordBits = BitWidth % APINT_BITS_PER_WORD;
720   uint32_t shift = (highWordBits == 0 ? 0 : APINT_BITS_PER_WORD - highWordBits);
721   int i = getNumWords() - 1;
722   uint32_t Count = countLeadingOnes_64(pVal[i], shift);
723   if (Count == highWordBits) {
724     for (i--; i >= 0; --i) {
725       if (pVal[i] == -1ULL)
726         Count += APINT_BITS_PER_WORD;
727       else {
728         Count += countLeadingOnes_64(pVal[i], 0);
729         break;
730       }
731     }
732   }
733   return Count;
734 }
735
736 uint32_t APInt::countTrailingZeros() const {
737   if (isSingleWord())
738     return CountTrailingZeros_64(VAL);
739   uint32_t Count = 0;
740   uint32_t i = 0;
741   for (; i < getNumWords() && pVal[i] == 0; ++i)
742     Count += APINT_BITS_PER_WORD;
743   if (i < getNumWords())
744     Count += CountTrailingZeros_64(pVal[i]);
745   return Count;
746 }
747
748 uint32_t APInt::countPopulation() const {
749   if (isSingleWord())
750     return CountPopulation_64(VAL);
751   uint32_t Count = 0;
752   for (uint32_t i = 0; i < getNumWords(); ++i)
753     Count += CountPopulation_64(pVal[i]);
754   return Count;
755 }
756
757 APInt APInt::byteSwap() const {
758   assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
759   if (BitWidth == 16)
760     return APInt(BitWidth, ByteSwap_16(VAL));
761   else if (BitWidth == 32)
762     return APInt(BitWidth, ByteSwap_32(VAL));
763   else if (BitWidth == 48) {
764     uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
765     Tmp1 = ByteSwap_32(Tmp1);
766     uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
767     Tmp2 = ByteSwap_16(Tmp2);
768     return 
769       APInt(BitWidth, 
770             (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
771   } else if (BitWidth == 64)
772     return APInt(BitWidth, ByteSwap_64(VAL));
773   else {
774     APInt Result(BitWidth, 0);
775     char *pByte = (char*)Result.pVal;
776     for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
777       char Tmp = pByte[i];
778       pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
779       pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
780     }
781     return Result;
782   }
783 }
784
785 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1, 
786                                             const APInt& API2) {
787   APInt A = API1, B = API2;
788   while (!!B) {
789     APInt T = B;
790     B = APIntOps::urem(A, B);
791     A = T;
792   }
793   return A;
794 }
795
796 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, uint32_t width) {
797   union {
798     double D;
799     uint64_t I;
800   } T;
801   T.D = Double;
802
803   // Get the sign bit from the highest order bit
804   bool isNeg = T.I >> 63;
805
806   // Get the 11-bit exponent and adjust for the 1023 bit bias
807   int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
808
809   // If the exponent is negative, the value is < 0 so just return 0.
810   if (exp < 0)
811     return APInt(width, 0u);
812
813   // Extract the mantissa by clearing the top 12 bits (sign + exponent).
814   uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
815
816   // If the exponent doesn't shift all bits out of the mantissa
817   if (exp < 52)
818     return isNeg ? -APInt(width, mantissa >> (52 - exp)) : 
819                     APInt(width, mantissa >> (52 - exp));
820
821   // If the client didn't provide enough bits for us to shift the mantissa into
822   // then the result is undefined, just return 0
823   if (width <= exp - 52)
824     return APInt(width, 0);
825
826   // Otherwise, we have to shift the mantissa bits up to the right location
827   APInt Tmp(width, mantissa);
828   Tmp = Tmp.shl(exp - 52);
829   return isNeg ? -Tmp : Tmp;
830 }
831
832 /// RoundToDouble - This function convert this APInt to a double.
833 /// The layout for double is as following (IEEE Standard 754):
834 ///  --------------------------------------
835 /// |  Sign    Exponent    Fraction    Bias |
836 /// |-------------------------------------- |
837 /// |  1[63]   11[62-52]   52[51-00]   1023 |
838 ///  -------------------------------------- 
839 double APInt::roundToDouble(bool isSigned) const {
840
841   // Handle the simple case where the value is contained in one uint64_t.
842   if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
843     if (isSigned) {
844       int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
845       return double(sext);
846     } else
847       return double(VAL);
848   }
849
850   // Determine if the value is negative.
851   bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
852
853   // Construct the absolute value if we're negative.
854   APInt Tmp(isNeg ? -(*this) : (*this));
855
856   // Figure out how many bits we're using.
857   uint32_t n = Tmp.getActiveBits();
858
859   // The exponent (without bias normalization) is just the number of bits
860   // we are using. Note that the sign bit is gone since we constructed the
861   // absolute value.
862   uint64_t exp = n;
863
864   // Return infinity for exponent overflow
865   if (exp > 1023) {
866     if (!isSigned || !isNeg)
867       return double(1.0E300 * 1.0E300); // positive infinity
868     else 
869       return double(-1.0E300 * 1.0E300); // negative infinity
870   }
871   exp += 1023; // Increment for 1023 bias
872
873   // Number of bits in mantissa is 52. To obtain the mantissa value, we must
874   // extract the high 52 bits from the correct words in pVal.
875   uint64_t mantissa;
876   unsigned hiWord = whichWord(n-1);
877   if (hiWord == 0) {
878     mantissa = Tmp.pVal[0];
879     if (n > 52)
880       mantissa >>= n - 52; // shift down, we want the top 52 bits.
881   } else {
882     assert(hiWord > 0 && "huh?");
883     uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
884     uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
885     mantissa = hibits | lobits;
886   }
887
888   // The leading bit of mantissa is implicit, so get rid of it.
889   uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
890   union {
891     double D;
892     uint64_t I;
893   } T;
894   T.I = sign | (exp << 52) | mantissa;
895   return T.D;
896 }
897
898 // Truncate to new width.
899 APInt &APInt::trunc(uint32_t width) {
900   assert(width < BitWidth && "Invalid APInt Truncate request");
901   assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
902   uint32_t wordsBefore = getNumWords();
903   BitWidth = width;
904   uint32_t wordsAfter = getNumWords();
905   if (wordsBefore != wordsAfter) {
906     if (wordsAfter == 1) {
907       uint64_t *tmp = pVal;
908       VAL = pVal[0];
909       delete [] tmp;
910     } else {
911       uint64_t *newVal = getClearedMemory(wordsAfter);
912       for (uint32_t i = 0; i < wordsAfter; ++i)
913         newVal[i] = pVal[i];
914       delete [] pVal;
915       pVal = newVal;
916     }
917   }
918   return clearUnusedBits();
919 }
920
921 // Sign extend to a new width.
922 APInt &APInt::sext(uint32_t width) {
923   assert(width > BitWidth && "Invalid APInt SignExtend request");
924   assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
925   // If the sign bit isn't set, this is the same as zext.
926   if (!isNegative()) {
927     zext(width);
928     return *this;
929   }
930
931   // The sign bit is set. First, get some facts
932   uint32_t wordsBefore = getNumWords();
933   uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
934   BitWidth = width;
935   uint32_t wordsAfter = getNumWords();
936
937   // Mask the high order word appropriately
938   if (wordsBefore == wordsAfter) {
939     uint32_t newWordBits = width % APINT_BITS_PER_WORD;
940     // The extension is contained to the wordsBefore-1th word.
941     uint64_t mask = (~0ULL >> (APINT_BITS_PER_WORD - newWordBits)) <<  wordBits;
942     if (wordsBefore == 1)
943       VAL |= mask;
944     else
945       pVal[wordsBefore-1] |= mask;
946     return clearUnusedBits();
947   }
948
949   uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
950   uint64_t *newVal = getMemory(wordsAfter);
951   if (wordsBefore == 1)
952     newVal[0] = VAL | mask;
953   else {
954     for (uint32_t i = 0; i < wordsBefore; ++i)
955       newVal[i] = pVal[i];
956     newVal[wordsBefore-1] |= mask;
957   }
958   for (uint32_t i = wordsBefore; i < wordsAfter; i++)
959     newVal[i] = -1ULL;
960   if (wordsBefore != 1)
961     delete [] pVal;
962   pVal = newVal;
963   return clearUnusedBits();
964 }
965
966 //  Zero extend to a new width.
967 APInt &APInt::zext(uint32_t width) {
968   assert(width > BitWidth && "Invalid APInt ZeroExtend request");
969   assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
970   uint32_t wordsBefore = getNumWords();
971   BitWidth = width;
972   uint32_t wordsAfter = getNumWords();
973   if (wordsBefore != wordsAfter) {
974     uint64_t *newVal = getClearedMemory(wordsAfter);
975     if (wordsBefore == 1)
976       newVal[0] = VAL;
977     else 
978       for (uint32_t i = 0; i < wordsBefore; ++i)
979         newVal[i] = pVal[i];
980     if (wordsBefore != 1)
981       delete [] pVal;
982     pVal = newVal;
983   }
984   return *this;
985 }
986
987 APInt &APInt::zextOrTrunc(uint32_t width) {
988   if (BitWidth < width)
989     return zext(width);
990   if (BitWidth > width)
991     return trunc(width);
992   return *this;
993 }
994
995 APInt &APInt::sextOrTrunc(uint32_t width) {
996   if (BitWidth < width)
997     return sext(width);
998   if (BitWidth > width)
999     return trunc(width);
1000   return *this;
1001 }
1002
1003 /// Arithmetic right-shift this APInt by shiftAmt.
1004 /// @brief Arithmetic right-shift function.
1005 APInt APInt::ashr(uint32_t shiftAmt) const {
1006   assert(shiftAmt <= BitWidth && "Invalid shift amount");
1007   if (isSingleWord()) {
1008     if (shiftAmt == BitWidth)
1009       return APInt(BitWidth, 0); // undefined
1010     else {
1011       uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
1012       return APInt(BitWidth, 
1013         (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1014     }
1015   }
1016
1017   // If all the bits were shifted out, the result is 0 or -1. This avoids issues
1018   // with shifting by the size of the integer type, which produces undefined
1019   // results. 
1020   if (shiftAmt == BitWidth)
1021     if (isNegative())
1022       return APInt(BitWidth, -1ULL);
1023     else
1024       return APInt(BitWidth, 0);
1025
1026   // Create some space for the result.
1027   uint64_t * val = new uint64_t[getNumWords()];
1028
1029   // If we are shifting less than a word, compute the shift with a simple carry
1030   if (shiftAmt < APINT_BITS_PER_WORD) {
1031     uint64_t carry = 0;
1032     for (int i = getNumWords()-1; i >= 0; --i) {
1033       val[i] = (pVal[i] >> shiftAmt) | carry;
1034       carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1035     }
1036     return APInt(val, BitWidth).clearUnusedBits();
1037   }
1038
1039   // Compute some values needed by the remaining shift algorithms
1040   uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1041   uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1042
1043   // If we are shifting whole words, just move whole words
1044   if (wordShift == 0) {
1045     for (uint32_t i = 0; i < getNumWords() - offset; ++i) 
1046       val[i] = pVal[i+offset];
1047     for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1048       val[i] = (isNegative() ? -1ULL : 0);
1049     return APInt(val,BitWidth).clearUnusedBits();
1050   }
1051
1052   // Shift the low order words 
1053   uint32_t breakWord = getNumWords() - offset -1;
1054   for (uint32_t i = 0; i < breakWord; ++i)
1055     val[i] = (pVal[i+offset] >> wordShift) |
1056              (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1057   // Shift the break word.
1058   uint32_t SignBit = APINT_BITS_PER_WORD - (BitWidth % APINT_BITS_PER_WORD);
1059   val[breakWord] = uint64_t(
1060     (((int64_t(pVal[breakWord+offset]) << SignBit) >> SignBit) >> wordShift));
1061
1062   // Remaining words are 0 or -1
1063   for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1064     val[i] = (isNegative() ? -1ULL : 0);
1065   return APInt(val, BitWidth).clearUnusedBits();
1066 }
1067
1068 /// Logical right-shift this APInt by shiftAmt.
1069 /// @brief Logical right-shift function.
1070 APInt APInt::lshr(uint32_t shiftAmt) const {
1071   if (isSingleWord())
1072     if (shiftAmt == BitWidth)
1073       return APInt(BitWidth, 0);
1074     else 
1075       return APInt(BitWidth, this->VAL >> shiftAmt);
1076
1077   // If all the bits were shifted out, the result is 0. This avoids issues
1078   // with shifting by the size of the integer type, which produces undefined
1079   // results. We define these "undefined results" to always be 0.
1080   if (shiftAmt == BitWidth)
1081     return APInt(BitWidth, 0);
1082
1083   // Create some space for the result.
1084   uint64_t * val = new uint64_t[getNumWords()];
1085
1086   // If we are shifting less than a word, compute the shift with a simple carry
1087   if (shiftAmt < APINT_BITS_PER_WORD) {
1088     uint64_t carry = 0;
1089     for (int i = getNumWords()-1; i >= 0; --i) {
1090       val[i] = (pVal[i] >> shiftAmt) | carry;
1091       carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1092     }
1093     return APInt(val, BitWidth).clearUnusedBits();
1094   }
1095
1096   // Compute some values needed by the remaining shift algorithms
1097   uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1098   uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1099
1100   // If we are shifting whole words, just move whole words
1101   if (wordShift == 0) {
1102     for (uint32_t i = 0; i < getNumWords() - offset; ++i) 
1103       val[i] = pVal[i+offset];
1104     for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1105       val[i] = 0;
1106     return APInt(val,BitWidth).clearUnusedBits();
1107   }
1108
1109   // Shift the low order words 
1110   uint32_t breakWord = getNumWords() - offset -1;
1111   for (uint32_t i = 0; i < breakWord; ++i)
1112     val[i] = (pVal[i+offset] >> wordShift) |
1113              (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1114   // Shift the break word.
1115   val[breakWord] = pVal[breakWord+offset] >> wordShift;
1116
1117   // Remaining words are 0
1118   for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1119     val[i] = 0;
1120   return APInt(val, BitWidth).clearUnusedBits();
1121 }
1122
1123 /// Left-shift this APInt by shiftAmt.
1124 /// @brief Left-shift function.
1125 APInt APInt::shl(uint32_t shiftAmt) const {
1126   assert(shiftAmt <= BitWidth && "Invalid shift amount");
1127   if (isSingleWord()) {
1128     if (shiftAmt == BitWidth)
1129       return APInt(BitWidth, 0); // avoid undefined shift results
1130     return APInt(BitWidth, VAL << shiftAmt);
1131   }
1132
1133   // If all the bits were shifted out, the result is 0. This avoids issues
1134   // with shifting by the size of the integer type, which produces undefined
1135   // results. We define these "undefined results" to always be 0.
1136   if (shiftAmt == BitWidth)
1137     return APInt(BitWidth, 0);
1138
1139   // Create some space for the result.
1140   uint64_t * val = new uint64_t[getNumWords()];
1141
1142   // If we are shifting less than a word, do it the easy way
1143   if (shiftAmt < APINT_BITS_PER_WORD) {
1144     uint64_t carry = 0;
1145     for (uint32_t i = 0; i < getNumWords(); i++) {
1146       val[i] = pVal[i] << shiftAmt | carry;
1147       carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1148     }
1149     return APInt(val, BitWidth).clearUnusedBits();
1150   }
1151
1152   // Compute some values needed by the remaining shift algorithms
1153   uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1154   uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1155
1156   // If we are shifting whole words, just move whole words
1157   if (wordShift == 0) {
1158     for (uint32_t i = 0; i < offset; i++) 
1159       val[i] = 0;
1160     for (uint32_t i = offset; i < getNumWords(); i++)
1161       val[i] = pVal[i-offset];
1162     return APInt(val,BitWidth).clearUnusedBits();
1163   }
1164
1165   // Copy whole words from this to Result.
1166   uint32_t i = getNumWords() - 1;
1167   for (; i > offset; --i)
1168     val[i] = pVal[i-offset] << wordShift |
1169              pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
1170   val[offset] = pVal[0] << wordShift;
1171   for (i = 0; i < offset; ++i)
1172     val[i] = 0;
1173   return APInt(val, BitWidth).clearUnusedBits();
1174 }
1175
1176
1177 // Square Root - this method computes and returns the square root of "this".
1178 // Three mechanisms are used for computation. For small values (<= 5 bits),
1179 // a table lookup is done. This gets some performance for common cases. For
1180 // values using less than 52 bits, the value is converted to double and then
1181 // the libc sqrt function is called. The result is rounded and then converted
1182 // back to a uint64_t which is then used to construct the result. Finally,
1183 // the Babylonian method for computing square roots is used. 
1184 APInt APInt::sqrt() const {
1185
1186   // Determine the magnitude of the value.
1187   uint32_t magnitude = getActiveBits();
1188
1189   // Use a fast table for some small values. This also gets rid of some
1190   // rounding errors in libc sqrt for small values.
1191   if (magnitude <= 5) {
1192     static const uint8_t results[32] = {
1193       /*     0 */ 0,
1194       /*  1- 2 */ 1, 1,
1195       /*  3- 6 */ 2, 2, 2, 2, 
1196       /*  7-12 */ 3, 3, 3, 3, 3, 3,
1197       /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1198       /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1199       /*    31 */ 6
1200     };
1201     return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
1202   }
1203
1204   // If the magnitude of the value fits in less than 52 bits (the precision of
1205   // an IEEE double precision floating point value), then we can use the
1206   // libc sqrt function which will probably use a hardware sqrt computation.
1207   // This should be faster than the algorithm below.
1208   if (magnitude < 52)
1209     return APInt(BitWidth, 
1210                  uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
1211
1212   // Okay, all the short cuts are exhausted. We must compute it. The following
1213   // is a classical Babylonian method for computing the square root. This code
1214   // was adapted to APINt from a wikipedia article on such computations.
1215   // See http://www.wikipedia.org/ and go to the page named
1216   // Calculate_an_integer_square_root. 
1217   uint32_t nbits = BitWidth, i = 4;
1218   APInt testy(BitWidth, 16);
1219   APInt x_old(BitWidth, 1);
1220   APInt x_new(BitWidth, 0);
1221   APInt two(BitWidth, 2);
1222
1223   // Select a good starting value using binary logarithms.
1224   for (;; i += 2, testy = testy.shl(2)) 
1225     if (i >= nbits || this->ule(testy)) {
1226       x_old = x_old.shl(i / 2);
1227       break;
1228     }
1229
1230   // Use the Babylonian method to arrive at the integer square root: 
1231   for (;;) {
1232     x_new = (this->udiv(x_old) + x_old).udiv(two);
1233     if (x_old.ule(x_new))
1234       break;
1235     x_old = x_new;
1236   }
1237
1238   // Make sure we return the closest approximation
1239   APInt square(x_old * x_old);
1240   APInt nextSquare((x_old + 1) * (x_old +1));
1241   if (this->ult(square))
1242     return x_old;
1243   else if (this->ule(nextSquare))
1244     if ((nextSquare - *this).ult(*this - square))
1245       return x_old + 1;
1246     else
1247       return x_old;
1248   else
1249     assert(0 && "Error in APInt::sqrt computation");
1250   return x_old + 1;
1251 }
1252
1253 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1254 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1255 /// variables here have the same names as in the algorithm. Comments explain
1256 /// the algorithm and any deviation from it.
1257 static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r, 
1258                      uint32_t m, uint32_t n) {
1259   assert(u && "Must provide dividend");
1260   assert(v && "Must provide divisor");
1261   assert(q && "Must provide quotient");
1262   assert(u != v && u != q && v != q && "Must us different memory");
1263   assert(n>1 && "n must be > 1");
1264
1265   // Knuth uses the value b as the base of the number system. In our case b
1266   // is 2^31 so we just set it to -1u.
1267   uint64_t b = uint64_t(1) << 32;
1268
1269   DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1270   DEBUG(cerr << "KnuthDiv: original:");
1271   DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1272   DEBUG(cerr << " by");
1273   DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1274   DEBUG(cerr << '\n');
1275   // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of 
1276   // u and v by d. Note that we have taken Knuth's advice here to use a power 
1277   // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of 
1278   // 2 allows us to shift instead of multiply and it is easy to determine the 
1279   // shift amount from the leading zeros.  We are basically normalizing the u
1280   // and v so that its high bits are shifted to the top of v's range without
1281   // overflow. Note that this can require an extra word in u so that u must
1282   // be of length m+n+1.
1283   uint32_t shift = CountLeadingZeros_32(v[n-1]);
1284   uint32_t v_carry = 0;
1285   uint32_t u_carry = 0;
1286   if (shift) {
1287     for (uint32_t i = 0; i < m+n; ++i) {
1288       uint32_t u_tmp = u[i] >> (32 - shift);
1289       u[i] = (u[i] << shift) | u_carry;
1290       u_carry = u_tmp;
1291     }
1292     for (uint32_t i = 0; i < n; ++i) {
1293       uint32_t v_tmp = v[i] >> (32 - shift);
1294       v[i] = (v[i] << shift) | v_carry;
1295       v_carry = v_tmp;
1296     }
1297   }
1298   u[m+n] = u_carry;
1299   DEBUG(cerr << "KnuthDiv:   normal:");
1300   DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1301   DEBUG(cerr << " by");
1302   DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1303   DEBUG(cerr << '\n');
1304
1305   // D2. [Initialize j.]  Set j to m. This is the loop counter over the places.
1306   int j = m;
1307   do {
1308     DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
1309     // D3. [Calculate q'.]. 
1310     //     Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1311     //     Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1312     // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1313     // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1314     // on v[n-2] determines at high speed most of the cases in which the trial
1315     // value qp is one too large, and it eliminates all cases where qp is two 
1316     // too large. 
1317     uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
1318     DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
1319     uint64_t qp = dividend / v[n-1];
1320     uint64_t rp = dividend % v[n-1];
1321     if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1322       qp--;
1323       rp += v[n-1];
1324       if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
1325         qp--;
1326     }
1327     DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
1328
1329     // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1330     // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1331     // consists of a simple multiplication by a one-place number, combined with
1332     // a subtraction. 
1333     bool isNeg = false;
1334     for (uint32_t i = 0; i < n; ++i) {
1335       uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
1336       uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
1337       bool borrow = subtrahend > u_tmp;
1338       DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp 
1339                  << ", subtrahend == " << subtrahend
1340                  << ", borrow = " << borrow << '\n');
1341
1342       uint64_t result = u_tmp - subtrahend;
1343       uint32_t k = j + i;
1344       u[k++] = result & (b-1); // subtract low word
1345       u[k++] = result >> 32;   // subtract high word
1346       while (borrow && k <= m+n) { // deal with borrow to the left
1347         borrow = u[k] == 0;
1348         u[k]--;
1349         k++;
1350       }
1351       isNeg |= borrow;
1352       DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ",  u[j+i+1] == " << 
1353                     u[j+i+1] << '\n'); 
1354     }
1355     DEBUG(cerr << "KnuthDiv: after subtraction:");
1356     DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1357     DEBUG(cerr << '\n');
1358     // The digits (u[j+n]...u[j]) should be kept positive; if the result of 
1359     // this step is actually negative, (u[j+n]...u[j]) should be left as the 
1360     // true value plus b**(n+1), namely as the b's complement of
1361     // the true value, and a "borrow" to the left should be remembered.
1362     //
1363     if (isNeg) {
1364       bool carry = true;  // true because b's complement is "complement + 1"
1365       for (uint32_t i = 0; i <= m+n; ++i) {
1366         u[i] = ~u[i] + carry; // b's complement
1367         carry = carry && u[i] == 0;
1368       }
1369     }
1370     DEBUG(cerr << "KnuthDiv: after complement:");
1371     DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1372     DEBUG(cerr << '\n');
1373
1374     // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was 
1375     // negative, go to step D6; otherwise go on to step D7.
1376     q[j] = qp;
1377     if (isNeg) {
1378       // D6. [Add back]. The probability that this step is necessary is very 
1379       // small, on the order of only 2/b. Make sure that test data accounts for
1380       // this possibility. Decrease q[j] by 1 
1381       q[j]--;
1382       // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]). 
1383       // A carry will occur to the left of u[j+n], and it should be ignored 
1384       // since it cancels with the borrow that occurred in D4.
1385       bool carry = false;
1386       for (uint32_t i = 0; i < n; i++) {
1387         uint32_t limit = std::min(u[j+i],v[i]);
1388         u[j+i] += v[i] + carry;
1389         carry = u[j+i] < limit || (carry && u[j+i] == limit);
1390       }
1391       u[j+n] += carry;
1392     }
1393     DEBUG(cerr << "KnuthDiv: after correction:");
1394     DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1395     DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
1396
1397   // D7. [Loop on j.]  Decrease j by one. Now if j >= 0, go back to D3.
1398   } while (--j >= 0);
1399
1400   DEBUG(cerr << "KnuthDiv: quotient:");
1401   DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1402   DEBUG(cerr << '\n');
1403
1404   // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1405   // remainder may be obtained by dividing u[...] by d. If r is non-null we
1406   // compute the remainder (urem uses this).
1407   if (r) {
1408     // The value d is expressed by the "shift" value above since we avoided
1409     // multiplication by d by using a shift left. So, all we have to do is
1410     // shift right here. In order to mak
1411     if (shift) {
1412       uint32_t carry = 0;
1413       DEBUG(cerr << "KnuthDiv: remainder:");
1414       for (int i = n-1; i >= 0; i--) {
1415         r[i] = (u[i] >> shift) | carry;
1416         carry = u[i] << (32 - shift);
1417         DEBUG(cerr << " " << r[i]);
1418       }
1419     } else {
1420       for (int i = n-1; i >= 0; i--) {
1421         r[i] = u[i];
1422         DEBUG(cerr << " " << r[i]);
1423       }
1424     }
1425     DEBUG(cerr << '\n');
1426   }
1427   DEBUG(cerr << std::setbase(10) << '\n');
1428 }
1429
1430 void APInt::divide(const APInt LHS, uint32_t lhsWords, 
1431                    const APInt &RHS, uint32_t rhsWords,
1432                    APInt *Quotient, APInt *Remainder)
1433 {
1434   assert(lhsWords >= rhsWords && "Fractional result");
1435
1436   // First, compose the values into an array of 32-bit words instead of 
1437   // 64-bit words. This is a necessity of both the "short division" algorithm
1438   // and the the Knuth "classical algorithm" which requires there to be native 
1439   // operations for +, -, and * on an m bit value with an m*2 bit result. We 
1440   // can't use 64-bit operands here because we don't have native results of 
1441   // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't 
1442   // work on large-endian machines.
1443   uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1444   uint32_t n = rhsWords * 2;
1445   uint32_t m = (lhsWords * 2) - n;
1446
1447   // Allocate space for the temporary values we need either on the stack, if
1448   // it will fit, or on the heap if it won't.
1449   uint32_t SPACE[128];
1450   uint32_t *U = 0;
1451   uint32_t *V = 0;
1452   uint32_t *Q = 0;
1453   uint32_t *R = 0;
1454   if ((Remainder?4:3)*n+2*m+1 <= 128) {
1455     U = &SPACE[0];
1456     V = &SPACE[m+n+1];
1457     Q = &SPACE[(m+n+1) + n];
1458     if (Remainder)
1459       R = &SPACE[(m+n+1) + n + (m+n)];
1460   } else {
1461     U = new uint32_t[m + n + 1];
1462     V = new uint32_t[n];
1463     Q = new uint32_t[m+n];
1464     if (Remainder)
1465       R = new uint32_t[n];
1466   }
1467
1468   // Initialize the dividend
1469   memset(U, 0, (m+n+1)*sizeof(uint32_t));
1470   for (unsigned i = 0; i < lhsWords; ++i) {
1471     uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
1472     U[i * 2] = tmp & mask;
1473     U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1474   }
1475   U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1476
1477   // Initialize the divisor
1478   memset(V, 0, (n)*sizeof(uint32_t));
1479   for (unsigned i = 0; i < rhsWords; ++i) {
1480     uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
1481     V[i * 2] = tmp & mask;
1482     V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1483   }
1484
1485   // initialize the quotient and remainder
1486   memset(Q, 0, (m+n) * sizeof(uint32_t));
1487   if (Remainder)
1488     memset(R, 0, n * sizeof(uint32_t));
1489
1490   // Now, adjust m and n for the Knuth division. n is the number of words in 
1491   // the divisor. m is the number of words by which the dividend exceeds the
1492   // divisor (i.e. m+n is the length of the dividend). These sizes must not 
1493   // contain any zero words or the Knuth algorithm fails.
1494   for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1495     n--;
1496     m++;
1497   }
1498   for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1499     m--;
1500
1501   // If we're left with only a single word for the divisor, Knuth doesn't work
1502   // so we implement the short division algorithm here. This is much simpler
1503   // and faster because we are certain that we can divide a 64-bit quantity
1504   // by a 32-bit quantity at hardware speed and short division is simply a
1505   // series of such operations. This is just like doing short division but we
1506   // are using base 2^32 instead of base 10.
1507   assert(n != 0 && "Divide by zero?");
1508   if (n == 1) {
1509     uint32_t divisor = V[0];
1510     uint32_t remainder = 0;
1511     for (int i = m+n-1; i >= 0; i--) {
1512       uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1513       if (partial_dividend == 0) {
1514         Q[i] = 0;
1515         remainder = 0;
1516       } else if (partial_dividend < divisor) {
1517         Q[i] = 0;
1518         remainder = partial_dividend;
1519       } else if (partial_dividend == divisor) {
1520         Q[i] = 1;
1521         remainder = 0;
1522       } else {
1523         Q[i] = partial_dividend / divisor;
1524         remainder = partial_dividend - (Q[i] * divisor);
1525       }
1526     }
1527     if (R)
1528       R[0] = remainder;
1529   } else {
1530     // Now we're ready to invoke the Knuth classical divide algorithm. In this
1531     // case n > 1.
1532     KnuthDiv(U, V, Q, R, m, n);
1533   }
1534
1535   // If the caller wants the quotient
1536   if (Quotient) {
1537     // Set up the Quotient value's memory.
1538     if (Quotient->BitWidth != LHS.BitWidth) {
1539       if (Quotient->isSingleWord())
1540         Quotient->VAL = 0;
1541       else
1542         delete [] Quotient->pVal;
1543       Quotient->BitWidth = LHS.BitWidth;
1544       if (!Quotient->isSingleWord())
1545         Quotient->pVal = getClearedMemory(Quotient->getNumWords());
1546     } else
1547       Quotient->clear();
1548
1549     // The quotient is in Q. Reconstitute the quotient into Quotient's low 
1550     // order words.
1551     if (lhsWords == 1) {
1552       uint64_t tmp = 
1553         uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1554       if (Quotient->isSingleWord())
1555         Quotient->VAL = tmp;
1556       else
1557         Quotient->pVal[0] = tmp;
1558     } else {
1559       assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1560       for (unsigned i = 0; i < lhsWords; ++i)
1561         Quotient->pVal[i] = 
1562           uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1563     }
1564   }
1565
1566   // If the caller wants the remainder
1567   if (Remainder) {
1568     // Set up the Remainder value's memory.
1569     if (Remainder->BitWidth != RHS.BitWidth) {
1570       if (Remainder->isSingleWord())
1571         Remainder->VAL = 0;
1572       else
1573         delete [] Remainder->pVal;
1574       Remainder->BitWidth = RHS.BitWidth;
1575       if (!Remainder->isSingleWord())
1576         Remainder->pVal = getClearedMemory(Remainder->getNumWords());
1577     } else
1578       Remainder->clear();
1579
1580     // The remainder is in R. Reconstitute the remainder into Remainder's low
1581     // order words.
1582     if (rhsWords == 1) {
1583       uint64_t tmp = 
1584         uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1585       if (Remainder->isSingleWord())
1586         Remainder->VAL = tmp;
1587       else
1588         Remainder->pVal[0] = tmp;
1589     } else {
1590       assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1591       for (unsigned i = 0; i < rhsWords; ++i)
1592         Remainder->pVal[i] = 
1593           uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1594     }
1595   }
1596
1597   // Clean up the memory we allocated.
1598   if (U != &SPACE[0]) {
1599     delete [] U;
1600     delete [] V;
1601     delete [] Q;
1602     delete [] R;
1603   }
1604 }
1605
1606 APInt APInt::udiv(const APInt& RHS) const {
1607   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1608
1609   // First, deal with the easy case
1610   if (isSingleWord()) {
1611     assert(RHS.VAL != 0 && "Divide by zero?");
1612     return APInt(BitWidth, VAL / RHS.VAL);
1613   }
1614
1615   // Get some facts about the LHS and RHS number of bits and words
1616   uint32_t rhsBits = RHS.getActiveBits();
1617   uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1618   assert(rhsWords && "Divided by zero???");
1619   uint32_t lhsBits = this->getActiveBits();
1620   uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1621
1622   // Deal with some degenerate cases
1623   if (!lhsWords) 
1624     // 0 / X ===> 0
1625     return APInt(BitWidth, 0); 
1626   else if (lhsWords < rhsWords || this->ult(RHS)) {
1627     // X / Y ===> 0, iff X < Y
1628     return APInt(BitWidth, 0);
1629   } else if (*this == RHS) {
1630     // X / X ===> 1
1631     return APInt(BitWidth, 1);
1632   } else if (lhsWords == 1 && rhsWords == 1) {
1633     // All high words are zero, just use native divide
1634     return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
1635   }
1636
1637   // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1638   APInt Quotient(1,0); // to hold result.
1639   divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1640   return Quotient;
1641 }
1642
1643 APInt APInt::urem(const APInt& RHS) const {
1644   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1645   if (isSingleWord()) {
1646     assert(RHS.VAL != 0 && "Remainder by zero?");
1647     return APInt(BitWidth, VAL % RHS.VAL);
1648   }
1649
1650   // Get some facts about the LHS
1651   uint32_t lhsBits = getActiveBits();
1652   uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
1653
1654   // Get some facts about the RHS
1655   uint32_t rhsBits = RHS.getActiveBits();
1656   uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1657   assert(rhsWords && "Performing remainder operation by zero ???");
1658
1659   // Check the degenerate cases
1660   if (lhsWords == 0) {
1661     // 0 % Y ===> 0
1662     return APInt(BitWidth, 0);
1663   } else if (lhsWords < rhsWords || this->ult(RHS)) {
1664     // X % Y ===> X, iff X < Y
1665     return *this;
1666   } else if (*this == RHS) {
1667     // X % X == 0;
1668     return APInt(BitWidth, 0);
1669   } else if (lhsWords == 1) {
1670     // All high words are zero, just use native remainder
1671     return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
1672   }
1673
1674   // We have to compute it the hard way. Invoke the Knute divide algorithm.
1675   APInt Remainder(1,0);
1676   divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1677   return Remainder;
1678 }
1679
1680 void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen, 
1681                        uint8_t radix) {
1682   // Check our assumptions here
1683   assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1684          "Radix should be 2, 8, 10, or 16!");
1685   assert(str && "String is null?");
1686   bool isNeg = str[0] == '-';
1687   if (isNeg)
1688     str++, slen--;
1689   assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1690   assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1691   assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1692   assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1693
1694   // Allocate memory
1695   if (!isSingleWord())
1696     pVal = getClearedMemory(getNumWords());
1697
1698   // Figure out if we can shift instead of multiply
1699   uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1700
1701   // Set up an APInt for the digit to add outside the loop so we don't
1702   // constantly construct/destruct it.
1703   APInt apdigit(getBitWidth(), 0);
1704   APInt apradix(getBitWidth(), radix);
1705
1706   // Enter digit traversal loop
1707   for (unsigned i = 0; i < slen; i++) {
1708     // Get a digit
1709     uint32_t digit = 0;
1710     char cdigit = str[i];
1711     if (isdigit(cdigit))
1712       digit = cdigit - '0';
1713     else if (isxdigit(cdigit))
1714       if (cdigit >= 'a')
1715         digit = cdigit - 'a' + 10;
1716       else if (cdigit >= 'A')
1717         digit = cdigit - 'A' + 10;
1718       else
1719         assert(0 && "huh?");
1720     else
1721       assert(0 && "Invalid character in digit string");
1722
1723     // Shift or multiple the value by the radix
1724     if (shift)
1725       this->shl(shift);
1726     else
1727       *this *= apradix;
1728
1729     // Add in the digit we just interpreted
1730     if (apdigit.isSingleWord())
1731       apdigit.VAL = digit;
1732     else
1733       apdigit.pVal[0] = digit;
1734     *this += apdigit;
1735   }
1736   // If its negative, put it in two's complement form
1737   if (isNeg) {
1738     (*this)--;
1739     this->flip();
1740   }
1741 }
1742
1743 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1744   assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1745          "Radix should be 2, 8, 10, or 16!");
1746   static const char *digits[] = { 
1747     "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F" 
1748   };
1749   std::string result;
1750   uint32_t bits_used = getActiveBits();
1751   if (isSingleWord()) {
1752     char buf[65];
1753     const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1754        (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1755     if (format) {
1756       if (wantSigned) {
1757         int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >> 
1758                            (APINT_BITS_PER_WORD-BitWidth);
1759         sprintf(buf, format, sextVal);
1760       } else 
1761         sprintf(buf, format, VAL);
1762     } else {
1763       memset(buf, 0, 65);
1764       uint64_t v = VAL;
1765       while (bits_used) {
1766         uint32_t bit = v & 1;
1767         bits_used--;
1768         buf[bits_used] = digits[bit][0];
1769         v >>=1;
1770       }
1771     }
1772     result = buf;
1773     return result;
1774   }
1775
1776   if (radix != 10) {
1777     uint64_t mask = radix - 1;
1778     uint32_t shift = (radix == 16 ? 4 : radix  == 8 ? 3 : 1);
1779     uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1780     for (uint32_t i = 0; i < getNumWords(); ++i) {
1781       uint64_t value = pVal[i];
1782       for (uint32_t j = 0; j < nibbles; ++j) {
1783         result.insert(0, digits[ value & mask ]);
1784         value >>= shift;
1785       }
1786     }
1787     return result;
1788   }
1789
1790   APInt tmp(*this);
1791   APInt divisor(4, radix);
1792   APInt zero(tmp.getBitWidth(), 0);
1793   size_t insert_at = 0;
1794   if (wantSigned && tmp[BitWidth-1]) {
1795     // They want to print the signed version and it is a negative value
1796     // Flip the bits and add one to turn it into the equivalent positive
1797     // value and put a '-' in the result.
1798     tmp.flip();
1799     tmp++;
1800     result = "-";
1801     insert_at = 1;
1802   }
1803   if (tmp == APInt(tmp.getBitWidth(), 0))
1804     result = "0";
1805   else while (tmp.ne(zero)) {
1806     APInt APdigit(1,0);
1807     APInt tmp2(tmp.getBitWidth(), 0);
1808     divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2, 
1809            &APdigit);
1810     uint32_t digit = APdigit.getZExtValue();
1811     assert(digit < radix && "divide failed");
1812     result.insert(insert_at,digits[digit]);
1813     tmp = tmp2;
1814   }
1815
1816   return result;
1817 }
1818
1819 #ifndef NDEBUG
1820 void APInt::dump() const
1821 {
1822   cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
1823   if (isSingleWord())
1824     cerr << VAL;
1825   else for (unsigned i = getNumWords(); i > 0; i--) {
1826     cerr << pVal[i-1] << " ";
1827   }
1828   cerr << " U(" << this->toString(10) << ") S(" << this->toStringSigned(10)
1829        << ")\n" << std::setbase(10);
1830 }
1831 #endif