1 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Sheng Zhou and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a class to represent arbitrary precision integral
11 // constant values and operations on them.
13 //===----------------------------------------------------------------------===//
18 #include "llvm/Support/DataTypes.h"
19 #include "llvm/Bitcode/SerializationFwd.h"
23 #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
27 /* An unsigned host type used as a single part of a multi-part
29 typedef uint64_t integerPart;
31 const unsigned int host_char_bit = 8;
32 const unsigned int integerPartWidth = host_char_bit * sizeof(integerPart);
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 /// APInt - This class represents arbitrary precision constant integral values.
39 /// It is a functional replacement for common case unsigned integer type like
40 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
41 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
42 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
43 /// and methods to manipulate integer values of any bit-width. It supports both
44 /// the typical integer arithmetic and comparison operations as well as bitwise
47 /// The class has several invariants worth noting:
48 /// * All bit, byte, and word positions are zero-based.
49 /// * Once the bit width is set, it doesn't change except by the Truncate,
50 /// SignExtend, or ZeroExtend operations.
51 /// * All binary operators must be on APInt instances of the same bit width.
52 /// Attempting to use these operators on instances with different bit
53 /// widths will yield an assertion.
54 /// * The value is stored canonically as an unsigned value. For operations
55 /// where it makes a difference, there are both signed and unsigned variants
56 /// of the operation. For example, sdiv and udiv. However, because the bit
57 /// widths must be the same, operations such as Mul and Add produce the same
58 /// results regardless of whether the values are interpreted as signed or
60 /// * In general, the class tries to follow the style of computation that LLVM
61 /// uses in its IR. This simplifies its use for LLVM.
63 /// @brief Class for arbitrary precision integers.
66 uint32_t BitWidth; ///< The number of bits in this APInt.
68 /// This union is used to store the integer value. When the
69 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
71 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
72 uint64_t *pVal; ///< Used to store the >64 bits integer value.
75 /// This enum is used to hold the constants we needed for APInt.
77 APINT_BITS_PER_WORD = sizeof(uint64_t) * 8, ///< Bits in a word
78 APINT_WORD_SIZE = sizeof(uint64_t) ///< Byte size of a word
81 /// This constructor is used only internally for speed of construction of
82 /// temporaries. It is unsafe for general use so it is not public.
83 /// @brief Fast internal constructor
84 APInt(uint64_t* val, uint32_t bits) : BitWidth(bits), pVal(val) { }
86 /// @returns true if the number of bits <= 64, false otherwise.
87 /// @brief Determine if this APInt just has one word to store value.
88 inline bool isSingleWord() const {
89 return BitWidth <= APINT_BITS_PER_WORD;
92 /// @returns the word position for the specified bit position.
93 /// @brief Determine which word a bit is in.
94 static inline uint32_t whichWord(uint32_t bitPosition) {
95 return bitPosition / APINT_BITS_PER_WORD;
98 /// @returns the bit position in a word for the specified bit position
100 /// @brief Determine which bit in a word a bit is in.
101 static inline uint32_t whichBit(uint32_t bitPosition) {
102 return bitPosition % APINT_BITS_PER_WORD;
105 /// This method generates and returns a uint64_t (word) mask for a single
106 /// bit at a specific bit position. This is used to mask the bit in the
107 /// corresponding word.
108 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
109 /// @brief Get a single bit mask.
110 static inline uint64_t maskBit(uint32_t bitPosition) {
111 return 1ULL << whichBit(bitPosition);
114 /// This method is used internally to clear the to "N" bits in the high order
115 /// word that are not used by the APInt. This is needed after the most
116 /// significant word is assigned a value to ensure that those bits are
118 /// @brief Clear unused high order bits
119 inline APInt& clearUnusedBits() {
120 // Compute how many bits are used in the final word
121 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
123 // If all bits are used, we want to leave the value alone. This also
124 // avoids the undefined behavior of >> when the shfit is the same size as
125 // the word size (64).
128 // Mask out the hight bits.
129 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
133 pVal[getNumWords() - 1] &= mask;
137 /// @returns the corresponding word for the specified bit position.
138 /// @brief Get the word corresponding to a bit position
139 inline uint64_t getWord(uint32_t bitPosition) const {
140 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
143 /// This is used by the constructors that take string arguments.
144 /// @brief Convert a char array into an APInt
145 void fromString(uint32_t numBits, const char *strStart, uint32_t slen,
148 /// This is used by the toString method to divide by the radix. It simply
149 /// provides a more convenient form of divide for internal use since KnuthDiv
150 /// has specific constraints on its inputs. If those constraints are not met
151 /// then it provides a simpler form of divide.
152 /// @brief An internal division function for dividing APInts.
153 static void divide(const APInt LHS, uint32_t lhsWords,
154 const APInt &RHS, uint32_t rhsWords,
155 APInt *Quotient, APInt *Remainder);
158 /// @name Constructors
160 /// If isSigned is true then val is treated as if it were a signed value
161 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
162 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
163 /// the range of val are zero filled).
164 /// @param numBits the bit width of the constructed APInt
165 /// @param val the initial value of the APInt
166 /// @param isSigned how to treat signedness of val
167 /// @brief Create a new APInt of numBits width, initialized as val.
168 APInt(uint32_t numBits, uint64_t val, bool isSigned = false);
170 /// Note that numWords can be smaller or larger than the corresponding bit
171 /// width but any extraneous bits will be dropped.
172 /// @param numBits the bit width of the constructed APInt
173 /// @param numWords the number of words in bigVal
174 /// @param bigVal a sequence of words to form the initial value of the APInt
175 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
176 APInt(uint32_t numBits, uint32_t numWords, const uint64_t bigVal[]);
178 /// This constructor interprets Val as a string in the given radix. The
179 /// interpretation stops when the first charater that is not suitable for the
180 /// radix is encountered. Acceptable radix values are 2, 8, 10 and 16. It is
181 /// an error for the value implied by the string to require more bits than
183 /// @param numBits the bit width of the constructed APInt
184 /// @param val the string to be interpreted
185 /// @param radix the radix of Val to use for the intepretation
186 /// @brief Construct an APInt from a string representation.
187 APInt(uint32_t numBits, const std::string& val, uint8_t radix);
189 /// This constructor interprets the slen characters starting at StrStart as
190 /// a string in the given radix. The interpretation stops when the first
191 /// character that is not suitable for the radix is encountered. Acceptable
192 /// radix values are 2, 8, 10 and 16. It is an error for the value implied by
193 /// the string to require more bits than numBits.
194 /// @param numBits the bit width of the constructed APInt
195 /// @param strStart the start of the string to be interpreted
196 /// @param slen the maximum number of characters to interpret
197 /// @param radix the radix to use for the conversion
198 /// @brief Construct an APInt from a string representation.
199 APInt(uint32_t numBits, const char strStart[], uint32_t slen, uint8_t radix);
201 /// Simply makes *this a copy of that.
202 /// @brief Copy Constructor.
203 APInt(const APInt& that);
205 /// @brief Destructor.
208 /// Default constructor that creates an uninitialized APInt. This is useful
209 /// for object deserialization (pair this with the static method Read).
210 explicit APInt() : BitWidth(1) {}
212 /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
213 void Emit(Serializer& S) const;
215 /// @brief Used by the Bitcode deserializer to deserialize APInts.
216 void Read(Deserializer& D);
219 /// @name Value Tests
221 /// This tests the high bit of this APInt to determine if it is set.
222 /// @returns true if this APInt is negative, false otherwise
223 /// @brief Determine sign of this APInt.
224 bool isNegative() const {
225 return (*this)[BitWidth - 1];
228 /// This tests the high bit of the APInt to determine if it is unset.
229 /// @brief Determine if this APInt Value is positive (not negative).
230 bool isPositive() const {
231 return !isNegative();
234 /// This tests if the value of this APInt is strictly positive (> 0).
235 /// @returns true if this APInt is Positive and not zero.
236 /// @brief Determine if this APInt Value is strictly positive.
237 inline bool isStrictlyPositive() const {
238 return isPositive() && (*this) != 0;
241 /// This checks to see if the value has all bits of the APInt are set or not.
242 /// @brief Determine if all bits are set
243 inline bool isAllOnesValue() const {
244 return countPopulation() == BitWidth;
247 /// This checks to see if the value of this APInt is the maximum unsigned
248 /// value for the APInt's bit width.
249 /// @brief Determine if this is the largest unsigned value.
250 bool isMaxValue() const {
251 return countPopulation() == BitWidth;
254 /// This checks to see if the value of this APInt is the maximum signed
255 /// value for the APInt's bit width.
256 /// @brief Determine if this is the largest signed value.
257 bool isMaxSignedValue() const {
258 return BitWidth == 1 ? VAL == 0 :
259 !isNegative() && countPopulation() == BitWidth - 1;
262 /// This checks to see if the value of this APInt is the minimum unsigned
263 /// value for the APInt's bit width.
264 /// @brief Determine if this is the smallest unsigned value.
265 bool isMinValue() const {
266 return countPopulation() == 0;
269 /// This checks to see if the value of this APInt is the minimum signed
270 /// value for the APInt's bit width.
271 /// @brief Determine if this is the smallest signed value.
272 bool isMinSignedValue() const {
273 return BitWidth == 1 ? VAL == 1 :
274 isNegative() && countPopulation() == 1;
277 /// @brief Check if this APInt has an N-bits integer value.
278 inline bool isIntN(uint32_t N) const {
279 assert(N && "N == 0 ???");
280 if (isSingleWord()) {
281 return VAL == (VAL & (~0ULL >> (64 - N)));
283 APInt Tmp(N, getNumWords(), pVal);
284 return Tmp == (*this);
288 /// @returns true if the argument APInt value is a power of two > 0.
289 bool isPowerOf2() const;
291 /// isSignBit - Return true if this is the value returned by getSignBit.
292 bool isSignBit() const { return isMinSignedValue(); }
294 /// This converts the APInt to a boolean value as a test against zero.
295 /// @brief Boolean conversion function.
296 inline bool getBoolValue() const {
300 /// getLimitedValue - If this value is smaller than the specified limit,
301 /// return it, otherwise return the limit value. This causes the value
302 /// to saturate to the limit.
303 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
304 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
305 Limit : getZExtValue();
309 /// @name Value Generators
311 /// @brief Gets maximum unsigned value of APInt for specific bit width.
312 static APInt getMaxValue(uint32_t numBits) {
313 return APInt(numBits, 0).set();
316 /// @brief Gets maximum signed value of APInt for a specific bit width.
317 static APInt getSignedMaxValue(uint32_t numBits) {
318 return APInt(numBits, 0).set().clear(numBits - 1);
321 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
322 static APInt getMinValue(uint32_t numBits) {
323 return APInt(numBits, 0);
326 /// @brief Gets minimum signed value of APInt for a specific bit width.
327 static APInt getSignedMinValue(uint32_t numBits) {
328 return APInt(numBits, 0).set(numBits - 1);
331 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
332 /// it helps code readability when we want to get a SignBit.
333 /// @brief Get the SignBit for a specific bit width.
334 inline static APInt getSignBit(uint32_t BitWidth) {
335 return getSignedMinValue(BitWidth);
338 /// @returns the all-ones value for an APInt of the specified bit-width.
339 /// @brief Get the all-ones value.
340 static APInt getAllOnesValue(uint32_t numBits) {
341 return APInt(numBits, 0).set();
344 /// @returns the '0' value for an APInt of the specified bit-width.
345 /// @brief Get the '0' value.
346 static APInt getNullValue(uint32_t numBits) {
347 return APInt(numBits, 0);
350 /// Get an APInt with the same BitWidth as this APInt, just zero mask
351 /// the low bits and right shift to the least significant bit.
352 /// @returns the high "numBits" bits of this APInt.
353 APInt getHiBits(uint32_t numBits) const;
355 /// Get an APInt with the same BitWidth as this APInt, just zero mask
357 /// @returns the low "numBits" bits of this APInt.
358 APInt getLoBits(uint32_t numBits) const;
360 /// Constructs an APInt value that has a contiguous range of bits set. The
361 /// bits from loBit to hiBit will be set. All other bits will be zero. For
362 /// example, with parameters(32, 15, 0) you would get 0x0000FFFF. If hiBit is
363 /// less than loBit then the set bits "wrap". For example, with
364 /// parameters (32, 3, 28), you would get 0xF000000F.
365 /// @param numBits the intended bit width of the result
366 /// @param loBit the index of the lowest bit set.
367 /// @param hiBit the index of the highest bit set.
368 /// @returns An APInt value with the requested bits set.
369 /// @brief Get a value with a block of bits set.
370 static APInt getBitsSet(uint32_t numBits, uint32_t loBit, uint32_t hiBit) {
371 assert(hiBit < numBits && "hiBit out of range");
372 assert(loBit < numBits && "loBit out of range");
374 return getLowBitsSet(numBits, hiBit+1) |
375 getHighBitsSet(numBits, numBits-loBit+1);
376 return getLowBitsSet(numBits, hiBit-loBit+1).shl(loBit);
379 /// Constructs an APInt value that has the top hiBitsSet bits set.
380 /// @param numBits the bitwidth of the result
381 /// @param hiBitsSet the number of high-order bits set in the result.
382 /// @brief Get a value with high bits set
383 static APInt getHighBitsSet(uint32_t numBits, uint32_t hiBitsSet) {
384 assert(hiBitsSet <= numBits && "Too many bits to set!");
385 // Handle a degenerate case, to avoid shifting by word size
387 return APInt(numBits, 0);
388 uint32_t shiftAmt = numBits - hiBitsSet;
389 // For small values, return quickly
390 if (numBits <= APINT_BITS_PER_WORD)
391 return APInt(numBits, ~0ULL << shiftAmt);
392 return (~APInt(numBits, 0)).shl(shiftAmt);
395 /// Constructs an APInt value that has the bottom loBitsSet bits set.
396 /// @param numBits the bitwidth of the result
397 /// @param loBitsSet the number of low-order bits set in the result.
398 /// @brief Get a value with low bits set
399 static APInt getLowBitsSet(uint32_t numBits, uint32_t loBitsSet) {
400 assert(loBitsSet <= numBits && "Too many bits to set!");
401 // Handle a degenerate case, to avoid shifting by word size
403 return APInt(numBits, 0);
404 if (loBitsSet == APINT_BITS_PER_WORD)
405 return APInt(numBits, -1ULL);
406 // For small values, return quickly
407 if (numBits < APINT_BITS_PER_WORD)
408 return APInt(numBits, (1ULL << loBitsSet) - 1);
409 return (~APInt(numBits, 0)).lshr(numBits - loBitsSet);
412 /// The hash value is computed as the sum of the words and the bit width.
413 /// @returns A hash value computed from the sum of the APInt words.
414 /// @brief Get a hash value based on this APInt
415 uint64_t getHashValue() const;
417 /// This function returns a pointer to the internal storage of the APInt.
418 /// This is useful for writing out the APInt in binary form without any
420 inline const uint64_t* getRawData() const {
427 /// @name Unary Operators
429 /// @returns a new APInt value representing *this incremented by one
430 /// @brief Postfix increment operator.
431 inline const APInt operator++(int) {
437 /// @returns *this incremented by one
438 /// @brief Prefix increment operator.
441 /// @returns a new APInt representing *this decremented by one.
442 /// @brief Postfix decrement operator.
443 inline const APInt operator--(int) {
449 /// @returns *this decremented by one.
450 /// @brief Prefix decrement operator.
453 /// Performs a bitwise complement operation on this APInt.
454 /// @returns an APInt that is the bitwise complement of *this
455 /// @brief Unary bitwise complement operator.
456 APInt operator~() const;
458 /// Negates *this using two's complement logic.
459 /// @returns An APInt value representing the negation of *this.
460 /// @brief Unary negation operator
461 inline APInt operator-() const {
462 return APInt(BitWidth, 0) - (*this);
465 /// Performs logical negation operation on this APInt.
466 /// @returns true if *this is zero, false otherwise.
467 /// @brief Logical negation operator.
468 bool operator !() const;
471 /// @name Assignment Operators
473 /// @returns *this after assignment of RHS.
474 /// @brief Copy assignment operator.
475 APInt& operator=(const APInt& RHS);
477 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
478 /// the bit width, the excess bits are truncated. If the bit width is larger
479 /// than 64, the value is zero filled in the unspecified high order bits.
480 /// @returns *this after assignment of RHS value.
481 /// @brief Assignment operator.
482 APInt& operator=(uint64_t RHS);
484 /// Performs a bitwise AND operation on this APInt and RHS. The result is
485 /// assigned to *this.
486 /// @returns *this after ANDing with RHS.
487 /// @brief Bitwise AND assignment operator.
488 APInt& operator&=(const APInt& RHS);
490 /// Performs a bitwise OR operation on this APInt and RHS. The result is
492 /// @returns *this after ORing with RHS.
493 /// @brief Bitwise OR assignment operator.
494 APInt& operator|=(const APInt& RHS);
496 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
497 /// assigned to *this.
498 /// @returns *this after XORing with RHS.
499 /// @brief Bitwise XOR assignment operator.
500 APInt& operator^=(const APInt& RHS);
502 /// Multiplies this APInt by RHS and assigns the result to *this.
504 /// @brief Multiplication assignment operator.
505 APInt& operator*=(const APInt& RHS);
507 /// Adds RHS to *this and assigns the result to *this.
509 /// @brief Addition assignment operator.
510 APInt& operator+=(const APInt& RHS);
512 /// Subtracts RHS from *this and assigns the result to *this.
514 /// @brief Subtraction assignment operator.
515 APInt& operator-=(const APInt& RHS);
517 /// Shifts *this left by shiftAmt and assigns the result to *this.
518 /// @returns *this after shifting left by shiftAmt
519 /// @brief Left-shift assignment function.
520 inline APInt& operator<<=(uint32_t shiftAmt) {
521 *this = shl(shiftAmt);
526 /// @name Binary Operators
528 /// Performs a bitwise AND operation on *this and RHS.
529 /// @returns An APInt value representing the bitwise AND of *this and RHS.
530 /// @brief Bitwise AND operator.
531 APInt operator&(const APInt& RHS) const;
532 APInt And(const APInt& RHS) const {
533 return this->operator&(RHS);
536 /// Performs a bitwise OR operation on *this and RHS.
537 /// @returns An APInt value representing the bitwise OR of *this and RHS.
538 /// @brief Bitwise OR operator.
539 APInt operator|(const APInt& RHS) const;
540 APInt Or(const APInt& RHS) const {
541 return this->operator|(RHS);
544 /// Performs a bitwise XOR operation on *this and RHS.
545 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
546 /// @brief Bitwise XOR operator.
547 APInt operator^(const APInt& RHS) const;
548 APInt Xor(const APInt& RHS) const {
549 return this->operator^(RHS);
552 /// Multiplies this APInt by RHS and returns the result.
553 /// @brief Multiplication operator.
554 APInt operator*(const APInt& RHS) const;
556 /// Adds RHS to this APInt and returns the result.
557 /// @brief Addition operator.
558 APInt operator+(const APInt& RHS) const;
559 APInt operator+(uint64_t RHS) const {
560 return (*this) + APInt(BitWidth, RHS);
563 /// Subtracts RHS from this APInt and returns the result.
564 /// @brief Subtraction operator.
565 APInt operator-(const APInt& RHS) const;
566 APInt operator-(uint64_t RHS) const {
567 return (*this) - APInt(BitWidth, RHS);
570 APInt operator<<(unsigned Bits) const {
574 /// Arithmetic right-shift this APInt by shiftAmt.
575 /// @brief Arithmetic right-shift function.
576 APInt ashr(uint32_t shiftAmt) const;
578 /// Logical right-shift this APInt by shiftAmt.
579 /// @brief Logical right-shift function.
580 APInt lshr(uint32_t shiftAmt) const;
582 /// Left-shift this APInt by shiftAmt.
583 /// @brief Left-shift function.
584 APInt shl(uint32_t shiftAmt) const;
586 /// @brief Rotate left by rotateAmt.
587 APInt rotl(uint32_t rotateAmt) const;
589 /// @brief Rotate right by rotateAmt.
590 APInt rotr(uint32_t rotateAmt) const;
592 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
593 /// RHS are treated as unsigned quantities for purposes of this division.
594 /// @returns a new APInt value containing the division result
595 /// @brief Unsigned division operation.
596 APInt udiv(const APInt& RHS) const;
598 /// Signed divide this APInt by APInt RHS.
599 /// @brief Signed division function for APInt.
600 inline APInt sdiv(const APInt& RHS) const {
602 if (RHS.isNegative())
603 return (-(*this)).udiv(-RHS);
605 return -((-(*this)).udiv(RHS));
606 else if (RHS.isNegative())
607 return -(this->udiv(-RHS));
608 return this->udiv(RHS);
611 /// Perform an unsigned remainder operation on this APInt with RHS being the
612 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
613 /// of this operation. Note that this is a true remainder operation and not
614 /// a modulo operation because the sign follows the sign of the dividend
616 /// @returns a new APInt value containing the remainder result
617 /// @brief Unsigned remainder operation.
618 APInt urem(const APInt& RHS) const;
620 /// Signed remainder operation on APInt.
621 /// @brief Function for signed remainder operation.
622 inline APInt srem(const APInt& RHS) const {
624 if (RHS.isNegative())
625 return -((-(*this)).urem(-RHS));
627 return -((-(*this)).urem(RHS));
628 else if (RHS.isNegative())
629 return this->urem(-RHS);
630 return this->urem(RHS);
633 /// Sometimes it is convenient to divide two APInt values and obtain both
634 /// the quotient and remainder. This function does both operations in the
635 /// same computation making it a little more efficient.
636 /// @brief Dual division/remainder interface.
637 static void udivrem(const APInt &LHS, const APInt &RHS,
638 APInt &Quotient, APInt &Remainder);
640 static void sdivrem(const APInt &LHS, const APInt &RHS,
641 APInt &Quotient, APInt &Remainder)
643 if (LHS.isNegative()) {
644 if (RHS.isNegative())
645 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
647 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
648 Quotient = -Quotient;
649 Remainder = -Remainder;
650 } else if (RHS.isNegative()) {
651 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
652 Quotient = -Quotient;
654 APInt::udivrem(LHS, RHS, Quotient, Remainder);
658 /// @returns the bit value at bitPosition
659 /// @brief Array-indexing support.
660 bool operator[](uint32_t bitPosition) const;
663 /// @name Comparison Operators
665 /// Compares this APInt with RHS for the validity of the equality
667 /// @brief Equality operator.
668 bool operator==(const APInt& RHS) const;
670 /// Compares this APInt with a uint64_t for the validity of the equality
672 /// @returns true if *this == Val
673 /// @brief Equality operator.
674 bool operator==(uint64_t Val) const;
676 /// Compares this APInt with RHS for the validity of the equality
678 /// @returns true if *this == Val
679 /// @brief Equality comparison.
680 bool eq(const APInt &RHS) const {
681 return (*this) == RHS;
684 /// Compares this APInt with RHS for the validity of the inequality
686 /// @returns true if *this != Val
687 /// @brief Inequality operator.
688 inline bool operator!=(const APInt& RHS) const {
689 return !((*this) == RHS);
692 /// Compares this APInt with a uint64_t for the validity of the inequality
694 /// @returns true if *this != Val
695 /// @brief Inequality operator.
696 inline bool operator!=(uint64_t Val) const {
697 return !((*this) == Val);
700 /// Compares this APInt with RHS for the validity of the inequality
702 /// @returns true if *this != Val
703 /// @brief Inequality comparison
704 bool ne(const APInt &RHS) const {
705 return !((*this) == RHS);
708 /// Regards both *this and RHS as unsigned quantities and compares them for
709 /// the validity of the less-than relationship.
710 /// @returns true if *this < RHS when both are considered unsigned.
711 /// @brief Unsigned less than comparison
712 bool ult(const APInt& RHS) const;
714 /// Regards both *this and RHS as signed quantities and compares them for
715 /// validity of the less-than relationship.
716 /// @returns true if *this < RHS when both are considered signed.
717 /// @brief Signed less than comparison
718 bool slt(const APInt& RHS) const;
720 /// Regards both *this and RHS as unsigned quantities and compares them for
721 /// validity of the less-or-equal relationship.
722 /// @returns true if *this <= RHS when both are considered unsigned.
723 /// @brief Unsigned less or equal comparison
724 bool ule(const APInt& RHS) const {
725 return ult(RHS) || eq(RHS);
728 /// Regards both *this and RHS as signed quantities and compares them for
729 /// validity of the less-or-equal relationship.
730 /// @returns true if *this <= RHS when both are considered signed.
731 /// @brief Signed less or equal comparison
732 bool sle(const APInt& RHS) const {
733 return slt(RHS) || eq(RHS);
736 /// Regards both *this and RHS as unsigned quantities and compares them for
737 /// the validity of the greater-than relationship.
738 /// @returns true if *this > RHS when both are considered unsigned.
739 /// @brief Unsigned greather than comparison
740 bool ugt(const APInt& RHS) const {
741 return !ult(RHS) && !eq(RHS);
744 /// Regards both *this and RHS as signed quantities and compares them for
745 /// the validity of the greater-than relationship.
746 /// @returns true if *this > RHS when both are considered signed.
747 /// @brief Signed greather than comparison
748 bool sgt(const APInt& RHS) const {
749 return !slt(RHS) && !eq(RHS);
752 /// Regards both *this and RHS as unsigned quantities and compares them for
753 /// validity of the greater-or-equal relationship.
754 /// @returns true if *this >= RHS when both are considered unsigned.
755 /// @brief Unsigned greater or equal comparison
756 bool uge(const APInt& RHS) const {
760 /// Regards both *this and RHS as signed quantities and compares them for
761 /// validity of the greater-or-equal relationship.
762 /// @returns true if *this >= RHS when both are considered signed.
763 /// @brief Signed greather or equal comparison
764 bool sge(const APInt& RHS) const {
769 /// @name Resizing Operators
771 /// Truncate the APInt to a specified width. It is an error to specify a width
772 /// that is greater than or equal to the current width.
773 /// @brief Truncate to new width.
774 APInt &trunc(uint32_t width);
776 /// This operation sign extends the APInt to a new width. If the high order
777 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
778 /// It is an error to specify a width that is less than or equal to the
780 /// @brief Sign extend to a new width.
781 APInt &sext(uint32_t width);
783 /// This operation zero extends the APInt to a new width. The high order bits
784 /// are filled with 0 bits. It is an error to specify a width that is less
785 /// than or equal to the current width.
786 /// @brief Zero extend to a new width.
787 APInt &zext(uint32_t width);
789 /// Make this APInt have the bit width given by \p width. The value is sign
790 /// extended, truncated, or left alone to make it that width.
791 /// @brief Sign extend or truncate to width
792 APInt &sextOrTrunc(uint32_t width);
794 /// Make this APInt have the bit width given by \p width. The value is zero
795 /// extended, truncated, or left alone to make it that width.
796 /// @brief Zero extend or truncate to width
797 APInt &zextOrTrunc(uint32_t width);
800 /// @name Bit Manipulation Operators
802 /// @brief Set every bit to 1.
805 /// Set the given bit to 1 whose position is given as "bitPosition".
806 /// @brief Set a given bit to 1.
807 APInt& set(uint32_t bitPosition);
809 /// @brief Set every bit to 0.
812 /// Set the given bit to 0 whose position is given as "bitPosition".
813 /// @brief Set a given bit to 0.
814 APInt& clear(uint32_t bitPosition);
816 /// @brief Toggle every bit to its opposite value.
819 /// Toggle a given bit to its opposite value whose position is given
820 /// as "bitPosition".
821 /// @brief Toggles a given bit to its opposite value.
822 APInt& flip(uint32_t bitPosition);
825 /// @name Value Characterization Functions
828 /// @returns the total number of bits.
829 inline uint32_t getBitWidth() const {
833 /// Here one word's bitwidth equals to that of uint64_t.
834 /// @returns the number of words to hold the integer value of this APInt.
835 /// @brief Get the number of words.
836 inline uint32_t getNumWords() const {
837 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
840 /// This function returns the number of active bits which is defined as the
841 /// bit width minus the number of leading zeros. This is used in several
842 /// computations to see how "wide" the value is.
843 /// @brief Compute the number of active bits in the value
844 inline uint32_t getActiveBits() const {
845 return BitWidth - countLeadingZeros();
848 /// This function returns the number of active words in the value of this
849 /// APInt. This is used in conjunction with getActiveData to extract the raw
850 /// value of the APInt.
851 inline uint32_t getActiveWords() const {
852 return whichWord(getActiveBits()-1) + 1;
855 /// Computes the minimum bit width for this APInt while considering it to be
856 /// a signed (and probably negative) value. If the value is not negative,
857 /// this function returns the same value as getActiveBits(). Otherwise, it
858 /// returns the smallest bit width that will retain the negative value. For
859 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
860 /// for -1, this function will always return 1.
861 /// @brief Get the minimum bit size for this signed APInt
862 inline uint32_t getMinSignedBits() const {
864 return BitWidth - countLeadingOnes() + 1;
865 return getActiveBits()+1;
868 /// This method attempts to return the value of this APInt as a zero extended
869 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
870 /// uint64_t. Otherwise an assertion will result.
871 /// @brief Get zero extended value
872 inline uint64_t getZExtValue() const {
875 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
879 /// This method attempts to return the value of this APInt as a sign extended
880 /// int64_t. The bit width must be <= 64 or the value must fit within an
881 /// int64_t. Otherwise an assertion will result.
882 /// @brief Get sign extended value
883 inline int64_t getSExtValue() const {
885 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
886 (APINT_BITS_PER_WORD - BitWidth);
887 assert(getActiveBits() <= 64 && "Too many bits for int64_t");
888 return int64_t(pVal[0]);
891 /// This method determines how many bits are required to hold the APInt
892 /// equivalent of the string given by \p str of length \p slen.
893 /// @brief Get bits required for string value.
894 static uint32_t getBitsNeeded(const char* str, uint32_t slen, uint8_t radix);
896 /// countLeadingZeros - This function is an APInt version of the
897 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
898 /// of zeros from the most significant bit to the first one bit.
899 /// @returns BitWidth if the value is zero.
900 /// @returns the number of zeros from the most significant bit to the first
902 uint32_t countLeadingZeros() const;
904 /// countLeadingOnes - This function counts the number of contiguous 1 bits
905 /// in the high order bits. The count stops when the first 0 bit is reached.
906 /// @returns 0 if the high order bit is not set
907 /// @returns the number of 1 bits from the most significant to the least
908 /// @brief Count the number of leading one bits.
909 uint32_t countLeadingOnes() const;
911 /// countTrailingZeros - This function is an APInt version of the
912 /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts
913 /// the number of zeros from the least significant bit to the first set bit.
914 /// @returns BitWidth if the value is zero.
915 /// @returns the number of zeros from the least significant bit to the first
917 /// @brief Count the number of trailing zero bits.
918 uint32_t countTrailingZeros() const;
920 /// countPopulation - This function is an APInt version of the
921 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
922 /// of 1 bits in the APInt value.
923 /// @returns 0 if the value is zero.
924 /// @returns the number of set bits.
925 /// @brief Count the number of bits set.
926 uint32_t countPopulation() const;
929 /// @name Conversion Functions
932 /// This is used internally to convert an APInt to a string.
933 /// @brief Converts an APInt to a std::string
934 std::string toString(uint8_t radix, bool wantSigned) const;
936 /// Considers the APInt to be unsigned and converts it into a string in the
937 /// radix given. The radix can be 2, 8, 10 or 16.
938 /// @returns a character interpretation of the APInt
939 /// @brief Convert unsigned APInt to string representation.
940 inline std::string toStringUnsigned(uint8_t radix = 10) const {
941 return toString(radix, false);
944 /// Considers the APInt to be unsigned and converts it into a string in the
945 /// radix given. The radix can be 2, 8, 10 or 16.
946 /// @returns a character interpretation of the APInt
947 /// @brief Convert unsigned APInt to string representation.
948 inline std::string toStringSigned(uint8_t radix = 10) const {
949 return toString(radix, true);
952 /// @returns a byte-swapped representation of this APInt Value.
953 APInt byteSwap() const;
955 /// @brief Converts this APInt to a double value.
956 double roundToDouble(bool isSigned) const;
958 /// @brief Converts this unsigned APInt to a double value.
959 double roundToDouble() const {
960 return roundToDouble(false);
963 /// @brief Converts this signed APInt to a double value.
964 double signedRoundToDouble() const {
965 return roundToDouble(true);
968 /// The conversion does not do a translation from integer to double, it just
969 /// re-interprets the bits as a double. Note that it is valid to do this on
970 /// any bit width. Exactly 64 bits will be translated.
971 /// @brief Converts APInt bits to a double
972 double bitsToDouble() const {
977 T.I = (isSingleWord() ? VAL : pVal[0]);
981 /// The conversion does not do a translation from integer to float, it just
982 /// re-interprets the bits as a float. Note that it is valid to do this on
983 /// any bit width. Exactly 32 bits will be translated.
984 /// @brief Converts APInt bits to a double
985 float bitsToFloat() const {
990 T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
994 /// The conversion does not do a translation from double to integer, it just
995 /// re-interprets the bits of the double. Note that it is valid to do this on
996 /// any bit width but bits from V may get truncated.
997 /// @brief Converts a double to APInt bits.
998 APInt& doubleToBits(double V) {
1008 return clearUnusedBits();
1011 /// The conversion does not do a translation from float to integer, it just
1012 /// re-interprets the bits of the float. Note that it is valid to do this on
1013 /// any bit width but bits from V may get truncated.
1014 /// @brief Converts a float to APInt bits.
1015 APInt& floatToBits(float V) {
1025 return clearUnusedBits();
1029 /// @name Mathematics Operations
1032 /// @returns the floor log base 2 of this APInt.
1033 inline uint32_t logBase2() const {
1034 return BitWidth - 1 - countLeadingZeros();
1037 /// @returns the log base 2 of this APInt if its an exact power of two, -1
1039 inline int32_t exactLogBase2() const {
1045 /// @brief Compute the square root
1048 /// If *this is < 0 then return -(*this), otherwise *this;
1049 /// @brief Get the absolute value;
1059 /// @name Building-block Operations for APInt and APFloat
1062 // These building block operations operate on a representation of
1063 // arbitrary precision, two's-complement, bignum integer values.
1064 // They should be sufficient to implement APInt and APFloat bignum
1065 // requirements. Inputs are generally a pointer to the base of an
1066 // array of integer parts, representing an unsigned bignum, and a
1067 // count of how many parts there are.
1069 /// Sets the least significant part of a bignum to the input value,
1070 /// and zeroes out higher parts. */
1071 static void tcSet(integerPart *, integerPart, unsigned int);
1073 /// Assign one bignum to another.
1074 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1076 /// Returns true if a bignum is zero, false otherwise.
1077 static bool tcIsZero(const integerPart *, unsigned int);
1079 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1080 static int tcExtractBit(const integerPart *, unsigned int bit);
1082 /// Copy the bit vector of width srcBITS from SRC, starting at bit
1083 /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
1084 /// becomes the least significant bit of DST. All high bits above
1085 /// srcBITS in DST are zero-filled.
1086 static void tcExtract(integerPart *, unsigned int dstCount, const integerPart *,
1087 unsigned int srcBits, unsigned int srcLSB);
1089 /// Set the given bit of a bignum. Zero-based.
1090 static void tcSetBit(integerPart *, unsigned int bit);
1092 /// Returns the bit number of the least or most significant set bit
1093 /// of a number. If the input number has no bits set -1U is
1095 static unsigned int tcLSB(const integerPart *, unsigned int);
1096 static unsigned int tcMSB(const integerPart *, unsigned int);
1098 /// Negate a bignum in-place.
1099 static void tcNegate(integerPart *, unsigned int);
1101 /// DST += RHS + CARRY where CARRY is zero or one. Returns the
1103 static integerPart tcAdd(integerPart *, const integerPart *,
1104 integerPart carry, unsigned);
1106 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the
1108 static integerPart tcSubtract(integerPart *, const integerPart *,
1109 integerPart carry, unsigned);
1111 /// DST += SRC * MULTIPLIER + PART if add is true
1112 /// DST = SRC * MULTIPLIER + PART if add is false
1114 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
1115 /// they must start at the same point, i.e. DST == SRC.
1117 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1118 /// returned. Otherwise DST is filled with the least significant
1119 /// DSTPARTS parts of the result, and if all of the omitted higher
1120 /// parts were zero return zero, otherwise overflow occurred and
1122 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1123 integerPart multiplier, integerPart carry,
1124 unsigned int srcParts, unsigned int dstParts,
1127 /// DST = LHS * RHS, where DST has the same width as the operands
1128 /// and is filled with the least significant parts of the result.
1129 /// Returns one if overflow occurred, otherwise zero. DST must be
1130 /// disjoint from both operands.
1131 static int tcMultiply(integerPart *, const integerPart *,
1132 const integerPart *, unsigned);
1134 /// DST = LHS * RHS, where DST has width the sum of the widths of
1135 /// the operands. No overflow occurs. DST must be disjoint from
1136 /// both operands. Returns the number of parts required to hold the
1138 static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1139 const integerPart *, unsigned, unsigned);
1141 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1142 /// Otherwise set LHS to LHS / RHS with the fractional part
1143 /// discarded, set REMAINDER to the remainder, return zero. i.e.
1145 /// OLD_LHS = RHS * LHS + REMAINDER
1147 /// SCRATCH is a bignum of the same size as the operands and result
1148 /// for use by the routine; its contents need not be initialized
1149 /// and are destroyed. LHS, REMAINDER and SCRATCH must be
1151 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1152 integerPart *remainder, integerPart *scratch,
1153 unsigned int parts);
1155 /// Shift a bignum left COUNT bits. Shifted in bits are zero.
1156 /// There are no restrictions on COUNT.
1157 static void tcShiftLeft(integerPart *, unsigned int parts,
1158 unsigned int count);
1160 /// Shift a bignum right COUNT bits. Shifted in bits are zero.
1161 /// There are no restrictions on COUNT.
1162 static void tcShiftRight(integerPart *, unsigned int parts,
1163 unsigned int count);
1165 /// The obvious AND, OR and XOR and complement operations.
1166 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1167 static void tcOr(integerPart *, const integerPart *, unsigned int);
1168 static void tcXor(integerPart *, const integerPart *, unsigned int);
1169 static void tcComplement(integerPart *, unsigned int);
1171 /// Comparison (unsigned) of two bignums.
1172 static int tcCompare(const integerPart *, const integerPart *,
1175 /// Increment a bignum in-place. Return the carry flag.
1176 static integerPart tcIncrement(integerPart *, unsigned int);
1178 /// Set the least significant BITS and clear the rest.
1179 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1182 /// @brief debug method
1188 inline bool operator==(uint64_t V1, const APInt& V2) {
1192 inline bool operator!=(uint64_t V1, const APInt& V2) {
1196 namespace APIntOps {
1198 /// @brief Determine the smaller of two APInts considered to be signed.
1199 inline APInt smin(const APInt &A, const APInt &B) {
1200 return A.slt(B) ? A : B;
1203 /// @brief Determine the larger of two APInts considered to be signed.
1204 inline APInt smax(const APInt &A, const APInt &B) {
1205 return A.sgt(B) ? A : B;
1208 /// @brief Determine the smaller of two APInts considered to be signed.
1209 inline APInt umin(const APInt &A, const APInt &B) {
1210 return A.ult(B) ? A : B;
1213 /// @brief Determine the larger of two APInts considered to be unsigned.
1214 inline APInt umax(const APInt &A, const APInt &B) {
1215 return A.ugt(B) ? A : B;
1218 /// @brief Check if the specified APInt has a N-bits integer value.
1219 inline bool isIntN(uint32_t N, const APInt& APIVal) {
1220 return APIVal.isIntN(N);
1223 /// @returns true if the argument APInt value is a sequence of ones
1224 /// starting at the least significant bit with the remainder zero.
1225 inline bool isMask(uint32_t numBits, const APInt& APIVal) {
1226 return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
1229 /// @returns true if the argument APInt value contains a sequence of ones
1230 /// with the remainder zero.
1231 inline bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
1232 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1235 /// @returns a byte-swapped representation of the specified APInt Value.
1236 inline APInt byteSwap(const APInt& APIVal) {
1237 return APIVal.byteSwap();
1240 /// @returns the floor log base 2 of the specified APInt value.
1241 inline uint32_t logBase2(const APInt& APIVal) {
1242 return APIVal.logBase2();
1245 /// GreatestCommonDivisor - This function returns the greatest common
1246 /// divisor of the two APInt values using Enclid's algorithm.
1247 /// @returns the greatest common divisor of Val1 and Val2
1248 /// @brief Compute GCD of two APInt values.
1249 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1251 /// Treats the APInt as an unsigned value for conversion purposes.
1252 /// @brief Converts the given APInt to a double value.
1253 inline double RoundAPIntToDouble(const APInt& APIVal) {
1254 return APIVal.roundToDouble();
1257 /// Treats the APInt as a signed value for conversion purposes.
1258 /// @brief Converts the given APInt to a double value.
1259 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1260 return APIVal.signedRoundToDouble();
1263 /// @brief Converts the given APInt to a float vlalue.
1264 inline float RoundAPIntToFloat(const APInt& APIVal) {
1265 return float(RoundAPIntToDouble(APIVal));
1268 /// Treast the APInt as a signed value for conversion purposes.
1269 /// @brief Converts the given APInt to a float value.
1270 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1271 return float(APIVal.signedRoundToDouble());
1274 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1275 /// @brief Converts the given double value into a APInt.
1276 APInt RoundDoubleToAPInt(double Double, uint32_t width);
1278 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1279 /// @brief Converts a float value into a APInt.
1280 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
1281 return RoundDoubleToAPInt(double(Float), width);
1284 /// Arithmetic right-shift the APInt by shiftAmt.
1285 /// @brief Arithmetic right-shift function.
1286 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
1287 return LHS.ashr(shiftAmt);
1290 /// Logical right-shift the APInt by shiftAmt.
1291 /// @brief Logical right-shift function.
1292 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
1293 return LHS.lshr(shiftAmt);
1296 /// Left-shift the APInt by shiftAmt.
1297 /// @brief Left-shift function.
1298 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
1299 return LHS.shl(shiftAmt);
1302 /// Signed divide APInt LHS by APInt RHS.
1303 /// @brief Signed division function for APInt.
1304 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1305 return LHS.sdiv(RHS);
1308 /// Unsigned divide APInt LHS by APInt RHS.
1309 /// @brief Unsigned division function for APInt.
1310 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1311 return LHS.udiv(RHS);
1314 /// Signed remainder operation on APInt.
1315 /// @brief Function for signed remainder operation.
1316 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1317 return LHS.srem(RHS);
1320 /// Unsigned remainder operation on APInt.
1321 /// @brief Function for unsigned remainder operation.
1322 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1323 return LHS.urem(RHS);
1326 /// Performs multiplication on APInt values.
1327 /// @brief Function for multiplication operation.
1328 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1332 /// Performs addition on APInt values.
1333 /// @brief Function for addition operation.
1334 inline APInt add(const APInt& LHS, const APInt& RHS) {
1338 /// Performs subtraction on APInt values.
1339 /// @brief Function for subtraction operation.
1340 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1344 /// Performs bitwise AND operation on APInt LHS and
1346 /// @brief Bitwise AND function for APInt.
1347 inline APInt And(const APInt& LHS, const APInt& RHS) {
1351 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1352 /// @brief Bitwise OR function for APInt.
1353 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1357 /// Performs bitwise XOR operation on APInt.
1358 /// @brief Bitwise XOR function for APInt.
1359 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1363 /// Performs a bitwise complement operation on APInt.
1364 /// @brief Bitwise complement function.
1365 inline APInt Not(const APInt& APIVal) {
1369 } // End of APIntOps namespace
1371 } // End of llvm namespace