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