blob: 86fde19192b2ef9ee72fb1a128662d082f7619ba [file] [log] [blame]
Zhou Shengdac63782007-02-06 03:00:16 +00001//===-- APInt.cpp - Implement APInt class ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Zhou Shengdac63782007-02-06 03:00:16 +00007//
8//===----------------------------------------------------------------------===//
9//
Reid Spencera41e93b2007-02-25 19:32:03 +000010// This file implements a class to represent arbitrary precision integer
11// constant values and provide a variety of arithmetic operations on them.
Zhou Shengdac63782007-02-06 03:00:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
Ted Kremenek5c75d542008-01-19 04:23:33 +000016#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000017#include "llvm/ADT/Hashing.h"
Chris Lattner17f71652008-08-17 07:19:36 +000018#include "llvm/ADT/SmallString.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000019#include "llvm/ADT/StringRef.h"
Reid Spencera5e0d202007-02-24 03:58:46 +000020#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000021#include "llvm/Support/ErrorHandling.h"
Zhou Shengdac63782007-02-06 03:00:16 +000022#include "llvm/Support/MathExtras.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000023#include "llvm/Support/raw_ostream.h"
Chris Lattner17f71652008-08-17 07:19:36 +000024#include <cmath>
Zhou Shengdac63782007-02-06 03:00:16 +000025#include <cstdlib>
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include <cstring>
27#include <limits>
Zhou Shengdac63782007-02-06 03:00:16 +000028using namespace llvm;
29
Chandler Carruth64648262014-04-22 03:07:47 +000030#define DEBUG_TYPE "apint"
31
Reid Spencera41e93b2007-02-25 19:32:03 +000032/// A utility function for allocating memory, checking for allocation failures,
33/// and ensuring the contents are zeroed.
Chris Lattner77527f52009-01-21 18:09:24 +000034inline static uint64_t* getClearedMemory(unsigned numWords) {
Reid Spencera856b6e2007-02-18 18:38:44 +000035 uint64_t * result = new uint64_t[numWords];
36 assert(result && "APInt memory allocation fails!");
37 memset(result, 0, numWords * sizeof(uint64_t));
38 return result;
Zhou Sheng94b623a2007-02-06 06:04:53 +000039}
40
Eric Christopher820256b2009-08-21 04:06:45 +000041/// A utility function for allocating memory and checking for allocation
Reid Spencera41e93b2007-02-25 19:32:03 +000042/// failure. The content is not zeroed.
Chris Lattner77527f52009-01-21 18:09:24 +000043inline static uint64_t* getMemory(unsigned numWords) {
Reid Spencera856b6e2007-02-18 18:38:44 +000044 uint64_t * result = new uint64_t[numWords];
45 assert(result && "APInt memory allocation fails!");
46 return result;
47}
48
Erick Tryzelaardadb15712009-08-21 03:15:28 +000049/// A utility function that converts a character to a digit.
50inline static unsigned getDigit(char cdigit, uint8_t radix) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000051 unsigned r;
52
Douglas Gregor663c0682011-09-14 15:54:46 +000053 if (radix == 16 || radix == 36) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000054 r = cdigit - '0';
55 if (r <= 9)
56 return r;
57
58 r = cdigit - 'A';
Douglas Gregorc98ac852011-09-20 18:33:29 +000059 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000060 return r + 10;
61
62 r = cdigit - 'a';
Douglas Gregorc98ac852011-09-20 18:33:29 +000063 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000064 return r + 10;
Douglas Gregore4e20f42011-09-20 18:11:52 +000065
66 radix = 10;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000067 }
68
Erick Tryzelaar60964092009-08-21 06:48:37 +000069 r = cdigit - '0';
70 if (r < radix)
71 return r;
72
73 return -1U;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000074}
75
76
Chris Lattner77527f52009-01-21 18:09:24 +000077void APInt::initSlowCase(unsigned numBits, uint64_t val, bool isSigned) {
Chris Lattner1ac3e252008-08-20 17:02:31 +000078 pVal = getClearedMemory(getNumWords());
79 pVal[0] = val;
Eric Christopher820256b2009-08-21 04:06:45 +000080 if (isSigned && int64_t(val) < 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +000081 for (unsigned i = 1; i < getNumWords(); ++i)
82 pVal[i] = -1ULL;
Zhou Shengdac63782007-02-06 03:00:16 +000083}
84
Chris Lattnerd57b7602008-10-11 22:07:19 +000085void APInt::initSlowCase(const APInt& that) {
86 pVal = getMemory(getNumWords());
87 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
88}
89
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000090void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +000091 assert(BitWidth && "Bitwidth too small");
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000092 assert(bigVal.data() && "Null pointer detected!");
Zhou Shengdac63782007-02-06 03:00:16 +000093 if (isSingleWord())
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000094 VAL = bigVal[0];
Zhou Shengdac63782007-02-06 03:00:16 +000095 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000096 // Get memory, cleared to 0
97 pVal = getClearedMemory(getNumWords());
98 // Calculate the number of words to copy
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000099 unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000100 // Copy the words from bigVal to pVal
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000101 memcpy(pVal, bigVal.data(), words * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000102 }
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000103 // Make sure unused high bits are cleared
104 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000105}
106
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000107APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal)
108 : BitWidth(numBits), VAL(0) {
109 initFromArray(bigVal);
110}
111
112APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
113 : BitWidth(numBits), VAL(0) {
114 initFromArray(makeArrayRef(bigVal, numWords));
115}
116
Benjamin Kramer92d89982010-07-14 22:38:02 +0000117APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
Reid Spencer1ba83352007-02-21 03:55:44 +0000118 : BitWidth(numbits), VAL(0) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000119 assert(BitWidth && "Bitwidth too small");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000120 fromString(numbits, Str, radix);
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000121}
122
Chris Lattner1ac3e252008-08-20 17:02:31 +0000123APInt& APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer7c16cd22007-02-26 23:38:21 +0000124 // Don't do anything for X = X
125 if (this == &RHS)
126 return *this;
127
Reid Spencer7c16cd22007-02-26 23:38:21 +0000128 if (BitWidth == RHS.getBitWidth()) {
Chris Lattner1ac3e252008-08-20 17:02:31 +0000129 // assume same bit-width single-word case is already handled
130 assert(!isSingleWord());
131 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Reid Spencer7c16cd22007-02-26 23:38:21 +0000132 return *this;
133 }
134
Chris Lattner1ac3e252008-08-20 17:02:31 +0000135 if (isSingleWord()) {
136 // assume case where both are single words is already handled
137 assert(!RHS.isSingleWord());
138 VAL = 0;
139 pVal = getMemory(RHS.getNumWords());
140 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
Eric Christopher820256b2009-08-21 04:06:45 +0000141 } else if (getNumWords() == RHS.getNumWords())
Reid Spencer7c16cd22007-02-26 23:38:21 +0000142 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
143 else if (RHS.isSingleWord()) {
144 delete [] pVal;
Reid Spencera856b6e2007-02-18 18:38:44 +0000145 VAL = RHS.VAL;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000146 } else {
147 delete [] pVal;
148 pVal = getMemory(RHS.getNumWords());
149 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
150 }
151 BitWidth = RHS.BitWidth;
152 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000153}
154
Zhou Shengdac63782007-02-06 03:00:16 +0000155APInt& APInt::operator=(uint64_t RHS) {
Eric Christopher820256b2009-08-21 04:06:45 +0000156 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000157 VAL = RHS;
Zhou Shengdac63782007-02-06 03:00:16 +0000158 else {
159 pVal[0] = RHS;
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000160 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000161 }
Reid Spencer7c16cd22007-02-26 23:38:21 +0000162 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000163}
164
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000165/// This method 'profiles' an APInt for use with FoldingSet.
Ted Kremenek5c75d542008-01-19 04:23:33 +0000166void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremenek901540f2008-02-19 20:50:41 +0000167 ID.AddInteger(BitWidth);
Eric Christopher820256b2009-08-21 04:06:45 +0000168
Ted Kremenek5c75d542008-01-19 04:23:33 +0000169 if (isSingleWord()) {
170 ID.AddInteger(VAL);
171 return;
172 }
173
Chris Lattner77527f52009-01-21 18:09:24 +0000174 unsigned NumWords = getNumWords();
Ted Kremenek5c75d542008-01-19 04:23:33 +0000175 for (unsigned i = 0; i < NumWords; ++i)
176 ID.AddInteger(pVal[i]);
177}
178
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000179/// This function adds a single "digit" integer, y, to the multiple
Reid Spencera856b6e2007-02-18 18:38:44 +0000180/// "digit" integer array, x[]. x[] is modified to reflect the addition and
181/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer100502d2007-02-17 03:16:00 +0000182/// @returns the carry of the addition.
Chris Lattner77527f52009-01-21 18:09:24 +0000183static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
184 for (unsigned i = 0; i < len; ++i) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000185 dest[i] = y + x[i];
186 if (dest[i] < y)
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000187 y = 1; // Carry one to next digit.
Reid Spenceree0a6852007-02-18 06:39:42 +0000188 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000189 y = 0; // No need to carry so exit early
Reid Spenceree0a6852007-02-18 06:39:42 +0000190 break;
191 }
Reid Spencer100502d2007-02-17 03:16:00 +0000192 }
Reid Spenceree0a6852007-02-18 06:39:42 +0000193 return y;
Reid Spencer100502d2007-02-17 03:16:00 +0000194}
195
Zhou Shengdac63782007-02-06 03:00:16 +0000196/// @brief Prefix increment operator. Increments the APInt by one.
197APInt& APInt::operator++() {
Eric Christopher820256b2009-08-21 04:06:45 +0000198 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000199 ++VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000200 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000201 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000202 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000203}
204
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000205/// This function subtracts a single "digit" (64-bit word), y, from
Eric Christopher820256b2009-08-21 04:06:45 +0000206/// the multi-digit integer array, x[], propagating the borrowed 1 value until
Reid Spencera856b6e2007-02-18 18:38:44 +0000207/// no further borrowing is neeeded or it runs out of "digits" in x. The result
208/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
209/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencera41e93b2007-02-25 19:32:03 +0000210/// @returns the borrow out of the subtraction
Chris Lattner77527f52009-01-21 18:09:24 +0000211static bool sub_1(uint64_t x[], unsigned len, uint64_t y) {
212 for (unsigned i = 0; i < len; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000213 uint64_t X = x[i];
Reid Spenceree0a6852007-02-18 06:39:42 +0000214 x[i] -= y;
Eric Christopher820256b2009-08-21 04:06:45 +0000215 if (y > X)
Reid Spencera856b6e2007-02-18 18:38:44 +0000216 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer100502d2007-02-17 03:16:00 +0000217 else {
Reid Spencera856b6e2007-02-18 18:38:44 +0000218 y = 0; // No need to borrow
219 break; // Remaining digits are unchanged so exit early
Reid Spencer100502d2007-02-17 03:16:00 +0000220 }
221 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000222 return bool(y);
Reid Spencer100502d2007-02-17 03:16:00 +0000223}
224
Zhou Shengdac63782007-02-06 03:00:16 +0000225/// @brief Prefix decrement operator. Decrements the APInt by one.
226APInt& APInt::operator--() {
Eric Christopher820256b2009-08-21 04:06:45 +0000227 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000228 --VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000229 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000230 sub_1(pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000231 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000232}
233
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000234/// This function adds the integer array x to the integer array Y and
Eric Christopher820256b2009-08-21 04:06:45 +0000235/// places the result in dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000236/// @returns the carry out from the addition
237/// @brief General addition of 64-bit integer arrays
Eric Christopher820256b2009-08-21 04:06:45 +0000238static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000239 unsigned len) {
Reid Spencera5e0d202007-02-24 03:58:46 +0000240 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000241 for (unsigned i = 0; i< len; ++i) {
Reid Spencercb292e42007-02-23 01:57:13 +0000242 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000243 dest[i] = x[i] + y[i] + carry;
Reid Spencerdb2abec2007-02-21 05:44:56 +0000244 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer100502d2007-02-17 03:16:00 +0000245 }
246 return carry;
247}
248
Reid Spencera41e93b2007-02-25 19:32:03 +0000249/// Adds the RHS APint to this APInt.
250/// @returns this, after addition of RHS.
Eric Christopher820256b2009-08-21 04:06:45 +0000251/// @brief Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000252APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000253 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000254 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000255 VAL += RHS.VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000256 else {
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000257 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000258 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000259 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000260}
261
Eric Christopher820256b2009-08-21 04:06:45 +0000262/// Subtracts the integer array y from the integer array x
Reid Spencera41e93b2007-02-25 19:32:03 +0000263/// @returns returns the borrow out.
264/// @brief Generalized subtraction of 64-bit integer arrays.
Eric Christopher820256b2009-08-21 04:06:45 +0000265static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000266 unsigned len) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000267 bool borrow = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000268 for (unsigned i = 0; i < len; ++i) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000269 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
270 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
271 dest[i] = x_tmp - y[i];
Reid Spencer100502d2007-02-17 03:16:00 +0000272 }
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000273 return borrow;
Reid Spencer100502d2007-02-17 03:16:00 +0000274}
275
Reid Spencera41e93b2007-02-25 19:32:03 +0000276/// Subtracts the RHS APInt from this APInt
277/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000278/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000279APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000280 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000281 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000282 VAL -= RHS.VAL;
283 else
284 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000285 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000286}
287
Dan Gohman4a618822010-02-10 16:03:48 +0000288/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000289/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000290/// @returns the carry out of the multiplication.
291/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000292static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000293 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000294 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000295 uint64_t carry = 0;
296
297 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000298 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000299 // Split x into high and low words
300 uint64_t lx = x[i] & 0xffffffffULL;
301 uint64_t hx = x[i] >> 32;
302 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000303 // hasCarry == 0, no carry
304 // hasCarry == 1, has carry
305 // hasCarry == 2, no carry and the calculation result == 0.
306 uint8_t hasCarry = 0;
307 dest[i] = carry + lx * ly;
308 // Determine if the add above introduces carry.
309 hasCarry = (dest[i] < carry) ? 1 : 0;
310 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000311 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000312 // (2^32 - 1) + 2^32 = 2^64.
313 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
314
315 carry += (lx * hy) & 0xffffffffULL;
316 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000317 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000318 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
319 }
Reid Spencer100502d2007-02-17 03:16:00 +0000320 return carry;
321}
322
Eric Christopher820256b2009-08-21 04:06:45 +0000323/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000324/// the integer array dest. Note that dest's size must be >= xlen + ylen.
325/// @brief Generalized multiplicate of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000326static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
327 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000328 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000329 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000330 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000331 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000332 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000333 lx = x[j] & 0xffffffffULL;
334 hx = x[j] >> 32;
335 // hasCarry - A flag to indicate if has carry.
336 // hasCarry == 0, no carry
337 // hasCarry == 1, has carry
338 // hasCarry == 2, no carry and the calculation result == 0.
339 uint8_t hasCarry = 0;
340 uint64_t resul = carry + lx * ly;
341 hasCarry = (resul < carry) ? 1 : 0;
342 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
343 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
344
345 carry += (lx * hy) & 0xffffffffULL;
346 resul = (carry << 32) | (resul & 0xffffffffULL);
347 dest[i+j] += resul;
348 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000349 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000350 ((lx * hy) >> 32) + hx * hy;
351 }
352 dest[i+xlen] = carry;
353 }
354}
355
Zhou Shengdac63782007-02-06 03:00:16 +0000356APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000357 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000358 if (isSingleWord()) {
Reid Spencer4bb430c2007-02-20 20:42:10 +0000359 VAL *= RHS.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000360 clearUnusedBits();
361 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000362 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000363
364 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000365 unsigned lhsBits = getActiveBits();
366 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000367 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000368 // 0 * X ===> 0
369 return *this;
370
371 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000372 unsigned rhsBits = RHS.getActiveBits();
373 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000374 if (!rhsWords) {
375 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000376 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000377 return *this;
378 }
379
380 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000381 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000382 uint64_t *dest = getMemory(destWords);
383
384 // Perform the long multiply
385 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
386
387 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000388 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000389 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000390 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000391 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000392
393 // delete dest array and return
394 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000395 return *this;
396}
397
Zhou Shengdac63782007-02-06 03:00:16 +0000398APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000399 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000400 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000401 VAL &= RHS.VAL;
402 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000403 }
Chris Lattner77527f52009-01-21 18:09:24 +0000404 unsigned numWords = getNumWords();
405 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000406 pVal[i] &= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000407 return *this;
408}
409
Zhou Shengdac63782007-02-06 03:00:16 +0000410APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000411 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000412 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000413 VAL |= RHS.VAL;
414 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000415 }
Chris Lattner77527f52009-01-21 18:09:24 +0000416 unsigned numWords = getNumWords();
417 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000418 pVal[i] |= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000419 return *this;
420}
421
Zhou Shengdac63782007-02-06 03:00:16 +0000422APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000423 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000424 if (isSingleWord()) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000425 VAL ^= RHS.VAL;
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000426 this->clearUnusedBits();
Reid Spenceree0a6852007-02-18 06:39:42 +0000427 return *this;
Eric Christopher820256b2009-08-21 04:06:45 +0000428 }
Chris Lattner77527f52009-01-21 18:09:24 +0000429 unsigned numWords = getNumWords();
430 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000431 pVal[i] ^= RHS.pVal[i];
Reid Spencera41e93b2007-02-25 19:32:03 +0000432 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000433}
434
Chris Lattner1ac3e252008-08-20 17:02:31 +0000435APInt APInt::AndSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000436 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000437 uint64_t* val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000438 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000439 val[i] = pVal[i] & RHS.pVal[i];
440 return APInt(val, getBitWidth());
Zhou Shengdac63782007-02-06 03:00:16 +0000441}
442
Chris Lattner1ac3e252008-08-20 17:02:31 +0000443APInt APInt::OrSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000444 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000445 uint64_t *val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000446 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000447 val[i] = pVal[i] | RHS.pVal[i];
448 return APInt(val, getBitWidth());
Zhou Shengdac63782007-02-06 03:00:16 +0000449}
450
Chris Lattner1ac3e252008-08-20 17:02:31 +0000451APInt APInt::XorSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000452 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000453 uint64_t *val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000454 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000455 val[i] = pVal[i] ^ RHS.pVal[i];
456
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000457 APInt Result(val, getBitWidth());
Reid Spencera41e93b2007-02-25 19:32:03 +0000458 // 0^0==1 so clear the high bits in case they got set.
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000459 Result.clearUnusedBits();
460 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000461}
462
Zhou Shengdac63782007-02-06 03:00:16 +0000463APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000464 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000465 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000466 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000467 APInt Result(*this);
468 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000469 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000470}
471
Zhou Shengdac63782007-02-06 03:00:16 +0000472APInt APInt::operator+(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000473 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000474 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000475 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000476 APInt Result(BitWidth, 0);
477 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000478 Result.clearUnusedBits();
479 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000480}
481
Zhou Shengdac63782007-02-06 03:00:16 +0000482APInt APInt::operator-(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000483 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000484 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000485 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000486 APInt Result(BitWidth, 0);
487 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000488 Result.clearUnusedBits();
489 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000490}
491
Chris Lattner1ac3e252008-08-20 17:02:31 +0000492bool APInt::EqualSlowCase(const APInt& RHS) const {
Matthias Braun5117fcd2016-02-15 20:06:19 +0000493 return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000494}
495
Chris Lattner1ac3e252008-08-20 17:02:31 +0000496bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000497 unsigned n = getActiveBits();
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000498 if (n <= APINT_BITS_PER_WORD)
499 return pVal[0] == Val;
500 else
501 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000502}
503
Reid Spencer1d072122007-02-16 22:36:51 +0000504bool APInt::ult(const APInt& RHS) const {
505 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
506 if (isSingleWord())
507 return VAL < RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000508
509 // Get active bit length of both operands
Chris Lattner77527f52009-01-21 18:09:24 +0000510 unsigned n1 = getActiveBits();
511 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000512
513 // If magnitude of LHS is less than RHS, return true.
514 if (n1 < n2)
515 return true;
516
517 // If magnitude of RHS is greather than LHS, return false.
518 if (n2 < n1)
519 return false;
520
521 // If they bot fit in a word, just compare the low order word
522 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
523 return pVal[0] < RHS.pVal[0];
524
525 // Otherwise, compare all words
Chris Lattner77527f52009-01-21 18:09:24 +0000526 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000527 for (int i = topWord; i >= 0; --i) {
Eric Christopher820256b2009-08-21 04:06:45 +0000528 if (pVal[i] > RHS.pVal[i])
Reid Spencer1d072122007-02-16 22:36:51 +0000529 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000530 if (pVal[i] < RHS.pVal[i])
Reid Spencera41e93b2007-02-25 19:32:03 +0000531 return true;
Zhou Shengdac63782007-02-06 03:00:16 +0000532 }
533 return false;
534}
535
Reid Spencer1d072122007-02-16 22:36:51 +0000536bool APInt::slt(const APInt& RHS) const {
537 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000538 if (isSingleWord()) {
539 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
540 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
541 return lhsSext < rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000542 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000543
544 APInt lhs(*this);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000545 APInt rhs(RHS);
546 bool lhsNeg = isNegative();
547 bool rhsNeg = rhs.isNegative();
548 if (lhsNeg) {
549 // Sign bit is set so perform two's complement to make it positive
Jay Foad25a5e4c2010-12-01 08:53:58 +0000550 lhs.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +0000551 ++lhs;
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000552 }
Reid Spencer54abdcf2007-02-27 18:23:40 +0000553 if (rhsNeg) {
554 // Sign bit is set so perform two's complement to make it positive
Jay Foad25a5e4c2010-12-01 08:53:58 +0000555 rhs.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +0000556 ++rhs;
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000557 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000558
559 // Now we have unsigned values to compare so do the comparison if necessary
560 // based on the negativeness of the values.
Reid Spencer54abdcf2007-02-27 18:23:40 +0000561 if (lhsNeg)
562 if (rhsNeg)
563 return lhs.ugt(rhs);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000564 else
565 return true;
Reid Spencer54abdcf2007-02-27 18:23:40 +0000566 else if (rhsNeg)
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000567 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000568 else
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000569 return lhs.ult(rhs);
Zhou Shengdac63782007-02-06 03:00:16 +0000570}
571
Jay Foad25a5e4c2010-12-01 08:53:58 +0000572void APInt::setBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000573 if (isSingleWord())
Reid Spencera41e93b2007-02-25 19:32:03 +0000574 VAL |= maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000575 else
Reid Spencera41e93b2007-02-25 19:32:03 +0000576 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000577}
578
Zhou Shengdac63782007-02-06 03:00:16 +0000579/// Set the given bit to 0 whose position is given as "bitPosition".
580/// @brief Set a given bit to 0.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000581void APInt::clearBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000582 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000583 VAL &= ~maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000584 else
Reid Spencera856b6e2007-02-18 18:38:44 +0000585 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000586}
587
Zhou Shengdac63782007-02-06 03:00:16 +0000588/// @brief Toggle every bit to its opposite value.
Zhou Shengdac63782007-02-06 03:00:16 +0000589
Eric Christopher820256b2009-08-21 04:06:45 +0000590/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000591/// as "bitPosition".
592/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000593void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000594 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000595 if ((*this)[bitPosition]) clearBit(bitPosition);
596 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000597}
598
Benjamin Kramer92d89982010-07-14 22:38:02 +0000599unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000600 assert(!str.empty() && "Invalid string length");
Douglas Gregor663c0682011-09-14 15:54:46 +0000601 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
602 radix == 36) &&
603 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000604
605 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000606
Eric Christopher43a1dec2009-08-21 04:10:31 +0000607 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000608 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000609 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000610 if (*p == '-' || *p == '+') {
611 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000612 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000613 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000614 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000615
Reid Spencer9329e7b2007-04-13 19:19:07 +0000616 // For radixes of power-of-two values, the bits required is accurately and
617 // easily computed
618 if (radix == 2)
619 return slen + isNegative;
620 if (radix == 8)
621 return slen * 3 + isNegative;
622 if (radix == 16)
623 return slen * 4 + isNegative;
624
Douglas Gregor663c0682011-09-14 15:54:46 +0000625 // FIXME: base 36
626
Reid Spencer9329e7b2007-04-13 19:19:07 +0000627 // This is grossly inefficient but accurate. We could probably do something
628 // with a computation of roughly slen*64/20 and then adjust by the value of
629 // the first few digits. But, I'm not sure how accurate that could be.
630
631 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000632 // be too large. This avoids the assertion in the constructor. This
633 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
634 // bits in that case.
Douglas Gregor663c0682011-09-14 15:54:46 +0000635 unsigned sufficient
636 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
637 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000638
639 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000640 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000641
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000642 // Compute how many bits are required. If the log is infinite, assume we need
643 // just bit.
644 unsigned log = tmp.logBase2();
645 if (log == (unsigned)-1) {
646 return isNegative + 1;
647 } else {
648 return isNegative + log + 1;
649 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000650}
651
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000652hash_code llvm::hash_value(const APInt &Arg) {
653 if (Arg.isSingleWord())
654 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000655
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000656 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000657}
658
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000659bool APInt::isSplat(unsigned SplatSizeInBits) const {
660 assert(getBitWidth() % SplatSizeInBits == 0 &&
661 "SplatSizeInBits must divide width!");
662 // We can check that all parts of an integer are equal by making use of a
663 // little trick: rotate and check if it's still the same value.
664 return *this == rotl(SplatSizeInBits);
665}
666
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000667/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000668APInt APInt::getHiBits(unsigned numBits) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000669 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000670}
671
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000672/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000673APInt APInt::getLoBits(unsigned numBits) const {
Eric Christopher820256b2009-08-21 04:06:45 +0000674 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
Reid Spencer1d072122007-02-16 22:36:51 +0000675 BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000676}
677
Chris Lattner77527f52009-01-21 18:09:24 +0000678unsigned APInt::countLeadingZerosSlowCase() const {
John McCalldf951bd2010-02-03 03:42:44 +0000679 // Treat the most significand word differently because it might have
680 // meaningless bits set beyond the precision.
681 unsigned BitsInMSW = BitWidth % APINT_BITS_PER_WORD;
682 integerPart MSWMask;
683 if (BitsInMSW) MSWMask = (integerPart(1) << BitsInMSW) - 1;
684 else {
685 MSWMask = ~integerPart(0);
686 BitsInMSW = APINT_BITS_PER_WORD;
687 }
688
689 unsigned i = getNumWords();
690 integerPart MSW = pVal[i-1] & MSWMask;
691 if (MSW)
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000692 return llvm::countLeadingZeros(MSW) - (APINT_BITS_PER_WORD - BitsInMSW);
John McCalldf951bd2010-02-03 03:42:44 +0000693
694 unsigned Count = BitsInMSW;
695 for (--i; i > 0u; --i) {
Chris Lattner1ac3e252008-08-20 17:02:31 +0000696 if (pVal[i-1] == 0)
697 Count += APINT_BITS_PER_WORD;
698 else {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000699 Count += llvm::countLeadingZeros(pVal[i-1]);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000700 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000701 }
Zhou Shengdac63782007-02-06 03:00:16 +0000702 }
John McCalldf951bd2010-02-03 03:42:44 +0000703 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000704}
705
Chris Lattner77527f52009-01-21 18:09:24 +0000706unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000707 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000708 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000709
Chris Lattner77527f52009-01-21 18:09:24 +0000710 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000711 unsigned shift;
712 if (!highWordBits) {
713 highWordBits = APINT_BITS_PER_WORD;
714 shift = 0;
715 } else {
716 shift = APINT_BITS_PER_WORD - highWordBits;
717 }
Reid Spencer31acef52007-02-27 21:59:26 +0000718 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000719 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000720 if (Count == highWordBits) {
721 for (i--; i >= 0; --i) {
722 if (pVal[i] == -1ULL)
723 Count += APINT_BITS_PER_WORD;
724 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000725 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000726 break;
727 }
728 }
729 }
730 return Count;
731}
732
Chris Lattner77527f52009-01-21 18:09:24 +0000733unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000734 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000735 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000736 unsigned Count = 0;
737 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000738 for (; i < getNumWords() && pVal[i] == 0; ++i)
739 Count += APINT_BITS_PER_WORD;
740 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000741 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000742 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000743}
744
Chris Lattner77527f52009-01-21 18:09:24 +0000745unsigned APInt::countTrailingOnesSlowCase() const {
746 unsigned Count = 0;
747 unsigned i = 0;
Dan Gohmanc354ebd2008-02-14 22:38:45 +0000748 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000749 Count += APINT_BITS_PER_WORD;
750 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000751 Count += llvm::countTrailingOnes(pVal[i]);
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000752 return std::min(Count, BitWidth);
753}
754
Chris Lattner77527f52009-01-21 18:09:24 +0000755unsigned APInt::countPopulationSlowCase() const {
756 unsigned Count = 0;
757 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000758 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000759 return Count;
760}
761
Richard Smith4f9a8082011-11-23 21:33:37 +0000762/// Perform a logical right-shift from Src to Dst, which must be equal or
763/// non-overlapping, of Words words, by Shift, which must be less than 64.
764static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
765 unsigned Shift) {
766 uint64_t Carry = 0;
767 for (int I = Words - 1; I >= 0; --I) {
768 uint64_t Tmp = Src[I];
769 Dst[I] = (Tmp >> Shift) | Carry;
770 Carry = Tmp << (64 - Shift);
771 }
772}
773
Reid Spencer1d072122007-02-16 22:36:51 +0000774APInt APInt::byteSwap() const {
775 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
776 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000777 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000778 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000779 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000780 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000781 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000782 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000783 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000784 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000785 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000786 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000787 if (BitWidth == 64)
788 return APInt(BitWidth, ByteSwap_64(VAL));
789
790 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
791 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
792 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
793 if (Result.BitWidth != BitWidth) {
794 lshrNear(Result.pVal, Result.pVal, getNumWords(),
795 Result.BitWidth - BitWidth);
796 Result.BitWidth = BitWidth;
797 }
798 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000799}
800
Eric Christopher820256b2009-08-21 04:06:45 +0000801APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
Zhou Shengfbf61ea2007-02-08 14:35:19 +0000802 const APInt& API2) {
Zhou Shengdac63782007-02-06 03:00:16 +0000803 APInt A = API1, B = API2;
804 while (!!B) {
805 APInt T = B;
Reid Spencer1d072122007-02-16 22:36:51 +0000806 B = APIntOps::urem(A, B);
Zhou Shengdac63782007-02-06 03:00:16 +0000807 A = T;
808 }
809 return A;
810}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000811
Chris Lattner77527f52009-01-21 18:09:24 +0000812APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000813 union {
814 double D;
815 uint64_t I;
816 } T;
817 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000818
819 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000820 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000821
822 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000823 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000824
825 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000826 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000827 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000828
829 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
830 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
831
832 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000833 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000834 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000835 APInt(width, mantissa >> (52 - exp));
836
837 // If the client didn't provide enough bits for us to shift the mantissa into
838 // then the result is undefined, just return 0
839 if (width <= exp - 52)
840 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000841
842 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000843 APInt Tmp(width, mantissa);
Chris Lattner77527f52009-01-21 18:09:24 +0000844 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd707d632007-02-12 20:02:55 +0000845 return isNeg ? -Tmp : Tmp;
846}
847
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000848/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000849/// The layout for double is as following (IEEE Standard 754):
850/// --------------------------------------
851/// | Sign Exponent Fraction Bias |
852/// |-------------------------------------- |
853/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000854/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000855double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000856
857 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000858 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000859 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
860 if (isSigned) {
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000861 int64_t sext = (int64_t(getWord(0)) << (64-BitWidth)) >> (64-BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000862 return double(sext);
863 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000864 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000865 }
866
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000867 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000868 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000869
870 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000871 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000872
873 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000874 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000875
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000876 // The exponent (without bias normalization) is just the number of bits
877 // we are using. Note that the sign bit is gone since we constructed the
878 // absolute value.
879 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000880
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000881 // Return infinity for exponent overflow
882 if (exp > 1023) {
883 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000884 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000885 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000886 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000887 }
888 exp += 1023; // Increment for 1023 bias
889
890 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
891 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000892 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000893 unsigned hiWord = whichWord(n-1);
894 if (hiWord == 0) {
895 mantissa = Tmp.pVal[0];
896 if (n > 52)
897 mantissa >>= n - 52; // shift down, we want the top 52 bits.
898 } else {
899 assert(hiWord > 0 && "huh?");
900 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
901 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
902 mantissa = hibits | lobits;
903 }
904
Zhou Shengd707d632007-02-12 20:02:55 +0000905 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000906 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000907 union {
908 double D;
909 uint64_t I;
910 } T;
911 T.I = sign | (exp << 52) | mantissa;
912 return T.D;
913}
914
Reid Spencer1d072122007-02-16 22:36:51 +0000915// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000916APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000917 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000918 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000919
920 if (width <= APINT_BITS_PER_WORD)
921 return APInt(width, getRawData()[0]);
922
923 APInt Result(getMemory(getNumWords(width)), width);
924
925 // Copy full words.
926 unsigned i;
927 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
928 Result.pVal[i] = pVal[i];
929
930 // Truncate and copy any partial word.
931 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
932 if (bits != 0)
933 Result.pVal[i] = pVal[i] << bits >> bits;
934
935 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000936}
937
938// Sign extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000939APInt APInt::sext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000940 assert(width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000941
942 if (width <= APINT_BITS_PER_WORD) {
943 uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
944 val = (int64_t)val >> (width - BitWidth);
945 return APInt(width, val >> (APINT_BITS_PER_WORD - width));
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000946 }
947
Jay Foad583abbc2010-12-07 08:25:19 +0000948 APInt Result(getMemory(getNumWords(width)), width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000949
Jay Foad583abbc2010-12-07 08:25:19 +0000950 // Copy full words.
951 unsigned i;
952 uint64_t word = 0;
953 for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
954 word = getRawData()[i];
955 Result.pVal[i] = word;
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000956 }
957
Jay Foad583abbc2010-12-07 08:25:19 +0000958 // Read and sign-extend any partial word.
959 unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
960 if (bits != 0)
961 word = (int64_t)getRawData()[i] << bits >> bits;
962 else
963 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
964
965 // Write remaining full words.
966 for (; i != width / APINT_BITS_PER_WORD; i++) {
967 Result.pVal[i] = word;
968 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000969 }
Jay Foad583abbc2010-12-07 08:25:19 +0000970
971 // Write any partial word.
972 bits = (0 - width) % APINT_BITS_PER_WORD;
973 if (bits != 0)
974 Result.pVal[i] = word << bits >> bits;
975
976 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000977}
978
979// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000980APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000981 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000982
983 if (width <= APINT_BITS_PER_WORD)
984 return APInt(width, VAL);
985
986 APInt Result(getMemory(getNumWords(width)), width);
987
988 // Copy words.
989 unsigned i;
990 for (i = 0; i != getNumWords(); i++)
991 Result.pVal[i] = getRawData()[i];
992
993 // Zero remaining words.
994 memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
995
996 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000997}
998
Jay Foad583abbc2010-12-07 08:25:19 +0000999APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001000 if (BitWidth < width)
1001 return zext(width);
1002 if (BitWidth > width)
1003 return trunc(width);
1004 return *this;
1005}
1006
Jay Foad583abbc2010-12-07 08:25:19 +00001007APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001008 if (BitWidth < width)
1009 return sext(width);
1010 if (BitWidth > width)
1011 return trunc(width);
1012 return *this;
1013}
1014
Rafael Espindolabb893fe2012-01-27 23:33:07 +00001015APInt APInt::zextOrSelf(unsigned width) const {
1016 if (BitWidth < width)
1017 return zext(width);
1018 return *this;
1019}
1020
1021APInt APInt::sextOrSelf(unsigned width) const {
1022 if (BitWidth < width)
1023 return sext(width);
1024 return *this;
1025}
1026
Zhou Shenge93db8f2007-02-09 07:48:24 +00001027/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001028/// @brief Arithmetic right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001029APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001030 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001031}
1032
1033/// Arithmetic right-shift this APInt by shiftAmt.
1034/// @brief Arithmetic right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001035APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001036 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer1825dd02007-03-02 22:39:11 +00001037 // Handle a degenerate case
1038 if (shiftAmt == 0)
1039 return *this;
1040
1041 // Handle single word shifts with built-in ashr
Reid Spencer522ca7c2007-02-25 01:56:07 +00001042 if (isSingleWord()) {
1043 if (shiftAmt == BitWidth)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001044 return APInt(BitWidth, 0); // undefined
1045 else {
Chris Lattner77527f52009-01-21 18:09:24 +00001046 unsigned SignBit = APINT_BITS_PER_WORD - BitWidth;
Eric Christopher820256b2009-08-21 04:06:45 +00001047 return APInt(BitWidth,
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001048 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1049 }
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001050 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001051
Reid Spencer1825dd02007-03-02 22:39:11 +00001052 // If all the bits were shifted out, the result is, technically, undefined.
1053 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1054 // issues in the algorithm below.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001055 if (shiftAmt == BitWidth) {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001056 if (isNegative())
Zhou Sheng1247c072008-06-05 13:27:38 +00001057 return APInt(BitWidth, -1ULL, true);
Reid Spencera41e93b2007-02-25 19:32:03 +00001058 else
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001059 return APInt(BitWidth, 0);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001060 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001061
1062 // Create some space for the result.
1063 uint64_t * val = new uint64_t[getNumWords()];
1064
Reid Spencer1825dd02007-03-02 22:39:11 +00001065 // Compute some values needed by the following shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001066 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1067 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1068 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1069 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer1825dd02007-03-02 22:39:11 +00001070 if (bitsInWord == 0)
1071 bitsInWord = APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001072
1073 // If we are shifting whole words, just move whole words
1074 if (wordShift == 0) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001075 // Move the words containing significant bits
Chris Lattner77527f52009-01-21 18:09:24 +00001076 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001077 val[i] = pVal[i+offset]; // move whole word
1078
1079 // Adjust the top significant word for sign bit fill, if negative
1080 if (isNegative())
1081 if (bitsInWord < APINT_BITS_PER_WORD)
1082 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1083 } else {
Eric Christopher820256b2009-08-21 04:06:45 +00001084 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001085 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001086 // This combines the shifted corresponding word with the low bits from
1087 // the next word (shifted into this word's high bits).
Eric Christopher820256b2009-08-21 04:06:45 +00001088 val[i] = (pVal[i+offset] >> wordShift) |
Reid Spencer1825dd02007-03-02 22:39:11 +00001089 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1090 }
1091
1092 // Shift the break word. In this case there are no bits from the next word
1093 // to include in this word.
1094 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1095
Alp Tokercb402912014-01-24 17:20:08 +00001096 // Deal with sign extension in the break word, and possibly the word before
Reid Spencer1825dd02007-03-02 22:39:11 +00001097 // it.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001098 if (isNegative()) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001099 if (wordShift > bitsInWord) {
1100 if (breakWord > 0)
Eric Christopher820256b2009-08-21 04:06:45 +00001101 val[breakWord-1] |=
Reid Spencer1825dd02007-03-02 22:39:11 +00001102 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1103 val[breakWord] |= ~0ULL;
Eric Christopher820256b2009-08-21 04:06:45 +00001104 } else
Reid Spencer1825dd02007-03-02 22:39:11 +00001105 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnerdad2d092007-05-03 18:15:36 +00001106 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001107 }
1108
Reid Spencer1825dd02007-03-02 22:39:11 +00001109 // Remaining words are 0 or -1, just assign them.
1110 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner77527f52009-01-21 18:09:24 +00001111 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001112 val[i] = fillValue;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001113 APInt Result(val, BitWidth);
1114 Result.clearUnusedBits();
1115 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001116}
1117
Zhou Shenge93db8f2007-02-09 07:48:24 +00001118/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001119/// @brief Logical right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001120APInt APInt::lshr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001121 return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001122}
1123
1124/// Logical right-shift this APInt by shiftAmt.
1125/// @brief Logical right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001126APInt APInt::lshr(unsigned shiftAmt) const {
Chris Lattnerdad2d092007-05-03 18:15:36 +00001127 if (isSingleWord()) {
Ahmed Charles0dca5d82012-02-24 19:06:15 +00001128 if (shiftAmt >= BitWidth)
Reid Spencer522ca7c2007-02-25 01:56:07 +00001129 return APInt(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001130 else
Reid Spencer522ca7c2007-02-25 01:56:07 +00001131 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001132 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001133
Reid Spencer44eef162007-02-26 01:19:48 +00001134 // If all the bits were shifted out, the result is 0. This avoids issues
1135 // with shifting by the size of the integer type, which produces undefined
1136 // results. We define these "undefined results" to always be 0.
Chad Rosier3d464d82012-06-08 18:04:52 +00001137 if (shiftAmt >= BitWidth)
Reid Spencer44eef162007-02-26 01:19:48 +00001138 return APInt(BitWidth, 0);
1139
Reid Spencerfffdf102007-05-17 06:26:29 +00001140 // If none of the bits are shifted out, the result is *this. This avoids
Eric Christopher820256b2009-08-21 04:06:45 +00001141 // issues with shifting by the size of the integer type, which produces
Reid Spencerfffdf102007-05-17 06:26:29 +00001142 // undefined results in the code below. This is also an optimization.
1143 if (shiftAmt == 0)
1144 return *this;
1145
Reid Spencer44eef162007-02-26 01:19:48 +00001146 // Create some space for the result.
1147 uint64_t * val = new uint64_t[getNumWords()];
1148
1149 // If we are shifting less than a word, compute the shift with a simple carry
1150 if (shiftAmt < APINT_BITS_PER_WORD) {
Richard Smith4f9a8082011-11-23 21:33:37 +00001151 lshrNear(val, pVal, getNumWords(), shiftAmt);
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001152 APInt Result(val, BitWidth);
1153 Result.clearUnusedBits();
1154 return Result;
Reid Spencera41e93b2007-02-25 19:32:03 +00001155 }
1156
Reid Spencer44eef162007-02-26 01:19:48 +00001157 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001158 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1159 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencer44eef162007-02-26 01:19:48 +00001160
1161 // If we are shifting whole words, just move whole words
1162 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001163 for (unsigned i = 0; i < getNumWords() - offset; ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001164 val[i] = pVal[i+offset];
Chris Lattner77527f52009-01-21 18:09:24 +00001165 for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
Reid Spencer44eef162007-02-26 01:19:48 +00001166 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001167 APInt Result(val, BitWidth);
1168 Result.clearUnusedBits();
1169 return Result;
Reid Spencer44eef162007-02-26 01:19:48 +00001170 }
1171
Eric Christopher820256b2009-08-21 04:06:45 +00001172 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001173 unsigned breakWord = getNumWords() - offset -1;
1174 for (unsigned i = 0; i < breakWord; ++i)
Reid Spencerd99feaf2007-03-01 05:39:56 +00001175 val[i] = (pVal[i+offset] >> wordShift) |
1176 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencer44eef162007-02-26 01:19:48 +00001177 // Shift the break word.
1178 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1179
1180 // Remaining words are 0
Chris Lattner77527f52009-01-21 18:09:24 +00001181 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001182 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001183 APInt Result(val, BitWidth);
1184 Result.clearUnusedBits();
1185 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001186}
1187
Zhou Shenge93db8f2007-02-09 07:48:24 +00001188/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001189/// @brief Left-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001190APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky030c4502009-01-19 17:42:33 +00001191 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner77527f52009-01-21 18:09:24 +00001192 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001193}
1194
Chris Lattner77527f52009-01-21 18:09:24 +00001195APInt APInt::shlSlowCase(unsigned shiftAmt) const {
Reid Spencera5c84d92007-02-25 00:56:44 +00001196 // If all the bits were shifted out, the result is 0. This avoids issues
1197 // with shifting by the size of the integer type, which produces undefined
1198 // results. We define these "undefined results" to always be 0.
1199 if (shiftAmt == BitWidth)
1200 return APInt(BitWidth, 0);
1201
Reid Spencer81ee0202007-05-12 18:01:57 +00001202 // If none of the bits are shifted out, the result is *this. This avoids a
1203 // lshr by the words size in the loop below which can produce incorrect
1204 // results. It also avoids the expensive computation below for a common case.
1205 if (shiftAmt == 0)
1206 return *this;
1207
Reid Spencera5c84d92007-02-25 00:56:44 +00001208 // Create some space for the result.
1209 uint64_t * val = new uint64_t[getNumWords()];
1210
1211 // If we are shifting less than a word, do it the easy way
1212 if (shiftAmt < APINT_BITS_PER_WORD) {
1213 uint64_t carry = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001214 for (unsigned i = 0; i < getNumWords(); i++) {
Reid Spencera5c84d92007-02-25 00:56:44 +00001215 val[i] = pVal[i] << shiftAmt | carry;
1216 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1217 }
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001218 APInt Result(val, BitWidth);
1219 Result.clearUnusedBits();
1220 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001221 }
1222
Reid Spencera5c84d92007-02-25 00:56:44 +00001223 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001224 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1225 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencera5c84d92007-02-25 00:56:44 +00001226
1227 // If we are shifting whole words, just move whole words
1228 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001229 for (unsigned i = 0; i < offset; i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001230 val[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001231 for (unsigned i = offset; i < getNumWords(); i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001232 val[i] = pVal[i-offset];
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001233 APInt Result(val, BitWidth);
1234 Result.clearUnusedBits();
1235 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001236 }
Reid Spencera5c84d92007-02-25 00:56:44 +00001237
1238 // Copy whole words from this to Result.
Chris Lattner77527f52009-01-21 18:09:24 +00001239 unsigned i = getNumWords() - 1;
Reid Spencera5c84d92007-02-25 00:56:44 +00001240 for (; i > offset; --i)
1241 val[i] = pVal[i-offset] << wordShift |
1242 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencerab0e08a2007-02-25 01:08:58 +00001243 val[offset] = pVal[0] << wordShift;
Reid Spencera5c84d92007-02-25 00:56:44 +00001244 for (i = 0; i < offset; ++i)
1245 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001246 APInt Result(val, BitWidth);
1247 Result.clearUnusedBits();
1248 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001249}
1250
Dan Gohman105c1d42008-02-29 01:40:47 +00001251APInt APInt::rotl(const APInt &rotateAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001252 return rotl((unsigned)rotateAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001253}
1254
Chris Lattner77527f52009-01-21 18:09:24 +00001255APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001256 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001257 if (rotateAmt == 0)
1258 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001259 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001260}
1261
Dan Gohman105c1d42008-02-29 01:40:47 +00001262APInt APInt::rotr(const APInt &rotateAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001263 return rotr((unsigned)rotateAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001264}
1265
Chris Lattner77527f52009-01-21 18:09:24 +00001266APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001267 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001268 if (rotateAmt == 0)
1269 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001270 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001271}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001272
1273// Square Root - this method computes and returns the square root of "this".
1274// Three mechanisms are used for computation. For small values (<= 5 bits),
1275// a table lookup is done. This gets some performance for common cases. For
1276// values using less than 52 bits, the value is converted to double and then
1277// the libc sqrt function is called. The result is rounded and then converted
1278// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001279// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001280APInt APInt::sqrt() const {
1281
1282 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001283 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001284
1285 // Use a fast table for some small values. This also gets rid of some
1286 // rounding errors in libc sqrt for small values.
1287 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001288 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001289 /* 0 */ 0,
1290 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001291 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001292 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1293 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1294 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1295 /* 31 */ 6
1296 };
1297 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001298 }
1299
1300 // If the magnitude of the value fits in less than 52 bits (the precision of
1301 // an IEEE double precision floating point value), then we can use the
1302 // libc sqrt function which will probably use a hardware sqrt computation.
1303 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001304 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001305 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001306 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001307 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001308
1309 // Okay, all the short cuts are exhausted. We must compute it. The following
1310 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001311 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001312 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001313 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001314 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001315 APInt testy(BitWidth, 16);
1316 APInt x_old(BitWidth, 1);
1317 APInt x_new(BitWidth, 0);
1318 APInt two(BitWidth, 2);
1319
1320 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001321 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001322 if (i >= nbits || this->ule(testy)) {
1323 x_old = x_old.shl(i / 2);
1324 break;
1325 }
1326
Eric Christopher820256b2009-08-21 04:06:45 +00001327 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001328 for (;;) {
1329 x_new = (this->udiv(x_old) + x_old).udiv(two);
1330 if (x_old.ule(x_new))
1331 break;
1332 x_old = x_new;
1333 }
1334
1335 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001336 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001337 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001338 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001339 // floating point representation after 192 bits. There are no discrepancies
1340 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001341 APInt square(x_old * x_old);
1342 APInt nextSquare((x_old + 1) * (x_old +1));
1343 if (this->ult(square))
1344 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001345 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1346 APInt midpoint((nextSquare - square).udiv(two));
1347 APInt offset(*this - square);
1348 if (offset.ult(midpoint))
1349 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001350 return x_old + 1;
1351}
1352
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001353/// Computes the multiplicative inverse of this APInt for a given modulo. The
1354/// iterative extended Euclidean algorithm is used to solve for this value,
1355/// however we simplify it to speed up calculating only the inverse, and take
1356/// advantage of div+rem calculations. We also use some tricks to avoid copying
1357/// (potentially large) APInts around.
1358APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1359 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1360
1361 // Using the properties listed at the following web page (accessed 06/21/08):
1362 // http://www.numbertheory.org/php/euclid.html
1363 // (especially the properties numbered 3, 4 and 9) it can be proved that
1364 // BitWidth bits suffice for all the computations in the algorithm implemented
1365 // below. More precisely, this number of bits suffice if the multiplicative
1366 // inverse exists, but may not suffice for the general extended Euclidean
1367 // algorithm.
1368
1369 APInt r[2] = { modulo, *this };
1370 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1371 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001372
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001373 unsigned i;
1374 for (i = 0; r[i^1] != 0; i ^= 1) {
1375 // An overview of the math without the confusing bit-flipping:
1376 // q = r[i-2] / r[i-1]
1377 // r[i] = r[i-2] % r[i-1]
1378 // t[i] = t[i-2] - t[i-1] * q
1379 udivrem(r[i], r[i^1], q, r[i]);
1380 t[i] -= t[i^1] * q;
1381 }
1382
1383 // If this APInt and the modulo are not coprime, there is no multiplicative
1384 // inverse, so return 0. We check this by looking at the next-to-last
1385 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1386 // algorithm.
1387 if (r[i] != 1)
1388 return APInt(BitWidth, 0);
1389
1390 // The next-to-last t is the multiplicative inverse. However, we are
1391 // interested in a positive inverse. Calcuate a positive one from a negative
1392 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001393 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001394 return t[i].isNegative() ? t[i] + modulo : t[i];
1395}
1396
Jay Foadfe0c6482009-04-30 10:15:35 +00001397/// Calculate the magic numbers required to implement a signed integer division
1398/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1399/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1400/// Warren, Jr., chapter 10.
1401APInt::ms APInt::magic() const {
1402 const APInt& d = *this;
1403 unsigned p;
1404 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001405 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001406 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001407
Jay Foadfe0c6482009-04-30 10:15:35 +00001408 ad = d.abs();
1409 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1410 anc = t - 1 - t.urem(ad); // absolute value of nc
1411 p = d.getBitWidth() - 1; // initialize p
1412 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1413 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1414 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1415 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1416 do {
1417 p = p + 1;
1418 q1 = q1<<1; // update q1 = 2p/abs(nc)
1419 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1420 if (r1.uge(anc)) { // must be unsigned comparison
1421 q1 = q1 + 1;
1422 r1 = r1 - anc;
1423 }
1424 q2 = q2<<1; // update q2 = 2p/abs(d)
1425 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1426 if (r2.uge(ad)) { // must be unsigned comparison
1427 q2 = q2 + 1;
1428 r2 = r2 - ad;
1429 }
1430 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001431 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001432
Jay Foadfe0c6482009-04-30 10:15:35 +00001433 mag.m = q2 + 1;
1434 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1435 mag.s = p - d.getBitWidth(); // resulting shift
1436 return mag;
1437}
1438
1439/// Calculate the magic numbers required to implement an unsigned integer
1440/// division by a constant as a sequence of multiplies, adds and shifts.
1441/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1442/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001443/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001444/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001445APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001446 const APInt& d = *this;
1447 unsigned p;
1448 APInt nc, delta, q1, r1, q2, r2;
1449 struct mu magu;
1450 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001451 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001452 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1453 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1454
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001455 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001456 p = d.getBitWidth() - 1; // initialize p
1457 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1458 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1459 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1460 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1461 do {
1462 p = p + 1;
1463 if (r1.uge(nc - r1)) {
1464 q1 = q1 + q1 + 1; // update q1
1465 r1 = r1 + r1 - nc; // update r1
1466 }
1467 else {
1468 q1 = q1+q1; // update q1
1469 r1 = r1+r1; // update r1
1470 }
1471 if ((r2 + 1).uge(d - r2)) {
1472 if (q2.uge(signedMax)) magu.a = 1;
1473 q2 = q2+q2 + 1; // update q2
1474 r2 = r2+r2 + 1 - d; // update r2
1475 }
1476 else {
1477 if (q2.uge(signedMin)) magu.a = 1;
1478 q2 = q2+q2; // update q2
1479 r2 = r2+r2 + 1; // update r2
1480 }
1481 delta = d - 1 - r2;
1482 } while (p < d.getBitWidth()*2 &&
1483 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1484 magu.m = q2 + 1; // resulting magic number
1485 magu.s = p - d.getBitWidth(); // resulting shift
1486 return magu;
1487}
1488
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001489/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1490/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1491/// variables here have the same names as in the algorithm. Comments explain
1492/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001493static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1494 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001495 assert(u && "Must provide dividend");
1496 assert(v && "Must provide divisor");
1497 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001498 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001499 assert(n>1 && "n must be > 1");
1500
Yaron Keren39fc5a62015-03-26 19:45:19 +00001501 // b denotes the base of the number system. In our case b is 2^32.
1502 LLVM_CONSTEXPR uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001503
David Greenef32fcb42010-01-05 01:28:52 +00001504 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1505 DEBUG(dbgs() << "KnuthDiv: original:");
1506 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1507 DEBUG(dbgs() << " by");
1508 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1509 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001510 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1511 // u and v by d. Note that we have taken Knuth's advice here to use a power
1512 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1513 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001514 // shift amount from the leading zeros. We are basically normalizing the u
1515 // and v so that its high bits are shifted to the top of v's range without
1516 // overflow. Note that this can require an extra word in u so that u must
1517 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001518 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001519 unsigned v_carry = 0;
1520 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001521 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001522 for (unsigned i = 0; i < m+n; ++i) {
1523 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001524 u[i] = (u[i] << shift) | u_carry;
1525 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001526 }
Chris Lattner77527f52009-01-21 18:09:24 +00001527 for (unsigned i = 0; i < n; ++i) {
1528 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001529 v[i] = (v[i] << shift) | v_carry;
1530 v_carry = v_tmp;
1531 }
1532 }
1533 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001534
David Greenef32fcb42010-01-05 01:28:52 +00001535 DEBUG(dbgs() << "KnuthDiv: normal:");
1536 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1537 DEBUG(dbgs() << " by");
1538 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1539 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001540
1541 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1542 int j = m;
1543 do {
David Greenef32fcb42010-01-05 01:28:52 +00001544 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001545 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001546 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1547 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1548 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1549 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1550 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001551 // value qp is one too large, and it eliminates all cases where qp is two
1552 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001553 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001554 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001555 uint64_t qp = dividend / v[n-1];
1556 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001557 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1558 qp--;
1559 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001560 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001561 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001562 }
David Greenef32fcb42010-01-05 01:28:52 +00001563 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001564
Reid Spencercb292e42007-02-23 01:57:13 +00001565 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1566 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1567 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001568 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001569 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1570 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1571 // true value plus b**(n+1), namely as the b's complement of
1572 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001573 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001574 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001575 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1576 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1577 u[j+i] = (unsigned)subres;
1578 borrow = (p >> 32) - (subres >> 32);
1579 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001580 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001581 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001582 bool isNeg = u[j+n] < borrow;
1583 u[j+n] -= (unsigned)borrow;
1584
David Greenef32fcb42010-01-05 01:28:52 +00001585 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1586 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1587 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001588
Eric Christopher820256b2009-08-21 04:06:45 +00001589 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001590 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001591 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001592 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001593 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001594 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001595 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001596 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001597 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1598 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001599 // since it cancels with the borrow that occurred in D4.
1600 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001601 for (unsigned i = 0; i < n; i++) {
1602 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001603 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001604 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001605 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001606 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001607 }
David Greenef32fcb42010-01-05 01:28:52 +00001608 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001609 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001610 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001611
Reid Spencercb292e42007-02-23 01:57:13 +00001612 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1613 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001614
David Greenef32fcb42010-01-05 01:28:52 +00001615 DEBUG(dbgs() << "KnuthDiv: quotient:");
1616 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1617 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001618
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001619 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1620 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1621 // compute the remainder (urem uses this).
1622 if (r) {
1623 // The value d is expressed by the "shift" value above since we avoided
1624 // multiplication by d by using a shift left. So, all we have to do is
1625 // shift right here. In order to mak
Reid Spencer468ad9112007-02-24 20:38:01 +00001626 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001627 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001628 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001629 for (int i = n-1; i >= 0; i--) {
1630 r[i] = (u[i] >> shift) | carry;
1631 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001632 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001633 }
1634 } else {
1635 for (int i = n-1; i >= 0; i--) {
1636 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001637 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001638 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001639 }
David Greenef32fcb42010-01-05 01:28:52 +00001640 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001641 }
David Greenef32fcb42010-01-05 01:28:52 +00001642 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001643}
1644
Chris Lattner77527f52009-01-21 18:09:24 +00001645void APInt::divide(const APInt LHS, unsigned lhsWords,
1646 const APInt &RHS, unsigned rhsWords,
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001647 APInt *Quotient, APInt *Remainder)
1648{
1649 assert(lhsWords >= rhsWords && "Fractional result");
1650
Eric Christopher820256b2009-08-21 04:06:45 +00001651 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001652 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001653 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001654 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1655 // can't use 64-bit operands here because we don't have native results of
1656 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001657 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001658 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001659 unsigned n = rhsWords * 2;
1660 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001661
1662 // Allocate space for the temporary values we need either on the stack, if
1663 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001664 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001665 unsigned *U = nullptr;
1666 unsigned *V = nullptr;
1667 unsigned *Q = nullptr;
1668 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001669 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1670 U = &SPACE[0];
1671 V = &SPACE[m+n+1];
1672 Q = &SPACE[(m+n+1) + n];
1673 if (Remainder)
1674 R = &SPACE[(m+n+1) + n + (m+n)];
1675 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001676 U = new unsigned[m + n + 1];
1677 V = new unsigned[n];
1678 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001679 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001680 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001681 }
1682
1683 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001684 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001685 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001686 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001687 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001688 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001689 }
1690 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1691
Reid Spencer522ca7c2007-02-25 01:56:07 +00001692 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001693 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001694 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001695 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001696 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001697 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001698 }
1699
Reid Spencer522ca7c2007-02-25 01:56:07 +00001700 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001701 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001702 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001703 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001704
Eric Christopher820256b2009-08-21 04:06:45 +00001705 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001706 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001707 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001708 // contain any zero words or the Knuth algorithm fails.
1709 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1710 n--;
1711 m++;
1712 }
1713 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1714 m--;
1715
1716 // If we're left with only a single word for the divisor, Knuth doesn't work
1717 // so we implement the short division algorithm here. This is much simpler
1718 // and faster because we are certain that we can divide a 64-bit quantity
1719 // by a 32-bit quantity at hardware speed and short division is simply a
1720 // series of such operations. This is just like doing short division but we
1721 // are using base 2^32 instead of base 10.
1722 assert(n != 0 && "Divide by zero?");
1723 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001724 unsigned divisor = V[0];
1725 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001726 for (int i = m+n-1; i >= 0; i--) {
1727 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1728 if (partial_dividend == 0) {
1729 Q[i] = 0;
1730 remainder = 0;
1731 } else if (partial_dividend < divisor) {
1732 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001733 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001734 } else if (partial_dividend == divisor) {
1735 Q[i] = 1;
1736 remainder = 0;
1737 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001738 Q[i] = (unsigned)(partial_dividend / divisor);
1739 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001740 }
1741 }
1742 if (R)
1743 R[0] = remainder;
1744 } else {
1745 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1746 // case n > 1.
1747 KnuthDiv(U, V, Q, R, m, n);
1748 }
1749
1750 // If the caller wants the quotient
1751 if (Quotient) {
1752 // Set up the Quotient value's memory.
1753 if (Quotient->BitWidth != LHS.BitWidth) {
1754 if (Quotient->isSingleWord())
1755 Quotient->VAL = 0;
1756 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001757 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001758 Quotient->BitWidth = LHS.BitWidth;
1759 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001760 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001761 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001762 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001763
Eric Christopher820256b2009-08-21 04:06:45 +00001764 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001765 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001766 // This case is currently dead as all users of divide() handle trivial cases
1767 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001768 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001769 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001770 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1771 if (Quotient->isSingleWord())
1772 Quotient->VAL = tmp;
1773 else
1774 Quotient->pVal[0] = tmp;
1775 } else {
1776 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1777 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001778 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001779 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1780 }
1781 }
1782
1783 // If the caller wants the remainder
1784 if (Remainder) {
1785 // Set up the Remainder value's memory.
1786 if (Remainder->BitWidth != RHS.BitWidth) {
1787 if (Remainder->isSingleWord())
1788 Remainder->VAL = 0;
1789 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001790 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001791 Remainder->BitWidth = RHS.BitWidth;
1792 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001793 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001794 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001795 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001796
1797 // The remainder is in R. Reconstitute the remainder into Remainder's low
1798 // order words.
1799 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001800 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001801 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1802 if (Remainder->isSingleWord())
1803 Remainder->VAL = tmp;
1804 else
1805 Remainder->pVal[0] = tmp;
1806 } else {
1807 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1808 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001809 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001810 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1811 }
1812 }
1813
1814 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001815 if (U != &SPACE[0]) {
1816 delete [] U;
1817 delete [] V;
1818 delete [] Q;
1819 delete [] R;
1820 }
Reid Spencer100502d2007-02-17 03:16:00 +00001821}
1822
Reid Spencer1d072122007-02-16 22:36:51 +00001823APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001824 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001825
1826 // First, deal with the easy case
1827 if (isSingleWord()) {
1828 assert(RHS.VAL != 0 && "Divide by zero?");
1829 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001830 }
Reid Spencer39867762007-02-17 02:07:07 +00001831
Reid Spencer39867762007-02-17 02:07:07 +00001832 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001833 unsigned rhsBits = RHS.getActiveBits();
1834 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001835 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001836 unsigned lhsBits = this->getActiveBits();
1837 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001838
1839 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001840 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001841 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001842 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001843 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001844 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001845 return APInt(BitWidth, 0);
1846 } else if (*this == RHS) {
1847 // X / X ===> 1
1848 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001849 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001850 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001851 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001852 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001853
1854 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1855 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001856 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001857 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001858}
1859
Jakub Staszak6605c602013-02-20 00:17:42 +00001860APInt APInt::sdiv(const APInt &RHS) const {
1861 if (isNegative()) {
1862 if (RHS.isNegative())
1863 return (-(*this)).udiv(-RHS);
1864 return -((-(*this)).udiv(RHS));
1865 }
1866 if (RHS.isNegative())
1867 return -(this->udiv(-RHS));
1868 return this->udiv(RHS);
1869}
1870
Reid Spencer1d072122007-02-16 22:36:51 +00001871APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001872 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001873 if (isSingleWord()) {
1874 assert(RHS.VAL != 0 && "Remainder by zero?");
1875 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001876 }
Reid Spencer39867762007-02-17 02:07:07 +00001877
Reid Spencer58a6a432007-02-21 08:21:52 +00001878 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001879 unsigned lhsBits = getActiveBits();
1880 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001881
1882 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001883 unsigned rhsBits = RHS.getActiveBits();
1884 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001885 assert(rhsWords && "Performing remainder operation by zero ???");
1886
Reid Spencer39867762007-02-17 02:07:07 +00001887 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001888 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001889 // 0 % Y ===> 0
1890 return APInt(BitWidth, 0);
1891 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001892 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001893 return *this;
1894 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001895 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001896 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001897 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001898 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00001899 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001900 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001901
Reid Spencer4c50b522007-05-13 23:44:59 +00001902 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001903 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001904 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001905 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001906}
Reid Spencer100502d2007-02-17 03:16:00 +00001907
Jakub Staszak6605c602013-02-20 00:17:42 +00001908APInt APInt::srem(const APInt &RHS) const {
1909 if (isNegative()) {
1910 if (RHS.isNegative())
1911 return -((-(*this)).urem(-RHS));
1912 return -((-(*this)).urem(RHS));
1913 }
1914 if (RHS.isNegative())
1915 return this->urem(-RHS);
1916 return this->urem(RHS);
1917}
1918
Eric Christopher820256b2009-08-21 04:06:45 +00001919void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001920 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001921 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1922
1923 // First, deal with the easy case
1924 if (LHS.isSingleWord()) {
1925 assert(RHS.VAL != 0 && "Divide by zero?");
1926 uint64_t QuotVal = LHS.VAL / RHS.VAL;
1927 uint64_t RemVal = LHS.VAL % RHS.VAL;
1928 Quotient = APInt(LHS.BitWidth, QuotVal);
1929 Remainder = APInt(LHS.BitWidth, RemVal);
1930 return;
1931 }
1932
Reid Spencer4c50b522007-05-13 23:44:59 +00001933 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001934 unsigned lhsBits = LHS.getActiveBits();
1935 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1936 unsigned rhsBits = RHS.getActiveBits();
1937 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00001938
1939 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001940 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00001941 Quotient = 0; // 0 / Y ===> 0
1942 Remainder = 0; // 0 % Y ===> 0
1943 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001944 }
1945
1946 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001947 Remainder = LHS; // X % Y ===> X, iff X < Y
1948 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00001949 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001950 }
1951
Reid Spencer4c50b522007-05-13 23:44:59 +00001952 if (LHS == RHS) {
1953 Quotient = 1; // X / X ===> 1
1954 Remainder = 0; // X % X ===> 0;
1955 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001956 }
1957
Reid Spencer4c50b522007-05-13 23:44:59 +00001958 if (lhsWords == 1 && rhsWords == 1) {
1959 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001960 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
1961 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1962 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
1963 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00001964 return;
1965 }
1966
1967 // Okay, lets do it the long way
1968 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
1969}
1970
Jakub Staszak6605c602013-02-20 00:17:42 +00001971void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
1972 APInt &Quotient, APInt &Remainder) {
1973 if (LHS.isNegative()) {
1974 if (RHS.isNegative())
1975 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
1976 else {
1977 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
1978 Quotient = -Quotient;
1979 }
1980 Remainder = -Remainder;
1981 } else if (RHS.isNegative()) {
1982 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
1983 Quotient = -Quotient;
1984 } else {
1985 APInt::udivrem(LHS, RHS, Quotient, Remainder);
1986 }
1987}
1988
Chris Lattner2c819b02010-10-13 23:54:10 +00001989APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001990 APInt Res = *this+RHS;
1991 Overflow = isNonNegative() == RHS.isNonNegative() &&
1992 Res.isNonNegative() != isNonNegative();
1993 return Res;
1994}
1995
Chris Lattner698661c2010-10-14 00:05:07 +00001996APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
1997 APInt Res = *this+RHS;
1998 Overflow = Res.ult(RHS);
1999 return Res;
2000}
2001
Chris Lattner2c819b02010-10-13 23:54:10 +00002002APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002003 APInt Res = *this - RHS;
2004 Overflow = isNonNegative() != RHS.isNonNegative() &&
2005 Res.isNonNegative() != isNonNegative();
2006 return Res;
2007}
2008
Chris Lattner698661c2010-10-14 00:05:07 +00002009APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00002010 APInt Res = *this-RHS;
2011 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00002012 return Res;
2013}
2014
Chris Lattner2c819b02010-10-13 23:54:10 +00002015APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002016 // MININT/-1 --> overflow.
2017 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
2018 return sdiv(RHS);
2019}
2020
Chris Lattner2c819b02010-10-13 23:54:10 +00002021APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002022 APInt Res = *this * RHS;
2023
2024 if (*this != 0 && RHS != 0)
2025 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
2026 else
2027 Overflow = false;
2028 return Res;
2029}
2030
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00002031APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
2032 APInt Res = *this * RHS;
2033
2034 if (*this != 0 && RHS != 0)
2035 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
2036 else
2037 Overflow = false;
2038 return Res;
2039}
2040
David Majnemera2521382014-10-13 21:48:30 +00002041APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
2042 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00002043 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00002044 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00002045
2046 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00002047 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00002048 else
David Majnemera2521382014-10-13 21:48:30 +00002049 Overflow = ShAmt.uge(countLeadingOnes());
Chris Lattner79bdd882010-10-13 23:46:33 +00002050
2051 return *this << ShAmt;
2052}
2053
David Majnemera2521382014-10-13 21:48:30 +00002054APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
2055 Overflow = ShAmt.uge(getBitWidth());
2056 if (Overflow)
2057 return APInt(BitWidth, 0);
2058
2059 Overflow = ShAmt.ugt(countLeadingZeros());
2060
2061 return *this << ShAmt;
2062}
2063
Chris Lattner79bdd882010-10-13 23:46:33 +00002064
2065
2066
Benjamin Kramer92d89982010-07-14 22:38:02 +00002067void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00002068 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002069 assert(!str.empty() && "Invalid string length");
Douglas Gregor663c0682011-09-14 15:54:46 +00002070 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
2071 radix == 36) &&
2072 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002073
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002074 StringRef::iterator p = str.begin();
2075 size_t slen = str.size();
2076 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002077 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002078 p++;
2079 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00002080 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002081 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00002082 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002083 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2084 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002085 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2086 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00002087
2088 // Allocate memory
2089 if (!isSingleWord())
2090 pVal = getClearedMemory(getNumWords());
2091
2092 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00002093 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00002094
2095 // Set up an APInt for the digit to add outside the loop so we don't
2096 // constantly construct/destruct it.
2097 APInt apdigit(getBitWidth(), 0);
2098 APInt apradix(getBitWidth(), radix);
2099
2100 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002101 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00002102 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00002103 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00002104
Reid Spencera93c9812007-05-16 19:18:22 +00002105 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002106 if (slen > 1) {
2107 if (shift)
2108 *this <<= shift;
2109 else
2110 *this *= apradix;
2111 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002112
2113 // Add in the digit we just interpreted
Reid Spencer632ebdf2007-02-24 20:19:37 +00002114 if (apdigit.isSingleWord())
2115 apdigit.VAL = digit;
2116 else
2117 apdigit.pVal[0] = digit;
Reid Spencer1ba83352007-02-21 03:55:44 +00002118 *this += apdigit;
Reid Spencer100502d2007-02-17 03:16:00 +00002119 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002120 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00002121 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00002122 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002123 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002124 }
Reid Spencer100502d2007-02-17 03:16:00 +00002125}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002126
Chris Lattner17f71652008-08-17 07:19:36 +00002127void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002128 bool Signed, bool formatAsCLiteral) const {
Douglas Gregor663c0682011-09-14 15:54:46 +00002129 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
2130 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002131 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002132
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002133 const char *Prefix = "";
2134 if (formatAsCLiteral) {
2135 switch (Radix) {
2136 case 2:
2137 // Binary literals are a non-standard extension added in gcc 4.3:
2138 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2139 Prefix = "0b";
2140 break;
2141 case 8:
2142 Prefix = "0";
2143 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002144 case 10:
2145 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002146 case 16:
2147 Prefix = "0x";
2148 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002149 default:
2150 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002151 }
2152 }
2153
Chris Lattner17f71652008-08-17 07:19:36 +00002154 // First, check for a zero value and just short circuit the logic below.
2155 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002156 while (*Prefix) {
2157 Str.push_back(*Prefix);
2158 ++Prefix;
2159 };
Chris Lattner17f71652008-08-17 07:19:36 +00002160 Str.push_back('0');
2161 return;
2162 }
Eric Christopher820256b2009-08-21 04:06:45 +00002163
Douglas Gregor663c0682011-09-14 15:54:46 +00002164 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002165
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002166 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002167 char Buffer[65];
2168 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002169
Chris Lattner17f71652008-08-17 07:19:36 +00002170 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002171 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002172 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002173 } else {
2174 int64_t I = getSExtValue();
2175 if (I >= 0) {
2176 N = I;
2177 } else {
2178 Str.push_back('-');
2179 N = -(uint64_t)I;
2180 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002181 }
Eric Christopher820256b2009-08-21 04:06:45 +00002182
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002183 while (*Prefix) {
2184 Str.push_back(*Prefix);
2185 ++Prefix;
2186 };
2187
Chris Lattner17f71652008-08-17 07:19:36 +00002188 while (N) {
2189 *--BufPtr = Digits[N % Radix];
2190 N /= Radix;
2191 }
2192 Str.append(BufPtr, Buffer+65);
2193 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002194 }
2195
Chris Lattner17f71652008-08-17 07:19:36 +00002196 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002197
Chris Lattner17f71652008-08-17 07:19:36 +00002198 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002199 // They want to print the signed version and it is a negative value
2200 // Flip the bits and add one to turn it into the equivalent positive
2201 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002202 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002203 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002204 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002205 }
Eric Christopher820256b2009-08-21 04:06:45 +00002206
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002207 while (*Prefix) {
2208 Str.push_back(*Prefix);
2209 ++Prefix;
2210 };
2211
Chris Lattner17f71652008-08-17 07:19:36 +00002212 // We insert the digits backward, then reverse them to get the right order.
2213 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002214
2215 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2216 // because the number of bits per digit (1, 3 and 4 respectively) divides
Chris Lattner17f71652008-08-17 07:19:36 +00002217 // equaly. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002218 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002219 // Just shift tmp right for each digit width until it becomes zero
2220 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2221 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002222
Chris Lattner17f71652008-08-17 07:19:36 +00002223 while (Tmp != 0) {
2224 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2225 Str.push_back(Digits[Digit]);
2226 Tmp = Tmp.lshr(ShiftAmt);
2227 }
2228 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002229 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002230 while (Tmp != 0) {
2231 APInt APdigit(1, 0);
2232 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002233 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002234 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002235 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002236 assert(Digit < Radix && "divide failed");
2237 Str.push_back(Digits[Digit]);
2238 Tmp = tmp2;
2239 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002240 }
Eric Christopher820256b2009-08-21 04:06:45 +00002241
Chris Lattner17f71652008-08-17 07:19:36 +00002242 // Reverse the digits before returning.
2243 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002244}
2245
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002246/// Returns the APInt as a std::string. Note that this is an inefficient method.
2247/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002248std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2249 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002250 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002251 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002252}
Chris Lattner6b695682007-08-16 15:56:55 +00002253
Chris Lattner17f71652008-08-17 07:19:36 +00002254
Yaron Kereneb2a2542016-01-29 20:50:44 +00002255LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002256 SmallString<40> S, U;
2257 this->toStringUnsigned(U);
2258 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002259 dbgs() << "APInt(" << BitWidth << "b, "
Yaron Keren09fb7c62015-03-10 07:33:23 +00002260 << U << "u " << S << "s)";
Chris Lattner17f71652008-08-17 07:19:36 +00002261}
2262
Chris Lattner0c19df42008-08-23 22:23:09 +00002263void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002264 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002265 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002266 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002267}
2268
Chris Lattner6b695682007-08-16 15:56:55 +00002269// This implements a variety of operations on a representation of
2270// arbitrary precision, two's-complement, bignum integer values.
2271
Chris Lattner96cffa62009-08-23 23:11:28 +00002272// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2273// and unrestricting assumption.
Benjamin Kramer7000ca32014-10-12 17:56:40 +00002274static_assert(integerPartWidth % 2 == 0, "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002275
2276/* Some handy functions local to this file. */
2277namespace {
2278
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002279 /* Returns the integer part with the least significant BITS set.
2280 BITS cannot be zero. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002281 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002282 lowBitMask(unsigned int bits)
2283 {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002284 assert(bits != 0 && bits <= integerPartWidth);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002285
2286 return ~(integerPart) 0 >> (integerPartWidth - bits);
2287 }
2288
Neil Boothc8b650a2007-10-06 00:43:45 +00002289 /* Returns the value of the lower half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002290 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002291 lowHalf(integerPart part)
2292 {
2293 return part & lowBitMask(integerPartWidth / 2);
2294 }
2295
Neil Boothc8b650a2007-10-06 00:43:45 +00002296 /* Returns the value of the upper half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002297 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002298 highHalf(integerPart part)
2299 {
2300 return part >> (integerPartWidth / 2);
2301 }
2302
Neil Boothc8b650a2007-10-06 00:43:45 +00002303 /* Returns the bit number of the most significant set bit of a part.
2304 If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002305 static unsigned int
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002306 partMSB(integerPart value)
Chris Lattner6b695682007-08-16 15:56:55 +00002307 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002308 return findLastSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002309 }
2310
Neil Boothc8b650a2007-10-06 00:43:45 +00002311 /* Returns the bit number of the least significant set bit of a
2312 part. If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002313 static unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002314 partLSB(integerPart value)
2315 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002316 return findFirstSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002317 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002318}
Chris Lattner6b695682007-08-16 15:56:55 +00002319
2320/* Sets the least significant part of a bignum to the input value, and
2321 zeroes out higher parts. */
2322void
2323APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts)
2324{
2325 unsigned int i;
2326
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002327 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002328
Chris Lattner6b695682007-08-16 15:56:55 +00002329 dst[0] = part;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002330 for (i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002331 dst[i] = 0;
2332}
2333
2334/* Assign one bignum to another. */
2335void
2336APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts)
2337{
2338 unsigned int i;
2339
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002340 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002341 dst[i] = src[i];
2342}
2343
2344/* Returns true if a bignum is zero, false otherwise. */
2345bool
2346APInt::tcIsZero(const integerPart *src, unsigned int parts)
2347{
2348 unsigned int i;
2349
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002350 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002351 if (src[i])
2352 return false;
2353
2354 return true;
2355}
2356
2357/* Extract the given bit of a bignum; returns 0 or 1. */
2358int
2359APInt::tcExtractBit(const integerPart *parts, unsigned int bit)
2360{
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002361 return (parts[bit / integerPartWidth] &
2362 ((integerPart) 1 << bit % integerPartWidth)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002363}
2364
John McCalldcb9a7a2010-02-28 02:51:25 +00002365/* Set the given bit of a bignum. */
Chris Lattner6b695682007-08-16 15:56:55 +00002366void
2367APInt::tcSetBit(integerPart *parts, unsigned int bit)
2368{
2369 parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
2370}
2371
John McCalldcb9a7a2010-02-28 02:51:25 +00002372/* Clears the given bit of a bignum. */
2373void
2374APInt::tcClearBit(integerPart *parts, unsigned int bit)
2375{
2376 parts[bit / integerPartWidth] &=
2377 ~((integerPart) 1 << (bit % integerPartWidth));
2378}
2379
Neil Boothc8b650a2007-10-06 00:43:45 +00002380/* Returns the bit number of the least significant set bit of a
2381 number. If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002382unsigned int
2383APInt::tcLSB(const integerPart *parts, unsigned int n)
2384{
2385 unsigned int i, lsb;
2386
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002387 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002388 if (parts[i] != 0) {
2389 lsb = partLSB(parts[i]);
2390
2391 return lsb + i * integerPartWidth;
2392 }
2393 }
2394
2395 return -1U;
2396}
2397
Neil Boothc8b650a2007-10-06 00:43:45 +00002398/* Returns the bit number of the most significant set bit of a number.
2399 If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002400unsigned int
2401APInt::tcMSB(const integerPart *parts, unsigned int n)
2402{
2403 unsigned int msb;
2404
2405 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002406 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002407
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002408 if (parts[n] != 0) {
2409 msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002410
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002411 return msb + n * integerPartWidth;
2412 }
Chris Lattner6b695682007-08-16 15:56:55 +00002413 } while (n);
2414
2415 return -1U;
2416}
2417
Neil Boothb6182162007-10-08 13:47:12 +00002418/* Copy the bit vector of width srcBITS from SRC, starting at bit
2419 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2420 the least significant bit of DST. All high bits above srcBITS in
2421 DST are zero-filled. */
2422void
Evan Chengdb338f32009-05-21 23:47:47 +00002423APInt::tcExtract(integerPart *dst, unsigned int dstCount,const integerPart *src,
Neil Boothb6182162007-10-08 13:47:12 +00002424 unsigned int srcBits, unsigned int srcLSB)
2425{
2426 unsigned int firstSrcPart, dstParts, shift, n;
2427
2428 dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002429 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002430
2431 firstSrcPart = srcLSB / integerPartWidth;
2432 tcAssign (dst, src + firstSrcPart, dstParts);
2433
2434 shift = srcLSB % integerPartWidth;
2435 tcShiftRight (dst, dstParts, shift);
2436
2437 /* We now have (dstParts * integerPartWidth - shift) bits from SRC
2438 in DST. If this is less that srcBits, append the rest, else
2439 clear the high bits. */
2440 n = dstParts * integerPartWidth - shift;
2441 if (n < srcBits) {
2442 integerPart mask = lowBitMask (srcBits - n);
2443 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2444 << n % integerPartWidth);
2445 } else if (n > srcBits) {
Neil Booth7e74b172007-10-12 15:31:31 +00002446 if (srcBits % integerPartWidth)
2447 dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
Neil Boothb6182162007-10-08 13:47:12 +00002448 }
2449
2450 /* Clear high parts. */
2451 while (dstParts < dstCount)
2452 dst[dstParts++] = 0;
2453}
2454
Chris Lattner6b695682007-08-16 15:56:55 +00002455/* DST += RHS + C where C is zero or one. Returns the carry flag. */
2456integerPart
2457APInt::tcAdd(integerPart *dst, const integerPart *rhs,
2458 integerPart c, unsigned int parts)
2459{
2460 unsigned int i;
2461
2462 assert(c <= 1);
2463
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002464 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002465 integerPart l;
2466
2467 l = dst[i];
2468 if (c) {
2469 dst[i] += rhs[i] + 1;
2470 c = (dst[i] <= l);
2471 } else {
2472 dst[i] += rhs[i];
2473 c = (dst[i] < l);
2474 }
2475 }
2476
2477 return c;
2478}
2479
2480/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
2481integerPart
2482APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
2483 integerPart c, unsigned int parts)
2484{
2485 unsigned int i;
2486
2487 assert(c <= 1);
2488
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002489 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002490 integerPart l;
2491
2492 l = dst[i];
2493 if (c) {
2494 dst[i] -= rhs[i] + 1;
2495 c = (dst[i] >= l);
2496 } else {
2497 dst[i] -= rhs[i];
2498 c = (dst[i] > l);
2499 }
2500 }
2501
2502 return c;
2503}
2504
2505/* Negate a bignum in-place. */
2506void
2507APInt::tcNegate(integerPart *dst, unsigned int parts)
2508{
2509 tcComplement(dst, parts);
2510 tcIncrement(dst, parts);
2511}
2512
Neil Boothc8b650a2007-10-06 00:43:45 +00002513/* DST += SRC * MULTIPLIER + CARRY if add is true
2514 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002515
2516 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2517 they must start at the same point, i.e. DST == SRC.
2518
2519 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2520 returned. Otherwise DST is filled with the least significant
2521 DSTPARTS parts of the result, and if all of the omitted higher
2522 parts were zero return zero, otherwise overflow occurred and
2523 return one. */
2524int
2525APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
2526 integerPart multiplier, integerPart carry,
2527 unsigned int srcParts, unsigned int dstParts,
2528 bool add)
2529{
2530 unsigned int i, n;
2531
2532 /* Otherwise our writes of DST kill our later reads of SRC. */
2533 assert(dst <= src || dst >= src + srcParts);
2534 assert(dstParts <= srcParts + 1);
2535
2536 /* N loops; minimum of dstParts and srcParts. */
2537 n = dstParts < srcParts ? dstParts: srcParts;
2538
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002539 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002540 integerPart low, mid, high, srcPart;
2541
2542 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2543
2544 This cannot overflow, because
2545
2546 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2547
2548 which is less than n^2. */
2549
2550 srcPart = src[i];
2551
2552 if (multiplier == 0 || srcPart == 0) {
2553 low = carry;
2554 high = 0;
2555 } else {
2556 low = lowHalf(srcPart) * lowHalf(multiplier);
2557 high = highHalf(srcPart) * highHalf(multiplier);
2558
2559 mid = lowHalf(srcPart) * highHalf(multiplier);
2560 high += highHalf(mid);
2561 mid <<= integerPartWidth / 2;
2562 if (low + mid < low)
2563 high++;
2564 low += mid;
2565
2566 mid = highHalf(srcPart) * lowHalf(multiplier);
2567 high += highHalf(mid);
2568 mid <<= integerPartWidth / 2;
2569 if (low + mid < low)
2570 high++;
2571 low += mid;
2572
2573 /* Now add carry. */
2574 if (low + carry < low)
2575 high++;
2576 low += carry;
2577 }
2578
2579 if (add) {
2580 /* And now DST[i], and store the new low part there. */
2581 if (low + dst[i] < low)
2582 high++;
2583 dst[i] += low;
2584 } else
2585 dst[i] = low;
2586
2587 carry = high;
2588 }
2589
2590 if (i < dstParts) {
2591 /* Full multiplication, there is no overflow. */
2592 assert(i + 1 == dstParts);
2593 dst[i] = carry;
2594 return 0;
2595 } else {
2596 /* We overflowed if there is carry. */
2597 if (carry)
2598 return 1;
2599
2600 /* We would overflow if any significant unwritten parts would be
2601 non-zero. This is true if any remaining src parts are non-zero
2602 and the multiplier is non-zero. */
2603 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002604 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002605 if (src[i])
2606 return 1;
2607
2608 /* We fitted in the narrow destination. */
2609 return 0;
2610 }
2611}
2612
2613/* DST = LHS * RHS, where DST has the same width as the operands and
2614 is filled with the least significant parts of the result. Returns
2615 one if overflow occurred, otherwise zero. DST must be disjoint
2616 from both operands. */
2617int
2618APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
2619 const integerPart *rhs, unsigned int parts)
2620{
2621 unsigned int i;
2622 int overflow;
2623
2624 assert(dst != lhs && dst != rhs);
2625
2626 overflow = 0;
2627 tcSet(dst, 0, parts);
2628
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002629 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002630 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2631 parts - i, true);
2632
2633 return overflow;
2634}
2635
Neil Booth0ea72a92007-10-06 00:24:48 +00002636/* DST = LHS * RHS, where DST has width the sum of the widths of the
2637 operands. No overflow occurs. DST must be disjoint from both
2638 operands. Returns the number of parts required to hold the
2639 result. */
2640unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002641APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
Neil Booth0ea72a92007-10-06 00:24:48 +00002642 const integerPart *rhs, unsigned int lhsParts,
2643 unsigned int rhsParts)
Chris Lattner6b695682007-08-16 15:56:55 +00002644{
Neil Booth0ea72a92007-10-06 00:24:48 +00002645 /* Put the narrower number on the LHS for less loops below. */
2646 if (lhsParts > rhsParts) {
2647 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2648 } else {
2649 unsigned int n;
Chris Lattner6b695682007-08-16 15:56:55 +00002650
Neil Booth0ea72a92007-10-06 00:24:48 +00002651 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002652
Neil Booth0ea72a92007-10-06 00:24:48 +00002653 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002654
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002655 for (n = 0; n < lhsParts; n++)
Neil Booth0ea72a92007-10-06 00:24:48 +00002656 tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002657
Neil Booth0ea72a92007-10-06 00:24:48 +00002658 n = lhsParts + rhsParts;
2659
2660 return n - (dst[n - 1] == 0);
2661 }
Chris Lattner6b695682007-08-16 15:56:55 +00002662}
2663
2664/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2665 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2666 set REMAINDER to the remainder, return zero. i.e.
2667
2668 OLD_LHS = RHS * LHS + REMAINDER
2669
2670 SCRATCH is a bignum of the same size as the operands and result for
2671 use by the routine; its contents need not be initialized and are
2672 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2673*/
2674int
2675APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
2676 integerPart *remainder, integerPart *srhs,
2677 unsigned int parts)
2678{
2679 unsigned int n, shiftCount;
2680 integerPart mask;
2681
2682 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2683
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002684 shiftCount = tcMSB(rhs, parts) + 1;
2685 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002686 return true;
2687
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002688 shiftCount = parts * integerPartWidth - shiftCount;
Chris Lattner6b695682007-08-16 15:56:55 +00002689 n = shiftCount / integerPartWidth;
2690 mask = (integerPart) 1 << (shiftCount % integerPartWidth);
2691
2692 tcAssign(srhs, rhs, parts);
2693 tcShiftLeft(srhs, parts, shiftCount);
2694 tcAssign(remainder, lhs, parts);
2695 tcSet(lhs, 0, parts);
2696
2697 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2698 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002699 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002700 int compare;
2701
2702 compare = tcCompare(remainder, srhs, parts);
2703 if (compare >= 0) {
2704 tcSubtract(remainder, srhs, 0, parts);
2705 lhs[n] |= mask;
2706 }
2707
2708 if (shiftCount == 0)
2709 break;
2710 shiftCount--;
2711 tcShiftRight(srhs, parts, 1);
2712 if ((mask >>= 1) == 0)
2713 mask = (integerPart) 1 << (integerPartWidth - 1), n--;
2714 }
2715
2716 return false;
2717}
2718
2719/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2720 There are no restrictions on COUNT. */
2721void
2722APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count)
2723{
Neil Boothb6182162007-10-08 13:47:12 +00002724 if (count) {
2725 unsigned int jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002726
Neil Boothb6182162007-10-08 13:47:12 +00002727 /* Jump is the inter-part jump; shift is is intra-part shift. */
2728 jump = count / integerPartWidth;
2729 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002730
Neil Boothb6182162007-10-08 13:47:12 +00002731 while (parts > jump) {
2732 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002733
Neil Boothb6182162007-10-08 13:47:12 +00002734 parts--;
Chris Lattner6b695682007-08-16 15:56:55 +00002735
Neil Boothb6182162007-10-08 13:47:12 +00002736 /* dst[i] comes from the two parts src[i - jump] and, if we have
2737 an intra-part shift, src[i - jump - 1]. */
2738 part = dst[parts - jump];
2739 if (shift) {
2740 part <<= shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002741 if (parts >= jump + 1)
2742 part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
2743 }
2744
Neil Boothb6182162007-10-08 13:47:12 +00002745 dst[parts] = part;
2746 }
Chris Lattner6b695682007-08-16 15:56:55 +00002747
Neil Boothb6182162007-10-08 13:47:12 +00002748 while (parts > 0)
2749 dst[--parts] = 0;
2750 }
Chris Lattner6b695682007-08-16 15:56:55 +00002751}
2752
2753/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2754 zero. There are no restrictions on COUNT. */
2755void
2756APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count)
2757{
Neil Boothb6182162007-10-08 13:47:12 +00002758 if (count) {
2759 unsigned int i, jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002760
Neil Boothb6182162007-10-08 13:47:12 +00002761 /* Jump is the inter-part jump; shift is is intra-part shift. */
2762 jump = count / integerPartWidth;
2763 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002764
Neil Boothb6182162007-10-08 13:47:12 +00002765 /* Perform the shift. This leaves the most significant COUNT bits
2766 of the result at zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002767 for (i = 0; i < parts; i++) {
Neil Boothb6182162007-10-08 13:47:12 +00002768 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002769
Neil Boothb6182162007-10-08 13:47:12 +00002770 if (i + jump >= parts) {
2771 part = 0;
2772 } else {
2773 part = dst[i + jump];
2774 if (shift) {
2775 part >>= shift;
2776 if (i + jump + 1 < parts)
2777 part |= dst[i + jump + 1] << (integerPartWidth - shift);
2778 }
Chris Lattner6b695682007-08-16 15:56:55 +00002779 }
Chris Lattner6b695682007-08-16 15:56:55 +00002780
Neil Boothb6182162007-10-08 13:47:12 +00002781 dst[i] = part;
2782 }
Chris Lattner6b695682007-08-16 15:56:55 +00002783 }
2784}
2785
2786/* Bitwise and of two bignums. */
2787void
2788APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts)
2789{
2790 unsigned int i;
2791
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002792 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002793 dst[i] &= rhs[i];
2794}
2795
2796/* Bitwise inclusive or of two bignums. */
2797void
2798APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts)
2799{
2800 unsigned int i;
2801
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002802 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002803 dst[i] |= rhs[i];
2804}
2805
2806/* Bitwise exclusive or of two bignums. */
2807void
2808APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts)
2809{
2810 unsigned int i;
2811
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002812 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002813 dst[i] ^= rhs[i];
2814}
2815
2816/* Complement a bignum in-place. */
2817void
2818APInt::tcComplement(integerPart *dst, unsigned int parts)
2819{
2820 unsigned int i;
2821
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002822 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002823 dst[i] = ~dst[i];
2824}
2825
2826/* Comparison (unsigned) of two bignums. */
2827int
2828APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
2829 unsigned int parts)
2830{
2831 while (parts) {
2832 parts--;
2833 if (lhs[parts] == rhs[parts])
2834 continue;
2835
2836 if (lhs[parts] > rhs[parts])
2837 return 1;
2838 else
2839 return -1;
2840 }
2841
2842 return 0;
2843}
2844
2845/* Increment a bignum in-place, return the carry flag. */
2846integerPart
2847APInt::tcIncrement(integerPart *dst, unsigned int parts)
2848{
2849 unsigned int i;
2850
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002851 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002852 if (++dst[i] != 0)
2853 break;
2854
2855 return i == parts;
2856}
2857
Michael Gottesman9d406f42013-05-28 19:50:20 +00002858/* Decrement a bignum in-place, return the borrow flag. */
2859integerPart
2860APInt::tcDecrement(integerPart *dst, unsigned int parts) {
2861 for (unsigned int i = 0; i < parts; i++) {
2862 // If the current word is non-zero, then the decrement has no effect on the
2863 // higher-order words of the integer and no borrow can occur. Exit early.
2864 if (dst[i]--)
2865 return 0;
2866 }
2867 // If every word was zero, then there is a borrow.
2868 return 1;
2869}
2870
2871
Chris Lattner6b695682007-08-16 15:56:55 +00002872/* Set the least significant BITS bits of a bignum, clear the
2873 rest. */
2874void
2875APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts,
2876 unsigned int bits)
2877{
2878 unsigned int i;
2879
2880 i = 0;
2881 while (bits > integerPartWidth) {
2882 dst[i++] = ~(integerPart) 0;
2883 bits -= integerPartWidth;
2884 }
2885
2886 if (bits)
2887 dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
2888
2889 while (i < parts)
2890 dst[i++] = 0;
2891}