LLVM API Documentation
00001 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements a class to represent arbitrary precision integral 00011 // constant values and operations on them. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #ifndef LLVM_APINT_H 00016 #define LLVM_APINT_H 00017 00018 #include "llvm/Support/DataTypes.h" 00019 #include "llvm/Support/MathExtras.h" 00020 #include <cassert> 00021 #include <cstring> 00022 #include <string> 00023 00024 namespace llvm { 00025 class Serializer; 00026 class Deserializer; 00027 class FoldingSetNodeID; 00028 class raw_ostream; 00029 00030 template<typename T> 00031 class SmallVectorImpl; 00032 00033 /* An unsigned host type used as a single part of a multi-part 00034 bignum. */ 00035 typedef uint64_t integerPart; 00036 00037 const unsigned int host_char_bit = 8; 00038 const unsigned int integerPartWidth = host_char_bit * 00039 static_cast<unsigned int>(sizeof(integerPart)); 00040 00041 //===----------------------------------------------------------------------===// 00042 // APInt Class 00043 //===----------------------------------------------------------------------===// 00044 00045 /// APInt - This class represents arbitrary precision constant integral values. 00046 /// It is a functional replacement for common case unsigned integer type like 00047 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width 00048 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more 00049 /// than 64-bits of precision. APInt provides a variety of arithmetic operators 00050 /// and methods to manipulate integer values of any bit-width. It supports both 00051 /// the typical integer arithmetic and comparison operations as well as bitwise 00052 /// manipulation. 00053 /// 00054 /// The class has several invariants worth noting: 00055 /// * All bit, byte, and word positions are zero-based. 00056 /// * Once the bit width is set, it doesn't change except by the Truncate, 00057 /// SignExtend, or ZeroExtend operations. 00058 /// * All binary operators must be on APInt instances of the same bit width. 00059 /// Attempting to use these operators on instances with different bit 00060 /// widths will yield an assertion. 00061 /// * The value is stored canonically as an unsigned value. For operations 00062 /// where it makes a difference, there are both signed and unsigned variants 00063 /// of the operation. For example, sdiv and udiv. However, because the bit 00064 /// widths must be the same, operations such as Mul and Add produce the same 00065 /// results regardless of whether the values are interpreted as signed or 00066 /// not. 00067 /// * In general, the class tries to follow the style of computation that LLVM 00068 /// uses in its IR. This simplifies its use for LLVM. 00069 /// 00070 /// @brief Class for arbitrary precision integers. 00071 class APInt { 00072 unsigned BitWidth; ///< The number of bits in this APInt. 00073 00074 /// This union is used to store the integer value. When the 00075 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal. 00076 union { 00077 uint64_t VAL; ///< Used to store the <= 64 bits integer value. 00078 uint64_t *pVal; ///< Used to store the >64 bits integer value. 00079 }; 00080 00081 /// This enum is used to hold the constants we needed for APInt. 00082 enum { 00083 /// Bits in a word 00084 APINT_BITS_PER_WORD = static_cast<unsigned int>(sizeof(uint64_t)) * 8, 00085 /// Byte size of a word 00086 APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t)) 00087 }; 00088 00089 /// This constructor is used only internally for speed of construction of 00090 /// temporaries. It is unsafe for general use so it is not public. 00091 /// @brief Fast internal constructor 00092 APInt(uint64_t* val, unsigned bits) : BitWidth(bits), pVal(val) { } 00093 00094 /// @returns true if the number of bits <= 64, false otherwise. 00095 /// @brief Determine if this APInt just has one word to store value. 00096 bool isSingleWord() const { 00097 return BitWidth <= APINT_BITS_PER_WORD; 00098 } 00099 00100 /// @returns the word position for the specified bit position. 00101 /// @brief Determine which word a bit is in. 00102 static unsigned whichWord(unsigned bitPosition) { 00103 return bitPosition / APINT_BITS_PER_WORD; 00104 } 00105 00106 /// @returns the bit position in a word for the specified bit position 00107 /// in the APInt. 00108 /// @brief Determine which bit in a word a bit is in. 00109 static unsigned whichBit(unsigned bitPosition) { 00110 return bitPosition % APINT_BITS_PER_WORD; 00111 } 00112 00113 /// This method generates and returns a uint64_t (word) mask for a single 00114 /// bit at a specific bit position. This is used to mask the bit in the 00115 /// corresponding word. 00116 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set 00117 /// @brief Get a single bit mask. 00118 static uint64_t maskBit(unsigned bitPosition) { 00119 return 1ULL << whichBit(bitPosition); 00120 } 00121 00122 /// This method is used internally to clear the to "N" bits in the high order 00123 /// word that are not used by the APInt. This is needed after the most 00124 /// significant word is assigned a value to ensure that those bits are 00125 /// zero'd out. 00126 /// @brief Clear unused high order bits 00127 APInt& clearUnusedBits() { 00128 // Compute how many bits are used in the final word 00129 unsigned wordBits = BitWidth % APINT_BITS_PER_WORD; 00130 if (wordBits == 0) 00131 // If all bits are used, we want to leave the value alone. This also 00132 // avoids the undefined behavior of >> when the shift is the same size as 00133 // the word size (64). 00134 return *this; 00135 00136 // Mask out the high bits. 00137 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits); 00138 if (isSingleWord()) 00139 VAL &= mask; 00140 else 00141 pVal[getNumWords() - 1] &= mask; 00142 return *this; 00143 } 00144 00145 /// @returns the corresponding word for the specified bit position. 00146 /// @brief Get the word corresponding to a bit position 00147 uint64_t getWord(unsigned bitPosition) const { 00148 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)]; 00149 } 00150 00151 /// This is used by the constructors that take string arguments. 00152 /// @brief Convert a char array into an APInt 00153 void fromString(unsigned numBits, const char *strStart, unsigned slen, 00154 uint8_t radix); 00155 00156 /// This is used by the toString method to divide by the radix. It simply 00157 /// provides a more convenient form of divide for internal use since KnuthDiv 00158 /// has specific constraints on its inputs. If those constraints are not met 00159 /// then it provides a simpler form of divide. 00160 /// @brief An internal division function for dividing APInts. 00161 static void divide(const APInt LHS, unsigned lhsWords, 00162 const APInt &RHS, unsigned rhsWords, 00163 APInt *Quotient, APInt *Remainder); 00164 00165 /// out-of-line slow case for inline constructor 00166 void initSlowCase(unsigned numBits, uint64_t val, bool isSigned); 00167 00168 /// out-of-line slow case for inline copy constructor 00169 void initSlowCase(const APInt& that); 00170 00171 /// out-of-line slow case for shl 00172 APInt shlSlowCase(unsigned shiftAmt) const; 00173 00174 /// out-of-line slow case for operator& 00175 APInt AndSlowCase(const APInt& RHS) const; 00176 00177 /// out-of-line slow case for operator| 00178 APInt OrSlowCase(const APInt& RHS) const; 00179 00180 /// out-of-line slow case for operator^ 00181 APInt XorSlowCase(const APInt& RHS) const; 00182 00183 /// out-of-line slow case for operator= 00184 APInt& AssignSlowCase(const APInt& RHS); 00185 00186 /// out-of-line slow case for operator== 00187 bool EqualSlowCase(const APInt& RHS) const; 00188 00189 /// out-of-line slow case for operator== 00190 bool EqualSlowCase(uint64_t Val) const; 00191 00192 /// out-of-line slow case for countLeadingZeros 00193 unsigned countLeadingZerosSlowCase() const; 00194 00195 /// out-of-line slow case for countTrailingOnes 00196 unsigned countTrailingOnesSlowCase() const; 00197 00198 /// out-of-line slow case for countPopulation 00199 unsigned countPopulationSlowCase() const; 00200 00201 public: 00202 /// @name Constructors 00203 /// @{ 00204 /// If isSigned is true then val is treated as if it were a signed value 00205 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width 00206 /// will be done. Otherwise, no sign extension occurs (high order bits beyond 00207 /// the range of val are zero filled). 00208 /// @param numBits the bit width of the constructed APInt 00209 /// @param val the initial value of the APInt 00210 /// @param isSigned how to treat signedness of val 00211 /// @brief Create a new APInt of numBits width, initialized as val. 00212 APInt(unsigned numBits, uint64_t val, bool isSigned = false) 00213 : BitWidth(numBits), VAL(0) { 00214 assert(BitWidth && "bitwidth too small"); 00215 if (isSingleWord()) 00216 VAL = val; 00217 else 00218 initSlowCase(numBits, val, isSigned); 00219 clearUnusedBits(); 00220 } 00221 00222 /// Note that numWords can be smaller or larger than the corresponding bit 00223 /// width but any extraneous bits will be dropped. 00224 /// @param numBits the bit width of the constructed APInt 00225 /// @param numWords the number of words in bigVal 00226 /// @param bigVal a sequence of words to form the initial value of the APInt 00227 /// @brief Construct an APInt of numBits width, initialized as bigVal[]. 00228 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]); 00229 00230 /// This constructor interprets the slen characters starting at StrStart as 00231 /// a string in the given radix. The interpretation stops when the first 00232 /// character that is not suitable for the radix is encountered. Acceptable 00233 /// radix values are 2, 8, 10 and 16. It is an error for the value implied by 00234 /// the string to require more bits than numBits. 00235 /// @param numBits the bit width of the constructed APInt 00236 /// @param strStart the start of the string to be interpreted 00237 /// @param slen the maximum number of characters to interpret 00238 /// @param radix the radix to use for the conversion 00239 /// @brief Construct an APInt from a string representation. 00240 APInt(unsigned numBits, const char strStart[], unsigned slen, uint8_t radix); 00241 00242 /// Simply makes *this a copy of that. 00243 /// @brief Copy Constructor. 00244 APInt(const APInt& that) 00245 : BitWidth(that.BitWidth), VAL(0) { 00246 assert(BitWidth && "bitwidth too small"); 00247 if (isSingleWord()) 00248 VAL = that.VAL; 00249 else 00250 initSlowCase(that); 00251 } 00252 00253 /// @brief Destructor. 00254 ~APInt() { 00255 if (!isSingleWord()) 00256 delete [] pVal; 00257 } 00258 00259 /// Default constructor that creates an uninitialized APInt. This is useful 00260 /// for object deserialization (pair this with the static method Read). 00261 explicit APInt() : BitWidth(1) {} 00262 00263 /// Profile - Used to insert APInt objects, or objects that contain APInt 00264 /// objects, into FoldingSets. 00265 void Profile(FoldingSetNodeID& id) const; 00266 00267 /// @brief Used by the Bitcode serializer to emit APInts to Bitcode. 00268 void Emit(Serializer& S) const; 00269 00270 /// @brief Used by the Bitcode deserializer to deserialize APInts. 00271 void Read(Deserializer& D); 00272 00273 /// @} 00274 /// @name Value Tests 00275 /// @{ 00276 /// This tests the high bit of this APInt to determine if it is set. 00277 /// @returns true if this APInt is negative, false otherwise 00278 /// @brief Determine sign of this APInt. 00279 bool isNegative() const { 00280 return (*this)[BitWidth - 1]; 00281 } 00282 00283 /// This tests the high bit of the APInt to determine if it is unset. 00284 /// @brief Determine if this APInt Value is non-negative (>= 0) 00285 bool isNonNegative() const { 00286 return !isNegative(); 00287 } 00288 00289 /// This tests if the value of this APInt is positive (> 0). Note 00290 /// that 0 is not a positive value. 00291 /// @returns true if this APInt is positive. 00292 /// @brief Determine if this APInt Value is positive. 00293 bool isStrictlyPositive() const { 00294 return isNonNegative() && (*this) != 0; 00295 } 00296 00297 /// This checks to see if the value has all bits of the APInt are set or not. 00298 /// @brief Determine if all bits are set 00299 bool isAllOnesValue() const { 00300 return countPopulation() == BitWidth; 00301 } 00302 00303 /// This checks to see if the value of this APInt is the maximum unsigned 00304 /// value for the APInt's bit width. 00305 /// @brief Determine if this is the largest unsigned value. 00306 bool isMaxValue() const { 00307 return countPopulation() == BitWidth; 00308 } 00309 00310 /// This checks to see if the value of this APInt is the maximum signed 00311 /// value for the APInt's bit width. 00312 /// @brief Determine if this is the largest signed value. 00313 bool isMaxSignedValue() const { 00314 return BitWidth == 1 ? VAL == 0 : 00315 !isNegative() && countPopulation() == BitWidth - 1; 00316 } 00317 00318 /// This checks to see if the value of this APInt is the minimum unsigned 00319 /// value for the APInt's bit width. 00320 /// @brief Determine if this is the smallest unsigned value. 00321 bool isMinValue() const { 00322 return countPopulation() == 0; 00323 } 00324 00325 /// This checks to see if the value of this APInt is the minimum signed 00326 /// value for the APInt's bit width. 00327 /// @brief Determine if this is the smallest signed value. 00328 bool isMinSignedValue() const { 00329 return BitWidth == 1 ? VAL == 1 : 00330 isNegative() && countPopulation() == 1; 00331 } 00332 00333 /// @brief Check if this APInt has an N-bits unsigned integer value. 00334 bool isIntN(unsigned N) const { 00335 assert(N && "N == 0 ???"); 00336 if (N >= getBitWidth()) 00337 return true; 00338 00339 if (isSingleWord()) 00340 return VAL == (VAL & (~0ULL >> (64 - N))); 00341 APInt Tmp(N, getNumWords(), pVal); 00342 Tmp.zext(getBitWidth()); 00343 return Tmp == (*this); 00344 } 00345 00346 /// @brief Check if this APInt has an N-bits signed integer value. 00347 bool isSignedIntN(unsigned N) const { 00348 assert(N && "N == 0 ???"); 00349 return getMinSignedBits() <= N; 00350 } 00351 00352 /// @returns true if the argument APInt value is a power of two > 0. 00353 bool isPowerOf2() const; 00354 00355 /// isSignBit - Return true if this is the value returned by getSignBit. 00356 bool isSignBit() const { return isMinSignedValue(); } 00357 00358 /// This converts the APInt to a boolean value as a test against zero. 00359 /// @brief Boolean conversion function. 00360 bool getBoolValue() const { 00361 return *this != 0; 00362 } 00363 00364 /// getLimitedValue - If this value is smaller than the specified limit, 00365 /// return it, otherwise return the limit value. This causes the value 00366 /// to saturate to the limit. 00367 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const { 00368 return (getActiveBits() > 64 || getZExtValue() > Limit) ? 00369 Limit : getZExtValue(); 00370 } 00371 00372 /// @} 00373 /// @name Value Generators 00374 /// @{ 00375 /// @brief Gets maximum unsigned value of APInt for specific bit width. 00376 static APInt getMaxValue(unsigned numBits) { 00377 return APInt(numBits, 0).set(); 00378 } 00379 00380 /// @brief Gets maximum signed value of APInt for a specific bit width. 00381 static APInt getSignedMaxValue(unsigned numBits) { 00382 return APInt(numBits, 0).set().clear(numBits - 1); 00383 } 00384 00385 /// @brief Gets minimum unsigned value of APInt for a specific bit width. 00386 static APInt getMinValue(unsigned numBits) { 00387 return APInt(numBits, 0); 00388 } 00389 00390 /// @brief Gets minimum signed value of APInt for a specific bit width. 00391 static APInt getSignedMinValue(unsigned numBits) { 00392 return APInt(numBits, 0).set(numBits - 1); 00393 } 00394 00395 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and 00396 /// it helps code readability when we want to get a SignBit. 00397 /// @brief Get the SignBit for a specific bit width. 00398 static APInt getSignBit(unsigned BitWidth) { 00399 return getSignedMinValue(BitWidth); 00400 } 00401 00402 /// @returns the all-ones value for an APInt of the specified bit-width. 00403 /// @brief Get the all-ones value. 00404 static APInt getAllOnesValue(unsigned numBits) { 00405 return APInt(numBits, 0).set(); 00406 } 00407 00408 /// @returns the '0' value for an APInt of the specified bit-width. 00409 /// @brief Get the '0' value. 00410 static APInt getNullValue(unsigned numBits) { 00411 return APInt(numBits, 0); 00412 } 00413 00414 /// Get an APInt with the same BitWidth as this APInt, just zero mask 00415 /// the low bits and right shift to the least significant bit. 00416 /// @returns the high "numBits" bits of this APInt. 00417 APInt getHiBits(unsigned numBits) const; 00418 00419 /// Get an APInt with the same BitWidth as this APInt, just zero mask 00420 /// the high bits. 00421 /// @returns the low "numBits" bits of this APInt. 00422 APInt getLoBits(unsigned numBits) const; 00423 00424 /// Constructs an APInt value that has a contiguous range of bits set. The 00425 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other 00426 /// bits will be zero. For example, with parameters(32, 0, 16) you would get 00427 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For 00428 /// example, with parameters (32, 28, 4), you would get 0xF000000F. 00429 /// @param numBits the intended bit width of the result 00430 /// @param loBit the index of the lowest bit set. 00431 /// @param hiBit the index of the highest bit set. 00432 /// @returns An APInt value with the requested bits set. 00433 /// @brief Get a value with a block of bits set. 00434 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) { 00435 assert(hiBit <= numBits && "hiBit out of range"); 00436 assert(loBit < numBits && "loBit out of range"); 00437 if (hiBit < loBit) 00438 return getLowBitsSet(numBits, hiBit) | 00439 getHighBitsSet(numBits, numBits-loBit); 00440 return getLowBitsSet(numBits, hiBit-loBit).shl(loBit); 00441 } 00442 00443 /// Constructs an APInt value that has the top hiBitsSet bits set. 00444 /// @param numBits the bitwidth of the result 00445 /// @param hiBitsSet the number of high-order bits set in the result. 00446 /// @brief Get a value with high bits set 00447 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) { 00448 assert(hiBitsSet <= numBits && "Too many bits to set!"); 00449 // Handle a degenerate case, to avoid shifting by word size 00450 if (hiBitsSet == 0) 00451 return APInt(numBits, 0); 00452 unsigned shiftAmt = numBits - hiBitsSet; 00453 // For small values, return quickly 00454 if (numBits <= APINT_BITS_PER_WORD) 00455 return APInt(numBits, ~0ULL << shiftAmt); 00456 return (~APInt(numBits, 0)).shl(shiftAmt); 00457 } 00458 00459 /// Constructs an APInt value that has the bottom loBitsSet bits set. 00460 /// @param numBits the bitwidth of the result 00461 /// @param loBitsSet the number of low-order bits set in the result. 00462 /// @brief Get a value with low bits set 00463 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) { 00464 assert(loBitsSet <= numBits && "Too many bits to set!"); 00465 // Handle a degenerate case, to avoid shifting by word size 00466 if (loBitsSet == 0) 00467 return APInt(numBits, 0); 00468 if (loBitsSet == APINT_BITS_PER_WORD) 00469 return APInt(numBits, -1ULL); 00470 // For small values, return quickly. 00471 if (numBits < APINT_BITS_PER_WORD) 00472 return APInt(numBits, (1ULL << loBitsSet) - 1); 00473 return (~APInt(numBits, 0)).lshr(numBits - loBitsSet); 00474 } 00475 00476 /// The hash value is computed as the sum of the words and the bit width. 00477 /// @returns A hash value computed from the sum of the APInt words. 00478 /// @brief Get a hash value based on this APInt 00479 uint64_t getHashValue() const; 00480 00481 /// This function returns a pointer to the internal storage of the APInt. 00482 /// This is useful for writing out the APInt in binary form without any 00483 /// conversions. 00484 const uint64_t* getRawData() const { 00485 if (isSingleWord()) 00486 return &VAL; 00487 return &pVal[0]; 00488 } 00489 00490 /// @} 00491 /// @name Unary Operators 00492 /// @{ 00493 /// @returns a new APInt value representing *this incremented by one 00494 /// @brief Postfix increment operator. 00495 const APInt operator++(int) { 00496 APInt API(*this); 00497 ++(*this); 00498 return API; 00499 } 00500 00501 /// @returns *this incremented by one 00502 /// @brief Prefix increment operator. 00503 APInt& operator++(); 00504 00505 /// @returns a new APInt representing *this decremented by one. 00506 /// @brief Postfix decrement operator. 00507 const APInt operator--(int) { 00508 APInt API(*this); 00509 --(*this); 00510 return API; 00511 } 00512 00513 /// @returns *this decremented by one. 00514 /// @brief Prefix decrement operator. 00515 APInt& operator--(); 00516 00517 /// Performs a bitwise complement operation on this APInt. 00518 /// @returns an APInt that is the bitwise complement of *this 00519 /// @brief Unary bitwise complement operator. 00520 APInt operator~() const { 00521 APInt Result(*this); 00522 Result.flip(); 00523 return Result; 00524 } 00525 00526 /// Negates *this using two's complement logic. 00527 /// @returns An APInt value representing the negation of *this. 00528 /// @brief Unary negation operator 00529 APInt operator-() const { 00530 return APInt(BitWidth, 0) - (*this); 00531 } 00532 00533 /// Performs logical negation operation on this APInt. 00534 /// @returns true if *this is zero, false otherwise. 00535 /// @brief Logical negation operator. 00536 bool operator!() const; 00537 00538 /// @} 00539 /// @name Assignment Operators 00540 /// @{ 00541 /// @returns *this after assignment of RHS. 00542 /// @brief Copy assignment operator. 00543 APInt& operator=(const APInt& RHS) { 00544 // If the bitwidths are the same, we can avoid mucking with memory 00545 if (isSingleWord() && RHS.isSingleWord()) { 00546 VAL = RHS.VAL; 00547 BitWidth = RHS.BitWidth; 00548 return clearUnusedBits(); 00549 } 00550 00551 return AssignSlowCase(RHS); 00552 } 00553 00554 /// The RHS value is assigned to *this. If the significant bits in RHS exceed 00555 /// the bit width, the excess bits are truncated. If the bit width is larger 00556 /// than 64, the value is zero filled in the unspecified high order bits. 00557 /// @returns *this after assignment of RHS value. 00558 /// @brief Assignment operator. 00559 APInt& operator=(uint64_t RHS); 00560 00561 /// Performs a bitwise AND operation on this APInt and RHS. The result is 00562 /// assigned to *this. 00563 /// @returns *this after ANDing with RHS. 00564 /// @brief Bitwise AND assignment operator. 00565 APInt& operator&=(const APInt& RHS); 00566 00567 /// Performs a bitwise OR operation on this APInt and RHS. The result is 00568 /// assigned *this; 00569 /// @returns *this after ORing with RHS. 00570 /// @brief Bitwise OR assignment operator. 00571 APInt& operator|=(const APInt& RHS); 00572 00573 /// Performs a bitwise XOR operation on this APInt and RHS. The result is 00574 /// assigned to *this. 00575 /// @returns *this after XORing with RHS. 00576 /// @brief Bitwise XOR assignment operator. 00577 APInt& operator^=(const APInt& RHS); 00578 00579 /// Multiplies this APInt by RHS and assigns the result to *this. 00580 /// @returns *this 00581 /// @brief Multiplication assignment operator. 00582 APInt& operator*=(const APInt& RHS); 00583 00584 /// Adds RHS to *this and assigns the result to *this. 00585 /// @returns *this 00586 /// @brief Addition assignment operator. 00587 APInt& operator+=(const APInt& RHS); 00588 00589 /// Subtracts RHS from *this and assigns the result to *this. 00590 /// @returns *this 00591 /// @brief Subtraction assignment operator. 00592 APInt& operator-=(const APInt& RHS); 00593 00594 /// Shifts *this left by shiftAmt and assigns the result to *this. 00595 /// @returns *this after shifting left by shiftAmt 00596 /// @brief Left-shift assignment function. 00597 APInt& operator<<=(unsigned shiftAmt) { 00598 *this = shl(shiftAmt); 00599 return *this; 00600 } 00601 00602 /// @} 00603 /// @name Binary Operators 00604 /// @{ 00605 /// Performs a bitwise AND operation on *this and RHS. 00606 /// @returns An APInt value representing the bitwise AND of *this and RHS. 00607 /// @brief Bitwise AND operator. 00608 APInt operator&(const APInt& RHS) const { 00609 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 00610 if (isSingleWord()) 00611 return APInt(getBitWidth(), VAL & RHS.VAL); 00612 return AndSlowCase(RHS); 00613 } 00614 APInt And(const APInt& RHS) const { 00615 return this->operator&(RHS); 00616 } 00617 00618 /// Performs a bitwise OR operation on *this and RHS. 00619 /// @returns An APInt value representing the bitwise OR of *this and RHS. 00620 /// @brief Bitwise OR operator. 00621 APInt operator|(const APInt& RHS) const { 00622 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 00623 if (isSingleWord()) 00624 return APInt(getBitWidth(), VAL | RHS.VAL); 00625 return OrSlowCase(RHS); 00626 } 00627 APInt Or(const APInt& RHS) const { 00628 return this->operator|(RHS); 00629 } 00630 00631 /// Performs a bitwise XOR operation on *this and RHS. 00632 /// @returns An APInt value representing the bitwise XOR of *this and RHS. 00633 /// @brief Bitwise XOR operator. 00634 APInt operator^(const APInt& RHS) const { 00635 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 00636 if (isSingleWord()) 00637 return APInt(BitWidth, VAL ^ RHS.VAL); 00638 return XorSlowCase(RHS); 00639 } 00640 APInt Xor(const APInt& RHS) const { 00641 return this->operator^(RHS); 00642 } 00643 00644 /// Multiplies this APInt by RHS and returns the result. 00645 /// @brief Multiplication operator. 00646 APInt operator*(const APInt& RHS) const; 00647 00648 /// Adds RHS to this APInt and returns the result. 00649 /// @brief Addition operator. 00650 APInt operator+(const APInt& RHS) const; 00651 APInt operator+(uint64_t RHS) const { 00652 return (*this) + APInt(BitWidth, RHS); 00653 } 00654 00655 /// Subtracts RHS from this APInt and returns the result. 00656 /// @brief Subtraction operator. 00657 APInt operator-(const APInt& RHS) const; 00658 APInt operator-(uint64_t RHS) const { 00659 return (*this) - APInt(BitWidth, RHS); 00660 } 00661 00662 APInt operator<<(unsigned Bits) const { 00663 return shl(Bits); 00664 } 00665 00666 APInt operator<<(const APInt &Bits) const { 00667 return shl(Bits); 00668 } 00669 00670 /// Arithmetic right-shift this APInt by shiftAmt. 00671 /// @brief Arithmetic right-shift function. 00672 APInt ashr(unsigned shiftAmt) const; 00673 00674 /// Logical right-shift this APInt by shiftAmt. 00675 /// @brief Logical right-shift function. 00676 APInt lshr(unsigned shiftAmt) const; 00677 00678 /// Left-shift this APInt by shiftAmt. 00679 /// @brief Left-shift function. 00680 APInt shl(unsigned shiftAmt) const { 00681 assert(shiftAmt <= BitWidth && "Invalid shift amount"); 00682 if (isSingleWord()) { 00683 if (shiftAmt == BitWidth) 00684 return APInt(BitWidth, 0); // avoid undefined shift results 00685 return APInt(BitWidth, VAL << shiftAmt); 00686 } 00687 return shlSlowCase(shiftAmt); 00688 } 00689 00690 /// @brief Rotate left by rotateAmt. 00691 APInt rotl(unsigned rotateAmt) const; 00692 00693 /// @brief Rotate right by rotateAmt. 00694 APInt rotr(unsigned rotateAmt) const; 00695 00696 /// Arithmetic right-shift this APInt by shiftAmt. 00697 /// @brief Arithmetic right-shift function. 00698 APInt ashr(const APInt &shiftAmt) const; 00699 00700 /// Logical right-shift this APInt by shiftAmt. 00701 /// @brief Logical right-shift function. 00702 APInt lshr(const APInt &shiftAmt) const; 00703 00704 /// Left-shift this APInt by shiftAmt. 00705 /// @brief Left-shift function. 00706 APInt shl(const APInt &shiftAmt) const; 00707 00708 /// @brief Rotate left by rotateAmt. 00709 APInt rotl(const APInt &rotateAmt) const; 00710 00711 /// @brief Rotate right by rotateAmt. 00712 APInt rotr(const APInt &rotateAmt) const; 00713 00714 /// Perform an unsigned divide operation on this APInt by RHS. Both this and 00715 /// RHS are treated as unsigned quantities for purposes of this division. 00716 /// @returns a new APInt value containing the division result 00717 /// @brief Unsigned division operation. 00718 APInt udiv(const APInt& RHS) const; 00719 00720 /// Signed divide this APInt by APInt RHS. 00721 /// @brief Signed division function for APInt. 00722 APInt sdiv(const APInt& RHS) const { 00723 if (isNegative()) 00724 if (RHS.isNegative()) 00725 return (-(*this)).udiv(-RHS); 00726 else 00727 return -((-(*this)).udiv(RHS)); 00728 else if (RHS.isNegative()) 00729 return -(this->udiv(-RHS)); 00730 return this->udiv(RHS); 00731 } 00732 00733 /// Perform an unsigned remainder operation on this APInt with RHS being the 00734 /// divisor. Both this and RHS are treated as unsigned quantities for purposes 00735 /// of this operation. Note that this is a true remainder operation and not 00736 /// a modulo operation because the sign follows the sign of the dividend 00737 /// which is *this. 00738 /// @returns a new APInt value containing the remainder result 00739 /// @brief Unsigned remainder operation. 00740 APInt urem(const APInt& RHS) const; 00741 00742 /// Signed remainder operation on APInt. 00743 /// @brief Function for signed remainder operation. 00744 APInt srem(const APInt& RHS) const { 00745 if (isNegative()) 00746 if (RHS.isNegative()) 00747 return -((-(*this)).urem(-RHS)); 00748 else 00749 return -((-(*this)).urem(RHS)); 00750 else if (RHS.isNegative()) 00751 return this->urem(-RHS); 00752 return this->urem(RHS); 00753 } 00754 00755 /// Sometimes it is convenient to divide two APInt values and obtain both the 00756 /// quotient and remainder. This function does both operations in the same 00757 /// computation making it a little more efficient. The pair of input arguments 00758 /// may overlap with the pair of output arguments. It is safe to call 00759 /// udivrem(X, Y, X, Y), for example. 00760 /// @brief Dual division/remainder interface. 00761 static void udivrem(const APInt &LHS, const APInt &RHS, 00762 APInt &Quotient, APInt &Remainder); 00763 00764 static void sdivrem(const APInt &LHS, const APInt &RHS, 00765 APInt &Quotient, APInt &Remainder) 00766 { 00767 if (LHS.isNegative()) { 00768 if (RHS.isNegative()) 00769 APInt::udivrem(-LHS, -RHS, Quotient, Remainder); 00770 else 00771 APInt::udivrem(-LHS, RHS, Quotient, Remainder); 00772 Quotient = -Quotient; 00773 Remainder = -Remainder; 00774 } else if (RHS.isNegative()) { 00775 APInt::udivrem(LHS, -RHS, Quotient, Remainder); 00776 Quotient = -Quotient; 00777 } else { 00778 APInt::udivrem(LHS, RHS, Quotient, Remainder); 00779 } 00780 } 00781 00782 /// @returns the bit value at bitPosition 00783 /// @brief Array-indexing support. 00784 bool operator[](unsigned bitPosition) const; 00785 00786 /// @} 00787 /// @name Comparison Operators 00788 /// @{ 00789 /// Compares this APInt with RHS for the validity of the equality 00790 /// relationship. 00791 /// @brief Equality operator. 00792 bool operator==(const APInt& RHS) const { 00793 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths"); 00794 if (isSingleWord()) 00795 return VAL == RHS.VAL; 00796 return EqualSlowCase(RHS); 00797 } 00798 00799 /// Compares this APInt with a uint64_t for the validity of the equality 00800 /// relationship. 00801 /// @returns true if *this == Val 00802 /// @brief Equality operator. 00803 bool operator==(uint64_t Val) const { 00804 if (isSingleWord()) 00805 return VAL == Val; 00806 return EqualSlowCase(Val); 00807 } 00808 00809 /// Compares this APInt with RHS for the validity of the equality 00810 /// relationship. 00811 /// @returns true if *this == Val 00812 /// @brief Equality comparison. 00813 bool eq(const APInt &RHS) const { 00814 return (*this) == RHS; 00815 } 00816 00817 /// Compares this APInt with RHS for the validity of the inequality 00818 /// relationship. 00819 /// @returns true if *this != Val 00820 /// @brief Inequality operator. 00821 bool operator!=(const APInt& RHS) const { 00822 return !((*this) == RHS); 00823 } 00824 00825 /// Compares this APInt with a uint64_t for the validity of the inequality 00826 /// relationship. 00827 /// @returns true if *this != Val 00828 /// @brief Inequality operator. 00829 bool operator!=(uint64_t Val) const { 00830 return !((*this) == Val); 00831 } 00832 00833 /// Compares this APInt with RHS for the validity of the inequality 00834 /// relationship. 00835 /// @returns true if *this != Val 00836 /// @brief Inequality comparison 00837 bool ne(const APInt &RHS) const { 00838 return !((*this) == RHS); 00839 } 00840 00841 /// Regards both *this and RHS as unsigned quantities and compares them for 00842 /// the validity of the less-than relationship. 00843 /// @returns true if *this < RHS when both are considered unsigned. 00844 /// @brief Unsigned less than comparison 00845 bool ult(const APInt& RHS) const; 00846 00847 /// Regards both *this and RHS as signed quantities and compares them for 00848 /// validity of the less-than relationship. 00849 /// @returns true if *this < RHS when both are considered signed. 00850 /// @brief Signed less than comparison 00851 bool slt(const APInt& RHS) const; 00852 00853 /// Regards both *this and RHS as unsigned quantities and compares them for 00854 /// validity of the less-or-equal relationship. 00855 /// @returns true if *this <= RHS when both are considered unsigned. 00856 /// @brief Unsigned less or equal comparison 00857 bool ule(const APInt& RHS) const { 00858 return ult(RHS) || eq(RHS); 00859 } 00860 00861 /// Regards both *this and RHS as signed quantities and compares them for 00862 /// validity of the less-or-equal relationship. 00863 /// @returns true if *this <= RHS when both are considered signed. 00864 /// @brief Signed less or equal comparison 00865 bool sle(const APInt& RHS) const { 00866 return slt(RHS) || eq(RHS); 00867 } 00868 00869 /// Regards both *this and RHS as unsigned quantities and compares them for 00870 /// the validity of the greater-than relationship. 00871 /// @returns true if *this > RHS when both are considered unsigned. 00872 /// @brief Unsigned greather than comparison 00873 bool ugt(const APInt& RHS) const { 00874 return !ult(RHS) && !eq(RHS); 00875 } 00876 00877 /// Regards both *this and RHS as signed quantities and compares them for 00878 /// the validity of the greater-than relationship. 00879 /// @returns true if *this > RHS when both are considered signed. 00880 /// @brief Signed greather than comparison 00881 bool sgt(const APInt& RHS) const { 00882 return !slt(RHS) && !eq(RHS); 00883 } 00884 00885 /// Regards both *this and RHS as unsigned quantities and compares them for 00886 /// validity of the greater-or-equal relationship. 00887 /// @returns true if *this >= RHS when both are considered unsigned. 00888 /// @brief Unsigned greater or equal comparison 00889 bool uge(const APInt& RHS) const { 00890 return !ult(RHS); 00891 } 00892 00893 /// Regards both *this and RHS as signed quantities and compares them for 00894 /// validity of the greater-or-equal relationship. 00895 /// @returns true if *this >= RHS when both are considered signed. 00896 /// @brief Signed greather or equal comparison 00897 bool sge(const APInt& RHS) const { 00898 return !slt(RHS); 00899 } 00900 00901 /// This operation tests if there are any pairs of corresponding bits 00902 /// between this APInt and RHS that are both set. 00903 bool intersects(const APInt &RHS) const { 00904 return (*this & RHS) != 0; 00905 } 00906 00907 /// @} 00908 /// @name Resizing Operators 00909 /// @{ 00910 /// Truncate the APInt to a specified width. It is an error to specify a width 00911 /// that is greater than or equal to the current width. 00912 /// @brief Truncate to new width. 00913 APInt &trunc(unsigned width); 00914 00915 /// This operation sign extends the APInt to a new width. If the high order 00916 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero. 00917 /// It is an error to specify a width that is less than or equal to the 00918 /// current width. 00919 /// @brief Sign extend to a new width. 00920 APInt &sext(unsigned width); 00921 00922 /// This operation zero extends the APInt to a new width. The high order bits 00923 /// are filled with 0 bits. It is an error to specify a width that is less 00924 /// than or equal to the current width. 00925 /// @brief Zero extend to a new width. 00926 APInt &zext(unsigned width); 00927 00928 /// Make this APInt have the bit width given by \p width. The value is sign 00929 /// extended, truncated, or left alone to make it that width. 00930 /// @brief Sign extend or truncate to width 00931 APInt &sextOrTrunc(unsigned width); 00932 00933 /// Make this APInt have the bit width given by \p width. The value is zero 00934 /// extended, truncated, or left alone to make it that width. 00935 /// @brief Zero extend or truncate to width 00936 APInt &zextOrTrunc(unsigned width); 00937 00938 /// @} 00939 /// @name Bit Manipulation Operators 00940 /// @{ 00941 /// @brief Set every bit to 1. 00942 APInt& set() { 00943 if (isSingleWord()) { 00944 VAL = -1ULL; 00945 return clearUnusedBits(); 00946 } 00947 00948 // Set all the bits in all the words. 00949 for (unsigned i = 0; i < getNumWords(); ++i) 00950 pVal[i] = -1ULL; 00951 // Clear the unused ones 00952 return clearUnusedBits(); 00953 } 00954 00955 /// Set the given bit to 1 whose position is given as "bitPosition". 00956 /// @brief Set a given bit to 1. 00957 APInt& set(unsigned bitPosition); 00958 00959 /// @brief Set every bit to 0. 00960 APInt& clear() { 00961 if (isSingleWord()) 00962 VAL = 0; 00963 else 00964 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE); 00965 return *this; 00966 } 00967 00968 /// Set the given bit to 0 whose position is given as "bitPosition". 00969 /// @brief Set a given bit to 0. 00970 APInt& clear(unsigned bitPosition); 00971 00972 /// @brief Toggle every bit to its opposite value. 00973 APInt& flip() { 00974 if (isSingleWord()) { 00975 VAL ^= -1ULL; 00976 return clearUnusedBits(); 00977 } 00978 for (unsigned i = 0; i < getNumWords(); ++i) 00979 pVal[i] ^= -1ULL; 00980 return clearUnusedBits(); 00981 } 00982 00983 /// Toggle a given bit to its opposite value whose position is given 00984 /// as "bitPosition". 00985 /// @brief Toggles a given bit to its opposite value. 00986 APInt& flip(unsigned bitPosition); 00987 00988 /// @} 00989 /// @name Value Characterization Functions 00990 /// @{ 00991 00992 /// @returns the total number of bits. 00993 unsigned getBitWidth() const { 00994 return BitWidth; 00995 } 00996 00997 /// Here one word's bitwidth equals to that of uint64_t. 00998 /// @returns the number of words to hold the integer value of this APInt. 00999 /// @brief Get the number of words. 01000 unsigned getNumWords() const { 01001 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD; 01002 } 01003 01004 /// This function returns the number of active bits which is defined as the 01005 /// bit width minus the number of leading zeros. This is used in several 01006 /// computations to see how "wide" the value is. 01007 /// @brief Compute the number of active bits in the value 01008 unsigned getActiveBits() const { 01009 return BitWidth - countLeadingZeros(); 01010 } 01011 01012 /// This function returns the number of active words in the value of this 01013 /// APInt. This is used in conjunction with getActiveData to extract the raw 01014 /// value of the APInt. 01015 unsigned getActiveWords() const { 01016 return whichWord(getActiveBits()-1) + 1; 01017 } 01018 01019 /// Computes the minimum bit width for this APInt while considering it to be 01020 /// a signed (and probably negative) value. If the value is not negative, 01021 /// this function returns the same value as getActiveBits()+1. Otherwise, it 01022 /// returns the smallest bit width that will retain the negative value. For 01023 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so 01024 /// for -1, this function will always return 1. 01025 /// @brief Get the minimum bit size for this signed APInt 01026 unsigned getMinSignedBits() const { 01027 if (isNegative()) 01028 return BitWidth - countLeadingOnes() + 1; 01029 return getActiveBits()+1; 01030 } 01031 01032 /// This method attempts to return the value of this APInt as a zero extended 01033 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a 01034 /// uint64_t. Otherwise an assertion will result. 01035 /// @brief Get zero extended value 01036 uint64_t getZExtValue() const { 01037 if (isSingleWord()) 01038 return VAL; 01039 assert(getActiveBits() <= 64 && "Too many bits for uint64_t"); 01040 return pVal[0]; 01041 } 01042 01043 /// This method attempts to return the value of this APInt as a sign extended 01044 /// int64_t. The bit width must be <= 64 or the value must fit within an 01045 /// int64_t. Otherwise an assertion will result. 01046 /// @brief Get sign extended value 01047 int64_t getSExtValue() const { 01048 if (isSingleWord()) 01049 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >> 01050 (APINT_BITS_PER_WORD - BitWidth); 01051 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t"); 01052 return int64_t(pVal[0]); 01053 } 01054 01055 /// This method determines how many bits are required to hold the APInt 01056 /// equivalent of the string given by \p str of length \p slen. 01057 /// @brief Get bits required for string value. 01058 static unsigned getBitsNeeded(const char* str, unsigned slen, uint8_t radix); 01059 01060 /// countLeadingZeros - This function is an APInt version of the 01061 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number 01062 /// of zeros from the most significant bit to the first one bit. 01063 /// @returns BitWidth if the value is zero. 01064 /// @returns the number of zeros from the most significant bit to the first 01065 /// one bits. 01066 unsigned countLeadingZeros() const { 01067 if (isSingleWord()) { 01068 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth; 01069 return CountLeadingZeros_64(VAL) - unusedBits; 01070 } 01071 return countLeadingZerosSlowCase(); 01072 } 01073 01074 /// countLeadingOnes - This function is an APInt version of the 01075 /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number 01076 /// of ones from the most significant bit to the first zero bit. 01077 /// @returns 0 if the high order bit is not set 01078 /// @returns the number of 1 bits from the most significant to the least 01079 /// @brief Count the number of leading one bits. 01080 unsigned countLeadingOnes() const; 01081 01082 /// countTrailingZeros - This function is an APInt version of the 01083 /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts 01084 /// the number of zeros from the least significant bit to the first set bit. 01085 /// @returns BitWidth if the value is zero. 01086 /// @returns the number of zeros from the least significant bit to the first 01087 /// one bit. 01088 /// @brief Count the number of trailing zero bits. 01089 unsigned countTrailingZeros() const; 01090 01091 /// countTrailingOnes - This function is an APInt version of the 01092 /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts 01093 /// the number of ones from the least significant bit to the first zero bit. 01094 /// @returns BitWidth if the value is all ones. 01095 /// @returns the number of ones from the least significant bit to the first 01096 /// zero bit. 01097 /// @brief Count the number of trailing one bits. 01098 unsigned countTrailingOnes() const { 01099 if (isSingleWord()) 01100 return CountTrailingOnes_64(VAL); 01101 return countTrailingOnesSlowCase(); 01102 } 01103 01104 /// countPopulation - This function is an APInt version of the 01105 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number 01106 /// of 1 bits in the APInt value. 01107 /// @returns 0 if the value is zero. 01108 /// @returns the number of set bits. 01109 /// @brief Count the number of bits set. 01110 unsigned countPopulation() const { 01111 if (isSingleWord()) 01112 return CountPopulation_64(VAL); 01113 return countPopulationSlowCase(); 01114 } 01115 01116 /// @} 01117 /// @name Conversion Functions 01118 /// @{ 01119 void print(raw_ostream &OS, bool isSigned) const; 01120 01121 /// toString - Converts an APInt to a string and append it to Str. Str is 01122 /// commonly a SmallString. 01123 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed) const; 01124 01125 /// Considers the APInt to be unsigned and converts it into a string in the 01126 /// radix given. The radix can be 2, 8, 10 or 16. 01127 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const { 01128 return toString(Str, Radix, false); 01129 } 01130 01131 /// Considers the APInt to be signed and converts it into a string in the 01132 /// radix given. The radix can be 2, 8, 10 or 16. 01133 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const { 01134 return toString(Str, Radix, true); 01135 } 01136 01137 /// toString - This returns the APInt as a std::string. Note that this is an 01138 /// inefficient method. It is better to pass in a SmallVector/SmallString 01139 /// to the methods above to avoid thrashing the heap for the string. 01140 std::string toString(unsigned Radix, bool Signed) const; 01141 01142 01143 /// @returns a byte-swapped representation of this APInt Value. 01144 APInt byteSwap() const; 01145 01146 /// @brief Converts this APInt to a double value. 01147 double roundToDouble(bool isSigned) const; 01148 01149 /// @brief Converts this unsigned APInt to a double value. 01150 double roundToDouble() const { 01151 return roundToDouble(false); 01152 } 01153 01154 /// @brief Converts this signed APInt to a double value. 01155 double signedRoundToDouble() const { 01156 return roundToDouble(true); 01157 } 01158 01159 /// The conversion does not do a translation from integer to double, it just 01160 /// re-interprets the bits as a double. Note that it is valid to do this on 01161 /// any bit width. Exactly 64 bits will be translated. 01162 /// @brief Converts APInt bits to a double 01163 double bitsToDouble() const { 01164 union { 01165 uint64_t I; 01166 double D; 01167 } T; 01168 T.I = (isSingleWord() ? VAL : pVal[0]); 01169 return T.D; 01170 } 01171 01172 /// The conversion does not do a translation from integer to float, it just 01173 /// re-interprets the bits as a float. Note that it is valid to do this on 01174 /// any bit width. Exactly 32 bits will be translated. 01175 /// @brief Converts APInt bits to a double 01176 float bitsToFloat() const { 01177 union { 01178 unsigned I; 01179 float F; 01180 } T; 01181 T.I = unsigned((isSingleWord() ? VAL : pVal[0])); 01182 return T.F; 01183 } 01184 01185 /// The conversion does not do a translation from double to integer, it just 01186 /// re-interprets the bits of the double. Note that it is valid to do this on 01187 /// any bit width but bits from V may get truncated. 01188 /// @brief Converts a double to APInt bits. 01189 APInt& doubleToBits(double V) { 01190 union { 01191 uint64_t I; 01192 double D; 01193 } T; 01194 T.D = V; 01195 if (isSingleWord()) 01196 VAL = T.I; 01197 else 01198 pVal[0] = T.I; 01199 return clearUnusedBits(); 01200 } 01201 01202 /// The conversion does not do a translation from float to integer, it just 01203 /// re-interprets the bits of the float. Note that it is valid to do this on 01204 /// any bit width but bits from V may get truncated. 01205 /// @brief Converts a float to APInt bits. 01206 APInt& floatToBits(float V) { 01207 union { 01208 unsigned I; 01209 float F; 01210 } T; 01211 T.F = V; 01212 if (isSingleWord()) 01213 VAL = T.I; 01214 else 01215 pVal[0] = T.I; 01216 return clearUnusedBits(); 01217 } 01218 01219 /// @} 01220 /// @name Mathematics Operations 01221 /// @{ 01222 01223 /// @returns the floor log base 2 of this APInt. 01224 unsigned logBase2() const { 01225 return BitWidth - 1 - countLeadingZeros(); 01226 } 01227 01228 /// @returns the log base 2 of this APInt if its an exact power of two, -1 01229 /// otherwise 01230 int32_t exactLogBase2() const { 01231 if (!isPowerOf2()) 01232 return -1; 01233 return logBase2(); 01234 } 01235 01236 /// @brief Compute the square root 01237 APInt sqrt() const; 01238 01239 /// If *this is < 0 then return -(*this), otherwise *this; 01240 /// @brief Get the absolute value; 01241 APInt abs() const { 01242 if (isNegative()) 01243 return -(*this); 01244 return *this; 01245 } 01246 01247 /// @returns the multiplicative inverse for a given modulo. 01248 APInt multiplicativeInverse(const APInt& modulo) const; 01249 01250 /// @} 01251 /// @name Building-block Operations for APInt and APFloat 01252 /// @{ 01253 01254 // These building block operations operate on a representation of 01255 // arbitrary precision, two's-complement, bignum integer values. 01256 // They should be sufficient to implement APInt and APFloat bignum 01257 // requirements. Inputs are generally a pointer to the base of an 01258 // array of integer parts, representing an unsigned bignum, and a 01259 // count of how many parts there are. 01260 01261 /// Sets the least significant part of a bignum to the input value, 01262 /// and zeroes out higher parts. */ 01263 static void tcSet(integerPart *, integerPart, unsigned int); 01264 01265 /// Assign one bignum to another. 01266 static void tcAssign(integerPart *, const integerPart *, unsigned int); 01267 01268 /// Returns true if a bignum is zero, false otherwise. 01269 static bool tcIsZero(const integerPart *, unsigned int); 01270 01271 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based. 01272 static int tcExtractBit(const integerPart *, unsigned int bit); 01273 01274 /// Copy the bit vector of width srcBITS from SRC, starting at bit 01275 /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB 01276 /// becomes the least significant bit of DST. All high bits above 01277 /// srcBITS in DST are zero-filled. 01278 static void tcExtract(integerPart *, unsigned int dstCount, const integerPart *, 01279 unsigned int srcBits, unsigned int srcLSB); 01280 01281 /// Set the given bit of a bignum. Zero-based. 01282 static void tcSetBit(integerPart *, unsigned int bit); 01283 01284 /// Returns the bit number of the least or most significant set bit 01285 /// of a number. If the input number has no bits set -1U is 01286 /// returned. 01287 static unsigned int tcLSB(const integerPart *, unsigned int); 01288 static unsigned int tcMSB(const integerPart *parts, unsigned int n); 01289 01290 /// Negate a bignum in-place. 01291 static void tcNegate(integerPart *, unsigned int); 01292 01293 /// DST += RHS + CARRY where CARRY is zero or one. Returns the 01294 /// carry flag. 01295 static integerPart tcAdd(integerPart *, const integerPart *, 01296 integerPart carry, unsigned); 01297 01298 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the 01299 /// carry flag. 01300 static integerPart tcSubtract(integerPart *, const integerPart *, 01301 integerPart carry, unsigned); 01302 01303 /// DST += SRC * MULTIPLIER + PART if add is true 01304 /// DST = SRC * MULTIPLIER + PART if add is false 01305 /// 01306 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC 01307 /// they must start at the same point, i.e. DST == SRC. 01308 /// 01309 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is 01310 /// returned. Otherwise DST is filled with the least significant 01311 /// DSTPARTS parts of the result, and if all of the omitted higher 01312 /// parts were zero return zero, otherwise overflow occurred and 01313 /// return one. 01314 static int tcMultiplyPart(integerPart *dst, const integerPart *src, 01315 integerPart multiplier, integerPart carry, 01316 unsigned int srcParts, unsigned int dstParts, 01317 bool add); 01318 01319 /// DST = LHS * RHS, where DST has the same width as the operands 01320 /// and is filled with the least significant parts of the result. 01321 /// Returns one if overflow occurred, otherwise zero. DST must be 01322 /// disjoint from both operands. 01323 static int tcMultiply(integerPart *, const integerPart *, 01324 const integerPart *, unsigned); 01325 01326 /// DST = LHS * RHS, where DST has width the sum of the widths of 01327 /// the operands. No overflow occurs. DST must be disjoint from 01328 /// both operands. Returns the number of parts required to hold the 01329 /// result. 01330 static unsigned int tcFullMultiply(integerPart *, const integerPart *, 01331 const integerPart *, unsigned, unsigned); 01332 01333 /// If RHS is zero LHS and REMAINDER are left unchanged, return one. 01334 /// Otherwise set LHS to LHS / RHS with the fractional part 01335 /// discarded, set REMAINDER to the remainder, return zero. i.e. 01336 /// 01337 /// OLD_LHS = RHS * LHS + REMAINDER 01338 /// 01339 /// SCRATCH is a bignum of the same size as the operands and result 01340 /// for use by the routine; its contents need not be initialized 01341 /// and are destroyed. LHS, REMAINDER and SCRATCH must be 01342 /// distinct. 01343 static int tcDivide(integerPart *lhs, const integerPart *rhs, 01344 integerPart *remainder, integerPart *scratch, 01345 unsigned int parts); 01346 01347 /// Shift a bignum left COUNT bits. Shifted in bits are zero. 01348 /// There are no restrictions on COUNT. 01349 static void tcShiftLeft(integerPart *, unsigned int parts, 01350 unsigned int count); 01351 01352 /// Shift a bignum right COUNT bits. Shifted in bits are zero. 01353 /// There are no restrictions on COUNT. 01354 static void tcShiftRight(integerPart *, unsigned int parts, 01355 unsigned int count); 01356 01357 /// The obvious AND, OR and XOR and complement operations. 01358 static void tcAnd(integerPart *, const integerPart *, unsigned int); 01359 static void tcOr(integerPart *, const integerPart *, unsigned int); 01360 static void tcXor(integerPart *, const integerPart *, unsigned int); 01361 static void tcComplement(integerPart *, unsigned int); 01362 01363 /// Comparison (unsigned) of two bignums. 01364 static int tcCompare(const integerPart *, const integerPart *, 01365 unsigned int); 01366 01367 /// Increment a bignum in-place. Return the carry flag. 01368 static integerPart tcIncrement(integerPart *, unsigned int); 01369 01370 /// Set the least significant BITS and clear the rest. 01371 static void tcSetLeastSignificantBits(integerPart *, unsigned int, 01372 unsigned int bits); 01373 01374 /// @brief debug method 01375 void dump() const; 01376 01377 /// @} 01378 }; 01379 01380 inline bool operator==(uint64_t V1, const APInt& V2) { 01381 return V2 == V1; 01382 } 01383 01384 inline bool operator!=(uint64_t V1, const APInt& V2) { 01385 return V2 != V1; 01386 } 01387 01388 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) { 01389 I.print(OS, true); 01390 return OS; 01391 } 01392 01393 namespace APIntOps { 01394 01395 /// @brief Determine the smaller of two APInts considered to be signed. 01396 inline APInt smin(const APInt &A, const APInt &B) { 01397 return A.slt(B) ? A : B; 01398 } 01399 01400 /// @brief Determine the larger of two APInts considered to be signed. 01401 inline APInt smax(const APInt &A, const APInt &B) { 01402 return A.sgt(B) ? A : B; 01403 } 01404 01405 /// @brief Determine the smaller of two APInts considered to be signed. 01406 inline APInt umin(const APInt &A, const APInt &B) { 01407 return A.ult(B) ? A : B; 01408 } 01409 01410 /// @brief Determine the larger of two APInts considered to be unsigned. 01411 inline APInt umax(const APInt &A, const APInt &B) { 01412 return A.ugt(B) ? A : B; 01413 } 01414 01415 /// @brief Check if the specified APInt has a N-bits unsigned integer value. 01416 inline bool isIntN(unsigned N, const APInt& APIVal) { 01417 return APIVal.isIntN(N); 01418 } 01419 01420 /// @brief Check if the specified APInt has a N-bits signed integer value. 01421 inline bool isSignedIntN(unsigned N, const APInt& APIVal) { 01422 return APIVal.isSignedIntN(N); 01423 } 01424 01425 /// @returns true if the argument APInt value is a sequence of ones 01426 /// starting at the least significant bit with the remainder zero. 01427 inline bool isMask(unsigned numBits, const APInt& APIVal) { 01428 return numBits <= APIVal.getBitWidth() && 01429 APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits); 01430 } 01431 01432 /// @returns true if the argument APInt value contains a sequence of ones 01433 /// with the remainder zero. 01434 inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) { 01435 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal); 01436 } 01437 01438 /// @returns a byte-swapped representation of the specified APInt Value. 01439 inline APInt byteSwap(const APInt& APIVal) { 01440 return APIVal.byteSwap(); 01441 } 01442 01443 /// @returns the floor log base 2 of the specified APInt value. 01444 inline unsigned logBase2(const APInt& APIVal) { 01445 return APIVal.logBase2(); 01446 } 01447 01448 /// GreatestCommonDivisor - This function returns the greatest common 01449 /// divisor of the two APInt values using Euclid's algorithm. 01450 /// @returns the greatest common divisor of Val1 and Val2 01451 /// @brief Compute GCD of two APInt values. 01452 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2); 01453 01454 /// Treats the APInt as an unsigned value for conversion purposes. 01455 /// @brief Converts the given APInt to a double value. 01456 inline double RoundAPIntToDouble(const APInt& APIVal) { 01457 return APIVal.roundToDouble(); 01458 } 01459 01460 /// Treats the APInt as a signed value for conversion purposes. 01461 /// @brief Converts the given APInt to a double value. 01462 inline double RoundSignedAPIntToDouble(const APInt& APIVal) { 01463 return APIVal.signedRoundToDouble(); 01464 } 01465 01466 /// @brief Converts the given APInt to a float vlalue. 01467 inline float RoundAPIntToFloat(const APInt& APIVal) { 01468 return float(RoundAPIntToDouble(APIVal)); 01469 } 01470 01471 /// Treast the APInt as a signed value for conversion purposes. 01472 /// @brief Converts the given APInt to a float value. 01473 inline float RoundSignedAPIntToFloat(const APInt& APIVal) { 01474 return float(APIVal.signedRoundToDouble()); 01475 } 01476 01477 /// RoundDoubleToAPInt - This function convert a double value to an APInt value. 01478 /// @brief Converts the given double value into a APInt. 01479 APInt RoundDoubleToAPInt(double Double, unsigned width); 01480 01481 /// RoundFloatToAPInt - Converts a float value into an APInt value. 01482 /// @brief Converts a float value into a APInt. 01483 inline APInt RoundFloatToAPInt(float Float, unsigned width) { 01484 return RoundDoubleToAPInt(double(Float), width); 01485 } 01486 01487 /// Arithmetic right-shift the APInt by shiftAmt. 01488 /// @brief Arithmetic right-shift function. 01489 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) { 01490 return LHS.ashr(shiftAmt); 01491 } 01492 01493 /// Logical right-shift the APInt by shiftAmt. 01494 /// @brief Logical right-shift function. 01495 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) { 01496 return LHS.lshr(shiftAmt); 01497 } 01498 01499 /// Left-shift the APInt by shiftAmt. 01500 /// @brief Left-shift function. 01501 inline APInt shl(const APInt& LHS, unsigned shiftAmt) { 01502 return LHS.shl(shiftAmt); 01503 } 01504 01505 /// Signed divide APInt LHS by APInt RHS. 01506 /// @brief Signed division function for APInt. 01507 inline APInt sdiv(const APInt& LHS, const APInt& RHS) { 01508 return LHS.sdiv(RHS); 01509 } 01510 01511 /// Unsigned divide APInt LHS by APInt RHS. 01512 /// @brief Unsigned division function for APInt. 01513 inline APInt udiv(const APInt& LHS, const APInt& RHS) { 01514 return LHS.udiv(RHS); 01515 } 01516 01517 /// Signed remainder operation on APInt. 01518 /// @brief Function for signed remainder operation. 01519 inline APInt srem(const APInt& LHS, const APInt& RHS) { 01520 return LHS.srem(RHS); 01521 } 01522 01523 /// Unsigned remainder operation on APInt. 01524 /// @brief Function for unsigned remainder operation. 01525 inline APInt urem(const APInt& LHS, const APInt& RHS) { 01526 return LHS.urem(RHS); 01527 } 01528 01529 /// Performs multiplication on APInt values. 01530 /// @brief Function for multiplication operation. 01531 inline APInt mul(const APInt& LHS, const APInt& RHS) { 01532 return LHS * RHS; 01533 } 01534 01535 /// Performs addition on APInt values. 01536 /// @brief Function for addition operation. 01537 inline APInt add(const APInt& LHS, const APInt& RHS) { 01538 return LHS + RHS; 01539 } 01540 01541 /// Performs subtraction on APInt values. 01542 /// @brief Function for subtraction operation. 01543 inline APInt sub(const APInt& LHS, const APInt& RHS) { 01544 return LHS - RHS; 01545 } 01546 01547 /// Performs bitwise AND operation on APInt LHS and 01548 /// APInt RHS. 01549 /// @brief Bitwise AND function for APInt. 01550 inline APInt And(const APInt& LHS, const APInt& RHS) { 01551 return LHS & RHS; 01552 } 01553 01554 /// Performs bitwise OR operation on APInt LHS and APInt RHS. 01555 /// @brief Bitwise OR function for APInt. 01556 inline APInt Or(const APInt& LHS, const APInt& RHS) { 01557 return LHS | RHS; 01558 } 01559 01560 /// Performs bitwise XOR operation on APInt. 01561 /// @brief Bitwise XOR function for APInt. 01562 inline APInt Xor(const APInt& LHS, const APInt& RHS) { 01563 return LHS ^ RHS; 01564 } 01565 01566 /// Performs a bitwise complement operation on APInt. 01567 /// @brief Bitwise complement function. 01568 inline APInt Not(const APInt& APIVal) { 01569 return ~APIVal; 01570 } 01571 01572 } // End of APIntOps namespace 01573 01574 } // End of llvm namespace 01575 01576 #endif