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