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 a word is assigned a value to ensure
111 /// 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 /// This is a constant version.
123 inline uint64_t getWord(uint32_t bitPosition) const {
124 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
127 /// @brief Converts a char array into an integer.
128 void fromString(uint32_t numBits, const char *StrStart, uint32_t slen,
131 /// @brief An internal division function for dividing APInts.
132 static void divide(const APInt LHS, uint32_t lhsWords,
133 const APInt &RHS, uint32_t rhsWords,
134 APInt *Quotient, APInt *Remainder);
137 /// @brief Create a new APInt of numBits bit-width, and initialized as val.
138 APInt(uint32_t numBits, uint64_t val);
140 /// @brief Create a new APInt of numBits bit-width, and initialized as
142 APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
144 /// @brief Create a new APInt by translating the string represented
146 APInt(uint32_t numBits, const std::string& Val, uint8_t radix);
148 /// @brief Create a new APInt by translating the char array represented
150 APInt(uint32_t numBits, const char StrStart[], uint32_t slen, uint8_t radix);
152 /// @brief Copy Constructor.
153 APInt(const APInt& API);
155 /// @brief Destructor.
158 /// @brief Copy assignment operator.
159 APInt& operator=(const APInt& RHS);
161 /// Assigns an integer value to the APInt.
162 /// @brief Assignment operator.
163 APInt& operator=(uint64_t RHS);
165 /// Increments the APInt by one.
166 /// @brief Postfix increment operator.
167 inline const APInt operator++(int) {
173 /// Increments the APInt by one.
174 /// @brief Prefix increment operator.
177 /// Decrements the APInt by one.
178 /// @brief Postfix decrement operator.
179 inline const APInt operator--(int) {
185 /// Decrements the APInt by one.
186 /// @brief Prefix decrement operator.
189 /// Performs bitwise AND operation on this APInt and the given APInt& RHS,
190 /// assigns the result to this APInt.
191 /// @brief Bitwise AND assignment operator.
192 APInt& operator&=(const APInt& RHS);
194 /// Performs bitwise OR operation on this APInt and the given APInt& RHS,
195 /// assigns the result to this APInt.
196 /// @brief Bitwise OR assignment operator.
197 APInt& operator|=(const APInt& RHS);
199 /// Performs bitwise XOR operation on this APInt and the given APInt& RHS,
200 /// assigns the result to this APInt.
201 /// @brief Bitwise XOR assignment operator.
202 APInt& operator^=(const APInt& RHS);
204 /// Performs a bitwise complement operation on this APInt.
205 /// @brief Bitwise complement operator.
206 APInt operator~() const;
208 /// Multiplies this APInt by the given APInt& RHS and
209 /// assigns the result to this APInt.
210 /// @brief Multiplication assignment operator.
211 APInt& operator*=(const APInt& RHS);
213 /// Adds this APInt by the given APInt& RHS and
214 /// assigns the result to this APInt.
215 /// @brief Addition assignment operator.
216 APInt& operator+=(const APInt& RHS);
218 /// Subtracts this APInt by the given APInt &RHS and
219 /// assigns the result to this APInt.
220 /// @brief Subtraction assignment operator.
221 APInt& operator-=(const APInt& RHS);
223 /// Performs bitwise AND operation on this APInt and
224 /// the given APInt& RHS.
225 /// @brief Bitwise AND operator.
226 APInt operator&(const APInt& RHS) const;
228 /// Performs bitwise OR operation on this APInt and the given APInt& RHS.
229 /// @brief Bitwise OR operator.
230 APInt operator|(const APInt& RHS) const;
232 /// Performs bitwise XOR operation on this APInt and the given APInt& RHS.
233 /// @brief Bitwise XOR operator.
234 APInt operator^(const APInt& RHS) const;
236 /// Performs logical negation operation on this APInt.
237 /// @brief Logical negation operator.
238 bool operator !() const;
240 /// Multiplies this APInt by the given APInt& RHS.
241 /// @brief Multiplication operator.
242 APInt operator*(const APInt& RHS) const;
244 /// Adds this APInt by the given APInt& RHS.
245 /// @brief Addition operator.
246 APInt operator+(const APInt& RHS) const;
248 /// Subtracts this APInt by the given APInt& RHS
249 /// @brief Subtraction operator.
250 APInt operator-(const APInt& RHS) const;
252 /// @brief Unary negation operator
253 inline APInt operator-() const {
254 return APInt(BitWidth, 0) - (*this);
257 /// @brief Array-indexing support.
258 bool operator[](uint32_t bitPosition) const;
260 /// Compare this APInt with the given APInt& RHS
261 /// for the validity of the equality relationship.
262 /// @brief Equality operator.
263 bool operator==(const APInt& RHS) const;
265 /// Compare this APInt with the given uint64_t value
266 /// for the validity of the equality relationship.
267 /// @brief Equality operator.
268 bool operator==(uint64_t Val) const;
270 /// Compare this APInt with the given APInt& RHS
271 /// for the validity of the inequality relationship.
272 /// @brief Inequality operator.
273 inline bool operator!=(const APInt& RHS) const {
274 return !((*this) == RHS);
277 /// Compare this APInt with the given uint64_t value
278 /// for the validity of the inequality relationship.
279 /// @brief Inequality operator.
280 inline bool operator!=(uint64_t Val) const {
281 return !((*this) == Val);
284 /// @brief Equality comparison
285 bool eq(const APInt &RHS) const {
286 return (*this) == RHS;
289 /// @brief Inequality comparison
290 bool ne(const APInt &RHS) const {
291 return !((*this) == RHS);
294 /// @brief Unsigned less than comparison
295 bool ult(const APInt& RHS) const;
297 /// @brief Signed less than comparison
298 bool slt(const APInt& RHS) const;
300 /// @brief Unsigned less or equal comparison
301 bool ule(const APInt& RHS) const {
302 return ult(RHS) || eq(RHS);
305 /// @brief Signed less or equal comparison
306 bool sle(const APInt& RHS) const {
307 return slt(RHS) || eq(RHS);
310 /// @brief Unsigned greather than comparison
311 bool ugt(const APInt& RHS) const {
312 return !ult(RHS) && !eq(RHS);
315 /// @brief Signed greather than comparison
316 bool sgt(const APInt& RHS) const {
317 return !slt(RHS) && !eq(RHS);
320 /// @brief Unsigned greater or equal comparison
321 bool uge(const APInt& RHS) const {
325 /// @brief Signed greather or equal comparison
326 bool sge(const APInt& RHS) const {
330 /// Arithmetic right-shift this APInt by shiftAmt.
331 /// @brief Arithmetic right-shift function.
332 APInt ashr(uint32_t shiftAmt) const;
334 /// Logical right-shift this APInt by shiftAmt.
335 /// @brief Logical right-shift function.
336 APInt lshr(uint32_t shiftAmt) const;
338 /// Left-shift this APInt by shiftAmt.
339 /// @brief Left-shift function.
340 APInt shl(uint32_t shiftAmt) const;
342 /// Signed divide this APInt by APInt RHS.
343 /// @brief Signed division function for APInt.
344 inline APInt sdiv(const APInt& RHS) const {
345 bool isNegativeLHS = (*this)[BitWidth - 1];
346 bool isNegativeRHS = RHS[RHS.BitWidth - 1];
347 APInt Result = APIntOps::udiv(
348 isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
349 return isNegativeLHS != isNegativeRHS ? -Result : Result;
352 /// Unsigned divide this APInt by APInt RHS.
353 /// @brief Unsigned division function for APInt.
354 APInt udiv(const APInt& RHS) const;
356 /// Signed remainder operation on APInt.
357 /// @brief Function for signed remainder operation.
358 inline APInt srem(const APInt& RHS) const {
359 bool isNegativeLHS = (*this)[BitWidth - 1];
360 bool isNegativeRHS = RHS[RHS.BitWidth - 1];
361 APInt Result = APIntOps::urem(
362 isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
363 return isNegativeLHS ? -Result : Result;
366 /// Unsigned remainder operation on APInt.
367 /// @brief Function for unsigned remainder operation.
368 APInt urem(const APInt& RHS) const;
370 /// Truncate the APInt to a specified width. It is an error to specify a width
371 /// that is greater than or equal to the current width.
372 /// @brief Truncate to new width.
373 void trunc(uint32_t width);
375 /// This operation sign extends the APInt to a new width. If the high order
376 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
377 /// It is an error to specify a width that is less than or equal to the
379 /// @brief Sign extend to a new width.
380 void sext(uint32_t width);
382 /// This operation zero extends the APInt to a new width. Thie high order bits
383 /// are filled with 0 bits. It is an error to specify a width that is less
384 /// than or equal to the current width.
385 /// @brief Zero extend to a new width.
386 void zext(uint32_t width);
388 /// @brief Set every bit to 1.
391 /// Set the given bit to 1 whose position is given as "bitPosition".
392 /// @brief Set a given bit to 1.
393 APInt& set(uint32_t bitPosition);
395 /// @brief Set every bit to 0.
398 /// Set the given bit to 0 whose position is given as "bitPosition".
399 /// @brief Set a given bit to 0.
400 APInt& clear(uint32_t bitPosition);
402 /// @brief Toggle every bit to its opposite value.
405 /// Toggle a given bit to its opposite value whose position is given
406 /// as "bitPosition".
407 /// @brief Toggles a given bit to its opposite value.
408 APInt& flip(uint32_t bitPosition);
410 /// This function returns the number of active bits which is defined as the
411 /// bit width minus the number of leading zeros. This is used in several
412 /// computations to see how "wide" the value is.
413 /// @brief Compute the number of active bits in the value
414 inline uint32_t getActiveBits() const {
415 return getNumWords() * APINT_BITS_PER_WORD - countLeadingZeros();
418 /// @returns a uint64_t value from this APInt. If this APInt contains a single
419 /// word, just returns VAL, otherwise pVal[0].
420 inline uint64_t getValue(bool isSigned = false) const {
422 return isSigned ? int64_t(VAL << (64 - BitWidth)) >>
423 (64 - BitWidth) : VAL;
424 uint32_t n = getActiveBits();
427 assert(0 && "This APInt's bitwidth > 64");
430 /// @returns the largest value for an APInt of the specified bit-width and
431 /// if isSign == true, it should be largest signed value, otherwise largest
433 /// @brief Gets max value of the APInt with bitwidth <= 64.
434 static APInt getMaxValue(uint32_t numBits, bool isSign);
436 /// @returns the smallest value for an APInt of the given bit-width and
437 /// if isSign == true, it should be smallest signed value, otherwise zero.
438 /// @brief Gets min value of the APInt with bitwidth <= 64.
439 static APInt getMinValue(uint32_t numBits, bool isSign);
441 /// @returns the all-ones value for an APInt of the specified bit-width.
442 /// @brief Get the all-ones value.
443 static APInt getAllOnesValue(uint32_t numBits);
445 /// @returns the '0' value for an APInt of the specified bit-width.
446 /// @brief Get the '0' value.
447 static APInt getNullValue(uint32_t numBits);
449 /// This converts the APInt to a boolean valy as a test against zero.
450 /// @brief Boolean conversion function.
451 inline bool getBoolValue() const {
452 return countLeadingZeros() != BitWidth;
455 /// @returns a character interpretation of the APInt.
456 std::string toString(uint8_t radix = 10, bool wantSigned = true) const;
458 /// Get an APInt with the same BitWidth as this APInt, just zero mask
459 /// the low bits and right shift to the least significant bit.
460 /// @returns the high "numBits" bits of this APInt.
461 APInt getHiBits(uint32_t numBits) const;
463 /// Get an APInt with the same BitWidth as this APInt, just zero mask
465 /// @returns the low "numBits" bits of this APInt.
466 APInt getLoBits(uint32_t numBits) const;
468 /// @returns true if the argument APInt value is a power of two > 0.
469 bool isPowerOf2() const;
471 /// @returns the number of zeros from the most significant bit to the first
473 uint32_t countLeadingZeros() const;
475 /// @returns the number of zeros from the least significant bit to the first
477 uint32_t countTrailingZeros() const;
479 /// @returns the number of set bits.
480 uint32_t countPopulation() const;
482 /// @returns the total number of bits.
483 inline uint32_t getBitWidth() const {
487 /// @brief Check if this APInt has a N-bits integer value.
488 inline bool isIntN(uint32_t N) const {
489 assert(N && "N == 0 ???");
490 if (isSingleWord()) {
491 return VAL == (VAL & (~0ULL >> (64 - N)));
493 APInt Tmp(N, getNumWords(), pVal);
494 return Tmp == (*this);
498 /// @returns a byte-swapped representation of this APInt Value.
499 APInt byteSwap() const;
501 /// @returns the floor log base 2 of this APInt.
502 inline uint32_t logBase2() const {
503 return getNumWords() * APINT_BITS_PER_WORD - 1 - countLeadingZeros();
506 /// @brief Converts this APInt to a double value.
507 double roundToDouble(bool isSigned = false) const;
513 /// @brief Check if the specified APInt has a N-bits integer value.
514 inline bool isIntN(uint32_t N, const APInt& APIVal) {
515 return APIVal.isIntN(N);
518 /// @returns true if the argument APInt value is a sequence of ones
519 /// starting at the least significant bit with the remainder zero.
520 inline const bool isMask(uint32_t numBits, const APInt& APIVal) {
521 return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
524 /// @returns true if the argument APInt value contains a sequence of ones
525 /// with the remainder zero.
526 inline const bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
527 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
530 /// @returns a byte-swapped representation of the specified APInt Value.
531 inline APInt byteSwap(const APInt& APIVal) {
532 return APIVal.byteSwap();
535 /// @returns the floor log base 2 of the specified APInt value.
536 inline uint32_t logBase2(const APInt& APIVal) {
537 return APIVal.logBase2();
540 /// @returns the greatest common divisor of the two values
541 /// using Euclid's algorithm.
542 APInt GreatestCommonDivisor(const APInt& API1, const APInt& API2);
544 /// @brief Converts the given APInt to a double value.
545 inline double RoundAPIntToDouble(const APInt& APIVal, bool isSigned = false) {
546 return APIVal.roundToDouble(isSigned);
549 /// @brief Converts the given APInt to a float vlalue.
550 inline float RoundAPIntToFloat(const APInt& APIVal) {
551 return float(RoundAPIntToDouble(APIVal));
554 /// @brief Converts the given double value into a APInt.
555 APInt RoundDoubleToAPInt(double Double);
557 /// @brief Converts the given float value into a APInt.
558 inline APInt RoundFloatToAPInt(float Float) {
559 return RoundDoubleToAPInt(double(Float));
562 /// Arithmetic right-shift the APInt by shiftAmt.
563 /// @brief Arithmetic right-shift function.
564 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
565 return LHS.ashr(shiftAmt);
568 /// Logical right-shift the APInt by shiftAmt.
569 /// @brief Logical right-shift function.
570 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
571 return LHS.lshr(shiftAmt);
574 /// Left-shift the APInt by shiftAmt.
575 /// @brief Left-shift function.
576 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
577 return LHS.shl(shiftAmt);
580 /// Signed divide APInt LHS by APInt RHS.
581 /// @brief Signed division function for APInt.
582 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
583 return LHS.sdiv(RHS);
586 /// Unsigned divide APInt LHS by APInt RHS.
587 /// @brief Unsigned division function for APInt.
588 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
589 return LHS.udiv(RHS);
592 /// Signed remainder operation on APInt.
593 /// @brief Function for signed remainder operation.
594 inline APInt srem(const APInt& LHS, const APInt& RHS) {
595 return LHS.srem(RHS);
598 /// Unsigned remainder operation on APInt.
599 /// @brief Function for unsigned remainder operation.
600 inline APInt urem(const APInt& LHS, const APInt& RHS) {
601 return LHS.urem(RHS);
604 /// Performs multiplication on APInt values.
605 /// @brief Function for multiplication operation.
606 inline APInt mul(const APInt& LHS, const APInt& RHS) {
610 /// Performs addition on APInt values.
611 /// @brief Function for addition operation.
612 inline APInt add(const APInt& LHS, const APInt& RHS) {
616 /// Performs subtraction on APInt values.
617 /// @brief Function for subtraction operation.
618 inline APInt sub(const APInt& LHS, const APInt& RHS) {
622 /// Performs bitwise AND operation on APInt LHS and
624 /// @brief Bitwise AND function for APInt.
625 inline APInt And(const APInt& LHS, const APInt& RHS) {
629 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
630 /// @brief Bitwise OR function for APInt.
631 inline APInt Or(const APInt& LHS, const APInt& RHS) {
635 /// Performs bitwise XOR operation on APInt.
636 /// @brief Bitwise XOR function for APInt.
637 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
641 /// Performs a bitwise complement operation on APInt.
642 /// @brief Bitwise complement function.
643 inline APInt Not(const APInt& APIVal) {
647 } // End of APIntOps namespace
649 } // End of llvm namespace