1 //===-- APInt.cpp - Implement APInt class ---------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements a class to represent arbitrary precision integral
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Support/MathExtras.h"
27 // A utility function for allocating memory, checking for allocation failures,
28 // and ensuring the contents is zeroed.
29 inline 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));
36 // A utility function for allocating memory and checking for allocation failure.
37 inline static uint64_t* getMemory(uint32_t numWords) {
38 uint64_t * result = new uint64_t[numWords];
39 assert(result && "APInt memory allocation fails!");
43 APInt::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");
48 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
50 pVal = getClearedMemory(getNumWords());
55 APInt::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!");
61 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
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] &
70 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
71 if (maxN == getNumWords())
72 memset(pVal+numWords, 0, (getNumWords() - numWords) * APINT_WORD_SIZE);
76 /// @brief Create a new APInt by translating the char array represented
78 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
80 : BitWidth(numbits), VAL(0) {
81 fromString(numbits, StrStart, slen, radix);
84 /// @brief Create a new APInt by translating the string represented
86 APInt::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);
92 /// @brief Copy constructor
93 APInt::APInt(const APInt& that)
94 : BitWidth(that.BitWidth), VAL(0) {
98 pVal = getMemory(getNumWords());
99 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
104 if (!isSingleWord() && pVal)
108 /// @brief Copy assignment operator. Create a new object from the given
109 /// APInt one by initialization.
110 APInt& APInt::operator=(const APInt& RHS) {
111 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
115 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
119 /// @brief Assignment operator. Assigns a common case integer value to
121 APInt& APInt::operator=(uint64_t RHS) {
126 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
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.
135 static uint64_t add_1(uint64_t dest[],
136 uint64_t x[], uint32_t len,
138 for (uint32_t i = 0; i < len; ++i) {
150 /// @brief Prefix increment operator. Increments the APInt by one.
151 APInt& APInt::operator++() {
155 add_1(pVal, pVal, getNumWords(), 1);
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.
165 static uint64_t sub_1(uint64_t x[], uint32_t len,
167 for (uint32_t i = 0; i < len; ++i) {
171 y = 1; // We have to "borrow 1" from next "digit"
173 y = 0; // No need to borrow
174 break; // Remaining digits are unchanged so exit early
180 /// @brief Prefix decrement operator. Decrements the APInt by one.
181 APInt& APInt::operator--() {
185 sub_1(pVal, getNumWords(), 1);
190 /// add - This function adds the integer array x[] by integer array
191 /// y[] and returns the carry.
192 static uint64_t add(uint64_t dest[], uint64_t x[], uint64_t y[], uint32_t len) {
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);
202 /// @brief Addition assignment operator. Adds this APInt by the given APInt&
203 /// RHS and assigns the result to this APInt.
204 APInt& APInt::operator+=(const APInt& RHS) {
205 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
209 add(pVal, pVal, RHS.pVal, getNumWords());
215 /// sub - This function subtracts the integer array x[] by
216 /// integer array y[], and returns the borrow-out carry.
217 static uint64_t sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
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];
228 /// @brief Subtraction assignment operator. Subtracts this APInt by the given
229 /// APInt &RHS and assigns the result to this APInt.
230 APInt& APInt::operator-=(const APInt& RHS) {
231 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
235 sub(pVal, pVal, RHS.pVal, getNumWords());
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.
243 static uint64_t mul_1(uint64_t dest[],
244 uint64_t x[], uint32_t len,
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;
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);
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;
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.
277 static 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]);
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;
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);
297 carry += (lx * hy) & 0xffffffffULL;
298 resul = (carry << 32) | (resul & 0xffffffffULL);
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;
304 dest[i+xlen] = carry;
308 /// @brief Multiplication assignment operator. Multiplies this APInt by the
309 /// given APInt& RHS and assigns the result to this APInt.
310 APInt& APInt::operator*=(const APInt& RHS) {
311 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
312 if (isSingleWord()) {
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;
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;
334 // Allocate space for the result
335 uint32_t destWords = rhsWords + lhsWords;
336 uint64_t *dest = getMemory(destWords);
338 // Perform the long multiply
339 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
341 // Copy result back into *this
343 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
344 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
346 // delete dest array and return
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.
353 APInt& APInt::operator&=(const APInt& RHS) {
354 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
355 if (isSingleWord()) {
359 uint32_t numWords = getNumWords();
360 for (uint32_t i = 0; i < numWords; ++i)
361 pVal[i] &= RHS.pVal[i];
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.
367 APInt& APInt::operator|=(const APInt& RHS) {
368 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
369 if (isSingleWord()) {
373 uint32_t numWords = getNumWords();
374 for (uint32_t i = 0; i < numWords; ++i)
375 pVal[i] |= RHS.pVal[i];
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.
381 APInt& APInt::operator^=(const APInt& RHS) {
382 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
383 if (isSingleWord()) {
385 this->clearUnusedBits();
388 uint32_t numWords = getNumWords();
389 for (uint32_t i = 0; i < numWords; ++i)
390 pVal[i] ^= RHS.pVal[i];
391 this->clearUnusedBits();
395 /// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
396 /// and the given APInt& RHS.
397 APInt APInt::operator&(const APInt& RHS) const {
398 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
400 return APInt(getBitWidth(), VAL & RHS.VAL);
403 uint32_t numWords = getNumWords();
404 for (uint32_t i = 0; i < numWords; ++i)
405 Result.pVal[i] &= RHS.pVal[i];
409 /// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
410 /// and the given APInt& RHS.
411 APInt APInt::operator|(const APInt& RHS) const {
412 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
414 return APInt(getBitWidth(), VAL | RHS.VAL);
417 uint32_t numWords = getNumWords();
418 for (uint32_t i = 0; i < numWords; ++i)
419 Result.pVal[i] |= RHS.pVal[i];
423 /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
424 /// and the given APInt& RHS.
425 APInt 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();
433 uint32_t numWords = getNumWords();
434 for (uint32_t i = 0; i < numWords; ++i)
435 Result.pVal[i] ^= RHS.pVal[i];
439 /// @brief Logical negation operator. Performs logical negation operation on
441 bool APInt::operator !() const {
445 for (uint32_t i = 0; i < getNumWords(); ++i)
451 /// @brief Multiplication operator. Multiplies this APInt by the given APInt&
453 APInt 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();
462 Result.clearUnusedBits();
466 /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
467 APInt 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();
474 APInt Result(BitWidth, 0);
475 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
476 Result.clearUnusedBits();
480 /// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
481 APInt 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();
488 APInt Result(BitWidth, 0);
489 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
490 Result.clearUnusedBits();
494 /// @brief Array-indexing support.
495 bool APInt::operator[](uint32_t bitPosition) const {
496 return (maskBit(bitPosition) & (isSingleWord() ?
497 VAL : pVal[whichWord(bitPosition)])) != 0;
500 /// @brief Equality operator. Compare this APInt with the given APInt& RHS
501 /// for the validity of the equality relationship.
502 bool APInt::operator==(const APInt& RHS) const {
504 return VAL == RHS.VAL;
506 uint32_t n1 = getActiveBits();
507 uint32_t n2 = RHS.getActiveBits();
511 if (n1 <= APINT_BITS_PER_WORD)
512 return pVal[0] == RHS.pVal[0];
514 for (int i = whichWord(n1 - 1); i >= 0; --i)
515 if (pVal[i] != RHS.pVal[i])
520 /// @brief Equality operator. Compare this APInt with the given uint64_t value
521 /// for the validity of the equality relationship.
522 bool APInt::operator==(uint64_t Val) const {
526 uint32_t n = getActiveBits();
527 if (n <= APINT_BITS_PER_WORD)
528 return pVal[0] == Val;
533 /// @brief Unsigned less than comparison
534 bool APInt::ult(const APInt& RHS) const {
535 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
537 return VAL < RHS.VAL;
539 uint32_t n1 = getActiveBits();
540 uint32_t n2 = RHS.getActiveBits();
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;
555 /// @brief Signed less than comparison
556 bool 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;
566 bool lhsNegative = false;
567 bool rhsNegative = false;
568 if (lhs[BitWidth-1]) {
573 if (rhs[BitWidth-1]) {
580 return !lhs.ult(rhs);
583 else if (rhsNegative)
589 /// Set the given bit to 1 whose poition is given as "bitPosition".
590 /// @brief Set a given bit to 1.
591 APInt& APInt::set(uint32_t bitPosition) {
592 if (isSingleWord()) VAL |= maskBit(bitPosition);
593 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
597 /// @brief Set every bit to 1.
598 APInt& APInt::set() {
600 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
602 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
604 pVal[getNumWords() - 1] = ~0ULL >>
605 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
610 /// Set the given bit to 0 whose position is given as "bitPosition".
611 /// @brief Set a given bit to 0.
612 APInt& APInt::clear(uint32_t bitPosition) {
614 VAL &= ~maskBit(bitPosition);
616 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
620 /// @brief Set every bit to 0.
621 APInt& APInt::clear() {
625 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
629 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
631 APInt APInt::operator~() const {
637 /// @brief Toggle every bit to its opposite value.
638 APInt& APInt::flip() {
639 if (isSingleWord()) VAL = (~(VAL <<
640 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
643 for (; i < getNumWords() - 1; ++i)
646 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
647 pVal[i] = (~(pVal[i] << offset)) >> offset;
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.
655 APInt& 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);
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.
665 APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
666 APInt Result(numBits, 0);
669 Result.clear(numBits - 1);
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.
676 APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
677 APInt Result(numBits, 0);
679 Result.set(numBits - 1);
683 /// getAllOnesValue - This function returns an all-ones value for
684 /// an APInt of the specified bit-width.
685 APInt APInt::getAllOnesValue(uint32_t numBits) {
686 return getMaxValue(numBits, false);
689 /// getNullValue - This function creates an '0' value for an
690 /// APInt of the specified bit-width.
691 APInt APInt::getNullValue(uint32_t numBits) {
692 return getMinValue(numBits, false);
695 /// HiBits - This function returns the high "numBits" bits of this APInt.
696 APInt APInt::getHiBits(uint32_t numBits) const {
697 return APIntOps::lshr(*this, BitWidth - numBits);
700 /// LoBits - This function returns the low "numBits" bits of this APInt.
701 APInt APInt::getLoBits(uint32_t numBits) const {
702 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
706 bool APInt::isPowerOf2() const {
707 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
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.
715 uint32_t APInt::countLeadingZeros() const {
718 Count = CountLeadingZeros_64(VAL);
720 for (uint32_t i = getNumWords(); i > 0u; --i) {
722 Count += APINT_BITS_PER_WORD;
724 Count += CountLeadingZeros_64(pVal[i-1]);
729 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
731 Count -= APINT_BITS_PER_WORD - remainder;
735 /// countTrailingZeros - This function is a APInt version corresponding to
736 /// llvm/include/llvm/Support/MathExtras.h's function
737 /// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
738 /// the number of zeros from the least significant bit to the first one bit.
739 /// @returns numWord() * 64 if the value is zero.
740 uint32_t APInt::countTrailingZeros() const {
742 return CountTrailingZeros_64(VAL);
743 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
744 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
747 /// countPopulation - This function is a APInt version corresponding to
748 /// llvm/include/llvm/Support/MathExtras.h's function
749 /// countPopulation_{32, 64}. It counts the number of set bits in a value.
750 /// @returns 0 if the value is zero.
751 uint32_t APInt::countPopulation() const {
753 return CountPopulation_64(VAL);
755 for (uint32_t i = 0; i < getNumWords(); ++i)
756 Count += CountPopulation_64(pVal[i]);
761 /// byteSwap - This function returns a byte-swapped representation of the
763 APInt APInt::byteSwap() const {
764 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
766 return APInt(BitWidth, ByteSwap_16(VAL));
767 else if (BitWidth == 32)
768 return APInt(BitWidth, ByteSwap_32(VAL));
769 else if (BitWidth == 48) {
770 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
771 Tmp1 = ByteSwap_32(Tmp1);
772 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
773 Tmp2 = ByteSwap_16(Tmp2);
776 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
777 } else if (BitWidth == 64)
778 return APInt(BitWidth, ByteSwap_64(VAL));
780 APInt Result(BitWidth, 0);
781 char *pByte = (char*)Result.pVal;
782 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
784 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
785 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
791 /// GreatestCommonDivisor - This function returns the greatest common
792 /// divisor of the two APInt values using Enclid's algorithm.
793 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
795 APInt A = API1, B = API2;
798 B = APIntOps::urem(A, B);
804 /// DoubleRoundToAPInt - This function convert a double value to
806 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
812 bool isNeg = T.I >> 63;
813 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
815 return APInt(64ull, 0u);
816 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
818 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
819 APInt(64u, mantissa >> (52 - exp));
820 APInt Tmp(exp + 1, mantissa);
821 Tmp = Tmp.shl(exp - 52);
822 return isNeg ? -Tmp : Tmp;
825 /// RoundToDouble - This function convert this APInt to a double.
826 /// The layout for double is as following (IEEE Standard 754):
827 /// --------------------------------------
828 /// | Sign Exponent Fraction Bias |
829 /// |-------------------------------------- |
830 /// | 1[63] 11[62-52] 52[51-00] 1023 |
831 /// --------------------------------------
832 double APInt::roundToDouble(bool isSigned) const {
834 // Handle the simple case where the value is contained in one uint64_t.
835 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
837 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
843 // Determine if the value is negative.
844 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
846 // Construct the absolute value if we're negative.
847 APInt Tmp(isNeg ? -(*this) : (*this));
849 // Figure out how many bits we're using.
850 uint32_t n = Tmp.getActiveBits();
852 // The exponent (without bias normalization) is just the number of bits
853 // we are using. Note that the sign bit is gone since we constructed the
857 // Return infinity for exponent overflow
859 if (!isSigned || !isNeg)
860 return double(1.0E300 * 1.0E300); // positive infinity
862 return double(-1.0E300 * 1.0E300); // negative infinity
864 exp += 1023; // Increment for 1023 bias
866 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
867 // extract the high 52 bits from the correct words in pVal.
869 unsigned hiWord = whichWord(n-1);
871 mantissa = Tmp.pVal[0];
873 mantissa >>= n - 52; // shift down, we want the top 52 bits.
875 assert(hiWord > 0 && "huh?");
876 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
877 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
878 mantissa = hibits | lobits;
881 // The leading bit of mantissa is implicit, so get rid of it.
882 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
887 T.I = sign | (exp << 52) | mantissa;
891 // Truncate to new width.
892 void APInt::trunc(uint32_t width) {
893 assert(width < BitWidth && "Invalid APInt Truncate request");
896 // Sign extend to a new width.
897 void APInt::sext(uint32_t width) {
898 assert(width > BitWidth && "Invalid APInt SignExtend request");
901 // Zero extend to a new width.
902 void APInt::zext(uint32_t width) {
903 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
906 /// Arithmetic right-shift this APInt by shiftAmt.
907 /// @brief Arithmetic right-shift function.
908 APInt APInt::ashr(uint32_t shiftAmt) const {
910 if (API.isSingleWord())
912 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
913 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
914 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
916 if (shiftAmt >= API.BitWidth) {
917 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
918 (API.getNumWords()-1) * APINT_WORD_SIZE);
919 API.pVal[API.getNumWords() - 1] =
921 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
924 for (; i < API.BitWidth - shiftAmt; ++i)
929 for (; i < API.BitWidth; ++i)
930 if (API[API.BitWidth-1])
938 /// Logical right-shift this APInt by shiftAmt.
939 /// @brief Logical right-shift function.
940 APInt APInt::lshr(uint32_t shiftAmt) const {
942 if (API.isSingleWord())
943 API.VAL >>= shiftAmt;
945 if (shiftAmt >= API.BitWidth)
946 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
948 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
949 if (API[i+shiftAmt]) API.set(i);
951 for (; i < API.BitWidth; ++i)
957 /// Left-shift this APInt by shiftAmt.
958 /// @brief Left-shift function.
959 APInt APInt::shl(uint32_t shiftAmt) const {
961 if (API.isSingleWord())
962 API.VAL <<= shiftAmt;
963 else if (shiftAmt >= API.BitWidth)
964 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
966 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
967 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
968 API.pVal[i] = API.pVal[i-offset];
969 memset(API.pVal, 0, offset * APINT_WORD_SIZE);
971 shiftAmt %= APINT_BITS_PER_WORD;
973 for (i = API.getNumWords() - 1; i > 0; --i)
974 API.pVal[i] = (API.pVal[i] << shiftAmt) |
975 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
976 API.pVal[i] <<= shiftAmt;
978 API.clearUnusedBits();
983 /// subMul - This function substracts x[len-1:0] * y from
984 /// dest[offset+len-1:offset], and returns the most significant
985 /// word of the product, minus the borrow-out from the subtraction.
986 static uint32_t subMul(uint32_t dest[], uint32_t offset,
987 uint32_t x[], uint32_t len, uint32_t y) {
988 uint64_t yl = (uint64_t) y & 0xffffffffL;
992 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
993 uint32_t prod_low = (uint32_t) prod;
994 uint32_t prod_high = (uint32_t) (prod >> 32);
996 carry = (prod_low < carry ? 1 : 0) + prod_high;
997 uint32_t x_j = dest[offset+j];
998 prod_low = x_j - prod_low;
999 if (prod_low > x_j) ++carry;
1000 dest[offset+j] = prod_low;
1001 } while (++j < len);
1005 /// unitDiv - This function divides N by D,
1006 /// and returns (remainder << 32) | quotient.
1007 /// Assumes (N >> 32) < D.
1008 static uint64_t unitDiv(uint64_t N, uint32_t D) {
1009 uint64_t q, r; // q: quotient, r: remainder.
1010 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
1011 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
1012 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
1017 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
1018 uint64_t c = N - ((uint64_t) D << 31);
1019 // Divide (c1*2^32 + c0) by d
1022 // Add 2^31 to quotient
1026 return (r << 32) | (q & 0xFFFFFFFFl);
1031 /// div - This is basically Knuth's formulation of the classical algorithm.
1032 /// Correspondance with Knuth's notation:
1033 /// Knuth's u[0:m+n] == zds[nx:0].
1034 /// Knuth's v[1:n] == y[ny-1:0]
1035 /// Knuth's n == ny.
1036 /// Knuth's m == nx-ny.
1037 /// Our nx == Knuth's m+n.
1038 /// Could be re-implemented using gmp's mpn_divrem:
1039 /// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
1041 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1042 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1043 /// variables here have the same names as in the algorithm. Comments explain
1044 /// the algorithm and any deviation from it.
1045 static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1046 uint32_t m, uint32_t n) {
1047 assert(u && "Must provide dividend");
1048 assert(v && "Must provide divisor");
1049 assert(q && "Must provide quotient");
1050 assert(n>1 && "n must be > 1");
1052 // Knuth uses the value b as the base of the number system. In our case b
1053 // is 2^31 so we just set it to -1u.
1054 uint64_t b = uint64_t(1) << 32;
1056 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1057 // u and v by d. Note that we have taken Knuth's advice here to use a power
1058 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1059 // 2 allows us to shift instead of multiply and it is easy to determine the
1060 // shift amount from the leading zeros. We are basically normalizing the u
1061 // and v so that its high bits are shifted to the top of v's range without
1062 // overflow. Note that this can require an extra word in u so that u must
1063 // be of length m+n+1.
1064 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1065 uint32_t v_carry = 0;
1066 uint32_t u_carry = 0;
1068 for (uint32_t i = 0; i < m+n; ++i) {
1069 uint32_t u_tmp = u[i] >> (32 - shift);
1070 u[i] = (u[i] << shift) | u_carry;
1073 for (uint32_t i = 0; i < n; ++i) {
1074 uint32_t v_tmp = v[i] >> (32 - shift);
1075 v[i] = (v[i] << shift) | v_carry;
1081 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1084 // D3. [Calculate q'.].
1085 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1086 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1087 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1088 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1089 // on v[n-2] determines at high speed most of the cases in which the trial
1090 // value qp is one too large, and it eliminates all cases where qp is two
1092 uint64_t qp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) / v[n-1];
1093 uint64_t rp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) % v[n-1];
1094 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1099 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1104 // D4. [Multiply and subtract.] Replace u with u - q*v (for each word).
1105 uint32_t borrow = 0;
1106 for (uint32_t i = 0; i < n; i++) {
1107 uint32_t save = u[j+i];
1108 u[j+i] = uint64_t(u[j+i]) - (qp * v[i]) - borrow;
1109 if (u[j+i] > save) {
1119 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1120 // negative, go to step D6; otherwise go on to step D7.
1123 // D6. [Add back]. The probability that this step is necessary is very
1124 // small, on the order of only 2/b. Make sure that test data accounts for
1125 // this possibility. Decreate qj by 1 and add v[...] to u[...]. A carry
1126 // will occur to the left of u[j+n], and it should be ignored since it
1127 // cancels with the borrow that occurred in D4.
1129 for (uint32_t i = 0; i < n; i++) {
1130 uint32_t save = u[j+i];
1131 u[j+i] += v[i] + carry;
1132 carry = u[j+i] < save;
1136 // D7. [Loop on j.] Decreate j by one. Now if j >= 0, go back to D3.
1140 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1141 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1142 // compute the remainder (urem uses this).
1144 // The value d is expressed by the "shift" value above since we avoided
1145 // multiplication by d by using a shift left. So, all we have to do is
1146 // shift right here. In order to mak
1147 uint32_t mask = ~0u >> (32 - shift);
1149 for (int i = n-1; i >= 0; i--) {
1150 uint32_t save = u[i] & mask;
1151 r[i] = (u[i] >> shift) | carry;
1157 // This function makes calling KnuthDiv a little more convenient. It uses
1158 // APInt parameters instead of uint32_t* parameters. It can also divide APInt
1159 // values of different widths.
1160 void APInt::divide(const APInt LHS, uint32_t lhsWords,
1161 const APInt &RHS, uint32_t rhsWords,
1162 APInt *Quotient, APInt *Remainder)
1164 assert(lhsWords >= rhsWords && "Fractional result");
1166 // First, compose the values into an array of 32-bit words instead of
1167 // 64-bit words. This is a necessity of both the "short division" algorithm
1168 // and the the Knuth "classical algorithm" which requires there to be native
1169 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1170 // can't use 64-bit operands here because we don't have native results of
1171 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1172 // work on large-endian machines.
1173 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1174 uint32_t n = rhsWords * 2;
1175 uint32_t m = (lhsWords * 2) - n;
1176 // FIXME: allocate space on stack if m and n are sufficiently small.
1177 uint32_t *U = new uint32_t[m + n + 1];
1178 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1179 for (unsigned i = 0; i < lhsWords; ++i) {
1180 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
1181 U[i * 2] = tmp & mask;
1182 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1184 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1186 uint32_t *V = new uint32_t[n];
1187 memset(V, 0, (n)*sizeof(uint32_t));
1188 for (unsigned i = 0; i < rhsWords; ++i) {
1189 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
1190 V[i * 2] = tmp & mask;
1191 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1194 // Set up the quotient and remainder
1195 uint32_t *Q = new uint32_t[m+n];
1196 memset(Q, 0, (m+n) * sizeof(uint32_t));
1199 R = new uint32_t[n];
1200 memset(R, 0, n * sizeof(uint32_t));
1203 // Now, adjust m and n for the Knuth division. n is the number of words in
1204 // the divisor. m is the number of words by which the dividend exceeds the
1205 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1206 // contain any zero words or the Knuth algorithm fails.
1207 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1211 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1214 // If we're left with only a single word for the divisor, Knuth doesn't work
1215 // so we implement the short division algorithm here. This is much simpler
1216 // and faster because we are certain that we can divide a 64-bit quantity
1217 // by a 32-bit quantity at hardware speed and short division is simply a
1218 // series of such operations. This is just like doing short division but we
1219 // are using base 2^32 instead of base 10.
1220 assert(n != 0 && "Divide by zero?");
1222 uint32_t divisor = V[0];
1223 uint32_t remainder = 0;
1224 for (int i = m+n-1; i >= 0; i--) {
1225 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1226 if (partial_dividend == 0) {
1229 } else if (partial_dividend < divisor) {
1231 remainder = partial_dividend;
1232 } else if (partial_dividend == divisor) {
1236 Q[i] = partial_dividend / divisor;
1237 remainder = partial_dividend - (Q[i] * divisor);
1243 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1245 KnuthDiv(U, V, Q, R, m, n);
1248 // If the caller wants the quotient
1250 // Set up the Quotient value's memory.
1251 if (Quotient->BitWidth != LHS.BitWidth) {
1252 if (Quotient->isSingleWord())
1255 delete Quotient->pVal;
1256 Quotient->BitWidth = LHS.BitWidth;
1257 if (!Quotient->isSingleWord())
1258 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
1262 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1264 if (lhsWords == 1) {
1266 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1267 if (Quotient->isSingleWord())
1268 Quotient->VAL = tmp;
1270 Quotient->pVal[0] = tmp;
1272 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1273 for (unsigned i = 0; i < lhsWords; ++i)
1275 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1279 // If the caller wants the remainder
1281 // Set up the Remainder value's memory.
1282 if (Remainder->BitWidth != RHS.BitWidth) {
1283 if (Remainder->isSingleWord())
1286 delete Remainder->pVal;
1287 Remainder->BitWidth = RHS.BitWidth;
1288 if (!Remainder->isSingleWord())
1289 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
1293 // The remainder is in R. Reconstitute the remainder into Remainder's low
1295 if (rhsWords == 1) {
1297 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1298 if (Remainder->isSingleWord())
1299 Remainder->VAL = tmp;
1301 Remainder->pVal[0] = tmp;
1303 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1304 for (unsigned i = 0; i < rhsWords; ++i)
1305 Remainder->pVal[i] =
1306 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1310 // Clean up the memory we allocated.
1317 /// Unsigned divide this APInt by APInt RHS.
1318 /// @brief Unsigned division function for APInt.
1319 APInt APInt::udiv(const APInt& RHS) const {
1320 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1322 // First, deal with the easy case
1323 if (isSingleWord()) {
1324 assert(RHS.VAL != 0 && "Divide by zero?");
1325 return APInt(BitWidth, VAL / RHS.VAL);
1328 // Get some facts about the LHS and RHS number of bits and words
1329 uint32_t rhsBits = RHS.getActiveBits();
1330 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1331 assert(rhsWords && "Divided by zero???");
1332 uint32_t lhsBits = this->getActiveBits();
1333 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1335 // Deal with some degenerate cases
1338 return APInt(BitWidth, 0);
1339 else if (lhsWords < rhsWords || this->ult(RHS)) {
1340 // X / Y ===> 0, iff X < Y
1341 return APInt(BitWidth, 0);
1342 } else if (*this == RHS) {
1344 return APInt(BitWidth, 1);
1345 } else if (lhsWords == 1 && rhsWords == 1) {
1346 // All high words are zero, just use native divide
1347 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
1350 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1351 APInt Quotient(1,0); // to hold result.
1352 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1356 /// Unsigned remainder operation on APInt.
1357 /// @brief Function for unsigned remainder operation.
1358 APInt APInt::urem(const APInt& RHS) const {
1359 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1360 if (isSingleWord()) {
1361 assert(RHS.VAL != 0 && "Remainder by zero?");
1362 return APInt(BitWidth, VAL % RHS.VAL);
1365 // Get some facts about the LHS
1366 uint32_t lhsBits = getActiveBits();
1367 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
1369 // Get some facts about the RHS
1370 uint32_t rhsBits = RHS.getActiveBits();
1371 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1372 assert(rhsWords && "Performing remainder operation by zero ???");
1374 // Check the degenerate cases
1375 if (lhsWords == 0) {
1377 return APInt(BitWidth, 0);
1378 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1379 // X % Y ===> X, iff X < Y
1381 } else if (*this == RHS) {
1383 return APInt(BitWidth, 0);
1384 } else if (lhsWords == 1) {
1385 // All high words are zero, just use native remainder
1386 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
1389 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1390 APInt Remainder(1,0);
1391 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1395 /// @brief Converts a char array into an integer.
1396 void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
1398 // Check our assumptions here
1399 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1400 "Radix should be 2, 8, 10, or 16!");
1401 assert(str && "String is null?");
1402 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1403 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1404 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1405 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1408 if (!isSingleWord())
1409 pVal = getClearedMemory(getNumWords());
1411 // Figure out if we can shift instead of multiply
1412 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1414 // Set up an APInt for the digit to add outside the loop so we don't
1415 // constantly construct/destruct it.
1416 APInt apdigit(getBitWidth(), 0);
1417 APInt apradix(getBitWidth(), radix);
1419 // Enter digit traversal loop
1420 for (unsigned i = 0; i < slen; i++) {
1423 char cdigit = str[i];
1424 if (isdigit(cdigit))
1425 digit = cdigit - '0';
1426 else if (isxdigit(cdigit))
1428 digit = cdigit - 'a' + 10;
1429 else if (cdigit >= 'A')
1430 digit = cdigit - 'A' + 10;
1432 assert(0 && "huh?");
1434 assert(0 && "Invalid character in digit string");
1436 // Shift or multiple the value by the radix
1442 // Add in the digit we just interpreted
1443 apdigit.pVal[0] = digit;
1448 /// to_string - This function translates the APInt into a string.
1449 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1450 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1451 "Radix should be 2, 8, 10, or 16!");
1452 static const char *digits[] = {
1453 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1456 uint32_t bits_used = getActiveBits();
1457 if (isSingleWord()) {
1459 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1460 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1463 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1464 (APINT_BITS_PER_WORD-BitWidth);
1465 sprintf(buf, format, sextVal);
1467 sprintf(buf, format, VAL);
1472 uint32_t bit = v & 1;
1474 buf[bits_used] = digits[bit][0];
1483 uint64_t mask = radix - 1;
1484 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1485 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1486 for (uint32_t i = 0; i < getNumWords(); ++i) {
1487 uint64_t value = pVal[i];
1488 for (uint32_t j = 0; j < nibbles; ++j) {
1489 result.insert(0, digits[ value & mask ]);
1497 APInt divisor(4, radix);
1498 APInt zero(tmp.getBitWidth(), 0);
1499 size_t insert_at = 0;
1500 if (wantSigned && tmp[BitWidth-1]) {
1501 // They want to print the signed version and it is a negative value
1502 // Flip the bits and add one to turn it into the equivalent positive
1503 // value and put a '-' in the result.
1509 if (tmp == APInt(tmp.getBitWidth(), 0))
1511 else while (tmp.ne(zero)) {
1513 APInt tmp2(tmp.getBitWidth(), 0);
1514 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1516 uint32_t digit = APdigit.getValue();
1517 assert(digit < radix && "divide failed");
1518 result.insert(insert_at,digits[digit]);
1526 void APInt::dump() const
1528 std::cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
1531 else for (unsigned i = getNumWords(); i > 0; i--) {
1532 std::cerr << pVal[i-1] << " ";
1534 std::cerr << " (" << this->toString(10, false) << ")\n" << std::setbase(10);