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;
37 inline APInt operator-(APInt);
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 /// \brief Class for arbitrary precision integers.
45 /// APInt is a functional replacement for common case unsigned integer type like
46 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
47 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
48 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
49 /// and methods to manipulate integer values of any bit-width. It supports both
50 /// the typical integer arithmetic and comparison operations as well as bitwise
53 /// The class has several invariants worth noting:
54 /// * All bit, byte, and word positions are zero-based.
55 /// * Once the bit width is set, it doesn't change except by the Truncate,
56 /// SignExtend, or ZeroExtend operations.
57 /// * All binary operators must be on APInt instances of the same bit width.
58 /// Attempting to use these operators on instances with different bit
59 /// widths will yield an assertion.
60 /// * The value is stored canonically as an unsigned value. For operations
61 /// where it makes a difference, there are both signed and unsigned variants
62 /// of the operation. For example, sdiv and udiv. However, because the bit
63 /// widths must be the same, operations such as Mul and Add produce the same
64 /// results regardless of whether the values are interpreted as signed or
66 /// * In general, the class tries to follow the style of computation that LLVM
67 /// uses in its IR. This simplifies its use for LLVM.
69 class LLVM_NODISCARD APInt {
71 typedef uint64_t WordType;
73 /// This enum is used to hold the constants we needed for APInt.
75 /// Byte size of a word.
76 APINT_WORD_SIZE = sizeof(WordType),
78 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT
81 static const WordType WORD_MAX = ~WordType(0);
84 /// This union is used to store the integer value. When the
85 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
87 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
88 uint64_t *pVal; ///< Used to store the >64 bits integer value.
91 unsigned BitWidth; ///< The number of bits in this APInt.
93 friend struct DenseMapAPIntKeyInfo;
97 /// \brief Fast internal constructor
99 /// This constructor is used only internally for speed of construction of
100 /// temporaries. It is unsafe for general use so it is not public.
101 APInt(uint64_t *val, unsigned bits) : pVal(val), BitWidth(bits) {}
103 /// \brief Determine if this APInt just has one word to store value.
105 /// \returns true if the number of bits <= 64, false otherwise.
106 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
108 /// \brief Determine which word a bit is in.
110 /// \returns the word position for the specified bit position.
111 static unsigned whichWord(unsigned bitPosition) {
112 return bitPosition / APINT_BITS_PER_WORD;
115 /// \brief Determine which bit in a word a bit is in.
117 /// \returns the bit position in a word for the specified bit position
119 static unsigned whichBit(unsigned bitPosition) {
120 return bitPosition % APINT_BITS_PER_WORD;
123 /// \brief Get a single bit mask.
125 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
126 /// This method generates and returns a uint64_t (word) mask for a single
127 /// bit at a specific bit position. This is used to mask the bit in the
128 /// corresponding word.
129 static uint64_t maskBit(unsigned bitPosition) {
130 return 1ULL << whichBit(bitPosition);
133 /// \brief Clear unused high order bits
135 /// This method is used internally to clear the top "N" bits in the high order
136 /// word that are not used by the APInt. This is needed after the most
137 /// significant word is assigned a value to ensure that those bits are
139 APInt &clearUnusedBits() {
140 // Compute how many bits are used in the final word
141 unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1;
143 // Mask out the high bits.
144 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - WordBits);
148 pVal[getNumWords() - 1] &= mask;
152 /// \brief Get the word corresponding to a bit position
153 /// \returns the corresponding word for the specified bit position.
154 uint64_t getWord(unsigned bitPosition) const {
155 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
158 /// \brief Convert a char array into an APInt
160 /// \param radix 2, 8, 10, 16, or 36
161 /// Converts a string into a number. The string must be non-empty
162 /// and well-formed as a number of the given base. The bit-width
163 /// must be sufficient to hold the result.
165 /// This is used by the constructors that take string arguments.
167 /// StringRef::getAsInteger is superficially similar but (1) does
168 /// not assume that the string is well-formed and (2) grows the
169 /// result to hold the input.
170 void fromString(unsigned numBits, StringRef str, uint8_t radix);
172 /// \brief An internal division function for dividing APInts.
174 /// This is used by the toString method to divide by the radix. It simply
175 /// provides a more convenient form of divide for internal use since KnuthDiv
176 /// has specific constraints on its inputs. If those constraints are not met
177 /// then it provides a simpler form of divide.
178 static void divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
179 unsigned rhsWords, APInt *Quotient, APInt *Remainder);
181 /// out-of-line slow case for inline constructor
182 void initSlowCase(uint64_t val, bool isSigned);
184 /// shared code between two array constructors
185 void initFromArray(ArrayRef<uint64_t> array);
187 /// out-of-line slow case for inline copy constructor
188 void initSlowCase(const APInt &that);
190 /// out-of-line slow case for shl
191 void shlSlowCase(unsigned ShiftAmt);
193 /// out-of-line slow case for lshr.
194 void lshrSlowCase(unsigned ShiftAmt);
196 /// out-of-line slow case for ashr.
197 void ashrSlowCase(unsigned ShiftAmt);
199 /// out-of-line slow case for operator=
200 void AssignSlowCase(const APInt &RHS);
202 /// out-of-line slow case for operator==
203 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY;
205 /// out-of-line slow case for countLeadingZeros
206 unsigned countLeadingZerosSlowCase() const LLVM_READONLY;
208 /// out-of-line slow case for countTrailingOnes
209 unsigned countTrailingOnesSlowCase() const LLVM_READONLY;
211 /// out-of-line slow case for countPopulation
212 unsigned countPopulationSlowCase() const LLVM_READONLY;
214 /// out-of-line slow case for intersects.
215 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY;
217 /// out-of-line slow case for isSubsetOf.
218 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY;
220 /// out-of-line slow case for setBits.
221 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
223 /// out-of-line slow case for flipAllBits.
224 void flipAllBitsSlowCase();
226 /// out-of-line slow case for operator&=.
227 void AndAssignSlowCase(const APInt& RHS);
229 /// out-of-line slow case for operator|=.
230 void OrAssignSlowCase(const APInt& RHS);
232 /// out-of-line slow case for operator^=.
233 void XorAssignSlowCase(const APInt& RHS);
235 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
236 /// to, or greater than RHS.
237 int compare(const APInt &RHS) const LLVM_READONLY;
239 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
240 /// to, or greater than RHS.
241 int compareSigned(const APInt &RHS) const LLVM_READONLY;
244 /// \name Constructors
247 /// \brief Create a new APInt of numBits width, initialized as val.
249 /// If isSigned is true then val is treated as if it were a signed value
250 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
251 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
252 /// the range of val are zero filled).
254 /// \param numBits the bit width of the constructed APInt
255 /// \param val the initial value of the APInt
256 /// \param isSigned how to treat signedness of val
257 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
258 : BitWidth(numBits) {
259 assert(BitWidth && "bitwidth too small");
260 if (isSingleWord()) {
264 initSlowCase(val, isSigned);
268 /// \brief Construct an APInt of numBits width, initialized as bigVal[].
270 /// Note that bigVal.size() can be smaller or larger than the corresponding
271 /// bit width but any extraneous bits will be dropped.
273 /// \param numBits the bit width of the constructed APInt
274 /// \param bigVal a sequence of words to form the initial value of the APInt
275 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
277 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
278 /// deprecated because this constructor is prone to ambiguity with the
279 /// APInt(unsigned, uint64_t, bool) constructor.
281 /// If this overload is ever deleted, care should be taken to prevent calls
282 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
284 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
286 /// \brief Construct an APInt from a string representation.
288 /// This constructor interprets the string \p str in the given radix. The
289 /// interpretation stops when the first character that is not suitable for the
290 /// radix is encountered, or the end of the string. Acceptable radix values
291 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
292 /// string to require more bits than numBits.
294 /// \param numBits the bit width of the constructed APInt
295 /// \param str the string to be interpreted
296 /// \param radix the radix to use for the conversion
297 APInt(unsigned numBits, StringRef str, uint8_t radix);
299 /// Simply makes *this a copy of that.
300 /// @brief Copy Constructor.
301 APInt(const APInt &that) : BitWidth(that.BitWidth) {
308 /// \brief Move Constructor.
309 APInt(APInt &&that) : VAL(that.VAL), BitWidth(that.BitWidth) {
313 /// \brief Destructor.
319 /// \brief Default constructor that creates an uninteresting APInt
320 /// representing a 1-bit zero value.
322 /// This is useful for object deserialization (pair this with the static
324 explicit APInt() : VAL(0), BitWidth(1) {}
326 /// \brief Returns whether this instance allocated memory.
327 bool needsCleanup() const { return !isSingleWord(); }
329 /// Used to insert APInt objects, or objects that contain APInt objects, into
331 void Profile(FoldingSetNodeID &id) const;
334 /// \name Value Tests
337 /// \brief Determine sign of this APInt.
339 /// This tests the high bit of this APInt to determine if it is set.
341 /// \returns true if this APInt is negative, false otherwise
342 bool isNegative() const { return (*this)[BitWidth - 1]; }
344 /// \brief Determine if this APInt Value is non-negative (>= 0)
346 /// This tests the high bit of the APInt to determine if it is unset.
347 bool isNonNegative() const { return !isNegative(); }
349 /// \brief Determine if sign bit of this APInt is set.
351 /// This tests the high bit of this APInt to determine if it is set.
353 /// \returns true if this APInt has its sign bit set, false otherwise.
354 bool isSignBitSet() const { return (*this)[BitWidth-1]; }
356 /// \brief Determine if sign bit of this APInt is clear.
358 /// This tests the high bit of this APInt to determine if it is clear.
360 /// \returns true if this APInt has its sign bit clear, false otherwise.
361 bool isSignBitClear() const { return !isSignBitSet(); }
363 /// \brief Determine if this APInt Value is positive.
365 /// This tests if the value of this APInt is positive (> 0). Note
366 /// that 0 is not a positive value.
368 /// \returns true if this APInt is positive.
369 bool isStrictlyPositive() const { return isNonNegative() && !!*this; }
371 /// \brief Determine if all bits are set
373 /// This checks to see if the value has all bits of the APInt are set or not.
374 bool isAllOnesValue() const {
376 return VAL == WORD_MAX >> (APINT_BITS_PER_WORD - BitWidth);
377 return countPopulationSlowCase() == BitWidth;
380 /// \brief Determine if this is the largest unsigned value.
382 /// This checks to see if the value of this APInt is the maximum unsigned
383 /// value for the APInt's bit width.
384 bool isMaxValue() const { return isAllOnesValue(); }
386 /// \brief Determine if this is the largest signed value.
388 /// This checks to see if the value of this APInt is the maximum signed
389 /// value for the APInt's bit width.
390 bool isMaxSignedValue() const {
391 return !isNegative() && countPopulation() == BitWidth - 1;
394 /// \brief Determine if this is the smallest unsigned value.
396 /// This checks to see if the value of this APInt is the minimum unsigned
397 /// value for the APInt's bit width.
398 bool isMinValue() const { return !*this; }
400 /// \brief Determine if this is the smallest signed value.
402 /// This checks to see if the value of this APInt is the minimum signed
403 /// value for the APInt's bit width.
404 bool isMinSignedValue() const {
405 return isNegative() && isPowerOf2();
408 /// \brief Check if this APInt has an N-bits unsigned integer value.
409 bool isIntN(unsigned N) const {
410 assert(N && "N == 0 ???");
411 return getActiveBits() <= N;
414 /// \brief Check if this APInt has an N-bits signed integer value.
415 bool isSignedIntN(unsigned N) const {
416 assert(N && "N == 0 ???");
417 return getMinSignedBits() <= N;
420 /// \brief Check if this APInt's value is a power of two greater than zero.
422 /// \returns true if the argument APInt value is a power of two > 0.
423 bool isPowerOf2() const {
425 return isPowerOf2_64(VAL);
426 return countPopulationSlowCase() == 1;
429 /// \brief Check if the APInt's value is returned by getSignMask.
431 /// \returns true if this is the value returned by getSignMask.
432 bool isSignMask() const { return isMinSignedValue(); }
434 /// \brief Convert APInt to a boolean value.
436 /// This converts the APInt to a boolean value as a test against zero.
437 bool getBoolValue() const { return !!*this; }
439 /// If this value is smaller than the specified limit, return it, otherwise
440 /// return the limit value. This causes the value to saturate to the limit.
441 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) const {
442 return ugt(Limit) ? Limit : getZExtValue();
445 /// \brief Check if the APInt consists of a repeated bit pattern.
447 /// e.g. 0x01010101 satisfies isSplat(8).
448 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
449 /// width without remainder.
450 bool isSplat(unsigned SplatSizeInBits) const;
452 /// \returns true if this APInt value is a sequence of \param numBits ones
453 /// starting at the least significant bit with the remainder zero.
454 bool isMask(unsigned numBits) const {
455 assert(numBits != 0 && "numBits must be non-zero");
456 assert(numBits <= BitWidth && "numBits out of range");
458 return VAL == (WORD_MAX >> (APINT_BITS_PER_WORD - numBits));
459 unsigned Ones = countTrailingOnesSlowCase();
460 return (numBits == Ones) &&
461 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
464 /// \returns true if this APInt is a non-empty sequence of ones starting at
465 /// the least significant bit with the remainder zero.
466 /// Ex. isMask(0x0000FFFFU) == true.
467 bool isMask() const {
469 return isMask_64(VAL);
470 unsigned Ones = countTrailingOnesSlowCase();
471 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
474 /// \brief Return true if this APInt value contains a sequence of ones with
475 /// the remainder zero.
476 bool isShiftedMask() const {
478 return isShiftedMask_64(VAL);
479 unsigned Ones = countPopulationSlowCase();
480 unsigned LeadZ = countLeadingZerosSlowCase();
481 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
485 /// \name Value Generators
488 /// \brief Gets maximum unsigned value of APInt for specific bit width.
489 static APInt getMaxValue(unsigned numBits) {
490 return getAllOnesValue(numBits);
493 /// \brief Gets maximum signed value of APInt for a specific bit width.
494 static APInt getSignedMaxValue(unsigned numBits) {
495 APInt API = getAllOnesValue(numBits);
496 API.clearBit(numBits - 1);
500 /// \brief Gets minimum unsigned value of APInt for a specific bit width.
501 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
503 /// \brief Gets minimum signed value of APInt for a specific bit width.
504 static APInt getSignedMinValue(unsigned numBits) {
505 APInt API(numBits, 0);
506 API.setBit(numBits - 1);
510 /// \brief Get the SignMask for a specific bit width.
512 /// This is just a wrapper function of getSignedMinValue(), and it helps code
513 /// readability when we want to get a SignMask.
514 static APInt getSignMask(unsigned BitWidth) {
515 return getSignedMinValue(BitWidth);
518 /// \brief Get the all-ones value.
520 /// \returns the all-ones value for an APInt of the specified bit-width.
521 static APInt getAllOnesValue(unsigned numBits) {
522 return APInt(numBits, WORD_MAX, true);
525 /// \brief Get the '0' value.
527 /// \returns the '0' value for an APInt of the specified bit-width.
528 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
530 /// \brief Compute an APInt containing numBits highbits from this APInt.
532 /// Get an APInt with the same BitWidth as this APInt, just zero mask
533 /// the low bits and right shift to the least significant bit.
535 /// \returns the high "numBits" bits of this APInt.
536 APInt getHiBits(unsigned numBits) const;
538 /// \brief Compute an APInt containing numBits lowbits from this APInt.
540 /// Get an APInt with the same BitWidth as this APInt, just zero mask
543 /// \returns the low "numBits" bits of this APInt.
544 APInt getLoBits(unsigned numBits) const;
546 /// \brief Return an APInt with exactly one bit set in the result.
547 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
548 APInt Res(numBits, 0);
553 /// \brief Get a value with a block of bits set.
555 /// Constructs an APInt value that has a contiguous range of bits set. The
556 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
557 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
558 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
559 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
561 /// \param numBits the intended bit width of the result
562 /// \param loBit the index of the lowest bit set.
563 /// \param hiBit the index of the highest bit set.
565 /// \returns An APInt value with the requested bits set.
566 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
567 APInt Res(numBits, 0);
568 Res.setBits(loBit, hiBit);
572 /// \brief Get a value with upper bits starting at loBit set.
574 /// Constructs an APInt value that has a contiguous range of bits set. The
575 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
576 /// bits will be zero. For example, with parameters(32, 12) you would get
579 /// \param numBits the intended bit width of the result
580 /// \param loBit the index of the lowest bit to set.
582 /// \returns An APInt value with the requested bits set.
583 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
584 APInt Res(numBits, 0);
585 Res.setBitsFrom(loBit);
589 /// \brief Get a value with high bits set
591 /// Constructs an APInt value that has the top hiBitsSet bits set.
593 /// \param numBits the bitwidth of the result
594 /// \param hiBitsSet the number of high-order bits set in the result.
595 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
596 APInt Res(numBits, 0);
597 Res.setHighBits(hiBitsSet);
601 /// \brief Get a value with low bits set
603 /// Constructs an APInt value that has the bottom loBitsSet bits set.
605 /// \param numBits the bitwidth of the result
606 /// \param loBitsSet the number of low-order bits set in the result.
607 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
608 APInt Res(numBits, 0);
609 Res.setLowBits(loBitsSet);
613 /// \brief Return a value containing V broadcasted over NewLen bits.
614 static APInt getSplat(unsigned NewLen, const APInt &V) {
615 assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
617 APInt Val = V.zextOrSelf(NewLen);
618 for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
624 /// \brief Determine if two APInts have the same value, after zero-extending
625 /// one of them (if needed!) to ensure that the bit-widths match.
626 static bool isSameValue(const APInt &I1, const APInt &I2) {
627 if (I1.getBitWidth() == I2.getBitWidth())
630 if (I1.getBitWidth() > I2.getBitWidth())
631 return I1 == I2.zext(I1.getBitWidth());
633 return I1.zext(I2.getBitWidth()) == I2;
636 /// \brief Overload to compute a hash_code for an APInt value.
637 friend hash_code hash_value(const APInt &Arg);
639 /// This function returns a pointer to the internal storage of the APInt.
640 /// This is useful for writing out the APInt in binary form without any
642 const uint64_t *getRawData() const {
649 /// \name Unary Operators
652 /// \brief Postfix increment operator.
654 /// Increments *this by 1.
656 /// \returns a new APInt value representing the original value of *this.
657 const APInt operator++(int) {
663 /// \brief Prefix increment operator.
665 /// \returns *this incremented by one
668 /// \brief Postfix decrement operator.
670 /// Decrements *this by 1.
672 /// \returns a new APInt value representing the original value of *this.
673 const APInt operator--(int) {
679 /// \brief Prefix decrement operator.
681 /// \returns *this decremented by one.
684 /// \brief Logical negation operator.
686 /// Performs logical negation operation on this APInt.
688 /// \returns true if *this is zero, false otherwise.
689 bool operator!() const {
694 /// \name Assignment Operators
697 /// \brief Copy assignment operator.
699 /// \returns *this after assignment of RHS.
700 APInt &operator=(const APInt &RHS) {
701 // If the bitwidths are the same, we can avoid mucking with memory
702 if (isSingleWord() && RHS.isSingleWord()) {
704 BitWidth = RHS.BitWidth;
705 return clearUnusedBits();
712 /// @brief Move assignment operator.
713 APInt &operator=(APInt &&that) {
714 assert(this != &that && "Self-move not supported");
718 // Use memcpy so that type based alias analysis sees both VAL and pVal
720 memcpy(&VAL, &that.VAL, sizeof(uint64_t));
722 BitWidth = that.BitWidth;
728 /// \brief Assignment operator.
730 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
731 /// the bit width, the excess bits are truncated. If the bit width is larger
732 /// than 64, the value is zero filled in the unspecified high order bits.
734 /// \returns *this after assignment of RHS value.
735 APInt &operator=(uint64_t RHS) {
736 if (isSingleWord()) {
741 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
746 /// \brief Bitwise AND assignment operator.
748 /// Performs a bitwise AND operation on this APInt and RHS. The result is
749 /// assigned to *this.
751 /// \returns *this after ANDing with RHS.
752 APInt &operator&=(const APInt &RHS) {
753 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
757 AndAssignSlowCase(RHS);
761 /// \brief Bitwise AND assignment operator.
763 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
764 /// logically zero-extended or truncated to match the bit-width of
766 APInt &operator&=(uint64_t RHS) {
767 if (isSingleWord()) {
772 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
776 /// \brief Bitwise OR assignment operator.
778 /// Performs a bitwise OR operation on this APInt and RHS. The result is
781 /// \returns *this after ORing with RHS.
782 APInt &operator|=(const APInt &RHS) {
783 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
787 OrAssignSlowCase(RHS);
791 /// \brief Bitwise OR assignment operator.
793 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
794 /// logically zero-extended or truncated to match the bit-width of
796 APInt &operator|=(uint64_t RHS) {
797 if (isSingleWord()) {
806 /// \brief Bitwise XOR assignment operator.
808 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
809 /// assigned to *this.
811 /// \returns *this after XORing with RHS.
812 APInt &operator^=(const APInt &RHS) {
813 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
817 XorAssignSlowCase(RHS);
821 /// \brief Bitwise XOR assignment operator.
823 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
824 /// logically zero-extended or truncated to match the bit-width of
826 APInt &operator^=(uint64_t RHS) {
827 if (isSingleWord()) {
836 /// \brief Multiplication assignment operator.
838 /// Multiplies this APInt by RHS and assigns the result to *this.
841 APInt &operator*=(const APInt &RHS);
843 /// \brief Addition assignment operator.
845 /// Adds RHS to *this and assigns the result to *this.
848 APInt &operator+=(const APInt &RHS);
849 APInt &operator+=(uint64_t RHS);
851 /// \brief Subtraction assignment operator.
853 /// Subtracts RHS from *this and assigns the result to *this.
856 APInt &operator-=(const APInt &RHS);
857 APInt &operator-=(uint64_t RHS);
859 /// \brief Left-shift assignment function.
861 /// Shifts *this left by shiftAmt and assigns the result to *this.
863 /// \returns *this after shifting left by ShiftAmt
864 APInt &operator<<=(unsigned ShiftAmt) {
865 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
866 if (isSingleWord()) {
867 if (ShiftAmt == BitWidth)
871 return clearUnusedBits();
873 shlSlowCase(ShiftAmt);
878 /// \name Binary Operators
881 /// \brief Multiplication operator.
883 /// Multiplies this APInt by RHS and returns the result.
884 APInt operator*(const APInt &RHS) const;
886 /// \brief Left logical shift operator.
888 /// Shifts this APInt left by \p Bits and returns the result.
889 APInt operator<<(unsigned Bits) const { return shl(Bits); }
891 /// \brief Left logical shift operator.
893 /// Shifts this APInt left by \p Bits and returns the result.
894 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
896 /// \brief Arithmetic right-shift function.
898 /// Arithmetic right-shift this APInt by shiftAmt.
899 APInt ashr(unsigned ShiftAmt) const {
901 R.ashrInPlace(ShiftAmt);
905 /// Arithmetic right-shift this APInt by ShiftAmt in place.
906 void ashrInPlace(unsigned ShiftAmt) {
907 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
908 if (isSingleWord()) {
909 int64_t SExtVAL = SignExtend64(VAL, BitWidth);
910 if (ShiftAmt == BitWidth)
911 VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
913 VAL = SExtVAL >> ShiftAmt;
917 ashrSlowCase(ShiftAmt);
920 /// \brief Logical right-shift function.
922 /// Logical right-shift this APInt by shiftAmt.
923 APInt lshr(unsigned shiftAmt) const {
925 R.lshrInPlace(shiftAmt);
929 /// Logical right-shift this APInt by ShiftAmt in place.
930 void lshrInPlace(unsigned ShiftAmt) {
931 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
932 if (isSingleWord()) {
933 if (ShiftAmt == BitWidth)
939 lshrSlowCase(ShiftAmt);
942 /// \brief Left-shift function.
944 /// Left-shift this APInt by shiftAmt.
945 APInt shl(unsigned shiftAmt) const {
951 /// \brief Rotate left by rotateAmt.
952 APInt rotl(unsigned rotateAmt) const;
954 /// \brief Rotate right by rotateAmt.
955 APInt rotr(unsigned rotateAmt) const;
957 /// \brief Arithmetic right-shift function.
959 /// Arithmetic right-shift this APInt by shiftAmt.
960 APInt ashr(const APInt &ShiftAmt) const {
962 R.ashrInPlace(ShiftAmt);
966 /// Arithmetic right-shift this APInt by shiftAmt in place.
967 void ashrInPlace(const APInt &shiftAmt);
969 /// \brief Logical right-shift function.
971 /// Logical right-shift this APInt by shiftAmt.
972 APInt lshr(const APInt &ShiftAmt) const {
974 R.lshrInPlace(ShiftAmt);
978 /// Logical right-shift this APInt by ShiftAmt in place.
979 void lshrInPlace(const APInt &ShiftAmt);
981 /// \brief Left-shift function.
983 /// Left-shift this APInt by shiftAmt.
984 APInt shl(const APInt &shiftAmt) const;
986 /// \brief Rotate left by rotateAmt.
987 APInt rotl(const APInt &rotateAmt) const;
989 /// \brief Rotate right by rotateAmt.
990 APInt rotr(const APInt &rotateAmt) const;
992 /// \brief Unsigned division operation.
994 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
995 /// RHS are treated as unsigned quantities for purposes of this division.
997 /// \returns a new APInt value containing the division result
998 APInt udiv(const APInt &RHS) const;
1000 /// \brief Signed division function for APInt.
1002 /// Signed divide this APInt by APInt RHS.
1003 APInt sdiv(const APInt &RHS) const;
1005 /// \brief Unsigned remainder operation.
1007 /// Perform an unsigned remainder operation on this APInt with RHS being the
1008 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
1009 /// of this operation. Note that this is a true remainder operation and not a
1010 /// modulo operation because the sign follows the sign of the dividend which
1013 /// \returns a new APInt value containing the remainder result
1014 APInt urem(const APInt &RHS) const;
1016 /// \brief Function for signed remainder operation.
1018 /// Signed remainder operation on APInt.
1019 APInt srem(const APInt &RHS) const;
1021 /// \brief Dual division/remainder interface.
1023 /// Sometimes it is convenient to divide two APInt values and obtain both the
1024 /// quotient and remainder. This function does both operations in the same
1025 /// computation making it a little more efficient. The pair of input arguments
1026 /// may overlap with the pair of output arguments. It is safe to call
1027 /// udivrem(X, Y, X, Y), for example.
1028 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1031 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1034 // Operations that return overflow indicators.
1035 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
1036 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
1037 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
1038 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
1039 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
1040 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
1041 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
1042 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
1043 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1045 /// \brief Array-indexing support.
1047 /// \returns the bit value at bitPosition
1048 bool operator[](unsigned bitPosition) const {
1049 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
1050 return (maskBit(bitPosition) &
1051 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) !=
1056 /// \name Comparison Operators
1059 /// \brief Equality operator.
1061 /// Compares this APInt with RHS for the validity of the equality
1063 bool operator==(const APInt &RHS) const {
1064 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
1066 return VAL == RHS.VAL;
1067 return EqualSlowCase(RHS);
1070 /// \brief Equality operator.
1072 /// Compares this APInt with a uint64_t for the validity of the equality
1075 /// \returns true if *this == Val
1076 bool operator==(uint64_t Val) const {
1077 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1080 /// \brief Equality comparison.
1082 /// Compares this APInt with RHS for the validity of the equality
1085 /// \returns true if *this == Val
1086 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1088 /// \brief Inequality operator.
1090 /// Compares this APInt with RHS for the validity of the inequality
1093 /// \returns true if *this != Val
1094 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1096 /// \brief Inequality operator.
1098 /// Compares this APInt with a uint64_t for the validity of the inequality
1101 /// \returns true if *this != Val
1102 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1104 /// \brief Inequality comparison
1106 /// Compares this APInt with RHS for the validity of the inequality
1109 /// \returns true if *this != Val
1110 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1112 /// \brief Unsigned less than comparison
1114 /// Regards both *this and RHS as unsigned quantities and compares them for
1115 /// the validity of the less-than relationship.
1117 /// \returns true if *this < RHS when both are considered unsigned.
1118 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1120 /// \brief Unsigned less than comparison
1122 /// Regards both *this as an unsigned quantity and compares it with RHS for
1123 /// the validity of the less-than relationship.
1125 /// \returns true if *this < RHS when considered unsigned.
1126 bool ult(uint64_t RHS) const {
1127 // Only need to check active bits if not a single word.
1128 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1131 /// \brief Signed less than comparison
1133 /// Regards both *this and RHS as signed quantities and compares them for
1134 /// validity of the less-than relationship.
1136 /// \returns true if *this < RHS when both are considered signed.
1137 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1139 /// \brief Signed less than comparison
1141 /// Regards both *this as a signed quantity and compares it with RHS for
1142 /// the validity of the less-than relationship.
1144 /// \returns true if *this < RHS when considered signed.
1145 bool slt(int64_t RHS) const {
1146 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1147 : getSExtValue() < RHS;
1150 /// \brief Unsigned less or equal comparison
1152 /// Regards both *this and RHS as unsigned quantities and compares them for
1153 /// validity of the less-or-equal relationship.
1155 /// \returns true if *this <= RHS when both are considered unsigned.
1156 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1158 /// \brief Unsigned less or equal comparison
1160 /// Regards both *this as an unsigned quantity and compares it with RHS for
1161 /// the validity of the less-or-equal relationship.
1163 /// \returns true if *this <= RHS when considered unsigned.
1164 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1166 /// \brief Signed less or equal comparison
1168 /// Regards both *this and RHS as signed quantities and compares them for
1169 /// validity of the less-or-equal relationship.
1171 /// \returns true if *this <= RHS when both are considered signed.
1172 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1174 /// \brief Signed less or equal comparison
1176 /// Regards both *this as a signed quantity and compares it with RHS for the
1177 /// validity of the less-or-equal relationship.
1179 /// \returns true if *this <= RHS when considered signed.
1180 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1182 /// \brief Unsigned greather than comparison
1184 /// Regards both *this and RHS as unsigned quantities and compares them for
1185 /// the validity of the greater-than relationship.
1187 /// \returns true if *this > RHS when both are considered unsigned.
1188 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1190 /// \brief Unsigned greater than comparison
1192 /// Regards both *this as an unsigned quantity and compares it with RHS for
1193 /// the validity of the greater-than relationship.
1195 /// \returns true if *this > RHS when considered unsigned.
1196 bool ugt(uint64_t RHS) const {
1197 // Only need to check active bits if not a single word.
1198 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1201 /// \brief Signed greather than comparison
1203 /// Regards both *this and RHS as signed quantities and compares them for the
1204 /// validity of the greater-than relationship.
1206 /// \returns true if *this > RHS when both are considered signed.
1207 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1209 /// \brief Signed greater than comparison
1211 /// Regards both *this as a signed quantity and compares it with RHS for
1212 /// the validity of the greater-than relationship.
1214 /// \returns true if *this > RHS when considered signed.
1215 bool sgt(int64_t RHS) const {
1216 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1217 : getSExtValue() > RHS;
1220 /// \brief Unsigned greater or equal comparison
1222 /// Regards both *this and RHS as unsigned quantities and compares them for
1223 /// validity of the greater-or-equal relationship.
1225 /// \returns true if *this >= RHS when both are considered unsigned.
1226 bool uge(const APInt &RHS) const { return !ult(RHS); }
1228 /// \brief Unsigned greater or equal comparison
1230 /// Regards both *this as an unsigned quantity and compares it with RHS for
1231 /// the validity of the greater-or-equal relationship.
1233 /// \returns true if *this >= RHS when considered unsigned.
1234 bool uge(uint64_t RHS) const { return !ult(RHS); }
1236 /// \brief Signed greather or equal comparison
1238 /// Regards both *this and RHS as signed quantities and compares them for
1239 /// validity of the greater-or-equal relationship.
1241 /// \returns true if *this >= RHS when both are considered signed.
1242 bool sge(const APInt &RHS) const { return !slt(RHS); }
1244 /// \brief Signed greater or equal comparison
1246 /// Regards both *this as a signed quantity and compares it with RHS for
1247 /// the validity of the greater-or-equal relationship.
1249 /// \returns true if *this >= RHS when considered signed.
1250 bool sge(int64_t RHS) const { return !slt(RHS); }
1252 /// This operation tests if there are any pairs of corresponding bits
1253 /// between this APInt and RHS that are both set.
1254 bool intersects(const APInt &RHS) const {
1255 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1257 return (VAL & RHS.VAL) != 0;
1258 return intersectsSlowCase(RHS);
1261 /// This operation checks that all bits set in this APInt are also set in RHS.
1262 bool isSubsetOf(const APInt &RHS) const {
1263 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1265 return (VAL & ~RHS.VAL) == 0;
1266 return isSubsetOfSlowCase(RHS);
1270 /// \name Resizing Operators
1273 /// \brief Truncate to new width.
1275 /// Truncate the APInt to a specified width. It is an error to specify a width
1276 /// that is greater than or equal to the current width.
1277 APInt trunc(unsigned width) const;
1279 /// \brief Sign extend to a new width.
1281 /// This operation sign extends the APInt to a new width. If the high order
1282 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1283 /// It is an error to specify a width that is less than or equal to the
1285 APInt sext(unsigned width) const;
1287 /// \brief Zero extend to a new width.
1289 /// This operation zero extends the APInt to a new width. The high order bits
1290 /// are filled with 0 bits. It is an error to specify a width that is less
1291 /// than or equal to the current width.
1292 APInt zext(unsigned width) const;
1294 /// \brief Sign extend or truncate to width
1296 /// Make this APInt have the bit width given by \p width. The value is sign
1297 /// extended, truncated, or left alone to make it that width.
1298 APInt sextOrTrunc(unsigned width) const;
1300 /// \brief Zero extend or truncate to width
1302 /// Make this APInt have the bit width given by \p width. The value is zero
1303 /// extended, truncated, or left alone to make it that width.
1304 APInt zextOrTrunc(unsigned width) const;
1306 /// \brief Sign extend or truncate to width
1308 /// Make this APInt have the bit width given by \p width. The value is sign
1309 /// extended, or left alone to make it that width.
1310 APInt sextOrSelf(unsigned width) const;
1312 /// \brief Zero extend or truncate to width
1314 /// Make this APInt have the bit width given by \p width. The value is zero
1315 /// extended, or left alone to make it that width.
1316 APInt zextOrSelf(unsigned width) const;
1319 /// \name Bit Manipulation Operators
1322 /// \brief Set every bit to 1.
1327 // Set all the bits in all the words.
1328 memset(pVal, -1, getNumWords() * APINT_WORD_SIZE);
1329 // Clear the unused ones
1333 /// \brief Set a given bit to 1.
1335 /// Set the given bit to 1 whose position is given as "bitPosition".
1336 void setBit(unsigned bitPosition);
1338 /// Set the sign bit to 1.
1340 setBit(BitWidth - 1);
1343 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1344 void setBits(unsigned loBit, unsigned hiBit) {
1345 assert(hiBit <= BitWidth && "hiBit out of range");
1346 assert(loBit <= BitWidth && "loBit out of range");
1349 if (loBit > hiBit) {
1351 setHighBits(BitWidth - loBit);
1354 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1355 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1362 setBitsSlowCase(loBit, hiBit);
1366 /// Set the top bits starting from loBit.
1367 void setBitsFrom(unsigned loBit) {
1368 return setBits(loBit, BitWidth);
1371 /// Set the bottom loBits bits.
1372 void setLowBits(unsigned loBits) {
1373 return setBits(0, loBits);
1376 /// Set the top hiBits bits.
1377 void setHighBits(unsigned hiBits) {
1378 return setBits(BitWidth - hiBits, BitWidth);
1381 /// \brief Set every bit to 0.
1382 void clearAllBits() {
1386 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
1389 /// \brief Set a given bit to 0.
1391 /// Set the given bit to 0 whose position is given as "bitPosition".
1392 void clearBit(unsigned bitPosition);
1394 /// \brief Toggle every bit to its opposite value.
1395 void flipAllBits() {
1396 if (isSingleWord()) {
1400 flipAllBitsSlowCase();
1404 /// \brief Toggles a given bit to its opposite value.
1406 /// Toggle a given bit to its opposite value whose position is given
1407 /// as "bitPosition".
1408 void flipBit(unsigned bitPosition);
1410 /// Insert the bits from a smaller APInt starting at bitPosition.
1411 void insertBits(const APInt &SubBits, unsigned bitPosition);
1413 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1414 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1417 /// \name Value Characterization Functions
1420 /// \brief Return the number of bits in the APInt.
1421 unsigned getBitWidth() const { return BitWidth; }
1423 /// \brief Get the number of words.
1425 /// Here one word's bitwidth equals to that of uint64_t.
1427 /// \returns the number of words to hold the integer value of this APInt.
1428 unsigned getNumWords() const { return getNumWords(BitWidth); }
1430 /// \brief Get the number of words.
1432 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1434 /// \returns the number of words to hold the integer value with a given bit
1436 static unsigned getNumWords(unsigned BitWidth) {
1437 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1440 /// \brief Compute the number of active bits in the value
1442 /// This function returns the number of active bits which is defined as the
1443 /// bit width minus the number of leading zeros. This is used in several
1444 /// computations to see how "wide" the value is.
1445 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1447 /// \brief Compute the number of active words in the value of this APInt.
1449 /// This is used in conjunction with getActiveData to extract the raw value of
1451 unsigned getActiveWords() const {
1452 unsigned numActiveBits = getActiveBits();
1453 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1456 /// \brief Get the minimum bit size for this signed APInt
1458 /// Computes the minimum bit width for this APInt while considering it to be a
1459 /// signed (and probably negative) value. If the value is not negative, this
1460 /// function returns the same value as getActiveBits()+1. Otherwise, it
1461 /// returns the smallest bit width that will retain the negative value. For
1462 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1463 /// for -1, this function will always return 1.
1464 unsigned getMinSignedBits() const {
1466 return BitWidth - countLeadingOnes() + 1;
1467 return getActiveBits() + 1;
1470 /// \brief Get zero extended value
1472 /// This method attempts to return the value of this APInt as a zero extended
1473 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1474 /// uint64_t. Otherwise an assertion will result.
1475 uint64_t getZExtValue() const {
1478 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1482 /// \brief Get sign extended value
1484 /// This method attempts to return the value of this APInt as a sign extended
1485 /// int64_t. The bit width must be <= 64 or the value must fit within an
1486 /// int64_t. Otherwise an assertion will result.
1487 int64_t getSExtValue() const {
1489 return SignExtend64(VAL, BitWidth);
1490 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1491 return int64_t(pVal[0]);
1494 /// \brief Get bits required for string value.
1496 /// This method determines how many bits are required to hold the APInt
1497 /// equivalent of the string given by \p str.
1498 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1500 /// \brief The APInt version of the countLeadingZeros functions in
1503 /// It counts the number of zeros from the most significant bit to the first
1506 /// \returns BitWidth if the value is zero, otherwise returns the number of
1507 /// zeros from the most significant bit to the first one bits.
1508 unsigned countLeadingZeros() const {
1509 if (isSingleWord()) {
1510 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1511 return llvm::countLeadingZeros(VAL) - unusedBits;
1513 return countLeadingZerosSlowCase();
1516 /// \brief Count the number of leading one bits.
1518 /// This function is an APInt version of the countLeadingOnes
1519 /// functions in MathExtras.h. It counts the number of ones from the most
1520 /// significant bit to the first zero bit.
1522 /// \returns 0 if the high order bit is not set, otherwise returns the number
1523 /// of 1 bits from the most significant to the least
1524 unsigned countLeadingOnes() const LLVM_READONLY;
1526 /// Computes the number of leading bits of this APInt that are equal to its
1528 unsigned getNumSignBits() const {
1529 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1532 /// \brief Count the number of trailing zero bits.
1534 /// This function is an APInt version of the countTrailingZeros
1535 /// functions in MathExtras.h. It counts the number of zeros from the least
1536 /// significant bit to the first set bit.
1538 /// \returns BitWidth if the value is zero, otherwise returns the number of
1539 /// zeros from the least significant bit to the first one bit.
1540 unsigned countTrailingZeros() const LLVM_READONLY;
1542 /// \brief Count the number of trailing one bits.
1544 /// This function is an APInt version of the countTrailingOnes
1545 /// functions in MathExtras.h. It counts the number of ones from the least
1546 /// significant bit to the first zero bit.
1548 /// \returns BitWidth if the value is all ones, otherwise returns the number
1549 /// of ones from the least significant bit to the first zero bit.
1550 unsigned countTrailingOnes() const {
1552 return llvm::countTrailingOnes(VAL);
1553 return countTrailingOnesSlowCase();
1556 /// \brief Count the number of bits set.
1558 /// This function is an APInt version of the countPopulation functions
1559 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1561 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1562 unsigned countPopulation() const {
1564 return llvm::countPopulation(VAL);
1565 return countPopulationSlowCase();
1569 /// \name Conversion Functions
1571 void print(raw_ostream &OS, bool isSigned) const;
1573 /// Converts an APInt to a string and append it to Str. Str is commonly a
1575 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1576 bool formatAsCLiteral = false) const;
1578 /// Considers the APInt to be unsigned and converts it into a string in the
1579 /// radix given. The radix can be 2, 8, 10 16, or 36.
1580 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1581 toString(Str, Radix, false, false);
1584 /// Considers the APInt to be signed and converts it into a string in the
1585 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1586 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1587 toString(Str, Radix, true, false);
1590 /// \brief Return the APInt as a std::string.
1592 /// Note that this is an inefficient method. It is better to pass in a
1593 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1595 std::string toString(unsigned Radix, bool Signed) const;
1597 /// \returns a byte-swapped representation of this APInt Value.
1598 APInt byteSwap() const;
1600 /// \returns the value with the bit representation reversed of this APInt
1602 APInt reverseBits() const;
1604 /// \brief Converts this APInt to a double value.
1605 double roundToDouble(bool isSigned) const;
1607 /// \brief Converts this unsigned APInt to a double value.
1608 double roundToDouble() const { return roundToDouble(false); }
1610 /// \brief Converts this signed APInt to a double value.
1611 double signedRoundToDouble() const { return roundToDouble(true); }
1613 /// \brief Converts APInt bits to a double
1615 /// The conversion does not do a translation from integer to double, it just
1616 /// re-interprets the bits as a double. Note that it is valid to do this on
1617 /// any bit width. Exactly 64 bits will be translated.
1618 double bitsToDouble() const {
1623 T.I = (isSingleWord() ? VAL : pVal[0]);
1627 /// \brief Converts APInt bits to a double
1629 /// The conversion does not do a translation from integer to float, it just
1630 /// re-interprets the bits as a float. Note that it is valid to do this on
1631 /// any bit width. Exactly 32 bits will be translated.
1632 float bitsToFloat() const {
1637 T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1641 /// \brief Converts a double to APInt bits.
1643 /// The conversion does not do a translation from double to integer, it just
1644 /// re-interprets the bits of the double.
1645 static APInt doubleToBits(double V) {
1651 return APInt(sizeof T * CHAR_BIT, T.I);
1654 /// \brief Converts a float to APInt bits.
1656 /// The conversion does not do a translation from float to integer, it just
1657 /// re-interprets the bits of the float.
1658 static APInt floatToBits(float V) {
1664 return APInt(sizeof T * CHAR_BIT, T.I);
1668 /// \name Mathematics Operations
1671 /// \returns the floor log base 2 of this APInt.
1672 unsigned logBase2() const { return BitWidth - 1 - countLeadingZeros(); }
1674 /// \returns the ceil log base 2 of this APInt.
1675 unsigned ceilLogBase2() const {
1678 return BitWidth - temp.countLeadingZeros();
1681 /// \returns the nearest log base 2 of this APInt. Ties round up.
1683 /// NOTE: When we have a BitWidth of 1, we define:
1685 /// log2(0) = UINT32_MAX
1688 /// to get around any mathematical concerns resulting from
1689 /// referencing 2 in a space where 2 does no exist.
1690 unsigned nearestLogBase2() const {
1691 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1692 // get 0. If VAL is 0, we get WORD_MAX which gets truncated to
1697 // Handle the zero case.
1698 if (!getBoolValue())
1701 // The non-zero case is handled by computing:
1703 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1705 // where x[i] is referring to the value of the ith bit of x.
1706 unsigned lg = logBase2();
1707 return lg + unsigned((*this)[lg - 1]);
1710 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1712 int32_t exactLogBase2() const {
1718 /// \brief Compute the square root
1721 /// \brief Get the absolute value;
1723 /// If *this is < 0 then return -(*this), otherwise *this;
1730 /// \returns the multiplicative inverse for a given modulo.
1731 APInt multiplicativeInverse(const APInt &modulo) const;
1734 /// \name Support for division by constant
1737 /// Calculate the magic number for signed division by a constant.
1741 /// Calculate the magic number for unsigned division by a constant.
1743 mu magicu(unsigned LeadingZeros = 0) const;
1746 /// \name Building-block Operations for APInt and APFloat
1749 // These building block operations operate on a representation of arbitrary
1750 // precision, two's-complement, bignum integer values. They should be
1751 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1752 // generally a pointer to the base of an array of integer parts, representing
1753 // an unsigned bignum, and a count of how many parts there are.
1755 /// Sets the least significant part of a bignum to the input value, and zeroes
1756 /// out higher parts.
1757 static void tcSet(WordType *, WordType, unsigned);
1759 /// Assign one bignum to another.
1760 static void tcAssign(WordType *, const WordType *, unsigned);
1762 /// Returns true if a bignum is zero, false otherwise.
1763 static bool tcIsZero(const WordType *, unsigned);
1765 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1766 static int tcExtractBit(const WordType *, unsigned bit);
1768 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1769 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1770 /// significant bit of DST. All high bits above srcBITS in DST are
1772 static void tcExtract(WordType *, unsigned dstCount,
1773 const WordType *, unsigned srcBits,
1776 /// Set the given bit of a bignum. Zero-based.
1777 static void tcSetBit(WordType *, unsigned bit);
1779 /// Clear the given bit of a bignum. Zero-based.
1780 static void tcClearBit(WordType *, unsigned bit);
1782 /// Returns the bit number of the least or most significant set bit of a
1783 /// number. If the input number has no bits set -1U is returned.
1784 static unsigned tcLSB(const WordType *, unsigned n);
1785 static unsigned tcMSB(const WordType *parts, unsigned n);
1787 /// Negate a bignum in-place.
1788 static void tcNegate(WordType *, unsigned);
1790 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1791 static WordType tcAdd(WordType *, const WordType *,
1792 WordType carry, unsigned);
1793 /// DST += RHS. Returns the carry flag.
1794 static WordType tcAddPart(WordType *, WordType, unsigned);
1796 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1797 static WordType tcSubtract(WordType *, const WordType *,
1798 WordType carry, unsigned);
1799 /// DST -= RHS. Returns the carry flag.
1800 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1802 /// DST += SRC * MULTIPLIER + PART if add is true
1803 /// DST = SRC * MULTIPLIER + PART if add is false
1805 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1806 /// start at the same point, i.e. DST == SRC.
1808 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1809 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1810 /// result, and if all of the omitted higher parts were zero return zero,
1811 /// otherwise overflow occurred and return one.
1812 static int tcMultiplyPart(WordType *dst, const WordType *src,
1813 WordType multiplier, WordType carry,
1814 unsigned srcParts, unsigned dstParts,
1817 /// DST = LHS * RHS, where DST has the same width as the operands and is
1818 /// filled with the least significant parts of the result. Returns one if
1819 /// overflow occurred, otherwise zero. DST must be disjoint from both
1821 static int tcMultiply(WordType *, const WordType *, const WordType *,
1824 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1825 /// operands. No overflow occurs. DST must be disjoint from both
1826 /// operands. Returns the number of parts required to hold the result.
1827 static unsigned tcFullMultiply(WordType *, const WordType *,
1828 const WordType *, unsigned, unsigned);
1830 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1831 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1832 /// REMAINDER to the remainder, return zero. i.e.
1834 /// OLD_LHS = RHS * LHS + REMAINDER
1836 /// SCRATCH is a bignum of the same size as the operands and result for use by
1837 /// the routine; its contents need not be initialized and are destroyed. LHS,
1838 /// REMAINDER and SCRATCH must be distinct.
1839 static int tcDivide(WordType *lhs, const WordType *rhs,
1840 WordType *remainder, WordType *scratch,
1843 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1844 /// restrictions on Count.
1845 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1847 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1848 /// restrictions on Count.
1849 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1851 /// The obvious AND, OR and XOR and complement operations.
1852 static void tcAnd(WordType *, const WordType *, unsigned);
1853 static void tcOr(WordType *, const WordType *, unsigned);
1854 static void tcXor(WordType *, const WordType *, unsigned);
1855 static void tcComplement(WordType *, unsigned);
1857 /// Comparison (unsigned) of two bignums.
1858 static int tcCompare(const WordType *, const WordType *, unsigned);
1860 /// Increment a bignum in-place. Return the carry flag.
1861 static WordType tcIncrement(WordType *dst, unsigned parts) {
1862 return tcAddPart(dst, 1, parts);
1865 /// Decrement a bignum in-place. Return the borrow flag.
1866 static WordType tcDecrement(WordType *dst, unsigned parts) {
1867 return tcSubtractPart(dst, 1, parts);
1870 /// Set the least significant BITS and clear the rest.
1871 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits);
1873 /// \brief debug method
1879 /// Magic data for optimising signed division by a constant.
1881 APInt m; ///< magic number
1882 unsigned s; ///< shift amount
1885 /// Magic data for optimising unsigned division by a constant.
1887 APInt m; ///< magic number
1888 bool a; ///< add indicator
1889 unsigned s; ///< shift amount
1892 inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1894 inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1896 /// \brief Unary bitwise complement operator.
1898 /// \returns an APInt that is the bitwise complement of \p v.
1899 inline APInt operator~(APInt v) {
1904 inline APInt operator&(APInt a, const APInt &b) {
1909 inline APInt operator&(const APInt &a, APInt &&b) {
1911 return std::move(b);
1914 inline APInt operator&(APInt a, uint64_t RHS) {
1919 inline APInt operator&(uint64_t LHS, APInt b) {
1924 inline APInt operator|(APInt a, const APInt &b) {
1929 inline APInt operator|(const APInt &a, APInt &&b) {
1931 return std::move(b);
1934 inline APInt operator|(APInt a, uint64_t RHS) {
1939 inline APInt operator|(uint64_t LHS, APInt b) {
1944 inline APInt operator^(APInt a, const APInt &b) {
1949 inline APInt operator^(const APInt &a, APInt &&b) {
1951 return std::move(b);
1954 inline APInt operator^(APInt a, uint64_t RHS) {
1959 inline APInt operator^(uint64_t LHS, APInt b) {
1964 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1969 inline APInt operator-(APInt v) {
1975 inline APInt operator+(APInt a, const APInt &b) {
1980 inline APInt operator+(const APInt &a, APInt &&b) {
1982 return std::move(b);
1985 inline APInt operator+(APInt a, uint64_t RHS) {
1990 inline APInt operator+(uint64_t LHS, APInt b) {
1995 inline APInt operator-(APInt a, const APInt &b) {
2000 inline APInt operator-(const APInt &a, APInt &&b) {
2003 return std::move(b);
2006 inline APInt operator-(APInt a, uint64_t RHS) {
2011 inline APInt operator-(uint64_t LHS, APInt b) {
2018 namespace APIntOps {
2020 /// \brief Determine the smaller of two APInts considered to be signed.
2021 inline const APInt &smin(const APInt &A, const APInt &B) {
2022 return A.slt(B) ? A : B;
2025 /// \brief Determine the larger of two APInts considered to be signed.
2026 inline const APInt &smax(const APInt &A, const APInt &B) {
2027 return A.sgt(B) ? A : B;
2030 /// \brief Determine the smaller of two APInts considered to be signed.
2031 inline const APInt &umin(const APInt &A, const APInt &B) {
2032 return A.ult(B) ? A : B;
2035 /// \brief Determine the larger of two APInts considered to be unsigned.
2036 inline const APInt &umax(const APInt &A, const APInt &B) {
2037 return A.ugt(B) ? A : B;
2040 /// \brief Compute GCD of two unsigned APInt values.
2042 /// This function returns the greatest common divisor of the two APInt values
2043 /// using Stein's algorithm.
2045 /// \returns the greatest common divisor of A and B.
2046 APInt GreatestCommonDivisor(APInt A, APInt B);
2048 /// \brief Converts the given APInt to a double value.
2050 /// Treats the APInt as an unsigned value for conversion purposes.
2051 inline double RoundAPIntToDouble(const APInt &APIVal) {
2052 return APIVal.roundToDouble();
2055 /// \brief Converts the given APInt to a double value.
2057 /// Treats the APInt as a signed value for conversion purposes.
2058 inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2059 return APIVal.signedRoundToDouble();
2062 /// \brief Converts the given APInt to a float vlalue.
2063 inline float RoundAPIntToFloat(const APInt &APIVal) {
2064 return float(RoundAPIntToDouble(APIVal));
2067 /// \brief Converts the given APInt to a float value.
2069 /// Treast the APInt as a signed value for conversion purposes.
2070 inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2071 return float(APIVal.signedRoundToDouble());
2074 /// \brief Converts the given double value into a APInt.
2076 /// This function convert a double value to an APInt value.
2077 APInt RoundDoubleToAPInt(double Double, unsigned width);
2079 /// \brief Converts a float value into a APInt.
2081 /// Converts a float value into an APInt value.
2082 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2083 return RoundDoubleToAPInt(double(Float), width);
2086 } // End of APIntOps namespace
2088 // See friend declaration above. This additional declaration is required in
2089 // order to compile LLVM with IBM xlC compiler.
2090 hash_code hash_value(const APInt &Arg);
2091 } // End of llvm namespace