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