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