1 //===-- llvm/Support/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"
24 //===----------------------------------------------------------------------===//
26 //===----------------------------------------------------------------------===//
28 /// APInt - This class represents arbitrary precision constant integral values.
29 /// It is a functional replacement for common case unsigned integer type like
30 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
31 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
32 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
33 /// and methods to manipulate integer values of any bit-width. It supports both
34 /// the typical integer arithmetic and comparison operations as well as bitwise
37 /// The class has several invariants worth noting:
38 /// * All bit, byte, and word positions are zero-based.
39 /// * Once the bit width is set, it doesn't change except by the Truncate,
40 /// SignExtend, or ZeroExtend operations.
41 /// * All binary operators must be on APInt instances of the same bit width.
42 /// Attempting to use these operators on instances with different bit
43 /// widths will yield an assertion.
44 /// * The value is stored canonically as an unsigned value. For operations
45 /// where it makes a difference, there are both signed and unsigned variants
46 /// of the operation. For example, sdiv and udiv. However, because the bit
47 /// widths must be the same, operations such as Mul and Add produce the same
48 /// results regardless of whether the values are interpreted as signed or
50 /// * In general, the class tries to follow the style of computation that LLVM
51 /// uses in its IR. This simplifies its use for LLVM.
53 /// @brief Class for arbitrary precision integers.
56 uint32_t BitWidth; ///< The number of bits in this APInt.
58 /// This union is used to store the integer value. When the
59 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
61 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
62 uint64_t *pVal; ///< Used to store the >64 bits integer value.
65 /// This enum is used to hold the constants we needed for APInt.
67 APINT_BITS_PER_WORD = sizeof(uint64_t) * 8, ///< Bits in a word
68 APINT_WORD_SIZE = sizeof(uint64_t) ///< Byte size of a word
71 /// This constructor is used only internally for speed of construction of
72 /// temporaries. It is unsafe for general use so it is not public.
73 /// @brief Fast internal constructor
74 APInt(uint64_t* val, uint32_t bits) : BitWidth(bits), pVal(val) { }
76 /// @returns true if the number of bits <= 64, false otherwise.
77 /// @brief Determine if this APInt just has one word to store value.
78 inline bool isSingleWord() const {
79 return BitWidth <= APINT_BITS_PER_WORD;
82 /// @returns the word position for the specified bit position.
83 /// @brief Determine which word a bit is in.
84 static inline uint32_t whichWord(uint32_t bitPosition) {
85 return bitPosition / APINT_BITS_PER_WORD;
88 /// @returns the bit position in a word for the specified bit position
90 /// @brief Determine which bit in a word a bit is in.
91 static inline uint32_t whichBit(uint32_t bitPosition) {
92 return bitPosition % APINT_BITS_PER_WORD;
95 /// This method generates and returns a uint64_t (word) mask for a single
96 /// bit at a specific bit position. This is used to mask the bit in the
97 /// corresponding word.
98 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
99 /// @brief Get a single bit mask.
100 static inline uint64_t maskBit(uint32_t bitPosition) {
101 return 1ULL << whichBit(bitPosition);
104 /// This method is used internally to clear the to "N" bits in the high order
105 /// word that are not used by the APInt. This is needed after the most
106 /// significant word is assigned a value to ensure that those bits are
108 /// @brief Clear unused high order bits
109 inline APInt& clearUnusedBits() {
110 // Compute how many bits are used in the final word
111 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
113 // If all bits are used, we want to leave the value alone. This also
114 // avoids the undefined behavior of >> when the shfit is the same size as
115 // the word size (64).
118 // Mask out the hight bits.
119 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
123 pVal[getNumWords() - 1] &= mask;
127 /// @returns the corresponding word for the specified bit position.
128 /// @brief Get the word corresponding to a bit position
129 inline uint64_t getWord(uint32_t bitPosition) const {
130 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
133 /// This is used by the constructors that take string arguments.
134 /// @brief Convert a char array into an APInt
135 void fromString(uint32_t numBits, const char *strStart, uint32_t slen,
138 /// This is used by the toString method to divide by the radix. It simply
139 /// provides a more convenient form of divide for internal use since KnuthDiv
140 /// has specific constraints on its inputs. If those constraints are not met
141 /// then it provides a simpler form of divide.
142 /// @brief An internal division function for dividing APInts.
143 static void divide(const APInt LHS, uint32_t lhsWords,
144 const APInt &RHS, uint32_t rhsWords,
145 APInt *Quotient, APInt *Remainder);
148 /// @brief debug method
153 /// @name Constructors
155 /// If isSigned is true then val is treated as if it were a signed value
156 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
157 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
158 /// the range of val are zero filled).
159 /// @param numBits the bit width of the constructed APInt
160 /// @param val the initial value of the APInt
161 /// @param isSigned how to treat signedness of val
162 /// @brief Create a new APInt of numBits width, initialized as val.
163 APInt(uint32_t numBits, uint64_t val, bool isSigned = false);
165 /// Note that numWords can be smaller or larger than the corresponding bit
166 /// width but any extraneous bits will be dropped.
167 /// @param numBits the bit width of the constructed APInt
168 /// @param numWords the number of words in bigVal
169 /// @param bigVal a sequence of words to form the initial value of the APInt
170 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
171 APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
173 /// This constructor interprets Val as a string in the given radix. The
174 /// interpretation stops when the first charater that is not suitable for the
175 /// radix is encountered. Acceptable radix values are 2, 8, 10 and 16. It is
176 /// an error for the value implied by the string to require more bits than
178 /// @param numBits the bit width of the constructed APInt
179 /// @param val the string to be interpreted
180 /// @param radix the radix of Val to use for the intepretation
181 /// @brief Construct an APInt from a string representation.
182 APInt(uint32_t numBits, const std::string& val, uint8_t radix);
184 /// This constructor interprets the slen characters starting at StrStart as
185 /// a string in the given radix. The interpretation stops when the first
186 /// character that is not suitable for the radix is encountered. Acceptable
187 /// radix values are 2, 8, 10 and 16. It is an error for the value implied by
188 /// the string to require more bits than numBits.
189 /// @param numBits the bit width of the constructed APInt
190 /// @param strStart the start of the string to be interpreted
191 /// @param slen the maximum number of characters to interpret
192 /// @param radix the radix to use for the conversion
193 /// @brief Construct an APInt from a string representation.
194 APInt(uint32_t numBits, const char strStart[], uint32_t slen, uint8_t radix);
196 /// Simply makes *this a copy of that.
197 /// @brief Copy Constructor.
198 APInt(const APInt& that);
200 /// @brief Destructor.
204 /// @name Value Tests
206 /// This tests the high bit of this APInt to determine if it is set.
207 /// @returns true if this APInt is negative, false otherwise
208 /// @brief Determine sign of this APInt.
209 bool isNegative() const {
210 return (*this)[BitWidth - 1];
213 /// This tests the high bit of the APInt to determine if it is unset.
214 /// @brief Determine if this APInt Value is positive (not negative).
215 bool isPositive() const {
216 return !isNegative();
219 /// This tests if the value of this APInt is strictly positive (> 0).
220 /// @returns true if this APInt is Positive and not zero.
221 /// @brief Determine if this APInt Value is strictly positive.
222 inline bool isStrictlyPositive() const {
223 return isPositive() && (*this) != 0;
226 /// This checks to see if the value has all bits of the APInt are set or not.
227 /// @brief Determine if all bits are set
228 inline bool isAllOnesValue() const {
229 return countPopulation() == BitWidth;
232 /// This checks to see if the value of this APInt is the maximum unsigned
233 /// value for the APInt's bit width.
234 /// @brief Determine if this is the largest unsigned value.
235 bool isMaxValue() const {
236 return countPopulation() == BitWidth;
239 /// This checks to see if the value of this APInt is the maximum signed
240 /// value for the APInt's bit width.
241 /// @brief Determine if this is the largest signed value.
242 bool isMaxSignedValue() const {
243 return BitWidth == 1 ? VAL == 0 :
244 !isNegative() && countPopulation() == BitWidth - 1;
247 /// This checks to see if the value of this APInt is the minimum unsigned
248 /// value for the APInt's bit width.
249 /// @brief Determine if this is the smallest unsigned value.
250 bool isMinValue() const {
251 return countPopulation() == 0;
254 /// This checks to see if the value of this APInt is the minimum signed
255 /// value for the APInt's bit width.
256 /// @brief Determine if this is the smallest signed value.
257 bool isMinSignedValue() const {
258 return BitWidth == 1 ? VAL == 1 :
259 isNegative() && countPopulation() == 1;
262 /// @brief Check if this APInt has an N-bits integer value.
263 inline bool isIntN(uint32_t N) const {
264 assert(N && "N == 0 ???");
265 if (isSingleWord()) {
266 return VAL == (VAL & (~0ULL >> (64 - N)));
268 APInt Tmp(N, getNumWords(), pVal);
269 return Tmp == (*this);
273 /// @returns true if the argument APInt value is a power of two > 0.
274 bool isPowerOf2() const;
276 /// isSignBit - Return true if this is the value returned by getSignBit.
277 bool isSignBit() const { return isMinSignedValue(); }
279 /// This converts the APInt to a boolean value as a test against zero.
280 /// @brief Boolean conversion function.
281 inline bool getBoolValue() const {
285 /// getLimitedValue - If this value is smaller than the specified limit,
286 /// return it, otherwise return the limit value. This causes the value
287 /// to saturate to the limit.
288 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
289 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
290 Limit : getZExtValue();
294 /// @name Value Generators
296 /// @brief Gets maximum unsigned value of APInt for specific bit width.
297 static APInt getMaxValue(uint32_t numBits) {
298 return APInt(numBits, 0).set();
301 /// @brief Gets maximum signed value of APInt for a specific bit width.
302 static APInt getSignedMaxValue(uint32_t numBits) {
303 return APInt(numBits, 0).set().clear(numBits - 1);
306 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
307 static APInt getMinValue(uint32_t numBits) {
308 return APInt(numBits, 0);
311 /// @brief Gets minimum signed value of APInt for a specific bit width.
312 static APInt getSignedMinValue(uint32_t numBits) {
313 return APInt(numBits, 0).set(numBits - 1);
316 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
317 /// it helps code readability when we want to get a SignBit.
318 /// @brief Get the SignBit for a specific bit width.
319 inline static APInt getSignBit(uint32_t BitWidth) {
320 return getSignedMinValue(BitWidth);
323 /// @returns the all-ones value for an APInt of the specified bit-width.
324 /// @brief Get the all-ones value.
325 static APInt getAllOnesValue(uint32_t numBits) {
326 return APInt(numBits, 0).set();
329 /// @returns the '0' value for an APInt of the specified bit-width.
330 /// @brief Get the '0' value.
331 static APInt getNullValue(uint32_t numBits) {
332 return APInt(numBits, 0);
335 /// Get an APInt with the same BitWidth as this APInt, just zero mask
336 /// the low bits and right shift to the least significant bit.
337 /// @returns the high "numBits" bits of this APInt.
338 APInt getHiBits(uint32_t numBits) const;
340 /// Get an APInt with the same BitWidth as this APInt, just zero mask
342 /// @returns the low "numBits" bits of this APInt.
343 APInt getLoBits(uint32_t numBits) const;
345 /// Constructs an APInt value that has a contiguous range of bits set. The
346 /// bits from loBit to hiBit will be set. All other bits will be zero. For
347 /// example, with parameters(32, 15, 0) you would get 0x0000FFFF. If hiBit is
348 /// less than loBit then the set bits "wrap". For example, with
349 /// parameters (32, 3, 28), you would get 0xF000000F.
350 /// @param numBits the intended bit width of the result
351 /// @param loBit the index of the lowest bit set.
352 /// @param hiBit the index of the highest bit set.
353 /// @returns An APInt value with the requested bits set.
354 /// @brief Get a value with a block of bits set.
355 static APInt getBitsSet(uint32_t numBits, uint32_t loBit, uint32_t hiBit) {
356 assert(hiBit < numBits && "hiBit out of range");
357 assert(loBit < numBits && "loBit out of range");
359 return getLowBitsSet(numBits, hiBit+1) |
360 getHighBitsSet(numBits, numBits-loBit+1);
361 return getLowBitsSet(numBits, hiBit-loBit+1).shl(loBit);
364 /// Constructs an APInt value that has the top hiBitsSet bits set.
365 /// @param numBits the bitwidth of the result
366 /// @param hiBitsSet the number of high-order bits set in the result.
367 /// @brief Get a value with high bits set
368 static APInt getHighBitsSet(uint32_t numBits, uint32_t hiBitsSet) {
369 assert(hiBitsSet <= numBits && "Too many bits to set!");
370 // Handle a degenerate case, to avoid shifting by word size
372 return APInt(numBits, 0);
373 uint32_t shiftAmt = numBits - hiBitsSet;
374 // For small values, return quickly
375 if (numBits <= APINT_BITS_PER_WORD)
376 return APInt(numBits, ~0ULL << shiftAmt);
377 return (~APInt(numBits, 0)).shl(shiftAmt);
380 /// Constructs an APInt value that has the bottom loBitsSet bits set.
381 /// @param numBits the bitwidth of the result
382 /// @param loBitsSet the number of low-order bits set in the result.
383 /// @brief Get a value with low bits set
384 static APInt getLowBitsSet(uint32_t numBits, uint32_t loBitsSet) {
385 assert(loBitsSet <= numBits && "Too many bits to set!");
386 // Handle a degenerate case, to avoid shifting by word size
388 return APInt(numBits, 0);
389 if (loBitsSet == APINT_BITS_PER_WORD)
390 return APInt(numBits, -1ULL);
391 // For small values, return quickly
392 if (numBits < APINT_BITS_PER_WORD)
393 return APInt(numBits, (1ULL << loBitsSet) - 1);
394 return (~APInt(numBits, 0)).lshr(numBits - loBitsSet);
397 /// The hash value is computed as the sum of the words and the bit width.
398 /// @returns A hash value computed from the sum of the APInt words.
399 /// @brief Get a hash value based on this APInt
400 uint64_t getHashValue() const;
402 /// This function returns a pointer to the internal storage of the APInt.
403 /// This is useful for writing out the APInt in binary form without any
405 inline const uint64_t* getRawData() const {
412 /// @name Unary Operators
414 /// @returns a new APInt value representing *this incremented by one
415 /// @brief Postfix increment operator.
416 inline const APInt operator++(int) {
422 /// @returns *this incremented by one
423 /// @brief Prefix increment operator.
426 /// @returns a new APInt representing *this decremented by one.
427 /// @brief Postfix decrement operator.
428 inline const APInt operator--(int) {
434 /// @returns *this decremented by one.
435 /// @brief Prefix decrement operator.
438 /// Performs a bitwise complement operation on this APInt.
439 /// @returns an APInt that is the bitwise complement of *this
440 /// @brief Unary bitwise complement operator.
441 APInt operator~() const;
443 /// Negates *this using two's complement logic.
444 /// @returns An APInt value representing the negation of *this.
445 /// @brief Unary negation operator
446 inline APInt operator-() const {
447 return APInt(BitWidth, 0) - (*this);
450 /// Performs logical negation operation on this APInt.
451 /// @returns true if *this is zero, false otherwise.
452 /// @brief Logical negation operator.
453 bool operator !() const;
456 /// @name Assignment Operators
458 /// @returns *this after assignment of RHS.
459 /// @brief Copy assignment operator.
460 APInt& operator=(const APInt& RHS);
462 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
463 /// the bit width, the excess bits are truncated. If the bit width is larger
464 /// than 64, the value is zero filled in the unspecified high order bits.
465 /// @returns *this after assignment of RHS value.
466 /// @brief Assignment operator.
467 APInt& operator=(uint64_t RHS);
469 /// Performs a bitwise AND operation on this APInt and RHS. The result is
470 /// assigned to *this.
471 /// @returns *this after ANDing with RHS.
472 /// @brief Bitwise AND assignment operator.
473 APInt& operator&=(const APInt& RHS);
475 /// Performs a bitwise OR operation on this APInt and RHS. The result is
477 /// @returns *this after ORing with RHS.
478 /// @brief Bitwise OR assignment operator.
479 APInt& operator|=(const APInt& RHS);
481 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
482 /// assigned to *this.
483 /// @returns *this after XORing with RHS.
484 /// @brief Bitwise XOR assignment operator.
485 APInt& operator^=(const APInt& RHS);
487 /// Multiplies this APInt by RHS and assigns the result to *this.
489 /// @brief Multiplication assignment operator.
490 APInt& operator*=(const APInt& RHS);
492 /// Adds RHS to *this and assigns the result to *this.
494 /// @brief Addition assignment operator.
495 APInt& operator+=(const APInt& RHS);
497 /// Subtracts RHS from *this and assigns the result to *this.
499 /// @brief Subtraction assignment operator.
500 APInt& operator-=(const APInt& RHS);
502 /// Shifts *this left by shiftAmt and assigns the result to *this.
503 /// @returns *this after shifting left by shiftAmt
504 /// @brief Left-shift assignment function.
505 inline APInt& operator<<=(uint32_t shiftAmt) {
506 *this = shl(shiftAmt);
511 /// @name Binary Operators
513 /// Performs a bitwise AND operation on *this and RHS.
514 /// @returns An APInt value representing the bitwise AND of *this and RHS.
515 /// @brief Bitwise AND operator.
516 APInt operator&(const APInt& RHS) const;
517 APInt And(const APInt& RHS) const {
518 return this->operator&(RHS);
521 /// Performs a bitwise OR operation on *this and RHS.
522 /// @returns An APInt value representing the bitwise OR of *this and RHS.
523 /// @brief Bitwise OR operator.
524 APInt operator|(const APInt& RHS) const;
525 APInt Or(const APInt& RHS) const {
526 return this->operator|(RHS);
529 /// Performs a bitwise XOR operation on *this and RHS.
530 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
531 /// @brief Bitwise XOR operator.
532 APInt operator^(const APInt& RHS) const;
533 APInt Xor(const APInt& RHS) const {
534 return this->operator^(RHS);
537 /// Multiplies this APInt by RHS and returns the result.
538 /// @brief Multiplication operator.
539 APInt operator*(const APInt& RHS) const;
541 /// Adds RHS to this APInt and returns the result.
542 /// @brief Addition operator.
543 APInt operator+(const APInt& RHS) const;
544 APInt operator+(uint64_t RHS) const {
545 return (*this) + APInt(BitWidth, RHS);
548 /// Subtracts RHS from this APInt and returns the result.
549 /// @brief Subtraction operator.
550 APInt operator-(const APInt& RHS) const;
551 APInt operator-(uint64_t RHS) const {
552 return (*this) - APInt(BitWidth, RHS);
555 APInt operator<<(unsigned Bits) const {
559 /// Arithmetic right-shift this APInt by shiftAmt.
560 /// @brief Arithmetic right-shift function.
561 APInt ashr(uint32_t shiftAmt) const;
563 /// Logical right-shift this APInt by shiftAmt.
564 /// @brief Logical right-shift function.
565 APInt lshr(uint32_t shiftAmt) const;
567 /// Left-shift this APInt by shiftAmt.
568 /// @brief Left-shift function.
569 APInt shl(uint32_t shiftAmt) const;
571 /// @brief Rotate left by rotateAmt.
572 APInt rotl(uint32_t rotateAmt) const;
574 /// @brief Rotate right by rotateAmt.
575 APInt rotr(uint32_t rotateAmt) const;
577 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
578 /// RHS are treated as unsigned quantities for purposes of this division.
579 /// @returns a new APInt value containing the division result
580 /// @brief Unsigned division operation.
581 APInt udiv(const APInt& RHS) const;
583 /// Signed divide this APInt by APInt RHS.
584 /// @brief Signed division function for APInt.
585 inline APInt sdiv(const APInt& RHS) const {
587 if (RHS.isNegative())
588 return (-(*this)).udiv(-RHS);
590 return -((-(*this)).udiv(RHS));
591 else if (RHS.isNegative())
592 return -(this->udiv(-RHS));
593 return this->udiv(RHS);
596 /// Perform an unsigned remainder operation on this APInt with RHS being the
597 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
598 /// of this operation. Note that this is a true remainder operation and not
599 /// a modulo operation because the sign follows the sign of the dividend
601 /// @returns a new APInt value containing the remainder result
602 /// @brief Unsigned remainder operation.
603 APInt urem(const APInt& RHS) const;
605 /// Signed remainder operation on APInt.
606 /// @brief Function for signed remainder operation.
607 inline APInt srem(const APInt& RHS) const {
609 if (RHS.isNegative())
610 return -((-(*this)).urem(-RHS));
612 return -((-(*this)).urem(RHS));
613 else if (RHS.isNegative())
614 return this->urem(-RHS);
615 return this->urem(RHS);
618 /// Sometimes it is convenient to divide two APInt values and obtain both
619 /// the quotient and remainder. This function does both operations in the
620 /// same computation making it a little more efficient.
621 /// @brief Dual division/remainder interface.
622 static void udivrem(const APInt &LHS, const APInt &RHS,
623 APInt &Quotient, APInt &Remainder);
625 static void sdivrem(const APInt &LHS, const APInt &RHS,
626 APInt &Quotient, APInt &Remainder)
628 if (LHS.isNegative()) {
629 if (RHS.isNegative())
630 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
632 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
633 Quotient = -Quotient;
634 Remainder = -Remainder;
635 } else if (RHS.isNegative()) {
636 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
637 Quotient = -Quotient;
639 APInt::udivrem(LHS, RHS, Quotient, Remainder);
643 /// @returns the bit value at bitPosition
644 /// @brief Array-indexing support.
645 bool operator[](uint32_t bitPosition) const;
648 /// @name Comparison Operators
650 /// Compares this APInt with RHS for the validity of the equality
652 /// @brief Equality operator.
653 bool operator==(const APInt& RHS) const;
655 /// Compares this APInt with a uint64_t for the validity of the equality
657 /// @returns true if *this == Val
658 /// @brief Equality operator.
659 bool operator==(uint64_t Val) const;
661 /// Compares this APInt with RHS for the validity of the equality
663 /// @returns true if *this == Val
664 /// @brief Equality comparison.
665 bool eq(const APInt &RHS) const {
666 return (*this) == RHS;
669 /// Compares this APInt with RHS for the validity of the inequality
671 /// @returns true if *this != Val
672 /// @brief Inequality operator.
673 inline bool operator!=(const APInt& RHS) const {
674 return !((*this) == RHS);
677 /// Compares this APInt with a uint64_t for the validity of the inequality
679 /// @returns true if *this != Val
680 /// @brief Inequality operator.
681 inline bool operator!=(uint64_t Val) const {
682 return !((*this) == Val);
685 /// Compares this APInt with RHS for the validity of the inequality
687 /// @returns true if *this != Val
688 /// @brief Inequality comparison
689 bool ne(const APInt &RHS) const {
690 return !((*this) == RHS);
693 /// Regards both *this and RHS as unsigned quantities and compares them for
694 /// the validity of the less-than relationship.
695 /// @returns true if *this < RHS when both are considered unsigned.
696 /// @brief Unsigned less than comparison
697 bool ult(const APInt& RHS) const;
699 /// Regards both *this and RHS as signed quantities and compares them for
700 /// validity of the less-than relationship.
701 /// @returns true if *this < RHS when both are considered signed.
702 /// @brief Signed less than comparison
703 bool slt(const APInt& RHS) const;
705 /// Regards both *this and RHS as unsigned quantities and compares them for
706 /// validity of the less-or-equal relationship.
707 /// @returns true if *this <= RHS when both are considered unsigned.
708 /// @brief Unsigned less or equal comparison
709 bool ule(const APInt& RHS) const {
710 return ult(RHS) || eq(RHS);
713 /// Regards both *this and RHS as signed quantities and compares them for
714 /// validity of the less-or-equal relationship.
715 /// @returns true if *this <= RHS when both are considered signed.
716 /// @brief Signed less or equal comparison
717 bool sle(const APInt& RHS) const {
718 return slt(RHS) || eq(RHS);
721 /// Regards both *this and RHS as unsigned quantities and compares them for
722 /// the validity of the greater-than relationship.
723 /// @returns true if *this > RHS when both are considered unsigned.
724 /// @brief Unsigned greather than comparison
725 bool ugt(const APInt& RHS) const {
726 return !ult(RHS) && !eq(RHS);
729 /// Regards both *this and RHS as signed quantities and compares them for
730 /// the validity of the greater-than relationship.
731 /// @returns true if *this > RHS when both are considered signed.
732 /// @brief Signed greather than comparison
733 bool sgt(const APInt& RHS) const {
734 return !slt(RHS) && !eq(RHS);
737 /// Regards both *this and RHS as unsigned quantities and compares them for
738 /// validity of the greater-or-equal relationship.
739 /// @returns true if *this >= RHS when both are considered unsigned.
740 /// @brief Unsigned greater or equal comparison
741 bool uge(const APInt& RHS) const {
745 /// Regards both *this and RHS as signed quantities and compares them for
746 /// validity of the greater-or-equal relationship.
747 /// @returns true if *this >= RHS when both are considered signed.
748 /// @brief Signed greather or equal comparison
749 bool sge(const APInt& RHS) const {
754 /// @name Resizing Operators
756 /// Truncate the APInt to a specified width. It is an error to specify a width
757 /// that is greater than or equal to the current width.
758 /// @brief Truncate to new width.
759 APInt &trunc(uint32_t width);
761 /// This operation sign extends the APInt to a new width. If the high order
762 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
763 /// It is an error to specify a width that is less than or equal to the
765 /// @brief Sign extend to a new width.
766 APInt &sext(uint32_t width);
768 /// This operation zero extends the APInt to a new width. The high order bits
769 /// are filled with 0 bits. It is an error to specify a width that is less
770 /// than or equal to the current width.
771 /// @brief Zero extend to a new width.
772 APInt &zext(uint32_t width);
774 /// Make this APInt have the bit width given by \p width. The value is sign
775 /// extended, truncated, or left alone to make it that width.
776 /// @brief Sign extend or truncate to width
777 APInt &sextOrTrunc(uint32_t width);
779 /// Make this APInt have the bit width given by \p width. The value is zero
780 /// extended, truncated, or left alone to make it that width.
781 /// @brief Zero extend or truncate to width
782 APInt &zextOrTrunc(uint32_t width);
785 /// @name Bit Manipulation Operators
787 /// @brief Set every bit to 1.
790 /// Set the given bit to 1 whose position is given as "bitPosition".
791 /// @brief Set a given bit to 1.
792 APInt& set(uint32_t bitPosition);
794 /// @brief Set every bit to 0.
797 /// Set the given bit to 0 whose position is given as "bitPosition".
798 /// @brief Set a given bit to 0.
799 APInt& clear(uint32_t bitPosition);
801 /// @brief Toggle every bit to its opposite value.
804 /// Toggle a given bit to its opposite value whose position is given
805 /// as "bitPosition".
806 /// @brief Toggles a given bit to its opposite value.
807 APInt& flip(uint32_t bitPosition);
810 /// @name Value Characterization Functions
813 /// @returns the total number of bits.
814 inline uint32_t getBitWidth() const {
818 /// Here one word's bitwidth equals to that of uint64_t.
819 /// @returns the number of words to hold the integer value of this APInt.
820 /// @brief Get the number of words.
821 inline uint32_t getNumWords() const {
822 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
825 /// This function returns the number of active bits which is defined as the
826 /// bit width minus the number of leading zeros. This is used in several
827 /// computations to see how "wide" the value is.
828 /// @brief Compute the number of active bits in the value
829 inline uint32_t getActiveBits() const {
830 return BitWidth - countLeadingZeros();
833 /// This function returns the number of active words in the value of this
834 /// APInt. This is used in conjunction with getActiveData to extract the raw
835 /// value of the APInt.
836 inline uint32_t getActiveWords() const {
837 return whichWord(getActiveBits()-1) + 1;
840 /// Computes the minimum bit width for this APInt while considering it to be
841 /// a signed (and probably negative) value. If the value is not negative,
842 /// this function returns the same value as getActiveBits(). Otherwise, it
843 /// returns the smallest bit width that will retain the negative value. For
844 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
845 /// for -1, this function will always return 1.
846 /// @brief Get the minimum bit size for this signed APInt
847 inline uint32_t getMinSignedBits() const {
849 return BitWidth - countLeadingOnes() + 1;
850 return getActiveBits();
853 /// This method attempts to return the value of this APInt as a zero extended
854 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
855 /// uint64_t. Otherwise an assertion will result.
856 /// @brief Get zero extended value
857 inline uint64_t getZExtValue() const {
860 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
864 /// This method attempts to return the value of this APInt as a sign extended
865 /// int64_t. The bit width must be <= 64 or the value must fit within an
866 /// int64_t. Otherwise an assertion will result.
867 /// @brief Get sign extended value
868 inline int64_t getSExtValue() const {
870 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
871 (APINT_BITS_PER_WORD - BitWidth);
872 assert(getActiveBits() <= 64 && "Too many bits for int64_t");
873 return int64_t(pVal[0]);
876 /// This method determines how many bits are required to hold the APInt
877 /// equivalent of the string given by \p str of length \p slen.
878 /// @brief Get bits required for string value.
879 static uint32_t getBitsNeeded(const char* str, uint32_t slen, uint8_t radix);
881 /// countLeadingZeros - This function is an APInt version of the
882 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
883 /// of zeros from the most significant bit to the first one bit.
884 /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
885 /// @returns the number of zeros from the most significant bit to the first
887 /// @brief Count the number of leading one bits.
888 uint32_t countLeadingZeros() const;
890 /// countLeadingOnes - This function counts the number of contiguous 1 bits
891 /// in the high order bits. The count stops when the first 0 bit is reached.
892 /// @returns 0 if the high order bit is not set
893 /// @returns the number of 1 bits from the most significant to the least
894 /// @brief Count the number of leading one bits.
895 uint32_t countLeadingOnes() const;
897 /// countTrailingZeros - This function is an APInt version of the
898 /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts
899 /// the number of zeros from the least significant bit to the first one bit.
900 /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
901 /// @returns the number of zeros from the least significant bit to the first
903 /// @brief Count the number of trailing zero bits.
904 uint32_t countTrailingZeros() const;
906 /// countPopulation - This function is an APInt version of the
907 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
908 /// of 1 bits in the APInt value.
909 /// @returns 0 if the value is zero.
910 /// @returns the number of set bits.
911 /// @brief Count the number of bits set.
912 uint32_t countPopulation() const;
915 /// @name Conversion Functions
918 /// This is used internally to convert an APInt to a string.
919 /// @brief Converts an APInt to a std::string
920 std::string toString(uint8_t radix, bool wantSigned) const;
922 /// Considers the APInt to be unsigned and converts it into a string in the
923 /// radix given. The radix can be 2, 8, 10 or 16.
924 /// @returns a character interpretation of the APInt
925 /// @brief Convert unsigned APInt to string representation.
926 inline std::string toString(uint8_t radix = 10) const {
927 return toString(radix, false);
930 /// Considers the APInt to be unsigned and converts it into a string in the
931 /// radix given. The radix can be 2, 8, 10 or 16.
932 /// @returns a character interpretation of the APInt
933 /// @brief Convert unsigned APInt to string representation.
934 inline std::string toStringSigned(uint8_t radix = 10) const {
935 return toString(radix, true);
938 /// @returns a byte-swapped representation of this APInt Value.
939 APInt byteSwap() const;
941 /// @brief Converts this APInt to a double value.
942 double roundToDouble(bool isSigned) const;
944 /// @brief Converts this unsigned APInt to a double value.
945 double roundToDouble() const {
946 return roundToDouble(false);
949 /// @brief Converts this signed APInt to a double value.
950 double signedRoundToDouble() const {
951 return roundToDouble(true);
954 /// The conversion does not do a translation from integer to double, it just
955 /// re-interprets the bits as a double. Note that it is valid to do this on
956 /// any bit width. Exactly 64 bits will be translated.
957 /// @brief Converts APInt bits to a double
958 double bitsToDouble() const {
963 T.I = (isSingleWord() ? VAL : pVal[0]);
967 /// The conversion does not do a translation from integer to float, it just
968 /// re-interprets the bits as a float. Note that it is valid to do this on
969 /// any bit width. Exactly 32 bits will be translated.
970 /// @brief Converts APInt bits to a double
971 float bitsToFloat() const {
976 T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
980 /// The conversion does not do a translation from double to integer, it just
981 /// re-interprets the bits of the double. Note that it is valid to do this on
982 /// any bit width but bits from V may get truncated.
983 /// @brief Converts a double to APInt bits.
984 APInt& doubleToBits(double V) {
994 return clearUnusedBits();
997 /// The conversion does not do a translation from float to integer, it just
998 /// re-interprets the bits of the float. Note that it is valid to do this on
999 /// any bit width but bits from V may get truncated.
1000 /// @brief Converts a float to APInt bits.
1001 APInt& floatToBits(float V) {
1011 return clearUnusedBits();
1015 /// @name Mathematics Operations
1018 /// @returns the floor log base 2 of this APInt.
1019 inline uint32_t logBase2() const {
1020 return BitWidth - 1 - countLeadingZeros();
1023 /// @returns the log base 2 of this APInt if its an exact power of two, -1
1025 inline int32_t exactLogBase2() const {
1031 /// @brief Compute the square root
1034 /// If *this is < 0 then return -(*this), otherwise *this;
1035 /// @brief Get the absolute value;
1044 inline bool operator==(uint64_t V1, const APInt& V2) {
1048 inline bool operator!=(uint64_t V1, const APInt& V2) {
1052 namespace APIntOps {
1054 /// @brief Determine the smaller of two APInts considered to be signed.
1055 inline APInt smin(const APInt &A, const APInt &B) {
1056 return A.slt(B) ? A : B;
1059 /// @brief Determine the larger of two APInts considered to be signed.
1060 inline APInt smax(const APInt &A, const APInt &B) {
1061 return A.sgt(B) ? A : B;
1064 /// @brief Determine the smaller of two APInts considered to be signed.
1065 inline APInt umin(const APInt &A, const APInt &B) {
1066 return A.ult(B) ? A : B;
1069 /// @brief Determine the larger of two APInts considered to be unsigned.
1070 inline APInt umax(const APInt &A, const APInt &B) {
1071 return A.ugt(B) ? A : B;
1074 /// @brief Check if the specified APInt has a N-bits integer value.
1075 inline bool isIntN(uint32_t N, const APInt& APIVal) {
1076 return APIVal.isIntN(N);
1079 /// @returns true if the argument APInt value is a sequence of ones
1080 /// starting at the least significant bit with the remainder zero.
1081 inline bool isMask(uint32_t numBits, const APInt& APIVal) {
1082 return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
1085 /// @returns true if the argument APInt value contains a sequence of ones
1086 /// with the remainder zero.
1087 inline bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
1088 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1091 /// @returns a byte-swapped representation of the specified APInt Value.
1092 inline APInt byteSwap(const APInt& APIVal) {
1093 return APIVal.byteSwap();
1096 /// @returns the floor log base 2 of the specified APInt value.
1097 inline uint32_t logBase2(const APInt& APIVal) {
1098 return APIVal.logBase2();
1101 /// GreatestCommonDivisor - This function returns the greatest common
1102 /// divisor of the two APInt values using Enclid's algorithm.
1103 /// @returns the greatest common divisor of Val1 and Val2
1104 /// @brief Compute GCD of two APInt values.
1105 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1107 /// Treats the APInt as an unsigned value for conversion purposes.
1108 /// @brief Converts the given APInt to a double value.
1109 inline double RoundAPIntToDouble(const APInt& APIVal) {
1110 return APIVal.roundToDouble();
1113 /// Treats the APInt as a signed value for conversion purposes.
1114 /// @brief Converts the given APInt to a double value.
1115 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1116 return APIVal.signedRoundToDouble();
1119 /// @brief Converts the given APInt to a float vlalue.
1120 inline float RoundAPIntToFloat(const APInt& APIVal) {
1121 return float(RoundAPIntToDouble(APIVal));
1124 /// Treast the APInt as a signed value for conversion purposes.
1125 /// @brief Converts the given APInt to a float value.
1126 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1127 return float(APIVal.signedRoundToDouble());
1130 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1131 /// @brief Converts the given double value into a APInt.
1132 APInt RoundDoubleToAPInt(double Double, uint32_t width);
1134 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1135 /// @brief Converts a float value into a APInt.
1136 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
1137 return RoundDoubleToAPInt(double(Float), width);
1140 /// Arithmetic right-shift the APInt by shiftAmt.
1141 /// @brief Arithmetic right-shift function.
1142 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
1143 return LHS.ashr(shiftAmt);
1146 /// Logical right-shift the APInt by shiftAmt.
1147 /// @brief Logical right-shift function.
1148 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
1149 return LHS.lshr(shiftAmt);
1152 /// Left-shift the APInt by shiftAmt.
1153 /// @brief Left-shift function.
1154 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
1155 return LHS.shl(shiftAmt);
1158 /// Signed divide APInt LHS by APInt RHS.
1159 /// @brief Signed division function for APInt.
1160 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1161 return LHS.sdiv(RHS);
1164 /// Unsigned divide APInt LHS by APInt RHS.
1165 /// @brief Unsigned division function for APInt.
1166 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1167 return LHS.udiv(RHS);
1170 /// Signed remainder operation on APInt.
1171 /// @brief Function for signed remainder operation.
1172 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1173 return LHS.srem(RHS);
1176 /// Unsigned remainder operation on APInt.
1177 /// @brief Function for unsigned remainder operation.
1178 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1179 return LHS.urem(RHS);
1182 /// Performs multiplication on APInt values.
1183 /// @brief Function for multiplication operation.
1184 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1188 /// Performs addition on APInt values.
1189 /// @brief Function for addition operation.
1190 inline APInt add(const APInt& LHS, const APInt& RHS) {
1194 /// Performs subtraction on APInt values.
1195 /// @brief Function for subtraction operation.
1196 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1200 /// Performs bitwise AND operation on APInt LHS and
1202 /// @brief Bitwise AND function for APInt.
1203 inline APInt And(const APInt& LHS, const APInt& RHS) {
1207 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1208 /// @brief Bitwise OR function for APInt.
1209 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1213 /// Performs bitwise XOR operation on APInt.
1214 /// @brief Bitwise XOR function for APInt.
1215 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1219 /// Performs a bitwise complement operation on APInt.
1220 /// @brief Bitwise complement function.
1221 inline APInt Not(const APInt& APIVal) {
1225 } // End of APIntOps namespace
1227 } // End of llvm namespace