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