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"
23 // A utility function for allocating memory, checking for allocation failures,
24 // and ensuring the contents is zeroed.
25 inline static uint64_t* getClearedMemory(uint32_t numWords) {
26 uint64_t * result = new uint64_t[numWords];
27 assert(result && "APInt memory allocation fails!");
28 memset(result, 0, numWords * sizeof(uint64_t));
32 // A utility function for allocating memory and checking for allocation failure.
33 inline static uint64_t* getMemory(uint32_t numWords) {
34 uint64_t * result = new uint64_t[numWords];
35 assert(result && "APInt memory allocation fails!");
39 APInt::APInt(uint32_t numBits, uint64_t val)
40 : BitWidth(numBits), pVal(0) {
41 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
42 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
44 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
46 pVal = getClearedMemory(getNumWords());
51 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
52 : BitWidth(numBits), pVal(0) {
53 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
54 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
55 assert(bigVal && "Null pointer detected!");
57 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
59 pVal = getMemory(getNumWords());
60 // Calculate the actual length of bigVal[].
61 uint32_t maxN = std::max<uint32_t>(numWords, getNumWords());
62 uint32_t minN = std::min<uint32_t>(numWords, getNumWords());
63 memcpy(pVal, bigVal, (minN - 1) * APINT_WORD_SIZE);
64 pVal[minN-1] = bigVal[minN-1] &
66 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
67 if (maxN == getNumWords())
68 memset(pVal+numWords, 0, (getNumWords() - numWords) * APINT_WORD_SIZE);
72 /// @brief Create a new APInt by translating the char array represented
74 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
76 : BitWidth(numbits), pVal(0) {
77 fromString(numbits, StrStart, slen, radix);
80 /// @brief Create a new APInt by translating the string represented
82 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
83 : BitWidth(numbits), pVal(0) {
84 assert(!Val.empty() && "String empty?");
85 fromString(numbits, Val.c_str(), Val.size(), radix);
88 /// @brief Copy constructor
89 APInt::APInt(const APInt& APIVal)
90 : BitWidth(APIVal.BitWidth), pVal(0) {
94 pVal = getMemory(getNumWords());
95 memcpy(pVal, APIVal.pVal, getNumWords() * APINT_WORD_SIZE);
100 if (!isSingleWord() && pVal)
104 /// @brief Copy assignment operator. Create a new object from the given
105 /// APInt one by initialization.
106 APInt& APInt::operator=(const APInt& RHS) {
107 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
111 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
115 /// @brief Assignment operator. Assigns a common case integer value to
117 APInt& APInt::operator=(uint64_t RHS) {
122 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
127 /// add_1 - This function adds a single "digit" integer, y, to the multiple
128 /// "digit" integer array, x[]. x[] is modified to reflect the addition and
129 /// 1 is returned if there is a carry out, otherwise 0 is returned.
130 /// @returns the carry of the addition.
131 static uint64_t add_1(uint64_t dest[],
132 uint64_t x[], uint32_t len,
134 for (uint32_t i = 0; i < len; ++i) {
146 /// @brief Prefix increment operator. Increments the APInt by one.
147 APInt& APInt::operator++() {
151 add_1(pVal, pVal, getNumWords(), 1);
156 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
157 /// the multi-digit integer array, x[], propagating the borrowed 1 value until
158 /// no further borrowing is neeeded or it runs out of "digits" in x. The result
159 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
160 /// In other words, if y > x then this function returns 1, otherwise 0.
161 static uint64_t sub_1(uint64_t x[], uint32_t len,
163 for (uint32_t i = 0; i < len; ++i) {
167 y = 1; // We have to "borrow 1" from next "digit"
169 y = 0; // No need to borrow
170 break; // Remaining digits are unchanged so exit early
176 /// @brief Prefix decrement operator. Decrements the APInt by one.
177 APInt& APInt::operator--() {
181 sub_1(pVal, getNumWords(), 1);
186 /// add - This function adds the integer array x[] by integer array
187 /// y[] and returns the carry.
188 static uint64_t add(uint64_t dest[], uint64_t x[],
189 uint64_t y[], uint32_t len) {
191 for (uint32_t i = 0; i< len; ++i) {
193 dest[i] = carry + y[i];
194 carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
199 /// @brief Addition assignment operator. Adds this APInt by the given APInt&
200 /// RHS and assigns the result to this APInt.
201 APInt& APInt::operator+=(const APInt& RHS) {
202 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
203 if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
205 if (RHS.isSingleWord()) add_1(pVal, pVal, getNumWords(), RHS.VAL);
207 if (getNumWords() <= RHS.getNumWords())
208 add(pVal, pVal, RHS.pVal, getNumWords());
210 uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.getNumWords());
211 add_1(pVal + RHS.getNumWords(), pVal + RHS.getNumWords(),
212 getNumWords() - RHS.getNumWords(), carry);
220 /// sub - This function subtracts the integer array x[] by
221 /// integer array y[], and returns the borrow-out carry.
222 static uint64_t sub(uint64_t dest[], uint64_t x[],
223 uint64_t y[], uint32_t len) {
227 for (uint32_t i = 0; i < len; ++i) {
228 uint64_t Y = y[i], X = x[i];
239 /// @brief Subtraction assignment operator. Subtracts this APInt by the given
240 /// APInt &RHS and assigns the result to this APInt.
241 APInt& APInt::operator-=(const APInt& RHS) {
242 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
244 VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
246 if (RHS.isSingleWord())
247 sub_1(pVal, getNumWords(), RHS.VAL);
249 if (RHS.getNumWords() < getNumWords()) {
250 uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.getNumWords());
251 sub_1(pVal + RHS.getNumWords(), getNumWords() - RHS.getNumWords(),
255 sub(pVal, pVal, RHS.pVal, getNumWords());
262 /// mul_1 - This function performs the multiplication operation on a
263 /// large integer (represented as an integer array) and a uint64_t integer.
264 /// @returns the carry of the multiplication.
265 static uint64_t mul_1(uint64_t dest[],
266 uint64_t x[], uint32_t len,
268 // Split y into high 32-bit part and low 32-bit part.
269 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
270 uint64_t carry = 0, lx, hx;
271 for (uint32_t i = 0; i < len; ++i) {
272 lx = x[i] & 0xffffffffULL;
274 // hasCarry - A flag to indicate if has carry.
275 // hasCarry == 0, no carry
276 // hasCarry == 1, has carry
277 // hasCarry == 2, no carry and the calculation result == 0.
278 uint8_t hasCarry = 0;
279 dest[i] = carry + lx * ly;
280 // Determine if the add above introduces carry.
281 hasCarry = (dest[i] < carry) ? 1 : 0;
282 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
283 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
284 // (2^32 - 1) + 2^32 = 2^64.
285 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
287 carry += (lx * hy) & 0xffffffffULL;
288 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
289 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
290 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
296 /// mul - This function multiplies integer array x[] by integer array y[] and
297 /// stores the result into integer array dest[].
298 /// Note the array dest[]'s size should no less than xlen + ylen.
299 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
300 uint64_t y[], uint32_t ylen) {
301 dest[xlen] = mul_1(dest, x, xlen, y[0]);
303 for (uint32_t i = 1; i < ylen; ++i) {
304 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
305 uint64_t carry = 0, lx, hx;
306 for (uint32_t j = 0; j < xlen; ++j) {
307 lx = x[j] & 0xffffffffULL;
309 // hasCarry - A flag to indicate if has carry.
310 // hasCarry == 0, no carry
311 // hasCarry == 1, has carry
312 // hasCarry == 2, no carry and the calculation result == 0.
313 uint8_t hasCarry = 0;
314 uint64_t resul = carry + lx * ly;
315 hasCarry = (resul < carry) ? 1 : 0;
316 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
317 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
319 carry += (lx * hy) & 0xffffffffULL;
320 resul = (carry << 32) | (resul & 0xffffffffULL);
322 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
323 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
324 ((lx * hy) >> 32) + hx * hy;
326 dest[i+xlen] = carry;
330 /// @brief Multiplication assignment operator. Multiplies this APInt by the
331 /// given APInt& RHS and assigns the result to this APInt.
332 APInt& APInt::operator*=(const APInt& RHS) {
333 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
334 if (isSingleWord()) VAL *= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
336 // one-based first non-zero bit position.
337 uint32_t first = getActiveBits();
338 uint32_t xlen = !first ? 0 : whichWord(first - 1) + 1;
341 else if (RHS.isSingleWord())
342 mul_1(pVal, pVal, xlen, RHS.VAL);
344 first = RHS.getActiveBits();
345 uint32_t ylen = !first ? 0 : whichWord(first - 1) + 1;
347 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
350 uint64_t *dest = getMemory(xlen+ylen);
351 mul(dest, pVal, xlen, RHS.pVal, ylen);
352 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
353 getNumWords() : xlen + ylen) * APINT_WORD_SIZE);
361 /// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
362 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
363 APInt& APInt::operator&=(const APInt& RHS) {
364 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
365 if (isSingleWord()) {
369 uint32_t numWords = getNumWords();
370 for (uint32_t i = 0; i < numWords; ++i)
371 pVal[i] &= RHS.pVal[i];
375 /// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
376 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
377 APInt& APInt::operator|=(const APInt& RHS) {
378 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
379 if (isSingleWord()) {
383 uint32_t numWords = getNumWords();
384 for (uint32_t i = 0; i < numWords; ++i)
385 pVal[i] |= RHS.pVal[i];
389 /// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
390 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
391 APInt& APInt::operator^=(const APInt& RHS) {
392 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
393 if (isSingleWord()) {
397 uint32_t numWords = getNumWords();
398 for (uint32_t i = 0; i < numWords; ++i)
399 pVal[i] ^= RHS.pVal[i];
403 /// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
404 /// and the given APInt& RHS.
405 APInt APInt::operator&(const APInt& RHS) const {
406 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
408 return APInt(getBitWidth(), VAL & RHS.VAL);
411 uint32_t numWords = getNumWords();
412 for (uint32_t i = 0; i < numWords; ++i)
413 Result.pVal[i] &= RHS.pVal[i];
417 /// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
418 /// and the given APInt& RHS.
419 APInt APInt::operator|(const APInt& RHS) const {
420 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
422 return APInt(getBitWidth(), VAL | RHS.VAL);
424 uint32_t numWords = getNumWords();
425 for (uint32_t i = 0; i < numWords; ++i)
426 Result.pVal[i] |= RHS.pVal[i];
430 /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
431 /// and the given APInt& RHS.
432 APInt APInt::operator^(const APInt& RHS) const {
433 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
435 return APInt(getBitWidth(), VAL ^ RHS.VAL);
437 uint32_t numWords = getNumWords();
438 for (uint32_t i = 0; i < numWords; ++i)
439 Result.pVal[i] ^= RHS.pVal[i];
443 /// @brief Logical negation operator. Performs logical negation operation on
445 bool APInt::operator !() const {
449 for (uint32_t i = 0; i < getNumWords(); ++i)
455 /// @brief Multiplication operator. Multiplies this APInt by the given APInt&
457 APInt APInt::operator*(const APInt& RHS) const {
458 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
461 API.clearUnusedBits();
465 /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
466 APInt APInt::operator+(const APInt& RHS) const {
467 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
470 API.clearUnusedBits();
474 /// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
475 APInt APInt::operator-(const APInt& RHS) const {
476 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
482 /// @brief Array-indexing support.
483 bool APInt::operator[](uint32_t bitPosition) const {
484 return (maskBit(bitPosition) & (isSingleWord() ?
485 VAL : pVal[whichWord(bitPosition)])) != 0;
488 /// @brief Equality operator. Compare this APInt with the given APInt& RHS
489 /// for the validity of the equality relationship.
490 bool APInt::operator==(const APInt& RHS) const {
491 uint32_t n1 = getActiveBits();
492 uint32_t n2 = RHS.getActiveBits();
493 if (n1 != n2) return false;
494 else if (isSingleWord())
495 return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
497 if (n1 <= APINT_BITS_PER_WORD)
498 return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
499 for (int i = whichWord(n1 - 1); i >= 0; --i)
500 if (pVal[i] != RHS.pVal[i]) return false;
505 /// @brief Equality operator. Compare this APInt with the given uint64_t value
506 /// for the validity of the equality relationship.
507 bool APInt::operator==(uint64_t Val) const {
511 uint32_t n = getActiveBits();
512 if (n <= APINT_BITS_PER_WORD)
513 return pVal[0] == Val;
519 /// @brief Unsigned less than comparison
520 bool APInt::ult(const APInt& RHS) const {
521 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
523 return VAL < RHS.VAL;
525 uint32_t n1 = getActiveBits();
526 uint32_t n2 = RHS.getActiveBits();
531 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
532 return pVal[0] < RHS.pVal[0];
533 for (int i = whichWord(n1 - 1); i >= 0; --i) {
534 if (pVal[i] > RHS.pVal[i]) return false;
535 else if (pVal[i] < RHS.pVal[i]) return true;
541 /// @brief Signed less than comparison
542 bool APInt::slt(const APInt& RHS) const {
543 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
544 if (isSingleWord()) {
545 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
546 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
547 return lhsSext < rhsSext;
552 bool lhsNegative = false;
553 bool rhsNegative = false;
554 if (lhs[BitWidth-1]) {
559 if (rhs[BitWidth-1]) {
566 return !lhs.ult(rhs);
569 else if (rhsNegative)
575 /// Set the given bit to 1 whose poition is given as "bitPosition".
576 /// @brief Set a given bit to 1.
577 APInt& APInt::set(uint32_t bitPosition) {
578 if (isSingleWord()) VAL |= maskBit(bitPosition);
579 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
583 /// @brief Set every bit to 1.
584 APInt& APInt::set() {
586 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
588 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
590 pVal[getNumWords() - 1] = ~0ULL >>
591 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
596 /// Set the given bit to 0 whose position is given as "bitPosition".
597 /// @brief Set a given bit to 0.
598 APInt& APInt::clear(uint32_t bitPosition) {
600 VAL &= ~maskBit(bitPosition);
602 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
606 /// @brief Set every bit to 0.
607 APInt& APInt::clear() {
611 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
615 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
617 APInt APInt::operator~() const {
623 /// @brief Toggle every bit to its opposite value.
624 APInt& APInt::flip() {
625 if (isSingleWord()) VAL = (~(VAL <<
626 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
629 for (; i < getNumWords() - 1; ++i)
632 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
633 pVal[i] = (~(pVal[i] << offset)) >> offset;
638 /// Toggle a given bit to its opposite value whose position is given
639 /// as "bitPosition".
640 /// @brief Toggles a given bit to its opposite value.
641 APInt& APInt::flip(uint32_t bitPosition) {
642 assert(bitPosition < BitWidth && "Out of the bit-width range!");
643 if ((*this)[bitPosition]) clear(bitPosition);
644 else set(bitPosition);
648 /// getMaxValue - This function returns the largest value
649 /// for an APInt of the specified bit-width and if isSign == true,
650 /// it should be largest signed value, otherwise unsigned value.
651 APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
652 APInt Result(numBits, 0);
655 Result.clear(numBits - 1);
659 /// getMinValue - This function returns the smallest value for
660 /// an APInt of the given bit-width and if isSign == true,
661 /// it should be smallest signed value, otherwise zero.
662 APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
663 APInt Result(numBits, 0);
665 Result.set(numBits - 1);
669 /// getAllOnesValue - This function returns an all-ones value for
670 /// an APInt of the specified bit-width.
671 APInt APInt::getAllOnesValue(uint32_t numBits) {
672 return getMaxValue(numBits, false);
675 /// getNullValue - This function creates an '0' value for an
676 /// APInt of the specified bit-width.
677 APInt APInt::getNullValue(uint32_t numBits) {
678 return getMinValue(numBits, false);
681 /// HiBits - This function returns the high "numBits" bits of this APInt.
682 APInt APInt::getHiBits(uint32_t numBits) const {
683 return APIntOps::lshr(*this, BitWidth - numBits);
686 /// LoBits - This function returns the low "numBits" bits of this APInt.
687 APInt APInt::getLoBits(uint32_t numBits) const {
688 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
692 bool APInt::isPowerOf2() const {
693 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
696 /// countLeadingZeros - This function is a APInt version corresponding to
697 /// llvm/include/llvm/Support/MathExtras.h's function
698 /// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
699 /// the number of zeros from the most significant bit to the first one bit.
700 /// @returns numWord() * 64 if the value is zero.
701 uint32_t APInt::countLeadingZeros() const {
703 return CountLeadingZeros_64(VAL) - (APINT_BITS_PER_WORD - BitWidth);
705 for (uint32_t i = getNumWords(); i > 0u; --i) {
706 uint32_t tmp = CountLeadingZeros_64(pVal[i-1]);
708 if (tmp != APINT_BITS_PER_WORD)
709 if (i == getNumWords())
710 Count -= (APINT_BITS_PER_WORD - whichBit(BitWidth));
716 /// countTrailingZeros - This function is a APInt version corresponding to
717 /// llvm/include/llvm/Support/MathExtras.h's function
718 /// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
719 /// the number of zeros from the least significant bit to the first one bit.
720 /// @returns numWord() * 64 if the value is zero.
721 uint32_t APInt::countTrailingZeros() const {
723 return CountTrailingZeros_64(VAL);
724 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
725 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
728 /// countPopulation - This function is a APInt version corresponding to
729 /// llvm/include/llvm/Support/MathExtras.h's function
730 /// countPopulation_{32, 64}. It counts the number of set bits in a value.
731 /// @returns 0 if the value is zero.
732 uint32_t APInt::countPopulation() const {
734 return CountPopulation_64(VAL);
736 for (uint32_t i = 0; i < getNumWords(); ++i)
737 Count += CountPopulation_64(pVal[i]);
742 /// byteSwap - This function returns a byte-swapped representation of the
744 APInt APInt::byteSwap() const {
745 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
747 return APInt(BitWidth, ByteSwap_16(VAL));
748 else if (BitWidth == 32)
749 return APInt(BitWidth, ByteSwap_32(VAL));
750 else if (BitWidth == 48) {
751 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
752 Tmp1 = ByteSwap_32(Tmp1);
753 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
754 Tmp2 = ByteSwap_16(Tmp2);
757 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
758 } else if (BitWidth == 64)
759 return APInt(BitWidth, ByteSwap_64(VAL));
761 APInt Result(BitWidth, 0);
762 char *pByte = (char*)Result.pVal;
763 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
765 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
766 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
772 /// GreatestCommonDivisor - This function returns the greatest common
773 /// divisor of the two APInt values using Enclid's algorithm.
774 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
776 APInt A = API1, B = API2;
779 B = APIntOps::urem(A, B);
785 /// DoubleRoundToAPInt - This function convert a double value to
787 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
793 bool isNeg = T.I >> 63;
794 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
796 return APInt(64ull, 0u);
797 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
799 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
800 APInt(64u, mantissa >> (52 - exp));
801 APInt Tmp(exp + 1, mantissa);
802 Tmp = Tmp.shl(exp - 52);
803 return isNeg ? -Tmp : Tmp;
806 /// RoundToDouble - This function convert this APInt to a double.
807 /// The layout for double is as following (IEEE Standard 754):
808 /// --------------------------------------
809 /// | Sign Exponent Fraction Bias |
810 /// |-------------------------------------- |
811 /// | 1[63] 11[62-52] 52[51-00] 1023 |
812 /// --------------------------------------
813 double APInt::roundToDouble(bool isSigned) const {
815 // Handle the simple case where the value is contained in one uint64_t.
816 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
818 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
824 // Determine if the value is negative.
825 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
827 // Construct the absolute value if we're negative.
828 APInt Tmp(isNeg ? -(*this) : (*this));
830 // Figure out how many bits we're using.
831 uint32_t n = Tmp.getActiveBits();
833 // The exponent (without bias normalization) is just the number of bits
834 // we are using. Note that the sign bit is gone since we constructed the
838 // Return infinity for exponent overflow
840 if (!isSigned || !isNeg)
841 return double(INFINITY); // positive infinity
843 return double(-INFINITY); // negative infinity
845 exp += 1023; // Increment for 1023 bias
847 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
848 // extract the high 52 bits from the correct words in pVal.
850 unsigned hiWord = whichWord(n-1);
852 mantissa = Tmp.pVal[0];
854 mantissa >>= n - 52; // shift down, we want the top 52 bits.
856 assert(hiWord > 0 && "huh?");
857 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
858 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
859 mantissa = hibits | lobits;
862 // The leading bit of mantissa is implicit, so get rid of it.
863 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
868 T.I = sign | (exp << 52) | mantissa;
872 // Truncate to new width.
873 void APInt::trunc(uint32_t width) {
874 assert(width < BitWidth && "Invalid APInt Truncate request");
877 // Sign extend to a new width.
878 void APInt::sext(uint32_t width) {
879 assert(width > BitWidth && "Invalid APInt SignExtend request");
882 // Zero extend to a new width.
883 void APInt::zext(uint32_t width) {
884 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
887 /// Arithmetic right-shift this APInt by shiftAmt.
888 /// @brief Arithmetic right-shift function.
889 APInt APInt::ashr(uint32_t shiftAmt) const {
891 if (API.isSingleWord())
893 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
894 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
895 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
897 if (shiftAmt >= API.BitWidth) {
898 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
899 (API.getNumWords()-1) * APINT_WORD_SIZE);
900 API.pVal[API.getNumWords() - 1] =
902 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
905 for (; i < API.BitWidth - shiftAmt; ++i)
910 for (; i < API.BitWidth; ++i)
911 if (API[API.BitWidth-1])
919 /// Logical right-shift this APInt by shiftAmt.
920 /// @brief Logical right-shift function.
921 APInt APInt::lshr(uint32_t shiftAmt) const {
923 if (API.isSingleWord())
924 API.VAL >>= shiftAmt;
926 if (shiftAmt >= API.BitWidth)
927 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
929 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
930 if (API[i+shiftAmt]) API.set(i);
932 for (; i < API.BitWidth; ++i)
938 /// Left-shift this APInt by shiftAmt.
939 /// @brief Left-shift function.
940 APInt APInt::shl(uint32_t shiftAmt) const {
942 if (API.isSingleWord())
943 API.VAL <<= shiftAmt;
944 else if (shiftAmt >= API.BitWidth)
945 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
947 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
948 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
949 API.pVal[i] = API.pVal[i-offset];
950 memset(API.pVal, 0, offset * APINT_WORD_SIZE);
952 shiftAmt %= APINT_BITS_PER_WORD;
954 for (i = API.getNumWords() - 1; i > 0; --i)
955 API.pVal[i] = (API.pVal[i] << shiftAmt) |
956 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
957 API.pVal[i] <<= shiftAmt;
959 API.clearUnusedBits();
964 /// subMul - This function substracts x[len-1:0] * y from
965 /// dest[offset+len-1:offset], and returns the most significant
966 /// word of the product, minus the borrow-out from the subtraction.
967 static uint32_t subMul(uint32_t dest[], uint32_t offset,
968 uint32_t x[], uint32_t len, uint32_t y) {
969 uint64_t yl = (uint64_t) y & 0xffffffffL;
973 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
974 uint32_t prod_low = (uint32_t) prod;
975 uint32_t prod_high = (uint32_t) (prod >> 32);
977 carry = (prod_low < carry ? 1 : 0) + prod_high;
978 uint32_t x_j = dest[offset+j];
979 prod_low = x_j - prod_low;
980 if (prod_low > x_j) ++carry;
981 dest[offset+j] = prod_low;
986 /// unitDiv - This function divides N by D,
987 /// and returns (remainder << 32) | quotient.
988 /// Assumes (N >> 32) < D.
989 static uint64_t unitDiv(uint64_t N, uint32_t D) {
990 uint64_t q, r; // q: quotient, r: remainder.
991 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
992 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
993 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
998 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
999 uint64_t c = N - ((uint64_t) D << 31);
1000 // Divide (c1*2^32 + c0) by d
1003 // Add 2^31 to quotient
1007 return (r << 32) | (q & 0xFFFFFFFFl);
1012 /// div - This is basically Knuth's formulation of the classical algorithm.
1013 /// Correspondance with Knuth's notation:
1014 /// Knuth's u[0:m+n] == zds[nx:0].
1015 /// Knuth's v[1:n] == y[ny-1:0]
1016 /// Knuth's n == ny.
1017 /// Knuth's m == nx-ny.
1018 /// Our nx == Knuth's m+n.
1019 /// Could be re-implemented using gmp's mpn_divrem:
1020 /// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
1022 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1023 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1024 /// variables here have the same names as in the algorithm. Comments explain
1025 /// the algorithm and any deviation from it.
1026 static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1027 uint32_t m, uint32_t n) {
1028 assert(u && "Must provide dividend");
1029 assert(v && "Must provide divisor");
1030 assert(q && "Must provide quotient");
1031 assert(n>1 && "n must be > 1");
1033 // Knuth uses the value b as the base of the number system. In our case b
1034 // is 2^31 so we just set it to -1u.
1035 uint64_t b = uint64_t(1) << 32;
1037 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1038 // u and v by d. Note that we have taken Knuth's advice here to use a power
1039 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1040 // 2 allows us to shift instead of multiply and it is easy to determine the
1041 // shift amount from the leading zeros. We are basically normalizing the u
1042 // and v so that its high bits are shifted to the top of v's range without
1043 // overflow. Note that this can require an extra word in u so that u must
1044 // be of length m+n+1.
1045 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1046 uint32_t v_carry = 0;
1047 uint32_t u_carry = 0;
1049 for (uint32_t i = 0; i < m+n; ++i) {
1050 uint32_t u_tmp = u[i] >> (32 - shift);
1051 u[i] = (u[i] << shift) | u_carry;
1054 for (uint32_t i = 0; i < n; ++i) {
1055 uint32_t v_tmp = v[i] >> (32 - shift);
1056 v[i] = (v[i] << shift) | v_carry;
1062 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1065 // D3. [Calculate q'.].
1066 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1067 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1068 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1069 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1070 // on v[n-2] determines at high speed most of the cases in which the trial
1071 // value qp is one too large, and it eliminates all cases where qp is two
1073 uint64_t qp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) / v[n-1];
1074 uint64_t rp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) % v[n-1];
1075 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1080 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1085 // D4. [Multiply and subtract.] Replace u with u - q*v (for each word).
1086 uint32_t borrow = 0;
1087 for (uint32_t i = 0; i < n; i++) {
1088 uint32_t save = u[j+i];
1089 u[j+i] = uint64_t(u[j+i]) - (qp * v[i]) - borrow;
1090 if (u[j+i] > save) {
1100 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1101 // negative, go to step D6; otherwise go on to step D7.
1104 // D6. [Add back]. The probability that this step is necessary is very
1105 // small, on the order of only 2/b. Make sure that test data accounts for
1106 // this possibility. Decreate qj by 1 and add v[...] to u[...]. A carry
1107 // will occur to the left of u[j+n], and it should be ignored since it
1108 // cancels with the borrow that occurred in D4.
1110 for (uint32_t i = 0; i < n; i++) {
1111 uint32_t save = u[j+i];
1112 u[j+i] += v[i] + carry;
1113 carry = u[j+i] < save;
1117 // D7. [Loop on j.] Decreate j by one. Now if j >= 0, go back to D3.
1121 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1122 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1123 // compute the remainder (urem uses this).
1125 // The value d is expressed by the "shift" value above since we avoided
1126 // multiplication by d by using a shift left. So, all we have to do is
1127 // shift right here. In order to mak
1128 uint32_t mask = ~0u >> (32 - shift);
1130 for (int i = n-1; i >= 0; i--) {
1131 uint32_t save = u[i] & mask;
1132 r[i] = (u[i] >> shift) | carry;
1138 // This function makes calling KnuthDiv a little more convenient. It uses
1139 // APInt parameters instead of uint32_t* parameters. It can also divide APInt
1140 // values of different widths.
1141 void APInt::divide(const APInt LHS, uint32_t lhsWords,
1142 const APInt &RHS, uint32_t rhsWords,
1143 APInt *Quotient, APInt *Remainder)
1145 assert(lhsWords >= rhsWords && "Fractional result");
1147 // First, compose the values into an array of 32-bit words instead of
1148 // 64-bit words. This is a necessity of both the "short division" algorithm
1149 // and the the Knuth "classical algorithm" which requires there to be native
1150 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1151 // can't use 64-bit operands here because we don't have native results of
1152 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1153 // work on large-endian machines.
1154 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1155 uint32_t n = rhsWords * 2;
1156 uint32_t m = (lhsWords * 2) - n;
1157 // FIXME: allocate space on stack if m and n are sufficiently small.
1158 uint32_t *U = new uint32_t[m + n + 1];
1159 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1160 for (unsigned i = 0; i < lhsWords; ++i) {
1161 uint64_t tmp = (lhsWords == 1 ? LHS.VAL : LHS.pVal[i]);
1162 U[i * 2] = tmp & mask;
1163 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1165 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1167 uint32_t *V = new uint32_t[n];
1168 memset(V, 0, (n)*sizeof(uint32_t));
1169 for (unsigned i = 0; i < rhsWords; ++i) {
1170 uint64_t tmp = (rhsWords == 1 ? RHS.VAL : RHS.pVal[i]);
1171 V[i * 2] = tmp & mask;
1172 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1175 // Set up the quotient and remainder
1176 uint32_t *Q = new uint32_t[m+n];
1177 memset(Q, 0, (m+n) * sizeof(uint32_t));
1180 R = new uint32_t[n];
1181 memset(R, 0, n * sizeof(uint32_t));
1184 // Now, adjust m and n for the Knuth division. n is the number of words in
1185 // the divisor. m is the number of words by which the dividend exceeds the
1186 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1187 // contain any zero words or the Knuth algorithm fails.
1188 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1192 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1195 // If we're left with only a single word for the divisor, Knuth doesn't work
1196 // so we implement the short division algorithm here. This is much simpler
1197 // and faster because we are certain that we can divide a 64-bit quantity
1198 // by a 32-bit quantity at hardware speed and short division is simply a
1199 // series of such operations. This is just like doing short division but we
1200 // are using base 2^32 instead of base 10.
1201 assert(n != 0 && "Divide by zero?");
1203 uint32_t divisor = V[0];
1204 uint32_t remainder = 0;
1205 for (int i = m+n-1; i >= 0; i--) {
1206 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1207 if (partial_dividend == 0) {
1210 } else if (partial_dividend < divisor) {
1212 remainder = partial_dividend;
1213 } else if (partial_dividend == divisor) {
1217 Q[i] = partial_dividend / divisor;
1218 remainder = partial_dividend - (Q[i] * divisor);
1224 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1226 KnuthDiv(U, V, Q, R, m, n);
1229 // If the caller wants the quotient
1231 // Set up the Quotient value's memory.
1232 if (Quotient->BitWidth != LHS.BitWidth) {
1233 if (Quotient->isSingleWord())
1236 delete Quotient->pVal;
1237 Quotient->BitWidth = LHS.BitWidth;
1238 if (!Quotient->isSingleWord())
1239 Quotient->pVal = getClearedMemory(lhsWords);
1243 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1245 if (lhsWords == 1) {
1247 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1248 if (Quotient->isSingleWord())
1249 Quotient->VAL = tmp;
1251 Quotient->pVal[0] = tmp;
1253 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1254 for (unsigned i = 0; i < lhsWords; ++i)
1256 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1260 // If the caller wants the remainder
1262 // Set up the Remainder value's memory.
1263 if (Remainder->BitWidth != RHS.BitWidth) {
1264 if (Remainder->isSingleWord())
1267 delete Remainder->pVal;
1268 Remainder->BitWidth = RHS.BitWidth;
1269 if (!Remainder->isSingleWord())
1270 Remainder->pVal = getClearedMemory(rhsWords);
1274 // The remainder is in R. Reconstitute the remainder into Remainder's low
1276 if (rhsWords == 1) {
1278 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1279 if (Remainder->isSingleWord())
1280 Remainder->VAL = tmp;
1282 Remainder->pVal[0] = tmp;
1284 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1285 for (unsigned i = 0; i < rhsWords; ++i)
1286 Remainder->pVal[i] =
1287 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1291 // Clean up the memory we allocated.
1298 /// Unsigned divide this APInt by APInt RHS.
1299 /// @brief Unsigned division function for APInt.
1300 APInt APInt::udiv(const APInt& RHS) const {
1301 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1303 // First, deal with the easy case
1304 if (isSingleWord()) {
1305 assert(RHS.VAL != 0 && "Divide by zero?");
1306 return APInt(BitWidth, VAL / RHS.VAL);
1309 // Get some facts about the LHS and RHS number of bits and words
1310 uint32_t rhsBits = RHS.getActiveBits();
1311 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1312 assert(rhsWords && "Divided by zero???");
1313 uint32_t lhsBits = this->getActiveBits();
1314 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1316 // Make a temporary to hold the result
1317 APInt Result(*this);
1319 // Deal with some degenerate cases
1321 return Result; // 0 / X == 0
1322 else if (lhsWords < rhsWords || Result.ult(RHS)) {
1323 // X / Y with X < Y == 0
1324 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1326 } else if (Result == RHS) {
1328 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1331 } else if (lhsWords == 1 && rhsWords == 1) {
1332 // All high words are zero, just use native divide
1333 Result.pVal[0] /= RHS.pVal[0];
1337 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1338 APInt Quotient(1,0); // to hold result.
1339 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1343 /// Unsigned remainder operation on APInt.
1344 /// @brief Function for unsigned remainder operation.
1345 APInt APInt::urem(const APInt& RHS) const {
1346 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1347 if (isSingleWord()) {
1348 assert(RHS.VAL != 0 && "Remainder by zero?");
1349 return APInt(BitWidth, VAL % RHS.VAL);
1352 // Make a temporary to hold the result
1353 APInt Result(*this);
1355 // Get some facts about the RHS
1356 uint32_t rhsBits = RHS.getActiveBits();
1357 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1358 assert(rhsWords && "Performing remainder operation by zero ???");
1360 // Get some facts about the LHS
1361 uint32_t lhsBits = Result.getActiveBits();
1362 uint32_t lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
1364 // Check the degenerate cases
1365 if (lhsWords == 0) {
1367 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1369 } else if (lhsWords < rhsWords || Result.ult(RHS)) {
1370 // X % Y == X iff X < Y
1372 } else if (Result == RHS) {
1374 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1376 } else if (lhsWords == 1) {
1377 // All high words are zero, just use native remainder
1378 Result.pVal[0] %= RHS.pVal[0];
1382 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1383 APInt Remainder(1,0);
1384 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1388 /// @brief Converts a char array into an integer.
1389 void APInt::fromString(uint32_t numbits, const char *StrStart, uint32_t slen,
1391 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1392 "Radix should be 2, 8, 10, or 16!");
1393 assert(StrStart && "String is null?");
1395 // If the radix is a power of 2, read the input
1396 // from most significant to least significant.
1397 if ((radix & (radix - 1)) == 0) {
1398 uint32_t nextBitPos = 0;
1399 uint32_t bits_per_digit = radix / 8 + 2;
1400 uint64_t resDigit = 0;
1401 BitWidth = slen * bits_per_digit;
1402 if (getNumWords() > 1)
1403 pVal = getMemory(getNumWords());
1404 for (int i = slen - 1; i >= 0; --i) {
1405 uint64_t digit = StrStart[i] - '0';
1406 resDigit |= digit << nextBitPos;
1407 nextBitPos += bits_per_digit;
1408 if (nextBitPos >= APINT_BITS_PER_WORD) {
1409 if (isSingleWord()) {
1413 pVal[size++] = resDigit;
1414 nextBitPos -= APINT_BITS_PER_WORD;
1415 resDigit = digit >> (bits_per_digit - nextBitPos);
1418 if (!isSingleWord() && size <= getNumWords())
1419 pVal[size] = resDigit;
1420 } else { // General case. The radix is not a power of 2.
1421 // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
1422 // and its digits number is 20.
1423 const uint32_t chars_per_word = 20;
1424 if (slen < chars_per_word ||
1425 (slen == chars_per_word && // In case the value <= 2^64 - 1
1426 strcmp(StrStart, "18446744073709551615") <= 0)) {
1427 BitWidth = APINT_BITS_PER_WORD;
1428 VAL = strtoull(StrStart, 0, 10);
1429 } else { // In case the value > 2^64 - 1
1430 BitWidth = (slen / chars_per_word + 1) * APINT_BITS_PER_WORD;
1431 pVal = getClearedMemory(getNumWords());
1432 uint32_t str_pos = 0;
1433 while (str_pos < slen) {
1434 uint32_t chunk = slen - str_pos;
1435 if (chunk > chars_per_word - 1)
1436 chunk = chars_per_word - 1;
1437 uint64_t resDigit = StrStart[str_pos++] - '0';
1438 uint64_t big_base = radix;
1439 while (--chunk > 0) {
1440 resDigit = resDigit * radix + StrStart[str_pos++] - '0';
1448 carry = mul_1(pVal, pVal, size, big_base);
1449 carry += add_1(pVal, pVal, size, resDigit);
1452 if (carry) pVal[size++] = carry;
1458 /// to_string - This function translates the APInt into a string.
1459 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1460 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1461 "Radix should be 2, 8, 10, or 16!");
1462 static const char *digits[] = {
1463 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1466 uint32_t bits_used = getActiveBits();
1467 if (isSingleWord()) {
1469 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1470 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1473 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1474 (APINT_BITS_PER_WORD-BitWidth);
1475 sprintf(buf, format, sextVal);
1477 sprintf(buf, format, VAL);
1482 uint32_t bit = v & 1;
1484 buf[bits_used] = digits[bit][0];
1493 uint64_t mask = radix - 1;
1494 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1495 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1496 for (uint32_t i = 0; i < getNumWords(); ++i) {
1497 uint64_t value = pVal[i];
1498 for (uint32_t j = 0; j < nibbles; ++j) {
1499 result.insert(0, digits[ value & mask ]);
1507 APInt divisor(4, radix);
1508 APInt zero(tmp.getBitWidth(), 0);
1509 size_t insert_at = 0;
1510 if (wantSigned && tmp[BitWidth-1]) {
1511 // They want to print the signed version and it is a negative value
1512 // Flip the bits and add one to turn it into the equivalent positive
1513 // value and put a '-' in the result.
1521 else while (tmp.ne(zero)) {
1523 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), 0, &APdigit);
1524 uint32_t digit = APdigit.getValue();
1525 assert(digit < radix && "urem failed");
1526 result.insert(insert_at,digits[digit]);
1527 APInt tmp2(tmp.getBitWidth(), 0);
1528 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2, 0);