f8c3f4ae22e9ea9f11d06f993c9d0087f1a68148
[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 #include "llvm/ADT/APInt.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Support/MathExtras.h"
18 #include <cstring>
19 #include <cstdlib>
20 using namespace llvm;
21
22 // A utility function for allocating memory, checking for allocation failures,
23 // and ensuring the contents is zeroed.
24 inline static uint64_t* getClearedMemory(uint32_t numWords) {
25   uint64_t * result = new uint64_t[numWords];
26   assert(result && "APInt memory allocation fails!");
27   memset(result, 0, numWords * sizeof(uint64_t));
28   return result;
29 }
30
31 // A utility function for allocating memory and checking for allocation failure.
32 inline static uint64_t* getMemory(uint32_t numWords) {
33   uint64_t * result = new uint64_t[numWords];
34   assert(result && "APInt memory allocation fails!");
35   return result;
36 }
37
38 APInt::APInt(uint32_t numBits, uint64_t val)
39   : BitWidth(numBits) {
40   assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
41   assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
42   if (isSingleWord()) 
43     VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
44   else {
45     pVal = getClearedMemory(getNumWords());
46     pVal[0] = val;
47   }
48 }
49
50 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
51   : BitWidth(numBits) {
52   assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
53   assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
54   assert(bigVal && "Null pointer detected!");
55   if (isSingleWord())
56     VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
57   else {
58     pVal = getMemory(getNumWords());
59     // Calculate the actual length of bigVal[].
60     uint32_t maxN = std::max<uint32_t>(numWords, getNumWords());
61     uint32_t minN = std::min<uint32_t>(numWords, getNumWords());
62     memcpy(pVal, bigVal, (minN - 1) * sizeof(uint64_t));
63     pVal[minN-1] = bigVal[minN-1] & 
64                     (~uint64_t(0ULL) >> 
65                      (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
66     if (maxN == getNumWords())
67       memset(pVal+numWords, 0, (getNumWords() - numWords) * sizeof(uint64_t));
68   }
69 }
70
71 /// @brief Create a new APInt by translating the char array represented
72 /// integer value.
73 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen, 
74              uint8_t radix) {
75   fromString(numbits, StrStart, slen, radix);
76 }
77
78 /// @brief Create a new APInt by translating the string represented
79 /// integer value.
80 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix) {
81   assert(!Val.empty() && "String empty?");
82   fromString(numbits, Val.c_str(), Val.size(), radix);
83 }
84
85 APInt::APInt(const APInt& APIVal)
86   : BitWidth(APIVal.BitWidth) {
87   if (isSingleWord()) 
88     VAL = APIVal.VAL;
89   else {
90     pVal = getMemory(getNumWords());
91     memcpy(pVal, APIVal.pVal, getNumWords() * sizeof(uint64_t));
92   }
93 }
94
95 APInt::~APInt() {
96   if (!isSingleWord() && pVal) delete[] pVal;
97 }
98
99 /// @brief Copy assignment operator. Create a new object from the given
100 /// APInt one by initialization.
101 APInt& APInt::operator=(const APInt& RHS) {
102   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
103   if (isSingleWord()) 
104     VAL = RHS.VAL;
105   else
106     memcpy(pVal, RHS.pVal, getNumWords() * sizeof(uint64_t));
107   return *this;
108 }
109
110 /// @brief Assignment operator. Assigns a common case integer value to 
111 /// the APInt.
112 APInt& APInt::operator=(uint64_t RHS) {
113   if (isSingleWord()) 
114     VAL = RHS;
115   else {
116     pVal[0] = RHS;
117     memset(pVal+1, 0, (getNumWords() - 1) * sizeof(uint64_t));
118   }
119   return *this;
120 }
121
122 /// add_1 - This function adds a single "digit" integer, y, to the multiple 
123 /// "digit" integer array,  x[]. x[] is modified to reflect the addition and
124 /// 1 is returned if there is a carry out, otherwise 0 is returned.
125 /// @returns the carry of the addition.
126 static uint64_t add_1(uint64_t dest[], 
127                              uint64_t x[], uint32_t len, 
128                              uint64_t y) {
129   for (uint32_t i = 0; i < len; ++i) {
130     dest[i] = y + x[i];
131     if (dest[i] < y)
132       y = 1;
133     else {
134       y = 0;
135       break;
136     }
137   }
138   return y;
139 }
140
141 /// @brief Prefix increment operator. Increments the APInt by one.
142 APInt& APInt::operator++() {
143   if (isSingleWord()) 
144     ++VAL;
145   else
146     add_1(pVal, pVal, getNumWords(), 1);
147   clearUnusedBits();
148   return *this;
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 static uint64_t sub_1(uint64_t x[], uint32_t len, 
157                              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 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   clearUnusedBits();
178   return *this;
179 }
180
181 /// add - This function adds the integer array x[] by integer array
182 /// y[] and returns the carry.
183 static uint64_t add(uint64_t dest[], uint64_t x[], 
184                            uint64_t y[], uint32_t len) {
185   uint32_t carry = 0;
186   for (uint32_t i = 0; i< len; ++i) {
187     carry += x[i];
188     dest[i] = carry + y[i];
189     carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
190   }
191   return carry;
192 }
193
194 /// @brief Addition assignment operator. Adds this APInt by the given APInt&
195 /// RHS and assigns the result to this APInt.
196 APInt& APInt::operator+=(const APInt& RHS) {
197   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
198   if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
199   else {
200     if (RHS.isSingleWord()) add_1(pVal, pVal, getNumWords(), RHS.VAL);
201     else {
202       if (getNumWords() <= RHS.getNumWords()) 
203         add(pVal, pVal, RHS.pVal, getNumWords());
204       else {
205         uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.getNumWords());
206         add_1(pVal + RHS.getNumWords(), pVal + RHS.getNumWords(), 
207               getNumWords() - RHS.getNumWords(), carry);
208       }
209     }
210   }
211   clearUnusedBits();
212   return *this;
213 }
214
215 /// sub - This function subtracts the integer array x[] by
216 /// integer array y[], and returns the borrow-out carry.
217 static uint64_t sub(uint64_t dest[], uint64_t x[], 
218                            uint64_t y[], uint32_t len) {
219   // Carry indicator.
220   uint64_t cy = 0;
221   
222   for (uint32_t i = 0; i < len; ++i) {
223     uint64_t Y = y[i], X = x[i];
224     Y += cy;
225
226     cy = Y < cy ? 1 : 0;
227     Y = X - Y;
228     cy += Y > X ? 1 : 0;
229     dest[i] = Y;
230   }
231   return cy;
232 }
233
234 /// @brief Subtraction assignment operator. Subtracts this APInt by the given
235 /// APInt &RHS and assigns the result to this APInt.
236 APInt& APInt::operator-=(const APInt& RHS) {
237   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
238   if (isSingleWord()) 
239     VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
240   else {
241     if (RHS.isSingleWord())
242       sub_1(pVal, getNumWords(), RHS.VAL);
243     else {
244       if (RHS.getNumWords() < getNumWords()) { 
245         uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.getNumWords());
246         sub_1(pVal + RHS.getNumWords(), getNumWords() - RHS.getNumWords(), 
247               carry); 
248       }
249       else
250         sub(pVal, pVal, RHS.pVal, getNumWords());
251     }
252   }
253   clearUnusedBits();
254   return *this;
255 }
256
257 /// mul_1 - This function performs the multiplication operation on a
258 /// large integer (represented as an integer array) and a uint64_t integer.
259 /// @returns the carry of the multiplication.
260 static uint64_t mul_1(uint64_t dest[], 
261                              uint64_t x[], uint32_t len, 
262                              uint64_t y) {
263   // Split y into high 32-bit part and low 32-bit part.
264   uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
265   uint64_t carry = 0, lx, hx;
266   for (uint32_t i = 0; i < len; ++i) {
267     lx = x[i] & 0xffffffffULL;
268     hx = x[i] >> 32;
269     // hasCarry - A flag to indicate if has carry.
270     // hasCarry == 0, no carry
271     // hasCarry == 1, has carry
272     // hasCarry == 2, no carry and the calculation result == 0.
273     uint8_t hasCarry = 0;
274     dest[i] = carry + lx * ly;
275     // Determine if the add above introduces carry.
276     hasCarry = (dest[i] < carry) ? 1 : 0;
277     carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
278     // The upper limit of carry can be (2^32 - 1)(2^32 - 1) + 
279     // (2^32 - 1) + 2^32 = 2^64.
280     hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
281
282     carry += (lx * hy) & 0xffffffffULL;
283     dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
284     carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) + 
285             (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
286   }
287
288   return carry;
289 }
290
291 /// mul - This function multiplies integer array x[] by integer array y[] and
292 /// stores the result into integer array dest[].
293 /// Note the array dest[]'s size should no less than xlen + ylen.
294 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
295                 uint64_t y[], uint32_t ylen) {
296   dest[xlen] = mul_1(dest, x, xlen, y[0]);
297
298   for (uint32_t i = 1; i < ylen; ++i) {
299     uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
300     uint64_t carry = 0, lx, hx;
301     for (uint32_t j = 0; j < xlen; ++j) {
302       lx = x[j] & 0xffffffffULL;
303       hx = x[j] >> 32;
304       // hasCarry - A flag to indicate if has carry.
305       // hasCarry == 0, no carry
306       // hasCarry == 1, has carry
307       // hasCarry == 2, no carry and the calculation result == 0.
308       uint8_t hasCarry = 0;
309       uint64_t resul = carry + lx * ly;
310       hasCarry = (resul < carry) ? 1 : 0;
311       carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
312       hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
313
314       carry += (lx * hy) & 0xffffffffULL;
315       resul = (carry << 32) | (resul & 0xffffffffULL);
316       dest[i+j] += resul;
317       carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
318               (carry >> 32) + (dest[i+j] < resul ? 1 : 0) + 
319               ((lx * hy) >> 32) + hx * hy;
320     }
321     dest[i+xlen] = carry;
322   }
323 }
324
325 /// @brief Multiplication assignment operator. Multiplies this APInt by the 
326 /// given APInt& RHS and assigns the result to this APInt.
327 APInt& APInt::operator*=(const APInt& RHS) {
328   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
329   if (isSingleWord()) VAL *= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
330   else {
331     // one-based first non-zero bit position.
332     uint32_t first = getActiveBits();
333     uint32_t xlen = !first ? 0 : whichWord(first - 1) + 1;
334     if (!xlen) 
335       return *this;
336     else if (RHS.isSingleWord()) 
337       mul_1(pVal, pVal, xlen, RHS.VAL);
338     else {
339       first = RHS.getActiveBits();
340       uint32_t ylen = !first ? 0 : whichWord(first - 1) + 1;
341       if (!ylen) {
342         memset(pVal, 0, getNumWords() * sizeof(uint64_t));
343         return *this;
344       }
345       uint64_t *dest = getMemory(xlen+ylen);
346       mul(dest, pVal, xlen, RHS.pVal, ylen);
347       memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ? 
348                          getNumWords() : xlen + ylen) * sizeof(uint64_t));
349       delete[] dest;
350     }
351   }
352   clearUnusedBits();
353   return *this;
354 }
355
356 /// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
357 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
358 APInt& APInt::operator&=(const APInt& RHS) {
359   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
360   if (isSingleWord()) {
361     VAL &= RHS.VAL;
362     return *this;
363   }
364   uint32_t numWords = getNumWords();
365   for (uint32_t i = 0; i < numWords; ++i)
366     pVal[i] &= RHS.pVal[i];
367   return *this;
368 }
369
370 /// @brief Bitwise OR assignment operator. Performs bitwise OR operation on 
371 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
372 APInt& APInt::operator|=(const APInt& RHS) {
373   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
374   if (isSingleWord()) {
375     VAL |= RHS.VAL;
376     return *this;
377   }
378   uint32_t numWords = getNumWords();
379   for (uint32_t i = 0; i < numWords; ++i)
380     pVal[i] |= RHS.pVal[i];
381   return *this;
382 }
383
384 /// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
385 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
386 APInt& APInt::operator^=(const APInt& RHS) {
387   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
388   if (isSingleWord()) {
389     VAL ^= RHS.VAL;
390     return *this;
391   } 
392   uint32_t numWords = getNumWords();
393   for (uint32_t i = 0; i < numWords; ++i)
394     pVal[i] ^= RHS.pVal[i];
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   APInt Result(*this);
419   uint32_t numWords = getNumWords();
420   for (uint32_t i = 0; i < numWords; ++i)
421     Result.pVal[i] |= RHS.pVal[i];
422   return Result;
423 }
424
425 /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
426 /// and the given APInt& RHS.
427 APInt APInt::operator^(const APInt& RHS) const {
428   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
429   if (isSingleWord())
430     return APInt(getBitWidth(), VAL ^ RHS.VAL);
431   APInt Result(*this);
432   uint32_t numWords = getNumWords();
433   for (uint32_t i = 0; i < numWords; ++i)
434     Result.pVal[i] ^= RHS.pVal[i];
435   return Result;
436 }
437
438 /// @brief Logical negation operator. Performs logical negation operation on
439 /// this APInt.
440 bool APInt::operator !() const {
441   if (isSingleWord())
442     return !VAL;
443
444   for (uint32_t i = 0; i < getNumWords(); ++i)
445     if (pVal[i]) 
446       return false;
447   return true;
448 }
449
450 /// @brief Multiplication operator. Multiplies this APInt by the given APInt& 
451 /// RHS.
452 APInt APInt::operator*(const APInt& RHS) const {
453   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
454   APInt API(RHS);
455   API *= *this;
456   API.clearUnusedBits();
457   return API;
458 }
459
460 /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
461 APInt APInt::operator+(const APInt& RHS) const {
462   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
463   APInt API(*this);
464   API += RHS;
465   API.clearUnusedBits();
466   return API;
467 }
468
469 /// @brief Subtraction operator. Subtracts 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   APInt API(*this);
473   API -= RHS;
474   return API;
475 }
476
477 /// @brief Array-indexing support.
478 bool APInt::operator[](uint32_t bitPosition) const {
479   return (maskBit(bitPosition) & (isSingleWord() ? 
480           VAL : pVal[whichWord(bitPosition)])) != 0;
481 }
482
483 /// @brief Equality operator. Compare this APInt with the given APInt& RHS 
484 /// for the validity of the equality relationship.
485 bool APInt::operator==(const APInt& RHS) const {
486   uint32_t n1 = getActiveBits();
487   uint32_t n2 = RHS.getActiveBits();
488   if (n1 != n2) return false;
489   else if (isSingleWord()) 
490     return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
491   else {
492     if (n1 <= APINT_BITS_PER_WORD)
493       return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
494     for (int i = whichWord(n1 - 1); i >= 0; --i)
495       if (pVal[i] != RHS.pVal[i]) return false;
496   }
497   return true;
498 }
499
500 /// @brief Equality operator. Compare this APInt with the given uint64_t value 
501 /// for the validity of the equality relationship.
502 bool APInt::operator==(uint64_t Val) const {
503   if (isSingleWord())
504     return VAL == Val;
505   else {
506     uint32_t n = getActiveBits(); 
507     if (n <= APINT_BITS_PER_WORD)
508       return pVal[0] == Val;
509     else
510       return false;
511   }
512 }
513
514 /// @brief Unsigned less than comparison
515 bool APInt::ult(const APInt& RHS) const {
516   assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
517   if (isSingleWord())
518     return VAL < RHS.VAL;
519   else {
520     uint32_t n1 = getActiveBits();
521     uint32_t n2 = RHS.getActiveBits();
522     if (n1 < n2)
523       return true;
524     else if (n2 < n1)
525       return false;
526     else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
527       return pVal[0] < RHS.pVal[0];
528     for (int i = whichWord(n1 - 1); i >= 0; --i) {
529       if (pVal[i] > RHS.pVal[i]) return false;
530       else if (pVal[i] < RHS.pVal[i]) return true;
531     }
532   }
533   return false;
534 }
535
536 /// @brief Signed less than comparison
537 bool APInt::slt(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 /// Set the given bit to 1 whose poition is given as "bitPosition".
559 /// @brief Set a given bit to 1.
560 APInt& APInt::set(uint32_t bitPosition) {
561   if (isSingleWord()) VAL |= maskBit(bitPosition);
562   else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
563   return *this;
564 }
565
566 /// @brief Set every bit to 1.
567 APInt& APInt::set() {
568   if (isSingleWord()) 
569     VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
570   else {
571     for (uint32_t i = 0; i < getNumWords() - 1; ++i)
572       pVal[i] = -1ULL;
573     pVal[getNumWords() - 1] = ~0ULL >> 
574       (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
575   }
576   return *this;
577 }
578
579 /// Set the given bit to 0 whose position is given as "bitPosition".
580 /// @brief Set a given bit to 0.
581 APInt& APInt::clear(uint32_t bitPosition) {
582   if (isSingleWord()) 
583     VAL &= ~maskBit(bitPosition);
584   else 
585     pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
586   return *this;
587 }
588
589 /// @brief Set every bit to 0.
590 APInt& APInt::clear() {
591   if (isSingleWord()) 
592     VAL = 0;
593   else 
594     memset(pVal, 0, getNumWords() * sizeof(uint64_t));
595   return *this;
596 }
597
598 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
599 /// this APInt.
600 APInt APInt::operator~() const {
601   APInt API(*this);
602   API.flip();
603   return API;
604 }
605
606 /// @brief Toggle every bit to its opposite value.
607 APInt& APInt::flip() {
608   if (isSingleWord()) VAL = (~(VAL << 
609         (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
610   else {
611     uint32_t i = 0;
612     for (; i < getNumWords() - 1; ++i)
613       pVal[i] = ~pVal[i];
614     uint32_t offset = 
615       APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
616     pVal[i] = (~(pVal[i] << offset)) >> offset;
617   }
618   return *this;
619 }
620
621 /// Toggle a given bit to its opposite value whose position is given 
622 /// as "bitPosition".
623 /// @brief Toggles a given bit to its opposite value.
624 APInt& APInt::flip(uint32_t bitPosition) {
625   assert(bitPosition < BitWidth && "Out of the bit-width range!");
626   if ((*this)[bitPosition]) clear(bitPosition);
627   else set(bitPosition);
628   return *this;
629 }
630
631 /// to_string - This function translates the APInt into a string.
632 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
633   assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
634          "Radix should be 2, 8, 10, or 16!");
635   static const char *digits[] = { 
636     "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F" 
637   };
638   std::string result;
639   uint32_t bits_used = getActiveBits();
640   if (isSingleWord()) {
641     char buf[65];
642     const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
643        (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
644     if (format) {
645       if (wantSigned) {
646         int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >> 
647                            (APINT_BITS_PER_WORD-BitWidth);
648         sprintf(buf, format, sextVal);
649       } else 
650         sprintf(buf, format, VAL);
651     } else {
652       memset(buf, 0, 65);
653       uint64_t v = VAL;
654       while (bits_used) {
655         uint32_t bit = v & 1;
656         bits_used--;
657         buf[bits_used] = digits[bit][0];
658         v >>=1;
659       }
660     }
661     result = buf;
662     return result;
663   }
664
665   APInt tmp(*this);
666   APInt divisor(tmp.getBitWidth(), radix);
667   APInt zero(tmp.getBitWidth(), 0);
668   size_t insert_at = 0;
669   if (wantSigned && tmp[BitWidth-1]) {
670     // They want to print the signed version and it is a negative value
671     // Flip the bits and add one to turn it into the equivalent positive
672     // value and put a '-' in the result.
673     tmp.flip();
674     tmp++;
675     result = "-";
676     insert_at = 1;
677   }
678   if (tmp == 0)
679     result = "0";
680   else while (tmp.ne(zero)) {
681     APInt APdigit = APIntOps::urem(tmp,divisor);
682     uint32_t digit = APdigit.getValue();
683     assert(digit < radix && "urem failed");
684     result.insert(insert_at,digits[digit]);
685     tmp = APIntOps::udiv(tmp, divisor);
686   }
687
688   return result;
689 }
690
691 /// getMaxValue - This function returns the largest value
692 /// for an APInt of the specified bit-width and if isSign == true,
693 /// it should be largest signed value, otherwise unsigned value.
694 APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
695   APInt APIVal(numBits, 0);
696   APIVal.set();
697   if (isSign) APIVal.clear(numBits - 1);
698   return APIVal;
699 }
700
701 /// getMinValue - This function returns the smallest value for
702 /// an APInt of the given bit-width and if isSign == true,
703 /// it should be smallest signed value, otherwise zero.
704 APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
705   APInt APIVal(numBits, 0);
706   if (isSign) APIVal.set(numBits - 1);
707   return APIVal;
708 }
709
710 /// getAllOnesValue - This function returns an all-ones value for
711 /// an APInt of the specified bit-width.
712 APInt APInt::getAllOnesValue(uint32_t numBits) {
713   return getMaxValue(numBits, false);
714 }
715
716 /// getNullValue - This function creates an '0' value for an
717 /// APInt of the specified bit-width.
718 APInt APInt::getNullValue(uint32_t numBits) {
719   return getMinValue(numBits, false);
720 }
721
722 /// HiBits - This function returns the high "numBits" bits of this APInt.
723 APInt APInt::getHiBits(uint32_t numBits) const {
724   return APIntOps::lshr(*this, BitWidth - numBits);
725 }
726
727 /// LoBits - This function returns the low "numBits" bits of this APInt.
728 APInt APInt::getLoBits(uint32_t numBits) const {
729   return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits), 
730                         BitWidth - numBits);
731 }
732
733 bool APInt::isPowerOf2() const {
734   return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
735 }
736
737 /// countLeadingZeros - This function is a APInt version corresponding to 
738 /// llvm/include/llvm/Support/MathExtras.h's function 
739 /// countLeadingZeros_{32, 64}. It performs platform optimal form of counting 
740 /// the number of zeros from the most significant bit to the first one bit.
741 /// @returns numWord() * 64 if the value is zero.
742 uint32_t APInt::countLeadingZeros() const {
743   if (isSingleWord())
744     return CountLeadingZeros_64(VAL) - (APINT_BITS_PER_WORD - BitWidth);
745   uint32_t Count = 0;
746   for (uint32_t i = getNumWords(); i > 0u; --i) {
747     uint32_t tmp = CountLeadingZeros_64(pVal[i-1]);
748     Count += tmp;
749     if (tmp != APINT_BITS_PER_WORD)
750       if (i == getNumWords())
751         Count -= (APINT_BITS_PER_WORD - whichBit(BitWidth));
752       break;
753   }
754   return Count;
755 }
756
757 /// countTrailingZeros - This function is a APInt version corresponding to
758 /// llvm/include/llvm/Support/MathExtras.h's function 
759 /// countTrailingZeros_{32, 64}. It performs platform optimal form of counting 
760 /// the number of zeros from the least significant bit to the first one bit.
761 /// @returns numWord() * 64 if the value is zero.
762 uint32_t APInt::countTrailingZeros() const {
763   if (isSingleWord())
764     return CountTrailingZeros_64(VAL);
765   APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
766   return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
767 }
768
769 /// countPopulation - This function is a APInt version corresponding to
770 /// llvm/include/llvm/Support/MathExtras.h's function
771 /// countPopulation_{32, 64}. It counts the number of set bits in a value.
772 /// @returns 0 if the value is zero.
773 uint32_t APInt::countPopulation() const {
774   if (isSingleWord())
775     return CountPopulation_64(VAL);
776   uint32_t Count = 0;
777   for (uint32_t i = 0; i < getNumWords(); ++i)
778     Count += CountPopulation_64(pVal[i]);
779   return Count;
780 }
781
782
783 /// byteSwap - This function returns a byte-swapped representation of the
784 /// this APInt.
785 APInt APInt::byteSwap() const {
786   assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
787   if (BitWidth == 16)
788     return APInt(BitWidth, ByteSwap_16(VAL));
789   else if (BitWidth == 32)
790     return APInt(BitWidth, ByteSwap_32(VAL));
791   else if (BitWidth == 48) {
792     uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
793     Tmp1 = ByteSwap_32(Tmp1);
794     uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
795     Tmp2 = ByteSwap_16(Tmp2);
796     return 
797       APInt(BitWidth, 
798             (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
799   } else if (BitWidth == 64)
800     return APInt(BitWidth, ByteSwap_64(VAL));
801   else {
802     APInt Result(BitWidth, 0);
803     char *pByte = (char*)Result.pVal;
804     for (uint32_t i = 0; i < BitWidth / sizeof(uint64_t) / 2; ++i) {
805       char Tmp = pByte[i];
806       pByte[i] = pByte[BitWidth / sizeof(uint64_t) - 1 - i];
807       pByte[BitWidth / sizeof(uint64_t) - i - 1] = Tmp;
808     }
809     return Result;
810   }
811 }
812
813 /// GreatestCommonDivisor - This function returns the greatest common
814 /// divisor of the two APInt values using Enclid's algorithm.
815 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1, 
816                                             const APInt& API2) {
817   APInt A = API1, B = API2;
818   while (!!B) {
819     APInt T = B;
820     B = APIntOps::urem(A, B);
821     A = T;
822   }
823   return A;
824 }
825
826 /// DoubleRoundToAPInt - This function convert a double value to
827 /// a APInt value.
828 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
829   union {
830     double D;
831     uint64_t I;
832   } T;
833   T.D = Double;
834   bool isNeg = T.I >> 63;
835   int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
836   if (exp < 0)
837     return APInt(64ull, 0u);
838   uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
839   if (exp < 52)
840     return isNeg ? -APInt(64u, mantissa >> (52 - exp)) : 
841                     APInt(64u, mantissa >> (52 - exp));
842   APInt Tmp(exp + 1, mantissa);
843   Tmp = Tmp.shl(exp - 52);
844   return isNeg ? -Tmp : Tmp;
845 }
846
847 /// RoundToDouble - This function convert this APInt to a double.
848 /// The layout for double is as following (IEEE Standard 754):
849 ///  --------------------------------------
850 /// |  Sign    Exponent    Fraction    Bias |
851 /// |-------------------------------------- |
852 /// |  1[63]   11[62-52]   52[51-00]   1023 |
853 ///  -------------------------------------- 
854 double APInt::roundToDouble(bool isSigned) const {
855   bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
856   APInt Tmp(isNeg ? -(*this) : (*this));
857   if (Tmp.isSingleWord())
858     return isSigned ? double(int64_t(Tmp.VAL)) : double(Tmp.VAL);
859   uint32_t n = Tmp.getActiveBits();
860   if (n <= APINT_BITS_PER_WORD) 
861     return isSigned ? double(int64_t(Tmp.pVal[0])) : double(Tmp.pVal[0]);
862   // Exponent when normalized to have decimal point directly after
863   // leading one. This is stored excess 1023 in the exponent bit field.
864   uint64_t exp = n - 1;
865
866   // Gross overflow.
867   assert(exp <= 1023 && "Infinity value!");
868
869   // Number of bits in mantissa including the leading one
870   // equals to 53.
871   uint64_t mantissa;
872   if (n % APINT_BITS_PER_WORD >= 53)
873     mantissa = Tmp.pVal[whichWord(n - 1)] >> (n % APINT_BITS_PER_WORD - 53);
874   else
875     mantissa = (Tmp.pVal[whichWord(n - 1)] << (53 - n % APINT_BITS_PER_WORD)) | 
876                (Tmp.pVal[whichWord(n - 1) - 1] >> 
877                 (11 + n % APINT_BITS_PER_WORD));
878   // The leading bit of mantissa is implicit, so get rid of it.
879   mantissa &= ~(1ULL << 52);
880   uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
881   exp += 1023;
882   union {
883     double D;
884     uint64_t I;
885   } T;
886   T.I = sign | (exp << 52) | mantissa;
887   return T.D;
888 }
889
890 // Truncate to new width.
891 void APInt::trunc(uint32_t width) {
892   assert(width < BitWidth && "Invalid APInt Truncate request");
893 }
894
895 // Sign extend to a new width.
896 void APInt::sext(uint32_t width) {
897   assert(width > BitWidth && "Invalid APInt SignExtend request");
898 }
899
900 //  Zero extend to a new width.
901 void APInt::zext(uint32_t width) {
902   assert(width > BitWidth && "Invalid APInt ZeroExtend request");
903 }
904
905 /// Arithmetic right-shift this APInt by shiftAmt.
906 /// @brief Arithmetic right-shift function.
907 APInt APInt::ashr(uint32_t shiftAmt) const {
908   APInt API(*this);
909   if (API.isSingleWord())
910     API.VAL = 
911       (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >> 
912           (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) & 
913       (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
914   else {
915     if (shiftAmt >= API.BitWidth) {
916       memset(API.pVal, API[API.BitWidth-1] ? 1 : 0, 
917              (API.getNumWords()-1) * sizeof(uint64_t));
918       API.pVal[API.getNumWords() - 1] = 
919         ~uint64_t(0UL) >> 
920           (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
921     } else {
922       uint32_t i = 0;
923       for (; i < API.BitWidth - shiftAmt; ++i)
924         if (API[i+shiftAmt]) 
925           API.set(i);
926         else
927           API.clear(i);
928       for (; i < API.BitWidth; ++i)
929         if (API[API.BitWidth-1]) 
930           API.set(i);
931         else API.clear(i);
932     }
933   }
934   return API;
935 }
936
937 /// Logical right-shift this APInt by shiftAmt.
938 /// @brief Logical right-shift function.
939 APInt APInt::lshr(uint32_t shiftAmt) const {
940   APInt API(*this);
941   if (API.isSingleWord())
942     API.VAL >>= shiftAmt;
943   else {
944     if (shiftAmt >= API.BitWidth)
945       memset(API.pVal, 0, API.getNumWords() * sizeof(uint64_t));
946     uint32_t i = 0;
947     for (i = 0; i < API.BitWidth - shiftAmt; ++i)
948       if (API[i+shiftAmt]) API.set(i);
949       else API.clear(i);
950     for (; i < API.BitWidth; ++i)
951       API.clear(i);
952   }
953   return API;
954 }
955
956 /// Left-shift this APInt by shiftAmt.
957 /// @brief Left-shift function.
958 APInt APInt::shl(uint32_t shiftAmt) const {
959   APInt API(*this);
960   if (API.isSingleWord())
961     API.VAL <<= shiftAmt;
962   else if (shiftAmt >= API.BitWidth)
963     memset(API.pVal, 0, API.getNumWords() * sizeof(uint64_t));
964   else {
965     if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
966       for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
967         API.pVal[i] = API.pVal[i-offset];
968       memset(API.pVal, 0, offset * sizeof(uint64_t));
969     }
970     shiftAmt %= APINT_BITS_PER_WORD;
971     uint32_t i;
972     for (i = API.getNumWords() - 1; i > 0; --i)
973       API.pVal[i] = (API.pVal[i] << shiftAmt) | 
974                     (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
975     API.pVal[i] <<= shiftAmt;
976   }
977   API.clearUnusedBits();
978   return API;
979 }
980
981 /// subMul - This function substracts x[len-1:0] * y from 
982 /// dest[offset+len-1:offset], and returns the most significant 
983 /// word of the product, minus the borrow-out from the subtraction.
984 static uint32_t subMul(uint32_t dest[], uint32_t offset, 
985                         uint32_t x[], uint32_t len, uint32_t y) {
986   uint64_t yl = (uint64_t) y & 0xffffffffL;
987   uint32_t carry = 0;
988   uint32_t j = 0;
989   do {
990     uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
991     uint32_t prod_low = (uint32_t) prod;
992     uint32_t prod_high = (uint32_t) (prod >> 32);
993     prod_low += carry;
994     carry = (prod_low < carry ? 1 : 0) + prod_high;
995     uint32_t x_j = dest[offset+j];
996     prod_low = x_j - prod_low;
997     if (prod_low > x_j) ++carry;
998     dest[offset+j] = prod_low;
999   } while (++j < len);
1000   return carry;
1001 }
1002
1003 /// unitDiv - This function divides N by D, 
1004 /// and returns (remainder << 32) | quotient.
1005 /// Assumes (N >> 32) < D.
1006 static uint64_t unitDiv(uint64_t N, uint32_t D) {
1007   uint64_t q, r;                   // q: quotient, r: remainder.
1008   uint64_t a1 = N >> 32;           // a1: high 32-bit part of N.
1009   uint64_t a0 = N & 0xffffffffL;   // a0: low 32-bit part of N
1010   if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
1011       q = N / D;
1012       r = N % D;
1013   }
1014   else {
1015     // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
1016     uint64_t c = N - ((uint64_t) D << 31);
1017     // Divide (c1*2^32 + c0) by d
1018     q = c / D;
1019     r = c % D;
1020     // Add 2^31 to quotient 
1021     q += 1 << 31;
1022   }
1023
1024   return (r << 32) | (q & 0xFFFFFFFFl);
1025 }
1026
1027 /// div - This is basically Knuth's formulation of the classical algorithm.
1028 /// Correspondance with Knuth's notation:
1029 /// Knuth's u[0:m+n] == zds[nx:0].
1030 /// Knuth's v[1:n] == y[ny-1:0]
1031 /// Knuth's n == ny.
1032 /// Knuth's m == nx-ny.
1033 /// Our nx == Knuth's m+n.
1034 /// Could be re-implemented using gmp's mpn_divrem:
1035 /// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
1036 static void div(uint32_t zds[], uint32_t nx, uint32_t y[], uint32_t ny) {
1037   uint32_t j = nx;
1038   do {                          // loop over digits of quotient
1039     // Knuth's j == our nx-j.
1040     // Knuth's u[j:j+n] == our zds[j:j-ny].
1041     uint32_t qhat;  // treated as unsigned
1042     if (zds[j] == y[ny-1]) 
1043       qhat = -1U;  // 0xffffffff
1044     else {
1045       uint64_t w = (((uint64_t)(zds[j])) << 32) + 
1046                    ((uint64_t)zds[j-1] & 0xffffffffL);
1047       qhat = (uint32_t) unitDiv(w, y[ny-1]);
1048     }
1049     if (qhat) {
1050       uint32_t borrow = subMul(zds, j - ny, y, ny, qhat);
1051       uint32_t save = zds[j];
1052       uint64_t num = ((uint64_t)save&0xffffffffL) - 
1053                      ((uint64_t)borrow&0xffffffffL);
1054       while (num) {
1055         qhat--;
1056         uint64_t carry = 0;
1057         for (uint32_t i = 0;  i < ny; i++) {
1058           carry += ((uint64_t) zds[j-ny+i] & 0xffffffffL)
1059             + ((uint64_t) y[i] & 0xffffffffL);
1060           zds[j-ny+i] = (uint32_t) carry;
1061           carry >>= 32;
1062         }
1063         zds[j] += carry;
1064         num = carry - 1;
1065       }
1066     }
1067     zds[j] = qhat;
1068   } while (--j >= ny);
1069 }
1070
1071 /// Unsigned divide this APInt by APInt RHS.
1072 /// @brief Unsigned division function for APInt.
1073 APInt APInt::udiv(const APInt& RHS) const {
1074   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1075
1076   // First, deal with the easy case
1077   if (isSingleWord()) {
1078     assert(RHS.VAL != 0 && "Divide by zero?");
1079     return APInt(BitWidth, VAL / RHS.VAL);
1080   }
1081
1082   // Make a temporary to hold the result
1083   APInt Result(*this);
1084
1085   // Get some facts about the LHS and RHS number of bits and words
1086   uint32_t rhsBits = RHS.getActiveBits();
1087   uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1088   assert(rhsWords && "Divided by zero???");
1089   uint32_t lhsBits = Result.getActiveBits();
1090   uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1091
1092   // Deal with some degenerate cases
1093   if (!lhsWords) 
1094     return Result; // 0 / X == 0
1095   else if (lhsWords < rhsWords || Result.ult(RHS))
1096     // X / Y with X < Y == 0
1097     memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1098   else if (Result == RHS) {
1099     // X / X == 1
1100     memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1101     Result.pVal[0] = 1;
1102   } else if (lhsWords == 1)
1103     // All high words are zero, just use native divide
1104     Result.pVal[0] /= RHS.pVal[0];
1105   else {
1106     // Compute it the hard way ..
1107     APInt X(BitWidth, 0);
1108     APInt Y(BitWidth, 0);
1109     uint32_t nshift = 
1110       (APINT_BITS_PER_WORD - 1) - ((rhsBits - 1) % APINT_BITS_PER_WORD );
1111     if (nshift) {
1112       Y = APIntOps::shl(RHS, nshift);
1113       X = APIntOps::shl(Result, nshift);
1114       ++lhsWords;
1115     }
1116     div((uint32_t*)X.pVal, lhsWords * 2 - 1, 
1117         (uint32_t*)(Y.isSingleWord()? &Y.VAL : Y.pVal), rhsWords*2);
1118     memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1119     memcpy(Result.pVal, X.pVal + rhsWords, 
1120            (lhsWords - rhsWords) * sizeof(uint64_t));
1121   }
1122   return Result;
1123 }
1124
1125 /// Unsigned remainder operation on APInt.
1126 /// @brief Function for unsigned remainder operation.
1127 APInt APInt::urem(const APInt& RHS) const {
1128   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1129   if (isSingleWord()) {
1130     assert(RHS.VAL != 0 && "Remainder by zero?");
1131     return APInt(BitWidth, VAL % RHS.VAL);
1132   }
1133
1134   // Make a temporary to hold the result
1135   APInt Result(*this);
1136
1137   // Get some facts about the RHS
1138   uint32_t rhsBits = RHS.getActiveBits();
1139   uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1140   assert(rhsWords && "Performing remainder operation by zero ???");
1141
1142   // Get some facts about the LHS
1143   uint32_t lhsBits = Result.getActiveBits();
1144   uint32_t lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
1145
1146   // Check the degenerate cases
1147   if (lhsWords == 0)
1148     // 0 % Y == 0
1149     memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1150   else if (lhsWords < rhsWords || Result.ult(RHS))
1151     // X % Y == X iff X < Y
1152     return Result;
1153   else if (Result == RHS)
1154     // X % X == 0;
1155     memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1156   else if (lhsWords == 1) 
1157     // All high words are zero, just use native remainder
1158     Result.pVal[0] %=  RHS.pVal[0];
1159   else {
1160     // Do it the hard way
1161     APInt X((lhsWords+1)*APINT_BITS_PER_WORD, 0);
1162     APInt Y(rhsWords*APINT_BITS_PER_WORD, 0);
1163     uint32_t nshift = 
1164       (APINT_BITS_PER_WORD - 1) - (rhsBits - 1) % APINT_BITS_PER_WORD;
1165     if (nshift) {
1166       APIntOps::shl(Y, nshift);
1167       APIntOps::shl(X, nshift);
1168     }
1169     div((uint32_t*)X.pVal, rhsWords*2-1, 
1170         (uint32_t*)(Y.isSingleWord()? &Y.VAL : Y.pVal), rhsWords*2);
1171     memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1172     for (uint32_t i = 0; i < rhsWords-1; ++i)
1173       Result.pVal[i] = (X.pVal[i] >> nshift) | 
1174                         (X.pVal[i+1] << (APINT_BITS_PER_WORD - nshift));
1175     Result.pVal[rhsWords-1] = X.pVal[rhsWords-1] >> nshift;
1176   }
1177   return Result;
1178 }
1179
1180 /// @brief Converts a char array into an integer.
1181 void APInt::fromString(uint32_t numbits, const char *StrStart, uint32_t slen, 
1182                        uint8_t radix) {
1183   assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1184          "Radix should be 2, 8, 10, or 16!");
1185   assert(StrStart && "String is null?");
1186   uint32_t size = 0;
1187   // If the radix is a power of 2, read the input
1188   // from most significant to least significant.
1189   if ((radix & (radix - 1)) == 0) {
1190     uint32_t nextBitPos = 0; 
1191     uint32_t bits_per_digit = radix / 8 + 2;
1192     uint64_t resDigit = 0;
1193     BitWidth = slen * bits_per_digit;
1194     if (getNumWords() > 1)
1195       pVal = getMemory(getNumWords());
1196     for (int i = slen - 1; i >= 0; --i) {
1197       uint64_t digit = StrStart[i] - '0';
1198       resDigit |= digit << nextBitPos;
1199       nextBitPos += bits_per_digit;
1200       if (nextBitPos >= APINT_BITS_PER_WORD) {
1201         if (isSingleWord()) {
1202           VAL = resDigit;
1203            break;
1204         }
1205         pVal[size++] = resDigit;
1206         nextBitPos -= APINT_BITS_PER_WORD;
1207         resDigit = digit >> (bits_per_digit - nextBitPos);
1208       }
1209     }
1210     if (!isSingleWord() && size <= getNumWords()) 
1211       pVal[size] = resDigit;
1212   } else {   // General case.  The radix is not a power of 2.
1213     // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
1214     // and its digits number is 20.
1215     const uint32_t chars_per_word = 20;
1216     if (slen < chars_per_word || 
1217         (slen == chars_per_word &&             // In case the value <= 2^64 - 1
1218          strcmp(StrStart, "18446744073709551615") <= 0)) {
1219       BitWidth = APINT_BITS_PER_WORD;
1220       VAL = strtoull(StrStart, 0, 10);
1221     } else { // In case the value > 2^64 - 1
1222       BitWidth = (slen / chars_per_word + 1) * APINT_BITS_PER_WORD;
1223       pVal = getClearedMemory(getNumWords());
1224       uint32_t str_pos = 0;
1225       while (str_pos < slen) {
1226         uint32_t chunk = slen - str_pos;
1227         if (chunk > chars_per_word - 1)
1228           chunk = chars_per_word - 1;
1229         uint64_t resDigit = StrStart[str_pos++] - '0';
1230         uint64_t big_base = radix;
1231         while (--chunk > 0) {
1232           resDigit = resDigit * radix + StrStart[str_pos++] - '0';
1233           big_base *= radix;
1234         }
1235        
1236         uint64_t carry;
1237         if (!size)
1238           carry = resDigit;
1239         else {
1240           carry = mul_1(pVal, pVal, size, big_base);
1241           carry += add_1(pVal, pVal, size, resDigit);
1242         }
1243         
1244         if (carry) pVal[size++] = carry;
1245       }
1246     }
1247   }
1248 }