Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1767 lines
62 KiB

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