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/ADT/ArrayRef.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/MathExtras.h"
29 class FoldingSetNodeID;
36 class SmallVectorImpl;
38 // An unsigned host type used as a single part of a multi-part
40 typedef uint64_t integerPart;
42 const unsigned int host_char_bit = 8;
43 const unsigned int integerPartWidth = host_char_bit *
44 static_cast<unsigned int>(sizeof(integerPart));
46 //===----------------------------------------------------------------------===//
48 //===----------------------------------------------------------------------===//
50 /// \brief Class for arbitrary precision integers.
52 /// APInt is a functional replacement for common case unsigned integer type like
53 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
54 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
55 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
56 /// and methods to manipulate integer values of any bit-width. It supports both
57 /// the typical integer arithmetic and comparison operations as well as bitwise
60 /// The class has several invariants worth noting:
61 /// * All bit, byte, and word positions are zero-based.
62 /// * Once the bit width is set, it doesn't change except by the Truncate,
63 /// SignExtend, or ZeroExtend operations.
64 /// * All binary operators must be on APInt instances of the same bit width.
65 /// Attempting to use these operators on instances with different bit
66 /// widths will yield an assertion.
67 /// * The value is stored canonically as an unsigned value. For operations
68 /// where it makes a difference, there are both signed and unsigned variants
69 /// of the operation. For example, sdiv and udiv. However, because the bit
70 /// widths must be the same, operations such as Mul and Add produce the same
71 /// results regardless of whether the values are interpreted as signed or
73 /// * In general, the class tries to follow the style of computation that LLVM
74 /// uses in its IR. This simplifies its use for LLVM.
77 unsigned BitWidth; ///< The number of bits in this APInt.
79 /// This union is used to store the integer value. When the
80 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
82 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
83 uint64_t *pVal; ///< Used to store the >64 bits integer value.
86 /// This enum is used to hold the constants we needed for APInt.
89 APINT_BITS_PER_WORD = static_cast<unsigned int>(sizeof(uint64_t)) *
91 /// Byte size of a word
92 APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t))
95 /// \brief Fast internal constructor
97 /// This constructor is used only internally for speed of construction of
98 /// temporaries. It is unsafe for general use so it is not public.
99 APInt(uint64_t* val, unsigned bits) : BitWidth(bits), pVal(val) { }
101 /// \brief Determine if this APInt just has one word to store value.
103 /// \returns true if the number of bits <= 64, false otherwise.
104 bool isSingleWord() const {
105 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 to "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 % APINT_BITS_PER_WORD;
143 // If all bits are used, we want to leave the value alone. This also
144 // avoids the undefined behavior of >> when the shift is the same size as
145 // the word size (64).
148 // Mask out the high bits.
149 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
153 pVal[getNumWords() - 1] &= mask;
157 /// \brief Get the word corresponding to a bit position
158 /// \returns the corresponding word for the specified bit position.
159 uint64_t getWord(unsigned bitPosition) const {
160 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
163 /// \brief Convert a char array into an APInt
165 /// \param radix 2, 8, 10, 16, or 36
166 /// Converts a string into a number. The string must be non-empty
167 /// and well-formed as a number of the given base. The bit-width
168 /// must be sufficient to hold the result.
170 /// This is used by the constructors that take string arguments.
172 /// StringRef::getAsInteger is superficially similar but (1) does
173 /// not assume that the string is well-formed and (2) grows the
174 /// result to hold the input.
175 void fromString(unsigned numBits, StringRef str, uint8_t radix);
177 /// \brief An internal division function for dividing APInts.
179 /// This is used by the toString method to divide by the radix. It simply
180 /// provides a more convenient form of divide for internal use since KnuthDiv
181 /// has specific constraints on its inputs. If those constraints are not met
182 /// then it provides a simpler form of divide.
183 static void divide(const APInt LHS, unsigned lhsWords,
184 const APInt &RHS, unsigned rhsWords,
185 APInt *Quotient, APInt *Remainder);
187 /// out-of-line slow case for inline constructor
188 void initSlowCase(unsigned numBits, uint64_t val, bool isSigned);
190 /// shared code between two array constructors
191 void initFromArray(ArrayRef<uint64_t> array);
193 /// out-of-line slow case for inline copy constructor
194 void initSlowCase(const APInt& that);
196 /// out-of-line slow case for shl
197 APInt shlSlowCase(unsigned shiftAmt) const;
199 /// out-of-line slow case for operator&
200 APInt AndSlowCase(const APInt& RHS) const;
202 /// out-of-line slow case for operator|
203 APInt OrSlowCase(const APInt& RHS) const;
205 /// out-of-line slow case for operator^
206 APInt XorSlowCase(const APInt& RHS) const;
208 /// out-of-line slow case for operator=
209 APInt& AssignSlowCase(const APInt& RHS);
211 /// out-of-line slow case for operator==
212 bool EqualSlowCase(const APInt& RHS) const;
214 /// out-of-line slow case for operator==
215 bool EqualSlowCase(uint64_t Val) const;
217 /// out-of-line slow case for countLeadingZeros
218 unsigned countLeadingZerosSlowCase() const;
220 /// out-of-line slow case for countTrailingOnes
221 unsigned countTrailingOnesSlowCase() const;
223 /// out-of-line slow case for countPopulation
224 unsigned countPopulationSlowCase() const;
227 /// \name Constructors
230 /// \brief Create a new APInt of numBits width, initialized as val.
232 /// If isSigned is true then val is treated as if it were a signed value
233 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
234 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
235 /// the range of val are zero filled).
237 /// \param numBits the bit width of the constructed APInt
238 /// \param val the initial value of the APInt
239 /// \param isSigned how to treat signedness of val
240 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
241 : BitWidth(numBits), VAL(0) {
242 assert(BitWidth && "bitwidth too small");
246 initSlowCase(numBits, val, isSigned);
250 /// \brief Construct an APInt of numBits width, initialized as bigVal[].
252 /// Note that bigVal.size() can be smaller or larger than the corresponding
253 /// bit width but any extraneous bits will be dropped.
255 /// \param numBits the bit width of the constructed APInt
256 /// \param bigVal a sequence of words to form the initial value of the APInt
257 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
259 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
260 /// deprecated because this constructor is prone to ambiguity with the
261 /// APInt(unsigned, uint64_t, bool) constructor.
263 /// If this overload is ever deleted, care should be taken to prevent calls
264 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
266 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
268 /// \brief Construct an APInt from a string representation.
270 /// This constructor interprets the string \p str in the given radix. The
271 /// interpretation stops when the first character that is not suitable for the
272 /// radix is encountered, or the end of the string. Acceptable radix values
273 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
274 /// string to require more bits than numBits.
276 /// \param numBits the bit width of the constructed APInt
277 /// \param str the string to be interpreted
278 /// \param radix the radix to use for the conversion
279 APInt(unsigned numBits, StringRef str, uint8_t radix);
281 /// Simply makes *this a copy of that.
282 /// @brief Copy Constructor.
283 APInt(const APInt& that)
284 : BitWidth(that.BitWidth), VAL(0) {
285 assert(BitWidth && "bitwidth too small");
292 #if LLVM_HAS_RVALUE_REFERENCES
293 /// \brief Move Constructor.
294 APInt(APInt&& that) : BitWidth(that.BitWidth), VAL(that.VAL) {
299 /// \brief Destructor.
305 /// \brief Default constructor that creates an uninitialized APInt.
307 /// This is useful for object deserialization (pair this with the static
309 explicit APInt() : BitWidth(1) {}
311 /// Used to insert APInt objects, or objects that contain APInt objects, into
313 void Profile(FoldingSetNodeID& id) const;
316 /// \name Value Tests
319 /// \brief Determine sign of this APInt.
321 /// This tests the high bit of this APInt to determine if it is set.
323 /// \returns true if this APInt is negative, false otherwise
324 bool isNegative() const {
325 return (*this)[BitWidth - 1];
328 /// \brief Determine if this APInt Value is non-negative (>= 0)
330 /// This tests the high bit of the APInt to determine if it is unset.
331 bool isNonNegative() const {
332 return !isNegative();
335 /// \brief Determine if this APInt Value is positive.
337 /// This tests if the value of this APInt is positive (> 0). Note
338 /// that 0 is not a positive value.
340 /// \returns true if this APInt is positive.
341 bool isStrictlyPositive() const {
342 return isNonNegative() && !!*this;
345 /// \brief Determine if all bits are set
347 /// This checks to see if the value has all bits of the APInt are set or not.
348 bool isAllOnesValue() const {
349 return countPopulation() == BitWidth;
352 /// \brief Determine if this is the largest unsigned value.
354 /// This checks to see if the value of this APInt is the maximum unsigned
355 /// value for the APInt's bit width.
356 bool isMaxValue() const {
357 return countPopulation() == BitWidth;
360 /// \brief Determine if this is the largest signed value.
362 /// This checks to see if the value of this APInt is the maximum signed
363 /// value for the APInt's bit width.
364 bool isMaxSignedValue() const {
365 return BitWidth == 1 ? VAL == 0 :
366 !isNegative() && countPopulation() == BitWidth - 1;
369 /// \brief Determine if this is the smallest unsigned value.
371 /// This checks to see if the value of this APInt is the minimum unsigned
372 /// value for the APInt's bit width.
373 bool isMinValue() const {
377 /// \brief Determine if this is the smallest signed value.
379 /// This checks to see if the value of this APInt is the minimum signed
380 /// value for the APInt's bit width.
381 bool isMinSignedValue() const {
382 return BitWidth == 1 ? VAL == 1 : isNegative() && isPowerOf2();
385 /// \brief Check if this APInt has an N-bits unsigned integer value.
386 bool isIntN(unsigned N) const {
387 assert(N && "N == 0 ???");
388 return getActiveBits() <= N;
391 /// \brief Check if this APInt has an N-bits signed integer value.
392 bool isSignedIntN(unsigned N) const {
393 assert(N && "N == 0 ???");
394 return getMinSignedBits() <= N;
397 /// \brief Check if this APInt's value is a power of two greater than zero.
399 /// \returns true if the argument APInt value is a power of two > 0.
400 bool isPowerOf2() const {
402 return isPowerOf2_64(VAL);
403 return countPopulationSlowCase() == 1;
406 /// \brief Check if the APInt's value is returned by getSignBit.
408 /// \returns true if this is the value returned by getSignBit.
409 bool isSignBit() const { return isMinSignedValue(); }
411 /// \brief Convert APInt to a boolean value.
413 /// This converts the APInt to a boolean value as a test against zero.
414 bool getBoolValue() const {
418 /// If this value is smaller than the specified limit, return it, otherwise
419 /// return the limit value. This causes the value to saturate to the limit.
420 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
421 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
422 Limit : getZExtValue();
426 /// \name Value Generators
429 /// \brief Gets maximum unsigned value of APInt for specific bit width.
430 static APInt getMaxValue(unsigned numBits) {
431 return getAllOnesValue(numBits);
434 /// \brief Gets maximum signed value of APInt for a specific bit width.
435 static APInt getSignedMaxValue(unsigned numBits) {
436 APInt API = getAllOnesValue(numBits);
437 API.clearBit(numBits - 1);
441 /// \brief Gets minimum unsigned value of APInt for a specific bit width.
442 static APInt getMinValue(unsigned numBits) {
443 return APInt(numBits, 0);
446 /// \brief Gets minimum signed value of APInt for a specific bit width.
447 static APInt getSignedMinValue(unsigned numBits) {
448 APInt API(numBits, 0);
449 API.setBit(numBits - 1);
453 /// \brief Get the SignBit for a specific bit width.
455 /// This is just a wrapper function of getSignedMinValue(), and it helps code
456 /// readability when we want to get a SignBit.
457 static APInt getSignBit(unsigned BitWidth) {
458 return getSignedMinValue(BitWidth);
461 /// \brief Get the all-ones value.
463 /// \returns the all-ones value for an APInt of the specified bit-width.
464 static APInt getAllOnesValue(unsigned numBits) {
465 return APInt(numBits, UINT64_MAX, true);
468 /// \brief Get the '0' value.
470 /// \returns the '0' value for an APInt of the specified bit-width.
471 static APInt getNullValue(unsigned numBits) {
472 return APInt(numBits, 0);
475 /// \brief Compute an APInt containing numBits highbits from this APInt.
477 /// Get an APInt with the same BitWidth as this APInt, just zero mask
478 /// the low bits and right shift to the least significant bit.
480 /// \returns the high "numBits" bits of this APInt.
481 APInt getHiBits(unsigned numBits) const;
483 /// \brief Compute an APInt containing numBits lowbits from this APInt.
485 /// Get an APInt with the same BitWidth as this APInt, just zero mask
488 /// \returns the low "numBits" bits of this APInt.
489 APInt getLoBits(unsigned numBits) const;
491 /// \brief Return an APInt with exactly one bit set in the result.
492 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
493 APInt Res(numBits, 0);
498 /// \brief Get a value with a block of bits set.
500 /// Constructs an APInt value that has a contiguous range of bits set. The
501 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
502 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
503 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
504 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
506 /// \param numBits the intended bit width of the result
507 /// \param loBit the index of the lowest bit set.
508 /// \param hiBit the index of the highest bit set.
510 /// \returns An APInt value with the requested bits set.
511 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
512 assert(hiBit <= numBits && "hiBit out of range");
513 assert(loBit < numBits && "loBit out of range");
515 return getLowBitsSet(numBits, hiBit) |
516 getHighBitsSet(numBits, numBits-loBit);
517 return getLowBitsSet(numBits, hiBit-loBit).shl(loBit);
520 /// \brief Get a value with high bits set
522 /// Constructs an APInt value that has the top hiBitsSet bits set.
524 /// \param numBits the bitwidth of the result
525 /// \param hiBitsSet the number of high-order bits set in the result.
526 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
527 assert(hiBitsSet <= numBits && "Too many bits to set!");
528 // Handle a degenerate case, to avoid shifting by word size
530 return APInt(numBits, 0);
531 unsigned shiftAmt = numBits - hiBitsSet;
532 // For small values, return quickly
533 if (numBits <= APINT_BITS_PER_WORD)
534 return APInt(numBits, ~0ULL << shiftAmt);
535 return getAllOnesValue(numBits).shl(shiftAmt);
538 /// \brief Get a value with low bits set
540 /// Constructs an APInt value that has the bottom loBitsSet bits set.
542 /// \param numBits the bitwidth of the result
543 /// \param loBitsSet the number of low-order bits set in the result.
544 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
545 assert(loBitsSet <= numBits && "Too many bits to set!");
546 // Handle a degenerate case, to avoid shifting by word size
548 return APInt(numBits, 0);
549 if (loBitsSet == APINT_BITS_PER_WORD)
550 return APInt(numBits, UINT64_MAX);
551 // For small values, return quickly.
552 if (loBitsSet <= APINT_BITS_PER_WORD)
553 return APInt(numBits, UINT64_MAX >> (APINT_BITS_PER_WORD - loBitsSet));
554 return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
557 /// \brief Return a value containing V broadcasted over NewLen bits.
558 static APInt getSplat(unsigned NewLen, const APInt &V) {
559 assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
561 APInt Val = V.zextOrSelf(NewLen);
562 for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
568 /// \brief Determine if two APInts have the same value, after zero-extending
569 /// one of them (if needed!) to ensure that the bit-widths match.
570 static bool isSameValue(const APInt &I1, const APInt &I2) {
571 if (I1.getBitWidth() == I2.getBitWidth())
574 if (I1.getBitWidth() > I2.getBitWidth())
575 return I1 == I2.zext(I1.getBitWidth());
577 return I1.zext(I2.getBitWidth()) == I2;
580 /// \brief Overload to compute a hash_code for an APInt value.
581 friend hash_code hash_value(const APInt &Arg);
583 /// This function returns a pointer to the internal storage of the APInt.
584 /// This is useful for writing out the APInt in binary form without any
586 const uint64_t* getRawData() const {
593 /// \name Unary Operators
596 /// \brief Postfix increment operator.
598 /// \returns a new APInt value representing *this incremented by one
599 const APInt operator++(int) {
605 /// \brief Prefix increment operator.
607 /// \returns *this incremented by one
610 /// \brief Postfix decrement operator.
612 /// \returns a new APInt representing *this decremented by one.
613 const APInt operator--(int) {
619 /// \brief Prefix decrement operator.
621 /// \returns *this decremented by one.
624 /// \brief Unary bitwise complement operator.
626 /// Performs a bitwise complement operation on this APInt.
628 /// \returns an APInt that is the bitwise complement of *this
629 APInt operator~() const {
631 Result.flipAllBits();
635 /// \brief Unary negation operator
637 /// Negates *this using two's complement logic.
639 /// \returns An APInt value representing the negation of *this.
640 APInt operator-() const {
641 return APInt(BitWidth, 0) - (*this);
644 /// \brief Logical negation operator.
646 /// Performs logical negation operation on this APInt.
648 /// \returns true if *this is zero, false otherwise.
649 bool operator!() const {
653 for (unsigned i = 0; i != getNumWords(); ++i)
660 /// \name Assignment Operators
663 /// \brief Copy assignment operator.
665 /// \returns *this after assignment of RHS.
666 APInt& operator=(const APInt& RHS) {
667 // If the bitwidths are the same, we can avoid mucking with memory
668 if (isSingleWord() && RHS.isSingleWord()) {
670 BitWidth = RHS.BitWidth;
671 return clearUnusedBits();
674 return AssignSlowCase(RHS);
677 #if LLVM_HAS_RVALUE_REFERENCES
678 /// @brief Move assignment operator.
679 APInt& operator=(APInt&& that) {
683 BitWidth = that.BitWidth;
692 /// \brief Assignment operator.
694 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
695 /// the bit width, the excess bits are truncated. If the bit width is larger
696 /// than 64, the value is zero filled in the unspecified high order bits.
698 /// \returns *this after assignment of RHS value.
699 APInt& operator=(uint64_t RHS);
701 /// \brief Bitwise AND assignment operator.
703 /// Performs a bitwise AND operation on this APInt and RHS. The result is
704 /// assigned to *this.
706 /// \returns *this after ANDing with RHS.
707 APInt& operator&=(const APInt& RHS);
709 /// \brief Bitwise OR assignment operator.
711 /// Performs a bitwise OR operation on this APInt and RHS. The result is
714 /// \returns *this after ORing with RHS.
715 APInt& operator|=(const APInt& RHS);
717 /// \brief Bitwise OR assignment operator.
719 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
720 /// logically zero-extended or truncated to match the bit-width of
722 APInt& operator|=(uint64_t RHS) {
723 if (isSingleWord()) {
732 /// \brief Bitwise XOR assignment operator.
734 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
735 /// assigned to *this.
737 /// \returns *this after XORing with RHS.
738 APInt& operator^=(const APInt& RHS);
740 /// \brief Multiplication assignment operator.
742 /// Multiplies this APInt by RHS and assigns the result to *this.
745 APInt& operator*=(const APInt& RHS);
747 /// \brief Addition assignment operator.
749 /// Adds RHS to *this and assigns the result to *this.
752 APInt& operator+=(const APInt& RHS);
754 /// \brief Subtraction assignment operator.
756 /// Subtracts RHS from *this and assigns the result to *this.
759 APInt& operator-=(const APInt& RHS);
761 /// \brief Left-shift assignment function.
763 /// Shifts *this left by shiftAmt and assigns the result to *this.
765 /// \returns *this after shifting left by shiftAmt
766 APInt& operator<<=(unsigned shiftAmt) {
767 *this = shl(shiftAmt);
772 /// \name Binary Operators
775 /// \brief Bitwise AND operator.
777 /// Performs a bitwise AND operation on *this and RHS.
779 /// \returns An APInt value representing the bitwise AND of *this and RHS.
780 APInt operator&(const APInt& RHS) const {
781 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
783 return APInt(getBitWidth(), VAL & RHS.VAL);
784 return AndSlowCase(RHS);
786 APInt And(const APInt& RHS) const {
787 return this->operator&(RHS);
790 /// \brief Bitwise OR operator.
792 /// Performs a bitwise OR operation on *this and RHS.
794 /// \returns An APInt value representing the bitwise OR of *this and RHS.
795 APInt operator|(const APInt& RHS) const {
796 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
798 return APInt(getBitWidth(), VAL | RHS.VAL);
799 return OrSlowCase(RHS);
802 /// \brief Bitwise OR function.
804 /// Performs a bitwise or on *this and RHS. This is implemented bny simply
805 /// calling operator|.
807 /// \returns An APInt value representing the bitwise OR of *this and RHS.
808 APInt Or(const APInt& RHS) const {
809 return this->operator|(RHS);
812 /// \brief Bitwise XOR operator.
814 /// Performs a bitwise XOR operation on *this and RHS.
816 /// \returns An APInt value representing the bitwise XOR of *this and RHS.
817 APInt operator^(const APInt& RHS) const {
818 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
820 return APInt(BitWidth, VAL ^ RHS.VAL);
821 return XorSlowCase(RHS);
824 /// \brief Bitwise XOR function.
826 /// Performs a bitwise XOR operation on *this and RHS. This is implemented
827 /// through the usage of operator^.
829 /// \returns An APInt value representing the bitwise XOR of *this and RHS.
830 APInt Xor(const APInt& RHS) const {
831 return this->operator^(RHS);
834 /// \brief Multiplication operator.
836 /// Multiplies this APInt by RHS and returns the result.
837 APInt operator*(const APInt& RHS) const;
839 /// \brief Addition operator.
841 /// Adds RHS to this APInt and returns the result.
842 APInt operator+(const APInt& RHS) const;
843 APInt operator+(uint64_t RHS) const {
844 return (*this) + APInt(BitWidth, RHS);
847 /// \brief Subtraction operator.
849 /// Subtracts RHS from this APInt and returns the result.
850 APInt operator-(const APInt& RHS) const;
851 APInt operator-(uint64_t RHS) const {
852 return (*this) - APInt(BitWidth, RHS);
855 /// \brief Left logical shift operator.
857 /// Shifts this APInt left by \p Bits and returns the result.
858 APInt operator<<(unsigned Bits) const {
862 /// \brief Left logical shift operator.
864 /// Shifts this APInt left by \p Bits and returns the result.
865 APInt operator<<(const APInt &Bits) const {
869 /// \brief Arithmetic right-shift function.
871 /// Arithmetic right-shift this APInt by shiftAmt.
872 APInt ashr(unsigned shiftAmt) const;
874 /// \brief Logical right-shift function.
876 /// Logical right-shift this APInt by shiftAmt.
877 APInt lshr(unsigned shiftAmt) const;
879 /// \brief Left-shift function.
881 /// Left-shift this APInt by shiftAmt.
882 APInt shl(unsigned shiftAmt) const {
883 assert(shiftAmt <= BitWidth && "Invalid shift amount");
884 if (isSingleWord()) {
885 if (shiftAmt >= BitWidth)
886 return APInt(BitWidth, 0); // avoid undefined shift results
887 return APInt(BitWidth, VAL << shiftAmt);
889 return shlSlowCase(shiftAmt);
892 /// \brief Rotate left by rotateAmt.
893 APInt rotl(unsigned rotateAmt) const;
895 /// \brief Rotate right by rotateAmt.
896 APInt rotr(unsigned rotateAmt) const;
898 /// \brief Arithmetic right-shift function.
900 /// Arithmetic right-shift this APInt by shiftAmt.
901 APInt ashr(const APInt &shiftAmt) const;
903 /// \brief Logical right-shift function.
905 /// Logical right-shift this APInt by shiftAmt.
906 APInt lshr(const APInt &shiftAmt) const;
908 /// \brief Left-shift function.
910 /// Left-shift this APInt by shiftAmt.
911 APInt shl(const APInt &shiftAmt) const;
913 /// \brief Rotate left by rotateAmt.
914 APInt rotl(const APInt &rotateAmt) const;
916 /// \brief Rotate right by rotateAmt.
917 APInt rotr(const APInt &rotateAmt) const;
919 /// \brief Unsigned division operation.
921 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
922 /// RHS are treated as unsigned quantities for purposes of this division.
924 /// \returns a new APInt value containing the division result
925 APInt udiv(const APInt &RHS) const;
927 /// \brief Signed division function for APInt.
929 /// Signed divide this APInt by APInt RHS.
930 APInt sdiv(const APInt &RHS) const;
932 /// \brief Unsigned remainder operation.
934 /// Perform an unsigned remainder operation on this APInt with RHS being the
935 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
936 /// of this operation. Note that this is a true remainder operation and not a
937 /// modulo operation because the sign follows the sign of the dividend which
940 /// \returns a new APInt value containing the remainder result
941 APInt urem(const APInt &RHS) const;
943 /// \brief Function for signed remainder operation.
945 /// Signed remainder operation on APInt.
946 APInt srem(const APInt &RHS) const;
948 /// \brief Dual division/remainder interface.
950 /// Sometimes it is convenient to divide two APInt values and obtain both the
951 /// quotient and remainder. This function does both operations in the same
952 /// computation making it a little more efficient. The pair of input arguments
953 /// may overlap with the pair of output arguments. It is safe to call
954 /// udivrem(X, Y, X, Y), for example.
955 static void udivrem(const APInt &LHS, const APInt &RHS,
956 APInt &Quotient, APInt &Remainder);
958 static void sdivrem(const APInt &LHS, const APInt &RHS,
959 APInt &Quotient, APInt &Remainder);
962 // Operations that return overflow indicators.
963 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
964 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
965 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
966 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
967 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
968 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
969 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
970 APInt sshl_ov(unsigned Amt, bool &Overflow) const;
972 /// \brief Array-indexing support.
974 /// \returns the bit value at bitPosition
975 bool operator[](unsigned bitPosition) const {
976 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
977 return (maskBit(bitPosition) &
978 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
982 /// \name Comparison Operators
985 /// \brief Equality operator.
987 /// Compares this APInt with RHS for the validity of the equality
989 bool operator==(const APInt& RHS) const {
990 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
992 return VAL == RHS.VAL;
993 return EqualSlowCase(RHS);
996 /// \brief Equality operator.
998 /// Compares this APInt with a uint64_t for the validity of the equality
1001 /// \returns true if *this == Val
1002 bool operator==(uint64_t Val) const {
1005 return EqualSlowCase(Val);
1008 /// \brief Equality comparison.
1010 /// Compares this APInt with RHS for the validity of the equality
1013 /// \returns true if *this == Val
1014 bool eq(const APInt &RHS) const {
1015 return (*this) == RHS;
1018 /// \brief Inequality operator.
1020 /// Compares this APInt with RHS for the validity of the inequality
1023 /// \returns true if *this != Val
1024 bool operator!=(const APInt& RHS) const {
1025 return !((*this) == RHS);
1028 /// \brief Inequality operator.
1030 /// Compares this APInt with a uint64_t for the validity of the inequality
1033 /// \returns true if *this != Val
1034 bool operator!=(uint64_t Val) const {
1035 return !((*this) == Val);
1038 /// \brief Inequality comparison
1040 /// Compares this APInt with RHS for the validity of the inequality
1043 /// \returns true if *this != Val
1044 bool ne(const APInt &RHS) const {
1045 return !((*this) == RHS);
1048 /// \brief Unsigned less than comparison
1050 /// Regards both *this and RHS as unsigned quantities and compares them for
1051 /// the validity of the less-than relationship.
1053 /// \returns true if *this < RHS when both are considered unsigned.
1054 bool ult(const APInt &RHS) const;
1056 /// \brief Unsigned less than comparison
1058 /// Regards both *this as an unsigned quantity and compares it with RHS for
1059 /// the validity of the less-than relationship.
1061 /// \returns true if *this < RHS when considered unsigned.
1062 bool ult(uint64_t RHS) const {
1063 return ult(APInt(getBitWidth(), RHS));
1066 /// \brief Signed less than comparison
1068 /// Regards both *this and RHS as signed quantities and compares them for
1069 /// validity of the less-than relationship.
1071 /// \returns true if *this < RHS when both are considered signed.
1072 bool slt(const APInt& RHS) const;
1074 /// \brief Signed less than comparison
1076 /// Regards both *this as a signed quantity and compares it with RHS for
1077 /// the validity of the less-than relationship.
1079 /// \returns true if *this < RHS when considered signed.
1080 bool slt(uint64_t RHS) const {
1081 return slt(APInt(getBitWidth(), RHS));
1084 /// \brief Unsigned less or equal comparison
1086 /// Regards both *this and RHS as unsigned quantities and compares them for
1087 /// validity of the less-or-equal relationship.
1089 /// \returns true if *this <= RHS when both are considered unsigned.
1090 bool ule(const APInt& RHS) const {
1091 return ult(RHS) || eq(RHS);
1094 /// \brief Unsigned less or equal comparison
1096 /// Regards both *this as an unsigned quantity and compares it with RHS for
1097 /// the validity of the less-or-equal relationship.
1099 /// \returns true if *this <= RHS when considered unsigned.
1100 bool ule(uint64_t RHS) const {
1101 return ule(APInt(getBitWidth(), RHS));
1104 /// \brief Signed less or equal comparison
1106 /// Regards both *this and RHS as signed quantities and compares them for
1107 /// validity of the less-or-equal relationship.
1109 /// \returns true if *this <= RHS when both are considered signed.
1110 bool sle(const APInt& RHS) const {
1111 return slt(RHS) || eq(RHS);
1114 /// \brief Signed less or equal comparison
1116 /// Regards both *this as a signed quantity and compares it with RHS for the
1117 /// validity of the less-or-equal relationship.
1119 /// \returns true if *this <= RHS when considered signed.
1120 bool sle(uint64_t RHS) const {
1121 return sle(APInt(getBitWidth(), RHS));
1124 /// \brief Unsigned greather than comparison
1126 /// Regards both *this and RHS as unsigned quantities and compares them for
1127 /// the validity of the greater-than relationship.
1129 /// \returns true if *this > RHS when both are considered unsigned.
1130 bool ugt(const APInt& RHS) const {
1131 return !ult(RHS) && !eq(RHS);
1134 /// \brief Unsigned greater than comparison
1136 /// Regards both *this as an unsigned quantity and compares it with RHS for
1137 /// the validity of the greater-than relationship.
1139 /// \returns true if *this > RHS when considered unsigned.
1140 bool ugt(uint64_t RHS) const {
1141 return ugt(APInt(getBitWidth(), RHS));
1144 /// \brief Signed greather than comparison
1146 /// Regards both *this and RHS as signed quantities and compares them for the
1147 /// validity of the greater-than relationship.
1149 /// \returns true if *this > RHS when both are considered signed.
1150 bool sgt(const APInt& RHS) const {
1151 return !slt(RHS) && !eq(RHS);
1154 /// \brief Signed greater than comparison
1156 /// Regards both *this as a signed quantity and compares it with RHS for
1157 /// the validity of the greater-than relationship.
1159 /// \returns true if *this > RHS when considered signed.
1160 bool sgt(uint64_t RHS) const {
1161 return sgt(APInt(getBitWidth(), RHS));
1164 /// \brief Unsigned greater or equal comparison
1166 /// Regards both *this and RHS as unsigned quantities and compares them for
1167 /// validity of the greater-or-equal relationship.
1169 /// \returns true if *this >= RHS when both are considered unsigned.
1170 bool uge(const APInt& RHS) const {
1174 /// \brief Unsigned greater or equal comparison
1176 /// Regards both *this as an unsigned quantity and compares it with RHS for
1177 /// the validity of the greater-or-equal relationship.
1179 /// \returns true if *this >= RHS when considered unsigned.
1180 bool uge(uint64_t RHS) const {
1181 return uge(APInt(getBitWidth(), RHS));
1184 /// \brief Signed greather or equal comparison
1186 /// Regards both *this and RHS as signed quantities and compares them for
1187 /// validity of the greater-or-equal relationship.
1189 /// \returns true if *this >= RHS when both are considered signed.
1190 bool sge(const APInt& RHS) const {
1194 /// \brief Signed greater or equal comparison
1196 /// Regards both *this as a signed quantity and compares it with RHS for
1197 /// the validity of the greater-or-equal relationship.
1199 /// \returns true if *this >= RHS when considered signed.
1200 bool sge(uint64_t RHS) const {
1201 return sge(APInt(getBitWidth(), RHS));
1204 /// This operation tests if there are any pairs of corresponding bits
1205 /// between this APInt and RHS that are both set.
1206 bool intersects(const APInt &RHS) const {
1207 return (*this & RHS) != 0;
1211 /// \name Resizing Operators
1214 /// \brief Truncate to new width.
1216 /// Truncate the APInt to a specified width. It is an error to specify a width
1217 /// that is greater than or equal to the current width.
1218 APInt trunc(unsigned width) const;
1220 /// \brief Sign extend to a new width.
1222 /// This operation sign extends the APInt to a new width. If the high order
1223 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1224 /// It is an error to specify a width that is less than or equal to the
1226 APInt sext(unsigned width) const;
1228 /// \brief Zero extend to a new width.
1230 /// This operation zero extends the APInt to a new width. The high order bits
1231 /// are filled with 0 bits. It is an error to specify a width that is less
1232 /// than or equal to the current width.
1233 APInt zext(unsigned width) const;
1235 /// \brief Sign extend or truncate to width
1237 /// Make this APInt have the bit width given by \p width. The value is sign
1238 /// extended, truncated, or left alone to make it that width.
1239 APInt sextOrTrunc(unsigned width) const;
1241 /// \brief Zero extend or truncate to width
1243 /// Make this APInt have the bit width given by \p width. The value is zero
1244 /// extended, truncated, or left alone to make it that width.
1245 APInt zextOrTrunc(unsigned width) const;
1247 /// \brief Sign extend or truncate to width
1249 /// Make this APInt have the bit width given by \p width. The value is sign
1250 /// extended, or left alone to make it that width.
1251 APInt sextOrSelf(unsigned width) const;
1253 /// \brief Zero extend or truncate to width
1255 /// Make this APInt have the bit width given by \p width. The value is zero
1256 /// extended, or left alone to make it that width.
1257 APInt zextOrSelf(unsigned width) const;
1260 /// \name Bit Manipulation Operators
1263 /// \brief Set every bit to 1.
1268 // Set all the bits in all the words.
1269 for (unsigned i = 0; i < getNumWords(); ++i)
1270 pVal[i] = UINT64_MAX;
1272 // Clear the unused ones
1276 /// \brief Set a given bit to 1.
1278 /// Set the given bit to 1 whose position is given as "bitPosition".
1279 void setBit(unsigned bitPosition);
1281 /// \brief Set every bit to 0.
1282 void clearAllBits() {
1286 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
1289 /// \brief Set a given bit to 0.
1291 /// Set the given bit to 0 whose position is given as "bitPosition".
1292 void clearBit(unsigned bitPosition);
1294 /// \brief Toggle every bit to its opposite value.
1295 void flipAllBits() {
1299 for (unsigned i = 0; i < getNumWords(); ++i)
1300 pVal[i] ^= UINT64_MAX;
1305 /// \brief Toggles a given bit to its opposite value.
1307 /// Toggle a given bit to its opposite value whose position is given
1308 /// as "bitPosition".
1309 void flipBit(unsigned bitPosition);
1312 /// \name Value Characterization Functions
1315 /// \brief Return the number of bits in the APInt.
1316 unsigned getBitWidth() const {
1320 /// \brief Get the number of words.
1322 /// Here one word's bitwidth equals to that of uint64_t.
1324 /// \returns the number of words to hold the integer value of this APInt.
1325 unsigned getNumWords() const {
1326 return getNumWords(BitWidth);
1329 /// \brief Get the number of words.
1331 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1333 /// \returns the number of words to hold the integer value with a given bit
1335 static unsigned getNumWords(unsigned BitWidth) {
1336 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1339 /// \brief Compute the number of active bits in the value
1341 /// This function returns the number of active bits which is defined as the
1342 /// bit width minus the number of leading zeros. This is used in several
1343 /// computations to see how "wide" the value is.
1344 unsigned getActiveBits() const {
1345 return BitWidth - countLeadingZeros();
1348 /// \brief Compute the number of active words in the value of this APInt.
1350 /// This is used in conjunction with getActiveData to extract the raw value of
1352 unsigned getActiveWords() const {
1353 unsigned numActiveBits = getActiveBits();
1354 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1357 /// \brief Get the minimum bit size for this signed APInt
1359 /// Computes the minimum bit width for this APInt while considering it to be a
1360 /// signed (and probably negative) value. If the value is not negative, this
1361 /// function returns the same value as getActiveBits()+1. Otherwise, it
1362 /// returns the smallest bit width that will retain the negative value. For
1363 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1364 /// for -1, this function will always return 1.
1365 unsigned getMinSignedBits() const {
1367 return BitWidth - countLeadingOnes() + 1;
1368 return getActiveBits()+1;
1371 /// \brief Get zero extended value
1373 /// This method attempts to return the value of this APInt as a zero extended
1374 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1375 /// uint64_t. Otherwise an assertion will result.
1376 uint64_t getZExtValue() const {
1379 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1383 /// \brief Get sign extended value
1385 /// This method attempts to return the value of this APInt as a sign extended
1386 /// int64_t. The bit width must be <= 64 or the value must fit within an
1387 /// int64_t. Otherwise an assertion will result.
1388 int64_t getSExtValue() const {
1390 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
1391 (APINT_BITS_PER_WORD - BitWidth);
1392 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1393 return int64_t(pVal[0]);
1396 /// \brief Get bits required for string value.
1398 /// This method determines how many bits are required to hold the APInt
1399 /// equivalent of the string given by \p str.
1400 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1402 /// \brief Count the number of zeros from the msb to the first one bit.
1404 /// This function is an APInt version of the countLeadingZeros_{32,64}
1405 /// functions in MathExtras.h. It counts the number of zeros from the most
1406 /// significant bit to the first one bit.
1408 /// \returns BitWidth if the value is zero, otherwise returns the number of
1409 /// zeros from the most significant bit to the first one bits.
1410 unsigned countLeadingZeros() const {
1411 if (isSingleWord()) {
1412 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1413 return CountLeadingZeros_64(VAL) - unusedBits;
1415 return countLeadingZerosSlowCase();
1418 /// \brief Count the number of leading one bits.
1420 /// This function is an APInt version of the countLeadingOnes_{32,64}
1421 /// functions in MathExtras.h. It counts the number of ones from the most
1422 /// significant bit to the first zero bit.
1424 /// \returns 0 if the high order bit is not set, otherwise returns the number
1425 /// of 1 bits from the most significant to the least
1426 unsigned countLeadingOnes() const;
1428 /// Computes the number of leading bits of this APInt that are equal to its
1430 unsigned getNumSignBits() const {
1431 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1434 /// \brief Count the number of trailing zero bits.
1436 /// This function is an APInt version of the countTrailingZeros_{32,64}
1437 /// functions in MathExtras.h. It counts the number of zeros from the least
1438 /// significant bit to the first set bit.
1440 /// \returns BitWidth if the value is zero, otherwise returns the number of
1441 /// zeros from the least significant bit to the first one bit.
1442 unsigned countTrailingZeros() const;
1444 /// \brief Count the number of trailing one bits.
1446 /// This function is an APInt version of the countTrailingOnes_{32,64}
1447 /// functions in MathExtras.h. It counts the number of ones from the least
1448 /// significant bit to the first zero bit.
1450 /// \returns BitWidth if the value is all ones, otherwise returns the number
1451 /// of ones from the least significant bit to the first zero bit.
1452 unsigned countTrailingOnes() const {
1454 return CountTrailingOnes_64(VAL);
1455 return countTrailingOnesSlowCase();
1458 /// \brief Count the number of bits set.
1460 /// This function is an APInt version of the countPopulation_{32,64} functions
1461 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1463 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1464 unsigned countPopulation() const {
1466 return CountPopulation_64(VAL);
1467 return countPopulationSlowCase();
1471 /// \name Conversion Functions
1473 void print(raw_ostream &OS, bool isSigned) const;
1475 /// Converts an APInt to a string and append it to Str. Str is commonly a
1477 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1478 bool formatAsCLiteral = false) const;
1480 /// Considers the APInt to be unsigned and converts it into a string in the
1481 /// radix given. The radix can be 2, 8, 10 16, or 36.
1482 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1483 toString(Str, Radix, false, false);
1486 /// Considers the APInt to be signed and converts it into a string in the
1487 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1488 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1489 toString(Str, Radix, true, false);
1492 /// \brief Return the APInt as a std::string.
1494 /// Note that this is an inefficient method. It is better to pass in a
1495 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1497 std::string toString(unsigned Radix, bool Signed) const;
1499 /// \returns a byte-swapped representation of this APInt Value.
1500 APInt byteSwap() const;
1502 /// \brief Converts this APInt to a double value.
1503 double roundToDouble(bool isSigned) const;
1505 /// \brief Converts this unsigned APInt to a double value.
1506 double roundToDouble() const {
1507 return roundToDouble(false);
1510 /// \brief Converts this signed APInt to a double value.
1511 double signedRoundToDouble() const {
1512 return roundToDouble(true);
1515 /// \brief Converts APInt bits to a double
1517 /// The conversion does not do a translation from integer to double, it just
1518 /// re-interprets the bits as a double. Note that it is valid to do this on
1519 /// any bit width. Exactly 64 bits will be translated.
1520 double bitsToDouble() const {
1525 T.I = (isSingleWord() ? VAL : pVal[0]);
1529 /// \brief Converts APInt bits to a double
1531 /// The conversion does not do a translation from integer to float, it just
1532 /// re-interprets the bits as a float. Note that it is valid to do this on
1533 /// any bit width. Exactly 32 bits will be translated.
1534 float bitsToFloat() const {
1539 T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1543 /// \brief Converts a double to APInt bits.
1545 /// The conversion does not do a translation from double to integer, it just
1546 /// re-interprets the bits of the double.
1547 static APInt doubleToBits(double V) {
1553 return APInt(sizeof T * CHAR_BIT, T.I);
1556 /// \brief Converts a float to APInt bits.
1558 /// The conversion does not do a translation from float to integer, it just
1559 /// re-interprets the bits of the float.
1560 static APInt floatToBits(float V) {
1566 return APInt(sizeof T * CHAR_BIT, T.I);
1570 /// \name Mathematics Operations
1573 /// \returns the floor log base 2 of this APInt.
1574 unsigned logBase2() const {
1575 return BitWidth - 1 - countLeadingZeros();
1578 /// \returns the ceil log base 2 of this APInt.
1579 unsigned ceilLogBase2() const {
1580 return BitWidth - (*this - 1).countLeadingZeros();
1583 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1585 int32_t exactLogBase2() const {
1591 /// \brief Compute the square root
1594 /// \brief Get the absolute value;
1596 /// If *this is < 0 then return -(*this), otherwise *this;
1603 /// \returns the multiplicative inverse for a given modulo.
1604 APInt multiplicativeInverse(const APInt& modulo) const;
1607 /// \name Support for division by constant
1610 /// Calculate the magic number for signed division by a constant.
1614 /// Calculate the magic number for unsigned division by a constant.
1616 mu magicu(unsigned LeadingZeros = 0) const;
1619 /// \name Building-block Operations for APInt and APFloat
1622 // These building block operations operate on a representation of arbitrary
1623 // precision, two's-complement, bignum integer values. They should be
1624 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1625 // generally a pointer to the base of an array of integer parts, representing
1626 // an unsigned bignum, and a count of how many parts there are.
1628 /// Sets the least significant part of a bignum to the input value, and zeroes
1629 /// out higher parts.
1630 static void tcSet(integerPart *, integerPart, unsigned int);
1632 /// Assign one bignum to another.
1633 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1635 /// Returns true if a bignum is zero, false otherwise.
1636 static bool tcIsZero(const integerPart *, unsigned int);
1638 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1639 static int tcExtractBit(const integerPart *, unsigned int bit);
1641 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1642 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1643 /// significant bit of DST. All high bits above srcBITS in DST are
1645 static void tcExtract(integerPart *, unsigned int dstCount,
1646 const integerPart *,
1647 unsigned int srcBits, unsigned int srcLSB);
1649 /// Set the given bit of a bignum. Zero-based.
1650 static void tcSetBit(integerPart *, unsigned int bit);
1652 /// Clear the given bit of a bignum. Zero-based.
1653 static void tcClearBit(integerPart *, unsigned int bit);
1655 /// Returns the bit number of the least or most significant set bit of a
1656 /// number. If the input number has no bits set -1U is returned.
1657 static unsigned int tcLSB(const integerPart *, unsigned int);
1658 static unsigned int tcMSB(const integerPart *parts, unsigned int n);
1660 /// Negate a bignum in-place.
1661 static void tcNegate(integerPart *, unsigned int);
1663 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1664 static integerPart tcAdd(integerPart *, const integerPart *,
1665 integerPart carry, unsigned);
1667 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1668 static integerPart tcSubtract(integerPart *, const integerPart *,
1669 integerPart carry, unsigned);
1671 /// DST += SRC * MULTIPLIER + PART if add is true
1672 /// DST = SRC * MULTIPLIER + PART if add is false
1674 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1675 /// start at the same point, i.e. DST == SRC.
1677 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1678 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1679 /// result, and if all of the omitted higher parts were zero return zero,
1680 /// otherwise overflow occurred and return one.
1681 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1682 integerPart multiplier, integerPart carry,
1683 unsigned int srcParts, unsigned int dstParts,
1686 /// DST = LHS * RHS, where DST has the same width as the operands and is
1687 /// filled with the least significant parts of the result. Returns one if
1688 /// overflow occurred, otherwise zero. DST must be disjoint from both
1690 static int tcMultiply(integerPart *, const integerPart *,
1691 const integerPart *, unsigned);
1693 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1694 /// operands. No overflow occurs. DST must be disjoint from both
1695 /// operands. Returns the number of parts required to hold the result.
1696 static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1697 const integerPart *, unsigned, unsigned);
1699 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1700 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1701 /// REMAINDER to the remainder, return zero. i.e.
1703 /// OLD_LHS = RHS * LHS + REMAINDER
1705 /// SCRATCH is a bignum of the same size as the operands and result for use by
1706 /// the routine; its contents need not be initialized and are destroyed. LHS,
1707 /// REMAINDER and SCRATCH must be distinct.
1708 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1709 integerPart *remainder, integerPart *scratch,
1710 unsigned int parts);
1712 /// Shift a bignum left COUNT bits. Shifted in bits are zero. There are no
1713 /// restrictions on COUNT.
1714 static void tcShiftLeft(integerPart *, unsigned int parts,
1715 unsigned int count);
1717 /// Shift a bignum right COUNT bits. Shifted in bits are zero. There are no
1718 /// restrictions on COUNT.
1719 static void tcShiftRight(integerPart *, unsigned int parts,
1720 unsigned int count);
1722 /// The obvious AND, OR and XOR and complement operations.
1723 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1724 static void tcOr(integerPart *, const integerPart *, unsigned int);
1725 static void tcXor(integerPart *, const integerPart *, unsigned int);
1726 static void tcComplement(integerPart *, unsigned int);
1728 /// Comparison (unsigned) of two bignums.
1729 static int tcCompare(const integerPart *, const integerPart *,
1732 /// Increment a bignum in-place. Return the carry flag.
1733 static integerPart tcIncrement(integerPart *, unsigned int);
1735 /// Set the least significant BITS and clear the rest.
1736 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1739 /// \brief debug method
1745 /// Magic data for optimising signed division by a constant.
1747 APInt m; ///< magic number
1748 unsigned s; ///< shift amount
1751 /// Magic data for optimising unsigned division by a constant.
1753 APInt m; ///< magic number
1754 bool a; ///< add indicator
1755 unsigned s; ///< shift amount
1758 inline bool operator==(uint64_t V1, const APInt& V2) {
1762 inline bool operator!=(uint64_t V1, const APInt& V2) {
1766 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1771 namespace APIntOps {
1773 /// \brief Determine the smaller of two APInts considered to be signed.
1774 inline APInt smin(const APInt &A, const APInt &B) {
1775 return A.slt(B) ? A : B;
1778 /// \brief Determine the larger of two APInts considered to be signed.
1779 inline APInt smax(const APInt &A, const APInt &B) {
1780 return A.sgt(B) ? A : B;
1783 /// \brief Determine the smaller of two APInts considered to be signed.
1784 inline APInt umin(const APInt &A, const APInt &B) {
1785 return A.ult(B) ? A : B;
1788 /// \brief Determine the larger of two APInts considered to be unsigned.
1789 inline APInt umax(const APInt &A, const APInt &B) {
1790 return A.ugt(B) ? A : B;
1793 /// \brief Check if the specified APInt has a N-bits unsigned integer value.
1794 inline bool isIntN(unsigned N, const APInt& APIVal) {
1795 return APIVal.isIntN(N);
1798 /// \brief Check if the specified APInt has a N-bits signed integer value.
1799 inline bool isSignedIntN(unsigned N, const APInt& APIVal) {
1800 return APIVal.isSignedIntN(N);
1803 /// \returns true if the argument APInt value is a sequence of ones starting at
1804 /// the least significant bit with the remainder zero.
1805 inline bool isMask(unsigned numBits, const APInt& APIVal) {
1806 return numBits <= APIVal.getBitWidth() &&
1807 APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
1810 /// \brief Return true if the argument APInt value contains a sequence of ones
1811 /// with the remainder zero.
1812 inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
1813 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1816 /// \brief Returns a byte-swapped representation of the specified APInt Value.
1817 inline APInt byteSwap(const APInt& APIVal) {
1818 return APIVal.byteSwap();
1821 /// \brief Returns the floor log base 2 of the specified APInt value.
1822 inline unsigned logBase2(const APInt& APIVal) {
1823 return APIVal.logBase2();
1826 /// \brief Compute GCD of two APInt values.
1828 /// This function returns the greatest common divisor of the two APInt values
1829 /// using Euclid's algorithm.
1831 /// \returns the greatest common divisor of Val1 and Val2
1832 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1834 /// \brief Converts the given APInt to a double value.
1836 /// Treats the APInt as an unsigned value for conversion purposes.
1837 inline double RoundAPIntToDouble(const APInt& APIVal) {
1838 return APIVal.roundToDouble();
1841 /// \brief Converts the given APInt to a double value.
1843 /// Treats the APInt as a signed value for conversion purposes.
1844 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1845 return APIVal.signedRoundToDouble();
1848 /// \brief Converts the given APInt to a float vlalue.
1849 inline float RoundAPIntToFloat(const APInt& APIVal) {
1850 return float(RoundAPIntToDouble(APIVal));
1853 /// \brief Converts the given APInt to a float value.
1855 /// Treast the APInt as a signed value for conversion purposes.
1856 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1857 return float(APIVal.signedRoundToDouble());
1860 /// \brief Converts the given double value into a APInt.
1862 /// This function convert a double value to an APInt value.
1863 APInt RoundDoubleToAPInt(double Double, unsigned width);
1865 /// \brief Converts a float value into a APInt.
1867 /// Converts a float value into an APInt value.
1868 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
1869 return RoundDoubleToAPInt(double(Float), width);
1872 /// \brief Arithmetic right-shift function.
1874 /// Arithmetic right-shift the APInt by shiftAmt.
1875 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
1876 return LHS.ashr(shiftAmt);
1879 /// \brief Logical right-shift function.
1881 /// Logical right-shift the APInt by shiftAmt.
1882 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
1883 return LHS.lshr(shiftAmt);
1886 /// \brief Left-shift function.
1888 /// Left-shift the APInt by shiftAmt.
1889 inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
1890 return LHS.shl(shiftAmt);
1893 /// \brief Signed division function for APInt.
1895 /// Signed divide APInt LHS by APInt RHS.
1896 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1897 return LHS.sdiv(RHS);
1900 /// \brief Unsigned division function for APInt.
1902 /// Unsigned divide APInt LHS by APInt RHS.
1903 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1904 return LHS.udiv(RHS);
1907 /// \brief Function for signed remainder operation.
1909 /// Signed remainder operation on APInt.
1910 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1911 return LHS.srem(RHS);
1914 /// \brief Function for unsigned remainder operation.
1916 /// Unsigned remainder operation on APInt.
1917 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1918 return LHS.urem(RHS);
1921 /// \brief Function for multiplication operation.
1923 /// Performs multiplication on APInt values.
1924 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1928 /// \brief Function for addition operation.
1930 /// Performs addition on APInt values.
1931 inline APInt add(const APInt& LHS, const APInt& RHS) {
1935 /// \brief Function for subtraction operation.
1937 /// Performs subtraction on APInt values.
1938 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1942 /// \brief Bitwise AND function for APInt.
1944 /// Performs bitwise AND operation on APInt LHS and
1946 inline APInt And(const APInt& LHS, const APInt& RHS) {
1950 /// \brief Bitwise OR function for APInt.
1952 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1953 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1957 /// \brief Bitwise XOR function for APInt.
1959 /// Performs bitwise XOR operation on APInt.
1960 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1964 /// \brief Bitwise complement function.
1966 /// Performs a bitwise complement operation on APInt.
1967 inline APInt Not(const APInt& APIVal) {
1971 } // End of APIntOps namespace
1973 // See friend declaration above. This additional declaration is required in
1974 // order to compile LLVM with IBM xlC compiler.
1975 hash_code hash_value(const APInt &Arg);
1976 } // End of llvm namespace