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