1 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// \brief This file implements a class to represent arbitrary precision 12 /// integral constant values and operations on them. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #ifndef LLVM_ADT_APINT_H 17 #define LLVM_ADT_APINT_H 18 19 #include "llvm/Support/Compiler.h" 20 #include "llvm/Support/MathExtras.h" 21 #include <cassert> 22 #include <climits> 23 #include <cstring> 24 #include <string> 25 26 namespace llvm { 27 class FoldingSetNodeID; 28 class StringRef; 29 class hash_code; 30 class raw_ostream; 31 32 template <typename T> class SmallVectorImpl; 33 template <typename T> class ArrayRef; 34 35 class APInt; 36 37 inline APInt operator-(APInt); 38 39 //===----------------------------------------------------------------------===// 40 // APInt Class 41 //===----------------------------------------------------------------------===// 42 43 /// \brief Class for arbitrary precision integers. 44 /// 45 /// APInt is a functional replacement for common case unsigned integer type like 46 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width 47 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more 48 /// than 64-bits of precision. APInt provides a variety of arithmetic operators 49 /// and methods to manipulate integer values of any bit-width. It supports both 50 /// the typical integer arithmetic and comparison operations as well as bitwise 51 /// manipulation. 52 /// 53 /// The class has several invariants worth noting: 54 /// * All bit, byte, and word positions are zero-based. 55 /// * Once the bit width is set, it doesn't change except by the Truncate, 56 /// SignExtend, or ZeroExtend operations. 57 /// * All binary operators must be on APInt instances of the same bit width. 58 /// Attempting to use these operators on instances with different bit 59 /// widths will yield an assertion. 60 /// * The value is stored canonically as an unsigned value. For operations 61 /// where it makes a difference, there are both signed and unsigned variants 62 /// of the operation. For example, sdiv and udiv. However, because the bit 63 /// widths must be the same, operations such as Mul and Add produce the same 64 /// results regardless of whether the values are interpreted as signed or 65 /// not. 66 /// * In general, the class tries to follow the style of computation that LLVM 67 /// uses in its IR. This simplifies its use for LLVM. 68 /// 69 class LLVM_NODISCARD APInt { 70 public: 71 typedef uint64_t WordType; 72 73 /// This enum is used to hold the constants we needed for APInt. 74 enum : unsigned { 75 /// Byte size of a word. 76 APINT_WORD_SIZE = sizeof(WordType), 77 /// Bits in a word. 78 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT 79 }; 80 81 static const WordType WORD_MAX = ~WordType(0); 82 83 private: 84 /// This union is used to store the integer value. When the 85 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal. 86 union { 87 uint64_t VAL; ///< Used to store the <= 64 bits integer value. 88 uint64_t *pVal; ///< Used to store the >64 bits integer value. 89 } U; 90 91 unsigned BitWidth; ///< The number of bits in this APInt. 92 93 friend struct DenseMapAPIntKeyInfo; 94 95 friend class APSInt; 96 97 /// \brief Fast internal constructor 98 /// 99 /// This constructor is used only internally for speed of construction of 100 /// temporaries. It is unsafe for general use so it is not public. 101 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) { 102 U.pVal = val; 103 } 104 105 /// \brief Determine if this APInt just has one word to store value. 106 /// 107 /// \returns true if the number of bits <= 64, false otherwise. 108 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; } 109 110 /// \brief Determine which word a bit is in. 111 /// 112 /// \returns the word position for the specified bit position. 113 static unsigned whichWord(unsigned bitPosition) { 114 return bitPosition / APINT_BITS_PER_WORD; 115 } 116 117 /// \brief Determine which bit in a word a bit is in. 118 /// 119 /// \returns the bit position in a word for the specified bit position 120 /// in the APInt. 121 static unsigned whichBit(unsigned bitPosition) { 122 return bitPosition % APINT_BITS_PER_WORD; 123 } 124 125 /// \brief Get a single bit mask. 126 /// 127 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set 128 /// This method generates and returns a uint64_t (word) mask for a single 129 /// bit at a specific bit position. This is used to mask the bit in the 130 /// corresponding word. 131 static uint64_t maskBit(unsigned bitPosition) { 132 return 1ULL << whichBit(bitPosition); 133 } 134 135 /// \brief Clear unused high order bits 136 /// 137 /// This method is used internally to clear the top "N" bits in the high order 138 /// word that are not used by the APInt. This is needed after the most 139 /// significant word is assigned a value to ensure that those bits are 140 /// zero'd out. 141 APInt &clearUnusedBits() { 142 // Compute how many bits are used in the final word 143 unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1; 144 145 // Mask out the high bits. 146 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - WordBits); 147 if (isSingleWord()) 148 U.VAL &= mask; 149 else 150 U.pVal[getNumWords() - 1] &= mask; 151 return *this; 152 } 153 154 /// \brief Get the word corresponding to a bit position 155 /// \returns the corresponding word for the specified bit position. 156 uint64_t getWord(unsigned bitPosition) const { 157 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)]; 158 } 159 160 /// Utility method to change the bit width of this APInt to new bit width, 161 /// allocating and/or deallocating as necessary. There is no guarantee on the 162 /// value of any bits upon return. Caller should populate the bits after. 163 void reallocate(unsigned NewBitWidth); 164 165 /// \brief Convert a char array into an APInt 166 /// 167 /// \param radix 2, 8, 10, 16, or 36 168 /// Converts a string into a number. The string must be non-empty 169 /// and well-formed as a number of the given base. The bit-width 170 /// must be sufficient to hold the result. 171 /// 172 /// This is used by the constructors that take string arguments. 173 /// 174 /// StringRef::getAsInteger is superficially similar but (1) does 175 /// not assume that the string is well-formed and (2) grows the 176 /// result to hold the input. 177 void fromString(unsigned numBits, StringRef str, uint8_t radix); 178 179 /// \brief An internal division function for dividing APInts. 180 /// 181 /// This is used by the toString method to divide by the radix. It simply 182 /// provides a more convenient form of divide for internal use since KnuthDiv 183 /// has specific constraints on its inputs. If those constraints are not met 184 /// then it provides a simpler form of divide. 185 static void divide(const WordType *LHS, unsigned lhsWords, 186 const WordType *RHS, unsigned rhsWords, WordType *Quotient, 187 WordType *Remainder); 188 189 /// out-of-line slow case for inline constructor 190 void initSlowCase(uint64_t val, bool isSigned); 191 192 /// shared code between two array constructors 193 void initFromArray(ArrayRef<uint64_t> array); 194 195 /// out-of-line slow case for inline copy constructor 196 void initSlowCase(const APInt &that); 197 198 /// out-of-line slow case for shl 199 void shlSlowCase(unsigned ShiftAmt); 200 201 /// out-of-line slow case for lshr. 202 void lshrSlowCase(unsigned ShiftAmt); 203 204 /// out-of-line slow case for ashr. 205 void ashrSlowCase(unsigned ShiftAmt); 206 207 /// out-of-line slow case for operator= 208 void AssignSlowCase(const APInt &RHS); 209 210 /// out-of-line slow case for operator== 211 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY; 212 213 /// out-of-line slow case for countLeadingZeros 214 unsigned countLeadingZerosSlowCase() const LLVM_READONLY; 215 216 /// out-of-line slow case for countTrailingOnes 217 unsigned countTrailingOnesSlowCase() const LLVM_READONLY; 218 219 /// out-of-line slow case for countPopulation 220 unsigned countPopulationSlowCase() const LLVM_READONLY; 221 222 /// out-of-line slow case for intersects. 223 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY; 224 225 /// out-of-line slow case for isSubsetOf. 226 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY; 227 228 /// out-of-line slow case for setBits. 229 void setBitsSlowCase(unsigned loBit, unsigned hiBit); 230 231 /// out-of-line slow case for flipAllBits. 232 void flipAllBitsSlowCase(); 233 234 /// out-of-line slow case for operator&=. 235 void AndAssignSlowCase(const APInt& RHS); 236 237 /// out-of-line slow case for operator|=. 238 void OrAssignSlowCase(const APInt& RHS); 239 240 /// out-of-line slow case for operator^=. 241 void XorAssignSlowCase(const APInt& RHS); 242 243 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal 244 /// to, or greater than RHS. 245 int compare(const APInt &RHS) const LLVM_READONLY; 246 247 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal 248 /// to, or greater than RHS. 249 int compareSigned(const APInt &RHS) const LLVM_READONLY; 250 251 public: 252 /// \name Constructors 253 /// @{ 254 255 /// \brief Create a new APInt of numBits width, initialized as val. 256 /// 257 /// If isSigned is true then val is treated as if it were a signed value 258 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width 259 /// will be done. Otherwise, no sign extension occurs (high order bits beyond 260 /// the range of val are zero filled). 261 /// 262 /// \param numBits the bit width of the constructed APInt 263 /// \param val the initial value of the APInt 264 /// \param isSigned how to treat signedness of val 265 APInt(unsigned numBits, uint64_t val, bool isSigned = false) 266 : BitWidth(numBits) { 267 assert(BitWidth && "bitwidth too small"); 268 if (isSingleWord()) { 269 U.VAL = val; 270 clearUnusedBits(); 271 } else { 272 initSlowCase(val, isSigned); 273 } 274 } 275 276 /// \brief Construct an APInt of numBits width, initialized as bigVal[]. 277 /// 278 /// Note that bigVal.size() can be smaller or larger than the corresponding 279 /// bit width but any extraneous bits will be dropped. 280 /// 281 /// \param numBits the bit width of the constructed APInt 282 /// \param bigVal a sequence of words to form the initial value of the APInt 283 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal); 284 285 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but 286 /// deprecated because this constructor is prone to ambiguity with the 287 /// APInt(unsigned, uint64_t, bool) constructor. 288 /// 289 /// If this overload is ever deleted, care should be taken to prevent calls 290 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool) 291 /// constructor. 292 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]); 293 294 /// \brief Construct an APInt from a string representation. 295 /// 296 /// This constructor interprets the string \p str in the given radix. The 297 /// interpretation stops when the first character that is not suitable for the 298 /// radix is encountered, or the end of the string. Acceptable radix values 299 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the 300 /// string to require more bits than numBits. 301 /// 302 /// \param numBits the bit width of the constructed APInt 303 /// \param str the string to be interpreted 304 /// \param radix the radix to use for the conversion 305 APInt(unsigned numBits, StringRef str, uint8_t radix); 306 307 /// Simply makes *this a copy of that. 308 /// @brief Copy Constructor. 309 APInt(const APInt &that) : BitWidth(that.BitWidth) { 310 if (isSingleWord()) 311 U.VAL = that.U.VAL; 312 else 313 initSlowCase(that); 314 } 315 316 /// \brief Move Constructor. 317 APInt(APInt &&that) : BitWidth(that.BitWidth) { 318 memcpy(&U, &that.U, sizeof(U)); 319 that.BitWidth = 0; 320 } 321 322 /// \brief Destructor. 323 ~APInt() { 324 if (needsCleanup()) 325 delete[] U.pVal; 326 } 327 328 /// \brief Default constructor that creates an uninteresting APInt 329 /// representing a 1-bit zero value. 330 /// 331 /// This is useful for object deserialization (pair this with the static 332 /// method Read). 333 explicit APInt() : BitWidth(1) { U.VAL = 0; } 334 335 /// \brief Returns whether this instance allocated memory. 336 bool needsCleanup() const { return !isSingleWord(); } 337 338 /// Used to insert APInt objects, or objects that contain APInt objects, into 339 /// FoldingSets. 340 void Profile(FoldingSetNodeID &id) const; 341 342 /// @} 343 /// \name Value Tests 344 /// @{ 345 346 /// \brief Determine sign of this APInt. 347 /// 348 /// This tests the high bit of this APInt to determine if it is set. 349 /// 350 /// \returns true if this APInt is negative, false otherwise 351 bool isNegative() const { return (*this)[BitWidth - 1]; } 352 353 /// \brief Determine if this APInt Value is non-negative (>= 0) 354 /// 355 /// This tests the high bit of the APInt to determine if it is unset. 356 bool isNonNegative() const { return !isNegative(); } 357 358 /// \brief Determine if sign bit of this APInt is set. 359 /// 360 /// This tests the high bit of this APInt to determine if it is set. 361 /// 362 /// \returns true if this APInt has its sign bit set, false otherwise. 363 bool isSignBitSet() const { return (*this)[BitWidth-1]; } 364 365 /// \brief Determine if sign bit of this APInt is clear. 366 /// 367 /// This tests the high bit of this APInt to determine if it is clear. 368 /// 369 /// \returns true if this APInt has its sign bit clear, false otherwise. 370 bool isSignBitClear() const { return !isSignBitSet(); } 371 372 /// \brief Determine if this APInt Value is positive. 373 /// 374 /// This tests if the value of this APInt is positive (> 0). Note 375 /// that 0 is not a positive value. 376 /// 377 /// \returns true if this APInt is positive. 378 bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); } 379 380 /// \brief Determine if all bits are set 381 /// 382 /// This checks to see if the value has all bits of the APInt are set or not. 383 bool isAllOnesValue() const { 384 if (isSingleWord()) 385 return U.VAL == WORD_MAX >> (APINT_BITS_PER_WORD - BitWidth); 386 return countPopulationSlowCase() == BitWidth; 387 } 388 389 /// \brief Determine if all bits are clear 390 /// 391 /// This checks to see if the value has all bits of the APInt are clear or 392 /// not. 393 bool isNullValue() const { return !*this; } 394 395 /// \brief Determine if this is a value of 1. 396 /// 397 /// This checks to see if the value of this APInt is one. 398 bool isOneValue() const { return getActiveBits() == 1; } 399 400 /// \brief Determine if this is the largest unsigned value. 401 /// 402 /// This checks to see if the value of this APInt is the maximum unsigned 403 /// value for the APInt's bit width. 404 bool isMaxValue() const { return isAllOnesValue(); } 405 406 /// \brief Determine if this is the largest signed value. 407 /// 408 /// This checks to see if the value of this APInt is the maximum signed 409 /// value for the APInt's bit width. 410 bool isMaxSignedValue() const { 411 return !isNegative() && countPopulation() == BitWidth - 1; 412 } 413 414 /// \brief Determine if this is the smallest unsigned value. 415 /// 416 /// This checks to see if the value of this APInt is the minimum unsigned 417 /// value for the APInt's bit width. 418 bool isMinValue() const { return isNullValue(); } 419 420 /// \brief Determine if this is the smallest signed value. 421 /// 422 /// This checks to see if the value of this APInt is the minimum signed 423 /// value for the APInt's bit width. 424 bool isMinSignedValue() const { 425 return isNegative() && isPowerOf2(); 426 } 427 428 /// \brief Check if this APInt has an N-bits unsigned integer value. 429 bool isIntN(unsigned N) const { 430 assert(N && "N == 0 ???"); 431 return getActiveBits() <= N; 432 } 433 434 /// \brief Check if this APInt has an N-bits signed integer value. 435 bool isSignedIntN(unsigned N) const { 436 assert(N && "N == 0 ???"); 437 return getMinSignedBits() <= N; 438 } 439 440 /// \brief Check if this APInt's value is a power of two greater than zero. 441 /// 442 /// \returns true if the argument APInt value is a power of two > 0. 443 bool isPowerOf2() const { 444 if (isSingleWord()) 445 return isPowerOf2_64(U.VAL); 446 return countPopulationSlowCase() == 1; 447 } 448 449 /// \brief Check if the APInt's value is returned by getSignMask. 450 /// 451 /// \returns true if this is the value returned by getSignMask. 452 bool isSignMask() const { return isMinSignedValue(); } 453 454 /// \brief Convert APInt to a boolean value. 455 /// 456 /// This converts the APInt to a boolean value as a test against zero. 457 bool getBoolValue() const { return !!*this; } 458 459 /// If this value is smaller than the specified limit, return it, otherwise 460 /// return the limit value. This causes the value to saturate to the limit. 461 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) const { 462 return ugt(Limit) ? Limit : getZExtValue(); 463 } 464 465 /// \brief Check if the APInt consists of a repeated bit pattern. 466 /// 467 /// e.g. 0x01010101 satisfies isSplat(8). 468 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit 469 /// width without remainder. 470 bool isSplat(unsigned SplatSizeInBits) const; 471 472 /// \returns true if this APInt value is a sequence of \param numBits ones 473 /// starting at the least significant bit with the remainder zero. 474 bool isMask(unsigned numBits) const { 475 assert(numBits != 0 && "numBits must be non-zero"); 476 assert(numBits <= BitWidth && "numBits out of range"); 477 if (isSingleWord()) 478 return U.VAL == (WORD_MAX >> (APINT_BITS_PER_WORD - numBits)); 479 unsigned Ones = countTrailingOnesSlowCase(); 480 return (numBits == Ones) && 481 ((Ones + countLeadingZerosSlowCase()) == BitWidth); 482 } 483 484 /// \returns true if this APInt is a non-empty sequence of ones starting at 485 /// the least significant bit with the remainder zero. 486 /// Ex. isMask(0x0000FFFFU) == true. 487 bool isMask() const { 488 if (isSingleWord()) 489 return isMask_64(U.VAL); 490 unsigned Ones = countTrailingOnesSlowCase(); 491 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth); 492 } 493 494 /// \brief Return true if this APInt value contains a sequence of ones with 495 /// the remainder zero. 496 bool isShiftedMask() const { 497 if (isSingleWord()) 498 return isShiftedMask_64(U.VAL); 499 unsigned Ones = countPopulationSlowCase(); 500 unsigned LeadZ = countLeadingZerosSlowCase(); 501 return (Ones + LeadZ + countTrailingZeros()) == BitWidth; 502 } 503 504 /// @} 505 /// \name Value Generators 506 /// @{ 507 508 /// \brief Gets maximum unsigned value of APInt for specific bit width. 509 static APInt getMaxValue(unsigned numBits) { 510 return getAllOnesValue(numBits); 511 } 512 513 /// \brief Gets maximum signed value of APInt for a specific bit width. 514 static APInt getSignedMaxValue(unsigned numBits) { 515 APInt API = getAllOnesValue(numBits); 516 API.clearBit(numBits - 1); 517 return API; 518 } 519 520 /// \brief Gets minimum unsigned value of APInt for a specific bit width. 521 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); } 522 523 /// \brief Gets minimum signed value of APInt for a specific bit width. 524 static APInt getSignedMinValue(unsigned numBits) { 525 APInt API(numBits, 0); 526 API.setBit(numBits - 1); 527 return API; 528 } 529 530 /// \brief Get the SignMask for a specific bit width. 531 /// 532 /// This is just a wrapper function of getSignedMinValue(), and it helps code 533 /// readability when we want to get a SignMask. 534 static APInt getSignMask(unsigned BitWidth) { 535 return getSignedMinValue(BitWidth); 536 } 537 538 /// \brief Get the all-ones value. 539 /// 540 /// \returns the all-ones value for an APInt of the specified bit-width. 541 static APInt getAllOnesValue(unsigned numBits) { 542 return APInt(numBits, WORD_MAX, true); 543 } 544 545 /// \brief Get the '0' value. 546 /// 547 /// \returns the '0' value for an APInt of the specified bit-width. 548 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); } 549 550 /// \brief Compute an APInt containing numBits highbits from this APInt. 551 /// 552 /// Get an APInt with the same BitWidth as this APInt, just zero mask 553 /// the low bits and right shift to the least significant bit. 554 /// 555 /// \returns the high "numBits" bits of this APInt. 556 APInt getHiBits(unsigned numBits) const; 557 558 /// \brief Compute an APInt containing numBits lowbits from this APInt. 559 /// 560 /// Get an APInt with the same BitWidth as this APInt, just zero mask 561 /// the high bits. 562 /// 563 /// \returns the low "numBits" bits of this APInt. 564 APInt getLoBits(unsigned numBits) const; 565 566 /// \brief Return an APInt with exactly one bit set in the result. 567 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) { 568 APInt Res(numBits, 0); 569 Res.setBit(BitNo); 570 return Res; 571 } 572 573 /// \brief Get a value with a block of bits set. 574 /// 575 /// Constructs an APInt value that has a contiguous range of bits set. The 576 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other 577 /// bits will be zero. For example, with parameters(32, 0, 16) you would get 578 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For 579 /// example, with parameters (32, 28, 4), you would get 0xF000000F. 580 /// 581 /// \param numBits the intended bit width of the result 582 /// \param loBit the index of the lowest bit set. 583 /// \param hiBit the index of the highest bit set. 584 /// 585 /// \returns An APInt value with the requested bits set. 586 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) { 587 APInt Res(numBits, 0); 588 Res.setBits(loBit, hiBit); 589 return Res; 590 } 591 592 /// \brief Get a value with upper bits starting at loBit set. 593 /// 594 /// Constructs an APInt value that has a contiguous range of bits set. The 595 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other 596 /// bits will be zero. For example, with parameters(32, 12) you would get 597 /// 0xFFFFF000. 598 /// 599 /// \param numBits the intended bit width of the result 600 /// \param loBit the index of the lowest bit to set. 601 /// 602 /// \returns An APInt value with the requested bits set. 603 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) { 604 APInt Res(numBits, 0); 605 Res.setBitsFrom(loBit); 606 return Res; 607 } 608 609 /// \brief Get a value with high bits set 610 /// 611 /// Constructs an APInt value that has the top hiBitsSet bits set. 612 /// 613 /// \param numBits the bitwidth of the result 614 /// \param hiBitsSet the number of high-order bits set in the result. 615 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) { 616 APInt Res(numBits, 0); 617 Res.setHighBits(hiBitsSet); 618 return Res; 619 } 620 621 /// \brief Get a value with low bits set 622 /// 623 /// Constructs an APInt value that has the bottom loBitsSet bits set. 624 /// 625 /// \param numBits the bitwidth of the result 626 /// \param loBitsSet the number of low-order bits set in the result. 627 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) { 628 APInt Res(numBits, 0); 629 Res.setLowBits(loBitsSet); 630 return Res; 631 } 632 633 /// \brief Return a value containing V broadcasted over NewLen bits. 634 static APInt getSplat(unsigned NewLen, const APInt &V); 635 636 /// \brief Determine if two APInts have the same value, after zero-extending 637 /// one of them (if needed!) to ensure that the bit-widths match. 638 static bool isSameValue(const APInt &I1, const APInt &I2) { 639 if (I1.getBitWidth() == I2.getBitWidth()) 640 return I1 == I2; 641 642 if (I1.getBitWidth() > I2.getBitWidth()) 643 return I1 == I2.zext(I1.getBitWidth()); 644 645 return I1.zext(I2.getBitWidth()) == I2; 646 } 647 648 /// \brief Overload to compute a hash_code for an APInt value. 649 friend hash_code hash_value(const APInt &Arg); 650 651 /// This function returns a pointer to the internal storage of the APInt. 652 /// This is useful for writing out the APInt in binary form without any 653 /// conversions. 654 const uint64_t *getRawData() const { 655 if (isSingleWord()) 656 return &U.VAL; 657 return &U.pVal[0]; 658 } 659 660 /// @} 661 /// \name Unary Operators 662 /// @{ 663 664 /// \brief Postfix increment operator. 665 /// 666 /// Increments *this by 1. 667 /// 668 /// \returns a new APInt value representing the original value of *this. 669 const APInt operator++(int) { 670 APInt API(*this); 671 ++(*this); 672 return API; 673 } 674 675 /// \brief Prefix increment operator. 676 /// 677 /// \returns *this incremented by one 678 APInt &operator++(); 679 680 /// \brief Postfix decrement operator. 681 /// 682 /// Decrements *this by 1. 683 /// 684 /// \returns a new APInt value representing the original value of *this. 685 const APInt operator--(int) { 686 APInt API(*this); 687 --(*this); 688 return API; 689 } 690 691 /// \brief Prefix decrement operator. 692 /// 693 /// \returns *this decremented by one. 694 APInt &operator--(); 695 696 /// \brief Logical negation operator. 697 /// 698 /// Performs logical negation operation on this APInt. 699 /// 700 /// \returns true if *this is zero, false otherwise. 701 bool operator!() const { 702 if (isSingleWord()) 703 return U.VAL == 0; 704 return countLeadingZerosSlowCase() == BitWidth; 705 } 706 707 /// @} 708 /// \name Assignment Operators 709 /// @{ 710 711 /// \brief Copy assignment operator. 712 /// 713 /// \returns *this after assignment of RHS. 714 APInt &operator=(const APInt &RHS) { 715 // If the bitwidths are the same, we can avoid mucking with memory 716 if (isSingleWord() && RHS.isSingleWord()) { 717 U.VAL = RHS.U.VAL; 718 BitWidth = RHS.BitWidth; 719 return clearUnusedBits(); 720 } 721 722 AssignSlowCase(RHS); 723 return *this; 724 } 725 726 /// @brief Move assignment operator. 727 APInt &operator=(APInt &&that) { 728 assert(this != &that && "Self-move not supported"); 729 if (!isSingleWord()) 730 delete[] U.pVal; 731 732 // Use memcpy so that type based alias analysis sees both VAL and pVal 733 // as modified. 734 memcpy(&U, &that.U, sizeof(U)); 735 736 BitWidth = that.BitWidth; 737 that.BitWidth = 0; 738 739 return *this; 740 } 741 742 /// \brief Assignment operator. 743 /// 744 /// The RHS value is assigned to *this. If the significant bits in RHS exceed 745 /// the bit width, the excess bits are truncated. If the bit width is larger 746 /// than 64, the value is zero filled in the unspecified high order bits. 747 /// 748 /// \returns *this after assignment of RHS value. 749 APInt &operator=(uint64_t RHS) { 750 if (isSingleWord()) { 751 U.VAL = RHS; 752 clearUnusedBits(); 753 } else { 754 U.pVal[0] = RHS; 755 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE); 756 } 757 return *this; 758 } 759 760 /// \brief Bitwise AND assignment operator. 761 /// 762 /// Performs a bitwise AND operation on this APInt and RHS. The result is 763 /// assigned to *this. 764 /// 765 /// \returns *this after ANDing with RHS. 766 APInt &operator&=(const APInt &RHS) { 767 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 768 if (isSingleWord()) 769 U.VAL &= RHS.U.VAL; 770 else 771 AndAssignSlowCase(RHS); 772 return *this; 773 } 774 775 /// \brief Bitwise AND assignment operator. 776 /// 777 /// Performs a bitwise AND operation on this APInt and RHS. RHS is 778 /// logically zero-extended or truncated to match the bit-width of 779 /// the LHS. 780 APInt &operator&=(uint64_t RHS) { 781 if (isSingleWord()) { 782 U.VAL &= RHS; 783 return *this; 784 } 785 U.pVal[0] &= RHS; 786 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE); 787 return *this; 788 } 789 790 /// \brief Bitwise OR assignment operator. 791 /// 792 /// Performs a bitwise OR operation on this APInt and RHS. The result is 793 /// assigned *this; 794 /// 795 /// \returns *this after ORing with RHS. 796 APInt &operator|=(const APInt &RHS) { 797 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 798 if (isSingleWord()) 799 U.VAL |= RHS.U.VAL; 800 else 801 OrAssignSlowCase(RHS); 802 return *this; 803 } 804 805 /// \brief Bitwise OR assignment operator. 806 /// 807 /// Performs a bitwise OR operation on this APInt and RHS. RHS is 808 /// logically zero-extended or truncated to match the bit-width of 809 /// the LHS. 810 APInt &operator|=(uint64_t RHS) { 811 if (isSingleWord()) { 812 U.VAL |= RHS; 813 clearUnusedBits(); 814 } else { 815 U.pVal[0] |= RHS; 816 } 817 return *this; 818 } 819 820 /// \brief Bitwise XOR assignment operator. 821 /// 822 /// Performs a bitwise XOR operation on this APInt and RHS. The result is 823 /// assigned to *this. 824 /// 825 /// \returns *this after XORing with RHS. 826 APInt &operator^=(const APInt &RHS) { 827 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 828 if (isSingleWord()) 829 U.VAL ^= RHS.U.VAL; 830 else 831 XorAssignSlowCase(RHS); 832 return *this; 833 } 834 835 /// \brief Bitwise XOR assignment operator. 836 /// 837 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is 838 /// logically zero-extended or truncated to match the bit-width of 839 /// the LHS. 840 APInt &operator^=(uint64_t RHS) { 841 if (isSingleWord()) { 842 U.VAL ^= RHS; 843 clearUnusedBits(); 844 } else { 845 U.pVal[0] ^= RHS; 846 } 847 return *this; 848 } 849 850 /// \brief Multiplication assignment operator. 851 /// 852 /// Multiplies this APInt by RHS and assigns the result to *this. 853 /// 854 /// \returns *this 855 APInt &operator*=(const APInt &RHS); 856 APInt &operator*=(uint64_t RHS); 857 858 /// \brief Addition assignment operator. 859 /// 860 /// Adds RHS to *this and assigns the result to *this. 861 /// 862 /// \returns *this 863 APInt &operator+=(const APInt &RHS); 864 APInt &operator+=(uint64_t RHS); 865 866 /// \brief Subtraction assignment operator. 867 /// 868 /// Subtracts RHS from *this and assigns the result to *this. 869 /// 870 /// \returns *this 871 APInt &operator-=(const APInt &RHS); 872 APInt &operator-=(uint64_t RHS); 873 874 /// \brief Left-shift assignment function. 875 /// 876 /// Shifts *this left by shiftAmt and assigns the result to *this. 877 /// 878 /// \returns *this after shifting left by ShiftAmt 879 APInt &operator<<=(unsigned ShiftAmt) { 880 assert(ShiftAmt <= BitWidth && "Invalid shift amount"); 881 if (isSingleWord()) { 882 if (ShiftAmt == BitWidth) 883 U.VAL = 0; 884 else 885 U.VAL <<= ShiftAmt; 886 return clearUnusedBits(); 887 } 888 shlSlowCase(ShiftAmt); 889 return *this; 890 } 891 892 /// \brief Left-shift assignment function. 893 /// 894 /// Shifts *this left by shiftAmt and assigns the result to *this. 895 /// 896 /// \returns *this after shifting left by ShiftAmt 897 APInt &operator<<=(const APInt &ShiftAmt); 898 899 /// @} 900 /// \name Binary Operators 901 /// @{ 902 903 /// \brief Multiplication operator. 904 /// 905 /// Multiplies this APInt by RHS and returns the result. 906 APInt operator*(const APInt &RHS) const; 907 908 /// \brief Left logical shift operator. 909 /// 910 /// Shifts this APInt left by \p Bits and returns the result. 911 APInt operator<<(unsigned Bits) const { return shl(Bits); } 912 913 /// \brief Left logical shift operator. 914 /// 915 /// Shifts this APInt left by \p Bits and returns the result. 916 APInt operator<<(const APInt &Bits) const { return shl(Bits); } 917 918 /// \brief Arithmetic right-shift function. 919 /// 920 /// Arithmetic right-shift this APInt by shiftAmt. 921 APInt ashr(unsigned ShiftAmt) const { 922 APInt R(*this); 923 R.ashrInPlace(ShiftAmt); 924 return R; 925 } 926 927 /// Arithmetic right-shift this APInt by ShiftAmt in place. 928 void ashrInPlace(unsigned ShiftAmt) { 929 assert(ShiftAmt <= BitWidth && "Invalid shift amount"); 930 if (isSingleWord()) { 931 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth); 932 if (ShiftAmt == BitWidth) 933 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit. 934 else 935 U.VAL = SExtVAL >> ShiftAmt; 936 clearUnusedBits(); 937 return; 938 } 939 ashrSlowCase(ShiftAmt); 940 } 941 942 /// \brief Logical right-shift function. 943 /// 944 /// Logical right-shift this APInt by shiftAmt. 945 APInt lshr(unsigned shiftAmt) const { 946 APInt R(*this); 947 R.lshrInPlace(shiftAmt); 948 return R; 949 } 950 951 /// Logical right-shift this APInt by ShiftAmt in place. 952 void lshrInPlace(unsigned ShiftAmt) { 953 assert(ShiftAmt <= BitWidth && "Invalid shift amount"); 954 if (isSingleWord()) { 955 if (ShiftAmt == BitWidth) 956 U.VAL = 0; 957 else 958 U.VAL >>= ShiftAmt; 959 return; 960 } 961 lshrSlowCase(ShiftAmt); 962 } 963 964 /// \brief Left-shift function. 965 /// 966 /// Left-shift this APInt by shiftAmt. 967 APInt shl(unsigned shiftAmt) const { 968 APInt R(*this); 969 R <<= shiftAmt; 970 return R; 971 } 972 973 /// \brief Rotate left by rotateAmt. 974 APInt rotl(unsigned rotateAmt) const; 975 976 /// \brief Rotate right by rotateAmt. 977 APInt rotr(unsigned rotateAmt) const; 978 979 /// \brief Arithmetic right-shift function. 980 /// 981 /// Arithmetic right-shift this APInt by shiftAmt. 982 APInt ashr(const APInt &ShiftAmt) const { 983 APInt R(*this); 984 R.ashrInPlace(ShiftAmt); 985 return R; 986 } 987 988 /// Arithmetic right-shift this APInt by shiftAmt in place. 989 void ashrInPlace(const APInt &shiftAmt); 990 991 /// \brief Logical right-shift function. 992 /// 993 /// Logical right-shift this APInt by shiftAmt. 994 APInt lshr(const APInt &ShiftAmt) const { 995 APInt R(*this); 996 R.lshrInPlace(ShiftAmt); 997 return R; 998 } 999 1000 /// Logical right-shift this APInt by ShiftAmt in place. 1001 void lshrInPlace(const APInt &ShiftAmt); 1002 1003 /// \brief Left-shift function. 1004 /// 1005 /// Left-shift this APInt by shiftAmt. 1006 APInt shl(const APInt &ShiftAmt) const { 1007 APInt R(*this); 1008 R <<= ShiftAmt; 1009 return R; 1010 } 1011 1012 /// \brief Rotate left by rotateAmt. 1013 APInt rotl(const APInt &rotateAmt) const; 1014 1015 /// \brief Rotate right by rotateAmt. 1016 APInt rotr(const APInt &rotateAmt) const; 1017 1018 /// \brief Unsigned division operation. 1019 /// 1020 /// Perform an unsigned divide operation on this APInt by RHS. Both this and 1021 /// RHS are treated as unsigned quantities for purposes of this division. 1022 /// 1023 /// \returns a new APInt value containing the division result 1024 APInt udiv(const APInt &RHS) const; 1025 APInt udiv(uint64_t RHS) const; 1026 1027 /// \brief Signed division function for APInt. 1028 /// 1029 /// Signed divide this APInt by APInt RHS. 1030 APInt sdiv(const APInt &RHS) const; 1031 APInt sdiv(int64_t RHS) const; 1032 1033 /// \brief Unsigned remainder operation. 1034 /// 1035 /// Perform an unsigned remainder operation on this APInt with RHS being the 1036 /// divisor. Both this and RHS are treated as unsigned quantities for purposes 1037 /// of this operation. Note that this is a true remainder operation and not a 1038 /// modulo operation because the sign follows the sign of the dividend which 1039 /// is *this. 1040 /// 1041 /// \returns a new APInt value containing the remainder result 1042 APInt urem(const APInt &RHS) const; 1043 uint64_t urem(uint64_t RHS) const; 1044 1045 /// \brief Function for signed remainder operation. 1046 /// 1047 /// Signed remainder operation on APInt. 1048 APInt srem(const APInt &RHS) const; 1049 int64_t srem(int64_t RHS) const; 1050 1051 /// \brief Dual division/remainder interface. 1052 /// 1053 /// Sometimes it is convenient to divide two APInt values and obtain both the 1054 /// quotient and remainder. This function does both operations in the same 1055 /// computation making it a little more efficient. The pair of input arguments 1056 /// may overlap with the pair of output arguments. It is safe to call 1057 /// udivrem(X, Y, X, Y), for example. 1058 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, 1059 APInt &Remainder); 1060 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient, 1061 uint64_t &Remainder); 1062 1063 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, 1064 APInt &Remainder); 1065 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient, 1066 int64_t &Remainder); 1067 1068 // Operations that return overflow indicators. 1069 APInt sadd_ov(const APInt &RHS, bool &Overflow) const; 1070 APInt uadd_ov(const APInt &RHS, bool &Overflow) const; 1071 APInt ssub_ov(const APInt &RHS, bool &Overflow) const; 1072 APInt usub_ov(const APInt &RHS, bool &Overflow) const; 1073 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const; 1074 APInt smul_ov(const APInt &RHS, bool &Overflow) const; 1075 APInt umul_ov(const APInt &RHS, bool &Overflow) const; 1076 APInt sshl_ov(const APInt &Amt, bool &Overflow) const; 1077 APInt ushl_ov(const APInt &Amt, bool &Overflow) const; 1078 1079 /// \brief Array-indexing support. 1080 /// 1081 /// \returns the bit value at bitPosition 1082 bool operator[](unsigned bitPosition) const { 1083 assert(bitPosition < getBitWidth() && "Bit position out of bounds!"); 1084 return (maskBit(bitPosition) & getWord(bitPosition)) != 0; 1085 } 1086 1087 /// @} 1088 /// \name Comparison Operators 1089 /// @{ 1090 1091 /// \brief Equality operator. 1092 /// 1093 /// Compares this APInt with RHS for the validity of the equality 1094 /// relationship. 1095 bool operator==(const APInt &RHS) const { 1096 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths"); 1097 if (isSingleWord()) 1098 return U.VAL == RHS.U.VAL; 1099 return EqualSlowCase(RHS); 1100 } 1101 1102 /// \brief Equality operator. 1103 /// 1104 /// Compares this APInt with a uint64_t for the validity of the equality 1105 /// relationship. 1106 /// 1107 /// \returns true if *this == Val 1108 bool operator==(uint64_t Val) const { 1109 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val; 1110 } 1111 1112 /// \brief Equality comparison. 1113 /// 1114 /// Compares this APInt with RHS for the validity of the equality 1115 /// relationship. 1116 /// 1117 /// \returns true if *this == Val 1118 bool eq(const APInt &RHS) const { return (*this) == RHS; } 1119 1120 /// \brief Inequality operator. 1121 /// 1122 /// Compares this APInt with RHS for the validity of the inequality 1123 /// relationship. 1124 /// 1125 /// \returns true if *this != Val 1126 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); } 1127 1128 /// \brief Inequality operator. 1129 /// 1130 /// Compares this APInt with a uint64_t for the validity of the inequality 1131 /// relationship. 1132 /// 1133 /// \returns true if *this != Val 1134 bool operator!=(uint64_t Val) const { return !((*this) == Val); } 1135 1136 /// \brief Inequality comparison 1137 /// 1138 /// Compares this APInt with RHS for the validity of the inequality 1139 /// relationship. 1140 /// 1141 /// \returns true if *this != Val 1142 bool ne(const APInt &RHS) const { return !((*this) == RHS); } 1143 1144 /// \brief Unsigned less than comparison 1145 /// 1146 /// Regards both *this and RHS as unsigned quantities and compares them for 1147 /// the validity of the less-than relationship. 1148 /// 1149 /// \returns true if *this < RHS when both are considered unsigned. 1150 bool ult(const APInt &RHS) const { return compare(RHS) < 0; } 1151 1152 /// \brief Unsigned less than comparison 1153 /// 1154 /// Regards both *this as an unsigned quantity and compares it with RHS for 1155 /// the validity of the less-than relationship. 1156 /// 1157 /// \returns true if *this < RHS when considered unsigned. 1158 bool ult(uint64_t RHS) const { 1159 // Only need to check active bits if not a single word. 1160 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS; 1161 } 1162 1163 /// \brief Signed less than comparison 1164 /// 1165 /// Regards both *this and RHS as signed quantities and compares them for 1166 /// validity of the less-than relationship. 1167 /// 1168 /// \returns true if *this < RHS when both are considered signed. 1169 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; } 1170 1171 /// \brief Signed less than comparison 1172 /// 1173 /// Regards both *this as a signed quantity and compares it with RHS for 1174 /// the validity of the less-than relationship. 1175 /// 1176 /// \returns true if *this < RHS when considered signed. 1177 bool slt(int64_t RHS) const { 1178 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative() 1179 : getSExtValue() < RHS; 1180 } 1181 1182 /// \brief Unsigned less or equal comparison 1183 /// 1184 /// Regards both *this and RHS as unsigned quantities and compares them for 1185 /// validity of the less-or-equal relationship. 1186 /// 1187 /// \returns true if *this <= RHS when both are considered unsigned. 1188 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; } 1189 1190 /// \brief Unsigned less or equal comparison 1191 /// 1192 /// Regards both *this as an unsigned quantity and compares it with RHS for 1193 /// the validity of the less-or-equal relationship. 1194 /// 1195 /// \returns true if *this <= RHS when considered unsigned. 1196 bool ule(uint64_t RHS) const { return !ugt(RHS); } 1197 1198 /// \brief Signed less or equal comparison 1199 /// 1200 /// Regards both *this and RHS as signed quantities and compares them for 1201 /// validity of the less-or-equal relationship. 1202 /// 1203 /// \returns true if *this <= RHS when both are considered signed. 1204 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; } 1205 1206 /// \brief Signed less or equal comparison 1207 /// 1208 /// Regards both *this as a signed quantity and compares it with RHS for the 1209 /// validity of the less-or-equal relationship. 1210 /// 1211 /// \returns true if *this <= RHS when considered signed. 1212 bool sle(uint64_t RHS) const { return !sgt(RHS); } 1213 1214 /// \brief Unsigned greather than comparison 1215 /// 1216 /// Regards both *this and RHS as unsigned quantities and compares them for 1217 /// the validity of the greater-than relationship. 1218 /// 1219 /// \returns true if *this > RHS when both are considered unsigned. 1220 bool ugt(const APInt &RHS) const { return !ule(RHS); } 1221 1222 /// \brief Unsigned greater than comparison 1223 /// 1224 /// Regards both *this as an unsigned quantity and compares it with RHS for 1225 /// the validity of the greater-than relationship. 1226 /// 1227 /// \returns true if *this > RHS when considered unsigned. 1228 bool ugt(uint64_t RHS) const { 1229 // Only need to check active bits if not a single word. 1230 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS; 1231 } 1232 1233 /// \brief Signed greather than comparison 1234 /// 1235 /// Regards both *this and RHS as signed quantities and compares them for the 1236 /// validity of the greater-than relationship. 1237 /// 1238 /// \returns true if *this > RHS when both are considered signed. 1239 bool sgt(const APInt &RHS) const { return !sle(RHS); } 1240 1241 /// \brief Signed greater than comparison 1242 /// 1243 /// Regards both *this as a signed quantity and compares it with RHS for 1244 /// the validity of the greater-than relationship. 1245 /// 1246 /// \returns true if *this > RHS when considered signed. 1247 bool sgt(int64_t RHS) const { 1248 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative() 1249 : getSExtValue() > RHS; 1250 } 1251 1252 /// \brief Unsigned greater or equal comparison 1253 /// 1254 /// Regards both *this and RHS as unsigned quantities and compares them for 1255 /// validity of the greater-or-equal relationship. 1256 /// 1257 /// \returns true if *this >= RHS when both are considered unsigned. 1258 bool uge(const APInt &RHS) const { return !ult(RHS); } 1259 1260 /// \brief Unsigned greater or equal comparison 1261 /// 1262 /// Regards both *this as an unsigned quantity and compares it with RHS for 1263 /// the validity of the greater-or-equal relationship. 1264 /// 1265 /// \returns true if *this >= RHS when considered unsigned. 1266 bool uge(uint64_t RHS) const { return !ult(RHS); } 1267 1268 /// \brief Signed greather or equal comparison 1269 /// 1270 /// Regards both *this and RHS as signed quantities and compares them for 1271 /// validity of the greater-or-equal relationship. 1272 /// 1273 /// \returns true if *this >= RHS when both are considered signed. 1274 bool sge(const APInt &RHS) const { return !slt(RHS); } 1275 1276 /// \brief Signed greater or equal comparison 1277 /// 1278 /// Regards both *this as a signed quantity and compares it with RHS for 1279 /// the validity of the greater-or-equal relationship. 1280 /// 1281 /// \returns true if *this >= RHS when considered signed. 1282 bool sge(int64_t RHS) const { return !slt(RHS); } 1283 1284 /// This operation tests if there are any pairs of corresponding bits 1285 /// between this APInt and RHS that are both set. 1286 bool intersects(const APInt &RHS) const { 1287 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 1288 if (isSingleWord()) 1289 return (U.VAL & RHS.U.VAL) != 0; 1290 return intersectsSlowCase(RHS); 1291 } 1292 1293 /// This operation checks that all bits set in this APInt are also set in RHS. 1294 bool isSubsetOf(const APInt &RHS) const { 1295 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 1296 if (isSingleWord()) 1297 return (U.VAL & ~RHS.U.VAL) == 0; 1298 return isSubsetOfSlowCase(RHS); 1299 } 1300 1301 /// @} 1302 /// \name Resizing Operators 1303 /// @{ 1304 1305 /// \brief Truncate to new width. 1306 /// 1307 /// Truncate the APInt to a specified width. It is an error to specify a width 1308 /// that is greater than or equal to the current width. 1309 APInt trunc(unsigned width) const; 1310 1311 /// \brief Sign extend to a new width. 1312 /// 1313 /// This operation sign extends the APInt to a new width. If the high order 1314 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero. 1315 /// It is an error to specify a width that is less than or equal to the 1316 /// current width. 1317 APInt sext(unsigned width) const; 1318 1319 /// \brief Zero extend to a new width. 1320 /// 1321 /// This operation zero extends the APInt to a new width. The high order bits 1322 /// are filled with 0 bits. It is an error to specify a width that is less 1323 /// than or equal to the current width. 1324 APInt zext(unsigned width) const; 1325 1326 /// \brief Sign extend or truncate to width 1327 /// 1328 /// Make this APInt have the bit width given by \p width. The value is sign 1329 /// extended, truncated, or left alone to make it that width. 1330 APInt sextOrTrunc(unsigned width) const; 1331 1332 /// \brief Zero extend or truncate to width 1333 /// 1334 /// Make this APInt have the bit width given by \p width. The value is zero 1335 /// extended, truncated, or left alone to make it that width. 1336 APInt zextOrTrunc(unsigned width) const; 1337 1338 /// \brief Sign extend or truncate to width 1339 /// 1340 /// Make this APInt have the bit width given by \p width. The value is sign 1341 /// extended, or left alone to make it that width. 1342 APInt sextOrSelf(unsigned width) const; 1343 1344 /// \brief Zero extend or truncate to width 1345 /// 1346 /// Make this APInt have the bit width given by \p width. The value is zero 1347 /// extended, or left alone to make it that width. 1348 APInt zextOrSelf(unsigned width) const; 1349 1350 /// @} 1351 /// \name Bit Manipulation Operators 1352 /// @{ 1353 1354 /// \brief Set every bit to 1. 1355 void setAllBits() { 1356 if (isSingleWord()) 1357 U.VAL = WORD_MAX; 1358 else 1359 // Set all the bits in all the words. 1360 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE); 1361 // Clear the unused ones 1362 clearUnusedBits(); 1363 } 1364 1365 /// \brief Set a given bit to 1. 1366 /// 1367 /// Set the given bit to 1 whose position is given as "bitPosition". 1368 void setBit(unsigned BitPosition) { 1369 assert(BitPosition <= BitWidth && "BitPosition out of range"); 1370 WordType Mask = maskBit(BitPosition); 1371 if (isSingleWord()) 1372 U.VAL |= Mask; 1373 else 1374 U.pVal[whichWord(BitPosition)] |= Mask; 1375 } 1376 1377 /// Set the sign bit to 1. 1378 void setSignBit() { 1379 setBit(BitWidth - 1); 1380 } 1381 1382 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1. 1383 void setBits(unsigned loBit, unsigned hiBit) { 1384 assert(hiBit <= BitWidth && "hiBit out of range"); 1385 assert(loBit <= BitWidth && "loBit out of range"); 1386 assert(loBit <= hiBit && "loBit greater than hiBit"); 1387 if (loBit == hiBit) 1388 return; 1389 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) { 1390 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit)); 1391 mask <<= loBit; 1392 if (isSingleWord()) 1393 U.VAL |= mask; 1394 else 1395 U.pVal[0] |= mask; 1396 } else { 1397 setBitsSlowCase(loBit, hiBit); 1398 } 1399 } 1400 1401 /// Set the top bits starting from loBit. 1402 void setBitsFrom(unsigned loBit) { 1403 return setBits(loBit, BitWidth); 1404 } 1405 1406 /// Set the bottom loBits bits. 1407 void setLowBits(unsigned loBits) { 1408 return setBits(0, loBits); 1409 } 1410 1411 /// Set the top hiBits bits. 1412 void setHighBits(unsigned hiBits) { 1413 return setBits(BitWidth - hiBits, BitWidth); 1414 } 1415 1416 /// \brief Set every bit to 0. 1417 void clearAllBits() { 1418 if (isSingleWord()) 1419 U.VAL = 0; 1420 else 1421 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE); 1422 } 1423 1424 /// \brief Set a given bit to 0. 1425 /// 1426 /// Set the given bit to 0 whose position is given as "bitPosition". 1427 void clearBit(unsigned BitPosition) { 1428 assert(BitPosition <= BitWidth && "BitPosition out of range"); 1429 WordType Mask = ~maskBit(BitPosition); 1430 if (isSingleWord()) 1431 U.VAL &= Mask; 1432 else 1433 U.pVal[whichWord(BitPosition)] &= Mask; 1434 } 1435 1436 /// Set the sign bit to 0. 1437 void clearSignBit() { 1438 clearBit(BitWidth - 1); 1439 } 1440 1441 /// \brief Toggle every bit to its opposite value. 1442 void flipAllBits() { 1443 if (isSingleWord()) { 1444 U.VAL ^= WORD_MAX; 1445 clearUnusedBits(); 1446 } else { 1447 flipAllBitsSlowCase(); 1448 } 1449 } 1450 1451 /// \brief Toggles a given bit to its opposite value. 1452 /// 1453 /// Toggle a given bit to its opposite value whose position is given 1454 /// as "bitPosition". 1455 void flipBit(unsigned bitPosition); 1456 1457 /// Negate this APInt in place. 1458 void negate() { 1459 flipAllBits(); 1460 ++(*this); 1461 } 1462 1463 /// Insert the bits from a smaller APInt starting at bitPosition. 1464 void insertBits(const APInt &SubBits, unsigned bitPosition); 1465 1466 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits). 1467 APInt extractBits(unsigned numBits, unsigned bitPosition) const; 1468 1469 /// @} 1470 /// \name Value Characterization Functions 1471 /// @{ 1472 1473 /// \brief Return the number of bits in the APInt. 1474 unsigned getBitWidth() const { return BitWidth; } 1475 1476 /// \brief Get the number of words. 1477 /// 1478 /// Here one word's bitwidth equals to that of uint64_t. 1479 /// 1480 /// \returns the number of words to hold the integer value of this APInt. 1481 unsigned getNumWords() const { return getNumWords(BitWidth); } 1482 1483 /// \brief Get the number of words. 1484 /// 1485 /// *NOTE* Here one word's bitwidth equals to that of uint64_t. 1486 /// 1487 /// \returns the number of words to hold the integer value with a given bit 1488 /// width. 1489 static unsigned getNumWords(unsigned BitWidth) { 1490 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD; 1491 } 1492 1493 /// \brief Compute the number of active bits in the value 1494 /// 1495 /// This function returns the number of active bits which is defined as the 1496 /// bit width minus the number of leading zeros. This is used in several 1497 /// computations to see how "wide" the value is. 1498 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); } 1499 1500 /// \brief Compute the number of active words in the value of this APInt. 1501 /// 1502 /// This is used in conjunction with getActiveData to extract the raw value of 1503 /// the APInt. 1504 unsigned getActiveWords() const { 1505 unsigned numActiveBits = getActiveBits(); 1506 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1; 1507 } 1508 1509 /// \brief Get the minimum bit size for this signed APInt 1510 /// 1511 /// Computes the minimum bit width for this APInt while considering it to be a 1512 /// signed (and probably negative) value. If the value is not negative, this 1513 /// function returns the same value as getActiveBits()+1. Otherwise, it 1514 /// returns the smallest bit width that will retain the negative value. For 1515 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so 1516 /// for -1, this function will always return 1. 1517 unsigned getMinSignedBits() const { 1518 if (isNegative()) 1519 return BitWidth - countLeadingOnes() + 1; 1520 return getActiveBits() + 1; 1521 } 1522 1523 /// \brief Get zero extended value 1524 /// 1525 /// This method attempts to return the value of this APInt as a zero extended 1526 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a 1527 /// uint64_t. Otherwise an assertion will result. 1528 uint64_t getZExtValue() const { 1529 if (isSingleWord()) 1530 return U.VAL; 1531 assert(getActiveBits() <= 64 && "Too many bits for uint64_t"); 1532 return U.pVal[0]; 1533 } 1534 1535 /// \brief Get sign extended value 1536 /// 1537 /// This method attempts to return the value of this APInt as a sign extended 1538 /// int64_t. The bit width must be <= 64 or the value must fit within an 1539 /// int64_t. Otherwise an assertion will result. 1540 int64_t getSExtValue() const { 1541 if (isSingleWord()) 1542 return SignExtend64(U.VAL, BitWidth); 1543 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t"); 1544 return int64_t(U.pVal[0]); 1545 } 1546 1547 /// \brief Get bits required for string value. 1548 /// 1549 /// This method determines how many bits are required to hold the APInt 1550 /// equivalent of the string given by \p str. 1551 static unsigned getBitsNeeded(StringRef str, uint8_t radix); 1552 1553 /// \brief The APInt version of the countLeadingZeros functions in 1554 /// MathExtras.h. 1555 /// 1556 /// It counts the number of zeros from the most significant bit to the first 1557 /// one bit. 1558 /// 1559 /// \returns BitWidth if the value is zero, otherwise returns the number of 1560 /// zeros from the most significant bit to the first one bits. 1561 unsigned countLeadingZeros() const { 1562 if (isSingleWord()) { 1563 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth; 1564 return llvm::countLeadingZeros(U.VAL) - unusedBits; 1565 } 1566 return countLeadingZerosSlowCase(); 1567 } 1568 1569 /// \brief Count the number of leading one bits. 1570 /// 1571 /// This function is an APInt version of the countLeadingOnes 1572 /// functions in MathExtras.h. It counts the number of ones from the most 1573 /// significant bit to the first zero bit. 1574 /// 1575 /// \returns 0 if the high order bit is not set, otherwise returns the number 1576 /// of 1 bits from the most significant to the least 1577 unsigned countLeadingOnes() const LLVM_READONLY; 1578 1579 /// Computes the number of leading bits of this APInt that are equal to its 1580 /// sign bit. 1581 unsigned getNumSignBits() const { 1582 return isNegative() ? countLeadingOnes() : countLeadingZeros(); 1583 } 1584 1585 /// \brief Count the number of trailing zero bits. 1586 /// 1587 /// This function is an APInt version of the countTrailingZeros 1588 /// functions in MathExtras.h. It counts the number of zeros from the least 1589 /// significant bit to the first set bit. 1590 /// 1591 /// \returns BitWidth if the value is zero, otherwise returns the number of 1592 /// zeros from the least significant bit to the first one bit. 1593 unsigned countTrailingZeros() const LLVM_READONLY; 1594 1595 /// \brief Count the number of trailing one bits. 1596 /// 1597 /// This function is an APInt version of the countTrailingOnes 1598 /// functions in MathExtras.h. It counts the number of ones from the least 1599 /// significant bit to the first zero bit. 1600 /// 1601 /// \returns BitWidth if the value is all ones, otherwise returns the number 1602 /// of ones from the least significant bit to the first zero bit. 1603 unsigned countTrailingOnes() const { 1604 if (isSingleWord()) 1605 return llvm::countTrailingOnes(U.VAL); 1606 return countTrailingOnesSlowCase(); 1607 } 1608 1609 /// \brief Count the number of bits set. 1610 /// 1611 /// This function is an APInt version of the countPopulation functions 1612 /// in MathExtras.h. It counts the number of 1 bits in the APInt value. 1613 /// 1614 /// \returns 0 if the value is zero, otherwise returns the number of set bits. 1615 unsigned countPopulation() const { 1616 if (isSingleWord()) 1617 return llvm::countPopulation(U.VAL); 1618 return countPopulationSlowCase(); 1619 } 1620 1621 /// @} 1622 /// \name Conversion Functions 1623 /// @{ 1624 void print(raw_ostream &OS, bool isSigned) const; 1625 1626 /// Converts an APInt to a string and append it to Str. Str is commonly a 1627 /// SmallString. 1628 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed, 1629 bool formatAsCLiteral = false) const; 1630 1631 /// Considers the APInt to be unsigned and converts it into a string in the 1632 /// radix given. The radix can be 2, 8, 10 16, or 36. 1633 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const { 1634 toString(Str, Radix, false, false); 1635 } 1636 1637 /// Considers the APInt to be signed and converts it into a string in the 1638 /// radix given. The radix can be 2, 8, 10, 16, or 36. 1639 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const { 1640 toString(Str, Radix, true, false); 1641 } 1642 1643 /// \brief Return the APInt as a std::string. 1644 /// 1645 /// Note that this is an inefficient method. It is better to pass in a 1646 /// SmallVector/SmallString to the methods above to avoid thrashing the heap 1647 /// for the string. 1648 std::string toString(unsigned Radix, bool Signed) const; 1649 1650 /// \returns a byte-swapped representation of this APInt Value. 1651 APInt byteSwap() const; 1652 1653 /// \returns the value with the bit representation reversed of this APInt 1654 /// Value. 1655 APInt reverseBits() const; 1656 1657 /// \brief Converts this APInt to a double value. 1658 double roundToDouble(bool isSigned) const; 1659 1660 /// \brief Converts this unsigned APInt to a double value. 1661 double roundToDouble() const { return roundToDouble(false); } 1662 1663 /// \brief Converts this signed APInt to a double value. 1664 double signedRoundToDouble() const { return roundToDouble(true); } 1665 1666 /// \brief Converts APInt bits to a double 1667 /// 1668 /// The conversion does not do a translation from integer to double, it just 1669 /// re-interprets the bits as a double. Note that it is valid to do this on 1670 /// any bit width. Exactly 64 bits will be translated. 1671 double bitsToDouble() const { 1672 return BitsToDouble(getWord(0)); 1673 } 1674 1675 /// \brief Converts APInt bits to a double 1676 /// 1677 /// The conversion does not do a translation from integer to float, it just 1678 /// re-interprets the bits as a float. Note that it is valid to do this on 1679 /// any bit width. Exactly 32 bits will be translated. 1680 float bitsToFloat() const { 1681 return BitsToFloat(getWord(0)); 1682 } 1683 1684 /// \brief Converts a double to APInt bits. 1685 /// 1686 /// The conversion does not do a translation from double to integer, it just 1687 /// re-interprets the bits of the double. 1688 static APInt doubleToBits(double V) { 1689 return APInt(sizeof(double) * CHAR_BIT, DoubleToBits(V)); 1690 } 1691 1692 /// \brief Converts a float to APInt bits. 1693 /// 1694 /// The conversion does not do a translation from float to integer, it just 1695 /// re-interprets the bits of the float. 1696 static APInt floatToBits(float V) { 1697 return APInt(sizeof(float) * CHAR_BIT, FloatToBits(V)); 1698 } 1699 1700 /// @} 1701 /// \name Mathematics Operations 1702 /// @{ 1703 1704 /// \returns the floor log base 2 of this APInt. 1705 unsigned logBase2() const { return BitWidth - 1 - countLeadingZeros(); } 1706 1707 /// \returns the ceil log base 2 of this APInt. 1708 unsigned ceilLogBase2() const { 1709 APInt temp(*this); 1710 --temp; 1711 return BitWidth - temp.countLeadingZeros(); 1712 } 1713 1714 /// \returns the nearest log base 2 of this APInt. Ties round up. 1715 /// 1716 /// NOTE: When we have a BitWidth of 1, we define: 1717 /// 1718 /// log2(0) = UINT32_MAX 1719 /// log2(1) = 0 1720 /// 1721 /// to get around any mathematical concerns resulting from 1722 /// referencing 2 in a space where 2 does no exist. 1723 unsigned nearestLogBase2() const { 1724 // Special case when we have a bitwidth of 1. If VAL is 1, then we 1725 // get 0. If VAL is 0, we get WORD_MAX which gets truncated to 1726 // UINT32_MAX. 1727 if (BitWidth == 1) 1728 return U.VAL - 1; 1729 1730 // Handle the zero case. 1731 if (isNullValue()) 1732 return UINT32_MAX; 1733 1734 // The non-zero case is handled by computing: 1735 // 1736 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1]. 1737 // 1738 // where x[i] is referring to the value of the ith bit of x. 1739 unsigned lg = logBase2(); 1740 return lg + unsigned((*this)[lg - 1]); 1741 } 1742 1743 /// \returns the log base 2 of this APInt if its an exact power of two, -1 1744 /// otherwise 1745 int32_t exactLogBase2() const { 1746 if (!isPowerOf2()) 1747 return -1; 1748 return logBase2(); 1749 } 1750 1751 /// \brief Compute the square root 1752 APInt sqrt() const; 1753 1754 /// \brief Get the absolute value; 1755 /// 1756 /// If *this is < 0 then return -(*this), otherwise *this; 1757 APInt abs() const { 1758 if (isNegative()) 1759 return -(*this); 1760 return *this; 1761 } 1762 1763 /// \returns the multiplicative inverse for a given modulo. 1764 APInt multiplicativeInverse(const APInt &modulo) const; 1765 1766 /// @} 1767 /// \name Support for division by constant 1768 /// @{ 1769 1770 /// Calculate the magic number for signed division by a constant. 1771 struct ms; 1772 ms magic() const; 1773 1774 /// Calculate the magic number for unsigned division by a constant. 1775 struct mu; 1776 mu magicu(unsigned LeadingZeros = 0) const; 1777 1778 /// @} 1779 /// \name Building-block Operations for APInt and APFloat 1780 /// @{ 1781 1782 // These building block operations operate on a representation of arbitrary 1783 // precision, two's-complement, bignum integer values. They should be 1784 // sufficient to implement APInt and APFloat bignum requirements. Inputs are 1785 // generally a pointer to the base of an array of integer parts, representing 1786 // an unsigned bignum, and a count of how many parts there are. 1787 1788 /// Sets the least significant part of a bignum to the input value, and zeroes 1789 /// out higher parts. 1790 static void tcSet(WordType *, WordType, unsigned); 1791 1792 /// Assign one bignum to another. 1793 static void tcAssign(WordType *, const WordType *, unsigned); 1794 1795 /// Returns true if a bignum is zero, false otherwise. 1796 static bool tcIsZero(const WordType *, unsigned); 1797 1798 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based. 1799 static int tcExtractBit(const WordType *, unsigned bit); 1800 1801 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to 1802 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least 1803 /// significant bit of DST. All high bits above srcBITS in DST are 1804 /// zero-filled. 1805 static void tcExtract(WordType *, unsigned dstCount, 1806 const WordType *, unsigned srcBits, 1807 unsigned srcLSB); 1808 1809 /// Set the given bit of a bignum. Zero-based. 1810 static void tcSetBit(WordType *, unsigned bit); 1811 1812 /// Clear the given bit of a bignum. Zero-based. 1813 static void tcClearBit(WordType *, unsigned bit); 1814 1815 /// Returns the bit number of the least or most significant set bit of a 1816 /// number. If the input number has no bits set -1U is returned. 1817 static unsigned tcLSB(const WordType *, unsigned n); 1818 static unsigned tcMSB(const WordType *parts, unsigned n); 1819 1820 /// Negate a bignum in-place. 1821 static void tcNegate(WordType *, unsigned); 1822 1823 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag. 1824 static WordType tcAdd(WordType *, const WordType *, 1825 WordType carry, unsigned); 1826 /// DST += RHS. Returns the carry flag. 1827 static WordType tcAddPart(WordType *, WordType, unsigned); 1828 1829 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag. 1830 static WordType tcSubtract(WordType *, const WordType *, 1831 WordType carry, unsigned); 1832 /// DST -= RHS. Returns the carry flag. 1833 static WordType tcSubtractPart(WordType *, WordType, unsigned); 1834 1835 /// DST += SRC * MULTIPLIER + PART if add is true 1836 /// DST = SRC * MULTIPLIER + PART if add is false 1837 /// 1838 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must 1839 /// start at the same point, i.e. DST == SRC. 1840 /// 1841 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned. 1842 /// Otherwise DST is filled with the least significant DSTPARTS parts of the 1843 /// result, and if all of the omitted higher parts were zero return zero, 1844 /// otherwise overflow occurred and return one. 1845 static int tcMultiplyPart(WordType *dst, const WordType *src, 1846 WordType multiplier, WordType carry, 1847 unsigned srcParts, unsigned dstParts, 1848 bool add); 1849 1850 /// DST = LHS * RHS, where DST has the same width as the operands and is 1851 /// filled with the least significant parts of the result. Returns one if 1852 /// overflow occurred, otherwise zero. DST must be disjoint from both 1853 /// operands. 1854 static int tcMultiply(WordType *, const WordType *, const WordType *, 1855 unsigned); 1856 1857 /// DST = LHS * RHS, where DST has width the sum of the widths of the 1858 /// operands. No overflow occurs. DST must be disjoint from both operands. 1859 static void tcFullMultiply(WordType *, const WordType *, 1860 const WordType *, unsigned, unsigned); 1861 1862 /// If RHS is zero LHS and REMAINDER are left unchanged, return one. 1863 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set 1864 /// REMAINDER to the remainder, return zero. i.e. 1865 /// 1866 /// OLD_LHS = RHS * LHS + REMAINDER 1867 /// 1868 /// SCRATCH is a bignum of the same size as the operands and result for use by 1869 /// the routine; its contents need not be initialized and are destroyed. LHS, 1870 /// REMAINDER and SCRATCH must be distinct. 1871 static int tcDivide(WordType *lhs, const WordType *rhs, 1872 WordType *remainder, WordType *scratch, 1873 unsigned parts); 1874 1875 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no 1876 /// restrictions on Count. 1877 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count); 1878 1879 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no 1880 /// restrictions on Count. 1881 static void tcShiftRight(WordType *, unsigned Words, unsigned Count); 1882 1883 /// The obvious AND, OR and XOR and complement operations. 1884 static void tcAnd(WordType *, const WordType *, unsigned); 1885 static void tcOr(WordType *, const WordType *, unsigned); 1886 static void tcXor(WordType *, const WordType *, unsigned); 1887 static void tcComplement(WordType *, unsigned); 1888 1889 /// Comparison (unsigned) of two bignums. 1890 static int tcCompare(const WordType *, const WordType *, unsigned); 1891 1892 /// Increment a bignum in-place. Return the carry flag. 1893 static WordType tcIncrement(WordType *dst, unsigned parts) { 1894 return tcAddPart(dst, 1, parts); 1895 } 1896 1897 /// Decrement a bignum in-place. Return the borrow flag. 1898 static WordType tcDecrement(WordType *dst, unsigned parts) { 1899 return tcSubtractPart(dst, 1, parts); 1900 } 1901 1902 /// Set the least significant BITS and clear the rest. 1903 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits); 1904 1905 /// \brief debug method 1906 void dump() const; 1907 1908 /// @} 1909 }; 1910 1911 /// Magic data for optimising signed division by a constant. 1912 struct APInt::ms { 1913 APInt m; ///< magic number 1914 unsigned s; ///< shift amount 1915 }; 1916 1917 /// Magic data for optimising unsigned division by a constant. 1918 struct APInt::mu { 1919 APInt m; ///< magic number 1920 bool a; ///< add indicator 1921 unsigned s; ///< shift amount 1922 }; 1923 1924 inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; } 1925 1926 inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; } 1927 1928 /// \brief Unary bitwise complement operator. 1929 /// 1930 /// \returns an APInt that is the bitwise complement of \p v. 1931 inline APInt operator~(APInt v) { 1932 v.flipAllBits(); 1933 return v; 1934 } 1935 1936 inline APInt operator&(APInt a, const APInt &b) { 1937 a &= b; 1938 return a; 1939 } 1940 1941 inline APInt operator&(const APInt &a, APInt &&b) { 1942 b &= a; 1943 return std::move(b); 1944 } 1945 1946 inline APInt operator&(APInt a, uint64_t RHS) { 1947 a &= RHS; 1948 return a; 1949 } 1950 1951 inline APInt operator&(uint64_t LHS, APInt b) { 1952 b &= LHS; 1953 return b; 1954 } 1955 1956 inline APInt operator|(APInt a, const APInt &b) { 1957 a |= b; 1958 return a; 1959 } 1960 1961 inline APInt operator|(const APInt &a, APInt &&b) { 1962 b |= a; 1963 return std::move(b); 1964 } 1965 1966 inline APInt operator|(APInt a, uint64_t RHS) { 1967 a |= RHS; 1968 return a; 1969 } 1970 1971 inline APInt operator|(uint64_t LHS, APInt b) { 1972 b |= LHS; 1973 return b; 1974 } 1975 1976 inline APInt operator^(APInt a, const APInt &b) { 1977 a ^= b; 1978 return a; 1979 } 1980 1981 inline APInt operator^(const APInt &a, APInt &&b) { 1982 b ^= a; 1983 return std::move(b); 1984 } 1985 1986 inline APInt operator^(APInt a, uint64_t RHS) { 1987 a ^= RHS; 1988 return a; 1989 } 1990 1991 inline APInt operator^(uint64_t LHS, APInt b) { 1992 b ^= LHS; 1993 return b; 1994 } 1995 1996 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) { 1997 I.print(OS, true); 1998 return OS; 1999 } 2000 2001 inline APInt operator-(APInt v) { 2002 v.negate(); 2003 return v; 2004 } 2005 2006 inline APInt operator+(APInt a, const APInt &b) { 2007 a += b; 2008 return a; 2009 } 2010 2011 inline APInt operator+(const APInt &a, APInt &&b) { 2012 b += a; 2013 return std::move(b); 2014 } 2015 2016 inline APInt operator+(APInt a, uint64_t RHS) { 2017 a += RHS; 2018 return a; 2019 } 2020 2021 inline APInt operator+(uint64_t LHS, APInt b) { 2022 b += LHS; 2023 return b; 2024 } 2025 2026 inline APInt operator-(APInt a, const APInt &b) { 2027 a -= b; 2028 return a; 2029 } 2030 2031 inline APInt operator-(const APInt &a, APInt &&b) { 2032 b.negate(); 2033 b += a; 2034 return std::move(b); 2035 } 2036 2037 inline APInt operator-(APInt a, uint64_t RHS) { 2038 a -= RHS; 2039 return a; 2040 } 2041 2042 inline APInt operator-(uint64_t LHS, APInt b) { 2043 b.negate(); 2044 b += LHS; 2045 return b; 2046 } 2047 2048 inline APInt operator*(APInt a, uint64_t RHS) { 2049 a *= RHS; 2050 return a; 2051 } 2052 2053 inline APInt operator*(uint64_t LHS, APInt b) { 2054 b *= LHS; 2055 return b; 2056 } 2057 2058 2059 namespace APIntOps { 2060 2061 /// \brief Determine the smaller of two APInts considered to be signed. 2062 inline const APInt &smin(const APInt &A, const APInt &B) { 2063 return A.slt(B) ? A : B; 2064 } 2065 2066 /// \brief Determine the larger of two APInts considered to be signed. 2067 inline const APInt &smax(const APInt &A, const APInt &B) { 2068 return A.sgt(B) ? A : B; 2069 } 2070 2071 /// \brief Determine the smaller of two APInts considered to be signed. 2072 inline const APInt &umin(const APInt &A, const APInt &B) { 2073 return A.ult(B) ? A : B; 2074 } 2075 2076 /// \brief Determine the larger of two APInts considered to be unsigned. 2077 inline const APInt &umax(const APInt &A, const APInt &B) { 2078 return A.ugt(B) ? A : B; 2079 } 2080 2081 /// \brief Compute GCD of two unsigned APInt values. 2082 /// 2083 /// This function returns the greatest common divisor of the two APInt values 2084 /// using Stein's algorithm. 2085 /// 2086 /// \returns the greatest common divisor of A and B. 2087 APInt GreatestCommonDivisor(APInt A, APInt B); 2088 2089 /// \brief Converts the given APInt to a double value. 2090 /// 2091 /// Treats the APInt as an unsigned value for conversion purposes. 2092 inline double RoundAPIntToDouble(const APInt &APIVal) { 2093 return APIVal.roundToDouble(); 2094 } 2095 2096 /// \brief Converts the given APInt to a double value. 2097 /// 2098 /// Treats the APInt as a signed value for conversion purposes. 2099 inline double RoundSignedAPIntToDouble(const APInt &APIVal) { 2100 return APIVal.signedRoundToDouble(); 2101 } 2102 2103 /// \brief Converts the given APInt to a float vlalue. 2104 inline float RoundAPIntToFloat(const APInt &APIVal) { 2105 return float(RoundAPIntToDouble(APIVal)); 2106 } 2107 2108 /// \brief Converts the given APInt to a float value. 2109 /// 2110 /// Treast the APInt as a signed value for conversion purposes. 2111 inline float RoundSignedAPIntToFloat(const APInt &APIVal) { 2112 return float(APIVal.signedRoundToDouble()); 2113 } 2114 2115 /// \brief Converts the given double value into a APInt. 2116 /// 2117 /// This function convert a double value to an APInt value. 2118 APInt RoundDoubleToAPInt(double Double, unsigned width); 2119 2120 /// \brief Converts a float value into a APInt. 2121 /// 2122 /// Converts a float value into an APInt value. 2123 inline APInt RoundFloatToAPInt(float Float, unsigned width) { 2124 return RoundDoubleToAPInt(double(Float), width); 2125 } 2126 2127 } // End of APIntOps namespace 2128 2129 // See friend declaration above. This additional declaration is required in 2130 // order to compile LLVM with IBM xlC compiler. 2131 hash_code hash_value(const APInt &Arg); 2132 } // End of llvm namespace 2133 2134 #endif 2135