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