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