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 #define DEBUG_TYPE "apint"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/MathExtras.h"
29 // A utility function for allocating memory, checking for allocation failures,
30 // and ensuring the contents is zeroed.
31 inline static uint64_t* getClearedMemory(uint32_t numWords) {
32 uint64_t * result = new uint64_t[numWords];
33 assert(result && "APInt memory allocation fails!");
34 memset(result, 0, numWords * sizeof(uint64_t));
38 // A utility function for allocating memory and checking for allocation failure.
39 inline static uint64_t* getMemory(uint32_t numWords) {
40 uint64_t * result = new uint64_t[numWords];
41 assert(result && "APInt memory allocation fails!");
45 APInt::APInt(uint32_t numBits, uint64_t val)
46 : BitWidth(numBits), VAL(0) {
47 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
48 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
50 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
52 pVal = getClearedMemory(getNumWords());
57 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
58 : BitWidth(numBits), VAL(0) {
59 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
60 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
61 assert(bigVal && "Null pointer detected!");
63 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
65 pVal = getMemory(getNumWords());
66 // Calculate the actual length of bigVal[].
67 uint32_t maxN = std::max<uint32_t>(numWords, getNumWords());
68 uint32_t minN = std::min<uint32_t>(numWords, getNumWords());
69 memcpy(pVal, bigVal, (minN - 1) * APINT_WORD_SIZE);
70 pVal[minN-1] = bigVal[minN-1] &
72 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
73 if (maxN == getNumWords())
74 memset(pVal+numWords, 0, (getNumWords() - numWords) * APINT_WORD_SIZE);
78 /// @brief Create a new APInt by translating the char array represented
80 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
82 : BitWidth(numbits), VAL(0) {
83 fromString(numbits, StrStart, slen, radix);
86 /// @brief Create a new APInt by translating the string represented
88 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
89 : BitWidth(numbits), VAL(0) {
90 assert(!Val.empty() && "String empty?");
91 fromString(numbits, Val.c_str(), Val.size(), radix);
94 /// @brief Copy constructor
95 APInt::APInt(const APInt& that)
96 : BitWidth(that.BitWidth), VAL(0) {
100 pVal = getMemory(getNumWords());
101 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
106 if (!isSingleWord() && pVal)
110 /// @brief Copy assignment operator. Create a new object from the given
111 /// APInt one by initialization.
112 APInt& APInt::operator=(const APInt& RHS) {
113 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
117 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
121 /// @brief Assignment operator. Assigns a common case integer value to
123 APInt& APInt::operator=(uint64_t RHS) {
128 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
133 /// add_1 - This function adds a single "digit" integer, y, to the multiple
134 /// "digit" integer array, x[]. x[] is modified to reflect the addition and
135 /// 1 is returned if there is a carry out, otherwise 0 is returned.
136 /// @returns the carry of the addition.
137 static uint64_t add_1(uint64_t dest[],
138 uint64_t x[], uint32_t len,
140 for (uint32_t i = 0; i < len; ++i) {
152 /// @brief Prefix increment operator. Increments the APInt by one.
153 APInt& APInt::operator++() {
157 add_1(pVal, pVal, getNumWords(), 1);
162 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
163 /// the multi-digit integer array, x[], propagating the borrowed 1 value until
164 /// no further borrowing is neeeded or it runs out of "digits" in x. The result
165 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
166 /// In other words, if y > x then this function returns 1, otherwise 0.
167 static uint64_t sub_1(uint64_t x[], uint32_t len,
169 for (uint32_t i = 0; i < len; ++i) {
173 y = 1; // We have to "borrow 1" from next "digit"
175 y = 0; // No need to borrow
176 break; // Remaining digits are unchanged so exit early
182 /// @brief Prefix decrement operator. Decrements the APInt by one.
183 APInt& APInt::operator--() {
187 sub_1(pVal, getNumWords(), 1);
192 /// add - This function adds the integer array x[] by integer array
193 /// y[] and returns the carry.
194 static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
197 for (uint32_t i = 0; i< len; ++i) {
198 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
199 dest[i] = x[i] + y[i] + carry;
200 carry = dest[i] < limit || (carry && dest[i] == limit);
205 /// @brief Addition assignment operator. Adds this APInt by the given APInt&
206 /// RHS and assigns the result to this APInt.
207 APInt& APInt::operator+=(const APInt& RHS) {
208 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
212 add(pVal, pVal, RHS.pVal, getNumWords());
218 /// sub - This function subtracts the integer array x[] by
219 /// integer array y[], and returns the borrow-out carry.
220 static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
223 for (uint32_t i = 0; i < len; ++i) {
224 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
225 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
226 dest[i] = x_tmp - y[i];
231 /// @brief Subtraction assignment operator. Subtracts this APInt by the given
232 /// APInt &RHS and assigns the result to this APInt.
233 APInt& APInt::operator-=(const APInt& RHS) {
234 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
238 sub(pVal, pVal, RHS.pVal, getNumWords());
243 /// mul_1 - This function performs the multiplication operation on a
244 /// large integer (represented as an integer array) and a uint64_t integer.
245 /// @returns the carry of the multiplication.
246 static uint64_t mul_1(uint64_t dest[],
247 uint64_t x[], uint32_t len,
249 // Split y into high 32-bit part and low 32-bit part.
250 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
251 uint64_t carry = 0, lx, hx;
252 for (uint32_t i = 0; i < len; ++i) {
253 lx = x[i] & 0xffffffffULL;
255 // hasCarry - A flag to indicate if has carry.
256 // hasCarry == 0, no carry
257 // hasCarry == 1, has carry
258 // hasCarry == 2, no carry and the calculation result == 0.
259 uint8_t hasCarry = 0;
260 dest[i] = carry + lx * ly;
261 // Determine if the add above introduces carry.
262 hasCarry = (dest[i] < carry) ? 1 : 0;
263 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
264 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
265 // (2^32 - 1) + 2^32 = 2^64.
266 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
268 carry += (lx * hy) & 0xffffffffULL;
269 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
270 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
271 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
277 /// mul - This function multiplies integer array x[] by integer array y[] and
278 /// stores the result into integer array dest[].
279 /// Note the array dest[]'s size should no less than xlen + ylen.
280 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
281 uint64_t y[], uint32_t ylen) {
282 dest[xlen] = mul_1(dest, x, xlen, y[0]);
284 for (uint32_t i = 1; i < ylen; ++i) {
285 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
286 uint64_t carry = 0, lx = 0, hx = 0;
287 for (uint32_t j = 0; j < xlen; ++j) {
288 lx = x[j] & 0xffffffffULL;
290 // hasCarry - A flag to indicate if has carry.
291 // hasCarry == 0, no carry
292 // hasCarry == 1, has carry
293 // hasCarry == 2, no carry and the calculation result == 0.
294 uint8_t hasCarry = 0;
295 uint64_t resul = carry + lx * ly;
296 hasCarry = (resul < carry) ? 1 : 0;
297 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
298 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
300 carry += (lx * hy) & 0xffffffffULL;
301 resul = (carry << 32) | (resul & 0xffffffffULL);
303 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
304 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
305 ((lx * hy) >> 32) + hx * hy;
307 dest[i+xlen] = carry;
311 /// @brief Multiplication assignment operator. Multiplies this APInt by the
312 /// given APInt& RHS and assigns the result to this APInt.
313 APInt& APInt::operator*=(const APInt& RHS) {
314 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
315 if (isSingleWord()) {
321 // Get some bit facts about LHS and check for zero
322 uint32_t lhsBits = getActiveBits();
323 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
328 // Get some bit facts about RHS and check for zero
329 uint32_t rhsBits = RHS.getActiveBits();
330 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
337 // Allocate space for the result
338 uint32_t destWords = rhsWords + lhsWords;
339 uint64_t *dest = getMemory(destWords);
341 // Perform the long multiply
342 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
344 // Copy result back into *this
346 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
347 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
349 // delete dest array and return
354 /// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
355 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
356 APInt& APInt::operator&=(const APInt& RHS) {
357 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
358 if (isSingleWord()) {
362 uint32_t numWords = getNumWords();
363 for (uint32_t i = 0; i < numWords; ++i)
364 pVal[i] &= RHS.pVal[i];
368 /// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
369 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
370 APInt& APInt::operator|=(const APInt& RHS) {
371 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
372 if (isSingleWord()) {
376 uint32_t numWords = getNumWords();
377 for (uint32_t i = 0; i < numWords; ++i)
378 pVal[i] |= RHS.pVal[i];
382 /// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
383 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
384 APInt& APInt::operator^=(const APInt& RHS) {
385 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
386 if (isSingleWord()) {
388 this->clearUnusedBits();
391 uint32_t numWords = getNumWords();
392 for (uint32_t i = 0; i < numWords; ++i)
393 pVal[i] ^= RHS.pVal[i];
394 this->clearUnusedBits();
398 /// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
399 /// and the given APInt& RHS.
400 APInt APInt::operator&(const APInt& RHS) const {
401 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
403 return APInt(getBitWidth(), VAL & RHS.VAL);
406 uint32_t numWords = getNumWords();
407 for (uint32_t i = 0; i < numWords; ++i)
408 Result.pVal[i] &= RHS.pVal[i];
412 /// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
413 /// and the given APInt& RHS.
414 APInt APInt::operator|(const APInt& RHS) const {
415 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
417 return APInt(getBitWidth(), VAL | RHS.VAL);
420 uint32_t numWords = getNumWords();
421 for (uint32_t i = 0; i < numWords; ++i)
422 Result.pVal[i] |= RHS.pVal[i];
426 /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
427 /// and the given APInt& RHS.
428 APInt APInt::operator^(const APInt& RHS) const {
429 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
430 if (isSingleWord()) {
431 APInt Result(BitWidth, VAL ^ RHS.VAL);
432 Result.clearUnusedBits();
436 uint32_t numWords = getNumWords();
437 for (uint32_t i = 0; i < numWords; ++i)
438 Result.pVal[i] ^= RHS.pVal[i];
442 /// @brief Logical negation operator. Performs logical negation operation on
444 bool APInt::operator !() const {
448 for (uint32_t i = 0; i < getNumWords(); ++i)
454 /// @brief Multiplication operator. Multiplies this APInt by the given APInt&
456 APInt APInt::operator*(const APInt& RHS) const {
457 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
458 if (isSingleWord()) {
459 APInt Result(BitWidth, VAL * RHS.VAL);
460 Result.clearUnusedBits();
465 Result.clearUnusedBits();
469 /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
470 APInt APInt::operator+(const APInt& RHS) const {
471 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
472 if (isSingleWord()) {
473 APInt Result(BitWidth, VAL + RHS.VAL);
474 Result.clearUnusedBits();
477 APInt Result(BitWidth, 0);
478 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
479 Result.clearUnusedBits();
483 /// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
484 APInt APInt::operator-(const APInt& RHS) const {
485 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
486 if (isSingleWord()) {
487 APInt Result(BitWidth, VAL - RHS.VAL);
488 Result.clearUnusedBits();
491 APInt Result(BitWidth, 0);
492 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
493 Result.clearUnusedBits();
497 /// @brief Array-indexing support.
498 bool APInt::operator[](uint32_t bitPosition) const {
499 return (maskBit(bitPosition) & (isSingleWord() ?
500 VAL : pVal[whichWord(bitPosition)])) != 0;
503 /// @brief Equality operator. Compare this APInt with the given APInt& RHS
504 /// for the validity of the equality relationship.
505 bool APInt::operator==(const APInt& RHS) const {
507 return VAL == RHS.VAL;
509 uint32_t n1 = getActiveBits();
510 uint32_t n2 = RHS.getActiveBits();
514 if (n1 <= APINT_BITS_PER_WORD)
515 return pVal[0] == RHS.pVal[0];
517 for (int i = whichWord(n1 - 1); i >= 0; --i)
518 if (pVal[i] != RHS.pVal[i])
523 /// @brief Equality operator. Compare this APInt with the given uint64_t value
524 /// for the validity of the equality relationship.
525 bool APInt::operator==(uint64_t Val) const {
529 uint32_t n = getActiveBits();
530 if (n <= APINT_BITS_PER_WORD)
531 return pVal[0] == Val;
536 /// @brief Unsigned less than comparison
537 bool APInt::ult(const APInt& RHS) const {
538 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
540 return VAL < RHS.VAL;
542 uint32_t n1 = getActiveBits();
543 uint32_t n2 = RHS.getActiveBits();
548 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
549 return pVal[0] < RHS.pVal[0];
550 for (int i = whichWord(n1 - 1); i >= 0; --i) {
551 if (pVal[i] > RHS.pVal[i]) return false;
552 else if (pVal[i] < RHS.pVal[i]) return true;
558 /// @brief Signed less than comparison
559 bool APInt::slt(const APInt& RHS) const {
560 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
561 if (isSingleWord()) {
562 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
563 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
564 return lhsSext < rhsSext;
569 bool lhsNegative = false;
570 bool rhsNegative = false;
571 if (lhs[BitWidth-1]) {
576 if (rhs[BitWidth-1]) {
583 return !lhs.ult(rhs);
586 else if (rhsNegative)
592 /// Set the given bit to 1 whose poition is given as "bitPosition".
593 /// @brief Set a given bit to 1.
594 APInt& APInt::set(uint32_t bitPosition) {
595 if (isSingleWord()) VAL |= maskBit(bitPosition);
596 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
600 /// @brief Set every bit to 1.
601 APInt& APInt::set() {
603 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
605 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
607 pVal[getNumWords() - 1] = ~0ULL >>
608 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
613 /// Set the given bit to 0 whose position is given as "bitPosition".
614 /// @brief Set a given bit to 0.
615 APInt& APInt::clear(uint32_t bitPosition) {
617 VAL &= ~maskBit(bitPosition);
619 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
623 /// @brief Set every bit to 0.
624 APInt& APInt::clear() {
628 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
632 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
634 APInt APInt::operator~() const {
640 /// @brief Toggle every bit to its opposite value.
641 APInt& APInt::flip() {
642 if (isSingleWord()) VAL = (~(VAL <<
643 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
646 for (; i < getNumWords() - 1; ++i)
649 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
650 pVal[i] = (~(pVal[i] << offset)) >> offset;
655 /// Toggle a given bit to its opposite value whose position is given
656 /// as "bitPosition".
657 /// @brief Toggles a given bit to its opposite value.
658 APInt& APInt::flip(uint32_t bitPosition) {
659 assert(bitPosition < BitWidth && "Out of the bit-width range!");
660 if ((*this)[bitPosition]) clear(bitPosition);
661 else set(bitPosition);
665 /// getMaxValue - This function returns the largest value
666 /// for an APInt of the specified bit-width and if isSign == true,
667 /// it should be largest signed value, otherwise unsigned value.
668 APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
669 APInt Result(numBits, 0);
672 Result.clear(numBits - 1);
676 /// getMinValue - This function returns the smallest value for
677 /// an APInt of the given bit-width and if isSign == true,
678 /// it should be smallest signed value, otherwise zero.
679 APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
680 APInt Result(numBits, 0);
682 Result.set(numBits - 1);
686 /// getAllOnesValue - This function returns an all-ones value for
687 /// an APInt of the specified bit-width.
688 APInt APInt::getAllOnesValue(uint32_t numBits) {
689 return getMaxValue(numBits, false);
692 /// getNullValue - This function creates an '0' value for an
693 /// APInt of the specified bit-width.
694 APInt APInt::getNullValue(uint32_t numBits) {
695 return getMinValue(numBits, false);
698 /// HiBits - This function returns the high "numBits" bits of this APInt.
699 APInt APInt::getHiBits(uint32_t numBits) const {
700 return APIntOps::lshr(*this, BitWidth - numBits);
703 /// LoBits - This function returns the low "numBits" bits of this APInt.
704 APInt APInt::getLoBits(uint32_t numBits) const {
705 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
709 bool APInt::isPowerOf2() const {
710 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
713 /// countLeadingZeros - This function is a APInt version corresponding to
714 /// llvm/include/llvm/Support/MathExtras.h's function
715 /// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
716 /// the number of zeros from the most significant bit to the first one bit.
717 /// @returns numWord() * 64 if the value is zero.
718 uint32_t APInt::countLeadingZeros() const {
721 Count = CountLeadingZeros_64(VAL);
723 for (uint32_t i = getNumWords(); i > 0u; --i) {
725 Count += APINT_BITS_PER_WORD;
727 Count += CountLeadingZeros_64(pVal[i-1]);
732 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
734 Count -= APINT_BITS_PER_WORD - remainder;
738 /// countTrailingZeros - This function is a APInt version corresponding to
739 /// llvm/include/llvm/Support/MathExtras.h's function
740 /// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
741 /// the number of zeros from the least significant bit to the first one bit.
742 /// @returns numWord() * 64 if the value is zero.
743 uint32_t APInt::countTrailingZeros() const {
745 return CountTrailingZeros_64(VAL);
746 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
747 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
750 /// countPopulation - This function is a APInt version corresponding to
751 /// llvm/include/llvm/Support/MathExtras.h's function
752 /// countPopulation_{32, 64}. It counts the number of set bits in a value.
753 /// @returns 0 if the value is zero.
754 uint32_t APInt::countPopulation() const {
756 return CountPopulation_64(VAL);
758 for (uint32_t i = 0; i < getNumWords(); ++i)
759 Count += CountPopulation_64(pVal[i]);
764 /// byteSwap - This function returns a byte-swapped representation of the
766 APInt APInt::byteSwap() const {
767 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
769 return APInt(BitWidth, ByteSwap_16(VAL));
770 else if (BitWidth == 32)
771 return APInt(BitWidth, ByteSwap_32(VAL));
772 else if (BitWidth == 48) {
773 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
774 Tmp1 = ByteSwap_32(Tmp1);
775 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
776 Tmp2 = ByteSwap_16(Tmp2);
779 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
780 } else if (BitWidth == 64)
781 return APInt(BitWidth, ByteSwap_64(VAL));
783 APInt Result(BitWidth, 0);
784 char *pByte = (char*)Result.pVal;
785 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
787 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
788 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
794 /// GreatestCommonDivisor - This function returns the greatest common
795 /// divisor of the two APInt values using Enclid's algorithm.
796 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
798 APInt A = API1, B = API2;
801 B = APIntOps::urem(A, B);
807 /// DoubleRoundToAPInt - This function convert a double value to
809 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
815 bool isNeg = T.I >> 63;
816 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
818 return APInt(64ull, 0u);
819 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
821 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
822 APInt(64u, mantissa >> (52 - exp));
823 APInt Tmp(exp + 1, mantissa);
824 Tmp = Tmp.shl(exp - 52);
825 return isNeg ? -Tmp : Tmp;
828 /// RoundToDouble - This function convert this APInt to a double.
829 /// The layout for double is as following (IEEE Standard 754):
830 /// --------------------------------------
831 /// | Sign Exponent Fraction Bias |
832 /// |-------------------------------------- |
833 /// | 1[63] 11[62-52] 52[51-00] 1023 |
834 /// --------------------------------------
835 double APInt::roundToDouble(bool isSigned) const {
837 // Handle the simple case where the value is contained in one uint64_t.
838 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
840 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
846 // Determine if the value is negative.
847 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
849 // Construct the absolute value if we're negative.
850 APInt Tmp(isNeg ? -(*this) : (*this));
852 // Figure out how many bits we're using.
853 uint32_t n = Tmp.getActiveBits();
855 // The exponent (without bias normalization) is just the number of bits
856 // we are using. Note that the sign bit is gone since we constructed the
860 // Return infinity for exponent overflow
862 if (!isSigned || !isNeg)
863 return double(1.0E300 * 1.0E300); // positive infinity
865 return double(-1.0E300 * 1.0E300); // negative infinity
867 exp += 1023; // Increment for 1023 bias
869 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
870 // extract the high 52 bits from the correct words in pVal.
872 unsigned hiWord = whichWord(n-1);
874 mantissa = Tmp.pVal[0];
876 mantissa >>= n - 52; // shift down, we want the top 52 bits.
878 assert(hiWord > 0 && "huh?");
879 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
880 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
881 mantissa = hibits | lobits;
884 // The leading bit of mantissa is implicit, so get rid of it.
885 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
890 T.I = sign | (exp << 52) | mantissa;
894 // Truncate to new width.
895 void APInt::trunc(uint32_t width) {
896 assert(width < BitWidth && "Invalid APInt Truncate request");
899 // Sign extend to a new width.
900 void APInt::sext(uint32_t width) {
901 assert(width > BitWidth && "Invalid APInt SignExtend request");
904 // Zero extend to a new width.
905 void APInt::zext(uint32_t width) {
906 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
909 /// Arithmetic right-shift this APInt by shiftAmt.
910 /// @brief Arithmetic right-shift function.
911 APInt APInt::ashr(uint32_t shiftAmt) const {
913 if (API.isSingleWord())
915 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
916 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
917 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
919 if (shiftAmt >= API.BitWidth) {
920 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
921 (API.getNumWords()-1) * APINT_WORD_SIZE);
922 API.pVal[API.getNumWords() - 1] =
924 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
927 for (; i < API.BitWidth - shiftAmt; ++i)
932 for (; i < API.BitWidth; ++i)
933 if (API[API.BitWidth-1])
941 /// Logical right-shift this APInt by shiftAmt.
942 /// @brief Logical right-shift function.
943 APInt APInt::lshr(uint32_t shiftAmt) const {
945 if (API.isSingleWord())
946 API.VAL >>= shiftAmt;
948 if (shiftAmt >= API.BitWidth)
949 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
951 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
952 if (API[i+shiftAmt]) API.set(i);
954 for (; i < API.BitWidth; ++i)
960 /// Left-shift this APInt by shiftAmt.
961 /// @brief Left-shift function.
962 APInt APInt::shl(uint32_t shiftAmt) const {
964 if (API.isSingleWord())
965 API.VAL <<= shiftAmt;
966 else if (shiftAmt >= API.BitWidth)
967 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
969 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
970 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
971 API.pVal[i] = API.pVal[i-offset];
972 memset(API.pVal, 0, offset * APINT_WORD_SIZE);
974 shiftAmt %= APINT_BITS_PER_WORD;
976 for (i = API.getNumWords() - 1; i > 0; --i)
977 API.pVal[i] = (API.pVal[i] << shiftAmt) |
978 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
979 API.pVal[i] <<= shiftAmt;
981 API.clearUnusedBits();
985 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
986 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
987 /// variables here have the same names as in the algorithm. Comments explain
988 /// the algorithm and any deviation from it.
989 static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
990 uint32_t m, uint32_t n) {
991 assert(u && "Must provide dividend");
992 assert(v && "Must provide divisor");
993 assert(q && "Must provide quotient");
994 assert(u != v && u != q && v != q && "Must us different memory");
995 assert(n>1 && "n must be > 1");
997 // Knuth uses the value b as the base of the number system. In our case b
998 // is 2^31 so we just set it to -1u.
999 uint64_t b = uint64_t(1) << 32;
1001 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1002 DEBUG(cerr << "KnuthDiv: original:");
1003 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1004 DEBUG(cerr << " by");
1005 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1006 DEBUG(cerr << '\n');
1007 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1008 // u and v by d. Note that we have taken Knuth's advice here to use a power
1009 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1010 // 2 allows us to shift instead of multiply and it is easy to determine the
1011 // shift amount from the leading zeros. We are basically normalizing the u
1012 // and v so that its high bits are shifted to the top of v's range without
1013 // overflow. Note that this can require an extra word in u so that u must
1014 // be of length m+n+1.
1015 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1016 uint32_t v_carry = 0;
1017 uint32_t u_carry = 0;
1019 for (uint32_t i = 0; i < m+n; ++i) {
1020 uint32_t u_tmp = u[i] >> (32 - shift);
1021 u[i] = (u[i] << shift) | u_carry;
1024 for (uint32_t i = 0; i < n; ++i) {
1025 uint32_t v_tmp = v[i] >> (32 - shift);
1026 v[i] = (v[i] << shift) | v_carry;
1031 DEBUG(cerr << "KnuthDiv: normal:");
1032 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1033 DEBUG(cerr << " by");
1034 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1035 DEBUG(cerr << '\n');
1037 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1040 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
1041 // D3. [Calculate q'.].
1042 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1043 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1044 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1045 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1046 // on v[n-2] determines at high speed most of the cases in which the trial
1047 // value qp is one too large, and it eliminates all cases where qp is two
1049 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
1050 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
1051 uint64_t qp = dividend / v[n-1];
1052 uint64_t rp = dividend % v[n-1];
1053 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1056 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2])) {
1061 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
1063 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1064 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1065 // consists of a simple multiplication by a one-place number, combined with
1066 // a subtraction. The digits (u[j+n]...u[j]) should be kept positive;
1067 bool borrow = false;
1068 for (uint32_t i = 0; i < n; ++i) {
1069 uint64_t u_tmp = borrow ? uint64_t(u[j+i] - 1) : uint64_t(u[j+i]);
1070 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
1071 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
1072 << ", subtrahend == " << subtrahend << '\n');
1074 borrow = subtrahend > u_tmp || (borrow && u[j+i] == 0);
1075 u[j+i] = u_tmp - subtrahend;
1078 borrow = u[j+n] == 0; // Was result negative?
1079 u[j+n]--; // handle the borrow
1081 DEBUG(cerr << "KnuthDiv: after subtraction:");
1082 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1083 DEBUG(cerr << '\n');
1084 // if the result of this step is actually negative, (u[j+n]...u[j]) should
1085 // be left as the true value plus b**(n+1), namely as the b's complement of
1086 // the true value, and a "borrow" to the left should be remembered.
1090 for (uint32_t i = 0; i <= n; ++i) {
1091 u[j+i] = ~u[j+i] + carry; // b's complement
1092 carry = u[j+i] == 0;
1095 DEBUG(cerr << "KnuthDiv: after complement:");
1096 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1097 DEBUG(cerr << '\n');
1099 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1100 // negative, go to step D6; otherwise go on to step D7.
1103 // D6. [Add back]. The probability that this step is necessary is very
1104 // small, on the order of only 2/b. Make sure that test data accounts for
1105 // this possibility. Decrease q[j] by 1
1107 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1108 // A carry will occur to the left of u[j+n], and it should be ignored
1109 // since it cancels with the borrow that occurred in D4.
1111 for (uint32_t i = 0; i < n; i++) {
1112 uint32_t limit = std::min(u[j+i],v[i]);
1113 u[j+i] += v[i] + carry;
1114 carry = u[j+i] < limit || (carry && u[j+i] == limit);
1118 DEBUG(cerr << "KnuthDiv: after correction:");
1119 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1120 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
1122 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1125 DEBUG(cerr << "KnuthDiv: quotient:");
1126 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1127 DEBUG(cerr << '\n');
1129 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1130 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1131 // compute the remainder (urem uses this).
1133 // The value d is expressed by the "shift" value above since we avoided
1134 // multiplication by d by using a shift left. So, all we have to do is
1135 // shift right here. In order to mak
1137 DEBUG(cerr << "KnuthDiv: remainder:");
1138 for (int i = n-1; i >= 0; i--) {
1139 r[i] = (u[i] >> shift) | carry;
1140 carry = u[i] << shift;
1141 DEBUG(cerr << " " << r[i]);
1143 DEBUG(cerr << '\n');
1145 DEBUG(cerr << std::setbase(10) << '\n');
1148 // This function makes calling KnuthDiv a little more convenient. It uses
1149 // APInt parameters instead of uint32_t* parameters. It can also divide APInt
1150 // values of different widths.
1151 void APInt::divide(const APInt LHS, uint32_t lhsWords,
1152 const APInt &RHS, uint32_t rhsWords,
1153 APInt *Quotient, APInt *Remainder)
1155 assert(lhsWords >= rhsWords && "Fractional result");
1157 // First, compose the values into an array of 32-bit words instead of
1158 // 64-bit words. This is a necessity of both the "short division" algorithm
1159 // and the the Knuth "classical algorithm" which requires there to be native
1160 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1161 // can't use 64-bit operands here because we don't have native results of
1162 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1163 // work on large-endian machines.
1164 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1165 uint32_t n = rhsWords * 2;
1166 uint32_t m = (lhsWords * 2) - n;
1167 // FIXME: allocate space on stack if m and n are sufficiently small.
1168 uint32_t *U = new uint32_t[m + n + 1];
1169 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1170 for (unsigned i = 0; i < lhsWords; ++i) {
1171 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
1172 U[i * 2] = tmp & mask;
1173 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1175 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1177 uint32_t *V = new uint32_t[n];
1178 memset(V, 0, (n)*sizeof(uint32_t));
1179 for (unsigned i = 0; i < rhsWords; ++i) {
1180 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
1181 V[i * 2] = tmp & mask;
1182 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1185 // Set up the quotient and remainder
1186 uint32_t *Q = new uint32_t[m+n];
1187 memset(Q, 0, (m+n) * sizeof(uint32_t));
1190 R = new uint32_t[n];
1191 memset(R, 0, n * sizeof(uint32_t));
1194 // Now, adjust m and n for the Knuth division. n is the number of words in
1195 // the divisor. m is the number of words by which the dividend exceeds the
1196 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1197 // contain any zero words or the Knuth algorithm fails.
1198 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1202 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1205 // If we're left with only a single word for the divisor, Knuth doesn't work
1206 // so we implement the short division algorithm here. This is much simpler
1207 // and faster because we are certain that we can divide a 64-bit quantity
1208 // by a 32-bit quantity at hardware speed and short division is simply a
1209 // series of such operations. This is just like doing short division but we
1210 // are using base 2^32 instead of base 10.
1211 assert(n != 0 && "Divide by zero?");
1213 uint32_t divisor = V[0];
1214 uint32_t remainder = 0;
1215 for (int i = m+n-1; i >= 0; i--) {
1216 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1217 if (partial_dividend == 0) {
1220 } else if (partial_dividend < divisor) {
1222 remainder = partial_dividend;
1223 } else if (partial_dividend == divisor) {
1227 Q[i] = partial_dividend / divisor;
1228 remainder = partial_dividend - (Q[i] * divisor);
1234 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1236 KnuthDiv(U, V, Q, R, m, n);
1239 // If the caller wants the quotient
1241 // Set up the Quotient value's memory.
1242 if (Quotient->BitWidth != LHS.BitWidth) {
1243 if (Quotient->isSingleWord())
1246 delete Quotient->pVal;
1247 Quotient->BitWidth = LHS.BitWidth;
1248 if (!Quotient->isSingleWord())
1249 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
1253 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1255 if (lhsWords == 1) {
1257 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1258 if (Quotient->isSingleWord())
1259 Quotient->VAL = tmp;
1261 Quotient->pVal[0] = tmp;
1263 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1264 for (unsigned i = 0; i < lhsWords; ++i)
1266 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1270 // If the caller wants the remainder
1272 // Set up the Remainder value's memory.
1273 if (Remainder->BitWidth != RHS.BitWidth) {
1274 if (Remainder->isSingleWord())
1277 delete Remainder->pVal;
1278 Remainder->BitWidth = RHS.BitWidth;
1279 if (!Remainder->isSingleWord())
1280 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
1284 // The remainder is in R. Reconstitute the remainder into Remainder's low
1286 if (rhsWords == 1) {
1288 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1289 if (Remainder->isSingleWord())
1290 Remainder->VAL = tmp;
1292 Remainder->pVal[0] = tmp;
1294 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1295 for (unsigned i = 0; i < rhsWords; ++i)
1296 Remainder->pVal[i] =
1297 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1301 // Clean up the memory we allocated.
1308 /// Unsigned divide this APInt by APInt RHS.
1309 /// @brief Unsigned division function for APInt.
1310 APInt APInt::udiv(const APInt& RHS) const {
1311 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1313 // First, deal with the easy case
1314 if (isSingleWord()) {
1315 assert(RHS.VAL != 0 && "Divide by zero?");
1316 return APInt(BitWidth, VAL / RHS.VAL);
1319 // Get some facts about the LHS and RHS number of bits and words
1320 uint32_t rhsBits = RHS.getActiveBits();
1321 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1322 assert(rhsWords && "Divided by zero???");
1323 uint32_t lhsBits = this->getActiveBits();
1324 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1326 // Deal with some degenerate cases
1329 return APInt(BitWidth, 0);
1330 else if (lhsWords < rhsWords || this->ult(RHS)) {
1331 // X / Y ===> 0, iff X < Y
1332 return APInt(BitWidth, 0);
1333 } else if (*this == RHS) {
1335 return APInt(BitWidth, 1);
1336 } else if (lhsWords == 1 && rhsWords == 1) {
1337 // All high words are zero, just use native divide
1338 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
1341 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1342 APInt Quotient(1,0); // to hold result.
1343 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1347 /// Unsigned remainder operation on APInt.
1348 /// @brief Function for unsigned remainder operation.
1349 APInt APInt::urem(const APInt& RHS) const {
1350 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1351 if (isSingleWord()) {
1352 assert(RHS.VAL != 0 && "Remainder by zero?");
1353 return APInt(BitWidth, VAL % RHS.VAL);
1356 // Get some facts about the LHS
1357 uint32_t lhsBits = getActiveBits();
1358 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
1360 // Get some facts about the RHS
1361 uint32_t rhsBits = RHS.getActiveBits();
1362 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1363 assert(rhsWords && "Performing remainder operation by zero ???");
1365 // Check the degenerate cases
1366 if (lhsWords == 0) {
1368 return APInt(BitWidth, 0);
1369 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1370 // X % Y ===> X, iff X < Y
1372 } else if (*this == RHS) {
1374 return APInt(BitWidth, 0);
1375 } else if (lhsWords == 1) {
1376 // All high words are zero, just use native remainder
1377 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
1380 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1381 APInt Remainder(1,0);
1382 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1386 /// @brief Converts a char array into an integer.
1387 void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
1389 // Check our assumptions here
1390 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1391 "Radix should be 2, 8, 10, or 16!");
1392 assert(str && "String is null?");
1393 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1394 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1395 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1396 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1399 if (!isSingleWord())
1400 pVal = getClearedMemory(getNumWords());
1402 // Figure out if we can shift instead of multiply
1403 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1405 // Set up an APInt for the digit to add outside the loop so we don't
1406 // constantly construct/destruct it.
1407 APInt apdigit(getBitWidth(), 0);
1408 APInt apradix(getBitWidth(), radix);
1410 // Enter digit traversal loop
1411 for (unsigned i = 0; i < slen; i++) {
1414 char cdigit = str[i];
1415 if (isdigit(cdigit))
1416 digit = cdigit - '0';
1417 else if (isxdigit(cdigit))
1419 digit = cdigit - 'a' + 10;
1420 else if (cdigit >= 'A')
1421 digit = cdigit - 'A' + 10;
1423 assert(0 && "huh?");
1425 assert(0 && "Invalid character in digit string");
1427 // Shift or multiple the value by the radix
1433 // Add in the digit we just interpreted
1434 apdigit.pVal[0] = digit;
1439 /// to_string - This function translates the APInt into a string.
1440 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1441 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1442 "Radix should be 2, 8, 10, or 16!");
1443 static const char *digits[] = {
1444 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1447 uint32_t bits_used = getActiveBits();
1448 if (isSingleWord()) {
1450 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1451 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1454 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1455 (APINT_BITS_PER_WORD-BitWidth);
1456 sprintf(buf, format, sextVal);
1458 sprintf(buf, format, VAL);
1463 uint32_t bit = v & 1;
1465 buf[bits_used] = digits[bit][0];
1474 uint64_t mask = radix - 1;
1475 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1476 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1477 for (uint32_t i = 0; i < getNumWords(); ++i) {
1478 uint64_t value = pVal[i];
1479 for (uint32_t j = 0; j < nibbles; ++j) {
1480 result.insert(0, digits[ value & mask ]);
1488 APInt divisor(4, radix);
1489 APInt zero(tmp.getBitWidth(), 0);
1490 size_t insert_at = 0;
1491 if (wantSigned && tmp[BitWidth-1]) {
1492 // They want to print the signed version and it is a negative value
1493 // Flip the bits and add one to turn it into the equivalent positive
1494 // value and put a '-' in the result.
1500 if (tmp == APInt(tmp.getBitWidth(), 0))
1502 else while (tmp.ne(zero)) {
1504 APInt tmp2(tmp.getBitWidth(), 0);
1505 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1507 uint32_t digit = APdigit.getValue();
1508 assert(digit < radix && "divide failed");
1509 result.insert(insert_at,digits[digit]);
1517 void APInt::dump() const
1519 std::cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
1522 else for (unsigned i = getNumWords(); i > 0; i--) {
1523 std::cerr << pVal[i-1] << " ";
1525 std::cerr << " (" << this->toString(10, false) << ")\n" << std::setbase(10);