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/Compiler.h"
20 #include "llvm/Support/MathExtras.h"
28 class FoldingSetNodeID;
35 class SmallVectorImpl;
37 // An unsigned host type used as a single part of a multi-part
39 typedef uint64_t integerPart;
41 const unsigned int host_char_bit = 8;
42 const unsigned int integerPartWidth = host_char_bit *
43 static_cast<unsigned int>(sizeof(integerPart));
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 /// APInt - This class represents arbitrary precision constant integral values.
50 /// It is a functional replacement for common case unsigned integer type like
51 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
52 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
53 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
54 /// and methods to manipulate integer values of any bit-width. It supports both
55 /// the typical integer arithmetic and comparison operations as well as bitwise
58 /// The class has several invariants worth noting:
59 /// * All bit, byte, and word positions are zero-based.
60 /// * Once the bit width is set, it doesn't change except by the Truncate,
61 /// SignExtend, or ZeroExtend operations.
62 /// * All binary operators must be on APInt instances of the same bit width.
63 /// Attempting to use these operators on instances with different bit
64 /// widths will yield an assertion.
65 /// * The value is stored canonically as an unsigned value. For operations
66 /// where it makes a difference, there are both signed and unsigned variants
67 /// of the operation. For example, sdiv and udiv. However, because the bit
68 /// widths must be the same, operations such as Mul and Add produce the same
69 /// results regardless of whether the values are interpreted as signed or
71 /// * In general, the class tries to follow the style of computation that LLVM
72 /// uses in its IR. This simplifies its use for LLVM.
74 /// @brief Class for arbitrary precision integers.
76 unsigned BitWidth; ///< The number of bits in this APInt.
78 /// This union is used to store the integer value. When the
79 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
81 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
82 uint64_t *pVal; ///< Used to store the >64 bits integer value.
85 /// This enum is used to hold the constants we needed for APInt.
88 APINT_BITS_PER_WORD = static_cast<unsigned int>(sizeof(uint64_t)) *
90 /// Byte size of a word
91 APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t))
94 /// This constructor is used only internally for speed of construction of
95 /// temporaries. It is unsafe for general use so it is not public.
96 /// @brief Fast internal constructor
97 APInt(uint64_t* val, unsigned bits) : BitWidth(bits), pVal(val) { }
99 /// @returns true if the number of bits <= 64, false otherwise.
100 /// @brief Determine if this APInt just has one word to store value.
101 bool isSingleWord() const {
102 return BitWidth <= APINT_BITS_PER_WORD;
105 /// @returns the word position for the specified bit position.
106 /// @brief Determine which word a bit is in.
107 static unsigned whichWord(unsigned bitPosition) {
108 return bitPosition / APINT_BITS_PER_WORD;
111 /// @returns the bit position in a word for the specified bit position
113 /// @brief Determine which bit in a word a bit is in.
114 static unsigned whichBit(unsigned bitPosition) {
115 return bitPosition % APINT_BITS_PER_WORD;
118 /// This method generates and returns a uint64_t (word) mask for a single
119 /// bit at a specific bit position. This is used to mask the bit in the
120 /// corresponding word.
121 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
122 /// @brief Get a single bit mask.
123 static uint64_t maskBit(unsigned bitPosition) {
124 return 1ULL << whichBit(bitPosition);
127 /// This method is used internally to clear the to "N" bits in the high order
128 /// word that are not used by the APInt. This is needed after the most
129 /// significant word is assigned a value to ensure that those bits are
131 /// @brief Clear unused high order bits
132 APInt& clearUnusedBits() {
133 // Compute how many bits are used in the final word
134 unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
136 // If all bits are used, we want to leave the value alone. This also
137 // avoids the undefined behavior of >> when the shift is the same size as
138 // the word size (64).
141 // Mask out the high bits.
142 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
146 pVal[getNumWords() - 1] &= mask;
150 /// @returns the corresponding word for the specified bit position.
151 /// @brief Get the word corresponding to a bit position
152 uint64_t getWord(unsigned bitPosition) const {
153 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
156 /// Converts a string into a number. The string must be non-empty
157 /// and well-formed as a number of the given base. The bit-width
158 /// must be sufficient to hold the result.
160 /// This is used by the constructors that take string arguments.
162 /// StringRef::getAsInteger is superficially similar but (1) does
163 /// not assume that the string is well-formed and (2) grows the
164 /// result to hold the input.
166 /// @param radix 2, 8, 10, 16, or 36
167 /// @brief Convert a char array into an APInt
168 void fromString(unsigned numBits, StringRef str, uint8_t radix);
170 /// This is used by the toString method to divide by the radix. It simply
171 /// provides a more convenient form of divide for internal use since KnuthDiv
172 /// has specific constraints on its inputs. If those constraints are not met
173 /// then it provides a simpler form of divide.
174 /// @brief An internal division function for dividing APInts.
175 static void divide(const APInt LHS, unsigned lhsWords,
176 const APInt &RHS, unsigned rhsWords,
177 APInt *Quotient, APInt *Remainder);
179 /// out-of-line slow case for inline constructor
180 void initSlowCase(unsigned numBits, uint64_t val, bool isSigned);
182 /// shared code between two array constructors
183 void initFromArray(ArrayRef<uint64_t> array);
185 /// out-of-line slow case for inline copy constructor
186 void initSlowCase(const APInt& that);
188 /// out-of-line slow case for shl
189 APInt shlSlowCase(unsigned shiftAmt) const;
191 /// out-of-line slow case for operator&
192 APInt AndSlowCase(const APInt& RHS) const;
194 /// out-of-line slow case for operator|
195 APInt OrSlowCase(const APInt& RHS) const;
197 /// out-of-line slow case for operator^
198 APInt XorSlowCase(const APInt& RHS) const;
200 /// out-of-line slow case for operator=
201 APInt& AssignSlowCase(const APInt& RHS);
203 /// out-of-line slow case for operator==
204 bool EqualSlowCase(const APInt& RHS) const;
206 /// out-of-line slow case for operator==
207 bool EqualSlowCase(uint64_t Val) const;
209 /// out-of-line slow case for countLeadingZeros
210 unsigned countLeadingZerosSlowCase() const;
212 /// out-of-line slow case for countTrailingOnes
213 unsigned countTrailingOnesSlowCase() const;
215 /// out-of-line slow case for countPopulation
216 unsigned countPopulationSlowCase() const;
219 /// @name Constructors
221 /// If isSigned is true then val is treated as if it were a signed value
222 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
223 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
224 /// the range of val are zero filled).
225 /// @param numBits the bit width of the constructed APInt
226 /// @param val the initial value of the APInt
227 /// @param isSigned how to treat signedness of val
228 /// @brief Create a new APInt of numBits width, initialized as val.
229 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
230 : BitWidth(numBits), VAL(0) {
231 assert(BitWidth && "bitwidth too small");
235 initSlowCase(numBits, val, isSigned);
239 /// Note that bigVal.size() can be smaller or larger than the corresponding
240 /// bit width but any extraneous bits will be dropped.
241 /// @param numBits the bit width of the constructed APInt
242 /// @param bigVal a sequence of words to form the initial value of the APInt
243 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
244 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
245 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
246 /// deprecated because this constructor is prone to ambiguity with the
247 /// APInt(unsigned, uint64_t, bool) constructor.
249 /// If this overload is ever deleted, care should be taken to prevent calls
250 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
252 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
254 /// This constructor interprets the string \arg str in the given radix. The
255 /// interpretation stops when the first character that is not suitable for the
256 /// radix is encountered, or the end of the string. Acceptable radix values
257 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
258 /// string to require more bits than numBits.
260 /// @param numBits the bit width of the constructed APInt
261 /// @param str the string to be interpreted
262 /// @param radix the radix to use for the conversion
263 /// @brief Construct an APInt from a string representation.
264 APInt(unsigned numBits, StringRef str, uint8_t radix);
266 /// Simply makes *this a copy of that.
267 /// @brief Copy Constructor.
268 APInt(const APInt& that)
269 : BitWidth(that.BitWidth), VAL(0) {
270 assert(BitWidth && "bitwidth too small");
277 #if LLVM_USE_RVALUE_REFERENCES
278 /// @brief Move Constructor.
279 APInt(APInt&& that) : BitWidth(that.BitWidth), VAL(that.VAL) {
284 /// @brief Destructor.
290 /// Default constructor that creates an uninitialized APInt. This is useful
291 /// for object deserialization (pair this with the static method Read).
292 explicit APInt() : BitWidth(1) {}
294 /// Profile - Used to insert APInt objects, or objects that contain APInt
295 /// objects, into FoldingSets.
296 void Profile(FoldingSetNodeID& id) const;
299 /// @name Value Tests
301 /// This tests the high bit of this APInt to determine if it is set.
302 /// @returns true if this APInt is negative, false otherwise
303 /// @brief Determine sign of this APInt.
304 bool isNegative() const {
305 return (*this)[BitWidth - 1];
308 /// This tests the high bit of the APInt to determine if it is unset.
309 /// @brief Determine if this APInt Value is non-negative (>= 0)
310 bool isNonNegative() const {
311 return !isNegative();
314 /// This tests if the value of this APInt is positive (> 0). Note
315 /// that 0 is not a positive value.
316 /// @returns true if this APInt is positive.
317 /// @brief Determine if this APInt Value is positive.
318 bool isStrictlyPositive() const {
319 return isNonNegative() && !!*this;
322 /// This checks to see if the value has all bits of the APInt are set or not.
323 /// @brief Determine if all bits are set
324 bool isAllOnesValue() const {
325 return countPopulation() == BitWidth;
328 /// This checks to see if the value of this APInt is the maximum unsigned
329 /// value for the APInt's bit width.
330 /// @brief Determine if this is the largest unsigned value.
331 bool isMaxValue() const {
332 return countPopulation() == BitWidth;
335 /// This checks to see if the value of this APInt is the maximum signed
336 /// value for the APInt's bit width.
337 /// @brief Determine if this is the largest signed value.
338 bool isMaxSignedValue() const {
339 return BitWidth == 1 ? VAL == 0 :
340 !isNegative() && countPopulation() == BitWidth - 1;
343 /// This checks to see if the value of this APInt is the minimum unsigned
344 /// value for the APInt's bit width.
345 /// @brief Determine if this is the smallest unsigned value.
346 bool isMinValue() const {
350 /// This checks to see if the value of this APInt is the minimum signed
351 /// value for the APInt's bit width.
352 /// @brief Determine if this is the smallest signed value.
353 bool isMinSignedValue() const {
354 return BitWidth == 1 ? VAL == 1 : isNegative() && isPowerOf2();
357 /// @brief Check if this APInt has an N-bits unsigned integer value.
358 bool isIntN(unsigned N) const {
359 assert(N && "N == 0 ???");
360 if (N >= getBitWidth())
364 return isUIntN(N, VAL);
365 return APInt(N, makeArrayRef(pVal, getNumWords())).zext(getBitWidth())
369 /// @brief Check if this APInt has an N-bits signed integer value.
370 bool isSignedIntN(unsigned N) const {
371 assert(N && "N == 0 ???");
372 return getMinSignedBits() <= N;
375 /// @returns true if the argument APInt value is a power of two > 0.
376 bool isPowerOf2() const {
378 return isPowerOf2_64(VAL);
379 return countPopulationSlowCase() == 1;
382 /// isSignBit - Return true if this is the value returned by getSignBit.
383 bool isSignBit() const { return isMinSignedValue(); }
385 /// This converts the APInt to a boolean value as a test against zero.
386 /// @brief Boolean conversion function.
387 bool getBoolValue() const {
391 /// getLimitedValue - If this value is smaller than the specified limit,
392 /// return it, otherwise return the limit value. This causes the value
393 /// to saturate to the limit.
394 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
395 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
396 Limit : getZExtValue();
400 /// @name Value Generators
402 /// @brief Gets maximum unsigned value of APInt for specific bit width.
403 static APInt getMaxValue(unsigned numBits) {
404 return getAllOnesValue(numBits);
407 /// @brief Gets maximum signed value of APInt for a specific bit width.
408 static APInt getSignedMaxValue(unsigned numBits) {
409 APInt API = getAllOnesValue(numBits);
410 API.clearBit(numBits - 1);
414 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
415 static APInt getMinValue(unsigned numBits) {
416 return APInt(numBits, 0);
419 /// @brief Gets minimum signed value of APInt for a specific bit width.
420 static APInt getSignedMinValue(unsigned numBits) {
421 APInt API(numBits, 0);
422 API.setBit(numBits - 1);
426 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
427 /// it helps code readability when we want to get a SignBit.
428 /// @brief Get the SignBit for a specific bit width.
429 static APInt getSignBit(unsigned BitWidth) {
430 return getSignedMinValue(BitWidth);
433 /// @returns the all-ones value for an APInt of the specified bit-width.
434 /// @brief Get the all-ones value.
435 static APInt getAllOnesValue(unsigned numBits) {
436 return APInt(numBits, -1ULL, true);
439 /// @returns the '0' value for an APInt of the specified bit-width.
440 /// @brief Get the '0' value.
441 static APInt getNullValue(unsigned numBits) {
442 return APInt(numBits, 0);
445 /// Get an APInt with the same BitWidth as this APInt, just zero mask
446 /// the low bits and right shift to the least significant bit.
447 /// @returns the high "numBits" bits of this APInt.
448 APInt getHiBits(unsigned numBits) const;
450 /// Get an APInt with the same BitWidth as this APInt, just zero mask
452 /// @returns the low "numBits" bits of this APInt.
453 APInt getLoBits(unsigned numBits) const;
455 /// getOneBitSet - Return an APInt with exactly one bit set in the result.
456 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
457 APInt Res(numBits, 0);
462 /// Constructs an APInt value that has a contiguous range of bits set. The
463 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
464 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
465 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
466 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
467 /// @param numBits the intended bit width of the result
468 /// @param loBit the index of the lowest bit set.
469 /// @param hiBit the index of the highest bit set.
470 /// @returns An APInt value with the requested bits set.
471 /// @brief Get a value with a block of bits set.
472 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
473 assert(hiBit <= numBits && "hiBit out of range");
474 assert(loBit < numBits && "loBit out of range");
476 return getLowBitsSet(numBits, hiBit) |
477 getHighBitsSet(numBits, numBits-loBit);
478 return getLowBitsSet(numBits, hiBit-loBit).shl(loBit);
481 /// Constructs an APInt value that has the top hiBitsSet bits set.
482 /// @param numBits the bitwidth of the result
483 /// @param hiBitsSet the number of high-order bits set in the result.
484 /// @brief Get a value with high bits set
485 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
486 assert(hiBitsSet <= numBits && "Too many bits to set!");
487 // Handle a degenerate case, to avoid shifting by word size
489 return APInt(numBits, 0);
490 unsigned shiftAmt = numBits - hiBitsSet;
491 // For small values, return quickly
492 if (numBits <= APINT_BITS_PER_WORD)
493 return APInt(numBits, ~0ULL << shiftAmt);
494 return getAllOnesValue(numBits).shl(shiftAmt);
497 /// Constructs an APInt value that has the bottom loBitsSet bits set.
498 /// @param numBits the bitwidth of the result
499 /// @param loBitsSet the number of low-order bits set in the result.
500 /// @brief Get a value with low bits set
501 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
502 assert(loBitsSet <= numBits && "Too many bits to set!");
503 // Handle a degenerate case, to avoid shifting by word size
505 return APInt(numBits, 0);
506 if (loBitsSet == APINT_BITS_PER_WORD)
507 return APInt(numBits, -1ULL);
508 // For small values, return quickly.
509 if (loBitsSet <= APINT_BITS_PER_WORD)
510 return APInt(numBits, -1ULL >> (APINT_BITS_PER_WORD - loBitsSet));
511 return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
514 /// \brief Determine if two APInts have the same value, after zero-extending
515 /// one of them (if needed!) to ensure that the bit-widths match.
516 static bool isSameValue(const APInt &I1, const APInt &I2) {
517 if (I1.getBitWidth() == I2.getBitWidth())
520 if (I1.getBitWidth() > I2.getBitWidth())
521 return I1 == I2.zext(I1.getBitWidth());
523 return I1.zext(I2.getBitWidth()) == I2;
526 /// \brief Overload to compute a hash_code for an APInt value.
527 friend hash_code hash_value(const APInt &Arg);
529 /// This function returns a pointer to the internal storage of the APInt.
530 /// This is useful for writing out the APInt in binary form without any
532 const uint64_t* getRawData() const {
539 /// @name Unary Operators
541 /// @returns a new APInt value representing *this incremented by one
542 /// @brief Postfix increment operator.
543 const APInt operator++(int) {
549 /// @returns *this incremented by one
550 /// @brief Prefix increment operator.
553 /// @returns a new APInt representing *this decremented by one.
554 /// @brief Postfix decrement operator.
555 const APInt operator--(int) {
561 /// @returns *this decremented by one.
562 /// @brief Prefix decrement operator.
565 /// Performs a bitwise complement operation on this APInt.
566 /// @returns an APInt that is the bitwise complement of *this
567 /// @brief Unary bitwise complement operator.
568 APInt operator~() const {
570 Result.flipAllBits();
574 /// Negates *this using two's complement logic.
575 /// @returns An APInt value representing the negation of *this.
576 /// @brief Unary negation operator
577 APInt operator-() const {
578 return APInt(BitWidth, 0) - (*this);
581 /// Performs logical negation operation on this APInt.
582 /// @returns true if *this is zero, false otherwise.
583 /// @brief Logical negation operator.
584 bool operator!() const {
588 for (unsigned i = 0; i != getNumWords(); ++i)
595 /// @name Assignment Operators
597 /// @returns *this after assignment of RHS.
598 /// @brief Copy assignment operator.
599 APInt& operator=(const APInt& RHS) {
600 // If the bitwidths are the same, we can avoid mucking with memory
601 if (isSingleWord() && RHS.isSingleWord()) {
603 BitWidth = RHS.BitWidth;
604 return clearUnusedBits();
607 return AssignSlowCase(RHS);
610 #if LLVM_USE_RVALUE_REFERENCES
611 /// @brief Move assignment operator.
612 APInt& operator=(APInt&& that) {
616 BitWidth = that.BitWidth;
625 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
626 /// the bit width, the excess bits are truncated. If the bit width is larger
627 /// than 64, the value is zero filled in the unspecified high order bits.
628 /// @returns *this after assignment of RHS value.
629 /// @brief Assignment operator.
630 APInt& operator=(uint64_t RHS);
632 /// Performs a bitwise AND operation on this APInt and RHS. The result is
633 /// assigned to *this.
634 /// @returns *this after ANDing with RHS.
635 /// @brief Bitwise AND assignment operator.
636 APInt& operator&=(const APInt& RHS);
638 /// Performs a bitwise OR operation on this APInt and RHS. The result is
640 /// @returns *this after ORing with RHS.
641 /// @brief Bitwise OR assignment operator.
642 APInt& operator|=(const APInt& RHS);
644 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
645 /// logically zero-extended or truncated to match the bit-width of
648 /// @brief Bitwise OR assignment operator.
649 APInt& operator|=(uint64_t RHS) {
650 if (isSingleWord()) {
659 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
660 /// assigned to *this.
661 /// @returns *this after XORing with RHS.
662 /// @brief Bitwise XOR assignment operator.
663 APInt& operator^=(const APInt& RHS);
665 /// Multiplies this APInt by RHS and assigns the result to *this.
667 /// @brief Multiplication assignment operator.
668 APInt& operator*=(const APInt& RHS);
670 /// Adds RHS to *this and assigns the result to *this.
672 /// @brief Addition assignment operator.
673 APInt& operator+=(const APInt& RHS);
675 /// Subtracts RHS from *this and assigns the result to *this.
677 /// @brief Subtraction assignment operator.
678 APInt& operator-=(const APInt& RHS);
680 /// Shifts *this left by shiftAmt and assigns the result to *this.
681 /// @returns *this after shifting left by shiftAmt
682 /// @brief Left-shift assignment function.
683 APInt& operator<<=(unsigned shiftAmt) {
684 *this = shl(shiftAmt);
689 /// @name Binary Operators
691 /// Performs a bitwise AND operation on *this and RHS.
692 /// @returns An APInt value representing the bitwise AND of *this and RHS.
693 /// @brief Bitwise AND operator.
694 APInt operator&(const APInt& RHS) const {
695 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
697 return APInt(getBitWidth(), VAL & RHS.VAL);
698 return AndSlowCase(RHS);
700 APInt And(const APInt& RHS) const {
701 return this->operator&(RHS);
704 /// Performs a bitwise OR operation on *this and RHS.
705 /// @returns An APInt value representing the bitwise OR of *this and RHS.
706 /// @brief Bitwise OR operator.
707 APInt operator|(const APInt& RHS) const {
708 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
710 return APInt(getBitWidth(), VAL | RHS.VAL);
711 return OrSlowCase(RHS);
713 APInt Or(const APInt& RHS) const {
714 return this->operator|(RHS);
717 /// Performs a bitwise XOR operation on *this and RHS.
718 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
719 /// @brief Bitwise XOR operator.
720 APInt operator^(const APInt& RHS) const {
721 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
723 return APInt(BitWidth, VAL ^ RHS.VAL);
724 return XorSlowCase(RHS);
726 APInt Xor(const APInt& RHS) const {
727 return this->operator^(RHS);
730 /// Multiplies this APInt by RHS and returns the result.
731 /// @brief Multiplication operator.
732 APInt operator*(const APInt& RHS) const;
734 /// Adds RHS to this APInt and returns the result.
735 /// @brief Addition operator.
736 APInt operator+(const APInt& RHS) const;
737 APInt operator+(uint64_t RHS) const {
738 return (*this) + APInt(BitWidth, RHS);
741 /// Subtracts RHS from this APInt and returns the result.
742 /// @brief Subtraction operator.
743 APInt operator-(const APInt& RHS) const;
744 APInt operator-(uint64_t RHS) const {
745 return (*this) - APInt(BitWidth, RHS);
748 APInt operator<<(unsigned Bits) const {
752 APInt operator<<(const APInt &Bits) const {
756 /// Arithmetic right-shift this APInt by shiftAmt.
757 /// @brief Arithmetic right-shift function.
758 APInt ashr(unsigned shiftAmt) const;
760 /// Logical right-shift this APInt by shiftAmt.
761 /// @brief Logical right-shift function.
762 APInt lshr(unsigned shiftAmt) const;
764 /// Left-shift this APInt by shiftAmt.
765 /// @brief Left-shift function.
766 APInt shl(unsigned shiftAmt) const {
767 assert(shiftAmt <= BitWidth && "Invalid shift amount");
768 if (isSingleWord()) {
769 if (shiftAmt == BitWidth)
770 return APInt(BitWidth, 0); // avoid undefined shift results
771 return APInt(BitWidth, VAL << shiftAmt);
773 return shlSlowCase(shiftAmt);
776 /// @brief Rotate left by rotateAmt.
777 APInt rotl(unsigned rotateAmt) const;
779 /// @brief Rotate right by rotateAmt.
780 APInt rotr(unsigned rotateAmt) const;
782 /// Arithmetic right-shift this APInt by shiftAmt.
783 /// @brief Arithmetic right-shift function.
784 APInt ashr(const APInt &shiftAmt) const;
786 /// Logical right-shift this APInt by shiftAmt.
787 /// @brief Logical right-shift function.
788 APInt lshr(const APInt &shiftAmt) const;
790 /// Left-shift this APInt by shiftAmt.
791 /// @brief Left-shift function.
792 APInt shl(const APInt &shiftAmt) const;
794 /// @brief Rotate left by rotateAmt.
795 APInt rotl(const APInt &rotateAmt) const;
797 /// @brief Rotate right by rotateAmt.
798 APInt rotr(const APInt &rotateAmt) const;
800 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
801 /// RHS are treated as unsigned quantities for purposes of this division.
802 /// @returns a new APInt value containing the division result
803 /// @brief Unsigned division operation.
804 APInt udiv(const APInt &RHS) const;
806 /// Signed divide this APInt by APInt RHS.
807 /// @brief Signed division function for APInt.
808 APInt sdiv(const APInt &RHS) const {
810 if (RHS.isNegative())
811 return (-(*this)).udiv(-RHS);
813 return -((-(*this)).udiv(RHS));
814 else if (RHS.isNegative())
815 return -(this->udiv(-RHS));
816 return this->udiv(RHS);
819 /// Perform an unsigned remainder operation on this APInt with RHS being the
820 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
821 /// of this operation. Note that this is a true remainder operation and not
822 /// a modulo operation because the sign follows the sign of the dividend
824 /// @returns a new APInt value containing the remainder result
825 /// @brief Unsigned remainder operation.
826 APInt urem(const APInt &RHS) const;
828 /// Signed remainder operation on APInt.
829 /// @brief Function for signed remainder operation.
830 APInt srem(const APInt &RHS) const {
832 if (RHS.isNegative())
833 return -((-(*this)).urem(-RHS));
835 return -((-(*this)).urem(RHS));
836 else if (RHS.isNegative())
837 return this->urem(-RHS);
838 return this->urem(RHS);
841 /// Sometimes it is convenient to divide two APInt values and obtain both the
842 /// quotient and remainder. This function does both operations in the same
843 /// computation making it a little more efficient. The pair of input arguments
844 /// may overlap with the pair of output arguments. It is safe to call
845 /// udivrem(X, Y, X, Y), for example.
846 /// @brief Dual division/remainder interface.
847 static void udivrem(const APInt &LHS, const APInt &RHS,
848 APInt &Quotient, APInt &Remainder);
850 static void sdivrem(const APInt &LHS, const APInt &RHS,
851 APInt &Quotient, APInt &Remainder) {
852 if (LHS.isNegative()) {
853 if (RHS.isNegative())
854 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
856 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
857 Quotient = -Quotient;
859 Remainder = -Remainder;
860 } else if (RHS.isNegative()) {
861 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
862 Quotient = -Quotient;
864 APInt::udivrem(LHS, RHS, Quotient, Remainder);
869 // Operations that return overflow indicators.
870 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
871 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
872 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
873 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
874 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
875 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
876 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
877 APInt sshl_ov(unsigned Amt, bool &Overflow) const;
879 /// @returns the bit value at bitPosition
880 /// @brief Array-indexing support.
881 bool operator[](unsigned bitPosition) const {
882 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
883 return (maskBit(bitPosition) &
884 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
888 /// @name Comparison Operators
890 /// Compares this APInt with RHS for the validity of the equality
892 /// @brief Equality operator.
893 bool operator==(const APInt& RHS) const {
894 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
896 return VAL == RHS.VAL;
897 return EqualSlowCase(RHS);
900 /// Compares this APInt with a uint64_t for the validity of the equality
902 /// @returns true if *this == Val
903 /// @brief Equality operator.
904 bool operator==(uint64_t Val) const {
907 return EqualSlowCase(Val);
910 /// Compares this APInt with RHS for the validity of the equality
912 /// @returns true if *this == Val
913 /// @brief Equality comparison.
914 bool eq(const APInt &RHS) const {
915 return (*this) == RHS;
918 /// Compares this APInt with RHS for the validity of the inequality
920 /// @returns true if *this != Val
921 /// @brief Inequality operator.
922 bool operator!=(const APInt& RHS) const {
923 return !((*this) == RHS);
926 /// Compares this APInt with a uint64_t for the validity of the inequality
928 /// @returns true if *this != Val
929 /// @brief Inequality operator.
930 bool operator!=(uint64_t Val) const {
931 return !((*this) == Val);
934 /// Compares this APInt with RHS for the validity of the inequality
936 /// @returns true if *this != Val
937 /// @brief Inequality comparison
938 bool ne(const APInt &RHS) const {
939 return !((*this) == RHS);
942 /// Regards both *this and RHS as unsigned quantities and compares them for
943 /// the validity of the less-than relationship.
944 /// @returns true if *this < RHS when both are considered unsigned.
945 /// @brief Unsigned less than comparison
946 bool ult(const APInt &RHS) const;
948 /// Regards both *this as an unsigned quantity and compares it with RHS for
949 /// the validity of the less-than relationship.
950 /// @returns true if *this < RHS when considered unsigned.
951 /// @brief Unsigned less than comparison
952 bool ult(uint64_t RHS) const {
953 return ult(APInt(getBitWidth(), RHS));
956 /// Regards both *this and RHS as signed quantities and compares them for
957 /// validity of the less-than relationship.
958 /// @returns true if *this < RHS when both are considered signed.
959 /// @brief Signed less than comparison
960 bool slt(const APInt& RHS) const;
962 /// Regards both *this as a signed quantity and compares it with RHS for
963 /// the validity of the less-than relationship.
964 /// @returns true if *this < RHS when considered signed.
965 /// @brief Signed less than comparison
966 bool slt(uint64_t RHS) const {
967 return slt(APInt(getBitWidth(), RHS));
970 /// Regards both *this and RHS as unsigned quantities and compares them for
971 /// validity of the less-or-equal relationship.
972 /// @returns true if *this <= RHS when both are considered unsigned.
973 /// @brief Unsigned less or equal comparison
974 bool ule(const APInt& RHS) const {
975 return ult(RHS) || eq(RHS);
978 /// Regards both *this as an unsigned quantity and compares it with RHS for
979 /// the validity of the less-or-equal relationship.
980 /// @returns true if *this <= RHS when considered unsigned.
981 /// @brief Unsigned less or equal comparison
982 bool ule(uint64_t RHS) const {
983 return ule(APInt(getBitWidth(), RHS));
986 /// Regards both *this and RHS as signed quantities and compares them for
987 /// validity of the less-or-equal relationship.
988 /// @returns true if *this <= RHS when both are considered signed.
989 /// @brief Signed less or equal comparison
990 bool sle(const APInt& RHS) const {
991 return slt(RHS) || eq(RHS);
994 /// Regards both *this as a signed quantity and compares it with RHS for
995 /// the validity of the less-or-equal relationship.
996 /// @returns true if *this <= RHS when considered signed.
997 /// @brief Signed less or equal comparison
998 bool sle(uint64_t RHS) const {
999 return sle(APInt(getBitWidth(), RHS));
1002 /// Regards both *this and RHS as unsigned quantities and compares them for
1003 /// the validity of the greater-than relationship.
1004 /// @returns true if *this > RHS when both are considered unsigned.
1005 /// @brief Unsigned greather than comparison
1006 bool ugt(const APInt& RHS) const {
1007 return !ult(RHS) && !eq(RHS);
1010 /// Regards both *this as an unsigned quantity and compares it with RHS for
1011 /// the validity of the greater-than relationship.
1012 /// @returns true if *this > RHS when considered unsigned.
1013 /// @brief Unsigned greater than comparison
1014 bool ugt(uint64_t RHS) const {
1015 return ugt(APInt(getBitWidth(), RHS));
1018 /// Regards both *this and RHS as signed quantities and compares them for
1019 /// the validity of the greater-than relationship.
1020 /// @returns true if *this > RHS when both are considered signed.
1021 /// @brief Signed greather than comparison
1022 bool sgt(const APInt& RHS) const {
1023 return !slt(RHS) && !eq(RHS);
1026 /// Regards both *this as a signed quantity and compares it with RHS for
1027 /// the validity of the greater-than relationship.
1028 /// @returns true if *this > RHS when considered signed.
1029 /// @brief Signed greater than comparison
1030 bool sgt(uint64_t RHS) const {
1031 return sgt(APInt(getBitWidth(), RHS));
1034 /// Regards both *this and RHS as unsigned quantities and compares them for
1035 /// validity of the greater-or-equal relationship.
1036 /// @returns true if *this >= RHS when both are considered unsigned.
1037 /// @brief Unsigned greater or equal comparison
1038 bool uge(const APInt& RHS) const {
1042 /// Regards both *this as an unsigned quantity and compares it with RHS for
1043 /// the validity of the greater-or-equal relationship.
1044 /// @returns true if *this >= RHS when considered unsigned.
1045 /// @brief Unsigned greater or equal comparison
1046 bool uge(uint64_t RHS) const {
1047 return uge(APInt(getBitWidth(), RHS));
1050 /// Regards both *this and RHS as signed quantities and compares them for
1051 /// validity of the greater-or-equal relationship.
1052 /// @returns true if *this >= RHS when both are considered signed.
1053 /// @brief Signed greather or equal comparison
1054 bool sge(const APInt& RHS) const {
1058 /// Regards both *this as a signed quantity and compares it with RHS for
1059 /// the validity of the greater-or-equal relationship.
1060 /// @returns true if *this >= RHS when considered signed.
1061 /// @brief Signed greater or equal comparison
1062 bool sge(uint64_t RHS) const {
1063 return sge(APInt(getBitWidth(), RHS));
1069 /// This operation tests if there are any pairs of corresponding bits
1070 /// between this APInt and RHS that are both set.
1071 bool intersects(const APInt &RHS) const {
1072 return (*this & RHS) != 0;
1076 /// @name Resizing Operators
1078 /// Truncate the APInt to a specified width. It is an error to specify a width
1079 /// that is greater than or equal to the current width.
1080 /// @brief Truncate to new width.
1081 APInt trunc(unsigned width) const;
1083 /// This operation sign extends the APInt to a new width. If the high order
1084 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1085 /// It is an error to specify a width that is less than or equal to the
1087 /// @brief Sign extend to a new width.
1088 APInt sext(unsigned width) const;
1090 /// This operation zero extends the APInt to a new width. The high order bits
1091 /// are filled with 0 bits. It is an error to specify a width that is less
1092 /// than or equal to the current width.
1093 /// @brief Zero extend to a new width.
1094 APInt zext(unsigned width) const;
1096 /// Make this APInt have the bit width given by \p width. The value is sign
1097 /// extended, truncated, or left alone to make it that width.
1098 /// @brief Sign extend or truncate to width
1099 APInt sextOrTrunc(unsigned width) const;
1101 /// Make this APInt have the bit width given by \p width. The value is zero
1102 /// extended, truncated, or left alone to make it that width.
1103 /// @brief Zero extend or truncate to width
1104 APInt zextOrTrunc(unsigned width) const;
1106 /// Make this APInt have the bit width given by \p width. The value is sign
1107 /// extended, or left alone to make it that width.
1108 /// @brief Sign extend or truncate to width
1109 APInt sextOrSelf(unsigned width) const;
1111 /// Make this APInt have the bit width given by \p width. The value is zero
1112 /// extended, or left alone to make it that width.
1113 /// @brief Zero extend or truncate to width
1114 APInt zextOrSelf(unsigned width) const;
1117 /// @name Bit Manipulation Operators
1119 /// @brief Set every bit to 1.
1124 // Set all the bits in all the words.
1125 for (unsigned i = 0; i < getNumWords(); ++i)
1128 // Clear the unused ones
1132 /// Set the given bit to 1 whose position is given as "bitPosition".
1133 /// @brief Set a given bit to 1.
1134 void setBit(unsigned bitPosition);
1136 /// @brief Set every bit to 0.
1137 void clearAllBits() {
1141 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
1144 /// Set the given bit to 0 whose position is given as "bitPosition".
1145 /// @brief Set a given bit to 0.
1146 void clearBit(unsigned bitPosition);
1148 /// @brief Toggle every bit to its opposite value.
1149 void flipAllBits() {
1153 for (unsigned i = 0; i < getNumWords(); ++i)
1159 /// Toggle a given bit to its opposite value whose position is given
1160 /// as "bitPosition".
1161 /// @brief Toggles a given bit to its opposite value.
1162 void flipBit(unsigned bitPosition);
1165 /// @name Value Characterization Functions
1168 /// @returns the total number of bits.
1169 unsigned getBitWidth() const {
1173 /// Here one word's bitwidth equals to that of uint64_t.
1174 /// @returns the number of words to hold the integer value of this APInt.
1175 /// @brief Get the number of words.
1176 unsigned getNumWords() const {
1177 return getNumWords(BitWidth);
1180 /// Here one word's bitwidth equals to that of uint64_t.
1181 /// @returns the number of words to hold the integer value with a
1182 /// given bit width.
1183 /// @brief Get the number of words.
1184 static unsigned getNumWords(unsigned BitWidth) {
1185 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1188 /// This function returns the number of active bits which is defined as the
1189 /// bit width minus the number of leading zeros. This is used in several
1190 /// computations to see how "wide" the value is.
1191 /// @brief Compute the number of active bits in the value
1192 unsigned getActiveBits() const {
1193 return BitWidth - countLeadingZeros();
1196 /// This function returns the number of active words in the value of this
1197 /// APInt. This is used in conjunction with getActiveData to extract the raw
1198 /// value of the APInt.
1199 unsigned getActiveWords() const {
1200 return whichWord(getActiveBits()-1) + 1;
1203 /// Computes the minimum bit width for this APInt while considering it to be
1204 /// a signed (and probably negative) value. If the value is not negative,
1205 /// this function returns the same value as getActiveBits()+1. Otherwise, it
1206 /// returns the smallest bit width that will retain the negative value. For
1207 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1208 /// for -1, this function will always return 1.
1209 /// @brief Get the minimum bit size for this signed APInt
1210 unsigned getMinSignedBits() const {
1212 return BitWidth - countLeadingOnes() + 1;
1213 return getActiveBits()+1;
1216 /// This method attempts to return the value of this APInt as a zero extended
1217 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1218 /// uint64_t. Otherwise an assertion will result.
1219 /// @brief Get zero extended value
1220 uint64_t getZExtValue() const {
1223 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1227 /// This method attempts to return the value of this APInt as a sign extended
1228 /// int64_t. The bit width must be <= 64 or the value must fit within an
1229 /// int64_t. Otherwise an assertion will result.
1230 /// @brief Get sign extended value
1231 int64_t getSExtValue() const {
1233 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
1234 (APINT_BITS_PER_WORD - BitWidth);
1235 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1236 return int64_t(pVal[0]);
1239 /// This method determines how many bits are required to hold the APInt
1240 /// equivalent of the string given by \arg str.
1241 /// @brief Get bits required for string value.
1242 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1244 /// countLeadingZeros - This function is an APInt version of the
1245 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
1246 /// of zeros from the most significant bit to the first one bit.
1247 /// @returns BitWidth if the value is zero.
1248 /// @returns the number of zeros from the most significant bit to the first
1250 unsigned countLeadingZeros() const {
1251 if (isSingleWord()) {
1252 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1253 return CountLeadingZeros_64(VAL) - unusedBits;
1255 return countLeadingZerosSlowCase();
1258 /// countLeadingOnes - This function is an APInt version of the
1259 /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number
1260 /// of ones from the most significant bit to the first zero bit.
1261 /// @returns 0 if the high order bit is not set
1262 /// @returns the number of 1 bits from the most significant to the least
1263 /// @brief Count the number of leading one bits.
1264 unsigned countLeadingOnes() const;
1266 /// Computes the number of leading bits of this APInt that are equal to its
1268 unsigned getNumSignBits() const {
1269 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1272 /// countTrailingZeros - This function is an APInt version of the
1273 /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
1274 /// the number of zeros from the least significant bit to the first set bit.
1275 /// @returns BitWidth if the value is zero.
1276 /// @returns the number of zeros from the least significant bit to the first
1278 /// @brief Count the number of trailing zero bits.
1279 unsigned countTrailingZeros() const;
1281 /// countTrailingOnes - This function is an APInt version of the
1282 /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
1283 /// the number of ones from the least significant bit to the first zero bit.
1284 /// @returns BitWidth if the value is all ones.
1285 /// @returns the number of ones from the least significant bit to the first
1287 /// @brief Count the number of trailing one bits.
1288 unsigned countTrailingOnes() const {
1290 return CountTrailingOnes_64(VAL);
1291 return countTrailingOnesSlowCase();
1294 /// countPopulation - This function is an APInt version of the
1295 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
1296 /// of 1 bits in the APInt value.
1297 /// @returns 0 if the value is zero.
1298 /// @returns the number of set bits.
1299 /// @brief Count the number of bits set.
1300 unsigned countPopulation() const {
1302 return CountPopulation_64(VAL);
1303 return countPopulationSlowCase();
1307 /// @name Conversion Functions
1309 void print(raw_ostream &OS, bool isSigned) const;
1311 /// toString - Converts an APInt to a string and append it to Str. Str is
1312 /// commonly a SmallString.
1313 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1314 bool formatAsCLiteral = false) const;
1316 /// Considers the APInt to be unsigned and converts it into a string in the
1317 /// radix given. The radix can be 2, 8, 10 16, or 36.
1318 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1319 toString(Str, Radix, false, false);
1322 /// Considers the APInt to be signed and converts it into a string in the
1323 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1324 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1325 toString(Str, Radix, true, false);
1328 /// toString - This returns the APInt as a std::string. Note that this is an
1329 /// inefficient method. It is better to pass in a SmallVector/SmallString
1330 /// to the methods above to avoid thrashing the heap for the string.
1331 std::string toString(unsigned Radix, bool Signed) const;
1334 /// @returns a byte-swapped representation of this APInt Value.
1335 APInt byteSwap() const;
1337 /// @brief Converts this APInt to a double value.
1338 double roundToDouble(bool isSigned) const;
1340 /// @brief Converts this unsigned APInt to a double value.
1341 double roundToDouble() const {
1342 return roundToDouble(false);
1345 /// @brief Converts this signed APInt to a double value.
1346 double signedRoundToDouble() const {
1347 return roundToDouble(true);
1350 /// The conversion does not do a translation from integer to double, it just
1351 /// re-interprets the bits as a double. Note that it is valid to do this on
1352 /// any bit width. Exactly 64 bits will be translated.
1353 /// @brief Converts APInt bits to a double
1354 double bitsToDouble() const {
1359 T.I = (isSingleWord() ? VAL : pVal[0]);
1363 /// The conversion does not do a translation from integer to float, it just
1364 /// re-interprets the bits as a float. Note that it is valid to do this on
1365 /// any bit width. Exactly 32 bits will be translated.
1366 /// @brief Converts APInt bits to a double
1367 float bitsToFloat() const {
1372 T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1376 /// The conversion does not do a translation from double to integer, it just
1377 /// re-interprets the bits of the double.
1378 /// @brief Converts a double to APInt bits.
1379 static APInt doubleToBits(double V) {
1385 return APInt(sizeof T * CHAR_BIT, T.I);
1388 /// The conversion does not do a translation from float to integer, it just
1389 /// re-interprets the bits of the float.
1390 /// @brief Converts a float to APInt bits.
1391 static APInt floatToBits(float V) {
1397 return APInt(sizeof T * CHAR_BIT, T.I);
1401 /// @name Mathematics Operations
1404 /// @returns the floor log base 2 of this APInt.
1405 unsigned logBase2() const {
1406 return BitWidth - 1 - countLeadingZeros();
1409 /// @returns the ceil log base 2 of this APInt.
1410 unsigned ceilLogBase2() const {
1411 return BitWidth - (*this - 1).countLeadingZeros();
1414 /// @returns the log base 2 of this APInt if its an exact power of two, -1
1416 int32_t exactLogBase2() const {
1422 /// @brief Compute the square root
1425 /// If *this is < 0 then return -(*this), otherwise *this;
1426 /// @brief Get the absolute value;
1433 /// @returns the multiplicative inverse for a given modulo.
1434 APInt multiplicativeInverse(const APInt& modulo) const;
1437 /// @name Support for division by constant
1440 /// Calculate the magic number for signed division by a constant.
1444 /// Calculate the magic number for unsigned division by a constant.
1446 mu magicu(unsigned LeadingZeros = 0) const;
1449 /// @name Building-block Operations for APInt and APFloat
1452 // These building block operations operate on a representation of
1453 // arbitrary precision, two's-complement, bignum integer values.
1454 // They should be sufficient to implement APInt and APFloat bignum
1455 // requirements. Inputs are generally a pointer to the base of an
1456 // array of integer parts, representing an unsigned bignum, and a
1457 // count of how many parts there are.
1459 /// Sets the least significant part of a bignum to the input value,
1460 /// and zeroes out higher parts. */
1461 static void tcSet(integerPart *, integerPart, unsigned int);
1463 /// Assign one bignum to another.
1464 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1466 /// Returns true if a bignum is zero, false otherwise.
1467 static bool tcIsZero(const integerPart *, unsigned int);
1469 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1470 static int tcExtractBit(const integerPart *, unsigned int bit);
1472 /// Copy the bit vector of width srcBITS from SRC, starting at bit
1473 /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
1474 /// becomes the least significant bit of DST. All high bits above
1475 /// srcBITS in DST are zero-filled.
1476 static void tcExtract(integerPart *, unsigned int dstCount,
1477 const integerPart *,
1478 unsigned int srcBits, unsigned int srcLSB);
1480 /// Set the given bit of a bignum. Zero-based.
1481 static void tcSetBit(integerPart *, unsigned int bit);
1483 /// Clear the given bit of a bignum. Zero-based.
1484 static void tcClearBit(integerPart *, unsigned int bit);
1486 /// Returns the bit number of the least or most significant set bit
1487 /// of a number. If the input number has no bits set -1U is
1489 static unsigned int tcLSB(const integerPart *, unsigned int);
1490 static unsigned int tcMSB(const integerPart *parts, unsigned int n);
1492 /// Negate a bignum in-place.
1493 static void tcNegate(integerPart *, unsigned int);
1495 /// DST += RHS + CARRY where CARRY is zero or one. Returns the
1497 static integerPart tcAdd(integerPart *, const integerPart *,
1498 integerPart carry, unsigned);
1500 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the
1502 static integerPart tcSubtract(integerPart *, const integerPart *,
1503 integerPart carry, unsigned);
1505 /// DST += SRC * MULTIPLIER + PART if add is true
1506 /// DST = SRC * MULTIPLIER + PART if add is false
1508 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
1509 /// they must start at the same point, i.e. DST == SRC.
1511 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1512 /// returned. Otherwise DST is filled with the least significant
1513 /// DSTPARTS parts of the result, and if all of the omitted higher
1514 /// parts were zero return zero, otherwise overflow occurred and
1516 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1517 integerPart multiplier, integerPart carry,
1518 unsigned int srcParts, unsigned int dstParts,
1521 /// DST = LHS * RHS, where DST has the same width as the operands
1522 /// and is filled with the least significant parts of the result.
1523 /// Returns one if overflow occurred, otherwise zero. DST must be
1524 /// disjoint from both operands.
1525 static int tcMultiply(integerPart *, const integerPart *,
1526 const integerPart *, unsigned);
1528 /// DST = LHS * RHS, where DST has width the sum of the widths of
1529 /// the operands. No overflow occurs. DST must be disjoint from
1530 /// both operands. Returns the number of parts required to hold the
1532 static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1533 const integerPart *, unsigned, unsigned);
1535 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1536 /// Otherwise set LHS to LHS / RHS with the fractional part
1537 /// discarded, set REMAINDER to the remainder, return zero. i.e.
1539 /// OLD_LHS = RHS * LHS + REMAINDER
1541 /// SCRATCH is a bignum of the same size as the operands and result
1542 /// for use by the routine; its contents need not be initialized
1543 /// and are destroyed. LHS, REMAINDER and SCRATCH must be
1545 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1546 integerPart *remainder, integerPart *scratch,
1547 unsigned int parts);
1549 /// Shift a bignum left COUNT bits. Shifted in bits are zero.
1550 /// There are no restrictions on COUNT.
1551 static void tcShiftLeft(integerPart *, unsigned int parts,
1552 unsigned int count);
1554 /// Shift a bignum right COUNT bits. Shifted in bits are zero.
1555 /// There are no restrictions on COUNT.
1556 static void tcShiftRight(integerPart *, unsigned int parts,
1557 unsigned int count);
1559 /// The obvious AND, OR and XOR and complement operations.
1560 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1561 static void tcOr(integerPart *, const integerPart *, unsigned int);
1562 static void tcXor(integerPart *, const integerPart *, unsigned int);
1563 static void tcComplement(integerPart *, unsigned int);
1565 /// Comparison (unsigned) of two bignums.
1566 static int tcCompare(const integerPart *, const integerPart *,
1569 /// Increment a bignum in-place. Return the carry flag.
1570 static integerPart tcIncrement(integerPart *, unsigned int);
1572 /// Set the least significant BITS and clear the rest.
1573 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1576 /// @brief debug method
1582 /// Magic data for optimising signed division by a constant.
1584 APInt m; ///< magic number
1585 unsigned s; ///< shift amount
1588 /// Magic data for optimising unsigned division by a constant.
1590 APInt m; ///< magic number
1591 bool a; ///< add indicator
1592 unsigned s; ///< shift amount
1595 inline bool operator==(uint64_t V1, const APInt& V2) {
1599 inline bool operator!=(uint64_t V1, const APInt& V2) {
1603 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1608 namespace APIntOps {
1610 /// @brief Determine the smaller of two APInts considered to be signed.
1611 inline APInt smin(const APInt &A, const APInt &B) {
1612 return A.slt(B) ? A : B;
1615 /// @brief Determine the larger of two APInts considered to be signed.
1616 inline APInt smax(const APInt &A, const APInt &B) {
1617 return A.sgt(B) ? A : B;
1620 /// @brief Determine the smaller of two APInts considered to be signed.
1621 inline APInt umin(const APInt &A, const APInt &B) {
1622 return A.ult(B) ? A : B;
1625 /// @brief Determine the larger of two APInts considered to be unsigned.
1626 inline APInt umax(const APInt &A, const APInt &B) {
1627 return A.ugt(B) ? A : B;
1630 /// @brief Check if the specified APInt has a N-bits unsigned integer value.
1631 inline bool isIntN(unsigned N, const APInt& APIVal) {
1632 return APIVal.isIntN(N);
1635 /// @brief Check if the specified APInt has a N-bits signed integer value.
1636 inline bool isSignedIntN(unsigned N, const APInt& APIVal) {
1637 return APIVal.isSignedIntN(N);
1640 /// @returns true if the argument APInt value is a sequence of ones
1641 /// starting at the least significant bit with the remainder zero.
1642 inline bool isMask(unsigned numBits, const APInt& APIVal) {
1643 return numBits <= APIVal.getBitWidth() &&
1644 APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
1647 /// @returns true if the argument APInt value contains a sequence of ones
1648 /// with the remainder zero.
1649 inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
1650 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1653 /// @returns a byte-swapped representation of the specified APInt Value.
1654 inline APInt byteSwap(const APInt& APIVal) {
1655 return APIVal.byteSwap();
1658 /// @returns the floor log base 2 of the specified APInt value.
1659 inline unsigned logBase2(const APInt& APIVal) {
1660 return APIVal.logBase2();
1663 /// GreatestCommonDivisor - This function returns the greatest common
1664 /// divisor of the two APInt values using Euclid's algorithm.
1665 /// @returns the greatest common divisor of Val1 and Val2
1666 /// @brief Compute GCD of two APInt values.
1667 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1669 /// Treats the APInt as an unsigned value for conversion purposes.
1670 /// @brief Converts the given APInt to a double value.
1671 inline double RoundAPIntToDouble(const APInt& APIVal) {
1672 return APIVal.roundToDouble();
1675 /// Treats the APInt as a signed value for conversion purposes.
1676 /// @brief Converts the given APInt to a double value.
1677 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1678 return APIVal.signedRoundToDouble();
1681 /// @brief Converts the given APInt to a float vlalue.
1682 inline float RoundAPIntToFloat(const APInt& APIVal) {
1683 return float(RoundAPIntToDouble(APIVal));
1686 /// Treast the APInt as a signed value for conversion purposes.
1687 /// @brief Converts the given APInt to a float value.
1688 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1689 return float(APIVal.signedRoundToDouble());
1692 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1693 /// @brief Converts the given double value into a APInt.
1694 APInt RoundDoubleToAPInt(double Double, unsigned width);
1696 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1697 /// @brief Converts a float value into a APInt.
1698 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
1699 return RoundDoubleToAPInt(double(Float), width);
1702 /// Arithmetic right-shift the APInt by shiftAmt.
1703 /// @brief Arithmetic right-shift function.
1704 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
1705 return LHS.ashr(shiftAmt);
1708 /// Logical right-shift the APInt by shiftAmt.
1709 /// @brief Logical right-shift function.
1710 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
1711 return LHS.lshr(shiftAmt);
1714 /// Left-shift the APInt by shiftAmt.
1715 /// @brief Left-shift function.
1716 inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
1717 return LHS.shl(shiftAmt);
1720 /// Signed divide APInt LHS by APInt RHS.
1721 /// @brief Signed division function for APInt.
1722 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1723 return LHS.sdiv(RHS);
1726 /// Unsigned divide APInt LHS by APInt RHS.
1727 /// @brief Unsigned division function for APInt.
1728 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1729 return LHS.udiv(RHS);
1732 /// Signed remainder operation on APInt.
1733 /// @brief Function for signed remainder operation.
1734 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1735 return LHS.srem(RHS);
1738 /// Unsigned remainder operation on APInt.
1739 /// @brief Function for unsigned remainder operation.
1740 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1741 return LHS.urem(RHS);
1744 /// Performs multiplication on APInt values.
1745 /// @brief Function for multiplication operation.
1746 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1750 /// Performs addition on APInt values.
1751 /// @brief Function for addition operation.
1752 inline APInt add(const APInt& LHS, const APInt& RHS) {
1756 /// Performs subtraction on APInt values.
1757 /// @brief Function for subtraction operation.
1758 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1762 /// Performs bitwise AND operation on APInt LHS and
1764 /// @brief Bitwise AND function for APInt.
1765 inline APInt And(const APInt& LHS, const APInt& RHS) {
1769 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1770 /// @brief Bitwise OR function for APInt.
1771 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1775 /// Performs bitwise XOR operation on APInt.
1776 /// @brief Bitwise XOR function for APInt.
1777 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1781 /// Performs a bitwise complement operation on APInt.
1782 /// @brief Bitwise complement function.
1783 inline APInt Not(const APInt& APIVal) {
1787 } // End of APIntOps namespace
1789 } // End of llvm namespace