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