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