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