Home | History | Annotate | Download | only in ADT
      1 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements a class to represent arbitrary precision integral
     11 // constant values and operations on them.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_APINT_H
     16 #define LLVM_APINT_H
     17 
     18 #include "llvm/ADT/ArrayRef.h"
     19 #include "llvm/Support/MathExtras.h"
     20 #include <cassert>
     21 #include <climits>
     22 #include <cstring>
     23 #include <string>
     24 
     25 namespace llvm {
     26   class Serializer;
     27   class Deserializer;
     28   class FoldingSetNodeID;
     29   class raw_ostream;
     30   class StringRef;
     31 
     32   template<typename T>
     33   class SmallVectorImpl;
     34 
     35   // An unsigned host type used as a single part of a multi-part
     36   // bignum.
     37   typedef uint64_t integerPart;
     38 
     39   const unsigned int host_char_bit = 8;
     40   const unsigned int integerPartWidth = host_char_bit *
     41     static_cast<unsigned int>(sizeof(integerPart));
     42 
     43 //===----------------------------------------------------------------------===//
     44 //                              APInt Class
     45 //===----------------------------------------------------------------------===//
     46 
     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
     54 /// manipulation.
     55 ///
     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
     68 ///     not.
     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.
     71 ///
     72 /// @brief Class for arbitrary precision integers.
     73 class APInt {
     74   unsigned BitWidth;      ///< The number of bits in this APInt.
     75 
     76   /// This union is used to store the integer value. When the
     77   /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
     78   union {
     79     uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
     80     uint64_t *pVal;  ///< Used to store the >64 bits integer value.
     81   };
     82 
     83   /// This enum is used to hold the constants we needed for APInt.
     84   enum {
     85     /// Bits in a word
     86     APINT_BITS_PER_WORD = static_cast<unsigned int>(sizeof(uint64_t)) *
     87                           CHAR_BIT,
     88     /// Byte size of a word
     89     APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t))
     90   };
     91 
     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) { }
     96 
     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;
    101   }
    102 
    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;
    107   }
    108 
    109   /// @returns the bit position in a word for the specified bit position
    110   /// in the APInt.
    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;
    114   }
    115 
    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);
    123   }
    124 
    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
    128   /// zero'd out.
    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;
    133     if (wordBits == 0)
    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).
    137       return *this;
    138 
    139     // Mask out the high bits.
    140     uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
    141     if (isSingleWord())
    142       VAL &= mask;
    143     else
    144       pVal[getNumWords() - 1] &= mask;
    145     return *this;
    146   }
    147 
    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)];
    152   }
    153 
    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.
    157   ///
    158   /// This is used by the constructors that take string arguments.
    159   ///
    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.
    163   ///
    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);
    167 
    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);
    176 
    177   /// out-of-line slow case for inline constructor
    178   void initSlowCase(unsigned numBits, uint64_t val, bool isSigned);
    179 
    180   /// shared code between two array constructors
    181   void initFromArray(ArrayRef<uint64_t> array);
    182 
    183   /// out-of-line slow case for inline copy constructor
    184   void initSlowCase(const APInt& that);
    185 
    186   /// out-of-line slow case for shl
    187   APInt shlSlowCase(unsigned shiftAmt) const;
    188 
    189   /// out-of-line slow case for operator&
    190   APInt AndSlowCase(const APInt& RHS) const;
    191 
    192   /// out-of-line slow case for operator|
    193   APInt OrSlowCase(const APInt& RHS) const;
    194 
    195   /// out-of-line slow case for operator^
    196   APInt XorSlowCase(const APInt& RHS) const;
    197 
    198   /// out-of-line slow case for operator=
    199   APInt& AssignSlowCase(const APInt& RHS);
    200 
    201   /// out-of-line slow case for operator==
    202   bool EqualSlowCase(const APInt& RHS) const;
    203 
    204   /// out-of-line slow case for operator==
    205   bool EqualSlowCase(uint64_t Val) const;
    206 
    207   /// out-of-line slow case for countLeadingZeros
    208   unsigned countLeadingZerosSlowCase() const;
    209 
    210   /// out-of-line slow case for countTrailingOnes
    211   unsigned countTrailingOnesSlowCase() const;
    212 
    213   /// out-of-line slow case for countPopulation
    214   unsigned countPopulationSlowCase() const;
    215 
    216 public:
    217   /// @name Constructors
    218   /// @{
    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");
    230     if (isSingleWord())
    231       VAL = val;
    232     else
    233       initSlowCase(numBits, val, isSigned);
    234     clearUnusedBits();
    235   }
    236 
    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.
    246   ///
    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)
    249   /// constructor.
    250   APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
    251 
    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.
    257   ///
    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);
    263 
    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");
    269     if (isSingleWord())
    270       VAL = that.VAL;
    271     else
    272       initSlowCase(that);
    273   }
    274 
    275   /// @brief Destructor.
    276   ~APInt() {
    277     if (!isSingleWord())
    278       delete [] pVal;
    279   }
    280 
    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) {}
    284 
    285   /// Profile - Used to insert APInt objects, or objects that contain APInt
    286   ///  objects, into FoldingSets.
    287   void Profile(FoldingSetNodeID& id) const;
    288 
    289   /// @}
    290   /// @name Value Tests
    291   /// @{
    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];
    297   }
    298 
    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();
    303   }
    304 
    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;
    311   }
    312 
    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;
    317   }
    318 
    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;
    324   }
    325 
    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;
    332   }
    333 
    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 {
    338     return !*this;
    339   }
    340 
    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();
    346   }
    347 
    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())
    352       return true;
    353 
    354     if (isSingleWord())
    355       return isUIntN(N, VAL);
    356     return APInt(N, makeArrayRef(pVal, getNumWords())).zext(getBitWidth())
    357       == (*this);
    358   }
    359 
    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;
    364   }
    365 
    366   /// @returns true if the argument APInt value is a power of two > 0.
    367   bool isPowerOf2() const {
    368     if (isSingleWord())
    369       return isPowerOf2_64(VAL);
    370     return countPopulationSlowCase() == 1;
    371   }
    372 
    373   /// isSignBit - Return true if this is the value returned by getSignBit.
    374   bool isSignBit() const { return isMinSignedValue(); }
    375 
    376   /// This converts the APInt to a boolean value as a test against zero.
    377   /// @brief Boolean conversion function.
    378   bool getBoolValue() const {
    379     return !!*this;
    380   }
    381 
    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();
    388   }
    389 
    390   /// @}
    391   /// @name Value Generators
    392   /// @{
    393   /// @brief Gets maximum unsigned value of APInt for specific bit width.
    394   static APInt getMaxValue(unsigned numBits) {
    395     return getAllOnesValue(numBits);
    396   }
    397 
    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);
    402     return API;
    403   }
    404 
    405   /// @brief Gets minimum unsigned value of APInt for a specific bit width.
    406   static APInt getMinValue(unsigned numBits) {
    407     return APInt(numBits, 0);
    408   }
    409 
    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);
    414     return API;
    415   }
    416 
    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);
    422   }
    423 
    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);
    428   }
    429 
    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);
    434   }
    435 
    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;
    440 
    441   /// Get an APInt with the same BitWidth as this APInt, just zero mask
    442   /// the high bits.
    443   /// @returns the low "numBits" bits of this APInt.
    444   APInt getLoBits(unsigned numBits) const;
    445 
    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);
    449     Res.setBit(BitNo);
    450     return Res;
    451   }
    452 
    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");
    466     if (hiBit < loBit)
    467       return getLowBitsSet(numBits, hiBit) |
    468              getHighBitsSet(numBits, numBits-loBit);
    469     return getLowBitsSet(numBits, hiBit-loBit).shl(loBit);
    470   }
    471 
    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
    479     if (hiBitsSet == 0)
    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);
    486   }
    487 
    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
    495     if (loBitsSet == 0)
    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 (numBits < APINT_BITS_PER_WORD)
    501       return APInt(numBits, (1ULL << loBitsSet) - 1);
    502     return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
    503   }
    504 
    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;
    509 
    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
    512   /// conversions.
    513   const uint64_t* getRawData() const {
    514     if (isSingleWord())
    515       return &VAL;
    516     return &pVal[0];
    517   }
    518 
    519   /// @}
    520   /// @name Unary Operators
    521   /// @{
    522   /// @returns a new APInt value representing *this incremented by one
    523   /// @brief Postfix increment operator.
    524   const APInt operator++(int) {
    525     APInt API(*this);
    526     ++(*this);
    527     return API;
    528   }
    529 
    530   /// @returns *this incremented by one
    531   /// @brief Prefix increment operator.
    532   APInt& operator++();
    533 
    534   /// @returns a new APInt representing *this decremented by one.
    535   /// @brief Postfix decrement operator.
    536   const APInt operator--(int) {
    537     APInt API(*this);
    538     --(*this);
    539     return API;
    540   }
    541 
    542   /// @returns *this decremented by one.
    543   /// @brief Prefix decrement operator.
    544   APInt& operator--();
    545 
    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 {
    550     APInt Result(*this);
    551     Result.flipAllBits();
    552     return Result;
    553   }
    554 
    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);
    560   }
    561 
    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;
    566 
    567   /// @}
    568   /// @name Assignment Operators
    569   /// @{
    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()) {
    575       VAL = RHS.VAL;
    576       BitWidth = RHS.BitWidth;
    577       return clearUnusedBits();
    578     }
    579 
    580     return AssignSlowCase(RHS);
    581   }
    582 
    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);
    589 
    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);
    595 
    596   /// Performs a bitwise OR operation on this APInt and RHS. The result is
    597   /// assigned *this;
    598   /// @returns *this after ORing with RHS.
    599   /// @brief Bitwise OR assignment operator.
    600   APInt& operator|=(const APInt& RHS);
    601 
    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
    604   /// the LHS.
    605   ///
    606   /// @brief Bitwise OR assignment operator.
    607   APInt& operator|=(uint64_t RHS) {
    608     if (isSingleWord()) {
    609       VAL |= RHS;
    610       clearUnusedBits();
    611     } else {
    612       pVal[0] |= RHS;
    613     }
    614     return *this;
    615   }
    616 
    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);
    622 
    623   /// Multiplies this APInt by RHS and assigns the result to *this.
    624   /// @returns *this
    625   /// @brief Multiplication assignment operator.
    626   APInt& operator*=(const APInt& RHS);
    627 
    628   /// Adds RHS to *this and assigns the result to *this.
    629   /// @returns *this
    630   /// @brief Addition assignment operator.
    631   APInt& operator+=(const APInt& RHS);
    632 
    633   /// Subtracts RHS from *this and assigns the result to *this.
    634   /// @returns *this
    635   /// @brief Subtraction assignment operator.
    636   APInt& operator-=(const APInt& RHS);
    637 
    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);
    643     return *this;
    644   }
    645 
    646   /// @}
    647   /// @name Binary Operators
    648   /// @{
    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");
    654     if (isSingleWord())
    655       return APInt(getBitWidth(), VAL & RHS.VAL);
    656     return AndSlowCase(RHS);
    657   }
    658   APInt And(const APInt& RHS) const {
    659     return this->operator&(RHS);
    660   }
    661 
    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");
    667     if (isSingleWord())
    668       return APInt(getBitWidth(), VAL | RHS.VAL);
    669     return OrSlowCase(RHS);
    670   }
    671   APInt Or(const APInt& RHS) const {
    672     return this->operator|(RHS);
    673   }
    674 
    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");
    680     if (isSingleWord())
    681       return APInt(BitWidth, VAL ^ RHS.VAL);
    682     return XorSlowCase(RHS);
    683   }
    684   APInt Xor(const APInt& RHS) const {
    685     return this->operator^(RHS);
    686   }
    687 
    688   /// Multiplies this APInt by RHS and returns the result.
    689   /// @brief Multiplication operator.
    690   APInt operator*(const APInt& RHS) const;
    691 
    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);
    697   }
    698 
    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);
    704   }
    705 
    706   APInt operator<<(unsigned Bits) const {
    707     return shl(Bits);
    708   }
    709 
    710   APInt operator<<(const APInt &Bits) const {
    711     return shl(Bits);
    712   }
    713 
    714   /// Arithmetic right-shift this APInt by shiftAmt.
    715   /// @brief Arithmetic right-shift function.
    716   APInt ashr(unsigned shiftAmt) const;
    717 
    718   /// Logical right-shift this APInt by shiftAmt.
    719   /// @brief Logical right-shift function.
    720   APInt lshr(unsigned shiftAmt) const;
    721 
    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);
    730     }
    731     return shlSlowCase(shiftAmt);
    732   }
    733 
    734   /// @brief Rotate left by rotateAmt.
    735   APInt rotl(unsigned rotateAmt) const;
    736 
    737   /// @brief Rotate right by rotateAmt.
    738   APInt rotr(unsigned rotateAmt) const;
    739 
    740   /// Arithmetic right-shift this APInt by shiftAmt.
    741   /// @brief Arithmetic right-shift function.
    742   APInt ashr(const APInt &shiftAmt) const;
    743 
    744   /// Logical right-shift this APInt by shiftAmt.
    745   /// @brief Logical right-shift function.
    746   APInt lshr(const APInt &shiftAmt) const;
    747 
    748   /// Left-shift this APInt by shiftAmt.
    749   /// @brief Left-shift function.
    750   APInt shl(const APInt &shiftAmt) const;
    751 
    752   /// @brief Rotate left by rotateAmt.
    753   APInt rotl(const APInt &rotateAmt) const;
    754 
    755   /// @brief Rotate right by rotateAmt.
    756   APInt rotr(const APInt &rotateAmt) const;
    757 
    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;
    763 
    764   /// Signed divide this APInt by APInt RHS.
    765   /// @brief Signed division function for APInt.
    766   APInt sdiv(const APInt &RHS) const {
    767     if (isNegative())
    768       if (RHS.isNegative())
    769         return (-(*this)).udiv(-RHS);
    770       else
    771         return -((-(*this)).udiv(RHS));
    772     else if (RHS.isNegative())
    773       return -(this->udiv(-RHS));
    774     return this->udiv(RHS);
    775   }
    776 
    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
    781   /// which is *this.
    782   /// @returns a new APInt value containing the remainder result
    783   /// @brief Unsigned remainder operation.
    784   APInt urem(const APInt &RHS) const;
    785 
    786   /// Signed remainder operation on APInt.
    787   /// @brief Function for signed remainder operation.
    788   APInt srem(const APInt &RHS) const {
    789     if (isNegative())
    790       if (RHS.isNegative())
    791         return -((-(*this)).urem(-RHS));
    792       else
    793         return -((-(*this)).urem(RHS));
    794     else if (RHS.isNegative())
    795       return this->urem(-RHS);
    796     return this->urem(RHS);
    797   }
    798 
    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);
    807 
    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);
    813       else
    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;
    820     } else {
    821       APInt::udivrem(LHS, RHS, Quotient, Remainder);
    822     }
    823   }
    824 
    825 
    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;
    835 
    836   /// @returns the bit value at bitPosition
    837   /// @brief Array-indexing support.
    838   bool operator[](unsigned bitPosition) const;
    839 
    840   /// @}
    841   /// @name Comparison Operators
    842   /// @{
    843   /// Compares this APInt with RHS for the validity of the equality
    844   /// relationship.
    845   /// @brief Equality operator.
    846   bool operator==(const APInt& RHS) const {
    847     assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
    848     if (isSingleWord())
    849       return VAL == RHS.VAL;
    850     return EqualSlowCase(RHS);
    851   }
    852 
    853   /// Compares this APInt with a uint64_t for the validity of the equality
    854   /// relationship.
    855   /// @returns true if *this == Val
    856   /// @brief Equality operator.
    857   bool operator==(uint64_t Val) const {
    858     if (isSingleWord())
    859       return VAL == Val;
    860     return EqualSlowCase(Val);
    861   }
    862 
    863   /// Compares this APInt with RHS for the validity of the equality
    864   /// relationship.
    865   /// @returns true if *this == Val
    866   /// @brief Equality comparison.
    867   bool eq(const APInt &RHS) const {
    868     return (*this) == RHS;
    869   }
    870 
    871   /// Compares this APInt with RHS for the validity of the inequality
    872   /// relationship.
    873   /// @returns true if *this != Val
    874   /// @brief Inequality operator.
    875   bool operator!=(const APInt& RHS) const {
    876     return !((*this) == RHS);
    877   }
    878 
    879   /// Compares this APInt with a uint64_t for the validity of the inequality
    880   /// relationship.
    881   /// @returns true if *this != Val
    882   /// @brief Inequality operator.
    883   bool operator!=(uint64_t Val) const {
    884     return !((*this) == Val);
    885   }
    886 
    887   /// Compares this APInt with RHS for the validity of the inequality
    888   /// relationship.
    889   /// @returns true if *this != Val
    890   /// @brief Inequality comparison
    891   bool ne(const APInt &RHS) const {
    892     return !((*this) == RHS);
    893   }
    894 
    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;
    900 
    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));
    907   }
    908 
    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;
    914 
    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));
    921   }
    922 
    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);
    929   }
    930 
    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));
    937   }
    938 
    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);
    945   }
    946 
    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));
    953   }
    954 
    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);
    961   }
    962 
    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));
    969   }
    970 
    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);
    977   }
    978 
    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));
    985   }
    986 
    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 {
    992     return !ult(RHS);
    993   }
    994 
    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));
   1001   }
   1002 
   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 {
   1008     return !slt(RHS);
   1009   }
   1010 
   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));
   1017   }
   1018 
   1019 
   1020 
   1021 
   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;
   1026   }
   1027 
   1028   /// @}
   1029   /// @name Resizing Operators
   1030   /// @{
   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;
   1035 
   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
   1039   /// current width.
   1040   /// @brief Sign extend to a new width.
   1041   APInt sext(unsigned width) const;
   1042 
   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;
   1048 
   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;
   1053 
   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;
   1058 
   1059   /// @}
   1060   /// @name Bit Manipulation Operators
   1061   /// @{
   1062   /// @brief Set every bit to 1.
   1063   void setAllBits() {
   1064     if (isSingleWord())
   1065       VAL = -1ULL;
   1066     else {
   1067       // Set all the bits in all the words.
   1068       for (unsigned i = 0; i < getNumWords(); ++i)
   1069 	pVal[i] = -1ULL;
   1070     }
   1071     // Clear the unused ones
   1072     clearUnusedBits();
   1073   }
   1074 
   1075   /// Set the given bit to 1 whose position is given as "bitPosition".
   1076   /// @brief Set a given bit to 1.
   1077   void setBit(unsigned bitPosition);
   1078 
   1079   /// @brief Set every bit to 0.
   1080   void clearAllBits() {
   1081     if (isSingleWord())
   1082       VAL = 0;
   1083     else
   1084       memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
   1085   }
   1086 
   1087   /// Set the given bit to 0 whose position is given as "bitPosition".
   1088   /// @brief Set a given bit to 0.
   1089   void clearBit(unsigned bitPosition);
   1090 
   1091   /// @brief Toggle every bit to its opposite value.
   1092   void flipAllBits() {
   1093     if (isSingleWord())
   1094       VAL ^= -1ULL;
   1095     else {
   1096       for (unsigned i = 0; i < getNumWords(); ++i)
   1097         pVal[i] ^= -1ULL;
   1098     }
   1099     clearUnusedBits();
   1100   }
   1101 
   1102   /// Toggle a given bit to its opposite value whose position is given
   1103   /// as "bitPosition".
   1104   /// @brief Toggles a given bit to its opposite value.
   1105   void flipBit(unsigned bitPosition);
   1106 
   1107   /// @}
   1108   /// @name Value Characterization Functions
   1109   /// @{
   1110 
   1111   /// @returns the total number of bits.
   1112   unsigned getBitWidth() const {
   1113     return BitWidth;
   1114   }
   1115 
   1116   /// Here one word's bitwidth equals to that of uint64_t.
   1117   /// @returns the number of words to hold the integer value of this APInt.
   1118   /// @brief Get the number of words.
   1119   unsigned getNumWords() const {
   1120     return getNumWords(BitWidth);
   1121   }
   1122 
   1123   /// Here one word's bitwidth equals to that of uint64_t.
   1124   /// @returns the number of words to hold the integer value with a
   1125   /// given bit width.
   1126   /// @brief Get the number of words.
   1127   static unsigned getNumWords(unsigned BitWidth) {
   1128     return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
   1129   }
   1130 
   1131   /// This function returns the number of active bits which is defined as the
   1132   /// bit width minus the number of leading zeros. This is used in several
   1133   /// computations to see how "wide" the value is.
   1134   /// @brief Compute the number of active bits in the value
   1135   unsigned getActiveBits() const {
   1136     return BitWidth - countLeadingZeros();
   1137   }
   1138 
   1139   /// This function returns the number of active words in the value of this
   1140   /// APInt. This is used in conjunction with getActiveData to extract the raw
   1141   /// value of the APInt.
   1142   unsigned getActiveWords() const {
   1143     return whichWord(getActiveBits()-1) + 1;
   1144   }
   1145 
   1146   /// Computes the minimum bit width for this APInt while considering it to be
   1147   /// a signed (and probably negative) value. If the value is not negative,
   1148   /// this function returns the same value as getActiveBits()+1. Otherwise, it
   1149   /// returns the smallest bit width that will retain the negative value. For
   1150   /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
   1151   /// for -1, this function will always return 1.
   1152   /// @brief Get the minimum bit size for this signed APInt
   1153   unsigned getMinSignedBits() const {
   1154     if (isNegative())
   1155       return BitWidth - countLeadingOnes() + 1;
   1156     return getActiveBits()+1;
   1157   }
   1158 
   1159   /// This method attempts to return the value of this APInt as a zero extended
   1160   /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
   1161   /// uint64_t. Otherwise an assertion will result.
   1162   /// @brief Get zero extended value
   1163   uint64_t getZExtValue() const {
   1164     if (isSingleWord())
   1165       return VAL;
   1166     assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
   1167     return pVal[0];
   1168   }
   1169 
   1170   /// This method attempts to return the value of this APInt as a sign extended
   1171   /// int64_t. The bit width must be <= 64 or the value must fit within an
   1172   /// int64_t. Otherwise an assertion will result.
   1173   /// @brief Get sign extended value
   1174   int64_t getSExtValue() const {
   1175     if (isSingleWord())
   1176       return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
   1177                      (APINT_BITS_PER_WORD - BitWidth);
   1178     assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
   1179     return int64_t(pVal[0]);
   1180   }
   1181 
   1182   /// This method determines how many bits are required to hold the APInt
   1183   /// equivalent of the string given by \arg str.
   1184   /// @brief Get bits required for string value.
   1185   static unsigned getBitsNeeded(StringRef str, uint8_t radix);
   1186 
   1187   /// countLeadingZeros - This function is an APInt version of the
   1188   /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
   1189   /// of zeros from the most significant bit to the first one bit.
   1190   /// @returns BitWidth if the value is zero.
   1191   /// @returns the number of zeros from the most significant bit to the first
   1192   /// one bits.
   1193   unsigned countLeadingZeros() const {
   1194     if (isSingleWord()) {
   1195       unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
   1196       return CountLeadingZeros_64(VAL) - unusedBits;
   1197     }
   1198     return countLeadingZerosSlowCase();
   1199   }
   1200 
   1201   /// countLeadingOnes - This function is an APInt version of the
   1202   /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number
   1203   /// of ones from the most significant bit to the first zero bit.
   1204   /// @returns 0 if the high order bit is not set
   1205   /// @returns the number of 1 bits from the most significant to the least
   1206   /// @brief Count the number of leading one bits.
   1207   unsigned countLeadingOnes() const;
   1208 
   1209   /// Computes the number of leading bits of this APInt that are equal to its
   1210   /// sign bit.
   1211   unsigned getNumSignBits() const {
   1212     return isNegative() ? countLeadingOnes() : countLeadingZeros();
   1213   }
   1214 
   1215   /// countTrailingZeros - This function is an APInt version of the
   1216   /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
   1217   /// the number of zeros from the least significant bit to the first set bit.
   1218   /// @returns BitWidth if the value is zero.
   1219   /// @returns the number of zeros from the least significant bit to the first
   1220   /// one bit.
   1221   /// @brief Count the number of trailing zero bits.
   1222   unsigned countTrailingZeros() const;
   1223 
   1224   /// countTrailingOnes - This function is an APInt version of the
   1225   /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
   1226   /// the number of ones from the least significant bit to the first zero bit.
   1227   /// @returns BitWidth if the value is all ones.
   1228   /// @returns the number of ones from the least significant bit to the first
   1229   /// zero bit.
   1230   /// @brief Count the number of trailing one bits.
   1231   unsigned countTrailingOnes() const {
   1232     if (isSingleWord())
   1233       return CountTrailingOnes_64(VAL);
   1234     return countTrailingOnesSlowCase();
   1235   }
   1236 
   1237   /// countPopulation - This function is an APInt version of the
   1238   /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
   1239   /// of 1 bits in the APInt value.
   1240   /// @returns 0 if the value is zero.
   1241   /// @returns the number of set bits.
   1242   /// @brief Count the number of bits set.
   1243   unsigned countPopulation() const {
   1244     if (isSingleWord())
   1245       return CountPopulation_64(VAL);
   1246     return countPopulationSlowCase();
   1247   }
   1248 
   1249   /// @}
   1250   /// @name Conversion Functions
   1251   /// @{
   1252   void print(raw_ostream &OS, bool isSigned) const;
   1253 
   1254   /// toString - Converts an APInt to a string and append it to Str.  Str is
   1255   /// commonly a SmallString.
   1256   void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
   1257                 bool formatAsCLiteral = false) const;
   1258 
   1259   /// Considers the APInt to be unsigned and converts it into a string in the
   1260   /// radix given. The radix can be 2, 8, 10 16, or 36.
   1261   void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
   1262     toString(Str, Radix, false, false);
   1263   }
   1264 
   1265   /// Considers the APInt to be signed and converts it into a string in the
   1266   /// radix given. The radix can be 2, 8, 10, 16, or 36.
   1267   void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
   1268     toString(Str, Radix, true, false);
   1269   }
   1270 
   1271   /// toString - This returns the APInt as a std::string.  Note that this is an
   1272   /// inefficient method.  It is better to pass in a SmallVector/SmallString
   1273   /// to the methods above to avoid thrashing the heap for the string.
   1274   std::string toString(unsigned Radix, bool Signed) const;
   1275 
   1276 
   1277   /// @returns a byte-swapped representation of this APInt Value.
   1278   APInt byteSwap() const;
   1279 
   1280   /// @brief Converts this APInt to a double value.
   1281   double roundToDouble(bool isSigned) const;
   1282 
   1283   /// @brief Converts this unsigned APInt to a double value.
   1284   double roundToDouble() const {
   1285     return roundToDouble(false);
   1286   }
   1287 
   1288   /// @brief Converts this signed APInt to a double value.
   1289   double signedRoundToDouble() const {
   1290     return roundToDouble(true);
   1291   }
   1292 
   1293   /// The conversion does not do a translation from integer to double, it just
   1294   /// re-interprets the bits as a double. Note that it is valid to do this on
   1295   /// any bit width. Exactly 64 bits will be translated.
   1296   /// @brief Converts APInt bits to a double
   1297   double bitsToDouble() const {
   1298     union {
   1299       uint64_t I;
   1300       double D;
   1301     } T;
   1302     T.I = (isSingleWord() ? VAL : pVal[0]);
   1303     return T.D;
   1304   }
   1305 
   1306   /// The conversion does not do a translation from integer to float, it just
   1307   /// re-interprets the bits as a float. Note that it is valid to do this on
   1308   /// any bit width. Exactly 32 bits will be translated.
   1309   /// @brief Converts APInt bits to a double
   1310   float bitsToFloat() const {
   1311     union {
   1312       unsigned I;
   1313       float F;
   1314     } T;
   1315     T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
   1316     return T.F;
   1317   }
   1318 
   1319   /// The conversion does not do a translation from double to integer, it just
   1320   /// re-interprets the bits of the double.
   1321   /// @brief Converts a double to APInt bits.
   1322   static APInt doubleToBits(double V) {
   1323     union {
   1324       uint64_t I;
   1325       double D;
   1326     } T;
   1327     T.D = V;
   1328     return APInt(sizeof T * CHAR_BIT, T.I);
   1329   }
   1330 
   1331   /// The conversion does not do a translation from float to integer, it just
   1332   /// re-interprets the bits of the float.
   1333   /// @brief Converts a float to APInt bits.
   1334   static APInt floatToBits(float V) {
   1335     union {
   1336       unsigned I;
   1337       float F;
   1338     } T;
   1339     T.F = V;
   1340     return APInt(sizeof T * CHAR_BIT, T.I);
   1341   }
   1342 
   1343   /// @}
   1344   /// @name Mathematics Operations
   1345   /// @{
   1346 
   1347   /// @returns the floor log base 2 of this APInt.
   1348   unsigned logBase2() const {
   1349     return BitWidth - 1 - countLeadingZeros();
   1350   }
   1351 
   1352   /// @returns the ceil log base 2 of this APInt.
   1353   unsigned ceilLogBase2() const {
   1354     return BitWidth - (*this - 1).countLeadingZeros();
   1355   }
   1356 
   1357   /// @returns the log base 2 of this APInt if its an exact power of two, -1
   1358   /// otherwise
   1359   int32_t exactLogBase2() const {
   1360     if (!isPowerOf2())
   1361       return -1;
   1362     return logBase2();
   1363   }
   1364 
   1365   /// @brief Compute the square root
   1366   APInt sqrt() const;
   1367 
   1368   /// If *this is < 0 then return -(*this), otherwise *this;
   1369   /// @brief Get the absolute value;
   1370   APInt abs() const {
   1371     if (isNegative())
   1372       return -(*this);
   1373     return *this;
   1374   }
   1375 
   1376   /// @returns the multiplicative inverse for a given modulo.
   1377   APInt multiplicativeInverse(const APInt& modulo) const;
   1378 
   1379   /// @}
   1380   /// @name Support for division by constant
   1381   /// @{
   1382 
   1383   /// Calculate the magic number for signed division by a constant.
   1384   struct ms;
   1385   ms magic() const;
   1386 
   1387   /// Calculate the magic number for unsigned division by a constant.
   1388   struct mu;
   1389   mu magicu(unsigned LeadingZeros = 0) const;
   1390 
   1391   /// @}
   1392   /// @name Building-block Operations for APInt and APFloat
   1393   /// @{
   1394 
   1395   // These building block operations operate on a representation of
   1396   // arbitrary precision, two's-complement, bignum integer values.
   1397   // They should be sufficient to implement APInt and APFloat bignum
   1398   // requirements.  Inputs are generally a pointer to the base of an
   1399   // array of integer parts, representing an unsigned bignum, and a
   1400   // count of how many parts there are.
   1401 
   1402   /// Sets the least significant part of a bignum to the input value,
   1403   /// and zeroes out higher parts.  */
   1404   static void tcSet(integerPart *, integerPart, unsigned int);
   1405 
   1406   /// Assign one bignum to another.
   1407   static void tcAssign(integerPart *, const integerPart *, unsigned int);
   1408 
   1409   /// Returns true if a bignum is zero, false otherwise.
   1410   static bool tcIsZero(const integerPart *, unsigned int);
   1411 
   1412   /// Extract the given bit of a bignum; returns 0 or 1.  Zero-based.
   1413   static int tcExtractBit(const integerPart *, unsigned int bit);
   1414 
   1415   /// Copy the bit vector of width srcBITS from SRC, starting at bit
   1416   /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
   1417   /// becomes the least significant bit of DST.  All high bits above
   1418   /// srcBITS in DST are zero-filled.
   1419   static void tcExtract(integerPart *, unsigned int dstCount,
   1420                         const integerPart *,
   1421                         unsigned int srcBits, unsigned int srcLSB);
   1422 
   1423   /// Set the given bit of a bignum.  Zero-based.
   1424   static void tcSetBit(integerPart *, unsigned int bit);
   1425 
   1426   /// Clear the given bit of a bignum.  Zero-based.
   1427   static void tcClearBit(integerPart *, unsigned int bit);
   1428 
   1429   /// Returns the bit number of the least or most significant set bit
   1430   /// of a number.  If the input number has no bits set -1U is
   1431   /// returned.
   1432   static unsigned int tcLSB(const integerPart *, unsigned int);
   1433   static unsigned int tcMSB(const integerPart *parts, unsigned int n);
   1434 
   1435   /// Negate a bignum in-place.
   1436   static void tcNegate(integerPart *, unsigned int);
   1437 
   1438   /// DST += RHS + CARRY where CARRY is zero or one.  Returns the
   1439   /// carry flag.
   1440   static integerPart tcAdd(integerPart *, const integerPart *,
   1441                            integerPart carry, unsigned);
   1442 
   1443   /// DST -= RHS + CARRY where CARRY is zero or one.  Returns the
   1444   /// carry flag.
   1445   static integerPart tcSubtract(integerPart *, const integerPart *,
   1446                                 integerPart carry, unsigned);
   1447 
   1448   ///  DST += SRC * MULTIPLIER + PART   if add is true
   1449   ///  DST  = SRC * MULTIPLIER + PART   if add is false
   1450   ///
   1451   ///  Requires 0 <= DSTPARTS <= SRCPARTS + 1.  If DST overlaps SRC
   1452   ///  they must start at the same point, i.e. DST == SRC.
   1453   ///
   1454   ///  If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
   1455   ///  returned.  Otherwise DST is filled with the least significant
   1456   ///  DSTPARTS parts of the result, and if all of the omitted higher
   1457   ///  parts were zero return zero, otherwise overflow occurred and
   1458   ///  return one.
   1459   static int tcMultiplyPart(integerPart *dst, const integerPart *src,
   1460                             integerPart multiplier, integerPart carry,
   1461                             unsigned int srcParts, unsigned int dstParts,
   1462                             bool add);
   1463 
   1464   /// DST = LHS * RHS, where DST has the same width as the operands
   1465   /// and is filled with the least significant parts of the result.
   1466   /// Returns one if overflow occurred, otherwise zero.  DST must be
   1467   /// disjoint from both operands.
   1468   static int tcMultiply(integerPart *, const integerPart *,
   1469                         const integerPart *, unsigned);
   1470 
   1471   /// DST = LHS * RHS, where DST has width the sum of the widths of
   1472   /// the operands.  No overflow occurs.  DST must be disjoint from
   1473   /// both operands. Returns the number of parts required to hold the
   1474   /// result.
   1475   static unsigned int tcFullMultiply(integerPart *, const integerPart *,
   1476                                      const integerPart *, unsigned, unsigned);
   1477 
   1478   /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
   1479   /// Otherwise set LHS to LHS / RHS with the fractional part
   1480   /// discarded, set REMAINDER to the remainder, return zero.  i.e.
   1481   ///
   1482   ///  OLD_LHS = RHS * LHS + REMAINDER
   1483   ///
   1484   ///  SCRATCH is a bignum of the same size as the operands and result
   1485   ///  for use by the routine; its contents need not be initialized
   1486   ///  and are destroyed.  LHS, REMAINDER and SCRATCH must be
   1487   ///  distinct.
   1488   static int tcDivide(integerPart *lhs, const integerPart *rhs,
   1489                       integerPart *remainder, integerPart *scratch,
   1490                       unsigned int parts);
   1491 
   1492   /// Shift a bignum left COUNT bits.  Shifted in bits are zero.
   1493   /// There are no restrictions on COUNT.
   1494   static void tcShiftLeft(integerPart *, unsigned int parts,
   1495                           unsigned int count);
   1496 
   1497   /// Shift a bignum right COUNT bits.  Shifted in bits are zero.
   1498   /// There are no restrictions on COUNT.
   1499   static void tcShiftRight(integerPart *, unsigned int parts,
   1500                            unsigned int count);
   1501 
   1502   /// The obvious AND, OR and XOR and complement operations.
   1503   static void tcAnd(integerPart *, const integerPart *, unsigned int);
   1504   static void tcOr(integerPart *, const integerPart *, unsigned int);
   1505   static void tcXor(integerPart *, const integerPart *, unsigned int);
   1506   static void tcComplement(integerPart *, unsigned int);
   1507 
   1508   /// Comparison (unsigned) of two bignums.
   1509   static int tcCompare(const integerPart *, const integerPart *,
   1510                        unsigned int);
   1511 
   1512   /// Increment a bignum in-place.  Return the carry flag.
   1513   static integerPart tcIncrement(integerPart *, unsigned int);
   1514 
   1515   /// Set the least significant BITS and clear the rest.
   1516   static void tcSetLeastSignificantBits(integerPart *, unsigned int,
   1517                                         unsigned int bits);
   1518 
   1519   /// @brief debug method
   1520   void dump() const;
   1521 
   1522   /// @}
   1523 };
   1524 
   1525 /// Magic data for optimising signed division by a constant.
   1526 struct APInt::ms {
   1527   APInt m;  ///< magic number
   1528   unsigned s;  ///< shift amount
   1529 };
   1530 
   1531 /// Magic data for optimising unsigned division by a constant.
   1532 struct APInt::mu {
   1533   APInt m;     ///< magic number
   1534   bool a;      ///< add indicator
   1535   unsigned s;  ///< shift amount
   1536 };
   1537 
   1538 inline bool operator==(uint64_t V1, const APInt& V2) {
   1539   return V2 == V1;
   1540 }
   1541 
   1542 inline bool operator!=(uint64_t V1, const APInt& V2) {
   1543   return V2 != V1;
   1544 }
   1545 
   1546 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
   1547   I.print(OS, true);
   1548   return OS;
   1549 }
   1550 
   1551 namespace APIntOps {
   1552 
   1553 /// @brief Determine the smaller of two APInts considered to be signed.
   1554 inline APInt smin(const APInt &A, const APInt &B) {
   1555   return A.slt(B) ? A : B;
   1556 }
   1557 
   1558 /// @brief Determine the larger of two APInts considered to be signed.
   1559 inline APInt smax(const APInt &A, const APInt &B) {
   1560   return A.sgt(B) ? A : B;
   1561 }
   1562 
   1563 /// @brief Determine the smaller of two APInts considered to be signed.
   1564 inline APInt umin(const APInt &A, const APInt &B) {
   1565   return A.ult(B) ? A : B;
   1566 }
   1567 
   1568 /// @brief Determine the larger of two APInts considered to be unsigned.
   1569 inline APInt umax(const APInt &A, const APInt &B) {
   1570   return A.ugt(B) ? A : B;
   1571 }
   1572 
   1573 /// @brief Check if the specified APInt has a N-bits unsigned integer value.
   1574 inline bool isIntN(unsigned N, const APInt& APIVal) {
   1575   return APIVal.isIntN(N);
   1576 }
   1577 
   1578 /// @brief Check if the specified APInt has a N-bits signed integer value.
   1579 inline bool isSignedIntN(unsigned N, const APInt& APIVal) {
   1580   return APIVal.isSignedIntN(N);
   1581 }
   1582 
   1583 /// @returns true if the argument APInt value is a sequence of ones
   1584 /// starting at the least significant bit with the remainder zero.
   1585 inline bool isMask(unsigned numBits, const APInt& APIVal) {
   1586   return numBits <= APIVal.getBitWidth() &&
   1587     APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
   1588 }
   1589 
   1590 /// @returns true if the argument APInt value contains a sequence of ones
   1591 /// with the remainder zero.
   1592 inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
   1593   return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
   1594 }
   1595 
   1596 /// @returns a byte-swapped representation of the specified APInt Value.
   1597 inline APInt byteSwap(const APInt& APIVal) {
   1598   return APIVal.byteSwap();
   1599 }
   1600 
   1601 /// @returns the floor log base 2 of the specified APInt value.
   1602 inline unsigned logBase2(const APInt& APIVal) {
   1603   return APIVal.logBase2();
   1604 }
   1605 
   1606 /// GreatestCommonDivisor - This function returns the greatest common
   1607 /// divisor of the two APInt values using Euclid's algorithm.
   1608 /// @returns the greatest common divisor of Val1 and Val2
   1609 /// @brief Compute GCD of two APInt values.
   1610 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
   1611 
   1612 /// Treats the APInt as an unsigned value for conversion purposes.
   1613 /// @brief Converts the given APInt to a double value.
   1614 inline double RoundAPIntToDouble(const APInt& APIVal) {
   1615   return APIVal.roundToDouble();
   1616 }
   1617 
   1618 /// Treats the APInt as a signed value for conversion purposes.
   1619 /// @brief Converts the given APInt to a double value.
   1620 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
   1621   return APIVal.signedRoundToDouble();
   1622 }
   1623 
   1624 /// @brief Converts the given APInt to a float vlalue.
   1625 inline float RoundAPIntToFloat(const APInt& APIVal) {
   1626   return float(RoundAPIntToDouble(APIVal));
   1627 }
   1628 
   1629 /// Treast the APInt as a signed value for conversion purposes.
   1630 /// @brief Converts the given APInt to a float value.
   1631 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
   1632   return float(APIVal.signedRoundToDouble());
   1633 }
   1634 
   1635 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
   1636 /// @brief Converts the given double value into a APInt.
   1637 APInt RoundDoubleToAPInt(double Double, unsigned width);
   1638 
   1639 /// RoundFloatToAPInt - Converts a float value into an APInt value.
   1640 /// @brief Converts a float value into a APInt.
   1641 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
   1642   return RoundDoubleToAPInt(double(Float), width);
   1643 }
   1644 
   1645 /// Arithmetic right-shift the APInt by shiftAmt.
   1646 /// @brief Arithmetic right-shift function.
   1647 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
   1648   return LHS.ashr(shiftAmt);
   1649 }
   1650 
   1651 /// Logical right-shift the APInt by shiftAmt.
   1652 /// @brief Logical right-shift function.
   1653 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
   1654   return LHS.lshr(shiftAmt);
   1655 }
   1656 
   1657 /// Left-shift the APInt by shiftAmt.
   1658 /// @brief Left-shift function.
   1659 inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
   1660   return LHS.shl(shiftAmt);
   1661 }
   1662 
   1663 /// Signed divide APInt LHS by APInt RHS.
   1664 /// @brief Signed division function for APInt.
   1665 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
   1666   return LHS.sdiv(RHS);
   1667 }
   1668 
   1669 /// Unsigned divide APInt LHS by APInt RHS.
   1670 /// @brief Unsigned division function for APInt.
   1671 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
   1672   return LHS.udiv(RHS);
   1673 }
   1674 
   1675 /// Signed remainder operation on APInt.
   1676 /// @brief Function for signed remainder operation.
   1677 inline APInt srem(const APInt& LHS, const APInt& RHS) {
   1678   return LHS.srem(RHS);
   1679 }
   1680 
   1681 /// Unsigned remainder operation on APInt.
   1682 /// @brief Function for unsigned remainder operation.
   1683 inline APInt urem(const APInt& LHS, const APInt& RHS) {
   1684   return LHS.urem(RHS);
   1685 }
   1686 
   1687 /// Performs multiplication on APInt values.
   1688 /// @brief Function for multiplication operation.
   1689 inline APInt mul(const APInt& LHS, const APInt& RHS) {
   1690   return LHS * RHS;
   1691 }
   1692 
   1693 /// Performs addition on APInt values.
   1694 /// @brief Function for addition operation.
   1695 inline APInt add(const APInt& LHS, const APInt& RHS) {
   1696   return LHS + RHS;
   1697 }
   1698 
   1699 /// Performs subtraction on APInt values.
   1700 /// @brief Function for subtraction operation.
   1701 inline APInt sub(const APInt& LHS, const APInt& RHS) {
   1702   return LHS - RHS;
   1703 }
   1704 
   1705 /// Performs bitwise AND operation on APInt LHS and
   1706 /// APInt RHS.
   1707 /// @brief Bitwise AND function for APInt.
   1708 inline APInt And(const APInt& LHS, const APInt& RHS) {
   1709   return LHS & RHS;
   1710 }
   1711 
   1712 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
   1713 /// @brief Bitwise OR function for APInt.
   1714 inline APInt Or(const APInt& LHS, const APInt& RHS) {
   1715   return LHS | RHS;
   1716 }
   1717 
   1718 /// Performs bitwise XOR operation on APInt.
   1719 /// @brief Bitwise XOR function for APInt.
   1720 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
   1721   return LHS ^ RHS;
   1722 }
   1723 
   1724 /// Performs a bitwise complement operation on APInt.
   1725 /// @brief Bitwise complement function.
   1726 inline APInt Not(const APInt& APIVal) {
   1727   return ~APIVal;
   1728 }
   1729 
   1730 } // End of APIntOps namespace
   1731 
   1732 } // End of llvm namespace
   1733 
   1734 #endif
   1735