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