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