blob: cbd2b34703e71aebbdebc3282015303eb1037546 [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"
Chris Lattner6ad4c142007-02-06 05:38:37 +000016
Zhou Shengfd43dcf2007-02-06 03:00:16 +000017#include "llvm/DerivedTypes.h"
18#include "llvm/Support/MathExtras.h"
Zhou Shenga3832fd2007-02-07 06:14:53 +000019#include <cstring>
Zhou Shengfd43dcf2007-02-06 03:00:16 +000020#include <cstdlib>
21using namespace llvm;
22
Zhou Sheng353815d2007-02-06 06:04:53 +000023/// mul_1 - This function performs the multiplication operation on a
24/// large integer (represented as an integer array) and a uint64_t integer.
25/// @returns the carry of the multiplication.
26static uint64_t mul_1(uint64_t dest[], uint64_t x[],
27 unsigned len, uint64_t y) {
28 // Split y into high 32-bit part and low 32-bit part.
29 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
30 uint64_t carry = 0, lx, hx;
31 for (unsigned i = 0; i < len; ++i) {
32 lx = x[i] & 0xffffffffULL;
33 hx = x[i] >> 32;
34 // hasCarry - A flag to indicate if has carry.
35 // hasCarry == 0, no carry
36 // hasCarry == 1, has carry
37 // hasCarry == 2, no carry and the calculation result == 0.
38 uint8_t hasCarry = 0;
39 dest[i] = carry + lx * ly;
40 // Determine if the add above introduces carry.
41 hasCarry = (dest[i] < carry) ? 1 : 0;
42 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
43 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
44 // (2^32 - 1) + 2^32 = 2^64.
45 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
46
47 carry += (lx * hy) & 0xffffffffULL;
48 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
49 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
50 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
51 }
52
53 return carry;
54}
55
56/// mul - This function multiplies integer array x[] by integer array y[] and
57/// stores the result into integer array dest[].
58/// Note the array dest[]'s size should no less than xlen + ylen.
59static void mul(uint64_t dest[], uint64_t x[], unsigned xlen,
60 uint64_t y[], unsigned ylen) {
61 dest[xlen] = mul_1(dest, x, xlen, y[0]);
62
63 for (unsigned i = 1; i < ylen; ++i) {
64 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
65 uint64_t carry = 0, lx, hx;
66 for (unsigned j = 0; j < xlen; ++j) {
67 lx = x[j] & 0xffffffffULL;
68 hx = x[j] >> 32;
69 // hasCarry - A flag to indicate if has carry.
70 // hasCarry == 0, no carry
71 // hasCarry == 1, has carry
72 // hasCarry == 2, no carry and the calculation result == 0.
73 uint8_t hasCarry = 0;
74 uint64_t resul = carry + lx * ly;
75 hasCarry = (resul < carry) ? 1 : 0;
76 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
77 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
78
79 carry += (lx * hy) & 0xffffffffULL;
80 resul = (carry << 32) | (resul & 0xffffffffULL);
81 dest[i+j] += resul;
82 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
83 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
84 ((lx * hy) >> 32) + hx * hy;
85 }
86 dest[i+xlen] = carry;
87 }
88}
89
90/// add_1 - This function adds the integer array x[] by integer y and
91/// returns the carry.
92/// @returns the carry of the addition.
93static uint64_t add_1(uint64_t dest[], uint64_t x[],
94 unsigned len, uint64_t y) {
95 uint64_t carry = y;
96
97 for (unsigned i = 0; i < len; ++i) {
98 dest[i] = carry + x[i];
99 carry = (dest[i] < carry) ? 1 : 0;
100 }
101 return carry;
102}
103
104/// add - This function adds the integer array x[] by integer array
105/// y[] and returns the carry.
106static uint64_t add(uint64_t dest[], uint64_t x[],
107 uint64_t y[], unsigned len) {
108 unsigned carry = 0;
109
110 for (unsigned i = 0; i< len; ++i) {
111 carry += x[i];
112 dest[i] = carry + y[i];
113 carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
114 }
115 return carry;
116}
117
118/// sub_1 - This function subtracts the integer array x[] by
119/// integer y and returns the borrow-out carry.
120static uint64_t sub_1(uint64_t x[], unsigned len, uint64_t y) {
121 uint64_t cy = y;
122
123 for (unsigned i = 0; i < len; ++i) {
124 uint64_t X = x[i];
125 x[i] -= cy;
126 if (cy > X)
127 cy = 1;
128 else {
129 cy = 0;
130 break;
131 }
132 }
133
134 return cy;
135}
136
137/// sub - This function subtracts the integer array x[] by
138/// integer array y[], and returns the borrow-out carry.
139static uint64_t sub(uint64_t dest[], uint64_t x[],
140 uint64_t y[], unsigned len) {
141 // Carry indicator.
142 uint64_t cy = 0;
143
144 for (unsigned i = 0; i < len; ++i) {
145 uint64_t Y = y[i], X = x[i];
146 Y += cy;
147
148 cy = Y < cy ? 1 : 0;
149 Y = X - Y;
150 cy += Y > X ? 1 : 0;
151 dest[i] = Y;
152 }
153 return cy;
154}
155
156/// UnitDiv - This function divides N by D,
157/// and returns (remainder << 32) | quotient.
158/// Assumes (N >> 32) < D.
159static uint64_t unitDiv(uint64_t N, unsigned D) {
160 uint64_t q, r; // q: quotient, r: remainder.
161 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
162 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
163 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
164 q = N / D;
165 r = N % D;
166 }
167 else {
168 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
169 uint64_t c = N - ((uint64_t) D << 31);
170 // Divide (c1*2^32 + c0) by d
171 q = c / D;
172 r = c % D;
173 // Add 2^31 to quotient
174 q += 1 << 31;
175 }
176
177 return (r << 32) | (q & 0xFFFFFFFFl);
178}
179
180/// subMul - This function substracts x[len-1:0] * y from
181/// dest[offset+len-1:offset], and returns the most significant
182/// word of the product, minus the borrow-out from the subtraction.
183static unsigned subMul(unsigned dest[], unsigned offset,
184 unsigned x[], unsigned len, unsigned y) {
185 uint64_t yl = (uint64_t) y & 0xffffffffL;
186 unsigned carry = 0;
187 unsigned j = 0;
188 do {
189 uint64_t prod = ((uint64_t) x[j] & 0xffffffffL) * yl;
190 unsigned prod_low = (unsigned) prod;
191 unsigned prod_high = (unsigned) (prod >> 32);
192 prod_low += carry;
193 carry = (prod_low < carry ? 1 : 0) + prod_high;
194 unsigned x_j = dest[offset+j];
195 prod_low = x_j - prod_low;
196 if (prod_low > x_j) ++carry;
197 dest[offset+j] = prod_low;
198 } while (++j < len);
199 return carry;
200}
201
202/// div - This is basically Knuth's formulation of the classical algorithm.
203/// Correspondance with Knuth's notation:
204/// Knuth's u[0:m+n] == zds[nx:0].
205/// Knuth's v[1:n] == y[ny-1:0]
206/// Knuth's n == ny.
207/// Knuth's m == nx-ny.
208/// Our nx == Knuth's m+n.
209/// Could be re-implemented using gmp's mpn_divrem:
210/// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
211static void div(unsigned zds[], unsigned nx, unsigned y[], unsigned ny) {
212 unsigned j = nx;
213 do { // loop over digits of quotient
214 // Knuth's j == our nx-j.
215 // Knuth's u[j:j+n] == our zds[j:j-ny].
216 unsigned qhat; // treated as unsigned
217 if (zds[j] == y[ny-1]) qhat = -1U; // 0xffffffff
218 else {
219 uint64_t w = (((uint64_t)(zds[j])) << 32) +
220 ((uint64_t)zds[j-1] & 0xffffffffL);
221 qhat = (unsigned) unitDiv(w, y[ny-1]);
222 }
223 if (qhat) {
224 unsigned borrow = subMul(zds, j - ny, y, ny, qhat);
225 unsigned save = zds[j];
226 uint64_t num = ((uint64_t)save&0xffffffffL) -
227 ((uint64_t)borrow&0xffffffffL);
228 while (num) {
229 qhat--;
230 uint64_t carry = 0;
231 for (unsigned i = 0; i < ny; i++) {
232 carry += ((uint64_t) zds[j-ny+i] & 0xffffffffL)
233 + ((uint64_t) y[i] & 0xffffffffL);
234 zds[j-ny+i] = (unsigned) carry;
235 carry >>= 32;
236 }
237 zds[j] += carry;
238 num = carry - 1;
239 }
240 }
241 zds[j] = qhat;
242 } while (--j >= ny);
243}
244
245/// lshift - This function shift x[0:len-1] left by shiftAmt bits, and
246/// store the len least significant words of the result in
247/// dest[d_offset:d_offset+len-1]. It returns the bits shifted out from
248/// the most significant digit.
249static uint64_t lshift(uint64_t dest[], unsigned d_offset,
250 uint64_t x[], unsigned len, unsigned shiftAmt) {
251 unsigned count = 64 - shiftAmt;
252 int i = len - 1;
253 uint64_t high_word = x[i], retVal = high_word >> count;
254 ++d_offset;
255 while (--i >= 0) {
256 uint64_t low_word = x[i];
257 dest[d_offset+i] = (high_word << shiftAmt) | (low_word >> count);
258 high_word = low_word;
259 }
260 dest[d_offset+i] = high_word << shiftAmt;
261 return retVal;
262}
263
Zhou Sheng0b706b12007-02-08 14:35:19 +0000264APInt::APInt(uint64_t val, unsigned numBits)
265 : BitsNum(numBits) {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000266 assert(BitsNum >= IntegerType::MIN_INT_BITS && "bitwidth too small");
267 assert(BitsNum <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000268 if (isSingleWord())
Zhou Shenga3832fd2007-02-07 06:14:53 +0000269 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitsNum));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000270 else {
271 // Memory allocation and check if successful.
Zhou Shenga3832fd2007-02-07 06:14:53 +0000272 assert((pVal = new uint64_t[getNumWords()]) &&
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000273 "APInt memory allocation fails!");
Zhou Shenga3832fd2007-02-07 06:14:53 +0000274 memset(pVal, 0, getNumWords() * 8);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000275 pVal[0] = val;
276 }
277}
278
Zhou Sheng0b706b12007-02-08 14:35:19 +0000279APInt::APInt(unsigned numBits, uint64_t bigVal[])
280 : BitsNum(numBits) {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000281 assert(BitsNum >= IntegerType::MIN_INT_BITS && "bitwidth too small");
282 assert(BitsNum <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000283 assert(bigVal && "Null pointer detected!");
284 if (isSingleWord())
Zhou Shenga3832fd2007-02-07 06:14:53 +0000285 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitsNum));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000286 else {
287 // Memory allocation and check if successful.
Zhou Shenga3832fd2007-02-07 06:14:53 +0000288 assert((pVal = new uint64_t[getNumWords()]) &&
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000289 "APInt memory allocation fails!");
290 // Calculate the actual length of bigVal[].
291 unsigned n = sizeof(*bigVal) / sizeof(bigVal[0]);
Zhou Shenga3832fd2007-02-07 06:14:53 +0000292 unsigned maxN = std::max<unsigned>(n, getNumWords());
293 unsigned minN = std::min<unsigned>(n, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000294 memcpy(pVal, bigVal, (minN - 1) * 8);
Zhou Shenga3832fd2007-02-07 06:14:53 +0000295 pVal[minN-1] = bigVal[minN-1] & (~uint64_t(0ULL) >> (64 - BitsNum % 64));
296 if (maxN == getNumWords())
297 memset(pVal+n, 0, (getNumWords() - n) * 8);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000298 }
299}
300
Zhou Shenga3832fd2007-02-07 06:14:53 +0000301/// @brief Create a new APInt by translating the char array represented
302/// integer value.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000303APInt::APInt(const char StrStart[], unsigned slen, uint8_t radix) {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000304 StrToAPInt(StrStart, slen, radix);
305}
306
307/// @brief Create a new APInt by translating the string represented
308/// integer value.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000309APInt::APInt(const std::string& Val, uint8_t radix) {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000310 assert(!Val.empty() && "String empty?");
311 StrToAPInt(Val.c_str(), Val.size(), radix);
312}
313
314/// @brief Converts a char array into an integer.
315void APInt::StrToAPInt(const char *StrStart, unsigned slen, uint8_t radix) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000316 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
317 "Radix should be 2, 8, 10, or 16!");
Zhou Shenga3832fd2007-02-07 06:14:53 +0000318 assert(StrStart && "String empty?");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000319 unsigned size = 0;
320 // If the radix is a power of 2, read the input
321 // from most significant to least significant.
322 if ((radix & (radix - 1)) == 0) {
323 unsigned nextBitPos = 0, bits_per_digit = radix / 8 + 2;
324 uint64_t resDigit = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000325 BitsNum = slen * bits_per_digit;
326 if (getNumWords() > 1)
327 assert((pVal = new uint64_t[getNumWords()]) &&
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000328 "APInt memory allocation fails!");
329 for (int i = slen - 1; i >= 0; --i) {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000330 uint64_t digit = StrStart[i] - 48; // '0' == 48.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000331 resDigit |= digit << nextBitPos;
332 nextBitPos += bits_per_digit;
333 if (nextBitPos >= 64) {
334 if (isSingleWord()) {
335 VAL = resDigit;
336 break;
337 }
338 pVal[size++] = resDigit;
339 nextBitPos -= 64;
340 resDigit = digit >> (bits_per_digit - nextBitPos);
341 }
342 }
Zhou Shenga3832fd2007-02-07 06:14:53 +0000343 if (!isSingleWord() && size <= getNumWords())
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000344 pVal[size] = resDigit;
345 } else { // General case. The radix is not a power of 2.
346 // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
347 // and its digits number is 14.
348 const unsigned chars_per_word = 20;
349 if (slen < chars_per_word ||
Zhou Shenga3832fd2007-02-07 06:14:53 +0000350 (slen == chars_per_word && // In case the value <= 2^64 - 1
351 strcmp(StrStart, "18446744073709551615") <= 0)) {
352 BitsNum = 64;
353 VAL = strtoull(StrStart, 0, 10);
354 } else { // In case the value > 2^64 - 1
355 BitsNum = (slen / chars_per_word + 1) * 64;
356 assert((pVal = new uint64_t[getNumWords()]) &&
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000357 "APInt memory allocation fails!");
Zhou Shenga3832fd2007-02-07 06:14:53 +0000358 memset(pVal, 0, getNumWords() * 8);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000359 unsigned str_pos = 0;
360 while (str_pos < slen) {
361 unsigned chunk = slen - str_pos;
362 if (chunk > chars_per_word - 1)
363 chunk = chars_per_word - 1;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000364 uint64_t resDigit = StrStart[str_pos++] - 48; // 48 == '0'.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000365 uint64_t big_base = radix;
366 while (--chunk > 0) {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000367 resDigit = resDigit * radix + StrStart[str_pos++] - 48;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000368 big_base *= radix;
369 }
370
371 uint64_t carry;
372 if (!size)
373 carry = resDigit;
374 else {
375 carry = mul_1(pVal, pVal, size, big_base);
376 carry += add_1(pVal, pVal, size, resDigit);
377 }
378
379 if (carry) pVal[size++] = carry;
380 }
381 }
382 }
383}
384
385APInt::APInt(const APInt& APIVal)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000386 : BitsNum(APIVal.BitsNum) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000387 if (isSingleWord()) VAL = APIVal.VAL;
388 else {
389 // Memory allocation and check if successful.
Zhou Shenga3832fd2007-02-07 06:14:53 +0000390 assert((pVal = new uint64_t[getNumWords()]) &&
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000391 "APInt memory allocation fails!");
Zhou Shenga3832fd2007-02-07 06:14:53 +0000392 memcpy(pVal, APIVal.pVal, getNumWords() * 8);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000393 }
394}
395
396APInt::~APInt() {
397 if (!isSingleWord() && pVal) delete[] pVal;
398}
399
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000400/// @brief Copy assignment operator. Create a new object from the given
401/// APInt one by initialization.
402APInt& APInt::operator=(const APInt& RHS) {
403 if (isSingleWord()) VAL = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
404 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000405 unsigned minN = std::min(getNumWords(), RHS.getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000406 memcpy(pVal, RHS.isSingleWord() ? &RHS.VAL : RHS.pVal, minN * 8);
Zhou Shenga3832fd2007-02-07 06:14:53 +0000407 if (getNumWords() != minN)
408 memset(pVal + minN, 0, (getNumWords() - minN) * 8);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000409 }
410 return *this;
411}
412
413/// @brief Assignment operator. Assigns a common case integer value to
414/// the APInt.
415APInt& APInt::operator=(uint64_t RHS) {
416 if (isSingleWord()) VAL = RHS;
417 else {
418 pVal[0] = RHS;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000419 memset(pVal, 0, (getNumWords() - 1) * 8);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000420 }
Zhou Sheng0b706b12007-02-08 14:35:19 +0000421 TruncToBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000422 return *this;
423}
424
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000425/// @brief Prefix increment operator. Increments the APInt by one.
426APInt& APInt::operator++() {
427 if (isSingleWord()) ++VAL;
428 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000429 add_1(pVal, pVal, getNumWords(), 1);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000430 TruncToBits();
431 return *this;
432}
433
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000434/// @brief Prefix decrement operator. Decrements the APInt by one.
435APInt& APInt::operator--() {
436 if (isSingleWord()) --VAL;
437 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000438 sub_1(pVal, getNumWords(), 1);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000439 TruncToBits();
440 return *this;
441}
442
443/// @brief Addition assignment operator. Adds this APInt by the given APInt&
444/// RHS and assigns the result to this APInt.
445APInt& APInt::operator+=(const APInt& RHS) {
446 if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
447 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000448 if (RHS.isSingleWord()) add_1(pVal, pVal, getNumWords(), RHS.VAL);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000449 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000450 if (getNumWords() <= RHS.getNumWords())
451 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000452 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000453 uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.getNumWords());
454 add_1(pVal + RHS.getNumWords(), pVal + RHS.getNumWords(),
455 getNumWords() - RHS.getNumWords(), carry);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000456 }
457 }
458 }
459 TruncToBits();
460 return *this;
461}
462
463/// @brief Subtraction assignment operator. Subtracts this APInt by the given
464/// APInt &RHS and assigns the result to this APInt.
465APInt& APInt::operator-=(const APInt& RHS) {
466 if (isSingleWord())
467 VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
468 else {
469 if (RHS.isSingleWord())
Zhou Shenga3832fd2007-02-07 06:14:53 +0000470 sub_1(pVal, getNumWords(), RHS.VAL);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000471 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000472 if (RHS.getNumWords() < getNumWords()) {
473 uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.getNumWords());
474 sub_1(pVal + RHS.getNumWords(), getNumWords() - RHS.getNumWords(), carry);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000475 }
476 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000477 sub(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000478 }
479 }
480 TruncToBits();
481 return *this;
482}
483
484/// @brief Multiplication assignment operator. Multiplies this APInt by the
485/// given APInt& RHS and assigns the result to this APInt.
486APInt& APInt::operator*=(const APInt& RHS) {
487 if (isSingleWord()) VAL *= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
488 else {
489 // one-based first non-zero bit position.
Zhou Shenga3832fd2007-02-07 06:14:53 +0000490 unsigned first = getNumWords() * APINT_BITS_PER_WORD - CountLeadingZeros();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000491 unsigned xlen = !first ? 0 : whichWord(first - 1) + 1;
492 if (!xlen)
493 return *this;
494 else if (RHS.isSingleWord())
495 mul_1(pVal, pVal, xlen, RHS.VAL);
496 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000497 first = RHS.getNumWords() * APINT_BITS_PER_WORD - RHS.CountLeadingZeros();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000498 unsigned ylen = !first ? 0 : whichWord(first - 1) + 1;
499 if (!ylen) {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000500 memset(pVal, 0, getNumWords() * 8);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000501 return *this;
502 }
503 uint64_t *dest = new uint64_t[xlen+ylen];
504 assert(dest && "Memory Allocation Failed!");
505 mul(dest, pVal, xlen, RHS.pVal, ylen);
Zhou Shenga3832fd2007-02-07 06:14:53 +0000506 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
507 getNumWords() : xlen + ylen) * 8);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000508 delete[] dest;
509 }
510 }
511 TruncToBits();
512 return *this;
513}
514
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000515/// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
516/// this APInt and the given APInt& RHS, assigns the result to this APInt.
517APInt& APInt::operator&=(const APInt& RHS) {
518 if (isSingleWord()) {
519 if (RHS.isSingleWord()) VAL &= RHS.VAL;
520 else VAL &= RHS.pVal[0];
521 } else {
522 if (RHS.isSingleWord()) {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000523 memset(pVal, 0, (getNumWords() - 1) * 8);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000524 pVal[0] &= RHS.VAL;
525 } else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000526 unsigned minwords = getNumWords() < RHS.getNumWords() ?
527 getNumWords() : RHS.getNumWords();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000528 for (unsigned i = 0; i < minwords; ++i)
529 pVal[i] &= RHS.pVal[i];
Zhou Shenga3832fd2007-02-07 06:14:53 +0000530 if (getNumWords() > minwords)
531 memset(pVal+minwords, 0, (getNumWords() - minwords) * 8);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000532 }
533 }
534 return *this;
535}
536
537/// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
538/// this APInt and the given APInt& RHS, assigns the result to this APInt.
539APInt& APInt::operator|=(const APInt& RHS) {
540 if (isSingleWord()) {
541 if (RHS.isSingleWord()) VAL |= RHS.VAL;
542 else VAL |= RHS.pVal[0];
543 } else {
544 if (RHS.isSingleWord()) {
545 pVal[0] |= RHS.VAL;
546 } else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000547 unsigned minwords = getNumWords() < RHS.getNumWords() ?
548 getNumWords() : RHS.getNumWords();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000549 for (unsigned i = 0; i < minwords; ++i)
550 pVal[i] |= RHS.pVal[i];
551 }
552 }
553 TruncToBits();
554 return *this;
555}
556
557/// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
558/// this APInt and the given APInt& RHS, assigns the result to this APInt.
559APInt& APInt::operator^=(const APInt& RHS) {
560 if (isSingleWord()) {
561 if (RHS.isSingleWord()) VAL ^= RHS.VAL;
562 else VAL ^= RHS.pVal[0];
563 } else {
564 if (RHS.isSingleWord()) {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000565 for (unsigned i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000566 pVal[i] ^= RHS.VAL;
567 } else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000568 unsigned minwords = getNumWords() < RHS.getNumWords() ?
569 getNumWords() : RHS.getNumWords();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000570 for (unsigned i = 0; i < minwords; ++i)
571 pVal[i] ^= RHS.pVal[i];
Zhou Shenga3832fd2007-02-07 06:14:53 +0000572 if (getNumWords() > minwords)
573 for (unsigned i = minwords; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000574 pVal[i] ^= 0;
575 }
576 }
577 TruncToBits();
578 return *this;
579}
580
581/// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
582/// and the given APInt& RHS.
583APInt APInt::operator&(const APInt& RHS) const {
584 APInt API(RHS);
585 return API &= *this;
586}
587
588/// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
589/// and the given APInt& RHS.
590APInt APInt::operator|(const APInt& RHS) const {
591 APInt API(RHS);
592 API |= *this;
593 API.TruncToBits();
594 return API;
595}
596
597/// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
598/// and the given APInt& RHS.
599APInt APInt::operator^(const APInt& RHS) const {
600 APInt API(RHS);
601 API ^= *this;
602 API.TruncToBits();
603 return API;
604}
605
606/// @brief Logical AND operator. Performs logical AND operation on this APInt
607/// and the given APInt& RHS.
608bool APInt::operator&&(const APInt& RHS) const {
609 if (isSingleWord())
610 return RHS.isSingleWord() ? VAL && RHS.VAL : VAL && RHS.pVal[0];
611 else if (RHS.isSingleWord())
612 return RHS.VAL && pVal[0];
613 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000614 unsigned minN = std::min(getNumWords(), RHS.getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000615 for (unsigned i = 0; i < minN; ++i)
616 if (pVal[i] && RHS.pVal[i])
617 return true;
618 }
619 return false;
620}
621
622/// @brief Logical OR operator. Performs logical OR operation on this APInt
623/// and the given APInt& RHS.
624bool APInt::operator||(const APInt& RHS) const {
625 if (isSingleWord())
626 return RHS.isSingleWord() ? VAL || RHS.VAL : VAL || RHS.pVal[0];
627 else if (RHS.isSingleWord())
628 return RHS.VAL || pVal[0];
629 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000630 unsigned minN = std::min(getNumWords(), RHS.getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000631 for (unsigned i = 0; i < minN; ++i)
632 if (pVal[i] || RHS.pVal[i])
633 return true;
634 }
635 return false;
636}
637
638/// @brief Logical negation operator. Performs logical negation operation on
639/// this APInt.
640bool APInt::operator !() const {
641 if (isSingleWord())
642 return !VAL;
643 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000644 for (unsigned i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000645 if (pVal[i])
646 return false;
647 return true;
648}
649
650/// @brief Multiplication operator. Multiplies this APInt by the given APInt&
651/// RHS.
652APInt APInt::operator*(const APInt& RHS) const {
653 APInt API(RHS);
654 API *= *this;
655 API.TruncToBits();
656 return API;
657}
658
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000659/// @brief Addition operator. Adds this APInt by the given APInt& RHS.
660APInt APInt::operator+(const APInt& RHS) const {
661 APInt API(*this);
662 API += RHS;
663 API.TruncToBits();
664 return API;
665}
666
667/// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
668APInt APInt::operator-(const APInt& RHS) const {
669 APInt API(*this);
670 API -= RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000671 return API;
672}
673
674/// @brief Array-indexing support.
675bool APInt::operator[](unsigned bitPosition) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000676 return (maskBit(bitPosition) & (isSingleWord() ?
677 VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000678}
679
680/// @brief Equality operator. Compare this APInt with the given APInt& RHS
681/// for the validity of the equality relationship.
682bool APInt::operator==(const APInt& RHS) const {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000683 unsigned n1 = getNumWords() * APINT_BITS_PER_WORD - CountLeadingZeros(),
684 n2 = RHS.getNumWords() * APINT_BITS_PER_WORD - RHS.CountLeadingZeros();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000685 if (n1 != n2) return false;
686 else if (isSingleWord())
687 return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
688 else {
689 if (n1 <= 64)
690 return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
691 for (int i = whichWord(n1 - 1); i >= 0; --i)
692 if (pVal[i] != RHS.pVal[i]) return false;
693 }
694 return true;
695}
696
Zhou Shenga3832fd2007-02-07 06:14:53 +0000697/// @brief Equality operator. Compare this APInt with the given uint64_t value
698/// for the validity of the equality relationship.
699bool APInt::operator==(uint64_t Val) const {
700 if (isSingleWord())
701 return VAL == Val;
702 else {
703 unsigned n = getNumWords() * APINT_BITS_PER_WORD - CountLeadingZeros();
704 if (n <= 64)
705 return pVal[0] == Val;
706 else
707 return false;
708 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000709}
710
711/// @brief Less-than operator. Compare this APInt with the given APInt& RHS
712/// for the validity of the less-than relationship.
713bool APInt::operator <(const APInt& RHS) const {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000714 unsigned n1 = getNumWords() * 64 - CountLeadingZeros(),
715 n2 = RHS.getNumWords() * 64 - RHS.CountLeadingZeros();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000716 if (n1 < n2) return true;
717 else if (n1 > n2) return false;
718 else if (isSingleWord())
719 return VAL < (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
720 else {
721 if (n1 <= 64)
722 return pVal[0] < (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
723 for (int i = whichWord(n1 - 1); i >= 0; --i) {
724 if (pVal[i] > RHS.pVal[i]) return false;
725 else if (pVal[i] < RHS.pVal[i]) return true;
726 }
727 }
728 return false;
729}
730
731/// @brief Less-than-or-equal operator. Compare this APInt with the given
732/// APInt& RHS for the validity of the less-than-or-equal relationship.
733bool APInt::operator<=(const APInt& RHS) const {
734 return (*this) == RHS || (*this) < RHS;
735}
736
737/// @brief Greater-than operator. Compare this APInt with the given APInt& RHS
738/// for the validity of the greater-than relationship.
739bool APInt::operator >(const APInt& RHS) const {
740 return !((*this) <= RHS);
741}
742
743/// @brief Greater-than-or-equal operator. Compare this APInt with the given
744/// APInt& RHS for the validity of the greater-than-or-equal relationship.
745bool APInt::operator>=(const APInt& RHS) const {
746 return !((*this) < RHS);
747}
748
749/// Set the given bit to 1 whose poition is given as "bitPosition".
750/// @brief Set a given bit to 1.
751APInt& APInt::set(unsigned bitPosition) {
752 if (isSingleWord()) VAL |= maskBit(bitPosition);
753 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
754 return *this;
755}
756
757/// @brief Set every bit to 1.
758APInt& APInt::set() {
759 if (isSingleWord()) VAL = -1ULL;
760 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000761 for (unsigned i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000762 pVal[i] = -1ULL;
763 return *this;
764}
765
766/// Set the given bit to 0 whose position is given as "bitPosition".
767/// @brief Set a given bit to 0.
768APInt& APInt::clear(unsigned bitPosition) {
769 if (isSingleWord()) VAL &= ~maskBit(bitPosition);
770 else pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
771 return *this;
772}
773
774/// @brief Set every bit to 0.
775APInt& APInt::clear() {
776 if (isSingleWord()) VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000777 else
778 memset(pVal, 0, getNumWords() * 8);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000779 return *this;
780}
781
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000782/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
783/// this APInt.
784APInt APInt::operator~() const {
785 APInt API(*this);
786 API.flip();
787 return API;
788}
789
790/// @brief Toggle every bit to its opposite value.
791APInt& APInt::flip() {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000792 if (isSingleWord()) VAL = (~(VAL << (64 - BitsNum))) >> (64 - BitsNum);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000793 else {
794 unsigned i = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000795 for (; i < getNumWords() - 1; ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000796 pVal[i] = ~pVal[i];
Zhou Shenga3832fd2007-02-07 06:14:53 +0000797 unsigned offset = 64 - (BitsNum - 64 * (i - 1));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000798 pVal[i] = (~(pVal[i] << offset)) >> offset;
799 }
800 return *this;
801}
802
803/// Toggle a given bit to its opposite value whose position is given
804/// as "bitPosition".
805/// @brief Toggles a given bit to its opposite value.
806APInt& APInt::flip(unsigned bitPosition) {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000807 assert(bitPosition < BitsNum && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000808 if ((*this)[bitPosition]) clear(bitPosition);
809 else set(bitPosition);
810 return *this;
811}
812
813/// to_string - This function translates the APInt into a string.
814std::string APInt::to_string(uint8_t radix) const {
815 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
816 "Radix should be 2, 8, 10, or 16!");
Zhou Shenga3832fd2007-02-07 06:14:53 +0000817 char *buf = 0;
818 unsigned n = getNumWords() * 64 - CountLeadingZeros();
819 std::string format = radix == 8 ?
820 "%0*llo" : (radix == 10 ? "%0*llu" : "%0*llx");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000821 // If the radix is a power of 2, set the format of ostringstream,
822 // and output the value into buf.
823 if ((radix & (radix - 1)) == 0) {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000824 assert((buf = new char[n / Log2_32(radix) + 2]) &&
825 "Memory allocation failed");
826 if (isSingleWord())
827 sprintf(buf, format.c_str(), 0, VAL);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000828 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000829 unsigned offset = sprintf(buf, format.c_str(), 0, pVal[whichWord(n-1)]);
830 for (int i = whichWord(n-1) - 1; i >= 0; --i)
831 offset += sprintf(buf + offset, format.c_str(),
832 64 / Log2_32(radix) + (64 % Log2_32(radix) ? 1 : 0), pVal[i]);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000833 }
834 }
835 else { // If the radix = 10, need to translate the value into a
836 // string.
Zhou Shenga3832fd2007-02-07 06:14:53 +0000837 assert((buf = new char[(n / 64 + 1) * 20]) && "Memory allocation failed");
838 if (isSingleWord())
839 sprintf(buf, format.c_str(), 0, VAL);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000840 else {
841 // FIXME: To be supported.
842 }
843 }
Zhou Shenga3832fd2007-02-07 06:14:53 +0000844 std::string retStr(buf);
845 delete[] buf;
846 return retStr;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000847}
848
849/// getMaxValue - This function returns the largest value
850/// for an APInt of the specified bit-width and if isSign == true,
851/// it should be largest signed value, otherwise unsigned value.
852APInt APInt::getMaxValue(unsigned numBits, bool isSign) {
853 APInt APIVal(numBits, 1);
854 APIVal.set();
855 return isSign ? APIVal.clear(numBits) : APIVal;
856}
857
858/// getMinValue - This function returns the smallest value for
859/// an APInt of the given bit-width and if isSign == true,
860/// it should be smallest signed value, otherwise zero.
861APInt APInt::getMinValue(unsigned numBits, bool isSign) {
862 APInt APIVal(0, numBits);
863 return isSign ? APIVal : APIVal.set(numBits);
864}
865
866/// getAllOnesValue - This function returns an all-ones value for
867/// an APInt of the specified bit-width.
868APInt APInt::getAllOnesValue(unsigned numBits) {
869 return getMaxValue(numBits, false);
870}
871
872/// getNullValue - This function creates an '0' value for an
873/// APInt of the specified bit-width.
874APInt APInt::getNullValue(unsigned numBits) {
875 return getMinValue(numBits, true);
876}
877
878/// HiBits - This function returns the high "numBits" bits of this APInt.
879APInt APInt::HiBits(unsigned numBits) const {
Reid Spencerdb3faa62007-02-13 22:41:58 +0000880 return APIntOps::LShr(*this, BitsNum - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000881}
882
883/// LoBits - This function returns the low "numBits" bits of this APInt.
884APInt APInt::LoBits(unsigned numBits) const {
Reid Spencerdb3faa62007-02-13 22:41:58 +0000885 return APIntOps::LShr(APIntOps::Shl(*this, BitsNum - numBits),
Zhou Sheng0b706b12007-02-08 14:35:19 +0000886 BitsNum - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000887}
888
889/// CountLeadingZeros - This function is a APInt version corresponding to
890/// llvm/include/llvm/Support/MathExtras.h's function
891/// CountLeadingZeros_{32, 64}. It performs platform optimal form of counting
892/// the number of zeros from the most significant bit to the first one bit.
893/// @returns numWord() * 64 if the value is zero.
894unsigned APInt::CountLeadingZeros() const {
895 if (isSingleWord())
896 return CountLeadingZeros_64(VAL);
897 unsigned Count = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000898 for (int i = getNumWords() - 1; i >= 0; --i) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000899 unsigned tmp = CountLeadingZeros_64(pVal[i]);
900 Count += tmp;
901 if (tmp != 64)
902 break;
903 }
904 return Count;
905}
906
907/// CountTrailingZero - This function is a APInt version corresponding to
908/// llvm/include/llvm/Support/MathExtras.h's function
909/// CountTrailingZeros_{32, 64}. It performs platform optimal form of counting
910/// the number of zeros from the least significant bit to the first one bit.
911/// @returns numWord() * 64 if the value is zero.
912unsigned APInt::CountTrailingZeros() const {
913 if (isSingleWord())
914 return CountTrailingZeros_64(~VAL & (VAL - 1));
915 APInt Tmp = ~(*this) & ((*this) - 1);
Zhou Shenga3832fd2007-02-07 06:14:53 +0000916 return getNumWords() * 64 - Tmp.CountLeadingZeros();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000917}
918
919/// CountPopulation - This function is a APInt version corresponding to
920/// llvm/include/llvm/Support/MathExtras.h's function
921/// CountPopulation_{32, 64}. It counts the number of set bits in a value.
922/// @returns 0 if the value is zero.
923unsigned APInt::CountPopulation() const {
924 if (isSingleWord())
925 return CountPopulation_64(VAL);
926 unsigned Count = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000927 for (unsigned i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000928 Count += CountPopulation_64(pVal[i]);
929 return Count;
930}
931
932
933/// ByteSwap - This function returns a byte-swapped representation of the
Zhou Shengff4304f2007-02-09 07:48:24 +0000934/// this APInt.
935APInt APInt::ByteSwap() const {
936 if (BitsNum <= 32)
937 return APInt(BitsNum, ByteSwap_32(unsigned(VAL)));
938 else if (BitsNum <= 64)
939 return APInt(BitsNum, ByteSwap_64(VAL));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000940 else
Zhou Shengff4304f2007-02-09 07:48:24 +0000941 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000942}
943
944/// GreatestCommonDivisor - This function returns the greatest common
945/// divisor of the two APInt values using Enclid's algorithm.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000946APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
947 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000948 APInt A = API1, B = API2;
949 while (!!B) {
950 APInt T = B;
Reid Spencerdb3faa62007-02-13 22:41:58 +0000951 B = APIntOps::URem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000952 A = T;
953 }
954 return A;
955}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000956
Zhou Shengd93f00c2007-02-12 20:02:55 +0000957/// DoubleRoundToAPInt - This function convert a double value to
958/// a APInt value.
959APInt llvm::APIntOps::DoubleRoundToAPInt(double Double) {
960 union {
961 double D;
962 uint64_t I;
963 } T;
964 T.D = Double;
965 bool isNeg = T.I >> 63;
966 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
967 if (exp < 0)
968 return APInt(0);
969 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
970 if (exp < 52)
971 return isNeg ? -APInt(mantissa >> (52 - exp)) :
972 APInt(mantissa >> (52 - exp));
973 APInt Tmp(mantissa, exp + 1);
Reid Spencerdb3faa62007-02-13 22:41:58 +0000974 Tmp = Tmp.Shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000975 return isNeg ? -Tmp : Tmp;
976}
977
Reid Spencerdb3faa62007-02-13 22:41:58 +0000978/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000979/// The layout for double is as following (IEEE Standard 754):
980/// --------------------------------------
981/// | Sign Exponent Fraction Bias |
982/// |-------------------------------------- |
983/// | 1[63] 11[62-52] 52[51-00] 1023 |
984/// --------------------------------------
Reid Spencerdb3faa62007-02-13 22:41:58 +0000985double APInt::RoundToDouble(bool isSigned) const {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000986 bool isNeg = isSigned ? (*this)[BitsNum-1] : false;
987 APInt Tmp(isNeg ? -(*this) : (*this));
988 if (Tmp.isSingleWord())
989 return isSigned ? double(int64_t(Tmp.VAL)) : double(Tmp.VAL);
990 unsigned n = Tmp.getNumWords() * 64 - Tmp.CountLeadingZeros();
991 if (n <= 64)
992 return isSigned ? double(int64_t(Tmp.pVal[0])) : double(Tmp.pVal[0]);
993 // Exponent when normalized to have decimal point directly after
994 // leading one. This is stored excess 1023 in the exponent bit field.
995 uint64_t exp = n - 1;
996
997 // Gross overflow.
998 assert(exp <= 1023 && "Infinity value!");
999
1000 // Number of bits in mantissa including the leading one
1001 // equals to 53.
1002 uint64_t mantissa;
1003 if (n % 64 >= 53)
1004 mantissa = Tmp.pVal[whichWord(n - 1)] >> (n % 64 - 53);
1005 else
1006 mantissa = (Tmp.pVal[whichWord(n - 1)] << (53 - n % 64)) |
1007 (Tmp.pVal[whichWord(n - 1) - 1] >> (11 + n % 64));
1008 // The leading bit of mantissa is implicit, so get rid of it.
1009 mantissa &= ~(1ULL << 52);
1010 uint64_t sign = isNeg ? (1ULL << 63) : 0;
1011 exp += 1023;
1012 union {
1013 double D;
1014 uint64_t I;
1015 } T;
1016 T.I = sign | (exp << 52) | mantissa;
1017 return T.D;
1018}
1019
Zhou Shengff4304f2007-02-09 07:48:24 +00001020/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001021/// @brief Arithmetic right-shift function.
Reid Spencerdb3faa62007-02-13 22:41:58 +00001022APInt APInt::AShr(unsigned shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +00001023 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001024 if (API.isSingleWord())
1025 API.VAL = (((int64_t(API.VAL) << (64 - API.BitsNum)) >> (64 - API.BitsNum))
1026 >> shiftAmt) & (~uint64_t(0UL) >> (64 - API.BitsNum));
1027 else {
1028 if (shiftAmt >= API.BitsNum) {
1029 memset(API.pVal, API[API.BitsNum-1] ? 1 : 0, (API.getNumWords()-1) * 8);
1030 API.pVal[API.getNumWords() - 1] = ~uint64_t(0UL) >>
1031 (64 - API.BitsNum % 64);
1032 } else {
1033 unsigned i = 0;
1034 for (; i < API.BitsNum - shiftAmt; ++i)
1035 if (API[i+shiftAmt])
1036 API.set(i);
1037 else
1038 API.clear(i);
1039 for (; i < API.BitsNum; ++i)
1040 API[API.BitsNum-1] ? API.set(i) : API.clear(i);
1041 }
1042 }
1043 return API;
1044}
1045
Zhou Shengff4304f2007-02-09 07:48:24 +00001046/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001047/// @brief Logical right-shift function.
Reid Spencerdb3faa62007-02-13 22:41:58 +00001048APInt APInt::LShr(unsigned shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +00001049 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001050 if (API.isSingleWord())
1051 API.VAL >>= shiftAmt;
1052 else {
1053 if (shiftAmt >= API.BitsNum)
1054 memset(API.pVal, 0, API.getNumWords() * 8);
1055 unsigned i = 0;
1056 for (i = 0; i < API.BitsNum - shiftAmt; ++i)
1057 if (API[i+shiftAmt]) API.set(i);
1058 else API.clear(i);
1059 for (; i < API.BitsNum; ++i)
1060 API.clear(i);
1061 }
1062 return API;
1063}
1064
Zhou Shengff4304f2007-02-09 07:48:24 +00001065/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001066/// @brief Left-shift function.
Reid Spencerdb3faa62007-02-13 22:41:58 +00001067APInt APInt::Shl(unsigned shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +00001068 APInt API(*this);
Zhou Shengd93f00c2007-02-12 20:02:55 +00001069 if (API.isSingleWord())
1070 API.VAL <<= shiftAmt;
1071 else if (shiftAmt >= API.BitsNum)
1072 memset(API.pVal, 0, API.getNumWords() * 8);
1073 else {
1074 if (unsigned offset = shiftAmt / 64) {
1075 for (unsigned i = API.getNumWords() - 1; i > offset - 1; --i)
1076 API.pVal[i] = API.pVal[i-offset];
1077 memset(API.pVal, 0, offset * 8);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001078 }
Zhou Shengd93f00c2007-02-12 20:02:55 +00001079 shiftAmt %= 64;
1080 unsigned i;
1081 for (i = API.getNumWords() - 1; i > 0; --i)
1082 API.pVal[i] = (API.pVal[i] << shiftAmt) |
1083 (API.pVal[i-1] >> (64-shiftAmt));
1084 API.pVal[i] <<= shiftAmt;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001085 }
1086 return API;
1087}
1088
Zhou Shengff4304f2007-02-09 07:48:24 +00001089/// Unsigned divide this APInt by APInt RHS.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001090/// @brief Unsigned division function for APInt.
Reid Spencerdb3faa62007-02-13 22:41:58 +00001091APInt APInt::UDiv(const APInt& RHS) const {
Zhou Shengff4304f2007-02-09 07:48:24 +00001092 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001093 unsigned first = RHS.getNumWords() * APInt::APINT_BITS_PER_WORD -
1094 RHS.CountLeadingZeros();
1095 unsigned ylen = !first ? 0 : APInt::whichWord(first - 1) + 1;
1096 assert(ylen && "Divided by zero???");
1097 if (API.isSingleWord()) {
1098 API.VAL = RHS.isSingleWord() ? (API.VAL / RHS.VAL) :
1099 (ylen > 1 ? 0 : API.VAL / RHS.pVal[0]);
1100 } else {
1101 unsigned first2 = API.getNumWords() * APInt::APINT_BITS_PER_WORD -
1102 API.CountLeadingZeros();
1103 unsigned xlen = !first2 ? 0 : APInt::whichWord(first2 - 1) + 1;
1104 if (!xlen)
1105 return API;
1106 else if (API < RHS)
1107 memset(API.pVal, 0, API.getNumWords() * 8);
1108 else if (API == RHS) {
1109 memset(API.pVal, 0, API.getNumWords() * 8);
1110 API.pVal[0] = 1;
1111 } else if (xlen == 1)
1112 API.pVal[0] /= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1113 else {
1114 uint64_t *xwords = new uint64_t[xlen+1], *ywords = new uint64_t[ylen];
1115 assert(xwords && ywords && "Memory Allocation Failed!");
1116 memcpy(xwords, API.pVal, xlen * 8);
1117 xwords[xlen] = 0;
1118 memcpy(ywords, RHS.isSingleWord() ? &RHS.VAL : RHS.pVal, ylen * 8);
1119 if (unsigned nshift = 63 - (first - 1) % 64) {
1120 lshift(ywords, 0, ywords, ylen, nshift);
1121 unsigned xlentmp = xlen;
1122 xwords[xlen++] = lshift(xwords, 0, xwords, xlentmp, nshift);
1123 }
1124 div((unsigned*)xwords, xlen*2-1, (unsigned*)ywords, ylen*2);
1125 memset(API.pVal, 0, API.getNumWords() * 8);
1126 memcpy(API.pVal, xwords + ylen, (xlen - ylen) * 8);
1127 delete[] xwords;
1128 delete[] ywords;
1129 }
1130 }
1131 return API;
1132}
1133
1134/// Unsigned remainder operation on APInt.
1135/// @brief Function for unsigned remainder operation.
Reid Spencerdb3faa62007-02-13 22:41:58 +00001136APInt APInt::URem(const APInt& RHS) const {
Zhou Shengff4304f2007-02-09 07:48:24 +00001137 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001138 unsigned first = RHS.getNumWords() * APInt::APINT_BITS_PER_WORD -
1139 RHS.CountLeadingZeros();
1140 unsigned ylen = !first ? 0 : APInt::whichWord(first - 1) + 1;
1141 assert(ylen && "Performing remainder operation by zero ???");
1142 if (API.isSingleWord()) {
1143 API.VAL = RHS.isSingleWord() ? (API.VAL % RHS.VAL) :
1144 (ylen > 1 ? API.VAL : API.VAL % RHS.pVal[0]);
1145 } else {
1146 unsigned first2 = API.getNumWords() * APInt::APINT_BITS_PER_WORD -
1147 API.CountLeadingZeros();
1148 unsigned xlen = !first2 ? 0 : API.whichWord(first2 - 1) + 1;
1149 if (!xlen || API < RHS)
1150 return API;
1151 else if (API == RHS)
1152 memset(API.pVal, 0, API.getNumWords() * 8);
1153 else if (xlen == 1)
1154 API.pVal[0] %= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1155 else {
1156 uint64_t *xwords = new uint64_t[xlen+1], *ywords = new uint64_t[ylen];
1157 assert(xwords && ywords && "Memory Allocation Failed!");
1158 memcpy(xwords, API.pVal, xlen * 8);
1159 xwords[xlen] = 0;
1160 memcpy(ywords, RHS.isSingleWord() ? &RHS.VAL : RHS.pVal, ylen * 8);
1161 unsigned nshift = 63 - (first - 1) % 64;
1162 if (nshift) {
1163 lshift(ywords, 0, ywords, ylen, nshift);
1164 unsigned xlentmp = xlen;
1165 xwords[xlen++] = lshift(xwords, 0, xwords, xlentmp, nshift);
1166 }
1167 div((unsigned*)xwords, xlen*2-1, (unsigned*)ywords, ylen*2);
1168 memset(API.pVal, 0, API.getNumWords() * 8);
1169 for (unsigned i = 0; i < ylen-1; ++i)
1170 API.pVal[i] = (xwords[i] >> nshift) | (xwords[i+1] << (64 - nshift));
1171 API.pVal[ylen-1] = xwords[ylen-1] >> nshift;
1172 delete[] xwords;
1173 delete[] ywords;
1174 }
1175 }
1176 return API;
1177}