Bug Summary

File:llvm/include/llvm/ADT/APInt.h
Warning:line 1857, column 33
Use of memory allocated with size zero

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name APInt.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Support -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Support -I include -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-10-17-004846-21170-1 -x c++ /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Support/APInt.cpp

/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Support/APInt.cpp

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

/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h

1//===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements a class to represent arbitrary precision
11/// integral constant values and operations on them.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_APINT_H
16#define LLVM_ADT_APINT_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/MathExtras.h"
20#include <cassert>
21#include <climits>
22#include <cstring>
23#include <utility>
24
25namespace llvm {
26class FoldingSetNodeID;
27class StringRef;
28class hash_code;
29class raw_ostream;
30
31template <typename T> class SmallVectorImpl;
32template <typename T> class ArrayRef;
33template <typename T> class Optional;
34template <typename T> struct DenseMapInfo;
35
36class APInt;
37
38inline APInt operator-(APInt);
39
40//===----------------------------------------------------------------------===//
41// APInt Class
42//===----------------------------------------------------------------------===//
43
44/// Class for arbitrary precision integers.
45///
46/// APInt is a functional replacement for common case unsigned integer type like
47/// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
48/// integer sizes and large integer value types such as 3-bits, 15-bits, or more
49/// than 64-bits of precision. APInt provides a variety of arithmetic operators
50/// and methods to manipulate integer values of any bit-width. It supports both
51/// the typical integer arithmetic and comparison operations as well as bitwise
52/// manipulation.
53///
54/// The class has several invariants worth noting:
55/// * All bit, byte, and word positions are zero-based.
56/// * Once the bit width is set, it doesn't change except by the Truncate,
57/// SignExtend, or ZeroExtend operations.
58/// * All binary operators must be on APInt instances of the same bit width.
59/// Attempting to use these operators on instances with different bit
60/// widths will yield an assertion.
61/// * The value is stored canonically as an unsigned value. For operations
62/// where it makes a difference, there are both signed and unsigned variants
63/// of the operation. For example, sdiv and udiv. However, because the bit
64/// widths must be the same, operations such as Mul and Add produce the same
65/// results regardless of whether the values are interpreted as signed or
66/// not.
67/// * In general, the class tries to follow the style of computation that LLVM
68/// uses in its IR. This simplifies its use for LLVM.
69/// * APInt supports zero-bit-width values, but operations that require bits
70/// are not defined on it (e.g. you cannot ask for the sign of a zero-bit
71/// integer). This means that operations like zero extension and logical
72/// shifts are defined, but sign extension and ashr is not. Zero bit values
73/// compare and hash equal to themselves, and countLeadingZeros returns 0.
74///
75class LLVM_NODISCARD[[clang::warn_unused_result]] APInt {
76public:
77 typedef uint64_t WordType;
78
79 /// This enum is used to hold the constants we needed for APInt.
80 enum : unsigned {
81 /// Byte size of a word.
82 APINT_WORD_SIZE = sizeof(WordType),
83 /// Bits in a word.
84 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT8
85 };
86
87 enum class Rounding {
88 DOWN,
89 TOWARD_ZERO,
90 UP,
91 };
92
93 static constexpr WordType WORDTYPE_MAX = ~WordType(0);
94
95 /// \name Constructors
96 /// @{
97
98 /// Create a new APInt of numBits width, initialized as val.
99 ///
100 /// If isSigned is true then val is treated as if it were a signed value
101 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
102 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
103 /// the range of val are zero filled).
104 ///
105 /// \param numBits the bit width of the constructed APInt
106 /// \param val the initial value of the APInt
107 /// \param isSigned how to treat signedness of val
108 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
109 : BitWidth(numBits) {
110 if (isSingleWord()) {
111 U.VAL = val;
112 clearUnusedBits();
113 } else {
114 initSlowCase(val, isSigned);
115 }
116 }
117
118 /// Construct an APInt of numBits width, initialized as bigVal[].
119 ///
120 /// Note that bigVal.size() can be smaller or larger than the corresponding
121 /// bit width but any extraneous bits will be dropped.
122 ///
123 /// \param numBits the bit width of the constructed APInt
124 /// \param bigVal a sequence of words to form the initial value of the APInt
125 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
126
127 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
128 /// deprecated because this constructor is prone to ambiguity with the
129 /// APInt(unsigned, uint64_t, bool) constructor.
130 ///
131 /// If this overload is ever deleted, care should be taken to prevent calls
132 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
133 /// constructor.
134 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
135
136 /// Construct an APInt from a string representation.
137 ///
138 /// This constructor interprets the string \p str in the given radix. The
139 /// interpretation stops when the first character that is not suitable for the
140 /// radix is encountered, or the end of the string. Acceptable radix values
141 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
142 /// string to require more bits than numBits.
143 ///
144 /// \param numBits the bit width of the constructed APInt
145 /// \param str the string to be interpreted
146 /// \param radix the radix to use for the conversion
147 APInt(unsigned numBits, StringRef str, uint8_t radix);
148
149 /// Default constructor that creates an APInt with a 1-bit zero value.
150 explicit APInt() : BitWidth(1) { U.VAL = 0; }
151
152 /// Copy Constructor.
153 APInt(const APInt &that) : BitWidth(that.BitWidth) {
154 if (isSingleWord())
39
Taking false branch
155 U.VAL = that.U.VAL;
156 else
157 initSlowCase(that);
40
Calling 'APInt::initSlowCase'
44
Returned allocated memory
158 }
159
160 /// Move Constructor.
161 APInt(APInt &&that) : BitWidth(that.BitWidth) {
162 memcpy(&U, &that.U, sizeof(U));
163 that.BitWidth = 0;
164 }
165
166 /// Destructor.
167 ~APInt() {
168 if (needsCleanup())
169 delete[] U.pVal;
170 }
171
172 /// @}
173 /// \name Value Generators
174 /// @{
175
176 /// Get the '0' value for the specified bit-width.
177 static APInt getZero(unsigned numBits) { return APInt(numBits, 0); }
178
179 /// NOTE: This is soft-deprecated. Please use `getZero()` instead.
180 static APInt getNullValue(unsigned numBits) { return getZero(numBits); }
181
182 /// Return an APInt zero bits wide.
183 static APInt getZeroWidth() { return getZero(0); }
184
185 /// Gets maximum unsigned value of APInt for specific bit width.
186 static APInt getMaxValue(unsigned numBits) { return getAllOnes(numBits); }
187
188 /// Gets maximum signed value of APInt for a specific bit width.
189 static APInt getSignedMaxValue(unsigned numBits) {
190 APInt API = getAllOnes(numBits);
191 API.clearBit(numBits - 1);
192 return API;
193 }
194
195 /// Gets minimum unsigned value of APInt for a specific bit width.
196 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
197
198 /// Gets minimum signed value of APInt for a specific bit width.
199 static APInt getSignedMinValue(unsigned numBits) {
200 APInt API(numBits, 0);
201 API.setBit(numBits - 1);
202 return API;
203 }
204
205 /// Get the SignMask for a specific bit width.
206 ///
207 /// This is just a wrapper function of getSignedMinValue(), and it helps code
208 /// readability when we want to get a SignMask.
209 static APInt getSignMask(unsigned BitWidth) {
210 return getSignedMinValue(BitWidth);
211 }
212
213 /// Return an APInt of a specified width with all bits set.
214 static APInt getAllOnes(unsigned numBits) {
215 return APInt(numBits, WORDTYPE_MAX, true);
216 }
217
218 /// NOTE: This is soft-deprecated. Please use `getAllOnes()` instead.
219 static APInt getAllOnesValue(unsigned numBits) { return getAllOnes(numBits); }
220
221 /// Return an APInt with exactly one bit set in the result.
222 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
223 APInt Res(numBits, 0);
224 Res.setBit(BitNo);
225 return Res;
226 }
227
228 /// Get a value with a block of bits set.
229 ///
230 /// Constructs an APInt value that has a contiguous range of bits set. The
231 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
232 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
233 /// 0x0000FFFF. Please call getBitsSetWithWrap if \p loBit may be greater than
234 /// \p hiBit.
235 ///
236 /// \param numBits the intended bit width of the result
237 /// \param loBit the index of the lowest bit set.
238 /// \param hiBit the index of the highest bit set.
239 ///
240 /// \returns An APInt value with the requested bits set.
241 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
242 APInt Res(numBits, 0);
243 Res.setBits(loBit, hiBit);
244 return Res;
245 }
246
247 /// Wrap version of getBitsSet.
248 /// If \p hiBit is bigger than \p loBit, this is same with getBitsSet.
249 /// If \p hiBit is not bigger than \p loBit, the set bits "wrap". For example,
250 /// with parameters (32, 28, 4), you would get 0xF000000F.
251 /// If \p hiBit is equal to \p loBit, you would get a result with all bits
252 /// set.
253 static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit,
254 unsigned hiBit) {
255 APInt Res(numBits, 0);
256 Res.setBitsWithWrap(loBit, hiBit);
257 return Res;
258 }
259
260 /// Constructs an APInt value that has a contiguous range of bits set. The
261 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
262 /// bits will be zero. For example, with parameters(32, 12) you would get
263 /// 0xFFFFF000.
264 ///
265 /// \param numBits the intended bit width of the result
266 /// \param loBit the index of the lowest bit to set.
267 ///
268 /// \returns An APInt value with the requested bits set.
269 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
270 APInt Res(numBits, 0);
271 Res.setBitsFrom(loBit);
272 return Res;
273 }
274
275 /// Constructs an APInt value that has the top hiBitsSet bits set.
276 ///
277 /// \param numBits the bitwidth of the result
278 /// \param hiBitsSet the number of high-order bits set in the result.
279 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
280 APInt Res(numBits, 0);
281 Res.setHighBits(hiBitsSet);
282 return Res;
283 }
284
285 /// Constructs an APInt value that has the bottom loBitsSet bits set.
286 ///
287 /// \param numBits the bitwidth of the result
288 /// \param loBitsSet the number of low-order bits set in the result.
289 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
290 APInt Res(numBits, 0);
291 Res.setLowBits(loBitsSet);
292 return Res;
293 }
294
295 /// Return a value containing V broadcasted over NewLen bits.
296 static APInt getSplat(unsigned NewLen, const APInt &V);
297
298 /// @}
299 /// \name Value Tests
300 /// @{
301
302 /// Determine if this APInt just has one word to store value.
303 ///
304 /// \returns true if the number of bits <= 64, false otherwise.
305 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
306
307 /// Determine sign of this APInt.
308 ///
309 /// This tests the high bit of this APInt to determine if it is set.
310 ///
311 /// \returns true if this APInt is negative, false otherwise
312 bool isNegative() const { return (*this)[BitWidth - 1]; }
313
314 /// Determine if this APInt Value is non-negative (>= 0)
315 ///
316 /// This tests the high bit of the APInt to determine if it is unset.
317 bool isNonNegative() const { return !isNegative(); }
318
319 /// Determine if sign bit of this APInt is set.
320 ///
321 /// This tests the high bit of this APInt to determine if it is set.
322 ///
323 /// \returns true if this APInt has its sign bit set, false otherwise.
324 bool isSignBitSet() const { return (*this)[BitWidth - 1]; }
325
326 /// Determine if sign bit of this APInt is clear.
327 ///
328 /// This tests the high bit of this APInt to determine if it is clear.
329 ///
330 /// \returns true if this APInt has its sign bit clear, false otherwise.
331 bool isSignBitClear() const { return !isSignBitSet(); }
332
333 /// Determine if this APInt Value is positive.
334 ///
335 /// This tests if the value of this APInt is positive (> 0). Note
336 /// that 0 is not a positive value.
337 ///
338 /// \returns true if this APInt is positive.
339 bool isStrictlyPositive() const { return isNonNegative() && !isZero(); }
340
341 /// Determine if this APInt Value is non-positive (<= 0).
342 ///
343 /// \returns true if this APInt is non-positive.
344 bool isNonPositive() const { return !isStrictlyPositive(); }
345
346 /// Determine if all bits are set. This is true for zero-width values.
347 bool isAllOnes() const {
348 if (BitWidth == 0)
349 return true;
350 if (isSingleWord())
351 return U.VAL == WORDTYPE_MAX >> (APINT_BITS_PER_WORD - BitWidth);
352 return countTrailingOnesSlowCase() == BitWidth;
353 }
354
355 /// NOTE: This is soft-deprecated. Please use `isAllOnes()` instead.
356 bool isAllOnesValue() const { return isAllOnes(); }
357
358 /// Determine if this value is zero, i.e. all bits are clear.
359 bool isZero() const {
360 if (isSingleWord())
361 return U.VAL == 0;
362 return countLeadingZerosSlowCase() == BitWidth;
363 }
364
365 /// NOTE: This is soft-deprecated. Please use `isZero()` instead.
366 bool isNullValue() const { return isZero(); }
367
368 /// Determine if this is a value of 1.
369 ///
370 /// This checks to see if the value of this APInt is one.
371 bool isOne() const {
372 if (isSingleWord())
373 return U.VAL == 1;
374 return countLeadingZerosSlowCase() == BitWidth - 1;
375 }
376
377 /// NOTE: This is soft-deprecated. Please use `isOne()` instead.
378 bool isOneValue() const { return isOne(); }
379
380 /// Determine if this is the largest unsigned value.
381 ///
382 /// This checks to see if the value of this APInt is the maximum unsigned
383 /// value for the APInt's bit width.
384 bool isMaxValue() const { return isAllOnes(); }
385
386 /// Determine if this is the largest signed value.
387 ///
388 /// This checks to see if the value of this APInt is the maximum signed
389 /// value for the APInt's bit width.
390 bool isMaxSignedValue() const {
391 if (isSingleWord()) {
392 assert(BitWidth && "zero width values not allowed")(static_cast <bool> (BitWidth && "zero width values not allowed"
) ? void (0) : __assert_fail ("BitWidth && \"zero width values not allowed\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 392, __extension__ __PRETTY_FUNCTION__))
;
393 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
394 }
395 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
396 }
397
398 /// Determine if this is the smallest unsigned value.
399 ///
400 /// This checks to see if the value of this APInt is the minimum unsigned
401 /// value for the APInt's bit width.
402 bool isMinValue() const { return isZero(); }
403
404 /// Determine if this is the smallest signed value.
405 ///
406 /// This checks to see if the value of this APInt is the minimum signed
407 /// value for the APInt's bit width.
408 bool isMinSignedValue() const {
409 if (isSingleWord()) {
410 assert(BitWidth && "zero width values not allowed")(static_cast <bool> (BitWidth && "zero width values not allowed"
) ? void (0) : __assert_fail ("BitWidth && \"zero width values not allowed\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 410, __extension__ __PRETTY_FUNCTION__))
;
411 return U.VAL == (WordType(1) << (BitWidth - 1));
412 }
413 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
414 }
415
416 /// Check if this APInt has an N-bits unsigned integer value.
417 bool isIntN(unsigned N) const { return getActiveBits() <= N; }
418
419 /// Check if this APInt has an N-bits signed integer value.
420 bool isSignedIntN(unsigned N) const { return getMinSignedBits() <= N; }
421
422 /// Check if this APInt's value is a power of two greater than zero.
423 ///
424 /// \returns true if the argument APInt value is a power of two > 0.
425 bool isPowerOf2() const {
426 if (isSingleWord()) {
427 assert(BitWidth && "zero width values not allowed")(static_cast <bool> (BitWidth && "zero width values not allowed"
) ? void (0) : __assert_fail ("BitWidth && \"zero width values not allowed\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 427, __extension__ __PRETTY_FUNCTION__))
;
428 return isPowerOf2_64(U.VAL);
429 }
430 return countPopulationSlowCase() == 1;
431 }
432
433 /// Check if the APInt's value is returned by getSignMask.
434 ///
435 /// \returns true if this is the value returned by getSignMask.
436 bool isSignMask() const { return isMinSignedValue(); }
437
438 /// Convert APInt to a boolean value.
439 ///
440 /// This converts the APInt to a boolean value as a test against zero.
441 bool getBoolValue() const { return !isZero(); }
442
443 /// If this value is smaller than the specified limit, return it, otherwise
444 /// return the limit value. This causes the value to saturate to the limit.
445 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) const {
446 return ugt(Limit) ? Limit : getZExtValue();
447 }
448
449 /// Check if the APInt consists of a repeated bit pattern.
450 ///
451 /// e.g. 0x01010101 satisfies isSplat(8).
452 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
453 /// width without remainder.
454 bool isSplat(unsigned SplatSizeInBits) const;
455
456 /// \returns true if this APInt value is a sequence of \param numBits ones
457 /// starting at the least significant bit with the remainder zero.
458 bool isMask(unsigned numBits) const {
459 assert(numBits != 0 && "numBits must be non-zero")(static_cast <bool> (numBits != 0 && "numBits must be non-zero"
) ? void (0) : __assert_fail ("numBits != 0 && \"numBits must be non-zero\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 459, __extension__ __PRETTY_FUNCTION__))
;
460 assert(numBits <= BitWidth && "numBits out of range")(static_cast <bool> (numBits <= BitWidth && "numBits out of range"
) ? void (0) : __assert_fail ("numBits <= BitWidth && \"numBits out of range\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 460, __extension__ __PRETTY_FUNCTION__))
;
461 if (isSingleWord())
462 return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits));
463 unsigned Ones = countTrailingOnesSlowCase();
464 return (numBits == Ones) &&
465 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
466 }
467
468 /// \returns true if this APInt is a non-empty sequence of ones starting at
469 /// the least significant bit with the remainder zero.
470 /// Ex. isMask(0x0000FFFFU) == true.
471 bool isMask() const {
472 if (isSingleWord())
473 return isMask_64(U.VAL);
474 unsigned Ones = countTrailingOnesSlowCase();
475 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
476 }
477
478 /// Return true if this APInt value contains a sequence of ones with
479 /// the remainder zero.
480 bool isShiftedMask() const {
481 if (isSingleWord())
482 return isShiftedMask_64(U.VAL);
483 unsigned Ones = countPopulationSlowCase();
484 unsigned LeadZ = countLeadingZerosSlowCase();
485 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
486 }
487
488 /// Compute an APInt containing numBits highbits from this APInt.
489 ///
490 /// Get an APInt with the same BitWidth as this APInt, just zero mask the low
491 /// bits and right shift to the least significant bit.
492 ///
493 /// \returns the high "numBits" bits of this APInt.
494 APInt getHiBits(unsigned numBits) const;
495
496 /// Compute an APInt containing numBits lowbits from this APInt.
497 ///
498 /// Get an APInt with the same BitWidth as this APInt, just zero mask the high
499 /// bits.
500 ///
501 /// \returns the low "numBits" bits of this APInt.
502 APInt getLoBits(unsigned numBits) const;
503
504 /// Determine if two APInts have the same value, after zero-extending
505 /// one of them (if needed!) to ensure that the bit-widths match.
506 static bool isSameValue(const APInt &I1, const APInt &I2) {
507 if (I1.getBitWidth() == I2.getBitWidth())
508 return I1 == I2;
509
510 if (I1.getBitWidth() > I2.getBitWidth())
511 return I1 == I2.zext(I1.getBitWidth());
512
513 return I1.zext(I2.getBitWidth()) == I2;
514 }
515
516 /// Overload to compute a hash_code for an APInt value.
517 friend hash_code hash_value(const APInt &Arg);
518
519 /// This function returns a pointer to the internal storage of the APInt.
520 /// This is useful for writing out the APInt in binary form without any
521 /// conversions.
522 const uint64_t *getRawData() const {
523 if (isSingleWord())
524 return &U.VAL;
525 return &U.pVal[0];
526 }
527
528 /// @}
529 /// \name Unary Operators
530 /// @{
531
532 /// Postfix increment operator. Increment *this by 1.
533 ///
534 /// \returns a new APInt value representing the original value of *this.
535 APInt operator++(int) {
536 APInt API(*this);
537 ++(*this);
538 return API;
539 }
540
541 /// Prefix increment operator.
542 ///
543 /// \returns *this incremented by one
544 APInt &operator++();
545
546 /// Postfix decrement operator. Decrement *this by 1.
547 ///
548 /// \returns a new APInt value representing the original value of *this.
549 APInt operator--(int) {
550 APInt API(*this);
551 --(*this);
552 return API;
553 }
554
555 /// Prefix decrement operator.
556 ///
557 /// \returns *this decremented by one.
558 APInt &operator--();
559
560 /// Logical negation operation on this APInt returns true if zero, like normal
561 /// integers.
562 bool operator!() const { return isZero(); }
563
564 /// @}
565 /// \name Assignment Operators
566 /// @{
567
568 /// Copy assignment operator.
569 ///
570 /// \returns *this after assignment of RHS.
571 APInt &operator=(const APInt &RHS) {
572 // The common case (both source or dest being inline) doesn't require
573 // allocation or deallocation.
574 if (isSingleWord() && RHS.isSingleWord()) {
575 U.VAL = RHS.U.VAL;
576 BitWidth = RHS.BitWidth;
577 return *this;
578 }
579
580 assignSlowCase(RHS);
581 return *this;
582 }
583
584 /// Move assignment operator.
585 APInt &operator=(APInt &&that) {
586#ifdef EXPENSIVE_CHECKS
587 // Some std::shuffle implementations still do self-assignment.
588 if (this == &that)
589 return *this;
590#endif
591 assert(this != &that && "Self-move not supported")(static_cast <bool> (this != &that && "Self-move not supported"
) ? void (0) : __assert_fail ("this != &that && \"Self-move not supported\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 591, __extension__ __PRETTY_FUNCTION__))
;
592 if (!isSingleWord())
593 delete[] U.pVal;
594
595 // Use memcpy so that type based alias analysis sees both VAL and pVal
596 // as modified.
597 memcpy(&U, &that.U, sizeof(U));
598
599 BitWidth = that.BitWidth;
600 that.BitWidth = 0;
601 return *this;
602 }
603
604 /// Assignment operator.
605 ///
606 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
607 /// the bit width, the excess bits are truncated. If the bit width is larger
608 /// than 64, the value is zero filled in the unspecified high order bits.
609 ///
610 /// \returns *this after assignment of RHS value.
611 APInt &operator=(uint64_t RHS) {
612 if (isSingleWord()) {
613 U.VAL = RHS;
614 return clearUnusedBits();
615 }
616 U.pVal[0] = RHS;
617 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
618 return *this;
619 }
620
621 /// Bitwise AND assignment operator.
622 ///
623 /// Performs a bitwise AND operation on this APInt and RHS. The result is
624 /// assigned to *this.
625 ///
626 /// \returns *this after ANDing with RHS.
627 APInt &operator&=(const APInt &RHS) {
628 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 628, __extension__ __PRETTY_FUNCTION__))
;
629 if (isSingleWord())
630 U.VAL &= RHS.U.VAL;
631 else
632 andAssignSlowCase(RHS);
633 return *this;
634 }
635
636 /// Bitwise AND assignment operator.
637 ///
638 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
639 /// logically zero-extended or truncated to match the bit-width of
640 /// the LHS.
641 APInt &operator&=(uint64_t RHS) {
642 if (isSingleWord()) {
643 U.VAL &= RHS;
644 return *this;
645 }
646 U.pVal[0] &= RHS;
647 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
648 return *this;
649 }
650
651 /// Bitwise OR assignment operator.
652 ///
653 /// Performs a bitwise OR operation on this APInt and RHS. The result is
654 /// assigned *this;
655 ///
656 /// \returns *this after ORing with RHS.
657 APInt &operator|=(const APInt &RHS) {
658 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 658, __extension__ __PRETTY_FUNCTION__))
;
659 if (isSingleWord())
660 U.VAL |= RHS.U.VAL;
661 else
662 orAssignSlowCase(RHS);
663 return *this;
664 }
665
666 /// Bitwise OR assignment operator.
667 ///
668 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
669 /// logically zero-extended or truncated to match the bit-width of
670 /// the LHS.
671 APInt &operator|=(uint64_t RHS) {
672 if (isSingleWord()) {
673 U.VAL |= RHS;
674 return clearUnusedBits();
675 }
676 U.pVal[0] |= RHS;
677 return *this;
678 }
679
680 /// Bitwise XOR assignment operator.
681 ///
682 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
683 /// assigned to *this.
684 ///
685 /// \returns *this after XORing with RHS.
686 APInt &operator^=(const APInt &RHS) {
687 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 687, __extension__ __PRETTY_FUNCTION__))
;
688 if (isSingleWord())
689 U.VAL ^= RHS.U.VAL;
690 else
691 xorAssignSlowCase(RHS);
692 return *this;
693 }
694
695 /// Bitwise XOR assignment operator.
696 ///
697 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
698 /// logically zero-extended or truncated to match the bit-width of
699 /// the LHS.
700 APInt &operator^=(uint64_t RHS) {
701 if (isSingleWord()) {
702 U.VAL ^= RHS;
703 return clearUnusedBits();
704 }
705 U.pVal[0] ^= RHS;
706 return *this;
707 }
708
709 /// Multiplication assignment operator.
710 ///
711 /// Multiplies this APInt by RHS and assigns the result to *this.
712 ///
713 /// \returns *this
714 APInt &operator*=(const APInt &RHS);
715 APInt &operator*=(uint64_t RHS);
716
717 /// Addition assignment operator.
718 ///
719 /// Adds RHS to *this and assigns the result to *this.
720 ///
721 /// \returns *this
722 APInt &operator+=(const APInt &RHS);
723 APInt &operator+=(uint64_t RHS);
724
725 /// Subtraction assignment operator.
726 ///
727 /// Subtracts RHS from *this and assigns the result to *this.
728 ///
729 /// \returns *this
730 APInt &operator-=(const APInt &RHS);
731 APInt &operator-=(uint64_t RHS);
732
733 /// Left-shift assignment function.
734 ///
735 /// Shifts *this left by shiftAmt and assigns the result to *this.
736 ///
737 /// \returns *this after shifting left by ShiftAmt
738 APInt &operator<<=(unsigned ShiftAmt) {
739 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 739, __extension__ __PRETTY_FUNCTION__))
;
740 if (isSingleWord()) {
741 if (ShiftAmt == BitWidth)
742 U.VAL = 0;
743 else
744 U.VAL <<= ShiftAmt;
745 return clearUnusedBits();
746 }
747 shlSlowCase(ShiftAmt);
748 return *this;
749 }
750
751 /// Left-shift assignment function.
752 ///
753 /// Shifts *this left by shiftAmt and assigns the result to *this.
754 ///
755 /// \returns *this after shifting left by ShiftAmt
756 APInt &operator<<=(const APInt &ShiftAmt);
757
758 /// @}
759 /// \name Binary Operators
760 /// @{
761
762 /// Multiplication operator.
763 ///
764 /// Multiplies this APInt by RHS and returns the result.
765 APInt operator*(const APInt &RHS) const;
766
767 /// Left logical shift operator.
768 ///
769 /// Shifts this APInt left by \p Bits and returns the result.
770 APInt operator<<(unsigned Bits) const { return shl(Bits); }
771
772 /// Left logical shift operator.
773 ///
774 /// Shifts this APInt left by \p Bits and returns the result.
775 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
776
777 /// Arithmetic right-shift function.
778 ///
779 /// Arithmetic right-shift this APInt by shiftAmt.
780 APInt ashr(unsigned ShiftAmt) const {
781 APInt R(*this);
782 R.ashrInPlace(ShiftAmt);
783 return R;
784 }
785
786 /// Arithmetic right-shift this APInt by ShiftAmt in place.
787 void ashrInPlace(unsigned ShiftAmt) {
788 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 788, __extension__ __PRETTY_FUNCTION__))
;
789 if (isSingleWord()) {
790 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
791 if (ShiftAmt == BitWidth)
792 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
793 else
794 U.VAL = SExtVAL >> ShiftAmt;
795 clearUnusedBits();
796 return;
797 }
798 ashrSlowCase(ShiftAmt);
799 }
800
801 /// Logical right-shift function.
802 ///
803 /// Logical right-shift this APInt by shiftAmt.
804 APInt lshr(unsigned shiftAmt) const {
805 APInt R(*this);
806 R.lshrInPlace(shiftAmt);
807 return R;
808 }
809
810 /// Logical right-shift this APInt by ShiftAmt in place.
811 void lshrInPlace(unsigned ShiftAmt) {
812 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 812, __extension__ __PRETTY_FUNCTION__))
;
813 if (isSingleWord()) {
814 if (ShiftAmt == BitWidth)
815 U.VAL = 0;
816 else
817 U.VAL >>= ShiftAmt;
818 return;
819 }
820 lshrSlowCase(ShiftAmt);
821 }
822
823 /// Left-shift function.
824 ///
825 /// Left-shift this APInt by shiftAmt.
826 APInt shl(unsigned shiftAmt) const {
827 APInt R(*this);
828 R <<= shiftAmt;
829 return R;
830 }
831
832 /// Rotate left by rotateAmt.
833 APInt rotl(unsigned rotateAmt) const;
834
835 /// Rotate right by rotateAmt.
836 APInt rotr(unsigned rotateAmt) const;
837
838 /// Arithmetic right-shift function.
839 ///
840 /// Arithmetic right-shift this APInt by shiftAmt.
841 APInt ashr(const APInt &ShiftAmt) const {
842 APInt R(*this);
843 R.ashrInPlace(ShiftAmt);
844 return R;
845 }
846
847 /// Arithmetic right-shift this APInt by shiftAmt in place.
848 void ashrInPlace(const APInt &shiftAmt);
849
850 /// Logical right-shift function.
851 ///
852 /// Logical right-shift this APInt by shiftAmt.
853 APInt lshr(const APInt &ShiftAmt) const {
854 APInt R(*this);
855 R.lshrInPlace(ShiftAmt);
856 return R;
857 }
858
859 /// Logical right-shift this APInt by ShiftAmt in place.
860 void lshrInPlace(const APInt &ShiftAmt);
861
862 /// Left-shift function.
863 ///
864 /// Left-shift this APInt by shiftAmt.
865 APInt shl(const APInt &ShiftAmt) const {
866 APInt R(*this);
867 R <<= ShiftAmt;
868 return R;
869 }
870
871 /// Rotate left by rotateAmt.
872 APInt rotl(const APInt &rotateAmt) const;
873
874 /// Rotate right by rotateAmt.
875 APInt rotr(const APInt &rotateAmt) const;
876
877 /// Concatenate the bits from "NewLSB" onto the bottom of *this. This is
878 /// equivalent to:
879 /// (this->zext(NewWidth) << NewLSB.getBitWidth()) | NewLSB.zext(NewWidth)
880 APInt concat(const APInt &NewLSB) const {
881 /// If the result will be small, then both the merged values are small.
882 unsigned NewWidth = getBitWidth() + NewLSB.getBitWidth();
883 if (NewWidth <= APINT_BITS_PER_WORD)
884 return APInt(NewWidth, (U.VAL << NewLSB.getBitWidth()) | NewLSB.U.VAL);
885 return concatSlowCase(NewLSB);
886 }
887
888 /// Unsigned division operation.
889 ///
890 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
891 /// RHS are treated as unsigned quantities for purposes of this division.
892 ///
893 /// \returns a new APInt value containing the division result, rounded towards
894 /// zero.
895 APInt udiv(const APInt &RHS) const;
896 APInt udiv(uint64_t RHS) const;
897
898 /// Signed division function for APInt.
899 ///
900 /// Signed divide this APInt by APInt RHS.
901 ///
902 /// The result is rounded towards zero.
903 APInt sdiv(const APInt &RHS) const;
904 APInt sdiv(int64_t RHS) const;
905
906 /// Unsigned remainder operation.
907 ///
908 /// Perform an unsigned remainder operation on this APInt with RHS being the
909 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
910 /// of this operation. Note that this is a true remainder operation and not a
911 /// modulo operation because the sign follows the sign of the dividend which
912 /// is *this.
913 ///
914 /// \returns a new APInt value containing the remainder result
915 APInt urem(const APInt &RHS) const;
916 uint64_t urem(uint64_t RHS) const;
917
918 /// Function for signed remainder operation.
919 ///
920 /// Signed remainder operation on APInt.
921 APInt srem(const APInt &RHS) const;
922 int64_t srem(int64_t RHS) const;
923
924 /// Dual division/remainder interface.
925 ///
926 /// Sometimes it is convenient to divide two APInt values and obtain both the
927 /// quotient and remainder. This function does both operations in the same
928 /// computation making it a little more efficient. The pair of input arguments
929 /// may overlap with the pair of output arguments. It is safe to call
930 /// udivrem(X, Y, X, Y), for example.
931 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
932 APInt &Remainder);
933 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
934 uint64_t &Remainder);
935
936 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
937 APInt &Remainder);
938 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
939 int64_t &Remainder);
940
941 // Operations that return overflow indicators.
942 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
943 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
944 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
945 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
946 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
947 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
948 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
949 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
950 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
951
952 // Operations that saturate
953 APInt sadd_sat(const APInt &RHS) const;
954 APInt uadd_sat(const APInt &RHS) const;
955 APInt ssub_sat(const APInt &RHS) const;
956 APInt usub_sat(const APInt &RHS) const;
957 APInt smul_sat(const APInt &RHS) const;
958 APInt umul_sat(const APInt &RHS) const;
959 APInt sshl_sat(const APInt &RHS) const;
960 APInt ushl_sat(const APInt &RHS) const;
961
962 /// Array-indexing support.
963 ///
964 /// \returns the bit value at bitPosition
965 bool operator[](unsigned bitPosition) const {
966 assert(bitPosition < getBitWidth() && "Bit position out of bounds!")(static_cast <bool> (bitPosition < getBitWidth() &&
"Bit position out of bounds!") ? void (0) : __assert_fail ("bitPosition < getBitWidth() && \"Bit position out of bounds!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 966, __extension__ __PRETTY_FUNCTION__))
;
967 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
968 }
969
970 /// @}
971 /// \name Comparison Operators
972 /// @{
973
974 /// Equality operator.
975 ///
976 /// Compares this APInt with RHS for the validity of the equality
977 /// relationship.
978 bool operator==(const APInt &RHS) const {
979 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Comparison requires equal bit widths") ? void (0) : __assert_fail
("BitWidth == RHS.BitWidth && \"Comparison requires equal bit widths\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 979, __extension__ __PRETTY_FUNCTION__))
;
980 if (isSingleWord())
981 return U.VAL == RHS.U.VAL;
982 return equalSlowCase(RHS);
983 }
984
985 /// Equality operator.
986 ///
987 /// Compares this APInt with a uint64_t for the validity of the equality
988 /// relationship.
989 ///
990 /// \returns true if *this == Val
991 bool operator==(uint64_t Val) const {
992 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
993 }
994
995 /// Equality comparison.
996 ///
997 /// Compares this APInt with RHS for the validity of the equality
998 /// relationship.
999 ///
1000 /// \returns true if *this == Val
1001 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1002
1003 /// Inequality operator.
1004 ///
1005 /// Compares this APInt with RHS for the validity of the inequality
1006 /// relationship.
1007 ///
1008 /// \returns true if *this != Val
1009 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1010
1011 /// Inequality operator.
1012 ///
1013 /// Compares this APInt with a uint64_t for the validity of the inequality
1014 /// relationship.
1015 ///
1016 /// \returns true if *this != Val
1017 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1018
1019 /// Inequality comparison
1020 ///
1021 /// Compares this APInt with RHS for the validity of the inequality
1022 /// relationship.
1023 ///
1024 /// \returns true if *this != Val
1025 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1026
1027 /// Unsigned less than comparison
1028 ///
1029 /// Regards both *this and RHS as unsigned quantities and compares them for
1030 /// the validity of the less-than relationship.
1031 ///
1032 /// \returns true if *this < RHS when both are considered unsigned.
1033 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1034
1035 /// Unsigned less than comparison
1036 ///
1037 /// Regards both *this as an unsigned quantity and compares it with RHS for
1038 /// the validity of the less-than relationship.
1039 ///
1040 /// \returns true if *this < RHS when considered unsigned.
1041 bool ult(uint64_t RHS) const {
1042 // Only need to check active bits if not a single word.
1043 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1044 }
1045
1046 /// Signed less than comparison
1047 ///
1048 /// Regards both *this and RHS as signed quantities and compares them for
1049 /// validity of the less-than relationship.
1050 ///
1051 /// \returns true if *this < RHS when both are considered signed.
1052 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1053
1054 /// Signed less than comparison
1055 ///
1056 /// Regards both *this as a signed quantity and compares it with RHS for
1057 /// the validity of the less-than relationship.
1058 ///
1059 /// \returns true if *this < RHS when considered signed.
1060 bool slt(int64_t RHS) const {
1061 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1062 : getSExtValue() < RHS;
1063 }
1064
1065 /// Unsigned less or equal comparison
1066 ///
1067 /// Regards both *this and RHS as unsigned quantities and compares them for
1068 /// validity of the less-or-equal relationship.
1069 ///
1070 /// \returns true if *this <= RHS when both are considered unsigned.
1071 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1072
1073 /// Unsigned less or equal comparison
1074 ///
1075 /// Regards both *this as an unsigned quantity and compares it with RHS for
1076 /// the validity of the less-or-equal relationship.
1077 ///
1078 /// \returns true if *this <= RHS when considered unsigned.
1079 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1080
1081 /// Signed less or equal comparison
1082 ///
1083 /// Regards both *this and RHS as signed quantities and compares them for
1084 /// validity of the less-or-equal relationship.
1085 ///
1086 /// \returns true if *this <= RHS when both are considered signed.
1087 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1088
1089 /// Signed less or equal comparison
1090 ///
1091 /// Regards both *this as a signed quantity and compares it with RHS for the
1092 /// validity of the less-or-equal relationship.
1093 ///
1094 /// \returns true if *this <= RHS when considered signed.
1095 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1096
1097 /// Unsigned greater than comparison
1098 ///
1099 /// Regards both *this and RHS as unsigned quantities and compares them for
1100 /// the validity of the greater-than relationship.
1101 ///
1102 /// \returns true if *this > RHS when both are considered unsigned.
1103 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1104
1105 /// Unsigned greater than comparison
1106 ///
1107 /// Regards both *this as an unsigned quantity and compares it with RHS for
1108 /// the validity of the greater-than relationship.
1109 ///
1110 /// \returns true if *this > RHS when considered unsigned.
1111 bool ugt(uint64_t RHS) const {
1112 // Only need to check active bits if not a single word.
1113 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1114 }
1115
1116 /// Signed greater than comparison
1117 ///
1118 /// Regards both *this and RHS as signed quantities and compares them for the
1119 /// validity of the greater-than relationship.
1120 ///
1121 /// \returns true if *this > RHS when both are considered signed.
1122 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1123
1124 /// Signed greater than comparison
1125 ///
1126 /// Regards both *this as a signed quantity and compares it with RHS for
1127 /// the validity of the greater-than relationship.
1128 ///
1129 /// \returns true if *this > RHS when considered signed.
1130 bool sgt(int64_t RHS) const {
1131 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1132 : getSExtValue() > RHS;
1133 }
1134
1135 /// Unsigned greater or equal comparison
1136 ///
1137 /// Regards both *this and RHS as unsigned quantities and compares them for
1138 /// validity of the greater-or-equal relationship.
1139 ///
1140 /// \returns true if *this >= RHS when both are considered unsigned.
1141 bool uge(const APInt &RHS) const { return !ult(RHS); }
1142
1143 /// Unsigned greater or equal comparison
1144 ///
1145 /// Regards both *this as an unsigned quantity and compares it with RHS for
1146 /// the validity of the greater-or-equal relationship.
1147 ///
1148 /// \returns true if *this >= RHS when considered unsigned.
1149 bool uge(uint64_t RHS) const { return !ult(RHS); }
1150
1151 /// Signed greater or equal comparison
1152 ///
1153 /// Regards both *this and RHS as signed quantities and compares them for
1154 /// validity of the greater-or-equal relationship.
1155 ///
1156 /// \returns true if *this >= RHS when both are considered signed.
1157 bool sge(const APInt &RHS) const { return !slt(RHS); }
1158
1159 /// Signed greater or equal comparison
1160 ///
1161 /// Regards both *this as a signed quantity and compares it with RHS for
1162 /// the validity of the greater-or-equal relationship.
1163 ///
1164 /// \returns true if *this >= RHS when considered signed.
1165 bool sge(int64_t RHS) const { return !slt(RHS); }
1166
1167 /// This operation tests if there are any pairs of corresponding bits
1168 /// between this APInt and RHS that are both set.
1169 bool intersects(const APInt &RHS) const {
1170 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1170, __extension__ __PRETTY_FUNCTION__))
;
1171 if (isSingleWord())
1172 return (U.VAL & RHS.U.VAL) != 0;
1173 return intersectsSlowCase(RHS);
1174 }
1175
1176 /// This operation checks that all bits set in this APInt are also set in RHS.
1177 bool isSubsetOf(const APInt &RHS) const {
1178 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1178, __extension__ __PRETTY_FUNCTION__))
;
1179 if (isSingleWord())
1180 return (U.VAL & ~RHS.U.VAL) == 0;
1181 return isSubsetOfSlowCase(RHS);
1182 }
1183
1184 /// @}
1185 /// \name Resizing Operators
1186 /// @{
1187
1188 /// Truncate to new width.
1189 ///
1190 /// Truncate the APInt to a specified width. It is an error to specify a width
1191 /// that is greater than or equal to the current width.
1192 APInt trunc(unsigned width) const;
1193
1194 /// Truncate to new width with unsigned saturation.
1195 ///
1196 /// If the APInt, treated as unsigned integer, can be losslessly truncated to
1197 /// the new bitwidth, then return truncated APInt. Else, return max value.
1198 APInt truncUSat(unsigned width) const;
1199
1200 /// Truncate to new width with signed saturation.
1201 ///
1202 /// If this APInt, treated as signed integer, can be losslessly truncated to
1203 /// the new bitwidth, then return truncated APInt. Else, return either
1204 /// signed min value if the APInt was negative, or signed max value.
1205 APInt truncSSat(unsigned width) const;
1206
1207 /// Sign extend to a new width.
1208 ///
1209 /// This operation sign extends the APInt to a new width. If the high order
1210 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1211 /// It is an error to specify a width that is less than or equal to the
1212 /// current width.
1213 APInt sext(unsigned width) const;
1214
1215 /// Zero extend to a new width.
1216 ///
1217 /// This operation zero extends the APInt to a new width. The high order bits
1218 /// are filled with 0 bits. It is an error to specify a width that is less
1219 /// than or equal to the current width.
1220 APInt zext(unsigned width) const;
1221
1222 /// Sign extend or truncate to width
1223 ///
1224 /// Make this APInt have the bit width given by \p width. The value is sign
1225 /// extended, truncated, or left alone to make it that width.
1226 APInt sextOrTrunc(unsigned width) const;
1227
1228 /// Zero extend or truncate to width
1229 ///
1230 /// Make this APInt have the bit width given by \p width. The value is zero
1231 /// extended, truncated, or left alone to make it that width.
1232 APInt zextOrTrunc(unsigned width) const;
1233
1234 /// Truncate to width
1235 ///
1236 /// Make this APInt have the bit width given by \p width. The value is
1237 /// truncated or left alone to make it that width.
1238 APInt truncOrSelf(unsigned width) const;
1239
1240 /// Sign extend or truncate to width
1241 ///
1242 /// Make this APInt have the bit width given by \p width. The value is sign
1243 /// extended, or left alone to make it that width.
1244 APInt sextOrSelf(unsigned width) const;
1245
1246 /// Zero extend or truncate to width
1247 ///
1248 /// Make this APInt have the bit width given by \p width. The value is zero
1249 /// extended, or left alone to make it that width.
1250 APInt zextOrSelf(unsigned width) const;
1251
1252 /// @}
1253 /// \name Bit Manipulation Operators
1254 /// @{
1255
1256 /// Set every bit to 1.
1257 void setAllBits() {
1258 if (isSingleWord())
1259 U.VAL = WORDTYPE_MAX;
1260 else
1261 // Set all the bits in all the words.
1262 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1263 // Clear the unused ones
1264 clearUnusedBits();
1265 }
1266
1267 /// Set the given bit to 1 whose position is given as "bitPosition".
1268 void setBit(unsigned BitPosition) {
1269 assert(BitPosition < BitWidth && "BitPosition out of range")(static_cast <bool> (BitPosition < BitWidth &&
"BitPosition out of range") ? void (0) : __assert_fail ("BitPosition < BitWidth && \"BitPosition out of range\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1269, __extension__ __PRETTY_FUNCTION__))
;
1270 WordType Mask = maskBit(BitPosition);
1271 if (isSingleWord())
1272 U.VAL |= Mask;
1273 else
1274 U.pVal[whichWord(BitPosition)] |= Mask;
1275 }
1276
1277 /// Set the sign bit to 1.
1278 void setSignBit() { setBit(BitWidth - 1); }
1279
1280 /// Set a given bit to a given value.
1281 void setBitVal(unsigned BitPosition, bool BitValue) {
1282 if (BitValue)
1283 setBit(BitPosition);
1284 else
1285 clearBit(BitPosition);
1286 }
1287
1288 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1289 /// This function handles "wrap" case when \p loBit >= \p hiBit, and calls
1290 /// setBits when \p loBit < \p hiBit.
1291 /// For \p loBit == \p hiBit wrap case, set every bit to 1.
1292 void setBitsWithWrap(unsigned loBit, unsigned hiBit) {
1293 assert(hiBit <= BitWidth && "hiBit out of range")(static_cast <bool> (hiBit <= BitWidth && "hiBit out of range"
) ? void (0) : __assert_fail ("hiBit <= BitWidth && \"hiBit out of range\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1293, __extension__ __PRETTY_FUNCTION__))
;
1294 assert(loBit <= BitWidth && "loBit out of range")(static_cast <bool> (loBit <= BitWidth && "loBit out of range"
) ? void (0) : __assert_fail ("loBit <= BitWidth && \"loBit out of range\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1294, __extension__ __PRETTY_FUNCTION__))
;
1295 if (loBit < hiBit) {
1296 setBits(loBit, hiBit);
1297 return;
1298 }
1299 setLowBits(hiBit);
1300 setHighBits(BitWidth - loBit);
1301 }
1302
1303 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1304 /// This function handles case when \p loBit <= \p hiBit.
1305 void setBits(unsigned loBit, unsigned hiBit) {
1306 assert(hiBit <= BitWidth && "hiBit out of range")(static_cast <bool> (hiBit <= BitWidth && "hiBit out of range"
) ? void (0) : __assert_fail ("hiBit <= BitWidth && \"hiBit out of range\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1306, __extension__ __PRETTY_FUNCTION__))
;
1307 assert(loBit <= BitWidth && "loBit out of range")(static_cast <bool> (loBit <= BitWidth && "loBit out of range"
) ? void (0) : __assert_fail ("loBit <= BitWidth && \"loBit out of range\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1307, __extension__ __PRETTY_FUNCTION__))
;
1308 assert(loBit <= hiBit && "loBit greater than hiBit")(static_cast <bool> (loBit <= hiBit && "loBit greater than hiBit"
) ? void (0) : __assert_fail ("loBit <= hiBit && \"loBit greater than hiBit\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1308, __extension__ __PRETTY_FUNCTION__))
;
1309 if (loBit == hiBit)
1310 return;
1311 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1312 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1313 mask <<= loBit;
1314 if (isSingleWord())
1315 U.VAL |= mask;
1316 else
1317 U.pVal[0] |= mask;
1318 } else {
1319 setBitsSlowCase(loBit, hiBit);
1320 }
1321 }
1322
1323 /// Set the top bits starting from loBit.
1324 void setBitsFrom(unsigned loBit) { return setBits(loBit, BitWidth); }
1325
1326 /// Set the bottom loBits bits.
1327 void setLowBits(unsigned loBits) { return setBits(0, loBits); }
1328
1329 /// Set the top hiBits bits.
1330 void setHighBits(unsigned hiBits) {
1331 return setBits(BitWidth - hiBits, BitWidth);
1332 }
1333
1334 /// Set every bit to 0.
1335 void clearAllBits() {
1336 if (isSingleWord())
1337 U.VAL = 0;
1338 else
1339 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1340 }
1341
1342 /// Set a given bit to 0.
1343 ///
1344 /// Set the given bit to 0 whose position is given as "bitPosition".
1345 void clearBit(unsigned BitPosition) {
1346 assert(BitPosition < BitWidth && "BitPosition out of range")(static_cast <bool> (BitPosition < BitWidth &&
"BitPosition out of range") ? void (0) : __assert_fail ("BitPosition < BitWidth && \"BitPosition out of range\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1346, __extension__ __PRETTY_FUNCTION__))
;
1347 WordType Mask = ~maskBit(BitPosition);
1348 if (isSingleWord())
1349 U.VAL &= Mask;
1350 else
1351 U.pVal[whichWord(BitPosition)] &= Mask;
1352 }
1353
1354 /// Set bottom loBits bits to 0.
1355 void clearLowBits(unsigned loBits) {
1356 assert(loBits <= BitWidth && "More bits than bitwidth")(static_cast <bool> (loBits <= BitWidth && "More bits than bitwidth"
) ? void (0) : __assert_fail ("loBits <= BitWidth && \"More bits than bitwidth\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1356, __extension__ __PRETTY_FUNCTION__))
;
1357 APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits);
1358 *this &= Keep;
1359 }
1360
1361 /// Set the sign bit to 0.
1362 void clearSignBit() { clearBit(BitWidth - 1); }
1363
1364 /// Toggle every bit to its opposite value.
1365 void flipAllBits() {
1366 if (isSingleWord()) {
50
Taking false branch
1367 U.VAL ^= WORDTYPE_MAX;
1368 clearUnusedBits();
1369 } else {
1370 flipAllBitsSlowCase();
51
Calling 'APInt::flipAllBitsSlowCase'
1371 }
1372 }
1373
1374 /// Toggles a given bit to its opposite value.
1375 ///
1376 /// Toggle a given bit to its opposite value whose position is given
1377 /// as "bitPosition".
1378 void flipBit(unsigned bitPosition);
1379
1380 /// Negate this APInt in place.
1381 void negate() {
1382 flipAllBits();
49
Calling 'APInt::flipAllBits'
1383 ++(*this);
1384 }
1385
1386 /// Insert the bits from a smaller APInt starting at bitPosition.
1387 void insertBits(const APInt &SubBits, unsigned bitPosition);
1388 void insertBits(uint64_t SubBits, unsigned bitPosition, unsigned numBits);
1389
1390 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1391 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1392 uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const;
1393
1394 /// @}
1395 /// \name Value Characterization Functions
1396 /// @{
1397
1398 /// Return the number of bits in the APInt.
1399 unsigned getBitWidth() const { return BitWidth; }
1400
1401 /// Get the number of words.
1402 ///
1403 /// Here one word's bitwidth equals to that of uint64_t.
1404 ///
1405 /// \returns the number of words to hold the integer value of this APInt.
1406 unsigned getNumWords() const { return getNumWords(BitWidth); }
1407
1408 /// Get the number of words.
1409 ///
1410 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1411 ///
1412 /// \returns the number of words to hold the integer value with a given bit
1413 /// width.
1414 static unsigned getNumWords(unsigned BitWidth) {
1415 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1416 }
1417
1418 /// Compute the number of active bits in the value
1419 ///
1420 /// This function returns the number of active bits which is defined as the
1421 /// bit width minus the number of leading zeros. This is used in several
1422 /// computations to see how "wide" the value is.
1423 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1424
1425 /// Compute the number of active words in the value of this APInt.
1426 ///
1427 /// This is used in conjunction with getActiveData to extract the raw value of
1428 /// the APInt.
1429 unsigned getActiveWords() const {
1430 unsigned numActiveBits = getActiveBits();
1431 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1432 }
1433
1434 /// Get the minimum bit size for this signed APInt
1435 ///
1436 /// Computes the minimum bit width for this APInt while considering it to be a
1437 /// signed (and probably negative) value. If the value is not negative, this
1438 /// function returns the same value as getActiveBits()+1. Otherwise, it
1439 /// returns the smallest bit width that will retain the negative value. For
1440 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1441 /// for -1, this function will always return 1.
1442 unsigned getMinSignedBits() const { return BitWidth - getNumSignBits() + 1; }
1443
1444 /// Get zero extended value
1445 ///
1446 /// This method attempts to return the value of this APInt as a zero extended
1447 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1448 /// uint64_t. Otherwise an assertion will result.
1449 uint64_t getZExtValue() const {
1450 if (isSingleWord()) {
1451 assert(BitWidth && "zero width values not allowed")(static_cast <bool> (BitWidth && "zero width values not allowed"
) ? void (0) : __assert_fail ("BitWidth && \"zero width values not allowed\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1451, __extension__ __PRETTY_FUNCTION__))
;
1452 return U.VAL;
1453 }
1454 assert(getActiveBits() <= 64 && "Too many bits for uint64_t")(static_cast <bool> (getActiveBits() <= 64 &&
"Too many bits for uint64_t") ? void (0) : __assert_fail ("getActiveBits() <= 64 && \"Too many bits for uint64_t\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1454, __extension__ __PRETTY_FUNCTION__))
;
1455 return U.pVal[0];
1456 }
1457
1458 /// Get sign extended value
1459 ///
1460 /// This method attempts to return the value of this APInt as a sign extended
1461 /// int64_t. The bit width must be <= 64 or the value must fit within an
1462 /// int64_t. Otherwise an assertion will result.
1463 int64_t getSExtValue() const {
1464 if (isSingleWord())
1465 return SignExtend64(U.VAL, BitWidth);
1466 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t")(static_cast <bool> (getMinSignedBits() <= 64 &&
"Too many bits for int64_t") ? void (0) : __assert_fail ("getMinSignedBits() <= 64 && \"Too many bits for int64_t\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/APInt.h"
, 1466, __extension__ __PRETTY_FUNCTION__))
;
1467 return int64_t(U.pVal[0]);
1468 }
1469
1470 /// Get bits required for string value.
1471 ///
1472 /// This method determines how many bits are required to hold the APInt
1473 /// equivalent of the string given by \p str.
1474 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1475
1476 /// The APInt version of the countLeadingZeros functions in
1477 /// MathExtras.h.
1478 ///
1479 /// It counts the number of zeros from the most significant bit to the first
1480 /// one bit.
1481 ///
1482 /// \returns BitWidth if the value is zero, otherwise returns the number of
1483 /// zeros from the most significant bit to the first one bits.
1484 unsigned countLeadingZeros() const {
1485 if (isSingleWord()) {
1486 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1487 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1488 }
1489 return countLeadingZerosSlowCase();
1490 }
1491
1492 /// Count the number of leading one bits.
1493 ///
1494 /// This function is an APInt version of the countLeadingOnes
1495 /// functions in MathExtras.h. It counts the number of ones from the most
1496 /// significant bit to the first zero bit.
1497 ///
1498 /// \returns 0 if the high order bit is not set, otherwise returns the number
1499 /// of 1 bits from the most significant to the least
1500 unsigned countLeadingOnes() const {
1501 if (isSingleWord()) {
1502 if (LLVM_UNLIKELY(BitWidth == 0)__builtin_expect((bool)(BitWidth == 0), false))
1503 return 0;
1504 return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1505 }
1506 return countLeadingOnesSlowCase();
1507 }
1508
1509 /// Computes the number of leading bits of this APInt that are equal to its
1510 /// sign bit.
1511 unsigned getNumSignBits() const {
1512 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1513 }
1514
1515 /// Count the number of trailing zero bits.
1516 ///
1517 /// This function is an APInt version of the countTrailingZeros
1518 /// functions in MathExtras.h. It counts the number of zeros from the least
1519 /// significant bit to the first set bit.
1520 ///
1521 /// \returns BitWidth if the value is zero, otherwise returns the number of
1522 /// zeros from the least significant bit to the first one bit.
1523 unsigned countTrailingZeros() const {
1524 if (isSingleWord()) {
1525 unsigned TrailingZeros = llvm::countTrailingZeros(U.VAL);
1526 return (TrailingZeros > BitWidth ? BitWidth : TrailingZeros);
1527 }
1528 return countTrailingZerosSlowCase();
1529 }
1530
1531 /// Count the number of trailing one bits.
1532 ///
1533 /// This function is an APInt version of the countTrailingOnes
1534 /// functions in MathExtras.h. It counts the number of ones from the least
1535 /// significant bit to the first zero bit.
1536 ///
1537 /// \returns BitWidth if the value is all ones, otherwise returns the number
1538 /// of ones from the least significant bit to the first zero bit.
1539 unsigned countTrailingOnes() const {
1540 if (isSingleWord())
1541 return llvm::countTrailingOnes(U.VAL);
1542 return countTrailingOnesSlowCase();
1543 }
1544
1545 /// Count the number of bits set.
1546 ///
1547 /// This function is an APInt version of the countPopulation functions
1548 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1549 ///
1550 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1551 unsigned countPopulation() const {
1552 if (isSingleWord())
1553 return llvm::countPopulation(U.VAL);
1554 return countPopulationSlowCase();
1555 }
1556
1557 /// @}
1558 /// \name Conversion Functions
1559 /// @{
1560 void print(raw_ostream &OS, bool isSigned) const;
1561
1562 /// Converts an APInt to a string and append it to Str. Str is commonly a
1563 /// SmallString.
1564 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1565 bool formatAsCLiteral = false) const;
1566
1567 /// Considers the APInt to be unsigned and converts it into a string in the
1568 /// radix given. The radix can be 2, 8, 10 16, or 36.
1569 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1570 toString(Str, Radix, false, false);
1571 }
1572
1573 /// Considers the APInt to be signed and converts it into a string in the
1574 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1575 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1576 toString(Str, Radix, true, false);
1577 }
1578
1579 /// \returns a byte-swapped representation of this APInt Value.
1580 APInt byteSwap() const;
1581
1582 /// \returns the value with the bit representation reversed of this APInt
1583 /// Value.
1584 APInt reverseBits() const;
1585
1586 /// Converts this APInt to a double value.
1587 double roundToDouble(bool isSigned) const;
1588
1589 /// Converts this unsigned APInt to a double value.
1590 double roundToDouble() const { return roundToDouble(false); }
1591
1592 /// Converts this signed APInt to a double value.
1593 double signedRoundToDouble() const { return roundToDouble(true); }
1594
1595 /// Converts APInt bits to a double
1596 ///
1597 /// The conversion does not do a translation from integer to double, it just
1598 /// re-interprets the bits as a double. Note that it is valid to do this on
1599 /// any bit width. Exactly 64 bits will be translated.
1600 double bitsToDouble() const { return BitsToDouble(getWord(0)); }
1601
1602 /// Converts APInt bits to a float
1603 ///
1604 /// The conversion does not do a translation from integer to float, it just
1605 /// re-interprets the bits as a float. Note that it is valid to do this on
1606 /// any bit width. Exactly 32 bits will be translated.
1607 float bitsToFloat() const {
1608 return BitsToFloat(static_cast<uint32_t>(getWord(0)));
1609 }
1610
1611 /// Converts a double to APInt bits.
1612 ///
1613 /// The conversion does not do a translation from double to integer, it just
1614 /// re-interprets the bits of the double.
1615 static APInt doubleToBits(double V) {
1616 return APInt(sizeof(double) * CHAR_BIT8, DoubleToBits(V));
1617 }
1618
1619 /// Converts a float to APInt bits.
1620 ///
1621 /// The conversion does not do a translation from float to integer, it just
1622 /// re-interprets the bits of the float.
1623 static APInt floatToBits(float V) {
1624 return APInt(sizeof(float) * CHAR_BIT8, FloatToBits(V));
1625 }
1626
1627 /// @}
1628 /// \name Mathematics Operations
1629 /// @{
1630
1631 /// \returns the floor log base 2 of this APInt.
1632 unsigned logBase2() const { return getActiveBits() - 1; }
1633
1634 /// \returns the ceil log base 2 of this APInt.
1635 unsigned ceilLogBase2() const {
1636 APInt temp(*this);
1637 --temp;
1638 return temp.getActiveBits();
1639 }
1640
1641 /// \returns the nearest log base 2 of this APInt. Ties round up.
1642 ///
1643 /// NOTE: When we have a BitWidth of 1, we define:
1644 ///
1645 /// log2(0) = UINT32_MAX
1646 /// log2(1) = 0
1647 ///
1648 /// to get around any mathematical concerns resulting from
1649 /// referencing 2 in a space where 2 does no exist.
1650 unsigned nearestLogBase2() const;
1651
1652 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1653 /// otherwise
1654 int32_t exactLogBase2() const {
1655 if (!isPowerOf2())
1656 return -1;
1657 return logBase2();
1658 }
1659
1660 /// Compute the square root.
1661 APInt sqrt() const;
1662
1663 /// Get the absolute value. If *this is < 0 then return -(*this), otherwise
1664 /// *this. Note that the "most negative" signed number (e.g. -128 for 8 bit
1665 /// wide APInt) is unchanged due to how negation works.
1666 APInt abs() const {
1667 if (isNegative())
1668 return -(*this);
1669 return *this;
1670 }
1671
1672 /// \returns the multiplicative inverse for a given modulo.
1673 APInt multiplicativeInverse(const APInt &modulo) const;
1674
1675 /// @}
1676 /// \name Building-block Operations for APInt and APFloat
1677 /// @{
1678
1679 // These building block operations operate on a representation of arbitrary
1680 // precision, two's-complement, bignum integer values. They should be
1681 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1682 // generally a pointer to the base of an array of integer parts, representing
1683 // an unsigned bignum, and a count of how many parts there are.
1684
1685 /// Sets the least significant part of a bignum to the input value, and zeroes
1686 /// out higher parts.
1687 static void tcSet(WordType *, WordType, unsigned);
1688
1689 /// Assign one bignum to another.
1690 static void tcAssign(WordType *, const WordType *, unsigned);
1691
1692 /// Returns true if a bignum is zero, false otherwise.
1693 static bool tcIsZero(const WordType *, unsigned);
1694
1695 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1696 static int tcExtractBit(const WordType *, unsigned bit);
1697
1698 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1699 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1700 /// significant bit of DST. All high bits above srcBITS in DST are
1701 /// zero-filled.
1702 static void tcExtract(WordType *, unsigned dstCount, const WordType *,
1703 unsigned srcBits, unsigned srcLSB);
1704
1705 /// Set the given bit of a bignum. Zero-based.
1706 static void tcSetBit(WordType *, unsigned bit);
1707
1708 /// Clear the given bit of a bignum. Zero-based.
1709 static void tcClearBit(WordType *, unsigned bit);
1710
1711 /// Returns the bit number of the least or most significant set bit of a
1712 /// number. If the input number has no bits set -1U is returned.
1713 static unsigned tcLSB(const WordType *, unsigned n);
1714 static unsigned tcMSB(const WordType *parts, unsigned n);
1715
1716 /// Negate a bignum in-place.
1717 static void tcNegate(WordType *, unsigned);
1718
1719 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1720 static WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned);
1721 /// DST += RHS. Returns the carry flag.
1722 static WordType tcAddPart(WordType *, WordType, unsigned);
1723
1724 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1725 static WordType tcSubtract(WordType *, const WordType *, WordType carry,
1726 unsigned);
1727 /// DST -= RHS. Returns the carry flag.
1728 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1729
1730 /// DST += SRC * MULTIPLIER + PART if add is true
1731 /// DST = SRC * MULTIPLIER + PART if add is false
1732 ///
1733 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1734 /// start at the same point, i.e. DST == SRC.
1735 ///
1736 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1737 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1738 /// result, and if all of the omitted higher parts were zero return zero,
1739 /// otherwise overflow occurred and return one.
1740 static int tcMultiplyPart(WordType *dst, const WordType *src,
1741 WordType multiplier, WordType carry,
1742 unsigned srcParts, unsigned dstParts, bool add);
1743
1744 /// DST = LHS * RHS, where DST has the same width as the operands and is
1745 /// filled with the least significant parts of the result. Returns one if
1746 /// overflow occurred, otherwise zero. DST must be disjoint from both
1747 /// operands.
1748 static int tcMultiply(WordType *, const WordType *, const WordType *,
1749 unsigned);
1750
1751 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1752 /// operands. No overflow occurs. DST must be disjoint from both operands.
1753 static void tcFullMultiply(WordType *, const WordType *, const WordType *,
1754 unsigned, unsigned);
1755
1756 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1757 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1758 /// REMAINDER to the remainder, return zero. i.e.
1759 ///
1760 /// OLD_LHS = RHS * LHS + REMAINDER
1761 ///
1762 /// SCRATCH is a bignum of the same size as the operands and result for use by
1763 /// the routine; its contents need not be initialized and are destroyed. LHS,
1764 /// REMAINDER and SCRATCH must be distinct.
1765 static int tcDivide(WordType *lhs, const WordType *rhs, WordType *remainder,
1766 WordType *scratch, unsigned parts);
1767
1768 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1769 /// restrictions on Count.
1770 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1771
1772 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1773 /// restrictions on Count.
1774 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1775
1776 /// Comparison (unsigned) of two bignums.
1777 static int tcCompare(const WordType *, const WordType *, unsigned);
1778
1779 /// Increment a bignum in-place. Return the carry flag.
1780 static WordType tcIncrement(WordType *dst, unsigned parts) {
1781 return tcAddPart(dst, 1, parts);
1782 }
1783
1784 /// Decrement a bignum in-place. Return the borrow flag.
1785 static WordType tcDecrement(WordType *dst, unsigned parts) {
1786 return tcSubtractPart(dst, 1, parts);
1787 }
1788
1789 /// Used to insert APInt objects, or objects that contain APInt objects, into
1790 /// FoldingSets.
1791 void Profile(FoldingSetNodeID &id) const;
1792
1793 /// debug method
1794 void dump() const;
1795
1796 /// Returns whether this instance allocated memory.
1797 bool needsCleanup() const { return !isSingleWord(); }
1798
1799private:
1800 /// This union is used to store the integer value. When the
1801 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
1802 union {
1803 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1804 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1805 } U;
1806
1807 unsigned BitWidth; ///< The number of bits in this APInt.
1808
1809 friend struct DenseMapInfo<APInt>;
1810 friend class APSInt;
1811
1812 /// This constructor is used only internally for speed of construction of
1813 /// temporaries. It is unsafe since it takes ownership of the pointer, so it
1814 /// is not public.
1815 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) { U.pVal = val; }
1816
1817 /// Determine which word a bit is in.
1818 ///
1819 /// \returns the word position for the specified bit position.
1820 static unsigned whichWord(unsigned bitPosition) {
1821 return bitPosition / APINT_BITS_PER_WORD;
1822 }
1823
1824 /// Determine which bit in a word the specified bit position is in.
1825 static unsigned whichBit(unsigned bitPosition) {
1826 return bitPosition % APINT_BITS_PER_WORD;
1827 }
1828
1829 /// Get a single bit mask.
1830 ///
1831 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
1832 /// This method generates and returns a uint64_t (word) mask for a single
1833 /// bit at a specific bit position. This is used to mask the bit in the
1834 /// corresponding word.
1835 static uint64_t maskBit(unsigned bitPosition) {
1836 return 1ULL << whichBit(bitPosition);
1837 }
1838
1839 /// Clear unused high order bits
1840 ///
1841 /// This method is used internally to clear the top "N" bits in the high order
1842 /// word that are not used by the APInt. This is needed after the most
1843 /// significant word is assigned a value to ensure that those bits are
1844 /// zero'd out.
1845 APInt &clearUnusedBits() {
1846 // Compute how many bits are used in the final word.
1847 unsigned WordBits = ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1;
1848
1849 // Mask out the high bits.
1850 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - WordBits);
1851 if (LLVM_UNLIKELY(BitWidth == 0)__builtin_expect((bool)(BitWidth == 0), false))
53
Taking false branch
1852 mask = 0;
1853
1854 if (isSingleWord())
54
Taking false branch
1855 U.VAL &= mask;
1856 else
1857 U.pVal[getNumWords() - 1] &= mask;
55
Use of memory allocated with size zero
1858 return *this;
1859 }
1860
1861 /// Get the word corresponding to a bit position
1862 /// \returns the corresponding word for the specified bit position.
1863 uint64_t getWord(unsigned bitPosition) const {
1864 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
1865 }
1866
1867 /// Utility method to change the bit width of this APInt to new bit width,
1868 /// allocating and/or deallocating as necessary. There is no guarantee on the
1869 /// value of any bits upon return. Caller should populate the bits after.
1870 void reallocate(unsigned NewBitWidth);
1871
1872 /// Convert a char array into an APInt
1873 ///
1874 /// \param radix 2, 8, 10, 16, or 36
1875 /// Converts a string into a number. The string must be non-empty
1876 /// and well-formed as a number of the given base. The bit-width
1877 /// must be sufficient to hold the result.
1878 ///
1879 /// This is used by the constructors that take string arguments.
1880 ///
1881 /// StringRef::getAsInteger is superficially similar but (1) does
1882 /// not assume that the string is well-formed and (2) grows the
1883 /// result to hold the input.
1884 void fromString(unsigned numBits, StringRef str, uint8_t radix);
1885
1886 /// An internal division function for dividing APInts.
1887 ///
1888 /// This is used by the toString method to divide by the radix. It simply
1889 /// provides a more convenient form of divide for internal use since KnuthDiv
1890 /// has specific constraints on its inputs. If those constraints are not met
1891 /// then it provides a simpler form of divide.
1892 static void divide(const WordType *LHS, unsigned lhsWords,
1893 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
1894 WordType *Remainder);
1895
1896 /// out-of-line slow case for inline constructor
1897 void initSlowCase(uint64_t val, bool isSigned);
1898
1899 /// shared code between two array constructors
1900 void initFromArray(ArrayRef<uint64_t> array);
1901
1902 /// out-of-line slow case for inline copy constructor
1903 void initSlowCase(const APInt &that);
1904
1905 /// out-of-line slow case for shl
1906 void shlSlowCase(unsigned ShiftAmt);
1907
1908 /// out-of-line slow case for lshr.
1909 void lshrSlowCase(unsigned ShiftAmt);
1910
1911 /// out-of-line slow case for ashr.
1912 void ashrSlowCase(unsigned ShiftAmt);
1913
1914 /// out-of-line slow case for operator=
1915 void assignSlowCase(const APInt &RHS);
1916
1917 /// out-of-line slow case for operator==
1918 bool equalSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
1919
1920 /// out-of-line slow case for countLeadingZeros
1921 unsigned countLeadingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__));
1922
1923 /// out-of-line slow case for countLeadingOnes.
1924 unsigned countLeadingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__));
1925
1926 /// out-of-line slow case for countTrailingZeros.
1927 unsigned countTrailingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__));
1928
1929 /// out-of-line slow case for countTrailingOnes
1930 unsigned countTrailingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__));
1931
1932 /// out-of-line slow case for countPopulation
1933 unsigned countPopulationSlowCase() const LLVM_READONLY__attribute__((__pure__));
1934
1935 /// out-of-line slow case for intersects.
1936 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
1937
1938 /// out-of-line slow case for isSubsetOf.
1939 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
1940
1941 /// out-of-line slow case for setBits.
1942 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
1943
1944 /// out-of-line slow case for flipAllBits.
1945 void flipAllBitsSlowCase();
1946
1947 /// out-of-line slow case for concat.
1948 APInt concatSlowCase(const APInt &NewLSB) const;
1949
1950 /// out-of-line slow case for operator&=.
1951 void andAssignSlowCase(const APInt &RHS);
1952
1953 /// out-of-line slow case for operator|=.
1954 void orAssignSlowCase(const APInt &RHS);
1955
1956 /// out-of-line slow case for operator^=.
1957 void xorAssignSlowCase(const APInt &RHS);
1958
1959 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
1960 /// to, or greater than RHS.
1961 int compare(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
1962
1963 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
1964 /// to, or greater than RHS.
1965 int compareSigned(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
1966
1967 /// @}
1968};
1969
1970inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1971
1972inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1973
1974/// Unary bitwise complement operator.
1975///
1976/// \returns an APInt that is the bitwise complement of \p v.
1977inline APInt operator~(APInt v) {
1978 v.flipAllBits();
1979 return v;
1980}
1981
1982inline APInt operator&(APInt a, const APInt &b) {
1983 a &= b;
1984 return a;
1985}
1986
1987inline APInt operator&(const APInt &a, APInt &&b) {
1988 b &= a;
1989 return std::move(b);
1990}
1991
1992inline APInt operator&(APInt a, uint64_t RHS) {
1993 a &= RHS;
1994 return a;
1995}
1996
1997inline APInt operator&(uint64_t LHS, APInt b) {
1998 b &= LHS;
1999 return b;
2000}
2001
2002inline APInt operator|(APInt a, const APInt &b) {
2003 a |= b;
2004 return a;
2005}
2006
2007inline APInt operator|(const APInt &a, APInt &&b) {
2008 b |= a;
2009 return std::move(b);
2010}
2011
2012inline APInt operator|(APInt a, uint64_t RHS) {
2013 a |= RHS;
2014 return a;
2015}
2016
2017inline APInt operator|(uint64_t LHS, APInt b) {
2018 b |= LHS;
2019 return b;
2020}
2021
2022inline APInt operator^(APInt a, const APInt &b) {
2023 a ^= b;
2024 return a;
2025}
2026
2027inline APInt operator^(const APInt &a, APInt &&b) {
2028 b ^= a;
2029 return std::move(b);
2030}
2031
2032inline APInt operator^(APInt a, uint64_t RHS) {
2033 a ^= RHS;
2034 return a;
2035}
2036
2037inline APInt operator^(uint64_t LHS, APInt b) {
2038 b ^= LHS;
2039 return b;
2040}
2041
2042inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
2043 I.print(OS, true);
32
Calling 'APInt::print'
2044 return OS;
2045}
2046
2047inline APInt operator-(APInt v) {
2048 v.negate();
2049 return v;
2050}
2051
2052inline APInt operator+(APInt a, const APInt &b) {
2053 a += b;
2054 return a;
2055}
2056
2057inline APInt operator+(const APInt &a, APInt &&b) {
2058 b += a;
2059 return std::move(b);
2060}
2061
2062inline APInt operator+(APInt a, uint64_t RHS) {
2063 a += RHS;
2064 return a;
2065}
2066
2067inline APInt operator+(uint64_t LHS, APInt b) {
2068 b += LHS;
2069 return b;
2070}
2071
2072inline APInt operator-(APInt a, const APInt &b) {
2073 a -= b;
2074 return a;
2075}
2076
2077inline APInt operator-(const APInt &a, APInt &&b) {
2078 b.negate();
2079 b += a;
2080 return std::move(b);
2081}
2082
2083inline APInt operator-(APInt a, uint64_t RHS) {
2084 a -= RHS;
2085 return a;
2086}
2087
2088inline APInt operator-(uint64_t LHS, APInt b) {
2089 b.negate();
2090 b += LHS;
2091 return b;
2092}
2093
2094inline APInt operator*(APInt a, uint64_t RHS) {
2095 a *= RHS;
2096 return a;
2097}
2098
2099inline APInt operator*(uint64_t LHS, APInt b) {
2100 b *= LHS;
2101 return b;
2102}
2103
2104namespace APIntOps {
2105
2106/// Determine the smaller of two APInts considered to be signed.
2107inline const APInt &smin(const APInt &A, const APInt &B) {
2108 return A.slt(B) ? A : B;
2109}
2110
2111/// Determine the larger of two APInts considered to be signed.
2112inline const APInt &smax(const APInt &A, const APInt &B) {
2113 return A.sgt(B) ? A : B;
2114}
2115
2116/// Determine the smaller of two APInts considered to be unsigned.
2117inline const APInt &umin(const APInt &A, const APInt &B) {
2118 return A.ult(B) ? A : B;
2119}
2120
2121/// Determine the larger of two APInts considered to be unsigned.
2122inline const APInt &umax(const APInt &A, const APInt &B) {
2123 return A.ugt(B) ? A : B;
2124}
2125
2126/// Compute GCD of two unsigned APInt values.
2127///
2128/// This function returns the greatest common divisor of the two APInt values
2129/// using Stein's algorithm.
2130///
2131/// \returns the greatest common divisor of A and B.
2132APInt GreatestCommonDivisor(APInt A, APInt B);
2133
2134/// Converts the given APInt to a double value.
2135///
2136/// Treats the APInt as an unsigned value for conversion purposes.
2137inline double RoundAPIntToDouble(const APInt &APIVal) {
2138 return APIVal.roundToDouble();
2139}
2140
2141/// Converts the given APInt to a double value.
2142///
2143/// Treats the APInt as a signed value for conversion purposes.
2144inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2145 return APIVal.signedRoundToDouble();
2146}
2147
2148/// Converts the given APInt to a float value.
2149inline float RoundAPIntToFloat(const APInt &APIVal) {
2150 return float(RoundAPIntToDouble(APIVal));
2151}
2152
2153/// Converts the given APInt to a float value.
2154///
2155/// Treats the APInt as a signed value for conversion purposes.
2156inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2157 return float(APIVal.signedRoundToDouble());
2158}
2159
2160/// Converts the given double value into a APInt.
2161///
2162/// This function convert a double value to an APInt value.
2163APInt RoundDoubleToAPInt(double Double, unsigned width);
2164
2165/// Converts a float value into a APInt.
2166///
2167/// Converts a float value into an APInt value.
2168inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2169 return RoundDoubleToAPInt(double(Float), width);
2170}
2171
2172/// Return A unsign-divided by B, rounded by the given rounding mode.
2173APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2174
2175/// Return A sign-divided by B, rounded by the given rounding mode.
2176APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2177
2178/// Let q(n) = An^2 + Bn + C, and BW = bit width of the value range
2179/// (e.g. 32 for i32).
2180/// This function finds the smallest number n, such that
2181/// (a) n >= 0 and q(n) = 0, or
2182/// (b) n >= 1 and q(n-1) and q(n), when evaluated in the set of all
2183/// integers, belong to two different intervals [Rk, Rk+R),
2184/// where R = 2^BW, and k is an integer.
2185/// The idea here is to find when q(n) "overflows" 2^BW, while at the
2186/// same time "allowing" subtraction. In unsigned modulo arithmetic a
2187/// subtraction (treated as addition of negated numbers) would always
2188/// count as an overflow, but here we want to allow values to decrease
2189/// and increase as long as they are within the same interval.
2190/// Specifically, adding of two negative numbers should not cause an
2191/// overflow (as long as the magnitude does not exceed the bit width).
2192/// On the other hand, given a positive number, adding a negative
2193/// number to it can give a negative result, which would cause the
2194/// value to go from [-2^BW, 0) to [0, 2^BW). In that sense, zero is
2195/// treated as a special case of an overflow.
2196///
2197/// This function returns None if after finding k that minimizes the
2198/// positive solution to q(n) = kR, both solutions are contained between
2199/// two consecutive integers.
2200///
2201/// There are cases where q(n) > T, and q(n+1) < T (assuming evaluation
2202/// in arithmetic modulo 2^BW, and treating the values as signed) by the
2203/// virtue of *signed* overflow. This function will *not* find such an n,
2204/// however it may find a value of n satisfying the inequalities due to
2205/// an *unsigned* overflow (if the values are treated as unsigned).
2206/// To find a solution for a signed overflow, treat it as a problem of
2207/// finding an unsigned overflow with a range with of BW-1.
2208///
2209/// The returned value may have a different bit width from the input
2210/// coefficients.
2211Optional<APInt> SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
2212 unsigned RangeWidth);
2213
2214/// Compare two values, and if they are different, return the position of the
2215/// most significant bit that is different in the values.
2216Optional<unsigned> GetMostSignificantDifferentBit(const APInt &A,
2217 const APInt &B);
2218
2219/// Splat/Merge neighboring bits to widen/narrow the bitmask represented
2220/// by \param A to \param NewBitWidth bits.
2221///
2222/// e.g. ScaleBitMask(0b0101, 8) -> 0b00110011
2223/// e.g. ScaleBitMask(0b00011011, 4) -> 0b0111
2224/// A.getBitwidth() or NewBitWidth must be a whole multiples of the other.
2225///
2226/// TODO: Do we need a mode where all bits must be set when merging down?
2227APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth);
2228} // namespace APIntOps
2229
2230// See friend declaration above. This additional declaration is required in
2231// order to compile LLVM with IBM xlC compiler.
2232hash_code hash_value(const APInt &Arg);
2233
2234/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
2235/// with the integer held in IntVal.
2236void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, unsigned StoreBytes);
2237
2238/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
2239/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
2240void LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, unsigned LoadBytes);
2241
2242/// Provide DenseMapInfo for APInt.
2243template <> struct DenseMapInfo<APInt> {
2244 static inline APInt getEmptyKey() {
2245 APInt V(nullptr, 0);
2246 V.U.VAL = 0;
2247 return V;
2248 }
2249
2250 static inline APInt getTombstoneKey() {
2251 APInt V(nullptr, 0);
2252 V.U.VAL = 1;
2253 return V;
2254 }
2255
2256 static unsigned getHashValue(const APInt &Key);
2257
2258 static bool isEqual(const APInt &LHS, const APInt &RHS) {
2259 return LHS.getBitWidth() == RHS.getBitWidth() && LHS == RHS;
2260 }
2261};
2262
2263} // namespace llvm
2264
2265#endif