1 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a class to represent arbitrary precision integral
11 // constant values and operations on them.
13 //===----------------------------------------------------------------------===//
18 #include "llvm/Support/MathExtras.h"
27 class FoldingSetNodeID;
32 class SmallVectorImpl;
34 // An unsigned host type used as a single part of a multi-part
36 typedef uint64_t integerPart;
38 const unsigned int host_char_bit = 8;
39 const unsigned int integerPartWidth = host_char_bit *
40 static_cast<unsigned int>(sizeof(integerPart));
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
46 /// APInt - This class represents arbitrary precision constant integral values.
47 /// It is a functional replacement for common case unsigned integer type like
48 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
49 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
50 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
51 /// and methods to manipulate integer values of any bit-width. It supports both
52 /// the typical integer arithmetic and comparison operations as well as bitwise
55 /// The class has several invariants worth noting:
56 /// * All bit, byte, and word positions are zero-based.
57 /// * Once the bit width is set, it doesn't change except by the Truncate,
58 /// SignExtend, or ZeroExtend operations.
59 /// * All binary operators must be on APInt instances of the same bit width.
60 /// Attempting to use these operators on instances with different bit
61 /// widths will yield an assertion.
62 /// * The value is stored canonically as an unsigned value. For operations
63 /// where it makes a difference, there are both signed and unsigned variants
64 /// of the operation. For example, sdiv and udiv. However, because the bit
65 /// widths must be the same, operations such as Mul and Add produce the same
66 /// results regardless of whether the values are interpreted as signed or
68 /// * In general, the class tries to follow the style of computation that LLVM
69 /// uses in its IR. This simplifies its use for LLVM.
71 /// @brief Class for arbitrary precision integers.
73 unsigned BitWidth; ///< The number of bits in this APInt.
75 /// This union is used to store the integer value. When the
76 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
78 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
79 uint64_t *pVal; ///< Used to store the >64 bits integer value.
82 /// This enum is used to hold the constants we needed for APInt.
85 APINT_BITS_PER_WORD = static_cast<unsigned int>(sizeof(uint64_t)) *
87 /// Byte size of a word
88 APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t))
91 /// This constructor is used only internally for speed of construction of
92 /// temporaries. It is unsafe for general use so it is not public.
93 /// @brief Fast internal constructor
94 APInt(uint64_t* val, unsigned bits) : BitWidth(bits), pVal(val) { }
96 /// @returns true if the number of bits <= 64, false otherwise.
97 /// @brief Determine if this APInt just has one word to store value.
98 bool isSingleWord() const {
99 return BitWidth <= APINT_BITS_PER_WORD;
102 /// @returns the word position for the specified bit position.
103 /// @brief Determine which word a bit is in.
104 static unsigned whichWord(unsigned bitPosition) {
105 return bitPosition / APINT_BITS_PER_WORD;
108 /// @returns the bit position in a word for the specified bit position
110 /// @brief Determine which bit in a word a bit is in.
111 static unsigned whichBit(unsigned bitPosition) {
112 return bitPosition % APINT_BITS_PER_WORD;
115 /// This method generates and returns a uint64_t (word) mask for a single
116 /// bit at a specific bit position. This is used to mask the bit in the
117 /// corresponding word.
118 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
119 /// @brief Get a single bit mask.
120 static uint64_t maskBit(unsigned bitPosition) {
121 return 1ULL << whichBit(bitPosition);
124 /// This method is used internally to clear the to "N" bits in the high order
125 /// word that are not used by the APInt. This is needed after the most
126 /// significant word is assigned a value to ensure that those bits are
128 /// @brief Clear unused high order bits
129 APInt& clearUnusedBits() {
130 // Compute how many bits are used in the final word
131 unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
133 // If all bits are used, we want to leave the value alone. This also
134 // avoids the undefined behavior of >> when the shift is the same size as
135 // the word size (64).
138 // Mask out the high bits.
139 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
143 pVal[getNumWords() - 1] &= mask;
147 /// @returns the corresponding word for the specified bit position.
148 /// @brief Get the word corresponding to a bit position
149 uint64_t getWord(unsigned bitPosition) const {
150 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
153 /// This is used by the constructors that take string arguments.
154 /// @brief Convert a char array into an APInt
155 void fromString(unsigned numBits, const StringRef &str, uint8_t radix);
157 /// This is used by the toString method to divide by the radix. It simply
158 /// provides a more convenient form of divide for internal use since KnuthDiv
159 /// has specific constraints on its inputs. If those constraints are not met
160 /// then it provides a simpler form of divide.
161 /// @brief An internal division function for dividing APInts.
162 static void divide(const APInt LHS, unsigned lhsWords,
163 const APInt &RHS, unsigned rhsWords,
164 APInt *Quotient, APInt *Remainder);
166 /// out-of-line slow case for inline constructor
167 void initSlowCase(unsigned numBits, uint64_t val, bool isSigned);
169 /// out-of-line slow case for inline copy constructor
170 void initSlowCase(const APInt& that);
172 /// out-of-line slow case for shl
173 APInt shlSlowCase(unsigned shiftAmt) const;
175 /// out-of-line slow case for operator&
176 APInt AndSlowCase(const APInt& RHS) const;
178 /// out-of-line slow case for operator|
179 APInt OrSlowCase(const APInt& RHS) const;
181 /// out-of-line slow case for operator^
182 APInt XorSlowCase(const APInt& RHS) const;
184 /// out-of-line slow case for operator=
185 APInt& AssignSlowCase(const APInt& RHS);
187 /// out-of-line slow case for operator==
188 bool EqualSlowCase(const APInt& RHS) const;
190 /// out-of-line slow case for operator==
191 bool EqualSlowCase(uint64_t Val) const;
193 /// out-of-line slow case for countLeadingZeros
194 unsigned countLeadingZerosSlowCase() const;
196 /// out-of-line slow case for countTrailingOnes
197 unsigned countTrailingOnesSlowCase() const;
199 /// out-of-line slow case for countPopulation
200 unsigned countPopulationSlowCase() const;
203 /// @name Constructors
205 /// If isSigned is true then val is treated as if it were a signed value
206 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
207 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
208 /// the range of val are zero filled).
209 /// @param numBits the bit width of the constructed APInt
210 /// @param val the initial value of the APInt
211 /// @param isSigned how to treat signedness of val
212 /// @brief Create a new APInt of numBits width, initialized as val.
213 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
214 : BitWidth(numBits), VAL(0) {
215 assert(BitWidth && "bitwidth too small");
219 initSlowCase(numBits, val, isSigned);
223 /// Note that numWords can be smaller or larger than the corresponding bit
224 /// width but any extraneous bits will be dropped.
225 /// @param numBits the bit width of the constructed APInt
226 /// @param numWords the number of words in bigVal
227 /// @param bigVal a sequence of words to form the initial value of the APInt
228 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
229 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
231 /// This constructor interprets the string \arg str in the given radix. The
232 /// interpretation stops when the first character that is not suitable for the
233 /// radix is encountered, or the end of the string. Acceptable radix values
234 /// are 2, 8, 10 and 16. It is an error for the value implied by the string to
235 /// require more bits than numBits.
237 /// @param numBits the bit width of the constructed APInt
238 /// @param str the string to be interpreted
239 /// @param radix the radix to use for the conversion
240 /// @brief Construct an APInt from a string representation.
241 APInt(unsigned numBits, const StringRef &str, uint8_t radix);
243 /// Simply makes *this a copy of that.
244 /// @brief Copy Constructor.
245 APInt(const APInt& that)
246 : BitWidth(that.BitWidth), VAL(0) {
247 assert(BitWidth && "bitwidth too small");
254 /// @brief Destructor.
260 /// Default constructor that creates an uninitialized APInt. This is useful
261 /// for object deserialization (pair this with the static method Read).
262 explicit APInt() : BitWidth(1) {}
264 /// Profile - Used to insert APInt objects, or objects that contain APInt
265 /// objects, into FoldingSets.
266 void Profile(FoldingSetNodeID& id) const;
268 /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
269 void Emit(Serializer& S) const;
271 /// @brief Used by the Bitcode deserializer to deserialize APInts.
272 void Read(Deserializer& D);
275 /// @name Value Tests
277 /// This tests the high bit of this APInt to determine if it is set.
278 /// @returns true if this APInt is negative, false otherwise
279 /// @brief Determine sign of this APInt.
280 bool isNegative() const {
281 return (*this)[BitWidth - 1];
284 /// This tests the high bit of the APInt to determine if it is unset.
285 /// @brief Determine if this APInt Value is non-negative (>= 0)
286 bool isNonNegative() const {
287 return !isNegative();
290 /// This tests if the value of this APInt is positive (> 0). Note
291 /// that 0 is not a positive value.
292 /// @returns true if this APInt is positive.
293 /// @brief Determine if this APInt Value is positive.
294 bool isStrictlyPositive() const {
295 return isNonNegative() && (*this) != 0;
298 /// This checks to see if the value has all bits of the APInt are set or not.
299 /// @brief Determine if all bits are set
300 bool isAllOnesValue() const {
301 return countPopulation() == BitWidth;
304 /// This checks to see if the value of this APInt is the maximum unsigned
305 /// value for the APInt's bit width.
306 /// @brief Determine if this is the largest unsigned value.
307 bool isMaxValue() const {
308 return countPopulation() == BitWidth;
311 /// This checks to see if the value of this APInt is the maximum signed
312 /// value for the APInt's bit width.
313 /// @brief Determine if this is the largest signed value.
314 bool isMaxSignedValue() const {
315 return BitWidth == 1 ? VAL == 0 :
316 !isNegative() && countPopulation() == BitWidth - 1;
319 /// This checks to see if the value of this APInt is the minimum unsigned
320 /// value for the APInt's bit width.
321 /// @brief Determine if this is the smallest unsigned value.
322 bool isMinValue() const {
323 return countPopulation() == 0;
326 /// This checks to see if the value of this APInt is the minimum signed
327 /// value for the APInt's bit width.
328 /// @brief Determine if this is the smallest signed value.
329 bool isMinSignedValue() const {
330 return BitWidth == 1 ? VAL == 1 :
331 isNegative() && countPopulation() == 1;
334 /// @brief Check if this APInt has an N-bits unsigned integer value.
335 bool isIntN(unsigned N) const {
336 assert(N && "N == 0 ???");
337 if (N >= getBitWidth())
341 return VAL == (VAL & (~0ULL >> (64 - N)));
342 APInt Tmp(N, getNumWords(), pVal);
343 Tmp.zext(getBitWidth());
344 return Tmp == (*this);
347 /// @brief Check if this APInt has an N-bits signed integer value.
348 bool isSignedIntN(unsigned N) const {
349 assert(N && "N == 0 ???");
350 return getMinSignedBits() <= N;
353 /// @returns true if the argument APInt value is a power of two > 0.
354 bool isPowerOf2() const;
356 /// isSignBit - Return true if this is the value returned by getSignBit.
357 bool isSignBit() const { return isMinSignedValue(); }
359 /// This converts the APInt to a boolean value as a test against zero.
360 /// @brief Boolean conversion function.
361 bool getBoolValue() const {
365 /// getLimitedValue - If this value is smaller than the specified limit,
366 /// return it, otherwise return the limit value. This causes the value
367 /// to saturate to the limit.
368 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
369 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
370 Limit : getZExtValue();
374 /// @name Value Generators
376 /// @brief Gets maximum unsigned value of APInt for specific bit width.
377 static APInt getMaxValue(unsigned numBits) {
378 return APInt(numBits, 0).set();
381 /// @brief Gets maximum signed value of APInt for a specific bit width.
382 static APInt getSignedMaxValue(unsigned numBits) {
383 return APInt(numBits, 0).set().clear(numBits - 1);
386 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
387 static APInt getMinValue(unsigned numBits) {
388 return APInt(numBits, 0);
391 /// @brief Gets minimum signed value of APInt for a specific bit width.
392 static APInt getSignedMinValue(unsigned numBits) {
393 return APInt(numBits, 0).set(numBits - 1);
396 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
397 /// it helps code readability when we want to get a SignBit.
398 /// @brief Get the SignBit for a specific bit width.
399 static APInt getSignBit(unsigned BitWidth) {
400 return getSignedMinValue(BitWidth);
403 /// @returns the all-ones value for an APInt of the specified bit-width.
404 /// @brief Get the all-ones value.
405 static APInt getAllOnesValue(unsigned numBits) {
406 return APInt(numBits, 0).set();
409 /// @returns the '0' value for an APInt of the specified bit-width.
410 /// @brief Get the '0' value.
411 static APInt getNullValue(unsigned numBits) {
412 return APInt(numBits, 0);
415 /// Get an APInt with the same BitWidth as this APInt, just zero mask
416 /// the low bits and right shift to the least significant bit.
417 /// @returns the high "numBits" bits of this APInt.
418 APInt getHiBits(unsigned numBits) const;
420 /// Get an APInt with the same BitWidth as this APInt, just zero mask
422 /// @returns the low "numBits" bits of this APInt.
423 APInt getLoBits(unsigned numBits) const;
425 /// Constructs an APInt value that has a contiguous range of bits set. The
426 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
427 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
428 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
429 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
430 /// @param numBits the intended bit width of the result
431 /// @param loBit the index of the lowest bit set.
432 /// @param hiBit the index of the highest bit set.
433 /// @returns An APInt value with the requested bits set.
434 /// @brief Get a value with a block of bits set.
435 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
436 assert(hiBit <= numBits && "hiBit out of range");
437 assert(loBit < numBits && "loBit out of range");
439 return getLowBitsSet(numBits, hiBit) |
440 getHighBitsSet(numBits, numBits-loBit);
441 return getLowBitsSet(numBits, hiBit-loBit).shl(loBit);
444 /// Constructs an APInt value that has the top hiBitsSet bits set.
445 /// @param numBits the bitwidth of the result
446 /// @param hiBitsSet the number of high-order bits set in the result.
447 /// @brief Get a value with high bits set
448 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
449 assert(hiBitsSet <= numBits && "Too many bits to set!");
450 // Handle a degenerate case, to avoid shifting by word size
452 return APInt(numBits, 0);
453 unsigned shiftAmt = numBits - hiBitsSet;
454 // For small values, return quickly
455 if (numBits <= APINT_BITS_PER_WORD)
456 return APInt(numBits, ~0ULL << shiftAmt);
457 return (~APInt(numBits, 0)).shl(shiftAmt);
460 /// Constructs an APInt value that has the bottom loBitsSet bits set.
461 /// @param numBits the bitwidth of the result
462 /// @param loBitsSet the number of low-order bits set in the result.
463 /// @brief Get a value with low bits set
464 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
465 assert(loBitsSet <= numBits && "Too many bits to set!");
466 // Handle a degenerate case, to avoid shifting by word size
468 return APInt(numBits, 0);
469 if (loBitsSet == APINT_BITS_PER_WORD)
470 return APInt(numBits, -1ULL);
471 // For small values, return quickly.
472 if (numBits < APINT_BITS_PER_WORD)
473 return APInt(numBits, (1ULL << loBitsSet) - 1);
474 return (~APInt(numBits, 0)).lshr(numBits - loBitsSet);
477 /// The hash value is computed as the sum of the words and the bit width.
478 /// @returns A hash value computed from the sum of the APInt words.
479 /// @brief Get a hash value based on this APInt
480 uint64_t getHashValue() const;
482 /// This function returns a pointer to the internal storage of the APInt.
483 /// This is useful for writing out the APInt in binary form without any
485 const uint64_t* getRawData() const {
492 /// @name Unary Operators
494 /// @returns a new APInt value representing *this incremented by one
495 /// @brief Postfix increment operator.
496 const APInt operator++(int) {
502 /// @returns *this incremented by one
503 /// @brief Prefix increment operator.
506 /// @returns a new APInt representing *this decremented by one.
507 /// @brief Postfix decrement operator.
508 const APInt operator--(int) {
514 /// @returns *this decremented by one.
515 /// @brief Prefix decrement operator.
518 /// Performs a bitwise complement operation on this APInt.
519 /// @returns an APInt that is the bitwise complement of *this
520 /// @brief Unary bitwise complement operator.
521 APInt operator~() const {
527 /// Negates *this using two's complement logic.
528 /// @returns An APInt value representing the negation of *this.
529 /// @brief Unary negation operator
530 APInt operator-() const {
531 return APInt(BitWidth, 0) - (*this);
534 /// Performs logical negation operation on this APInt.
535 /// @returns true if *this is zero, false otherwise.
536 /// @brief Logical negation operator.
537 bool operator!() const;
540 /// @name Assignment Operators
542 /// @returns *this after assignment of RHS.
543 /// @brief Copy assignment operator.
544 APInt& operator=(const APInt& RHS) {
545 // If the bitwidths are the same, we can avoid mucking with memory
546 if (isSingleWord() && RHS.isSingleWord()) {
548 BitWidth = RHS.BitWidth;
549 return clearUnusedBits();
552 return AssignSlowCase(RHS);
555 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
556 /// the bit width, the excess bits are truncated. If the bit width is larger
557 /// than 64, the value is zero filled in the unspecified high order bits.
558 /// @returns *this after assignment of RHS value.
559 /// @brief Assignment operator.
560 APInt& operator=(uint64_t RHS);
562 /// Performs a bitwise AND operation on this APInt and RHS. The result is
563 /// assigned to *this.
564 /// @returns *this after ANDing with RHS.
565 /// @brief Bitwise AND assignment operator.
566 APInt& operator&=(const APInt& RHS);
568 /// Performs a bitwise OR operation on this APInt and RHS. The result is
570 /// @returns *this after ORing with RHS.
571 /// @brief Bitwise OR assignment operator.
572 APInt& operator|=(const APInt& RHS);
574 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
575 /// assigned to *this.
576 /// @returns *this after XORing with RHS.
577 /// @brief Bitwise XOR assignment operator.
578 APInt& operator^=(const APInt& RHS);
580 /// Multiplies this APInt by RHS and assigns the result to *this.
582 /// @brief Multiplication assignment operator.
583 APInt& operator*=(const APInt& RHS);
585 /// Adds RHS to *this and assigns the result to *this.
587 /// @brief Addition assignment operator.
588 APInt& operator+=(const APInt& RHS);
590 /// Subtracts RHS from *this and assigns the result to *this.
592 /// @brief Subtraction assignment operator.
593 APInt& operator-=(const APInt& RHS);
595 /// Shifts *this left by shiftAmt and assigns the result to *this.
596 /// @returns *this after shifting left by shiftAmt
597 /// @brief Left-shift assignment function.
598 APInt& operator<<=(unsigned shiftAmt) {
599 *this = shl(shiftAmt);
604 /// @name Binary Operators
606 /// Performs a bitwise AND operation on *this and RHS.
607 /// @returns An APInt value representing the bitwise AND of *this and RHS.
608 /// @brief Bitwise AND operator.
609 APInt operator&(const APInt& RHS) const {
610 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
612 return APInt(getBitWidth(), VAL & RHS.VAL);
613 return AndSlowCase(RHS);
615 APInt And(const APInt& RHS) const {
616 return this->operator&(RHS);
619 /// Performs a bitwise OR operation on *this and RHS.
620 /// @returns An APInt value representing the bitwise OR of *this and RHS.
621 /// @brief Bitwise OR operator.
622 APInt operator|(const APInt& RHS) const {
623 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
625 return APInt(getBitWidth(), VAL | RHS.VAL);
626 return OrSlowCase(RHS);
628 APInt Or(const APInt& RHS) const {
629 return this->operator|(RHS);
632 /// Performs a bitwise XOR operation on *this and RHS.
633 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
634 /// @brief Bitwise XOR operator.
635 APInt operator^(const APInt& RHS) const {
636 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
638 return APInt(BitWidth, VAL ^ RHS.VAL);
639 return XorSlowCase(RHS);
641 APInt Xor(const APInt& RHS) const {
642 return this->operator^(RHS);
645 /// Multiplies this APInt by RHS and returns the result.
646 /// @brief Multiplication operator.
647 APInt operator*(const APInt& RHS) const;
649 /// Adds RHS to this APInt and returns the result.
650 /// @brief Addition operator.
651 APInt operator+(const APInt& RHS) const;
652 APInt operator+(uint64_t RHS) const {
653 return (*this) + APInt(BitWidth, RHS);
656 /// Subtracts RHS from this APInt and returns the result.
657 /// @brief Subtraction operator.
658 APInt operator-(const APInt& RHS) const;
659 APInt operator-(uint64_t RHS) const {
660 return (*this) - APInt(BitWidth, RHS);
663 APInt operator<<(unsigned Bits) const {
667 APInt operator<<(const APInt &Bits) const {
671 /// Arithmetic right-shift this APInt by shiftAmt.
672 /// @brief Arithmetic right-shift function.
673 APInt ashr(unsigned shiftAmt) const;
675 /// Logical right-shift this APInt by shiftAmt.
676 /// @brief Logical right-shift function.
677 APInt lshr(unsigned shiftAmt) const;
679 /// Left-shift this APInt by shiftAmt.
680 /// @brief Left-shift function.
681 APInt shl(unsigned shiftAmt) const {
682 assert(shiftAmt <= BitWidth && "Invalid shift amount");
683 if (isSingleWord()) {
684 if (shiftAmt == BitWidth)
685 return APInt(BitWidth, 0); // avoid undefined shift results
686 return APInt(BitWidth, VAL << shiftAmt);
688 return shlSlowCase(shiftAmt);
691 /// @brief Rotate left by rotateAmt.
692 APInt rotl(unsigned rotateAmt) const;
694 /// @brief Rotate right by rotateAmt.
695 APInt rotr(unsigned rotateAmt) const;
697 /// Arithmetic right-shift this APInt by shiftAmt.
698 /// @brief Arithmetic right-shift function.
699 APInt ashr(const APInt &shiftAmt) const;
701 /// Logical right-shift this APInt by shiftAmt.
702 /// @brief Logical right-shift function.
703 APInt lshr(const APInt &shiftAmt) const;
705 /// Left-shift this APInt by shiftAmt.
706 /// @brief Left-shift function.
707 APInt shl(const APInt &shiftAmt) const;
709 /// @brief Rotate left by rotateAmt.
710 APInt rotl(const APInt &rotateAmt) const;
712 /// @brief Rotate right by rotateAmt.
713 APInt rotr(const APInt &rotateAmt) const;
715 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
716 /// RHS are treated as unsigned quantities for purposes of this division.
717 /// @returns a new APInt value containing the division result
718 /// @brief Unsigned division operation.
719 APInt udiv(const APInt& RHS) const;
721 /// Signed divide this APInt by APInt RHS.
722 /// @brief Signed division function for APInt.
723 APInt sdiv(const APInt& RHS) const {
725 if (RHS.isNegative())
726 return (-(*this)).udiv(-RHS);
728 return -((-(*this)).udiv(RHS));
729 else if (RHS.isNegative())
730 return -(this->udiv(-RHS));
731 return this->udiv(RHS);
734 /// Perform an unsigned remainder operation on this APInt with RHS being the
735 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
736 /// of this operation. Note that this is a true remainder operation and not
737 /// a modulo operation because the sign follows the sign of the dividend
739 /// @returns a new APInt value containing the remainder result
740 /// @brief Unsigned remainder operation.
741 APInt urem(const APInt& RHS) const;
743 /// Signed remainder operation on APInt.
744 /// @brief Function for signed remainder operation.
745 APInt srem(const APInt& RHS) const {
747 if (RHS.isNegative())
748 return -((-(*this)).urem(-RHS));
750 return -((-(*this)).urem(RHS));
751 else if (RHS.isNegative())
752 return this->urem(-RHS);
753 return this->urem(RHS);
756 /// Sometimes it is convenient to divide two APInt values and obtain both the
757 /// quotient and remainder. This function does both operations in the same
758 /// computation making it a little more efficient. The pair of input arguments
759 /// may overlap with the pair of output arguments. It is safe to call
760 /// udivrem(X, Y, X, Y), for example.
761 /// @brief Dual division/remainder interface.
762 static void udivrem(const APInt &LHS, const APInt &RHS,
763 APInt &Quotient, APInt &Remainder);
765 static void sdivrem(const APInt &LHS, const APInt &RHS,
766 APInt &Quotient, APInt &Remainder)
768 if (LHS.isNegative()) {
769 if (RHS.isNegative())
770 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
772 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
773 Quotient = -Quotient;
774 Remainder = -Remainder;
775 } else if (RHS.isNegative()) {
776 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
777 Quotient = -Quotient;
779 APInt::udivrem(LHS, RHS, Quotient, Remainder);
783 /// @returns the bit value at bitPosition
784 /// @brief Array-indexing support.
785 bool operator[](unsigned bitPosition) const;
788 /// @name Comparison Operators
790 /// Compares this APInt with RHS for the validity of the equality
792 /// @brief Equality operator.
793 bool operator==(const APInt& RHS) const {
794 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
796 return VAL == RHS.VAL;
797 return EqualSlowCase(RHS);
800 /// Compares this APInt with a uint64_t for the validity of the equality
802 /// @returns true if *this == Val
803 /// @brief Equality operator.
804 bool operator==(uint64_t Val) const {
807 return EqualSlowCase(Val);
810 /// Compares this APInt with RHS for the validity of the equality
812 /// @returns true if *this == Val
813 /// @brief Equality comparison.
814 bool eq(const APInt &RHS) const {
815 return (*this) == RHS;
818 /// Compares this APInt with RHS for the validity of the inequality
820 /// @returns true if *this != Val
821 /// @brief Inequality operator.
822 bool operator!=(const APInt& RHS) const {
823 return !((*this) == RHS);
826 /// Compares this APInt with a uint64_t for the validity of the inequality
828 /// @returns true if *this != Val
829 /// @brief Inequality operator.
830 bool operator!=(uint64_t Val) const {
831 return !((*this) == Val);
834 /// Compares this APInt with RHS for the validity of the inequality
836 /// @returns true if *this != Val
837 /// @brief Inequality comparison
838 bool ne(const APInt &RHS) const {
839 return !((*this) == RHS);
842 /// Regards both *this and RHS as unsigned quantities and compares them for
843 /// the validity of the less-than relationship.
844 /// @returns true if *this < RHS when both are considered unsigned.
845 /// @brief Unsigned less than comparison
846 bool ult(const APInt& RHS) const;
848 /// Regards both *this and RHS as signed quantities and compares them for
849 /// validity of the less-than relationship.
850 /// @returns true if *this < RHS when both are considered signed.
851 /// @brief Signed less than comparison
852 bool slt(const APInt& RHS) const;
854 /// Regards both *this and RHS as unsigned quantities and compares them for
855 /// validity of the less-or-equal relationship.
856 /// @returns true if *this <= RHS when both are considered unsigned.
857 /// @brief Unsigned less or equal comparison
858 bool ule(const APInt& RHS) const {
859 return ult(RHS) || eq(RHS);
862 /// Regards both *this and RHS as signed quantities and compares them for
863 /// validity of the less-or-equal relationship.
864 /// @returns true if *this <= RHS when both are considered signed.
865 /// @brief Signed less or equal comparison
866 bool sle(const APInt& RHS) const {
867 return slt(RHS) || eq(RHS);
870 /// Regards both *this and RHS as unsigned quantities and compares them for
871 /// the validity of the greater-than relationship.
872 /// @returns true if *this > RHS when both are considered unsigned.
873 /// @brief Unsigned greather than comparison
874 bool ugt(const APInt& RHS) const {
875 return !ult(RHS) && !eq(RHS);
878 /// Regards both *this and RHS as signed quantities and compares them for
879 /// the validity of the greater-than relationship.
880 /// @returns true if *this > RHS when both are considered signed.
881 /// @brief Signed greather than comparison
882 bool sgt(const APInt& RHS) const {
883 return !slt(RHS) && !eq(RHS);
886 /// Regards both *this and RHS as unsigned quantities and compares them for
887 /// validity of the greater-or-equal relationship.
888 /// @returns true if *this >= RHS when both are considered unsigned.
889 /// @brief Unsigned greater or equal comparison
890 bool uge(const APInt& RHS) const {
894 /// Regards both *this and RHS as signed quantities and compares them for
895 /// validity of the greater-or-equal relationship.
896 /// @returns true if *this >= RHS when both are considered signed.
897 /// @brief Signed greather or equal comparison
898 bool sge(const APInt& RHS) const {
902 /// This operation tests if there are any pairs of corresponding bits
903 /// between this APInt and RHS that are both set.
904 bool intersects(const APInt &RHS) const {
905 return (*this & RHS) != 0;
909 /// @name Resizing Operators
911 /// Truncate the APInt to a specified width. It is an error to specify a width
912 /// that is greater than or equal to the current width.
913 /// @brief Truncate to new width.
914 APInt &trunc(unsigned width);
916 /// This operation sign extends the APInt to a new width. If the high order
917 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
918 /// It is an error to specify a width that is less than or equal to the
920 /// @brief Sign extend to a new width.
921 APInt &sext(unsigned width);
923 /// This operation zero extends the APInt to a new width. The high order bits
924 /// are filled with 0 bits. It is an error to specify a width that is less
925 /// than or equal to the current width.
926 /// @brief Zero extend to a new width.
927 APInt &zext(unsigned width);
929 /// Make this APInt have the bit width given by \p width. The value is sign
930 /// extended, truncated, or left alone to make it that width.
931 /// @brief Sign extend or truncate to width
932 APInt &sextOrTrunc(unsigned width);
934 /// Make this APInt have the bit width given by \p width. The value is zero
935 /// extended, truncated, or left alone to make it that width.
936 /// @brief Zero extend or truncate to width
937 APInt &zextOrTrunc(unsigned width);
940 /// @name Bit Manipulation Operators
942 /// @brief Set every bit to 1.
944 if (isSingleWord()) {
946 return clearUnusedBits();
949 // Set all the bits in all the words.
950 for (unsigned i = 0; i < getNumWords(); ++i)
952 // Clear the unused ones
953 return clearUnusedBits();
956 /// Set the given bit to 1 whose position is given as "bitPosition".
957 /// @brief Set a given bit to 1.
958 APInt& set(unsigned bitPosition);
960 /// @brief Set every bit to 0.
965 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
969 /// Set the given bit to 0 whose position is given as "bitPosition".
970 /// @brief Set a given bit to 0.
971 APInt& clear(unsigned bitPosition);
973 /// @brief Toggle every bit to its opposite value.
975 if (isSingleWord()) {
977 return clearUnusedBits();
979 for (unsigned i = 0; i < getNumWords(); ++i)
981 return clearUnusedBits();
984 /// Toggle a given bit to its opposite value whose position is given
985 /// as "bitPosition".
986 /// @brief Toggles a given bit to its opposite value.
987 APInt& flip(unsigned bitPosition);
990 /// @name Value Characterization Functions
993 /// @returns the total number of bits.
994 unsigned getBitWidth() const {
998 /// Here one word's bitwidth equals to that of uint64_t.
999 /// @returns the number of words to hold the integer value of this APInt.
1000 /// @brief Get the number of words.
1001 unsigned getNumWords() const {
1002 return getNumWords(BitWidth);
1005 /// Here one word's bitwidth equals to that of uint64_t.
1006 /// @returns the number of words to hold the integer value with a
1007 /// given bit width.
1008 /// @brief Get the number of words.
1009 static unsigned getNumWords(unsigned BitWidth) {
1010 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1013 /// This function returns the number of active bits which is defined as the
1014 /// bit width minus the number of leading zeros. This is used in several
1015 /// computations to see how "wide" the value is.
1016 /// @brief Compute the number of active bits in the value
1017 unsigned getActiveBits() const {
1018 return BitWidth - countLeadingZeros();
1021 /// This function returns the number of active words in the value of this
1022 /// APInt. This is used in conjunction with getActiveData to extract the raw
1023 /// value of the APInt.
1024 unsigned getActiveWords() const {
1025 return whichWord(getActiveBits()-1) + 1;
1028 /// Computes the minimum bit width for this APInt while considering it to be
1029 /// a signed (and probably negative) value. If the value is not negative,
1030 /// this function returns the same value as getActiveBits()+1. Otherwise, it
1031 /// returns the smallest bit width that will retain the negative value. For
1032 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1033 /// for -1, this function will always return 1.
1034 /// @brief Get the minimum bit size for this signed APInt
1035 unsigned getMinSignedBits() const {
1037 return BitWidth - countLeadingOnes() + 1;
1038 return getActiveBits()+1;
1041 /// This method attempts to return the value of this APInt as a zero extended
1042 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1043 /// uint64_t. Otherwise an assertion will result.
1044 /// @brief Get zero extended value
1045 uint64_t getZExtValue() const {
1048 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1052 /// This method attempts to return the value of this APInt as a sign extended
1053 /// int64_t. The bit width must be <= 64 or the value must fit within an
1054 /// int64_t. Otherwise an assertion will result.
1055 /// @brief Get sign extended value
1056 int64_t getSExtValue() const {
1058 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
1059 (APINT_BITS_PER_WORD - BitWidth);
1060 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1061 return int64_t(pVal[0]);
1064 /// This method determines how many bits are required to hold the APInt
1065 /// equivalent of the string given by \arg str.
1066 /// @brief Get bits required for string value.
1067 static unsigned getBitsNeeded(const StringRef& str, uint8_t radix);
1069 /// countLeadingZeros - This function is an APInt version of the
1070 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
1071 /// of zeros from the most significant bit to the first one bit.
1072 /// @returns BitWidth if the value is zero.
1073 /// @returns the number of zeros from the most significant bit to the first
1075 unsigned countLeadingZeros() const {
1076 if (isSingleWord()) {
1077 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1078 return CountLeadingZeros_64(VAL) - unusedBits;
1080 return countLeadingZerosSlowCase();
1083 /// countLeadingOnes - This function is an APInt version of the
1084 /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number
1085 /// of ones from the most significant bit to the first zero bit.
1086 /// @returns 0 if the high order bit is not set
1087 /// @returns the number of 1 bits from the most significant to the least
1088 /// @brief Count the number of leading one bits.
1089 unsigned countLeadingOnes() const;
1091 /// countTrailingZeros - This function is an APInt version of the
1092 /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
1093 /// the number of zeros from the least significant bit to the first set bit.
1094 /// @returns BitWidth if the value is zero.
1095 /// @returns the number of zeros from the least significant bit to the first
1097 /// @brief Count the number of trailing zero bits.
1098 unsigned countTrailingZeros() const;
1100 /// countTrailingOnes - This function is an APInt version of the
1101 /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
1102 /// the number of ones from the least significant bit to the first zero bit.
1103 /// @returns BitWidth if the value is all ones.
1104 /// @returns the number of ones from the least significant bit to the first
1106 /// @brief Count the number of trailing one bits.
1107 unsigned countTrailingOnes() const {
1109 return CountTrailingOnes_64(VAL);
1110 return countTrailingOnesSlowCase();
1113 /// countPopulation - This function is an APInt version of the
1114 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
1115 /// of 1 bits in the APInt value.
1116 /// @returns 0 if the value is zero.
1117 /// @returns the number of set bits.
1118 /// @brief Count the number of bits set.
1119 unsigned countPopulation() const {
1121 return CountPopulation_64(VAL);
1122 return countPopulationSlowCase();
1126 /// @name Conversion Functions
1128 void print(raw_ostream &OS, bool isSigned) const;
1130 /// toString - Converts an APInt to a string and append it to Str. Str is
1131 /// commonly a SmallString.
1132 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed) const;
1134 /// Considers the APInt to be unsigned and converts it into a string in the
1135 /// radix given. The radix can be 2, 8, 10 or 16.
1136 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1137 toString(Str, Radix, false);
1140 /// Considers the APInt to be signed and converts it into a string in the
1141 /// radix given. The radix can be 2, 8, 10 or 16.
1142 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1143 toString(Str, Radix, true);
1146 /// toString - This returns the APInt as a std::string. Note that this is an
1147 /// inefficient method. It is better to pass in a SmallVector/SmallString
1148 /// to the methods above to avoid thrashing the heap for the string.
1149 std::string toString(unsigned Radix, bool Signed) const;
1152 /// @returns a byte-swapped representation of this APInt Value.
1153 APInt byteSwap() const;
1155 /// @brief Converts this APInt to a double value.
1156 double roundToDouble(bool isSigned) const;
1158 /// @brief Converts this unsigned APInt to a double value.
1159 double roundToDouble() const {
1160 return roundToDouble(false);
1163 /// @brief Converts this signed APInt to a double value.
1164 double signedRoundToDouble() const {
1165 return roundToDouble(true);
1168 /// The conversion does not do a translation from integer to double, it just
1169 /// re-interprets the bits as a double. Note that it is valid to do this on
1170 /// any bit width. Exactly 64 bits will be translated.
1171 /// @brief Converts APInt bits to a double
1172 double bitsToDouble() const {
1177 T.I = (isSingleWord() ? VAL : pVal[0]);
1181 /// The conversion does not do a translation from integer to float, it just
1182 /// re-interprets the bits as a float. Note that it is valid to do this on
1183 /// any bit width. Exactly 32 bits will be translated.
1184 /// @brief Converts APInt bits to a double
1185 float bitsToFloat() const {
1190 T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1194 /// The conversion does not do a translation from double to integer, it just
1195 /// re-interprets the bits of the double. Note that it is valid to do this on
1196 /// any bit width but bits from V may get truncated.
1197 /// @brief Converts a double to APInt bits.
1198 APInt& doubleToBits(double V) {
1208 return clearUnusedBits();
1211 /// The conversion does not do a translation from float to integer, it just
1212 /// re-interprets the bits of the float. Note that it is valid to do this on
1213 /// any bit width but bits from V may get truncated.
1214 /// @brief Converts a float to APInt bits.
1215 APInt& floatToBits(float V) {
1225 return clearUnusedBits();
1229 /// @name Mathematics Operations
1232 /// @returns the floor log base 2 of this APInt.
1233 unsigned logBase2() const {
1234 return BitWidth - 1 - countLeadingZeros();
1237 /// @returns the ceil log base 2 of this APInt.
1238 unsigned ceilLogBase2() const {
1239 return BitWidth - (*this - 1).countLeadingZeros();
1242 /// @returns the log base 2 of this APInt if its an exact power of two, -1
1244 int32_t exactLogBase2() const {
1250 /// @brief Compute the square root
1253 /// If *this is < 0 then return -(*this), otherwise *this;
1254 /// @brief Get the absolute value;
1261 /// @returns the multiplicative inverse for a given modulo.
1262 APInt multiplicativeInverse(const APInt& modulo) const;
1265 /// @name Support for division by constant
1268 /// Calculate the magic number for signed division by a constant.
1272 /// Calculate the magic number for unsigned division by a constant.
1277 /// @name Building-block Operations for APInt and APFloat
1280 // These building block operations operate on a representation of
1281 // arbitrary precision, two's-complement, bignum integer values.
1282 // They should be sufficient to implement APInt and APFloat bignum
1283 // requirements. Inputs are generally a pointer to the base of an
1284 // array of integer parts, representing an unsigned bignum, and a
1285 // count of how many parts there are.
1287 /// Sets the least significant part of a bignum to the input value,
1288 /// and zeroes out higher parts. */
1289 static void tcSet(integerPart *, integerPart, unsigned int);
1291 /// Assign one bignum to another.
1292 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1294 /// Returns true if a bignum is zero, false otherwise.
1295 static bool tcIsZero(const integerPart *, unsigned int);
1297 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1298 static int tcExtractBit(const integerPart *, unsigned int bit);
1300 /// Copy the bit vector of width srcBITS from SRC, starting at bit
1301 /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
1302 /// becomes the least significant bit of DST. All high bits above
1303 /// srcBITS in DST are zero-filled.
1304 static void tcExtract(integerPart *, unsigned int dstCount,
1305 const integerPart *,
1306 unsigned int srcBits, unsigned int srcLSB);
1308 /// Set the given bit of a bignum. Zero-based.
1309 static void tcSetBit(integerPart *, unsigned int bit);
1311 /// Returns the bit number of the least or most significant set bit
1312 /// of a number. If the input number has no bits set -1U is
1314 static unsigned int tcLSB(const integerPart *, unsigned int);
1315 static unsigned int tcMSB(const integerPart *parts, unsigned int n);
1317 /// Negate a bignum in-place.
1318 static void tcNegate(integerPart *, unsigned int);
1320 /// DST += RHS + CARRY where CARRY is zero or one. Returns the
1322 static integerPart tcAdd(integerPart *, const integerPart *,
1323 integerPart carry, unsigned);
1325 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the
1327 static integerPart tcSubtract(integerPart *, const integerPart *,
1328 integerPart carry, unsigned);
1330 /// DST += SRC * MULTIPLIER + PART if add is true
1331 /// DST = SRC * MULTIPLIER + PART if add is false
1333 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
1334 /// they must start at the same point, i.e. DST == SRC.
1336 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1337 /// returned. Otherwise DST is filled with the least significant
1338 /// DSTPARTS parts of the result, and if all of the omitted higher
1339 /// parts were zero return zero, otherwise overflow occurred and
1341 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1342 integerPart multiplier, integerPart carry,
1343 unsigned int srcParts, unsigned int dstParts,
1346 /// DST = LHS * RHS, where DST has the same width as the operands
1347 /// and is filled with the least significant parts of the result.
1348 /// Returns one if overflow occurred, otherwise zero. DST must be
1349 /// disjoint from both operands.
1350 static int tcMultiply(integerPart *, const integerPart *,
1351 const integerPart *, unsigned);
1353 /// DST = LHS * RHS, where DST has width the sum of the widths of
1354 /// the operands. No overflow occurs. DST must be disjoint from
1355 /// both operands. Returns the number of parts required to hold the
1357 static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1358 const integerPart *, unsigned, unsigned);
1360 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1361 /// Otherwise set LHS to LHS / RHS with the fractional part
1362 /// discarded, set REMAINDER to the remainder, return zero. i.e.
1364 /// OLD_LHS = RHS * LHS + REMAINDER
1366 /// SCRATCH is a bignum of the same size as the operands and result
1367 /// for use by the routine; its contents need not be initialized
1368 /// and are destroyed. LHS, REMAINDER and SCRATCH must be
1370 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1371 integerPart *remainder, integerPart *scratch,
1372 unsigned int parts);
1374 /// Shift a bignum left COUNT bits. Shifted in bits are zero.
1375 /// There are no restrictions on COUNT.
1376 static void tcShiftLeft(integerPart *, unsigned int parts,
1377 unsigned int count);
1379 /// Shift a bignum right COUNT bits. Shifted in bits are zero.
1380 /// There are no restrictions on COUNT.
1381 static void tcShiftRight(integerPart *, unsigned int parts,
1382 unsigned int count);
1384 /// The obvious AND, OR and XOR and complement operations.
1385 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1386 static void tcOr(integerPart *, const integerPart *, unsigned int);
1387 static void tcXor(integerPart *, const integerPart *, unsigned int);
1388 static void tcComplement(integerPart *, unsigned int);
1390 /// Comparison (unsigned) of two bignums.
1391 static int tcCompare(const integerPart *, const integerPart *,
1394 /// Increment a bignum in-place. Return the carry flag.
1395 static integerPart tcIncrement(integerPart *, unsigned int);
1397 /// Set the least significant BITS and clear the rest.
1398 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1401 /// @brief debug method
1407 /// Magic data for optimising signed division by a constant.
1409 APInt m; ///< magic number
1410 unsigned s; ///< shift amount
1413 /// Magic data for optimising unsigned division by a constant.
1415 APInt m; ///< magic number
1416 bool a; ///< add indicator
1417 unsigned s; ///< shift amount
1420 inline bool operator==(uint64_t V1, const APInt& V2) {
1424 inline bool operator!=(uint64_t V1, const APInt& V2) {
1428 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1433 namespace APIntOps {
1435 /// @brief Determine the smaller of two APInts considered to be signed.
1436 inline APInt smin(const APInt &A, const APInt &B) {
1437 return A.slt(B) ? A : B;
1440 /// @brief Determine the larger of two APInts considered to be signed.
1441 inline APInt smax(const APInt &A, const APInt &B) {
1442 return A.sgt(B) ? A : B;
1445 /// @brief Determine the smaller of two APInts considered to be signed.
1446 inline APInt umin(const APInt &A, const APInt &B) {
1447 return A.ult(B) ? A : B;
1450 /// @brief Determine the larger of two APInts considered to be unsigned.
1451 inline APInt umax(const APInt &A, const APInt &B) {
1452 return A.ugt(B) ? A : B;
1455 /// @brief Check if the specified APInt has a N-bits unsigned integer value.
1456 inline bool isIntN(unsigned N, const APInt& APIVal) {
1457 return APIVal.isIntN(N);
1460 /// @brief Check if the specified APInt has a N-bits signed integer value.
1461 inline bool isSignedIntN(unsigned N, const APInt& APIVal) {
1462 return APIVal.isSignedIntN(N);
1465 /// @returns true if the argument APInt value is a sequence of ones
1466 /// starting at the least significant bit with the remainder zero.
1467 inline bool isMask(unsigned numBits, const APInt& APIVal) {
1468 return numBits <= APIVal.getBitWidth() &&
1469 APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
1472 /// @returns true if the argument APInt value contains a sequence of ones
1473 /// with the remainder zero.
1474 inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
1475 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1478 /// @returns a byte-swapped representation of the specified APInt Value.
1479 inline APInt byteSwap(const APInt& APIVal) {
1480 return APIVal.byteSwap();
1483 /// @returns the floor log base 2 of the specified APInt value.
1484 inline unsigned logBase2(const APInt& APIVal) {
1485 return APIVal.logBase2();
1488 /// GreatestCommonDivisor - This function returns the greatest common
1489 /// divisor of the two APInt values using Euclid's algorithm.
1490 /// @returns the greatest common divisor of Val1 and Val2
1491 /// @brief Compute GCD of two APInt values.
1492 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1494 /// Treats the APInt as an unsigned value for conversion purposes.
1495 /// @brief Converts the given APInt to a double value.
1496 inline double RoundAPIntToDouble(const APInt& APIVal) {
1497 return APIVal.roundToDouble();
1500 /// Treats the APInt as a signed value for conversion purposes.
1501 /// @brief Converts the given APInt to a double value.
1502 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1503 return APIVal.signedRoundToDouble();
1506 /// @brief Converts the given APInt to a float vlalue.
1507 inline float RoundAPIntToFloat(const APInt& APIVal) {
1508 return float(RoundAPIntToDouble(APIVal));
1511 /// Treast the APInt as a signed value for conversion purposes.
1512 /// @brief Converts the given APInt to a float value.
1513 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1514 return float(APIVal.signedRoundToDouble());
1517 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1518 /// @brief Converts the given double value into a APInt.
1519 APInt RoundDoubleToAPInt(double Double, unsigned width);
1521 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1522 /// @brief Converts a float value into a APInt.
1523 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
1524 return RoundDoubleToAPInt(double(Float), width);
1527 /// Arithmetic right-shift the APInt by shiftAmt.
1528 /// @brief Arithmetic right-shift function.
1529 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
1530 return LHS.ashr(shiftAmt);
1533 /// Logical right-shift the APInt by shiftAmt.
1534 /// @brief Logical right-shift function.
1535 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
1536 return LHS.lshr(shiftAmt);
1539 /// Left-shift the APInt by shiftAmt.
1540 /// @brief Left-shift function.
1541 inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
1542 return LHS.shl(shiftAmt);
1545 /// Signed divide APInt LHS by APInt RHS.
1546 /// @brief Signed division function for APInt.
1547 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1548 return LHS.sdiv(RHS);
1551 /// Unsigned divide APInt LHS by APInt RHS.
1552 /// @brief Unsigned division function for APInt.
1553 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1554 return LHS.udiv(RHS);
1557 /// Signed remainder operation on APInt.
1558 /// @brief Function for signed remainder operation.
1559 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1560 return LHS.srem(RHS);
1563 /// Unsigned remainder operation on APInt.
1564 /// @brief Function for unsigned remainder operation.
1565 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1566 return LHS.urem(RHS);
1569 /// Performs multiplication on APInt values.
1570 /// @brief Function for multiplication operation.
1571 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1575 /// Performs addition on APInt values.
1576 /// @brief Function for addition operation.
1577 inline APInt add(const APInt& LHS, const APInt& RHS) {
1581 /// Performs subtraction on APInt values.
1582 /// @brief Function for subtraction operation.
1583 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1587 /// Performs bitwise AND operation on APInt LHS and
1589 /// @brief Bitwise AND function for APInt.
1590 inline APInt And(const APInt& LHS, const APInt& RHS) {
1594 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1595 /// @brief Bitwise OR function for APInt.
1596 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1600 /// Performs bitwise XOR operation on APInt.
1601 /// @brief Bitwise XOR function for APInt.
1602 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1606 /// Performs a bitwise complement operation on APInt.
1607 /// @brief Bitwise complement function.
1608 inline APInt Not(const APInt& APIVal) {
1612 } // End of APIntOps namespace
1614 } // End of llvm namespace