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