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