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