722c6ba8ceb7d8db48b2ff72478517a25d465305
[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;
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 !*this;
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 : isNegative() && isPowerOf2();
335   }
336
337   /// @brief Check if this APInt has an N-bits unsigned integer value.
338   bool isIntN(unsigned N) const {
339     assert(N && "N == 0 ???");
340     if (N >= getBitWidth())
341       return true;
342
343     if (isSingleWord())
344       return isUIntN(N, VAL);
345     APInt Tmp(N, getNumWords(), pVal);
346     Tmp.zext(getBitWidth());
347     return Tmp == (*this);
348   }
349
350   /// @brief Check if this APInt has an N-bits signed integer value.
351   bool isSignedIntN(unsigned N) const {
352     assert(N && "N == 0 ???");
353     return getMinSignedBits() <= N;
354   }
355
356   /// @returns true if the argument APInt value is a power of two > 0.
357   bool isPowerOf2() const {
358     if (isSingleWord())
359       return isPowerOf2_64(VAL);
360     return countPopulationSlowCase() == 1;
361   }
362
363   /// isSignBit - Return true if this is the value returned by getSignBit.
364   bool isSignBit() const { return isMinSignedValue(); }
365
366   /// This converts the APInt to a boolean value as a test against zero.
367   /// @brief Boolean conversion function.
368   bool getBoolValue() const {
369     return !!*this;
370   }
371
372   /// getLimitedValue - If this value is smaller than the specified limit,
373   /// return it, otherwise return the limit value.  This causes the value
374   /// to saturate to the limit.
375   uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
376     return (getActiveBits() > 64 || getZExtValue() > Limit) ?
377       Limit :  getZExtValue();
378   }
379
380   /// @}
381   /// @name Value Generators
382   /// @{
383   /// @brief Gets maximum unsigned value of APInt for specific bit width.
384   static APInt getMaxValue(unsigned numBits) {
385     return getAllOnesValue(numBits);
386   }
387
388   /// @brief Gets maximum signed value of APInt for a specific bit width.
389   static APInt getSignedMaxValue(unsigned numBits) {
390     APInt API = getAllOnesValue(numBits);
391     API.clearBit(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.setBit(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     return APInt(numBits, -1ULL, true);
418   }
419
420   /// @returns the '0' value for an APInt of the specified bit-width.
421   /// @brief Get the '0' value.
422   static APInt getNullValue(unsigned numBits) {
423     return APInt(numBits, 0);
424   }
425
426   /// Get an APInt with the same BitWidth as this APInt, just zero mask
427   /// the low bits and right shift to the least significant bit.
428   /// @returns the high "numBits" bits of this APInt.
429   APInt getHiBits(unsigned numBits) const;
430
431   /// Get an APInt with the same BitWidth as this APInt, just zero mask
432   /// the high bits.
433   /// @returns the low "numBits" bits of this APInt.
434   APInt getLoBits(unsigned numBits) const;
435
436   /// Constructs an APInt value that has a contiguous range of bits set. The
437   /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
438   /// bits will be zero. For example, with parameters(32, 0, 16) you would get
439   /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
440   /// example, with parameters (32, 28, 4), you would get 0xF000000F.
441   /// @param numBits the intended bit width of the result
442   /// @param loBit the index of the lowest bit set.
443   /// @param hiBit the index of the highest bit set.
444   /// @returns An APInt value with the requested bits set.
445   /// @brief Get a value with a block of bits set.
446   static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
447     assert(hiBit <= numBits && "hiBit out of range");
448     assert(loBit < numBits && "loBit out of range");
449     if (hiBit < loBit)
450       return getLowBitsSet(numBits, hiBit) |
451              getHighBitsSet(numBits, numBits-loBit);
452     return getLowBitsSet(numBits, hiBit-loBit).shl(loBit);
453   }
454
455   /// Constructs an APInt value that has the top hiBitsSet bits set.
456   /// @param numBits the bitwidth of the result
457   /// @param hiBitsSet the number of high-order bits set in the result.
458   /// @brief Get a value with high bits set
459   static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
460     assert(hiBitsSet <= numBits && "Too many bits to set!");
461     // Handle a degenerate case, to avoid shifting by word size
462     if (hiBitsSet == 0)
463       return APInt(numBits, 0);
464     unsigned shiftAmt = numBits - hiBitsSet;
465     // For small values, return quickly
466     if (numBits <= APINT_BITS_PER_WORD)
467       return APInt(numBits, ~0ULL << shiftAmt);
468     return getAllOnesValue(numBits).shl(shiftAmt);
469   }
470
471   /// Constructs an APInt value that has the bottom loBitsSet bits set.
472   /// @param numBits the bitwidth of the result
473   /// @param loBitsSet the number of low-order bits set in the result.
474   /// @brief Get a value with low bits set
475   static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
476     assert(loBitsSet <= numBits && "Too many bits to set!");
477     // Handle a degenerate case, to avoid shifting by word size
478     if (loBitsSet == 0)
479       return APInt(numBits, 0);
480     if (loBitsSet == APINT_BITS_PER_WORD)
481       return APInt(numBits, -1ULL);
482     // For small values, return quickly.
483     if (numBits < APINT_BITS_PER_WORD)
484       return APInt(numBits, (1ULL << loBitsSet) - 1);
485     return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
486   }
487
488   /// The hash value is computed as the sum of the words and the bit width.
489   /// @returns A hash value computed from the sum of the APInt words.
490   /// @brief Get a hash value based on this APInt
491   uint64_t getHashValue() const;
492
493   /// This function returns a pointer to the internal storage of the APInt.
494   /// This is useful for writing out the APInt in binary form without any
495   /// conversions.
496   const uint64_t* getRawData() const {
497     if (isSingleWord())
498       return &VAL;
499     return &pVal[0];
500   }
501
502   /// @}
503   /// @name Unary Operators
504   /// @{
505   /// @returns a new APInt value representing *this incremented by one
506   /// @brief Postfix increment operator.
507   const APInt operator++(int) {
508     APInt API(*this);
509     ++(*this);
510     return API;
511   }
512
513   /// @returns *this incremented by one
514   /// @brief Prefix increment operator.
515   APInt& operator++();
516
517   /// @returns a new APInt representing *this decremented by one.
518   /// @brief Postfix decrement operator.
519   const APInt operator--(int) {
520     APInt API(*this);
521     --(*this);
522     return API;
523   }
524
525   /// @returns *this decremented by one.
526   /// @brief Prefix decrement operator.
527   APInt& operator--();
528
529   /// Performs a bitwise complement operation on this APInt.
530   /// @returns an APInt that is the bitwise complement of *this
531   /// @brief Unary bitwise complement operator.
532   APInt operator~() const {
533     APInt Result(*this);
534     Result.flipAllBits();
535     return Result;
536   }
537
538   /// Negates *this using two's complement logic.
539   /// @returns An APInt value representing the negation of *this.
540   /// @brief Unary negation operator
541   APInt operator-() const {
542     return APInt(BitWidth, 0) - (*this);
543   }
544
545   /// Performs logical negation operation on this APInt.
546   /// @returns true if *this is zero, false otherwise.
547   /// @brief Logical negation operator.
548   bool operator!() const;
549
550   /// @}
551   /// @name Assignment Operators
552   /// @{
553   /// @returns *this after assignment of RHS.
554   /// @brief Copy assignment operator.
555   APInt& operator=(const APInt& RHS) {
556     // If the bitwidths are the same, we can avoid mucking with memory
557     if (isSingleWord() && RHS.isSingleWord()) {
558       VAL = RHS.VAL;
559       BitWidth = RHS.BitWidth;
560       return clearUnusedBits();
561     }
562
563     return AssignSlowCase(RHS);
564   }
565
566   /// The RHS value is assigned to *this. If the significant bits in RHS exceed
567   /// the bit width, the excess bits are truncated. If the bit width is larger
568   /// than 64, the value is zero filled in the unspecified high order bits.
569   /// @returns *this after assignment of RHS value.
570   /// @brief Assignment operator.
571   APInt& operator=(uint64_t RHS);
572
573   /// Performs a bitwise AND operation on this APInt and RHS. The result is
574   /// assigned to *this.
575   /// @returns *this after ANDing with RHS.
576   /// @brief Bitwise AND assignment operator.
577   APInt& operator&=(const APInt& RHS);
578
579   /// Performs a bitwise OR operation on this APInt and RHS. The result is
580   /// assigned *this;
581   /// @returns *this after ORing with RHS.
582   /// @brief Bitwise OR assignment operator.
583   APInt& operator|=(const APInt& RHS);
584
585   /// Performs a bitwise OR operation on this APInt and RHS. RHS is
586   /// logically zero-extended or truncated to match the bit-width of
587   /// the LHS.
588   /// 
589   /// @brief Bitwise OR assignment operator.
590   APInt& operator|=(uint64_t RHS) {
591     if (isSingleWord()) {
592       VAL |= RHS;
593       clearUnusedBits();
594     } else {
595       pVal[0] |= RHS;
596     }
597     return *this;
598   }
599
600   /// Performs a bitwise XOR operation on this APInt and RHS. The result is
601   /// assigned to *this.
602   /// @returns *this after XORing with RHS.
603   /// @brief Bitwise XOR assignment operator.
604   APInt& operator^=(const APInt& RHS);
605
606   /// Multiplies this APInt by RHS and assigns the result to *this.
607   /// @returns *this
608   /// @brief Multiplication assignment operator.
609   APInt& operator*=(const APInt& RHS);
610
611   /// Adds RHS to *this and assigns the result to *this.
612   /// @returns *this
613   /// @brief Addition assignment operator.
614   APInt& operator+=(const APInt& RHS);
615
616   /// Subtracts RHS from *this and assigns the result to *this.
617   /// @returns *this
618   /// @brief Subtraction assignment operator.
619   APInt& operator-=(const APInt& RHS);
620
621   /// Shifts *this left by shiftAmt and assigns the result to *this.
622   /// @returns *this after shifting left by shiftAmt
623   /// @brief Left-shift assignment function.
624   APInt& operator<<=(unsigned shiftAmt) {
625     *this = shl(shiftAmt);
626     return *this;
627   }
628
629   /// @}
630   /// @name Binary Operators
631   /// @{
632   /// Performs a bitwise AND operation on *this and RHS.
633   /// @returns An APInt value representing the bitwise AND of *this and RHS.
634   /// @brief Bitwise AND operator.
635   APInt operator&(const APInt& RHS) const {
636     assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
637     if (isSingleWord())
638       return APInt(getBitWidth(), VAL & RHS.VAL);
639     return AndSlowCase(RHS);
640   }
641   APInt And(const APInt& RHS) const {
642     return this->operator&(RHS);
643   }
644
645   /// Performs a bitwise OR operation on *this and RHS.
646   /// @returns An APInt value representing the bitwise OR of *this and RHS.
647   /// @brief Bitwise OR operator.
648   APInt operator|(const APInt& RHS) const {
649     assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
650     if (isSingleWord())
651       return APInt(getBitWidth(), VAL | RHS.VAL);
652     return OrSlowCase(RHS);
653   }
654   APInt Or(const APInt& RHS) const {
655     return this->operator|(RHS);
656   }
657
658   /// Performs a bitwise XOR operation on *this and RHS.
659   /// @returns An APInt value representing the bitwise XOR of *this and RHS.
660   /// @brief Bitwise XOR operator.
661   APInt operator^(const APInt& RHS) const {
662     assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
663     if (isSingleWord())
664       return APInt(BitWidth, VAL ^ RHS.VAL);
665     return XorSlowCase(RHS);
666   }
667   APInt Xor(const APInt& RHS) const {
668     return this->operator^(RHS);
669   }
670
671   /// Multiplies this APInt by RHS and returns the result.
672   /// @brief Multiplication operator.
673   APInt operator*(const APInt& RHS) const;
674
675   /// Adds RHS to this APInt and returns the result.
676   /// @brief Addition operator.
677   APInt operator+(const APInt& RHS) const;
678   APInt operator+(uint64_t RHS) const {
679     return (*this) + APInt(BitWidth, RHS);
680   }
681
682   /// Subtracts RHS from this APInt and returns the result.
683   /// @brief Subtraction operator.
684   APInt operator-(const APInt& RHS) const;
685   APInt operator-(uint64_t RHS) const {
686     return (*this) - APInt(BitWidth, RHS);
687   }
688
689   APInt operator<<(unsigned Bits) const {
690     return shl(Bits);
691   }
692
693   APInt operator<<(const APInt &Bits) const {
694     return shl(Bits);
695   }
696
697   /// Arithmetic right-shift this APInt by shiftAmt.
698   /// @brief Arithmetic right-shift function.
699   APInt ashr(unsigned shiftAmt) const;
700
701   /// Logical right-shift this APInt by shiftAmt.
702   /// @brief Logical right-shift function.
703   APInt lshr(unsigned shiftAmt) const;
704
705   /// Left-shift this APInt by shiftAmt.
706   /// @brief Left-shift function.
707   APInt shl(unsigned shiftAmt) const {
708     assert(shiftAmt <= BitWidth && "Invalid shift amount");
709     if (isSingleWord()) {
710       if (shiftAmt == BitWidth)
711         return APInt(BitWidth, 0); // avoid undefined shift results
712       return APInt(BitWidth, VAL << shiftAmt);
713     }
714     return shlSlowCase(shiftAmt);
715   }
716
717   /// @brief Rotate left by rotateAmt.
718   APInt rotl(unsigned rotateAmt) const;
719
720   /// @brief Rotate right by rotateAmt.
721   APInt rotr(unsigned rotateAmt) const;
722
723   /// Arithmetic right-shift this APInt by shiftAmt.
724   /// @brief Arithmetic right-shift function.
725   APInt ashr(const APInt &shiftAmt) const;
726
727   /// Logical right-shift this APInt by shiftAmt.
728   /// @brief Logical right-shift function.
729   APInt lshr(const APInt &shiftAmt) const;
730
731   /// Left-shift this APInt by shiftAmt.
732   /// @brief Left-shift function.
733   APInt shl(const APInt &shiftAmt) const;
734
735   /// @brief Rotate left by rotateAmt.
736   APInt rotl(const APInt &rotateAmt) const;
737
738   /// @brief Rotate right by rotateAmt.
739   APInt rotr(const APInt &rotateAmt) const;
740
741   /// Perform an unsigned divide operation on this APInt by RHS. Both this and
742   /// RHS are treated as unsigned quantities for purposes of this division.
743   /// @returns a new APInt value containing the division result
744   /// @brief Unsigned division operation.
745   APInt udiv(const APInt &RHS) const;
746
747   /// Signed divide this APInt by APInt RHS.
748   /// @brief Signed division function for APInt.
749   APInt sdiv(const APInt &RHS) const {
750     if (isNegative())
751       if (RHS.isNegative())
752         return (-(*this)).udiv(-RHS);
753       else
754         return -((-(*this)).udiv(RHS));
755     else if (RHS.isNegative())
756       return -(this->udiv(-RHS));
757     return this->udiv(RHS);
758   }
759
760   /// Perform an unsigned remainder operation on this APInt with RHS being the
761   /// divisor. Both this and RHS are treated as unsigned quantities for purposes
762   /// of this operation. Note that this is a true remainder operation and not
763   /// a modulo operation because the sign follows the sign of the dividend
764   /// which is *this.
765   /// @returns a new APInt value containing the remainder result
766   /// @brief Unsigned remainder operation.
767   APInt urem(const APInt &RHS) const;
768
769   /// Signed remainder operation on APInt.
770   /// @brief Function for signed remainder operation.
771   APInt srem(const APInt &RHS) const {
772     if (isNegative())
773       if (RHS.isNegative())
774         return -((-(*this)).urem(-RHS));
775       else
776         return -((-(*this)).urem(RHS));
777     else if (RHS.isNegative())
778       return this->urem(-RHS);
779     return this->urem(RHS);
780   }
781
782   /// Sometimes it is convenient to divide two APInt values and obtain both the
783   /// quotient and remainder. This function does both operations in the same
784   /// computation making it a little more efficient. The pair of input arguments
785   /// may overlap with the pair of output arguments. It is safe to call
786   /// udivrem(X, Y, X, Y), for example.
787   /// @brief Dual division/remainder interface.
788   static void udivrem(const APInt &LHS, const APInt &RHS,
789                       APInt &Quotient, APInt &Remainder);
790
791   static void sdivrem(const APInt &LHS, const APInt &RHS,
792                       APInt &Quotient, APInt &Remainder) {
793     if (LHS.isNegative()) {
794       if (RHS.isNegative())
795         APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
796       else
797         APInt::udivrem(-LHS, RHS, Quotient, Remainder);
798       Quotient = -Quotient;
799       Remainder = -Remainder;
800     } else if (RHS.isNegative()) {
801       APInt::udivrem(LHS, -RHS, Quotient, Remainder);
802       Quotient = -Quotient;
803     } else {
804       APInt::udivrem(LHS, RHS, Quotient, Remainder);
805     }
806   }
807   
808   
809   // Operations that return overflow indicators.
810   APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
811   APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
812   APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
813   APInt usub_ov(const APInt &RHS, bool &Overflow) const;
814   APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
815   APInt smul_ov(const APInt &RHS, bool &Overflow) const;
816   APInt sshl_ov(unsigned Amt, bool &Overflow) const;
817
818   /// @returns the bit value at bitPosition
819   /// @brief Array-indexing support.
820   bool operator[](unsigned bitPosition) const;
821
822   /// @}
823   /// @name Comparison Operators
824   /// @{
825   /// Compares this APInt with RHS for the validity of the equality
826   /// relationship.
827   /// @brief Equality operator.
828   bool operator==(const APInt& RHS) const {
829     assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
830     if (isSingleWord())
831       return VAL == RHS.VAL;
832     return EqualSlowCase(RHS);
833   }
834
835   /// Compares this APInt with a uint64_t for the validity of the equality
836   /// relationship.
837   /// @returns true if *this == Val
838   /// @brief Equality operator.
839   bool operator==(uint64_t Val) const {
840     if (isSingleWord())
841       return VAL == Val;
842     return EqualSlowCase(Val);
843   }
844
845   /// Compares this APInt with RHS for the validity of the equality
846   /// relationship.
847   /// @returns true if *this == Val
848   /// @brief Equality comparison.
849   bool eq(const APInt &RHS) const {
850     return (*this) == RHS;
851   }
852
853   /// Compares this APInt with RHS for the validity of the inequality
854   /// relationship.
855   /// @returns true if *this != Val
856   /// @brief Inequality operator.
857   bool operator!=(const APInt& RHS) const {
858     return !((*this) == RHS);
859   }
860
861   /// Compares this APInt with a uint64_t for the validity of the inequality
862   /// relationship.
863   /// @returns true if *this != Val
864   /// @brief Inequality operator.
865   bool operator!=(uint64_t Val) const {
866     return !((*this) == Val);
867   }
868
869   /// Compares this APInt with RHS for the validity of the inequality
870   /// relationship.
871   /// @returns true if *this != Val
872   /// @brief Inequality comparison
873   bool ne(const APInt &RHS) const {
874     return !((*this) == RHS);
875   }
876
877   /// Regards both *this and RHS as unsigned quantities and compares them for
878   /// the validity of the less-than relationship.
879   /// @returns true if *this < RHS when both are considered unsigned.
880   /// @brief Unsigned less than comparison
881   bool ult(const APInt &RHS) const;
882
883   /// Regards both *this as an unsigned quantity and compares it with RHS for
884   /// the validity of the less-than relationship.
885   /// @returns true if *this < RHS when considered unsigned.
886   /// @brief Unsigned less than comparison
887   bool ult(uint64_t RHS) const {
888     return ult(APInt(getBitWidth(), RHS));
889   }
890
891   /// Regards both *this and RHS as signed quantities and compares them for
892   /// validity of the less-than relationship.
893   /// @returns true if *this < RHS when both are considered signed.
894   /// @brief Signed less than comparison
895   bool slt(const APInt& RHS) const;
896
897   /// Regards both *this as a signed quantity and compares it with RHS for
898   /// the validity of the less-than relationship.
899   /// @returns true if *this < RHS when considered signed.
900   /// @brief Signed less than comparison
901   bool slt(uint64_t RHS) const {
902     return slt(APInt(getBitWidth(), RHS));
903   }
904
905   /// Regards both *this and RHS as unsigned quantities and compares them for
906   /// validity of the less-or-equal relationship.
907   /// @returns true if *this <= RHS when both are considered unsigned.
908   /// @brief Unsigned less or equal comparison
909   bool ule(const APInt& RHS) const {
910     return ult(RHS) || eq(RHS);
911   }
912
913   /// Regards both *this as an unsigned quantity and compares it with RHS for
914   /// the validity of the less-or-equal relationship.
915   /// @returns true if *this <= RHS when considered unsigned.
916   /// @brief Unsigned less or equal comparison
917   bool ule(uint64_t RHS) const {
918     return ule(APInt(getBitWidth(), RHS));
919   }
920
921   /// Regards both *this and RHS as signed quantities and compares them for
922   /// validity of the less-or-equal relationship.
923   /// @returns true if *this <= RHS when both are considered signed.
924   /// @brief Signed less or equal comparison
925   bool sle(const APInt& RHS) const {
926     return slt(RHS) || eq(RHS);
927   }
928
929   /// Regards both *this as a signed quantity and compares it with RHS for
930   /// the validity of the less-or-equal relationship.
931   /// @returns true if *this <= RHS when considered signed.
932   /// @brief Signed less or equal comparison
933   bool sle(uint64_t RHS) const {
934     return sle(APInt(getBitWidth(), RHS));
935   }
936
937   /// Regards both *this and RHS as unsigned quantities and compares them for
938   /// the validity of the greater-than relationship.
939   /// @returns true if *this > RHS when both are considered unsigned.
940   /// @brief Unsigned greather than comparison
941   bool ugt(const APInt& RHS) const {
942     return !ult(RHS) && !eq(RHS);
943   }
944
945   /// Regards both *this as an unsigned quantity and compares it with RHS for
946   /// the validity of the greater-than relationship.
947   /// @returns true if *this > RHS when considered unsigned.
948   /// @brief Unsigned greater than comparison
949   bool ugt(uint64_t RHS) const {
950     return ugt(APInt(getBitWidth(), RHS));
951   }
952
953   /// Regards both *this and RHS as signed quantities and compares them for
954   /// the validity of the greater-than relationship.
955   /// @returns true if *this > RHS when both are considered signed.
956   /// @brief Signed greather than comparison
957   bool sgt(const APInt& RHS) const {
958     return !slt(RHS) && !eq(RHS);
959   }
960
961   /// Regards both *this as a signed quantity and compares it with RHS for
962   /// the validity of the greater-than relationship.
963   /// @returns true if *this > RHS when considered signed.
964   /// @brief Signed greater than comparison
965   bool sgt(uint64_t RHS) const {
966     return sgt(APInt(getBitWidth(), RHS));
967   }
968
969   /// Regards both *this and RHS as unsigned quantities and compares them for
970   /// validity of the greater-or-equal relationship.
971   /// @returns true if *this >= RHS when both are considered unsigned.
972   /// @brief Unsigned greater or equal comparison
973   bool uge(const APInt& RHS) const {
974     return !ult(RHS);
975   }
976
977   /// Regards both *this as an unsigned quantity and compares it with RHS for
978   /// the validity of the greater-or-equal relationship.
979   /// @returns true if *this >= RHS when considered unsigned.
980   /// @brief Unsigned greater or equal comparison
981   bool uge(uint64_t RHS) const {
982     return uge(APInt(getBitWidth(), RHS));
983   }
984
985   /// Regards both *this and RHS as signed quantities and compares them for
986   /// validity of the greater-or-equal relationship.
987   /// @returns true if *this >= RHS when both are considered signed.
988   /// @brief Signed greather or equal comparison
989   bool sge(const APInt& RHS) const {
990     return !slt(RHS);
991   }
992
993   /// Regards both *this as a signed quantity and compares it with RHS for
994   /// the validity of the greater-or-equal relationship.
995   /// @returns true if *this >= RHS when considered signed.
996   /// @brief Signed greater or equal comparison
997   bool sge(uint64_t RHS) const {
998     return sge(APInt(getBitWidth(), RHS));
999   }
1000
1001   
1002   
1003   
1004   /// This operation tests if there are any pairs of corresponding bits
1005   /// between this APInt and RHS that are both set.
1006   bool intersects(const APInt &RHS) const {
1007     return (*this & RHS) != 0;
1008   }
1009
1010   /// @}
1011   /// @name Resizing Operators
1012   /// @{
1013   /// Truncate the APInt to a specified width. It is an error to specify a width
1014   /// that is greater than or equal to the current width.
1015   /// @brief Truncate to new width.
1016   APInt &trunc(unsigned width);
1017
1018   /// This operation sign extends the APInt to a new width. If the high order
1019   /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1020   /// It is an error to specify a width that is less than or equal to the
1021   /// current width.
1022   /// @brief Sign extend to a new width.
1023   APInt &sext(unsigned width);
1024
1025   /// This operation zero extends the APInt to a new width. The high order bits
1026   /// are filled with 0 bits.  It is an error to specify a width that is less
1027   /// than or equal to the current width.
1028   /// @brief Zero extend to a new width.
1029   APInt &zext(unsigned width);
1030
1031   /// Make this APInt have the bit width given by \p width. The value is sign
1032   /// extended, truncated, or left alone to make it that width.
1033   /// @brief Sign extend or truncate to width
1034   APInt &sextOrTrunc(unsigned width);
1035
1036   /// Make this APInt have the bit width given by \p width. The value is zero
1037   /// extended, truncated, or left alone to make it that width.
1038   /// @brief Zero extend or truncate to width
1039   APInt &zextOrTrunc(unsigned width);
1040
1041   /// @}
1042   /// @name Bit Manipulation Operators
1043   /// @{
1044   /// @brief Set every bit to 1.
1045   void setAllBits() {
1046     if (isSingleWord())
1047       VAL = -1ULL;
1048     else {
1049       // Set all the bits in all the words.
1050       for (unsigned i = 0; i < getNumWords(); ++i)
1051         pVal[i] = -1ULL;
1052     }
1053     // Clear the unused ones
1054     clearUnusedBits();
1055   }
1056
1057   /// Set the given bit to 1 whose position is given as "bitPosition".
1058   /// @brief Set a given bit to 1.
1059   void setBit(unsigned bitPosition);
1060
1061   /// @brief Set every bit to 0.
1062   void clearAllBits() {
1063     if (isSingleWord())
1064       VAL = 0;
1065     else
1066       memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
1067   }
1068
1069   /// Set the given bit to 0 whose position is given as "bitPosition".
1070   /// @brief Set a given bit to 0.
1071   void clearBit(unsigned bitPosition);
1072
1073   /// @brief Toggle every bit to its opposite value.
1074   void flipAllBits() {
1075     if (isSingleWord())
1076       VAL ^= -1ULL;
1077     else {
1078       for (unsigned i = 0; i < getNumWords(); ++i)
1079         pVal[i] ^= -1ULL;
1080     }
1081     clearUnusedBits();
1082   }
1083
1084   /// Toggle a given bit to its opposite value whose position is given
1085   /// as "bitPosition".
1086   /// @brief Toggles a given bit to its opposite value.
1087   void flipBit(unsigned bitPosition);
1088
1089   /// @}
1090   /// @name Value Characterization Functions
1091   /// @{
1092
1093   /// @returns the total number of bits.
1094   unsigned getBitWidth() const {
1095     return BitWidth;
1096   }
1097
1098   /// Here one word's bitwidth equals to that of uint64_t.
1099   /// @returns the number of words to hold the integer value of this APInt.
1100   /// @brief Get the number of words.
1101   unsigned getNumWords() const {
1102     return getNumWords(BitWidth);
1103   }
1104
1105   /// Here one word's bitwidth equals to that of uint64_t.
1106   /// @returns the number of words to hold the integer value with a
1107   /// given bit width.
1108   /// @brief Get the number of words.
1109   static unsigned getNumWords(unsigned BitWidth) {
1110     return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1111   }
1112
1113   /// This function returns the number of active bits which is defined as the
1114   /// bit width minus the number of leading zeros. This is used in several
1115   /// computations to see how "wide" the value is.
1116   /// @brief Compute the number of active bits in the value
1117   unsigned getActiveBits() const {
1118     return BitWidth - countLeadingZeros();
1119   }
1120
1121   /// This function returns the number of active words in the value of this
1122   /// APInt. This is used in conjunction with getActiveData to extract the raw
1123   /// value of the APInt.
1124   unsigned getActiveWords() const {
1125     return whichWord(getActiveBits()-1) + 1;
1126   }
1127
1128   /// Computes the minimum bit width for this APInt while considering it to be
1129   /// a signed (and probably negative) value. If the value is not negative,
1130   /// this function returns the same value as getActiveBits()+1. Otherwise, it
1131   /// returns the smallest bit width that will retain the negative value. For
1132   /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1133   /// for -1, this function will always return 1.
1134   /// @brief Get the minimum bit size for this signed APInt
1135   unsigned getMinSignedBits() const {
1136     if (isNegative())
1137       return BitWidth - countLeadingOnes() + 1;
1138     return getActiveBits()+1;
1139   }
1140
1141   /// This method attempts to return the value of this APInt as a zero extended
1142   /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1143   /// uint64_t. Otherwise an assertion will result.
1144   /// @brief Get zero extended value
1145   uint64_t getZExtValue() const {
1146     if (isSingleWord())
1147       return VAL;
1148     assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1149     return pVal[0];
1150   }
1151
1152   /// This method attempts to return the value of this APInt as a sign extended
1153   /// int64_t. The bit width must be <= 64 or the value must fit within an
1154   /// int64_t. Otherwise an assertion will result.
1155   /// @brief Get sign extended value
1156   int64_t getSExtValue() const {
1157     if (isSingleWord())
1158       return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
1159                      (APINT_BITS_PER_WORD - BitWidth);
1160     assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1161     return int64_t(pVal[0]);
1162   }
1163
1164   /// This method determines how many bits are required to hold the APInt
1165   /// equivalent of the string given by \arg str.
1166   /// @brief Get bits required for string value.
1167   static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1168
1169   /// countLeadingZeros - This function is an APInt version of the
1170   /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
1171   /// of zeros from the most significant bit to the first one bit.
1172   /// @returns BitWidth if the value is zero.
1173   /// @returns the number of zeros from the most significant bit to the first
1174   /// one bits.
1175   unsigned countLeadingZeros() const {
1176     if (isSingleWord()) {
1177       unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1178       return CountLeadingZeros_64(VAL) - unusedBits;
1179     }
1180     return countLeadingZerosSlowCase();
1181   }
1182
1183   /// countLeadingOnes - This function is an APInt version of the
1184   /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number
1185   /// of ones from the most significant bit to the first zero bit.
1186   /// @returns 0 if the high order bit is not set
1187   /// @returns the number of 1 bits from the most significant to the least
1188   /// @brief Count the number of leading one bits.
1189   unsigned countLeadingOnes() const;
1190
1191   /// countTrailingZeros - This function is an APInt version of the
1192   /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
1193   /// the number of zeros from the least significant bit to the first set bit.
1194   /// @returns BitWidth if the value is zero.
1195   /// @returns the number of zeros from the least significant bit to the first
1196   /// one bit.
1197   /// @brief Count the number of trailing zero bits.
1198   unsigned countTrailingZeros() const;
1199
1200   /// countTrailingOnes - This function is an APInt version of the
1201   /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
1202   /// the number of ones from the least significant bit to the first zero bit.
1203   /// @returns BitWidth if the value is all ones.
1204   /// @returns the number of ones from the least significant bit to the first
1205   /// zero bit.
1206   /// @brief Count the number of trailing one bits.
1207   unsigned countTrailingOnes() const {
1208     if (isSingleWord())
1209       return CountTrailingOnes_64(VAL);
1210     return countTrailingOnesSlowCase();
1211   }
1212
1213   /// countPopulation - This function is an APInt version of the
1214   /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
1215   /// of 1 bits in the APInt value.
1216   /// @returns 0 if the value is zero.
1217   /// @returns the number of set bits.
1218   /// @brief Count the number of bits set.
1219   unsigned countPopulation() const {
1220     if (isSingleWord())
1221       return CountPopulation_64(VAL);
1222     return countPopulationSlowCase();
1223   }
1224
1225   /// @}
1226   /// @name Conversion Functions
1227   /// @{
1228   void print(raw_ostream &OS, bool isSigned) const;
1229
1230   /// toString - Converts an APInt to a string and append it to Str.  Str is
1231   /// commonly a SmallString.
1232   void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed) const;
1233
1234   /// Considers the APInt to be unsigned and converts it into a string in the
1235   /// radix given. The radix can be 2, 8, 10 or 16.
1236   void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1237     toString(Str, Radix, false);
1238   }
1239
1240   /// Considers the APInt to be signed and converts it into a string in the
1241   /// radix given. The radix can be 2, 8, 10 or 16.
1242   void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1243     toString(Str, Radix, true);
1244   }
1245
1246   /// toString - This returns the APInt as a std::string.  Note that this is an
1247   /// inefficient method.  It is better to pass in a SmallVector/SmallString
1248   /// to the methods above to avoid thrashing the heap for the string.
1249   std::string toString(unsigned Radix, bool Signed) const;
1250
1251
1252   /// @returns a byte-swapped representation of this APInt Value.
1253   APInt byteSwap() const;
1254
1255   /// @brief Converts this APInt to a double value.
1256   double roundToDouble(bool isSigned) const;
1257
1258   /// @brief Converts this unsigned APInt to a double value.
1259   double roundToDouble() const {
1260     return roundToDouble(false);
1261   }
1262
1263   /// @brief Converts this signed APInt to a double value.
1264   double signedRoundToDouble() const {
1265     return roundToDouble(true);
1266   }
1267
1268   /// The conversion does not do a translation from integer to double, it just
1269   /// re-interprets the bits as a double. Note that it is valid to do this on
1270   /// any bit width. Exactly 64 bits will be translated.
1271   /// @brief Converts APInt bits to a double
1272   double bitsToDouble() const {
1273     union {
1274       uint64_t I;
1275       double D;
1276     } T;
1277     T.I = (isSingleWord() ? VAL : pVal[0]);
1278     return T.D;
1279   }
1280
1281   /// The conversion does not do a translation from integer to float, it just
1282   /// re-interprets the bits as a float. Note that it is valid to do this on
1283   /// any bit width. Exactly 32 bits will be translated.
1284   /// @brief Converts APInt bits to a double
1285   float bitsToFloat() const {
1286     union {
1287       unsigned I;
1288       float F;
1289     } T;
1290     T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1291     return T.F;
1292   }
1293
1294   /// The conversion does not do a translation from double to integer, it just
1295   /// re-interprets the bits of the double.
1296   /// @brief Converts a double to APInt bits.
1297   static APInt doubleToBits(double V) {
1298     union {
1299       uint64_t I;
1300       double D;
1301     } T;
1302     T.D = V;
1303     return APInt(sizeof T * CHAR_BIT, T.I);
1304   }
1305
1306   /// The conversion does not do a translation from float to integer, it just
1307   /// re-interprets the bits of the float.
1308   /// @brief Converts a float to APInt bits.
1309   static APInt floatToBits(float V) {
1310     union {
1311       unsigned I;
1312       float F;
1313     } T;
1314     T.F = V;
1315     return APInt(sizeof T * CHAR_BIT, T.I);
1316   }
1317
1318   /// @}
1319   /// @name Mathematics Operations
1320   /// @{
1321
1322   /// @returns the floor log base 2 of this APInt.
1323   unsigned logBase2() const {
1324     return BitWidth - 1 - countLeadingZeros();
1325   }
1326
1327   /// @returns the ceil log base 2 of this APInt.
1328   unsigned ceilLogBase2() const {
1329     return BitWidth - (*this - 1).countLeadingZeros();
1330   }
1331
1332   /// @returns the log base 2 of this APInt if its an exact power of two, -1
1333   /// otherwise
1334   int32_t exactLogBase2() const {
1335     if (!isPowerOf2())
1336       return -1;
1337     return logBase2();
1338   }
1339
1340   /// @brief Compute the square root
1341   APInt sqrt() const;
1342
1343   /// If *this is < 0 then return -(*this), otherwise *this;
1344   /// @brief Get the absolute value;
1345   APInt abs() const {
1346     if (isNegative())
1347       return -(*this);
1348     return *this;
1349   }
1350
1351   /// @returns the multiplicative inverse for a given modulo.
1352   APInt multiplicativeInverse(const APInt& modulo) const;
1353
1354   /// @}
1355   /// @name Support for division by constant
1356   /// @{
1357
1358   /// Calculate the magic number for signed division by a constant.
1359   struct ms;
1360   ms magic() const;
1361
1362   /// Calculate the magic number for unsigned division by a constant.
1363   struct mu;
1364   mu magicu() const;
1365
1366   /// @}
1367   /// @name Building-block Operations for APInt and APFloat
1368   /// @{
1369
1370   // These building block operations operate on a representation of
1371   // arbitrary precision, two's-complement, bignum integer values.
1372   // They should be sufficient to implement APInt and APFloat bignum
1373   // requirements.  Inputs are generally a pointer to the base of an
1374   // array of integer parts, representing an unsigned bignum, and a
1375   // count of how many parts there are.
1376
1377   /// Sets the least significant part of a bignum to the input value,
1378   /// and zeroes out higher parts.  */
1379   static void tcSet(integerPart *, integerPart, unsigned int);
1380
1381   /// Assign one bignum to another.
1382   static void tcAssign(integerPart *, const integerPart *, unsigned int);
1383
1384   /// Returns true if a bignum is zero, false otherwise.
1385   static bool tcIsZero(const integerPart *, unsigned int);
1386
1387   /// Extract the given bit of a bignum; returns 0 or 1.  Zero-based.
1388   static int tcExtractBit(const integerPart *, unsigned int bit);
1389
1390   /// Copy the bit vector of width srcBITS from SRC, starting at bit
1391   /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
1392   /// becomes the least significant bit of DST.  All high bits above
1393   /// srcBITS in DST are zero-filled.
1394   static void tcExtract(integerPart *, unsigned int dstCount,
1395                         const integerPart *,
1396                         unsigned int srcBits, unsigned int srcLSB);
1397
1398   /// Set the given bit of a bignum.  Zero-based.
1399   static void tcSetBit(integerPart *, unsigned int bit);
1400
1401   /// Clear the given bit of a bignum.  Zero-based.
1402   static void tcClearBit(integerPart *, unsigned int bit);
1403
1404   /// Returns the bit number of the least or most significant set bit
1405   /// of a number.  If the input number has no bits set -1U is
1406   /// returned.
1407   static unsigned int tcLSB(const integerPart *, unsigned int);
1408   static unsigned int tcMSB(const integerPart *parts, unsigned int n);
1409
1410   /// Negate a bignum in-place.
1411   static void tcNegate(integerPart *, unsigned int);
1412
1413   /// DST += RHS + CARRY where CARRY is zero or one.  Returns the
1414   /// carry flag.
1415   static integerPart tcAdd(integerPart *, const integerPart *,
1416                            integerPart carry, unsigned);
1417
1418   /// DST -= RHS + CARRY where CARRY is zero or one.  Returns the
1419   /// carry flag.
1420   static integerPart tcSubtract(integerPart *, const integerPart *,
1421                                 integerPart carry, unsigned);
1422
1423   ///  DST += SRC * MULTIPLIER + PART   if add is true
1424   ///  DST  = SRC * MULTIPLIER + PART   if add is false
1425   ///
1426   ///  Requires 0 <= DSTPARTS <= SRCPARTS + 1.  If DST overlaps SRC
1427   ///  they must start at the same point, i.e. DST == SRC.
1428   ///
1429   ///  If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1430   ///  returned.  Otherwise DST is filled with the least significant
1431   ///  DSTPARTS parts of the result, and if all of the omitted higher
1432   ///  parts were zero return zero, otherwise overflow occurred and
1433   ///  return one.
1434   static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1435                             integerPart multiplier, integerPart carry,
1436                             unsigned int srcParts, unsigned int dstParts,
1437                             bool add);
1438
1439   /// DST = LHS * RHS, where DST has the same width as the operands
1440   /// and is filled with the least significant parts of the result.
1441   /// Returns one if overflow occurred, otherwise zero.  DST must be
1442   /// disjoint from both operands.
1443   static int tcMultiply(integerPart *, const integerPart *,
1444                         const integerPart *, unsigned);
1445
1446   /// DST = LHS * RHS, where DST has width the sum of the widths of
1447   /// the operands.  No overflow occurs.  DST must be disjoint from
1448   /// both operands. Returns the number of parts required to hold the
1449   /// result.
1450   static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1451                                      const integerPart *, unsigned, unsigned);
1452
1453   /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1454   /// Otherwise set LHS to LHS / RHS with the fractional part
1455   /// discarded, set REMAINDER to the remainder, return zero.  i.e.
1456   ///
1457   ///  OLD_LHS = RHS * LHS + REMAINDER
1458   ///
1459   ///  SCRATCH is a bignum of the same size as the operands and result
1460   ///  for use by the routine; its contents need not be initialized
1461   ///  and are destroyed.  LHS, REMAINDER and SCRATCH must be
1462   ///  distinct.
1463   static int tcDivide(integerPart *lhs, const integerPart *rhs,
1464                       integerPart *remainder, integerPart *scratch,
1465                       unsigned int parts);
1466
1467   /// Shift a bignum left COUNT bits.  Shifted in bits are zero.
1468   /// There are no restrictions on COUNT.
1469   static void tcShiftLeft(integerPart *, unsigned int parts,
1470                           unsigned int count);
1471
1472   /// Shift a bignum right COUNT bits.  Shifted in bits are zero.
1473   /// There are no restrictions on COUNT.
1474   static void tcShiftRight(integerPart *, unsigned int parts,
1475                            unsigned int count);
1476
1477   /// The obvious AND, OR and XOR and complement operations.
1478   static void tcAnd(integerPart *, const integerPart *, unsigned int);
1479   static void tcOr(integerPart *, const integerPart *, unsigned int);
1480   static void tcXor(integerPart *, const integerPart *, unsigned int);
1481   static void tcComplement(integerPart *, unsigned int);
1482
1483   /// Comparison (unsigned) of two bignums.
1484   static int tcCompare(const integerPart *, const integerPart *,
1485                        unsigned int);
1486
1487   /// Increment a bignum in-place.  Return the carry flag.
1488   static integerPart tcIncrement(integerPart *, unsigned int);
1489
1490   /// Set the least significant BITS and clear the rest.
1491   static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1492                                         unsigned int bits);
1493
1494   /// @brief debug method
1495   void dump() const;
1496
1497   /// @}
1498 };
1499
1500 /// Magic data for optimising signed division by a constant.
1501 struct APInt::ms {
1502   APInt m;  ///< magic number
1503   unsigned s;  ///< shift amount
1504 };
1505
1506 /// Magic data for optimising unsigned division by a constant.
1507 struct APInt::mu {
1508   APInt m;     ///< magic number
1509   bool a;      ///< add indicator
1510   unsigned s;  ///< shift amount
1511 };
1512
1513 inline bool operator==(uint64_t V1, const APInt& V2) {
1514   return V2 == V1;
1515 }
1516
1517 inline bool operator!=(uint64_t V1, const APInt& V2) {
1518   return V2 != V1;
1519 }
1520
1521 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1522   I.print(OS, true);
1523   return OS;
1524 }
1525
1526 namespace APIntOps {
1527
1528 /// @brief Determine the smaller of two APInts considered to be signed.
1529 inline APInt smin(const APInt &A, const APInt &B) {
1530   return A.slt(B) ? A : B;
1531 }
1532
1533 /// @brief Determine the larger of two APInts considered to be signed.
1534 inline APInt smax(const APInt &A, const APInt &B) {
1535   return A.sgt(B) ? A : B;
1536 }
1537
1538 /// @brief Determine the smaller of two APInts considered to be signed.
1539 inline APInt umin(const APInt &A, const APInt &B) {
1540   return A.ult(B) ? A : B;
1541 }
1542
1543 /// @brief Determine the larger of two APInts considered to be unsigned.
1544 inline APInt umax(const APInt &A, const APInt &B) {
1545   return A.ugt(B) ? A : B;
1546 }
1547
1548 /// @brief Check if the specified APInt has a N-bits unsigned integer value.
1549 inline bool isIntN(unsigned N, const APInt& APIVal) {
1550   return APIVal.isIntN(N);
1551 }
1552
1553 /// @brief Check if the specified APInt has a N-bits signed integer value.
1554 inline bool isSignedIntN(unsigned N, const APInt& APIVal) {
1555   return APIVal.isSignedIntN(N);
1556 }
1557
1558 /// @returns true if the argument APInt value is a sequence of ones
1559 /// starting at the least significant bit with the remainder zero.
1560 inline bool isMask(unsigned numBits, const APInt& APIVal) {
1561   return numBits <= APIVal.getBitWidth() &&
1562     APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
1563 }
1564
1565 /// @returns true if the argument APInt value contains a sequence of ones
1566 /// with the remainder zero.
1567 inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
1568   return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1569 }
1570
1571 /// @returns a byte-swapped representation of the specified APInt Value.
1572 inline APInt byteSwap(const APInt& APIVal) {
1573   return APIVal.byteSwap();
1574 }
1575
1576 /// @returns the floor log base 2 of the specified APInt value.
1577 inline unsigned logBase2(const APInt& APIVal) {
1578   return APIVal.logBase2();
1579 }
1580
1581 /// GreatestCommonDivisor - This function returns the greatest common
1582 /// divisor of the two APInt values using Euclid's algorithm.
1583 /// @returns the greatest common divisor of Val1 and Val2
1584 /// @brief Compute GCD of two APInt values.
1585 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1586
1587 /// Treats the APInt as an unsigned value for conversion purposes.
1588 /// @brief Converts the given APInt to a double value.
1589 inline double RoundAPIntToDouble(const APInt& APIVal) {
1590   return APIVal.roundToDouble();
1591 }
1592
1593 /// Treats the APInt as a signed value for conversion purposes.
1594 /// @brief Converts the given APInt to a double value.
1595 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1596   return APIVal.signedRoundToDouble();
1597 }
1598
1599 /// @brief Converts the given APInt to a float vlalue.
1600 inline float RoundAPIntToFloat(const APInt& APIVal) {
1601   return float(RoundAPIntToDouble(APIVal));
1602 }
1603
1604 /// Treast the APInt as a signed value for conversion purposes.
1605 /// @brief Converts the given APInt to a float value.
1606 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1607   return float(APIVal.signedRoundToDouble());
1608 }
1609
1610 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1611 /// @brief Converts the given double value into a APInt.
1612 APInt RoundDoubleToAPInt(double Double, unsigned width);
1613
1614 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1615 /// @brief Converts a float value into a APInt.
1616 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
1617   return RoundDoubleToAPInt(double(Float), width);
1618 }
1619
1620 /// Arithmetic right-shift the APInt by shiftAmt.
1621 /// @brief Arithmetic right-shift function.
1622 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
1623   return LHS.ashr(shiftAmt);
1624 }
1625
1626 /// Logical right-shift the APInt by shiftAmt.
1627 /// @brief Logical right-shift function.
1628 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
1629   return LHS.lshr(shiftAmt);
1630 }
1631
1632 /// Left-shift the APInt by shiftAmt.
1633 /// @brief Left-shift function.
1634 inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
1635   return LHS.shl(shiftAmt);
1636 }
1637
1638 /// Signed divide APInt LHS by APInt RHS.
1639 /// @brief Signed division function for APInt.
1640 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1641   return LHS.sdiv(RHS);
1642 }
1643
1644 /// Unsigned divide APInt LHS by APInt RHS.
1645 /// @brief Unsigned division function for APInt.
1646 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1647   return LHS.udiv(RHS);
1648 }
1649
1650 /// Signed remainder operation on APInt.
1651 /// @brief Function for signed remainder operation.
1652 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1653   return LHS.srem(RHS);
1654 }
1655
1656 /// Unsigned remainder operation on APInt.
1657 /// @brief Function for unsigned remainder operation.
1658 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1659   return LHS.urem(RHS);
1660 }
1661
1662 /// Performs multiplication on APInt values.
1663 /// @brief Function for multiplication operation.
1664 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1665   return LHS * RHS;
1666 }
1667
1668 /// Performs addition on APInt values.
1669 /// @brief Function for addition operation.
1670 inline APInt add(const APInt& LHS, const APInt& RHS) {
1671   return LHS + RHS;
1672 }
1673
1674 /// Performs subtraction on APInt values.
1675 /// @brief Function for subtraction operation.
1676 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1677   return LHS - RHS;
1678 }
1679
1680 /// Performs bitwise AND operation on APInt LHS and
1681 /// APInt RHS.
1682 /// @brief Bitwise AND function for APInt.
1683 inline APInt And(const APInt& LHS, const APInt& RHS) {
1684   return LHS & RHS;
1685 }
1686
1687 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1688 /// @brief Bitwise OR function for APInt.
1689 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1690   return LHS | RHS;
1691 }
1692
1693 /// Performs bitwise XOR operation on APInt.
1694 /// @brief Bitwise XOR function for APInt.
1695 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1696   return LHS ^ RHS;
1697 }
1698
1699 /// Performs a bitwise complement operation on APInt.
1700 /// @brief Bitwise complement function.
1701 inline APInt Not(const APInt& APIVal) {
1702   return ~APIVal;
1703 }
1704
1705 } // End of APIntOps namespace
1706
1707 } // End of llvm namespace
1708
1709 #endif