1 //===-- APInt.cpp - Implement APInt class ---------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements a class to represent arbitrary precision integer 10 // constant values and provide a variety of arithmetic operations on them. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ADT/APInt.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/FoldingSet.h" 17 #include "llvm/ADT/Hashing.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/bit.h" 21 #include "llvm/Config/llvm-config.h" 22 #include "llvm/Support/Alignment.h" 23 #include "llvm/Support/Debug.h" 24 #include "llvm/Support/ErrorHandling.h" 25 #include "llvm/Support/MathExtras.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include <cmath> 28 #include <optional> 29 30 using namespace llvm; 31 32 #define DEBUG_TYPE "apint" 33 34 /// A utility function for allocating memory, checking for allocation failures, 35 /// and ensuring the contents are zeroed. 36 inline static uint64_t* getClearedMemory(unsigned numWords) { 37 uint64_t *result = new uint64_t[numWords]; 38 memset(result, 0, numWords * sizeof(uint64_t)); 39 return result; 40 } 41 42 /// A utility function for allocating memory and checking for allocation 43 /// failure. The content is not zeroed. 44 inline static uint64_t* getMemory(unsigned numWords) { 45 return new uint64_t[numWords]; 46 } 47 48 /// A utility function that converts a character to a digit. 49 inline static unsigned getDigit(char cdigit, uint8_t radix) { 50 unsigned r; 51 52 if (radix == 16 || radix == 36) { 53 r = cdigit - '0'; 54 if (r <= 9) 55 return r; 56 57 r = cdigit - 'A'; 58 if (r <= radix - 11U) 59 return r + 10; 60 61 r = cdigit - 'a'; 62 if (r <= radix - 11U) 63 return r + 10; 64 65 radix = 10; 66 } 67 68 r = cdigit - '0'; 69 if (r < radix) 70 return r; 71 72 return UINT_MAX; 73 } 74 75 76 void APInt::initSlowCase(uint64_t val, bool isSigned) { 77 U.pVal = getClearedMemory(getNumWords()); 78 U.pVal[0] = val; 79 if (isSigned && int64_t(val) < 0) 80 for (unsigned i = 1; i < getNumWords(); ++i) 81 U.pVal[i] = WORDTYPE_MAX; 82 clearUnusedBits(); 83 } 84 85 void APInt::initSlowCase(const APInt& that) { 86 U.pVal = getMemory(getNumWords()); 87 memcpy(U.pVal, that.U.pVal, getNumWords() * APINT_WORD_SIZE); 88 } 89 90 void APInt::initFromArray(ArrayRef<uint64_t> bigVal) { 91 assert(bigVal.data() && "Null pointer detected!"); 92 if (isSingleWord()) 93 U.VAL = bigVal[0]; 94 else { 95 // Get memory, cleared to 0 96 U.pVal = getClearedMemory(getNumWords()); 97 // Calculate the number of words to copy 98 unsigned words = std::min<unsigned>(bigVal.size(), getNumWords()); 99 // Copy the words from bigVal to pVal 100 memcpy(U.pVal, bigVal.data(), words * APINT_WORD_SIZE); 101 } 102 // Make sure unused high bits are cleared 103 clearUnusedBits(); 104 } 105 106 APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal) : BitWidth(numBits) { 107 initFromArray(bigVal); 108 } 109 110 APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]) 111 : BitWidth(numBits) { 112 initFromArray(ArrayRef(bigVal, numWords)); 113 } 114 115 APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix) 116 : BitWidth(numbits) { 117 fromString(numbits, Str, radix); 118 } 119 120 void APInt::reallocate(unsigned NewBitWidth) { 121 // If the number of words is the same we can just change the width and stop. 122 if (getNumWords() == getNumWords(NewBitWidth)) { 123 BitWidth = NewBitWidth; 124 return; 125 } 126 127 // If we have an allocation, delete it. 128 if (!isSingleWord()) 129 delete [] U.pVal; 130 131 // Update BitWidth. 132 BitWidth = NewBitWidth; 133 134 // If we are supposed to have an allocation, create it. 135 if (!isSingleWord()) 136 U.pVal = getMemory(getNumWords()); 137 } 138 139 void APInt::assignSlowCase(const APInt &RHS) { 140 // Don't do anything for X = X 141 if (this == &RHS) 142 return; 143 144 // Adjust the bit width and handle allocations as necessary. 145 reallocate(RHS.getBitWidth()); 146 147 // Copy the data. 148 if (isSingleWord()) 149 U.VAL = RHS.U.VAL; 150 else 151 memcpy(U.pVal, RHS.U.pVal, getNumWords() * APINT_WORD_SIZE); 152 } 153 154 /// This method 'profiles' an APInt for use with FoldingSet. 155 void APInt::Profile(FoldingSetNodeID& ID) const { 156 ID.AddInteger(BitWidth); 157 158 if (isSingleWord()) { 159 ID.AddInteger(U.VAL); 160 return; 161 } 162 163 unsigned NumWords = getNumWords(); 164 for (unsigned i = 0; i < NumWords; ++i) 165 ID.AddInteger(U.pVal[i]); 166 } 167 168 bool APInt::isAligned(Align A) const { 169 if (isZero()) 170 return true; 171 const unsigned TrailingZeroes = countr_zero(); 172 const unsigned MinimumTrailingZeroes = Log2(A); 173 return TrailingZeroes >= MinimumTrailingZeroes; 174 } 175 176 /// Prefix increment operator. Increments the APInt by one. 177 APInt& APInt::operator++() { 178 if (isSingleWord()) 179 ++U.VAL; 180 else 181 tcIncrement(U.pVal, getNumWords()); 182 return clearUnusedBits(); 183 } 184 185 /// Prefix decrement operator. Decrements the APInt by one. 186 APInt& APInt::operator--() { 187 if (isSingleWord()) 188 --U.VAL; 189 else 190 tcDecrement(U.pVal, getNumWords()); 191 return clearUnusedBits(); 192 } 193 194 /// Adds the RHS APInt to this APInt. 195 /// @returns this, after addition of RHS. 196 /// Addition assignment operator. 197 APInt& APInt::operator+=(const APInt& RHS) { 198 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 199 if (isSingleWord()) 200 U.VAL += RHS.U.VAL; 201 else 202 tcAdd(U.pVal, RHS.U.pVal, 0, getNumWords()); 203 return clearUnusedBits(); 204 } 205 206 APInt& APInt::operator+=(uint64_t RHS) { 207 if (isSingleWord()) 208 U.VAL += RHS; 209 else 210 tcAddPart(U.pVal, RHS, getNumWords()); 211 return clearUnusedBits(); 212 } 213 214 /// Subtracts the RHS APInt from this APInt 215 /// @returns this, after subtraction 216 /// Subtraction assignment operator. 217 APInt& APInt::operator-=(const APInt& RHS) { 218 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 219 if (isSingleWord()) 220 U.VAL -= RHS.U.VAL; 221 else 222 tcSubtract(U.pVal, RHS.U.pVal, 0, getNumWords()); 223 return clearUnusedBits(); 224 } 225 226 APInt& APInt::operator-=(uint64_t RHS) { 227 if (isSingleWord()) 228 U.VAL -= RHS; 229 else 230 tcSubtractPart(U.pVal, RHS, getNumWords()); 231 return clearUnusedBits(); 232 } 233 234 APInt APInt::operator*(const APInt& RHS) const { 235 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 236 if (isSingleWord()) 237 return APInt(BitWidth, U.VAL * RHS.U.VAL); 238 239 APInt Result(getMemory(getNumWords()), getBitWidth()); 240 tcMultiply(Result.U.pVal, U.pVal, RHS.U.pVal, getNumWords()); 241 Result.clearUnusedBits(); 242 return Result; 243 } 244 245 void APInt::andAssignSlowCase(const APInt &RHS) { 246 WordType *dst = U.pVal, *rhs = RHS.U.pVal; 247 for (size_t i = 0, e = getNumWords(); i != e; ++i) 248 dst[i] &= rhs[i]; 249 } 250 251 void APInt::orAssignSlowCase(const APInt &RHS) { 252 WordType *dst = U.pVal, *rhs = RHS.U.pVal; 253 for (size_t i = 0, e = getNumWords(); i != e; ++i) 254 dst[i] |= rhs[i]; 255 } 256 257 void APInt::xorAssignSlowCase(const APInt &RHS) { 258 WordType *dst = U.pVal, *rhs = RHS.U.pVal; 259 for (size_t i = 0, e = getNumWords(); i != e; ++i) 260 dst[i] ^= rhs[i]; 261 } 262 263 APInt &APInt::operator*=(const APInt &RHS) { 264 *this = *this * RHS; 265 return *this; 266 } 267 268 APInt& APInt::operator*=(uint64_t RHS) { 269 if (isSingleWord()) { 270 U.VAL *= RHS; 271 } else { 272 unsigned NumWords = getNumWords(); 273 tcMultiplyPart(U.pVal, U.pVal, RHS, 0, NumWords, NumWords, false); 274 } 275 return clearUnusedBits(); 276 } 277 278 bool APInt::equalSlowCase(const APInt &RHS) const { 279 return std::equal(U.pVal, U.pVal + getNumWords(), RHS.U.pVal); 280 } 281 282 int APInt::compare(const APInt& RHS) const { 283 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison"); 284 if (isSingleWord()) 285 return U.VAL < RHS.U.VAL ? -1 : U.VAL > RHS.U.VAL; 286 287 return tcCompare(U.pVal, RHS.U.pVal, getNumWords()); 288 } 289 290 int APInt::compareSigned(const APInt& RHS) const { 291 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison"); 292 if (isSingleWord()) { 293 int64_t lhsSext = SignExtend64(U.VAL, BitWidth); 294 int64_t rhsSext = SignExtend64(RHS.U.VAL, BitWidth); 295 return lhsSext < rhsSext ? -1 : lhsSext > rhsSext; 296 } 297 298 bool lhsNeg = isNegative(); 299 bool rhsNeg = RHS.isNegative(); 300 301 // If the sign bits don't match, then (LHS < RHS) if LHS is negative 302 if (lhsNeg != rhsNeg) 303 return lhsNeg ? -1 : 1; 304 305 // Otherwise we can just use an unsigned comparison, because even negative 306 // numbers compare correctly this way if both have the same signed-ness. 307 return tcCompare(U.pVal, RHS.U.pVal, getNumWords()); 308 } 309 310 void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) { 311 unsigned loWord = whichWord(loBit); 312 unsigned hiWord = whichWord(hiBit); 313 314 // Create an initial mask for the low word with zeros below loBit. 315 uint64_t loMask = WORDTYPE_MAX << whichBit(loBit); 316 317 // If hiBit is not aligned, we need a high mask. 318 unsigned hiShiftAmt = whichBit(hiBit); 319 if (hiShiftAmt != 0) { 320 // Create a high mask with zeros above hiBit. 321 uint64_t hiMask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt); 322 // If loWord and hiWord are equal, then we combine the masks. Otherwise, 323 // set the bits in hiWord. 324 if (hiWord == loWord) 325 loMask &= hiMask; 326 else 327 U.pVal[hiWord] |= hiMask; 328 } 329 // Apply the mask to the low word. 330 U.pVal[loWord] |= loMask; 331 332 // Fill any words between loWord and hiWord with all ones. 333 for (unsigned word = loWord + 1; word < hiWord; ++word) 334 U.pVal[word] = WORDTYPE_MAX; 335 } 336 337 // Complement a bignum in-place. 338 static void tcComplement(APInt::WordType *dst, unsigned parts) { 339 for (unsigned i = 0; i < parts; i++) 340 dst[i] = ~dst[i]; 341 } 342 343 /// Toggle every bit to its opposite value. 344 void APInt::flipAllBitsSlowCase() { 345 tcComplement(U.pVal, getNumWords()); 346 clearUnusedBits(); 347 } 348 349 /// Concatenate the bits from "NewLSB" onto the bottom of *this. This is 350 /// equivalent to: 351 /// (this->zext(NewWidth) << NewLSB.getBitWidth()) | NewLSB.zext(NewWidth) 352 /// In the slow case, we know the result is large. 353 APInt APInt::concatSlowCase(const APInt &NewLSB) const { 354 unsigned NewWidth = getBitWidth() + NewLSB.getBitWidth(); 355 APInt Result = NewLSB.zext(NewWidth); 356 Result.insertBits(*this, NewLSB.getBitWidth()); 357 return Result; 358 } 359 360 /// Toggle a given bit to its opposite value whose position is given 361 /// as "bitPosition". 362 /// Toggles a given bit to its opposite value. 363 void APInt::flipBit(unsigned bitPosition) { 364 assert(bitPosition < BitWidth && "Out of the bit-width range!"); 365 setBitVal(bitPosition, !(*this)[bitPosition]); 366 } 367 368 void APInt::insertBits(const APInt &subBits, unsigned bitPosition) { 369 unsigned subBitWidth = subBits.getBitWidth(); 370 assert((subBitWidth + bitPosition) <= BitWidth && "Illegal bit insertion"); 371 372 // inserting no bits is a noop. 373 if (subBitWidth == 0) 374 return; 375 376 // Insertion is a direct copy. 377 if (subBitWidth == BitWidth) { 378 *this = subBits; 379 return; 380 } 381 382 // Single word result can be done as a direct bitmask. 383 if (isSingleWord()) { 384 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth); 385 U.VAL &= ~(mask << bitPosition); 386 U.VAL |= (subBits.U.VAL << bitPosition); 387 return; 388 } 389 390 unsigned loBit = whichBit(bitPosition); 391 unsigned loWord = whichWord(bitPosition); 392 unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1); 393 394 // Insertion within a single word can be done as a direct bitmask. 395 if (loWord == hi1Word) { 396 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth); 397 U.pVal[loWord] &= ~(mask << loBit); 398 U.pVal[loWord] |= (subBits.U.VAL << loBit); 399 return; 400 } 401 402 // Insert on word boundaries. 403 if (loBit == 0) { 404 // Direct copy whole words. 405 unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD; 406 memcpy(U.pVal + loWord, subBits.getRawData(), 407 numWholeSubWords * APINT_WORD_SIZE); 408 409 // Mask+insert remaining bits. 410 unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD; 411 if (remainingBits != 0) { 412 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - remainingBits); 413 U.pVal[hi1Word] &= ~mask; 414 U.pVal[hi1Word] |= subBits.getWord(subBitWidth - 1); 415 } 416 return; 417 } 418 419 // General case - set/clear individual bits in dst based on src. 420 // TODO - there is scope for optimization here, but at the moment this code 421 // path is barely used so prefer readability over performance. 422 for (unsigned i = 0; i != subBitWidth; ++i) 423 setBitVal(bitPosition + i, subBits[i]); 424 } 425 426 void APInt::insertBits(uint64_t subBits, unsigned bitPosition, unsigned numBits) { 427 uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits); 428 subBits &= maskBits; 429 if (isSingleWord()) { 430 U.VAL &= ~(maskBits << bitPosition); 431 U.VAL |= subBits << bitPosition; 432 return; 433 } 434 435 unsigned loBit = whichBit(bitPosition); 436 unsigned loWord = whichWord(bitPosition); 437 unsigned hiWord = whichWord(bitPosition + numBits - 1); 438 if (loWord == hiWord) { 439 U.pVal[loWord] &= ~(maskBits << loBit); 440 U.pVal[loWord] |= subBits << loBit; 441 return; 442 } 443 444 static_assert(8 * sizeof(WordType) <= 64, "This code assumes only two words affected"); 445 unsigned wordBits = 8 * sizeof(WordType); 446 U.pVal[loWord] &= ~(maskBits << loBit); 447 U.pVal[loWord] |= subBits << loBit; 448 449 U.pVal[hiWord] &= ~(maskBits >> (wordBits - loBit)); 450 U.pVal[hiWord] |= subBits >> (wordBits - loBit); 451 } 452 453 APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const { 454 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth && 455 "Illegal bit extraction"); 456 457 if (isSingleWord()) 458 return APInt(numBits, U.VAL >> bitPosition); 459 460 unsigned loBit = whichBit(bitPosition); 461 unsigned loWord = whichWord(bitPosition); 462 unsigned hiWord = whichWord(bitPosition + numBits - 1); 463 464 // Single word result extracting bits from a single word source. 465 if (loWord == hiWord) 466 return APInt(numBits, U.pVal[loWord] >> loBit); 467 468 // Extracting bits that start on a source word boundary can be done 469 // as a fast memory copy. 470 if (loBit == 0) 471 return APInt(numBits, ArrayRef(U.pVal + loWord, 1 + hiWord - loWord)); 472 473 // General case - shift + copy source words directly into place. 474 APInt Result(numBits, 0); 475 unsigned NumSrcWords = getNumWords(); 476 unsigned NumDstWords = Result.getNumWords(); 477 478 uint64_t *DestPtr = Result.isSingleWord() ? &Result.U.VAL : Result.U.pVal; 479 for (unsigned word = 0; word < NumDstWords; ++word) { 480 uint64_t w0 = U.pVal[loWord + word]; 481 uint64_t w1 = 482 (loWord + word + 1) < NumSrcWords ? U.pVal[loWord + word + 1] : 0; 483 DestPtr[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit)); 484 } 485 486 return Result.clearUnusedBits(); 487 } 488 489 uint64_t APInt::extractBitsAsZExtValue(unsigned numBits, 490 unsigned bitPosition) const { 491 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth && 492 "Illegal bit extraction"); 493 assert(numBits <= 64 && "Illegal bit extraction"); 494 495 uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits); 496 if (isSingleWord()) 497 return (U.VAL >> bitPosition) & maskBits; 498 499 unsigned loBit = whichBit(bitPosition); 500 unsigned loWord = whichWord(bitPosition); 501 unsigned hiWord = whichWord(bitPosition + numBits - 1); 502 if (loWord == hiWord) 503 return (U.pVal[loWord] >> loBit) & maskBits; 504 505 static_assert(8 * sizeof(WordType) <= 64, "This code assumes only two words affected"); 506 unsigned wordBits = 8 * sizeof(WordType); 507 uint64_t retBits = U.pVal[loWord] >> loBit; 508 retBits |= U.pVal[hiWord] << (wordBits - loBit); 509 retBits &= maskBits; 510 return retBits; 511 } 512 513 unsigned APInt::getSufficientBitsNeeded(StringRef Str, uint8_t Radix) { 514 assert(!Str.empty() && "Invalid string length"); 515 size_t StrLen = Str.size(); 516 517 // Each computation below needs to know if it's negative. 518 unsigned IsNegative = false; 519 if (Str[0] == '-' || Str[0] == '+') { 520 IsNegative = Str[0] == '-'; 521 StrLen--; 522 assert(StrLen && "String is only a sign, needs a value."); 523 } 524 525 // For radixes of power-of-two values, the bits required is accurately and 526 // easily computed. 527 if (Radix == 2) 528 return StrLen + IsNegative; 529 if (Radix == 8) 530 return StrLen * 3 + IsNegative; 531 if (Radix == 16) 532 return StrLen * 4 + IsNegative; 533 534 // Compute a sufficient number of bits that is always large enough but might 535 // be too large. This avoids the assertion in the constructor. This 536 // calculation doesn't work appropriately for the numbers 0-9, so just use 4 537 // bits in that case. 538 if (Radix == 10) 539 return (StrLen == 1 ? 4 : StrLen * 64 / 18) + IsNegative; 540 541 assert(Radix == 36); 542 return (StrLen == 1 ? 7 : StrLen * 16 / 3) + IsNegative; 543 } 544 545 unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) { 546 // Compute a sufficient number of bits that is always large enough but might 547 // be too large. 548 unsigned sufficient = getSufficientBitsNeeded(str, radix); 549 550 // For bases 2, 8, and 16, the sufficient number of bits is exact and we can 551 // return the value directly. For bases 10 and 36, we need to do extra work. 552 if (radix == 2 || radix == 8 || radix == 16) 553 return sufficient; 554 555 // This is grossly inefficient but accurate. We could probably do something 556 // with a computation of roughly slen*64/20 and then adjust by the value of 557 // the first few digits. But, I'm not sure how accurate that could be. 558 size_t slen = str.size(); 559 560 // Each computation below needs to know if it's negative. 561 StringRef::iterator p = str.begin(); 562 unsigned isNegative = *p == '-'; 563 if (*p == '-' || *p == '+') { 564 p++; 565 slen--; 566 assert(slen && "String is only a sign, needs a value."); 567 } 568 569 570 // Convert to the actual binary value. 571 APInt tmp(sufficient, StringRef(p, slen), radix); 572 573 // Compute how many bits are required. If the log is infinite, assume we need 574 // just bit. If the log is exact and value is negative, then the value is 575 // MinSignedValue with (log + 1) bits. 576 unsigned log = tmp.logBase2(); 577 if (log == (unsigned)-1) { 578 return isNegative + 1; 579 } else if (isNegative && tmp.isPowerOf2()) { 580 return isNegative + log; 581 } else { 582 return isNegative + log + 1; 583 } 584 } 585 586 hash_code llvm::hash_value(const APInt &Arg) { 587 if (Arg.isSingleWord()) 588 return hash_combine(Arg.BitWidth, Arg.U.VAL); 589 590 return hash_combine( 591 Arg.BitWidth, 592 hash_combine_range(Arg.U.pVal, Arg.U.pVal + Arg.getNumWords())); 593 } 594 595 unsigned DenseMapInfo<APInt, void>::getHashValue(const APInt &Key) { 596 return static_cast<unsigned>(hash_value(Key)); 597 } 598 599 bool APInt::isSplat(unsigned SplatSizeInBits) const { 600 assert(getBitWidth() % SplatSizeInBits == 0 && 601 "SplatSizeInBits must divide width!"); 602 // We can check that all parts of an integer are equal by making use of a 603 // little trick: rotate and check if it's still the same value. 604 return *this == rotl(SplatSizeInBits); 605 } 606 607 /// This function returns the high "numBits" bits of this APInt. 608 APInt APInt::getHiBits(unsigned numBits) const { 609 return this->lshr(BitWidth - numBits); 610 } 611 612 /// This function returns the low "numBits" bits of this APInt. 613 APInt APInt::getLoBits(unsigned numBits) const { 614 APInt Result(getLowBitsSet(BitWidth, numBits)); 615 Result &= *this; 616 return Result; 617 } 618 619 /// Return a value containing V broadcasted over NewLen bits. 620 APInt APInt::getSplat(unsigned NewLen, const APInt &V) { 621 assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!"); 622 623 APInt Val = V.zext(NewLen); 624 for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1) 625 Val |= Val << I; 626 627 return Val; 628 } 629 630 unsigned APInt::countLeadingZerosSlowCase() const { 631 unsigned Count = 0; 632 for (int i = getNumWords()-1; i >= 0; --i) { 633 uint64_t V = U.pVal[i]; 634 if (V == 0) 635 Count += APINT_BITS_PER_WORD; 636 else { 637 Count += llvm::countl_zero(V); 638 break; 639 } 640 } 641 // Adjust for unused bits in the most significant word (they are zero). 642 unsigned Mod = BitWidth % APINT_BITS_PER_WORD; 643 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0; 644 return Count; 645 } 646 647 unsigned APInt::countLeadingOnesSlowCase() const { 648 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD; 649 unsigned shift; 650 if (!highWordBits) { 651 highWordBits = APINT_BITS_PER_WORD; 652 shift = 0; 653 } else { 654 shift = APINT_BITS_PER_WORD - highWordBits; 655 } 656 int i = getNumWords() - 1; 657 unsigned Count = llvm::countl_one(U.pVal[i] << shift); 658 if (Count == highWordBits) { 659 for (i--; i >= 0; --i) { 660 if (U.pVal[i] == WORDTYPE_MAX) 661 Count += APINT_BITS_PER_WORD; 662 else { 663 Count += llvm::countl_one(U.pVal[i]); 664 break; 665 } 666 } 667 } 668 return Count; 669 } 670 671 unsigned APInt::countTrailingZerosSlowCase() const { 672 unsigned Count = 0; 673 unsigned i = 0; 674 for (; i < getNumWords() && U.pVal[i] == 0; ++i) 675 Count += APINT_BITS_PER_WORD; 676 if (i < getNumWords()) 677 Count += llvm::countr_zero(U.pVal[i]); 678 return std::min(Count, BitWidth); 679 } 680 681 unsigned APInt::countTrailingOnesSlowCase() const { 682 unsigned Count = 0; 683 unsigned i = 0; 684 for (; i < getNumWords() && U.pVal[i] == WORDTYPE_MAX; ++i) 685 Count += APINT_BITS_PER_WORD; 686 if (i < getNumWords()) 687 Count += llvm::countr_one(U.pVal[i]); 688 assert(Count <= BitWidth); 689 return Count; 690 } 691 692 unsigned APInt::countPopulationSlowCase() const { 693 unsigned Count = 0; 694 for (unsigned i = 0; i < getNumWords(); ++i) 695 Count += llvm::popcount(U.pVal[i]); 696 return Count; 697 } 698 699 bool APInt::intersectsSlowCase(const APInt &RHS) const { 700 for (unsigned i = 0, e = getNumWords(); i != e; ++i) 701 if ((U.pVal[i] & RHS.U.pVal[i]) != 0) 702 return true; 703 704 return false; 705 } 706 707 bool APInt::isSubsetOfSlowCase(const APInt &RHS) const { 708 for (unsigned i = 0, e = getNumWords(); i != e; ++i) 709 if ((U.pVal[i] & ~RHS.U.pVal[i]) != 0) 710 return false; 711 712 return true; 713 } 714 715 APInt APInt::byteSwap() const { 716 assert(BitWidth >= 16 && BitWidth % 8 == 0 && "Cannot byteswap!"); 717 if (BitWidth == 16) 718 return APInt(BitWidth, llvm::byteswap<uint16_t>(U.VAL)); 719 if (BitWidth == 32) 720 return APInt(BitWidth, llvm::byteswap<uint32_t>(U.VAL)); 721 if (BitWidth <= 64) { 722 uint64_t Tmp1 = llvm::byteswap<uint64_t>(U.VAL); 723 Tmp1 >>= (64 - BitWidth); 724 return APInt(BitWidth, Tmp1); 725 } 726 727 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0); 728 for (unsigned I = 0, N = getNumWords(); I != N; ++I) 729 Result.U.pVal[I] = llvm::byteswap<uint64_t>(U.pVal[N - I - 1]); 730 if (Result.BitWidth != BitWidth) { 731 Result.lshrInPlace(Result.BitWidth - BitWidth); 732 Result.BitWidth = BitWidth; 733 } 734 return Result; 735 } 736 737 APInt APInt::reverseBits() const { 738 switch (BitWidth) { 739 case 64: 740 return APInt(BitWidth, llvm::reverseBits<uint64_t>(U.VAL)); 741 case 32: 742 return APInt(BitWidth, llvm::reverseBits<uint32_t>(U.VAL)); 743 case 16: 744 return APInt(BitWidth, llvm::reverseBits<uint16_t>(U.VAL)); 745 case 8: 746 return APInt(BitWidth, llvm::reverseBits<uint8_t>(U.VAL)); 747 case 0: 748 return *this; 749 default: 750 break; 751 } 752 753 APInt Val(*this); 754 APInt Reversed(BitWidth, 0); 755 unsigned S = BitWidth; 756 757 for (; Val != 0; Val.lshrInPlace(1)) { 758 Reversed <<= 1; 759 Reversed |= Val[0]; 760 --S; 761 } 762 763 Reversed <<= S; 764 return Reversed; 765 } 766 767 APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) { 768 // Fast-path a common case. 769 if (A == B) return A; 770 771 // Corner cases: if either operand is zero, the other is the gcd. 772 if (!A) return B; 773 if (!B) return A; 774 775 // Count common powers of 2 and remove all other powers of 2. 776 unsigned Pow2; 777 { 778 unsigned Pow2_A = A.countr_zero(); 779 unsigned Pow2_B = B.countr_zero(); 780 if (Pow2_A > Pow2_B) { 781 A.lshrInPlace(Pow2_A - Pow2_B); 782 Pow2 = Pow2_B; 783 } else if (Pow2_B > Pow2_A) { 784 B.lshrInPlace(Pow2_B - Pow2_A); 785 Pow2 = Pow2_A; 786 } else { 787 Pow2 = Pow2_A; 788 } 789 } 790 791 // Both operands are odd multiples of 2^Pow_2: 792 // 793 // gcd(a, b) = gcd(|a - b| / 2^i, min(a, b)) 794 // 795 // This is a modified version of Stein's algorithm, taking advantage of 796 // efficient countTrailingZeros(). 797 while (A != B) { 798 if (A.ugt(B)) { 799 A -= B; 800 A.lshrInPlace(A.countr_zero() - Pow2); 801 } else { 802 B -= A; 803 B.lshrInPlace(B.countr_zero() - Pow2); 804 } 805 } 806 807 return A; 808 } 809 810 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) { 811 uint64_t I = bit_cast<uint64_t>(Double); 812 813 // Get the sign bit from the highest order bit 814 bool isNeg = I >> 63; 815 816 // Get the 11-bit exponent and adjust for the 1023 bit bias 817 int64_t exp = ((I >> 52) & 0x7ff) - 1023; 818 819 // If the exponent is negative, the value is < 0 so just return 0. 820 if (exp < 0) 821 return APInt(width, 0u); 822 823 // Extract the mantissa by clearing the top 12 bits (sign + exponent). 824 uint64_t mantissa = (I & (~0ULL >> 12)) | 1ULL << 52; 825 826 // If the exponent doesn't shift all bits out of the mantissa 827 if (exp < 52) 828 return isNeg ? -APInt(width, mantissa >> (52 - exp)) : 829 APInt(width, mantissa >> (52 - exp)); 830 831 // If the client didn't provide enough bits for us to shift the mantissa into 832 // then the result is undefined, just return 0 833 if (width <= exp - 52) 834 return APInt(width, 0); 835 836 // Otherwise, we have to shift the mantissa bits up to the right location 837 APInt Tmp(width, mantissa); 838 Tmp <<= (unsigned)exp - 52; 839 return isNeg ? -Tmp : Tmp; 840 } 841 842 /// This function converts this APInt to a double. 843 /// The layout for double is as following (IEEE Standard 754): 844 /// -------------------------------------- 845 /// | Sign Exponent Fraction Bias | 846 /// |-------------------------------------- | 847 /// | 1[63] 11[62-52] 52[51-00] 1023 | 848 /// -------------------------------------- 849 double APInt::roundToDouble(bool isSigned) const { 850 851 // Handle the simple case where the value is contained in one uint64_t. 852 // It is wrong to optimize getWord(0) to VAL; there might be more than one word. 853 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) { 854 if (isSigned) { 855 int64_t sext = SignExtend64(getWord(0), BitWidth); 856 return double(sext); 857 } else 858 return double(getWord(0)); 859 } 860 861 // Determine if the value is negative. 862 bool isNeg = isSigned ? (*this)[BitWidth-1] : false; 863 864 // Construct the absolute value if we're negative. 865 APInt Tmp(isNeg ? -(*this) : (*this)); 866 867 // Figure out how many bits we're using. 868 unsigned n = Tmp.getActiveBits(); 869 870 // The exponent (without bias normalization) is just the number of bits 871 // we are using. Note that the sign bit is gone since we constructed the 872 // absolute value. 873 uint64_t exp = n; 874 875 // Return infinity for exponent overflow 876 if (exp > 1023) { 877 if (!isSigned || !isNeg) 878 return std::numeric_limits<double>::infinity(); 879 else 880 return -std::numeric_limits<double>::infinity(); 881 } 882 exp += 1023; // Increment for 1023 bias 883 884 // Number of bits in mantissa is 52. To obtain the mantissa value, we must 885 // extract the high 52 bits from the correct words in pVal. 886 uint64_t mantissa; 887 unsigned hiWord = whichWord(n-1); 888 if (hiWord == 0) { 889 mantissa = Tmp.U.pVal[0]; 890 if (n > 52) 891 mantissa >>= n - 52; // shift down, we want the top 52 bits. 892 } else { 893 assert(hiWord > 0 && "huh?"); 894 uint64_t hibits = Tmp.U.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD); 895 uint64_t lobits = Tmp.U.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD); 896 mantissa = hibits | lobits; 897 } 898 899 // The leading bit of mantissa is implicit, so get rid of it. 900 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0; 901 uint64_t I = sign | (exp << 52) | mantissa; 902 return bit_cast<double>(I); 903 } 904 905 // Truncate to new width. 906 APInt APInt::trunc(unsigned width) const { 907 assert(width <= BitWidth && "Invalid APInt Truncate request"); 908 909 if (width <= APINT_BITS_PER_WORD) 910 return APInt(width, getRawData()[0]); 911 912 if (width == BitWidth) 913 return *this; 914 915 APInt Result(getMemory(getNumWords(width)), width); 916 917 // Copy full words. 918 unsigned i; 919 for (i = 0; i != width / APINT_BITS_PER_WORD; i++) 920 Result.U.pVal[i] = U.pVal[i]; 921 922 // Truncate and copy any partial word. 923 unsigned bits = (0 - width) % APINT_BITS_PER_WORD; 924 if (bits != 0) 925 Result.U.pVal[i] = U.pVal[i] << bits >> bits; 926 927 return Result; 928 } 929 930 // Truncate to new width with unsigned saturation. 931 APInt APInt::truncUSat(unsigned width) const { 932 assert(width <= BitWidth && "Invalid APInt Truncate request"); 933 934 // Can we just losslessly truncate it? 935 if (isIntN(width)) 936 return trunc(width); 937 // If not, then just return the new limit. 938 return APInt::getMaxValue(width); 939 } 940 941 // Truncate to new width with signed saturation. 942 APInt APInt::truncSSat(unsigned width) const { 943 assert(width <= BitWidth && "Invalid APInt Truncate request"); 944 945 // Can we just losslessly truncate it? 946 if (isSignedIntN(width)) 947 return trunc(width); 948 // If not, then just return the new limits. 949 return isNegative() ? APInt::getSignedMinValue(width) 950 : APInt::getSignedMaxValue(width); 951 } 952 953 // Sign extend to a new width. 954 APInt APInt::sext(unsigned Width) const { 955 assert(Width >= BitWidth && "Invalid APInt SignExtend request"); 956 957 if (Width <= APINT_BITS_PER_WORD) 958 return APInt(Width, SignExtend64(U.VAL, BitWidth)); 959 960 if (Width == BitWidth) 961 return *this; 962 963 APInt Result(getMemory(getNumWords(Width)), Width); 964 965 // Copy words. 966 std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE); 967 968 // Sign extend the last word since there may be unused bits in the input. 969 Result.U.pVal[getNumWords() - 1] = 970 SignExtend64(Result.U.pVal[getNumWords() - 1], 971 ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1); 972 973 // Fill with sign bits. 974 std::memset(Result.U.pVal + getNumWords(), isNegative() ? -1 : 0, 975 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE); 976 Result.clearUnusedBits(); 977 return Result; 978 } 979 980 // Zero extend to a new width. 981 APInt APInt::zext(unsigned width) const { 982 assert(width >= BitWidth && "Invalid APInt ZeroExtend request"); 983 984 if (width <= APINT_BITS_PER_WORD) 985 return APInt(width, U.VAL); 986 987 if (width == BitWidth) 988 return *this; 989 990 APInt Result(getMemory(getNumWords(width)), width); 991 992 // Copy words. 993 std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE); 994 995 // Zero remaining words. 996 std::memset(Result.U.pVal + getNumWords(), 0, 997 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE); 998 999 return Result; 1000 } 1001 1002 APInt APInt::zextOrTrunc(unsigned width) const { 1003 if (BitWidth < width) 1004 return zext(width); 1005 if (BitWidth > width) 1006 return trunc(width); 1007 return *this; 1008 } 1009 1010 APInt APInt::sextOrTrunc(unsigned width) const { 1011 if (BitWidth < width) 1012 return sext(width); 1013 if (BitWidth > width) 1014 return trunc(width); 1015 return *this; 1016 } 1017 1018 /// Arithmetic right-shift this APInt by shiftAmt. 1019 /// Arithmetic right-shift function. 1020 void APInt::ashrInPlace(const APInt &shiftAmt) { 1021 ashrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth)); 1022 } 1023 1024 /// Arithmetic right-shift this APInt by shiftAmt. 1025 /// Arithmetic right-shift function. 1026 void APInt::ashrSlowCase(unsigned ShiftAmt) { 1027 // Don't bother performing a no-op shift. 1028 if (!ShiftAmt) 1029 return; 1030 1031 // Save the original sign bit for later. 1032 bool Negative = isNegative(); 1033 1034 // WordShift is the inter-part shift; BitShift is intra-part shift. 1035 unsigned WordShift = ShiftAmt / APINT_BITS_PER_WORD; 1036 unsigned BitShift = ShiftAmt % APINT_BITS_PER_WORD; 1037 1038 unsigned WordsToMove = getNumWords() - WordShift; 1039 if (WordsToMove != 0) { 1040 // Sign extend the last word to fill in the unused bits. 1041 U.pVal[getNumWords() - 1] = SignExtend64( 1042 U.pVal[getNumWords() - 1], ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1); 1043 1044 // Fastpath for moving by whole words. 1045 if (BitShift == 0) { 1046 std::memmove(U.pVal, U.pVal + WordShift, WordsToMove * APINT_WORD_SIZE); 1047 } else { 1048 // Move the words containing significant bits. 1049 for (unsigned i = 0; i != WordsToMove - 1; ++i) 1050 U.pVal[i] = (U.pVal[i + WordShift] >> BitShift) | 1051 (U.pVal[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift)); 1052 1053 // Handle the last word which has no high bits to copy. 1054 U.pVal[WordsToMove - 1] = U.pVal[WordShift + WordsToMove - 1] >> BitShift; 1055 // Sign extend one more time. 1056 U.pVal[WordsToMove - 1] = 1057 SignExtend64(U.pVal[WordsToMove - 1], APINT_BITS_PER_WORD - BitShift); 1058 } 1059 } 1060 1061 // Fill in the remainder based on the original sign. 1062 std::memset(U.pVal + WordsToMove, Negative ? -1 : 0, 1063 WordShift * APINT_WORD_SIZE); 1064 clearUnusedBits(); 1065 } 1066 1067 /// Logical right-shift this APInt by shiftAmt. 1068 /// Logical right-shift function. 1069 void APInt::lshrInPlace(const APInt &shiftAmt) { 1070 lshrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth)); 1071 } 1072 1073 /// Logical right-shift this APInt by shiftAmt. 1074 /// Logical right-shift function. 1075 void APInt::lshrSlowCase(unsigned ShiftAmt) { 1076 tcShiftRight(U.pVal, getNumWords(), ShiftAmt); 1077 } 1078 1079 /// Left-shift this APInt by shiftAmt. 1080 /// Left-shift function. 1081 APInt &APInt::operator<<=(const APInt &shiftAmt) { 1082 // It's undefined behavior in C to shift by BitWidth or greater. 1083 *this <<= (unsigned)shiftAmt.getLimitedValue(BitWidth); 1084 return *this; 1085 } 1086 1087 void APInt::shlSlowCase(unsigned ShiftAmt) { 1088 tcShiftLeft(U.pVal, getNumWords(), ShiftAmt); 1089 clearUnusedBits(); 1090 } 1091 1092 // Calculate the rotate amount modulo the bit width. 1093 static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) { 1094 if (LLVM_UNLIKELY(BitWidth == 0)) 1095 return 0; 1096 unsigned rotBitWidth = rotateAmt.getBitWidth(); 1097 APInt rot = rotateAmt; 1098 if (rotBitWidth < BitWidth) { 1099 // Extend the rotate APInt, so that the urem doesn't divide by 0. 1100 // e.g. APInt(1, 32) would give APInt(1, 0). 1101 rot = rotateAmt.zext(BitWidth); 1102 } 1103 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth)); 1104 return rot.getLimitedValue(BitWidth); 1105 } 1106 1107 APInt APInt::rotl(const APInt &rotateAmt) const { 1108 return rotl(rotateModulo(BitWidth, rotateAmt)); 1109 } 1110 1111 APInt APInt::rotl(unsigned rotateAmt) const { 1112 if (LLVM_UNLIKELY(BitWidth == 0)) 1113 return *this; 1114 rotateAmt %= BitWidth; 1115 if (rotateAmt == 0) 1116 return *this; 1117 return shl(rotateAmt) | lshr(BitWidth - rotateAmt); 1118 } 1119 1120 APInt APInt::rotr(const APInt &rotateAmt) const { 1121 return rotr(rotateModulo(BitWidth, rotateAmt)); 1122 } 1123 1124 APInt APInt::rotr(unsigned rotateAmt) const { 1125 if (BitWidth == 0) 1126 return *this; 1127 rotateAmt %= BitWidth; 1128 if (rotateAmt == 0) 1129 return *this; 1130 return lshr(rotateAmt) | shl(BitWidth - rotateAmt); 1131 } 1132 1133 /// \returns the nearest log base 2 of this APInt. Ties round up. 1134 /// 1135 /// NOTE: When we have a BitWidth of 1, we define: 1136 /// 1137 /// log2(0) = UINT32_MAX 1138 /// log2(1) = 0 1139 /// 1140 /// to get around any mathematical concerns resulting from 1141 /// referencing 2 in a space where 2 does no exist. 1142 unsigned APInt::nearestLogBase2() const { 1143 // Special case when we have a bitwidth of 1. If VAL is 1, then we 1144 // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to 1145 // UINT32_MAX. 1146 if (BitWidth == 1) 1147 return U.VAL - 1; 1148 1149 // Handle the zero case. 1150 if (isZero()) 1151 return UINT32_MAX; 1152 1153 // The non-zero case is handled by computing: 1154 // 1155 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1]. 1156 // 1157 // where x[i] is referring to the value of the ith bit of x. 1158 unsigned lg = logBase2(); 1159 return lg + unsigned((*this)[lg - 1]); 1160 } 1161 1162 // Square Root - this method computes and returns the square root of "this". 1163 // Three mechanisms are used for computation. For small values (<= 5 bits), 1164 // a table lookup is done. This gets some performance for common cases. For 1165 // values using less than 52 bits, the value is converted to double and then 1166 // the libc sqrt function is called. The result is rounded and then converted 1167 // back to a uint64_t which is then used to construct the result. Finally, 1168 // the Babylonian method for computing square roots is used. 1169 APInt APInt::sqrt() const { 1170 1171 // Determine the magnitude of the value. 1172 unsigned magnitude = getActiveBits(); 1173 1174 // Use a fast table for some small values. This also gets rid of some 1175 // rounding errors in libc sqrt for small values. 1176 if (magnitude <= 5) { 1177 static const uint8_t results[32] = { 1178 /* 0 */ 0, 1179 /* 1- 2 */ 1, 1, 1180 /* 3- 6 */ 2, 2, 2, 2, 1181 /* 7-12 */ 3, 3, 3, 3, 3, 3, 1182 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4, 1183 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1184 /* 31 */ 6 1185 }; 1186 return APInt(BitWidth, results[ (isSingleWord() ? U.VAL : U.pVal[0]) ]); 1187 } 1188 1189 // If the magnitude of the value fits in less than 52 bits (the precision of 1190 // an IEEE double precision floating point value), then we can use the 1191 // libc sqrt function which will probably use a hardware sqrt computation. 1192 // This should be faster than the algorithm below. 1193 if (magnitude < 52) { 1194 return APInt(BitWidth, 1195 uint64_t(::round(::sqrt(double(isSingleWord() ? U.VAL 1196 : U.pVal[0]))))); 1197 } 1198 1199 // Okay, all the short cuts are exhausted. We must compute it. The following 1200 // is a classical Babylonian method for computing the square root. This code 1201 // was adapted to APInt from a wikipedia article on such computations. 1202 // See http://www.wikipedia.org/ and go to the page named 1203 // Calculate_an_integer_square_root. 1204 unsigned nbits = BitWidth, i = 4; 1205 APInt testy(BitWidth, 16); 1206 APInt x_old(BitWidth, 1); 1207 APInt x_new(BitWidth, 0); 1208 APInt two(BitWidth, 2); 1209 1210 // Select a good starting value using binary logarithms. 1211 for (;; i += 2, testy = testy.shl(2)) 1212 if (i >= nbits || this->ule(testy)) { 1213 x_old = x_old.shl(i / 2); 1214 break; 1215 } 1216 1217 // Use the Babylonian method to arrive at the integer square root: 1218 for (;;) { 1219 x_new = (this->udiv(x_old) + x_old).udiv(two); 1220 if (x_old.ule(x_new)) 1221 break; 1222 x_old = x_new; 1223 } 1224 1225 // Make sure we return the closest approximation 1226 // NOTE: The rounding calculation below is correct. It will produce an 1227 // off-by-one discrepancy with results from pari/gp. That discrepancy has been 1228 // determined to be a rounding issue with pari/gp as it begins to use a 1229 // floating point representation after 192 bits. There are no discrepancies 1230 // between this algorithm and pari/gp for bit widths < 192 bits. 1231 APInt square(x_old * x_old); 1232 APInt nextSquare((x_old + 1) * (x_old +1)); 1233 if (this->ult(square)) 1234 return x_old; 1235 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation"); 1236 APInt midpoint((nextSquare - square).udiv(two)); 1237 APInt offset(*this - square); 1238 if (offset.ult(midpoint)) 1239 return x_old; 1240 return x_old + 1; 1241 } 1242 1243 /// Computes the multiplicative inverse of this APInt for a given modulo. The 1244 /// iterative extended Euclidean algorithm is used to solve for this value, 1245 /// however we simplify it to speed up calculating only the inverse, and take 1246 /// advantage of div+rem calculations. We also use some tricks to avoid copying 1247 /// (potentially large) APInts around. 1248 /// WARNING: a value of '0' may be returned, 1249 /// signifying that no multiplicative inverse exists! 1250 APInt APInt::multiplicativeInverse(const APInt& modulo) const { 1251 assert(ult(modulo) && "This APInt must be smaller than the modulo"); 1252 1253 // Using the properties listed at the following web page (accessed 06/21/08): 1254 // http://www.numbertheory.org/php/euclid.html 1255 // (especially the properties numbered 3, 4 and 9) it can be proved that 1256 // BitWidth bits suffice for all the computations in the algorithm implemented 1257 // below. More precisely, this number of bits suffice if the multiplicative 1258 // inverse exists, but may not suffice for the general extended Euclidean 1259 // algorithm. 1260 1261 APInt r[2] = { modulo, *this }; 1262 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) }; 1263 APInt q(BitWidth, 0); 1264 1265 unsigned i; 1266 for (i = 0; r[i^1] != 0; i ^= 1) { 1267 // An overview of the math without the confusing bit-flipping: 1268 // q = r[i-2] / r[i-1] 1269 // r[i] = r[i-2] % r[i-1] 1270 // t[i] = t[i-2] - t[i-1] * q 1271 udivrem(r[i], r[i^1], q, r[i]); 1272 t[i] -= t[i^1] * q; 1273 } 1274 1275 // If this APInt and the modulo are not coprime, there is no multiplicative 1276 // inverse, so return 0. We check this by looking at the next-to-last 1277 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean 1278 // algorithm. 1279 if (r[i] != 1) 1280 return APInt(BitWidth, 0); 1281 1282 // The next-to-last t is the multiplicative inverse. However, we are 1283 // interested in a positive inverse. Calculate a positive one from a negative 1284 // one if necessary. A simple addition of the modulo suffices because 1285 // abs(t[i]) is known to be less than *this/2 (see the link above). 1286 if (t[i].isNegative()) 1287 t[i] += modulo; 1288 1289 return std::move(t[i]); 1290 } 1291 1292 /// \returns the multiplicative inverse of an odd APInt modulo 2^BitWidth. 1293 APInt APInt::multiplicativeInverse() const { 1294 assert((*this)[0] && 1295 "multiplicative inverse is only defined for odd numbers!"); 1296 1297 // Use Newton's method. 1298 APInt Factor = *this; 1299 APInt T; 1300 while (!(T = *this * Factor).isOne()) 1301 Factor *= 2 - T; 1302 return Factor; 1303 } 1304 1305 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers) 1306 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The 1307 /// variables here have the same names as in the algorithm. Comments explain 1308 /// the algorithm and any deviation from it. 1309 static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r, 1310 unsigned m, unsigned n) { 1311 assert(u && "Must provide dividend"); 1312 assert(v && "Must provide divisor"); 1313 assert(q && "Must provide quotient"); 1314 assert(u != v && u != q && v != q && "Must use different memory"); 1315 assert(n>1 && "n must be > 1"); 1316 1317 // b denotes the base of the number system. In our case b is 2^32. 1318 const uint64_t b = uint64_t(1) << 32; 1319 1320 // The DEBUG macros here tend to be spam in the debug output if you're not 1321 // debugging this code. Disable them unless KNUTH_DEBUG is defined. 1322 #ifdef KNUTH_DEBUG 1323 #define DEBUG_KNUTH(X) LLVM_DEBUG(X) 1324 #else 1325 #define DEBUG_KNUTH(X) do {} while(false) 1326 #endif 1327 1328 DEBUG_KNUTH(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n'); 1329 DEBUG_KNUTH(dbgs() << "KnuthDiv: original:"); 1330 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]); 1331 DEBUG_KNUTH(dbgs() << " by"); 1332 DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]); 1333 DEBUG_KNUTH(dbgs() << '\n'); 1334 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of 1335 // u and v by d. Note that we have taken Knuth's advice here to use a power 1336 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of 1337 // 2 allows us to shift instead of multiply and it is easy to determine the 1338 // shift amount from the leading zeros. We are basically normalizing the u 1339 // and v so that its high bits are shifted to the top of v's range without 1340 // overflow. Note that this can require an extra word in u so that u must 1341 // be of length m+n+1. 1342 unsigned shift = llvm::countl_zero(v[n - 1]); 1343 uint32_t v_carry = 0; 1344 uint32_t u_carry = 0; 1345 if (shift) { 1346 for (unsigned i = 0; i < m+n; ++i) { 1347 uint32_t u_tmp = u[i] >> (32 - shift); 1348 u[i] = (u[i] << shift) | u_carry; 1349 u_carry = u_tmp; 1350 } 1351 for (unsigned i = 0; i < n; ++i) { 1352 uint32_t v_tmp = v[i] >> (32 - shift); 1353 v[i] = (v[i] << shift) | v_carry; 1354 v_carry = v_tmp; 1355 } 1356 } 1357 u[m+n] = u_carry; 1358 1359 DEBUG_KNUTH(dbgs() << "KnuthDiv: normal:"); 1360 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]); 1361 DEBUG_KNUTH(dbgs() << " by"); 1362 DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]); 1363 DEBUG_KNUTH(dbgs() << '\n'); 1364 1365 // D2. [Initialize j.] Set j to m. This is the loop counter over the places. 1366 int j = m; 1367 do { 1368 DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient digit #" << j << '\n'); 1369 // D3. [Calculate q'.]. 1370 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q') 1371 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r') 1372 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease 1373 // qp by 1, increase rp by v[n-1], and repeat this test if rp < b. The test 1374 // on v[n-2] determines at high speed most of the cases in which the trial 1375 // value qp is one too large, and it eliminates all cases where qp is two 1376 // too large. 1377 uint64_t dividend = Make_64(u[j+n], u[j+n-1]); 1378 DEBUG_KNUTH(dbgs() << "KnuthDiv: dividend == " << dividend << '\n'); 1379 uint64_t qp = dividend / v[n-1]; 1380 uint64_t rp = dividend % v[n-1]; 1381 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) { 1382 qp--; 1383 rp += v[n-1]; 1384 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2])) 1385 qp--; 1386 } 1387 DEBUG_KNUTH(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n'); 1388 1389 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with 1390 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation 1391 // consists of a simple multiplication by a one-place number, combined with 1392 // a subtraction. 1393 // The digits (u[j+n]...u[j]) should be kept positive; if the result of 1394 // this step is actually negative, (u[j+n]...u[j]) should be left as the 1395 // true value plus b**(n+1), namely as the b's complement of 1396 // the true value, and a "borrow" to the left should be remembered. 1397 int64_t borrow = 0; 1398 for (unsigned i = 0; i < n; ++i) { 1399 uint64_t p = uint64_t(qp) * uint64_t(v[i]); 1400 int64_t subres = int64_t(u[j+i]) - borrow - Lo_32(p); 1401 u[j+i] = Lo_32(subres); 1402 borrow = Hi_32(p) - Hi_32(subres); 1403 DEBUG_KNUTH(dbgs() << "KnuthDiv: u[j+i] = " << u[j + i] 1404 << ", borrow = " << borrow << '\n'); 1405 } 1406 bool isNeg = u[j+n] < borrow; 1407 u[j+n] -= Lo_32(borrow); 1408 1409 DEBUG_KNUTH(dbgs() << "KnuthDiv: after subtraction:"); 1410 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]); 1411 DEBUG_KNUTH(dbgs() << '\n'); 1412 1413 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was 1414 // negative, go to step D6; otherwise go on to step D7. 1415 q[j] = Lo_32(qp); 1416 if (isNeg) { 1417 // D6. [Add back]. The probability that this step is necessary is very 1418 // small, on the order of only 2/b. Make sure that test data accounts for 1419 // this possibility. Decrease q[j] by 1 1420 q[j]--; 1421 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]). 1422 // A carry will occur to the left of u[j+n], and it should be ignored 1423 // since it cancels with the borrow that occurred in D4. 1424 bool carry = false; 1425 for (unsigned i = 0; i < n; i++) { 1426 uint32_t limit = std::min(u[j+i],v[i]); 1427 u[j+i] += v[i] + carry; 1428 carry = u[j+i] < limit || (carry && u[j+i] == limit); 1429 } 1430 u[j+n] += carry; 1431 } 1432 DEBUG_KNUTH(dbgs() << "KnuthDiv: after correction:"); 1433 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]); 1434 DEBUG_KNUTH(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n'); 1435 1436 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3. 1437 } while (--j >= 0); 1438 1439 DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient:"); 1440 DEBUG_KNUTH(for (int i = m; i >= 0; i--) dbgs() << " " << q[i]); 1441 DEBUG_KNUTH(dbgs() << '\n'); 1442 1443 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired 1444 // remainder may be obtained by dividing u[...] by d. If r is non-null we 1445 // compute the remainder (urem uses this). 1446 if (r) { 1447 // The value d is expressed by the "shift" value above since we avoided 1448 // multiplication by d by using a shift left. So, all we have to do is 1449 // shift right here. 1450 if (shift) { 1451 uint32_t carry = 0; 1452 DEBUG_KNUTH(dbgs() << "KnuthDiv: remainder:"); 1453 for (int i = n-1; i >= 0; i--) { 1454 r[i] = (u[i] >> shift) | carry; 1455 carry = u[i] << (32 - shift); 1456 DEBUG_KNUTH(dbgs() << " " << r[i]); 1457 } 1458 } else { 1459 for (int i = n-1; i >= 0; i--) { 1460 r[i] = u[i]; 1461 DEBUG_KNUTH(dbgs() << " " << r[i]); 1462 } 1463 } 1464 DEBUG_KNUTH(dbgs() << '\n'); 1465 } 1466 DEBUG_KNUTH(dbgs() << '\n'); 1467 } 1468 1469 void APInt::divide(const WordType *LHS, unsigned lhsWords, const WordType *RHS, 1470 unsigned rhsWords, WordType *Quotient, WordType *Remainder) { 1471 assert(lhsWords >= rhsWords && "Fractional result"); 1472 1473 // First, compose the values into an array of 32-bit words instead of 1474 // 64-bit words. This is a necessity of both the "short division" algorithm 1475 // and the Knuth "classical algorithm" which requires there to be native 1476 // operations for +, -, and * on an m bit value with an m*2 bit result. We 1477 // can't use 64-bit operands here because we don't have native results of 1478 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't 1479 // work on large-endian machines. 1480 unsigned n = rhsWords * 2; 1481 unsigned m = (lhsWords * 2) - n; 1482 1483 // Allocate space for the temporary values we need either on the stack, if 1484 // it will fit, or on the heap if it won't. 1485 uint32_t SPACE[128]; 1486 uint32_t *U = nullptr; 1487 uint32_t *V = nullptr; 1488 uint32_t *Q = nullptr; 1489 uint32_t *R = nullptr; 1490 if ((Remainder?4:3)*n+2*m+1 <= 128) { 1491 U = &SPACE[0]; 1492 V = &SPACE[m+n+1]; 1493 Q = &SPACE[(m+n+1) + n]; 1494 if (Remainder) 1495 R = &SPACE[(m+n+1) + n + (m+n)]; 1496 } else { 1497 U = new uint32_t[m + n + 1]; 1498 V = new uint32_t[n]; 1499 Q = new uint32_t[m+n]; 1500 if (Remainder) 1501 R = new uint32_t[n]; 1502 } 1503 1504 // Initialize the dividend 1505 memset(U, 0, (m+n+1)*sizeof(uint32_t)); 1506 for (unsigned i = 0; i < lhsWords; ++i) { 1507 uint64_t tmp = LHS[i]; 1508 U[i * 2] = Lo_32(tmp); 1509 U[i * 2 + 1] = Hi_32(tmp); 1510 } 1511 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm. 1512 1513 // Initialize the divisor 1514 memset(V, 0, (n)*sizeof(uint32_t)); 1515 for (unsigned i = 0; i < rhsWords; ++i) { 1516 uint64_t tmp = RHS[i]; 1517 V[i * 2] = Lo_32(tmp); 1518 V[i * 2 + 1] = Hi_32(tmp); 1519 } 1520 1521 // initialize the quotient and remainder 1522 memset(Q, 0, (m+n) * sizeof(uint32_t)); 1523 if (Remainder) 1524 memset(R, 0, n * sizeof(uint32_t)); 1525 1526 // Now, adjust m and n for the Knuth division. n is the number of words in 1527 // the divisor. m is the number of words by which the dividend exceeds the 1528 // divisor (i.e. m+n is the length of the dividend). These sizes must not 1529 // contain any zero words or the Knuth algorithm fails. 1530 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) { 1531 n--; 1532 m++; 1533 } 1534 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--) 1535 m--; 1536 1537 // If we're left with only a single word for the divisor, Knuth doesn't work 1538 // so we implement the short division algorithm here. This is much simpler 1539 // and faster because we are certain that we can divide a 64-bit quantity 1540 // by a 32-bit quantity at hardware speed and short division is simply a 1541 // series of such operations. This is just like doing short division but we 1542 // are using base 2^32 instead of base 10. 1543 assert(n != 0 && "Divide by zero?"); 1544 if (n == 1) { 1545 uint32_t divisor = V[0]; 1546 uint32_t remainder = 0; 1547 for (int i = m; i >= 0; i--) { 1548 uint64_t partial_dividend = Make_64(remainder, U[i]); 1549 if (partial_dividend == 0) { 1550 Q[i] = 0; 1551 remainder = 0; 1552 } else if (partial_dividend < divisor) { 1553 Q[i] = 0; 1554 remainder = Lo_32(partial_dividend); 1555 } else if (partial_dividend == divisor) { 1556 Q[i] = 1; 1557 remainder = 0; 1558 } else { 1559 Q[i] = Lo_32(partial_dividend / divisor); 1560 remainder = Lo_32(partial_dividend - (Q[i] * divisor)); 1561 } 1562 } 1563 if (R) 1564 R[0] = remainder; 1565 } else { 1566 // Now we're ready to invoke the Knuth classical divide algorithm. In this 1567 // case n > 1. 1568 KnuthDiv(U, V, Q, R, m, n); 1569 } 1570 1571 // If the caller wants the quotient 1572 if (Quotient) { 1573 for (unsigned i = 0; i < lhsWords; ++i) 1574 Quotient[i] = Make_64(Q[i*2+1], Q[i*2]); 1575 } 1576 1577 // If the caller wants the remainder 1578 if (Remainder) { 1579 for (unsigned i = 0; i < rhsWords; ++i) 1580 Remainder[i] = Make_64(R[i*2+1], R[i*2]); 1581 } 1582 1583 // Clean up the memory we allocated. 1584 if (U != &SPACE[0]) { 1585 delete [] U; 1586 delete [] V; 1587 delete [] Q; 1588 delete [] R; 1589 } 1590 } 1591 1592 APInt APInt::udiv(const APInt &RHS) const { 1593 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 1594 1595 // First, deal with the easy case 1596 if (isSingleWord()) { 1597 assert(RHS.U.VAL != 0 && "Divide by zero?"); 1598 return APInt(BitWidth, U.VAL / RHS.U.VAL); 1599 } 1600 1601 // Get some facts about the LHS and RHS number of bits and words 1602 unsigned lhsWords = getNumWords(getActiveBits()); 1603 unsigned rhsBits = RHS.getActiveBits(); 1604 unsigned rhsWords = getNumWords(rhsBits); 1605 assert(rhsWords && "Divided by zero???"); 1606 1607 // Deal with some degenerate cases 1608 if (!lhsWords) 1609 // 0 / X ===> 0 1610 return APInt(BitWidth, 0); 1611 if (rhsBits == 1) 1612 // X / 1 ===> X 1613 return *this; 1614 if (lhsWords < rhsWords || this->ult(RHS)) 1615 // X / Y ===> 0, iff X < Y 1616 return APInt(BitWidth, 0); 1617 if (*this == RHS) 1618 // X / X ===> 1 1619 return APInt(BitWidth, 1); 1620 if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1. 1621 // All high words are zero, just use native divide 1622 return APInt(BitWidth, this->U.pVal[0] / RHS.U.pVal[0]); 1623 1624 // We have to compute it the hard way. Invoke the Knuth divide algorithm. 1625 APInt Quotient(BitWidth, 0); // to hold result. 1626 divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal, nullptr); 1627 return Quotient; 1628 } 1629 1630 APInt APInt::udiv(uint64_t RHS) const { 1631 assert(RHS != 0 && "Divide by zero?"); 1632 1633 // First, deal with the easy case 1634 if (isSingleWord()) 1635 return APInt(BitWidth, U.VAL / RHS); 1636 1637 // Get some facts about the LHS words. 1638 unsigned lhsWords = getNumWords(getActiveBits()); 1639 1640 // Deal with some degenerate cases 1641 if (!lhsWords) 1642 // 0 / X ===> 0 1643 return APInt(BitWidth, 0); 1644 if (RHS == 1) 1645 // X / 1 ===> X 1646 return *this; 1647 if (this->ult(RHS)) 1648 // X / Y ===> 0, iff X < Y 1649 return APInt(BitWidth, 0); 1650 if (*this == RHS) 1651 // X / X ===> 1 1652 return APInt(BitWidth, 1); 1653 if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1. 1654 // All high words are zero, just use native divide 1655 return APInt(BitWidth, this->U.pVal[0] / RHS); 1656 1657 // We have to compute it the hard way. Invoke the Knuth divide algorithm. 1658 APInt Quotient(BitWidth, 0); // to hold result. 1659 divide(U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, nullptr); 1660 return Quotient; 1661 } 1662 1663 APInt APInt::sdiv(const APInt &RHS) const { 1664 if (isNegative()) { 1665 if (RHS.isNegative()) 1666 return (-(*this)).udiv(-RHS); 1667 return -((-(*this)).udiv(RHS)); 1668 } 1669 if (RHS.isNegative()) 1670 return -(this->udiv(-RHS)); 1671 return this->udiv(RHS); 1672 } 1673 1674 APInt APInt::sdiv(int64_t RHS) const { 1675 if (isNegative()) { 1676 if (RHS < 0) 1677 return (-(*this)).udiv(-RHS); 1678 return -((-(*this)).udiv(RHS)); 1679 } 1680 if (RHS < 0) 1681 return -(this->udiv(-RHS)); 1682 return this->udiv(RHS); 1683 } 1684 1685 APInt APInt::urem(const APInt &RHS) const { 1686 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 1687 if (isSingleWord()) { 1688 assert(RHS.U.VAL != 0 && "Remainder by zero?"); 1689 return APInt(BitWidth, U.VAL % RHS.U.VAL); 1690 } 1691 1692 // Get some facts about the LHS 1693 unsigned lhsWords = getNumWords(getActiveBits()); 1694 1695 // Get some facts about the RHS 1696 unsigned rhsBits = RHS.getActiveBits(); 1697 unsigned rhsWords = getNumWords(rhsBits); 1698 assert(rhsWords && "Performing remainder operation by zero ???"); 1699 1700 // Check the degenerate cases 1701 if (lhsWords == 0) 1702 // 0 % Y ===> 0 1703 return APInt(BitWidth, 0); 1704 if (rhsBits == 1) 1705 // X % 1 ===> 0 1706 return APInt(BitWidth, 0); 1707 if (lhsWords < rhsWords || this->ult(RHS)) 1708 // X % Y ===> X, iff X < Y 1709 return *this; 1710 if (*this == RHS) 1711 // X % X == 0; 1712 return APInt(BitWidth, 0); 1713 if (lhsWords == 1) 1714 // All high words are zero, just use native remainder 1715 return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]); 1716 1717 // We have to compute it the hard way. Invoke the Knuth divide algorithm. 1718 APInt Remainder(BitWidth, 0); 1719 divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, nullptr, Remainder.U.pVal); 1720 return Remainder; 1721 } 1722 1723 uint64_t APInt::urem(uint64_t RHS) const { 1724 assert(RHS != 0 && "Remainder by zero?"); 1725 1726 if (isSingleWord()) 1727 return U.VAL % RHS; 1728 1729 // Get some facts about the LHS 1730 unsigned lhsWords = getNumWords(getActiveBits()); 1731 1732 // Check the degenerate cases 1733 if (lhsWords == 0) 1734 // 0 % Y ===> 0 1735 return 0; 1736 if (RHS == 1) 1737 // X % 1 ===> 0 1738 return 0; 1739 if (this->ult(RHS)) 1740 // X % Y ===> X, iff X < Y 1741 return getZExtValue(); 1742 if (*this == RHS) 1743 // X % X == 0; 1744 return 0; 1745 if (lhsWords == 1) 1746 // All high words are zero, just use native remainder 1747 return U.pVal[0] % RHS; 1748 1749 // We have to compute it the hard way. Invoke the Knuth divide algorithm. 1750 uint64_t Remainder; 1751 divide(U.pVal, lhsWords, &RHS, 1, nullptr, &Remainder); 1752 return Remainder; 1753 } 1754 1755 APInt APInt::srem(const APInt &RHS) const { 1756 if (isNegative()) { 1757 if (RHS.isNegative()) 1758 return -((-(*this)).urem(-RHS)); 1759 return -((-(*this)).urem(RHS)); 1760 } 1761 if (RHS.isNegative()) 1762 return this->urem(-RHS); 1763 return this->urem(RHS); 1764 } 1765 1766 int64_t APInt::srem(int64_t RHS) const { 1767 if (isNegative()) { 1768 if (RHS < 0) 1769 return -((-(*this)).urem(-RHS)); 1770 return -((-(*this)).urem(RHS)); 1771 } 1772 if (RHS < 0) 1773 return this->urem(-RHS); 1774 return this->urem(RHS); 1775 } 1776 1777 void APInt::udivrem(const APInt &LHS, const APInt &RHS, 1778 APInt &Quotient, APInt &Remainder) { 1779 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same"); 1780 unsigned BitWidth = LHS.BitWidth; 1781 1782 // First, deal with the easy case 1783 if (LHS.isSingleWord()) { 1784 assert(RHS.U.VAL != 0 && "Divide by zero?"); 1785 uint64_t QuotVal = LHS.U.VAL / RHS.U.VAL; 1786 uint64_t RemVal = LHS.U.VAL % RHS.U.VAL; 1787 Quotient = APInt(BitWidth, QuotVal); 1788 Remainder = APInt(BitWidth, RemVal); 1789 return; 1790 } 1791 1792 // Get some size facts about the dividend and divisor 1793 unsigned lhsWords = getNumWords(LHS.getActiveBits()); 1794 unsigned rhsBits = RHS.getActiveBits(); 1795 unsigned rhsWords = getNumWords(rhsBits); 1796 assert(rhsWords && "Performing divrem operation by zero ???"); 1797 1798 // Check the degenerate cases 1799 if (lhsWords == 0) { 1800 Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0 1801 Remainder = APInt(BitWidth, 0); // 0 % Y ===> 0 1802 return; 1803 } 1804 1805 if (rhsBits == 1) { 1806 Quotient = LHS; // X / 1 ===> X 1807 Remainder = APInt(BitWidth, 0); // X % 1 ===> 0 1808 } 1809 1810 if (lhsWords < rhsWords || LHS.ult(RHS)) { 1811 Remainder = LHS; // X % Y ===> X, iff X < Y 1812 Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y 1813 return; 1814 } 1815 1816 if (LHS == RHS) { 1817 Quotient = APInt(BitWidth, 1); // X / X ===> 1 1818 Remainder = APInt(BitWidth, 0); // X % X ===> 0; 1819 return; 1820 } 1821 1822 // Make sure there is enough space to hold the results. 1823 // NOTE: This assumes that reallocate won't affect any bits if it doesn't 1824 // change the size. This is necessary if Quotient or Remainder is aliased 1825 // with LHS or RHS. 1826 Quotient.reallocate(BitWidth); 1827 Remainder.reallocate(BitWidth); 1828 1829 if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1. 1830 // There is only one word to consider so use the native versions. 1831 uint64_t lhsValue = LHS.U.pVal[0]; 1832 uint64_t rhsValue = RHS.U.pVal[0]; 1833 Quotient = lhsValue / rhsValue; 1834 Remainder = lhsValue % rhsValue; 1835 return; 1836 } 1837 1838 // Okay, lets do it the long way 1839 divide(LHS.U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal, 1840 Remainder.U.pVal); 1841 // Clear the rest of the Quotient and Remainder. 1842 std::memset(Quotient.U.pVal + lhsWords, 0, 1843 (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE); 1844 std::memset(Remainder.U.pVal + rhsWords, 0, 1845 (getNumWords(BitWidth) - rhsWords) * APINT_WORD_SIZE); 1846 } 1847 1848 void APInt::udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient, 1849 uint64_t &Remainder) { 1850 assert(RHS != 0 && "Divide by zero?"); 1851 unsigned BitWidth = LHS.BitWidth; 1852 1853 // First, deal with the easy case 1854 if (LHS.isSingleWord()) { 1855 uint64_t QuotVal = LHS.U.VAL / RHS; 1856 Remainder = LHS.U.VAL % RHS; 1857 Quotient = APInt(BitWidth, QuotVal); 1858 return; 1859 } 1860 1861 // Get some size facts about the dividend and divisor 1862 unsigned lhsWords = getNumWords(LHS.getActiveBits()); 1863 1864 // Check the degenerate cases 1865 if (lhsWords == 0) { 1866 Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0 1867 Remainder = 0; // 0 % Y ===> 0 1868 return; 1869 } 1870 1871 if (RHS == 1) { 1872 Quotient = LHS; // X / 1 ===> X 1873 Remainder = 0; // X % 1 ===> 0 1874 return; 1875 } 1876 1877 if (LHS.ult(RHS)) { 1878 Remainder = LHS.getZExtValue(); // X % Y ===> X, iff X < Y 1879 Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y 1880 return; 1881 } 1882 1883 if (LHS == RHS) { 1884 Quotient = APInt(BitWidth, 1); // X / X ===> 1 1885 Remainder = 0; // X % X ===> 0; 1886 return; 1887 } 1888 1889 // Make sure there is enough space to hold the results. 1890 // NOTE: This assumes that reallocate won't affect any bits if it doesn't 1891 // change the size. This is necessary if Quotient is aliased with LHS. 1892 Quotient.reallocate(BitWidth); 1893 1894 if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1. 1895 // There is only one word to consider so use the native versions. 1896 uint64_t lhsValue = LHS.U.pVal[0]; 1897 Quotient = lhsValue / RHS; 1898 Remainder = lhsValue % RHS; 1899 return; 1900 } 1901 1902 // Okay, lets do it the long way 1903 divide(LHS.U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, &Remainder); 1904 // Clear the rest of the Quotient. 1905 std::memset(Quotient.U.pVal + lhsWords, 0, 1906 (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE); 1907 } 1908 1909 void APInt::sdivrem(const APInt &LHS, const APInt &RHS, 1910 APInt &Quotient, APInt &Remainder) { 1911 if (LHS.isNegative()) { 1912 if (RHS.isNegative()) 1913 APInt::udivrem(-LHS, -RHS, Quotient, Remainder); 1914 else { 1915 APInt::udivrem(-LHS, RHS, Quotient, Remainder); 1916 Quotient.negate(); 1917 } 1918 Remainder.negate(); 1919 } else if (RHS.isNegative()) { 1920 APInt::udivrem(LHS, -RHS, Quotient, Remainder); 1921 Quotient.negate(); 1922 } else { 1923 APInt::udivrem(LHS, RHS, Quotient, Remainder); 1924 } 1925 } 1926 1927 void APInt::sdivrem(const APInt &LHS, int64_t RHS, 1928 APInt &Quotient, int64_t &Remainder) { 1929 uint64_t R = Remainder; 1930 if (LHS.isNegative()) { 1931 if (RHS < 0) 1932 APInt::udivrem(-LHS, -RHS, Quotient, R); 1933 else { 1934 APInt::udivrem(-LHS, RHS, Quotient, R); 1935 Quotient.negate(); 1936 } 1937 R = -R; 1938 } else if (RHS < 0) { 1939 APInt::udivrem(LHS, -RHS, Quotient, R); 1940 Quotient.negate(); 1941 } else { 1942 APInt::udivrem(LHS, RHS, Quotient, R); 1943 } 1944 Remainder = R; 1945 } 1946 1947 APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const { 1948 APInt Res = *this+RHS; 1949 Overflow = isNonNegative() == RHS.isNonNegative() && 1950 Res.isNonNegative() != isNonNegative(); 1951 return Res; 1952 } 1953 1954 APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const { 1955 APInt Res = *this+RHS; 1956 Overflow = Res.ult(RHS); 1957 return Res; 1958 } 1959 1960 APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const { 1961 APInt Res = *this - RHS; 1962 Overflow = isNonNegative() != RHS.isNonNegative() && 1963 Res.isNonNegative() != isNonNegative(); 1964 return Res; 1965 } 1966 1967 APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const { 1968 APInt Res = *this-RHS; 1969 Overflow = Res.ugt(*this); 1970 return Res; 1971 } 1972 1973 APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const { 1974 // MININT/-1 --> overflow. 1975 Overflow = isMinSignedValue() && RHS.isAllOnes(); 1976 return sdiv(RHS); 1977 } 1978 1979 APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const { 1980 APInt Res = *this * RHS; 1981 1982 if (RHS != 0) 1983 Overflow = Res.sdiv(RHS) != *this || 1984 (isMinSignedValue() && RHS.isAllOnes()); 1985 else 1986 Overflow = false; 1987 return Res; 1988 } 1989 1990 APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const { 1991 if (countl_zero() + RHS.countl_zero() + 2 <= BitWidth) { 1992 Overflow = true; 1993 return *this * RHS; 1994 } 1995 1996 APInt Res = lshr(1) * RHS; 1997 Overflow = Res.isNegative(); 1998 Res <<= 1; 1999 if ((*this)[0]) { 2000 Res += RHS; 2001 if (Res.ult(RHS)) 2002 Overflow = true; 2003 } 2004 return Res; 2005 } 2006 2007 APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const { 2008 return sshl_ov(ShAmt.getLimitedValue(getBitWidth()), Overflow); 2009 } 2010 2011 APInt APInt::sshl_ov(unsigned ShAmt, bool &Overflow) const { 2012 Overflow = ShAmt >= getBitWidth(); 2013 if (Overflow) 2014 return APInt(BitWidth, 0); 2015 2016 if (isNonNegative()) // Don't allow sign change. 2017 Overflow = ShAmt >= countl_zero(); 2018 else 2019 Overflow = ShAmt >= countl_one(); 2020 2021 return *this << ShAmt; 2022 } 2023 2024 APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const { 2025 return ushl_ov(ShAmt.getLimitedValue(getBitWidth()), Overflow); 2026 } 2027 2028 APInt APInt::ushl_ov(unsigned ShAmt, bool &Overflow) const { 2029 Overflow = ShAmt >= getBitWidth(); 2030 if (Overflow) 2031 return APInt(BitWidth, 0); 2032 2033 Overflow = ShAmt > countl_zero(); 2034 2035 return *this << ShAmt; 2036 } 2037 2038 APInt APInt::sfloordiv_ov(const APInt &RHS, bool &Overflow) const { 2039 APInt quotient = sdiv_ov(RHS, Overflow); 2040 if ((quotient * RHS != *this) && (isNegative() != RHS.isNegative())) 2041 return quotient - 1; 2042 return quotient; 2043 } 2044 2045 APInt APInt::sadd_sat(const APInt &RHS) const { 2046 bool Overflow; 2047 APInt Res = sadd_ov(RHS, Overflow); 2048 if (!Overflow) 2049 return Res; 2050 2051 return isNegative() ? APInt::getSignedMinValue(BitWidth) 2052 : APInt::getSignedMaxValue(BitWidth); 2053 } 2054 2055 APInt APInt::uadd_sat(const APInt &RHS) const { 2056 bool Overflow; 2057 APInt Res = uadd_ov(RHS, Overflow); 2058 if (!Overflow) 2059 return Res; 2060 2061 return APInt::getMaxValue(BitWidth); 2062 } 2063 2064 APInt APInt::ssub_sat(const APInt &RHS) const { 2065 bool Overflow; 2066 APInt Res = ssub_ov(RHS, Overflow); 2067 if (!Overflow) 2068 return Res; 2069 2070 return isNegative() ? APInt::getSignedMinValue(BitWidth) 2071 : APInt::getSignedMaxValue(BitWidth); 2072 } 2073 2074 APInt APInt::usub_sat(const APInt &RHS) const { 2075 bool Overflow; 2076 APInt Res = usub_ov(RHS, Overflow); 2077 if (!Overflow) 2078 return Res; 2079 2080 return APInt(BitWidth, 0); 2081 } 2082 2083 APInt APInt::smul_sat(const APInt &RHS) const { 2084 bool Overflow; 2085 APInt Res = smul_ov(RHS, Overflow); 2086 if (!Overflow) 2087 return Res; 2088 2089 // The result is negative if one and only one of inputs is negative. 2090 bool ResIsNegative = isNegative() ^ RHS.isNegative(); 2091 2092 return ResIsNegative ? APInt::getSignedMinValue(BitWidth) 2093 : APInt::getSignedMaxValue(BitWidth); 2094 } 2095 2096 APInt APInt::umul_sat(const APInt &RHS) const { 2097 bool Overflow; 2098 APInt Res = umul_ov(RHS, Overflow); 2099 if (!Overflow) 2100 return Res; 2101 2102 return APInt::getMaxValue(BitWidth); 2103 } 2104 2105 APInt APInt::sshl_sat(const APInt &RHS) const { 2106 return sshl_sat(RHS.getLimitedValue(getBitWidth())); 2107 } 2108 2109 APInt APInt::sshl_sat(unsigned RHS) const { 2110 bool Overflow; 2111 APInt Res = sshl_ov(RHS, Overflow); 2112 if (!Overflow) 2113 return Res; 2114 2115 return isNegative() ? APInt::getSignedMinValue(BitWidth) 2116 : APInt::getSignedMaxValue(BitWidth); 2117 } 2118 2119 APInt APInt::ushl_sat(const APInt &RHS) const { 2120 return ushl_sat(RHS.getLimitedValue(getBitWidth())); 2121 } 2122 2123 APInt APInt::ushl_sat(unsigned RHS) const { 2124 bool Overflow; 2125 APInt Res = ushl_ov(RHS, Overflow); 2126 if (!Overflow) 2127 return Res; 2128 2129 return APInt::getMaxValue(BitWidth); 2130 } 2131 2132 void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) { 2133 // Check our assumptions here 2134 assert(!str.empty() && "Invalid string length"); 2135 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 || 2136 radix == 36) && 2137 "Radix should be 2, 8, 10, 16, or 36!"); 2138 2139 StringRef::iterator p = str.begin(); 2140 size_t slen = str.size(); 2141 bool isNeg = *p == '-'; 2142 if (*p == '-' || *p == '+') { 2143 p++; 2144 slen--; 2145 assert(slen && "String is only a sign, needs a value."); 2146 } 2147 assert((slen <= numbits || radix != 2) && "Insufficient bit width"); 2148 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width"); 2149 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width"); 2150 assert((((slen-1)*64)/22 <= numbits || radix != 10) && 2151 "Insufficient bit width"); 2152 2153 // Allocate memory if needed 2154 if (isSingleWord()) 2155 U.VAL = 0; 2156 else 2157 U.pVal = getClearedMemory(getNumWords()); 2158 2159 // Figure out if we can shift instead of multiply 2160 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0); 2161 2162 // Enter digit traversal loop 2163 for (StringRef::iterator e = str.end(); p != e; ++p) { 2164 unsigned digit = getDigit(*p, radix); 2165 assert(digit < radix && "Invalid character in digit string"); 2166 2167 // Shift or multiply the value by the radix 2168 if (slen > 1) { 2169 if (shift) 2170 *this <<= shift; 2171 else 2172 *this *= radix; 2173 } 2174 2175 // Add in the digit we just interpreted 2176 *this += digit; 2177 } 2178 // If its negative, put it in two's complement form 2179 if (isNeg) 2180 this->negate(); 2181 } 2182 2183 void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed, 2184 bool formatAsCLiteral, bool UpperCase, 2185 bool InsertSeparators) const { 2186 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 || 2187 Radix == 36) && 2188 "Radix should be 2, 8, 10, 16, or 36!"); 2189 2190 const char *Prefix = ""; 2191 if (formatAsCLiteral) { 2192 switch (Radix) { 2193 case 2: 2194 // Binary literals are a non-standard extension added in gcc 4.3: 2195 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html 2196 Prefix = "0b"; 2197 break; 2198 case 8: 2199 Prefix = "0"; 2200 break; 2201 case 10: 2202 break; // No prefix 2203 case 16: 2204 Prefix = "0x"; 2205 break; 2206 default: 2207 llvm_unreachable("Invalid radix!"); 2208 } 2209 } 2210 2211 // Number of digits in a group between separators. 2212 unsigned Grouping = (Radix == 8 || Radix == 10) ? 3 : 4; 2213 2214 // First, check for a zero value and just short circuit the logic below. 2215 if (isZero()) { 2216 while (*Prefix) { 2217 Str.push_back(*Prefix); 2218 ++Prefix; 2219 }; 2220 Str.push_back('0'); 2221 return; 2222 } 2223 2224 static const char BothDigits[] = "0123456789abcdefghijklmnopqrstuvwxyz" 2225 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 2226 const char *Digits = BothDigits + (UpperCase ? 36 : 0); 2227 2228 if (isSingleWord()) { 2229 char Buffer[65]; 2230 char *BufPtr = std::end(Buffer); 2231 2232 uint64_t N; 2233 if (!Signed) { 2234 N = getZExtValue(); 2235 } else { 2236 int64_t I = getSExtValue(); 2237 if (I >= 0) { 2238 N = I; 2239 } else { 2240 Str.push_back('-'); 2241 N = -(uint64_t)I; 2242 } 2243 } 2244 2245 while (*Prefix) { 2246 Str.push_back(*Prefix); 2247 ++Prefix; 2248 }; 2249 2250 int Pos = 0; 2251 while (N) { 2252 if (InsertSeparators && Pos % Grouping == 0 && Pos > 0) 2253 *--BufPtr = '\''; 2254 *--BufPtr = Digits[N % Radix]; 2255 N /= Radix; 2256 Pos++; 2257 } 2258 Str.append(BufPtr, std::end(Buffer)); 2259 return; 2260 } 2261 2262 APInt Tmp(*this); 2263 2264 if (Signed && isNegative()) { 2265 // They want to print the signed version and it is a negative value 2266 // Flip the bits and add one to turn it into the equivalent positive 2267 // value and put a '-' in the result. 2268 Tmp.negate(); 2269 Str.push_back('-'); 2270 } 2271 2272 while (*Prefix) { 2273 Str.push_back(*Prefix); 2274 ++Prefix; 2275 }; 2276 2277 // We insert the digits backward, then reverse them to get the right order. 2278 unsigned StartDig = Str.size(); 2279 2280 // For the 2, 8 and 16 bit cases, we can just shift instead of divide 2281 // because the number of bits per digit (1, 3 and 4 respectively) divides 2282 // equally. We just shift until the value is zero. 2283 if (Radix == 2 || Radix == 8 || Radix == 16) { 2284 // Just shift tmp right for each digit width until it becomes zero 2285 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1)); 2286 unsigned MaskAmt = Radix - 1; 2287 2288 int Pos = 0; 2289 while (Tmp.getBoolValue()) { 2290 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt; 2291 if (InsertSeparators && Pos % Grouping == 0 && Pos > 0) 2292 Str.push_back('\''); 2293 2294 Str.push_back(Digits[Digit]); 2295 Tmp.lshrInPlace(ShiftAmt); 2296 Pos++; 2297 } 2298 } else { 2299 int Pos = 0; 2300 while (Tmp.getBoolValue()) { 2301 uint64_t Digit; 2302 udivrem(Tmp, Radix, Tmp, Digit); 2303 assert(Digit < Radix && "divide failed"); 2304 if (InsertSeparators && Pos % Grouping == 0 && Pos > 0) 2305 Str.push_back('\''); 2306 2307 Str.push_back(Digits[Digit]); 2308 Pos++; 2309 } 2310 } 2311 2312 // Reverse the digits before returning. 2313 std::reverse(Str.begin()+StartDig, Str.end()); 2314 } 2315 2316 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2317 LLVM_DUMP_METHOD void APInt::dump() const { 2318 SmallString<40> S, U; 2319 this->toStringUnsigned(U); 2320 this->toStringSigned(S); 2321 dbgs() << "APInt(" << BitWidth << "b, " 2322 << U << "u " << S << "s)\n"; 2323 } 2324 #endif 2325 2326 void APInt::print(raw_ostream &OS, bool isSigned) const { 2327 SmallString<40> S; 2328 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false); 2329 OS << S; 2330 } 2331 2332 // This implements a variety of operations on a representation of 2333 // arbitrary precision, two's-complement, bignum integer values. 2334 2335 // Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe 2336 // and unrestricting assumption. 2337 static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0, 2338 "Part width must be divisible by 2!"); 2339 2340 // Returns the integer part with the least significant BITS set. 2341 // BITS cannot be zero. 2342 static inline APInt::WordType lowBitMask(unsigned bits) { 2343 assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD); 2344 return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits); 2345 } 2346 2347 /// Returns the value of the lower half of PART. 2348 static inline APInt::WordType lowHalf(APInt::WordType part) { 2349 return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2); 2350 } 2351 2352 /// Returns the value of the upper half of PART. 2353 static inline APInt::WordType highHalf(APInt::WordType part) { 2354 return part >> (APInt::APINT_BITS_PER_WORD / 2); 2355 } 2356 2357 /// Sets the least significant part of a bignum to the input value, and zeroes 2358 /// out higher parts. 2359 void APInt::tcSet(WordType *dst, WordType part, unsigned parts) { 2360 assert(parts > 0); 2361 dst[0] = part; 2362 for (unsigned i = 1; i < parts; i++) 2363 dst[i] = 0; 2364 } 2365 2366 /// Assign one bignum to another. 2367 void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) { 2368 for (unsigned i = 0; i < parts; i++) 2369 dst[i] = src[i]; 2370 } 2371 2372 /// Returns true if a bignum is zero, false otherwise. 2373 bool APInt::tcIsZero(const WordType *src, unsigned parts) { 2374 for (unsigned i = 0; i < parts; i++) 2375 if (src[i]) 2376 return false; 2377 2378 return true; 2379 } 2380 2381 /// Extract the given bit of a bignum; returns 0 or 1. 2382 int APInt::tcExtractBit(const WordType *parts, unsigned bit) { 2383 return (parts[whichWord(bit)] & maskBit(bit)) != 0; 2384 } 2385 2386 /// Set the given bit of a bignum. 2387 void APInt::tcSetBit(WordType *parts, unsigned bit) { 2388 parts[whichWord(bit)] |= maskBit(bit); 2389 } 2390 2391 /// Clears the given bit of a bignum. 2392 void APInt::tcClearBit(WordType *parts, unsigned bit) { 2393 parts[whichWord(bit)] &= ~maskBit(bit); 2394 } 2395 2396 /// Returns the bit number of the least significant set bit of a number. If the 2397 /// input number has no bits set UINT_MAX is returned. 2398 unsigned APInt::tcLSB(const WordType *parts, unsigned n) { 2399 for (unsigned i = 0; i < n; i++) { 2400 if (parts[i] != 0) { 2401 unsigned lsb = llvm::countr_zero(parts[i]); 2402 return lsb + i * APINT_BITS_PER_WORD; 2403 } 2404 } 2405 2406 return UINT_MAX; 2407 } 2408 2409 /// Returns the bit number of the most significant set bit of a number. 2410 /// If the input number has no bits set UINT_MAX is returned. 2411 unsigned APInt::tcMSB(const WordType *parts, unsigned n) { 2412 do { 2413 --n; 2414 2415 if (parts[n] != 0) { 2416 static_assert(sizeof(parts[n]) <= sizeof(uint64_t)); 2417 unsigned msb = llvm::Log2_64(parts[n]); 2418 2419 return msb + n * APINT_BITS_PER_WORD; 2420 } 2421 } while (n); 2422 2423 return UINT_MAX; 2424 } 2425 2426 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to 2427 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least 2428 /// significant bit of DST. All high bits above srcBITS in DST are zero-filled. 2429 /// */ 2430 void 2431 APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src, 2432 unsigned srcBits, unsigned srcLSB) { 2433 unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD; 2434 assert(dstParts <= dstCount); 2435 2436 unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD; 2437 tcAssign(dst, src + firstSrcPart, dstParts); 2438 2439 unsigned shift = srcLSB % APINT_BITS_PER_WORD; 2440 tcShiftRight(dst, dstParts, shift); 2441 2442 // We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC 2443 // in DST. If this is less that srcBits, append the rest, else 2444 // clear the high bits. 2445 unsigned n = dstParts * APINT_BITS_PER_WORD - shift; 2446 if (n < srcBits) { 2447 WordType mask = lowBitMask (srcBits - n); 2448 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask) 2449 << n % APINT_BITS_PER_WORD); 2450 } else if (n > srcBits) { 2451 if (srcBits % APINT_BITS_PER_WORD) 2452 dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD); 2453 } 2454 2455 // Clear high parts. 2456 while (dstParts < dstCount) 2457 dst[dstParts++] = 0; 2458 } 2459 2460 //// DST += RHS + C where C is zero or one. Returns the carry flag. 2461 APInt::WordType APInt::tcAdd(WordType *dst, const WordType *rhs, 2462 WordType c, unsigned parts) { 2463 assert(c <= 1); 2464 2465 for (unsigned i = 0; i < parts; i++) { 2466 WordType l = dst[i]; 2467 if (c) { 2468 dst[i] += rhs[i] + 1; 2469 c = (dst[i] <= l); 2470 } else { 2471 dst[i] += rhs[i]; 2472 c = (dst[i] < l); 2473 } 2474 } 2475 2476 return c; 2477 } 2478 2479 /// This function adds a single "word" integer, src, to the multiple 2480 /// "word" integer array, dst[]. dst[] is modified to reflect the addition and 2481 /// 1 is returned if there is a carry out, otherwise 0 is returned. 2482 /// @returns the carry of the addition. 2483 APInt::WordType APInt::tcAddPart(WordType *dst, WordType src, 2484 unsigned parts) { 2485 for (unsigned i = 0; i < parts; ++i) { 2486 dst[i] += src; 2487 if (dst[i] >= src) 2488 return 0; // No need to carry so exit early. 2489 src = 1; // Carry one to next digit. 2490 } 2491 2492 return 1; 2493 } 2494 2495 /// DST -= RHS + C where C is zero or one. Returns the carry flag. 2496 APInt::WordType APInt::tcSubtract(WordType *dst, const WordType *rhs, 2497 WordType c, unsigned parts) { 2498 assert(c <= 1); 2499 2500 for (unsigned i = 0; i < parts; i++) { 2501 WordType l = dst[i]; 2502 if (c) { 2503 dst[i] -= rhs[i] + 1; 2504 c = (dst[i] >= l); 2505 } else { 2506 dst[i] -= rhs[i]; 2507 c = (dst[i] > l); 2508 } 2509 } 2510 2511 return c; 2512 } 2513 2514 /// This function subtracts a single "word" (64-bit word), src, from 2515 /// the multi-word integer array, dst[], propagating the borrowed 1 value until 2516 /// no further borrowing is needed or it runs out of "words" in dst. The result 2517 /// is 1 if "borrowing" exhausted the digits in dst, or 0 if dst was not 2518 /// exhausted. In other words, if src > dst then this function returns 1, 2519 /// otherwise 0. 2520 /// @returns the borrow out of the subtraction 2521 APInt::WordType APInt::tcSubtractPart(WordType *dst, WordType src, 2522 unsigned parts) { 2523 for (unsigned i = 0; i < parts; ++i) { 2524 WordType Dst = dst[i]; 2525 dst[i] -= src; 2526 if (src <= Dst) 2527 return 0; // No need to borrow so exit early. 2528 src = 1; // We have to "borrow 1" from next "word" 2529 } 2530 2531 return 1; 2532 } 2533 2534 /// Negate a bignum in-place. 2535 void APInt::tcNegate(WordType *dst, unsigned parts) { 2536 tcComplement(dst, parts); 2537 tcIncrement(dst, parts); 2538 } 2539 2540 /// DST += SRC * MULTIPLIER + CARRY if add is true 2541 /// DST = SRC * MULTIPLIER + CARRY if add is false 2542 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC 2543 /// they must start at the same point, i.e. DST == SRC. 2544 /// If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is 2545 /// returned. Otherwise DST is filled with the least significant 2546 /// DSTPARTS parts of the result, and if all of the omitted higher 2547 /// parts were zero return zero, otherwise overflow occurred and 2548 /// return one. 2549 int APInt::tcMultiplyPart(WordType *dst, const WordType *src, 2550 WordType multiplier, WordType carry, 2551 unsigned srcParts, unsigned dstParts, 2552 bool add) { 2553 // Otherwise our writes of DST kill our later reads of SRC. 2554 assert(dst <= src || dst >= src + srcParts); 2555 assert(dstParts <= srcParts + 1); 2556 2557 // N loops; minimum of dstParts and srcParts. 2558 unsigned n = std::min(dstParts, srcParts); 2559 2560 for (unsigned i = 0; i < n; i++) { 2561 // [LOW, HIGH] = MULTIPLIER * SRC[i] + DST[i] + CARRY. 2562 // This cannot overflow, because: 2563 // (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1) 2564 // which is less than n^2. 2565 WordType srcPart = src[i]; 2566 WordType low, mid, high; 2567 if (multiplier == 0 || srcPart == 0) { 2568 low = carry; 2569 high = 0; 2570 } else { 2571 low = lowHalf(srcPart) * lowHalf(multiplier); 2572 high = highHalf(srcPart) * highHalf(multiplier); 2573 2574 mid = lowHalf(srcPart) * highHalf(multiplier); 2575 high += highHalf(mid); 2576 mid <<= APINT_BITS_PER_WORD / 2; 2577 if (low + mid < low) 2578 high++; 2579 low += mid; 2580 2581 mid = highHalf(srcPart) * lowHalf(multiplier); 2582 high += highHalf(mid); 2583 mid <<= APINT_BITS_PER_WORD / 2; 2584 if (low + mid < low) 2585 high++; 2586 low += mid; 2587 2588 // Now add carry. 2589 if (low + carry < low) 2590 high++; 2591 low += carry; 2592 } 2593 2594 if (add) { 2595 // And now DST[i], and store the new low part there. 2596 if (low + dst[i] < low) 2597 high++; 2598 dst[i] += low; 2599 } else 2600 dst[i] = low; 2601 2602 carry = high; 2603 } 2604 2605 if (srcParts < dstParts) { 2606 // Full multiplication, there is no overflow. 2607 assert(srcParts + 1 == dstParts); 2608 dst[srcParts] = carry; 2609 return 0; 2610 } 2611 2612 // We overflowed if there is carry. 2613 if (carry) 2614 return 1; 2615 2616 // We would overflow if any significant unwritten parts would be 2617 // non-zero. This is true if any remaining src parts are non-zero 2618 // and the multiplier is non-zero. 2619 if (multiplier) 2620 for (unsigned i = dstParts; i < srcParts; i++) 2621 if (src[i]) 2622 return 1; 2623 2624 // We fitted in the narrow destination. 2625 return 0; 2626 } 2627 2628 /// DST = LHS * RHS, where DST has the same width as the operands and 2629 /// is filled with the least significant parts of the result. Returns 2630 /// one if overflow occurred, otherwise zero. DST must be disjoint 2631 /// from both operands. 2632 int APInt::tcMultiply(WordType *dst, const WordType *lhs, 2633 const WordType *rhs, unsigned parts) { 2634 assert(dst != lhs && dst != rhs); 2635 2636 int overflow = 0; 2637 tcSet(dst, 0, parts); 2638 2639 for (unsigned i = 0; i < parts; i++) 2640 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts, 2641 parts - i, true); 2642 2643 return overflow; 2644 } 2645 2646 /// DST = LHS * RHS, where DST has width the sum of the widths of the 2647 /// operands. No overflow occurs. DST must be disjoint from both operands. 2648 void APInt::tcFullMultiply(WordType *dst, const WordType *lhs, 2649 const WordType *rhs, unsigned lhsParts, 2650 unsigned rhsParts) { 2651 // Put the narrower number on the LHS for less loops below. 2652 if (lhsParts > rhsParts) 2653 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts); 2654 2655 assert(dst != lhs && dst != rhs); 2656 2657 tcSet(dst, 0, rhsParts); 2658 2659 for (unsigned i = 0; i < lhsParts; i++) 2660 tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, true); 2661 } 2662 2663 // If RHS is zero LHS and REMAINDER are left unchanged, return one. 2664 // Otherwise set LHS to LHS / RHS with the fractional part discarded, 2665 // set REMAINDER to the remainder, return zero. i.e. 2666 // 2667 // OLD_LHS = RHS * LHS + REMAINDER 2668 // 2669 // SCRATCH is a bignum of the same size as the operands and result for 2670 // use by the routine; its contents need not be initialized and are 2671 // destroyed. LHS, REMAINDER and SCRATCH must be distinct. 2672 int APInt::tcDivide(WordType *lhs, const WordType *rhs, 2673 WordType *remainder, WordType *srhs, 2674 unsigned parts) { 2675 assert(lhs != remainder && lhs != srhs && remainder != srhs); 2676 2677 unsigned shiftCount = tcMSB(rhs, parts) + 1; 2678 if (shiftCount == 0) 2679 return true; 2680 2681 shiftCount = parts * APINT_BITS_PER_WORD - shiftCount; 2682 unsigned n = shiftCount / APINT_BITS_PER_WORD; 2683 WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD); 2684 2685 tcAssign(srhs, rhs, parts); 2686 tcShiftLeft(srhs, parts, shiftCount); 2687 tcAssign(remainder, lhs, parts); 2688 tcSet(lhs, 0, parts); 2689 2690 // Loop, subtracting SRHS if REMAINDER is greater and adding that to the 2691 // total. 2692 for (;;) { 2693 int compare = tcCompare(remainder, srhs, parts); 2694 if (compare >= 0) { 2695 tcSubtract(remainder, srhs, 0, parts); 2696 lhs[n] |= mask; 2697 } 2698 2699 if (shiftCount == 0) 2700 break; 2701 shiftCount--; 2702 tcShiftRight(srhs, parts, 1); 2703 if ((mask >>= 1) == 0) { 2704 mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1); 2705 n--; 2706 } 2707 } 2708 2709 return false; 2710 } 2711 2712 /// Shift a bignum left Cound bits in-place. Shifted in bits are zero. There are 2713 /// no restrictions on Count. 2714 void APInt::tcShiftLeft(WordType *Dst, unsigned Words, unsigned Count) { 2715 // Don't bother performing a no-op shift. 2716 if (!Count) 2717 return; 2718 2719 // WordShift is the inter-part shift; BitShift is the intra-part shift. 2720 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words); 2721 unsigned BitShift = Count % APINT_BITS_PER_WORD; 2722 2723 // Fastpath for moving by whole words. 2724 if (BitShift == 0) { 2725 std::memmove(Dst + WordShift, Dst, (Words - WordShift) * APINT_WORD_SIZE); 2726 } else { 2727 while (Words-- > WordShift) { 2728 Dst[Words] = Dst[Words - WordShift] << BitShift; 2729 if (Words > WordShift) 2730 Dst[Words] |= 2731 Dst[Words - WordShift - 1] >> (APINT_BITS_PER_WORD - BitShift); 2732 } 2733 } 2734 2735 // Fill in the remainder with 0s. 2736 std::memset(Dst, 0, WordShift * APINT_WORD_SIZE); 2737 } 2738 2739 /// Shift a bignum right Count bits in-place. Shifted in bits are zero. There 2740 /// are no restrictions on Count. 2741 void APInt::tcShiftRight(WordType *Dst, unsigned Words, unsigned Count) { 2742 // Don't bother performing a no-op shift. 2743 if (!Count) 2744 return; 2745 2746 // WordShift is the inter-part shift; BitShift is the intra-part shift. 2747 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words); 2748 unsigned BitShift = Count % APINT_BITS_PER_WORD; 2749 2750 unsigned WordsToMove = Words - WordShift; 2751 // Fastpath for moving by whole words. 2752 if (BitShift == 0) { 2753 std::memmove(Dst, Dst + WordShift, WordsToMove * APINT_WORD_SIZE); 2754 } else { 2755 for (unsigned i = 0; i != WordsToMove; ++i) { 2756 Dst[i] = Dst[i + WordShift] >> BitShift; 2757 if (i + 1 != WordsToMove) 2758 Dst[i] |= Dst[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift); 2759 } 2760 } 2761 2762 // Fill in the remainder with 0s. 2763 std::memset(Dst + WordsToMove, 0, WordShift * APINT_WORD_SIZE); 2764 } 2765 2766 // Comparison (unsigned) of two bignums. 2767 int APInt::tcCompare(const WordType *lhs, const WordType *rhs, 2768 unsigned parts) { 2769 while (parts) { 2770 parts--; 2771 if (lhs[parts] != rhs[parts]) 2772 return (lhs[parts] > rhs[parts]) ? 1 : -1; 2773 } 2774 2775 return 0; 2776 } 2777 2778 APInt llvm::APIntOps::RoundingUDiv(const APInt &A, const APInt &B, 2779 APInt::Rounding RM) { 2780 // Currently udivrem always rounds down. 2781 switch (RM) { 2782 case APInt::Rounding::DOWN: 2783 case APInt::Rounding::TOWARD_ZERO: 2784 return A.udiv(B); 2785 case APInt::Rounding::UP: { 2786 APInt Quo, Rem; 2787 APInt::udivrem(A, B, Quo, Rem); 2788 if (Rem.isZero()) 2789 return Quo; 2790 return Quo + 1; 2791 } 2792 } 2793 llvm_unreachable("Unknown APInt::Rounding enum"); 2794 } 2795 2796 APInt llvm::APIntOps::RoundingSDiv(const APInt &A, const APInt &B, 2797 APInt::Rounding RM) { 2798 switch (RM) { 2799 case APInt::Rounding::DOWN: 2800 case APInt::Rounding::UP: { 2801 APInt Quo, Rem; 2802 APInt::sdivrem(A, B, Quo, Rem); 2803 if (Rem.isZero()) 2804 return Quo; 2805 // This algorithm deals with arbitrary rounding mode used by sdivrem. 2806 // We want to check whether the non-integer part of the mathematical value 2807 // is negative or not. If the non-integer part is negative, we need to round 2808 // down from Quo; otherwise, if it's positive or 0, we return Quo, as it's 2809 // already rounded down. 2810 if (RM == APInt::Rounding::DOWN) { 2811 if (Rem.isNegative() != B.isNegative()) 2812 return Quo - 1; 2813 return Quo; 2814 } 2815 if (Rem.isNegative() != B.isNegative()) 2816 return Quo; 2817 return Quo + 1; 2818 } 2819 // Currently sdiv rounds towards zero. 2820 case APInt::Rounding::TOWARD_ZERO: 2821 return A.sdiv(B); 2822 } 2823 llvm_unreachable("Unknown APInt::Rounding enum"); 2824 } 2825 2826 std::optional<APInt> 2827 llvm::APIntOps::SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, 2828 unsigned RangeWidth) { 2829 unsigned CoeffWidth = A.getBitWidth(); 2830 assert(CoeffWidth == B.getBitWidth() && CoeffWidth == C.getBitWidth()); 2831 assert(RangeWidth <= CoeffWidth && 2832 "Value range width should be less than coefficient width"); 2833 assert(RangeWidth > 1 && "Value range bit width should be > 1"); 2834 2835 LLVM_DEBUG(dbgs() << __func__ << ": solving " << A << "x^2 + " << B 2836 << "x + " << C << ", rw:" << RangeWidth << '\n'); 2837 2838 // Identify 0 as a (non)solution immediately. 2839 if (C.sextOrTrunc(RangeWidth).isZero()) { 2840 LLVM_DEBUG(dbgs() << __func__ << ": zero solution\n"); 2841 return APInt(CoeffWidth, 0); 2842 } 2843 2844 // The result of APInt arithmetic has the same bit width as the operands, 2845 // so it can actually lose high bits. A product of two n-bit integers needs 2846 // 2n-1 bits to represent the full value. 2847 // The operation done below (on quadratic coefficients) that can produce 2848 // the largest value is the evaluation of the equation during bisection, 2849 // which needs 3 times the bitwidth of the coefficient, so the total number 2850 // of required bits is 3n. 2851 // 2852 // The purpose of this extension is to simulate the set Z of all integers, 2853 // where n+1 > n for all n in Z. In Z it makes sense to talk about positive 2854 // and negative numbers (not so much in a modulo arithmetic). The method 2855 // used to solve the equation is based on the standard formula for real 2856 // numbers, and uses the concepts of "positive" and "negative" with their 2857 // usual meanings. 2858 CoeffWidth *= 3; 2859 A = A.sext(CoeffWidth); 2860 B = B.sext(CoeffWidth); 2861 C = C.sext(CoeffWidth); 2862 2863 // Make A > 0 for simplicity. Negate cannot overflow at this point because 2864 // the bit width has increased. 2865 if (A.isNegative()) { 2866 A.negate(); 2867 B.negate(); 2868 C.negate(); 2869 } 2870 2871 // Solving an equation q(x) = 0 with coefficients in modular arithmetic 2872 // is really solving a set of equations q(x) = kR for k = 0, 1, 2, ..., 2873 // and R = 2^BitWidth. 2874 // Since we're trying not only to find exact solutions, but also values 2875 // that "wrap around", such a set will always have a solution, i.e. an x 2876 // that satisfies at least one of the equations, or such that |q(x)| 2877 // exceeds kR, while |q(x-1)| for the same k does not. 2878 // 2879 // We need to find a value k, such that Ax^2 + Bx + C = kR will have a 2880 // positive solution n (in the above sense), and also such that the n 2881 // will be the least among all solutions corresponding to k = 0, 1, ... 2882 // (more precisely, the least element in the set 2883 // { n(k) | k is such that a solution n(k) exists }). 2884 // 2885 // Consider the parabola (over real numbers) that corresponds to the 2886 // quadratic equation. Since A > 0, the arms of the parabola will point 2887 // up. Picking different values of k will shift it up and down by R. 2888 // 2889 // We want to shift the parabola in such a way as to reduce the problem 2890 // of solving q(x) = kR to solving shifted_q(x) = 0. 2891 // (The interesting solutions are the ceilings of the real number 2892 // solutions.) 2893 APInt R = APInt::getOneBitSet(CoeffWidth, RangeWidth); 2894 APInt TwoA = 2 * A; 2895 APInt SqrB = B * B; 2896 bool PickLow; 2897 2898 auto RoundUp = [] (const APInt &V, const APInt &A) -> APInt { 2899 assert(A.isStrictlyPositive()); 2900 APInt T = V.abs().urem(A); 2901 if (T.isZero()) 2902 return V; 2903 return V.isNegative() ? V+T : V+(A-T); 2904 }; 2905 2906 // The vertex of the parabola is at -B/2A, but since A > 0, it's negative 2907 // iff B is positive. 2908 if (B.isNonNegative()) { 2909 // If B >= 0, the vertex it at a negative location (or at 0), so in 2910 // order to have a non-negative solution we need to pick k that makes 2911 // C-kR negative. To satisfy all the requirements for the solution 2912 // that we are looking for, it needs to be closest to 0 of all k. 2913 C = C.srem(R); 2914 if (C.isStrictlyPositive()) 2915 C -= R; 2916 // Pick the greater solution. 2917 PickLow = false; 2918 } else { 2919 // If B < 0, the vertex is at a positive location. For any solution 2920 // to exist, the discriminant must be non-negative. This means that 2921 // C-kR <= B^2/4A is a necessary condition for k, i.e. there is a 2922 // lower bound on values of k: kR >= C - B^2/4A. 2923 APInt LowkR = C - SqrB.udiv(2*TwoA); // udiv because all values > 0. 2924 // Round LowkR up (towards +inf) to the nearest kR. 2925 LowkR = RoundUp(LowkR, R); 2926 2927 // If there exists k meeting the condition above, and such that 2928 // C-kR > 0, there will be two positive real number solutions of 2929 // q(x) = kR. Out of all such values of k, pick the one that makes 2930 // C-kR closest to 0, (i.e. pick maximum k such that C-kR > 0). 2931 // In other words, find maximum k such that LowkR <= kR < C. 2932 if (C.sgt(LowkR)) { 2933 // If LowkR < C, then such a k is guaranteed to exist because 2934 // LowkR itself is a multiple of R. 2935 C -= -RoundUp(-C, R); // C = C - RoundDown(C, R) 2936 // Pick the smaller solution. 2937 PickLow = true; 2938 } else { 2939 // If C-kR < 0 for all potential k's, it means that one solution 2940 // will be negative, while the other will be positive. The positive 2941 // solution will shift towards 0 if the parabola is moved up. 2942 // Pick the kR closest to the lower bound (i.e. make C-kR closest 2943 // to 0, or in other words, out of all parabolas that have solutions, 2944 // pick the one that is the farthest "up"). 2945 // Since LowkR is itself a multiple of R, simply take C-LowkR. 2946 C -= LowkR; 2947 // Pick the greater solution. 2948 PickLow = false; 2949 } 2950 } 2951 2952 LLVM_DEBUG(dbgs() << __func__ << ": updated coefficients " << A << "x^2 + " 2953 << B << "x + " << C << ", rw:" << RangeWidth << '\n'); 2954 2955 APInt D = SqrB - 4*A*C; 2956 assert(D.isNonNegative() && "Negative discriminant"); 2957 APInt SQ = D.sqrt(); 2958 2959 APInt Q = SQ * SQ; 2960 bool InexactSQ = Q != D; 2961 // The calculated SQ may actually be greater than the exact (non-integer) 2962 // value. If that's the case, decrement SQ to get a value that is lower. 2963 if (Q.sgt(D)) 2964 SQ -= 1; 2965 2966 APInt X; 2967 APInt Rem; 2968 2969 // SQ is rounded down (i.e SQ * SQ <= D), so the roots may be inexact. 2970 // When using the quadratic formula directly, the calculated low root 2971 // may be greater than the exact one, since we would be subtracting SQ. 2972 // To make sure that the calculated root is not greater than the exact 2973 // one, subtract SQ+1 when calculating the low root (for inexact value 2974 // of SQ). 2975 if (PickLow) 2976 APInt::sdivrem(-B - (SQ+InexactSQ), TwoA, X, Rem); 2977 else 2978 APInt::sdivrem(-B + SQ, TwoA, X, Rem); 2979 2980 // The updated coefficients should be such that the (exact) solution is 2981 // positive. Since APInt division rounds towards 0, the calculated one 2982 // can be 0, but cannot be negative. 2983 assert(X.isNonNegative() && "Solution should be non-negative"); 2984 2985 if (!InexactSQ && Rem.isZero()) { 2986 LLVM_DEBUG(dbgs() << __func__ << ": solution (root): " << X << '\n'); 2987 return X; 2988 } 2989 2990 assert((SQ*SQ).sle(D) && "SQ = |_sqrt(D)_|, so SQ*SQ <= D"); 2991 // The exact value of the square root of D should be between SQ and SQ+1. 2992 // This implies that the solution should be between that corresponding to 2993 // SQ (i.e. X) and that corresponding to SQ+1. 2994 // 2995 // The calculated X cannot be greater than the exact (real) solution. 2996 // Actually it must be strictly less than the exact solution, while 2997 // X+1 will be greater than or equal to it. 2998 2999 APInt VX = (A*X + B)*X + C; 3000 APInt VY = VX + TwoA*X + A + B; 3001 bool SignChange = 3002 VX.isNegative() != VY.isNegative() || VX.isZero() != VY.isZero(); 3003 // If the sign did not change between X and X+1, X is not a valid solution. 3004 // This could happen when the actual (exact) roots don't have an integer 3005 // between them, so they would both be contained between X and X+1. 3006 if (!SignChange) { 3007 LLVM_DEBUG(dbgs() << __func__ << ": no valid solution\n"); 3008 return std::nullopt; 3009 } 3010 3011 X += 1; 3012 LLVM_DEBUG(dbgs() << __func__ << ": solution (wrap): " << X << '\n'); 3013 return X; 3014 } 3015 3016 std::optional<unsigned> 3017 llvm::APIntOps::GetMostSignificantDifferentBit(const APInt &A, const APInt &B) { 3018 assert(A.getBitWidth() == B.getBitWidth() && "Must have the same bitwidth"); 3019 if (A == B) 3020 return std::nullopt; 3021 return A.getBitWidth() - ((A ^ B).countl_zero() + 1); 3022 } 3023 3024 APInt llvm::APIntOps::ScaleBitMask(const APInt &A, unsigned NewBitWidth, 3025 bool MatchAllBits) { 3026 unsigned OldBitWidth = A.getBitWidth(); 3027 assert((((OldBitWidth % NewBitWidth) == 0) || 3028 ((NewBitWidth % OldBitWidth) == 0)) && 3029 "One size should be a multiple of the other one. " 3030 "Can't do fractional scaling."); 3031 3032 // Check for matching bitwidths. 3033 if (OldBitWidth == NewBitWidth) 3034 return A; 3035 3036 APInt NewA = APInt::getZero(NewBitWidth); 3037 3038 // Check for null input. 3039 if (A.isZero()) 3040 return NewA; 3041 3042 if (NewBitWidth > OldBitWidth) { 3043 // Repeat bits. 3044 unsigned Scale = NewBitWidth / OldBitWidth; 3045 for (unsigned i = 0; i != OldBitWidth; ++i) 3046 if (A[i]) 3047 NewA.setBits(i * Scale, (i + 1) * Scale); 3048 } else { 3049 unsigned Scale = OldBitWidth / NewBitWidth; 3050 for (unsigned i = 0; i != NewBitWidth; ++i) { 3051 if (MatchAllBits) { 3052 if (A.extractBits(Scale, i * Scale).isAllOnes()) 3053 NewA.setBit(i); 3054 } else { 3055 if (!A.extractBits(Scale, i * Scale).isZero()) 3056 NewA.setBit(i); 3057 } 3058 } 3059 } 3060 3061 return NewA; 3062 } 3063 3064 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst 3065 /// with the integer held in IntVal. 3066 void llvm::StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, 3067 unsigned StoreBytes) { 3068 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!"); 3069 const uint8_t *Src = (const uint8_t *)IntVal.getRawData(); 3070 3071 if (sys::IsLittleEndianHost) { 3072 // Little-endian host - the source is ordered from LSB to MSB. Order the 3073 // destination from LSB to MSB: Do a straight copy. 3074 memcpy(Dst, Src, StoreBytes); 3075 } else { 3076 // Big-endian host - the source is an array of 64 bit words ordered from 3077 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination 3078 // from MSB to LSB: Reverse the word order, but not the bytes in a word. 3079 while (StoreBytes > sizeof(uint64_t)) { 3080 StoreBytes -= sizeof(uint64_t); 3081 // May not be aligned so use memcpy. 3082 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 3083 Src += sizeof(uint64_t); 3084 } 3085 3086 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 3087 } 3088 } 3089 3090 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting 3091 /// from Src into IntVal, which is assumed to be wide enough and to hold zero. 3092 void llvm::LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, 3093 unsigned LoadBytes) { 3094 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!"); 3095 uint8_t *Dst = reinterpret_cast<uint8_t *>( 3096 const_cast<uint64_t *>(IntVal.getRawData())); 3097 3098 if (sys::IsLittleEndianHost) 3099 // Little-endian host - the destination must be ordered from LSB to MSB. 3100 // The source is ordered from LSB to MSB: Do a straight copy. 3101 memcpy(Dst, Src, LoadBytes); 3102 else { 3103 // Big-endian - the destination is an array of 64 bit words ordered from 3104 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 3105 // ordered from MSB to LSB: Reverse the word order, but not the bytes in 3106 // a word. 3107 while (LoadBytes > sizeof(uint64_t)) { 3108 LoadBytes -= sizeof(uint64_t); 3109 // May not be aligned so use memcpy. 3110 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 3111 Dst += sizeof(uint64_t); 3112 } 3113 3114 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 3115 } 3116 } 3117 3118 APInt APIntOps::avgFloorS(const APInt &C1, const APInt &C2) { 3119 // Return floor((C1 + C2) / 2) 3120 return (C1 & C2) + (C1 ^ C2).ashr(1); 3121 } 3122 3123 APInt APIntOps::avgFloorU(const APInt &C1, const APInt &C2) { 3124 // Return floor((C1 + C2) / 2) 3125 return (C1 & C2) + (C1 ^ C2).lshr(1); 3126 } 3127 3128 APInt APIntOps::avgCeilS(const APInt &C1, const APInt &C2) { 3129 // Return ceil((C1 + C2) / 2) 3130 return (C1 | C2) - (C1 ^ C2).ashr(1); 3131 } 3132 3133 APInt APIntOps::avgCeilU(const APInt &C1, const APInt &C2) { 3134 // Return ceil((C1 + C2) / 2) 3135 return (C1 | C2) - (C1 ^ C2).lshr(1); 3136 } 3137 3138 APInt APIntOps::mulhs(const APInt &C1, const APInt &C2) { 3139 assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths"); 3140 unsigned FullWidth = C1.getBitWidth() * 2; 3141 APInt C1Ext = C1.sext(FullWidth); 3142 APInt C2Ext = C2.sext(FullWidth); 3143 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 3144 } 3145 3146 APInt APIntOps::mulhu(const APInt &C1, const APInt &C2) { 3147 assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths"); 3148 unsigned FullWidth = C1.getBitWidth() * 2; 3149 APInt C1Ext = C1.zext(FullWidth); 3150 APInt C2Ext = C2.zext(FullWidth); 3151 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 3152 } 3153