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 /// 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;
34 template <typename T> class Optional;
38 inline APInt operator-(APInt);
40 //===----------------------------------------------------------------------===//
42 //===----------------------------------------------------------------------===//
44 /// Class for arbitrary precision integers.
46 /// APInt is a functional replacement for common case unsigned integer type like
47 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
48 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
49 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
50 /// and methods to manipulate integer values of any bit-width. It supports both
51 /// the typical integer arithmetic and comparison operations as well as bitwise
54 /// The class has several invariants worth noting:
55 /// * All bit, byte, and word positions are zero-based.
56 /// * Once the bit width is set, it doesn't change except by the Truncate,
57 /// SignExtend, or ZeroExtend operations.
58 /// * All binary operators must be on APInt instances of the same bit width.
59 /// Attempting to use these operators on instances with different bit
60 /// widths will yield an assertion.
61 /// * The value is stored canonically as an unsigned value. For operations
62 /// where it makes a difference, there are both signed and unsigned variants
63 /// of the operation. For example, sdiv and udiv. However, because the bit
64 /// widths must be the same, operations such as Mul and Add produce the same
65 /// results regardless of whether the values are interpreted as signed or
67 /// * In general, the class tries to follow the style of computation that LLVM
68 /// uses in its IR. This simplifies its use for LLVM.
70 class LLVM_NODISCARD APInt {
72 typedef uint64_t WordType;
74 /// This enum is used to hold the constants we needed for APInt.
76 /// Byte size of a word.
77 APINT_WORD_SIZE = sizeof(WordType),
79 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT
88 static const WordType WORDTYPE_MAX = ~WordType(0);
91 /// This union is used to store the integer value. When the
92 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
94 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
95 uint64_t *pVal; ///< Used to store the >64 bits integer value.
98 unsigned BitWidth; ///< The number of bits in this APInt.
100 friend struct DenseMapAPIntKeyInfo;
104 /// Fast internal constructor
106 /// This constructor is used only internally for speed of construction of
107 /// temporaries. It is unsafe for general use so it is not public.
108 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) {
112 /// Determine if this APInt just has one word to store value.
114 /// \returns true if the number of bits <= 64, false otherwise.
115 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
117 /// Determine which word a bit is in.
119 /// \returns the word position for the specified bit position.
120 static unsigned whichWord(unsigned bitPosition) {
121 return bitPosition / APINT_BITS_PER_WORD;
124 /// Determine which bit in a word a bit is in.
126 /// \returns the bit position in a word for the specified bit position
128 static unsigned whichBit(unsigned bitPosition) {
129 return bitPosition % APINT_BITS_PER_WORD;
132 /// Get a single bit mask.
134 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
135 /// This method generates and returns a uint64_t (word) mask for a single
136 /// bit at a specific bit position. This is used to mask the bit in the
137 /// corresponding word.
138 static uint64_t maskBit(unsigned bitPosition) {
139 return 1ULL << whichBit(bitPosition);
142 /// Clear unused high order bits
144 /// This method is used internally to clear the top "N" bits in the high order
145 /// word that are not used by the APInt. This is needed after the most
146 /// significant word is assigned a value to ensure that those bits are
148 APInt &clearUnusedBits() {
149 // Compute how many bits are used in the final word
150 unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1;
152 // Mask out the high bits.
153 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - WordBits);
157 U.pVal[getNumWords() - 1] &= mask;
161 /// Get the word corresponding to a bit position
162 /// \returns the corresponding word for the specified bit position.
163 uint64_t getWord(unsigned bitPosition) const {
164 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
167 /// Utility method to change the bit width of this APInt to new bit width,
168 /// allocating and/or deallocating as necessary. There is no guarantee on the
169 /// value of any bits upon return. Caller should populate the bits after.
170 void reallocate(unsigned NewBitWidth);
172 /// Convert a char array into an APInt
174 /// \param radix 2, 8, 10, 16, or 36
175 /// Converts a string into a number. The string must be non-empty
176 /// and well-formed as a number of the given base. The bit-width
177 /// must be sufficient to hold the result.
179 /// This is used by the constructors that take string arguments.
181 /// StringRef::getAsInteger is superficially similar but (1) does
182 /// not assume that the string is well-formed and (2) grows the
183 /// result to hold the input.
184 void fromString(unsigned numBits, StringRef str, uint8_t radix);
186 /// An internal division function for dividing APInts.
188 /// This is used by the toString method to divide by the radix. It simply
189 /// provides a more convenient form of divide for internal use since KnuthDiv
190 /// has specific constraints on its inputs. If those constraints are not met
191 /// then it provides a simpler form of divide.
192 static void divide(const WordType *LHS, unsigned lhsWords,
193 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
194 WordType *Remainder);
196 /// out-of-line slow case for inline constructor
197 void initSlowCase(uint64_t val, bool isSigned);
199 /// shared code between two array constructors
200 void initFromArray(ArrayRef<uint64_t> array);
202 /// out-of-line slow case for inline copy constructor
203 void initSlowCase(const APInt &that);
205 /// out-of-line slow case for shl
206 void shlSlowCase(unsigned ShiftAmt);
208 /// out-of-line slow case for lshr.
209 void lshrSlowCase(unsigned ShiftAmt);
211 /// out-of-line slow case for ashr.
212 void ashrSlowCase(unsigned ShiftAmt);
214 /// out-of-line slow case for operator=
215 void AssignSlowCase(const APInt &RHS);
217 /// out-of-line slow case for operator==
218 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY;
220 /// out-of-line slow case for countLeadingZeros
221 unsigned countLeadingZerosSlowCase() const LLVM_READONLY;
223 /// out-of-line slow case for countLeadingOnes.
224 unsigned countLeadingOnesSlowCase() const LLVM_READONLY;
226 /// out-of-line slow case for countTrailingZeros.
227 unsigned countTrailingZerosSlowCase() const LLVM_READONLY;
229 /// out-of-line slow case for countTrailingOnes
230 unsigned countTrailingOnesSlowCase() const LLVM_READONLY;
232 /// out-of-line slow case for countPopulation
233 unsigned countPopulationSlowCase() const LLVM_READONLY;
235 /// out-of-line slow case for intersects.
236 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY;
238 /// out-of-line slow case for isSubsetOf.
239 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY;
241 /// out-of-line slow case for setBits.
242 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
244 /// out-of-line slow case for flipAllBits.
245 void flipAllBitsSlowCase();
247 /// out-of-line slow case for operator&=.
248 void AndAssignSlowCase(const APInt& RHS);
250 /// out-of-line slow case for operator|=.
251 void OrAssignSlowCase(const APInt& RHS);
253 /// out-of-line slow case for operator^=.
254 void XorAssignSlowCase(const APInt& RHS);
256 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
257 /// to, or greater than RHS.
258 int compare(const APInt &RHS) const LLVM_READONLY;
260 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
261 /// to, or greater than RHS.
262 int compareSigned(const APInt &RHS) const LLVM_READONLY;
265 /// \name Constructors
268 /// Create a new APInt of numBits width, initialized as val.
270 /// If isSigned is true then val is treated as if it were a signed value
271 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
272 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
273 /// the range of val are zero filled).
275 /// \param numBits the bit width of the constructed APInt
276 /// \param val the initial value of the APInt
277 /// \param isSigned how to treat signedness of val
278 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
279 : BitWidth(numBits) {
280 assert(BitWidth && "bitwidth too small");
281 if (isSingleWord()) {
285 initSlowCase(val, isSigned);
289 /// Construct an APInt of numBits width, initialized as bigVal[].
291 /// Note that bigVal.size() can be smaller or larger than the corresponding
292 /// bit width but any extraneous bits will be dropped.
294 /// \param numBits the bit width of the constructed APInt
295 /// \param bigVal a sequence of words to form the initial value of the APInt
296 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
298 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
299 /// deprecated because this constructor is prone to ambiguity with the
300 /// APInt(unsigned, uint64_t, bool) constructor.
302 /// If this overload is ever deleted, care should be taken to prevent calls
303 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
305 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
307 /// Construct an APInt from a string representation.
309 /// This constructor interprets the string \p str in the given radix. The
310 /// interpretation stops when the first character that is not suitable for the
311 /// radix is encountered, or the end of the string. Acceptable radix values
312 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
313 /// string to require more bits than numBits.
315 /// \param numBits the bit width of the constructed APInt
316 /// \param str the string to be interpreted
317 /// \param radix the radix to use for the conversion
318 APInt(unsigned numBits, StringRef str, uint8_t radix);
320 /// Simply makes *this a copy of that.
321 /// Copy Constructor.
322 APInt(const APInt &that) : BitWidth(that.BitWidth) {
329 /// Move Constructor.
330 APInt(APInt &&that) : BitWidth(that.BitWidth) {
331 memcpy(&U, &that.U, sizeof(U));
341 /// Default constructor that creates an uninteresting APInt
342 /// representing a 1-bit zero value.
344 /// This is useful for object deserialization (pair this with the static
346 explicit APInt() : BitWidth(1) { U.VAL = 0; }
348 /// Returns whether this instance allocated memory.
349 bool needsCleanup() const { return !isSingleWord(); }
351 /// Used to insert APInt objects, or objects that contain APInt objects, into
353 void Profile(FoldingSetNodeID &id) const;
356 /// \name Value Tests
359 /// Determine sign of this APInt.
361 /// This tests the high bit of this APInt to determine if it is set.
363 /// \returns true if this APInt is negative, false otherwise
364 bool isNegative() const { return (*this)[BitWidth - 1]; }
366 /// Determine if this APInt Value is non-negative (>= 0)
368 /// This tests the high bit of the APInt to determine if it is unset.
369 bool isNonNegative() const { return !isNegative(); }
371 /// Determine if sign bit of this APInt is set.
373 /// This tests the high bit of this APInt to determine if it is set.
375 /// \returns true if this APInt has its sign bit set, false otherwise.
376 bool isSignBitSet() const { return (*this)[BitWidth-1]; }
378 /// Determine if sign bit of this APInt is clear.
380 /// This tests the high bit of this APInt to determine if it is clear.
382 /// \returns true if this APInt has its sign bit clear, false otherwise.
383 bool isSignBitClear() const { return !isSignBitSet(); }
385 /// Determine if this APInt Value is positive.
387 /// This tests if the value of this APInt is positive (> 0). Note
388 /// that 0 is not a positive value.
390 /// \returns true if this APInt is positive.
391 bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); }
393 /// Determine if all bits are set
395 /// This checks to see if the value has all bits of the APInt are set or not.
396 bool isAllOnesValue() const {
398 return U.VAL == WORDTYPE_MAX >> (APINT_BITS_PER_WORD - BitWidth);
399 return countTrailingOnesSlowCase() == BitWidth;
402 /// Determine if all bits are clear
404 /// This checks to see if the value has all bits of the APInt are clear or
406 bool isNullValue() const { return !*this; }
408 /// Determine if this is a value of 1.
410 /// This checks to see if the value of this APInt is one.
411 bool isOneValue() const {
414 return countLeadingZerosSlowCase() == BitWidth - 1;
417 /// Determine if this is the largest unsigned value.
419 /// This checks to see if the value of this APInt is the maximum unsigned
420 /// value for the APInt's bit width.
421 bool isMaxValue() const { return isAllOnesValue(); }
423 /// Determine if this is the largest signed value.
425 /// This checks to see if the value of this APInt is the maximum signed
426 /// value for the APInt's bit width.
427 bool isMaxSignedValue() const {
429 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
430 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
433 /// Determine if this is the smallest unsigned value.
435 /// This checks to see if the value of this APInt is the minimum unsigned
436 /// value for the APInt's bit width.
437 bool isMinValue() const { return isNullValue(); }
439 /// Determine if this is the smallest signed value.
441 /// This checks to see if the value of this APInt is the minimum signed
442 /// value for the APInt's bit width.
443 bool isMinSignedValue() const {
445 return U.VAL == (WordType(1) << (BitWidth - 1));
446 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
449 /// Check if this APInt has an N-bits unsigned integer value.
450 bool isIntN(unsigned N) const {
451 assert(N && "N == 0 ???");
452 return getActiveBits() <= N;
455 /// Check if this APInt has an N-bits signed integer value.
456 bool isSignedIntN(unsigned N) const {
457 assert(N && "N == 0 ???");
458 return getMinSignedBits() <= N;
461 /// Check if this APInt's value is a power of two greater than zero.
463 /// \returns true if the argument APInt value is a power of two > 0.
464 bool isPowerOf2() const {
466 return isPowerOf2_64(U.VAL);
467 return countPopulationSlowCase() == 1;
470 /// Check if the APInt's value is returned by getSignMask.
472 /// \returns true if this is the value returned by getSignMask.
473 bool isSignMask() const { return isMinSignedValue(); }
475 /// Convert APInt to a boolean value.
477 /// This converts the APInt to a boolean value as a test against zero.
478 bool getBoolValue() const { return !!*this; }
480 /// If this value is smaller than the specified limit, return it, otherwise
481 /// return the limit value. This causes the value to saturate to the limit.
482 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) const {
483 return ugt(Limit) ? Limit : getZExtValue();
486 /// Check if the APInt consists of a repeated bit pattern.
488 /// e.g. 0x01010101 satisfies isSplat(8).
489 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
490 /// width without remainder.
491 bool isSplat(unsigned SplatSizeInBits) const;
493 /// \returns true if this APInt value is a sequence of \param numBits ones
494 /// starting at the least significant bit with the remainder zero.
495 bool isMask(unsigned numBits) const {
496 assert(numBits != 0 && "numBits must be non-zero");
497 assert(numBits <= BitWidth && "numBits out of range");
499 return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits));
500 unsigned Ones = countTrailingOnesSlowCase();
501 return (numBits == Ones) &&
502 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
505 /// \returns true if this APInt is a non-empty sequence of ones starting at
506 /// the least significant bit with the remainder zero.
507 /// Ex. isMask(0x0000FFFFU) == true.
508 bool isMask() const {
510 return isMask_64(U.VAL);
511 unsigned Ones = countTrailingOnesSlowCase();
512 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
515 /// Return true if this APInt value contains a sequence of ones with
516 /// the remainder zero.
517 bool isShiftedMask() const {
519 return isShiftedMask_64(U.VAL);
520 unsigned Ones = countPopulationSlowCase();
521 unsigned LeadZ = countLeadingZerosSlowCase();
522 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
526 /// \name Value Generators
529 /// Gets maximum unsigned value of APInt for specific bit width.
530 static APInt getMaxValue(unsigned numBits) {
531 return getAllOnesValue(numBits);
534 /// Gets maximum signed value of APInt for a specific bit width.
535 static APInt getSignedMaxValue(unsigned numBits) {
536 APInt API = getAllOnesValue(numBits);
537 API.clearBit(numBits - 1);
541 /// Gets minimum unsigned value of APInt for a specific bit width.
542 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
544 /// Gets minimum signed value of APInt for a specific bit width.
545 static APInt getSignedMinValue(unsigned numBits) {
546 APInt API(numBits, 0);
547 API.setBit(numBits - 1);
551 /// Get the SignMask for a specific bit width.
553 /// This is just a wrapper function of getSignedMinValue(), and it helps code
554 /// readability when we want to get a SignMask.
555 static APInt getSignMask(unsigned BitWidth) {
556 return getSignedMinValue(BitWidth);
559 /// Get the all-ones value.
561 /// \returns the all-ones value for an APInt of the specified bit-width.
562 static APInt getAllOnesValue(unsigned numBits) {
563 return APInt(numBits, WORDTYPE_MAX, true);
566 /// Get the '0' value.
568 /// \returns the '0' value for an APInt of the specified bit-width.
569 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
571 /// Compute an APInt containing numBits highbits from this APInt.
573 /// Get an APInt with the same BitWidth as this APInt, just zero mask
574 /// the low bits and right shift to the least significant bit.
576 /// \returns the high "numBits" bits of this APInt.
577 APInt getHiBits(unsigned numBits) const;
579 /// Compute an APInt containing numBits lowbits from this APInt.
581 /// Get an APInt with the same BitWidth as this APInt, just zero mask
584 /// \returns the low "numBits" bits of this APInt.
585 APInt getLoBits(unsigned numBits) const;
587 /// Return an APInt with exactly one bit set in the result.
588 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
589 APInt Res(numBits, 0);
594 /// Get a value with a block of bits set.
596 /// Constructs an APInt value that has a contiguous range of bits set. The
597 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
598 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
599 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
600 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
602 /// \param numBits the intended bit width of the result
603 /// \param loBit the index of the lowest bit set.
604 /// \param hiBit the index of the highest bit set.
606 /// \returns An APInt value with the requested bits set.
607 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
608 APInt Res(numBits, 0);
609 Res.setBits(loBit, hiBit);
613 /// Get a value with upper bits starting at loBit set.
615 /// Constructs an APInt value that has a contiguous range of bits set. The
616 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
617 /// bits will be zero. For example, with parameters(32, 12) you would get
620 /// \param numBits the intended bit width of the result
621 /// \param loBit the index of the lowest bit to set.
623 /// \returns An APInt value with the requested bits set.
624 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
625 APInt Res(numBits, 0);
626 Res.setBitsFrom(loBit);
630 /// Get a value with high bits set
632 /// Constructs an APInt value that has the top hiBitsSet bits set.
634 /// \param numBits the bitwidth of the result
635 /// \param hiBitsSet the number of high-order bits set in the result.
636 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
637 APInt Res(numBits, 0);
638 Res.setHighBits(hiBitsSet);
642 /// Get a value with low bits set
644 /// Constructs an APInt value that has the bottom loBitsSet bits set.
646 /// \param numBits the bitwidth of the result
647 /// \param loBitsSet the number of low-order bits set in the result.
648 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
649 APInt Res(numBits, 0);
650 Res.setLowBits(loBitsSet);
654 /// Return a value containing V broadcasted over NewLen bits.
655 static APInt getSplat(unsigned NewLen, const APInt &V);
657 /// Determine if two APInts have the same value, after zero-extending
658 /// one of them (if needed!) to ensure that the bit-widths match.
659 static bool isSameValue(const APInt &I1, const APInt &I2) {
660 if (I1.getBitWidth() == I2.getBitWidth())
663 if (I1.getBitWidth() > I2.getBitWidth())
664 return I1 == I2.zext(I1.getBitWidth());
666 return I1.zext(I2.getBitWidth()) == I2;
669 /// Overload to compute a hash_code for an APInt value.
670 friend hash_code hash_value(const APInt &Arg);
672 /// This function returns a pointer to the internal storage of the APInt.
673 /// This is useful for writing out the APInt in binary form without any
675 const uint64_t *getRawData() const {
682 /// \name Unary Operators
685 /// Postfix increment operator.
687 /// Increments *this by 1.
689 /// \returns a new APInt value representing the original value of *this.
690 const APInt operator++(int) {
696 /// Prefix increment operator.
698 /// \returns *this incremented by one
701 /// Postfix decrement operator.
703 /// Decrements *this by 1.
705 /// \returns a new APInt value representing the original value of *this.
706 const APInt operator--(int) {
712 /// Prefix decrement operator.
714 /// \returns *this decremented by one.
717 /// Logical negation operator.
719 /// Performs logical negation operation on this APInt.
721 /// \returns true if *this is zero, false otherwise.
722 bool operator!() const {
725 return countLeadingZerosSlowCase() == BitWidth;
729 /// \name Assignment Operators
732 /// Copy assignment operator.
734 /// \returns *this after assignment of RHS.
735 APInt &operator=(const APInt &RHS) {
736 // If the bitwidths are the same, we can avoid mucking with memory
737 if (isSingleWord() && RHS.isSingleWord()) {
739 BitWidth = RHS.BitWidth;
740 return clearUnusedBits();
747 /// Move assignment operator.
748 APInt &operator=(APInt &&that) {
750 // The MSVC std::shuffle implementation still does self-assignment.
754 assert(this != &that && "Self-move not supported");
758 // Use memcpy so that type based alias analysis sees both VAL and pVal
760 memcpy(&U, &that.U, sizeof(U));
762 BitWidth = that.BitWidth;
768 /// Assignment operator.
770 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
771 /// the bit width, the excess bits are truncated. If the bit width is larger
772 /// than 64, the value is zero filled in the unspecified high order bits.
774 /// \returns *this after assignment of RHS value.
775 APInt &operator=(uint64_t RHS) {
776 if (isSingleWord()) {
781 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
786 /// Bitwise AND assignment operator.
788 /// Performs a bitwise AND operation on this APInt and RHS. The result is
789 /// assigned to *this.
791 /// \returns *this after ANDing with RHS.
792 APInt &operator&=(const APInt &RHS) {
793 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
797 AndAssignSlowCase(RHS);
801 /// Bitwise AND assignment operator.
803 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
804 /// logically zero-extended or truncated to match the bit-width of
806 APInt &operator&=(uint64_t RHS) {
807 if (isSingleWord()) {
812 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
816 /// Bitwise OR assignment operator.
818 /// Performs a bitwise OR operation on this APInt and RHS. The result is
821 /// \returns *this after ORing with RHS.
822 APInt &operator|=(const APInt &RHS) {
823 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
827 OrAssignSlowCase(RHS);
831 /// Bitwise OR assignment operator.
833 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
834 /// logically zero-extended or truncated to match the bit-width of
836 APInt &operator|=(uint64_t RHS) {
837 if (isSingleWord()) {
846 /// Bitwise XOR assignment operator.
848 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
849 /// assigned to *this.
851 /// \returns *this after XORing with RHS.
852 APInt &operator^=(const APInt &RHS) {
853 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
857 XorAssignSlowCase(RHS);
861 /// Bitwise XOR assignment operator.
863 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
864 /// logically zero-extended or truncated to match the bit-width of
866 APInt &operator^=(uint64_t RHS) {
867 if (isSingleWord()) {
876 /// Multiplication assignment operator.
878 /// Multiplies this APInt by RHS and assigns the result to *this.
881 APInt &operator*=(const APInt &RHS);
882 APInt &operator*=(uint64_t RHS);
884 /// Addition assignment operator.
886 /// Adds RHS to *this and assigns the result to *this.
889 APInt &operator+=(const APInt &RHS);
890 APInt &operator+=(uint64_t RHS);
892 /// Subtraction assignment operator.
894 /// Subtracts RHS from *this and assigns the result to *this.
897 APInt &operator-=(const APInt &RHS);
898 APInt &operator-=(uint64_t RHS);
900 /// Left-shift assignment function.
902 /// Shifts *this left by shiftAmt and assigns the result to *this.
904 /// \returns *this after shifting left by ShiftAmt
905 APInt &operator<<=(unsigned ShiftAmt) {
906 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
907 if (isSingleWord()) {
908 if (ShiftAmt == BitWidth)
912 return clearUnusedBits();
914 shlSlowCase(ShiftAmt);
918 /// Left-shift assignment function.
920 /// Shifts *this left by shiftAmt and assigns the result to *this.
922 /// \returns *this after shifting left by ShiftAmt
923 APInt &operator<<=(const APInt &ShiftAmt);
926 /// \name Binary Operators
929 /// Multiplication operator.
931 /// Multiplies this APInt by RHS and returns the result.
932 APInt operator*(const APInt &RHS) const;
934 /// Left logical shift operator.
936 /// Shifts this APInt left by \p Bits and returns the result.
937 APInt operator<<(unsigned Bits) const { return shl(Bits); }
939 /// Left logical shift operator.
941 /// Shifts this APInt left by \p Bits and returns the result.
942 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
944 /// Arithmetic right-shift function.
946 /// Arithmetic right-shift this APInt by shiftAmt.
947 APInt ashr(unsigned ShiftAmt) const {
949 R.ashrInPlace(ShiftAmt);
953 /// Arithmetic right-shift this APInt by ShiftAmt in place.
954 void ashrInPlace(unsigned ShiftAmt) {
955 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
956 if (isSingleWord()) {
957 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
958 if (ShiftAmt == BitWidth)
959 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
961 U.VAL = SExtVAL >> ShiftAmt;
965 ashrSlowCase(ShiftAmt);
968 /// Logical right-shift function.
970 /// Logical right-shift this APInt by shiftAmt.
971 APInt lshr(unsigned shiftAmt) const {
973 R.lshrInPlace(shiftAmt);
977 /// Logical right-shift this APInt by ShiftAmt in place.
978 void lshrInPlace(unsigned ShiftAmt) {
979 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
980 if (isSingleWord()) {
981 if (ShiftAmt == BitWidth)
987 lshrSlowCase(ShiftAmt);
990 /// Left-shift function.
992 /// Left-shift this APInt by shiftAmt.
993 APInt shl(unsigned shiftAmt) const {
999 /// Rotate left by rotateAmt.
1000 APInt rotl(unsigned rotateAmt) const;
1002 /// Rotate right by rotateAmt.
1003 APInt rotr(unsigned rotateAmt) const;
1005 /// Arithmetic right-shift function.
1007 /// Arithmetic right-shift this APInt by shiftAmt.
1008 APInt ashr(const APInt &ShiftAmt) const {
1010 R.ashrInPlace(ShiftAmt);
1014 /// Arithmetic right-shift this APInt by shiftAmt in place.
1015 void ashrInPlace(const APInt &shiftAmt);
1017 /// Logical right-shift function.
1019 /// Logical right-shift this APInt by shiftAmt.
1020 APInt lshr(const APInt &ShiftAmt) const {
1022 R.lshrInPlace(ShiftAmt);
1026 /// Logical right-shift this APInt by ShiftAmt in place.
1027 void lshrInPlace(const APInt &ShiftAmt);
1029 /// Left-shift function.
1031 /// Left-shift this APInt by shiftAmt.
1032 APInt shl(const APInt &ShiftAmt) const {
1038 /// Rotate left by rotateAmt.
1039 APInt rotl(const APInt &rotateAmt) const;
1041 /// Rotate right by rotateAmt.
1042 APInt rotr(const APInt &rotateAmt) const;
1044 /// Unsigned division operation.
1046 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
1047 /// RHS are treated as unsigned quantities for purposes of this division.
1049 /// \returns a new APInt value containing the division result, rounded towards
1051 APInt udiv(const APInt &RHS) const;
1052 APInt udiv(uint64_t RHS) const;
1054 /// Signed division function for APInt.
1056 /// Signed divide this APInt by APInt RHS.
1058 /// The result is rounded towards zero.
1059 APInt sdiv(const APInt &RHS) const;
1060 APInt sdiv(int64_t RHS) const;
1062 /// Unsigned remainder operation.
1064 /// Perform an unsigned remainder operation on this APInt with RHS being the
1065 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
1066 /// of this operation. Note that this is a true remainder operation and not a
1067 /// modulo operation because the sign follows the sign of the dividend which
1070 /// \returns a new APInt value containing the remainder result
1071 APInt urem(const APInt &RHS) const;
1072 uint64_t urem(uint64_t RHS) const;
1074 /// Function for signed remainder operation.
1076 /// Signed remainder operation on APInt.
1077 APInt srem(const APInt &RHS) const;
1078 int64_t srem(int64_t RHS) const;
1080 /// Dual division/remainder interface.
1082 /// Sometimes it is convenient to divide two APInt values and obtain both the
1083 /// quotient and remainder. This function does both operations in the same
1084 /// computation making it a little more efficient. The pair of input arguments
1085 /// may overlap with the pair of output arguments. It is safe to call
1086 /// udivrem(X, Y, X, Y), for example.
1087 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1089 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1090 uint64_t &Remainder);
1092 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1094 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
1095 int64_t &Remainder);
1097 // Operations that return overflow indicators.
1098 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
1099 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
1100 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
1101 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
1102 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
1103 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
1104 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
1105 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
1106 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1108 // Operations that saturate
1109 APInt sadd_sat(const APInt &RHS) const;
1110 APInt uadd_sat(const APInt &RHS) const;
1111 APInt ssub_sat(const APInt &RHS) const;
1112 APInt usub_sat(const APInt &RHS) const;
1114 /// Array-indexing support.
1116 /// \returns the bit value at bitPosition
1117 bool operator[](unsigned bitPosition) const {
1118 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
1119 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
1123 /// \name Comparison Operators
1126 /// Equality operator.
1128 /// Compares this APInt with RHS for the validity of the equality
1130 bool operator==(const APInt &RHS) const {
1131 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
1133 return U.VAL == RHS.U.VAL;
1134 return EqualSlowCase(RHS);
1137 /// Equality operator.
1139 /// Compares this APInt with a uint64_t for the validity of the equality
1142 /// \returns true if *this == Val
1143 bool operator==(uint64_t Val) const {
1144 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1147 /// Equality comparison.
1149 /// Compares this APInt with RHS for the validity of the equality
1152 /// \returns true if *this == Val
1153 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1155 /// Inequality operator.
1157 /// Compares this APInt with RHS for the validity of the inequality
1160 /// \returns true if *this != Val
1161 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1163 /// Inequality operator.
1165 /// Compares this APInt with a uint64_t for the validity of the inequality
1168 /// \returns true if *this != Val
1169 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1171 /// Inequality comparison
1173 /// Compares this APInt with RHS for the validity of the inequality
1176 /// \returns true if *this != Val
1177 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1179 /// Unsigned less than comparison
1181 /// Regards both *this and RHS as unsigned quantities and compares them for
1182 /// the validity of the less-than relationship.
1184 /// \returns true if *this < RHS when both are considered unsigned.
1185 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1187 /// Unsigned less than comparison
1189 /// Regards both *this as an unsigned quantity and compares it with RHS for
1190 /// the validity of the less-than relationship.
1192 /// \returns true if *this < RHS when considered unsigned.
1193 bool ult(uint64_t RHS) const {
1194 // Only need to check active bits if not a single word.
1195 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1198 /// Signed less than comparison
1200 /// Regards both *this and RHS as signed quantities and compares them for
1201 /// validity of the less-than relationship.
1203 /// \returns true if *this < RHS when both are considered signed.
1204 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1206 /// Signed less than comparison
1208 /// Regards both *this as a signed quantity and compares it with RHS for
1209 /// the validity of the less-than relationship.
1211 /// \returns true if *this < RHS when considered signed.
1212 bool slt(int64_t RHS) const {
1213 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1214 : getSExtValue() < RHS;
1217 /// Unsigned less or equal comparison
1219 /// Regards both *this and RHS as unsigned quantities and compares them for
1220 /// validity of the less-or-equal relationship.
1222 /// \returns true if *this <= RHS when both are considered unsigned.
1223 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1225 /// Unsigned less or equal comparison
1227 /// Regards both *this as an unsigned quantity and compares it with RHS for
1228 /// the validity of the less-or-equal relationship.
1230 /// \returns true if *this <= RHS when considered unsigned.
1231 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1233 /// Signed less or equal comparison
1235 /// Regards both *this and RHS as signed quantities and compares them for
1236 /// validity of the less-or-equal relationship.
1238 /// \returns true if *this <= RHS when both are considered signed.
1239 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1241 /// Signed less or equal comparison
1243 /// Regards both *this as a signed quantity and compares it with RHS for the
1244 /// validity of the less-or-equal relationship.
1246 /// \returns true if *this <= RHS when considered signed.
1247 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1249 /// Unsigned greather than comparison
1251 /// Regards both *this and RHS as unsigned quantities and compares them for
1252 /// the validity of the greater-than relationship.
1254 /// \returns true if *this > RHS when both are considered unsigned.
1255 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1257 /// Unsigned greater than comparison
1259 /// Regards both *this as an unsigned quantity and compares it with RHS for
1260 /// the validity of the greater-than relationship.
1262 /// \returns true if *this > RHS when considered unsigned.
1263 bool ugt(uint64_t RHS) const {
1264 // Only need to check active bits if not a single word.
1265 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1268 /// Signed greather than comparison
1270 /// Regards both *this and RHS as signed quantities and compares them for the
1271 /// validity of the greater-than relationship.
1273 /// \returns true if *this > RHS when both are considered signed.
1274 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1276 /// Signed greater than comparison
1278 /// Regards both *this as a signed quantity and compares it with RHS for
1279 /// the validity of the greater-than relationship.
1281 /// \returns true if *this > RHS when considered signed.
1282 bool sgt(int64_t RHS) const {
1283 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1284 : getSExtValue() > RHS;
1287 /// Unsigned greater or equal comparison
1289 /// Regards both *this and RHS as unsigned quantities and compares them for
1290 /// validity of the greater-or-equal relationship.
1292 /// \returns true if *this >= RHS when both are considered unsigned.
1293 bool uge(const APInt &RHS) const { return !ult(RHS); }
1295 /// Unsigned greater or equal comparison
1297 /// Regards both *this as an unsigned quantity and compares it with RHS for
1298 /// the validity of the greater-or-equal relationship.
1300 /// \returns true if *this >= RHS when considered unsigned.
1301 bool uge(uint64_t RHS) const { return !ult(RHS); }
1303 /// Signed greater or equal comparison
1305 /// Regards both *this and RHS as signed quantities and compares them for
1306 /// validity of the greater-or-equal relationship.
1308 /// \returns true if *this >= RHS when both are considered signed.
1309 bool sge(const APInt &RHS) const { return !slt(RHS); }
1311 /// Signed greater or equal comparison
1313 /// Regards both *this as a signed quantity and compares it with RHS for
1314 /// the validity of the greater-or-equal relationship.
1316 /// \returns true if *this >= RHS when considered signed.
1317 bool sge(int64_t RHS) const { return !slt(RHS); }
1319 /// This operation tests if there are any pairs of corresponding bits
1320 /// between this APInt and RHS that are both set.
1321 bool intersects(const APInt &RHS) const {
1322 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1324 return (U.VAL & RHS.U.VAL) != 0;
1325 return intersectsSlowCase(RHS);
1328 /// This operation checks that all bits set in this APInt are also set in RHS.
1329 bool isSubsetOf(const APInt &RHS) const {
1330 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1332 return (U.VAL & ~RHS.U.VAL) == 0;
1333 return isSubsetOfSlowCase(RHS);
1337 /// \name Resizing Operators
1340 /// Truncate to new width.
1342 /// Truncate the APInt to a specified width. It is an error to specify a width
1343 /// that is greater than or equal to the current width.
1344 APInt trunc(unsigned width) const;
1346 /// Sign extend to a new width.
1348 /// This operation sign extends the APInt to a new width. If the high order
1349 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1350 /// It is an error to specify a width that is less than or equal to the
1352 APInt sext(unsigned width) const;
1354 /// Zero extend to a new width.
1356 /// This operation zero extends the APInt to a new width. The high order bits
1357 /// are filled with 0 bits. It is an error to specify a width that is less
1358 /// than or equal to the current width.
1359 APInt zext(unsigned width) const;
1361 /// Sign extend or truncate to width
1363 /// Make this APInt have the bit width given by \p width. The value is sign
1364 /// extended, truncated, or left alone to make it that width.
1365 APInt sextOrTrunc(unsigned width) const;
1367 /// Zero extend or truncate to width
1369 /// Make this APInt have the bit width given by \p width. The value is zero
1370 /// extended, truncated, or left alone to make it that width.
1371 APInt zextOrTrunc(unsigned width) const;
1373 /// Sign extend or truncate to width
1375 /// Make this APInt have the bit width given by \p width. The value is sign
1376 /// extended, or left alone to make it that width.
1377 APInt sextOrSelf(unsigned width) const;
1379 /// Zero extend or truncate to width
1381 /// Make this APInt have the bit width given by \p width. The value is zero
1382 /// extended, or left alone to make it that width.
1383 APInt zextOrSelf(unsigned width) const;
1386 /// \name Bit Manipulation Operators
1389 /// Set every bit to 1.
1392 U.VAL = WORDTYPE_MAX;
1394 // Set all the bits in all the words.
1395 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1396 // Clear the unused ones
1400 /// Set a given bit to 1.
1402 /// Set the given bit to 1 whose position is given as "bitPosition".
1403 void setBit(unsigned BitPosition) {
1404 assert(BitPosition < BitWidth && "BitPosition out of range");
1405 WordType Mask = maskBit(BitPosition);
1409 U.pVal[whichWord(BitPosition)] |= Mask;
1412 /// Set the sign bit to 1.
1414 setBit(BitWidth - 1);
1417 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1418 void setBits(unsigned loBit, unsigned hiBit) {
1419 assert(hiBit <= BitWidth && "hiBit out of range");
1420 assert(loBit <= BitWidth && "loBit out of range");
1421 assert(loBit <= hiBit && "loBit greater than hiBit");
1424 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1425 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1432 setBitsSlowCase(loBit, hiBit);
1436 /// Set the top bits starting from loBit.
1437 void setBitsFrom(unsigned loBit) {
1438 return setBits(loBit, BitWidth);
1441 /// Set the bottom loBits bits.
1442 void setLowBits(unsigned loBits) {
1443 return setBits(0, loBits);
1446 /// Set the top hiBits bits.
1447 void setHighBits(unsigned hiBits) {
1448 return setBits(BitWidth - hiBits, BitWidth);
1451 /// Set every bit to 0.
1452 void clearAllBits() {
1456 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1459 /// Set a given bit to 0.
1461 /// Set the given bit to 0 whose position is given as "bitPosition".
1462 void clearBit(unsigned BitPosition) {
1463 assert(BitPosition < BitWidth && "BitPosition out of range");
1464 WordType Mask = ~maskBit(BitPosition);
1468 U.pVal[whichWord(BitPosition)] &= Mask;
1471 /// Set the sign bit to 0.
1472 void clearSignBit() {
1473 clearBit(BitWidth - 1);
1476 /// Toggle every bit to its opposite value.
1477 void flipAllBits() {
1478 if (isSingleWord()) {
1479 U.VAL ^= WORDTYPE_MAX;
1482 flipAllBitsSlowCase();
1486 /// Toggles a given bit to its opposite value.
1488 /// Toggle a given bit to its opposite value whose position is given
1489 /// as "bitPosition".
1490 void flipBit(unsigned bitPosition);
1492 /// Negate this APInt in place.
1498 /// Insert the bits from a smaller APInt starting at bitPosition.
1499 void insertBits(const APInt &SubBits, unsigned bitPosition);
1501 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1502 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1505 /// \name Value Characterization Functions
1508 /// Return the number of bits in the APInt.
1509 unsigned getBitWidth() const { return BitWidth; }
1511 /// Get the number of words.
1513 /// Here one word's bitwidth equals to that of uint64_t.
1515 /// \returns the number of words to hold the integer value of this APInt.
1516 unsigned getNumWords() const { return getNumWords(BitWidth); }
1518 /// Get the number of words.
1520 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1522 /// \returns the number of words to hold the integer value with a given bit
1524 static unsigned getNumWords(unsigned BitWidth) {
1525 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1528 /// Compute the number of active bits in the value
1530 /// This function returns the number of active bits which is defined as the
1531 /// bit width minus the number of leading zeros. This is used in several
1532 /// computations to see how "wide" the value is.
1533 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1535 /// Compute the number of active words in the value of this APInt.
1537 /// This is used in conjunction with getActiveData to extract the raw value of
1539 unsigned getActiveWords() const {
1540 unsigned numActiveBits = getActiveBits();
1541 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1544 /// Get the minimum bit size for this signed APInt
1546 /// Computes the minimum bit width for this APInt while considering it to be a
1547 /// signed (and probably negative) value. If the value is not negative, this
1548 /// function returns the same value as getActiveBits()+1. Otherwise, it
1549 /// returns the smallest bit width that will retain the negative value. For
1550 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1551 /// for -1, this function will always return 1.
1552 unsigned getMinSignedBits() const {
1554 return BitWidth - countLeadingOnes() + 1;
1555 return getActiveBits() + 1;
1558 /// Get zero extended value
1560 /// This method attempts to return the value of this APInt as a zero extended
1561 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1562 /// uint64_t. Otherwise an assertion will result.
1563 uint64_t getZExtValue() const {
1566 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1570 /// Get sign extended value
1572 /// This method attempts to return the value of this APInt as a sign extended
1573 /// int64_t. The bit width must be <= 64 or the value must fit within an
1574 /// int64_t. Otherwise an assertion will result.
1575 int64_t getSExtValue() const {
1577 return SignExtend64(U.VAL, BitWidth);
1578 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1579 return int64_t(U.pVal[0]);
1582 /// Get bits required for string value.
1584 /// This method determines how many bits are required to hold the APInt
1585 /// equivalent of the string given by \p str.
1586 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1588 /// The APInt version of the countLeadingZeros functions in
1591 /// It counts the number of zeros from the most significant bit to the first
1594 /// \returns BitWidth if the value is zero, otherwise returns the number of
1595 /// zeros from the most significant bit to the first one bits.
1596 unsigned countLeadingZeros() const {
1597 if (isSingleWord()) {
1598 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1599 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1601 return countLeadingZerosSlowCase();
1604 /// Count the number of leading one bits.
1606 /// This function is an APInt version of the countLeadingOnes
1607 /// functions in MathExtras.h. It counts the number of ones from the most
1608 /// significant bit to the first zero bit.
1610 /// \returns 0 if the high order bit is not set, otherwise returns the number
1611 /// of 1 bits from the most significant to the least
1612 unsigned countLeadingOnes() const {
1614 return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1615 return countLeadingOnesSlowCase();
1618 /// Computes the number of leading bits of this APInt that are equal to its
1620 unsigned getNumSignBits() const {
1621 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1624 /// Count the number of trailing zero bits.
1626 /// This function is an APInt version of the countTrailingZeros
1627 /// functions in MathExtras.h. It counts the number of zeros from the least
1628 /// significant bit to the first set bit.
1630 /// \returns BitWidth if the value is zero, otherwise returns the number of
1631 /// zeros from the least significant bit to the first one bit.
1632 unsigned countTrailingZeros() const {
1634 return std::min(unsigned(llvm::countTrailingZeros(U.VAL)), BitWidth);
1635 return countTrailingZerosSlowCase();
1638 /// Count the number of trailing one bits.
1640 /// This function is an APInt version of the countTrailingOnes
1641 /// functions in MathExtras.h. It counts the number of ones from the least
1642 /// significant bit to the first zero bit.
1644 /// \returns BitWidth if the value is all ones, otherwise returns the number
1645 /// of ones from the least significant bit to the first zero bit.
1646 unsigned countTrailingOnes() const {
1648 return llvm::countTrailingOnes(U.VAL);
1649 return countTrailingOnesSlowCase();
1652 /// Count the number of bits set.
1654 /// This function is an APInt version of the countPopulation functions
1655 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1657 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1658 unsigned countPopulation() const {
1660 return llvm::countPopulation(U.VAL);
1661 return countPopulationSlowCase();
1665 /// \name Conversion Functions
1667 void print(raw_ostream &OS, bool isSigned) const;
1669 /// Converts an APInt to a string and append it to Str. Str is commonly a
1671 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1672 bool formatAsCLiteral = false) const;
1674 /// Considers the APInt to be unsigned and converts it into a string in the
1675 /// radix given. The radix can be 2, 8, 10 16, or 36.
1676 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1677 toString(Str, Radix, false, false);
1680 /// Considers the APInt to be signed and converts it into a string in the
1681 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1682 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1683 toString(Str, Radix, true, false);
1686 /// Return the APInt as a std::string.
1688 /// Note that this is an inefficient method. It is better to pass in a
1689 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1691 std::string toString(unsigned Radix, bool Signed) const;
1693 /// \returns a byte-swapped representation of this APInt Value.
1694 APInt byteSwap() const;
1696 /// \returns the value with the bit representation reversed of this APInt
1698 APInt reverseBits() const;
1700 /// Converts this APInt to a double value.
1701 double roundToDouble(bool isSigned) const;
1703 /// Converts this unsigned APInt to a double value.
1704 double roundToDouble() const { return roundToDouble(false); }
1706 /// Converts this signed APInt to a double value.
1707 double signedRoundToDouble() const { return roundToDouble(true); }
1709 /// Converts APInt bits to a double
1711 /// The conversion does not do a translation from integer to double, it just
1712 /// re-interprets the bits as a double. Note that it is valid to do this on
1713 /// any bit width. Exactly 64 bits will be translated.
1714 double bitsToDouble() const {
1715 return BitsToDouble(getWord(0));
1718 /// Converts APInt bits to a double
1720 /// The conversion does not do a translation from integer to float, it just
1721 /// re-interprets the bits as a float. Note that it is valid to do this on
1722 /// any bit width. Exactly 32 bits will be translated.
1723 float bitsToFloat() const {
1724 return BitsToFloat(getWord(0));
1727 /// Converts a double to APInt bits.
1729 /// The conversion does not do a translation from double to integer, it just
1730 /// re-interprets the bits of the double.
1731 static APInt doubleToBits(double V) {
1732 return APInt(sizeof(double) * CHAR_BIT, DoubleToBits(V));
1735 /// Converts a float to APInt bits.
1737 /// The conversion does not do a translation from float to integer, it just
1738 /// re-interprets the bits of the float.
1739 static APInt floatToBits(float V) {
1740 return APInt(sizeof(float) * CHAR_BIT, FloatToBits(V));
1744 /// \name Mathematics Operations
1747 /// \returns the floor log base 2 of this APInt.
1748 unsigned logBase2() const { return getActiveBits() - 1; }
1750 /// \returns the ceil log base 2 of this APInt.
1751 unsigned ceilLogBase2() const {
1754 return temp.getActiveBits();
1757 /// \returns the nearest log base 2 of this APInt. Ties round up.
1759 /// NOTE: When we have a BitWidth of 1, we define:
1761 /// log2(0) = UINT32_MAX
1764 /// to get around any mathematical concerns resulting from
1765 /// referencing 2 in a space where 2 does no exist.
1766 unsigned nearestLogBase2() const {
1767 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1768 // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to
1773 // Handle the zero case.
1777 // The non-zero case is handled by computing:
1779 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1781 // where x[i] is referring to the value of the ith bit of x.
1782 unsigned lg = logBase2();
1783 return lg + unsigned((*this)[lg - 1]);
1786 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1788 int32_t exactLogBase2() const {
1794 /// Compute the square root
1797 /// Get the absolute value;
1799 /// If *this is < 0 then return -(*this), otherwise *this;
1806 /// \returns the multiplicative inverse for a given modulo.
1807 APInt multiplicativeInverse(const APInt &modulo) const;
1810 /// \name Support for division by constant
1813 /// Calculate the magic number for signed division by a constant.
1817 /// Calculate the magic number for unsigned division by a constant.
1819 mu magicu(unsigned LeadingZeros = 0) const;
1822 /// \name Building-block Operations for APInt and APFloat
1825 // These building block operations operate on a representation of arbitrary
1826 // precision, two's-complement, bignum integer values. They should be
1827 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1828 // generally a pointer to the base of an array of integer parts, representing
1829 // an unsigned bignum, and a count of how many parts there are.
1831 /// Sets the least significant part of a bignum to the input value, and zeroes
1832 /// out higher parts.
1833 static void tcSet(WordType *, WordType, unsigned);
1835 /// Assign one bignum to another.
1836 static void tcAssign(WordType *, const WordType *, unsigned);
1838 /// Returns true if a bignum is zero, false otherwise.
1839 static bool tcIsZero(const WordType *, unsigned);
1841 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1842 static int tcExtractBit(const WordType *, unsigned bit);
1844 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1845 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1846 /// significant bit of DST. All high bits above srcBITS in DST are
1848 static void tcExtract(WordType *, unsigned dstCount,
1849 const WordType *, unsigned srcBits,
1852 /// Set the given bit of a bignum. Zero-based.
1853 static void tcSetBit(WordType *, unsigned bit);
1855 /// Clear the given bit of a bignum. Zero-based.
1856 static void tcClearBit(WordType *, unsigned bit);
1858 /// Returns the bit number of the least or most significant set bit of a
1859 /// number. If the input number has no bits set -1U is returned.
1860 static unsigned tcLSB(const WordType *, unsigned n);
1861 static unsigned tcMSB(const WordType *parts, unsigned n);
1863 /// Negate a bignum in-place.
1864 static void tcNegate(WordType *, unsigned);
1866 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1867 static WordType tcAdd(WordType *, const WordType *,
1868 WordType carry, unsigned);
1869 /// DST += RHS. Returns the carry flag.
1870 static WordType tcAddPart(WordType *, WordType, unsigned);
1872 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1873 static WordType tcSubtract(WordType *, const WordType *,
1874 WordType carry, unsigned);
1875 /// DST -= RHS. Returns the carry flag.
1876 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1878 /// DST += SRC * MULTIPLIER + PART if add is true
1879 /// DST = SRC * MULTIPLIER + PART if add is false
1881 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1882 /// start at the same point, i.e. DST == SRC.
1884 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1885 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1886 /// result, and if all of the omitted higher parts were zero return zero,
1887 /// otherwise overflow occurred and return one.
1888 static int tcMultiplyPart(WordType *dst, const WordType *src,
1889 WordType multiplier, WordType carry,
1890 unsigned srcParts, unsigned dstParts,
1893 /// DST = LHS * RHS, where DST has the same width as the operands and is
1894 /// filled with the least significant parts of the result. Returns one if
1895 /// overflow occurred, otherwise zero. DST must be disjoint from both
1897 static int tcMultiply(WordType *, const WordType *, const WordType *,
1900 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1901 /// operands. No overflow occurs. DST must be disjoint from both operands.
1902 static void tcFullMultiply(WordType *, const WordType *,
1903 const WordType *, unsigned, unsigned);
1905 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1906 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1907 /// REMAINDER to the remainder, return zero. i.e.
1909 /// OLD_LHS = RHS * LHS + REMAINDER
1911 /// SCRATCH is a bignum of the same size as the operands and result for use by
1912 /// the routine; its contents need not be initialized and are destroyed. LHS,
1913 /// REMAINDER and SCRATCH must be distinct.
1914 static int tcDivide(WordType *lhs, const WordType *rhs,
1915 WordType *remainder, WordType *scratch,
1918 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1919 /// restrictions on Count.
1920 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1922 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1923 /// restrictions on Count.
1924 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1926 /// The obvious AND, OR and XOR and complement operations.
1927 static void tcAnd(WordType *, const WordType *, unsigned);
1928 static void tcOr(WordType *, const WordType *, unsigned);
1929 static void tcXor(WordType *, const WordType *, unsigned);
1930 static void tcComplement(WordType *, unsigned);
1932 /// Comparison (unsigned) of two bignums.
1933 static int tcCompare(const WordType *, const WordType *, unsigned);
1935 /// Increment a bignum in-place. Return the carry flag.
1936 static WordType tcIncrement(WordType *dst, unsigned parts) {
1937 return tcAddPart(dst, 1, parts);
1940 /// Decrement a bignum in-place. Return the borrow flag.
1941 static WordType tcDecrement(WordType *dst, unsigned parts) {
1942 return tcSubtractPart(dst, 1, parts);
1945 /// Set the least significant BITS and clear the rest.
1946 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits);
1954 /// Magic data for optimising signed division by a constant.
1956 APInt m; ///< magic number
1957 unsigned s; ///< shift amount
1960 /// Magic data for optimising unsigned division by a constant.
1962 APInt m; ///< magic number
1963 bool a; ///< add indicator
1964 unsigned s; ///< shift amount
1967 inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1969 inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1971 /// Unary bitwise complement operator.
1973 /// \returns an APInt that is the bitwise complement of \p v.
1974 inline APInt operator~(APInt v) {
1979 inline APInt operator&(APInt a, const APInt &b) {
1984 inline APInt operator&(const APInt &a, APInt &&b) {
1986 return std::move(b);
1989 inline APInt operator&(APInt a, uint64_t RHS) {
1994 inline APInt operator&(uint64_t LHS, APInt b) {
1999 inline APInt operator|(APInt a, const APInt &b) {
2004 inline APInt operator|(const APInt &a, APInt &&b) {
2006 return std::move(b);
2009 inline APInt operator|(APInt a, uint64_t RHS) {
2014 inline APInt operator|(uint64_t LHS, APInt b) {
2019 inline APInt operator^(APInt a, const APInt &b) {
2024 inline APInt operator^(const APInt &a, APInt &&b) {
2026 return std::move(b);
2029 inline APInt operator^(APInt a, uint64_t RHS) {
2034 inline APInt operator^(uint64_t LHS, APInt b) {
2039 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
2044 inline APInt operator-(APInt v) {
2049 inline APInt operator+(APInt a, const APInt &b) {
2054 inline APInt operator+(const APInt &a, APInt &&b) {
2056 return std::move(b);
2059 inline APInt operator+(APInt a, uint64_t RHS) {
2064 inline APInt operator+(uint64_t LHS, APInt b) {
2069 inline APInt operator-(APInt a, const APInt &b) {
2074 inline APInt operator-(const APInt &a, APInt &&b) {
2077 return std::move(b);
2080 inline APInt operator-(APInt a, uint64_t RHS) {
2085 inline APInt operator-(uint64_t LHS, APInt b) {
2091 inline APInt operator*(APInt a, uint64_t RHS) {
2096 inline APInt operator*(uint64_t LHS, APInt b) {
2102 namespace APIntOps {
2104 /// Determine the smaller of two APInts considered to be signed.
2105 inline const APInt &smin(const APInt &A, const APInt &B) {
2106 return A.slt(B) ? A : B;
2109 /// Determine the larger of two APInts considered to be signed.
2110 inline const APInt &smax(const APInt &A, const APInt &B) {
2111 return A.sgt(B) ? A : B;
2114 /// Determine the smaller of two APInts considered to be signed.
2115 inline const APInt &umin(const APInt &A, const APInt &B) {
2116 return A.ult(B) ? A : B;
2119 /// Determine the larger of two APInts considered to be unsigned.
2120 inline const APInt &umax(const APInt &A, const APInt &B) {
2121 return A.ugt(B) ? A : B;
2124 /// Compute GCD of two unsigned APInt values.
2126 /// This function returns the greatest common divisor of the two APInt values
2127 /// using Stein's algorithm.
2129 /// \returns the greatest common divisor of A and B.
2130 APInt GreatestCommonDivisor(APInt A, APInt B);
2132 /// Converts the given APInt to a double value.
2134 /// Treats the APInt as an unsigned value for conversion purposes.
2135 inline double RoundAPIntToDouble(const APInt &APIVal) {
2136 return APIVal.roundToDouble();
2139 /// Converts the given APInt to a double value.
2141 /// Treats the APInt as a signed value for conversion purposes.
2142 inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2143 return APIVal.signedRoundToDouble();
2146 /// Converts the given APInt to a float vlalue.
2147 inline float RoundAPIntToFloat(const APInt &APIVal) {
2148 return float(RoundAPIntToDouble(APIVal));
2151 /// Converts the given APInt to a float value.
2153 /// Treast the APInt as a signed value for conversion purposes.
2154 inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2155 return float(APIVal.signedRoundToDouble());
2158 /// Converts the given double value into a APInt.
2160 /// This function convert a double value to an APInt value.
2161 APInt RoundDoubleToAPInt(double Double, unsigned width);
2163 /// Converts a float value into a APInt.
2165 /// Converts a float value into an APInt value.
2166 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2167 return RoundDoubleToAPInt(double(Float), width);
2170 /// Return A unsign-divided by B, rounded by the given rounding mode.
2171 APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2173 /// Return A sign-divided by B, rounded by the given rounding mode.
2174 APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2176 /// Let q(n) = An^2 + Bn + C, and BW = bit width of the value range
2177 /// (e.g. 32 for i32).
2178 /// This function finds the smallest number n, such that
2179 /// (a) n >= 0 and q(n) = 0, or
2180 /// (b) n >= 1 and q(n-1) and q(n), when evaluated in the set of all
2181 /// integers, belong to two different intervals [Rk, Rk+R),
2182 /// where R = 2^BW, and k is an integer.
2183 /// The idea here is to find when q(n) "overflows" 2^BW, while at the
2184 /// same time "allowing" subtraction. In unsigned modulo arithmetic a
2185 /// subtraction (treated as addition of negated numbers) would always
2186 /// count as an overflow, but here we want to allow values to decrease
2187 /// and increase as long as they are within the same interval.
2188 /// Specifically, adding of two negative numbers should not cause an
2189 /// overflow (as long as the magnitude does not exceed the bith width).
2190 /// On the other hand, given a positive number, adding a negative
2191 /// number to it can give a negative result, which would cause the
2192 /// value to go from [-2^BW, 0) to [0, 2^BW). In that sense, zero is
2193 /// treated as a special case of an overflow.
2195 /// This function returns None if after finding k that minimizes the
2196 /// positive solution to q(n) = kR, both solutions are contained between
2197 /// two consecutive integers.
2199 /// There are cases where q(n) > T, and q(n+1) < T (assuming evaluation
2200 /// in arithmetic modulo 2^BW, and treating the values as signed) by the
2201 /// virtue of *signed* overflow. This function will *not* find such an n,
2202 /// however it may find a value of n satisfying the inequalities due to
2203 /// an *unsigned* overflow (if the values are treated as unsigned).
2204 /// To find a solution for a signed overflow, treat it as a problem of
2205 /// finding an unsigned overflow with a range with of BW-1.
2207 /// The returned value may have a different bit width from the input
2209 Optional<APInt> SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
2210 unsigned RangeWidth);
2211 } // End of APIntOps namespace
2213 // See friend declaration above. This additional declaration is required in
2214 // order to compile LLVM with IBM xlC compiler.
2215 hash_code hash_value(const APInt &Arg);
2216 } // End of llvm namespace