7e7c67bcaf697c0501774dd8474e28a1ee8af2df
[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   /// @param radix the radix to use for the conversion
193   /// @brief Construct an APInt from a string representation.
194   APInt(uint32_t numBits, const char strStart[], uint32_t slen, uint8_t radix);
195
196   /// Simply makes *this a copy of that.
197   /// @brief Copy Constructor.
198   APInt(const APInt& that);
199
200   /// @brief Destructor.
201   ~APInt();
202
203   /// @}
204   /// @name Value Tests
205   /// @{
206   /// This tests the high bit of this APInt to determine if it is set.
207   /// @returns true if this APInt is negative, false otherwise
208   /// @brief Determine sign of this APInt.
209   bool isNegative() const {
210     return (*this)[BitWidth - 1];
211   }
212
213   /// This tests the high bit of the APInt to determine if it is unset.
214   /// @brief Determine if this APInt Value is positive (not negative).
215   bool isPositive() const {
216     return !isNegative();
217   }
218
219   /// This tests if the value of this APInt is strictly positive (> 0).
220   /// @returns true if this APInt is Positive and not zero.
221   /// @brief Determine if this APInt Value is strictly positive.
222   inline bool isStrictlyPositive() const {
223     return isPositive() && (*this) != 0;
224   }
225
226   /// This checks to see if the value has all bits of the APInt are set or not.
227   /// @brief Determine if all bits are set
228   inline bool isAllOnesValue() const {
229     return countPopulation() == BitWidth;
230   }
231
232   /// This checks to see if the value of this APInt is the maximum unsigned
233   /// value for the APInt's bit width.
234   /// @brief Determine if this is the largest unsigned value.
235   bool isMaxValue() const {
236     return countPopulation() == BitWidth;
237   }
238
239   /// This checks to see if the value of this APInt is the maximum signed
240   /// value for the APInt's bit width.
241   /// @brief Determine if this is the largest signed value.
242   bool isMaxSignedValue() const {
243     return BitWidth == 1 ? VAL == 0 :
244                           !isNegative() && countPopulation() == BitWidth - 1;
245   }
246
247   /// This checks to see if the value of this APInt is the minimum unsigned
248   /// value for the APInt's bit width.
249   /// @brief Determine if this is the smallest unsigned value.
250   bool isMinValue() const {
251     return countPopulation() == 0;
252   }
253
254   /// This checks to see if the value of this APInt is the minimum signed
255   /// value for the APInt's bit width.
256   /// @brief Determine if this is the smallest signed value.
257   bool isMinSignedValue() const {
258     return BitWidth == 1 ? VAL == 1 :
259                            isNegative() && countPopulation() == 1;
260   }
261
262   /// @brief Check if this APInt has an N-bits integer value.
263   inline bool isIntN(uint32_t N) const {
264     assert(N && "N == 0 ???");
265     if (isSingleWord()) {
266       return VAL == (VAL & (~0ULL >> (64 - N)));
267     } else {
268       APInt Tmp(N, getNumWords(), pVal);
269       return Tmp == (*this);
270     }
271   }
272
273   /// @returns true if the argument APInt value is a power of two > 0.
274   bool isPowerOf2() const; 
275
276   /// isSignBit - Return true if this is the value returned by getSignBit.
277   bool isSignBit() const { return isMinSignedValue(); }
278   
279   /// This converts the APInt to a boolean value as a test against zero.
280   /// @brief Boolean conversion function. 
281   inline bool getBoolValue() const {
282     return *this != 0;
283   }
284
285   /// getLimitedValue - If this value is smaller than the specified limit,
286   /// return it, otherwise return the limit value.  This causes the value
287   /// to saturate to the limit.
288   uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
289     return (getActiveBits() > 64 || getZExtValue() > Limit) ?
290       Limit :  getZExtValue();
291   }
292
293   /// @}
294   /// @name Value Generators
295   /// @{
296   /// @brief Gets maximum unsigned value of APInt for specific bit width.
297   static APInt getMaxValue(uint32_t numBits) {
298     return APInt(numBits, 0).set();
299   }
300
301   /// @brief Gets maximum signed value of APInt for a specific bit width.
302   static APInt getSignedMaxValue(uint32_t numBits) {
303     return APInt(numBits, 0).set().clear(numBits - 1);
304   }
305
306   /// @brief Gets minimum unsigned value of APInt for a specific bit width.
307   static APInt getMinValue(uint32_t numBits) {
308     return APInt(numBits, 0);
309   }
310
311   /// @brief Gets minimum signed value of APInt for a specific bit width.
312   static APInt getSignedMinValue(uint32_t numBits) {
313     return APInt(numBits, 0).set(numBits - 1);
314   }
315
316   /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
317   /// it helps code readability when we want to get a SignBit.
318   /// @brief Get the SignBit for a specific bit width.
319   inline static APInt getSignBit(uint32_t BitWidth) {
320     return getSignedMinValue(BitWidth);
321   }
322
323   /// @returns the all-ones value for an APInt of the specified bit-width.
324   /// @brief Get the all-ones value.
325   static APInt getAllOnesValue(uint32_t numBits) {
326     return APInt(numBits, 0).set();
327   }
328
329   /// @returns the '0' value for an APInt of the specified bit-width.
330   /// @brief Get the '0' value.
331   static APInt getNullValue(uint32_t numBits) {
332     return APInt(numBits, 0);
333   }
334
335   /// Get an APInt with the same BitWidth as this APInt, just zero mask
336   /// the low bits and right shift to the least significant bit.
337   /// @returns the high "numBits" bits of this APInt.
338   APInt getHiBits(uint32_t numBits) const;
339
340   /// Get an APInt with the same BitWidth as this APInt, just zero mask
341   /// the high bits.
342   /// @returns the low "numBits" bits of this APInt.
343   APInt getLoBits(uint32_t numBits) const;
344
345   /// Constructs an APInt value that has a contiguous range of bits set. The
346   /// bits from loBit to hiBit will be set. All other bits will be zero. For
347   /// example, with parameters(32, 15, 0) you would get 0x0000FFFF. If hiBit is
348   /// less than loBit then the set bits "wrap". For example, with 
349   /// parameters (32, 3, 28), you would get 0xF000000F. 
350   /// @param numBits the intended bit width of the result
351   /// @param loBit the index of the lowest bit set.
352   /// @param hiBit the index of the highest bit set.
353   /// @returns An APInt value with the requested bits set.
354   /// @brief Get a value with a block of bits set.
355   static APInt getBitsSet(uint32_t numBits, uint32_t loBit, uint32_t hiBit) {
356     assert(hiBit < numBits && "hiBit out of range");
357     assert(loBit < numBits && "loBit out of range");
358     if (hiBit < loBit)
359       return getLowBitsSet(numBits, hiBit+1) |
360              getHighBitsSet(numBits, numBits-loBit+1);
361     return getLowBitsSet(numBits, hiBit-loBit+1).shl(loBit);
362   }
363
364   /// Constructs an APInt value that has the top hiBitsSet bits set.
365   /// @param numBits the bitwidth of the result
366   /// @param hiBitsSet the number of high-order bits set in the result.
367   /// @brief Get a value with high bits set
368   static APInt getHighBitsSet(uint32_t numBits, uint32_t hiBitsSet) {
369     assert(hiBitsSet <= numBits && "Too many bits to set!");
370     // Handle a degenerate case, to avoid shifting by word size
371     if (hiBitsSet == 0)
372       return APInt(numBits, 0);
373     uint32_t shiftAmt = numBits - hiBitsSet;
374     // For small values, return quickly
375     if (numBits <= APINT_BITS_PER_WORD)
376       return APInt(numBits, ~0ULL << shiftAmt);
377     return (~APInt(numBits, 0)).shl(shiftAmt);
378   }
379
380   /// Constructs an APInt value that has the bottom loBitsSet bits set.
381   /// @param numBits the bitwidth of the result
382   /// @param loBitsSet the number of low-order bits set in the result.
383   /// @brief Get a value with low bits set
384   static APInt getLowBitsSet(uint32_t numBits, uint32_t loBitsSet) {
385     assert(loBitsSet <= numBits && "Too many bits to set!");
386     // Handle a degenerate case, to avoid shifting by word size
387     if (loBitsSet == 0)
388       return APInt(numBits, 0);
389     if (loBitsSet == APINT_BITS_PER_WORD)
390       return APInt(numBits, -1ULL);
391     // For small values, return quickly
392     if (numBits < APINT_BITS_PER_WORD)
393       return APInt(numBits, (1ULL << loBitsSet) - 1);
394     return (~APInt(numBits, 0)).lshr(numBits - loBitsSet);
395   }
396
397   /// The hash value is computed as the sum of the words and the bit width.
398   /// @returns A hash value computed from the sum of the APInt words.
399   /// @brief Get a hash value based on this APInt
400   uint64_t getHashValue() const;
401
402   /// This function returns a pointer to the internal storage of the APInt. 
403   /// This is useful for writing out the APInt in binary form without any
404   /// conversions.
405   inline const uint64_t* getRawData() const {
406     if (isSingleWord())
407       return &VAL;
408     return &pVal[0];
409   }
410
411   /// @}
412   /// @name Unary Operators
413   /// @{
414   /// @returns a new APInt value representing *this incremented by one
415   /// @brief Postfix increment operator.
416   inline const APInt operator++(int) {
417     APInt API(*this);
418     ++(*this);
419     return API;
420   }
421
422   /// @returns *this incremented by one
423   /// @brief Prefix increment operator.
424   APInt& operator++();
425
426   /// @returns a new APInt representing *this decremented by one.
427   /// @brief Postfix decrement operator. 
428   inline const APInt operator--(int) {
429     APInt API(*this);
430     --(*this);
431     return API;
432   }
433
434   /// @returns *this decremented by one.
435   /// @brief Prefix decrement operator. 
436   APInt& operator--();
437
438   /// Performs a bitwise complement operation on this APInt. 
439   /// @returns an APInt that is the bitwise complement of *this
440   /// @brief Unary bitwise complement operator. 
441   APInt operator~() const;
442
443   /// Negates *this using two's complement logic.
444   /// @returns An APInt value representing the negation of *this.
445   /// @brief Unary negation operator
446   inline APInt operator-() const {
447     return APInt(BitWidth, 0) - (*this);
448   }
449
450   /// Performs logical negation operation on this APInt.
451   /// @returns true if *this is zero, false otherwise.
452   /// @brief Logical negation operator. 
453   bool operator !() const;
454
455   /// @}
456   /// @name Assignment Operators
457   /// @{
458   /// @returns *this after assignment of RHS.
459   /// @brief Copy assignment operator. 
460   APInt& operator=(const APInt& RHS);
461
462   /// The RHS value is assigned to *this. If the significant bits in RHS exceed
463   /// the bit width, the excess bits are truncated. If the bit width is larger
464   /// than 64, the value is zero filled in the unspecified high order bits.
465   /// @returns *this after assignment of RHS value.
466   /// @brief Assignment operator. 
467   APInt& operator=(uint64_t RHS);
468
469   /// Performs a bitwise AND operation on this APInt and RHS. The result is
470   /// assigned to *this. 
471   /// @returns *this after ANDing with RHS.
472   /// @brief Bitwise AND assignment operator. 
473   APInt& operator&=(const APInt& RHS);
474
475   /// Performs a bitwise OR operation on this APInt and RHS. The result is 
476   /// assigned *this;
477   /// @returns *this after ORing with RHS.
478   /// @brief Bitwise OR assignment operator. 
479   APInt& operator|=(const APInt& RHS);
480
481   /// Performs a bitwise XOR operation on this APInt and RHS. The result is
482   /// assigned to *this.
483   /// @returns *this after XORing with RHS.
484   /// @brief Bitwise XOR assignment operator. 
485   APInt& operator^=(const APInt& RHS);
486
487   /// Multiplies this APInt by RHS and assigns the result to *this.
488   /// @returns *this
489   /// @brief Multiplication assignment operator. 
490   APInt& operator*=(const APInt& RHS);
491
492   /// Adds RHS to *this and assigns the result to *this.
493   /// @returns *this
494   /// @brief Addition assignment operator. 
495   APInt& operator+=(const APInt& RHS);
496
497   /// Subtracts RHS from *this and assigns the result to *this.
498   /// @returns *this
499   /// @brief Subtraction assignment operator. 
500   APInt& operator-=(const APInt& RHS);
501
502   /// Shifts *this left by shiftAmt and assigns the result to *this.
503   /// @returns *this after shifting left by shiftAmt
504   /// @brief Left-shift assignment function.
505   inline APInt& operator<<=(uint32_t shiftAmt) {
506     *this = shl(shiftAmt);
507     return *this;
508   }
509
510   /// @}
511   /// @name Binary Operators
512   /// @{
513   /// Performs a bitwise AND operation on *this and RHS.
514   /// @returns An APInt value representing the bitwise AND of *this and RHS.
515   /// @brief Bitwise AND operator. 
516   APInt operator&(const APInt& RHS) const;
517   APInt And(const APInt& RHS) const {
518     return this->operator&(RHS);
519   }
520
521   /// Performs a bitwise OR operation on *this and RHS.
522   /// @returns An APInt value representing the bitwise OR of *this and RHS.
523   /// @brief Bitwise OR operator. 
524   APInt operator|(const APInt& RHS) const;
525   APInt Or(const APInt& RHS) const {
526     return this->operator|(RHS);
527   }
528
529   /// Performs a bitwise XOR operation on *this and RHS.
530   /// @returns An APInt value representing the bitwise XOR of *this and RHS.
531   /// @brief Bitwise XOR operator. 
532   APInt operator^(const APInt& RHS) const;
533   APInt Xor(const APInt& RHS) const {
534     return this->operator^(RHS);
535   }
536
537   /// Multiplies this APInt by RHS and returns the result.
538   /// @brief Multiplication operator. 
539   APInt operator*(const APInt& RHS) const;
540
541   /// Adds RHS to this APInt and returns the result.
542   /// @brief Addition operator. 
543   APInt operator+(const APInt& RHS) const;
544   APInt operator+(uint64_t RHS) const {
545     return (*this) + APInt(BitWidth, RHS);
546   }
547
548   /// Subtracts RHS from this APInt and returns the result.
549   /// @brief Subtraction operator. 
550   APInt operator-(const APInt& RHS) const;
551   APInt operator-(uint64_t RHS) const {
552     return (*this) - APInt(BitWidth, RHS);
553   }
554   
555   APInt operator<<(unsigned Bits) const {
556     return shl(Bits);
557   }
558
559   /// Arithmetic right-shift this APInt by shiftAmt.
560   /// @brief Arithmetic right-shift function.
561   APInt ashr(uint32_t shiftAmt) const;
562
563   /// Logical right-shift this APInt by shiftAmt.
564   /// @brief Logical right-shift function.
565   APInt lshr(uint32_t shiftAmt) const;
566
567   /// Left-shift this APInt by shiftAmt.
568   /// @brief Left-shift function.
569   APInt shl(uint32_t shiftAmt) const;
570
571   /// @brief Rotate left by rotateAmt.
572   APInt rotl(uint32_t rotateAmt) const;
573
574   /// @brief Rotate right by rotateAmt.
575   APInt rotr(uint32_t rotateAmt) const;
576
577   /// Perform an unsigned divide operation on this APInt by RHS. Both this and
578   /// RHS are treated as unsigned quantities for purposes of this division.
579   /// @returns a new APInt value containing the division result
580   /// @brief Unsigned division operation.
581   APInt udiv(const APInt& RHS) const;
582
583   /// Signed divide this APInt by APInt RHS.
584   /// @brief Signed division function for APInt.
585   inline APInt sdiv(const APInt& RHS) const {
586     if (isNegative())
587       if (RHS.isNegative())
588         return (-(*this)).udiv(-RHS);
589       else
590         return -((-(*this)).udiv(RHS));
591     else if (RHS.isNegative())
592       return -(this->udiv(-RHS));
593     return this->udiv(RHS);
594   }
595
596   /// Perform an unsigned remainder operation on this APInt with RHS being the
597   /// divisor. Both this and RHS are treated as unsigned quantities for purposes
598   /// of this operation. Note that this is a true remainder operation and not
599   /// a modulo operation because the sign follows the sign of the dividend
600   /// which is *this.
601   /// @returns a new APInt value containing the remainder result
602   /// @brief Unsigned remainder operation.
603   APInt urem(const APInt& RHS) const;
604
605   /// Signed remainder operation on APInt.
606   /// @brief Function for signed remainder operation.
607   inline APInt srem(const APInt& RHS) const {
608     if (isNegative())
609       if (RHS.isNegative())
610         return -((-(*this)).urem(-RHS));
611       else
612         return -((-(*this)).urem(RHS));
613     else if (RHS.isNegative())
614       return this->urem(-RHS);
615     return this->urem(RHS);
616   }
617
618   /// Sometimes it is convenient to divide two APInt values and obtain both
619   /// the quotient and remainder. This function does both operations in the
620   /// same computation making it a little more efficient.
621   /// @brief Dual division/remainder interface.
622   static void udivrem(const APInt &LHS, const APInt &RHS, 
623                       APInt &Quotient, APInt &Remainder);
624
625   static void sdivrem(const APInt &LHS, const APInt &RHS,
626                       APInt &Quotient, APInt &Remainder)
627   {
628     if (LHS.isNegative()) {
629       if (RHS.isNegative())
630         APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
631       else
632         APInt::udivrem(-LHS, RHS, Quotient, Remainder);
633       Quotient = -Quotient;
634       Remainder = -Remainder;
635     } else if (RHS.isNegative()) {
636       APInt::udivrem(LHS, -RHS, Quotient, Remainder);
637       Quotient = -Quotient;
638     } else {
639       APInt::udivrem(LHS, RHS, Quotient, Remainder);
640     }
641   }
642
643   /// @returns the bit value at bitPosition
644   /// @brief Array-indexing support.
645   bool operator[](uint32_t bitPosition) const;
646
647   /// @}
648   /// @name Comparison Operators
649   /// @{
650   /// Compares this APInt with RHS for the validity of the equality
651   /// relationship.
652   /// @brief Equality operator. 
653   bool operator==(const APInt& RHS) const;
654
655   /// Compares this APInt with a uint64_t for the validity of the equality 
656   /// relationship.
657   /// @returns true if *this == Val
658   /// @brief Equality operator.
659   bool operator==(uint64_t Val) const;
660
661   /// Compares this APInt with RHS for the validity of the equality
662   /// relationship.
663   /// @returns true if *this == Val
664   /// @brief Equality comparison.
665   bool eq(const APInt &RHS) const {
666     return (*this) == RHS; 
667   }
668
669   /// Compares this APInt with RHS for the validity of the inequality
670   /// relationship.
671   /// @returns true if *this != Val
672   /// @brief Inequality operator. 
673   inline bool operator!=(const APInt& RHS) const {
674     return !((*this) == RHS);
675   }
676
677   /// Compares this APInt with a uint64_t for the validity of the inequality 
678   /// relationship.
679   /// @returns true if *this != Val
680   /// @brief Inequality operator. 
681   inline bool operator!=(uint64_t Val) const {
682     return !((*this) == Val);
683   }
684   
685   /// Compares this APInt with RHS for the validity of the inequality
686   /// relationship.
687   /// @returns true if *this != Val
688   /// @brief Inequality comparison
689   bool ne(const APInt &RHS) const {
690     return !((*this) == RHS);
691   }
692
693   /// Regards both *this and RHS as unsigned quantities and compares them for
694   /// the validity of the less-than relationship.
695   /// @returns true if *this < RHS when both are considered unsigned.
696   /// @brief Unsigned less than comparison
697   bool ult(const APInt& RHS) const;
698
699   /// Regards both *this and RHS as signed quantities and compares them for
700   /// validity of the less-than relationship.
701   /// @returns true if *this < RHS when both are considered signed.
702   /// @brief Signed less than comparison
703   bool slt(const APInt& RHS) const;
704
705   /// Regards both *this and RHS as unsigned quantities and compares them for
706   /// validity of the less-or-equal relationship.
707   /// @returns true if *this <= RHS when both are considered unsigned.
708   /// @brief Unsigned less or equal comparison
709   bool ule(const APInt& RHS) const {
710     return ult(RHS) || eq(RHS);
711   }
712
713   /// Regards both *this and RHS as signed quantities and compares them for
714   /// validity of the less-or-equal relationship.
715   /// @returns true if *this <= RHS when both are considered signed.
716   /// @brief Signed less or equal comparison
717   bool sle(const APInt& RHS) const {
718     return slt(RHS) || eq(RHS);
719   }
720
721   /// Regards both *this and RHS as unsigned quantities and compares them for
722   /// the validity of the greater-than relationship.
723   /// @returns true if *this > RHS when both are considered unsigned.
724   /// @brief Unsigned greather than comparison
725   bool ugt(const APInt& RHS) const {
726     return !ult(RHS) && !eq(RHS);
727   }
728
729   /// Regards both *this and RHS as signed quantities and compares them for
730   /// the validity of the greater-than relationship.
731   /// @returns true if *this > RHS when both are considered signed.
732   /// @brief Signed greather than comparison
733   bool sgt(const APInt& RHS) const {
734     return !slt(RHS) && !eq(RHS);
735   }
736
737   /// Regards both *this and RHS as unsigned quantities and compares them for
738   /// validity of the greater-or-equal relationship.
739   /// @returns true if *this >= RHS when both are considered unsigned.
740   /// @brief Unsigned greater or equal comparison
741   bool uge(const APInt& RHS) const {
742     return !ult(RHS);
743   }
744
745   /// Regards both *this and RHS as signed quantities and compares them for
746   /// validity of the greater-or-equal relationship.
747   /// @returns true if *this >= RHS when both are considered signed.
748   /// @brief Signed greather or equal comparison
749   bool sge(const APInt& RHS) const {
750     return !slt(RHS);
751   }
752
753   /// @}
754   /// @name Resizing Operators
755   /// @{
756   /// Truncate the APInt to a specified width. It is an error to specify a width
757   /// that is greater than or equal to the current width. 
758   /// @brief Truncate to new width.
759   APInt &trunc(uint32_t width);
760
761   /// This operation sign extends the APInt to a new width. If the high order
762   /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
763   /// It is an error to specify a width that is less than or equal to the 
764   /// current width.
765   /// @brief Sign extend to a new width.
766   APInt &sext(uint32_t width);
767
768   /// This operation zero extends the APInt to a new width. The high order bits
769   /// are filled with 0 bits.  It is an error to specify a width that is less 
770   /// than or equal to the current width.
771   /// @brief Zero extend to a new width.
772   APInt &zext(uint32_t width);
773
774   /// Make this APInt have the bit width given by \p width. The value is sign
775   /// extended, truncated, or left alone to make it that width.
776   /// @brief Sign extend or truncate to width
777   APInt &sextOrTrunc(uint32_t width);
778
779   /// Make this APInt have the bit width given by \p width. The value is zero
780   /// extended, truncated, or left alone to make it that width.
781   /// @brief Zero extend or truncate to width
782   APInt &zextOrTrunc(uint32_t width);
783
784   /// @}
785   /// @name Bit Manipulation Operators
786   /// @{
787   /// @brief Set every bit to 1.
788   APInt& set();
789
790   /// Set the given bit to 1 whose position is given as "bitPosition".
791   /// @brief Set a given bit to 1.
792   APInt& set(uint32_t bitPosition);
793
794   /// @brief Set every bit to 0.
795   APInt& clear();
796
797   /// Set the given bit to 0 whose position is given as "bitPosition".
798   /// @brief Set a given bit to 0.
799   APInt& clear(uint32_t bitPosition);
800
801   /// @brief Toggle every bit to its opposite value.
802   APInt& flip();
803
804   /// Toggle a given bit to its opposite value whose position is given 
805   /// as "bitPosition".
806   /// @brief Toggles a given bit to its opposite value.
807   APInt& flip(uint32_t bitPosition);
808
809   /// @}
810   /// @name Value Characterization Functions
811   /// @{
812
813   /// @returns the total number of bits.
814   inline uint32_t getBitWidth() const { 
815     return BitWidth; 
816   }
817
818   /// Here one word's bitwidth equals to that of uint64_t.
819   /// @returns the number of words to hold the integer value of this APInt.
820   /// @brief Get the number of words.
821   inline uint32_t getNumWords() const {
822     return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
823   }
824
825   /// This function returns the number of active bits which is defined as the
826   /// bit width minus the number of leading zeros. This is used in several
827   /// computations to see how "wide" the value is.
828   /// @brief Compute the number of active bits in the value
829   inline uint32_t getActiveBits() const {
830     return BitWidth - countLeadingZeros();
831   }
832
833   /// This function returns the number of active words in the value of this
834   /// APInt. This is used in conjunction with getActiveData to extract the raw
835   /// value of the APInt.
836   inline uint32_t getActiveWords() const {
837     return whichWord(getActiveBits()-1) + 1;
838   }
839
840   /// Computes the minimum bit width for this APInt while considering it to be
841   /// a signed (and probably negative) value. If the value is not negative, 
842   /// this function returns the same value as getActiveBits(). Otherwise, it
843   /// returns the smallest bit width that will retain the negative value. For
844   /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
845   /// for -1, this function will always return 1.
846   /// @brief Get the minimum bit size for this signed APInt 
847   inline uint32_t getMinSignedBits() const {
848     if (isNegative())
849       return BitWidth - countLeadingOnes() + 1;
850     return getActiveBits();
851   }
852
853   /// This method attempts to return the value of this APInt as a zero extended
854   /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
855   /// uint64_t. Otherwise an assertion will result.
856   /// @brief Get zero extended value
857   inline uint64_t getZExtValue() const {
858     if (isSingleWord())
859       return VAL;
860     assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
861     return pVal[0];
862   }
863
864   /// This method attempts to return the value of this APInt as a sign extended
865   /// int64_t. The bit width must be <= 64 or the value must fit within an
866   /// int64_t. Otherwise an assertion will result.
867   /// @brief Get sign extended value
868   inline int64_t getSExtValue() const {
869     if (isSingleWord())
870       return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >> 
871                      (APINT_BITS_PER_WORD - BitWidth);
872     assert(getActiveBits() <= 64 && "Too many bits for int64_t");
873     return int64_t(pVal[0]);
874   }
875
876   /// This method determines how many bits are required to hold the APInt
877   /// equivalent of the string given by \p str of length \p slen.
878   /// @brief Get bits required for string value.
879   static uint32_t getBitsNeeded(const char* str, uint32_t slen, uint8_t radix);
880
881   /// countLeadingZeros - This function is an APInt version of the
882   /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
883   /// of zeros from the most significant bit to the first one bit.
884   /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
885   /// @returns the number of zeros from the most significant bit to the first
886   /// one bits.
887   /// @brief Count the number of leading one bits.
888   uint32_t countLeadingZeros() const;
889
890   /// countLeadingOnes - This function counts the number of contiguous 1 bits
891   /// in the high order bits. The count stops when the first 0 bit is reached.
892   /// @returns 0 if the high order bit is not set
893   /// @returns the number of 1 bits from the most significant to the least
894   /// @brief Count the number of leading one bits.
895   uint32_t countLeadingOnes() const;
896
897   /// countTrailingZeros - This function is an APInt version of the 
898   /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts 
899   /// the number of zeros from the least significant bit to the first one bit.
900   /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
901   /// @returns the number of zeros from the least significant bit to the first
902   /// one bit.
903   /// @brief Count the number of trailing zero bits.
904   uint32_t countTrailingZeros() const;
905
906   /// countPopulation - This function is an APInt version of the
907   /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
908   /// of 1 bits in the APInt value. 
909   /// @returns 0 if the value is zero.
910   /// @returns the number of set bits.
911   /// @brief Count the number of bits set.
912   uint32_t countPopulation() const; 
913
914   /// @}
915   /// @name Conversion Functions
916   /// @{
917
918   /// This is used internally to convert an APInt to a string.
919   /// @brief Converts an APInt to a std::string
920   std::string toString(uint8_t radix, bool wantSigned) const;
921
922   /// Considers the APInt to be unsigned and converts it into a string in the
923   /// radix given. The radix can be 2, 8, 10 or 16.
924   /// @returns a character interpretation of the APInt
925   /// @brief Convert unsigned APInt to string representation.
926   inline std::string toString(uint8_t radix = 10) const {
927     return toString(radix, false);
928   }
929
930   /// Considers the APInt to be unsigned and converts it into a string in the
931   /// radix given. The radix can be 2, 8, 10 or 16.
932   /// @returns a character interpretation of the APInt
933   /// @brief Convert unsigned APInt to string representation.
934   inline std::string toStringSigned(uint8_t radix = 10) const {
935     return toString(radix, true);
936   }
937
938   /// @returns a byte-swapped representation of this APInt Value.
939   APInt byteSwap() const;
940
941   /// @brief Converts this APInt to a double value.
942   double roundToDouble(bool isSigned) const;
943
944   /// @brief Converts this unsigned APInt to a double value.
945   double roundToDouble() const {
946     return roundToDouble(false);
947   }
948
949   /// @brief Converts this signed APInt to a double value.
950   double signedRoundToDouble() const {
951     return roundToDouble(true);
952   }
953
954   /// The conversion does not do a translation from integer to double, it just
955   /// re-interprets the bits as a double. Note that it is valid to do this on
956   /// any bit width. Exactly 64 bits will be translated.
957   /// @brief Converts APInt bits to a double
958   double bitsToDouble() const {
959     union {
960       uint64_t I;
961       double D;
962     } T;
963     T.I = (isSingleWord() ? VAL : pVal[0]);
964     return T.D;
965   }
966
967   /// The conversion does not do a translation from integer to float, it just
968   /// re-interprets the bits as a float. Note that it is valid to do this on
969   /// any bit width. Exactly 32 bits will be translated.
970   /// @brief Converts APInt bits to a double
971   float bitsToFloat() const {
972     union {
973       uint32_t I;
974       float F;
975     } T;
976     T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
977     return T.F;
978   }
979
980   /// The conversion does not do a translation from double to integer, it just
981   /// re-interprets the bits of the double. Note that it is valid to do this on
982   /// any bit width but bits from V may get truncated.
983   /// @brief Converts a double to APInt bits.
984   APInt& doubleToBits(double V) {
985     union {
986       uint64_t I;
987       double D;
988     } T;
989     T.D = V;
990     if (isSingleWord())
991       VAL = T.I;
992     else
993       pVal[0] = T.I;
994     return clearUnusedBits();
995   }
996
997   /// The conversion does not do a translation from float to integer, it just
998   /// re-interprets the bits of the float. Note that it is valid to do this on
999   /// any bit width but bits from V may get truncated.
1000   /// @brief Converts a float to APInt bits.
1001   APInt& floatToBits(float V) {
1002     union {
1003       uint32_t I;
1004       float F;
1005     } T;
1006     T.F = V;
1007     if (isSingleWord())
1008       VAL = T.I;
1009     else
1010       pVal[0] = T.I;
1011     return clearUnusedBits();
1012   }
1013
1014   /// @}
1015   /// @name Mathematics Operations
1016   /// @{
1017
1018   /// @returns the floor log base 2 of this APInt.
1019   inline uint32_t logBase2() const {
1020     return BitWidth - 1 - countLeadingZeros();
1021   }
1022
1023   /// @returns the log base 2 of this APInt if its an exact power of two, -1
1024   /// otherwise
1025   inline int32_t exactLogBase2() const {
1026     if (!isPowerOf2())
1027       return -1;
1028     return logBase2();
1029   }
1030
1031   /// @brief Compute the square root
1032   APInt sqrt() const;
1033
1034   /// If *this is < 0 then return -(*this), otherwise *this;
1035   /// @brief Get the absolute value;
1036   APInt abs() const {
1037     if (isNegative())
1038       return -(*this);
1039     return *this;
1040   }
1041   /// @}
1042 };
1043
1044 inline bool operator==(uint64_t V1, const APInt& V2) {
1045   return V2 == V1;
1046 }
1047
1048 inline bool operator!=(uint64_t V1, const APInt& V2) {
1049   return V2 != V1;
1050 }
1051
1052 namespace APIntOps {
1053
1054 /// @brief Determine the smaller of two APInts considered to be signed.
1055 inline APInt smin(const APInt &A, const APInt &B) {
1056   return A.slt(B) ? A : B;
1057 }
1058
1059 /// @brief Determine the larger of two APInts considered to be signed.
1060 inline APInt smax(const APInt &A, const APInt &B) {
1061   return A.sgt(B) ? A : B;
1062 }
1063
1064 /// @brief Determine the smaller of two APInts considered to be signed.
1065 inline APInt umin(const APInt &A, const APInt &B) {
1066   return A.ult(B) ? A : B;
1067 }
1068
1069 /// @brief Determine the larger of two APInts considered to be unsigned.
1070 inline APInt umax(const APInt &A, const APInt &B) {
1071   return A.ugt(B) ? A : B;
1072 }
1073
1074 /// @brief Check if the specified APInt has a N-bits integer value.
1075 inline bool isIntN(uint32_t N, const APInt& APIVal) {
1076   return APIVal.isIntN(N);
1077 }
1078
1079 /// @returns true if the argument APInt value is a sequence of ones
1080 /// starting at the least significant bit with the remainder zero.
1081 inline bool isMask(uint32_t numBits, const APInt& APIVal) {
1082   return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
1083 }
1084
1085 /// @returns true if the argument APInt value contains a sequence of ones
1086 /// with the remainder zero.
1087 inline bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
1088   return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1089 }
1090
1091 /// @returns a byte-swapped representation of the specified APInt Value.
1092 inline APInt byteSwap(const APInt& APIVal) {
1093   return APIVal.byteSwap();
1094 }
1095
1096 /// @returns the floor log base 2 of the specified APInt value.
1097 inline uint32_t logBase2(const APInt& APIVal) {
1098   return APIVal.logBase2(); 
1099 }
1100
1101 /// GreatestCommonDivisor - This function returns the greatest common
1102 /// divisor of the two APInt values using Enclid's algorithm.
1103 /// @returns the greatest common divisor of Val1 and Val2
1104 /// @brief Compute GCD of two APInt values.
1105 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1106
1107 /// Treats the APInt as an unsigned value for conversion purposes.
1108 /// @brief Converts the given APInt to a double value.
1109 inline double RoundAPIntToDouble(const APInt& APIVal) {
1110   return APIVal.roundToDouble();
1111 }
1112
1113 /// Treats the APInt as a signed value for conversion purposes.
1114 /// @brief Converts the given APInt to a double value.
1115 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1116   return APIVal.signedRoundToDouble();
1117 }
1118
1119 /// @brief Converts the given APInt to a float vlalue.
1120 inline float RoundAPIntToFloat(const APInt& APIVal) {
1121   return float(RoundAPIntToDouble(APIVal));
1122 }
1123
1124 /// Treast the APInt as a signed value for conversion purposes.
1125 /// @brief Converts the given APInt to a float value.
1126 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1127   return float(APIVal.signedRoundToDouble());
1128 }
1129
1130 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1131 /// @brief Converts the given double value into a APInt.
1132 APInt RoundDoubleToAPInt(double Double, uint32_t width);
1133
1134 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1135 /// @brief Converts a float value into a APInt.
1136 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
1137   return RoundDoubleToAPInt(double(Float), width);
1138 }
1139
1140 /// Arithmetic right-shift the APInt by shiftAmt.
1141 /// @brief Arithmetic right-shift function.
1142 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
1143   return LHS.ashr(shiftAmt);
1144 }
1145
1146 /// Logical right-shift the APInt by shiftAmt.
1147 /// @brief Logical right-shift function.
1148 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
1149   return LHS.lshr(shiftAmt);
1150 }
1151
1152 /// Left-shift the APInt by shiftAmt.
1153 /// @brief Left-shift function.
1154 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
1155   return LHS.shl(shiftAmt);
1156 }
1157
1158 /// Signed divide APInt LHS by APInt RHS.
1159 /// @brief Signed division function for APInt.
1160 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1161   return LHS.sdiv(RHS);
1162 }
1163
1164 /// Unsigned divide APInt LHS by APInt RHS.
1165 /// @brief Unsigned division function for APInt.
1166 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1167   return LHS.udiv(RHS);
1168 }
1169
1170 /// Signed remainder operation on APInt.
1171 /// @brief Function for signed remainder operation.
1172 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1173   return LHS.srem(RHS);
1174 }
1175
1176 /// Unsigned remainder operation on APInt.
1177 /// @brief Function for unsigned remainder operation.
1178 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1179   return LHS.urem(RHS);
1180 }
1181
1182 /// Performs multiplication on APInt values.
1183 /// @brief Function for multiplication operation.
1184 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1185   return LHS * RHS;
1186 }
1187
1188 /// Performs addition on APInt values.
1189 /// @brief Function for addition operation.
1190 inline APInt add(const APInt& LHS, const APInt& RHS) {
1191   return LHS + RHS;
1192 }
1193
1194 /// Performs subtraction on APInt values.
1195 /// @brief Function for subtraction operation.
1196 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1197   return LHS - RHS;
1198 }
1199
1200 /// Performs bitwise AND operation on APInt LHS and 
1201 /// APInt RHS.
1202 /// @brief Bitwise AND function for APInt.
1203 inline APInt And(const APInt& LHS, const APInt& RHS) {
1204   return LHS & RHS;
1205 }
1206
1207 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1208 /// @brief Bitwise OR function for APInt. 
1209 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1210   return LHS | RHS;
1211 }
1212
1213 /// Performs bitwise XOR operation on APInt.
1214 /// @brief Bitwise XOR function for APInt.
1215 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1216   return LHS ^ RHS;
1217
1218
1219 /// Performs a bitwise complement operation on APInt.
1220 /// @brief Bitwise complement function. 
1221 inline APInt Not(const APInt& APIVal) {
1222   return ~APIVal;
1223 }
1224
1225 } // End of APIntOps namespace
1226
1227 } // End of llvm namespace
1228
1229 #endif