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