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