1 //===-- llvm/Support/APInt.h - For Arbitrary Precision Integer -*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Sheng Zhou and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a class to represent arbitrary precision integral
13 //===----------------------------------------------------------------------===//
18 #include "llvm/Support/DataTypes.h"
24 /// Forward declaration.
27 APInt udiv(const APInt& LHS, const APInt& RHS);
28 APInt urem(const APInt& LHS, const APInt& RHS);
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 /// APInt - This class represents arbitrary precision constant integral values.
36 /// It is a functional replacement for common case unsigned integer type like
37 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
38 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
39 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
40 /// and methods to manipulate integer values of any bit-width. It supports both
41 /// the typical integer arithmetic and comparison operations as well as bitwise
44 /// The class has several invariants worth noting:
45 /// * All bit, byte, and word positions are zero-based.
46 /// * Once the bit width is set, it doesn't change except by the Truncate,
47 /// SignExtend, or ZeroExtend operations.
48 /// * All binary operators must be on APInt instances of the same bit width.
49 /// Attempting to use these operators on instances with different bit
50 /// widths will yield an assertion.
51 /// * The value is stored canonically as an unsigned value. For operations
52 /// where it makes a difference, there are both signed and unsigned variants
53 /// of the operation. For example, sdiv and udiv. However, because the bit
54 /// widths must be the same, operations such as Mul and Add produce the same
55 /// results regardless of whether the values are interpreted as signed or
57 /// * In general, the class tries to follow the style of computation that LLVM
58 /// uses in its IR. This simplifies its use for LLVM.
60 /// @brief Class for arbitrary precision integers.
63 uint32_t BitWidth; ///< The number of bits in this APInt.
65 /// This union is used to store the integer value. When the
66 /// integer bit-width <= 64, it uses VAL;
67 /// otherwise it uses the pVal.
69 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
70 uint64_t *pVal; ///< Used to store the >64 bits integer value.
73 /// This enum is just used to hold a constant we needed for APInt.
75 APINT_BITS_PER_WORD = sizeof(uint64_t) * 8,
76 APINT_WORD_SIZE = sizeof(uint64_t)
79 /// Here one word's bitwidth equals to that of uint64_t.
80 /// @returns the number of words to hold the integer value of this APInt.
81 /// @brief Get the number of words.
82 inline uint32_t getNumWords() const {
83 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
86 /// @returns true if the number of bits <= 64, false otherwise.
87 /// @brief Determine if this APInt just has one word to store value.
88 inline bool isSingleWord() const {
89 return BitWidth <= APINT_BITS_PER_WORD;
92 /// @returns the word position for the specified bit position.
93 static inline uint32_t whichWord(uint32_t bitPosition) {
94 return bitPosition / APINT_BITS_PER_WORD;
97 /// @returns the bit position in a word for the specified bit position
99 static inline uint32_t whichBit(uint32_t bitPosition) {
100 return bitPosition % APINT_BITS_PER_WORD;
103 /// @returns a uint64_t type integer with just bit position at
104 /// "whichBit(bitPosition)" setting, others zero.
105 static inline uint64_t maskBit(uint32_t bitPosition) {
106 return (static_cast<uint64_t>(1)) << whichBit(bitPosition);
109 /// This method is used internally to clear the to "N" bits that are not used
110 /// by the APInt. This is needed after the most significant word is assigned
111 /// a value to ensure that those bits are zero'd out.
112 /// @brief Clear high order bits
113 inline void clearUnusedBits() {
115 VAL &= ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth);
117 pVal[getNumWords() - 1] &= ~uint64_t(0ULL) >>
118 (APINT_BITS_PER_WORD - (whichBit(BitWidth - 1) + 1));
121 /// @returns the corresponding word for the specified bit position.
122 /// @brief Get the word corresponding to a bit position
123 inline uint64_t getWord(uint32_t bitPosition) const {
124 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
127 /// This is used by the constructors that take string arguments.
128 /// @brief Converts a char array into an APInt
129 void fromString(uint32_t numBits, const char *StrStart, uint32_t slen,
132 /// This is used by the toString method to divide by the radix. It simply
133 /// provides a more convenient form of divide for internal use.
134 /// @brief An internal division function for dividing APInts.
135 static void divide(const APInt LHS, uint32_t lhsWords,
136 const APInt &RHS, uint32_t rhsWords,
137 APInt *Quotient, APInt *Remainder);
140 /// @brief debug method
145 /// @brief Create a new APInt of numBits width, initialized as val.
146 APInt(uint32_t numBits, uint64_t val);
148 /// Note that numWords can be smaller or larger than the corresponding bit
149 /// width but any extraneous bits will be dropped.
150 /// @brief Create a new APInt of numBits width, initialized as bigVal[].
151 APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
153 /// @brief Create a new APInt by translating the string represented
155 APInt(uint32_t numBits, const std::string& Val, uint8_t radix);
157 /// @brief Create a new APInt by translating the char array represented
159 APInt(uint32_t numBits, const char StrStart[], uint32_t slen, uint8_t radix);
161 /// @brief Copy Constructor.
162 APInt(const APInt& API);
164 /// @brief Destructor.
167 /// @brief Copy assignment operator.
168 APInt& operator=(const APInt& RHS);
170 /// Assigns an integer value to the APInt.
171 /// @brief Assignment operator.
172 APInt& operator=(uint64_t RHS);
174 /// Increments the APInt by one.
175 /// @brief Postfix increment operator.
176 inline const APInt operator++(int) {
182 /// Increments the APInt by one.
183 /// @brief Prefix increment operator.
186 /// Decrements the APInt by one.
187 /// @brief Postfix decrement operator.
188 inline const APInt operator--(int) {
194 /// Decrements the APInt by one.
195 /// @brief Prefix decrement operator.
198 /// Performs bitwise AND operation on this APInt and the given APInt& RHS,
199 /// assigns the result to this APInt.
200 /// @brief Bitwise AND assignment operator.
201 APInt& operator&=(const APInt& RHS);
203 /// Performs bitwise OR operation on this APInt and the given APInt& RHS,
204 /// assigns the result to this APInt.
205 /// @brief Bitwise OR assignment operator.
206 APInt& operator|=(const APInt& RHS);
208 /// Performs bitwise XOR operation on this APInt and the given APInt& RHS,
209 /// assigns the result to this APInt.
210 /// @brief Bitwise XOR assignment operator.
211 APInt& operator^=(const APInt& RHS);
213 /// Performs a bitwise complement operation on this APInt.
214 /// @brief Bitwise complement operator.
215 APInt operator~() const;
217 /// Multiplies this APInt by the given APInt& RHS and
218 /// assigns the result to this APInt.
219 /// @brief Multiplication assignment operator.
220 APInt& operator*=(const APInt& RHS);
222 /// Adds this APInt by the given APInt& RHS and
223 /// assigns the result to this APInt.
224 /// @brief Addition assignment operator.
225 APInt& operator+=(const APInt& RHS);
227 /// Subtracts this APInt by the given APInt &RHS and
228 /// assigns the result to this APInt.
229 /// @brief Subtraction assignment operator.
230 APInt& operator-=(const APInt& RHS);
232 /// Performs bitwise AND operation on this APInt and
233 /// the given APInt& RHS.
234 /// @brief Bitwise AND operator.
235 APInt operator&(const APInt& RHS) const;
237 /// Performs bitwise OR operation on this APInt and the given APInt& RHS.
238 /// @brief Bitwise OR operator.
239 APInt operator|(const APInt& RHS) const;
241 /// Performs bitwise XOR operation on this APInt and the given APInt& RHS.
242 /// @brief Bitwise XOR operator.
243 APInt operator^(const APInt& RHS) const;
245 /// Performs logical negation operation on this APInt.
246 /// @brief Logical negation operator.
247 bool operator !() const;
249 /// Multiplies this APInt by the given APInt& RHS.
250 /// @brief Multiplication operator.
251 APInt operator*(const APInt& RHS) const;
253 /// Adds this APInt by the given APInt& RHS.
254 /// @brief Addition operator.
255 APInt operator+(const APInt& RHS) const;
257 /// Subtracts this APInt by the given APInt& RHS
258 /// @brief Subtraction operator.
259 APInt operator-(const APInt& RHS) const;
261 /// @brief Unary negation operator
262 inline APInt operator-() const {
263 return APInt(BitWidth, 0) - (*this);
266 /// @brief Array-indexing support.
267 bool operator[](uint32_t bitPosition) const;
269 /// Compare this APInt with the given APInt& RHS
270 /// for the validity of the equality relationship.
271 /// @brief Equality operator.
272 bool operator==(const APInt& RHS) const;
274 /// Compare this APInt with the given uint64_t value
275 /// for the validity of the equality relationship.
276 /// @brief Equality operator.
277 bool operator==(uint64_t Val) const;
279 /// Compare this APInt with the given APInt& RHS
280 /// for the validity of the inequality relationship.
281 /// @brief Inequality operator.
282 inline bool operator!=(const APInt& RHS) const {
283 return !((*this) == RHS);
286 /// Compare this APInt with the given uint64_t value
287 /// for the validity of the inequality relationship.
288 /// @brief Inequality operator.
289 inline bool operator!=(uint64_t Val) const {
290 return !((*this) == Val);
293 /// @brief Equality comparison
294 bool eq(const APInt &RHS) const {
295 return (*this) == RHS;
298 /// @brief Inequality comparison
299 bool ne(const APInt &RHS) const {
300 return !((*this) == RHS);
303 /// @brief Unsigned less than comparison
304 bool ult(const APInt& RHS) const;
306 /// @brief Signed less than comparison
307 bool slt(const APInt& RHS) const;
309 /// @brief Unsigned less or equal comparison
310 bool ule(const APInt& RHS) const {
311 return ult(RHS) || eq(RHS);
314 /// @brief Signed less or equal comparison
315 bool sle(const APInt& RHS) const {
316 return slt(RHS) || eq(RHS);
319 /// @brief Unsigned greather than comparison
320 bool ugt(const APInt& RHS) const {
321 return !ult(RHS) && !eq(RHS);
324 /// @brief Signed greather than comparison
325 bool sgt(const APInt& RHS) const {
326 return !slt(RHS) && !eq(RHS);
329 /// @brief Unsigned greater or equal comparison
330 bool uge(const APInt& RHS) const {
334 /// @brief Signed greather or equal comparison
335 bool sge(const APInt& RHS) const {
339 /// Arithmetic right-shift this APInt by shiftAmt.
340 /// @brief Arithmetic right-shift function.
341 APInt ashr(uint32_t shiftAmt) const;
343 /// Logical right-shift this APInt by shiftAmt.
344 /// @brief Logical right-shift function.
345 APInt lshr(uint32_t shiftAmt) const;
347 /// Left-shift this APInt by shiftAmt.
348 /// @brief Left-shift function.
349 APInt shl(uint32_t shiftAmt) const;
351 /// Signed divide this APInt by APInt RHS.
352 /// @brief Signed division function for APInt.
353 inline APInt sdiv(const APInt& RHS) const {
354 bool isNegativeLHS = (*this)[BitWidth - 1];
355 bool isNegativeRHS = RHS[RHS.BitWidth - 1];
356 APInt Result = APIntOps::udiv(
357 isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
358 return isNegativeLHS != isNegativeRHS ? -Result : Result;
361 /// Unsigned divide this APInt by APInt RHS.
362 /// @brief Unsigned division function for APInt.
363 APInt udiv(const APInt& RHS) const;
365 /// Signed remainder operation on APInt.
366 /// @brief Function for signed remainder operation.
367 inline APInt srem(const APInt& RHS) const {
368 bool isNegativeLHS = (*this)[BitWidth - 1];
369 bool isNegativeRHS = RHS[RHS.BitWidth - 1];
370 APInt Result = APIntOps::urem(
371 isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
372 return isNegativeLHS ? -Result : Result;
375 /// Unsigned remainder operation on APInt.
376 /// @brief Function for unsigned remainder operation.
377 APInt urem(const APInt& RHS) const;
379 /// Truncate the APInt to a specified width. It is an error to specify a width
380 /// that is greater than or equal to the current width.
381 /// @brief Truncate to new width.
382 void trunc(uint32_t width);
384 /// This operation sign extends the APInt to a new width. If the high order
385 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
386 /// It is an error to specify a width that is less than or equal to the
388 /// @brief Sign extend to a new width.
389 void sext(uint32_t width);
391 /// This operation zero extends the APInt to a new width. Thie high order bits
392 /// are filled with 0 bits. It is an error to specify a width that is less
393 /// than or equal to the current width.
394 /// @brief Zero extend to a new width.
395 void zext(uint32_t width);
397 /// @brief Set every bit to 1.
400 /// Set the given bit to 1 whose position is given as "bitPosition".
401 /// @brief Set a given bit to 1.
402 APInt& set(uint32_t bitPosition);
404 /// @brief Set every bit to 0.
407 /// Set the given bit to 0 whose position is given as "bitPosition".
408 /// @brief Set a given bit to 0.
409 APInt& clear(uint32_t bitPosition);
411 /// @brief Toggle every bit to its opposite value.
414 /// Toggle a given bit to its opposite value whose position is given
415 /// as "bitPosition".
416 /// @brief Toggles a given bit to its opposite value.
417 APInt& flip(uint32_t bitPosition);
419 /// This function returns the number of active bits which is defined as the
420 /// bit width minus the number of leading zeros. This is used in several
421 /// computations to see how "wide" the value is.
422 /// @brief Compute the number of active bits in the value
423 inline uint32_t getActiveBits() const {
424 return BitWidth - countLeadingZeros();
427 /// @returns a uint64_t value from this APInt. If this APInt contains a single
428 /// word, just returns VAL, otherwise pVal[0].
429 inline uint64_t getValue(bool isSigned = false) const {
431 return isSigned ? int64_t(VAL << (64 - BitWidth)) >>
432 (64 - BitWidth) : VAL;
433 uint32_t n = getActiveBits();
436 assert(0 && "This APInt's bitwidth > 64");
439 /// @returns the largest value for an APInt of the specified bit-width and
440 /// if isSign == true, it should be largest signed value, otherwise largest
442 /// @brief Gets max value of the APInt with bitwidth <= 64.
443 static APInt getMaxValue(uint32_t numBits, bool isSign);
445 /// @returns the smallest value for an APInt of the given bit-width and
446 /// if isSign == true, it should be smallest signed value, otherwise zero.
447 /// @brief Gets min value of the APInt with bitwidth <= 64.
448 static APInt getMinValue(uint32_t numBits, bool isSign);
450 /// @returns the all-ones value for an APInt of the specified bit-width.
451 /// @brief Get the all-ones value.
452 static APInt getAllOnesValue(uint32_t numBits);
454 /// @returns the '0' value for an APInt of the specified bit-width.
455 /// @brief Get the '0' value.
456 static APInt getNullValue(uint32_t numBits);
458 /// This converts the APInt to a boolean valy as a test against zero.
459 /// @brief Boolean conversion function.
460 inline bool getBoolValue() const {
461 return countLeadingZeros() != BitWidth;
464 /// @returns a character interpretation of the APInt.
465 std::string toString(uint8_t radix = 10, bool wantSigned = true) const;
467 /// Get an APInt with the same BitWidth as this APInt, just zero mask
468 /// the low bits and right shift to the least significant bit.
469 /// @returns the high "numBits" bits of this APInt.
470 APInt getHiBits(uint32_t numBits) const;
472 /// Get an APInt with the same BitWidth as this APInt, just zero mask
474 /// @returns the low "numBits" bits of this APInt.
475 APInt getLoBits(uint32_t numBits) const;
477 /// @returns true if the argument APInt value is a power of two > 0.
478 bool isPowerOf2() const;
480 /// @returns the number of zeros from the most significant bit to the first
482 uint32_t countLeadingZeros() const;
484 /// @returns the number of zeros from the least significant bit to the first
486 uint32_t countTrailingZeros() const;
488 /// @returns the number of set bits.
489 uint32_t countPopulation() const;
491 /// @returns the total number of bits.
492 inline uint32_t getBitWidth() const {
496 /// @brief Check if this APInt has a N-bits integer value.
497 inline bool isIntN(uint32_t N) const {
498 assert(N && "N == 0 ???");
499 if (isSingleWord()) {
500 return VAL == (VAL & (~0ULL >> (64 - N)));
502 APInt Tmp(N, getNumWords(), pVal);
503 return Tmp == (*this);
507 /// @returns a byte-swapped representation of this APInt Value.
508 APInt byteSwap() const;
510 /// @returns the floor log base 2 of this APInt.
511 inline uint32_t logBase2() const {
512 return getNumWords() * APINT_BITS_PER_WORD - 1 - countLeadingZeros();
515 /// @brief Converts this APInt to a double value.
516 double roundToDouble(bool isSigned = false) const;
522 /// @brief Check if the specified APInt has a N-bits integer value.
523 inline bool isIntN(uint32_t N, const APInt& APIVal) {
524 return APIVal.isIntN(N);
527 /// @returns true if the argument APInt value is a sequence of ones
528 /// starting at the least significant bit with the remainder zero.
529 inline const bool isMask(uint32_t numBits, const APInt& APIVal) {
530 return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
533 /// @returns true if the argument APInt value contains a sequence of ones
534 /// with the remainder zero.
535 inline const bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
536 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
539 /// @returns a byte-swapped representation of the specified APInt Value.
540 inline APInt byteSwap(const APInt& APIVal) {
541 return APIVal.byteSwap();
544 /// @returns the floor log base 2 of the specified APInt value.
545 inline uint32_t logBase2(const APInt& APIVal) {
546 return APIVal.logBase2();
549 /// @returns the greatest common divisor of the two values
550 /// using Euclid's algorithm.
551 APInt GreatestCommonDivisor(const APInt& API1, const APInt& API2);
553 /// @brief Converts the given APInt to a double value.
554 inline double RoundAPIntToDouble(const APInt& APIVal, bool isSigned = false) {
555 return APIVal.roundToDouble(isSigned);
558 /// @brief Converts the given APInt to a float vlalue.
559 inline float RoundAPIntToFloat(const APInt& APIVal) {
560 return float(RoundAPIntToDouble(APIVal));
563 /// @brief Converts the given double value into a APInt.
564 APInt RoundDoubleToAPInt(double Double);
566 /// @brief Converts the given float value into a APInt.
567 inline APInt RoundFloatToAPInt(float Float) {
568 return RoundDoubleToAPInt(double(Float));
571 /// Arithmetic right-shift the APInt by shiftAmt.
572 /// @brief Arithmetic right-shift function.
573 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
574 return LHS.ashr(shiftAmt);
577 /// Logical right-shift the APInt by shiftAmt.
578 /// @brief Logical right-shift function.
579 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
580 return LHS.lshr(shiftAmt);
583 /// Left-shift the APInt by shiftAmt.
584 /// @brief Left-shift function.
585 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
586 return LHS.shl(shiftAmt);
589 /// Signed divide APInt LHS by APInt RHS.
590 /// @brief Signed division function for APInt.
591 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
592 return LHS.sdiv(RHS);
595 /// Unsigned divide APInt LHS by APInt RHS.
596 /// @brief Unsigned division function for APInt.
597 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
598 return LHS.udiv(RHS);
601 /// Signed remainder operation on APInt.
602 /// @brief Function for signed remainder operation.
603 inline APInt srem(const APInt& LHS, const APInt& RHS) {
604 return LHS.srem(RHS);
607 /// Unsigned remainder operation on APInt.
608 /// @brief Function for unsigned remainder operation.
609 inline APInt urem(const APInt& LHS, const APInt& RHS) {
610 return LHS.urem(RHS);
613 /// Performs multiplication on APInt values.
614 /// @brief Function for multiplication operation.
615 inline APInt mul(const APInt& LHS, const APInt& RHS) {
619 /// Performs addition on APInt values.
620 /// @brief Function for addition operation.
621 inline APInt add(const APInt& LHS, const APInt& RHS) {
625 /// Performs subtraction on APInt values.
626 /// @brief Function for subtraction operation.
627 inline APInt sub(const APInt& LHS, const APInt& RHS) {
631 /// Performs bitwise AND operation on APInt LHS and
633 /// @brief Bitwise AND function for APInt.
634 inline APInt And(const APInt& LHS, const APInt& RHS) {
638 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
639 /// @brief Bitwise OR function for APInt.
640 inline APInt Or(const APInt& LHS, const APInt& RHS) {
644 /// Performs bitwise XOR operation on APInt.
645 /// @brief Bitwise XOR function for APInt.
646 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
650 /// Performs a bitwise complement operation on APInt.
651 /// @brief Bitwise complement function.
652 inline APInt Not(const APInt& APIVal) {
656 } // End of APIntOps namespace
658 } // End of llvm namespace