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