LLVM 20.0.0git
APInt.h
Go to the documentation of this file.
1//===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements a class to represent arbitrary precision
11/// integral constant values and operations on them.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_APINT_H
16#define LLVM_ADT_APINT_H
17
21#include <cassert>
22#include <climits>
23#include <cstring>
24#include <optional>
25#include <utility>
26
27namespace llvm {
28class FoldingSetNodeID;
29class StringRef;
30class hash_code;
31class raw_ostream;
32struct Align;
33class DynamicAPInt;
34
35template <typename T> class SmallVectorImpl;
36template <typename T> class ArrayRef;
37template <typename T, typename Enable> struct DenseMapInfo;
38
39class APInt;
40
41inline APInt operator-(APInt);
42
43//===----------------------------------------------------------------------===//
44// APInt Class
45//===----------------------------------------------------------------------===//
46
47/// 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/// * APInt supports zero-bit-width values, but operations that require bits
73/// are not defined on it (e.g. you cannot ask for the sign of a zero-bit
74/// integer). This means that operations like zero extension and logical
75/// shifts are defined, but sign extension and ashr is not. Zero bit values
76/// compare and hash equal to themselves, and countLeadingZeros returns 0.
77///
78class [[nodiscard]] APInt {
79public:
81
82 /// Byte size of a word.
83 static constexpr unsigned APINT_WORD_SIZE = sizeof(WordType);
84
85 /// Bits in a word.
86 static constexpr unsigned APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT;
87
88 enum class Rounding {
89 DOWN,
90 TOWARD_ZERO,
91 UP,
92 };
93
94 static constexpr WordType WORDTYPE_MAX = ~WordType(0);
95
96 /// \name Constructors
97 /// @{
98
99 /// Create a new APInt of numBits width, initialized as val.
100 ///
101 /// If isSigned is true then val is treated as if it were a signed value
102 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
103 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
104 /// the range of val are zero filled).
105 ///
106 /// \param numBits the bit width of the constructed APInt
107 /// \param val the initial value of the APInt
108 /// \param isSigned how to treat signedness of val
109 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
110 : BitWidth(numBits) {
111 if (isSingleWord()) {
112 U.VAL = val;
114 } else {
115 initSlowCase(val, isSigned);
116 }
117 }
118
119 /// Construct an APInt of numBits width, initialized as bigVal[].
120 ///
121 /// Note that bigVal.size() can be smaller or larger than the corresponding
122 /// bit width but any extraneous bits will be dropped.
123 ///
124 /// \param numBits the bit width of the constructed APInt
125 /// \param bigVal a sequence of words to form the initial value of the APInt
126 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
127
128 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
129 /// deprecated because this constructor is prone to ambiguity with the
130 /// APInt(unsigned, uint64_t, bool) constructor.
131 ///
132 /// If this overload is ever deleted, care should be taken to prevent calls
133 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
134 /// constructor.
135 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
136
137 /// Construct an APInt from a string representation.
138 ///
139 /// This constructor interprets the string \p str in the given radix. The
140 /// interpretation stops when the first character that is not suitable for the
141 /// radix is encountered, or the end of the string. Acceptable radix values
142 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
143 /// string to require more bits than numBits.
144 ///
145 /// \param numBits the bit width of the constructed APInt
146 /// \param str the string to be interpreted
147 /// \param radix the radix to use for the conversion
148 APInt(unsigned numBits, StringRef str, uint8_t radix);
149
150 /// Default constructor that creates an APInt with a 1-bit zero value.
151 explicit APInt() { U.VAL = 0; }
152
153 /// Copy Constructor.
154 APInt(const APInt &that) : BitWidth(that.BitWidth) {
155 if (isSingleWord())
156 U.VAL = that.U.VAL;
157 else
158 initSlowCase(that);
159 }
160
161 /// Move Constructor.
162 APInt(APInt &&that) : BitWidth(that.BitWidth) {
163 memcpy(&U, &that.U, sizeof(U));
164 that.BitWidth = 0;
165 }
166
167 /// Destructor.
169 if (needsCleanup())
170 delete[] U.pVal;
171 }
172
173 /// @}
174 /// \name Value Generators
175 /// @{
176
177 /// Get the '0' value for the specified bit-width.
178 static APInt getZero(unsigned numBits) { return APInt(numBits, 0); }
179
180 /// Return an APInt zero bits wide.
181 static APInt getZeroWidth() { return getZero(0); }
182
183 /// Gets maximum unsigned value of APInt for specific bit width.
184 static APInt getMaxValue(unsigned numBits) { return getAllOnes(numBits); }
185
186 /// Gets maximum signed value of APInt for a specific bit width.
187 static APInt getSignedMaxValue(unsigned numBits) {
188 APInt API = getAllOnes(numBits);
189 API.clearBit(numBits - 1);
190 return API;
191 }
192
193 /// Gets minimum unsigned value of APInt for a specific bit width.
194 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
195
196 /// Gets minimum signed value of APInt for a specific bit width.
197 static APInt getSignedMinValue(unsigned numBits) {
198 APInt API(numBits, 0);
199 API.setBit(numBits - 1);
200 return API;
201 }
202
203 /// Get the SignMask for a specific bit width.
204 ///
205 /// This is just a wrapper function of getSignedMinValue(), and it helps code
206 /// readability when we want to get a SignMask.
207 static APInt getSignMask(unsigned BitWidth) {
208 return getSignedMinValue(BitWidth);
209 }
210
211 /// Return an APInt of a specified width with all bits set.
212 static APInt getAllOnes(unsigned numBits) {
213 return APInt(numBits, WORDTYPE_MAX, true);
214 }
215
216 /// Return an APInt with exactly one bit set in the result.
217 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
218 APInt Res(numBits, 0);
219 Res.setBit(BitNo);
220 return Res;
221 }
222
223 /// Get a value with a block of bits set.
224 ///
225 /// Constructs an APInt value that has a contiguous range of bits set. The
226 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
227 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
228 /// 0x0000FFFF. Please call getBitsSetWithWrap if \p loBit may be greater than
229 /// \p hiBit.
230 ///
231 /// \param numBits the intended bit width of the result
232 /// \param loBit the index of the lowest bit set.
233 /// \param hiBit the index of the highest bit set.
234 ///
235 /// \returns An APInt value with the requested bits set.
236 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
237 APInt Res(numBits, 0);
238 Res.setBits(loBit, hiBit);
239 return Res;
240 }
241
242 /// Wrap version of getBitsSet.
243 /// If \p hiBit is bigger than \p loBit, this is same with getBitsSet.
244 /// If \p hiBit is not bigger than \p loBit, the set bits "wrap". For example,
245 /// with parameters (32, 28, 4), you would get 0xF000000F.
246 /// If \p hiBit is equal to \p loBit, you would get a result with all bits
247 /// set.
248 static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit,
249 unsigned hiBit) {
250 APInt Res(numBits, 0);
251 Res.setBitsWithWrap(loBit, hiBit);
252 return Res;
253 }
254
255 /// Constructs an APInt value that has a contiguous range of bits set. The
256 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
257 /// bits will be zero. For example, with parameters(32, 12) you would get
258 /// 0xFFFFF000.
259 ///
260 /// \param numBits the intended bit width of the result
261 /// \param loBit the index of the lowest bit to set.
262 ///
263 /// \returns An APInt value with the requested bits set.
264 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
265 APInt Res(numBits, 0);
266 Res.setBitsFrom(loBit);
267 return Res;
268 }
269
270 /// Constructs an APInt value that has the top hiBitsSet bits set.
271 ///
272 /// \param numBits the bitwidth of the result
273 /// \param hiBitsSet the number of high-order bits set in the result.
274 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
275 APInt Res(numBits, 0);
276 Res.setHighBits(hiBitsSet);
277 return Res;
278 }
279
280 /// Constructs an APInt value that has the bottom loBitsSet bits set.
281 ///
282 /// \param numBits the bitwidth of the result
283 /// \param loBitsSet the number of low-order bits set in the result.
284 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
285 APInt Res(numBits, 0);
286 Res.setLowBits(loBitsSet);
287 return Res;
288 }
289
290 /// Return a value containing V broadcasted over NewLen bits.
291 static APInt getSplat(unsigned NewLen, const APInt &V);
292
293 /// @}
294 /// \name Value Tests
295 /// @{
296
297 /// Determine if this APInt just has one word to store value.
298 ///
299 /// \returns true if the number of bits <= 64, false otherwise.
300 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
301
302 /// Determine sign of this APInt.
303 ///
304 /// This tests the high bit of this APInt to determine if it is set.
305 ///
306 /// \returns true if this APInt is negative, false otherwise
307 bool isNegative() const { return (*this)[BitWidth - 1]; }
308
309 /// Determine if this APInt Value is non-negative (>= 0)
310 ///
311 /// This tests the high bit of the APInt to determine if it is unset.
312 bool isNonNegative() const { return !isNegative(); }
313
314 /// Determine if sign bit of this APInt is set.
315 ///
316 /// This tests the high bit of this APInt to determine if it is set.
317 ///
318 /// \returns true if this APInt has its sign bit set, false otherwise.
319 bool isSignBitSet() const { return (*this)[BitWidth - 1]; }
320
321 /// Determine if sign bit of this APInt is clear.
322 ///
323 /// This tests the high bit of this APInt to determine if it is clear.
324 ///
325 /// \returns true if this APInt has its sign bit clear, false otherwise.
326 bool isSignBitClear() const { return !isSignBitSet(); }
327
328 /// Determine if this APInt Value is positive.
329 ///
330 /// This tests if the value of this APInt is positive (> 0). Note
331 /// that 0 is not a positive value.
332 ///
333 /// \returns true if this APInt is positive.
334 bool isStrictlyPositive() const { return isNonNegative() && !isZero(); }
335
336 /// Determine if this APInt Value is non-positive (<= 0).
337 ///
338 /// \returns true if this APInt is non-positive.
339 bool isNonPositive() const { return !isStrictlyPositive(); }
340
341 /// Determine if this APInt Value only has the specified bit set.
342 ///
343 /// \returns true if this APInt only has the specified bit set.
344 bool isOneBitSet(unsigned BitNo) const {
345 return (*this)[BitNo] && popcount() == 1;
346 }
347
348 /// Determine if all bits are set. This is true for zero-width values.
349 bool isAllOnes() const {
350 if (BitWidth == 0)
351 return true;
352 if (isSingleWord())
353 return U.VAL == WORDTYPE_MAX >> (APINT_BITS_PER_WORD - BitWidth);
354 return countTrailingOnesSlowCase() == BitWidth;
355 }
356
357 /// Determine if this value is zero, i.e. all bits are clear.
358 bool isZero() const {
359 if (isSingleWord())
360 return U.VAL == 0;
361 return countLeadingZerosSlowCase() == BitWidth;
362 }
363
364 /// Determine if this is a value of 1.
365 ///
366 /// This checks to see if the value of this APInt is one.
367 bool isOne() const {
368 if (isSingleWord())
369 return U.VAL == 1;
370 return countLeadingZerosSlowCase() == BitWidth - 1;
371 }
372
373 /// Determine if this is the largest unsigned value.
374 ///
375 /// This checks to see if the value of this APInt is the maximum unsigned
376 /// value for the APInt's bit width.
377 bool isMaxValue() const { return isAllOnes(); }
378
379 /// Determine if this is the largest signed value.
380 ///
381 /// This checks to see if the value of this APInt is the maximum signed
382 /// value for the APInt's bit width.
383 bool isMaxSignedValue() const {
384 if (isSingleWord()) {
385 assert(BitWidth && "zero width values not allowed");
386 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
387 }
388 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
389 }
390
391 /// Determine if this is the smallest unsigned value.
392 ///
393 /// This checks to see if the value of this APInt is the minimum unsigned
394 /// value for the APInt's bit width.
395 bool isMinValue() const { return isZero(); }
396
397 /// Determine if this is the smallest signed value.
398 ///
399 /// This checks to see if the value of this APInt is the minimum signed
400 /// value for the APInt's bit width.
401 bool isMinSignedValue() const {
402 if (isSingleWord()) {
403 assert(BitWidth && "zero width values not allowed");
404 return U.VAL == (WordType(1) << (BitWidth - 1));
405 }
406 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
407 }
408
409 /// Check if this APInt has an N-bits unsigned integer value.
410 bool isIntN(unsigned N) const { return getActiveBits() <= N; }
411
412 /// Check if this APInt has an N-bits signed integer value.
413 bool isSignedIntN(unsigned N) const { return getSignificantBits() <= N; }
414
415 /// Check if this APInt's value is a power of two greater than zero.
416 ///
417 /// \returns true if the argument APInt value is a power of two > 0.
418 bool isPowerOf2() const {
419 if (isSingleWord()) {
420 assert(BitWidth && "zero width values not allowed");
421 return isPowerOf2_64(U.VAL);
422 }
423 return countPopulationSlowCase() == 1;
424 }
425
426 /// Check if this APInt's negated value is a power of two greater than zero.
427 bool isNegatedPowerOf2() const {
428 assert(BitWidth && "zero width values not allowed");
429 if (isNonNegative())
430 return false;
431 // NegatedPowerOf2 - shifted mask in the top bits.
432 unsigned LO = countl_one();
433 unsigned TZ = countr_zero();
434 return (LO + TZ) == BitWidth;
435 }
436
437 /// Checks if this APInt -interpreted as an address- is aligned to the
438 /// provided value.
439 bool isAligned(Align A) const;
440
441 /// Check if the APInt's value is returned by getSignMask.
442 ///
443 /// \returns true if this is the value returned by getSignMask.
444 bool isSignMask() const { return isMinSignedValue(); }
445
446 /// Convert APInt to a boolean value.
447 ///
448 /// This converts the APInt to a boolean value as a test against zero.
449 bool getBoolValue() const { return !isZero(); }
450
451 /// If this value is smaller than the specified limit, return it, otherwise
452 /// return the limit value. This causes the value to saturate to the limit.
454 return ugt(Limit) ? Limit : getZExtValue();
455 }
456
457 /// Check if the APInt consists of a repeated bit pattern.
458 ///
459 /// e.g. 0x01010101 satisfies isSplat(8).
460 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
461 /// width without remainder.
462 bool isSplat(unsigned SplatSizeInBits) const;
463
464 /// \returns true if this APInt value is a sequence of \param numBits ones
465 /// starting at the least significant bit with the remainder zero.
466 bool isMask(unsigned numBits) const {
467 assert(numBits != 0 && "numBits must be non-zero");
468 assert(numBits <= BitWidth && "numBits out of range");
469 if (isSingleWord())
470 return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits));
471 unsigned Ones = countTrailingOnesSlowCase();
472 return (numBits == Ones) &&
473 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
474 }
475
476 /// \returns true if this APInt is a non-empty sequence of ones starting at
477 /// the least significant bit with the remainder zero.
478 /// Ex. isMask(0x0000FFFFU) == true.
479 bool isMask() const {
480 if (isSingleWord())
481 return isMask_64(U.VAL);
482 unsigned Ones = countTrailingOnesSlowCase();
483 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
484 }
485
486 /// Return true if this APInt value contains a non-empty sequence of ones with
487 /// the remainder zero.
488 bool isShiftedMask() const {
489 if (isSingleWord())
490 return isShiftedMask_64(U.VAL);
491 unsigned Ones = countPopulationSlowCase();
492 unsigned LeadZ = countLeadingZerosSlowCase();
493 return (Ones + LeadZ + countr_zero()) == BitWidth;
494 }
495
496 /// Return true if this APInt value contains a non-empty sequence of ones with
497 /// the remainder zero. If true, \p MaskIdx will specify the index of the
498 /// lowest set bit and \p MaskLen is updated to specify the length of the
499 /// mask, else neither are updated.
500 bool isShiftedMask(unsigned &MaskIdx, unsigned &MaskLen) const {
501 if (isSingleWord())
502 return isShiftedMask_64(U.VAL, MaskIdx, MaskLen);
503 unsigned Ones = countPopulationSlowCase();
504 unsigned LeadZ = countLeadingZerosSlowCase();
505 unsigned TrailZ = countTrailingZerosSlowCase();
506 if ((Ones + LeadZ + TrailZ) != BitWidth)
507 return false;
508 MaskLen = Ones;
509 MaskIdx = TrailZ;
510 return true;
511 }
512
513 /// Compute an APInt containing numBits highbits from this APInt.
514 ///
515 /// Get an APInt with the same BitWidth as this APInt, just zero mask the low
516 /// bits and right shift to the least significant bit.
517 ///
518 /// \returns the high "numBits" bits of this APInt.
519 APInt getHiBits(unsigned numBits) const;
520
521 /// Compute an APInt containing numBits lowbits from this APInt.
522 ///
523 /// Get an APInt with the same BitWidth as this APInt, just zero mask the high
524 /// bits.
525 ///
526 /// \returns the low "numBits" bits of this APInt.
527 APInt getLoBits(unsigned numBits) const;
528
529 /// Determine if two APInts have the same value, after zero-extending
530 /// one of them (if needed!) to ensure that the bit-widths match.
531 static bool isSameValue(const APInt &I1, const APInt &I2) {
532 if (I1.getBitWidth() == I2.getBitWidth())
533 return I1 == I2;
534
535 if (I1.getBitWidth() > I2.getBitWidth())
536 return I1 == I2.zext(I1.getBitWidth());
537
538 return I1.zext(I2.getBitWidth()) == I2;
539 }
540
541 /// Overload to compute a hash_code for an APInt value.
542 friend hash_code hash_value(const APInt &Arg);
543
544 /// This function returns a pointer to the internal storage of the APInt.
545 /// This is useful for writing out the APInt in binary form without any
546 /// conversions.
547 const uint64_t *getRawData() const {
548 if (isSingleWord())
549 return &U.VAL;
550 return &U.pVal[0];
551 }
552
553 /// @}
554 /// \name Unary Operators
555 /// @{
556
557 /// Postfix increment operator. Increment *this by 1.
558 ///
559 /// \returns a new APInt value representing the original value of *this.
561 APInt API(*this);
562 ++(*this);
563 return API;
564 }
565
566 /// Prefix increment operator.
567 ///
568 /// \returns *this incremented by one
569 APInt &operator++();
570
571 /// Postfix decrement operator. Decrement *this by 1.
572 ///
573 /// \returns a new APInt value representing the original value of *this.
575 APInt API(*this);
576 --(*this);
577 return API;
578 }
579
580 /// Prefix decrement operator.
581 ///
582 /// \returns *this decremented by one.
583 APInt &operator--();
584
585 /// Logical negation operation on this APInt returns true if zero, like normal
586 /// integers.
587 bool operator!() const { return isZero(); }
588
589 /// @}
590 /// \name Assignment Operators
591 /// @{
592
593 /// Copy assignment operator.
594 ///
595 /// \returns *this after assignment of RHS.
597 // The common case (both source or dest being inline) doesn't require
598 // allocation or deallocation.
599 if (isSingleWord() && RHS.isSingleWord()) {
600 U.VAL = RHS.U.VAL;
601 BitWidth = RHS.BitWidth;
602 return *this;
603 }
604
605 assignSlowCase(RHS);
606 return *this;
607 }
608
609 /// Move assignment operator.
611#ifdef EXPENSIVE_CHECKS
612 // Some std::shuffle implementations still do self-assignment.
613 if (this == &that)
614 return *this;
615#endif
616 assert(this != &that && "Self-move not supported");
617 if (!isSingleWord())
618 delete[] U.pVal;
619
620 // Use memcpy so that type based alias analysis sees both VAL and pVal
621 // as modified.
622 memcpy(&U, &that.U, sizeof(U));
623
624 BitWidth = that.BitWidth;
625 that.BitWidth = 0;
626 return *this;
627 }
628
629 /// Assignment operator.
630 ///
631 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
632 /// the bit width, the excess bits are truncated. If the bit width is larger
633 /// than 64, the value is zero filled in the unspecified high order bits.
634 ///
635 /// \returns *this after assignment of RHS value.
637 if (isSingleWord()) {
638 U.VAL = RHS;
639 return clearUnusedBits();
640 }
641 U.pVal[0] = RHS;
642 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
643 return *this;
644 }
645
646 /// Bitwise AND assignment operator.
647 ///
648 /// Performs a bitwise AND operation on this APInt and RHS. The result is
649 /// assigned to *this.
650 ///
651 /// \returns *this after ANDing with RHS.
653 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
654 if (isSingleWord())
655 U.VAL &= RHS.U.VAL;
656 else
657 andAssignSlowCase(RHS);
658 return *this;
659 }
660
661 /// Bitwise AND assignment operator.
662 ///
663 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
664 /// logically zero-extended or truncated to match the bit-width of
665 /// the LHS.
667 if (isSingleWord()) {
668 U.VAL &= RHS;
669 return *this;
670 }
671 U.pVal[0] &= RHS;
672 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
673 return *this;
674 }
675
676 /// Bitwise OR assignment operator.
677 ///
678 /// Performs a bitwise OR operation on this APInt and RHS. The result is
679 /// assigned *this;
680 ///
681 /// \returns *this after ORing with RHS.
683 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
684 if (isSingleWord())
685 U.VAL |= RHS.U.VAL;
686 else
687 orAssignSlowCase(RHS);
688 return *this;
689 }
690
691 /// Bitwise OR assignment operator.
692 ///
693 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
694 /// logically zero-extended or truncated to match the bit-width of
695 /// the LHS.
697 if (isSingleWord()) {
698 U.VAL |= RHS;
699 return clearUnusedBits();
700 }
701 U.pVal[0] |= RHS;
702 return *this;
703 }
704
705 /// Bitwise XOR assignment operator.
706 ///
707 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
708 /// assigned to *this.
709 ///
710 /// \returns *this after XORing with RHS.
712 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
713 if (isSingleWord())
714 U.VAL ^= RHS.U.VAL;
715 else
716 xorAssignSlowCase(RHS);
717 return *this;
718 }
719
720 /// Bitwise XOR assignment operator.
721 ///
722 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
723 /// logically zero-extended or truncated to match the bit-width of
724 /// the LHS.
726 if (isSingleWord()) {
727 U.VAL ^= RHS;
728 return clearUnusedBits();
729 }
730 U.pVal[0] ^= RHS;
731 return *this;
732 }
733
734 /// 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);
741
742 /// Addition assignment operator.
743 ///
744 /// Adds RHS to *this and assigns the result to *this.
745 ///
746 /// \returns *this
747 APInt &operator+=(const APInt &RHS);
749
750 /// Subtraction assignment operator.
751 ///
752 /// Subtracts RHS from *this and assigns the result to *this.
753 ///
754 /// \returns *this
755 APInt &operator-=(const APInt &RHS);
757
758 /// Left-shift assignment function.
759 ///
760 /// Shifts *this left by shiftAmt and assigns the result to *this.
761 ///
762 /// \returns *this after shifting left by ShiftAmt
763 APInt &operator<<=(unsigned ShiftAmt) {
764 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
765 if (isSingleWord()) {
766 if (ShiftAmt == BitWidth)
767 U.VAL = 0;
768 else
769 U.VAL <<= ShiftAmt;
770 return clearUnusedBits();
771 }
772 shlSlowCase(ShiftAmt);
773 return *this;
774 }
775
776 /// Left-shift assignment function.
777 ///
778 /// Shifts *this left by shiftAmt and assigns the result to *this.
779 ///
780 /// \returns *this after shifting left by ShiftAmt
781 APInt &operator<<=(const APInt &ShiftAmt);
782
783 /// @}
784 /// \name Binary Operators
785 /// @{
786
787 /// Multiplication operator.
788 ///
789 /// Multiplies this APInt by RHS and returns the result.
790 APInt operator*(const APInt &RHS) const;
791
792 /// Left logical shift operator.
793 ///
794 /// Shifts this APInt left by \p Bits and returns the result.
795 APInt operator<<(unsigned Bits) const { return shl(Bits); }
796
797 /// Left logical shift operator.
798 ///
799 /// Shifts this APInt left by \p Bits and returns the result.
800 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
801
802 /// Arithmetic right-shift function.
803 ///
804 /// Arithmetic right-shift this APInt by shiftAmt.
805 APInt ashr(unsigned ShiftAmt) const {
806 APInt R(*this);
807 R.ashrInPlace(ShiftAmt);
808 return R;
809 }
810
811 /// Arithmetic right-shift this APInt by ShiftAmt in place.
812 void ashrInPlace(unsigned ShiftAmt) {
813 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
814 if (isSingleWord()) {
815 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
816 if (ShiftAmt == BitWidth)
817 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
818 else
819 U.VAL = SExtVAL >> ShiftAmt;
821 return;
822 }
823 ashrSlowCase(ShiftAmt);
824 }
825
826 /// Logical right-shift function.
827 ///
828 /// Logical right-shift this APInt by shiftAmt.
829 APInt lshr(unsigned shiftAmt) const {
830 APInt R(*this);
831 R.lshrInPlace(shiftAmt);
832 return R;
833 }
834
835 /// Logical right-shift this APInt by ShiftAmt in place.
836 void lshrInPlace(unsigned ShiftAmt) {
837 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
838 if (isSingleWord()) {
839 if (ShiftAmt == BitWidth)
840 U.VAL = 0;
841 else
842 U.VAL >>= ShiftAmt;
843 return;
844 }
845 lshrSlowCase(ShiftAmt);
846 }
847
848 /// Left-shift function.
849 ///
850 /// Left-shift this APInt by shiftAmt.
851 APInt shl(unsigned shiftAmt) const {
852 APInt R(*this);
853 R <<= shiftAmt;
854 return R;
855 }
856
857 /// relative logical shift right
858 APInt relativeLShr(int RelativeShift) const {
859 return RelativeShift > 0 ? lshr(RelativeShift) : shl(-RelativeShift);
860 }
861
862 /// relative logical shift left
863 APInt relativeLShl(int RelativeShift) const {
864 return relativeLShr(-RelativeShift);
865 }
866
867 /// relative arithmetic shift right
868 APInt relativeAShr(int RelativeShift) const {
869 return RelativeShift > 0 ? ashr(RelativeShift) : shl(-RelativeShift);
870 }
871
872 /// relative arithmetic shift left
873 APInt relativeAShl(int RelativeShift) const {
874 return relativeAShr(-RelativeShift);
875 }
876
877 /// Rotate left by rotateAmt.
878 APInt rotl(unsigned rotateAmt) const;
879
880 /// Rotate right by rotateAmt.
881 APInt rotr(unsigned rotateAmt) const;
882
883 /// Arithmetic right-shift function.
884 ///
885 /// Arithmetic right-shift this APInt by shiftAmt.
886 APInt ashr(const APInt &ShiftAmt) const {
887 APInt R(*this);
888 R.ashrInPlace(ShiftAmt);
889 return R;
890 }
891
892 /// Arithmetic right-shift this APInt by shiftAmt in place.
893 void ashrInPlace(const APInt &shiftAmt);
894
895 /// Logical right-shift function.
896 ///
897 /// Logical right-shift this APInt by shiftAmt.
898 APInt lshr(const APInt &ShiftAmt) const {
899 APInt R(*this);
900 R.lshrInPlace(ShiftAmt);
901 return R;
902 }
903
904 /// Logical right-shift this APInt by ShiftAmt in place.
905 void lshrInPlace(const APInt &ShiftAmt);
906
907 /// Left-shift function.
908 ///
909 /// Left-shift this APInt by shiftAmt.
910 APInt shl(const APInt &ShiftAmt) const {
911 APInt R(*this);
912 R <<= ShiftAmt;
913 return R;
914 }
915
916 /// Rotate left by rotateAmt.
917 APInt rotl(const APInt &rotateAmt) const;
918
919 /// Rotate right by rotateAmt.
920 APInt rotr(const APInt &rotateAmt) const;
921
922 /// Concatenate the bits from "NewLSB" onto the bottom of *this. This is
923 /// equivalent to:
924 /// (this->zext(NewWidth) << NewLSB.getBitWidth()) | NewLSB.zext(NewWidth)
925 APInt concat(const APInt &NewLSB) const {
926 /// If the result will be small, then both the merged values are small.
927 unsigned NewWidth = getBitWidth() + NewLSB.getBitWidth();
928 if (NewWidth <= APINT_BITS_PER_WORD)
929 return APInt(NewWidth, (U.VAL << NewLSB.getBitWidth()) | NewLSB.U.VAL);
930 return concatSlowCase(NewLSB);
931 }
932
933 /// Unsigned division operation.
934 ///
935 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
936 /// RHS are treated as unsigned quantities for purposes of this division.
937 ///
938 /// \returns a new APInt value containing the division result, rounded towards
939 /// zero.
940 APInt udiv(const APInt &RHS) const;
941 APInt udiv(uint64_t RHS) const;
942
943 /// Signed division function for APInt.
944 ///
945 /// Signed divide this APInt by APInt RHS.
946 ///
947 /// The result is rounded towards zero.
948 APInt sdiv(const APInt &RHS) const;
949 APInt sdiv(int64_t RHS) const;
950
951 /// Unsigned remainder operation.
952 ///
953 /// Perform an unsigned remainder operation on this APInt with RHS being the
954 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
955 /// of this operation.
956 ///
957 /// \returns a new APInt value containing the remainder result
958 APInt urem(const APInt &RHS) const;
959 uint64_t urem(uint64_t RHS) const;
960
961 /// Function for signed remainder operation.
962 ///
963 /// Signed remainder operation on APInt.
964 ///
965 /// Note that this is a true remainder operation and not a modulo operation
966 /// because the sign follows the sign of the dividend which is *this.
967 APInt srem(const APInt &RHS) const;
968 int64_t srem(int64_t RHS) const;
969
970 /// Dual division/remainder interface.
971 ///
972 /// Sometimes it is convenient to divide two APInt values and obtain both the
973 /// quotient and remainder. This function does both operations in the same
974 /// computation making it a little more efficient. The pair of input arguments
975 /// may overlap with the pair of output arguments. It is safe to call
976 /// udivrem(X, Y, X, Y), for example.
977 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
978 APInt &Remainder);
979 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
980 uint64_t &Remainder);
981
982 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
983 APInt &Remainder);
984 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
985 int64_t &Remainder);
986
987 // Operations that return overflow indicators.
988 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
989 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
990 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
991 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
992 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
993 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
994 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
995 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
996 APInt sshl_ov(unsigned Amt, bool &Overflow) const;
997 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
998 APInt ushl_ov(unsigned Amt, bool &Overflow) const;
999
1000 /// Signed integer floor division operation.
1001 ///
1002 /// Rounds towards negative infinity, i.e. 5 / -2 = -3. Iff minimum value
1003 /// divided by -1 set Overflow to true.
1004 APInt sfloordiv_ov(const APInt &RHS, bool &Overflow) const;
1005
1006 // Operations that saturate
1007 APInt sadd_sat(const APInt &RHS) const;
1008 APInt uadd_sat(const APInt &RHS) const;
1009 APInt ssub_sat(const APInt &RHS) const;
1010 APInt usub_sat(const APInt &RHS) const;
1011 APInt smul_sat(const APInt &RHS) const;
1012 APInt umul_sat(const APInt &RHS) const;
1013 APInt sshl_sat(const APInt &RHS) const;
1014 APInt sshl_sat(unsigned RHS) const;
1015 APInt ushl_sat(const APInt &RHS) const;
1016 APInt ushl_sat(unsigned RHS) const;
1017
1018 /// Array-indexing support.
1019 ///
1020 /// \returns the bit value at bitPosition
1021 bool operator[](unsigned bitPosition) const {
1022 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
1023 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
1024 }
1025
1026 /// @}
1027 /// \name Comparison Operators
1028 /// @{
1029
1030 /// Equality operator.
1031 ///
1032 /// Compares this APInt with RHS for the validity of the equality
1033 /// relationship.
1034 bool operator==(const APInt &RHS) const {
1035 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
1036 if (isSingleWord())
1037 return U.VAL == RHS.U.VAL;
1038 return equalSlowCase(RHS);
1039 }
1040
1041 /// Equality operator.
1042 ///
1043 /// Compares this APInt with a uint64_t for the validity of the equality
1044 /// relationship.
1045 ///
1046 /// \returns true if *this == Val
1047 bool operator==(uint64_t Val) const {
1048 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1049 }
1050
1051 /// Equality comparison.
1052 ///
1053 /// Compares this APInt with RHS for the validity of the equality
1054 /// relationship.
1055 ///
1056 /// \returns true if *this == Val
1057 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1058
1059 /// Inequality operator.
1060 ///
1061 /// Compares this APInt with RHS for the validity of the inequality
1062 /// relationship.
1063 ///
1064 /// \returns true if *this != Val
1065 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1066
1067 /// Inequality operator.
1068 ///
1069 /// Compares this APInt with a uint64_t for the validity of the inequality
1070 /// relationship.
1071 ///
1072 /// \returns true if *this != Val
1073 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1074
1075 /// Inequality comparison
1076 ///
1077 /// Compares this APInt with RHS for the validity of the inequality
1078 /// relationship.
1079 ///
1080 /// \returns true if *this != Val
1081 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1082
1083 /// Unsigned less than comparison
1084 ///
1085 /// Regards both *this and RHS as unsigned quantities and compares them for
1086 /// the validity of the less-than relationship.
1087 ///
1088 /// \returns true if *this < RHS when both are considered unsigned.
1089 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1090
1091 /// Unsigned less than comparison
1092 ///
1093 /// Regards both *this as an unsigned quantity and compares it with RHS for
1094 /// the validity of the less-than relationship.
1095 ///
1096 /// \returns true if *this < RHS when considered unsigned.
1097 bool ult(uint64_t RHS) const {
1098 // Only need to check active bits if not a single word.
1099 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1100 }
1101
1102 /// Signed less than comparison
1103 ///
1104 /// Regards both *this and RHS as signed quantities and compares them for
1105 /// validity of the less-than relationship.
1106 ///
1107 /// \returns true if *this < RHS when both are considered signed.
1108 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1109
1110 /// Signed less than comparison
1111 ///
1112 /// Regards both *this as a signed quantity and compares it with RHS for
1113 /// the validity of the less-than relationship.
1114 ///
1115 /// \returns true if *this < RHS when considered signed.
1116 bool slt(int64_t RHS) const {
1117 return (!isSingleWord() && getSignificantBits() > 64)
1118 ? isNegative()
1119 : getSExtValue() < RHS;
1120 }
1121
1122 /// Unsigned less or equal comparison
1123 ///
1124 /// Regards both *this and RHS as unsigned quantities and compares them for
1125 /// validity of the less-or-equal relationship.
1126 ///
1127 /// \returns true if *this <= RHS when both are considered unsigned.
1128 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1129
1130 /// Unsigned less or equal comparison
1131 ///
1132 /// Regards both *this as an unsigned quantity and compares it with RHS for
1133 /// the validity of the less-or-equal relationship.
1134 ///
1135 /// \returns true if *this <= RHS when considered unsigned.
1136 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1137
1138 /// Signed less or equal comparison
1139 ///
1140 /// Regards both *this and RHS as signed quantities and compares them for
1141 /// validity of the less-or-equal relationship.
1142 ///
1143 /// \returns true if *this <= RHS when both are considered signed.
1144 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1145
1146 /// Signed less or equal comparison
1147 ///
1148 /// Regards both *this as a signed quantity and compares it with RHS for the
1149 /// validity of the less-or-equal relationship.
1150 ///
1151 /// \returns true if *this <= RHS when considered signed.
1152 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1153
1154 /// Unsigned greater than comparison
1155 ///
1156 /// Regards both *this and RHS as unsigned quantities and compares them for
1157 /// the validity of the greater-than relationship.
1158 ///
1159 /// \returns true if *this > RHS when both are considered unsigned.
1160 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1161
1162 /// Unsigned greater than comparison
1163 ///
1164 /// Regards both *this as an unsigned quantity and compares it with RHS for
1165 /// the validity of the greater-than relationship.
1166 ///
1167 /// \returns true if *this > RHS when considered unsigned.
1168 bool ugt(uint64_t RHS) const {
1169 // Only need to check active bits if not a single word.
1170 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1171 }
1172
1173 /// Signed greater than comparison
1174 ///
1175 /// Regards both *this and RHS as signed quantities and compares them for the
1176 /// validity of the greater-than relationship.
1177 ///
1178 /// \returns true if *this > RHS when both are considered signed.
1179 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1180
1181 /// Signed greater than comparison
1182 ///
1183 /// Regards both *this as a signed quantity and compares it with RHS for
1184 /// the validity of the greater-than relationship.
1185 ///
1186 /// \returns true if *this > RHS when considered signed.
1187 bool sgt(int64_t RHS) const {
1188 return (!isSingleWord() && getSignificantBits() > 64)
1189 ? !isNegative()
1190 : getSExtValue() > RHS;
1191 }
1192
1193 /// Unsigned greater or equal comparison
1194 ///
1195 /// Regards both *this and RHS as unsigned quantities and compares them for
1196 /// validity of the greater-or-equal relationship.
1197 ///
1198 /// \returns true if *this >= RHS when both are considered unsigned.
1199 bool uge(const APInt &RHS) const { return !ult(RHS); }
1200
1201 /// Unsigned greater or equal comparison
1202 ///
1203 /// Regards both *this as an unsigned quantity and compares it with RHS for
1204 /// the validity of the greater-or-equal relationship.
1205 ///
1206 /// \returns true if *this >= RHS when considered unsigned.
1207 bool uge(uint64_t RHS) const { return !ult(RHS); }
1208
1209 /// Signed greater or equal comparison
1210 ///
1211 /// Regards both *this and RHS as signed quantities and compares them for
1212 /// validity of the greater-or-equal relationship.
1213 ///
1214 /// \returns true if *this >= RHS when both are considered signed.
1215 bool sge(const APInt &RHS) const { return !slt(RHS); }
1216
1217 /// Signed greater or equal comparison
1218 ///
1219 /// Regards both *this as a signed quantity and compares it with RHS for
1220 /// the validity of the greater-or-equal relationship.
1221 ///
1222 /// \returns true if *this >= RHS when considered signed.
1223 bool sge(int64_t RHS) const { return !slt(RHS); }
1224
1225 /// This operation tests if there are any pairs of corresponding bits
1226 /// between this APInt and RHS that are both set.
1227 bool intersects(const APInt &RHS) const {
1228 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1229 if (isSingleWord())
1230 return (U.VAL & RHS.U.VAL) != 0;
1231 return intersectsSlowCase(RHS);
1232 }
1233
1234 /// This operation checks that all bits set in this APInt are also set in RHS.
1235 bool isSubsetOf(const APInt &RHS) const {
1236 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1237 if (isSingleWord())
1238 return (U.VAL & ~RHS.U.VAL) == 0;
1239 return isSubsetOfSlowCase(RHS);
1240 }
1241
1242 /// @}
1243 /// \name Resizing Operators
1244 /// @{
1245
1246 /// Truncate to new width.
1247 ///
1248 /// Truncate the APInt to a specified width. It is an error to specify a width
1249 /// that is greater than the current width.
1250 APInt trunc(unsigned width) const;
1251
1252 /// Truncate to new width with unsigned saturation.
1253 ///
1254 /// If the APInt, treated as unsigned integer, can be losslessly truncated to
1255 /// the new bitwidth, then return truncated APInt. Else, return max value.
1256 APInt truncUSat(unsigned width) const;
1257
1258 /// Truncate to new width with signed saturation.
1259 ///
1260 /// If this APInt, treated as signed integer, can be losslessly truncated to
1261 /// the new bitwidth, then return truncated APInt. Else, return either
1262 /// signed min value if the APInt was negative, or signed max value.
1263 APInt truncSSat(unsigned width) const;
1264
1265 /// Sign extend to a new width.
1266 ///
1267 /// This operation sign extends the APInt to a new width. If the high order
1268 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1269 /// It is an error to specify a width that is less than the
1270 /// current width.
1271 APInt sext(unsigned width) const;
1272
1273 /// Zero extend to a new width.
1274 ///
1275 /// This operation zero extends the APInt to a new width. The high order bits
1276 /// are filled with 0 bits. It is an error to specify a width that is less
1277 /// than the current width.
1278 APInt zext(unsigned width) const;
1279
1280 /// Sign extend or truncate to width
1281 ///
1282 /// Make this APInt have the bit width given by \p width. The value is sign
1283 /// extended, truncated, or left alone to make it that width.
1284 APInt sextOrTrunc(unsigned width) const;
1285
1286 /// Zero extend or truncate to width
1287 ///
1288 /// Make this APInt have the bit width given by \p width. The value is zero
1289 /// extended, truncated, or left alone to make it that width.
1290 APInt zextOrTrunc(unsigned width) const;
1291
1292 /// @}
1293 /// \name Bit Manipulation Operators
1294 /// @{
1295
1296 /// Set every bit to 1.
1297 void setAllBits() {
1298 if (isSingleWord())
1299 U.VAL = WORDTYPE_MAX;
1300 else
1301 // Set all the bits in all the words.
1302 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1303 // Clear the unused ones
1305 }
1306
1307 /// Set the given bit to 1 whose position is given as "bitPosition".
1308 void setBit(unsigned BitPosition) {
1309 assert(BitPosition < BitWidth && "BitPosition out of range");
1310 WordType Mask = maskBit(BitPosition);
1311 if (isSingleWord())
1312 U.VAL |= Mask;
1313 else
1314 U.pVal[whichWord(BitPosition)] |= Mask;
1315 }
1316
1317 /// Set the sign bit to 1.
1318 void setSignBit() { setBit(BitWidth - 1); }
1319
1320 /// Set a given bit to a given value.
1321 void setBitVal(unsigned BitPosition, bool BitValue) {
1322 if (BitValue)
1323 setBit(BitPosition);
1324 else
1325 clearBit(BitPosition);
1326 }
1327
1328 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1329 /// This function handles "wrap" case when \p loBit >= \p hiBit, and calls
1330 /// setBits when \p loBit < \p hiBit.
1331 /// For \p loBit == \p hiBit wrap case, set every bit to 1.
1332 void setBitsWithWrap(unsigned loBit, unsigned hiBit) {
1333 assert(hiBit <= BitWidth && "hiBit out of range");
1334 assert(loBit <= BitWidth && "loBit out of range");
1335 if (loBit < hiBit) {
1336 setBits(loBit, hiBit);
1337 return;
1338 }
1339 setLowBits(hiBit);
1340 setHighBits(BitWidth - loBit);
1341 }
1342
1343 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1344 /// This function handles case when \p loBit <= \p hiBit.
1345 void setBits(unsigned loBit, unsigned hiBit) {
1346 assert(hiBit <= BitWidth && "hiBit out of range");
1347 assert(loBit <= BitWidth && "loBit out of range");
1348 assert(loBit <= hiBit && "loBit greater than hiBit");
1349 if (loBit == hiBit)
1350 return;
1351 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1352 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1353 mask <<= loBit;
1354 if (isSingleWord())
1355 U.VAL |= mask;
1356 else
1357 U.pVal[0] |= mask;
1358 } else {
1359 setBitsSlowCase(loBit, hiBit);
1360 }
1361 }
1362
1363 /// Set the top bits starting from loBit.
1364 void setBitsFrom(unsigned loBit) { return setBits(loBit, BitWidth); }
1365
1366 /// Set the bottom loBits bits.
1367 void setLowBits(unsigned loBits) { return setBits(0, loBits); }
1368
1369 /// Set the top hiBits bits.
1370 void setHighBits(unsigned hiBits) {
1371 return setBits(BitWidth - hiBits, BitWidth);
1372 }
1373
1374 /// Set every bit to 0.
1376 if (isSingleWord())
1377 U.VAL = 0;
1378 else
1379 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1380 }
1381
1382 /// Set a given bit to 0.
1383 ///
1384 /// Set the given bit to 0 whose position is given as "bitPosition".
1385 void clearBit(unsigned BitPosition) {
1386 assert(BitPosition < BitWidth && "BitPosition out of range");
1387 WordType Mask = ~maskBit(BitPosition);
1388 if (isSingleWord())
1389 U.VAL &= Mask;
1390 else
1391 U.pVal[whichWord(BitPosition)] &= Mask;
1392 }
1393
1394 /// Set bottom loBits bits to 0.
1395 void clearLowBits(unsigned loBits) {
1396 assert(loBits <= BitWidth && "More bits than bitwidth");
1397 APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits);
1398 *this &= Keep;
1399 }
1400
1401 /// Set top hiBits bits to 0.
1402 void clearHighBits(unsigned hiBits) {
1403 assert(hiBits <= BitWidth && "More bits than bitwidth");
1404 APInt Keep = getLowBitsSet(BitWidth, BitWidth - hiBits);
1405 *this &= Keep;
1406 }
1407
1408 /// Set the sign bit to 0.
1409 void clearSignBit() { clearBit(BitWidth - 1); }
1410
1411 /// Toggle every bit to its opposite value.
1413 if (isSingleWord()) {
1414 U.VAL ^= WORDTYPE_MAX;
1416 } else {
1417 flipAllBitsSlowCase();
1418 }
1419 }
1420
1421 /// Toggles a given bit to its opposite value.
1422 ///
1423 /// Toggle a given bit to its opposite value whose position is given
1424 /// as "bitPosition".
1425 void flipBit(unsigned bitPosition);
1426
1427 /// Negate this APInt in place.
1428 void negate() {
1429 flipAllBits();
1430 ++(*this);
1431 }
1432
1433 /// Insert the bits from a smaller APInt starting at bitPosition.
1434 void insertBits(const APInt &SubBits, unsigned bitPosition);
1435 void insertBits(uint64_t SubBits, unsigned bitPosition, unsigned numBits);
1436
1437 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1438 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1439 uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const;
1440
1441 /// @}
1442 /// \name Value Characterization Functions
1443 /// @{
1444
1445 /// Return the number of bits in the APInt.
1446 unsigned getBitWidth() const { return BitWidth; }
1447
1448 /// Get the number of words.
1449 ///
1450 /// Here one word's bitwidth equals to that of uint64_t.
1451 ///
1452 /// \returns the number of words to hold the integer value of this APInt.
1453 unsigned getNumWords() const { return getNumWords(BitWidth); }
1454
1455 /// Get the number of words.
1456 ///
1457 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1458 ///
1459 /// \returns the number of words to hold the integer value with a given bit
1460 /// width.
1461 static unsigned getNumWords(unsigned BitWidth) {
1462 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1463 }
1464
1465 /// Compute the number of active bits in the value
1466 ///
1467 /// This function returns the number of active bits which is defined as the
1468 /// bit width minus the number of leading zeros. This is used in several
1469 /// computations to see how "wide" the value is.
1470 unsigned getActiveBits() const { return BitWidth - countl_zero(); }
1471
1472 /// Compute the number of active words in the value of this APInt.
1473 ///
1474 /// This is used in conjunction with getActiveData to extract the raw value of
1475 /// the APInt.
1476 unsigned getActiveWords() const {
1477 unsigned numActiveBits = getActiveBits();
1478 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1479 }
1480
1481 /// Get the minimum bit size for this signed APInt
1482 ///
1483 /// Computes the minimum bit width for this APInt while considering it to be a
1484 /// signed (and probably negative) value. If the value is not negative, this
1485 /// function returns the same value as getActiveBits()+1. Otherwise, it
1486 /// returns the smallest bit width that will retain the negative value. For
1487 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1488 /// for -1, this function will always return 1.
1489 unsigned getSignificantBits() const {
1490 return BitWidth - getNumSignBits() + 1;
1491 }
1492
1493 /// Get zero extended value
1494 ///
1495 /// This method attempts to return the value of this APInt as a zero extended
1496 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1497 /// uint64_t. Otherwise an assertion will result.
1499 if (isSingleWord())
1500 return U.VAL;
1501 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1502 return U.pVal[0];
1503 }
1504
1505 /// Get zero extended value if possible
1506 ///
1507 /// This method attempts to return the value of this APInt as a zero extended
1508 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1509 /// uint64_t. Otherwise no value is returned.
1510 std::optional<uint64_t> tryZExtValue() const {
1511 return (getActiveBits() <= 64) ? std::optional<uint64_t>(getZExtValue())
1512 : std::nullopt;
1513 };
1514
1515 /// Get sign extended value
1516 ///
1517 /// This method attempts to return the value of this APInt as a sign extended
1518 /// int64_t. The bit width must be <= 64 or the value must fit within an
1519 /// int64_t. Otherwise an assertion will result.
1520 int64_t getSExtValue() const {
1521 if (isSingleWord())
1522 return SignExtend64(U.VAL, BitWidth);
1523 assert(getSignificantBits() <= 64 && "Too many bits for int64_t");
1524 return int64_t(U.pVal[0]);
1525 }
1526
1527 /// Get sign extended value if possible
1528 ///
1529 /// This method attempts to return the value of this APInt as a sign extended
1530 /// int64_t. The bitwidth must be <= 64 or the value must fit within an
1531 /// int64_t. Otherwise no value is returned.
1532 std::optional<int64_t> trySExtValue() const {
1533 return (getSignificantBits() <= 64) ? std::optional<int64_t>(getSExtValue())
1534 : std::nullopt;
1535 };
1536
1537 /// Get bits required for string value.
1538 ///
1539 /// This method determines how many bits are required to hold the APInt
1540 /// equivalent of the string given by \p str.
1541 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1542
1543 /// Get the bits that are sufficient to represent the string value. This may
1544 /// over estimate the amount of bits required, but it does not require
1545 /// parsing the value in the string.
1546 static unsigned getSufficientBitsNeeded(StringRef Str, uint8_t Radix);
1547
1548 /// The APInt version of std::countl_zero.
1549 ///
1550 /// It counts the number of zeros from the most significant bit to the first
1551 /// one bit.
1552 ///
1553 /// \returns BitWidth if the value is zero, otherwise returns the number of
1554 /// zeros from the most significant bit to the first one bits.
1555 unsigned countl_zero() const {
1556 if (isSingleWord()) {
1557 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1558 return llvm::countl_zero(U.VAL) - unusedBits;
1559 }
1560 return countLeadingZerosSlowCase();
1561 }
1562
1563 unsigned countLeadingZeros() const { return countl_zero(); }
1564
1565 /// Count the number of leading one bits.
1566 ///
1567 /// This function is an APInt version of std::countl_one. It counts the number
1568 /// of ones from the most significant bit to the first zero bit.
1569 ///
1570 /// \returns 0 if the high order bit is not set, otherwise returns the number
1571 /// of 1 bits from the most significant to the least
1572 unsigned countl_one() const {
1573 if (isSingleWord()) {
1574 if (LLVM_UNLIKELY(BitWidth == 0))
1575 return 0;
1576 return llvm::countl_one(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1577 }
1578 return countLeadingOnesSlowCase();
1579 }
1580
1581 unsigned countLeadingOnes() const { return countl_one(); }
1582
1583 /// Computes the number of leading bits of this APInt that are equal to its
1584 /// sign bit.
1585 unsigned getNumSignBits() const {
1586 return isNegative() ? countl_one() : countl_zero();
1587 }
1588
1589 /// Count the number of trailing zero bits.
1590 ///
1591 /// This function is an APInt version of std::countr_zero. It counts the
1592 /// number of zeros from the least significant bit to the first set bit.
1593 ///
1594 /// \returns BitWidth if the value is zero, otherwise returns the number of
1595 /// zeros from the least significant bit to the first one bit.
1596 unsigned countr_zero() const {
1597 if (isSingleWord()) {
1598 unsigned TrailingZeros = llvm::countr_zero(U.VAL);
1599 return (TrailingZeros > BitWidth ? BitWidth : TrailingZeros);
1600 }
1601 return countTrailingZerosSlowCase();
1602 }
1603
1604 unsigned countTrailingZeros() const { return countr_zero(); }
1605
1606 /// Count the number of trailing one bits.
1607 ///
1608 /// This function is an APInt version of std::countr_one. It counts the number
1609 /// of ones from the least significant bit to the first zero bit.
1610 ///
1611 /// \returns BitWidth if the value is all ones, otherwise returns the number
1612 /// of ones from the least significant bit to the first zero bit.
1613 unsigned countr_one() const {
1614 if (isSingleWord())
1615 return llvm::countr_one(U.VAL);
1616 return countTrailingOnesSlowCase();
1617 }
1618
1619 unsigned countTrailingOnes() const { return countr_one(); }
1620
1621 /// Count the number of bits set.
1622 ///
1623 /// This function is an APInt version of std::popcount. It counts the number
1624 /// of 1 bits in the APInt value.
1625 ///
1626 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1627 unsigned popcount() const {
1628 if (isSingleWord())
1629 return llvm::popcount(U.VAL);
1630 return countPopulationSlowCase();
1631 }
1632
1633 /// @}
1634 /// \name Conversion Functions
1635 /// @{
1636 void print(raw_ostream &OS, bool isSigned) const;
1637
1638 /// Converts an APInt to a string and append it to Str. Str is commonly a
1639 /// SmallString. If Radix > 10, UpperCase determine the case of letter
1640 /// digits.
1641 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1642 bool formatAsCLiteral = false, bool UpperCase = true,
1643 bool InsertSeparators = false) const;
1644
1645 /// Considers the APInt to be unsigned and converts it into a string in the
1646 /// radix given. The radix can be 2, 8, 10 16, or 36.
1647 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1648 toString(Str, Radix, false, false);
1649 }
1650
1651 /// Considers the APInt to be signed and converts it into a string in the
1652 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1653 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1654 toString(Str, Radix, true, false);
1655 }
1656
1657 /// \returns a byte-swapped representation of this APInt Value.
1658 APInt byteSwap() const;
1659
1660 /// \returns the value with the bit representation reversed of this APInt
1661 /// Value.
1662 APInt reverseBits() const;
1663
1664 /// Converts this APInt to a double value.
1665 double roundToDouble(bool isSigned) const;
1666
1667 /// Converts this unsigned APInt to a double value.
1668 double roundToDouble() const { return roundToDouble(false); }
1669
1670 /// Converts this signed APInt to a double value.
1671 double signedRoundToDouble() const { return roundToDouble(true); }
1672
1673 /// Converts APInt bits to a double
1674 ///
1675 /// The conversion does not do a translation from integer to double, it just
1676 /// re-interprets the bits as a double. Note that it is valid to do this on
1677 /// any bit width. Exactly 64 bits will be translated.
1678 double bitsToDouble() const { return llvm::bit_cast<double>(getWord(0)); }
1679
1680#ifdef HAS_IEE754_FLOAT128
1681 float128 bitsToQuad() const {
1682 __uint128_t ul = ((__uint128_t)U.pVal[1] << 64) + U.pVal[0];
1683 return llvm::bit_cast<float128>(ul);
1684 }
1685#endif
1686
1687 /// Converts APInt bits to a float
1688 ///
1689 /// The conversion does not do a translation from integer to float, it just
1690 /// re-interprets the bits as a float. Note that it is valid to do this on
1691 /// any bit width. Exactly 32 bits will be translated.
1692 float bitsToFloat() const {
1693 return llvm::bit_cast<float>(static_cast<uint32_t>(getWord(0)));
1694 }
1695
1696 /// Converts a double to APInt bits.
1697 ///
1698 /// The conversion does not do a translation from double to integer, it just
1699 /// re-interprets the bits of the double.
1700 static APInt doubleToBits(double V) {
1701 return APInt(sizeof(double) * CHAR_BIT, llvm::bit_cast<uint64_t>(V));
1702 }
1703
1704 /// Converts a float to APInt bits.
1705 ///
1706 /// The conversion does not do a translation from float to integer, it just
1707 /// re-interprets the bits of the float.
1708 static APInt floatToBits(float V) {
1709 return APInt(sizeof(float) * CHAR_BIT, llvm::bit_cast<uint32_t>(V));
1710 }
1711
1712 /// @}
1713 /// \name Mathematics Operations
1714 /// @{
1715
1716 /// \returns the floor log base 2 of this APInt.
1717 unsigned logBase2() const { return getActiveBits() - 1; }
1718
1719 /// \returns the ceil log base 2 of this APInt.
1720 unsigned ceilLogBase2() const {
1721 APInt temp(*this);
1722 --temp;
1723 return temp.getActiveBits();
1724 }
1725
1726 /// \returns the nearest log base 2 of this APInt. Ties round up.
1727 ///
1728 /// NOTE: When we have a BitWidth of 1, we define:
1729 ///
1730 /// log2(0) = UINT32_MAX
1731 /// log2(1) = 0
1732 ///
1733 /// to get around any mathematical concerns resulting from
1734 /// referencing 2 in a space where 2 does no exist.
1735 unsigned nearestLogBase2() const;
1736
1737 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1738 /// otherwise
1739 int32_t exactLogBase2() const {
1740 if (!isPowerOf2())
1741 return -1;
1742 return logBase2();
1743 }
1744
1745 /// Compute the square root.
1746 APInt sqrt() const;
1747
1748 /// Get the absolute value. If *this is < 0 then return -(*this), otherwise
1749 /// *this. Note that the "most negative" signed number (e.g. -128 for 8 bit
1750 /// wide APInt) is unchanged due to how negation works.
1751 APInt abs() const {
1752 if (isNegative())
1753 return -(*this);
1754 return *this;
1755 }
1756
1757 /// \returns the multiplicative inverse of an odd APInt modulo 2^BitWidth.
1758 APInt multiplicativeInverse() const;
1759
1760 /// @}
1761 /// \name Building-block Operations for APInt and APFloat
1762 /// @{
1763
1764 // These building block operations operate on a representation of arbitrary
1765 // precision, two's-complement, bignum integer values. They should be
1766 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1767 // generally a pointer to the base of an array of integer parts, representing
1768 // an unsigned bignum, and a count of how many parts there are.
1769
1770 /// Sets the least significant part of a bignum to the input value, and zeroes
1771 /// out higher parts.
1772 static void tcSet(WordType *, WordType, unsigned);
1773
1774 /// Assign one bignum to another.
1775 static void tcAssign(WordType *, const WordType *, unsigned);
1776
1777 /// Returns true if a bignum is zero, false otherwise.
1778 static bool tcIsZero(const WordType *, unsigned);
1779
1780 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1781 static int tcExtractBit(const WordType *, unsigned bit);
1782
1783 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1784 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1785 /// significant bit of DST. All high bits above srcBITS in DST are
1786 /// zero-filled.
1787 static void tcExtract(WordType *, unsigned dstCount, const WordType *,
1788 unsigned srcBits, unsigned srcLSB);
1789
1790 /// Set the given bit of a bignum. Zero-based.
1791 static void tcSetBit(WordType *, unsigned bit);
1792
1793 /// Clear the given bit of a bignum. Zero-based.
1794 static void tcClearBit(WordType *, unsigned bit);
1795
1796 /// Returns the bit number of the least or most significant set bit of a
1797 /// number. If the input number has no bits set -1U is returned.
1798 static unsigned tcLSB(const WordType *, unsigned n);
1799 static unsigned tcMSB(const WordType *parts, unsigned n);
1800
1801 /// Negate a bignum in-place.
1802 static void tcNegate(WordType *, unsigned);
1803
1804 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1805 static WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned);
1806 /// DST += RHS. Returns the carry flag.
1807 static WordType tcAddPart(WordType *, WordType, unsigned);
1808
1809 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1810 static WordType tcSubtract(WordType *, const WordType *, WordType carry,
1811 unsigned);
1812 /// DST -= RHS. Returns the carry flag.
1813 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1814
1815 /// DST += SRC * MULTIPLIER + PART if add is true
1816 /// DST = SRC * MULTIPLIER + PART if add is false
1817 ///
1818 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1819 /// start at the same point, i.e. DST == SRC.
1820 ///
1821 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1822 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1823 /// result, and if all of the omitted higher parts were zero return zero,
1824 /// otherwise overflow occurred and return one.
1825 static int tcMultiplyPart(WordType *dst, const WordType *src,
1826 WordType multiplier, WordType carry,
1827 unsigned srcParts, unsigned dstParts, bool add);
1828
1829 /// DST = LHS * RHS, where DST has the same width as the operands and is
1830 /// filled with the least significant parts of the result. Returns one if
1831 /// overflow occurred, otherwise zero. DST must be disjoint from both
1832 /// operands.
1833 static int tcMultiply(WordType *, const WordType *, const WordType *,
1834 unsigned);
1835
1836 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1837 /// operands. No overflow occurs. DST must be disjoint from both operands.
1838 static void tcFullMultiply(WordType *, const WordType *, const WordType *,
1839 unsigned, unsigned);
1840
1841 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1842 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1843 /// REMAINDER to the remainder, return zero. i.e.
1844 ///
1845 /// OLD_LHS = RHS * LHS + REMAINDER
1846 ///
1847 /// SCRATCH is a bignum of the same size as the operands and result for use by
1848 /// the routine; its contents need not be initialized and are destroyed. LHS,
1849 /// REMAINDER and SCRATCH must be distinct.
1850 static int tcDivide(WordType *lhs, const WordType *rhs, WordType *remainder,
1851 WordType *scratch, unsigned parts);
1852
1853 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1854 /// restrictions on Count.
1855 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1856
1857 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1858 /// restrictions on Count.
1859 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1860
1861 /// Comparison (unsigned) of two bignums.
1862 static int tcCompare(const WordType *, const WordType *, unsigned);
1863
1864 /// Increment a bignum in-place. Return the carry flag.
1865 static WordType tcIncrement(WordType *dst, unsigned parts) {
1866 return tcAddPart(dst, 1, parts);
1867 }
1868
1869 /// Decrement a bignum in-place. Return the borrow flag.
1870 static WordType tcDecrement(WordType *dst, unsigned parts) {
1871 return tcSubtractPart(dst, 1, parts);
1872 }
1873
1874 /// Used to insert APInt objects, or objects that contain APInt objects, into
1875 /// FoldingSets.
1876 void Profile(FoldingSetNodeID &id) const;
1877
1878 /// debug method
1879 void dump() const;
1880
1881 /// Returns whether this instance allocated memory.
1882 bool needsCleanup() const { return !isSingleWord(); }
1883
1884private:
1885 /// This union is used to store the integer value. When the
1886 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
1887 union {
1888 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1889 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1890 } U;
1891
1892 unsigned BitWidth = 1; ///< The number of bits in this APInt.
1893
1894 friend struct DenseMapInfo<APInt, void>;
1895 friend class APSInt;
1896
1897 // Make DynamicAPInt a friend so it can access BitWidth directly.
1898 friend DynamicAPInt;
1899
1900 /// This constructor is used only internally for speed of construction of
1901 /// temporaries. It is unsafe since it takes ownership of the pointer, so it
1902 /// is not public.
1903 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) { U.pVal = val; }
1904
1905 /// Determine which word a bit is in.
1906 ///
1907 /// \returns the word position for the specified bit position.
1908 static unsigned whichWord(unsigned bitPosition) {
1909 return bitPosition / APINT_BITS_PER_WORD;
1910 }
1911
1912 /// Determine which bit in a word the specified bit position is in.
1913 static unsigned whichBit(unsigned bitPosition) {
1914 return bitPosition % APINT_BITS_PER_WORD;
1915 }
1916
1917 /// Get a single bit mask.
1918 ///
1919 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
1920 /// This method generates and returns a uint64_t (word) mask for a single
1921 /// bit at a specific bit position. This is used to mask the bit in the
1922 /// corresponding word.
1923 static uint64_t maskBit(unsigned bitPosition) {
1924 return 1ULL << whichBit(bitPosition);
1925 }
1926
1927 /// Clear unused high order bits
1928 ///
1929 /// This method is used internally to clear the top "N" bits in the high order
1930 /// word that are not used by the APInt. This is needed after the most
1931 /// significant word is assigned a value to ensure that those bits are
1932 /// zero'd out.
1933 APInt &clearUnusedBits() {
1934 // Compute how many bits are used in the final word.
1935 unsigned WordBits = ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1;
1936
1937 // Mask out the high bits.
1938 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - WordBits);
1939 if (LLVM_UNLIKELY(BitWidth == 0))
1940 mask = 0;
1941
1942 if (isSingleWord())
1943 U.VAL &= mask;
1944 else
1945 U.pVal[getNumWords() - 1] &= mask;
1946 return *this;
1947 }
1948
1949 /// Get the word corresponding to a bit position
1950 /// \returns the corresponding word for the specified bit position.
1951 uint64_t getWord(unsigned bitPosition) const {
1952 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
1953 }
1954
1955 /// Utility method to change the bit width of this APInt to new bit width,
1956 /// allocating and/or deallocating as necessary. There is no guarantee on the
1957 /// value of any bits upon return. Caller should populate the bits after.
1958 void reallocate(unsigned NewBitWidth);
1959
1960 /// Convert a char array into an APInt
1961 ///
1962 /// \param radix 2, 8, 10, 16, or 36
1963 /// Converts a string into a number. The string must be non-empty
1964 /// and well-formed as a number of the given base. The bit-width
1965 /// must be sufficient to hold the result.
1966 ///
1967 /// This is used by the constructors that take string arguments.
1968 ///
1969 /// StringRef::getAsInteger is superficially similar but (1) does
1970 /// not assume that the string is well-formed and (2) grows the
1971 /// result to hold the input.
1972 void fromString(unsigned numBits, StringRef str, uint8_t radix);
1973
1974 /// An internal division function for dividing APInts.
1975 ///
1976 /// This is used by the toString method to divide by the radix. It simply
1977 /// provides a more convenient form of divide for internal use since KnuthDiv
1978 /// has specific constraints on its inputs. If those constraints are not met
1979 /// then it provides a simpler form of divide.
1980 static void divide(const WordType *LHS, unsigned lhsWords,
1981 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
1982 WordType *Remainder);
1983
1984 /// out-of-line slow case for inline constructor
1985 void initSlowCase(uint64_t val, bool isSigned);
1986
1987 /// shared code between two array constructors
1988 void initFromArray(ArrayRef<uint64_t> array);
1989
1990 /// out-of-line slow case for inline copy constructor
1991 void initSlowCase(const APInt &that);
1992
1993 /// out-of-line slow case for shl
1994 void shlSlowCase(unsigned ShiftAmt);
1995
1996 /// out-of-line slow case for lshr.
1997 void lshrSlowCase(unsigned ShiftAmt);
1998
1999 /// out-of-line slow case for ashr.
2000 void ashrSlowCase(unsigned ShiftAmt);
2001
2002 /// out-of-line slow case for operator=
2003 void assignSlowCase(const APInt &RHS);
2004
2005 /// out-of-line slow case for operator==
2006 bool equalSlowCase(const APInt &RHS) const LLVM_READONLY;
2007
2008 /// out-of-line slow case for countLeadingZeros
2009 unsigned countLeadingZerosSlowCase() const LLVM_READONLY;
2010
2011 /// out-of-line slow case for countLeadingOnes.
2012 unsigned countLeadingOnesSlowCase() const LLVM_READONLY;
2013
2014 /// out-of-line slow case for countTrailingZeros.
2015 unsigned countTrailingZerosSlowCase() const LLVM_READONLY;
2016
2017 /// out-of-line slow case for countTrailingOnes
2018 unsigned countTrailingOnesSlowCase() const LLVM_READONLY;
2019
2020 /// out-of-line slow case for countPopulation
2021 unsigned countPopulationSlowCase() const LLVM_READONLY;
2022
2023 /// out-of-line slow case for intersects.
2024 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY;
2025
2026 /// out-of-line slow case for isSubsetOf.
2027 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY;
2028
2029 /// out-of-line slow case for setBits.
2030 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
2031
2032 /// out-of-line slow case for flipAllBits.
2033 void flipAllBitsSlowCase();
2034
2035 /// out-of-line slow case for concat.
2036 APInt concatSlowCase(const APInt &NewLSB) const;
2037
2038 /// out-of-line slow case for operator&=.
2039 void andAssignSlowCase(const APInt &RHS);
2040
2041 /// out-of-line slow case for operator|=.
2042 void orAssignSlowCase(const APInt &RHS);
2043
2044 /// out-of-line slow case for operator^=.
2045 void xorAssignSlowCase(const APInt &RHS);
2046
2047 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
2048 /// to, or greater than RHS.
2049 int compare(const APInt &RHS) const LLVM_READONLY;
2050
2051 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
2052 /// to, or greater than RHS.
2053 int compareSigned(const APInt &RHS) const LLVM_READONLY;
2054
2055 /// @}
2056};
2057
2058inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
2059
2060inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
2061
2062/// Unary bitwise complement operator.
2063///
2064/// \returns an APInt that is the bitwise complement of \p v.
2066 v.flipAllBits();
2067 return v;
2068}
2069
2070inline APInt operator&(APInt a, const APInt &b) {
2071 a &= b;
2072 return a;
2073}
2074
2075inline APInt operator&(const APInt &a, APInt &&b) {
2076 b &= a;
2077 return std::move(b);
2078}
2079
2081 a &= RHS;
2082 return a;
2083}
2084
2086 b &= LHS;
2087 return b;
2088}
2089
2090inline APInt operator|(APInt a, const APInt &b) {
2091 a |= b;
2092 return a;
2093}
2094
2095inline APInt operator|(const APInt &a, APInt &&b) {
2096 b |= a;
2097 return std::move(b);
2098}
2099
2101 a |= RHS;
2102 return a;
2103}
2104
2106 b |= LHS;
2107 return b;
2108}
2109
2110inline APInt operator^(APInt a, const APInt &b) {
2111 a ^= b;
2112 return a;
2113}
2114
2115inline APInt operator^(const APInt &a, APInt &&b) {
2116 b ^= a;
2117 return std::move(b);
2118}
2119
2121 a ^= RHS;
2122 return a;
2123}
2124
2126 b ^= LHS;
2127 return b;
2128}
2129
2131 I.print(OS, true);
2132 return OS;
2133}
2134
2136 v.negate();
2137 return v;
2138}
2139
2140inline APInt operator+(APInt a, const APInt &b) {
2141 a += b;
2142 return a;
2143}
2144
2145inline APInt operator+(const APInt &a, APInt &&b) {
2146 b += a;
2147 return std::move(b);
2148}
2149
2151 a += RHS;
2152 return a;
2153}
2154
2156 b += LHS;
2157 return b;
2158}
2159
2160inline APInt operator-(APInt a, const APInt &b) {
2161 a -= b;
2162 return a;
2163}
2164
2165inline APInt operator-(const APInt &a, APInt &&b) {
2166 b.negate();
2167 b += a;
2168 return std::move(b);
2169}
2170
2172 a -= RHS;
2173 return a;
2174}
2175
2177 b.negate();
2178 b += LHS;
2179 return b;
2180}
2181
2183 a *= RHS;
2184 return a;
2185}
2186
2188 b *= LHS;
2189 return b;
2190}
2191
2192namespace APIntOps {
2193
2194/// Determine the smaller of two APInts considered to be signed.
2195inline const APInt &smin(const APInt &A, const APInt &B) {
2196 return A.slt(B) ? A : B;
2197}
2198
2199/// Determine the larger of two APInts considered to be signed.
2200inline const APInt &smax(const APInt &A, const APInt &B) {
2201 return A.sgt(B) ? A : B;
2202}
2203
2204/// Determine the smaller of two APInts considered to be unsigned.
2205inline const APInt &umin(const APInt &A, const APInt &B) {
2206 return A.ult(B) ? A : B;
2207}
2208
2209/// Determine the larger of two APInts considered to be unsigned.
2210inline const APInt &umax(const APInt &A, const APInt &B) {
2211 return A.ugt(B) ? A : B;
2212}
2213
2214/// Determine the absolute difference of two APInts considered to be signed.
2215inline const APInt abds(const APInt &A, const APInt &B) {
2216 return A.sge(B) ? (A - B) : (B - A);
2217}
2218
2219/// Determine the absolute difference of two APInts considered to be unsigned.
2220inline const APInt abdu(const APInt &A, const APInt &B) {
2221 return A.uge(B) ? (A - B) : (B - A);
2222}
2223
2224/// Compute the floor of the signed average of C1 and C2
2225APInt avgFloorS(const APInt &C1, const APInt &C2);
2226
2227/// Compute the floor of the unsigned average of C1 and C2
2228APInt avgFloorU(const APInt &C1, const APInt &C2);
2229
2230/// Compute the ceil of the signed average of C1 and C2
2231APInt avgCeilS(const APInt &C1, const APInt &C2);
2232
2233/// Compute the ceil of the unsigned average of C1 and C2
2234APInt avgCeilU(const APInt &C1, const APInt &C2);
2235
2236/// Performs (2*N)-bit multiplication on sign-extended operands.
2237/// Returns the high N bits of the multiplication result.
2238APInt mulhs(const APInt &C1, const APInt &C2);
2239
2240/// Performs (2*N)-bit multiplication on zero-extended operands.
2241/// Returns the high N bits of the multiplication result.
2242APInt mulhu(const APInt &C1, const APInt &C2);
2243
2244/// Compute GCD of two unsigned APInt values.
2245///
2246/// This function returns the greatest common divisor of the two APInt values
2247/// using Stein's algorithm.
2248///
2249/// \returns the greatest common divisor of A and B.
2250APInt GreatestCommonDivisor(APInt A, APInt B);
2251
2252/// Converts the given APInt to a double value.
2253///
2254/// Treats the APInt as an unsigned value for conversion purposes.
2255inline double RoundAPIntToDouble(const APInt &APIVal) {
2256 return APIVal.roundToDouble();
2257}
2258
2259/// Converts the given APInt to a double value.
2260///
2261/// Treats the APInt as a signed value for conversion purposes.
2262inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2263 return APIVal.signedRoundToDouble();
2264}
2265
2266/// Converts the given APInt to a float value.
2267inline float RoundAPIntToFloat(const APInt &APIVal) {
2268 return float(RoundAPIntToDouble(APIVal));
2269}
2270
2271/// Converts the given APInt to a float value.
2272///
2273/// Treats the APInt as a signed value for conversion purposes.
2274inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2275 return float(APIVal.signedRoundToDouble());
2276}
2277
2278/// Converts the given double value into a APInt.
2279///
2280/// This function convert a double value to an APInt value.
2281APInt RoundDoubleToAPInt(double Double, unsigned width);
2282
2283/// Converts a float value into a APInt.
2284///
2285/// Converts a float value into an APInt value.
2286inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2287 return RoundDoubleToAPInt(double(Float), width);
2288}
2289
2290/// Return A unsign-divided by B, rounded by the given rounding mode.
2291APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2292
2293/// Return A sign-divided by B, rounded by the given rounding mode.
2294APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2295
2296/// Let q(n) = An^2 + Bn + C, and BW = bit width of the value range
2297/// (e.g. 32 for i32).
2298/// This function finds the smallest number n, such that
2299/// (a) n >= 0 and q(n) = 0, or
2300/// (b) n >= 1 and q(n-1) and q(n), when evaluated in the set of all
2301/// integers, belong to two different intervals [Rk, Rk+R),
2302/// where R = 2^BW, and k is an integer.
2303/// The idea here is to find when q(n) "overflows" 2^BW, while at the
2304/// same time "allowing" subtraction. In unsigned modulo arithmetic a
2305/// subtraction (treated as addition of negated numbers) would always
2306/// count as an overflow, but here we want to allow values to decrease
2307/// and increase as long as they are within the same interval.
2308/// Specifically, adding of two negative numbers should not cause an
2309/// overflow (as long as the magnitude does not exceed the bit width).
2310/// On the other hand, given a positive number, adding a negative
2311/// number to it can give a negative result, which would cause the
2312/// value to go from [-2^BW, 0) to [0, 2^BW). In that sense, zero is
2313/// treated as a special case of an overflow.
2314///
2315/// This function returns std::nullopt if after finding k that minimizes the
2316/// positive solution to q(n) = kR, both solutions are contained between
2317/// two consecutive integers.
2318///
2319/// There are cases where q(n) > T, and q(n+1) < T (assuming evaluation
2320/// in arithmetic modulo 2^BW, and treating the values as signed) by the
2321/// virtue of *signed* overflow. This function will *not* find such an n,
2322/// however it may find a value of n satisfying the inequalities due to
2323/// an *unsigned* overflow (if the values are treated as unsigned).
2324/// To find a solution for a signed overflow, treat it as a problem of
2325/// finding an unsigned overflow with a range with of BW-1.
2326///
2327/// The returned value may have a different bit width from the input
2328/// coefficients.
2329std::optional<APInt> SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
2330 unsigned RangeWidth);
2331
2332/// Compare two values, and if they are different, return the position of the
2333/// most significant bit that is different in the values.
2334std::optional<unsigned> GetMostSignificantDifferentBit(const APInt &A,
2335 const APInt &B);
2336
2337/// Splat/Merge neighboring bits to widen/narrow the bitmask represented
2338/// by \param A to \param NewBitWidth bits.
2339///
2340/// MatchAnyBits: (Default)
2341/// e.g. ScaleBitMask(0b0101, 8) -> 0b00110011
2342/// e.g. ScaleBitMask(0b00011011, 4) -> 0b0111
2343///
2344/// MatchAllBits:
2345/// e.g. ScaleBitMask(0b0101, 8) -> 0b00110011
2346/// e.g. ScaleBitMask(0b00011011, 4) -> 0b0001
2347/// A.getBitwidth() or NewBitWidth must be a whole multiples of the other.
2348APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth,
2349 bool MatchAllBits = false);
2350} // namespace APIntOps
2351
2352// See friend declaration above. This additional declaration is required in
2353// order to compile LLVM with IBM xlC compiler.
2354hash_code hash_value(const APInt &Arg);
2355
2356/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
2357/// with the integer held in IntVal.
2358void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, unsigned StoreBytes);
2359
2360/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
2361/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
2362void LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, unsigned LoadBytes);
2363
2364/// Provide DenseMapInfo for APInt.
2365template <> struct DenseMapInfo<APInt, void> {
2366 static inline APInt getEmptyKey() {
2367 APInt V(nullptr, 0);
2368 V.U.VAL = ~0ULL;
2369 return V;
2370 }
2371
2372 static inline APInt getTombstoneKey() {
2373 APInt V(nullptr, 0);
2374 V.U.VAL = ~1ULL;
2375 return V;
2376 }
2377
2378 static unsigned getHashValue(const APInt &Key);
2379
2380 static bool isEqual(const APInt &LHS, const APInt &RHS) {
2381 return LHS.getBitWidth() == RHS.getBitWidth() && LHS == RHS;
2382 }
2383};
2384
2385} // namespace llvm
2386
2387#endif
aarch64 promote const
always inline
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
raw_ostream & operator<<(raw_ostream &OS, const binary_le_impl< value_type > &BLE)
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:241
#define LLVM_READONLY
Definition: Compiler.h:227
uint64_t Align
static bool isSigned(unsigned int Opcode)
static KnownBits extractBits(unsigned BitWidth, const KnownBits &SrcOpKnown, const KnownBits &OffsetKnown, const KnownBits &WidthKnown)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:512
static bool isAligned(const Value *Base, const APInt &Offset, Align Alignment, const DataLayout &DL)
Definition: Loads.cpp:29
static bool isSplat(Value *V)
Return true if V is a splat of a value (which is used when multiplying a matrix with a scalar).
#define I(x, y, z)
Definition: MD5.cpp:58
static const char * toString(MIToken::TokenKind TokenKind)
Definition: MIParser.cpp:616
Load MIR Sample Profile
const uint64_t BitWidth
static uint64_t clearUnusedBits(uint64_t Val, unsigned Size)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
std::optional< uint64_t > tryZExtValue() const
Get zero extended value if possible.
Definition: APInt.h:1510
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:212
bool slt(int64_t RHS) const
Signed less than comparison.
Definition: APInt.h:1116
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition: APInt.h:1385
APInt relativeLShr(int RelativeShift) const
relative logical shift right
Definition: APInt.h:858
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition: APInt.h:427
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:981
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:207
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition: APInt.h:401
APInt operator--(int)
Postfix decrement operator.
Definition: APInt.h:574
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1498
uint64_t * pVal
Used to store the >64 bits integer value.
Definition: APInt.h:1889
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition: APInt.h:1370
unsigned popcount() const
Count the number of bits set.
Definition: APInt.h:1627
~APInt()
Destructor.
Definition: APInt.h:168
void setBitsFrom(unsigned loBit)
Set the top bits starting from loBit.
Definition: APInt.h:1364
APInt operator<<(const APInt &Bits) const
Left logical shift operator.
Definition: APInt.h:800
bool isMask() const
Definition: APInt.h:479
APInt operator<<(unsigned Bits) const
Left logical shift operator.
Definition: APInt.h:795
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1470
bool sgt(int64_t RHS) const
Signed greater than comparison.
Definition: APInt.h:1187
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition: APInt.h:184
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition: APInt.h:1308
bool operator[](unsigned bitPosition) const
Array-indexing support.
Definition: APInt.h:1021
bool operator!=(const APInt &RHS) const
Inequality operator.
Definition: APInt.h:1065
void toStringUnsigned(SmallVectorImpl< char > &Str, unsigned Radix=10) const
Considers the APInt to be unsigned and converts it into a string in the radix given.
Definition: APInt.h:1647
APInt & operator&=(const APInt &RHS)
Bitwise AND assignment operator.
Definition: APInt.h:652
APInt abs() const
Get the absolute value.
Definition: APInt.h:1751
unsigned ceilLogBase2() const
Definition: APInt.h:1720
unsigned countLeadingOnes() const
Definition: APInt.h:1581
APInt relativeLShl(int RelativeShift) const
relative logical shift left
Definition: APInt.h:863
APInt & operator=(const APInt &RHS)
Copy assignment operator.
Definition: APInt.h:596
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition: APInt.h:1179
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition: APInt.h:349
APInt & operator^=(uint64_t RHS)
Bitwise XOR assignment operator.
Definition: APInt.h:725
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition: APInt.h:1160
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition: APInt.h:236
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:358
APInt & operator|=(uint64_t RHS)
Bitwise OR assignment operator.
Definition: APInt.h:696
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition: APInt.h:444
static APInt floatToBits(float V)
Converts a float to APInt bits.
Definition: APInt.h:1708
void setSignBit()
Set the sign bit to 1.
Definition: APInt.h:1318
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1446
uint64_t WordType
Definition: APInt.h:80
bool sle(uint64_t RHS) const
Signed less or equal comparison.
Definition: APInt.h:1152
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1089
bool uge(uint64_t RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1207
bool operator!() const
Logical negation operation on this APInt returns true if zero, like normal integers.
Definition: APInt.h:587
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition: APInt.h:187
APInt & operator=(uint64_t RHS)
Assignment operator.
Definition: APInt.h:636
APInt relativeAShr(int RelativeShift) const
relative arithmetic shift right
Definition: APInt.h:868
friend hash_code hash_value(const APInt &Arg)
Overload to compute a hash_code for an APInt value.
APInt(const APInt &that)
Copy Constructor.
Definition: APInt.h:154
APInt & operator|=(const APInt &RHS)
Bitwise OR assignment operator.
Definition: APInt.h:682
bool isSingleWord() const
Determine if this APInt just has one word to store value.
Definition: APInt.h:300
bool operator==(uint64_t Val) const
Equality operator.
Definition: APInt.h:1047
APInt operator++(int)
Postfix increment operator.
Definition: APInt.h:560
unsigned getNumWords() const
Get the number of words.
Definition: APInt.h:1453
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition: APInt.h:395
APInt ashr(const APInt &ShiftAmt) const
Arithmetic right-shift function.
Definition: APInt.h:886
APInt(unsigned numBits, uint64_t val, bool isSigned=false)
Create a new APInt of numBits width, initialized as val.
Definition: APInt.h:109
APInt()
Default constructor that creates an APInt with a 1-bit zero value.
Definition: APInt.h:151
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition: APInt.h:194
APInt(APInt &&that)
Move Constructor.
Definition: APInt.h:162
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:307
APInt concat(const APInt &NewLSB) const
Concatenate the bits from "NewLSB" onto the bottom of *this.
Definition: APInt.h:925
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition: APInt.h:1227
bool eq(const APInt &RHS) const
Equality comparison.
Definition: APInt.h:1057
int32_t exactLogBase2() const
Definition: APInt.h:1739
APInt & operator<<=(unsigned ShiftAmt)
Left-shift assignment function.
Definition: APInt.h:763
double roundToDouble() const
Converts this unsigned APInt to a double value.
Definition: APInt.h:1668
void clearAllBits()
Set every bit to 0.
Definition: APInt.h:1375
APInt relativeAShl(int RelativeShift) const
relative arithmetic shift left
Definition: APInt.h:873
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:812
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition: APInt.h:1144
void negate()
Negate this APInt in place.
Definition: APInt.h:1428
static WordType tcDecrement(WordType *dst, unsigned parts)
Decrement a bignum in-place. Return the borrow flag.
Definition: APInt.h:1870
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition: APInt.h:1596
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition: APInt.h:413
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition: APInt.h:1585
bool isOneBitSet(unsigned BitNo) const
Determine if this APInt Value only has the specified bit set.
Definition: APInt.h:344
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition: APInt.h:1555
bool operator==(const APInt &RHS) const
Equality operator.
Definition: APInt.h:1034
APInt shl(const APInt &ShiftAmt) const
Left-shift function.
Definition: APInt.h:910
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:197
bool isShiftedMask(unsigned &MaskIdx, unsigned &MaskLen) const
Return true if this APInt value contains a non-empty sequence of ones with the remainder zero.
Definition: APInt.h:500
void setBitsWithWrap(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition: APInt.h:1332
APInt lshr(const APInt &ShiftAmt) const
Logical right-shift function.
Definition: APInt.h:898
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition: APInt.h:339
unsigned countTrailingZeros() const
Definition: APInt.h:1604
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition: APInt.h:1489
unsigned countLeadingZeros() const
Definition: APInt.h:1563
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition: APInt.h:334
void flipAllBits()
Toggle every bit to its opposite value.
Definition: APInt.h:1412
static unsigned getNumWords(unsigned BitWidth)
Get the number of words.
Definition: APInt.h:1461
bool needsCleanup() const
Returns whether this instance allocated memory.
Definition: APInt.h:1882
unsigned countl_one() const
Count the number of leading one bits.
Definition: APInt.h:1572
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition: APInt.h:1395
unsigned logBase2() const
Definition: APInt.h:1717
static APInt getZeroWidth()
Return an APInt zero bits wide.
Definition: APInt.h:181
double signedRoundToDouble() const
Converts this signed APInt to a double value.
Definition: APInt.h:1671
bool isShiftedMask() const
Return true if this APInt value contains a non-empty sequence of ones with the remainder zero.
Definition: APInt.h:488
float bitsToFloat() const
Converts APInt bits to a float.
Definition: APInt.h:1692
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:453
bool ule(uint64_t RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1136
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition: APInt.h:805
void setAllBits()
Set every bit to 1.
Definition: APInt.h:1297
uint64_t VAL
Used to store the <= 64 bits integer value.
Definition: APInt.h:1888
bool ugt(uint64_t RHS) const
Unsigned greater than comparison.
Definition: APInt.h:1168
bool sge(int64_t RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1223
bool getBoolValue() const
Convert APInt to a boolean value.
Definition: APInt.h:449
static APInt doubleToBits(double V)
Converts a double to APInt bits.
Definition: APInt.h:1700
bool isMask(unsigned numBits) const
Definition: APInt.h:466
APInt & operator=(APInt &&that)
Move assignment operator.
Definition: APInt.h:610
static WordType tcIncrement(WordType *dst, unsigned parts)
Increment a bignum in-place. Return the carry flag.
Definition: APInt.h:1865
APInt & operator^=(const APInt &RHS)
Bitwise XOR assignment operator.
Definition: APInt.h:711
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition: APInt.h:383
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition: APInt.h:312
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1128
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition: APInt.h:1345
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:851
double bitsToDouble() const
Converts APInt bits to a double.
Definition: APInt.h:1678
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition: APInt.h:1235
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition: APInt.h:418
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
Definition: APInt.h:1476
bool ne(const APInt &RHS) const
Inequality comparison.
Definition: APInt.h:1081
static bool isSameValue(const APInt &I1, const APInt &I2)
Determine if two APInts have the same value, after zero-extending one of them (if needed!...
Definition: APInt.h:531
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:284
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition: APInt.h:319
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition: APInt.h:547
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1108
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition: APInt.h:274
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:178
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition: APInt.h:1367
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition: APInt.h:410
unsigned countTrailingOnes() const
Definition: APInt.h:1619
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1215
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition: APInt.h:1532
APInt & operator&=(uint64_t RHS)
Bitwise AND assignment operator.
Definition: APInt.h:666
double roundToDouble(bool isSigned) const
Converts this APInt to a double value.
Definition: APInt.cpp:849
bool isOne() const
Determine if this is a value of 1.
Definition: APInt.h:367
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition: APInt.h:264
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:217
void clearHighBits(unsigned hiBits)
Set top hiBits bits to 0.
Definition: APInt.h:1402
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1520
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:836
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:829
unsigned countr_one() const
Count the number of trailing one bits.
Definition: APInt.h:1613
static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit, unsigned hiBit)
Wrap version of getBitsSet.
Definition: APInt.h:248
bool isSignBitClear() const
Determine if sign bit of this APInt is clear.
Definition: APInt.h:326
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1199
void setBitVal(unsigned BitPosition, bool BitValue)
Set a given bit to a given value.
Definition: APInt.h:1321
void clearSignBit()
Set the sign bit to 0.
Definition: APInt.h:1409
bool isMaxValue() const
Determine if this is the largest unsigned value.
Definition: APInt.h:377
void toStringSigned(SmallVectorImpl< char > &Str, unsigned Radix=10) const
Considers the APInt to be signed and converts it into a string in the radix given.
Definition: APInt.h:1653
bool ult(uint64_t RHS) const
Unsigned less than comparison.
Definition: APInt.h:1097
bool operator!=(uint64_t Val) const
Inequality operator.
Definition: APInt.h:1073
An arbitrary precision integer that knows its signedness.
Definition: APSInt.h:23
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
This class provides support for dynamic arbitrary-precision arithmetic.
Definition: DynamicAPInt.h:46
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition: FoldingSet.h:327
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
An opaque object representing a hash code.
Definition: Hashing.h:75
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define UINT64_MAX
Definition: DataTypes.h:77
std::error_code fromString(StringRef String, Metadata &HSAMetadata)
Converts String to HSAMetadata.
float RoundAPIntToFloat(const APInt &APIVal)
Converts the given APInt to a float value.
Definition: APInt.h:2267
const APInt abdu(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be unsigned.
Definition: APInt.h:2220
const APInt abds(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be signed.
Definition: APInt.h:2215
double RoundAPIntToDouble(const APInt &APIVal)
Converts the given APInt to a double value.
Definition: APInt.h:2255
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition: APInt.h:2195
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition: APInt.h:2200
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition: APInt.h:2205
APInt RoundFloatToAPInt(float Float, unsigned width)
Converts a float value into a APInt.
Definition: APInt.h:2286
APInt RoundDoubleToAPInt(double Double, unsigned width)
Converts the given double value into a APInt.
Definition: APInt.cpp:810
double RoundSignedAPIntToDouble(const APInt &APIVal)
Converts the given APInt to a double value.
Definition: APInt.h:2262
float RoundSignedAPIntToFloat(const APInt &APIVal)
Converts the given APInt to a float value.
Definition: APInt.h:2274
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition: APInt.h:2210
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
constexpr T rotr(T V, int R)
Definition: bit.h:407
int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition: bit.h:385
APInt operator&(APInt a, const APInt &b)
Definition: APInt.h:2070
APInt operator*(APInt a, uint64_t RHS)
Definition: APInt.h:2182
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition: bit.h:307
bool operator!=(uint64_t V1, const APInt &V2)
Definition: APInt.h:2060
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator+=(DynamicAPInt &A, int64_t B)
Definition: DynamicAPInt.h:518
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator-=(DynamicAPInt &A, int64_t B)
Definition: DynamicAPInt.h:522
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:296
APInt operator~(APInt v)
Unary bitwise complement operator.
Definition: APInt.h:2065
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition: bit.h:215
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition: MathExtras.h:285
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator*=(DynamicAPInt &A, int64_t B)
Definition: DynamicAPInt.h:526
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition: bit.h:281
APInt operator^(APInt a, const APInt &b)
Definition: APInt.h:2110
constexpr bool isMask_64(uint64_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition: MathExtras.h:273
int countl_one(T Value)
Count the number of ones from the most significant bit to the first zero bit.
Definition: bit.h:294
ArrayRef(const T &OneElt) -> ArrayRef< T >
APInt operator-(APInt)
Definition: APInt.h:2135
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition: MathExtras.h:581
APInt operator+(APInt a, const APInt &b)
Definition: APInt.h:2140
APInt operator|(APInt a, const APInt &b)
Definition: APInt.h:2090
T reverseBits(T Val)
Reverse the bits in Val.
Definition: MathExtras.h:122
constexpr T rotl(T V, int R)
Definition: bit.h:394
@ Keep
No function return thunk.
auto mask(ShuffFunc S, unsigned Length, OptArgs... args) -> MaskT
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
static APInt getTombstoneKey()
Definition: APInt.h:2372
static bool isEqual(const APInt &LHS, const APInt &RHS)
Definition: APInt.h:2380
static unsigned getHashValue(const APInt &Key)
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:52