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"
22 // A utility function for allocating memory, checking for allocation failures,
23 // and ensuring the contents is zeroed.
24 inline static uint64_t* getClearedMemory(uint32_t numWords) {
25 uint64_t * result = new uint64_t[numWords];
26 assert(result && "APInt memory allocation fails!");
27 memset(result, 0, numWords * sizeof(uint64_t));
31 // A utility function for allocating memory and checking for allocation failure.
32 inline static uint64_t* getMemory(uint32_t numWords) {
33 uint64_t * result = new uint64_t[numWords];
34 assert(result && "APInt memory allocation fails!");
38 APInt::APInt(uint32_t numBits, uint64_t val)
40 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
41 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
43 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
45 pVal = getClearedMemory(getNumWords());
50 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
52 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
53 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
54 assert(bigVal && "Null pointer detected!");
56 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
58 pVal = getMemory(getNumWords());
59 // Calculate the actual length of bigVal[].
60 uint32_t maxN = std::max<uint32_t>(numWords, getNumWords());
61 uint32_t minN = std::min<uint32_t>(numWords, getNumWords());
62 memcpy(pVal, bigVal, (minN - 1) * sizeof(uint64_t));
63 pVal[minN-1] = bigVal[minN-1] &
65 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
66 if (maxN == getNumWords())
67 memset(pVal+numWords, 0, (getNumWords() - numWords) * sizeof(uint64_t));
71 /// @brief Create a new APInt by translating the char array represented
73 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
75 fromString(numbits, StrStart, slen, radix);
78 /// @brief Create a new APInt by translating the string represented
80 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix) {
81 assert(!Val.empty() && "String empty?");
82 fromString(numbits, Val.c_str(), Val.size(), radix);
85 APInt::APInt(const APInt& APIVal)
86 : BitWidth(APIVal.BitWidth) {
90 pVal = getMemory(getNumWords());
91 memcpy(pVal, APIVal.pVal, getNumWords() * sizeof(uint64_t));
96 if (!isSingleWord() && pVal) delete[] pVal;
99 /// @brief Copy assignment operator. Create a new object from the given
100 /// APInt one by initialization.
101 APInt& APInt::operator=(const APInt& RHS) {
102 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
106 memcpy(pVal, RHS.pVal, getNumWords() * sizeof(uint64_t));
110 /// @brief Assignment operator. Assigns a common case integer value to
112 APInt& APInt::operator=(uint64_t RHS) {
117 memset(pVal+1, 0, (getNumWords() - 1) * sizeof(uint64_t));
122 /// add_1 - This function adds a single "digit" integer, y, to the multiple
123 /// "digit" integer array, x[]. x[] is modified to reflect the addition and
124 /// 1 is returned if there is a carry out, otherwise 0 is returned.
125 /// @returns the carry of the addition.
126 static uint64_t add_1(uint64_t dest[],
127 uint64_t x[], uint32_t len,
129 for (uint32_t i = 0; i < len; ++i) {
141 /// @brief Prefix increment operator. Increments the APInt by one.
142 APInt& APInt::operator++() {
146 add_1(pVal, pVal, getNumWords(), 1);
151 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
152 /// the multi-digit integer array, x[], propagating the borrowed 1 value until
153 /// no further borrowing is neeeded or it runs out of "digits" in x. The result
154 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
155 /// In other words, if y > x then this function returns 1, otherwise 0.
156 static uint64_t sub_1(uint64_t x[], uint32_t len,
158 for (uint32_t i = 0; i < len; ++i) {
162 y = 1; // We have to "borrow 1" from next "digit"
164 y = 0; // No need to borrow
165 break; // Remaining digits are unchanged so exit early
171 /// @brief Prefix decrement operator. Decrements the APInt by one.
172 APInt& APInt::operator--() {
176 sub_1(pVal, getNumWords(), 1);
181 /// add - This function adds the integer array x[] by integer array
182 /// y[] and returns the carry.
183 static uint64_t add(uint64_t dest[], uint64_t x[],
184 uint64_t y[], uint32_t len) {
186 for (uint32_t i = 0; i< len; ++i) {
188 dest[i] = carry + y[i];
189 carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
194 /// @brief Addition assignment operator. Adds this APInt by the given APInt&
195 /// RHS and assigns the result to this APInt.
196 APInt& APInt::operator+=(const APInt& RHS) {
197 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
198 if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
200 if (RHS.isSingleWord()) add_1(pVal, pVal, getNumWords(), RHS.VAL);
202 if (getNumWords() <= RHS.getNumWords())
203 add(pVal, pVal, RHS.pVal, getNumWords());
205 uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.getNumWords());
206 add_1(pVal + RHS.getNumWords(), pVal + RHS.getNumWords(),
207 getNumWords() - RHS.getNumWords(), carry);
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[], uint64_t x[],
218 uint64_t y[], uint32_t len) {
222 for (uint32_t i = 0; i < len; ++i) {
223 uint64_t Y = y[i], X = x[i];
234 /// @brief Subtraction assignment operator. Subtracts this APInt by the given
235 /// APInt &RHS and assigns the result to this APInt.
236 APInt& APInt::operator-=(const APInt& RHS) {
237 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
239 VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
241 if (RHS.isSingleWord())
242 sub_1(pVal, getNumWords(), RHS.VAL);
244 if (RHS.getNumWords() < getNumWords()) {
245 uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.getNumWords());
246 sub_1(pVal + RHS.getNumWords(), getNumWords() - RHS.getNumWords(),
250 sub(pVal, pVal, RHS.pVal, getNumWords());
257 /// mul_1 - This function performs the multiplication operation on a
258 /// large integer (represented as an integer array) and a uint64_t integer.
259 /// @returns the carry of the multiplication.
260 static uint64_t mul_1(uint64_t dest[],
261 uint64_t x[], uint32_t len,
263 // Split y into high 32-bit part and low 32-bit part.
264 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
265 uint64_t carry = 0, lx, hx;
266 for (uint32_t i = 0; i < len; ++i) {
267 lx = x[i] & 0xffffffffULL;
269 // hasCarry - A flag to indicate if has carry.
270 // hasCarry == 0, no carry
271 // hasCarry == 1, has carry
272 // hasCarry == 2, no carry and the calculation result == 0.
273 uint8_t hasCarry = 0;
274 dest[i] = carry + lx * ly;
275 // Determine if the add above introduces carry.
276 hasCarry = (dest[i] < carry) ? 1 : 0;
277 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
278 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
279 // (2^32 - 1) + 2^32 = 2^64.
280 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
282 carry += (lx * hy) & 0xffffffffULL;
283 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
284 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
285 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
291 /// mul - This function multiplies integer array x[] by integer array y[] and
292 /// stores the result into integer array dest[].
293 /// Note the array dest[]'s size should no less than xlen + ylen.
294 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
295 uint64_t y[], uint32_t ylen) {
296 dest[xlen] = mul_1(dest, x, xlen, y[0]);
298 for (uint32_t i = 1; i < ylen; ++i) {
299 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
300 uint64_t carry = 0, lx, hx;
301 for (uint32_t j = 0; j < xlen; ++j) {
302 lx = x[j] & 0xffffffffULL;
304 // hasCarry - A flag to indicate if has carry.
305 // hasCarry == 0, no carry
306 // hasCarry == 1, has carry
307 // hasCarry == 2, no carry and the calculation result == 0.
308 uint8_t hasCarry = 0;
309 uint64_t resul = carry + lx * ly;
310 hasCarry = (resul < carry) ? 1 : 0;
311 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
312 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
314 carry += (lx * hy) & 0xffffffffULL;
315 resul = (carry << 32) | (resul & 0xffffffffULL);
317 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
318 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
319 ((lx * hy) >> 32) + hx * hy;
321 dest[i+xlen] = carry;
325 /// @brief Multiplication assignment operator. Multiplies this APInt by the
326 /// given APInt& RHS and assigns the result to this APInt.
327 APInt& APInt::operator*=(const APInt& RHS) {
328 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
329 if (isSingleWord()) VAL *= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
331 // one-based first non-zero bit position.
332 uint32_t first = getActiveBits();
333 uint32_t xlen = !first ? 0 : whichWord(first - 1) + 1;
336 else if (RHS.isSingleWord())
337 mul_1(pVal, pVal, xlen, RHS.VAL);
339 first = RHS.getActiveBits();
340 uint32_t ylen = !first ? 0 : whichWord(first - 1) + 1;
342 memset(pVal, 0, getNumWords() * sizeof(uint64_t));
345 uint64_t *dest = getMemory(xlen+ylen);
346 mul(dest, pVal, xlen, RHS.pVal, ylen);
347 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
348 getNumWords() : xlen + ylen) * sizeof(uint64_t));
356 /// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
357 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
358 APInt& APInt::operator&=(const APInt& RHS) {
359 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
360 if (isSingleWord()) {
364 uint32_t numWords = getNumWords();
365 for (uint32_t i = 0; i < numWords; ++i)
366 pVal[i] &= RHS.pVal[i];
370 /// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
371 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
372 APInt& APInt::operator|=(const APInt& RHS) {
373 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
374 if (isSingleWord()) {
378 uint32_t numWords = getNumWords();
379 for (uint32_t i = 0; i < numWords; ++i)
380 pVal[i] |= RHS.pVal[i];
384 /// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
385 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
386 APInt& APInt::operator^=(const APInt& RHS) {
387 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
388 if (isSingleWord()) {
392 uint32_t numWords = getNumWords();
393 for (uint32_t i = 0; i < numWords; ++i)
394 pVal[i] ^= RHS.pVal[i];
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);
419 uint32_t numWords = getNumWords();
420 for (uint32_t i = 0; i < numWords; ++i)
421 Result.pVal[i] |= RHS.pVal[i];
425 /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
426 /// and the given APInt& RHS.
427 APInt APInt::operator^(const APInt& RHS) const {
428 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
430 return APInt(getBitWidth(), VAL ^ RHS.VAL);
432 uint32_t numWords = getNumWords();
433 for (uint32_t i = 0; i < numWords; ++i)
434 Result.pVal[i] ^= RHS.pVal[i];
438 /// @brief Logical negation operator. Performs logical negation operation on
440 bool APInt::operator !() const {
444 for (uint32_t i = 0; i < getNumWords(); ++i)
450 /// @brief Multiplication operator. Multiplies this APInt by the given APInt&
452 APInt APInt::operator*(const APInt& RHS) const {
453 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
456 API.clearUnusedBits();
460 /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
461 APInt APInt::operator+(const APInt& RHS) const {
462 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
465 API.clearUnusedBits();
469 /// @brief Subtraction operator. Subtracts 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");
477 /// @brief Array-indexing support.
478 bool APInt::operator[](uint32_t bitPosition) const {
479 return (maskBit(bitPosition) & (isSingleWord() ?
480 VAL : pVal[whichWord(bitPosition)])) != 0;
483 /// @brief Equality operator. Compare this APInt with the given APInt& RHS
484 /// for the validity of the equality relationship.
485 bool APInt::operator==(const APInt& RHS) const {
486 uint32_t n1 = getActiveBits();
487 uint32_t n2 = RHS.getActiveBits();
488 if (n1 != n2) return false;
489 else if (isSingleWord())
490 return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
492 if (n1 <= APINT_BITS_PER_WORD)
493 return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
494 for (int i = whichWord(n1 - 1); i >= 0; --i)
495 if (pVal[i] != RHS.pVal[i]) return false;
500 /// @brief Equality operator. Compare this APInt with the given uint64_t value
501 /// for the validity of the equality relationship.
502 bool APInt::operator==(uint64_t Val) const {
506 uint32_t n = getActiveBits();
507 if (n <= APINT_BITS_PER_WORD)
508 return pVal[0] == Val;
514 /// @brief Unsigned less than comparison
515 bool APInt::ult(const APInt& RHS) const {
516 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
518 return VAL < RHS.VAL;
520 uint32_t n1 = getActiveBits();
521 uint32_t n2 = RHS.getActiveBits();
526 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
527 return pVal[0] < RHS.pVal[0];
528 for (int i = whichWord(n1 - 1); i >= 0; --i) {
529 if (pVal[i] > RHS.pVal[i]) return false;
530 else if (pVal[i] < RHS.pVal[i]) return true;
536 /// @brief Signed less than comparison
537 bool APInt::slt(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 /// Set the given bit to 1 whose poition is given as "bitPosition".
559 /// @brief Set a given bit to 1.
560 APInt& APInt::set(uint32_t bitPosition) {
561 if (isSingleWord()) VAL |= maskBit(bitPosition);
562 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
566 /// @brief Set every bit to 1.
567 APInt& APInt::set() {
569 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
571 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
573 pVal[getNumWords() - 1] = ~0ULL >>
574 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
579 /// Set the given bit to 0 whose position is given as "bitPosition".
580 /// @brief Set a given bit to 0.
581 APInt& APInt::clear(uint32_t bitPosition) {
583 VAL &= ~maskBit(bitPosition);
585 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
589 /// @brief Set every bit to 0.
590 APInt& APInt::clear() {
594 memset(pVal, 0, getNumWords() * sizeof(uint64_t));
598 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
600 APInt APInt::operator~() const {
606 /// @brief Toggle every bit to its opposite value.
607 APInt& APInt::flip() {
608 if (isSingleWord()) VAL = (~(VAL <<
609 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
612 for (; i < getNumWords() - 1; ++i)
615 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
616 pVal[i] = (~(pVal[i] << offset)) >> offset;
621 /// Toggle a given bit to its opposite value whose position is given
622 /// as "bitPosition".
623 /// @brief Toggles a given bit to its opposite value.
624 APInt& APInt::flip(uint32_t bitPosition) {
625 assert(bitPosition < BitWidth && "Out of the bit-width range!");
626 if ((*this)[bitPosition]) clear(bitPosition);
627 else set(bitPosition);
631 /// to_string - This function translates the APInt into a string.
632 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
633 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
634 "Radix should be 2, 8, 10, or 16!");
635 static const char *digits[] = {
636 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
639 uint32_t bits_used = getActiveBits();
640 if (isSingleWord()) {
642 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
643 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
646 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
647 (APINT_BITS_PER_WORD-BitWidth);
648 sprintf(buf, format, sextVal);
650 sprintf(buf, format, VAL);
655 uint32_t bit = v & 1;
657 buf[bits_used] = digits[bit][0];
666 APInt divisor(tmp.getBitWidth(), radix);
667 APInt zero(tmp.getBitWidth(), 0);
668 size_t insert_at = 0;
669 if (wantSigned && tmp[BitWidth-1]) {
670 // They want to print the signed version and it is a negative value
671 // Flip the bits and add one to turn it into the equivalent positive
672 // value and put a '-' in the result.
680 else while (tmp.ne(zero)) {
681 APInt APdigit = APIntOps::urem(tmp,divisor);
682 uint32_t digit = APdigit.getValue();
683 assert(digit < radix && "urem failed");
684 result.insert(insert_at,digits[digit]);
685 tmp = APIntOps::udiv(tmp, divisor);
691 /// getMaxValue - This function returns the largest value
692 /// for an APInt of the specified bit-width and if isSign == true,
693 /// it should be largest signed value, otherwise unsigned value.
694 APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
695 APInt APIVal(numBits, 0);
697 if (isSign) APIVal.clear(numBits - 1);
701 /// getMinValue - This function returns the smallest value for
702 /// an APInt of the given bit-width and if isSign == true,
703 /// it should be smallest signed value, otherwise zero.
704 APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
705 APInt APIVal(numBits, 0);
706 if (isSign) APIVal.set(numBits - 1);
710 /// getAllOnesValue - This function returns an all-ones value for
711 /// an APInt of the specified bit-width.
712 APInt APInt::getAllOnesValue(uint32_t numBits) {
713 return getMaxValue(numBits, false);
716 /// getNullValue - This function creates an '0' value for an
717 /// APInt of the specified bit-width.
718 APInt APInt::getNullValue(uint32_t numBits) {
719 return getMinValue(numBits, false);
722 /// HiBits - This function returns the high "numBits" bits of this APInt.
723 APInt APInt::getHiBits(uint32_t numBits) const {
724 return APIntOps::lshr(*this, BitWidth - numBits);
727 /// LoBits - This function returns the low "numBits" bits of this APInt.
728 APInt APInt::getLoBits(uint32_t numBits) const {
729 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
733 bool APInt::isPowerOf2() const {
734 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
737 /// countLeadingZeros - This function is a APInt version corresponding to
738 /// llvm/include/llvm/Support/MathExtras.h's function
739 /// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
740 /// the number of zeros from the most significant bit to the first one bit.
741 /// @returns numWord() * 64 if the value is zero.
742 uint32_t APInt::countLeadingZeros() const {
744 return CountLeadingZeros_64(VAL) - (APINT_BITS_PER_WORD - BitWidth);
746 for (uint32_t i = getNumWords(); i > 0u; --i) {
747 uint32_t tmp = CountLeadingZeros_64(pVal[i-1]);
749 if (tmp != APINT_BITS_PER_WORD)
750 if (i == getNumWords())
751 Count -= (APINT_BITS_PER_WORD - whichBit(BitWidth));
757 /// countTrailingZeros - This function is a APInt version corresponding to
758 /// llvm/include/llvm/Support/MathExtras.h's function
759 /// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
760 /// the number of zeros from the least significant bit to the first one bit.
761 /// @returns numWord() * 64 if the value is zero.
762 uint32_t APInt::countTrailingZeros() const {
764 return CountTrailingZeros_64(VAL);
765 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
766 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
769 /// countPopulation - This function is a APInt version corresponding to
770 /// llvm/include/llvm/Support/MathExtras.h's function
771 /// countPopulation_{32, 64}. It counts the number of set bits in a value.
772 /// @returns 0 if the value is zero.
773 uint32_t APInt::countPopulation() const {
775 return CountPopulation_64(VAL);
777 for (uint32_t i = 0; i < getNumWords(); ++i)
778 Count += CountPopulation_64(pVal[i]);
783 /// byteSwap - This function returns a byte-swapped representation of the
785 APInt APInt::byteSwap() const {
786 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
788 return APInt(BitWidth, ByteSwap_16(VAL));
789 else if (BitWidth == 32)
790 return APInt(BitWidth, ByteSwap_32(VAL));
791 else if (BitWidth == 48) {
792 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
793 Tmp1 = ByteSwap_32(Tmp1);
794 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
795 Tmp2 = ByteSwap_16(Tmp2);
798 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
799 } else if (BitWidth == 64)
800 return APInt(BitWidth, ByteSwap_64(VAL));
802 APInt Result(BitWidth, 0);
803 char *pByte = (char*)Result.pVal;
804 for (uint32_t i = 0; i < BitWidth / sizeof(uint64_t) / 2; ++i) {
806 pByte[i] = pByte[BitWidth / sizeof(uint64_t) - 1 - i];
807 pByte[BitWidth / sizeof(uint64_t) - i - 1] = Tmp;
813 /// GreatestCommonDivisor - This function returns the greatest common
814 /// divisor of the two APInt values using Enclid's algorithm.
815 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
817 APInt A = API1, B = API2;
820 B = APIntOps::urem(A, B);
826 /// DoubleRoundToAPInt - This function convert a double value to
828 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
834 bool isNeg = T.I >> 63;
835 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
837 return APInt(64ull, 0u);
838 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
840 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
841 APInt(64u, mantissa >> (52 - exp));
842 APInt Tmp(exp + 1, mantissa);
843 Tmp = Tmp.shl(exp - 52);
844 return isNeg ? -Tmp : Tmp;
847 /// RoundToDouble - This function convert this APInt to a double.
848 /// The layout for double is as following (IEEE Standard 754):
849 /// --------------------------------------
850 /// | Sign Exponent Fraction Bias |
851 /// |-------------------------------------- |
852 /// | 1[63] 11[62-52] 52[51-00] 1023 |
853 /// --------------------------------------
854 double APInt::roundToDouble(bool isSigned) const {
855 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
856 APInt Tmp(isNeg ? -(*this) : (*this));
857 if (Tmp.isSingleWord())
858 return isSigned ? double(int64_t(Tmp.VAL)) : double(Tmp.VAL);
859 uint32_t n = Tmp.getActiveBits();
860 if (n <= APINT_BITS_PER_WORD)
861 return isSigned ? double(int64_t(Tmp.pVal[0])) : double(Tmp.pVal[0]);
862 // Exponent when normalized to have decimal point directly after
863 // leading one. This is stored excess 1023 in the exponent bit field.
864 uint64_t exp = n - 1;
867 assert(exp <= 1023 && "Infinity value!");
869 // Number of bits in mantissa including the leading one
872 if (n % APINT_BITS_PER_WORD >= 53)
873 mantissa = Tmp.pVal[whichWord(n - 1)] >> (n % APINT_BITS_PER_WORD - 53);
875 mantissa = (Tmp.pVal[whichWord(n - 1)] << (53 - n % APINT_BITS_PER_WORD)) |
876 (Tmp.pVal[whichWord(n - 1) - 1] >>
877 (11 + n % APINT_BITS_PER_WORD));
878 // The leading bit of mantissa is implicit, so get rid of it.
879 mantissa &= ~(1ULL << 52);
880 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
886 T.I = sign | (exp << 52) | mantissa;
890 // Truncate to new width.
891 void APInt::trunc(uint32_t width) {
892 assert(width < BitWidth && "Invalid APInt Truncate request");
895 // Sign extend to a new width.
896 void APInt::sext(uint32_t width) {
897 assert(width > BitWidth && "Invalid APInt SignExtend request");
900 // Zero extend to a new width.
901 void APInt::zext(uint32_t width) {
902 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
905 /// Arithmetic right-shift this APInt by shiftAmt.
906 /// @brief Arithmetic right-shift function.
907 APInt APInt::ashr(uint32_t shiftAmt) const {
909 if (API.isSingleWord())
911 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
912 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
913 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
915 if (shiftAmt >= API.BitWidth) {
916 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
917 (API.getNumWords()-1) * sizeof(uint64_t));
918 API.pVal[API.getNumWords() - 1] =
920 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
923 for (; i < API.BitWidth - shiftAmt; ++i)
928 for (; i < API.BitWidth; ++i)
929 if (API[API.BitWidth-1])
937 /// Logical right-shift this APInt by shiftAmt.
938 /// @brief Logical right-shift function.
939 APInt APInt::lshr(uint32_t shiftAmt) const {
941 if (API.isSingleWord())
942 API.VAL >>= shiftAmt;
944 if (shiftAmt >= API.BitWidth)
945 memset(API.pVal, 0, API.getNumWords() * sizeof(uint64_t));
947 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
948 if (API[i+shiftAmt]) API.set(i);
950 for (; i < API.BitWidth; ++i)
956 /// Left-shift this APInt by shiftAmt.
957 /// @brief Left-shift function.
958 APInt APInt::shl(uint32_t shiftAmt) const {
960 if (API.isSingleWord())
961 API.VAL <<= shiftAmt;
962 else if (shiftAmt >= API.BitWidth)
963 memset(API.pVal, 0, API.getNumWords() * sizeof(uint64_t));
965 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
966 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
967 API.pVal[i] = API.pVal[i-offset];
968 memset(API.pVal, 0, offset * sizeof(uint64_t));
970 shiftAmt %= APINT_BITS_PER_WORD;
972 for (i = API.getNumWords() - 1; i > 0; --i)
973 API.pVal[i] = (API.pVal[i] << shiftAmt) |
974 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
975 API.pVal[i] <<= shiftAmt;
977 API.clearUnusedBits();
981 /// subMul - This function substracts x[len-1:0] * y from
982 /// dest[offset+len-1:offset], and returns the most significant
983 /// word of the product, minus the borrow-out from the subtraction.
984 static uint32_t subMul(uint32_t dest[], uint32_t offset,
985 uint32_t x[], uint32_t len, uint32_t y) {
986 uint64_t yl = (uint64_t) y & 0xffffffffL;
990 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
991 uint32_t prod_low = (uint32_t) prod;
992 uint32_t prod_high = (uint32_t) (prod >> 32);
994 carry = (prod_low < carry ? 1 : 0) + prod_high;
995 uint32_t x_j = dest[offset+j];
996 prod_low = x_j - prod_low;
997 if (prod_low > x_j) ++carry;
998 dest[offset+j] = prod_low;
1003 /// unitDiv - This function divides N by D,
1004 /// and returns (remainder << 32) | quotient.
1005 /// Assumes (N >> 32) < D.
1006 static uint64_t unitDiv(uint64_t N, uint32_t D) {
1007 uint64_t q, r; // q: quotient, r: remainder.
1008 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
1009 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
1010 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
1015 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
1016 uint64_t c = N - ((uint64_t) D << 31);
1017 // Divide (c1*2^32 + c0) by d
1020 // Add 2^31 to quotient
1024 return (r << 32) | (q & 0xFFFFFFFFl);
1027 /// div - This is basically Knuth's formulation of the classical algorithm.
1028 /// Correspondance with Knuth's notation:
1029 /// Knuth's u[0:m+n] == zds[nx:0].
1030 /// Knuth's v[1:n] == y[ny-1:0]
1031 /// Knuth's n == ny.
1032 /// Knuth's m == nx-ny.
1033 /// Our nx == Knuth's m+n.
1034 /// Could be re-implemented using gmp's mpn_divrem:
1035 /// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
1036 static void div(uint32_t zds[], uint32_t nx, uint32_t y[], uint32_t ny) {
1038 do { // loop over digits of quotient
1039 // Knuth's j == our nx-j.
1040 // Knuth's u[j:j+n] == our zds[j:j-ny].
1041 uint32_t qhat; // treated as unsigned
1042 if (zds[j] == y[ny-1])
1043 qhat = -1U; // 0xffffffff
1045 uint64_t w = (((uint64_t)(zds[j])) << 32) +
1046 ((uint64_t)zds[j-1] & 0xffffffffL);
1047 qhat = (uint32_t) unitDiv(w, y[ny-1]);
1050 uint32_t borrow = subMul(zds, j - ny, y, ny, qhat);
1051 uint32_t save = zds[j];
1052 uint64_t num = ((uint64_t)save&0xffffffffL) -
1053 ((uint64_t)borrow&0xffffffffL);
1057 for (uint32_t i = 0; i < ny; i++) {
1058 carry += ((uint64_t) zds[j-ny+i] & 0xffffffffL)
1059 + ((uint64_t) y[i] & 0xffffffffL);
1060 zds[j-ny+i] = (uint32_t) carry;
1068 } while (--j >= ny);
1071 /// Unsigned divide this APInt by APInt RHS.
1072 /// @brief Unsigned division function for APInt.
1073 APInt APInt::udiv(const APInt& RHS) const {
1074 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1076 // First, deal with the easy case
1077 if (isSingleWord()) {
1078 assert(RHS.VAL != 0 && "Divide by zero?");
1079 return APInt(BitWidth, VAL / RHS.VAL);
1082 // Make a temporary to hold the result
1083 APInt Result(*this);
1085 // Get some facts about the LHS and RHS number of bits and words
1086 uint32_t rhsBits = RHS.getActiveBits();
1087 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1088 assert(rhsWords && "Divided by zero???");
1089 uint32_t lhsBits = Result.getActiveBits();
1090 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1092 // Deal with some degenerate cases
1094 return Result; // 0 / X == 0
1095 else if (lhsWords < rhsWords || Result.ult(RHS))
1096 // X / Y with X < Y == 0
1097 memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1098 else if (Result == RHS) {
1100 memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1102 } else if (lhsWords == 1)
1103 // All high words are zero, just use native divide
1104 Result.pVal[0] /= RHS.pVal[0];
1106 // Compute it the hard way ..
1107 APInt X(BitWidth, 0);
1108 APInt Y(BitWidth, 0);
1110 (APINT_BITS_PER_WORD - 1) - ((rhsBits - 1) % APINT_BITS_PER_WORD );
1112 Y = APIntOps::shl(RHS, nshift);
1113 X = APIntOps::shl(Result, nshift);
1116 div((uint32_t*)X.pVal, lhsWords * 2 - 1,
1117 (uint32_t*)(Y.isSingleWord()? &Y.VAL : Y.pVal), rhsWords*2);
1118 memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1119 memcpy(Result.pVal, X.pVal + rhsWords,
1120 (lhsWords - rhsWords) * sizeof(uint64_t));
1125 /// Unsigned remainder operation on APInt.
1126 /// @brief Function for unsigned remainder operation.
1127 APInt APInt::urem(const APInt& RHS) const {
1128 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1129 if (isSingleWord()) {
1130 assert(RHS.VAL != 0 && "Remainder by zero?");
1131 return APInt(BitWidth, VAL % RHS.VAL);
1134 // Make a temporary to hold the result
1135 APInt Result(*this);
1137 // Get some facts about the RHS
1138 uint32_t rhsBits = RHS.getActiveBits();
1139 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1140 assert(rhsWords && "Performing remainder operation by zero ???");
1142 // Get some facts about the LHS
1143 uint32_t lhsBits = Result.getActiveBits();
1144 uint32_t lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
1146 // Check the degenerate cases
1149 memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1150 else if (lhsWords < rhsWords || Result.ult(RHS))
1151 // X % Y == X iff X < Y
1153 else if (Result == RHS)
1155 memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1156 else if (lhsWords == 1)
1157 // All high words are zero, just use native remainder
1158 Result.pVal[0] %= RHS.pVal[0];
1160 // Do it the hard way
1161 APInt X((lhsWords+1)*APINT_BITS_PER_WORD, 0);
1162 APInt Y(rhsWords*APINT_BITS_PER_WORD, 0);
1164 (APINT_BITS_PER_WORD - 1) - (rhsBits - 1) % APINT_BITS_PER_WORD;
1166 APIntOps::shl(Y, nshift);
1167 APIntOps::shl(X, nshift);
1169 div((uint32_t*)X.pVal, rhsWords*2-1,
1170 (uint32_t*)(Y.isSingleWord()? &Y.VAL : Y.pVal), rhsWords*2);
1171 memset(Result.pVal, 0, Result.getNumWords() * sizeof(uint64_t));
1172 for (uint32_t i = 0; i < rhsWords-1; ++i)
1173 Result.pVal[i] = (X.pVal[i] >> nshift) |
1174 (X.pVal[i+1] << (APINT_BITS_PER_WORD - nshift));
1175 Result.pVal[rhsWords-1] = X.pVal[rhsWords-1] >> nshift;
1180 /// @brief Converts a char array into an integer.
1181 void APInt::fromString(uint32_t numbits, const char *StrStart, uint32_t slen,
1183 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1184 "Radix should be 2, 8, 10, or 16!");
1185 assert(StrStart && "String is null?");
1187 // If the radix is a power of 2, read the input
1188 // from most significant to least significant.
1189 if ((radix & (radix - 1)) == 0) {
1190 uint32_t nextBitPos = 0;
1191 uint32_t bits_per_digit = radix / 8 + 2;
1192 uint64_t resDigit = 0;
1193 BitWidth = slen * bits_per_digit;
1194 if (getNumWords() > 1)
1195 pVal = getMemory(getNumWords());
1196 for (int i = slen - 1; i >= 0; --i) {
1197 uint64_t digit = StrStart[i] - '0';
1198 resDigit |= digit << nextBitPos;
1199 nextBitPos += bits_per_digit;
1200 if (nextBitPos >= APINT_BITS_PER_WORD) {
1201 if (isSingleWord()) {
1205 pVal[size++] = resDigit;
1206 nextBitPos -= APINT_BITS_PER_WORD;
1207 resDigit = digit >> (bits_per_digit - nextBitPos);
1210 if (!isSingleWord() && size <= getNumWords())
1211 pVal[size] = resDigit;
1212 } else { // General case. The radix is not a power of 2.
1213 // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
1214 // and its digits number is 20.
1215 const uint32_t chars_per_word = 20;
1216 if (slen < chars_per_word ||
1217 (slen == chars_per_word && // In case the value <= 2^64 - 1
1218 strcmp(StrStart, "18446744073709551615") <= 0)) {
1219 BitWidth = APINT_BITS_PER_WORD;
1220 VAL = strtoull(StrStart, 0, 10);
1221 } else { // In case the value > 2^64 - 1
1222 BitWidth = (slen / chars_per_word + 1) * APINT_BITS_PER_WORD;
1223 pVal = getClearedMemory(getNumWords());
1224 uint32_t str_pos = 0;
1225 while (str_pos < slen) {
1226 uint32_t chunk = slen - str_pos;
1227 if (chunk > chars_per_word - 1)
1228 chunk = chars_per_word - 1;
1229 uint64_t resDigit = StrStart[str_pos++] - '0';
1230 uint64_t big_base = radix;
1231 while (--chunk > 0) {
1232 resDigit = resDigit * radix + StrStart[str_pos++] - '0';
1240 carry = mul_1(pVal, pVal, size, big_base);
1241 carry += add_1(pVal, pVal, size, resDigit);
1244 if (carry) pVal[size++] = carry;