Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/Support/APInt.cpp
Warning:line 1442, column 22
The result of the right shift is undefined due to shifting by '32', which is greater or equal to the width of type 'uint32_t'

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 -ffp-contract=on -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-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.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-15~++20220420111733+e13d2efed663/llvm/lib/Support -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -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-15/lib/clang/15.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 -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -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-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -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-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/Support/APInt.cpp

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

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include/llvm/Support/MathExtras.h

1//===-- llvm/Support/MathExtras.h - Useful math functions -------*- 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// This file contains some functions that are useful for math stuff.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_MATHEXTRAS_H
14#define LLVM_SUPPORT_MATHEXTRAS_H
15
16#include "llvm/Support/Compiler.h"
17#include <cassert>
18#include <climits>
19#include <cmath>
20#include <cstdint>
21#include <cstring>
22#include <limits>
23#include <type_traits>
24
25#ifdef __ANDROID_NDK__
26#include <android/api-level.h>
27#endif
28
29#ifdef _MSC_VER
30// Declare these intrinsics manually rather including intrin.h. It's very
31// expensive, and MathExtras.h is popular.
32// #include <intrin.h>
33extern "C" {
34unsigned char _BitScanForward(unsigned long *_Index, unsigned long _Mask);
35unsigned char _BitScanForward64(unsigned long *_Index, unsigned __int64 _Mask);
36unsigned char _BitScanReverse(unsigned long *_Index, unsigned long _Mask);
37unsigned char _BitScanReverse64(unsigned long *_Index, unsigned __int64 _Mask);
38}
39#endif
40
41namespace llvm {
42
43/// The behavior an operation has on an input of 0.
44enum ZeroBehavior {
45 /// The returned value is undefined.
46 ZB_Undefined,
47 /// The returned value is numeric_limits<T>::max()
48 ZB_Max,
49 /// The returned value is numeric_limits<T>::digits
50 ZB_Width
51};
52
53/// Mathematical constants.
54namespace numbers {
55// TODO: Track C++20 std::numbers.
56// TODO: Favor using the hexadecimal FP constants (requires C++17).
57constexpr double e = 2.7182818284590452354, // (0x1.5bf0a8b145749P+1) https://oeis.org/A001113
58 egamma = .57721566490153286061, // (0x1.2788cfc6fb619P-1) https://oeis.org/A001620
59 ln2 = .69314718055994530942, // (0x1.62e42fefa39efP-1) https://oeis.org/A002162
60 ln10 = 2.3025850929940456840, // (0x1.24bb1bbb55516P+1) https://oeis.org/A002392
61 log2e = 1.4426950408889634074, // (0x1.71547652b82feP+0)
62 log10e = .43429448190325182765, // (0x1.bcb7b1526e50eP-2)
63 pi = 3.1415926535897932385, // (0x1.921fb54442d18P+1) https://oeis.org/A000796
64 inv_pi = .31830988618379067154, // (0x1.45f306bc9c883P-2) https://oeis.org/A049541
65 sqrtpi = 1.7724538509055160273, // (0x1.c5bf891b4ef6bP+0) https://oeis.org/A002161
66 inv_sqrtpi = .56418958354775628695, // (0x1.20dd750429b6dP-1) https://oeis.org/A087197
67 sqrt2 = 1.4142135623730950488, // (0x1.6a09e667f3bcdP+0) https://oeis.org/A00219
68 inv_sqrt2 = .70710678118654752440, // (0x1.6a09e667f3bcdP-1)
69 sqrt3 = 1.7320508075688772935, // (0x1.bb67ae8584caaP+0) https://oeis.org/A002194
70 inv_sqrt3 = .57735026918962576451, // (0x1.279a74590331cP-1)
71 phi = 1.6180339887498948482; // (0x1.9e3779b97f4a8P+0) https://oeis.org/A001622
72constexpr float ef = 2.71828183F, // (0x1.5bf0a8P+1) https://oeis.org/A001113
73 egammaf = .577215665F, // (0x1.2788d0P-1) https://oeis.org/A001620
74 ln2f = .693147181F, // (0x1.62e430P-1) https://oeis.org/A002162
75 ln10f = 2.30258509F, // (0x1.26bb1cP+1) https://oeis.org/A002392
76 log2ef = 1.44269504F, // (0x1.715476P+0)
77 log10ef = .434294482F, // (0x1.bcb7b2P-2)
78 pif = 3.14159265F, // (0x1.921fb6P+1) https://oeis.org/A000796
79 inv_pif = .318309886F, // (0x1.45f306P-2) https://oeis.org/A049541
80 sqrtpif = 1.77245385F, // (0x1.c5bf8aP+0) https://oeis.org/A002161
81 inv_sqrtpif = .564189584F, // (0x1.20dd76P-1) https://oeis.org/A087197
82 sqrt2f = 1.41421356F, // (0x1.6a09e6P+0) https://oeis.org/A002193
83 inv_sqrt2f = .707106781F, // (0x1.6a09e6P-1)
84 sqrt3f = 1.73205081F, // (0x1.bb67aeP+0) https://oeis.org/A002194
85 inv_sqrt3f = .577350269F, // (0x1.279a74P-1)
86 phif = 1.61803399F; // (0x1.9e377aP+0) https://oeis.org/A001622
87} // namespace numbers
88
89namespace detail {
90template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
91 static unsigned count(T Val, ZeroBehavior) {
92 if (!Val)
93 return std::numeric_limits<T>::digits;
94 if (Val & 0x1)
95 return 0;
96
97 // Bisection method.
98 unsigned ZeroBits = 0;
99 T Shift = std::numeric_limits<T>::digits >> 1;
100 T Mask = std::numeric_limits<T>::max() >> Shift;
101 while (Shift) {
102 if ((Val & Mask) == 0) {
103 Val >>= Shift;
104 ZeroBits |= Shift;
105 }
106 Shift >>= 1;
107 Mask >>= Shift;
108 }
109 return ZeroBits;
110 }
111};
112
113#if defined(__GNUC__4) || defined(_MSC_VER)
114template <typename T> struct TrailingZerosCounter<T, 4> {
115 static unsigned count(T Val, ZeroBehavior ZB) {
116 if (ZB != ZB_Undefined && Val == 0)
117 return 32;
118
119#if __has_builtin(__builtin_ctz)1 || defined(__GNUC__4)
120 return __builtin_ctz(Val);
121#elif defined(_MSC_VER)
122 unsigned long Index;
123 _BitScanForward(&Index, Val);
124 return Index;
125#endif
126 }
127};
128
129#if !defined(_MSC_VER) || defined(_M_X64)
130template <typename T> struct TrailingZerosCounter<T, 8> {
131 static unsigned count(T Val, ZeroBehavior ZB) {
132 if (ZB != ZB_Undefined && Val == 0)
133 return 64;
134
135#if __has_builtin(__builtin_ctzll)1 || defined(__GNUC__4)
136 return __builtin_ctzll(Val);
137#elif defined(_MSC_VER)
138 unsigned long Index;
139 _BitScanForward64(&Index, Val);
140 return Index;
141#endif
142 }
143};
144#endif
145#endif
146} // namespace detail
147
148/// Count number of 0's from the least significant bit to the most
149/// stopping at the first 1.
150///
151/// Only unsigned integral types are allowed.
152///
153/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
154/// valid arguments.
155template <typename T>
156unsigned countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
157 static_assert(std::numeric_limits<T>::is_integer &&
158 !std::numeric_limits<T>::is_signed,
159 "Only unsigned integral types are allowed.");
160 return llvm::detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
161}
162
163namespace detail {
164template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
165 static unsigned count(T Val, ZeroBehavior) {
166 if (!Val)
167 return std::numeric_limits<T>::digits;
168
169 // Bisection method.
170 unsigned ZeroBits = 0;
171 for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
172 T Tmp = Val >> Shift;
173 if (Tmp)
174 Val = Tmp;
175 else
176 ZeroBits |= Shift;
177 }
178 return ZeroBits;
179 }
180};
181
182#if defined(__GNUC__4) || defined(_MSC_VER)
183template <typename T> struct LeadingZerosCounter<T, 4> {
184 static unsigned count(T Val, ZeroBehavior ZB) {
185 if (ZB
20.1
'ZB' is not equal to ZB_Undefined
20.1
'ZB' is not equal to ZB_Undefined
!= ZB_Undefined && Val == 0)
21
Assuming 'Val' is equal to 0
22
Taking true branch
186 return 32;
23
Returning the value 32, which participates in a condition later
24
Returning the value 32
187
188#if __has_builtin(__builtin_clz)1 || defined(__GNUC__4)
189 return __builtin_clz(Val);
190#elif defined(_MSC_VER)
191 unsigned long Index;
192 _BitScanReverse(&Index, Val);
193 return Index ^ 31;
194#endif
195 }
196};
197
198#if !defined(_MSC_VER) || defined(_M_X64)
199template <typename T> struct LeadingZerosCounter<T, 8> {
200 static unsigned count(T Val, ZeroBehavior ZB) {
201 if (ZB != ZB_Undefined && Val == 0)
202 return 64;
203
204#if __has_builtin(__builtin_clzll)1 || defined(__GNUC__4)
205 return __builtin_clzll(Val);
206#elif defined(_MSC_VER)
207 unsigned long Index;
208 _BitScanReverse64(&Index, Val);
209 return Index ^ 63;
210#endif
211 }
212};
213#endif
214#endif
215} // namespace detail
216
217/// Count number of 0's from the most significant bit to the least
218/// stopping at the first 1.
219///
220/// Only unsigned integral types are allowed.
221///
222/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
223/// valid arguments.
224template <typename T>
225unsigned countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
226 static_assert(std::numeric_limits<T>::is_integer &&
227 !std::numeric_limits<T>::is_signed,
228 "Only unsigned integral types are allowed.");
229 return llvm::detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
20
Calling 'LeadingZerosCounter::count'
25
Returning from 'LeadingZerosCounter::count'
26
Returning the value 32, which participates in a condition later
27
Returning the value 32
230}
231
232/// Get the index of the first set bit starting from the least
233/// significant bit.
234///
235/// Only unsigned integral types are allowed.
236///
237/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
238/// valid arguments.
239template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
240 if (ZB == ZB_Max && Val == 0)
241 return std::numeric_limits<T>::max();
242
243 return countTrailingZeros(Val, ZB_Undefined);
244}
245
246/// Create a bitmask with the N right-most bits set to 1, and all other
247/// bits set to 0. Only unsigned types are allowed.
248template <typename T> T maskTrailingOnes(unsigned N) {
249 static_assert(std::is_unsigned<T>::value, "Invalid type!");
250 const unsigned Bits = CHAR_BIT8 * sizeof(T);
251 assert(N <= Bits && "Invalid bit index")(static_cast <bool> (N <= Bits && "Invalid bit index"
) ? void (0) : __assert_fail ("N <= Bits && \"Invalid bit index\""
, "llvm/include/llvm/Support/MathExtras.h", 251, __extension__
__PRETTY_FUNCTION__))
;
252 return N == 0 ? 0 : (T(-1) >> (Bits - N));
253}
254
255/// Create a bitmask with the N left-most bits set to 1, and all other
256/// bits set to 0. Only unsigned types are allowed.
257template <typename T> T maskLeadingOnes(unsigned N) {
258 return ~maskTrailingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
259}
260
261/// Create a bitmask with the N right-most bits set to 0, and all other
262/// bits set to 1. Only unsigned types are allowed.
263template <typename T> T maskTrailingZeros(unsigned N) {
264 return maskLeadingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
265}
266
267/// Create a bitmask with the N left-most bits set to 0, and all other
268/// bits set to 1. Only unsigned types are allowed.
269template <typename T> T maskLeadingZeros(unsigned N) {
270 return maskTrailingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
271}
272
273/// Get the index of the last set bit starting from the least
274/// significant bit.
275///
276/// Only unsigned integral types are allowed.
277///
278/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
279/// valid arguments.
280template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
281 if (ZB == ZB_Max && Val == 0)
282 return std::numeric_limits<T>::max();
283
284 // Use ^ instead of - because both gcc and llvm can remove the associated ^
285 // in the __builtin_clz intrinsic on x86.
286 return countLeadingZeros(Val, ZB_Undefined) ^
287 (std::numeric_limits<T>::digits - 1);
288}
289
290/// Macro compressed bit reversal table for 256 bits.
291///
292/// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
293static const unsigned char BitReverseTable256[256] = {
294#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
295#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
296#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
297 R6(0), R6(2), R6(1), R6(3)
298#undef R2
299#undef R4
300#undef R6
301};
302
303/// Reverse the bits in \p Val.
304template <typename T>
305T reverseBits(T Val) {
306 unsigned char in[sizeof(Val)];
307 unsigned char out[sizeof(Val)];
308 std::memcpy(in, &Val, sizeof(Val));
309 for (unsigned i = 0; i < sizeof(Val); ++i)
310 out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
311 std::memcpy(&Val, out, sizeof(Val));
312 return Val;
313}
314
315#if __has_builtin(__builtin_bitreverse8)1
316template<>
317inline uint8_t reverseBits<uint8_t>(uint8_t Val) {
318 return __builtin_bitreverse8(Val);
319}
320#endif
321
322#if __has_builtin(__builtin_bitreverse16)1
323template<>
324inline uint16_t reverseBits<uint16_t>(uint16_t Val) {
325 return __builtin_bitreverse16(Val);
326}
327#endif
328
329#if __has_builtin(__builtin_bitreverse32)1
330template<>
331inline uint32_t reverseBits<uint32_t>(uint32_t Val) {
332 return __builtin_bitreverse32(Val);
333}
334#endif
335
336#if __has_builtin(__builtin_bitreverse64)1
337template<>
338inline uint64_t reverseBits<uint64_t>(uint64_t Val) {
339 return __builtin_bitreverse64(Val);
340}
341#endif
342
343// NOTE: The following support functions use the _32/_64 extensions instead of
344// type overloading so that signed and unsigned integers can be used without
345// ambiguity.
346
347/// Return the high 32 bits of a 64 bit value.
348constexpr inline uint32_t Hi_32(uint64_t Value) {
349 return static_cast<uint32_t>(Value >> 32);
350}
351
352/// Return the low 32 bits of a 64 bit value.
353constexpr inline uint32_t Lo_32(uint64_t Value) {
354 return static_cast<uint32_t>(Value);
355}
356
357/// Make a 64-bit integer from a high / low pair of 32-bit integers.
358constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) {
359 return ((uint64_t)High << 32) | (uint64_t)Low;
360}
361
362/// Checks if an integer fits into the given bit width.
363template <unsigned N> constexpr inline bool isInt(int64_t x) {
364 return N >= 64 || (-(INT64_C(1)1L<<(N-1)) <= x && x < (INT64_C(1)1L<<(N-1)));
365}
366// Template specializations to get better code for common cases.
367template <> constexpr inline bool isInt<8>(int64_t x) {
368 return static_cast<int8_t>(x) == x;
369}
370template <> constexpr inline bool isInt<16>(int64_t x) {
371 return static_cast<int16_t>(x) == x;
372}
373template <> constexpr inline bool isInt<32>(int64_t x) {
374 return static_cast<int32_t>(x) == x;
375}
376
377/// Checks if a signed integer is an N bit number shifted left by S.
378template <unsigned N, unsigned S>
379constexpr inline bool isShiftedInt(int64_t x) {
380 static_assert(
381 N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number.");
382 static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
383 return isInt<N + S>(x) && (x % (UINT64_C(1)1UL << S) == 0);
384}
385
386/// Checks if an unsigned integer fits into the given bit width.
387///
388/// This is written as two functions rather than as simply
389///
390/// return N >= 64 || X < (UINT64_C(1) << N);
391///
392/// to keep MSVC from (incorrectly) warning on isUInt<64> that we're shifting
393/// left too many places.
394template <unsigned N>
395constexpr inline std::enable_if_t<(N < 64), bool> isUInt(uint64_t X) {
396 static_assert(N > 0, "isUInt<0> doesn't make sense");
397 return X < (UINT64_C(1)1UL << (N));
398}
399template <unsigned N>
400constexpr inline std::enable_if_t<N >= 64, bool> isUInt(uint64_t) {
401 return true;
402}
403
404// Template specializations to get better code for common cases.
405template <> constexpr inline bool isUInt<8>(uint64_t x) {
406 return static_cast<uint8_t>(x) == x;
407}
408template <> constexpr inline bool isUInt<16>(uint64_t x) {
409 return static_cast<uint16_t>(x) == x;
410}
411template <> constexpr inline bool isUInt<32>(uint64_t x) {
412 return static_cast<uint32_t>(x) == x;
413}
414
415/// Checks if a unsigned integer is an N bit number shifted left by S.
416template <unsigned N, unsigned S>
417constexpr inline bool isShiftedUInt(uint64_t x) {
418 static_assert(
419 N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)");
420 static_assert(N + S <= 64,
421 "isShiftedUInt<N, S> with N + S > 64 is too wide.");
422 // Per the two static_asserts above, S must be strictly less than 64. So
423 // 1 << S is not undefined behavior.
424 return isUInt<N + S>(x) && (x % (UINT64_C(1)1UL << S) == 0);
425}
426
427/// Gets the maximum value for a N-bit unsigned integer.
428inline uint64_t maxUIntN(uint64_t N) {
429 assert(N > 0 && N <= 64 && "integer width out of range")(static_cast <bool> (N > 0 && N <= 64 &&
"integer width out of range") ? void (0) : __assert_fail ("N > 0 && N <= 64 && \"integer width out of range\""
, "llvm/include/llvm/Support/MathExtras.h", 429, __extension__
__PRETTY_FUNCTION__))
;
430
431 // uint64_t(1) << 64 is undefined behavior, so we can't do
432 // (uint64_t(1) << N) - 1
433 // without checking first that N != 64. But this works and doesn't have a
434 // branch.
435 return UINT64_MAX(18446744073709551615UL) >> (64 - N);
436}
437
438/// Gets the minimum value for a N-bit signed integer.
439inline int64_t minIntN(int64_t N) {
440 assert(N > 0 && N <= 64 && "integer width out of range")(static_cast <bool> (N > 0 && N <= 64 &&
"integer width out of range") ? void (0) : __assert_fail ("N > 0 && N <= 64 && \"integer width out of range\""
, "llvm/include/llvm/Support/MathExtras.h", 440, __extension__
__PRETTY_FUNCTION__))
;
441
442 return UINT64_C(1)1UL + ~(UINT64_C(1)1UL << (N - 1));
443}
444
445/// Gets the maximum value for a N-bit signed integer.
446inline int64_t maxIntN(int64_t N) {
447 assert(N > 0 && N <= 64 && "integer width out of range")(static_cast <bool> (N > 0 && N <= 64 &&
"integer width out of range") ? void (0) : __assert_fail ("N > 0 && N <= 64 && \"integer width out of range\""
, "llvm/include/llvm/Support/MathExtras.h", 447, __extension__
__PRETTY_FUNCTION__))
;
448
449 // This relies on two's complement wraparound when N == 64, so we convert to
450 // int64_t only at the very end to avoid UB.
451 return (UINT64_C(1)1UL << (N - 1)) - 1;
452}
453
454/// Checks if an unsigned integer fits into the given (dynamic) bit width.
455inline bool isUIntN(unsigned N, uint64_t x) {
456 return N >= 64 || x <= maxUIntN(N);
457}
458
459/// Checks if an signed integer fits into the given (dynamic) bit width.
460inline bool isIntN(unsigned N, int64_t x) {
461 return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
462}
463
464/// Return true if the argument is a non-empty sequence of ones starting at the
465/// least significant bit with the remainder zero (32 bit version).
466/// Ex. isMask_32(0x0000FFFFU) == true.
467constexpr inline bool isMask_32(uint32_t Value) {
468 return Value && ((Value + 1) & Value) == 0;
469}
470
471/// Return true if the argument is a non-empty sequence of ones starting at the
472/// least significant bit with the remainder zero (64 bit version).
473constexpr inline bool isMask_64(uint64_t Value) {
474 return Value && ((Value + 1) & Value) == 0;
475}
476
477/// Return true if the argument contains a non-empty sequence of ones with the
478/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
479constexpr inline bool isShiftedMask_32(uint32_t Value) {
480 return Value && isMask_32((Value - 1) | Value);
481}
482
483/// Return true if the argument contains a non-empty sequence of ones with the
484/// remainder zero (64 bit version.)
485constexpr inline bool isShiftedMask_64(uint64_t Value) {
486 return Value && isMask_64((Value - 1) | Value);
487}
488
489/// Return true if the argument is a power of two > 0.
490/// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
491constexpr inline bool isPowerOf2_32(uint32_t Value) {
492 return Value && !(Value & (Value - 1));
493}
494
495/// Return true if the argument is a power of two > 0 (64 bit edition.)
496constexpr inline bool isPowerOf2_64(uint64_t Value) {
497 return Value && !(Value & (Value - 1));
498}
499
500/// Count the number of ones from the most significant bit to the first
501/// zero bit.
502///
503/// Ex. countLeadingOnes(0xFF0FFF00) == 8.
504/// Only unsigned integral types are allowed.
505///
506/// \param ZB the behavior on an input of all ones. Only ZB_Width and
507/// ZB_Undefined are valid arguments.
508template <typename T>
509unsigned countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
510 static_assert(std::numeric_limits<T>::is_integer &&
511 !std::numeric_limits<T>::is_signed,
512 "Only unsigned integral types are allowed.");
513 return countLeadingZeros<T>(~Value, ZB);
514}
515
516/// Count the number of ones from the least significant bit to the first
517/// zero bit.
518///
519/// Ex. countTrailingOnes(0x00FF00FF) == 8.
520/// Only unsigned integral types are allowed.
521///
522/// \param ZB the behavior on an input of all ones. Only ZB_Width and
523/// ZB_Undefined are valid arguments.
524template <typename T>
525unsigned countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
526 static_assert(std::numeric_limits<T>::is_integer &&
527 !std::numeric_limits<T>::is_signed,
528 "Only unsigned integral types are allowed.");
529 return countTrailingZeros<T>(~Value, ZB);
530}
531
532namespace detail {
533template <typename T, std::size_t SizeOfT> struct PopulationCounter {
534 static unsigned count(T Value) {
535 // Generic version, forward to 32 bits.
536 static_assert(SizeOfT <= 4, "Not implemented!");
537#if defined(__GNUC__4)
538 return __builtin_popcount(Value);
539#else
540 uint32_t v = Value;
541 v = v - ((v >> 1) & 0x55555555);
542 v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
543 return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
544#endif
545 }
546};
547
548template <typename T> struct PopulationCounter<T, 8> {
549 static unsigned count(T Value) {
550#if defined(__GNUC__4)
551 return __builtin_popcountll(Value);
552#else
553 uint64_t v = Value;
554 v = v - ((v >> 1) & 0x5555555555555555ULL);
555 v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
556 v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
557 return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
558#endif
559 }
560};
561} // namespace detail
562
563/// Count the number of set bits in a value.
564/// Ex. countPopulation(0xF000F000) = 8
565/// Returns 0 if the word is zero.
566template <typename T>
567inline unsigned countPopulation(T Value) {
568 static_assert(std::numeric_limits<T>::is_integer &&
569 !std::numeric_limits<T>::is_signed,
570 "Only unsigned integral types are allowed.");
571 return detail::PopulationCounter<T, sizeof(T)>::count(Value);
572}
573
574/// Return true if the argument contains a non-empty sequence of ones with the
575/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
576/// If true, \p MaskIdx will specify the index of the lowest set bit and \p
577/// MaskLen is updated to specify the length of the mask, else neither are
578/// updated.
579inline bool isShiftedMask_32(uint32_t Value, unsigned &MaskIdx,
580 unsigned &MaskLen) {
581 if (!isShiftedMask_32(Value))
582 return false;
583 MaskIdx = countTrailingZeros(Value);
584 MaskLen = countPopulation(Value);
585 return true;
586}
587
588/// Return true if the argument contains a non-empty sequence of ones with the
589/// remainder zero (64 bit version.) If true, \p MaskIdx will specify the index
590/// of the lowest set bit and \p MaskLen is updated to specify the length of the
591/// mask, else neither are updated.
592inline bool isShiftedMask_64(uint64_t Value, unsigned &MaskIdx,
593 unsigned &MaskLen) {
594 if (!isShiftedMask_64(Value))
595 return false;
596 MaskIdx = countTrailingZeros(Value);
597 MaskLen = countPopulation(Value);
598 return true;
599}
600
601/// Compile time Log2.
602/// Valid only for positive powers of two.
603template <size_t kValue> constexpr inline size_t CTLog2() {
604 static_assert(kValue > 0 && llvm::isPowerOf2_64(kValue),
605 "Value is not a valid power of 2");
606 return 1 + CTLog2<kValue / 2>();
607}
608
609template <> constexpr inline size_t CTLog2<1>() { return 0; }
610
611/// Return the log base 2 of the specified value.
612inline double Log2(double Value) {
613#if defined(__ANDROID_API__) && __ANDROID_API__ < 18
614 return __builtin_log(Value) / __builtin_log(2.0);
615#else
616 return log2(Value);
617#endif
618}
619
620/// Return the floor log base 2 of the specified value, -1 if the value is zero.
621/// (32 bit edition.)
622/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
623inline unsigned Log2_32(uint32_t Value) {
624 return 31 - countLeadingZeros(Value);
625}
626
627/// Return the floor log base 2 of the specified value, -1 if the value is zero.
628/// (64 bit edition.)
629inline unsigned Log2_64(uint64_t Value) {
630 return 63 - countLeadingZeros(Value);
631}
632
633/// Return the ceil log base 2 of the specified value, 32 if the value is zero.
634/// (32 bit edition).
635/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
636inline unsigned Log2_32_Ceil(uint32_t Value) {
637 return 32 - countLeadingZeros(Value - 1);
638}
639
640/// Return the ceil log base 2 of the specified value, 64 if the value is zero.
641/// (64 bit edition.)
642inline unsigned Log2_64_Ceil(uint64_t Value) {
643 return 64 - countLeadingZeros(Value - 1);
644}
645
646/// Return the greatest common divisor of the values using Euclid's algorithm.
647template <typename T>
648inline T greatestCommonDivisor(T A, T B) {
649 while (B) {
650 T Tmp = B;
651 B = A % B;
652 A = Tmp;
653 }
654 return A;
655}
656
657inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
658 return greatestCommonDivisor<uint64_t>(A, B);
659}
660
661/// This function takes a 64-bit integer and returns the bit equivalent double.
662inline double BitsToDouble(uint64_t Bits) {
663 double D;
664 static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
665 memcpy(&D, &Bits, sizeof(Bits));
666 return D;
667}
668
669/// This function takes a 32-bit integer and returns the bit equivalent float.
670inline float BitsToFloat(uint32_t Bits) {
671 float F;
672 static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
673 memcpy(&F, &Bits, sizeof(Bits));
674 return F;
675}
676
677/// This function takes a double and returns the bit equivalent 64-bit integer.
678/// Note that copying doubles around changes the bits of NaNs on some hosts,
679/// notably x86, so this routine cannot be used if these bits are needed.
680inline uint64_t DoubleToBits(double Double) {
681 uint64_t Bits;
682 static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
683 memcpy(&Bits, &Double, sizeof(Double));
684 return Bits;
685}
686
687/// This function takes a float and returns the bit equivalent 32-bit integer.
688/// Note that copying floats around changes the bits of NaNs on some hosts,
689/// notably x86, so this routine cannot be used if these bits are needed.
690inline uint32_t FloatToBits(float Float) {
691 uint32_t Bits;
692 static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
693 memcpy(&Bits, &Float, sizeof(Float));
694 return Bits;
695}
696
697/// A and B are either alignments or offsets. Return the minimum alignment that
698/// may be assumed after adding the two together.
699constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) {
700 // The largest power of 2 that divides both A and B.
701 //
702 // Replace "-Value" by "1+~Value" in the following commented code to avoid
703 // MSVC warning C4146
704 // return (A | B) & -(A | B);
705 return (A | B) & (1 + ~(A | B));
706}
707
708/// Returns the next power of two (in 64-bits) that is strictly greater than A.
709/// Returns zero on overflow.
710constexpr inline uint64_t NextPowerOf2(uint64_t A) {
711 A |= (A >> 1);
712 A |= (A >> 2);
713 A |= (A >> 4);
714 A |= (A >> 8);
715 A |= (A >> 16);
716 A |= (A >> 32);
717 return A + 1;
718}
719
720/// Returns the power of two which is less than or equal to the given value.
721/// Essentially, it is a floor operation across the domain of powers of two.
722inline uint64_t PowerOf2Floor(uint64_t A) {
723 if (!A) return 0;
724 return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
725}
726
727/// Returns the power of two which is greater than or equal to the given value.
728/// Essentially, it is a ceil operation across the domain of powers of two.
729inline uint64_t PowerOf2Ceil(uint64_t A) {
730 if (!A)
731 return 0;
732 return NextPowerOf2(A - 1);
733}
734
735/// Returns the next integer (mod 2**64) that is greater than or equal to
736/// \p Value and is a multiple of \p Align. \p Align must be non-zero.
737///
738/// If non-zero \p Skew is specified, the return value will be a minimal
739/// integer that is greater than or equal to \p Value and equal to
740/// \p Align * N + \p Skew for some integer N. If \p Skew is larger than
741/// \p Align, its value is adjusted to '\p Skew mod \p Align'.
742///
743/// Examples:
744/// \code
745/// alignTo(5, 8) = 8
746/// alignTo(17, 8) = 24
747/// alignTo(~0LL, 8) = 0
748/// alignTo(321, 255) = 510
749///
750/// alignTo(5, 8, 7) = 7
751/// alignTo(17, 8, 1) = 17
752/// alignTo(~0LL, 8, 3) = 3
753/// alignTo(321, 255, 42) = 552
754/// \endcode
755inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
756 assert(Align != 0u && "Align can't be 0.")(static_cast <bool> (Align != 0u && "Align can't be 0."
) ? void (0) : __assert_fail ("Align != 0u && \"Align can't be 0.\""
, "llvm/include/llvm/Support/MathExtras.h", 756, __extension__
__PRETTY_FUNCTION__))
;
757 Skew %= Align;
758 return (Value + Align - 1 - Skew) / Align * Align + Skew;
759}
760
761/// Returns the next integer (mod 2**64) that is greater than or equal to
762/// \p Value and is a multiple of \c Align. \c Align must be non-zero.
763template <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) {
764 static_assert(Align != 0u, "Align must be non-zero");
765 return (Value + Align - 1) / Align * Align;
766}
767
768/// Returns the integer ceil(Numerator / Denominator).
769inline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
770 return alignTo(Numerator, Denominator) / Denominator;
771}
772
773/// Returns the integer nearest(Numerator / Denominator).
774inline uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator) {
775 return (Numerator + (Denominator / 2)) / Denominator;
776}
777
778/// Returns the largest uint64_t less than or equal to \p Value and is
779/// \p Skew mod \p Align. \p Align must be non-zero
780inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
781 assert(Align != 0u && "Align can't be 0.")(static_cast <bool> (Align != 0u && "Align can't be 0."
) ? void (0) : __assert_fail ("Align != 0u && \"Align can't be 0.\""
, "llvm/include/llvm/Support/MathExtras.h", 781, __extension__
__PRETTY_FUNCTION__))
;
782 Skew %= Align;
783 return (Value - Skew) / Align * Align + Skew;
784}
785
786/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
787/// Requires 0 < B <= 32.
788template <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) {
789 static_assert(B > 0, "Bit width can't be 0.");
790 static_assert(B <= 32, "Bit width out of range.");
791 return int32_t(X << (32 - B)) >> (32 - B);
792}
793
794/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
795/// Requires 0 < B <= 32.
796inline int32_t SignExtend32(uint32_t X, unsigned B) {
797 assert(B > 0 && "Bit width can't be 0.")(static_cast <bool> (B > 0 && "Bit width can't be 0."
) ? void (0) : __assert_fail ("B > 0 && \"Bit width can't be 0.\""
, "llvm/include/llvm/Support/MathExtras.h", 797, __extension__
__PRETTY_FUNCTION__))
;
798 assert(B <= 32 && "Bit width out of range.")(static_cast <bool> (B <= 32 && "Bit width out of range."
) ? void (0) : __assert_fail ("B <= 32 && \"Bit width out of range.\""
, "llvm/include/llvm/Support/MathExtras.h", 798, __extension__
__PRETTY_FUNCTION__))
;
799 return int32_t(X << (32 - B)) >> (32 - B);
800}
801
802/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
803/// Requires 0 < B <= 64.
804template <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) {
805 static_assert(B > 0, "Bit width can't be 0.");
806 static_assert(B <= 64, "Bit width out of range.");
807 return int64_t(x << (64 - B)) >> (64 - B);
808}
809
810/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
811/// Requires 0 < B <= 64.
812inline int64_t SignExtend64(uint64_t X, unsigned B) {
813 assert(B > 0 && "Bit width can't be 0.")(static_cast <bool> (B > 0 && "Bit width can't be 0."
) ? void (0) : __assert_fail ("B > 0 && \"Bit width can't be 0.\""
, "llvm/include/llvm/Support/MathExtras.h", 813, __extension__
__PRETTY_FUNCTION__))
;
814 assert(B <= 64 && "Bit width out of range.")(static_cast <bool> (B <= 64 && "Bit width out of range."
) ? void (0) : __assert_fail ("B <= 64 && \"Bit width out of range.\""
, "llvm/include/llvm/Support/MathExtras.h", 814, __extension__
__PRETTY_FUNCTION__))
;
815 return int64_t(X << (64 - B)) >> (64 - B);
816}
817
818/// Subtract two unsigned integers, X and Y, of type T and return the absolute
819/// value of the result.
820template <typename T>
821std::enable_if_t<std::is_unsigned<T>::value, T> AbsoluteDifference(T X, T Y) {
822 return X > Y ? (X - Y) : (Y - X);
823}
824
825/// Add two unsigned integers, X and Y, of type T. Clamp the result to the
826/// maximum representable value of T on overflow. ResultOverflowed indicates if
827/// the result is larger than the maximum representable value of type T.
828template <typename T>
829std::enable_if_t<std::is_unsigned<T>::value, T>
830SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
831 bool Dummy;
832 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
833 // Hacker's Delight, p. 29
834 T Z = X + Y;
835 Overflowed = (Z < X || Z < Y);
836 if (Overflowed)
837 return std::numeric_limits<T>::max();
838 else
839 return Z;
840}
841
842/// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the
843/// maximum representable value of T on overflow. ResultOverflowed indicates if
844/// the result is larger than the maximum representable value of type T.
845template <typename T>
846std::enable_if_t<std::is_unsigned<T>::value, T>
847SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
848 bool Dummy;
849 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
850
851 // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
852 // because it fails for uint16_t (where multiplication can have undefined
853 // behavior due to promotion to int), and requires a division in addition
854 // to the multiplication.
855
856 Overflowed = false;
857
858 // Log2(Z) would be either Log2Z or Log2Z + 1.
859 // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
860 // will necessarily be less than Log2Max as desired.
861 int Log2Z = Log2_64(X) + Log2_64(Y);
862 const T Max = std::numeric_limits<T>::max();
863 int Log2Max = Log2_64(Max);
864 if (Log2Z < Log2Max) {
865 return X * Y;
866 }
867 if (Log2Z > Log2Max) {
868 Overflowed = true;
869 return Max;
870 }
871
872 // We're going to use the top bit, and maybe overflow one
873 // bit past it. Multiply all but the bottom bit then add
874 // that on at the end.
875 T Z = (X >> 1) * Y;
876 if (Z & ~(Max >> 1)) {
877 Overflowed = true;
878 return Max;
879 }
880 Z <<= 1;
881 if (X & 1)
882 return SaturatingAdd(Z, Y, ResultOverflowed);
883
884 return Z;
885}
886
887/// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
888/// the product. Clamp the result to the maximum representable value of T on
889/// overflow. ResultOverflowed indicates if the result is larger than the
890/// maximum representable value of type T.
891template <typename T>
892std::enable_if_t<std::is_unsigned<T>::value, T>
893SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
894 bool Dummy;
895 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
896
897 T Product = SaturatingMultiply(X, Y, &Overflowed);
898 if (Overflowed)
899 return Product;
900
901 return SaturatingAdd(A, Product, &Overflowed);
902}
903
904/// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
905extern const float huge_valf;
906
907
908/// Add two signed integers, computing the two's complement truncated result,
909/// returning true if overflow occurred.
910template <typename T>
911std::enable_if_t<std::is_signed<T>::value, T> AddOverflow(T X, T Y, T &Result) {
912#if __has_builtin(__builtin_add_overflow)1
913 return __builtin_add_overflow(X, Y, &Result);
914#else
915 // Perform the unsigned addition.
916 using U = std::make_unsigned_t<T>;
917 const U UX = static_cast<U>(X);
918 const U UY = static_cast<U>(Y);
919 const U UResult = UX + UY;
920
921 // Convert to signed.
922 Result = static_cast<T>(UResult);
923
924 // Adding two positive numbers should result in a positive number.
925 if (X > 0 && Y > 0)
926 return Result <= 0;
927 // Adding two negatives should result in a negative number.
928 if (X < 0 && Y < 0)
929 return Result >= 0;
930 return false;
931#endif
932}
933
934/// Subtract two signed integers, computing the two's complement truncated
935/// result, returning true if an overflow ocurred.
936template <typename T>
937std::enable_if_t<std::is_signed<T>::value, T> SubOverflow(T X, T Y, T &Result) {
938#if __has_builtin(__builtin_sub_overflow)1
939 return __builtin_sub_overflow(X, Y, &Result);
940#else
941 // Perform the unsigned addition.
942 using U = std::make_unsigned_t<T>;
943 const U UX = static_cast<U>(X);
944 const U UY = static_cast<U>(Y);
945 const U UResult = UX - UY;
946
947 // Convert to signed.
948 Result = static_cast<T>(UResult);
949
950 // Subtracting a positive number from a negative results in a negative number.
951 if (X <= 0 && Y > 0)
952 return Result >= 0;
953 // Subtracting a negative number from a positive results in a positive number.
954 if (X >= 0 && Y < 0)
955 return Result <= 0;
956 return false;
957#endif
958}
959
960/// Multiply two signed integers, computing the two's complement truncated
961/// result, returning true if an overflow ocurred.
962template <typename T>
963std::enable_if_t<std::is_signed<T>::value, T> MulOverflow(T X, T Y, T &Result) {
964 // Perform the unsigned multiplication on absolute values.
965 using U = std::make_unsigned_t<T>;
966 const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
967 const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
968 const U UResult = UX * UY;
969
970 // Convert to signed.
971 const bool IsNegative = (X < 0) ^ (Y < 0);
972 Result = IsNegative ? (0 - UResult) : UResult;
973
974 // If any of the args was 0, result is 0 and no overflow occurs.
975 if (UX == 0 || UY == 0)
976 return false;
977
978 // UX and UY are in [1, 2^n], where n is the number of digits.
979 // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
980 // positive) divided by an argument compares to the other.
981 if (IsNegative)
982 return UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY;
983 else
984 return UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
985}
986
987} // End llvm namespace
988
989#endif