blob: 9dca64085c57add1250be1b81b8e4ef4ae9d74f2 [file] [log] [blame]
Zhou Shengfd43dcf2007-02-06 03:00:16 +00001//===-- APInt.cpp - Implement APInt class ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Sheng Zhou and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision integral
11// constant values.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
16#include "llvm/DerivedTypes.h"
17#include "llvm/Support/MathExtras.h"
Zhou Shenga3832fd2007-02-07 06:14:53 +000018#include <cstring>
Zhou Shengfd43dcf2007-02-06 03:00:16 +000019#include <cstdlib>
20using namespace llvm;
21
Reid Spenceraf0e9562007-02-18 18:38:44 +000022// A utility function for allocating memory, checking for allocation failures,
23// and ensuring the contents is zeroed.
24inline static uint64_t* getClearedMemory(uint32_t numWords) {
25 uint64_t * result = new uint64_t[numWords];
26 assert(result && "APInt memory allocation fails!");
27 memset(result, 0, numWords * sizeof(uint64_t));
28 return result;
Zhou Sheng353815d2007-02-06 06:04:53 +000029}
30
Reid Spenceraf0e9562007-02-18 18:38:44 +000031// A utility function for allocating memory and checking for allocation failure.
32inline static uint64_t* getMemory(uint32_t numWords) {
33 uint64_t * result = new uint64_t[numWords];
34 assert(result && "APInt memory allocation fails!");
35 return result;
36}
37
38APInt::APInt(uint32_t numBits, uint64_t val)
Reid Spencer9c0696f2007-02-20 08:51:03 +000039 : BitWidth(numBits), pVal(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000040 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
41 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000042 if (isSingleWord())
Reid Spencere81d2da2007-02-16 22:36:51 +000043 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
Zhou Shengfd43dcf2007-02-06 03:00:16 +000044 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000045 pVal = getClearedMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000046 pVal[0] = val;
47 }
48}
49
Reid Spenceraf0e9562007-02-18 18:38:44 +000050APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
Reid Spencer9c0696f2007-02-20 08:51:03 +000051 : BitWidth(numBits), pVal(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000052 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
53 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000054 assert(bigVal && "Null pointer detected!");
55 if (isSingleWord())
Reid Spencere81d2da2007-02-16 22:36:51 +000056 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
Zhou Shengfd43dcf2007-02-06 03:00:16 +000057 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000058 pVal = getMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000059 // Calculate the actual length of bigVal[].
Reid Spenceraf0e9562007-02-18 18:38:44 +000060 uint32_t maxN = std::max<uint32_t>(numWords, getNumWords());
61 uint32_t minN = std::min<uint32_t>(numWords, getNumWords());
Reid Spencera58f0582007-02-18 20:09:41 +000062 memcpy(pVal, bigVal, (minN - 1) * APINT_WORD_SIZE);
Reid Spencer443b5702007-02-18 00:44:22 +000063 pVal[minN-1] = bigVal[minN-1] &
64 (~uint64_t(0ULL) >>
65 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
Zhou Shenga3832fd2007-02-07 06:14:53 +000066 if (maxN == getNumWords())
Reid Spencera58f0582007-02-18 20:09:41 +000067 memset(pVal+numWords, 0, (getNumWords() - numWords) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000068 }
69}
70
Zhou Shenga3832fd2007-02-07 06:14:53 +000071/// @brief Create a new APInt by translating the char array represented
72/// integer value.
Reid Spenceraf0e9562007-02-18 18:38:44 +000073APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000074 uint8_t radix)
75 : BitWidth(numbits), pVal(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000076 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000077}
78
79/// @brief Create a new APInt by translating the string represented
80/// integer value.
Reid Spencer9c0696f2007-02-20 08:51:03 +000081APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
82 : BitWidth(numbits), pVal(0) {
Zhou Shenga3832fd2007-02-07 06:14:53 +000083 assert(!Val.empty() && "String empty?");
Reid Spencere81d2da2007-02-16 22:36:51 +000084 fromString(numbits, Val.c_str(), Val.size(), radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000085}
86
Reid Spencera58f0582007-02-18 20:09:41 +000087/// @brief Copy constructor
Reid Spencer54362ca2007-02-20 23:40:25 +000088APInt::APInt(const APInt& that)
89 : BitWidth(that.BitWidth), pVal(0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +000090 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +000091 VAL = that.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000092 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000093 pVal = getMemory(getNumWords());
Reid Spencer54362ca2007-02-20 23:40:25 +000094 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000095 }
96}
97
98APInt::~APInt() {
Reid Spencer9c0696f2007-02-20 08:51:03 +000099 if (!isSingleWord() && pVal)
100 delete[] pVal;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000101}
102
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000103/// @brief Copy assignment operator. Create a new object from the given
104/// APInt one by initialization.
105APInt& APInt::operator=(const APInt& RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000106 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
107 if (isSingleWord())
Reid Spenceraf0e9562007-02-18 18:38:44 +0000108 VAL = RHS.VAL;
109 else
Reid Spencera58f0582007-02-18 20:09:41 +0000110 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000111 return *this;
112}
113
114/// @brief Assignment operator. Assigns a common case integer value to
115/// the APInt.
116APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000117 if (isSingleWord())
118 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000119 else {
120 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000121 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000122 }
123 return *this;
124}
125
Reid Spenceraf0e9562007-02-18 18:38:44 +0000126/// add_1 - This function adds a single "digit" integer, y, to the multiple
127/// "digit" integer array, x[]. x[] is modified to reflect the addition and
128/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000129/// @returns the carry of the addition.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000130static uint64_t add_1(uint64_t dest[],
131 uint64_t x[], uint32_t len,
132 uint64_t y) {
133 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000134 dest[i] = y + x[i];
135 if (dest[i] < y)
136 y = 1;
137 else {
138 y = 0;
139 break;
140 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000141 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000142 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000143}
144
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000145/// @brief Prefix increment operator. Increments the APInt by one.
146APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000147 if (isSingleWord())
148 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000149 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000150 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000151 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000152 return *this;
153}
154
Reid Spenceraf0e9562007-02-18 18:38:44 +0000155/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
156/// the multi-digit integer array, x[], propagating the borrowed 1 value until
157/// no further borrowing is neeeded or it runs out of "digits" in x. The result
158/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
159/// In other words, if y > x then this function returns 1, otherwise 0.
160static uint64_t sub_1(uint64_t x[], uint32_t len,
161 uint64_t y) {
162 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000163 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000164 x[i] -= y;
165 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000166 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000167 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000168 y = 0; // No need to borrow
169 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000170 }
171 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000172 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000173}
174
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000175/// @brief Prefix decrement operator. Decrements the APInt by one.
176APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000177 if (isSingleWord())
178 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000179 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000180 sub_1(pVal, getNumWords(), 1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000181 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000182 return *this;
183}
184
Reid Spencer5e0a8512007-02-17 03:16:00 +0000185/// add - This function adds the integer array x[] by integer array
186/// y[] and returns the carry.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000187static uint64_t add(uint64_t dest[], uint64_t x[],
188 uint64_t y[], uint32_t len) {
Reid Spencer54362ca2007-02-20 23:40:25 +0000189 uint64_t carry = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000190 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer54362ca2007-02-20 23:40:25 +0000191 uint64_t save = x[i];
192 dest[i] = x[i] + y[i] + carry;
193 carry = dest[i] < save ? 1 : 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000194 }
195 return carry;
196}
197
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000198/// @brief Addition assignment operator. Adds this APInt by the given APInt&
199/// RHS and assigns the result to this APInt.
200APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000201 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000202 if (isSingleWord())
203 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000204 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000205 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000206 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000207 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000208 return *this;
209}
210
Reid Spencer5e0a8512007-02-17 03:16:00 +0000211/// sub - This function subtracts the integer array x[] by
212/// integer array y[], and returns the borrow-out carry.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000213static uint64_t sub(uint64_t dest[], uint64_t x[],
214 uint64_t y[], uint32_t len) {
Reid Spencer54362ca2007-02-20 23:40:25 +0000215 uint64_t borrow = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000216 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer54362ca2007-02-20 23:40:25 +0000217 uint64_t save = x[i];
218 dest[i] = x[i] - borrow - y[i];
219 borrow = save < dest[i] ? 1 : 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000220 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000221 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000222}
223
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000224/// @brief Subtraction assignment operator. Subtracts this APInt by the given
225/// APInt &RHS and assigns the result to this APInt.
226APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000227 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000228 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000229 VAL -= RHS.VAL;
230 else
231 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencere81d2da2007-02-16 22:36:51 +0000232 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000233 return *this;
234}
235
Reid Spencer5e0a8512007-02-17 03:16:00 +0000236/// mul_1 - This function performs the multiplication operation on a
237/// large integer (represented as an integer array) and a uint64_t integer.
238/// @returns the carry of the multiplication.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000239static uint64_t mul_1(uint64_t dest[],
240 uint64_t x[], uint32_t len,
241 uint64_t y) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000242 // Split y into high 32-bit part and low 32-bit part.
243 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
244 uint64_t carry = 0, lx, hx;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000245 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000246 lx = x[i] & 0xffffffffULL;
247 hx = x[i] >> 32;
248 // hasCarry - A flag to indicate if has carry.
249 // hasCarry == 0, no carry
250 // hasCarry == 1, has carry
251 // hasCarry == 2, no carry and the calculation result == 0.
252 uint8_t hasCarry = 0;
253 dest[i] = carry + lx * ly;
254 // Determine if the add above introduces carry.
255 hasCarry = (dest[i] < carry) ? 1 : 0;
256 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
257 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
258 // (2^32 - 1) + 2^32 = 2^64.
259 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
260
261 carry += (lx * hy) & 0xffffffffULL;
262 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
263 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
264 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
265 }
266
267 return carry;
268}
269
270/// mul - This function multiplies integer array x[] by integer array y[] and
271/// stores the result into integer array dest[].
272/// Note the array dest[]'s size should no less than xlen + ylen.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000273static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
274 uint64_t y[], uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000275 dest[xlen] = mul_1(dest, x, xlen, y[0]);
276
Reid Spenceraf0e9562007-02-18 18:38:44 +0000277 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000278 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
279 uint64_t carry = 0, lx, hx;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000280 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000281 lx = x[j] & 0xffffffffULL;
282 hx = x[j] >> 32;
283 // hasCarry - A flag to indicate if has carry.
284 // hasCarry == 0, no carry
285 // hasCarry == 1, has carry
286 // hasCarry == 2, no carry and the calculation result == 0.
287 uint8_t hasCarry = 0;
288 uint64_t resul = carry + lx * ly;
289 hasCarry = (resul < carry) ? 1 : 0;
290 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
291 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
292
293 carry += (lx * hy) & 0xffffffffULL;
294 resul = (carry << 32) | (resul & 0xffffffffULL);
295 dest[i+j] += resul;
296 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
297 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
298 ((lx * hy) >> 32) + hx * hy;
299 }
300 dest[i+xlen] = carry;
301 }
302}
303
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000304/// @brief Multiplication assignment operator. Multiplies this APInt by the
305/// given APInt& RHS and assigns the result to this APInt.
306APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000307 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000308 if (isSingleWord())
Reid Spencer61eb1802007-02-20 20:42:10 +0000309 VAL *= RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000310 else {
311 // one-based first non-zero bit position.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000312 uint32_t first = getActiveBits();
313 uint32_t xlen = !first ? 0 : whichWord(first - 1) + 1;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000314 if (!xlen)
315 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000316 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000317 first = RHS.getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +0000318 uint32_t ylen = !first ? 0 : whichWord(first - 1) + 1;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000319 if (!ylen) {
Reid Spencera58f0582007-02-18 20:09:41 +0000320 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000321 return *this;
322 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000323 uint64_t *dest = getMemory(xlen+ylen);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000324 mul(dest, pVal, xlen, RHS.pVal, ylen);
Zhou Shenga3832fd2007-02-07 06:14:53 +0000325 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
Reid Spencera58f0582007-02-18 20:09:41 +0000326 getNumWords() : xlen + ylen) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000327 delete[] dest;
328 }
329 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000330 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000331 return *this;
332}
333
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000334/// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
335/// this APInt and the given APInt& RHS, assigns the result to this APInt.
336APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000337 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000338 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000339 VAL &= RHS.VAL;
340 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000341 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000342 uint32_t numWords = getNumWords();
343 for (uint32_t i = 0; i < numWords; ++i)
344 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000345 return *this;
346}
347
348/// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
349/// this APInt and the given APInt& RHS, assigns the result to this APInt.
350APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000351 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000352 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000353 VAL |= RHS.VAL;
354 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000355 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000356 uint32_t numWords = getNumWords();
357 for (uint32_t i = 0; i < numWords; ++i)
358 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000359 return *this;
360}
361
362/// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
363/// this APInt and the given APInt& RHS, assigns the result to this APInt.
364APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000365 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000366 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000367 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000368 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000369 return *this;
370 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000371 uint32_t numWords = getNumWords();
372 for (uint32_t i = 0; i < numWords; ++i)
373 pVal[i] ^= RHS.pVal[i];
Reid Spencer54362ca2007-02-20 23:40:25 +0000374 this->clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000375 return *this;
376}
377
378/// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
379/// and the given APInt& RHS.
380APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000381 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000382 if (isSingleWord())
383 return APInt(getBitWidth(), VAL & RHS.VAL);
384
385 APInt Result(*this);
386 uint32_t numWords = getNumWords();
387 for (uint32_t i = 0; i < numWords; ++i)
388 Result.pVal[i] &= RHS.pVal[i];
389 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000390}
391
392/// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
393/// and the given APInt& RHS.
394APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000395 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000396 if (isSingleWord())
397 return APInt(getBitWidth(), VAL | RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000398
Reid Spenceraf0e9562007-02-18 18:38:44 +0000399 APInt Result(*this);
400 uint32_t numWords = getNumWords();
401 for (uint32_t i = 0; i < numWords; ++i)
402 Result.pVal[i] |= RHS.pVal[i];
403 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000404}
405
406/// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
407/// and the given APInt& RHS.
408APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000409 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000410 if (isSingleWord()) {
411 APInt Result(BitWidth, VAL ^ RHS.VAL);
412 Result.clearUnusedBits();
413 return Result;
414 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000415 APInt Result(*this);
416 uint32_t numWords = getNumWords();
417 for (uint32_t i = 0; i < numWords; ++i)
418 Result.pVal[i] ^= RHS.pVal[i];
419 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000420}
421
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000422/// @brief Logical negation operator. Performs logical negation operation on
423/// this APInt.
424bool APInt::operator !() const {
425 if (isSingleWord())
426 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000427
428 for (uint32_t i = 0; i < getNumWords(); ++i)
429 if (pVal[i])
430 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000431 return true;
432}
433
434/// @brief Multiplication operator. Multiplies this APInt by the given APInt&
435/// RHS.
436APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000437 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000438 if (isSingleWord()) {
439 APInt Result(BitWidth, VAL * RHS.VAL);
440 Result.clearUnusedBits();
441 return Result;
442 }
Reid Spencer61eb1802007-02-20 20:42:10 +0000443 APInt Result(*this);
444 Result *= RHS;
445 Result.clearUnusedBits();
446 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000447}
448
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000449/// @brief Addition operator. Adds this APInt by the given APInt& RHS.
450APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000451 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000452 if (isSingleWord()) {
453 APInt Result(BitWidth, VAL + RHS.VAL);
454 Result.clearUnusedBits();
455 return Result;
456 }
457 APInt Result(BitWidth, 0);
458 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
459 Result.clearUnusedBits();
460 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000461}
462
463/// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
464APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000465 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000466 if (isSingleWord()) {
467 APInt Result(BitWidth, VAL - RHS.VAL);
468 Result.clearUnusedBits();
469 return Result;
470 }
471 APInt Result(BitWidth, 0);
472 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
473 Result.clearUnusedBits();
474 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000475}
476
477/// @brief Array-indexing support.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000478bool APInt::operator[](uint32_t bitPosition) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000479 return (maskBit(bitPosition) & (isSingleWord() ?
480 VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000481}
482
483/// @brief Equality operator. Compare this APInt with the given APInt& RHS
484/// for the validity of the equality relationship.
485bool APInt::operator==(const APInt& RHS) const {
Reid Spencer54362ca2007-02-20 23:40:25 +0000486 if (isSingleWord())
487 return VAL == RHS.VAL;
488
Reid Spenceraf0e9562007-02-18 18:38:44 +0000489 uint32_t n1 = getActiveBits();
490 uint32_t n2 = RHS.getActiveBits();
Reid Spencer54362ca2007-02-20 23:40:25 +0000491 if (n1 != n2)
492 return false;
493
494 if (n1 <= APINT_BITS_PER_WORD)
495 return pVal[0] == RHS.pVal[0];
496
497 for (int i = whichWord(n1 - 1); i >= 0; --i)
498 if (pVal[i] != RHS.pVal[i])
499 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000500 return true;
501}
502
Zhou Shenga3832fd2007-02-07 06:14:53 +0000503/// @brief Equality operator. Compare this APInt with the given uint64_t value
504/// for the validity of the equality relationship.
505bool APInt::operator==(uint64_t Val) const {
506 if (isSingleWord())
507 return VAL == Val;
Reid Spencer54362ca2007-02-20 23:40:25 +0000508
509 uint32_t n = getActiveBits();
510 if (n <= APINT_BITS_PER_WORD)
511 return pVal[0] == Val;
512 else
513 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000514}
515
Reid Spencere81d2da2007-02-16 22:36:51 +0000516/// @brief Unsigned less than comparison
517bool APInt::ult(const APInt& RHS) const {
518 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
519 if (isSingleWord())
520 return VAL < RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000521 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000522 uint32_t n1 = getActiveBits();
523 uint32_t n2 = RHS.getActiveBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000524 if (n1 < n2)
525 return true;
526 else if (n2 < n1)
527 return false;
Reid Spencer443b5702007-02-18 00:44:22 +0000528 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
Reid Spencere81d2da2007-02-16 22:36:51 +0000529 return pVal[0] < RHS.pVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000530 for (int i = whichWord(n1 - 1); i >= 0; --i) {
531 if (pVal[i] > RHS.pVal[i]) return false;
532 else if (pVal[i] < RHS.pVal[i]) return true;
533 }
534 }
535 return false;
536}
537
Reid Spencere81d2da2007-02-16 22:36:51 +0000538/// @brief Signed less than comparison
539bool APInt::slt(const APInt& RHS) const {
540 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000541 if (isSingleWord()) {
542 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
543 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
544 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000545 }
Reid Spencera58f0582007-02-18 20:09:41 +0000546
547 APInt lhs(*this);
548 APInt rhs(*this);
549 bool lhsNegative = false;
550 bool rhsNegative = false;
551 if (lhs[BitWidth-1]) {
552 lhsNegative = true;
553 lhs.flip();
554 lhs++;
555 }
556 if (rhs[BitWidth-1]) {
557 rhsNegative = true;
558 rhs.flip();
559 rhs++;
560 }
561 if (lhsNegative)
562 if (rhsNegative)
563 return !lhs.ult(rhs);
564 else
565 return true;
566 else if (rhsNegative)
567 return false;
568 else
569 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000570}
571
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000572/// Set the given bit to 1 whose poition is given as "bitPosition".
573/// @brief Set a given bit to 1.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000574APInt& APInt::set(uint32_t bitPosition) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000575 if (isSingleWord()) VAL |= maskBit(bitPosition);
576 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
577 return *this;
578}
579
580/// @brief Set every bit to 1.
581APInt& APInt::set() {
Reid Spencer443b5702007-02-18 00:44:22 +0000582 if (isSingleWord())
583 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
Zhou Shengb04973e2007-02-15 06:36:31 +0000584 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000585 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000586 pVal[i] = -1ULL;
Reid Spencer443b5702007-02-18 00:44:22 +0000587 pVal[getNumWords() - 1] = ~0ULL >>
588 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
Zhou Shengb04973e2007-02-15 06:36:31 +0000589 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000590 return *this;
591}
592
593/// Set the given bit to 0 whose position is given as "bitPosition".
594/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000595APInt& APInt::clear(uint32_t bitPosition) {
596 if (isSingleWord())
597 VAL &= ~maskBit(bitPosition);
598 else
599 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000600 return *this;
601}
602
603/// @brief Set every bit to 0.
604APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000605 if (isSingleWord())
606 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000607 else
Reid Spencera58f0582007-02-18 20:09:41 +0000608 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000609 return *this;
610}
611
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000612/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
613/// this APInt.
614APInt APInt::operator~() const {
615 APInt API(*this);
616 API.flip();
617 return API;
618}
619
620/// @brief Toggle every bit to its opposite value.
621APInt& APInt::flip() {
Reid Spencer443b5702007-02-18 00:44:22 +0000622 if (isSingleWord()) VAL = (~(VAL <<
623 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000624 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000625 uint32_t i = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000626 for (; i < getNumWords() - 1; ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000627 pVal[i] = ~pVal[i];
Reid Spenceraf0e9562007-02-18 18:38:44 +0000628 uint32_t offset =
Reid Spencer443b5702007-02-18 00:44:22 +0000629 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000630 pVal[i] = (~(pVal[i] << offset)) >> offset;
631 }
632 return *this;
633}
634
635/// Toggle a given bit to its opposite value whose position is given
636/// as "bitPosition".
637/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000638APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000639 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000640 if ((*this)[bitPosition]) clear(bitPosition);
641 else set(bitPosition);
642 return *this;
643}
644
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000645/// getMaxValue - This function returns the largest value
646/// for an APInt of the specified bit-width and if isSign == true,
647/// it should be largest signed value, otherwise unsigned value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000648APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000649 APInt Result(numBits, 0);
650 Result.set();
651 if (isSign)
652 Result.clear(numBits - 1);
653 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000654}
655
656/// getMinValue - This function returns the smallest value for
657/// an APInt of the given bit-width and if isSign == true,
658/// it should be smallest signed value, otherwise zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000659APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000660 APInt Result(numBits, 0);
661 if (isSign)
662 Result.set(numBits - 1);
663 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000664}
665
666/// getAllOnesValue - This function returns an all-ones value for
667/// an APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000668APInt APInt::getAllOnesValue(uint32_t numBits) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000669 return getMaxValue(numBits, false);
670}
671
672/// getNullValue - This function creates an '0' value for an
673/// APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000674APInt APInt::getNullValue(uint32_t numBits) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000675 return getMinValue(numBits, false);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000676}
677
678/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000679APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000680 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000681}
682
683/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000684APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000685 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
686 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000687}
688
Reid Spencere81d2da2007-02-16 22:36:51 +0000689bool APInt::isPowerOf2() const {
690 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
691}
692
693/// countLeadingZeros - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000694/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000695/// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000696/// the number of zeros from the most significant bit to the first one bit.
697/// @returns numWord() * 64 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000698uint32_t APInt::countLeadingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000699 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000700 return CountLeadingZeros_64(VAL) - (APINT_BITS_PER_WORD - BitWidth);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000701 uint32_t Count = 0;
702 for (uint32_t i = getNumWords(); i > 0u; --i) {
703 uint32_t tmp = CountLeadingZeros_64(pVal[i-1]);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000704 Count += tmp;
Reid Spencer443b5702007-02-18 00:44:22 +0000705 if (tmp != APINT_BITS_PER_WORD)
706 if (i == getNumWords())
707 Count -= (APINT_BITS_PER_WORD - whichBit(BitWidth));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000708 break;
709 }
710 return Count;
711}
712
Reid Spencere81d2da2007-02-16 22:36:51 +0000713/// countTrailingZeros - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000714/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000715/// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000716/// the number of zeros from the least significant bit to the first one bit.
717/// @returns numWord() * 64 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000718uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000719 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000720 return CountTrailingZeros_64(VAL);
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000721 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
Reid Spencere81d2da2007-02-16 22:36:51 +0000722 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000723}
724
Reid Spencere81d2da2007-02-16 22:36:51 +0000725/// countPopulation - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000726/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000727/// countPopulation_{32, 64}. It counts the number of set bits in a value.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000728/// @returns 0 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000729uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000730 if (isSingleWord())
731 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000732 uint32_t Count = 0;
733 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000734 Count += CountPopulation_64(pVal[i]);
735 return Count;
736}
737
738
Reid Spencere81d2da2007-02-16 22:36:51 +0000739/// byteSwap - This function returns a byte-swapped representation of the
Zhou Shengff4304f2007-02-09 07:48:24 +0000740/// this APInt.
Reid Spencere81d2da2007-02-16 22:36:51 +0000741APInt APInt::byteSwap() const {
742 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
743 if (BitWidth == 16)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000744 return APInt(BitWidth, ByteSwap_16(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000745 else if (BitWidth == 32)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000746 return APInt(BitWidth, ByteSwap_32(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000747 else if (BitWidth == 48) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000748 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
749 Tmp1 = ByteSwap_32(Tmp1);
750 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
751 Tmp2 = ByteSwap_16(Tmp2);
752 return
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000753 APInt(BitWidth,
754 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
Reid Spencere81d2da2007-02-16 22:36:51 +0000755 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000756 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000757 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000758 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000759 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000760 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000761 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000762 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
763 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000764 }
765 return Result;
766 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000767}
768
769/// GreatestCommonDivisor - This function returns the greatest common
770/// divisor of the two APInt values using Enclid's algorithm.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000771APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
772 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000773 APInt A = API1, B = API2;
774 while (!!B) {
775 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000776 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000777 A = T;
778 }
779 return A;
780}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000781
Zhou Shengd93f00c2007-02-12 20:02:55 +0000782/// DoubleRoundToAPInt - This function convert a double value to
783/// a APInt value.
Reid Spencere81d2da2007-02-16 22:36:51 +0000784APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000785 union {
786 double D;
787 uint64_t I;
788 } T;
789 T.D = Double;
790 bool isNeg = T.I >> 63;
791 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
792 if (exp < 0)
Reid Spencere81d2da2007-02-16 22:36:51 +0000793 return APInt(64ull, 0u);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000794 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
795 if (exp < 52)
Reid Spencere81d2da2007-02-16 22:36:51 +0000796 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
797 APInt(64u, mantissa >> (52 - exp));
798 APInt Tmp(exp + 1, mantissa);
799 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000800 return isNeg ? -Tmp : Tmp;
801}
802
Reid Spencerdb3faa62007-02-13 22:41:58 +0000803/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000804/// The layout for double is as following (IEEE Standard 754):
805/// --------------------------------------
806/// | Sign Exponent Fraction Bias |
807/// |-------------------------------------- |
808/// | 1[63] 11[62-52] 52[51-00] 1023 |
809/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000810double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000811
812 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000813 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
814 if (isSigned) {
815 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
816 return double(sext);
817 } else
818 return double(VAL);
819 }
820
Reid Spencer9c0696f2007-02-20 08:51:03 +0000821 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000822 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000823
824 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000825 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000826
827 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000828 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000829
Reid Spencer9c0696f2007-02-20 08:51:03 +0000830 // The exponent (without bias normalization) is just the number of bits
831 // we are using. Note that the sign bit is gone since we constructed the
832 // absolute value.
833 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000834
Reid Spencer9c0696f2007-02-20 08:51:03 +0000835 // Return infinity for exponent overflow
836 if (exp > 1023) {
837 if (!isSigned || !isNeg)
Reid Spencer61eb1802007-02-20 20:42:10 +0000838 return double(1.0E300 * 1.0E300); // positive infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000839 else
Reid Spencer61eb1802007-02-20 20:42:10 +0000840 return double(-1.0E300 * 1.0E300); // negative infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000841 }
842 exp += 1023; // Increment for 1023 bias
843
844 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
845 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000846 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000847 unsigned hiWord = whichWord(n-1);
848 if (hiWord == 0) {
849 mantissa = Tmp.pVal[0];
850 if (n > 52)
851 mantissa >>= n - 52; // shift down, we want the top 52 bits.
852 } else {
853 assert(hiWord > 0 && "huh?");
854 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
855 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
856 mantissa = hibits | lobits;
857 }
858
Zhou Shengd93f00c2007-02-12 20:02:55 +0000859 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000860 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000861 union {
862 double D;
863 uint64_t I;
864 } T;
865 T.I = sign | (exp << 52) | mantissa;
866 return T.D;
867}
868
Reid Spencere81d2da2007-02-16 22:36:51 +0000869// Truncate to new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000870void APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000871 assert(width < BitWidth && "Invalid APInt Truncate request");
872}
873
874// Sign extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000875void APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000876 assert(width > BitWidth && "Invalid APInt SignExtend request");
877}
878
879// Zero extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000880void APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000881 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
882}
883
Zhou Shengff4304f2007-02-09 07:48:24 +0000884/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000885/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000886APInt APInt::ashr(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000887 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000888 if (API.isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000889 API.VAL =
890 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
891 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
892 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
Zhou Sheng0b706b12007-02-08 14:35:19 +0000893 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000894 if (shiftAmt >= API.BitWidth) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000895 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
Reid Spencera58f0582007-02-18 20:09:41 +0000896 (API.getNumWords()-1) * APINT_WORD_SIZE);
Reid Spencer443b5702007-02-18 00:44:22 +0000897 API.pVal[API.getNumWords() - 1] =
898 ~uint64_t(0UL) >>
899 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000900 } else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000901 uint32_t i = 0;
Reid Spencere81d2da2007-02-16 22:36:51 +0000902 for (; i < API.BitWidth - shiftAmt; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000903 if (API[i+shiftAmt])
904 API.set(i);
905 else
906 API.clear(i);
Reid Spencere81d2da2007-02-16 22:36:51 +0000907 for (; i < API.BitWidth; ++i)
908 if (API[API.BitWidth-1])
Zhou Shengb04973e2007-02-15 06:36:31 +0000909 API.set(i);
910 else API.clear(i);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000911 }
912 }
913 return API;
914}
915
Zhou Shengff4304f2007-02-09 07:48:24 +0000916/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000917/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000918APInt APInt::lshr(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000919 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000920 if (API.isSingleWord())
921 API.VAL >>= shiftAmt;
922 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000923 if (shiftAmt >= API.BitWidth)
Reid Spencera58f0582007-02-18 20:09:41 +0000924 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000925 uint32_t i = 0;
Reid Spencere81d2da2007-02-16 22:36:51 +0000926 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000927 if (API[i+shiftAmt]) API.set(i);
928 else API.clear(i);
Reid Spencere81d2da2007-02-16 22:36:51 +0000929 for (; i < API.BitWidth; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000930 API.clear(i);
931 }
932 return API;
933}
934
Zhou Shengff4304f2007-02-09 07:48:24 +0000935/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000936/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000937APInt APInt::shl(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000938 APInt API(*this);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000939 if (API.isSingleWord())
940 API.VAL <<= shiftAmt;
Reid Spencere81d2da2007-02-16 22:36:51 +0000941 else if (shiftAmt >= API.BitWidth)
Reid Spencera58f0582007-02-18 20:09:41 +0000942 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000943 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000944 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
945 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
Zhou Shengd93f00c2007-02-12 20:02:55 +0000946 API.pVal[i] = API.pVal[i-offset];
Reid Spencera58f0582007-02-18 20:09:41 +0000947 memset(API.pVal, 0, offset * APINT_WORD_SIZE);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000948 }
Reid Spencer443b5702007-02-18 00:44:22 +0000949 shiftAmt %= APINT_BITS_PER_WORD;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000950 uint32_t i;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000951 for (i = API.getNumWords() - 1; i > 0; --i)
952 API.pVal[i] = (API.pVal[i] << shiftAmt) |
Reid Spencer443b5702007-02-18 00:44:22 +0000953 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
Zhou Shengd93f00c2007-02-12 20:02:55 +0000954 API.pVal[i] <<= shiftAmt;
Zhou Sheng0b706b12007-02-08 14:35:19 +0000955 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000956 API.clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +0000957 return API;
958}
959
Reid Spencer9c0696f2007-02-20 08:51:03 +0000960#if 0
Reid Spencer5e0a8512007-02-17 03:16:00 +0000961/// subMul - This function substracts x[len-1:0] * y from
962/// dest[offset+len-1:offset], and returns the most significant
963/// word of the product, minus the borrow-out from the subtraction.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000964static uint32_t subMul(uint32_t dest[], uint32_t offset,
965 uint32_t x[], uint32_t len, uint32_t y) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000966 uint64_t yl = (uint64_t) y & 0xffffffffL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000967 uint32_t carry = 0;
968 uint32_t j = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000969 do {
Reid Spencerc72f2802007-02-17 22:38:07 +0000970 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000971 uint32_t prod_low = (uint32_t) prod;
972 uint32_t prod_high = (uint32_t) (prod >> 32);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000973 prod_low += carry;
974 carry = (prod_low < carry ? 1 : 0) + prod_high;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000975 uint32_t x_j = dest[offset+j];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000976 prod_low = x_j - prod_low;
977 if (prod_low > x_j) ++carry;
978 dest[offset+j] = prod_low;
979 } while (++j < len);
980 return carry;
981}
982
983/// unitDiv - This function divides N by D,
984/// and returns (remainder << 32) | quotient.
985/// Assumes (N >> 32) < D.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000986static uint64_t unitDiv(uint64_t N, uint32_t D) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000987 uint64_t q, r; // q: quotient, r: remainder.
988 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
989 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
990 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
991 q = N / D;
992 r = N % D;
993 }
994 else {
995 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
996 uint64_t c = N - ((uint64_t) D << 31);
997 // Divide (c1*2^32 + c0) by d
998 q = c / D;
999 r = c % D;
1000 // Add 2^31 to quotient
1001 q += 1 << 31;
1002 }
1003
1004 return (r << 32) | (q & 0xFFFFFFFFl);
1005}
1006
Reid Spencer9c0696f2007-02-20 08:51:03 +00001007#endif
1008
Reid Spencer5e0a8512007-02-17 03:16:00 +00001009/// div - This is basically Knuth's formulation of the classical algorithm.
1010/// Correspondance with Knuth's notation:
1011/// Knuth's u[0:m+n] == zds[nx:0].
1012/// Knuth's v[1:n] == y[ny-1:0]
1013/// Knuth's n == ny.
1014/// Knuth's m == nx-ny.
1015/// Our nx == Knuth's m+n.
1016/// Could be re-implemented using gmp's mpn_divrem:
1017/// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
Reid Spencer9c0696f2007-02-20 08:51:03 +00001018
1019/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1020/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1021/// variables here have the same names as in the algorithm. Comments explain
1022/// the algorithm and any deviation from it.
1023static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1024 uint32_t m, uint32_t n) {
1025 assert(u && "Must provide dividend");
1026 assert(v && "Must provide divisor");
1027 assert(q && "Must provide quotient");
1028 assert(n>1 && "n must be > 1");
1029
1030 // Knuth uses the value b as the base of the number system. In our case b
1031 // is 2^31 so we just set it to -1u.
1032 uint64_t b = uint64_t(1) << 32;
1033
1034 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1035 // u and v by d. Note that we have taken Knuth's advice here to use a power
1036 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1037 // 2 allows us to shift instead of multiply and it is easy to determine the
1038 // shift amount from the leading zeros. We are basically normalizing the u
1039 // and v so that its high bits are shifted to the top of v's range without
1040 // overflow. Note that this can require an extra word in u so that u must
1041 // be of length m+n+1.
1042 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1043 uint32_t v_carry = 0;
1044 uint32_t u_carry = 0;
1045 if (shift) {
1046 for (uint32_t i = 0; i < m+n; ++i) {
1047 uint32_t u_tmp = u[i] >> (32 - shift);
1048 u[i] = (u[i] << shift) | u_carry;
1049 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001050 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001051 for (uint32_t i = 0; i < n; ++i) {
1052 uint32_t v_tmp = v[i] >> (32 - shift);
1053 v[i] = (v[i] << shift) | v_carry;
1054 v_carry = v_tmp;
1055 }
1056 }
1057 u[m+n] = u_carry;
1058
1059 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1060 int j = m;
1061 do {
1062 // D3. [Calculate q'.].
1063 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1064 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1065 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1066 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1067 // on v[n-2] determines at high speed most of the cases in which the trial
1068 // value qp is one too large, and it eliminates all cases where qp is two
1069 // too large.
1070 uint64_t qp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) / v[n-1];
1071 uint64_t rp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) % v[n-1];
1072 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1073 qp--;
1074 rp += v[n-1];
1075 }
1076 if (rp < b)
1077 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1078 qp--;
1079 rp += v[n-1];
1080 }
1081
1082 // D4. [Multiply and subtract.] Replace u with u - q*v (for each word).
1083 uint32_t borrow = 0;
1084 for (uint32_t i = 0; i < n; i++) {
1085 uint32_t save = u[j+i];
1086 u[j+i] = uint64_t(u[j+i]) - (qp * v[i]) - borrow;
1087 if (u[j+i] > save) {
1088 borrow = 1;
1089 u[j+i+1] += b;
1090 } else {
1091 borrow = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001092 }
1093 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001094 if (borrow)
1095 u[j+n] += 1;
1096
1097 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1098 // negative, go to step D6; otherwise go on to step D7.
1099 q[j] = qp;
1100 if (borrow) {
1101 // D6. [Add back]. The probability that this step is necessary is very
1102 // small, on the order of only 2/b. Make sure that test data accounts for
1103 // this possibility. Decreate qj by 1 and add v[...] to u[...]. A carry
1104 // will occur to the left of u[j+n], and it should be ignored since it
1105 // cancels with the borrow that occurred in D4.
1106 uint32_t carry = 0;
1107 for (uint32_t i = 0; i < n; i++) {
1108 uint32_t save = u[j+i];
1109 u[j+i] += v[i] + carry;
1110 carry = u[j+i] < save;
1111 }
1112 }
1113
1114 // D7. [Loop on j.] Decreate j by one. Now if j >= 0, go back to D3.
1115 j--;
1116 } while (j >= 0);
1117
1118 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1119 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1120 // compute the remainder (urem uses this).
1121 if (r) {
1122 // The value d is expressed by the "shift" value above since we avoided
1123 // multiplication by d by using a shift left. So, all we have to do is
1124 // shift right here. In order to mak
1125 uint32_t mask = ~0u >> (32 - shift);
1126 uint32_t carry = 0;
1127 for (int i = n-1; i >= 0; i--) {
1128 uint32_t save = u[i] & mask;
1129 r[i] = (u[i] >> shift) | carry;
1130 carry = save;
1131 }
1132 }
1133}
1134
1135// This function makes calling KnuthDiv a little more convenient. It uses
1136// APInt parameters instead of uint32_t* parameters. It can also divide APInt
1137// values of different widths.
1138void APInt::divide(const APInt LHS, uint32_t lhsWords,
1139 const APInt &RHS, uint32_t rhsWords,
1140 APInt *Quotient, APInt *Remainder)
1141{
1142 assert(lhsWords >= rhsWords && "Fractional result");
1143
1144 // First, compose the values into an array of 32-bit words instead of
1145 // 64-bit words. This is a necessity of both the "short division" algorithm
1146 // and the the Knuth "classical algorithm" which requires there to be native
1147 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1148 // can't use 64-bit operands here because we don't have native results of
1149 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1150 // work on large-endian machines.
1151 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1152 uint32_t n = rhsWords * 2;
1153 uint32_t m = (lhsWords * 2) - n;
1154 // FIXME: allocate space on stack if m and n are sufficiently small.
1155 uint32_t *U = new uint32_t[m + n + 1];
1156 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1157 for (unsigned i = 0; i < lhsWords; ++i) {
1158 uint64_t tmp = (lhsWords == 1 ? LHS.VAL : LHS.pVal[i]);
1159 U[i * 2] = tmp & mask;
1160 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1161 }
1162 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1163
1164 uint32_t *V = new uint32_t[n];
1165 memset(V, 0, (n)*sizeof(uint32_t));
1166 for (unsigned i = 0; i < rhsWords; ++i) {
1167 uint64_t tmp = (rhsWords == 1 ? RHS.VAL : RHS.pVal[i]);
1168 V[i * 2] = tmp & mask;
1169 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1170 }
1171
1172 // Set up the quotient and remainder
1173 uint32_t *Q = new uint32_t[m+n];
1174 memset(Q, 0, (m+n) * sizeof(uint32_t));
1175 uint32_t *R = 0;
1176 if (Remainder) {
1177 R = new uint32_t[n];
1178 memset(R, 0, n * sizeof(uint32_t));
1179 }
1180
1181 // Now, adjust m and n for the Knuth division. n is the number of words in
1182 // the divisor. m is the number of words by which the dividend exceeds the
1183 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1184 // contain any zero words or the Knuth algorithm fails.
1185 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1186 n--;
1187 m++;
1188 }
1189 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1190 m--;
1191
1192 // If we're left with only a single word for the divisor, Knuth doesn't work
1193 // so we implement the short division algorithm here. This is much simpler
1194 // and faster because we are certain that we can divide a 64-bit quantity
1195 // by a 32-bit quantity at hardware speed and short division is simply a
1196 // series of such operations. This is just like doing short division but we
1197 // are using base 2^32 instead of base 10.
1198 assert(n != 0 && "Divide by zero?");
1199 if (n == 1) {
1200 uint32_t divisor = V[0];
1201 uint32_t remainder = 0;
1202 for (int i = m+n-1; i >= 0; i--) {
1203 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1204 if (partial_dividend == 0) {
1205 Q[i] = 0;
1206 remainder = 0;
1207 } else if (partial_dividend < divisor) {
1208 Q[i] = 0;
1209 remainder = partial_dividend;
1210 } else if (partial_dividend == divisor) {
1211 Q[i] = 1;
1212 remainder = 0;
1213 } else {
1214 Q[i] = partial_dividend / divisor;
1215 remainder = partial_dividend - (Q[i] * divisor);
1216 }
1217 }
1218 if (R)
1219 R[0] = remainder;
1220 } else {
1221 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1222 // case n > 1.
1223 KnuthDiv(U, V, Q, R, m, n);
1224 }
1225
1226 // If the caller wants the quotient
1227 if (Quotient) {
1228 // Set up the Quotient value's memory.
1229 if (Quotient->BitWidth != LHS.BitWidth) {
1230 if (Quotient->isSingleWord())
1231 Quotient->VAL = 0;
1232 else
1233 delete Quotient->pVal;
1234 Quotient->BitWidth = LHS.BitWidth;
1235 if (!Quotient->isSingleWord())
1236 Quotient->pVal = getClearedMemory(lhsWords);
1237 } else
1238 Quotient->clear();
1239
1240 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1241 // order words.
1242 if (lhsWords == 1) {
1243 uint64_t tmp =
1244 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1245 if (Quotient->isSingleWord())
1246 Quotient->VAL = tmp;
1247 else
1248 Quotient->pVal[0] = tmp;
1249 } else {
1250 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1251 for (unsigned i = 0; i < lhsWords; ++i)
1252 Quotient->pVal[i] =
1253 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1254 }
1255 }
1256
1257 // If the caller wants the remainder
1258 if (Remainder) {
1259 // Set up the Remainder value's memory.
1260 if (Remainder->BitWidth != RHS.BitWidth) {
1261 if (Remainder->isSingleWord())
1262 Remainder->VAL = 0;
1263 else
1264 delete Remainder->pVal;
1265 Remainder->BitWidth = RHS.BitWidth;
1266 if (!Remainder->isSingleWord())
1267 Remainder->pVal = getClearedMemory(rhsWords);
1268 } else
1269 Remainder->clear();
1270
1271 // The remainder is in R. Reconstitute the remainder into Remainder's low
1272 // order words.
1273 if (rhsWords == 1) {
1274 uint64_t tmp =
1275 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1276 if (Remainder->isSingleWord())
1277 Remainder->VAL = tmp;
1278 else
1279 Remainder->pVal[0] = tmp;
1280 } else {
1281 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1282 for (unsigned i = 0; i < rhsWords; ++i)
1283 Remainder->pVal[i] =
1284 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1285 }
1286 }
1287
1288 // Clean up the memory we allocated.
1289 delete [] U;
1290 delete [] V;
1291 delete [] Q;
1292 delete [] R;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001293}
1294
Zhou Shengff4304f2007-02-09 07:48:24 +00001295/// Unsigned divide this APInt by APInt RHS.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001296/// @brief Unsigned division function for APInt.
Reid Spencere81d2da2007-02-16 22:36:51 +00001297APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001298 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001299
1300 // First, deal with the easy case
1301 if (isSingleWord()) {
1302 assert(RHS.VAL != 0 && "Divide by zero?");
1303 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001304 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001305
Reid Spencer71bd08f2007-02-17 02:07:07 +00001306 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001307 uint32_t rhsBits = RHS.getActiveBits();
1308 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001309 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001310 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001311 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001312
Reid Spencer9c0696f2007-02-20 08:51:03 +00001313 // Make a temporary to hold the result
1314 APInt Result(*this);
1315
Reid Spencer71bd08f2007-02-17 02:07:07 +00001316 // Deal with some degenerate cases
1317 if (!lhsWords)
1318 return Result; // 0 / X == 0
Reid Spencer9c0696f2007-02-20 08:51:03 +00001319 else if (lhsWords < rhsWords || Result.ult(RHS)) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001320 // X / Y with X < Y == 0
Reid Spencera58f0582007-02-18 20:09:41 +00001321 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001322 return Result;
1323 } else if (Result == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001324 // X / X == 1
Reid Spencera58f0582007-02-18 20:09:41 +00001325 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001326 Result.pVal[0] = 1;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001327 return Result;
1328 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001329 // All high words are zero, just use native divide
1330 Result.pVal[0] /= RHS.pVal[0];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001331 return Result;
Reid Spencer71bd08f2007-02-17 02:07:07 +00001332 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001333
1334 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1335 APInt Quotient(1,0); // to hold result.
1336 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1337 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001338}
1339
1340/// Unsigned remainder operation on APInt.
1341/// @brief Function for unsigned remainder operation.
Reid Spencere81d2da2007-02-16 22:36:51 +00001342APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001343 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001344 if (isSingleWord()) {
1345 assert(RHS.VAL != 0 && "Remainder by zero?");
1346 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001347 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001348
1349 // Make a temporary to hold the result
1350 APInt Result(*this);
1351
1352 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001353 uint32_t rhsBits = RHS.getActiveBits();
1354 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001355 assert(rhsWords && "Performing remainder operation by zero ???");
1356
1357 // Get some facts about the LHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001358 uint32_t lhsBits = Result.getActiveBits();
1359 uint32_t lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001360
1361 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001362 if (lhsWords == 0) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001363 // 0 % Y == 0
Reid Spencera58f0582007-02-18 20:09:41 +00001364 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001365 return Result;
1366 } else if (lhsWords < rhsWords || Result.ult(RHS)) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001367 // X % Y == X iff X < Y
1368 return Result;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001369 } else if (Result == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001370 // X % X == 0;
Reid Spencera58f0582007-02-18 20:09:41 +00001371 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001372 return Result;
1373 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001374 // All high words are zero, just use native remainder
1375 Result.pVal[0] %= RHS.pVal[0];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001376 return Result;
Reid Spencer71bd08f2007-02-17 02:07:07 +00001377 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001378
1379 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1380 APInt Remainder(1,0);
1381 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1382 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001383}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001384
1385/// @brief Converts a char array into an integer.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001386void APInt::fromString(uint32_t numbits, const char *StrStart, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001387 uint8_t radix) {
1388 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1389 "Radix should be 2, 8, 10, or 16!");
1390 assert(StrStart && "String is null?");
Reid Spenceraf0e9562007-02-18 18:38:44 +00001391 uint32_t size = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001392 // If the radix is a power of 2, read the input
1393 // from most significant to least significant.
1394 if ((radix & (radix - 1)) == 0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +00001395 uint32_t nextBitPos = 0;
1396 uint32_t bits_per_digit = radix / 8 + 2;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001397 uint64_t resDigit = 0;
1398 BitWidth = slen * bits_per_digit;
1399 if (getNumWords() > 1)
Reid Spenceraf0e9562007-02-18 18:38:44 +00001400 pVal = getMemory(getNumWords());
Reid Spencer5e0a8512007-02-17 03:16:00 +00001401 for (int i = slen - 1; i >= 0; --i) {
Reid Spencer443b5702007-02-18 00:44:22 +00001402 uint64_t digit = StrStart[i] - '0';
Reid Spencer5e0a8512007-02-17 03:16:00 +00001403 resDigit |= digit << nextBitPos;
1404 nextBitPos += bits_per_digit;
Reid Spencer443b5702007-02-18 00:44:22 +00001405 if (nextBitPos >= APINT_BITS_PER_WORD) {
Reid Spencer5e0a8512007-02-17 03:16:00 +00001406 if (isSingleWord()) {
1407 VAL = resDigit;
1408 break;
1409 }
1410 pVal[size++] = resDigit;
Reid Spencer443b5702007-02-18 00:44:22 +00001411 nextBitPos -= APINT_BITS_PER_WORD;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001412 resDigit = digit >> (bits_per_digit - nextBitPos);
1413 }
1414 }
1415 if (!isSingleWord() && size <= getNumWords())
1416 pVal[size] = resDigit;
1417 } else { // General case. The radix is not a power of 2.
1418 // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
1419 // and its digits number is 20.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001420 const uint32_t chars_per_word = 20;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001421 if (slen < chars_per_word ||
1422 (slen == chars_per_word && // In case the value <= 2^64 - 1
1423 strcmp(StrStart, "18446744073709551615") <= 0)) {
Reid Spencer443b5702007-02-18 00:44:22 +00001424 BitWidth = APINT_BITS_PER_WORD;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001425 VAL = strtoull(StrStart, 0, 10);
1426 } else { // In case the value > 2^64 - 1
Reid Spencer443b5702007-02-18 00:44:22 +00001427 BitWidth = (slen / chars_per_word + 1) * APINT_BITS_PER_WORD;
Reid Spenceraf0e9562007-02-18 18:38:44 +00001428 pVal = getClearedMemory(getNumWords());
1429 uint32_t str_pos = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001430 while (str_pos < slen) {
Reid Spenceraf0e9562007-02-18 18:38:44 +00001431 uint32_t chunk = slen - str_pos;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001432 if (chunk > chars_per_word - 1)
1433 chunk = chars_per_word - 1;
Reid Spencer443b5702007-02-18 00:44:22 +00001434 uint64_t resDigit = StrStart[str_pos++] - '0';
Reid Spencer5e0a8512007-02-17 03:16:00 +00001435 uint64_t big_base = radix;
1436 while (--chunk > 0) {
Reid Spencer443b5702007-02-18 00:44:22 +00001437 resDigit = resDigit * radix + StrStart[str_pos++] - '0';
Reid Spencer5e0a8512007-02-17 03:16:00 +00001438 big_base *= radix;
1439 }
1440
1441 uint64_t carry;
1442 if (!size)
1443 carry = resDigit;
1444 else {
1445 carry = mul_1(pVal, pVal, size, big_base);
1446 carry += add_1(pVal, pVal, size, resDigit);
1447 }
1448
1449 if (carry) pVal[size++] = carry;
1450 }
1451 }
1452 }
1453}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001454
1455/// to_string - This function translates the APInt into a string.
1456std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1457 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1458 "Radix should be 2, 8, 10, or 16!");
1459 static const char *digits[] = {
1460 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1461 };
1462 std::string result;
1463 uint32_t bits_used = getActiveBits();
1464 if (isSingleWord()) {
1465 char buf[65];
1466 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1467 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1468 if (format) {
1469 if (wantSigned) {
1470 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1471 (APINT_BITS_PER_WORD-BitWidth);
1472 sprintf(buf, format, sextVal);
1473 } else
1474 sprintf(buf, format, VAL);
1475 } else {
1476 memset(buf, 0, 65);
1477 uint64_t v = VAL;
1478 while (bits_used) {
1479 uint32_t bit = v & 1;
1480 bits_used--;
1481 buf[bits_used] = digits[bit][0];
1482 v >>=1;
1483 }
1484 }
1485 result = buf;
1486 return result;
1487 }
1488
1489 if (radix != 10) {
1490 uint64_t mask = radix - 1;
1491 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1492 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1493 for (uint32_t i = 0; i < getNumWords(); ++i) {
1494 uint64_t value = pVal[i];
1495 for (uint32_t j = 0; j < nibbles; ++j) {
1496 result.insert(0, digits[ value & mask ]);
1497 value >>= shift;
1498 }
1499 }
1500 return result;
1501 }
1502
1503 APInt tmp(*this);
1504 APInt divisor(4, radix);
1505 APInt zero(tmp.getBitWidth(), 0);
1506 size_t insert_at = 0;
1507 if (wantSigned && tmp[BitWidth-1]) {
1508 // They want to print the signed version and it is a negative value
1509 // Flip the bits and add one to turn it into the equivalent positive
1510 // value and put a '-' in the result.
1511 tmp.flip();
1512 tmp++;
1513 result = "-";
1514 insert_at = 1;
1515 }
1516 if (tmp == 0)
1517 result = "0";
1518 else while (tmp.ne(zero)) {
1519 APInt APdigit(1,0);
1520 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), 0, &APdigit);
1521 uint32_t digit = APdigit.getValue();
1522 assert(digit < radix && "urem failed");
1523 result.insert(insert_at,digits[digit]);
1524 APInt tmp2(tmp.getBitWidth(), 0);
1525 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2, 0);
1526 tmp = tmp2;
1527 }
1528
1529 return result;
1530}
1531