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