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 /// Converts a string into a number. The string must be non-empty
154 /// and well-formed as a number of the given base. The bit-width
155 /// must be sufficient to hold the result.
157 /// This is used by the constructors that take string arguments.
159 /// StringRef::getAsInteger is superficially similar but (1) does
160 /// not assume that the string is well-formed and (2) grows the
161 /// result to hold the input.
163 /// @param radix 2, 8, 10, or 16
164 /// @brief Convert a char array into an APInt
165 void fromString(unsigned numBits, StringRef str, uint8_t radix);
167 /// This is used by the toString method to divide by the radix. It simply
168 /// provides a more convenient form of divide for internal use since KnuthDiv
169 /// has specific constraints on its inputs. If those constraints are not met
170 /// then it provides a simpler form of divide.
171 /// @brief An internal division function for dividing APInts.
172 static void divide(const APInt LHS, unsigned lhsWords,
173 const APInt &RHS, unsigned rhsWords,
174 APInt *Quotient, APInt *Remainder);
176 /// out-of-line slow case for inline constructor
177 void initSlowCase(unsigned numBits, uint64_t val, bool isSigned);
179 /// out-of-line slow case for inline copy constructor
180 void initSlowCase(const APInt& that);
182 /// out-of-line slow case for shl
183 APInt shlSlowCase(unsigned shiftAmt) const;
185 /// out-of-line slow case for operator&
186 APInt AndSlowCase(const APInt& RHS) const;
188 /// out-of-line slow case for operator|
189 APInt OrSlowCase(const APInt& RHS) const;
191 /// out-of-line slow case for operator^
192 APInt XorSlowCase(const APInt& RHS) const;
194 /// out-of-line slow case for operator=
195 APInt& AssignSlowCase(const APInt& RHS);
197 /// out-of-line slow case for operator==
198 bool EqualSlowCase(const APInt& RHS) const;
200 /// out-of-line slow case for operator==
201 bool EqualSlowCase(uint64_t Val) const;
203 /// out-of-line slow case for countLeadingZeros
204 unsigned countLeadingZerosSlowCase() const;
206 /// out-of-line slow case for countTrailingOnes
207 unsigned countTrailingOnesSlowCase() const;
209 /// out-of-line slow case for countPopulation
210 unsigned countPopulationSlowCase() const;
213 /// @name Constructors
215 /// If isSigned is true then val is treated as if it were a signed value
216 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
217 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
218 /// the range of val are zero filled).
219 /// @param numBits the bit width of the constructed APInt
220 /// @param val the initial value of the APInt
221 /// @param isSigned how to treat signedness of val
222 /// @brief Create a new APInt of numBits width, initialized as val.
223 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
224 : BitWidth(numBits), VAL(0) {
225 assert(BitWidth && "bitwidth too small");
229 initSlowCase(numBits, val, isSigned);
233 /// Note that numWords can be smaller or larger than the corresponding bit
234 /// width but any extraneous bits will be dropped.
235 /// @param numBits the bit width of the constructed APInt
236 /// @param numWords the number of words in bigVal
237 /// @param bigVal a sequence of words to form the initial value of the APInt
238 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
239 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
241 /// This constructor interprets the string \arg str in the given radix. The
242 /// interpretation stops when the first character that is not suitable for the
243 /// radix is encountered, or the end of the string. Acceptable radix values
244 /// are 2, 8, 10 and 16. It is an error for the value implied by the string to
245 /// require more bits than numBits.
247 /// @param numBits the bit width of the constructed APInt
248 /// @param str the string to be interpreted
249 /// @param radix the radix to use for the conversion
250 /// @brief Construct an APInt from a string representation.
251 APInt(unsigned numBits, StringRef str, uint8_t radix);
253 /// Simply makes *this a copy of that.
254 /// @brief Copy Constructor.
255 APInt(const APInt& that)
256 : BitWidth(that.BitWidth), VAL(0) {
257 assert(BitWidth && "bitwidth too small");
264 /// @brief Destructor.
270 /// Default constructor that creates an uninitialized APInt. This is useful
271 /// for object deserialization (pair this with the static method Read).
272 explicit APInt() : BitWidth(1) {}
274 /// Profile - Used to insert APInt objects, or objects that contain APInt
275 /// objects, into FoldingSets.
276 void Profile(FoldingSetNodeID& id) const;
279 /// @name Value Tests
281 /// This tests the high bit of this APInt to determine if it is set.
282 /// @returns true if this APInt is negative, false otherwise
283 /// @brief Determine sign of this APInt.
284 bool isNegative() const {
285 return (*this)[BitWidth - 1];
288 /// This tests the high bit of the APInt to determine if it is unset.
289 /// @brief Determine if this APInt Value is non-negative (>= 0)
290 bool isNonNegative() const {
291 return !isNegative();
294 /// This tests if the value of this APInt is positive (> 0). Note
295 /// that 0 is not a positive value.
296 /// @returns true if this APInt is positive.
297 /// @brief Determine if this APInt Value is positive.
298 bool isStrictlyPositive() const {
299 return isNonNegative() && (*this) != 0;
302 /// This checks to see if the value has all bits of the APInt are set or not.
303 /// @brief Determine if all bits are set
304 bool isAllOnesValue() const {
305 return countPopulation() == BitWidth;
308 /// This checks to see if the value of this APInt is the maximum unsigned
309 /// value for the APInt's bit width.
310 /// @brief Determine if this is the largest unsigned value.
311 bool isMaxValue() const {
312 return countPopulation() == BitWidth;
315 /// This checks to see if the value of this APInt is the maximum signed
316 /// value for the APInt's bit width.
317 /// @brief Determine if this is the largest signed value.
318 bool isMaxSignedValue() const {
319 return BitWidth == 1 ? VAL == 0 :
320 !isNegative() && countPopulation() == BitWidth - 1;
323 /// This checks to see if the value of this APInt is the minimum unsigned
324 /// value for the APInt's bit width.
325 /// @brief Determine if this is the smallest unsigned value.
326 bool isMinValue() const {
327 return countPopulation() == 0;
330 /// This checks to see if the value of this APInt is the minimum signed
331 /// value for the APInt's bit width.
332 /// @brief Determine if this is the smallest signed value.
333 bool isMinSignedValue() const {
334 return BitWidth == 1 ? VAL == 1 :
335 isNegative() && countPopulation() == 1;
338 /// @brief Check if this APInt has an N-bits unsigned integer value.
339 bool isIntN(unsigned N) const {
340 assert(N && "N == 0 ???");
341 if (N >= getBitWidth())
345 return isUIntN(N, VAL);
346 APInt Tmp(N, getNumWords(), pVal);
347 Tmp.zext(getBitWidth());
348 return Tmp == (*this);
351 /// @brief Check if this APInt has an N-bits signed integer value.
352 bool isSignedIntN(unsigned N) const {
353 assert(N && "N == 0 ???");
354 return getMinSignedBits() <= N;
357 /// @returns true if the argument APInt value is a power of two > 0.
358 bool isPowerOf2() const;
360 /// isSignBit - Return true if this is the value returned by getSignBit.
361 bool isSignBit() const { return isMinSignedValue(); }
363 /// This converts the APInt to a boolean value as a test against zero.
364 /// @brief Boolean conversion function.
365 bool getBoolValue() const {
369 /// getLimitedValue - If this value is smaller than the specified limit,
370 /// return it, otherwise return the limit value. This causes the value
371 /// to saturate to the limit.
372 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
373 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
374 Limit : getZExtValue();
378 /// @name Value Generators
380 /// @brief Gets maximum unsigned value of APInt for specific bit width.
381 static APInt getMaxValue(unsigned numBits) {
382 return getAllOnesValue(numBits);
385 /// @brief Gets maximum signed value of APInt for a specific bit width.
386 static APInt getSignedMaxValue(unsigned numBits) {
387 APInt API = getAllOnesValue(numBits);
388 API.clearBit(numBits - 1);
392 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
393 static APInt getMinValue(unsigned numBits) {
394 return APInt(numBits, 0);
397 /// @brief Gets minimum signed value of APInt for a specific bit width.
398 static APInt getSignedMinValue(unsigned numBits) {
399 APInt API(numBits, 0);
400 API.setBit(numBits - 1);
404 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
405 /// it helps code readability when we want to get a SignBit.
406 /// @brief Get the SignBit for a specific bit width.
407 static APInt getSignBit(unsigned BitWidth) {
408 return getSignedMinValue(BitWidth);
411 /// @returns the all-ones value for an APInt of the specified bit-width.
412 /// @brief Get the all-ones value.
413 static APInt getAllOnesValue(unsigned numBits) {
414 return APInt(numBits, -1ULL, true);
417 /// @returns the '0' value for an APInt of the specified bit-width.
418 /// @brief Get the '0' value.
419 static APInt getNullValue(unsigned numBits) {
420 return APInt(numBits, 0);
423 /// Get an APInt with the same BitWidth as this APInt, just zero mask
424 /// the low bits and right shift to the least significant bit.
425 /// @returns the high "numBits" bits of this APInt.
426 APInt getHiBits(unsigned numBits) const;
428 /// Get an APInt with the same BitWidth as this APInt, just zero mask
430 /// @returns the low "numBits" bits of this APInt.
431 APInt getLoBits(unsigned numBits) const;
433 /// Constructs an APInt value that has a contiguous range of bits set. The
434 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
435 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
436 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
437 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
438 /// @param numBits the intended bit width of the result
439 /// @param loBit the index of the lowest bit set.
440 /// @param hiBit the index of the highest bit set.
441 /// @returns An APInt value with the requested bits set.
442 /// @brief Get a value with a block of bits set.
443 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
444 assert(hiBit <= numBits && "hiBit out of range");
445 assert(loBit < numBits && "loBit out of range");
447 return getLowBitsSet(numBits, hiBit) |
448 getHighBitsSet(numBits, numBits-loBit);
449 return getLowBitsSet(numBits, hiBit-loBit).shl(loBit);
452 /// Constructs an APInt value that has the top hiBitsSet bits set.
453 /// @param numBits the bitwidth of the result
454 /// @param hiBitsSet the number of high-order bits set in the result.
455 /// @brief Get a value with high bits set
456 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
457 assert(hiBitsSet <= numBits && "Too many bits to set!");
458 // Handle a degenerate case, to avoid shifting by word size
460 return APInt(numBits, 0);
461 unsigned shiftAmt = numBits - hiBitsSet;
462 // For small values, return quickly
463 if (numBits <= APINT_BITS_PER_WORD)
464 return APInt(numBits, ~0ULL << shiftAmt);
465 return getAllOnesValue(numBits).shl(shiftAmt);
468 /// Constructs an APInt value that has the bottom loBitsSet bits set.
469 /// @param numBits the bitwidth of the result
470 /// @param loBitsSet the number of low-order bits set in the result.
471 /// @brief Get a value with low bits set
472 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
473 assert(loBitsSet <= numBits && "Too many bits to set!");
474 // Handle a degenerate case, to avoid shifting by word size
476 return APInt(numBits, 0);
477 if (loBitsSet == APINT_BITS_PER_WORD)
478 return APInt(numBits, -1ULL);
479 // For small values, return quickly.
480 if (numBits < APINT_BITS_PER_WORD)
481 return APInt(numBits, (1ULL << loBitsSet) - 1);
482 return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
485 /// The hash value is computed as the sum of the words and the bit width.
486 /// @returns A hash value computed from the sum of the APInt words.
487 /// @brief Get a hash value based on this APInt
488 uint64_t getHashValue() const;
490 /// This function returns a pointer to the internal storage of the APInt.
491 /// This is useful for writing out the APInt in binary form without any
493 const uint64_t* getRawData() const {
500 /// @name Unary Operators
502 /// @returns a new APInt value representing *this incremented by one
503 /// @brief Postfix increment operator.
504 const APInt operator++(int) {
510 /// @returns *this incremented by one
511 /// @brief Prefix increment operator.
514 /// @returns a new APInt representing *this decremented by one.
515 /// @brief Postfix decrement operator.
516 const APInt operator--(int) {
522 /// @returns *this decremented by one.
523 /// @brief Prefix decrement operator.
526 /// Performs a bitwise complement operation on this APInt.
527 /// @returns an APInt that is the bitwise complement of *this
528 /// @brief Unary bitwise complement operator.
529 APInt operator~() const {
531 Result.flipAllBits();
535 /// Negates *this using two's complement logic.
536 /// @returns An APInt value representing the negation of *this.
537 /// @brief Unary negation operator
538 APInt operator-() const {
539 return APInt(BitWidth, 0) - (*this);
542 /// Performs logical negation operation on this APInt.
543 /// @returns true if *this is zero, false otherwise.
544 /// @brief Logical negation operator.
545 bool operator!() const;
548 /// @name Assignment Operators
550 /// @returns *this after assignment of RHS.
551 /// @brief Copy assignment operator.
552 APInt& operator=(const APInt& RHS) {
553 // If the bitwidths are the same, we can avoid mucking with memory
554 if (isSingleWord() && RHS.isSingleWord()) {
556 BitWidth = RHS.BitWidth;
557 return clearUnusedBits();
560 return AssignSlowCase(RHS);
563 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
564 /// the bit width, the excess bits are truncated. If the bit width is larger
565 /// than 64, the value is zero filled in the unspecified high order bits.
566 /// @returns *this after assignment of RHS value.
567 /// @brief Assignment operator.
568 APInt& operator=(uint64_t RHS);
570 /// Performs a bitwise AND operation on this APInt and RHS. The result is
571 /// assigned to *this.
572 /// @returns *this after ANDing with RHS.
573 /// @brief Bitwise AND assignment operator.
574 APInt& operator&=(const APInt& RHS);
576 /// Performs a bitwise OR operation on this APInt and RHS. The result is
578 /// @returns *this after ORing with RHS.
579 /// @brief Bitwise OR assignment operator.
580 APInt& operator|=(const APInt& RHS);
582 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
583 /// logically zero-extended or truncated to match the bit-width of
586 /// @brief Bitwise OR assignment operator.
587 APInt& operator|=(uint64_t RHS) {
588 if (isSingleWord()) {
597 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
598 /// assigned to *this.
599 /// @returns *this after XORing with RHS.
600 /// @brief Bitwise XOR assignment operator.
601 APInt& operator^=(const APInt& RHS);
603 /// Multiplies this APInt by RHS and assigns the result to *this.
605 /// @brief Multiplication assignment operator.
606 APInt& operator*=(const APInt& RHS);
608 /// Adds RHS to *this and assigns the result to *this.
610 /// @brief Addition assignment operator.
611 APInt& operator+=(const APInt& RHS);
613 /// Subtracts RHS from *this and assigns the result to *this.
615 /// @brief Subtraction assignment operator.
616 APInt& operator-=(const APInt& RHS);
618 /// Shifts *this left by shiftAmt and assigns the result to *this.
619 /// @returns *this after shifting left by shiftAmt
620 /// @brief Left-shift assignment function.
621 APInt& operator<<=(unsigned shiftAmt) {
622 *this = shl(shiftAmt);
627 /// @name Binary Operators
629 /// Performs a bitwise AND operation on *this and RHS.
630 /// @returns An APInt value representing the bitwise AND of *this and RHS.
631 /// @brief Bitwise AND operator.
632 APInt operator&(const APInt& RHS) const {
633 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
635 return APInt(getBitWidth(), VAL & RHS.VAL);
636 return AndSlowCase(RHS);
638 APInt And(const APInt& RHS) const {
639 return this->operator&(RHS);
642 /// Performs a bitwise OR operation on *this and RHS.
643 /// @returns An APInt value representing the bitwise OR of *this and RHS.
644 /// @brief Bitwise OR operator.
645 APInt operator|(const APInt& RHS) const {
646 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
648 return APInt(getBitWidth(), VAL | RHS.VAL);
649 return OrSlowCase(RHS);
651 APInt Or(const APInt& RHS) const {
652 return this->operator|(RHS);
655 /// Performs a bitwise XOR operation on *this and RHS.
656 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
657 /// @brief Bitwise XOR operator.
658 APInt operator^(const APInt& RHS) const {
659 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
661 return APInt(BitWidth, VAL ^ RHS.VAL);
662 return XorSlowCase(RHS);
664 APInt Xor(const APInt& RHS) const {
665 return this->operator^(RHS);
668 /// Multiplies this APInt by RHS and returns the result.
669 /// @brief Multiplication operator.
670 APInt operator*(const APInt& RHS) const;
672 /// Adds RHS to this APInt and returns the result.
673 /// @brief Addition operator.
674 APInt operator+(const APInt& RHS) const;
675 APInt operator+(uint64_t RHS) const {
676 return (*this) + APInt(BitWidth, RHS);
679 /// Subtracts RHS from this APInt and returns the result.
680 /// @brief Subtraction operator.
681 APInt operator-(const APInt& RHS) const;
682 APInt operator-(uint64_t RHS) const {
683 return (*this) - APInt(BitWidth, RHS);
686 APInt operator<<(unsigned Bits) const {
690 APInt operator<<(const APInt &Bits) const {
694 /// Arithmetic right-shift this APInt by shiftAmt.
695 /// @brief Arithmetic right-shift function.
696 APInt ashr(unsigned shiftAmt) const;
698 /// Logical right-shift this APInt by shiftAmt.
699 /// @brief Logical right-shift function.
700 APInt lshr(unsigned shiftAmt) const;
702 /// Left-shift this APInt by shiftAmt.
703 /// @brief Left-shift function.
704 APInt shl(unsigned shiftAmt) const {
705 assert(shiftAmt <= BitWidth && "Invalid shift amount");
706 if (isSingleWord()) {
707 if (shiftAmt == BitWidth)
708 return APInt(BitWidth, 0); // avoid undefined shift results
709 return APInt(BitWidth, VAL << shiftAmt);
711 return shlSlowCase(shiftAmt);
714 /// @brief Rotate left by rotateAmt.
715 APInt rotl(unsigned rotateAmt) const;
717 /// @brief Rotate right by rotateAmt.
718 APInt rotr(unsigned rotateAmt) const;
720 /// Arithmetic right-shift this APInt by shiftAmt.
721 /// @brief Arithmetic right-shift function.
722 APInt ashr(const APInt &shiftAmt) const;
724 /// Logical right-shift this APInt by shiftAmt.
725 /// @brief Logical right-shift function.
726 APInt lshr(const APInt &shiftAmt) const;
728 /// Left-shift this APInt by shiftAmt.
729 /// @brief Left-shift function.
730 APInt shl(const APInt &shiftAmt) const;
732 /// @brief Rotate left by rotateAmt.
733 APInt rotl(const APInt &rotateAmt) const;
735 /// @brief Rotate right by rotateAmt.
736 APInt rotr(const APInt &rotateAmt) const;
738 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
739 /// RHS are treated as unsigned quantities for purposes of this division.
740 /// @returns a new APInt value containing the division result
741 /// @brief Unsigned division operation.
742 APInt udiv(const APInt &RHS) const;
744 /// Signed divide this APInt by APInt RHS.
745 /// @brief Signed division function for APInt.
746 APInt sdiv(const APInt &RHS) const {
748 if (RHS.isNegative())
749 return (-(*this)).udiv(-RHS);
751 return -((-(*this)).udiv(RHS));
752 else if (RHS.isNegative())
753 return -(this->udiv(-RHS));
754 return this->udiv(RHS);
757 /// Perform an unsigned remainder operation on this APInt with RHS being the
758 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
759 /// of this operation. Note that this is a true remainder operation and not
760 /// a modulo operation because the sign follows the sign of the dividend
762 /// @returns a new APInt value containing the remainder result
763 /// @brief Unsigned remainder operation.
764 APInt urem(const APInt &RHS) const;
766 /// Signed remainder operation on APInt.
767 /// @brief Function for signed remainder operation.
768 APInt srem(const APInt &RHS) const {
770 if (RHS.isNegative())
771 return -((-(*this)).urem(-RHS));
773 return -((-(*this)).urem(RHS));
774 else if (RHS.isNegative())
775 return this->urem(-RHS);
776 return this->urem(RHS);
779 /// Sometimes it is convenient to divide two APInt values and obtain both the
780 /// quotient and remainder. This function does both operations in the same
781 /// computation making it a little more efficient. The pair of input arguments
782 /// may overlap with the pair of output arguments. It is safe to call
783 /// udivrem(X, Y, X, Y), for example.
784 /// @brief Dual division/remainder interface.
785 static void udivrem(const APInt &LHS, const APInt &RHS,
786 APInt &Quotient, APInt &Remainder);
788 static void sdivrem(const APInt &LHS, const APInt &RHS,
789 APInt &Quotient, APInt &Remainder) {
790 if (LHS.isNegative()) {
791 if (RHS.isNegative())
792 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
794 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
795 Quotient = -Quotient;
796 Remainder = -Remainder;
797 } else if (RHS.isNegative()) {
798 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
799 Quotient = -Quotient;
801 APInt::udivrem(LHS, RHS, Quotient, Remainder);
806 // Operations that return overflow indicators.
807 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
808 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
809 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
810 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
811 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
812 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
813 APInt sshl_ov(unsigned Amt, bool &Overflow) const;
815 /// @returns the bit value at bitPosition
816 /// @brief Array-indexing support.
817 bool operator[](unsigned bitPosition) const;
820 /// @name Comparison Operators
822 /// Compares this APInt with RHS for the validity of the equality
824 /// @brief Equality operator.
825 bool operator==(const APInt& RHS) const {
826 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
828 return VAL == RHS.VAL;
829 return EqualSlowCase(RHS);
832 /// Compares this APInt with a uint64_t for the validity of the equality
834 /// @returns true if *this == Val
835 /// @brief Equality operator.
836 bool operator==(uint64_t Val) const {
839 return EqualSlowCase(Val);
842 /// Compares this APInt with RHS for the validity of the equality
844 /// @returns true if *this == Val
845 /// @brief Equality comparison.
846 bool eq(const APInt &RHS) const {
847 return (*this) == RHS;
850 /// Compares this APInt with RHS for the validity of the inequality
852 /// @returns true if *this != Val
853 /// @brief Inequality operator.
854 bool operator!=(const APInt& RHS) const {
855 return !((*this) == RHS);
858 /// Compares this APInt with a uint64_t for the validity of the inequality
860 /// @returns true if *this != Val
861 /// @brief Inequality operator.
862 bool operator!=(uint64_t Val) const {
863 return !((*this) == Val);
866 /// Compares this APInt with RHS for the validity of the inequality
868 /// @returns true if *this != Val
869 /// @brief Inequality comparison
870 bool ne(const APInt &RHS) const {
871 return !((*this) == RHS);
874 /// Regards both *this and RHS as unsigned quantities and compares them for
875 /// the validity of the less-than relationship.
876 /// @returns true if *this < RHS when both are considered unsigned.
877 /// @brief Unsigned less than comparison
878 bool ult(const APInt &RHS) const;
880 /// Regards both *this as an unsigned quantity and compares it with RHS for
881 /// the validity of the less-than relationship.
882 /// @returns true if *this < RHS when considered unsigned.
883 /// @brief Unsigned less than comparison
884 bool ult(uint64_t RHS) const {
885 return ult(APInt(getBitWidth(), RHS));
888 /// Regards both *this and RHS as signed quantities and compares them for
889 /// validity of the less-than relationship.
890 /// @returns true if *this < RHS when both are considered signed.
891 /// @brief Signed less than comparison
892 bool slt(const APInt& RHS) const;
894 /// Regards both *this as a signed quantity and compares it with RHS for
895 /// the validity of the less-than relationship.
896 /// @returns true if *this < RHS when considered signed.
897 /// @brief Signed less than comparison
898 bool slt(uint64_t RHS) const {
899 return slt(APInt(getBitWidth(), RHS));
902 /// Regards both *this and RHS as unsigned quantities and compares them for
903 /// validity of the less-or-equal relationship.
904 /// @returns true if *this <= RHS when both are considered unsigned.
905 /// @brief Unsigned less or equal comparison
906 bool ule(const APInt& RHS) const {
907 return ult(RHS) || eq(RHS);
910 /// Regards both *this as an unsigned quantity and compares it with RHS for
911 /// the validity of the less-or-equal relationship.
912 /// @returns true if *this <= RHS when considered unsigned.
913 /// @brief Unsigned less or equal comparison
914 bool ule(uint64_t RHS) const {
915 return ule(APInt(getBitWidth(), RHS));
918 /// Regards both *this and RHS as signed quantities and compares them for
919 /// validity of the less-or-equal relationship.
920 /// @returns true if *this <= RHS when both are considered signed.
921 /// @brief Signed less or equal comparison
922 bool sle(const APInt& RHS) const {
923 return slt(RHS) || eq(RHS);
926 /// Regards both *this as a signed quantity and compares it with RHS for
927 /// the validity of the less-or-equal relationship.
928 /// @returns true if *this <= RHS when considered signed.
929 /// @brief Signed less or equal comparison
930 bool sle(uint64_t RHS) const {
931 return sle(APInt(getBitWidth(), RHS));
934 /// Regards both *this and RHS as unsigned quantities and compares them for
935 /// the validity of the greater-than relationship.
936 /// @returns true if *this > RHS when both are considered unsigned.
937 /// @brief Unsigned greather than comparison
938 bool ugt(const APInt& RHS) const {
939 return !ult(RHS) && !eq(RHS);
942 /// Regards both *this as an unsigned quantity and compares it with RHS for
943 /// the validity of the greater-than relationship.
944 /// @returns true if *this > RHS when considered unsigned.
945 /// @brief Unsigned greater than comparison
946 bool ugt(uint64_t RHS) const {
947 return ugt(APInt(getBitWidth(), RHS));
950 /// Regards both *this and RHS as signed quantities and compares them for
951 /// the validity of the greater-than relationship.
952 /// @returns true if *this > RHS when both are considered signed.
953 /// @brief Signed greather than comparison
954 bool sgt(const APInt& RHS) const {
955 return !slt(RHS) && !eq(RHS);
958 /// Regards both *this as a signed quantity and compares it with RHS for
959 /// the validity of the greater-than relationship.
960 /// @returns true if *this > RHS when considered signed.
961 /// @brief Signed greater than comparison
962 bool sgt(uint64_t RHS) const {
963 return sgt(APInt(getBitWidth(), RHS));
966 /// Regards both *this and RHS as unsigned quantities and compares them for
967 /// validity of the greater-or-equal relationship.
968 /// @returns true if *this >= RHS when both are considered unsigned.
969 /// @brief Unsigned greater or equal comparison
970 bool uge(const APInt& RHS) const {
974 /// Regards both *this as an unsigned quantity and compares it with RHS for
975 /// the validity of the greater-or-equal relationship.
976 /// @returns true if *this >= RHS when considered unsigned.
977 /// @brief Unsigned greater or equal comparison
978 bool uge(uint64_t RHS) const {
979 return uge(APInt(getBitWidth(), RHS));
982 /// Regards both *this and RHS as signed quantities and compares them for
983 /// validity of the greater-or-equal relationship.
984 /// @returns true if *this >= RHS when both are considered signed.
985 /// @brief Signed greather or equal comparison
986 bool sge(const APInt& RHS) const {
990 /// Regards both *this as a signed quantity and compares it with RHS for
991 /// the validity of the greater-or-equal relationship.
992 /// @returns true if *this >= RHS when considered signed.
993 /// @brief Signed greater or equal comparison
994 bool sge(uint64_t RHS) const {
995 return sge(APInt(getBitWidth(), RHS));
1001 /// This operation tests if there are any pairs of corresponding bits
1002 /// between this APInt and RHS that are both set.
1003 bool intersects(const APInt &RHS) const {
1004 return (*this & RHS) != 0;
1008 /// @name Resizing Operators
1010 /// Truncate the APInt to a specified width. It is an error to specify a width
1011 /// that is greater than or equal to the current width.
1012 /// @brief Truncate to new width.
1013 APInt &trunc(unsigned width);
1015 /// This operation sign extends the APInt to a new width. If the high order
1016 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1017 /// It is an error to specify a width that is less than or equal to the
1019 /// @brief Sign extend to a new width.
1020 APInt &sext(unsigned width);
1022 /// This operation zero extends the APInt to a new width. The high order bits
1023 /// are filled with 0 bits. It is an error to specify a width that is less
1024 /// than or equal to the current width.
1025 /// @brief Zero extend to a new width.
1026 APInt &zext(unsigned width);
1028 /// Make this APInt have the bit width given by \p width. The value is sign
1029 /// extended, truncated, or left alone to make it that width.
1030 /// @brief Sign extend or truncate to width
1031 APInt &sextOrTrunc(unsigned width);
1033 /// Make this APInt have the bit width given by \p width. The value is zero
1034 /// extended, truncated, or left alone to make it that width.
1035 /// @brief Zero extend or truncate to width
1036 APInt &zextOrTrunc(unsigned width);
1039 /// @name Bit Manipulation Operators
1041 /// @brief Set every bit to 1.
1046 // Set all the bits in all the words.
1047 for (unsigned i = 0; i < getNumWords(); ++i)
1050 // Clear the unused ones
1054 /// Set the given bit to 1 whose position is given as "bitPosition".
1055 /// @brief Set a given bit to 1.
1056 void setBit(unsigned bitPosition);
1058 /// @brief Set every bit to 0.
1059 void clearAllBits() {
1063 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
1066 /// Set the given bit to 0 whose position is given as "bitPosition".
1067 /// @brief Set a given bit to 0.
1068 void clearBit(unsigned bitPosition);
1070 /// @brief Toggle every bit to its opposite value.
1071 void flipAllBits() {
1075 for (unsigned i = 0; i < getNumWords(); ++i)
1081 /// Toggle a given bit to its opposite value whose position is given
1082 /// as "bitPosition".
1083 /// @brief Toggles a given bit to its opposite value.
1084 void flipBit(unsigned bitPosition);
1087 /// @name Value Characterization Functions
1090 /// @returns the total number of bits.
1091 unsigned getBitWidth() const {
1095 /// Here one word's bitwidth equals to that of uint64_t.
1096 /// @returns the number of words to hold the integer value of this APInt.
1097 /// @brief Get the number of words.
1098 unsigned getNumWords() const {
1099 return getNumWords(BitWidth);
1102 /// Here one word's bitwidth equals to that of uint64_t.
1103 /// @returns the number of words to hold the integer value with a
1104 /// given bit width.
1105 /// @brief Get the number of words.
1106 static unsigned getNumWords(unsigned BitWidth) {
1107 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1110 /// This function returns the number of active bits which is defined as the
1111 /// bit width minus the number of leading zeros. This is used in several
1112 /// computations to see how "wide" the value is.
1113 /// @brief Compute the number of active bits in the value
1114 unsigned getActiveBits() const {
1115 return BitWidth - countLeadingZeros();
1118 /// This function returns the number of active words in the value of this
1119 /// APInt. This is used in conjunction with getActiveData to extract the raw
1120 /// value of the APInt.
1121 unsigned getActiveWords() const {
1122 return whichWord(getActiveBits()-1) + 1;
1125 /// Computes the minimum bit width for this APInt while considering it to be
1126 /// a signed (and probably negative) value. If the value is not negative,
1127 /// this function returns the same value as getActiveBits()+1. Otherwise, it
1128 /// returns the smallest bit width that will retain the negative value. For
1129 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1130 /// for -1, this function will always return 1.
1131 /// @brief Get the minimum bit size for this signed APInt
1132 unsigned getMinSignedBits() const {
1134 return BitWidth - countLeadingOnes() + 1;
1135 return getActiveBits()+1;
1138 /// This method attempts to return the value of this APInt as a zero extended
1139 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1140 /// uint64_t. Otherwise an assertion will result.
1141 /// @brief Get zero extended value
1142 uint64_t getZExtValue() const {
1145 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1149 /// This method attempts to return the value of this APInt as a sign extended
1150 /// int64_t. The bit width must be <= 64 or the value must fit within an
1151 /// int64_t. Otherwise an assertion will result.
1152 /// @brief Get sign extended value
1153 int64_t getSExtValue() const {
1155 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
1156 (APINT_BITS_PER_WORD - BitWidth);
1157 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1158 return int64_t(pVal[0]);
1161 /// This method determines how many bits are required to hold the APInt
1162 /// equivalent of the string given by \arg str.
1163 /// @brief Get bits required for string value.
1164 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1166 /// countLeadingZeros - This function is an APInt version of the
1167 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
1168 /// of zeros from the most significant bit to the first one bit.
1169 /// @returns BitWidth if the value is zero.
1170 /// @returns the number of zeros from the most significant bit to the first
1172 unsigned countLeadingZeros() const {
1173 if (isSingleWord()) {
1174 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1175 return CountLeadingZeros_64(VAL) - unusedBits;
1177 return countLeadingZerosSlowCase();
1180 /// countLeadingOnes - This function is an APInt version of the
1181 /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number
1182 /// of ones from the most significant bit to the first zero bit.
1183 /// @returns 0 if the high order bit is not set
1184 /// @returns the number of 1 bits from the most significant to the least
1185 /// @brief Count the number of leading one bits.
1186 unsigned countLeadingOnes() const;
1188 /// countTrailingZeros - This function is an APInt version of the
1189 /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
1190 /// the number of zeros from the least significant bit to the first set bit.
1191 /// @returns BitWidth if the value is zero.
1192 /// @returns the number of zeros from the least significant bit to the first
1194 /// @brief Count the number of trailing zero bits.
1195 unsigned countTrailingZeros() const;
1197 /// countTrailingOnes - This function is an APInt version of the
1198 /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
1199 /// the number of ones from the least significant bit to the first zero bit.
1200 /// @returns BitWidth if the value is all ones.
1201 /// @returns the number of ones from the least significant bit to the first
1203 /// @brief Count the number of trailing one bits.
1204 unsigned countTrailingOnes() const {
1206 return CountTrailingOnes_64(VAL);
1207 return countTrailingOnesSlowCase();
1210 /// countPopulation - This function is an APInt version of the
1211 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
1212 /// of 1 bits in the APInt value.
1213 /// @returns 0 if the value is zero.
1214 /// @returns the number of set bits.
1215 /// @brief Count the number of bits set.
1216 unsigned countPopulation() const {
1218 return CountPopulation_64(VAL);
1219 return countPopulationSlowCase();
1223 /// @name Conversion Functions
1225 void print(raw_ostream &OS, bool isSigned) const;
1227 /// toString - Converts an APInt to a string and append it to Str. Str is
1228 /// commonly a SmallString.
1229 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed) const;
1231 /// Considers the APInt to be unsigned and converts it into a string in the
1232 /// radix given. The radix can be 2, 8, 10 or 16.
1233 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1234 toString(Str, Radix, false);
1237 /// Considers the APInt to be signed and converts it into a string in the
1238 /// radix given. The radix can be 2, 8, 10 or 16.
1239 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1240 toString(Str, Radix, true);
1243 /// toString - This returns the APInt as a std::string. Note that this is an
1244 /// inefficient method. It is better to pass in a SmallVector/SmallString
1245 /// to the methods above to avoid thrashing the heap for the string.
1246 std::string toString(unsigned Radix, bool Signed) const;
1249 /// @returns a byte-swapped representation of this APInt Value.
1250 APInt byteSwap() const;
1252 /// @brief Converts this APInt to a double value.
1253 double roundToDouble(bool isSigned) const;
1255 /// @brief Converts this unsigned APInt to a double value.
1256 double roundToDouble() const {
1257 return roundToDouble(false);
1260 /// @brief Converts this signed APInt to a double value.
1261 double signedRoundToDouble() const {
1262 return roundToDouble(true);
1265 /// The conversion does not do a translation from integer to double, it just
1266 /// re-interprets the bits as a double. Note that it is valid to do this on
1267 /// any bit width. Exactly 64 bits will be translated.
1268 /// @brief Converts APInt bits to a double
1269 double bitsToDouble() const {
1274 T.I = (isSingleWord() ? VAL : pVal[0]);
1278 /// The conversion does not do a translation from integer to float, it just
1279 /// re-interprets the bits as a float. Note that it is valid to do this on
1280 /// any bit width. Exactly 32 bits will be translated.
1281 /// @brief Converts APInt bits to a double
1282 float bitsToFloat() const {
1287 T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1291 /// The conversion does not do a translation from double to integer, it just
1292 /// re-interprets the bits of the double.
1293 /// @brief Converts a double to APInt bits.
1294 static APInt doubleToBits(double V) {
1300 return APInt(sizeof T * CHAR_BIT, T.I);
1303 /// The conversion does not do a translation from float to integer, it just
1304 /// re-interprets the bits of the float.
1305 /// @brief Converts a float to APInt bits.
1306 static APInt floatToBits(float V) {
1312 return APInt(sizeof T * CHAR_BIT, T.I);
1316 /// @name Mathematics Operations
1319 /// @returns the floor log base 2 of this APInt.
1320 unsigned logBase2() const {
1321 return BitWidth - 1 - countLeadingZeros();
1324 /// @returns the ceil log base 2 of this APInt.
1325 unsigned ceilLogBase2() const {
1326 return BitWidth - (*this - 1).countLeadingZeros();
1329 /// @returns the log base 2 of this APInt if its an exact power of two, -1
1331 int32_t exactLogBase2() const {
1337 /// @brief Compute the square root
1340 /// If *this is < 0 then return -(*this), otherwise *this;
1341 /// @brief Get the absolute value;
1348 /// @returns the multiplicative inverse for a given modulo.
1349 APInt multiplicativeInverse(const APInt& modulo) const;
1352 /// @name Support for division by constant
1355 /// Calculate the magic number for signed division by a constant.
1359 /// Calculate the magic number for unsigned division by a constant.
1364 /// @name Building-block Operations for APInt and APFloat
1367 // These building block operations operate on a representation of
1368 // arbitrary precision, two's-complement, bignum integer values.
1369 // They should be sufficient to implement APInt and APFloat bignum
1370 // requirements. Inputs are generally a pointer to the base of an
1371 // array of integer parts, representing an unsigned bignum, and a
1372 // count of how many parts there are.
1374 /// Sets the least significant part of a bignum to the input value,
1375 /// and zeroes out higher parts. */
1376 static void tcSet(integerPart *, integerPart, unsigned int);
1378 /// Assign one bignum to another.
1379 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1381 /// Returns true if a bignum is zero, false otherwise.
1382 static bool tcIsZero(const integerPart *, unsigned int);
1384 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1385 static int tcExtractBit(const integerPart *, unsigned int bit);
1387 /// Copy the bit vector of width srcBITS from SRC, starting at bit
1388 /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
1389 /// becomes the least significant bit of DST. All high bits above
1390 /// srcBITS in DST are zero-filled.
1391 static void tcExtract(integerPart *, unsigned int dstCount,
1392 const integerPart *,
1393 unsigned int srcBits, unsigned int srcLSB);
1395 /// Set the given bit of a bignum. Zero-based.
1396 static void tcSetBit(integerPart *, unsigned int bit);
1398 /// Clear the given bit of a bignum. Zero-based.
1399 static void tcClearBit(integerPart *, unsigned int bit);
1401 /// Returns the bit number of the least or most significant set bit
1402 /// of a number. If the input number has no bits set -1U is
1404 static unsigned int tcLSB(const integerPart *, unsigned int);
1405 static unsigned int tcMSB(const integerPart *parts, unsigned int n);
1407 /// Negate a bignum in-place.
1408 static void tcNegate(integerPart *, unsigned int);
1410 /// DST += RHS + CARRY where CARRY is zero or one. Returns the
1412 static integerPart tcAdd(integerPart *, const integerPart *,
1413 integerPart carry, unsigned);
1415 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the
1417 static integerPart tcSubtract(integerPart *, const integerPart *,
1418 integerPart carry, unsigned);
1420 /// DST += SRC * MULTIPLIER + PART if add is true
1421 /// DST = SRC * MULTIPLIER + PART if add is false
1423 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
1424 /// they must start at the same point, i.e. DST == SRC.
1426 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1427 /// returned. Otherwise DST is filled with the least significant
1428 /// DSTPARTS parts of the result, and if all of the omitted higher
1429 /// parts were zero return zero, otherwise overflow occurred and
1431 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1432 integerPart multiplier, integerPart carry,
1433 unsigned int srcParts, unsigned int dstParts,
1436 /// DST = LHS * RHS, where DST has the same width as the operands
1437 /// and is filled with the least significant parts of the result.
1438 /// Returns one if overflow occurred, otherwise zero. DST must be
1439 /// disjoint from both operands.
1440 static int tcMultiply(integerPart *, const integerPart *,
1441 const integerPart *, unsigned);
1443 /// DST = LHS * RHS, where DST has width the sum of the widths of
1444 /// the operands. No overflow occurs. DST must be disjoint from
1445 /// both operands. Returns the number of parts required to hold the
1447 static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1448 const integerPart *, unsigned, unsigned);
1450 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1451 /// Otherwise set LHS to LHS / RHS with the fractional part
1452 /// discarded, set REMAINDER to the remainder, return zero. i.e.
1454 /// OLD_LHS = RHS * LHS + REMAINDER
1456 /// SCRATCH is a bignum of the same size as the operands and result
1457 /// for use by the routine; its contents need not be initialized
1458 /// and are destroyed. LHS, REMAINDER and SCRATCH must be
1460 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1461 integerPart *remainder, integerPart *scratch,
1462 unsigned int parts);
1464 /// Shift a bignum left COUNT bits. Shifted in bits are zero.
1465 /// There are no restrictions on COUNT.
1466 static void tcShiftLeft(integerPart *, unsigned int parts,
1467 unsigned int count);
1469 /// Shift a bignum right COUNT bits. Shifted in bits are zero.
1470 /// There are no restrictions on COUNT.
1471 static void tcShiftRight(integerPart *, unsigned int parts,
1472 unsigned int count);
1474 /// The obvious AND, OR and XOR and complement operations.
1475 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1476 static void tcOr(integerPart *, const integerPart *, unsigned int);
1477 static void tcXor(integerPart *, const integerPart *, unsigned int);
1478 static void tcComplement(integerPart *, unsigned int);
1480 /// Comparison (unsigned) of two bignums.
1481 static int tcCompare(const integerPart *, const integerPart *,
1484 /// Increment a bignum in-place. Return the carry flag.
1485 static integerPart tcIncrement(integerPart *, unsigned int);
1487 /// Set the least significant BITS and clear the rest.
1488 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1491 /// @brief debug method
1497 /// Magic data for optimising signed division by a constant.
1499 APInt m; ///< magic number
1500 unsigned s; ///< shift amount
1503 /// Magic data for optimising unsigned division by a constant.
1505 APInt m; ///< magic number
1506 bool a; ///< add indicator
1507 unsigned s; ///< shift amount
1510 inline bool operator==(uint64_t V1, const APInt& V2) {
1514 inline bool operator!=(uint64_t V1, const APInt& V2) {
1518 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1523 namespace APIntOps {
1525 /// @brief Determine the smaller of two APInts considered to be signed.
1526 inline APInt smin(const APInt &A, const APInt &B) {
1527 return A.slt(B) ? A : B;
1530 /// @brief Determine the larger of two APInts considered to be signed.
1531 inline APInt smax(const APInt &A, const APInt &B) {
1532 return A.sgt(B) ? A : B;
1535 /// @brief Determine the smaller of two APInts considered to be signed.
1536 inline APInt umin(const APInt &A, const APInt &B) {
1537 return A.ult(B) ? A : B;
1540 /// @brief Determine the larger of two APInts considered to be unsigned.
1541 inline APInt umax(const APInt &A, const APInt &B) {
1542 return A.ugt(B) ? A : B;
1545 /// @brief Check if the specified APInt has a N-bits unsigned integer value.
1546 inline bool isIntN(unsigned N, const APInt& APIVal) {
1547 return APIVal.isIntN(N);
1550 /// @brief Check if the specified APInt has a N-bits signed integer value.
1551 inline bool isSignedIntN(unsigned N, const APInt& APIVal) {
1552 return APIVal.isSignedIntN(N);
1555 /// @returns true if the argument APInt value is a sequence of ones
1556 /// starting at the least significant bit with the remainder zero.
1557 inline bool isMask(unsigned numBits, const APInt& APIVal) {
1558 return numBits <= APIVal.getBitWidth() &&
1559 APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
1562 /// @returns true if the argument APInt value contains a sequence of ones
1563 /// with the remainder zero.
1564 inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
1565 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1568 /// @returns a byte-swapped representation of the specified APInt Value.
1569 inline APInt byteSwap(const APInt& APIVal) {
1570 return APIVal.byteSwap();
1573 /// @returns the floor log base 2 of the specified APInt value.
1574 inline unsigned logBase2(const APInt& APIVal) {
1575 return APIVal.logBase2();
1578 /// GreatestCommonDivisor - This function returns the greatest common
1579 /// divisor of the two APInt values using Euclid's algorithm.
1580 /// @returns the greatest common divisor of Val1 and Val2
1581 /// @brief Compute GCD of two APInt values.
1582 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1584 /// Treats the APInt as an unsigned value for conversion purposes.
1585 /// @brief Converts the given APInt to a double value.
1586 inline double RoundAPIntToDouble(const APInt& APIVal) {
1587 return APIVal.roundToDouble();
1590 /// Treats the APInt as a signed value for conversion purposes.
1591 /// @brief Converts the given APInt to a double value.
1592 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1593 return APIVal.signedRoundToDouble();
1596 /// @brief Converts the given APInt to a float vlalue.
1597 inline float RoundAPIntToFloat(const APInt& APIVal) {
1598 return float(RoundAPIntToDouble(APIVal));
1601 /// Treast the APInt as a signed value for conversion purposes.
1602 /// @brief Converts the given APInt to a float value.
1603 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1604 return float(APIVal.signedRoundToDouble());
1607 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1608 /// @brief Converts the given double value into a APInt.
1609 APInt RoundDoubleToAPInt(double Double, unsigned width);
1611 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1612 /// @brief Converts a float value into a APInt.
1613 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
1614 return RoundDoubleToAPInt(double(Float), width);
1617 /// Arithmetic right-shift the APInt by shiftAmt.
1618 /// @brief Arithmetic right-shift function.
1619 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
1620 return LHS.ashr(shiftAmt);
1623 /// Logical right-shift the APInt by shiftAmt.
1624 /// @brief Logical right-shift function.
1625 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
1626 return LHS.lshr(shiftAmt);
1629 /// Left-shift the APInt by shiftAmt.
1630 /// @brief Left-shift function.
1631 inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
1632 return LHS.shl(shiftAmt);
1635 /// Signed divide APInt LHS by APInt RHS.
1636 /// @brief Signed division function for APInt.
1637 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1638 return LHS.sdiv(RHS);
1641 /// Unsigned divide APInt LHS by APInt RHS.
1642 /// @brief Unsigned division function for APInt.
1643 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1644 return LHS.udiv(RHS);
1647 /// Signed remainder operation on APInt.
1648 /// @brief Function for signed remainder operation.
1649 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1650 return LHS.srem(RHS);
1653 /// Unsigned remainder operation on APInt.
1654 /// @brief Function for unsigned remainder operation.
1655 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1656 return LHS.urem(RHS);
1659 /// Performs multiplication on APInt values.
1660 /// @brief Function for multiplication operation.
1661 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1665 /// Performs addition on APInt values.
1666 /// @brief Function for addition operation.
1667 inline APInt add(const APInt& LHS, const APInt& RHS) {
1671 /// Performs subtraction on APInt values.
1672 /// @brief Function for subtraction operation.
1673 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1677 /// Performs bitwise AND operation on APInt LHS and
1679 /// @brief Bitwise AND function for APInt.
1680 inline APInt And(const APInt& LHS, const APInt& RHS) {
1684 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1685 /// @brief Bitwise OR function for APInt.
1686 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1690 /// Performs bitwise XOR operation on APInt.
1691 /// @brief Bitwise XOR function for APInt.
1692 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1696 /// Performs a bitwise complement operation on APInt.
1697 /// @brief Bitwise complement function.
1698 inline APInt Not(const APInt& APIVal) {
1702 } // End of APIntOps namespace
1704 } // End of llvm namespace