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