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"
28 class FoldingSetNodeID;
33 class SmallVectorImpl;
35 // An unsigned host type used as a single part of a multi-part
37 typedef uint64_t integerPart;
39 const unsigned int host_char_bit = 8;
40 const unsigned int integerPartWidth = host_char_bit *
41 static_cast<unsigned int>(sizeof(integerPart));
43 //===----------------------------------------------------------------------===//
45 //===----------------------------------------------------------------------===//
47 /// APInt - This class represents arbitrary precision constant integral values.
48 /// It is a functional replacement for common case unsigned integer type like
49 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
50 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
51 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
52 /// and methods to manipulate integer values of any bit-width. It supports both
53 /// the typical integer arithmetic and comparison operations as well as bitwise
56 /// The class has several invariants worth noting:
57 /// * All bit, byte, and word positions are zero-based.
58 /// * Once the bit width is set, it doesn't change except by the Truncate,
59 /// SignExtend, or ZeroExtend operations.
60 /// * All binary operators must be on APInt instances of the same bit width.
61 /// Attempting to use these operators on instances with different bit
62 /// widths will yield an assertion.
63 /// * The value is stored canonically as an unsigned value. For operations
64 /// where it makes a difference, there are both signed and unsigned variants
65 /// of the operation. For example, sdiv and udiv. However, because the bit
66 /// widths must be the same, operations such as Mul and Add produce the same
67 /// results regardless of whether the values are interpreted as signed or
69 /// * In general, the class tries to follow the style of computation that LLVM
70 /// uses in its IR. This simplifies its use for LLVM.
72 /// @brief Class for arbitrary precision integers.
74 unsigned BitWidth; ///< The number of bits in this APInt.
76 /// This union is used to store the integer value. When the
77 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
79 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
80 uint64_t *pVal; ///< Used to store the >64 bits integer value.
83 /// This enum is used to hold the constants we needed for APInt.
86 APINT_BITS_PER_WORD = static_cast<unsigned int>(sizeof(uint64_t)) *
88 /// Byte size of a word
89 APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t))
92 /// This constructor is used only internally for speed of construction of
93 /// temporaries. It is unsafe for general use so it is not public.
94 /// @brief Fast internal constructor
95 APInt(uint64_t* val, unsigned bits) : BitWidth(bits), pVal(val) { }
97 /// @returns true if the number of bits <= 64, false otherwise.
98 /// @brief Determine if this APInt just has one word to store value.
99 bool isSingleWord() const {
100 return BitWidth <= APINT_BITS_PER_WORD;
103 /// @returns the word position for the specified bit position.
104 /// @brief Determine which word a bit is in.
105 static unsigned whichWord(unsigned bitPosition) {
106 return bitPosition / APINT_BITS_PER_WORD;
109 /// @returns the bit position in a word for the specified bit position
111 /// @brief Determine which bit in a word a bit is in.
112 static unsigned whichBit(unsigned bitPosition) {
113 return bitPosition % APINT_BITS_PER_WORD;
116 /// This method generates and returns a uint64_t (word) mask for a single
117 /// bit at a specific bit position. This is used to mask the bit in the
118 /// corresponding word.
119 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
120 /// @brief Get a single bit mask.
121 static uint64_t maskBit(unsigned bitPosition) {
122 return 1ULL << whichBit(bitPosition);
125 /// This method is used internally to clear the to "N" bits in the high order
126 /// word that are not used by the APInt. This is needed after the most
127 /// significant word is assigned a value to ensure that those bits are
129 /// @brief Clear unused high order bits
130 APInt& clearUnusedBits() {
131 // Compute how many bits are used in the final word
132 unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
134 // If all bits are used, we want to leave the value alone. This also
135 // avoids the undefined behavior of >> when the shift is the same size as
136 // the word size (64).
139 // Mask out the high bits.
140 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
144 pVal[getNumWords() - 1] &= mask;
148 /// @returns the corresponding word for the specified bit position.
149 /// @brief Get the word corresponding to a bit position
150 uint64_t getWord(unsigned bitPosition) const {
151 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
154 /// Converts a string into a number. The string must be non-empty
155 /// and well-formed as a number of the given base. The bit-width
156 /// must be sufficient to hold the result.
158 /// This is used by the constructors that take string arguments.
160 /// StringRef::getAsInteger is superficially similar but (1) does
161 /// not assume that the string is well-formed and (2) grows the
162 /// result to hold the input.
164 /// @param radix 2, 8, 10, 16, or 36
165 /// @brief Convert a char array into an APInt
166 void fromString(unsigned numBits, StringRef str, uint8_t radix);
168 /// This is used by the toString method to divide by the radix. It simply
169 /// provides a more convenient form of divide for internal use since KnuthDiv
170 /// has specific constraints on its inputs. If those constraints are not met
171 /// then it provides a simpler form of divide.
172 /// @brief An internal division function for dividing APInts.
173 static void divide(const APInt LHS, unsigned lhsWords,
174 const APInt &RHS, unsigned rhsWords,
175 APInt *Quotient, APInt *Remainder);
177 /// out-of-line slow case for inline constructor
178 void initSlowCase(unsigned numBits, uint64_t val, bool isSigned);
180 /// shared code between two array constructors
181 void initFromArray(ArrayRef<uint64_t> array);
183 /// out-of-line slow case for inline copy constructor
184 void initSlowCase(const APInt& that);
186 /// out-of-line slow case for shl
187 APInt shlSlowCase(unsigned shiftAmt) const;
189 /// out-of-line slow case for operator&
190 APInt AndSlowCase(const APInt& RHS) const;
192 /// out-of-line slow case for operator|
193 APInt OrSlowCase(const APInt& RHS) const;
195 /// out-of-line slow case for operator^
196 APInt XorSlowCase(const APInt& RHS) const;
198 /// out-of-line slow case for operator=
199 APInt& AssignSlowCase(const APInt& RHS);
201 /// out-of-line slow case for operator==
202 bool EqualSlowCase(const APInt& RHS) const;
204 /// out-of-line slow case for operator==
205 bool EqualSlowCase(uint64_t Val) const;
207 /// out-of-line slow case for countLeadingZeros
208 unsigned countLeadingZerosSlowCase() const;
210 /// out-of-line slow case for countTrailingOnes
211 unsigned countTrailingOnesSlowCase() const;
213 /// out-of-line slow case for countPopulation
214 unsigned countPopulationSlowCase() const;
217 /// @name Constructors
219 /// If isSigned is true then val is treated as if it were a signed value
220 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
221 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
222 /// the range of val are zero filled).
223 /// @param numBits the bit width of the constructed APInt
224 /// @param val the initial value of the APInt
225 /// @param isSigned how to treat signedness of val
226 /// @brief Create a new APInt of numBits width, initialized as val.
227 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
228 : BitWidth(numBits), VAL(0) {
229 assert(BitWidth && "bitwidth too small");
233 initSlowCase(numBits, val, isSigned);
237 /// Note that bigVal.size() can be smaller or larger than the corresponding
238 /// bit width but any extraneous bits will be dropped.
239 /// @param numBits the bit width of the constructed APInt
240 /// @param bigVal a sequence of words to form the initial value of the APInt
241 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
242 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
243 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
244 /// deprecated because this constructor is prone to ambiguity with the
245 /// APInt(unsigned, uint64_t, bool) constructor.
247 /// If this overload is ever deleted, care should be taken to prevent calls
248 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
250 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
252 /// This constructor interprets the string \arg str in the given radix. The
253 /// interpretation stops when the first character that is not suitable for the
254 /// radix is encountered, or the end of the string. Acceptable radix values
255 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
256 /// string to require more bits than numBits.
258 /// @param numBits the bit width of the constructed APInt
259 /// @param str the string to be interpreted
260 /// @param radix the radix to use for the conversion
261 /// @brief Construct an APInt from a string representation.
262 APInt(unsigned numBits, StringRef str, uint8_t radix);
264 /// Simply makes *this a copy of that.
265 /// @brief Copy Constructor.
266 APInt(const APInt& that)
267 : BitWidth(that.BitWidth), VAL(0) {
268 assert(BitWidth && "bitwidth too small");
275 /// @brief Destructor.
281 /// Default constructor that creates an uninitialized APInt. This is useful
282 /// for object deserialization (pair this with the static method Read).
283 explicit APInt() : BitWidth(1) {}
285 /// Profile - Used to insert APInt objects, or objects that contain APInt
286 /// objects, into FoldingSets.
287 void Profile(FoldingSetNodeID& id) const;
290 /// @name Value Tests
292 /// This tests the high bit of this APInt to determine if it is set.
293 /// @returns true if this APInt is negative, false otherwise
294 /// @brief Determine sign of this APInt.
295 bool isNegative() const {
296 return (*this)[BitWidth - 1];
299 /// This tests the high bit of the APInt to determine if it is unset.
300 /// @brief Determine if this APInt Value is non-negative (>= 0)
301 bool isNonNegative() const {
302 return !isNegative();
305 /// This tests if the value of this APInt is positive (> 0). Note
306 /// that 0 is not a positive value.
307 /// @returns true if this APInt is positive.
308 /// @brief Determine if this APInt Value is positive.
309 bool isStrictlyPositive() const {
310 return isNonNegative() && !!*this;
313 /// This checks to see if the value has all bits of the APInt are set or not.
314 /// @brief Determine if all bits are set
315 bool isAllOnesValue() const {
316 return countPopulation() == BitWidth;
319 /// This checks to see if the value of this APInt is the maximum unsigned
320 /// value for the APInt's bit width.
321 /// @brief Determine if this is the largest unsigned value.
322 bool isMaxValue() const {
323 return countPopulation() == BitWidth;
326 /// This checks to see if the value of this APInt is the maximum signed
327 /// value for the APInt's bit width.
328 /// @brief Determine if this is the largest signed value.
329 bool isMaxSignedValue() const {
330 return BitWidth == 1 ? VAL == 0 :
331 !isNegative() && countPopulation() == BitWidth - 1;
334 /// This checks to see if the value of this APInt is the minimum unsigned
335 /// value for the APInt's bit width.
336 /// @brief Determine if this is the smallest unsigned value.
337 bool isMinValue() const {
341 /// This checks to see if the value of this APInt is the minimum signed
342 /// value for the APInt's bit width.
343 /// @brief Determine if this is the smallest signed value.
344 bool isMinSignedValue() const {
345 return BitWidth == 1 ? VAL == 1 : isNegative() && isPowerOf2();
348 /// @brief Check if this APInt has an N-bits unsigned integer value.
349 bool isIntN(unsigned N) const {
350 assert(N && "N == 0 ???");
351 if (N >= getBitWidth())
355 return isUIntN(N, VAL);
356 return APInt(N, makeArrayRef(pVal, getNumWords())).zext(getBitWidth())
360 /// @brief Check if this APInt has an N-bits signed integer value.
361 bool isSignedIntN(unsigned N) const {
362 assert(N && "N == 0 ???");
363 return getMinSignedBits() <= N;
366 /// @returns true if the argument APInt value is a power of two > 0.
367 bool isPowerOf2() const {
369 return isPowerOf2_64(VAL);
370 return countPopulationSlowCase() == 1;
373 /// isSignBit - Return true if this is the value returned by getSignBit.
374 bool isSignBit() const { return isMinSignedValue(); }
376 /// This converts the APInt to a boolean value as a test against zero.
377 /// @brief Boolean conversion function.
378 bool getBoolValue() const {
382 /// getLimitedValue - If this value is smaller than the specified limit,
383 /// return it, otherwise return the limit value. This causes the value
384 /// to saturate to the limit.
385 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
386 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
387 Limit : getZExtValue();
391 /// @name Value Generators
393 /// @brief Gets maximum unsigned value of APInt for specific bit width.
394 static APInt getMaxValue(unsigned numBits) {
395 return getAllOnesValue(numBits);
398 /// @brief Gets maximum signed value of APInt for a specific bit width.
399 static APInt getSignedMaxValue(unsigned numBits) {
400 APInt API = getAllOnesValue(numBits);
401 API.clearBit(numBits - 1);
405 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
406 static APInt getMinValue(unsigned numBits) {
407 return APInt(numBits, 0);
410 /// @brief Gets minimum signed value of APInt for a specific bit width.
411 static APInt getSignedMinValue(unsigned numBits) {
412 APInt API(numBits, 0);
413 API.setBit(numBits - 1);
417 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
418 /// it helps code readability when we want to get a SignBit.
419 /// @brief Get the SignBit for a specific bit width.
420 static APInt getSignBit(unsigned BitWidth) {
421 return getSignedMinValue(BitWidth);
424 /// @returns the all-ones value for an APInt of the specified bit-width.
425 /// @brief Get the all-ones value.
426 static APInt getAllOnesValue(unsigned numBits) {
427 return APInt(numBits, -1ULL, true);
430 /// @returns the '0' value for an APInt of the specified bit-width.
431 /// @brief Get the '0' value.
432 static APInt getNullValue(unsigned numBits) {
433 return APInt(numBits, 0);
436 /// Get an APInt with the same BitWidth as this APInt, just zero mask
437 /// the low bits and right shift to the least significant bit.
438 /// @returns the high "numBits" bits of this APInt.
439 APInt getHiBits(unsigned numBits) const;
441 /// Get an APInt with the same BitWidth as this APInt, just zero mask
443 /// @returns the low "numBits" bits of this APInt.
444 APInt getLoBits(unsigned numBits) const;
446 /// getOneBitSet - Return an APInt with exactly one bit set in the result.
447 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
448 APInt Res(numBits, 0);
453 /// Constructs an APInt value that has a contiguous range of bits set. The
454 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
455 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
456 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
457 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
458 /// @param numBits the intended bit width of the result
459 /// @param loBit the index of the lowest bit set.
460 /// @param hiBit the index of the highest bit set.
461 /// @returns An APInt value with the requested bits set.
462 /// @brief Get a value with a block of bits set.
463 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
464 assert(hiBit <= numBits && "hiBit out of range");
465 assert(loBit < numBits && "loBit out of range");
467 return getLowBitsSet(numBits, hiBit) |
468 getHighBitsSet(numBits, numBits-loBit);
469 return getLowBitsSet(numBits, hiBit-loBit).shl(loBit);
472 /// Constructs an APInt value that has the top hiBitsSet bits set.
473 /// @param numBits the bitwidth of the result
474 /// @param hiBitsSet the number of high-order bits set in the result.
475 /// @brief Get a value with high bits set
476 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
477 assert(hiBitsSet <= numBits && "Too many bits to set!");
478 // Handle a degenerate case, to avoid shifting by word size
480 return APInt(numBits, 0);
481 unsigned shiftAmt = numBits - hiBitsSet;
482 // For small values, return quickly
483 if (numBits <= APINT_BITS_PER_WORD)
484 return APInt(numBits, ~0ULL << shiftAmt);
485 return getAllOnesValue(numBits).shl(shiftAmt);
488 /// Constructs an APInt value that has the bottom loBitsSet bits set.
489 /// @param numBits the bitwidth of the result
490 /// @param loBitsSet the number of low-order bits set in the result.
491 /// @brief Get a value with low bits set
492 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
493 assert(loBitsSet <= numBits && "Too many bits to set!");
494 // Handle a degenerate case, to avoid shifting by word size
496 return APInt(numBits, 0);
497 if (loBitsSet == APINT_BITS_PER_WORD)
498 return APInt(numBits, -1ULL);
499 // For small values, return quickly.
500 if (loBitsSet <= APINT_BITS_PER_WORD)
501 return APInt(numBits, -1ULL >> (APINT_BITS_PER_WORD - loBitsSet));
502 return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
505 /// The hash value is computed as the sum of the words and the bit width.
506 /// @returns A hash value computed from the sum of the APInt words.
507 /// @brief Get a hash value based on this APInt
508 uint64_t getHashValue() const;
510 /// This function returns a pointer to the internal storage of the APInt.
511 /// This is useful for writing out the APInt in binary form without any
513 const uint64_t* getRawData() const {
520 /// @name Unary Operators
522 /// @returns a new APInt value representing *this incremented by one
523 /// @brief Postfix increment operator.
524 const APInt operator++(int) {
530 /// @returns *this incremented by one
531 /// @brief Prefix increment operator.
534 /// @returns a new APInt representing *this decremented by one.
535 /// @brief Postfix decrement operator.
536 const APInt operator--(int) {
542 /// @returns *this decremented by one.
543 /// @brief Prefix decrement operator.
546 /// Performs a bitwise complement operation on this APInt.
547 /// @returns an APInt that is the bitwise complement of *this
548 /// @brief Unary bitwise complement operator.
549 APInt operator~() const {
551 Result.flipAllBits();
555 /// Negates *this using two's complement logic.
556 /// @returns An APInt value representing the negation of *this.
557 /// @brief Unary negation operator
558 APInt operator-() const {
559 return APInt(BitWidth, 0) - (*this);
562 /// Performs logical negation operation on this APInt.
563 /// @returns true if *this is zero, false otherwise.
564 /// @brief Logical negation operator.
565 bool operator!() const;
568 /// @name Assignment Operators
570 /// @returns *this after assignment of RHS.
571 /// @brief Copy assignment operator.
572 APInt& operator=(const APInt& RHS) {
573 // If the bitwidths are the same, we can avoid mucking with memory
574 if (isSingleWord() && RHS.isSingleWord()) {
576 BitWidth = RHS.BitWidth;
577 return clearUnusedBits();
580 return AssignSlowCase(RHS);
583 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
584 /// the bit width, the excess bits are truncated. If the bit width is larger
585 /// than 64, the value is zero filled in the unspecified high order bits.
586 /// @returns *this after assignment of RHS value.
587 /// @brief Assignment operator.
588 APInt& operator=(uint64_t RHS);
590 /// Performs a bitwise AND operation on this APInt and RHS. The result is
591 /// assigned to *this.
592 /// @returns *this after ANDing with RHS.
593 /// @brief Bitwise AND assignment operator.
594 APInt& operator&=(const APInt& RHS);
596 /// Performs a bitwise OR operation on this APInt and RHS. The result is
598 /// @returns *this after ORing with RHS.
599 /// @brief Bitwise OR assignment operator.
600 APInt& operator|=(const APInt& RHS);
602 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
603 /// logically zero-extended or truncated to match the bit-width of
606 /// @brief Bitwise OR assignment operator.
607 APInt& operator|=(uint64_t RHS) {
608 if (isSingleWord()) {
617 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
618 /// assigned to *this.
619 /// @returns *this after XORing with RHS.
620 /// @brief Bitwise XOR assignment operator.
621 APInt& operator^=(const APInt& RHS);
623 /// Multiplies this APInt by RHS and assigns the result to *this.
625 /// @brief Multiplication assignment operator.
626 APInt& operator*=(const APInt& RHS);
628 /// Adds RHS to *this and assigns the result to *this.
630 /// @brief Addition assignment operator.
631 APInt& operator+=(const APInt& RHS);
633 /// Subtracts RHS from *this and assigns the result to *this.
635 /// @brief Subtraction assignment operator.
636 APInt& operator-=(const APInt& RHS);
638 /// Shifts *this left by shiftAmt and assigns the result to *this.
639 /// @returns *this after shifting left by shiftAmt
640 /// @brief Left-shift assignment function.
641 APInt& operator<<=(unsigned shiftAmt) {
642 *this = shl(shiftAmt);
647 /// @name Binary Operators
649 /// Performs a bitwise AND operation on *this and RHS.
650 /// @returns An APInt value representing the bitwise AND of *this and RHS.
651 /// @brief Bitwise AND operator.
652 APInt operator&(const APInt& RHS) const {
653 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
655 return APInt(getBitWidth(), VAL & RHS.VAL);
656 return AndSlowCase(RHS);
658 APInt And(const APInt& RHS) const {
659 return this->operator&(RHS);
662 /// Performs a bitwise OR operation on *this and RHS.
663 /// @returns An APInt value representing the bitwise OR of *this and RHS.
664 /// @brief Bitwise OR operator.
665 APInt operator|(const APInt& RHS) const {
666 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
668 return APInt(getBitWidth(), VAL | RHS.VAL);
669 return OrSlowCase(RHS);
671 APInt Or(const APInt& RHS) const {
672 return this->operator|(RHS);
675 /// Performs a bitwise XOR operation on *this and RHS.
676 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
677 /// @brief Bitwise XOR operator.
678 APInt operator^(const APInt& RHS) const {
679 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
681 return APInt(BitWidth, VAL ^ RHS.VAL);
682 return XorSlowCase(RHS);
684 APInt Xor(const APInt& RHS) const {
685 return this->operator^(RHS);
688 /// Multiplies this APInt by RHS and returns the result.
689 /// @brief Multiplication operator.
690 APInt operator*(const APInt& RHS) const;
692 /// Adds RHS to this APInt and returns the result.
693 /// @brief Addition operator.
694 APInt operator+(const APInt& RHS) const;
695 APInt operator+(uint64_t RHS) const {
696 return (*this) + APInt(BitWidth, RHS);
699 /// Subtracts RHS from this APInt and returns the result.
700 /// @brief Subtraction operator.
701 APInt operator-(const APInt& RHS) const;
702 APInt operator-(uint64_t RHS) const {
703 return (*this) - APInt(BitWidth, RHS);
706 APInt operator<<(unsigned Bits) const {
710 APInt operator<<(const APInt &Bits) const {
714 /// Arithmetic right-shift this APInt by shiftAmt.
715 /// @brief Arithmetic right-shift function.
716 APInt ashr(unsigned shiftAmt) const;
718 /// Logical right-shift this APInt by shiftAmt.
719 /// @brief Logical right-shift function.
720 APInt lshr(unsigned shiftAmt) const;
722 /// Left-shift this APInt by shiftAmt.
723 /// @brief Left-shift function.
724 APInt shl(unsigned shiftAmt) const {
725 assert(shiftAmt <= BitWidth && "Invalid shift amount");
726 if (isSingleWord()) {
727 if (shiftAmt == BitWidth)
728 return APInt(BitWidth, 0); // avoid undefined shift results
729 return APInt(BitWidth, VAL << shiftAmt);
731 return shlSlowCase(shiftAmt);
734 /// @brief Rotate left by rotateAmt.
735 APInt rotl(unsigned rotateAmt) const;
737 /// @brief Rotate right by rotateAmt.
738 APInt rotr(unsigned rotateAmt) const;
740 /// Arithmetic right-shift this APInt by shiftAmt.
741 /// @brief Arithmetic right-shift function.
742 APInt ashr(const APInt &shiftAmt) const;
744 /// Logical right-shift this APInt by shiftAmt.
745 /// @brief Logical right-shift function.
746 APInt lshr(const APInt &shiftAmt) const;
748 /// Left-shift this APInt by shiftAmt.
749 /// @brief Left-shift function.
750 APInt shl(const APInt &shiftAmt) const;
752 /// @brief Rotate left by rotateAmt.
753 APInt rotl(const APInt &rotateAmt) const;
755 /// @brief Rotate right by rotateAmt.
756 APInt rotr(const APInt &rotateAmt) const;
758 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
759 /// RHS are treated as unsigned quantities for purposes of this division.
760 /// @returns a new APInt value containing the division result
761 /// @brief Unsigned division operation.
762 APInt udiv(const APInt &RHS) const;
764 /// Signed divide this APInt by APInt RHS.
765 /// @brief Signed division function for APInt.
766 APInt sdiv(const APInt &RHS) const {
768 if (RHS.isNegative())
769 return (-(*this)).udiv(-RHS);
771 return -((-(*this)).udiv(RHS));
772 else if (RHS.isNegative())
773 return -(this->udiv(-RHS));
774 return this->udiv(RHS);
777 /// Perform an unsigned remainder operation on this APInt with RHS being the
778 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
779 /// of this operation. Note that this is a true remainder operation and not
780 /// a modulo operation because the sign follows the sign of the dividend
782 /// @returns a new APInt value containing the remainder result
783 /// @brief Unsigned remainder operation.
784 APInt urem(const APInt &RHS) const;
786 /// Signed remainder operation on APInt.
787 /// @brief Function for signed remainder operation.
788 APInt srem(const APInt &RHS) const {
790 if (RHS.isNegative())
791 return -((-(*this)).urem(-RHS));
793 return -((-(*this)).urem(RHS));
794 else if (RHS.isNegative())
795 return this->urem(-RHS);
796 return this->urem(RHS);
799 /// Sometimes it is convenient to divide two APInt values and obtain both the
800 /// quotient and remainder. This function does both operations in the same
801 /// computation making it a little more efficient. The pair of input arguments
802 /// may overlap with the pair of output arguments. It is safe to call
803 /// udivrem(X, Y, X, Y), for example.
804 /// @brief Dual division/remainder interface.
805 static void udivrem(const APInt &LHS, const APInt &RHS,
806 APInt &Quotient, APInt &Remainder);
808 static void sdivrem(const APInt &LHS, const APInt &RHS,
809 APInt &Quotient, APInt &Remainder) {
810 if (LHS.isNegative()) {
811 if (RHS.isNegative())
812 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
814 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
815 Quotient = -Quotient;
816 Remainder = -Remainder;
817 } else if (RHS.isNegative()) {
818 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
819 Quotient = -Quotient;
821 APInt::udivrem(LHS, RHS, Quotient, Remainder);
826 // Operations that return overflow indicators.
827 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
828 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
829 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
830 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
831 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
832 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
833 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
834 APInt sshl_ov(unsigned Amt, bool &Overflow) const;
836 /// @returns the bit value at bitPosition
837 /// @brief Array-indexing support.
838 bool operator[](unsigned bitPosition) const;
841 /// @name Comparison Operators
843 /// Compares this APInt with RHS for the validity of the equality
845 /// @brief Equality operator.
846 bool operator==(const APInt& RHS) const {
847 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
849 return VAL == RHS.VAL;
850 return EqualSlowCase(RHS);
853 /// Compares this APInt with a uint64_t for the validity of the equality
855 /// @returns true if *this == Val
856 /// @brief Equality operator.
857 bool operator==(uint64_t Val) const {
860 return EqualSlowCase(Val);
863 /// Compares this APInt with RHS for the validity of the equality
865 /// @returns true if *this == Val
866 /// @brief Equality comparison.
867 bool eq(const APInt &RHS) const {
868 return (*this) == RHS;
871 /// Compares this APInt with RHS for the validity of the inequality
873 /// @returns true if *this != Val
874 /// @brief Inequality operator.
875 bool operator!=(const APInt& RHS) const {
876 return !((*this) == RHS);
879 /// Compares this APInt with a uint64_t for the validity of the inequality
881 /// @returns true if *this != Val
882 /// @brief Inequality operator.
883 bool operator!=(uint64_t Val) const {
884 return !((*this) == Val);
887 /// Compares this APInt with RHS for the validity of the inequality
889 /// @returns true if *this != Val
890 /// @brief Inequality comparison
891 bool ne(const APInt &RHS) const {
892 return !((*this) == RHS);
895 /// Regards both *this and RHS as unsigned quantities and compares them for
896 /// the validity of the less-than relationship.
897 /// @returns true if *this < RHS when both are considered unsigned.
898 /// @brief Unsigned less than comparison
899 bool ult(const APInt &RHS) const;
901 /// Regards both *this as an unsigned quantity and compares it with RHS for
902 /// the validity of the less-than relationship.
903 /// @returns true if *this < RHS when considered unsigned.
904 /// @brief Unsigned less than comparison
905 bool ult(uint64_t RHS) const {
906 return ult(APInt(getBitWidth(), RHS));
909 /// Regards both *this and RHS as signed quantities and compares them for
910 /// validity of the less-than relationship.
911 /// @returns true if *this < RHS when both are considered signed.
912 /// @brief Signed less than comparison
913 bool slt(const APInt& RHS) const;
915 /// Regards both *this as a signed quantity and compares it with RHS for
916 /// the validity of the less-than relationship.
917 /// @returns true if *this < RHS when considered signed.
918 /// @brief Signed less than comparison
919 bool slt(uint64_t RHS) const {
920 return slt(APInt(getBitWidth(), RHS));
923 /// Regards both *this and RHS as unsigned quantities and compares them for
924 /// validity of the less-or-equal relationship.
925 /// @returns true if *this <= RHS when both are considered unsigned.
926 /// @brief Unsigned less or equal comparison
927 bool ule(const APInt& RHS) const {
928 return ult(RHS) || eq(RHS);
931 /// Regards both *this as an unsigned quantity and compares it with RHS for
932 /// the validity of the less-or-equal relationship.
933 /// @returns true if *this <= RHS when considered unsigned.
934 /// @brief Unsigned less or equal comparison
935 bool ule(uint64_t RHS) const {
936 return ule(APInt(getBitWidth(), RHS));
939 /// Regards both *this and RHS as signed quantities and compares them for
940 /// validity of the less-or-equal relationship.
941 /// @returns true if *this <= RHS when both are considered signed.
942 /// @brief Signed less or equal comparison
943 bool sle(const APInt& RHS) const {
944 return slt(RHS) || eq(RHS);
947 /// Regards both *this as a signed quantity and compares it with RHS for
948 /// the validity of the less-or-equal relationship.
949 /// @returns true if *this <= RHS when considered signed.
950 /// @brief Signed less or equal comparison
951 bool sle(uint64_t RHS) const {
952 return sle(APInt(getBitWidth(), RHS));
955 /// Regards both *this and RHS as unsigned quantities and compares them for
956 /// the validity of the greater-than relationship.
957 /// @returns true if *this > RHS when both are considered unsigned.
958 /// @brief Unsigned greather than comparison
959 bool ugt(const APInt& RHS) const {
960 return !ult(RHS) && !eq(RHS);
963 /// Regards both *this as an unsigned quantity and compares it with RHS for
964 /// the validity of the greater-than relationship.
965 /// @returns true if *this > RHS when considered unsigned.
966 /// @brief Unsigned greater than comparison
967 bool ugt(uint64_t RHS) const {
968 return ugt(APInt(getBitWidth(), RHS));
971 /// Regards both *this and RHS as signed quantities and compares them for
972 /// the validity of the greater-than relationship.
973 /// @returns true if *this > RHS when both are considered signed.
974 /// @brief Signed greather than comparison
975 bool sgt(const APInt& RHS) const {
976 return !slt(RHS) && !eq(RHS);
979 /// Regards both *this as a signed quantity and compares it with RHS for
980 /// the validity of the greater-than relationship.
981 /// @returns true if *this > RHS when considered signed.
982 /// @brief Signed greater than comparison
983 bool sgt(uint64_t RHS) const {
984 return sgt(APInt(getBitWidth(), RHS));
987 /// Regards both *this and RHS as unsigned quantities and compares them for
988 /// validity of the greater-or-equal relationship.
989 /// @returns true if *this >= RHS when both are considered unsigned.
990 /// @brief Unsigned greater or equal comparison
991 bool uge(const APInt& RHS) const {
995 /// Regards both *this as an unsigned quantity and compares it with RHS for
996 /// the validity of the greater-or-equal relationship.
997 /// @returns true if *this >= RHS when considered unsigned.
998 /// @brief Unsigned greater or equal comparison
999 bool uge(uint64_t RHS) const {
1000 return uge(APInt(getBitWidth(), RHS));
1003 /// Regards both *this and RHS as signed quantities and compares them for
1004 /// validity of the greater-or-equal relationship.
1005 /// @returns true if *this >= RHS when both are considered signed.
1006 /// @brief Signed greather or equal comparison
1007 bool sge(const APInt& RHS) const {
1011 /// Regards both *this as a signed quantity and compares it with RHS for
1012 /// the validity of the greater-or-equal relationship.
1013 /// @returns true if *this >= RHS when considered signed.
1014 /// @brief Signed greater or equal comparison
1015 bool sge(uint64_t RHS) const {
1016 return sge(APInt(getBitWidth(), RHS));
1022 /// This operation tests if there are any pairs of corresponding bits
1023 /// between this APInt and RHS that are both set.
1024 bool intersects(const APInt &RHS) const {
1025 return (*this & RHS) != 0;
1029 /// @name Resizing Operators
1031 /// Truncate the APInt to a specified width. It is an error to specify a width
1032 /// that is greater than or equal to the current width.
1033 /// @brief Truncate to new width.
1034 APInt trunc(unsigned width) const;
1036 /// This operation sign extends the APInt to a new width. If the high order
1037 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1038 /// It is an error to specify a width that is less than or equal to the
1040 /// @brief Sign extend to a new width.
1041 APInt sext(unsigned width) const;
1043 /// This operation zero extends the APInt to a new width. The high order bits
1044 /// are filled with 0 bits. It is an error to specify a width that is less
1045 /// than or equal to the current width.
1046 /// @brief Zero extend to a new width.
1047 APInt zext(unsigned width) const;
1049 /// Make this APInt have the bit width given by \p width. The value is sign
1050 /// extended, truncated, or left alone to make it that width.
1051 /// @brief Sign extend or truncate to width
1052 APInt sextOrTrunc(unsigned width) const;
1054 /// Make this APInt have the bit width given by \p width. The value is zero
1055 /// extended, truncated, or left alone to make it that width.
1056 /// @brief Zero extend or truncate to width
1057 APInt zextOrTrunc(unsigned width) const;
1059 /// Make this APInt have the bit width given by \p width. The value is sign
1060 /// extended, or left alone to make it that width.
1061 /// @brief Sign extend or truncate to width
1062 APInt sextOrSelf(unsigned width) const;
1064 /// Make this APInt have the bit width given by \p width. The value is zero
1065 /// extended, or left alone to make it that width.
1066 /// @brief Zero extend or truncate to width
1067 APInt zextOrSelf(unsigned width) const;
1070 /// @name Bit Manipulation Operators
1072 /// @brief Set every bit to 1.
1077 // Set all the bits in all the words.
1078 for (unsigned i = 0; i < getNumWords(); ++i)
1081 // Clear the unused ones
1085 /// Set the given bit to 1 whose position is given as "bitPosition".
1086 /// @brief Set a given bit to 1.
1087 void setBit(unsigned bitPosition);
1089 /// @brief Set every bit to 0.
1090 void clearAllBits() {
1094 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
1097 /// Set the given bit to 0 whose position is given as "bitPosition".
1098 /// @brief Set a given bit to 0.
1099 void clearBit(unsigned bitPosition);
1101 /// @brief Toggle every bit to its opposite value.
1102 void flipAllBits() {
1106 for (unsigned i = 0; i < getNumWords(); ++i)
1112 /// Toggle a given bit to its opposite value whose position is given
1113 /// as "bitPosition".
1114 /// @brief Toggles a given bit to its opposite value.
1115 void flipBit(unsigned bitPosition);
1118 /// @name Value Characterization Functions
1121 /// @returns the total number of bits.
1122 unsigned getBitWidth() const {
1126 /// Here one word's bitwidth equals to that of uint64_t.
1127 /// @returns the number of words to hold the integer value of this APInt.
1128 /// @brief Get the number of words.
1129 unsigned getNumWords() const {
1130 return getNumWords(BitWidth);
1133 /// Here one word's bitwidth equals to that of uint64_t.
1134 /// @returns the number of words to hold the integer value with a
1135 /// given bit width.
1136 /// @brief Get the number of words.
1137 static unsigned getNumWords(unsigned BitWidth) {
1138 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1141 /// This function returns the number of active bits which is defined as the
1142 /// bit width minus the number of leading zeros. This is used in several
1143 /// computations to see how "wide" the value is.
1144 /// @brief Compute the number of active bits in the value
1145 unsigned getActiveBits() const {
1146 return BitWidth - countLeadingZeros();
1149 /// This function returns the number of active words in the value of this
1150 /// APInt. This is used in conjunction with getActiveData to extract the raw
1151 /// value of the APInt.
1152 unsigned getActiveWords() const {
1153 return whichWord(getActiveBits()-1) + 1;
1156 /// Computes the minimum bit width for this APInt while considering it to be
1157 /// a signed (and probably negative) value. If the value is not negative,
1158 /// this function returns the same value as getActiveBits()+1. Otherwise, it
1159 /// returns the smallest bit width that will retain the negative value. For
1160 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1161 /// for -1, this function will always return 1.
1162 /// @brief Get the minimum bit size for this signed APInt
1163 unsigned getMinSignedBits() const {
1165 return BitWidth - countLeadingOnes() + 1;
1166 return getActiveBits()+1;
1169 /// This method attempts to return the value of this APInt as a zero extended
1170 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1171 /// uint64_t. Otherwise an assertion will result.
1172 /// @brief Get zero extended value
1173 uint64_t getZExtValue() const {
1176 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1180 /// This method attempts to return the value of this APInt as a sign extended
1181 /// int64_t. The bit width must be <= 64 or the value must fit within an
1182 /// int64_t. Otherwise an assertion will result.
1183 /// @brief Get sign extended value
1184 int64_t getSExtValue() const {
1186 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
1187 (APINT_BITS_PER_WORD - BitWidth);
1188 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1189 return int64_t(pVal[0]);
1192 /// This method determines how many bits are required to hold the APInt
1193 /// equivalent of the string given by \arg str.
1194 /// @brief Get bits required for string value.
1195 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1197 /// countLeadingZeros - This function is an APInt version of the
1198 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
1199 /// of zeros from the most significant bit to the first one bit.
1200 /// @returns BitWidth if the value is zero.
1201 /// @returns the number of zeros from the most significant bit to the first
1203 unsigned countLeadingZeros() const {
1204 if (isSingleWord()) {
1205 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1206 return CountLeadingZeros_64(VAL) - unusedBits;
1208 return countLeadingZerosSlowCase();
1211 /// countLeadingOnes - This function is an APInt version of the
1212 /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number
1213 /// of ones from the most significant bit to the first zero bit.
1214 /// @returns 0 if the high order bit is not set
1215 /// @returns the number of 1 bits from the most significant to the least
1216 /// @brief Count the number of leading one bits.
1217 unsigned countLeadingOnes() const;
1219 /// Computes the number of leading bits of this APInt that are equal to its
1221 unsigned getNumSignBits() const {
1222 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1225 /// countTrailingZeros - This function is an APInt version of the
1226 /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
1227 /// the number of zeros from the least significant bit to the first set bit.
1228 /// @returns BitWidth if the value is zero.
1229 /// @returns the number of zeros from the least significant bit to the first
1231 /// @brief Count the number of trailing zero bits.
1232 unsigned countTrailingZeros() const;
1234 /// countTrailingOnes - This function is an APInt version of the
1235 /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
1236 /// the number of ones from the least significant bit to the first zero bit.
1237 /// @returns BitWidth if the value is all ones.
1238 /// @returns the number of ones from the least significant bit to the first
1240 /// @brief Count the number of trailing one bits.
1241 unsigned countTrailingOnes() const {
1243 return CountTrailingOnes_64(VAL);
1244 return countTrailingOnesSlowCase();
1247 /// countPopulation - This function is an APInt version of the
1248 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
1249 /// of 1 bits in the APInt value.
1250 /// @returns 0 if the value is zero.
1251 /// @returns the number of set bits.
1252 /// @brief Count the number of bits set.
1253 unsigned countPopulation() const {
1255 return CountPopulation_64(VAL);
1256 return countPopulationSlowCase();
1260 /// @name Conversion Functions
1262 void print(raw_ostream &OS, bool isSigned) const;
1264 /// toString - Converts an APInt to a string and append it to Str. Str is
1265 /// commonly a SmallString.
1266 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1267 bool formatAsCLiteral = false) const;
1269 /// Considers the APInt to be unsigned and converts it into a string in the
1270 /// radix given. The radix can be 2, 8, 10 16, or 36.
1271 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1272 toString(Str, Radix, false, false);
1275 /// Considers the APInt to be signed and converts it into a string in the
1276 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1277 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1278 toString(Str, Radix, true, false);
1281 /// toString - This returns the APInt as a std::string. Note that this is an
1282 /// inefficient method. It is better to pass in a SmallVector/SmallString
1283 /// to the methods above to avoid thrashing the heap for the string.
1284 std::string toString(unsigned Radix, bool Signed) const;
1287 /// @returns a byte-swapped representation of this APInt Value.
1288 APInt byteSwap() const;
1290 /// @brief Converts this APInt to a double value.
1291 double roundToDouble(bool isSigned) const;
1293 /// @brief Converts this unsigned APInt to a double value.
1294 double roundToDouble() const {
1295 return roundToDouble(false);
1298 /// @brief Converts this signed APInt to a double value.
1299 double signedRoundToDouble() const {
1300 return roundToDouble(true);
1303 /// The conversion does not do a translation from integer to double, it just
1304 /// re-interprets the bits as a double. Note that it is valid to do this on
1305 /// any bit width. Exactly 64 bits will be translated.
1306 /// @brief Converts APInt bits to a double
1307 double bitsToDouble() const {
1312 T.I = (isSingleWord() ? VAL : pVal[0]);
1316 /// The conversion does not do a translation from integer to float, it just
1317 /// re-interprets the bits as a float. Note that it is valid to do this on
1318 /// any bit width. Exactly 32 bits will be translated.
1319 /// @brief Converts APInt bits to a double
1320 float bitsToFloat() const {
1325 T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1329 /// The conversion does not do a translation from double to integer, it just
1330 /// re-interprets the bits of the double.
1331 /// @brief Converts a double to APInt bits.
1332 static APInt doubleToBits(double V) {
1338 return APInt(sizeof T * CHAR_BIT, T.I);
1341 /// The conversion does not do a translation from float to integer, it just
1342 /// re-interprets the bits of the float.
1343 /// @brief Converts a float to APInt bits.
1344 static APInt floatToBits(float V) {
1350 return APInt(sizeof T * CHAR_BIT, T.I);
1354 /// @name Mathematics Operations
1357 /// @returns the floor log base 2 of this APInt.
1358 unsigned logBase2() const {
1359 return BitWidth - 1 - countLeadingZeros();
1362 /// @returns the ceil log base 2 of this APInt.
1363 unsigned ceilLogBase2() const {
1364 return BitWidth - (*this - 1).countLeadingZeros();
1367 /// @returns the log base 2 of this APInt if its an exact power of two, -1
1369 int32_t exactLogBase2() const {
1375 /// @brief Compute the square root
1378 /// If *this is < 0 then return -(*this), otherwise *this;
1379 /// @brief Get the absolute value;
1386 /// @returns the multiplicative inverse for a given modulo.
1387 APInt multiplicativeInverse(const APInt& modulo) const;
1390 /// @name Support for division by constant
1393 /// Calculate the magic number for signed division by a constant.
1397 /// Calculate the magic number for unsigned division by a constant.
1399 mu magicu(unsigned LeadingZeros = 0) const;
1402 /// @name Building-block Operations for APInt and APFloat
1405 // These building block operations operate on a representation of
1406 // arbitrary precision, two's-complement, bignum integer values.
1407 // They should be sufficient to implement APInt and APFloat bignum
1408 // requirements. Inputs are generally a pointer to the base of an
1409 // array of integer parts, representing an unsigned bignum, and a
1410 // count of how many parts there are.
1412 /// Sets the least significant part of a bignum to the input value,
1413 /// and zeroes out higher parts. */
1414 static void tcSet(integerPart *, integerPart, unsigned int);
1416 /// Assign one bignum to another.
1417 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1419 /// Returns true if a bignum is zero, false otherwise.
1420 static bool tcIsZero(const integerPart *, unsigned int);
1422 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1423 static int tcExtractBit(const integerPart *, unsigned int bit);
1425 /// Copy the bit vector of width srcBITS from SRC, starting at bit
1426 /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
1427 /// becomes the least significant bit of DST. All high bits above
1428 /// srcBITS in DST are zero-filled.
1429 static void tcExtract(integerPart *, unsigned int dstCount,
1430 const integerPart *,
1431 unsigned int srcBits, unsigned int srcLSB);
1433 /// Set the given bit of a bignum. Zero-based.
1434 static void tcSetBit(integerPart *, unsigned int bit);
1436 /// Clear the given bit of a bignum. Zero-based.
1437 static void tcClearBit(integerPart *, unsigned int bit);
1439 /// Returns the bit number of the least or most significant set bit
1440 /// of a number. If the input number has no bits set -1U is
1442 static unsigned int tcLSB(const integerPart *, unsigned int);
1443 static unsigned int tcMSB(const integerPart *parts, unsigned int n);
1445 /// Negate a bignum in-place.
1446 static void tcNegate(integerPart *, unsigned int);
1448 /// DST += RHS + CARRY where CARRY is zero or one. Returns the
1450 static integerPart tcAdd(integerPart *, const integerPart *,
1451 integerPart carry, unsigned);
1453 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the
1455 static integerPart tcSubtract(integerPart *, const integerPart *,
1456 integerPart carry, unsigned);
1458 /// DST += SRC * MULTIPLIER + PART if add is true
1459 /// DST = SRC * MULTIPLIER + PART if add is false
1461 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
1462 /// they must start at the same point, i.e. DST == SRC.
1464 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1465 /// returned. Otherwise DST is filled with the least significant
1466 /// DSTPARTS parts of the result, and if all of the omitted higher
1467 /// parts were zero return zero, otherwise overflow occurred and
1469 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1470 integerPart multiplier, integerPart carry,
1471 unsigned int srcParts, unsigned int dstParts,
1474 /// DST = LHS * RHS, where DST has the same width as the operands
1475 /// and is filled with the least significant parts of the result.
1476 /// Returns one if overflow occurred, otherwise zero. DST must be
1477 /// disjoint from both operands.
1478 static int tcMultiply(integerPart *, const integerPart *,
1479 const integerPart *, unsigned);
1481 /// DST = LHS * RHS, where DST has width the sum of the widths of
1482 /// the operands. No overflow occurs. DST must be disjoint from
1483 /// both operands. Returns the number of parts required to hold the
1485 static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1486 const integerPart *, unsigned, unsigned);
1488 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1489 /// Otherwise set LHS to LHS / RHS with the fractional part
1490 /// discarded, set REMAINDER to the remainder, return zero. i.e.
1492 /// OLD_LHS = RHS * LHS + REMAINDER
1494 /// SCRATCH is a bignum of the same size as the operands and result
1495 /// for use by the routine; its contents need not be initialized
1496 /// and are destroyed. LHS, REMAINDER and SCRATCH must be
1498 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1499 integerPart *remainder, integerPart *scratch,
1500 unsigned int parts);
1502 /// Shift a bignum left COUNT bits. Shifted in bits are zero.
1503 /// There are no restrictions on COUNT.
1504 static void tcShiftLeft(integerPart *, unsigned int parts,
1505 unsigned int count);
1507 /// Shift a bignum right COUNT bits. Shifted in bits are zero.
1508 /// There are no restrictions on COUNT.
1509 static void tcShiftRight(integerPart *, unsigned int parts,
1510 unsigned int count);
1512 /// The obvious AND, OR and XOR and complement operations.
1513 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1514 static void tcOr(integerPart *, const integerPart *, unsigned int);
1515 static void tcXor(integerPart *, const integerPart *, unsigned int);
1516 static void tcComplement(integerPart *, unsigned int);
1518 /// Comparison (unsigned) of two bignums.
1519 static int tcCompare(const integerPart *, const integerPart *,
1522 /// Increment a bignum in-place. Return the carry flag.
1523 static integerPart tcIncrement(integerPart *, unsigned int);
1525 /// Set the least significant BITS and clear the rest.
1526 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1529 /// @brief debug method
1535 /// Magic data for optimising signed division by a constant.
1537 APInt m; ///< magic number
1538 unsigned s; ///< shift amount
1541 /// Magic data for optimising unsigned division by a constant.
1543 APInt m; ///< magic number
1544 bool a; ///< add indicator
1545 unsigned s; ///< shift amount
1548 inline bool operator==(uint64_t V1, const APInt& V2) {
1552 inline bool operator!=(uint64_t V1, const APInt& V2) {
1556 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1561 namespace APIntOps {
1563 /// @brief Determine the smaller of two APInts considered to be signed.
1564 inline APInt smin(const APInt &A, const APInt &B) {
1565 return A.slt(B) ? A : B;
1568 /// @brief Determine the larger of two APInts considered to be signed.
1569 inline APInt smax(const APInt &A, const APInt &B) {
1570 return A.sgt(B) ? A : B;
1573 /// @brief Determine the smaller of two APInts considered to be signed.
1574 inline APInt umin(const APInt &A, const APInt &B) {
1575 return A.ult(B) ? A : B;
1578 /// @brief Determine the larger of two APInts considered to be unsigned.
1579 inline APInt umax(const APInt &A, const APInt &B) {
1580 return A.ugt(B) ? A : B;
1583 /// @brief Check if the specified APInt has a N-bits unsigned integer value.
1584 inline bool isIntN(unsigned N, const APInt& APIVal) {
1585 return APIVal.isIntN(N);
1588 /// @brief Check if the specified APInt has a N-bits signed integer value.
1589 inline bool isSignedIntN(unsigned N, const APInt& APIVal) {
1590 return APIVal.isSignedIntN(N);
1593 /// @returns true if the argument APInt value is a sequence of ones
1594 /// starting at the least significant bit with the remainder zero.
1595 inline bool isMask(unsigned numBits, const APInt& APIVal) {
1596 return numBits <= APIVal.getBitWidth() &&
1597 APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
1600 /// @returns true if the argument APInt value contains a sequence of ones
1601 /// with the remainder zero.
1602 inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
1603 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1606 /// @returns a byte-swapped representation of the specified APInt Value.
1607 inline APInt byteSwap(const APInt& APIVal) {
1608 return APIVal.byteSwap();
1611 /// @returns the floor log base 2 of the specified APInt value.
1612 inline unsigned logBase2(const APInt& APIVal) {
1613 return APIVal.logBase2();
1616 /// GreatestCommonDivisor - This function returns the greatest common
1617 /// divisor of the two APInt values using Euclid's algorithm.
1618 /// @returns the greatest common divisor of Val1 and Val2
1619 /// @brief Compute GCD of two APInt values.
1620 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1622 /// Treats the APInt as an unsigned value for conversion purposes.
1623 /// @brief Converts the given APInt to a double value.
1624 inline double RoundAPIntToDouble(const APInt& APIVal) {
1625 return APIVal.roundToDouble();
1628 /// Treats the APInt as a signed value for conversion purposes.
1629 /// @brief Converts the given APInt to a double value.
1630 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1631 return APIVal.signedRoundToDouble();
1634 /// @brief Converts the given APInt to a float vlalue.
1635 inline float RoundAPIntToFloat(const APInt& APIVal) {
1636 return float(RoundAPIntToDouble(APIVal));
1639 /// Treast the APInt as a signed value for conversion purposes.
1640 /// @brief Converts the given APInt to a float value.
1641 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1642 return float(APIVal.signedRoundToDouble());
1645 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1646 /// @brief Converts the given double value into a APInt.
1647 APInt RoundDoubleToAPInt(double Double, unsigned width);
1649 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1650 /// @brief Converts a float value into a APInt.
1651 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
1652 return RoundDoubleToAPInt(double(Float), width);
1655 /// Arithmetic right-shift the APInt by shiftAmt.
1656 /// @brief Arithmetic right-shift function.
1657 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
1658 return LHS.ashr(shiftAmt);
1661 /// Logical right-shift the APInt by shiftAmt.
1662 /// @brief Logical right-shift function.
1663 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
1664 return LHS.lshr(shiftAmt);
1667 /// Left-shift the APInt by shiftAmt.
1668 /// @brief Left-shift function.
1669 inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
1670 return LHS.shl(shiftAmt);
1673 /// Signed divide APInt LHS by APInt RHS.
1674 /// @brief Signed division function for APInt.
1675 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1676 return LHS.sdiv(RHS);
1679 /// Unsigned divide APInt LHS by APInt RHS.
1680 /// @brief Unsigned division function for APInt.
1681 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1682 return LHS.udiv(RHS);
1685 /// Signed remainder operation on APInt.
1686 /// @brief Function for signed remainder operation.
1687 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1688 return LHS.srem(RHS);
1691 /// Unsigned remainder operation on APInt.
1692 /// @brief Function for unsigned remainder operation.
1693 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1694 return LHS.urem(RHS);
1697 /// Performs multiplication on APInt values.
1698 /// @brief Function for multiplication operation.
1699 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1703 /// Performs addition on APInt values.
1704 /// @brief Function for addition operation.
1705 inline APInt add(const APInt& LHS, const APInt& RHS) {
1709 /// Performs subtraction on APInt values.
1710 /// @brief Function for subtraction operation.
1711 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1715 /// Performs bitwise AND operation on APInt LHS and
1717 /// @brief Bitwise AND function for APInt.
1718 inline APInt And(const APInt& LHS, const APInt& RHS) {
1722 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1723 /// @brief Bitwise OR function for APInt.
1724 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1728 /// Performs bitwise XOR operation on APInt.
1729 /// @brief Bitwise XOR function for APInt.
1730 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1734 /// Performs a bitwise complement operation on APInt.
1735 /// @brief Bitwise complement function.
1736 inline APInt Not(const APInt& APIVal) {
1740 } // End of APIntOps namespace
1742 } // End of llvm namespace