1 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file implements a class to represent arbitrary precision
12 /// integral constant values and operations on them.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_ADT_APINT_H
17 #define LLVM_ADT_APINT_H
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/MathExtras.h"
27 class FoldingSetNodeID;
32 template <typename T> class SmallVectorImpl;
33 template <typename T> class ArrayRef;
35 // An unsigned host type used as a single part of a multi-part
37 typedef uint64_t integerPart;
39 const unsigned int host_char_bit = 8;
40 const unsigned int integerPartWidth =
41 host_char_bit * static_cast<unsigned int>(sizeof(integerPart));
45 inline APInt operator-(APInt);
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 /// \brief Class for arbitrary precision integers.
53 /// APInt is a functional replacement for common case unsigned integer type like
54 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
55 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
56 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
57 /// and methods to manipulate integer values of any bit-width. It supports both
58 /// the typical integer arithmetic and comparison operations as well as bitwise
61 /// The class has several invariants worth noting:
62 /// * All bit, byte, and word positions are zero-based.
63 /// * Once the bit width is set, it doesn't change except by the Truncate,
64 /// SignExtend, or ZeroExtend operations.
65 /// * All binary operators must be on APInt instances of the same bit width.
66 /// Attempting to use these operators on instances with different bit
67 /// widths will yield an assertion.
68 /// * The value is stored canonically as an unsigned value. For operations
69 /// where it makes a difference, there are both signed and unsigned variants
70 /// of the operation. For example, sdiv and udiv. However, because the bit
71 /// widths must be the same, operations such as Mul and Add produce the same
72 /// results regardless of whether the values are interpreted as signed or
74 /// * In general, the class tries to follow the style of computation that LLVM
75 /// uses in its IR. This simplifies its use for LLVM.
77 class LLVM_NODISCARD APInt {
78 unsigned BitWidth; ///< The number of bits in this APInt.
80 /// This union is used to store the integer value. When the
81 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
83 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
84 uint64_t *pVal; ///< Used to store the >64 bits integer value.
87 /// This enum is used to hold the constants we needed for APInt.
91 static_cast<unsigned int>(sizeof(uint64_t)) * CHAR_BIT,
92 /// Byte size of a word
93 APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t))
96 friend struct DenseMapAPIntKeyInfo;
98 /// \brief Fast internal constructor
100 /// This constructor is used only internally for speed of construction of
101 /// temporaries. It is unsafe for general use so it is not public.
102 APInt(uint64_t *val, unsigned bits) : BitWidth(bits), pVal(val) {}
104 /// \brief Determine if this APInt just has one word to store value.
106 /// \returns true if the number of bits <= 64, false otherwise.
107 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
109 /// \brief Determine which word a bit is in.
111 /// \returns the word position for the specified bit position.
112 static unsigned whichWord(unsigned bitPosition) {
113 return bitPosition / APINT_BITS_PER_WORD;
116 /// \brief Determine which bit in a word a bit is in.
118 /// \returns the bit position in a word for the specified bit position
120 static unsigned whichBit(unsigned bitPosition) {
121 return bitPosition % APINT_BITS_PER_WORD;
124 /// \brief Get a single bit mask.
126 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
127 /// This method generates and returns a uint64_t (word) mask for a single
128 /// bit at a specific bit position. This is used to mask the bit in the
129 /// corresponding word.
130 static uint64_t maskBit(unsigned bitPosition) {
131 return 1ULL << whichBit(bitPosition);
134 /// \brief Clear unused high order bits
136 /// This method is used internally to clear the top "N" bits in the high order
137 /// word that are not used by the APInt. This is needed after the most
138 /// significant word is assigned a value to ensure that those bits are
140 APInt &clearUnusedBits() {
141 // Compute how many bits are used in the final word
142 unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
144 // If all bits are used, we want to leave the value alone. This also
145 // avoids the undefined behavior of >> when the shift is the same size as
146 // the word size (64).
149 // Mask out the high bits.
150 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
154 pVal[getNumWords() - 1] &= mask;
158 /// \brief Get the word corresponding to a bit position
159 /// \returns the corresponding word for the specified bit position.
160 uint64_t getWord(unsigned bitPosition) const {
161 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
164 /// \brief Convert a char array into an APInt
166 /// \param radix 2, 8, 10, 16, or 36
167 /// Converts a string into a number. The string must be non-empty
168 /// and well-formed as a number of the given base. The bit-width
169 /// must be sufficient to hold the result.
171 /// This is used by the constructors that take string arguments.
173 /// StringRef::getAsInteger is superficially similar but (1) does
174 /// not assume that the string is well-formed and (2) grows the
175 /// result to hold the input.
176 void fromString(unsigned numBits, StringRef str, uint8_t radix);
178 /// \brief An internal division function for dividing APInts.
180 /// This is used by the toString method to divide by the radix. It simply
181 /// provides a more convenient form of divide for internal use since KnuthDiv
182 /// has specific constraints on its inputs. If those constraints are not met
183 /// then it provides a simpler form of divide.
184 static void divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
185 unsigned rhsWords, APInt *Quotient, APInt *Remainder);
187 /// out-of-line slow case for inline constructor
188 void initSlowCase(uint64_t val, bool isSigned);
190 /// shared code between two array constructors
191 void initFromArray(ArrayRef<uint64_t> array);
193 /// out-of-line slow case for inline copy constructor
194 void initSlowCase(const APInt &that);
196 /// out-of-line slow case for shl
197 APInt shlSlowCase(unsigned shiftAmt) const;
199 /// out-of-line slow case for operator&
200 APInt AndSlowCase(const APInt &RHS) const;
202 /// out-of-line slow case for operator|
203 APInt OrSlowCase(const APInt &RHS) const;
205 /// out-of-line slow case for operator^
206 APInt XorSlowCase(const APInt &RHS) const;
208 /// out-of-line slow case for operator=
209 APInt &AssignSlowCase(const APInt &RHS);
211 /// out-of-line slow case for operator==
212 bool EqualSlowCase(const APInt &RHS) const;
214 /// out-of-line slow case for operator==
215 bool EqualSlowCase(uint64_t Val) const;
217 /// out-of-line slow case for countLeadingZeros
218 unsigned countLeadingZerosSlowCase() const;
220 /// out-of-line slow case for countTrailingOnes
221 unsigned countTrailingOnesSlowCase() const;
223 /// out-of-line slow case for countPopulation
224 unsigned countPopulationSlowCase() const;
227 /// \name Constructors
230 /// \brief Create a new APInt of numBits width, initialized as val.
232 /// If isSigned is true then val is treated as if it were a signed value
233 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
234 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
235 /// the range of val are zero filled).
237 /// \param numBits the bit width of the constructed APInt
238 /// \param val the initial value of the APInt
239 /// \param isSigned how to treat signedness of val
240 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
241 : BitWidth(numBits), VAL(0) {
242 assert(BitWidth && "bitwidth too small");
246 initSlowCase(val, isSigned);
250 /// \brief Construct an APInt of numBits width, initialized as bigVal[].
252 /// Note that bigVal.size() can be smaller or larger than the corresponding
253 /// bit width but any extraneous bits will be dropped.
255 /// \param numBits the bit width of the constructed APInt
256 /// \param bigVal a sequence of words to form the initial value of the APInt
257 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
259 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
260 /// deprecated because this constructor is prone to ambiguity with the
261 /// APInt(unsigned, uint64_t, bool) constructor.
263 /// If this overload is ever deleted, care should be taken to prevent calls
264 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
266 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
268 /// \brief Construct an APInt from a string representation.
270 /// This constructor interprets the string \p str in the given radix. The
271 /// interpretation stops when the first character that is not suitable for the
272 /// radix is encountered, or the end of the string. Acceptable radix values
273 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
274 /// string to require more bits than numBits.
276 /// \param numBits the bit width of the constructed APInt
277 /// \param str the string to be interpreted
278 /// \param radix the radix to use for the conversion
279 APInt(unsigned numBits, StringRef str, uint8_t radix);
281 /// Simply makes *this a copy of that.
282 /// @brief Copy Constructor.
283 APInt(const APInt &that) : BitWidth(that.BitWidth), VAL(0) {
290 /// \brief Move Constructor.
291 APInt(APInt &&that) : BitWidth(that.BitWidth), VAL(that.VAL) {
295 /// \brief Destructor.
301 /// \brief Default constructor that creates an uninteresting APInt
302 /// representing a 1-bit zero value.
304 /// This is useful for object deserialization (pair this with the static
306 explicit APInt() : BitWidth(1), VAL(0) {}
308 /// \brief Returns whether this instance allocated memory.
309 bool needsCleanup() const { return !isSingleWord(); }
311 /// Used to insert APInt objects, or objects that contain APInt objects, into
313 void Profile(FoldingSetNodeID &id) const;
316 /// \name Value Tests
319 /// \brief Determine sign of this APInt.
321 /// This tests the high bit of this APInt to determine if it is set.
323 /// \returns true if this APInt is negative, false otherwise
324 bool isNegative() const { return (*this)[BitWidth - 1]; }
326 /// \brief Determine if this APInt Value is non-negative (>= 0)
328 /// This tests the high bit of the APInt to determine if it is unset.
329 bool isNonNegative() const { return !isNegative(); }
331 /// \brief Determine if this APInt Value is positive.
333 /// This tests if the value of this APInt is positive (> 0). Note
334 /// that 0 is not a positive value.
336 /// \returns true if this APInt is positive.
337 bool isStrictlyPositive() const { return isNonNegative() && !!*this; }
339 /// \brief Determine if all bits are set
341 /// This checks to see if the value has all bits of the APInt are set or not.
342 bool isAllOnesValue() const {
344 return VAL == ~integerPart(0) >> (APINT_BITS_PER_WORD - BitWidth);
345 return countPopulationSlowCase() == BitWidth;
348 /// \brief Determine if this is the largest unsigned value.
350 /// This checks to see if the value of this APInt is the maximum unsigned
351 /// value for the APInt's bit width.
352 bool isMaxValue() const { return isAllOnesValue(); }
354 /// \brief Determine if this is the largest signed value.
356 /// This checks to see if the value of this APInt is the maximum signed
357 /// value for the APInt's bit width.
358 bool isMaxSignedValue() const {
359 return !isNegative() && countPopulation() == BitWidth - 1;
362 /// \brief Determine if this is the smallest unsigned value.
364 /// This checks to see if the value of this APInt is the minimum unsigned
365 /// value for the APInt's bit width.
366 bool isMinValue() const { return !*this; }
368 /// \brief Determine if this is the smallest signed value.
370 /// This checks to see if the value of this APInt is the minimum signed
371 /// value for the APInt's bit width.
372 bool isMinSignedValue() const {
373 return isNegative() && isPowerOf2();
376 /// \brief Check if this APInt has an N-bits unsigned integer value.
377 bool isIntN(unsigned N) const {
378 assert(N && "N == 0 ???");
379 return getActiveBits() <= N;
382 /// \brief Check if this APInt has an N-bits signed integer value.
383 bool isSignedIntN(unsigned N) const {
384 assert(N && "N == 0 ???");
385 return getMinSignedBits() <= N;
388 /// \brief Check if this APInt's value is a power of two greater than zero.
390 /// \returns true if the argument APInt value is a power of two > 0.
391 bool isPowerOf2() const {
393 return isPowerOf2_64(VAL);
394 return countPopulationSlowCase() == 1;
397 /// \brief Check if the APInt's value is returned by getSignBit.
399 /// \returns true if this is the value returned by getSignBit.
400 bool isSignBit() const { return isMinSignedValue(); }
402 /// \brief Convert APInt to a boolean value.
404 /// This converts the APInt to a boolean value as a test against zero.
405 bool getBoolValue() const { return !!*this; }
407 /// If this value is smaller than the specified limit, return it, otherwise
408 /// return the limit value. This causes the value to saturate to the limit.
409 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
410 return (getActiveBits() > 64 || getZExtValue() > Limit) ? Limit
414 /// \brief Check if the APInt consists of a repeated bit pattern.
416 /// e.g. 0x01010101 satisfies isSplat(8).
417 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
418 /// width without remainder.
419 bool isSplat(unsigned SplatSizeInBits) const;
422 /// \name Value Generators
425 /// \brief Gets maximum unsigned value of APInt for specific bit width.
426 static APInt getMaxValue(unsigned numBits) {
427 return getAllOnesValue(numBits);
430 /// \brief Gets maximum signed value of APInt for a specific bit width.
431 static APInt getSignedMaxValue(unsigned numBits) {
432 APInt API = getAllOnesValue(numBits);
433 API.clearBit(numBits - 1);
437 /// \brief Gets minimum unsigned value of APInt for a specific bit width.
438 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
440 /// \brief Gets minimum signed value of APInt for a specific bit width.
441 static APInt getSignedMinValue(unsigned numBits) {
442 APInt API(numBits, 0);
443 API.setBit(numBits - 1);
447 /// \brief Get the SignBit for a specific bit width.
449 /// This is just a wrapper function of getSignedMinValue(), and it helps code
450 /// readability when we want to get a SignBit.
451 static APInt getSignBit(unsigned BitWidth) {
452 return getSignedMinValue(BitWidth);
455 /// \brief Get the all-ones value.
457 /// \returns the all-ones value for an APInt of the specified bit-width.
458 static APInt getAllOnesValue(unsigned numBits) {
459 return APInt(numBits, UINT64_MAX, true);
462 /// \brief Get the '0' value.
464 /// \returns the '0' value for an APInt of the specified bit-width.
465 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
467 /// \brief Compute an APInt containing numBits highbits from this APInt.
469 /// Get an APInt with the same BitWidth as this APInt, just zero mask
470 /// the low bits and right shift to the least significant bit.
472 /// \returns the high "numBits" bits of this APInt.
473 APInt getHiBits(unsigned numBits) const;
475 /// \brief Compute an APInt containing numBits lowbits from this APInt.
477 /// Get an APInt with the same BitWidth as this APInt, just zero mask
480 /// \returns the low "numBits" bits of this APInt.
481 APInt getLoBits(unsigned numBits) const;
483 /// \brief Return an APInt with exactly one bit set in the result.
484 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
485 APInt Res(numBits, 0);
490 /// \brief Get a value with a block of bits set.
492 /// Constructs an APInt value that has a contiguous range of bits set. The
493 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
494 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
495 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
496 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
498 /// \param numBits the intended bit width of the result
499 /// \param loBit the index of the lowest bit set.
500 /// \param hiBit the index of the highest bit set.
502 /// \returns An APInt value with the requested bits set.
503 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
504 assert(hiBit <= numBits && "hiBit out of range");
505 assert(loBit < numBits && "loBit out of range");
507 return getLowBitsSet(numBits, hiBit) |
508 getHighBitsSet(numBits, numBits - loBit);
509 return getLowBitsSet(numBits, hiBit - loBit).shl(loBit);
512 /// \brief Get a value with high bits set
514 /// Constructs an APInt value that has the top hiBitsSet bits set.
516 /// \param numBits the bitwidth of the result
517 /// \param hiBitsSet the number of high-order bits set in the result.
518 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
519 assert(hiBitsSet <= numBits && "Too many bits to set!");
520 // Handle a degenerate case, to avoid shifting by word size
522 return APInt(numBits, 0);
523 unsigned shiftAmt = numBits - hiBitsSet;
524 // For small values, return quickly
525 if (numBits <= APINT_BITS_PER_WORD)
526 return APInt(numBits, ~0ULL << shiftAmt);
527 return getAllOnesValue(numBits).shl(shiftAmt);
530 /// \brief Get a value with low bits set
532 /// Constructs an APInt value that has the bottom loBitsSet bits set.
534 /// \param numBits the bitwidth of the result
535 /// \param loBitsSet the number of low-order bits set in the result.
536 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
537 assert(loBitsSet <= numBits && "Too many bits to set!");
538 // Handle a degenerate case, to avoid shifting by word size
540 return APInt(numBits, 0);
541 if (loBitsSet == APINT_BITS_PER_WORD)
542 return APInt(numBits, UINT64_MAX);
543 // For small values, return quickly.
544 if (loBitsSet <= APINT_BITS_PER_WORD)
545 return APInt(numBits, UINT64_MAX >> (APINT_BITS_PER_WORD - loBitsSet));
546 return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
549 /// \brief Return a value containing V broadcasted over NewLen bits.
550 static APInt getSplat(unsigned NewLen, const APInt &V) {
551 assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
553 APInt Val = V.zextOrSelf(NewLen);
554 for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
560 /// \brief Determine if two APInts have the same value, after zero-extending
561 /// one of them (if needed!) to ensure that the bit-widths match.
562 static bool isSameValue(const APInt &I1, const APInt &I2) {
563 if (I1.getBitWidth() == I2.getBitWidth())
566 if (I1.getBitWidth() > I2.getBitWidth())
567 return I1 == I2.zext(I1.getBitWidth());
569 return I1.zext(I2.getBitWidth()) == I2;
572 /// \brief Overload to compute a hash_code for an APInt value.
573 friend hash_code hash_value(const APInt &Arg);
575 /// This function returns a pointer to the internal storage of the APInt.
576 /// This is useful for writing out the APInt in binary form without any
578 const uint64_t *getRawData() const {
585 /// \name Unary Operators
588 /// \brief Postfix increment operator.
590 /// \returns a new APInt value representing *this incremented by one
591 const APInt operator++(int) {
597 /// \brief Prefix increment operator.
599 /// \returns *this incremented by one
602 /// \brief Postfix decrement operator.
604 /// \returns a new APInt representing *this decremented by one.
605 const APInt operator--(int) {
611 /// \brief Prefix decrement operator.
613 /// \returns *this decremented by one.
616 /// \brief Unary bitwise complement operator.
618 /// Performs a bitwise complement operation on this APInt.
620 /// \returns an APInt that is the bitwise complement of *this
621 APInt operator~() const {
623 Result.flipAllBits();
627 /// \brief Logical negation operator.
629 /// Performs logical negation operation on this APInt.
631 /// \returns true if *this is zero, false otherwise.
632 bool operator!() const {
636 for (unsigned i = 0; i != getNumWords(); ++i)
643 /// \name Assignment Operators
646 /// \brief Copy assignment operator.
648 /// \returns *this after assignment of RHS.
649 APInt &operator=(const APInt &RHS) {
650 // If the bitwidths are the same, we can avoid mucking with memory
651 if (isSingleWord() && RHS.isSingleWord()) {
653 BitWidth = RHS.BitWidth;
654 return clearUnusedBits();
657 return AssignSlowCase(RHS);
660 /// @brief Move assignment operator.
661 APInt &operator=(APInt &&that) {
662 if (!isSingleWord()) {
663 // The MSVC STL shipped in 2013 requires that self move assignment be a
664 // no-op. Otherwise algorithms like stable_sort will produce answers
665 // where half of the output is left in a moved-from state.
671 // Use memcpy so that type based alias analysis sees both VAL and pVal
673 memcpy(&VAL, &that.VAL, sizeof(uint64_t));
675 // If 'this == &that', avoid zeroing our own bitwidth by storing to 'that'
677 unsigned ThatBitWidth = that.BitWidth;
679 BitWidth = ThatBitWidth;
684 /// \brief Assignment operator.
686 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
687 /// the bit width, the excess bits are truncated. If the bit width is larger
688 /// than 64, the value is zero filled in the unspecified high order bits.
690 /// \returns *this after assignment of RHS value.
691 APInt &operator=(uint64_t RHS);
693 /// \brief Bitwise AND assignment operator.
695 /// Performs a bitwise AND operation on this APInt and RHS. The result is
696 /// assigned to *this.
698 /// \returns *this after ANDing with RHS.
699 APInt &operator&=(const APInt &RHS);
701 /// \brief Bitwise OR assignment operator.
703 /// Performs a bitwise OR operation on this APInt and RHS. The result is
706 /// \returns *this after ORing with RHS.
707 APInt &operator|=(const APInt &RHS);
709 /// \brief Bitwise OR assignment operator.
711 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
712 /// logically zero-extended or truncated to match the bit-width of
714 APInt &operator|=(uint64_t RHS) {
715 if (isSingleWord()) {
724 /// \brief Bitwise XOR assignment operator.
726 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
727 /// assigned to *this.
729 /// \returns *this after XORing with RHS.
730 APInt &operator^=(const APInt &RHS);
732 /// \brief Multiplication assignment operator.
734 /// Multiplies this APInt by RHS and assigns the result to *this.
737 APInt &operator*=(const APInt &RHS);
739 /// \brief Addition assignment operator.
741 /// Adds RHS to *this and assigns the result to *this.
744 APInt &operator+=(const APInt &RHS);
745 APInt &operator+=(uint64_t RHS);
747 /// \brief Subtraction assignment operator.
749 /// Subtracts RHS from *this and assigns the result to *this.
752 APInt &operator-=(const APInt &RHS);
753 APInt &operator-=(uint64_t RHS);
755 /// \brief Left-shift assignment function.
757 /// Shifts *this left by shiftAmt and assigns the result to *this.
759 /// \returns *this after shifting left by shiftAmt
760 APInt &operator<<=(unsigned shiftAmt) {
761 *this = shl(shiftAmt);
766 /// \name Binary Operators
769 /// \brief Bitwise AND operator.
771 /// Performs a bitwise AND operation on *this and RHS.
773 /// \returns An APInt value representing the bitwise AND of *this and RHS.
774 APInt operator&(const APInt &RHS) const {
775 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
777 return APInt(getBitWidth(), VAL & RHS.VAL);
778 return AndSlowCase(RHS);
780 APInt And(const APInt &RHS) const { return this->operator&(RHS); }
782 /// \brief Bitwise OR operator.
784 /// Performs a bitwise OR operation on *this and RHS.
786 /// \returns An APInt value representing the bitwise OR of *this and RHS.
787 APInt operator|(const APInt &RHS) const {
788 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
790 return APInt(getBitWidth(), VAL | RHS.VAL);
791 return OrSlowCase(RHS);
794 /// \brief Bitwise OR function.
796 /// Performs a bitwise or on *this and RHS. This is implemented by simply
797 /// calling operator|.
799 /// \returns An APInt value representing the bitwise OR of *this and RHS.
800 APInt Or(const APInt &RHS) const { return this->operator|(RHS); }
802 /// \brief Bitwise XOR operator.
804 /// Performs a bitwise XOR operation on *this and RHS.
806 /// \returns An APInt value representing the bitwise XOR of *this and RHS.
807 APInt operator^(const APInt &RHS) const {
808 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
810 return APInt(BitWidth, VAL ^ RHS.VAL);
811 return XorSlowCase(RHS);
814 /// \brief Bitwise XOR function.
816 /// Performs a bitwise XOR operation on *this and RHS. This is implemented
817 /// through the usage of operator^.
819 /// \returns An APInt value representing the bitwise XOR of *this and RHS.
820 APInt Xor(const APInt &RHS) const { return this->operator^(RHS); }
822 /// \brief Multiplication operator.
824 /// Multiplies this APInt by RHS and returns the result.
825 APInt operator*(const APInt &RHS) const;
827 /// \brief Left logical shift operator.
829 /// Shifts this APInt left by \p Bits and returns the result.
830 APInt operator<<(unsigned Bits) const { return shl(Bits); }
832 /// \brief Left logical shift operator.
834 /// Shifts this APInt left by \p Bits and returns the result.
835 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
837 /// \brief Arithmetic right-shift function.
839 /// Arithmetic right-shift this APInt by shiftAmt.
840 APInt ashr(unsigned shiftAmt) const;
842 /// \brief Logical right-shift function.
844 /// Logical right-shift this APInt by shiftAmt.
845 APInt lshr(unsigned shiftAmt) const;
847 /// \brief Left-shift function.
849 /// Left-shift this APInt by shiftAmt.
850 APInt shl(unsigned shiftAmt) const {
851 assert(shiftAmt <= BitWidth && "Invalid shift amount");
852 if (isSingleWord()) {
853 if (shiftAmt >= BitWidth)
854 return APInt(BitWidth, 0); // avoid undefined shift results
855 return APInt(BitWidth, VAL << shiftAmt);
857 return shlSlowCase(shiftAmt);
860 /// \brief Rotate left by rotateAmt.
861 APInt rotl(unsigned rotateAmt) const;
863 /// \brief Rotate right by rotateAmt.
864 APInt rotr(unsigned rotateAmt) const;
866 /// \brief Arithmetic right-shift function.
868 /// Arithmetic right-shift this APInt by shiftAmt.
869 APInt ashr(const APInt &shiftAmt) const;
871 /// \brief Logical right-shift function.
873 /// Logical right-shift this APInt by shiftAmt.
874 APInt lshr(const APInt &shiftAmt) const;
876 /// \brief Left-shift function.
878 /// Left-shift this APInt by shiftAmt.
879 APInt shl(const APInt &shiftAmt) const;
881 /// \brief Rotate left by rotateAmt.
882 APInt rotl(const APInt &rotateAmt) const;
884 /// \brief Rotate right by rotateAmt.
885 APInt rotr(const APInt &rotateAmt) const;
887 /// \brief Unsigned division operation.
889 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
890 /// RHS are treated as unsigned quantities for purposes of this division.
892 /// \returns a new APInt value containing the division result
893 APInt udiv(const APInt &RHS) const;
895 /// \brief Signed division function for APInt.
897 /// Signed divide this APInt by APInt RHS.
898 APInt sdiv(const APInt &RHS) const;
900 /// \brief Unsigned remainder operation.
902 /// Perform an unsigned remainder operation on this APInt with RHS being the
903 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
904 /// of this operation. Note that this is a true remainder operation and not a
905 /// modulo operation because the sign follows the sign of the dividend which
908 /// \returns a new APInt value containing the remainder result
909 APInt urem(const APInt &RHS) const;
911 /// \brief Function for signed remainder operation.
913 /// Signed remainder operation on APInt.
914 APInt srem(const APInt &RHS) const;
916 /// \brief Dual division/remainder interface.
918 /// Sometimes it is convenient to divide two APInt values and obtain both the
919 /// quotient and remainder. This function does both operations in the same
920 /// computation making it a little more efficient. The pair of input arguments
921 /// may overlap with the pair of output arguments. It is safe to call
922 /// udivrem(X, Y, X, Y), for example.
923 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
926 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
929 // Operations that return overflow indicators.
930 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
931 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
932 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
933 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
934 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
935 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
936 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
937 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
938 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
940 /// \brief Array-indexing support.
942 /// \returns the bit value at bitPosition
943 bool operator[](unsigned bitPosition) const {
944 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
945 return (maskBit(bitPosition) &
946 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) !=
951 /// \name Comparison Operators
954 /// \brief Equality operator.
956 /// Compares this APInt with RHS for the validity of the equality
958 bool operator==(const APInt &RHS) const {
959 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
961 return VAL == RHS.VAL;
962 return EqualSlowCase(RHS);
965 /// \brief Equality operator.
967 /// Compares this APInt with a uint64_t for the validity of the equality
970 /// \returns true if *this == Val
971 bool operator==(uint64_t Val) const {
974 return EqualSlowCase(Val);
977 /// \brief Equality comparison.
979 /// Compares this APInt with RHS for the validity of the equality
982 /// \returns true if *this == Val
983 bool eq(const APInt &RHS) const { return (*this) == RHS; }
985 /// \brief Inequality operator.
987 /// Compares this APInt with RHS for the validity of the inequality
990 /// \returns true if *this != Val
991 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
993 /// \brief Inequality operator.
995 /// Compares this APInt with a uint64_t for the validity of the inequality
998 /// \returns true if *this != Val
999 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1001 /// \brief Inequality comparison
1003 /// Compares this APInt with RHS for the validity of the inequality
1006 /// \returns true if *this != Val
1007 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1009 /// \brief Unsigned less than comparison
1011 /// Regards both *this and RHS as unsigned quantities and compares them for
1012 /// the validity of the less-than relationship.
1014 /// \returns true if *this < RHS when both are considered unsigned.
1015 bool ult(const APInt &RHS) const;
1017 /// \brief Unsigned less than comparison
1019 /// Regards both *this as an unsigned quantity and compares it with RHS for
1020 /// the validity of the less-than relationship.
1022 /// \returns true if *this < RHS when considered unsigned.
1023 bool ult(uint64_t RHS) const {
1024 return getActiveBits() > 64 ? false : getZExtValue() < RHS;
1027 /// \brief Signed less than comparison
1029 /// Regards both *this and RHS as signed quantities and compares them for
1030 /// validity of the less-than relationship.
1032 /// \returns true if *this < RHS when both are considered signed.
1033 bool slt(const APInt &RHS) const;
1035 /// \brief Signed less than comparison
1037 /// Regards both *this as a signed quantity and compares it with RHS for
1038 /// the validity of the less-than relationship.
1040 /// \returns true if *this < RHS when considered signed.
1041 bool slt(int64_t RHS) const {
1042 return getMinSignedBits() > 64 ? isNegative() : getSExtValue() < RHS;
1045 /// \brief Unsigned less or equal comparison
1047 /// Regards both *this and RHS as unsigned quantities and compares them for
1048 /// validity of the less-or-equal relationship.
1050 /// \returns true if *this <= RHS when both are considered unsigned.
1051 bool ule(const APInt &RHS) const { return ult(RHS) || eq(RHS); }
1053 /// \brief Unsigned less or equal comparison
1055 /// Regards both *this as an unsigned quantity and compares it with RHS for
1056 /// the validity of the less-or-equal relationship.
1058 /// \returns true if *this <= RHS when considered unsigned.
1059 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1061 /// \brief Signed less or equal comparison
1063 /// Regards both *this and RHS as signed quantities and compares them for
1064 /// validity of the less-or-equal relationship.
1066 /// \returns true if *this <= RHS when both are considered signed.
1067 bool sle(const APInt &RHS) const { return slt(RHS) || eq(RHS); }
1069 /// \brief Signed less or equal comparison
1071 /// Regards both *this as a signed quantity and compares it with RHS for the
1072 /// validity of the less-or-equal relationship.
1074 /// \returns true if *this <= RHS when considered signed.
1075 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1077 /// \brief Unsigned greather than comparison
1079 /// Regards both *this and RHS as unsigned quantities and compares them for
1080 /// the validity of the greater-than relationship.
1082 /// \returns true if *this > RHS when both are considered unsigned.
1083 bool ugt(const APInt &RHS) const { return !ult(RHS) && !eq(RHS); }
1085 /// \brief Unsigned greater than comparison
1087 /// Regards both *this as an unsigned quantity and compares it with RHS for
1088 /// the validity of the greater-than relationship.
1090 /// \returns true if *this > RHS when considered unsigned.
1091 bool ugt(uint64_t RHS) const {
1092 return getActiveBits() > 64 ? true : getZExtValue() > RHS;
1095 /// \brief Signed greather than comparison
1097 /// Regards both *this and RHS as signed quantities and compares them for the
1098 /// validity of the greater-than relationship.
1100 /// \returns true if *this > RHS when both are considered signed.
1101 bool sgt(const APInt &RHS) const { return !slt(RHS) && !eq(RHS); }
1103 /// \brief Signed greater than comparison
1105 /// Regards both *this as a signed quantity and compares it with RHS for
1106 /// the validity of the greater-than relationship.
1108 /// \returns true if *this > RHS when considered signed.
1109 bool sgt(int64_t RHS) const {
1110 return getMinSignedBits() > 64 ? !isNegative() : getSExtValue() > RHS;
1113 /// \brief Unsigned greater or equal comparison
1115 /// Regards both *this and RHS as unsigned quantities and compares them for
1116 /// validity of the greater-or-equal relationship.
1118 /// \returns true if *this >= RHS when both are considered unsigned.
1119 bool uge(const APInt &RHS) const { return !ult(RHS); }
1121 /// \brief Unsigned greater or equal comparison
1123 /// Regards both *this as an unsigned quantity and compares it with RHS for
1124 /// the validity of the greater-or-equal relationship.
1126 /// \returns true if *this >= RHS when considered unsigned.
1127 bool uge(uint64_t RHS) const { return !ult(RHS); }
1129 /// \brief Signed greather or equal comparison
1131 /// Regards both *this and RHS as signed quantities and compares them for
1132 /// validity of the greater-or-equal relationship.
1134 /// \returns true if *this >= RHS when both are considered signed.
1135 bool sge(const APInt &RHS) const { return !slt(RHS); }
1137 /// \brief Signed greater or equal comparison
1139 /// Regards both *this as a signed quantity and compares it with RHS for
1140 /// the validity of the greater-or-equal relationship.
1142 /// \returns true if *this >= RHS when considered signed.
1143 bool sge(int64_t RHS) const { return !slt(RHS); }
1145 /// This operation tests if there are any pairs of corresponding bits
1146 /// between this APInt and RHS that are both set.
1147 bool intersects(const APInt &RHS) const { return (*this & RHS) != 0; }
1150 /// \name Resizing Operators
1153 /// \brief Truncate to new width.
1155 /// Truncate the APInt to a specified width. It is an error to specify a width
1156 /// that is greater than or equal to the current width.
1157 APInt trunc(unsigned width) const;
1159 /// \brief Sign extend to a new width.
1161 /// This operation sign extends the APInt to a new width. If the high order
1162 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1163 /// It is an error to specify a width that is less than or equal to the
1165 APInt sext(unsigned width) const;
1167 /// \brief Zero extend to a new width.
1169 /// This operation zero extends the APInt to a new width. The high order bits
1170 /// are filled with 0 bits. It is an error to specify a width that is less
1171 /// than or equal to the current width.
1172 APInt zext(unsigned width) const;
1174 /// \brief Sign extend or truncate to width
1176 /// Make this APInt have the bit width given by \p width. The value is sign
1177 /// extended, truncated, or left alone to make it that width.
1178 APInt sextOrTrunc(unsigned width) const;
1180 /// \brief Zero extend or truncate to width
1182 /// Make this APInt have the bit width given by \p width. The value is zero
1183 /// extended, truncated, or left alone to make it that width.
1184 APInt zextOrTrunc(unsigned width) const;
1186 /// \brief Sign extend or truncate to width
1188 /// Make this APInt have the bit width given by \p width. The value is sign
1189 /// extended, or left alone to make it that width.
1190 APInt sextOrSelf(unsigned width) const;
1192 /// \brief Zero extend or truncate to width
1194 /// Make this APInt have the bit width given by \p width. The value is zero
1195 /// extended, or left alone to make it that width.
1196 APInt zextOrSelf(unsigned width) const;
1199 /// \name Bit Manipulation Operators
1202 /// \brief Set every bit to 1.
1207 // Set all the bits in all the words.
1208 for (unsigned i = 0; i < getNumWords(); ++i)
1209 pVal[i] = UINT64_MAX;
1211 // Clear the unused ones
1215 /// \brief Set a given bit to 1.
1217 /// Set the given bit to 1 whose position is given as "bitPosition".
1218 void setBit(unsigned bitPosition);
1220 /// \brief Set every bit to 0.
1221 void clearAllBits() {
1225 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
1228 /// \brief Set a given bit to 0.
1230 /// Set the given bit to 0 whose position is given as "bitPosition".
1231 void clearBit(unsigned bitPosition);
1233 /// \brief Toggle every bit to its opposite value.
1234 void flipAllBits() {
1238 for (unsigned i = 0; i < getNumWords(); ++i)
1239 pVal[i] ^= UINT64_MAX;
1244 /// \brief Toggles a given bit to its opposite value.
1246 /// Toggle a given bit to its opposite value whose position is given
1247 /// as "bitPosition".
1248 void flipBit(unsigned bitPosition);
1251 /// \name Value Characterization Functions
1254 /// \brief Return the number of bits in the APInt.
1255 unsigned getBitWidth() const { return BitWidth; }
1257 /// \brief Get the number of words.
1259 /// Here one word's bitwidth equals to that of uint64_t.
1261 /// \returns the number of words to hold the integer value of this APInt.
1262 unsigned getNumWords() const { return getNumWords(BitWidth); }
1264 /// \brief Get the number of words.
1266 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1268 /// \returns the number of words to hold the integer value with a given bit
1270 static unsigned getNumWords(unsigned BitWidth) {
1271 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1274 /// \brief Compute the number of active bits in the value
1276 /// This function returns the number of active bits which is defined as the
1277 /// bit width minus the number of leading zeros. This is used in several
1278 /// computations to see how "wide" the value is.
1279 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1281 /// \brief Compute the number of active words in the value of this APInt.
1283 /// This is used in conjunction with getActiveData to extract the raw value of
1285 unsigned getActiveWords() const {
1286 unsigned numActiveBits = getActiveBits();
1287 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1290 /// \brief Get the minimum bit size for this signed APInt
1292 /// Computes the minimum bit width for this APInt while considering it to be a
1293 /// signed (and probably negative) value. If the value is not negative, this
1294 /// function returns the same value as getActiveBits()+1. Otherwise, it
1295 /// returns the smallest bit width that will retain the negative value. For
1296 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1297 /// for -1, this function will always return 1.
1298 unsigned getMinSignedBits() const {
1300 return BitWidth - countLeadingOnes() + 1;
1301 return getActiveBits() + 1;
1304 /// \brief Get zero extended value
1306 /// This method attempts to return the value of this APInt as a zero extended
1307 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1308 /// uint64_t. Otherwise an assertion will result.
1309 uint64_t getZExtValue() const {
1312 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1316 /// \brief Get sign extended value
1318 /// This method attempts to return the value of this APInt as a sign extended
1319 /// int64_t. The bit width must be <= 64 or the value must fit within an
1320 /// int64_t. Otherwise an assertion will result.
1321 int64_t getSExtValue() const {
1323 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
1324 (APINT_BITS_PER_WORD - BitWidth);
1325 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1326 return int64_t(pVal[0]);
1329 /// \brief Get bits required for string value.
1331 /// This method determines how many bits are required to hold the APInt
1332 /// equivalent of the string given by \p str.
1333 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1335 /// \brief The APInt version of the countLeadingZeros functions in
1338 /// It counts the number of zeros from the most significant bit to the first
1341 /// \returns BitWidth if the value is zero, otherwise returns the number of
1342 /// zeros from the most significant bit to the first one bits.
1343 unsigned countLeadingZeros() const {
1344 if (isSingleWord()) {
1345 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1346 return llvm::countLeadingZeros(VAL) - unusedBits;
1348 return countLeadingZerosSlowCase();
1351 /// \brief Count the number of leading one bits.
1353 /// This function is an APInt version of the countLeadingOnes
1354 /// functions in MathExtras.h. It counts the number of ones from the most
1355 /// significant bit to the first zero bit.
1357 /// \returns 0 if the high order bit is not set, otherwise returns the number
1358 /// of 1 bits from the most significant to the least
1359 unsigned countLeadingOnes() const;
1361 /// Computes the number of leading bits of this APInt that are equal to its
1363 unsigned getNumSignBits() const {
1364 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1367 /// \brief Count the number of trailing zero bits.
1369 /// This function is an APInt version of the countTrailingZeros
1370 /// functions in MathExtras.h. It counts the number of zeros from the least
1371 /// significant bit to the first set bit.
1373 /// \returns BitWidth if the value is zero, otherwise returns the number of
1374 /// zeros from the least significant bit to the first one bit.
1375 unsigned countTrailingZeros() const;
1377 /// \brief Count the number of trailing one bits.
1379 /// This function is an APInt version of the countTrailingOnes
1380 /// functions in MathExtras.h. It counts the number of ones from the least
1381 /// significant bit to the first zero bit.
1383 /// \returns BitWidth if the value is all ones, otherwise returns the number
1384 /// of ones from the least significant bit to the first zero bit.
1385 unsigned countTrailingOnes() const {
1387 return llvm::countTrailingOnes(VAL);
1388 return countTrailingOnesSlowCase();
1391 /// \brief Count the number of bits set.
1393 /// This function is an APInt version of the countPopulation functions
1394 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1396 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1397 unsigned countPopulation() const {
1399 return llvm::countPopulation(VAL);
1400 return countPopulationSlowCase();
1404 /// \name Conversion Functions
1406 void print(raw_ostream &OS, bool isSigned) const;
1408 /// Converts an APInt to a string and append it to Str. Str is commonly a
1410 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1411 bool formatAsCLiteral = false) const;
1413 /// Considers the APInt to be unsigned and converts it into a string in the
1414 /// radix given. The radix can be 2, 8, 10 16, or 36.
1415 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1416 toString(Str, Radix, false, false);
1419 /// Considers the APInt to be signed and converts it into a string in the
1420 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1421 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1422 toString(Str, Radix, true, false);
1425 /// \brief Return the APInt as a std::string.
1427 /// Note that this is an inefficient method. It is better to pass in a
1428 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1430 std::string toString(unsigned Radix, bool Signed) const;
1432 /// \returns a byte-swapped representation of this APInt Value.
1433 APInt byteSwap() const;
1435 /// \returns the value with the bit representation reversed of this APInt
1437 APInt reverseBits() const;
1439 /// \brief Converts this APInt to a double value.
1440 double roundToDouble(bool isSigned) const;
1442 /// \brief Converts this unsigned APInt to a double value.
1443 double roundToDouble() const { return roundToDouble(false); }
1445 /// \brief Converts this signed APInt to a double value.
1446 double signedRoundToDouble() const { return roundToDouble(true); }
1448 /// \brief Converts APInt bits to a double
1450 /// The conversion does not do a translation from integer to double, it just
1451 /// re-interprets the bits as a double. Note that it is valid to do this on
1452 /// any bit width. Exactly 64 bits will be translated.
1453 double bitsToDouble() const {
1458 T.I = (isSingleWord() ? VAL : pVal[0]);
1462 /// \brief Converts APInt bits to a double
1464 /// The conversion does not do a translation from integer to float, it just
1465 /// re-interprets the bits as a float. Note that it is valid to do this on
1466 /// any bit width. Exactly 32 bits will be translated.
1467 float bitsToFloat() const {
1472 T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1476 /// \brief Converts a double to APInt bits.
1478 /// The conversion does not do a translation from double to integer, it just
1479 /// re-interprets the bits of the double.
1480 static APInt doubleToBits(double V) {
1486 return APInt(sizeof T * CHAR_BIT, T.I);
1489 /// \brief Converts a float to APInt bits.
1491 /// The conversion does not do a translation from float to integer, it just
1492 /// re-interprets the bits of the float.
1493 static APInt floatToBits(float V) {
1499 return APInt(sizeof T * CHAR_BIT, T.I);
1503 /// \name Mathematics Operations
1506 /// \returns the floor log base 2 of this APInt.
1507 unsigned logBase2() const { return BitWidth - 1 - countLeadingZeros(); }
1509 /// \returns the ceil log base 2 of this APInt.
1510 unsigned ceilLogBase2() const {
1513 return BitWidth - temp.countLeadingZeros();
1516 /// \returns the nearest log base 2 of this APInt. Ties round up.
1518 /// NOTE: When we have a BitWidth of 1, we define:
1520 /// log2(0) = UINT32_MAX
1523 /// to get around any mathematical concerns resulting from
1524 /// referencing 2 in a space where 2 does no exist.
1525 unsigned nearestLogBase2() const {
1526 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1527 // get 0. If VAL is 0, we get UINT64_MAX which gets truncated to
1532 // Handle the zero case.
1533 if (!getBoolValue())
1536 // The non-zero case is handled by computing:
1538 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1540 // where x[i] is referring to the value of the ith bit of x.
1541 unsigned lg = logBase2();
1542 return lg + unsigned((*this)[lg - 1]);
1545 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1547 int32_t exactLogBase2() const {
1553 /// \brief Compute the square root
1556 /// \brief Get the absolute value;
1558 /// If *this is < 0 then return -(*this), otherwise *this;
1565 /// \returns the multiplicative inverse for a given modulo.
1566 APInt multiplicativeInverse(const APInt &modulo) const;
1569 /// \name Support for division by constant
1572 /// Calculate the magic number for signed division by a constant.
1576 /// Calculate the magic number for unsigned division by a constant.
1578 mu magicu(unsigned LeadingZeros = 0) const;
1581 /// \name Building-block Operations for APInt and APFloat
1584 // These building block operations operate on a representation of arbitrary
1585 // precision, two's-complement, bignum integer values. They should be
1586 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1587 // generally a pointer to the base of an array of integer parts, representing
1588 // an unsigned bignum, and a count of how many parts there are.
1590 /// Sets the least significant part of a bignum to the input value, and zeroes
1591 /// out higher parts.
1592 static void tcSet(integerPart *, integerPart, unsigned int);
1594 /// Assign one bignum to another.
1595 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1597 /// Returns true if a bignum is zero, false otherwise.
1598 static bool tcIsZero(const integerPart *, unsigned int);
1600 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1601 static int tcExtractBit(const integerPart *, unsigned int bit);
1603 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1604 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1605 /// significant bit of DST. All high bits above srcBITS in DST are
1607 static void tcExtract(integerPart *, unsigned int dstCount,
1608 const integerPart *, unsigned int srcBits,
1609 unsigned int srcLSB);
1611 /// Set the given bit of a bignum. Zero-based.
1612 static void tcSetBit(integerPart *, unsigned int bit);
1614 /// Clear the given bit of a bignum. Zero-based.
1615 static void tcClearBit(integerPart *, unsigned int bit);
1617 /// Returns the bit number of the least or most significant set bit of a
1618 /// number. If the input number has no bits set -1U is returned.
1619 static unsigned int tcLSB(const integerPart *, unsigned int);
1620 static unsigned int tcMSB(const integerPart *parts, unsigned int n);
1622 /// Negate a bignum in-place.
1623 static void tcNegate(integerPart *, unsigned int);
1625 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1626 static integerPart tcAdd(integerPart *, const integerPart *,
1627 integerPart carry, unsigned);
1629 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1630 static integerPart tcSubtract(integerPart *, const integerPart *,
1631 integerPart carry, unsigned);
1633 /// DST += SRC * MULTIPLIER + PART if add is true
1634 /// DST = SRC * MULTIPLIER + PART if add is false
1636 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1637 /// start at the same point, i.e. DST == SRC.
1639 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1640 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1641 /// result, and if all of the omitted higher parts were zero return zero,
1642 /// otherwise overflow occurred and return one.
1643 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1644 integerPart multiplier, integerPart carry,
1645 unsigned int srcParts, unsigned int dstParts,
1648 /// DST = LHS * RHS, where DST has the same width as the operands and is
1649 /// filled with the least significant parts of the result. Returns one if
1650 /// overflow occurred, otherwise zero. DST must be disjoint from both
1652 static int tcMultiply(integerPart *, const integerPart *, const integerPart *,
1655 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1656 /// operands. No overflow occurs. DST must be disjoint from both
1657 /// operands. Returns the number of parts required to hold the result.
1658 static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1659 const integerPart *, unsigned, unsigned);
1661 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1662 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1663 /// REMAINDER to the remainder, return zero. i.e.
1665 /// OLD_LHS = RHS * LHS + REMAINDER
1667 /// SCRATCH is a bignum of the same size as the operands and result for use by
1668 /// the routine; its contents need not be initialized and are destroyed. LHS,
1669 /// REMAINDER and SCRATCH must be distinct.
1670 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1671 integerPart *remainder, integerPart *scratch,
1672 unsigned int parts);
1674 /// Shift a bignum left COUNT bits. Shifted in bits are zero. There are no
1675 /// restrictions on COUNT.
1676 static void tcShiftLeft(integerPart *, unsigned int parts,
1677 unsigned int count);
1679 /// Shift a bignum right COUNT bits. Shifted in bits are zero. There are no
1680 /// restrictions on COUNT.
1681 static void tcShiftRight(integerPart *, unsigned int parts,
1682 unsigned int count);
1684 /// The obvious AND, OR and XOR and complement operations.
1685 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1686 static void tcOr(integerPart *, const integerPart *, unsigned int);
1687 static void tcXor(integerPart *, const integerPart *, unsigned int);
1688 static void tcComplement(integerPart *, unsigned int);
1690 /// Comparison (unsigned) of two bignums.
1691 static int tcCompare(const integerPart *, const integerPart *, unsigned int);
1693 /// Increment a bignum in-place. Return the carry flag.
1694 static integerPart tcIncrement(integerPart *, unsigned int);
1696 /// Decrement a bignum in-place. Return the borrow flag.
1697 static integerPart tcDecrement(integerPart *, unsigned int);
1699 /// Set the least significant BITS and clear the rest.
1700 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1703 /// \brief debug method
1709 /// Magic data for optimising signed division by a constant.
1711 APInt m; ///< magic number
1712 unsigned s; ///< shift amount
1715 /// Magic data for optimising unsigned division by a constant.
1717 APInt m; ///< magic number
1718 bool a; ///< add indicator
1719 unsigned s; ///< shift amount
1722 inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1724 inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1726 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1731 inline APInt operator-(APInt v) {
1737 inline APInt operator+(APInt a, const APInt &b) {
1742 inline APInt operator+(const APInt &a, APInt &&b) {
1744 return std::move(b);
1747 inline APInt operator+(APInt a, uint64_t RHS) {
1752 inline APInt operator+(uint64_t LHS, APInt b) {
1757 inline APInt operator-(APInt a, const APInt &b) {
1762 inline APInt operator-(const APInt &a, APInt &&b) {
1765 return std::move(b);
1768 inline APInt operator-(APInt a, uint64_t RHS) {
1773 inline APInt operator-(uint64_t LHS, APInt b) {
1780 namespace APIntOps {
1782 /// \brief Determine the smaller of two APInts considered to be signed.
1783 inline const APInt &smin(const APInt &A, const APInt &B) {
1784 return A.slt(B) ? A : B;
1787 /// \brief Determine the larger of two APInts considered to be signed.
1788 inline const APInt &smax(const APInt &A, const APInt &B) {
1789 return A.sgt(B) ? A : B;
1792 /// \brief Determine the smaller of two APInts considered to be signed.
1793 inline const APInt &umin(const APInt &A, const APInt &B) {
1794 return A.ult(B) ? A : B;
1797 /// \brief Determine the larger of two APInts considered to be unsigned.
1798 inline const APInt &umax(const APInt &A, const APInt &B) {
1799 return A.ugt(B) ? A : B;
1802 /// \brief Check if the specified APInt has a N-bits unsigned integer value.
1803 inline bool isIntN(unsigned N, const APInt &APIVal) { return APIVal.isIntN(N); }
1805 /// \brief Check if the specified APInt has a N-bits signed integer value.
1806 inline bool isSignedIntN(unsigned N, const APInt &APIVal) {
1807 return APIVal.isSignedIntN(N);
1810 /// \returns true if the argument APInt value is a sequence of ones starting at
1811 /// the least significant bit with the remainder zero.
1812 inline bool isMask(unsigned numBits, const APInt &APIVal) {
1813 return numBits <= APIVal.getBitWidth() &&
1814 APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
1817 /// \returns true if the argument is a non-empty sequence of ones starting at
1818 /// the least significant bit with the remainder zero (32 bit version).
1819 /// Ex. isMask(0x0000FFFFU) == true.
1820 inline bool isMask(const APInt &Value) {
1821 return (Value != 0) && ((Value + 1) & Value) == 0;
1824 /// \brief Return true if the argument APInt value contains a sequence of ones
1825 /// with the remainder zero.
1826 inline bool isShiftedMask(unsigned numBits, const APInt &APIVal) {
1827 return isMask(numBits, (APIVal - APInt(numBits, 1)) | APIVal);
1830 /// \brief Returns a byte-swapped representation of the specified APInt Value.
1831 inline APInt byteSwap(const APInt &APIVal) { return APIVal.byteSwap(); }
1833 /// \brief Returns the floor log base 2 of the specified APInt value.
1834 inline unsigned logBase2(const APInt &APIVal) { return APIVal.logBase2(); }
1836 /// \brief Compute GCD of two APInt values.
1838 /// This function returns the greatest common divisor of the two APInt values
1839 /// using Euclid's algorithm.
1841 /// \returns the greatest common divisor of Val1 and Val2
1842 APInt GreatestCommonDivisor(const APInt &Val1, const APInt &Val2);
1844 /// \brief Converts the given APInt to a double value.
1846 /// Treats the APInt as an unsigned value for conversion purposes.
1847 inline double RoundAPIntToDouble(const APInt &APIVal) {
1848 return APIVal.roundToDouble();
1851 /// \brief Converts the given APInt to a double value.
1853 /// Treats the APInt as a signed value for conversion purposes.
1854 inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
1855 return APIVal.signedRoundToDouble();
1858 /// \brief Converts the given APInt to a float vlalue.
1859 inline float RoundAPIntToFloat(const APInt &APIVal) {
1860 return float(RoundAPIntToDouble(APIVal));
1863 /// \brief Converts the given APInt to a float value.
1865 /// Treast the APInt as a signed value for conversion purposes.
1866 inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
1867 return float(APIVal.signedRoundToDouble());
1870 /// \brief Converts the given double value into a APInt.
1872 /// This function convert a double value to an APInt value.
1873 APInt RoundDoubleToAPInt(double Double, unsigned width);
1875 /// \brief Converts a float value into a APInt.
1877 /// Converts a float value into an APInt value.
1878 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
1879 return RoundDoubleToAPInt(double(Float), width);
1882 /// \brief Arithmetic right-shift function.
1884 /// Arithmetic right-shift the APInt by shiftAmt.
1885 inline APInt ashr(const APInt &LHS, unsigned shiftAmt) {
1886 return LHS.ashr(shiftAmt);
1889 /// \brief Logical right-shift function.
1891 /// Logical right-shift the APInt by shiftAmt.
1892 inline APInt lshr(const APInt &LHS, unsigned shiftAmt) {
1893 return LHS.lshr(shiftAmt);
1896 /// \brief Left-shift function.
1898 /// Left-shift the APInt by shiftAmt.
1899 inline APInt shl(const APInt &LHS, unsigned shiftAmt) {
1900 return LHS.shl(shiftAmt);
1903 /// \brief Signed division function for APInt.
1905 /// Signed divide APInt LHS by APInt RHS.
1906 inline APInt sdiv(const APInt &LHS, const APInt &RHS) { return LHS.sdiv(RHS); }
1908 /// \brief Unsigned division function for APInt.
1910 /// Unsigned divide APInt LHS by APInt RHS.
1911 inline APInt udiv(const APInt &LHS, const APInt &RHS) { return LHS.udiv(RHS); }
1913 /// \brief Function for signed remainder operation.
1915 /// Signed remainder operation on APInt.
1916 inline APInt srem(const APInt &LHS, const APInt &RHS) { return LHS.srem(RHS); }
1918 /// \brief Function for unsigned remainder operation.
1920 /// Unsigned remainder operation on APInt.
1921 inline APInt urem(const APInt &LHS, const APInt &RHS) { return LHS.urem(RHS); }
1923 /// \brief Function for multiplication operation.
1925 /// Performs multiplication on APInt values.
1926 inline APInt mul(const APInt &LHS, const APInt &RHS) { return LHS * RHS; }
1928 /// \brief Function for addition operation.
1930 /// Performs addition on APInt values.
1931 inline APInt add(const APInt &LHS, const APInt &RHS) { return LHS + RHS; }
1933 /// \brief Function for subtraction operation.
1935 /// Performs subtraction on APInt values.
1936 inline APInt sub(const APInt &LHS, const APInt &RHS) { return LHS - RHS; }
1938 /// \brief Bitwise AND function for APInt.
1940 /// Performs bitwise AND operation on APInt LHS and
1942 inline APInt And(const APInt &LHS, const APInt &RHS) { return LHS & RHS; }
1944 /// \brief Bitwise OR function for APInt.
1946 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1947 inline APInt Or(const APInt &LHS, const APInt &RHS) { return LHS | RHS; }
1949 /// \brief Bitwise XOR function for APInt.
1951 /// Performs bitwise XOR operation on APInt.
1952 inline APInt Xor(const APInt &LHS, const APInt &RHS) { return LHS ^ RHS; }
1954 /// \brief Bitwise complement function.
1956 /// Performs a bitwise complement operation on APInt.
1957 inline APInt Not(const APInt &APIVal) { return ~APIVal; }
1959 } // End of APIntOps namespace
1961 // See friend declaration above. This additional declaration is required in
1962 // order to compile LLVM with IBM xlC compiler.
1963 hash_code hash_value(const APInt &Arg);
1964 } // End of llvm namespace