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