Add a class APInt to represent arbitrary precision constant integral values.
[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 <string>
20
21 namespace llvm {
22
23 //===----------------------------------------------------------------------===//
24 //                              APInt Class
25 //===----------------------------------------------------------------------===//
26
27 /// APInt - This class represents arbitrary precision constant integral values.
28 /// It is a functional replacement for common case unsigned integer type like 
29 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width 
30 /// integer type and large integer value types such as 3-bits, 15-bits, or more
31 /// than 64-bits of precision. APInt provides a variety of arithmetic operators 
32 /// and methods to manipulate integer values of any bit-width. It supports not 
33 /// only all the operations of uint64_t but also bitwise manipulation.
34 ///
35 /// @brief Class for arbitrary precision integers.
36 ///
37 class APInt {
38   /// Friend Functions of APInt Declared here. For detailed comments,
39   /// see bottom of this file.
40   friend bool isIntN(unsigned N, const APInt& APIVal);
41   friend APInt ByteSwap(const APInt& APIVal);
42   friend APInt LogBase2(const APInt& APIVal);
43   friend double APIntToDouble(const APInt& APIVal);
44   friend float APIntToFloat(const APInt& APIVal);
45
46   unsigned bitsnum;      ///< The number of bits.
47   bool isSigned;         ///< The sign flag for this APInt.
48
49   /// This union is used to store the integer value. When the
50   /// integer bit-width <= 64, it is used as an uint64_t; 
51   /// otherwise it uses an uint64_t array.
52   union {
53     uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
54     uint64_t *pVal;  ///< Used to store the >64 bits integer value.
55   };
56
57   /// This enum is just used to hold constant we needed for APInt.
58   enum {
59     APINT_BITS_PER_WORD = sizeof(uint64_t) * 8
60   };
61
62   /// @returns the number of words to hold the integer value of this APInt.
63   /// Here one word's bitwidth equals to that of uint64_t.
64   /// @brief Get the number of the words.
65   inline unsigned numWords() const {
66     return bitsnum < 1 ? 0 : (bitsnum + APINT_BITS_PER_WORD - 1) /
67                              APINT_BITS_PER_WORD;
68   }
69
70   /// @returns true if the number of bits <= 64, false otherwise.
71   /// @brief Determine if this APInt just has one word to store value.
72   inline bool isSingleWord() const
73   { return bitsnum <= APINT_BITS_PER_WORD; }
74
75   /// @returns the word position for the specified bit position.
76   /// Note: the bitPosition and the return value are zero-based.
77   static inline unsigned whichWord(unsigned bitPosition)
78   { return bitPosition / APINT_BITS_PER_WORD; }
79
80   /// @returns the byte position for the specified bit position.
81   /// Note: the bitPosition and the return value are zero-based.
82   static inline unsigned whichByte(unsigned bitPosition);
83
84   /// @returns the bit position in a word for the specified bit position 
85   /// in APInt.
86   /// Note: the bitPosition and the return value are zero-based.
87   static inline unsigned whichBit(unsigned bitPosition)
88   { return bitPosition % APINT_BITS_PER_WORD; }
89
90   /// @returns a uint64_t type integer with just bit position at
91   /// "whichBit(bitPosition)" setting, others zero.
92   /// Note: the bitPosition and the return value are zero-based.
93   static inline uint64_t maskBit(unsigned bitPosition)
94   { return (static_cast<uint64_t>(1)) << whichBit(bitPosition); }
95
96   inline void TruncToBits() {
97     if (isSingleWord())
98       VAL &= ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - bitsnum);
99     else
100       pVal[numWords() - 1] &= ~uint64_t(0ULL) >> 
101         (APINT_BITS_PER_WORD - (whichBit(bitsnum - 1) + 1));
102   }
103
104   /// @returns the corresponding word for the specified bit position.
105   /// Note: the bitPosition is zero-based.
106   inline uint64_t& getWord(unsigned bitPosition);
107
108   /// @returns the corresponding word for the specified bit position.
109   /// This is a constant version.
110   /// Note: the bitPosition is zero-based.
111   inline uint64_t getWord(unsigned bitPosition) const;
112
113   /// mul_1 - This function performs the multiplication operation on a
114   /// large integer (represented as a integer array) and a uint64_t integer.
115   /// @returns the carry of the multiplication.
116   static uint64_t mul_1(uint64_t dest[], uint64_t x[], 
117                         unsigned len, uint64_t y);
118
119   /// mul - This function performs the multiplication operation on two large
120   /// integers (represented as integer arrays).
121   static void mul(uint64_t dest[], uint64_t x[], unsigned xlen,
122                   uint64_t y[], unsigned ylen);
123
124   /// add_1 - This function performs the addition operation on a large integer
125   /// and a uint64_t integer.
126   /// @returns the carry of the addtion.
127   static uint64_t add_1(uint64_t dest[], uint64_t x[], 
128                         unsigned len, uint64_t y);
129
130   /// add - This function performs the addtion operation on two large integers.
131   static uint64_t add(uint64_t dest[], uint64_t x[], 
132                       uint64_t y[], unsigned len);
133
134   /// sub_1 - This function performs the subtraction operation on a large 
135   /// integer and a uint64_t integer.
136   static uint64_t sub_1(uint64_t x[], unsigned len, uint64_t y);
137
138   /// sub - This function performs the subtraction operation on two large 
139   /// integers.
140   static uint64_t sub(uint64_t dest[], uint64_t x[], 
141                       uint64_t y[], unsigned len);
142
143   /// unitDiv - This function divides uint64_t N by unsigned D.
144   /// @returns (remainder << 32) + quotient.
145   /// @assumes (N >> 32) < D.
146   static uint64_t unitDiv(uint64_t N, unsigned D);
147
148   /// subMul - This function subtract x[len-1 : 0] * y from 
149   /// dest[offset+len-1 : offset].
150   /// @returns the most significant word of the product, minus borrow-out from
151   /// the subtraction.
152   static unsigned subMul(unsigned dest[], unsigned offset, 
153                          unsigned x[], unsigned len, unsigned y);
154
155   /// div - This function divides the large integer zds[] by y[].
156   /// The remainder ends up in zds[ny-1 : 0].
157   /// The quotient ends up in zds[ny : nx].
158   /// @assumes nx > ny and (int)y[ny-1] < 0.
159   static void div(unsigned zds[], unsigned nx, unsigned y[], unsigned ny);
160
161   /// lshift - This function shifts x[len-1 : 0] by shiftAmt, and store the 
162   /// "len" least significant words of the result in 
163   /// dest[d_offset+len-1 : d_offset].
164   /// @returns the bits shifted out from the most significant digit.
165   static uint64_t lshift(uint64_t dest[], unsigned d_offset, 
166                          uint64_t x[], unsigned len, unsigned shiftAmt);
167
168 public:
169   /// Create a new APInt of numBits bit-width, and initalized as val.
170   APInt(uint64_t val = 0, unsigned numBits = APINT_BITS_PER_WORD, 
171         bool sign = false);
172
173   /// Create a new APInt of numBits bit-width, and initalized as bigVal[].
174   APInt(unsigned numBits, uint64_t bigVal[], bool sign = false);
175
176   /// Create a new APInt by translating the string represented integer value.
177   APInt(std::string& Val, uint8_t radix = 10, bool sign = false);
178
179   /// Copy Constructor.
180   APInt(const APInt& API);
181
182   /// Destructor.
183   ~APInt();
184
185   /// @brief Copy assignment operator. Create a new object from the given
186   /// APInt one by initialization.
187   APInt& operator=(const APInt& RHS);
188
189   /// @brief Assignment operator. Assigns a common case integer value to 
190   /// the APInt.
191   APInt& operator=(uint64_t RHS);
192
193   /// @brief Postfix increment operator. Increments the APInt by one.
194   const APInt operator++(int);
195
196   /// @brief Prefix increment operator. Increments the APInt by one.
197   APInt& operator++();
198
199   /// @brief Postfix decrement operator. Decrements the APInt by one.
200   const APInt operator--(int);
201
202   /// @brief Prefix decrement operator. Decrements the APInt by one.
203   APInt& operator--();
204
205   /// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
206   /// this APInt and the given APInt& RHS, assigns the result to this APInt.
207   APInt& operator&=(const APInt& RHS);
208
209   /// @brief Bitwise OR assignment operator. Performs bitwise OR operation on 
210   /// this APInt and the given APInt& RHS, assigns the result to this APInt.
211   APInt& operator|=(const APInt& RHS);
212
213   /// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
214   /// this APInt and the given APInt& RHS, assigns the result to this APInt.
215   APInt& operator^=(const APInt& RHS);
216
217   /// @brief Left-shift assignment operator. Left-shift the APInt by shiftAmt
218   /// and assigns the result to this APInt.
219   APInt& operator<<=(unsigned shiftAmt);
220
221   /// @brief Right-shift assignment operator. Right-shift the APInt by shiftAmt
222   /// and assigns the result to this APInt.
223   APInt& operator>>=(unsigned shiftAmt);
224
225   /// @brief Bitwise complement operator. Performs a bitwise complement 
226   /// operation on this APInt.
227   APInt operator~() const;
228
229   /// @brief Multiplication assignment operator. Multiplies this APInt by the 
230   /// given APInt& RHS and assigns the result to this APInt.
231   APInt& operator*=(const APInt& RHS);
232
233   /// @brief Division assignment operator. Divides this APInt by the given APInt
234   /// &RHS and assigns the result to this APInt.
235   APInt& operator/=(const APInt& RHS);
236
237   /// @brief Addition assignment operator. Adds this APInt by the given APInt&
238   /// RHS and assigns the result to this APInt.
239   APInt& operator+=(const APInt& RHS);
240
241   /// @brief Subtraction assignment operator. Subtracts this APInt by the given
242   /// APInt &RHS and assigns the result to this APInt.
243   APInt& operator-=(const APInt& RHS);
244
245   /// @brief Remainder assignment operator. Yields the remainder from the 
246   /// division of this APInt by the given APInt& RHS and assigns the remainder 
247   /// to this APInt.
248   APInt& operator%=(const APInt& RHS);
249
250   /// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
251   /// and the given APInt& RHS.
252   APInt operator&(const APInt& RHS) const;
253
254   /// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt 
255   /// and the given APInt& RHS.
256   APInt operator|(const APInt& RHS) const;
257
258   /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
259   /// and the given APInt& RHS.
260   APInt operator^(const APInt& RHS) const;
261
262   /// @brief Logical AND operator. Performs logical AND operation on this APInt
263   /// and the given APInt& RHS.
264   bool operator&&(const APInt& RHS) const;
265
266   /// @brief Logical OR operator. Performs logical OR operation on this APInt 
267   /// and the given APInt& RHS.
268   bool operator||(const APInt& RHS) const;
269
270   /// @brief Logical negation operator. Performs logical negation operation on
271   /// this APInt.
272   bool operator !() const;
273
274   /// @brief Multiplication operator. Multiplies this APInt by the given APInt& 
275   /// RHS.
276   APInt operator*(const APInt& RHS) const;
277
278   /// @brief Division operator. Divides this APInt by the given APInt& RHS.
279   APInt operator/(const APInt& RHS) const;
280
281   /// @brief Remainder operator. Yields the remainder from the division of this
282   /// APInt and the given APInt& RHS.
283   APInt operator%(const APInt& RHS) const;
284
285   /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
286   APInt operator+(const APInt& RHS) const;
287
288   /// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
289   APInt operator-(const APInt& RHS) const;
290
291   /// @brief Left-shift operator. Left-shift the APInt by shiftAmt.
292   APInt operator<<(unsigned shiftAmt) const;
293
294   /// @brief Right-shift operator. Right-shift the APInt by shiftAmt.
295   APInt operator>>(unsigned shiftAmt) const;
296
297   /// @brief Array-indexing support.
298   bool operator[](unsigned bitPosition) const;
299
300   /// @brief Equality operator. Compare this APInt with the given APInt& RHS 
301   /// for the validity of the equality relationship.
302   bool operator==(const APInt& RHS) const;
303
304   /// @brief Inequality operator. Compare this APInt with the given APInt& RHS
305   /// for the validity of the inequality relationship.
306   bool operator!=(const APInt& RHS) const;
307
308   /// @brief Less-than operator. Compare this APInt with the given APInt& RHS
309   /// for the validity of the less-than relationship.
310   bool operator <(const APInt& RHS) const;
311
312   /// @brief Less-than-or-equal operator. Compare this APInt with the given 
313   /// APInt& RHS for the validity of the less-than-or-equal relationship.
314   bool operator<=(const APInt& RHS) const;
315
316   /// @brief Greater-than operator. Compare this APInt with the given APInt& RHS
317   /// for the validity of the greater-than relationship.
318   bool operator> (const APInt& RHS) const;
319
320   /// @brief Greater-than-or-equal operator. Compare this APInt with the given 
321   /// APInt& RHS for the validity of the greater-than-or-equal relationship.
322   bool operator>=(const APInt& RHS) const;
323
324   /// @returns a uint64_t value from this APInt. If this APInt contains a single
325   /// word, just returns VAL, otherwise pVal[0].
326   inline uint64_t getValue() {
327     if (isSingleWord())
328       return isSigned ? ((int64_t(VAL) << (APINT_BITS_PER_WORD - bitsnum)) >> 
329                          (APINT_BITS_PER_WORD - bitsnum)) :
330                         VAL;
331     else
332       return pVal[0];
333   }
334
335   /// @returns the largest value for an APInt of the specified bit-width and 
336   /// if isSign == true, it should be largest signed value, otherwise largest
337   /// unsigned value.
338   /// @brief Gets max value of the APInt with bitwidth <= 64.
339   static APInt getMaxValue(unsigned numBits, bool isSign);
340
341   /// @returns the smallest value for an APInt of the given bit-width and
342   /// if isSign == true, it should be smallest signed value, otherwise zero.
343   /// @brief Gets min value of the APInt with bitwidth <= 64.
344   static APInt getMinValue(unsigned numBits, bool isSign);
345
346   /// @returns the all-ones value for an APInt of the specified bit-width.
347   /// @brief Get the all-ones value.
348   static APInt getAllOnesValue(unsigned numBits);
349
350   /// @brief Set every bit to 1.
351   APInt& set();
352
353   /// Set the given bit to 1 whose poition is given as "bitPosition".
354   /// @brief Set a given bit to 1.
355   APInt& set(unsigned bitPosition);
356
357   /// @returns the '0' value for an APInt of the specified bit-width.
358   /// @brief Get the '0' value.
359   static APInt getNullValue(unsigned numBits);
360
361   /// @brief Set every bit to 0.
362   APInt& clear();
363
364   /// Set the given bit to 0 whose position is given as "bitPosition".
365   /// @brief Set a given bit to 0.
366   APInt& clear(unsigned bitPosition);
367
368   /// @brief Toggle every bit to its opposite value.
369   APInt& flip();
370
371   /// Toggle a given bit to its opposite value whose position is given 
372   /// as "bitPosition".
373   /// @brief Toggles a given bit to its opposite value.
374   APInt& flip(unsigned bitPosition);
375
376   /// @returns a character interpretation of the APInt.
377   std::string to_string(uint8_t radix = 10) const;
378
379   /// @returns the high "numBits" bits of this APInt.
380   APInt HiBits(unsigned numBits) const;
381
382   /// @returns the low "numBits" bits of this APInt.
383   APInt LoBits(unsigned numBits) const;
384
385   /// @returns true if the argument APInt value is a power of two > 0.
386   inline const bool isPowerOf2() const {
387     return *this && !(*this & (*this - 1));
388   }
389
390   /// @returns the number of zeros from the most significant bit to the first
391   /// one bits.
392   unsigned CountLeadingZeros() const;
393
394   /// @returns the number of zeros from the least significant bit to the first
395   /// one bit.
396   unsigned CountTrailingZeros() const;
397
398   /// @returns the number of set bits.
399   unsigned CountPopulation() const; 
400
401   /// @returns the total number of bits.
402   inline unsigned getNumBits() const
403   { return bitsnum; }
404
405 };
406
407 /// @brief Check if the specified APInt has a N-bits integer value.
408 inline bool isIntN(unsigned N, const APInt& APIVal) {
409   if (APIVal.isSingleWord()) {
410     APInt Tmp(N, APIVal.VAL);
411     return Tmp == APIVal;
412   } else {
413     APInt Tmp(N, APIVal.pVal);
414     return Tmp == APIVal;
415   }
416 }
417
418 /// @returns true if the argument APInt value is a sequence of ones
419 /// starting at the least significant bit with the remainder zero.
420 inline const bool isMask(unsigned numBits, const APInt& APIVal) {
421   return APIVal && ((APIVal + 1) & APIVal) == 0;
422 }
423
424 /// @returns true if the argument APInt value contains a sequence of ones
425 /// with the remainder zero.
426 inline const bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
427   return isMask(numBits, (APIVal - 1) | APIVal);
428 }
429
430 /// @returns a byte-swapped representation of the specified APInt Value.
431 APInt ByteSwap(const APInt& APIVal);
432
433 /// @returns the floor log base 2 of the specified APInt value.
434 inline APInt LogBase2(const APInt& APIVal) {
435   return APIVal.numWords() * APInt::APINT_BITS_PER_WORD - 
436          APIVal.CountLeadingZeros();
437 }
438
439 /// @returns the greatest common divisor of the two values 
440 /// using Euclid's algorithm.
441 APInt GreatestCommonDivisor(const APInt& API1, const APInt& API2);
442
443 /// @returns the bit equivalent double.
444 /// If the APInt numBits > 64, truncated first and then convert to double.
445 inline double APIntToDouble(const APInt& APIVal) {
446   uint64_t value = APIVal.isSingleWord() ? APIVal.VAL : APIVal.pVal[0];
447   union {
448     uint64_t I;
449     double D;
450   } T;
451   T.I = value;
452   return T.D;
453 }
454
455 /// @returns the bit equivalent float.
456 /// If the APInt numBits > 32, truncated first and then convert to double.
457 inline float APIntToFloat(const APInt& APIVal) {
458   unsigned value = APIVal.isSingleWord() ? APIVal.VAL : APIVal.pVal[0];
459   union {
460     unsigned I;
461     float F;
462   } T;
463   T.I = value;
464   return T.F;
465 }
466
467 /// @returns the bit equivalent APInt.
468 inline APInt DoubleToAPInt(double Double) {
469   union {
470     uint64_t L;
471     double D;
472   } T;
473   T.D = Double;
474   return APInt(T.L);
475 }
476
477 /// @returns the bit equivalent APInt.
478 inline APInt FloatToAPInt(float Float) {
479   union {
480     uint32_t I;
481     float F;
482   } T;
483   T.F = Float;
484   return APInt(uint64_t(T.I));
485 }
486
487 } // End of llvm namespace
488
489 #endif