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