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