Add zextOrCopy() into APInt for convenience.
[oota-llvm.git] / include / llvm / ADT / APInt.h
1 //===-- llvm/Support/APInt.h - For Arbitrary Precision Integer -*- C++ -*--===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Sheng Zhou and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a class to represent arbitrary precision integral
11 // constant values.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_APINT_H
16 #define LLVM_APINT_H
17
18 #include "llvm/Support/DataTypes.h"
19 #include <cassert>
20 #include <string>
21
22 namespace llvm {
23
24 /// Forward declaration.
25 class APInt;
26 namespace APIntOps {
27   APInt udiv(const APInt& LHS, const APInt& RHS);
28   APInt urem(const APInt& LHS, const APInt& RHS);
29 }
30
31 //===----------------------------------------------------------------------===//
32 //                              APInt Class
33 //===----------------------------------------------------------------------===//
34
35 /// APInt - This class represents arbitrary precision constant integral values.
36 /// It is a functional replacement for common case unsigned integer type like 
37 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width 
38 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
39 /// than 64-bits of precision. APInt provides a variety of arithmetic operators 
40 /// and methods to manipulate integer values of any bit-width. It supports both
41 /// the typical integer arithmetic and comparison operations as well as bitwise
42 /// manipulation.
43 ///
44 /// The class has several invariants worth noting:
45 ///   * All bit, byte, and word positions are zero-based.
46 ///   * Once the bit width is set, it doesn't change except by the Truncate, 
47 ///     SignExtend, or ZeroExtend operations.
48 ///   * All binary operators must be on APInt instances of the same bit width.
49 ///     Attempting to use these operators on instances with different bit 
50 ///     widths will yield an assertion.
51 ///   * The value is stored canonically as an unsigned value. For operations
52 ///     where it makes a difference, there are both signed and unsigned variants
53 ///     of the operation. For example, sdiv and udiv. However, because the bit
54 ///     widths must be the same, operations such as Mul and Add produce the same
55 ///     results regardless of whether the values are interpreted as signed or
56 ///     not.
57 ///   * In general, the class tries to follow the style of computation that LLVM
58 ///     uses in its IR. This simplifies its use for LLVM.
59 ///
60 /// @brief Class for arbitrary precision integers.
61 class APInt {
62
63   uint32_t BitWidth;      ///< The number of bits in this APInt.
64
65   /// This union is used to store the integer value. When the
66   /// integer bit-width <= 64, it uses VAL; 
67   /// otherwise it uses the pVal.
68   union {
69     uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
70     uint64_t *pVal;  ///< Used to store the >64 bits integer value.
71   };
72
73   /// This enum is just used to hold a constant we needed for APInt.
74   enum {
75     APINT_BITS_PER_WORD = sizeof(uint64_t) * 8,
76     APINT_WORD_SIZE = sizeof(uint64_t)
77   };
78
79   // Fast internal constructor
80   APInt(uint64_t* val, uint32_t bits) : BitWidth(bits), pVal(val) { }
81
82   /// @returns true if the number of bits <= 64, false otherwise.
83   /// @brief Determine if this APInt just has one word to store value.
84   inline bool isSingleWord() const { 
85     return BitWidth <= APINT_BITS_PER_WORD; 
86   }
87
88   /// @returns the word position for the specified bit position.
89   static inline uint32_t whichWord(uint32_t bitPosition) { 
90     return bitPosition / APINT_BITS_PER_WORD; 
91   }
92
93   /// @returns the bit position in a word for the specified bit position 
94   /// in APInt.
95   static inline uint32_t whichBit(uint32_t bitPosition) { 
96     return bitPosition % APINT_BITS_PER_WORD; 
97   }
98
99   /// @returns a uint64_t type integer with just bit position at
100   /// "whichBit(bitPosition)" setting, others zero.
101   static inline uint64_t maskBit(uint32_t bitPosition) { 
102     return 1ULL << whichBit(bitPosition); 
103   }
104
105   /// This method is used internally to clear the to "N" bits that are not used
106   /// by the APInt. This is needed after the most significant word is assigned 
107   /// a value to ensure that those bits are zero'd out.
108   /// @brief Clear high order bits
109   inline APInt& clearUnusedBits() {
110     // Compute how many bits are used in the final word
111     uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
112     if (wordBits == 0)
113       // If all bits are used, we want to leave the value alone. This also
114       // avoids the undefined behavior of >> when the shfit is the same size as
115       // the word size (64).
116       return *this;
117
118     // Mask out the hight bits.
119     uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
120     if (isSingleWord())
121       VAL &= mask;
122     else
123       pVal[getNumWords() - 1] &= mask;
124     return *this;
125   }
126
127   /// @returns the corresponding word for the specified bit position.
128   /// @brief Get the word corresponding to a bit position
129   inline uint64_t getWord(uint32_t bitPosition) const { 
130     return isSingleWord() ? VAL : pVal[whichWord(bitPosition)]; 
131   }
132
133   /// This is used by the constructors that take string arguments.
134   /// @brief Converts a char array into an APInt
135   void fromString(uint32_t numBits, const char *StrStart, uint32_t slen, 
136                   uint8_t radix);
137
138   /// This is used by the toString method to divide by the radix. It simply
139   /// provides a more convenient form of divide for internal use since KnuthDiv
140   /// has specific constraints on its inputs. If those constraints are not met
141   /// then it provides a simpler form of divide.
142   /// @brief An internal division function for dividing APInts.
143   static void divide(const APInt LHS, uint32_t lhsWords, 
144                      const APInt &RHS, uint32_t rhsWords,
145                      APInt *Quotient, APInt *Remainder);
146
147 #ifndef NDEBUG
148   /// @brief debug method
149   void dump() const;
150 #endif
151
152 public:
153   /// @brief Create a new APInt of numBits width, initialized as val.
154   APInt(uint32_t numBits, uint64_t val);
155
156   /// Note that numWords can be smaller or larger than the corresponding bit
157   /// width but any extraneous bits will be dropped.
158   /// @brief Create a new APInt of numBits width, initialized as bigVal[].
159   APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
160
161   /// @brief Create a new APInt by translating the string represented 
162   /// integer value.
163   APInt(uint32_t numBits, const std::string& Val, uint8_t radix);
164
165   /// @brief Create a new APInt by translating the char array represented
166   /// integer value.
167   APInt(uint32_t numBits, const char StrStart[], uint32_t slen, uint8_t radix);
168
169   /// @brief Copy Constructor.
170   APInt(const APInt& API);
171
172   /// @brief Destructor.
173   ~APInt();
174
175   /// @brief Copy assignment operator. 
176   APInt& operator=(const APInt& RHS);
177
178   /// Assigns an integer value to the APInt.
179   /// @brief Assignment operator. 
180   APInt& operator=(uint64_t RHS);
181
182   /// Increments the APInt by one.
183   /// @brief Postfix increment operator.
184   inline const APInt operator++(int) {
185     APInt API(*this);
186     ++(*this);
187     return API;
188   }
189
190   /// Increments the APInt by one.
191   /// @brief Prefix increment operator.
192   APInt& operator++();
193
194   /// Decrements the APInt by one.
195   /// @brief Postfix decrement operator. 
196   inline const APInt operator--(int) {
197     APInt API(*this);
198     --(*this);
199     return API;
200   }
201
202   /// Decrements the APInt by one.
203   /// @brief Prefix decrement operator. 
204   APInt& operator--();
205
206   /// Performs bitwise AND operation on this APInt and the given APInt& RHS, 
207   /// assigns the result to this APInt.
208   /// @brief Bitwise AND assignment operator. 
209   APInt& operator&=(const APInt& RHS);
210
211   /// Performs bitwise OR operation on this APInt and the given APInt& RHS, 
212   /// assigns the result to this APInt.
213   /// @brief Bitwise OR assignment operator. 
214   APInt& operator|=(const APInt& RHS);
215
216   /// Performs bitwise XOR operation on this APInt and the given APInt& RHS, 
217   /// assigns the result to this APInt.
218   /// @brief Bitwise XOR assignment operator. 
219   APInt& operator^=(const APInt& RHS);
220
221   /// Performs a bitwise complement operation on this APInt.
222   /// @brief Bitwise complement operator. 
223   APInt operator~() const;
224
225   /// Multiplies this APInt by the  given APInt& RHS and 
226   /// assigns the result to this APInt.
227   /// @brief Multiplication assignment operator. 
228   APInt& operator*=(const APInt& RHS);
229
230   /// Adds this APInt by the given APInt& RHS and 
231   /// assigns the result to this APInt.
232   /// @brief Addition assignment operator. 
233   APInt& operator+=(const APInt& RHS);
234
235   /// Subtracts this APInt by the given APInt &RHS and 
236   /// assigns the result to this APInt.
237   /// @brief Subtraction assignment operator. 
238   APInt& operator-=(const APInt& RHS);
239
240   /// Performs bitwise AND operation on this APInt and 
241   /// the given APInt& RHS.
242   /// @brief Bitwise AND operator. 
243   APInt operator&(const APInt& RHS) const;
244   APInt And(const APInt& RHS) const {
245     return this->operator&(RHS);
246   }
247
248   /// Performs bitwise OR operation on this APInt and the given APInt& RHS.
249   /// @brief Bitwise OR operator. 
250   APInt operator|(const APInt& RHS) const;
251   APInt Or(const APInt& RHS) const {
252     return this->operator|(RHS);
253   }
254
255   /// Performs bitwise XOR operation on this APInt and the given APInt& RHS.
256   /// @brief Bitwise XOR operator. 
257   APInt operator^(const APInt& RHS) const;
258   APInt Xor(const APInt& RHS) const {
259     return this->operator^(RHS);
260   }
261
262   /// Performs logical negation operation on this APInt.
263   /// @brief Logical negation operator. 
264   bool operator !() const;
265
266   /// Multiplies this APInt by the given APInt& RHS.
267   /// @brief Multiplication operator. 
268   APInt operator*(const APInt& RHS) const;
269
270   /// Adds this APInt by the given APInt& RHS.
271   /// @brief Addition operator. 
272   APInt operator+(const APInt& RHS) const;
273   APInt operator+(uint64_t RHS) const {
274     return (*this) + APInt(BitWidth, RHS);
275   }
276
277
278   /// Subtracts this APInt by the given APInt& RHS
279   /// @brief Subtraction operator. 
280   APInt operator-(const APInt& RHS) const;
281   APInt operator-(uint64_t RHS) const {
282     return (*this) - APInt(BitWidth, RHS);
283   }
284
285   /// @brief Unary negation operator
286   inline APInt operator-() const {
287     return APInt(BitWidth, 0) - (*this);
288   }
289
290   /// @brief Array-indexing support.
291   bool operator[](uint32_t bitPosition) const;
292
293   /// Compare this APInt with the given APInt& RHS 
294   /// for the validity of the equality relationship.
295   /// @brief Equality operator. 
296   bool operator==(const APInt& RHS) const;
297
298   /// Compare this APInt with the given uint64_t value
299   /// for the validity of the equality relationship.
300   /// @brief Equality operator.
301   bool operator==(uint64_t Val) const;
302
303   /// Compare this APInt with the given APInt& RHS 
304   /// for the validity of the inequality relationship.
305   /// @brief Inequality operator. 
306   inline bool operator!=(const APInt& RHS) const {
307     return !((*this) == RHS);
308   }
309
310   /// Compare this APInt with the given uint64_t value 
311   /// for the validity of the inequality relationship.
312   /// @brief Inequality operator. 
313   inline bool operator!=(uint64_t Val) const {
314     return !((*this) == Val);
315   }
316   
317   /// @brief Equality comparison
318   bool eq(const APInt &RHS) const {
319     return (*this) == RHS; 
320   }
321
322   /// @brief Inequality comparison
323   bool ne(const APInt &RHS) const {
324     return !((*this) == RHS);
325   }
326
327   /// @brief Unsigned less than comparison
328   bool ult(const APInt& RHS) const;
329
330   /// @brief Signed less than comparison
331   bool slt(const APInt& RHS) const;
332
333   /// @brief Unsigned less or equal comparison
334   bool ule(const APInt& RHS) const {
335     return ult(RHS) || eq(RHS);
336   }
337
338   /// @brief Signed less or equal comparison
339   bool sle(const APInt& RHS) const {
340     return slt(RHS) || eq(RHS);
341   }
342
343   /// @brief Unsigned greather than comparison
344   bool ugt(const APInt& RHS) const {
345     return !ult(RHS) && !eq(RHS);
346   }
347
348   /// @brief Signed greather than comparison
349   bool sgt(const APInt& RHS) const {
350     return !slt(RHS) && !eq(RHS);
351   }
352
353   /// @brief Unsigned greater or equal comparison
354   bool uge(const APInt& RHS) const {
355     return !ult(RHS);
356   }
357
358   /// @brief Signed greather or equal comparison
359   bool sge(const APInt& RHS) const {
360     return !slt(RHS);
361   }
362
363   /// This just tests the high bit of this APInt to determine if it is negative.
364   /// @returns true if this APInt is negative, false otherwise
365   /// @brief Determine sign of this APInt.
366   bool isNegative() const {
367     return (*this)[BitWidth - 1];
368   }
369
370   /// This just tests the high bit of the APInt to determine if the value is
371   /// positove or not.
372   /// @brief Determine if this APInt Value is positive.
373   bool isPositive() const {
374     return !isNegative();
375   }
376
377   /// Arithmetic right-shift this APInt by shiftAmt.
378   /// @brief Arithmetic right-shift function.
379   APInt ashr(uint32_t shiftAmt) const;
380
381   /// Logical right-shift this APInt by shiftAmt.
382   /// @brief Logical right-shift function.
383   APInt lshr(uint32_t shiftAmt) const;
384
385   /// Left-shift this APInt by shiftAmt.
386   /// @brief Left-shift function.
387   APInt shl(uint32_t shiftAmt) const;
388
389   /// Left-shift this APInt by shiftAmt and
390   /// assigns the result to this APInt.
391   /// @brief Lef-shift assignment function.
392   inline APInt& operator<<=(uint32_t shiftAmt) {
393     *this = shl(shiftAmt);
394     return *this;
395   }
396
397   /// Signed divide this APInt by APInt RHS.
398   /// @brief Signed division function for APInt.
399   inline APInt sdiv(const APInt& RHS) const {
400     bool isNegativeLHS = isNegative();
401     bool isNegativeRHS = RHS.isNegative();
402     APInt Result = APIntOps::udiv(
403         isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
404     return isNegativeLHS != isNegativeRHS ? -Result : Result;
405   }
406
407   /// Unsigned divide this APInt by APInt RHS.
408   /// @brief Unsigned division function for APInt.
409   APInt udiv(const APInt& RHS) const;
410
411   /// Signed remainder operation on APInt.
412   /// @brief Function for signed remainder operation.
413   inline APInt srem(const APInt& RHS) const {
414     bool isNegativeLHS = isNegative();
415     bool isNegativeRHS = RHS.isNegative();
416     APInt Result = APIntOps::urem(
417         isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
418     return isNegativeLHS ? -Result : Result;
419   }
420
421   /// Unsigned remainder operation on APInt.
422   /// @brief Function for unsigned remainder operation.
423   APInt urem(const APInt& RHS) const;
424
425   /// Truncate the APInt to a specified width. It is an error to specify a width
426   /// that is greater than or equal to the current width. 
427   /// @brief Truncate to new width.
428   APInt &trunc(uint32_t width);
429
430   /// This operation sign extends the APInt to a new width. If the high order
431   /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
432   /// It is an error to specify a width that is less than or equal to the 
433   /// current width.
434   /// @brief Sign extend to a new width.
435   APInt &sext(uint32_t width);
436
437   /// This operation zero extends the APInt to a new width. Thie high order bits
438   /// are filled with 0 bits.  It is an error to specify a width that is less 
439   /// than or equal to the current width.
440   /// @brief Zero extend to a new width.
441   APInt &zext(uint32_t width);
442
443   /// Make this APInt have the bit width given by \p width. The value is sign
444   /// extended, truncated, or left alone to make it that width.
445   /// @brief Sign extend or truncate to width
446   APInt &sextOrTrunc(uint32_t width);
447
448   /// Make this APInt have the bit width given by \p width. The value is zero
449   /// extended, truncated, or left alone to make it that width.
450   /// @brief Zero extend or truncate to width
451   APInt &zextOrTrunc(uint32_t width);
452
453   /// This is a help function for convenience. If the given \p width equals to
454   /// this APInt's BitWidth, just return this APInt, otherwise, just zero 
455   /// extend it.
456   inline APInt &zextOrCopy(uint32_t width) {
457     if (width == BitWidth)
458       return *this;
459     return zext(width);
460   }
461
462   /// @brief Set every bit to 1.
463   APInt& set();
464
465   /// Set the given bit to 1 whose position is given as "bitPosition".
466   /// @brief Set a given bit to 1.
467   APInt& set(uint32_t bitPosition);
468
469   /// @brief Set every bit to 0.
470   APInt& clear();
471
472   /// Set the given bit to 0 whose position is given as "bitPosition".
473   /// @brief Set a given bit to 0.
474   APInt& clear(uint32_t bitPosition);
475
476   /// @brief Toggle every bit to its opposite value.
477   APInt& flip();
478
479   /// Toggle a given bit to its opposite value whose position is given 
480   /// as "bitPosition".
481   /// @brief Toggles a given bit to its opposite value.
482   APInt& flip(uint32_t bitPosition);
483
484   inline void setWordToValue(uint32_t idx, uint64_t Val) {
485     assert(idx < getNumWords() && "Invalid word array index");
486     if (isSingleWord())
487       VAL = Val;
488     else
489       pVal[idx] = Val;
490   }
491
492   /// This function returns the number of active bits which is defined as the
493   /// bit width minus the number of leading zeros. This is used in several
494   /// computations to see how "wide" the value is.
495   /// @brief Compute the number of active bits in the value
496   inline uint32_t getActiveBits() const {
497     return BitWidth - countLeadingZeros();
498   }
499
500   /// This function returns the number of active words in the value of this
501   /// APInt. This is used in conjunction with getActiveData to extract the raw
502   /// value of the APInt.
503   inline uint32_t getActiveWords() const {
504     return whichWord(getActiveBits()-1) + 1;
505   }
506
507   /// Here one word's bitwidth equals to that of uint64_t.
508   /// @returns the number of words to hold the integer value of this APInt.
509   /// @brief Get the number of words.
510   inline uint32_t getNumWords() const {
511     return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
512   }
513
514   /// This function returns a pointer to the internal storage of the APInt. 
515   /// This is useful for writing out the APInt in binary form without any
516   /// conversions.
517   inline const uint64_t* getRawData() const {
518     if (isSingleWord())
519       return &VAL;
520     return &pVal[0];
521   }
522
523   /// Computes the minimum bit width for this APInt while considering it to be
524   /// a signed (and probably negative) value. If the value is not negative, 
525   /// this function returns the same value as getActiveBits(). Otherwise, it
526   /// returns the smallest bit width that will retain the negative value. For
527   /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
528   /// for -1, this function will always return 1.
529   /// @brief Get the minimum bit size for this signed APInt 
530   inline uint32_t getMinSignedBits() const {
531     if (isNegative())
532       return BitWidth - countLeadingOnes() + 1;
533     return getActiveBits();
534   }
535
536   /// This method attempts to return the value of this APInt as a zero extended
537   /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
538   /// uint64_t. Otherwise an assertion will result.
539   /// @brief Get zero extended value
540   inline uint64_t getZExtValue() const {
541     if (isSingleWord())
542       return VAL;
543     assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
544     return pVal[0];
545   }
546
547   /// This method attempts to return the value of this APInt as a sign extended
548   /// int64_t. The bit width must be <= 64 or the value must fit within an
549   /// int64_t. Otherwise an assertion will result.
550   /// @brief Get sign extended value
551   inline int64_t getSExtValue() const {
552     if (isSingleWord())
553       return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >> 
554                      (APINT_BITS_PER_WORD - BitWidth);
555     assert(getActiveBits() <= 64 && "Too many bits for int64_t");
556     return int64_t(pVal[0]);
557   }
558
559   /// @brief Gets maximum unsigned value of APInt for specific bit width.
560   static APInt getMaxValue(uint32_t numBits) {
561     return APInt(numBits, 0).set();
562   }
563
564   /// @brief Gets maximum signed value of APInt for a specific bit width.
565   static APInt getSignedMaxValue(uint32_t numBits) {
566     return APInt(numBits, 0).set().clear(numBits - 1);
567   }
568
569   /// @brief Gets minimum unsigned value of APInt for a specific bit width.
570   static APInt getMinValue(uint32_t numBits) {
571     return APInt(numBits, 0);
572   }
573
574   /// @brief Gets minimum signed value of APInt for a specific bit width.
575   static APInt getSignedMinValue(uint32_t numBits) {
576     return APInt(numBits, 0).set(numBits - 1);
577   }
578
579   /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
580   /// it helps code readability when we want to get a SignBit.
581   /// @brief Get the SignBit for a specific bit width.
582   inline static APInt getSignBit(uint32_t BitWidth) {
583     return getSignedMinValue(BitWidth);
584   }
585
586   /// @returns the all-ones value for an APInt of the specified bit-width.
587   /// @brief Get the all-ones value.
588   static APInt getAllOnesValue(uint32_t numBits) {
589     return APInt(numBits, 0).set();
590   }
591
592   /// @returns the '0' value for an APInt of the specified bit-width.
593   /// @brief Get the '0' value.
594   static APInt getNullValue(uint32_t numBits) {
595     return APInt(numBits, 0);
596   }
597
598   /// The hash value is computed as the sum of the words and the bit width.
599   /// @returns A hash value computed from the sum of the APInt words.
600   /// @brief Get a hash value based on this APInt
601   uint64_t getHashValue() const;
602
603   /// This converts the APInt to a boolean valy as a test against zero.
604   /// @brief Boolean conversion function. 
605   inline bool getBoolValue() const {
606     return countLeadingZeros() != BitWidth;
607   }
608
609   /// This checks to see if the value has all bits of the APInt are set or not.
610   /// @brief Determine if all bits are set
611   inline bool isAllOnesValue() const {
612     return countPopulation() == BitWidth;
613   }
614
615   /// This checks to see if the value of this APInt is the maximum unsigned
616   /// value for the APInt's bit width.
617   /// @brief Determine if this is the largest unsigned value.
618   bool isMaxValue() const {
619     return countPopulation() == BitWidth;
620   }
621
622   /// This checks to see if the value of this APInt is the maximum signed
623   /// value for the APInt's bit width.
624   /// @brief Determine if this is the largest signed value.
625   bool isMaxSignedValue() const {
626     return BitWidth == 1 ? VAL == 0 :
627                           !isNegative() && countPopulation() == BitWidth - 1;
628   }
629
630   /// This checks to see if the value of this APInt is the minimum signed
631   /// value for the APInt's bit width.
632   /// @brief Determine if this is the smallest unsigned value.
633   bool isMinValue() const {
634     return countPopulation() == 0;
635   }
636
637   /// This checks to see if the value of this APInt is the minimum signed
638   /// value for the APInt's bit width.
639   /// @brief Determine if this is the smallest signed value.
640   bool isMinSignedValue() const {
641     return BitWidth == 1 ? VAL == 1 :
642                            isNegative() && countPopulation() == 1;
643   }
644
645   /// This is used internally to convert an APInt to a string.
646   /// @brief Converts an APInt to a std::string
647   std::string toString(uint8_t radix, bool wantSigned) const;
648
649   /// Considers the APInt to be unsigned and converts it into a string in the
650   /// radix given. The radix can be 2, 8, 10 or 16.
651   /// @returns a character interpretation of the APInt
652   /// @brief Convert unsigned APInt to string representation.
653   inline std::string toString(uint8_t radix = 10) const {
654     return toString(radix, false);
655   }
656
657   /// Considers the APInt to be unsigned and converts it into a string in the
658   /// radix given. The radix can be 2, 8, 10 or 16.
659   /// @returns a character interpretation of the APInt
660   /// @brief Convert unsigned APInt to string representation.
661   inline std::string toStringSigned(uint8_t radix = 10) const {
662     return toString(radix, true);
663   }
664
665   /// Get an APInt with the same BitWidth as this APInt, just zero mask
666   /// the low bits and right shift to the least significant bit.
667   /// @returns the high "numBits" bits of this APInt.
668   APInt getHiBits(uint32_t numBits) const;
669
670   /// Get an APInt with the same BitWidth as this APInt, just zero mask
671   /// the high bits.
672   /// @returns the low "numBits" bits of this APInt.
673   APInt getLoBits(uint32_t numBits) const;
674
675   /// @returns true if the argument APInt value is a power of two > 0.
676   bool isPowerOf2() const; 
677
678   /// countLeadingZeros - This function is an APInt version of the
679   /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
680   /// of zeros from the most significant bit to the first one bit.
681   /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
682   /// @returns the number of zeros from the most significant bit to the first
683   /// one bits.
684   /// @brief Count the number of leading one bits.
685   uint32_t countLeadingZeros() const;
686
687   /// countLeadingOnes - This function counts the number of contiguous 1 bits
688   /// in the high order bits. The count stops when the first 0 bit is reached.
689   /// @returns 0 if the high order bit is not set
690   /// @returns the number of 1 bits from the most significant to the least
691   /// @brief Count the number of leading one bits.
692   uint32_t countLeadingOnes() const;
693
694   /// countTrailingZeros - This function is an APInt version of the 
695   /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts 
696   /// the number of zeros from the least significant bit to the first one bit.
697   /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
698   /// @returns the number of zeros from the least significant bit to the first
699   /// one bit.
700   /// @brief Count the number of trailing zero bits.
701   uint32_t countTrailingZeros() const;
702
703   /// countPopulation - This function is an APInt version of the
704   /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
705   /// of 1 bits in the APInt value. 
706   /// @returns 0 if the value is zero.
707   /// @returns the number of set bits.
708   /// @brief Count the number of bits set.
709   uint32_t countPopulation() const; 
710
711   /// @returns the total number of bits.
712   inline uint32_t getBitWidth() const { 
713     return BitWidth; 
714   }
715
716   /// @brief Check if this APInt has a N-bits integer value.
717   inline bool isIntN(uint32_t N) const {
718     assert(N && "N == 0 ???");
719     if (isSingleWord()) {
720       return VAL == (VAL & (~0ULL >> (64 - N)));
721     } else {
722       APInt Tmp(N, getNumWords(), pVal);
723       return Tmp == (*this);
724     }
725   }
726
727   /// @returns a byte-swapped representation of this APInt Value.
728   APInt byteSwap() const;
729
730   /// @returns the floor log base 2 of this APInt.
731   inline uint32_t logBase2() const {
732     return BitWidth - 1 - countLeadingZeros();
733   }
734
735   /// @brief Converts this APInt to a double value.
736   double roundToDouble(bool isSigned) const;
737
738   /// @brief Converts this unsigned APInt to a double value.
739   double roundToDouble() const {
740     return roundToDouble(false);
741   }
742
743   /// @brief Converts this signed APInt to a double value.
744   double signedRoundToDouble() const {
745     return roundToDouble(true);
746   }
747
748   /// The conversion does not do a translation from integer to double, it just
749   /// re-interprets the bits as a double. Note that it is valid to do this on
750   /// any bit width. Exactly 64 bits will be translated.
751   /// @brief Converts APInt bits to a double
752   double bitsToDouble() const {
753     union {
754       uint64_t I;
755       double D;
756     } T;
757     T.I = (isSingleWord() ? VAL : pVal[0]);
758     return T.D;
759   }
760
761   /// The conversion does not do a translation from integer to float, it just
762   /// re-interprets the bits as a float. Note that it is valid to do this on
763   /// any bit width. Exactly 32 bits will be translated.
764   /// @brief Converts APInt bits to a double
765   float bitsToFloat() const {
766     union {
767       uint32_t I;
768       float F;
769     } T;
770     T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
771     return T.F;
772   }
773
774   /// The conversion does not do a translation from double to integer, it just
775   /// re-interprets the bits of the double. Note that it is valid to do this on
776   /// any bit width but bits from V may get truncated.
777   /// @brief Converts a double to APInt bits.
778   APInt& doubleToBits(double V) {
779     union {
780       uint64_t I;
781       double D;
782     } T;
783     T.D = V;
784     if (isSingleWord())
785       VAL = T.I;
786     else
787       pVal[0] = T.I;
788     return clearUnusedBits();
789   }
790
791   /// The conversion does not do a translation from float to integer, it just
792   /// re-interprets the bits of the float. Note that it is valid to do this on
793   /// any bit width but bits from V may get truncated.
794   /// @brief Converts a float to APInt bits.
795   APInt& floatToBits(float V) {
796     union {
797       uint32_t I;
798       float F;
799     } T;
800     T.F = V;
801     if (isSingleWord())
802       VAL = T.I;
803     else
804       pVal[0] = T.I;
805     return clearUnusedBits();
806   }
807
808   /// @brief Compute the square root
809   APInt sqrt() const;
810
811   /// If *this is < 0 then return -(*this), otherwise *this;
812   /// @brief Get the absolute value;
813   APInt abs() const {
814     if (isNegative())
815       return -(*this);
816     return *this;
817   }
818 };
819
820 inline bool operator==(uint64_t V1, const APInt& V2) {
821   return V2 == V1;
822 }
823
824 inline bool operator!=(uint64_t V1, const APInt& V2) {
825   return V2 != V1;
826 }
827
828 namespace APIntOps {
829
830 /// @brief Determine the smaller of two APInts considered to be signed.
831 inline APInt smin(const APInt &A, const APInt &B) {
832   return A.slt(B) ? A : B;
833 }
834
835 /// @brief Determine the larger of two APInts considered to be signed.
836 inline APInt smax(const APInt &A, const APInt &B) {
837   return A.sgt(B) ? A : B;
838 }
839
840 /// @brief Determine the smaller of two APInts considered to be signed.
841 inline APInt umin(const APInt &A, const APInt &B) {
842   return A.ult(B) ? A : B;
843 }
844
845 /// @brief Determine the larger of two APInts considered to be unsigned.
846 inline APInt umax(const APInt &A, const APInt &B) {
847   return A.ugt(B) ? A : B;
848 }
849
850 /// @brief Check if the specified APInt has a N-bits integer value.
851 inline bool isIntN(uint32_t N, const APInt& APIVal) {
852   return APIVal.isIntN(N);
853 }
854
855 /// @returns true if the argument APInt value is a sequence of ones
856 /// starting at the least significant bit with the remainder zero.
857 inline const bool isMask(uint32_t numBits, const APInt& APIVal) {
858   return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
859 }
860
861 /// @returns true if the argument APInt value contains a sequence of ones
862 /// with the remainder zero.
863 inline const bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
864   return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
865 }
866
867 /// @returns a byte-swapped representation of the specified APInt Value.
868 inline APInt byteSwap(const APInt& APIVal) {
869   return APIVal.byteSwap();
870 }
871
872 /// @returns the floor log base 2 of the specified APInt value.
873 inline uint32_t logBase2(const APInt& APIVal) {
874   return APIVal.logBase2(); 
875 }
876
877 /// GreatestCommonDivisor - This function returns the greatest common
878 /// divisor of the two APInt values using Enclid's algorithm.
879 /// @returns the greatest common divisor of Val1 and Val2
880 /// @brief Compute GCD of two APInt values.
881 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
882
883 /// Treats the APInt as an unsigned value for conversion purposes.
884 /// @brief Converts the given APInt to a double value.
885 inline double RoundAPIntToDouble(const APInt& APIVal) {
886   return APIVal.roundToDouble();
887 }
888
889 /// Treats the APInt as a signed value for conversion purposes.
890 /// @brief Converts the given APInt to a double value.
891 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
892   return APIVal.signedRoundToDouble();
893 }
894
895 /// @brief Converts the given APInt to a float vlalue.
896 inline float RoundAPIntToFloat(const APInt& APIVal) {
897   return float(RoundAPIntToDouble(APIVal));
898 }
899
900 /// Treast the APInt as a signed value for conversion purposes.
901 /// @brief Converts the given APInt to a float value.
902 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
903   return float(APIVal.signedRoundToDouble());
904 }
905
906 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
907 /// @brief Converts the given double value into a APInt.
908 APInt RoundDoubleToAPInt(double Double, uint32_t width);
909
910 /// RoundFloatToAPInt - Converts a float value into an APInt value.
911 /// @brief Converts a float value into a APInt.
912 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
913   return RoundDoubleToAPInt(double(Float), width);
914 }
915
916 /// Arithmetic right-shift the APInt by shiftAmt.
917 /// @brief Arithmetic right-shift function.
918 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
919   return LHS.ashr(shiftAmt);
920 }
921
922 /// Logical right-shift the APInt by shiftAmt.
923 /// @brief Logical right-shift function.
924 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
925   return LHS.lshr(shiftAmt);
926 }
927
928 /// Left-shift the APInt by shiftAmt.
929 /// @brief Left-shift function.
930 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
931   return LHS.shl(shiftAmt);
932 }
933
934 /// Signed divide APInt LHS by APInt RHS.
935 /// @brief Signed division function for APInt.
936 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
937   return LHS.sdiv(RHS);
938 }
939
940 /// Unsigned divide APInt LHS by APInt RHS.
941 /// @brief Unsigned division function for APInt.
942 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
943   return LHS.udiv(RHS);
944 }
945
946 /// Signed remainder operation on APInt.
947 /// @brief Function for signed remainder operation.
948 inline APInt srem(const APInt& LHS, const APInt& RHS) {
949   return LHS.srem(RHS);
950 }
951
952 /// Unsigned remainder operation on APInt.
953 /// @brief Function for unsigned remainder operation.
954 inline APInt urem(const APInt& LHS, const APInt& RHS) {
955   return LHS.urem(RHS);
956 }
957
958 /// Performs multiplication on APInt values.
959 /// @brief Function for multiplication operation.
960 inline APInt mul(const APInt& LHS, const APInt& RHS) {
961   return LHS * RHS;
962 }
963
964 /// Performs addition on APInt values.
965 /// @brief Function for addition operation.
966 inline APInt add(const APInt& LHS, const APInt& RHS) {
967   return LHS + RHS;
968 }
969
970 /// Performs subtraction on APInt values.
971 /// @brief Function for subtraction operation.
972 inline APInt sub(const APInt& LHS, const APInt& RHS) {
973   return LHS - RHS;
974 }
975
976 /// Performs bitwise AND operation on APInt LHS and 
977 /// APInt RHS.
978 /// @brief Bitwise AND function for APInt.
979 inline APInt And(const APInt& LHS, const APInt& RHS) {
980   return LHS & RHS;
981 }
982
983 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
984 /// @brief Bitwise OR function for APInt. 
985 inline APInt Or(const APInt& LHS, const APInt& RHS) {
986   return LHS | RHS;
987 }
988
989 /// Performs bitwise XOR operation on APInt.
990 /// @brief Bitwise XOR function for APInt.
991 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
992   return LHS ^ RHS;
993
994
995 /// Performs a bitwise complement operation on APInt.
996 /// @brief Bitwise complement function. 
997 inline APInt Not(const APInt& APIVal) {
998   return ~APIVal;
999 }
1000
1001 } // End of APIntOps namespace
1002
1003 } // End of llvm namespace
1004
1005 #endif