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