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