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