661276e0789285bf9cc198e89874eb95a7af9854
[oota-llvm.git] / include / llvm / ADT / APInt.h
1 //===-- llvm/Support/APInt.h - For Arbitrary Precision Integer -*- C++ -*--===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Sheng Zhou and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a class to represent arbitrary precision integral
11 // constant values.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_APINT_H
16 #define LLVM_APINT_H
17
18 #include "llvm/Support/DataTypes.h"
19 #include <cassert>
20 #include <string>
21
22 namespace llvm {
23
24 /// Forward declaration.
25 class APInt;
26 namespace APIntOps {
27   APInt udiv(const APInt& LHS, const APInt& RHS);
28   APInt urem(const APInt& LHS, const APInt& RHS);
29 }
30
31 //===----------------------------------------------------------------------===//
32 //                              APInt Class
33 //===----------------------------------------------------------------------===//
34
35 /// APInt - This class represents arbitrary precision constant integral values.
36 /// It is a functional replacement for common case unsigned integer type like 
37 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width 
38 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
39 /// than 64-bits of precision. APInt provides a variety of arithmetic operators 
40 /// and methods to manipulate integer values of any bit-width. It supports both
41 /// the typical integer arithmetic and comparison operations as well as bitwise
42 /// manipulation.
43 ///
44 /// The class has several invariants worth noting:
45 ///   * All bit, byte, and word positions are zero-based.
46 ///   * Once the bit width is set, it doesn't change except by the Truncate, 
47 ///     SignExtend, or ZeroExtend operations.
48 ///   * All binary operators must be on APInt instances of the same bit width.
49 ///     Attempting to use these operators on instances with different bit 
50 ///     widths will yield an assertion.
51 ///   * The value is stored canonically as an unsigned value. For operations
52 ///     where it makes a difference, there are both signed and unsigned variants
53 ///     of the operation. For example, sdiv and udiv. However, because the bit
54 ///     widths must be the same, operations such as Mul and Add produce the same
55 ///     results regardless of whether the values are interpreted as signed or
56 ///     not.
57 ///   * In general, the class tries to follow the style of computation that LLVM
58 ///     uses in its IR. This simplifies its use for LLVM.
59 ///
60 /// @brief Class for arbitrary precision integers.
61 class APInt {
62 public:
63   uint32_t BitWidth;      ///< The number of bits in this APInt.
64
65   /// This union is used to store the integer value. When the
66   /// integer bit-width <= 64, it uses VAL; 
67   /// otherwise it uses the pVal.
68   union {
69     uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
70     uint64_t *pVal;  ///< Used to store the >64 bits integer value.
71   };
72
73   /// This enum is just used to hold a constant we needed for APInt.
74   enum {
75     APINT_BITS_PER_WORD = sizeof(uint64_t) * 8
76   };
77
78   /// Here one word's bitwidth equals to that of uint64_t.
79   /// @returns the number of words to hold the integer value of this APInt.
80   /// @brief Get the number of words.
81   inline uint32_t getNumWords() const {
82     return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
83   }
84
85   /// @returns true if the number of bits <= 64, false otherwise.
86   /// @brief Determine if this APInt just has one word to store value.
87   inline bool isSingleWord() const { 
88     return BitWidth <= APINT_BITS_PER_WORD; 
89   }
90
91   /// @returns the word position for the specified bit position.
92   static inline uint32_t whichWord(uint32_t bitPosition) { 
93     return bitPosition / APINT_BITS_PER_WORD; 
94   }
95
96   /// @returns the bit position in a word for the specified bit position 
97   /// in APInt.
98   static inline uint32_t whichBit(uint32_t bitPosition) { 
99     return bitPosition % APINT_BITS_PER_WORD; 
100   }
101
102   /// @returns a uint64_t type integer with just bit position at
103   /// "whichBit(bitPosition)" setting, others zero.
104   static inline uint64_t maskBit(uint32_t bitPosition) { 
105     return (static_cast<uint64_t>(1)) << whichBit(bitPosition); 
106   }
107
108   /// This method is used internally to clear the to "N" bits that are not used
109   /// by the APInt. This is needed after a word is assigned a value to ensure 
110   /// that those bits are zero'd out.
111   /// @brief Clear high order bits
112   inline void clearUnusedBits() {
113     if (isSingleWord())
114       VAL &= ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth);
115     else
116       pVal[getNumWords() - 1] &= ~uint64_t(0ULL) >> 
117         (APINT_BITS_PER_WORD - (whichBit(BitWidth - 1) + 1));
118   }
119
120   /// @returns the corresponding word for the specified bit position.
121   /// This is a constant version.
122   inline uint64_t getWord(uint32_t bitPosition) const { 
123     return isSingleWord() ? VAL : pVal[whichWord(bitPosition)]; 
124   }
125
126   /// @brief Converts a char array into an integer.
127   void fromString(uint32_t numBits, const char *StrStart, uint32_t slen, 
128                   uint8_t radix);
129
130 public:
131   /// @brief Create a new APInt of numBits bit-width, and initialized as val.
132   APInt(uint32_t numBits, uint64_t val);
133
134   /// @brief Create a new APInt of numBits bit-width, and initialized as 
135   /// bigVal[].
136   APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
137
138   /// @brief Create a new APInt by translating the string represented 
139   /// integer value.
140   APInt(uint32_t numBits, const std::string& Val, uint8_t radix);
141
142   /// @brief Create a new APInt by translating the char array represented
143   /// integer value.
144   APInt(uint32_t numBits, const char StrStart[], uint32_t slen, uint8_t radix);
145
146   /// @brief Copy Constructor.
147   APInt(const APInt& API);
148
149   /// @brief Destructor.
150   ~APInt();
151
152   /// @brief Copy assignment operator. 
153   APInt& operator=(const APInt& RHS);
154
155   /// Assigns an integer value to the APInt.
156   /// @brief Assignment operator. 
157   APInt& operator=(uint64_t RHS);
158
159   /// Increments the APInt by one.
160   /// @brief Postfix increment operator.
161   inline const APInt operator++(int) {
162     APInt API(*this);
163     ++(*this);
164     return API;
165   }
166
167   /// Increments the APInt by one.
168   /// @brief Prefix increment operator.
169   APInt& operator++();
170
171   /// Decrements the APInt by one.
172   /// @brief Postfix decrement operator. 
173   inline const APInt operator--(int) {
174     APInt API(*this);
175     --(*this);
176     return API;
177   }
178
179   /// Decrements the APInt by one.
180   /// @brief Prefix decrement operator. 
181   APInt& operator--();
182
183   /// Performs bitwise AND operation on this APInt and the given APInt& RHS, 
184   /// assigns the result to this APInt.
185   /// @brief Bitwise AND assignment operator. 
186   APInt& operator&=(const APInt& RHS);
187
188   /// Performs bitwise OR operation on this APInt and the given APInt& RHS, 
189   /// assigns the result to this APInt.
190   /// @brief Bitwise OR assignment operator. 
191   APInt& operator|=(const APInt& RHS);
192
193   /// Performs bitwise XOR operation on this APInt and the given APInt& RHS, 
194   /// assigns the result to this APInt.
195   /// @brief Bitwise XOR assignment operator. 
196   APInt& operator^=(const APInt& RHS);
197
198   /// Performs a bitwise complement operation on this APInt.
199   /// @brief Bitwise complement operator. 
200   APInt operator~() const;
201
202   /// Multiplies this APInt by the  given APInt& RHS and 
203   /// assigns the result to this APInt.
204   /// @brief Multiplication assignment operator. 
205   APInt& operator*=(const APInt& RHS);
206
207   /// Adds this APInt by the given APInt& RHS and 
208   /// assigns the result to this APInt.
209   /// @brief Addition assignment operator. 
210   APInt& operator+=(const APInt& RHS);
211
212   /// Subtracts this APInt by the given APInt &RHS and 
213   /// assigns the result to this APInt.
214   /// @brief Subtraction assignment operator. 
215   APInt& operator-=(const APInt& RHS);
216
217   /// Performs bitwise AND operation on this APInt and 
218   /// the given APInt& RHS.
219   /// @brief Bitwise AND operator. 
220   APInt operator&(const APInt& RHS) const;
221
222   /// Performs bitwise OR operation on this APInt and the given APInt& RHS.
223   /// @brief Bitwise OR operator. 
224   APInt operator|(const APInt& RHS) const;
225
226   /// Performs bitwise XOR operation on this APInt and the given APInt& RHS.
227   /// @brief Bitwise XOR operator. 
228   APInt operator^(const APInt& RHS) const;
229
230   /// Performs logical negation operation on this APInt.
231   /// @brief Logical negation operator. 
232   bool operator !() const;
233
234   /// Multiplies this APInt by the given APInt& RHS.
235   /// @brief Multiplication operator. 
236   APInt operator*(const APInt& RHS) const;
237
238   /// Adds this APInt by the given APInt& RHS.
239   /// @brief Addition operator. 
240   APInt operator+(const APInt& RHS) const;
241
242   /// Subtracts this APInt by the given APInt& RHS
243   /// @brief Subtraction operator. 
244   APInt operator-(const APInt& RHS) const;
245
246   /// @brief Unary negation operator
247   inline APInt operator-() const {
248     return APInt(BitWidth, 0) - (*this);
249   }
250
251   /// @brief Array-indexing support.
252   bool operator[](uint32_t bitPosition) const;
253
254   /// Compare this APInt with the given APInt& RHS 
255   /// for the validity of the equality relationship.
256   /// @brief Equality operator. 
257   bool operator==(const APInt& RHS) const;
258
259   /// Compare this APInt with the given uint64_t value
260   /// for the validity of the equality relationship.
261   /// @brief Equality operator.
262   bool operator==(uint64_t Val) const;
263
264   /// Compare this APInt with the given APInt& RHS 
265   /// for the validity of the inequality relationship.
266   /// @brief Inequality operator. 
267   inline bool operator!=(const APInt& RHS) const {
268     return !((*this) == RHS);
269   }
270
271   /// Compare this APInt with the given uint64_t value 
272   /// for the validity of the inequality relationship.
273   /// @brief Inequality operator. 
274   inline bool operator!=(uint64_t Val) const {
275     return !((*this) == Val);
276   }
277   
278   /// @brief Equality comparison
279   bool eq(const APInt &RHS) const {
280     return (*this) == RHS; 
281   }
282
283   /// @brief Inequality comparison
284   bool ne(const APInt &RHS) const {
285     return !((*this) == RHS);
286   }
287
288   /// @brief Unsigned less than comparison
289   bool ult(const APInt& RHS) const;
290
291   /// @brief Signed less than comparison
292   bool slt(const APInt& RHS) const;
293
294   /// @brief Unsigned less or equal comparison
295   bool ule(const APInt& RHS) const {
296     return ult(RHS) || eq(RHS);
297   }
298
299   /// @brief Signed less or equal comparison
300   bool sle(const APInt& RHS) const {
301     return slt(RHS) || eq(RHS);
302   }
303
304   /// @brief Unsigned greather than comparison
305   bool ugt(const APInt& RHS) const {
306     return !ult(RHS) && !eq(RHS);
307   }
308
309   /// @brief Signed greather than comparison
310   bool sgt(const APInt& RHS) const {
311     return !slt(RHS) && !eq(RHS);
312   }
313
314   /// @brief Unsigned greater or equal comparison
315   bool uge(const APInt& RHS) const {
316     return !ult(RHS);
317   }
318
319   /// @brief Signed greather or equal comparison
320   bool sge(const APInt& RHS) const {
321     return !slt(RHS);
322   }
323
324   /// Arithmetic right-shift this APInt by shiftAmt.
325   /// @brief Arithmetic right-shift function.
326   APInt ashr(uint32_t shiftAmt) const;
327
328   /// Logical right-shift this APInt by shiftAmt.
329   /// @brief Logical right-shift function.
330   APInt lshr(uint32_t shiftAmt) const;
331
332   /// Left-shift this APInt by shiftAmt.
333   /// @brief Left-shift function.
334   APInt shl(uint32_t shiftAmt) const;
335
336   /// Signed divide this APInt by APInt RHS.
337   /// @brief Signed division function for APInt.
338   inline APInt sdiv(const APInt& RHS) const {
339     bool isNegativeLHS = (*this)[BitWidth - 1];
340     bool isNegativeRHS = RHS[RHS.BitWidth - 1];
341     APInt Result = APIntOps::udiv(
342         isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
343     return isNegativeLHS != isNegativeRHS ? -Result : Result;
344   }
345
346   /// Unsigned divide this APInt by APInt RHS.
347   /// @brief Unsigned division function for APInt.
348   APInt udiv(const APInt& RHS) const;
349
350   /// Signed remainder operation on APInt.
351   /// @brief Function for signed remainder operation.
352   inline APInt srem(const APInt& RHS) const {
353     bool isNegativeLHS = (*this)[BitWidth - 1];
354     bool isNegativeRHS = RHS[RHS.BitWidth - 1];
355     APInt Result = APIntOps::urem(
356         isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
357     return isNegativeLHS ? -Result : Result;
358   }
359
360   /// Unsigned remainder operation on APInt.
361   /// @brief Function for unsigned remainder operation.
362   APInt urem(const APInt& RHS) const;
363
364   /// Truncate the APInt to a specified width. It is an error to specify a width
365   /// that is greater than or equal to the current width. 
366   /// @brief Truncate to new width.
367   void trunc(uint32_t width);
368
369   /// This operation sign extends the APInt to a new width. If the high order
370   /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
371   /// It is an error to specify a width that is less than or equal to the 
372   /// current width.
373   /// @brief Sign extend to a new width.
374   void sext(uint32_t width);
375
376   /// This operation zero extends the APInt to a new width. Thie high order bits
377   /// are filled with 0 bits.  It is an error to specify a width that is less 
378   /// than or equal to the current width.
379   /// @brief Zero extend to a new width.
380   void zext(uint32_t width);
381
382   /// @brief Set every bit to 1.
383   APInt& set();
384
385   /// Set the given bit to 1 whose position is given as "bitPosition".
386   /// @brief Set a given bit to 1.
387   APInt& set(uint32_t bitPosition);
388
389   /// @brief Set every bit to 0.
390   APInt& clear();
391
392   /// Set the given bit to 0 whose position is given as "bitPosition".
393   /// @brief Set a given bit to 0.
394   APInt& clear(uint32_t bitPosition);
395
396   /// @brief Toggle every bit to its opposite value.
397   APInt& flip();
398
399   /// Toggle a given bit to its opposite value whose position is given 
400   /// as "bitPosition".
401   /// @brief Toggles a given bit to its opposite value.
402   APInt& flip(uint32_t bitPosition);
403
404   /// This function returns the number of active bits which is defined as the
405   /// bit width minus the number of leading zeros. This is used in several
406   /// computations to see how "wide" the value is.
407   /// @brief Compute the number of active bits in the value
408   inline uint32_t getActiveBits() const {
409     return getNumWords() * APINT_BITS_PER_WORD - countLeadingZeros();
410   }
411
412   /// @returns a uint64_t value from this APInt. If this APInt contains a single
413   /// word, just returns VAL, otherwise pVal[0].
414   inline uint64_t getValue(bool isSigned = false) const {
415     if (isSingleWord())
416       return isSigned ? int64_t(VAL << (64 - BitWidth)) >> 
417                                        (64 - BitWidth) : VAL;
418     uint32_t n = getActiveBits();
419     if (n <= 64)
420       return pVal[0];
421     assert(0 && "This APInt's bitwidth > 64");
422   }
423
424   /// @returns the largest value for an APInt of the specified bit-width and 
425   /// if isSign == true, it should be largest signed value, otherwise largest
426   /// unsigned value.
427   /// @brief Gets max value of the APInt with bitwidth <= 64.
428   static APInt getMaxValue(uint32_t numBits, bool isSign);
429
430   /// @returns the smallest value for an APInt of the given bit-width and
431   /// if isSign == true, it should be smallest signed value, otherwise zero.
432   /// @brief Gets min value of the APInt with bitwidth <= 64.
433   static APInt getMinValue(uint32_t numBits, bool isSign);
434
435   /// @returns the all-ones value for an APInt of the specified bit-width.
436   /// @brief Get the all-ones value.
437   static APInt getAllOnesValue(uint32_t numBits);
438
439   /// @returns the '0' value for an APInt of the specified bit-width.
440   /// @brief Get the '0' value.
441   static APInt getNullValue(uint32_t numBits);
442
443   /// This converts the APInt to a boolean valy as a test against zero.
444   /// @brief Boolean conversion function. 
445   inline bool getBoolValue() const {
446     return countLeadingZeros() != BitWidth;
447   }
448
449   /// @returns a character interpretation of the APInt.
450   std::string toString(uint8_t radix = 10, bool wantSigned = true) const;
451
452   /// Get an APInt with the same BitWidth as this APInt, just zero mask
453   /// the low bits and right shift to the least significant bit.
454   /// @returns the high "numBits" bits of this APInt.
455   APInt getHiBits(uint32_t numBits) const;
456
457   /// Get an APInt with the same BitWidth as this APInt, just zero mask
458   /// the high bits.
459   /// @returns the low "numBits" bits of this APInt.
460   APInt getLoBits(uint32_t numBits) const;
461
462   /// @returns true if the argument APInt value is a power of two > 0.
463   bool isPowerOf2() const; 
464
465   /// @returns the number of zeros from the most significant bit to the first
466   /// one bits.
467   uint32_t countLeadingZeros() const;
468
469   /// @returns the number of zeros from the least significant bit to the first
470   /// one bit.
471   uint32_t countTrailingZeros() const;
472
473   /// @returns the number of set bits.
474   uint32_t countPopulation() const; 
475
476   /// @returns the total number of bits.
477   inline uint32_t getBitWidth() const { 
478     return BitWidth; 
479   }
480
481   /// @brief Check if this APInt has a N-bits integer value.
482   inline bool isIntN(uint32_t N) const {
483     assert(N && "N == 0 ???");
484     if (isSingleWord()) {
485       return VAL == (VAL & (~0ULL >> (64 - N)));
486     } else {
487       APInt Tmp(N, getNumWords(), pVal);
488       return Tmp == (*this);
489     }
490   }
491
492   /// @returns a byte-swapped representation of this APInt Value.
493   APInt byteSwap() const;
494
495   /// @returns the floor log base 2 of this APInt.
496   inline uint32_t logBase2() const {
497     return getNumWords() * APINT_BITS_PER_WORD - 1 - countLeadingZeros();
498   }
499
500   /// @brief Converts this APInt to a double value.
501   double roundToDouble(bool isSigned = false) const;
502
503 };
504
505 namespace APIntOps {
506
507 /// @brief Check if the specified APInt has a N-bits integer value.
508 inline bool isIntN(uint32_t N, const APInt& APIVal) {
509   return APIVal.isIntN(N);
510 }
511
512 /// @returns true if the argument APInt value is a sequence of ones
513 /// starting at the least significant bit with the remainder zero.
514 inline const bool isMask(uint32_t numBits, const APInt& APIVal) {
515   return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
516 }
517
518 /// @returns true if the argument APInt value contains a sequence of ones
519 /// with the remainder zero.
520 inline const bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
521   return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
522 }
523
524 /// @returns a byte-swapped representation of the specified APInt Value.
525 inline APInt byteSwap(const APInt& APIVal) {
526   return APIVal.byteSwap();
527 }
528
529 /// @returns the floor log base 2 of the specified APInt value.
530 inline uint32_t logBase2(const APInt& APIVal) {
531   return APIVal.logBase2(); 
532 }
533
534 /// @returns the greatest common divisor of the two values 
535 /// using Euclid's algorithm.
536 APInt GreatestCommonDivisor(const APInt& API1, const APInt& API2);
537
538 /// @brief Converts the given APInt to a double value.
539 inline double RoundAPIntToDouble(const APInt& APIVal, bool isSigned = false) {
540   return APIVal.roundToDouble(isSigned);
541 }
542
543 /// @brief Converts the given APInt to a float vlalue.
544 inline float RoundAPIntToFloat(const APInt& APIVal) {
545   return float(RoundAPIntToDouble(APIVal));
546 }
547
548 /// @brief Converts the given double value into a APInt.
549 APInt RoundDoubleToAPInt(double Double);
550
551 /// @brief Converts the given float value into a APInt.
552 inline APInt RoundFloatToAPInt(float Float) {
553   return RoundDoubleToAPInt(double(Float));
554 }
555
556 /// Arithmetic right-shift the APInt by shiftAmt.
557 /// @brief Arithmetic right-shift function.
558 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
559   return LHS.ashr(shiftAmt);
560 }
561
562 /// Logical right-shift the APInt by shiftAmt.
563 /// @brief Logical right-shift function.
564 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
565   return LHS.lshr(shiftAmt);
566 }
567
568 /// Left-shift the APInt by shiftAmt.
569 /// @brief Left-shift function.
570 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
571   return LHS.shl(shiftAmt);
572 }
573
574 /// Signed divide APInt LHS by APInt RHS.
575 /// @brief Signed division function for APInt.
576 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
577   return LHS.sdiv(RHS);
578 }
579
580 /// Unsigned divide APInt LHS by APInt RHS.
581 /// @brief Unsigned division function for APInt.
582 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
583   return LHS.udiv(RHS);
584 }
585
586 /// Signed remainder operation on APInt.
587 /// @brief Function for signed remainder operation.
588 inline APInt srem(const APInt& LHS, const APInt& RHS) {
589   return LHS.srem(RHS);
590 }
591
592 /// Unsigned remainder operation on APInt.
593 /// @brief Function for unsigned remainder operation.
594 inline APInt urem(const APInt& LHS, const APInt& RHS) {
595   return LHS.urem(RHS);
596 }
597
598 /// Performs multiplication on APInt values.
599 /// @brief Function for multiplication operation.
600 inline APInt mul(const APInt& LHS, const APInt& RHS) {
601   return LHS * RHS;
602 }
603
604 /// Performs addition on APInt values.
605 /// @brief Function for addition operation.
606 inline APInt add(const APInt& LHS, const APInt& RHS) {
607   return LHS + RHS;
608 }
609
610 /// Performs subtraction on APInt values.
611 /// @brief Function for subtraction operation.
612 inline APInt sub(const APInt& LHS, const APInt& RHS) {
613   return LHS - RHS;
614 }
615
616 /// Performs bitwise AND operation on APInt LHS and 
617 /// APInt RHS.
618 /// @brief Bitwise AND function for APInt.
619 inline APInt And(const APInt& LHS, const APInt& RHS) {
620   return LHS & RHS;
621 }
622
623 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
624 /// @brief Bitwise OR function for APInt. 
625 inline APInt Or(const APInt& LHS, const APInt& RHS) {
626   return LHS | RHS;
627 }
628
629 /// Performs bitwise XOR operation on APInt.
630 /// @brief Bitwise XOR function for APInt.
631 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
632   return LHS ^ RHS;
633
634
635 /// Performs a bitwise complement operation on APInt.
636 /// @brief Bitwise complement function. 
637 inline APInt Not(const APInt& APIVal) {
638   return ~APIVal;
639 }
640
641 } // End of APIntOps namespace
642
643 } // End of llvm namespace
644
645 #endif