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