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