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/ADT/ArrayRef.h"
19 #include "llvm/Support/MathExtras.h"
27 class FoldingSetNodeID;
34 class SmallVectorImpl;
36 // An unsigned host type used as a single part of a multi-part
38 typedef uint64_t integerPart;
40 const unsigned int host_char_bit = 8;
41 const unsigned int integerPartWidth = host_char_bit *
42 static_cast<unsigned int>(sizeof(integerPart));
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 /// APInt - This class represents arbitrary precision constant integral values.
49 /// It is a functional replacement for common case unsigned integer type like
50 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
51 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
52 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
53 /// and methods to manipulate integer values of any bit-width. It supports both
54 /// the typical integer arithmetic and comparison operations as well as bitwise
57 /// The class has several invariants worth noting:
58 /// * All bit, byte, and word positions are zero-based.
59 /// * Once the bit width is set, it doesn't change except by the Truncate,
60 /// SignExtend, or ZeroExtend operations.
61 /// * All binary operators must be on APInt instances of the same bit width.
62 /// Attempting to use these operators on instances with different bit
63 /// widths will yield an assertion.
64 /// * The value is stored canonically as an unsigned value. For operations
65 /// where it makes a difference, there are both signed and unsigned variants
66 /// of the operation. For example, sdiv and udiv. However, because the bit
67 /// widths must be the same, operations such as Mul and Add produce the same
68 /// results regardless of whether the values are interpreted as signed or
70 /// * In general, the class tries to follow the style of computation that LLVM
71 /// uses in its IR. This simplifies its use for LLVM.
73 /// @brief Class for arbitrary precision integers.
75 unsigned BitWidth; ///< The number of bits in this APInt.
77 /// This union is used to store the integer value. When the
78 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
80 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
81 uint64_t *pVal; ///< Used to store the >64 bits integer value.
84 /// This enum is used to hold the constants we needed for APInt.
87 APINT_BITS_PER_WORD = static_cast<unsigned int>(sizeof(uint64_t)) *
89 /// Byte size of a word
90 APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t))
93 /// This constructor is used only internally for speed of construction of
94 /// temporaries. It is unsafe for general use so it is not public.
95 /// @brief Fast internal constructor
96 APInt(uint64_t* val, unsigned bits) : BitWidth(bits), pVal(val) { }
98 /// @returns true if the number of bits <= 64, false otherwise.
99 /// @brief Determine if this APInt just has one word to store value.
100 bool isSingleWord() const {
101 return BitWidth <= APINT_BITS_PER_WORD;
104 /// @returns the word position for the specified bit position.
105 /// @brief Determine which word a bit is in.
106 static unsigned whichWord(unsigned bitPosition) {
107 return bitPosition / APINT_BITS_PER_WORD;
110 /// @returns the bit position in a word for the specified bit position
112 /// @brief Determine which bit in a word a bit is in.
113 static unsigned whichBit(unsigned bitPosition) {
114 return bitPosition % APINT_BITS_PER_WORD;
117 /// This method generates and returns a uint64_t (word) mask for a single
118 /// bit at a specific bit position. This is used to mask the bit in the
119 /// corresponding word.
120 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
121 /// @brief Get a single bit mask.
122 static uint64_t maskBit(unsigned bitPosition) {
123 return 1ULL << whichBit(bitPosition);
126 /// This method is used internally to clear the to "N" bits in the high order
127 /// word that are not used by the APInt. This is needed after the most
128 /// significant word is assigned a value to ensure that those bits are
130 /// @brief Clear unused high order bits
131 APInt& clearUnusedBits() {
132 // Compute how many bits are used in the final word
133 unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
135 // If all bits are used, we want to leave the value alone. This also
136 // avoids the undefined behavior of >> when the shift is the same size as
137 // the word size (64).
140 // Mask out the high bits.
141 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
145 pVal[getNumWords() - 1] &= mask;
149 /// @returns the corresponding word for the specified bit position.
150 /// @brief Get the word corresponding to a bit position
151 uint64_t getWord(unsigned bitPosition) const {
152 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
155 /// Converts a string into a number. The string must be non-empty
156 /// and well-formed as a number of the given base. The bit-width
157 /// must be sufficient to hold the result.
159 /// This is used by the constructors that take string arguments.
161 /// StringRef::getAsInteger is superficially similar but (1) does
162 /// not assume that the string is well-formed and (2) grows the
163 /// result to hold the input.
165 /// @param radix 2, 8, 10, 16, or 36
166 /// @brief Convert a char array into an APInt
167 void fromString(unsigned numBits, StringRef str, uint8_t radix);
169 /// This is used by the toString method to divide by the radix. It simply
170 /// provides a more convenient form of divide for internal use since KnuthDiv
171 /// has specific constraints on its inputs. If those constraints are not met
172 /// then it provides a simpler form of divide.
173 /// @brief An internal division function for dividing APInts.
174 static void divide(const APInt LHS, unsigned lhsWords,
175 const APInt &RHS, unsigned rhsWords,
176 APInt *Quotient, APInt *Remainder);
178 /// out-of-line slow case for inline constructor
179 void initSlowCase(unsigned numBits, uint64_t val, bool isSigned);
181 /// shared code between two array constructors
182 void initFromArray(ArrayRef<uint64_t> array);
184 /// out-of-line slow case for inline copy constructor
185 void initSlowCase(const APInt& that);
187 /// out-of-line slow case for shl
188 APInt shlSlowCase(unsigned shiftAmt) const;
190 /// out-of-line slow case for operator&
191 APInt AndSlowCase(const APInt& RHS) const;
193 /// out-of-line slow case for operator|
194 APInt OrSlowCase(const APInt& RHS) const;
196 /// out-of-line slow case for operator^
197 APInt XorSlowCase(const APInt& RHS) const;
199 /// out-of-line slow case for operator=
200 APInt& AssignSlowCase(const APInt& RHS);
202 /// out-of-line slow case for operator==
203 bool EqualSlowCase(const APInt& RHS) const;
205 /// out-of-line slow case for operator==
206 bool EqualSlowCase(uint64_t Val) const;
208 /// out-of-line slow case for countLeadingZeros
209 unsigned countLeadingZerosSlowCase() const;
211 /// out-of-line slow case for countTrailingOnes
212 unsigned countTrailingOnesSlowCase() const;
214 /// out-of-line slow case for countPopulation
215 unsigned countPopulationSlowCase() const;
218 /// @name Constructors
220 /// If isSigned is true then val is treated as if it were a signed value
221 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
222 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
223 /// the range of val are zero filled).
224 /// @param numBits the bit width of the constructed APInt
225 /// @param val the initial value of the APInt
226 /// @param isSigned how to treat signedness of val
227 /// @brief Create a new APInt of numBits width, initialized as val.
228 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
229 : BitWidth(numBits), VAL(0) {
230 assert(BitWidth && "bitwidth too small");
234 initSlowCase(numBits, val, isSigned);
238 /// Note that bigVal.size() can be smaller or larger than the corresponding
239 /// bit width but any extraneous bits will be dropped.
240 /// @param numBits the bit width of the constructed APInt
241 /// @param bigVal a sequence of words to form the initial value of the APInt
242 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
243 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
244 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
245 /// deprecated because this constructor is prone to ambiguity with the
246 /// APInt(unsigned, uint64_t, bool) constructor.
248 /// If this overload is ever deleted, care should be taken to prevent calls
249 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
251 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
253 /// This constructor interprets the string \arg str in the given radix. The
254 /// interpretation stops when the first character that is not suitable for the
255 /// radix is encountered, or the end of the string. Acceptable radix values
256 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
257 /// string to require more bits than numBits.
259 /// @param numBits the bit width of the constructed APInt
260 /// @param str the string to be interpreted
261 /// @param radix the radix to use for the conversion
262 /// @brief Construct an APInt from a string representation.
263 APInt(unsigned numBits, StringRef str, uint8_t radix);
265 /// Simply makes *this a copy of that.
266 /// @brief Copy Constructor.
267 APInt(const APInt& that)
268 : BitWidth(that.BitWidth), VAL(0) {
269 assert(BitWidth && "bitwidth too small");
276 /// @brief Destructor.
282 /// Default constructor that creates an uninitialized APInt. This is useful
283 /// for object deserialization (pair this with the static method Read).
284 explicit APInt() : BitWidth(1) {}
286 /// Profile - Used to insert APInt objects, or objects that contain APInt
287 /// objects, into FoldingSets.
288 void Profile(FoldingSetNodeID& id) const;
291 /// @name Value Tests
293 /// This tests the high bit of this APInt to determine if it is set.
294 /// @returns true if this APInt is negative, false otherwise
295 /// @brief Determine sign of this APInt.
296 bool isNegative() const {
297 return (*this)[BitWidth - 1];
300 /// This tests the high bit of the APInt to determine if it is unset.
301 /// @brief Determine if this APInt Value is non-negative (>= 0)
302 bool isNonNegative() const {
303 return !isNegative();
306 /// This tests if the value of this APInt is positive (> 0). Note
307 /// that 0 is not a positive value.
308 /// @returns true if this APInt is positive.
309 /// @brief Determine if this APInt Value is positive.
310 bool isStrictlyPositive() const {
311 return isNonNegative() && !!*this;
314 /// This checks to see if the value has all bits of the APInt are set or not.
315 /// @brief Determine if all bits are set
316 bool isAllOnesValue() const {
317 return countPopulation() == BitWidth;
320 /// This checks to see if the value of this APInt is the maximum unsigned
321 /// value for the APInt's bit width.
322 /// @brief Determine if this is the largest unsigned value.
323 bool isMaxValue() const {
324 return countPopulation() == BitWidth;
327 /// This checks to see if the value of this APInt is the maximum signed
328 /// value for the APInt's bit width.
329 /// @brief Determine if this is the largest signed value.
330 bool isMaxSignedValue() const {
331 return BitWidth == 1 ? VAL == 0 :
332 !isNegative() && countPopulation() == BitWidth - 1;
335 /// This checks to see if the value of this APInt is the minimum unsigned
336 /// value for the APInt's bit width.
337 /// @brief Determine if this is the smallest unsigned value.
338 bool isMinValue() const {
342 /// This checks to see if the value of this APInt is the minimum signed
343 /// value for the APInt's bit width.
344 /// @brief Determine if this is the smallest signed value.
345 bool isMinSignedValue() const {
346 return BitWidth == 1 ? VAL == 1 : isNegative() && isPowerOf2();
349 /// @brief Check if this APInt has an N-bits unsigned integer value.
350 bool isIntN(unsigned N) const {
351 assert(N && "N == 0 ???");
352 if (N >= getBitWidth())
356 return isUIntN(N, VAL);
357 return APInt(N, makeArrayRef(pVal, getNumWords())).zext(getBitWidth())
361 /// @brief Check if this APInt has an N-bits signed integer value.
362 bool isSignedIntN(unsigned N) const {
363 assert(N && "N == 0 ???");
364 return getMinSignedBits() <= N;
367 /// @returns true if the argument APInt value is a power of two > 0.
368 bool isPowerOf2() const {
370 return isPowerOf2_64(VAL);
371 return countPopulationSlowCase() == 1;
374 /// isSignBit - Return true if this is the value returned by getSignBit.
375 bool isSignBit() const { return isMinSignedValue(); }
377 /// This converts the APInt to a boolean value as a test against zero.
378 /// @brief Boolean conversion function.
379 bool getBoolValue() const {
383 /// getLimitedValue - If this value is smaller than the specified limit,
384 /// return it, otherwise return the limit value. This causes the value
385 /// to saturate to the limit.
386 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
387 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
388 Limit : getZExtValue();
392 /// @name Value Generators
394 /// @brief Gets maximum unsigned value of APInt for specific bit width.
395 static APInt getMaxValue(unsigned numBits) {
396 return getAllOnesValue(numBits);
399 /// @brief Gets maximum signed value of APInt for a specific bit width.
400 static APInt getSignedMaxValue(unsigned numBits) {
401 APInt API = getAllOnesValue(numBits);
402 API.clearBit(numBits - 1);
406 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
407 static APInt getMinValue(unsigned numBits) {
408 return APInt(numBits, 0);
411 /// @brief Gets minimum signed value of APInt for a specific bit width.
412 static APInt getSignedMinValue(unsigned numBits) {
413 APInt API(numBits, 0);
414 API.setBit(numBits - 1);
418 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
419 /// it helps code readability when we want to get a SignBit.
420 /// @brief Get the SignBit for a specific bit width.
421 static APInt getSignBit(unsigned BitWidth) {
422 return getSignedMinValue(BitWidth);
425 /// @returns the all-ones value for an APInt of the specified bit-width.
426 /// @brief Get the all-ones value.
427 static APInt getAllOnesValue(unsigned numBits) {
428 return APInt(numBits, -1ULL, true);
431 /// @returns the '0' value for an APInt of the specified bit-width.
432 /// @brief Get the '0' value.
433 static APInt getNullValue(unsigned numBits) {
434 return APInt(numBits, 0);
437 /// Get an APInt with the same BitWidth as this APInt, just zero mask
438 /// the low bits and right shift to the least significant bit.
439 /// @returns the high "numBits" bits of this APInt.
440 APInt getHiBits(unsigned numBits) const;
442 /// Get an APInt with the same BitWidth as this APInt, just zero mask
444 /// @returns the low "numBits" bits of this APInt.
445 APInt getLoBits(unsigned numBits) const;
447 /// getOneBitSet - Return an APInt with exactly one bit set in the result.
448 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
449 APInt Res(numBits, 0);
454 /// Constructs an APInt value that has a contiguous range of bits set. The
455 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
456 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
457 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
458 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
459 /// @param numBits the intended bit width of the result
460 /// @param loBit the index of the lowest bit set.
461 /// @param hiBit the index of the highest bit set.
462 /// @returns An APInt value with the requested bits set.
463 /// @brief Get a value with a block of bits set.
464 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
465 assert(hiBit <= numBits && "hiBit out of range");
466 assert(loBit < numBits && "loBit out of range");
468 return getLowBitsSet(numBits, hiBit) |
469 getHighBitsSet(numBits, numBits-loBit);
470 return getLowBitsSet(numBits, hiBit-loBit).shl(loBit);
473 /// Constructs an APInt value that has the top hiBitsSet bits set.
474 /// @param numBits the bitwidth of the result
475 /// @param hiBitsSet the number of high-order bits set in the result.
476 /// @brief Get a value with high bits set
477 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
478 assert(hiBitsSet <= numBits && "Too many bits to set!");
479 // Handle a degenerate case, to avoid shifting by word size
481 return APInt(numBits, 0);
482 unsigned shiftAmt = numBits - hiBitsSet;
483 // For small values, return quickly
484 if (numBits <= APINT_BITS_PER_WORD)
485 return APInt(numBits, ~0ULL << shiftAmt);
486 return getAllOnesValue(numBits).shl(shiftAmt);
489 /// Constructs an APInt value that has the bottom loBitsSet bits set.
490 /// @param numBits the bitwidth of the result
491 /// @param loBitsSet the number of low-order bits set in the result.
492 /// @brief Get a value with low bits set
493 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
494 assert(loBitsSet <= numBits && "Too many bits to set!");
495 // Handle a degenerate case, to avoid shifting by word size
497 return APInt(numBits, 0);
498 if (loBitsSet == APINT_BITS_PER_WORD)
499 return APInt(numBits, -1ULL);
500 // For small values, return quickly.
501 if (loBitsSet <= APINT_BITS_PER_WORD)
502 return APInt(numBits, -1ULL >> (APINT_BITS_PER_WORD - loBitsSet));
503 return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
506 /// \brief Overload to compute a hash_code for an APInt value.
507 friend hash_code hash_value(const APInt &Arg);
509 /// This function returns a pointer to the internal storage of the APInt.
510 /// This is useful for writing out the APInt in binary form without any
512 const uint64_t* getRawData() const {
519 /// @name Unary Operators
521 /// @returns a new APInt value representing *this incremented by one
522 /// @brief Postfix increment operator.
523 const APInt operator++(int) {
529 /// @returns *this incremented by one
530 /// @brief Prefix increment operator.
533 /// @returns a new APInt representing *this decremented by one.
534 /// @brief Postfix decrement operator.
535 const APInt operator--(int) {
541 /// @returns *this decremented by one.
542 /// @brief Prefix decrement operator.
545 /// Performs a bitwise complement operation on this APInt.
546 /// @returns an APInt that is the bitwise complement of *this
547 /// @brief Unary bitwise complement operator.
548 APInt operator~() const {
550 Result.flipAllBits();
554 /// Negates *this using two's complement logic.
555 /// @returns An APInt value representing the negation of *this.
556 /// @brief Unary negation operator
557 APInt operator-() const {
558 return APInt(BitWidth, 0) - (*this);
561 /// Performs logical negation operation on this APInt.
562 /// @returns true if *this is zero, false otherwise.
563 /// @brief Logical negation operator.
564 bool operator!() const {
568 for (unsigned i = 0; i != getNumWords(); ++i)
575 /// @name Assignment Operators
577 /// @returns *this after assignment of RHS.
578 /// @brief Copy assignment operator.
579 APInt& operator=(const APInt& RHS) {
580 // If the bitwidths are the same, we can avoid mucking with memory
581 if (isSingleWord() && RHS.isSingleWord()) {
583 BitWidth = RHS.BitWidth;
584 return clearUnusedBits();
587 return AssignSlowCase(RHS);
590 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
591 /// the bit width, the excess bits are truncated. If the bit width is larger
592 /// than 64, the value is zero filled in the unspecified high order bits.
593 /// @returns *this after assignment of RHS value.
594 /// @brief Assignment operator.
595 APInt& operator=(uint64_t RHS);
597 /// Performs a bitwise AND operation on this APInt and RHS. The result is
598 /// assigned to *this.
599 /// @returns *this after ANDing with RHS.
600 /// @brief Bitwise AND assignment operator.
601 APInt& operator&=(const APInt& RHS);
603 /// Performs a bitwise OR operation on this APInt and RHS. The result is
605 /// @returns *this after ORing with RHS.
606 /// @brief Bitwise OR assignment operator.
607 APInt& operator|=(const APInt& RHS);
609 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
610 /// logically zero-extended or truncated to match the bit-width of
613 /// @brief Bitwise OR assignment operator.
614 APInt& operator|=(uint64_t RHS) {
615 if (isSingleWord()) {
624 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
625 /// assigned to *this.
626 /// @returns *this after XORing with RHS.
627 /// @brief Bitwise XOR assignment operator.
628 APInt& operator^=(const APInt& RHS);
630 /// Multiplies this APInt by RHS and assigns the result to *this.
632 /// @brief Multiplication assignment operator.
633 APInt& operator*=(const APInt& RHS);
635 /// Adds RHS to *this and assigns the result to *this.
637 /// @brief Addition assignment operator.
638 APInt& operator+=(const APInt& RHS);
640 /// Subtracts RHS from *this and assigns the result to *this.
642 /// @brief Subtraction assignment operator.
643 APInt& operator-=(const APInt& RHS);
645 /// Shifts *this left by shiftAmt and assigns the result to *this.
646 /// @returns *this after shifting left by shiftAmt
647 /// @brief Left-shift assignment function.
648 APInt& operator<<=(unsigned shiftAmt) {
649 *this = shl(shiftAmt);
654 /// @name Binary Operators
656 /// Performs a bitwise AND operation on *this and RHS.
657 /// @returns An APInt value representing the bitwise AND of *this and RHS.
658 /// @brief Bitwise AND operator.
659 APInt operator&(const APInt& RHS) const {
660 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
662 return APInt(getBitWidth(), VAL & RHS.VAL);
663 return AndSlowCase(RHS);
665 APInt And(const APInt& RHS) const {
666 return this->operator&(RHS);
669 /// Performs a bitwise OR operation on *this and RHS.
670 /// @returns An APInt value representing the bitwise OR of *this and RHS.
671 /// @brief Bitwise OR operator.
672 APInt operator|(const APInt& RHS) const {
673 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
675 return APInt(getBitWidth(), VAL | RHS.VAL);
676 return OrSlowCase(RHS);
678 APInt Or(const APInt& RHS) const {
679 return this->operator|(RHS);
682 /// Performs a bitwise XOR operation on *this and RHS.
683 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
684 /// @brief Bitwise XOR operator.
685 APInt operator^(const APInt& RHS) const {
686 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
688 return APInt(BitWidth, VAL ^ RHS.VAL);
689 return XorSlowCase(RHS);
691 APInt Xor(const APInt& RHS) const {
692 return this->operator^(RHS);
695 /// Multiplies this APInt by RHS and returns the result.
696 /// @brief Multiplication operator.
697 APInt operator*(const APInt& RHS) const;
699 /// Adds RHS to this APInt and returns the result.
700 /// @brief Addition operator.
701 APInt operator+(const APInt& RHS) const;
702 APInt operator+(uint64_t RHS) const {
703 return (*this) + APInt(BitWidth, RHS);
706 /// Subtracts RHS from this APInt and returns the result.
707 /// @brief Subtraction operator.
708 APInt operator-(const APInt& RHS) const;
709 APInt operator-(uint64_t RHS) const {
710 return (*this) - APInt(BitWidth, RHS);
713 APInt operator<<(unsigned Bits) const {
717 APInt operator<<(const APInt &Bits) const {
721 /// Arithmetic right-shift this APInt by shiftAmt.
722 /// @brief Arithmetic right-shift function.
723 APInt ashr(unsigned shiftAmt) const;
725 /// Logical right-shift this APInt by shiftAmt.
726 /// @brief Logical right-shift function.
727 APInt lshr(unsigned shiftAmt) const;
729 /// Left-shift this APInt by shiftAmt.
730 /// @brief Left-shift function.
731 APInt shl(unsigned shiftAmt) const {
732 assert(shiftAmt <= BitWidth && "Invalid shift amount");
733 if (isSingleWord()) {
734 if (shiftAmt == BitWidth)
735 return APInt(BitWidth, 0); // avoid undefined shift results
736 return APInt(BitWidth, VAL << shiftAmt);
738 return shlSlowCase(shiftAmt);
741 /// @brief Rotate left by rotateAmt.
742 APInt rotl(unsigned rotateAmt) const;
744 /// @brief Rotate right by rotateAmt.
745 APInt rotr(unsigned rotateAmt) const;
747 /// Arithmetic right-shift this APInt by shiftAmt.
748 /// @brief Arithmetic right-shift function.
749 APInt ashr(const APInt &shiftAmt) const;
751 /// Logical right-shift this APInt by shiftAmt.
752 /// @brief Logical right-shift function.
753 APInt lshr(const APInt &shiftAmt) const;
755 /// Left-shift this APInt by shiftAmt.
756 /// @brief Left-shift function.
757 APInt shl(const APInt &shiftAmt) const;
759 /// @brief Rotate left by rotateAmt.
760 APInt rotl(const APInt &rotateAmt) const;
762 /// @brief Rotate right by rotateAmt.
763 APInt rotr(const APInt &rotateAmt) const;
765 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
766 /// RHS are treated as unsigned quantities for purposes of this division.
767 /// @returns a new APInt value containing the division result
768 /// @brief Unsigned division operation.
769 APInt udiv(const APInt &RHS) const;
771 /// Signed divide this APInt by APInt RHS.
772 /// @brief Signed division function for APInt.
773 APInt sdiv(const APInt &RHS) const {
775 if (RHS.isNegative())
776 return (-(*this)).udiv(-RHS);
778 return -((-(*this)).udiv(RHS));
779 else if (RHS.isNegative())
780 return -(this->udiv(-RHS));
781 return this->udiv(RHS);
784 /// Perform an unsigned remainder operation on this APInt with RHS being the
785 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
786 /// of this operation. Note that this is a true remainder operation and not
787 /// a modulo operation because the sign follows the sign of the dividend
789 /// @returns a new APInt value containing the remainder result
790 /// @brief Unsigned remainder operation.
791 APInt urem(const APInt &RHS) const;
793 /// Signed remainder operation on APInt.
794 /// @brief Function for signed remainder operation.
795 APInt srem(const APInt &RHS) const {
797 if (RHS.isNegative())
798 return -((-(*this)).urem(-RHS));
800 return -((-(*this)).urem(RHS));
801 else if (RHS.isNegative())
802 return this->urem(-RHS);
803 return this->urem(RHS);
806 /// Sometimes it is convenient to divide two APInt values and obtain both the
807 /// quotient and remainder. This function does both operations in the same
808 /// computation making it a little more efficient. The pair of input arguments
809 /// may overlap with the pair of output arguments. It is safe to call
810 /// udivrem(X, Y, X, Y), for example.
811 /// @brief Dual division/remainder interface.
812 static void udivrem(const APInt &LHS, const APInt &RHS,
813 APInt &Quotient, APInt &Remainder);
815 static void sdivrem(const APInt &LHS, const APInt &RHS,
816 APInt &Quotient, APInt &Remainder) {
817 if (LHS.isNegative()) {
818 if (RHS.isNegative())
819 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
821 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
822 Quotient = -Quotient;
823 Remainder = -Remainder;
824 } else if (RHS.isNegative()) {
825 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
826 Quotient = -Quotient;
828 APInt::udivrem(LHS, RHS, Quotient, Remainder);
833 // Operations that return overflow indicators.
834 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
835 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
836 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
837 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
838 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
839 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
840 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
841 APInt sshl_ov(unsigned Amt, bool &Overflow) const;
843 /// @returns the bit value at bitPosition
844 /// @brief Array-indexing support.
845 bool operator[](unsigned bitPosition) const;
848 /// @name Comparison Operators
850 /// Compares this APInt with RHS for the validity of the equality
852 /// @brief Equality operator.
853 bool operator==(const APInt& RHS) const {
854 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
856 return VAL == RHS.VAL;
857 return EqualSlowCase(RHS);
860 /// Compares this APInt with a uint64_t for the validity of the equality
862 /// @returns true if *this == Val
863 /// @brief Equality operator.
864 bool operator==(uint64_t Val) const {
867 return EqualSlowCase(Val);
870 /// Compares this APInt with RHS for the validity of the equality
872 /// @returns true if *this == Val
873 /// @brief Equality comparison.
874 bool eq(const APInt &RHS) const {
875 return (*this) == RHS;
878 /// Compares this APInt with RHS for the validity of the inequality
880 /// @returns true if *this != Val
881 /// @brief Inequality operator.
882 bool operator!=(const APInt& RHS) const {
883 return !((*this) == RHS);
886 /// Compares this APInt with a uint64_t for the validity of the inequality
888 /// @returns true if *this != Val
889 /// @brief Inequality operator.
890 bool operator!=(uint64_t Val) const {
891 return !((*this) == Val);
894 /// Compares this APInt with RHS for the validity of the inequality
896 /// @returns true if *this != Val
897 /// @brief Inequality comparison
898 bool ne(const APInt &RHS) const {
899 return !((*this) == RHS);
902 /// Regards both *this and RHS as unsigned quantities and compares them for
903 /// the validity of the less-than relationship.
904 /// @returns true if *this < RHS when both are considered unsigned.
905 /// @brief Unsigned less than comparison
906 bool ult(const APInt &RHS) const;
908 /// Regards both *this as an unsigned quantity and compares it with RHS for
909 /// the validity of the less-than relationship.
910 /// @returns true if *this < RHS when considered unsigned.
911 /// @brief Unsigned less than comparison
912 bool ult(uint64_t RHS) const {
913 return ult(APInt(getBitWidth(), RHS));
916 /// Regards both *this and RHS as signed quantities and compares them for
917 /// validity of the less-than relationship.
918 /// @returns true if *this < RHS when both are considered signed.
919 /// @brief Signed less than comparison
920 bool slt(const APInt& RHS) const;
922 /// Regards both *this as a signed quantity and compares it with RHS for
923 /// the validity of the less-than relationship.
924 /// @returns true if *this < RHS when considered signed.
925 /// @brief Signed less than comparison
926 bool slt(uint64_t RHS) const {
927 return slt(APInt(getBitWidth(), RHS));
930 /// Regards both *this and RHS as unsigned quantities and compares them for
931 /// validity of the less-or-equal relationship.
932 /// @returns true if *this <= RHS when both are considered unsigned.
933 /// @brief Unsigned less or equal comparison
934 bool ule(const APInt& RHS) const {
935 return ult(RHS) || eq(RHS);
938 /// Regards both *this as an unsigned quantity and compares it with RHS for
939 /// the validity of the less-or-equal relationship.
940 /// @returns true if *this <= RHS when considered unsigned.
941 /// @brief Unsigned less or equal comparison
942 bool ule(uint64_t RHS) const {
943 return ule(APInt(getBitWidth(), RHS));
946 /// Regards both *this and RHS as signed quantities and compares them for
947 /// validity of the less-or-equal relationship.
948 /// @returns true if *this <= RHS when both are considered signed.
949 /// @brief Signed less or equal comparison
950 bool sle(const APInt& RHS) const {
951 return slt(RHS) || eq(RHS);
954 /// Regards both *this as a signed quantity and compares it with RHS for
955 /// the validity of the less-or-equal relationship.
956 /// @returns true if *this <= RHS when considered signed.
957 /// @brief Signed less or equal comparison
958 bool sle(uint64_t RHS) const {
959 return sle(APInt(getBitWidth(), RHS));
962 /// Regards both *this and RHS as unsigned quantities and compares them for
963 /// the validity of the greater-than relationship.
964 /// @returns true if *this > RHS when both are considered unsigned.
965 /// @brief Unsigned greather than comparison
966 bool ugt(const APInt& RHS) const {
967 return !ult(RHS) && !eq(RHS);
970 /// Regards both *this as an unsigned quantity and compares it with RHS for
971 /// the validity of the greater-than relationship.
972 /// @returns true if *this > RHS when considered unsigned.
973 /// @brief Unsigned greater than comparison
974 bool ugt(uint64_t RHS) const {
975 return ugt(APInt(getBitWidth(), RHS));
978 /// Regards both *this and RHS as signed quantities and compares them for
979 /// the validity of the greater-than relationship.
980 /// @returns true if *this > RHS when both are considered signed.
981 /// @brief Signed greather than comparison
982 bool sgt(const APInt& RHS) const {
983 return !slt(RHS) && !eq(RHS);
986 /// Regards both *this as a signed quantity and compares it with RHS for
987 /// the validity of the greater-than relationship.
988 /// @returns true if *this > RHS when considered signed.
989 /// @brief Signed greater than comparison
990 bool sgt(uint64_t RHS) const {
991 return sgt(APInt(getBitWidth(), RHS));
994 /// Regards both *this and RHS as unsigned quantities and compares them for
995 /// validity of the greater-or-equal relationship.
996 /// @returns true if *this >= RHS when both are considered unsigned.
997 /// @brief Unsigned greater or equal comparison
998 bool uge(const APInt& RHS) const {
1002 /// Regards both *this as an unsigned quantity and compares it with RHS for
1003 /// the validity of the greater-or-equal relationship.
1004 /// @returns true if *this >= RHS when considered unsigned.
1005 /// @brief Unsigned greater or equal comparison
1006 bool uge(uint64_t RHS) const {
1007 return uge(APInt(getBitWidth(), RHS));
1010 /// Regards both *this and RHS as signed quantities and compares them for
1011 /// validity of the greater-or-equal relationship.
1012 /// @returns true if *this >= RHS when both are considered signed.
1013 /// @brief Signed greather or equal comparison
1014 bool sge(const APInt& RHS) const {
1018 /// Regards both *this as a signed quantity and compares it with RHS for
1019 /// the validity of the greater-or-equal relationship.
1020 /// @returns true if *this >= RHS when considered signed.
1021 /// @brief Signed greater or equal comparison
1022 bool sge(uint64_t RHS) const {
1023 return sge(APInt(getBitWidth(), RHS));
1029 /// This operation tests if there are any pairs of corresponding bits
1030 /// between this APInt and RHS that are both set.
1031 bool intersects(const APInt &RHS) const {
1032 return (*this & RHS) != 0;
1036 /// @name Resizing Operators
1038 /// Truncate the APInt to a specified width. It is an error to specify a width
1039 /// that is greater than or equal to the current width.
1040 /// @brief Truncate to new width.
1041 APInt trunc(unsigned width) const;
1043 /// This operation sign extends the APInt to a new width. If the high order
1044 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1045 /// It is an error to specify a width that is less than or equal to the
1047 /// @brief Sign extend to a new width.
1048 APInt sext(unsigned width) const;
1050 /// This operation zero extends the APInt to a new width. The high order bits
1051 /// are filled with 0 bits. It is an error to specify a width that is less
1052 /// than or equal to the current width.
1053 /// @brief Zero extend to a new width.
1054 APInt zext(unsigned width) const;
1056 /// Make this APInt have the bit width given by \p width. The value is sign
1057 /// extended, truncated, or left alone to make it that width.
1058 /// @brief Sign extend or truncate to width
1059 APInt sextOrTrunc(unsigned width) const;
1061 /// Make this APInt have the bit width given by \p width. The value is zero
1062 /// extended, truncated, or left alone to make it that width.
1063 /// @brief Zero extend or truncate to width
1064 APInt zextOrTrunc(unsigned width) const;
1066 /// Make this APInt have the bit width given by \p width. The value is sign
1067 /// extended, or left alone to make it that width.
1068 /// @brief Sign extend or truncate to width
1069 APInt sextOrSelf(unsigned width) const;
1071 /// Make this APInt have the bit width given by \p width. The value is zero
1072 /// extended, or left alone to make it that width.
1073 /// @brief Zero extend or truncate to width
1074 APInt zextOrSelf(unsigned width) const;
1077 /// @name Bit Manipulation Operators
1079 /// @brief Set every bit to 1.
1084 // Set all the bits in all the words.
1085 for (unsigned i = 0; i < getNumWords(); ++i)
1088 // Clear the unused ones
1092 /// Set the given bit to 1 whose position is given as "bitPosition".
1093 /// @brief Set a given bit to 1.
1094 void setBit(unsigned bitPosition);
1096 /// @brief Set every bit to 0.
1097 void clearAllBits() {
1101 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
1104 /// Set the given bit to 0 whose position is given as "bitPosition".
1105 /// @brief Set a given bit to 0.
1106 void clearBit(unsigned bitPosition);
1108 /// @brief Toggle every bit to its opposite value.
1109 void flipAllBits() {
1113 for (unsigned i = 0; i < getNumWords(); ++i)
1119 /// Toggle a given bit to its opposite value whose position is given
1120 /// as "bitPosition".
1121 /// @brief Toggles a given bit to its opposite value.
1122 void flipBit(unsigned bitPosition);
1125 /// @name Value Characterization Functions
1128 /// @returns the total number of bits.
1129 unsigned getBitWidth() const {
1133 /// Here one word's bitwidth equals to that of uint64_t.
1134 /// @returns the number of words to hold the integer value of this APInt.
1135 /// @brief Get the number of words.
1136 unsigned getNumWords() const {
1137 return getNumWords(BitWidth);
1140 /// Here one word's bitwidth equals to that of uint64_t.
1141 /// @returns the number of words to hold the integer value with a
1142 /// given bit width.
1143 /// @brief Get the number of words.
1144 static unsigned getNumWords(unsigned BitWidth) {
1145 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1148 /// This function returns the number of active bits which is defined as the
1149 /// bit width minus the number of leading zeros. This is used in several
1150 /// computations to see how "wide" the value is.
1151 /// @brief Compute the number of active bits in the value
1152 unsigned getActiveBits() const {
1153 return BitWidth - countLeadingZeros();
1156 /// This function returns the number of active words in the value of this
1157 /// APInt. This is used in conjunction with getActiveData to extract the raw
1158 /// value of the APInt.
1159 unsigned getActiveWords() const {
1160 return whichWord(getActiveBits()-1) + 1;
1163 /// Computes the minimum bit width for this APInt while considering it to be
1164 /// a signed (and probably negative) value. If the value is not negative,
1165 /// this function returns the same value as getActiveBits()+1. Otherwise, it
1166 /// returns the smallest bit width that will retain the negative value. For
1167 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1168 /// for -1, this function will always return 1.
1169 /// @brief Get the minimum bit size for this signed APInt
1170 unsigned getMinSignedBits() const {
1172 return BitWidth - countLeadingOnes() + 1;
1173 return getActiveBits()+1;
1176 /// This method attempts to return the value of this APInt as a zero extended
1177 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1178 /// uint64_t. Otherwise an assertion will result.
1179 /// @brief Get zero extended value
1180 uint64_t getZExtValue() const {
1183 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1187 /// This method attempts to return the value of this APInt as a sign extended
1188 /// int64_t. The bit width must be <= 64 or the value must fit within an
1189 /// int64_t. Otherwise an assertion will result.
1190 /// @brief Get sign extended value
1191 int64_t getSExtValue() const {
1193 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
1194 (APINT_BITS_PER_WORD - BitWidth);
1195 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1196 return int64_t(pVal[0]);
1199 /// This method determines how many bits are required to hold the APInt
1200 /// equivalent of the string given by \arg str.
1201 /// @brief Get bits required for string value.
1202 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1204 /// countLeadingZeros - This function is an APInt version of the
1205 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
1206 /// of zeros from the most significant bit to the first one bit.
1207 /// @returns BitWidth if the value is zero.
1208 /// @returns the number of zeros from the most significant bit to the first
1210 unsigned countLeadingZeros() const {
1211 if (isSingleWord()) {
1212 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1213 return CountLeadingZeros_64(VAL) - unusedBits;
1215 return countLeadingZerosSlowCase();
1218 /// countLeadingOnes - This function is an APInt version of the
1219 /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number
1220 /// of ones from the most significant bit to the first zero bit.
1221 /// @returns 0 if the high order bit is not set
1222 /// @returns the number of 1 bits from the most significant to the least
1223 /// @brief Count the number of leading one bits.
1224 unsigned countLeadingOnes() const;
1226 /// Computes the number of leading bits of this APInt that are equal to its
1228 unsigned getNumSignBits() const {
1229 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1232 /// countTrailingZeros - This function is an APInt version of the
1233 /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
1234 /// the number of zeros from the least significant bit to the first set bit.
1235 /// @returns BitWidth if the value is zero.
1236 /// @returns the number of zeros from the least significant bit to the first
1238 /// @brief Count the number of trailing zero bits.
1239 unsigned countTrailingZeros() const;
1241 /// countTrailingOnes - This function is an APInt version of the
1242 /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
1243 /// the number of ones from the least significant bit to the first zero bit.
1244 /// @returns BitWidth if the value is all ones.
1245 /// @returns the number of ones from the least significant bit to the first
1247 /// @brief Count the number of trailing one bits.
1248 unsigned countTrailingOnes() const {
1250 return CountTrailingOnes_64(VAL);
1251 return countTrailingOnesSlowCase();
1254 /// countPopulation - This function is an APInt version of the
1255 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
1256 /// of 1 bits in the APInt value.
1257 /// @returns 0 if the value is zero.
1258 /// @returns the number of set bits.
1259 /// @brief Count the number of bits set.
1260 unsigned countPopulation() const {
1262 return CountPopulation_64(VAL);
1263 return countPopulationSlowCase();
1267 /// @name Conversion Functions
1269 void print(raw_ostream &OS, bool isSigned) const;
1271 /// toString - Converts an APInt to a string and append it to Str. Str is
1272 /// commonly a SmallString.
1273 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1274 bool formatAsCLiteral = false) const;
1276 /// Considers the APInt to be unsigned and converts it into a string in the
1277 /// radix given. The radix can be 2, 8, 10 16, or 36.
1278 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1279 toString(Str, Radix, false, false);
1282 /// Considers the APInt to be signed and converts it into a string in the
1283 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1284 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1285 toString(Str, Radix, true, false);
1288 /// toString - This returns the APInt as a std::string. Note that this is an
1289 /// inefficient method. It is better to pass in a SmallVector/SmallString
1290 /// to the methods above to avoid thrashing the heap for the string.
1291 std::string toString(unsigned Radix, bool Signed) const;
1294 /// @returns a byte-swapped representation of this APInt Value.
1295 APInt byteSwap() const;
1297 /// @brief Converts this APInt to a double value.
1298 double roundToDouble(bool isSigned) const;
1300 /// @brief Converts this unsigned APInt to a double value.
1301 double roundToDouble() const {
1302 return roundToDouble(false);
1305 /// @brief Converts this signed APInt to a double value.
1306 double signedRoundToDouble() const {
1307 return roundToDouble(true);
1310 /// The conversion does not do a translation from integer to double, it just
1311 /// re-interprets the bits as a double. Note that it is valid to do this on
1312 /// any bit width. Exactly 64 bits will be translated.
1313 /// @brief Converts APInt bits to a double
1314 double bitsToDouble() const {
1319 T.I = (isSingleWord() ? VAL : pVal[0]);
1323 /// The conversion does not do a translation from integer to float, it just
1324 /// re-interprets the bits as a float. Note that it is valid to do this on
1325 /// any bit width. Exactly 32 bits will be translated.
1326 /// @brief Converts APInt bits to a double
1327 float bitsToFloat() const {
1332 T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1336 /// The conversion does not do a translation from double to integer, it just
1337 /// re-interprets the bits of the double.
1338 /// @brief Converts a double to APInt bits.
1339 static APInt doubleToBits(double V) {
1345 return APInt(sizeof T * CHAR_BIT, T.I);
1348 /// The conversion does not do a translation from float to integer, it just
1349 /// re-interprets the bits of the float.
1350 /// @brief Converts a float to APInt bits.
1351 static APInt floatToBits(float V) {
1357 return APInt(sizeof T * CHAR_BIT, T.I);
1361 /// @name Mathematics Operations
1364 /// @returns the floor log base 2 of this APInt.
1365 unsigned logBase2() const {
1366 return BitWidth - 1 - countLeadingZeros();
1369 /// @returns the ceil log base 2 of this APInt.
1370 unsigned ceilLogBase2() const {
1371 return BitWidth - (*this - 1).countLeadingZeros();
1374 /// @returns the log base 2 of this APInt if its an exact power of two, -1
1376 int32_t exactLogBase2() const {
1382 /// @brief Compute the square root
1385 /// If *this is < 0 then return -(*this), otherwise *this;
1386 /// @brief Get the absolute value;
1393 /// @returns the multiplicative inverse for a given modulo.
1394 APInt multiplicativeInverse(const APInt& modulo) const;
1397 /// @name Support for division by constant
1400 /// Calculate the magic number for signed division by a constant.
1404 /// Calculate the magic number for unsigned division by a constant.
1406 mu magicu(unsigned LeadingZeros = 0) const;
1409 /// @name Building-block Operations for APInt and APFloat
1412 // These building block operations operate on a representation of
1413 // arbitrary precision, two's-complement, bignum integer values.
1414 // They should be sufficient to implement APInt and APFloat bignum
1415 // requirements. Inputs are generally a pointer to the base of an
1416 // array of integer parts, representing an unsigned bignum, and a
1417 // count of how many parts there are.
1419 /// Sets the least significant part of a bignum to the input value,
1420 /// and zeroes out higher parts. */
1421 static void tcSet(integerPart *, integerPart, unsigned int);
1423 /// Assign one bignum to another.
1424 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1426 /// Returns true if a bignum is zero, false otherwise.
1427 static bool tcIsZero(const integerPart *, unsigned int);
1429 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1430 static int tcExtractBit(const integerPart *, unsigned int bit);
1432 /// Copy the bit vector of width srcBITS from SRC, starting at bit
1433 /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
1434 /// becomes the least significant bit of DST. All high bits above
1435 /// srcBITS in DST are zero-filled.
1436 static void tcExtract(integerPart *, unsigned int dstCount,
1437 const integerPart *,
1438 unsigned int srcBits, unsigned int srcLSB);
1440 /// Set the given bit of a bignum. Zero-based.
1441 static void tcSetBit(integerPart *, unsigned int bit);
1443 /// Clear the given bit of a bignum. Zero-based.
1444 static void tcClearBit(integerPart *, unsigned int bit);
1446 /// Returns the bit number of the least or most significant set bit
1447 /// of a number. If the input number has no bits set -1U is
1449 static unsigned int tcLSB(const integerPart *, unsigned int);
1450 static unsigned int tcMSB(const integerPart *parts, unsigned int n);
1452 /// Negate a bignum in-place.
1453 static void tcNegate(integerPart *, unsigned int);
1455 /// DST += RHS + CARRY where CARRY is zero or one. Returns the
1457 static integerPart tcAdd(integerPart *, const integerPart *,
1458 integerPart carry, unsigned);
1460 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the
1462 static integerPart tcSubtract(integerPart *, const integerPart *,
1463 integerPart carry, unsigned);
1465 /// DST += SRC * MULTIPLIER + PART if add is true
1466 /// DST = SRC * MULTIPLIER + PART if add is false
1468 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
1469 /// they must start at the same point, i.e. DST == SRC.
1471 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1472 /// returned. Otherwise DST is filled with the least significant
1473 /// DSTPARTS parts of the result, and if all of the omitted higher
1474 /// parts were zero return zero, otherwise overflow occurred and
1476 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1477 integerPart multiplier, integerPart carry,
1478 unsigned int srcParts, unsigned int dstParts,
1481 /// DST = LHS * RHS, where DST has the same width as the operands
1482 /// and is filled with the least significant parts of the result.
1483 /// Returns one if overflow occurred, otherwise zero. DST must be
1484 /// disjoint from both operands.
1485 static int tcMultiply(integerPart *, const integerPart *,
1486 const integerPart *, unsigned);
1488 /// DST = LHS * RHS, where DST has width the sum of the widths of
1489 /// the operands. No overflow occurs. DST must be disjoint from
1490 /// both operands. Returns the number of parts required to hold the
1492 static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1493 const integerPart *, unsigned, unsigned);
1495 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1496 /// Otherwise set LHS to LHS / RHS with the fractional part
1497 /// discarded, set REMAINDER to the remainder, return zero. i.e.
1499 /// OLD_LHS = RHS * LHS + REMAINDER
1501 /// SCRATCH is a bignum of the same size as the operands and result
1502 /// for use by the routine; its contents need not be initialized
1503 /// and are destroyed. LHS, REMAINDER and SCRATCH must be
1505 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1506 integerPart *remainder, integerPart *scratch,
1507 unsigned int parts);
1509 /// Shift a bignum left COUNT bits. Shifted in bits are zero.
1510 /// There are no restrictions on COUNT.
1511 static void tcShiftLeft(integerPart *, unsigned int parts,
1512 unsigned int count);
1514 /// Shift a bignum right COUNT bits. Shifted in bits are zero.
1515 /// There are no restrictions on COUNT.
1516 static void tcShiftRight(integerPart *, unsigned int parts,
1517 unsigned int count);
1519 /// The obvious AND, OR and XOR and complement operations.
1520 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1521 static void tcOr(integerPart *, const integerPart *, unsigned int);
1522 static void tcXor(integerPart *, const integerPart *, unsigned int);
1523 static void tcComplement(integerPart *, unsigned int);
1525 /// Comparison (unsigned) of two bignums.
1526 static int tcCompare(const integerPart *, const integerPart *,
1529 /// Increment a bignum in-place. Return the carry flag.
1530 static integerPart tcIncrement(integerPart *, unsigned int);
1532 /// Set the least significant BITS and clear the rest.
1533 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1536 /// @brief debug method
1542 /// Magic data for optimising signed division by a constant.
1544 APInt m; ///< magic number
1545 unsigned s; ///< shift amount
1548 /// Magic data for optimising unsigned division by a constant.
1550 APInt m; ///< magic number
1551 bool a; ///< add indicator
1552 unsigned s; ///< shift amount
1555 inline bool operator==(uint64_t V1, const APInt& V2) {
1559 inline bool operator!=(uint64_t V1, const APInt& V2) {
1563 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1568 namespace APIntOps {
1570 /// @brief Determine the smaller of two APInts considered to be signed.
1571 inline APInt smin(const APInt &A, const APInt &B) {
1572 return A.slt(B) ? A : B;
1575 /// @brief Determine the larger of two APInts considered to be signed.
1576 inline APInt smax(const APInt &A, const APInt &B) {
1577 return A.sgt(B) ? A : B;
1580 /// @brief Determine the smaller of two APInts considered to be signed.
1581 inline APInt umin(const APInt &A, const APInt &B) {
1582 return A.ult(B) ? A : B;
1585 /// @brief Determine the larger of two APInts considered to be unsigned.
1586 inline APInt umax(const APInt &A, const APInt &B) {
1587 return A.ugt(B) ? A : B;
1590 /// @brief Check if the specified APInt has a N-bits unsigned integer value.
1591 inline bool isIntN(unsigned N, const APInt& APIVal) {
1592 return APIVal.isIntN(N);
1595 /// @brief Check if the specified APInt has a N-bits signed integer value.
1596 inline bool isSignedIntN(unsigned N, const APInt& APIVal) {
1597 return APIVal.isSignedIntN(N);
1600 /// @returns true if the argument APInt value is a sequence of ones
1601 /// starting at the least significant bit with the remainder zero.
1602 inline bool isMask(unsigned numBits, const APInt& APIVal) {
1603 return numBits <= APIVal.getBitWidth() &&
1604 APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
1607 /// @returns true if the argument APInt value contains a sequence of ones
1608 /// with the remainder zero.
1609 inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
1610 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1613 /// @returns a byte-swapped representation of the specified APInt Value.
1614 inline APInt byteSwap(const APInt& APIVal) {
1615 return APIVal.byteSwap();
1618 /// @returns the floor log base 2 of the specified APInt value.
1619 inline unsigned logBase2(const APInt& APIVal) {
1620 return APIVal.logBase2();
1623 /// GreatestCommonDivisor - This function returns the greatest common
1624 /// divisor of the two APInt values using Euclid's algorithm.
1625 /// @returns the greatest common divisor of Val1 and Val2
1626 /// @brief Compute GCD of two APInt values.
1627 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1629 /// Treats the APInt as an unsigned value for conversion purposes.
1630 /// @brief Converts the given APInt to a double value.
1631 inline double RoundAPIntToDouble(const APInt& APIVal) {
1632 return APIVal.roundToDouble();
1635 /// Treats the APInt as a signed value for conversion purposes.
1636 /// @brief Converts the given APInt to a double value.
1637 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1638 return APIVal.signedRoundToDouble();
1641 /// @brief Converts the given APInt to a float vlalue.
1642 inline float RoundAPIntToFloat(const APInt& APIVal) {
1643 return float(RoundAPIntToDouble(APIVal));
1646 /// Treast the APInt as a signed value for conversion purposes.
1647 /// @brief Converts the given APInt to a float value.
1648 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1649 return float(APIVal.signedRoundToDouble());
1652 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1653 /// @brief Converts the given double value into a APInt.
1654 APInt RoundDoubleToAPInt(double Double, unsigned width);
1656 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1657 /// @brief Converts a float value into a APInt.
1658 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
1659 return RoundDoubleToAPInt(double(Float), width);
1662 /// Arithmetic right-shift the APInt by shiftAmt.
1663 /// @brief Arithmetic right-shift function.
1664 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
1665 return LHS.ashr(shiftAmt);
1668 /// Logical right-shift the APInt by shiftAmt.
1669 /// @brief Logical right-shift function.
1670 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
1671 return LHS.lshr(shiftAmt);
1674 /// Left-shift the APInt by shiftAmt.
1675 /// @brief Left-shift function.
1676 inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
1677 return LHS.shl(shiftAmt);
1680 /// Signed divide APInt LHS by APInt RHS.
1681 /// @brief Signed division function for APInt.
1682 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1683 return LHS.sdiv(RHS);
1686 /// Unsigned divide APInt LHS by APInt RHS.
1687 /// @brief Unsigned division function for APInt.
1688 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1689 return LHS.udiv(RHS);
1692 /// Signed remainder operation on APInt.
1693 /// @brief Function for signed remainder operation.
1694 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1695 return LHS.srem(RHS);
1698 /// Unsigned remainder operation on APInt.
1699 /// @brief Function for unsigned remainder operation.
1700 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1701 return LHS.urem(RHS);
1704 /// Performs multiplication on APInt values.
1705 /// @brief Function for multiplication operation.
1706 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1710 /// Performs addition on APInt values.
1711 /// @brief Function for addition operation.
1712 inline APInt add(const APInt& LHS, const APInt& RHS) {
1716 /// Performs subtraction on APInt values.
1717 /// @brief Function for subtraction operation.
1718 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1722 /// Performs bitwise AND operation on APInt LHS and
1724 /// @brief Bitwise AND function for APInt.
1725 inline APInt And(const APInt& LHS, const APInt& RHS) {
1729 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1730 /// @brief Bitwise OR function for APInt.
1731 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1735 /// Performs bitwise XOR operation on APInt.
1736 /// @brief Bitwise XOR function for APInt.
1737 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1741 /// Performs a bitwise complement operation on APInt.
1742 /// @brief Bitwise complement function.
1743 inline APInt Not(const APInt& APIVal) {
1747 } // End of APIntOps namespace
1749 } // End of llvm namespace