blob: ad728e9f6a5b35b98777a4e2f0bd2e8fcf12ed30 [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
Zhou Shengfd43dcf2007-02-06 03:00:16 +000088APInt::APInt(const APInt& APIVal)
Reid Spencer9c0696f2007-02-20 08:51:03 +000089 : BitWidth(APIVal.BitWidth), pVal(0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +000090 if (isSingleWord())
91 VAL = APIVal.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000092 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000093 pVal = getMemory(getNumWords());
Reid Spencera58f0582007-02-18 20:09:41 +000094 memcpy(pVal, APIVal.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) {
189 uint32_t carry = 0;
190 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000191 carry += x[i];
192 dest[i] = carry + y[i];
193 carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
194 }
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");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000202 if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
203 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000204 if (RHS.isSingleWord()) add_1(pVal, pVal, getNumWords(), RHS.VAL);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000205 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000206 if (getNumWords() <= RHS.getNumWords())
207 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000208 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000209 uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.getNumWords());
210 add_1(pVal + RHS.getNumWords(), pVal + RHS.getNumWords(),
211 getNumWords() - RHS.getNumWords(), carry);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000212 }
213 }
214 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000215 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000216 return *this;
217}
218
Reid Spencer5e0a8512007-02-17 03:16:00 +0000219/// sub - This function subtracts the integer array x[] by
220/// integer array y[], and returns the borrow-out carry.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000221static uint64_t sub(uint64_t dest[], uint64_t x[],
222 uint64_t y[], uint32_t len) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000223 // Carry indicator.
224 uint64_t cy = 0;
225
Reid Spenceraf0e9562007-02-18 18:38:44 +0000226 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000227 uint64_t Y = y[i], X = x[i];
228 Y += cy;
229
230 cy = Y < cy ? 1 : 0;
231 Y = X - Y;
232 cy += Y > X ? 1 : 0;
233 dest[i] = Y;
234 }
235 return cy;
236}
237
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000238/// @brief Subtraction assignment operator. Subtracts this APInt by the given
239/// APInt &RHS and assigns the result to this APInt.
240APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000241 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000242 if (isSingleWord())
243 VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
244 else {
245 if (RHS.isSingleWord())
Zhou Shenga3832fd2007-02-07 06:14:53 +0000246 sub_1(pVal, getNumWords(), RHS.VAL);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000247 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000248 if (RHS.getNumWords() < getNumWords()) {
249 uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.getNumWords());
Reid Spencerf2c521c2007-02-18 06:39:42 +0000250 sub_1(pVal + RHS.getNumWords(), getNumWords() - RHS.getNumWords(),
251 carry);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000252 }
253 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000254 sub(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000255 }
256 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000257 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000258 return *this;
259}
260
Reid Spencer5e0a8512007-02-17 03:16:00 +0000261/// mul_1 - This function performs the multiplication operation on a
262/// large integer (represented as an integer array) and a uint64_t integer.
263/// @returns the carry of the multiplication.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000264static uint64_t mul_1(uint64_t dest[],
265 uint64_t x[], uint32_t len,
266 uint64_t y) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000267 // Split y into high 32-bit part and low 32-bit part.
268 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
269 uint64_t carry = 0, lx, hx;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000270 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000271 lx = x[i] & 0xffffffffULL;
272 hx = x[i] >> 32;
273 // hasCarry - A flag to indicate if has carry.
274 // hasCarry == 0, no carry
275 // hasCarry == 1, has carry
276 // hasCarry == 2, no carry and the calculation result == 0.
277 uint8_t hasCarry = 0;
278 dest[i] = carry + lx * ly;
279 // Determine if the add above introduces carry.
280 hasCarry = (dest[i] < carry) ? 1 : 0;
281 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
282 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
283 // (2^32 - 1) + 2^32 = 2^64.
284 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
285
286 carry += (lx * hy) & 0xffffffffULL;
287 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
288 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
289 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
290 }
291
292 return carry;
293}
294
295/// mul - This function multiplies integer array x[] by integer array y[] and
296/// stores the result into integer array dest[].
297/// Note the array dest[]'s size should no less than xlen + ylen.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000298static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
299 uint64_t y[], uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000300 dest[xlen] = mul_1(dest, x, xlen, y[0]);
301
Reid Spenceraf0e9562007-02-18 18:38:44 +0000302 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000303 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
304 uint64_t carry = 0, lx, hx;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000305 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000306 lx = x[j] & 0xffffffffULL;
307 hx = x[j] >> 32;
308 // hasCarry - A flag to indicate if has carry.
309 // hasCarry == 0, no carry
310 // hasCarry == 1, has carry
311 // hasCarry == 2, no carry and the calculation result == 0.
312 uint8_t hasCarry = 0;
313 uint64_t resul = carry + lx * ly;
314 hasCarry = (resul < carry) ? 1 : 0;
315 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
316 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
317
318 carry += (lx * hy) & 0xffffffffULL;
319 resul = (carry << 32) | (resul & 0xffffffffULL);
320 dest[i+j] += resul;
321 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
322 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
323 ((lx * hy) >> 32) + hx * hy;
324 }
325 dest[i+xlen] = carry;
326 }
327}
328
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000329/// @brief Multiplication assignment operator. Multiplies this APInt by the
330/// given APInt& RHS and assigns the result to this APInt.
331APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000332 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000333 if (isSingleWord()) VAL *= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
334 else {
335 // one-based first non-zero bit position.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000336 uint32_t first = getActiveBits();
337 uint32_t xlen = !first ? 0 : whichWord(first - 1) + 1;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000338 if (!xlen)
339 return *this;
340 else if (RHS.isSingleWord())
341 mul_1(pVal, pVal, xlen, RHS.VAL);
342 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000343 first = RHS.getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +0000344 uint32_t ylen = !first ? 0 : whichWord(first - 1) + 1;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000345 if (!ylen) {
Reid Spencera58f0582007-02-18 20:09:41 +0000346 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000347 return *this;
348 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000349 uint64_t *dest = getMemory(xlen+ylen);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000350 mul(dest, pVal, xlen, RHS.pVal, ylen);
Zhou Shenga3832fd2007-02-07 06:14:53 +0000351 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
Reid Spencera58f0582007-02-18 20:09:41 +0000352 getNumWords() : xlen + ylen) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000353 delete[] dest;
354 }
355 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000356 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000357 return *this;
358}
359
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000360/// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
361/// this APInt and the given APInt& RHS, assigns the result to this APInt.
362APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000363 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000364 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000365 VAL &= RHS.VAL;
366 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000367 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000368 uint32_t numWords = getNumWords();
369 for (uint32_t i = 0; i < numWords; ++i)
370 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000371 return *this;
372}
373
374/// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
375/// this APInt and the given APInt& RHS, assigns the result to this APInt.
376APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000377 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000378 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000379 VAL |= RHS.VAL;
380 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000381 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000382 uint32_t numWords = getNumWords();
383 for (uint32_t i = 0; i < numWords; ++i)
384 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000385 return *this;
386}
387
388/// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
389/// this APInt and the given APInt& RHS, assigns the result to this APInt.
390APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000391 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000392 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000393 VAL ^= RHS.VAL;
394 return *this;
395 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000396 uint32_t numWords = getNumWords();
397 for (uint32_t i = 0; i < numWords; ++i)
398 pVal[i] ^= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000399 return *this;
400}
401
402/// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
403/// and the given APInt& RHS.
404APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000405 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000406 if (isSingleWord())
407 return APInt(getBitWidth(), VAL & RHS.VAL);
408
409 APInt Result(*this);
410 uint32_t numWords = getNumWords();
411 for (uint32_t i = 0; i < numWords; ++i)
412 Result.pVal[i] &= RHS.pVal[i];
413 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000414}
415
416/// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
417/// and the given APInt& RHS.
418APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000419 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000420 if (isSingleWord())
421 return APInt(getBitWidth(), VAL | RHS.VAL);
422 APInt Result(*this);
423 uint32_t numWords = getNumWords();
424 for (uint32_t i = 0; i < numWords; ++i)
425 Result.pVal[i] |= RHS.pVal[i];
426 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000427}
428
429/// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
430/// and the given APInt& RHS.
431APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000432 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000433 if (isSingleWord())
434 return APInt(getBitWidth(), VAL ^ RHS.VAL);
435 APInt Result(*this);
436 uint32_t numWords = getNumWords();
437 for (uint32_t i = 0; i < numWords; ++i)
438 Result.pVal[i] ^= RHS.pVal[i];
439 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000440}
441
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000442/// @brief Logical negation operator. Performs logical negation operation on
443/// this APInt.
444bool APInt::operator !() const {
445 if (isSingleWord())
446 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000447
448 for (uint32_t i = 0; i < getNumWords(); ++i)
449 if (pVal[i])
450 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000451 return true;
452}
453
454/// @brief Multiplication operator. Multiplies this APInt by the given APInt&
455/// RHS.
456APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000457 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000458 APInt API(RHS);
459 API *= *this;
Reid Spencere81d2da2007-02-16 22:36:51 +0000460 API.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000461 return API;
462}
463
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000464/// @brief Addition operator. Adds this APInt by the given APInt& RHS.
465APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000466 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000467 APInt API(*this);
468 API += RHS;
Reid Spencere81d2da2007-02-16 22:36:51 +0000469 API.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000470 return API;
471}
472
473/// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
474APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000475 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000476 APInt API(*this);
477 API -= RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000478 return API;
479}
480
481/// @brief Array-indexing support.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000482bool APInt::operator[](uint32_t bitPosition) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000483 return (maskBit(bitPosition) & (isSingleWord() ?
484 VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000485}
486
487/// @brief Equality operator. Compare this APInt with the given APInt& RHS
488/// for the validity of the equality relationship.
489bool APInt::operator==(const APInt& RHS) const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000490 uint32_t n1 = getActiveBits();
491 uint32_t n2 = RHS.getActiveBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000492 if (n1 != n2) return false;
493 else if (isSingleWord())
494 return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
495 else {
Reid Spencer443b5702007-02-18 00:44:22 +0000496 if (n1 <= APINT_BITS_PER_WORD)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000497 return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
498 for (int i = whichWord(n1 - 1); i >= 0; --i)
499 if (pVal[i] != RHS.pVal[i]) return false;
500 }
501 return true;
502}
503
Zhou Shenga3832fd2007-02-07 06:14:53 +0000504/// @brief Equality operator. Compare this APInt with the given uint64_t value
505/// for the validity of the equality relationship.
506bool APInt::operator==(uint64_t Val) const {
507 if (isSingleWord())
508 return VAL == Val;
509 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000510 uint32_t n = getActiveBits();
Reid Spencer443b5702007-02-18 00:44:22 +0000511 if (n <= APINT_BITS_PER_WORD)
Zhou Shenga3832fd2007-02-07 06:14:53 +0000512 return pVal[0] == Val;
513 else
514 return false;
515 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000516}
517
Reid Spencere81d2da2007-02-16 22:36:51 +0000518/// @brief Unsigned less than comparison
519bool APInt::ult(const APInt& RHS) const {
520 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
521 if (isSingleWord())
522 return VAL < RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000523 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000524 uint32_t n1 = getActiveBits();
525 uint32_t n2 = RHS.getActiveBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000526 if (n1 < n2)
527 return true;
528 else if (n2 < n1)
529 return false;
Reid Spencer443b5702007-02-18 00:44:22 +0000530 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
Reid Spencere81d2da2007-02-16 22:36:51 +0000531 return pVal[0] < RHS.pVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000532 for (int i = whichWord(n1 - 1); i >= 0; --i) {
533 if (pVal[i] > RHS.pVal[i]) return false;
534 else if (pVal[i] < RHS.pVal[i]) return true;
535 }
536 }
537 return false;
538}
539
Reid Spencere81d2da2007-02-16 22:36:51 +0000540/// @brief Signed less than comparison
541bool APInt::slt(const APInt& RHS) const {
542 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000543 if (isSingleWord()) {
544 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
545 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
546 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000547 }
Reid Spencera58f0582007-02-18 20:09:41 +0000548
549 APInt lhs(*this);
550 APInt rhs(*this);
551 bool lhsNegative = false;
552 bool rhsNegative = false;
553 if (lhs[BitWidth-1]) {
554 lhsNegative = true;
555 lhs.flip();
556 lhs++;
557 }
558 if (rhs[BitWidth-1]) {
559 rhsNegative = true;
560 rhs.flip();
561 rhs++;
562 }
563 if (lhsNegative)
564 if (rhsNegative)
565 return !lhs.ult(rhs);
566 else
567 return true;
568 else if (rhsNegative)
569 return false;
570 else
571 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000572}
573
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000574/// Set the given bit to 1 whose poition is given as "bitPosition".
575/// @brief Set a given bit to 1.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000576APInt& APInt::set(uint32_t bitPosition) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000577 if (isSingleWord()) VAL |= maskBit(bitPosition);
578 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
579 return *this;
580}
581
582/// @brief Set every bit to 1.
583APInt& APInt::set() {
Reid Spencer443b5702007-02-18 00:44:22 +0000584 if (isSingleWord())
585 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
Zhou Shengb04973e2007-02-15 06:36:31 +0000586 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000587 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000588 pVal[i] = -1ULL;
Reid Spencer443b5702007-02-18 00:44:22 +0000589 pVal[getNumWords() - 1] = ~0ULL >>
590 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
Zhou Shengb04973e2007-02-15 06:36:31 +0000591 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000592 return *this;
593}
594
595/// Set the given bit to 0 whose position is given as "bitPosition".
596/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000597APInt& APInt::clear(uint32_t bitPosition) {
598 if (isSingleWord())
599 VAL &= ~maskBit(bitPosition);
600 else
601 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000602 return *this;
603}
604
605/// @brief Set every bit to 0.
606APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000607 if (isSingleWord())
608 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000609 else
Reid Spencera58f0582007-02-18 20:09:41 +0000610 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000611 return *this;
612}
613
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000614/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
615/// this APInt.
616APInt APInt::operator~() const {
617 APInt API(*this);
618 API.flip();
619 return API;
620}
621
622/// @brief Toggle every bit to its opposite value.
623APInt& APInt::flip() {
Reid Spencer443b5702007-02-18 00:44:22 +0000624 if (isSingleWord()) VAL = (~(VAL <<
625 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000626 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000627 uint32_t i = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000628 for (; i < getNumWords() - 1; ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000629 pVal[i] = ~pVal[i];
Reid Spenceraf0e9562007-02-18 18:38:44 +0000630 uint32_t offset =
Reid Spencer443b5702007-02-18 00:44:22 +0000631 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000632 pVal[i] = (~(pVal[i] << offset)) >> offset;
633 }
634 return *this;
635}
636
637/// Toggle a given bit to its opposite value whose position is given
638/// as "bitPosition".
639/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000640APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000641 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000642 if ((*this)[bitPosition]) clear(bitPosition);
643 else set(bitPosition);
644 return *this;
645}
646
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000647/// getMaxValue - This function returns the largest value
648/// for an APInt of the specified bit-width and if isSign == true,
649/// it should be largest signed value, otherwise unsigned value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000650APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000651 APInt Result(numBits, 0);
652 Result.set();
653 if (isSign)
654 Result.clear(numBits - 1);
655 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000656}
657
658/// getMinValue - This function returns the smallest value for
659/// an APInt of the given bit-width and if isSign == true,
660/// it should be smallest signed value, otherwise zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000661APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000662 APInt Result(numBits, 0);
663 if (isSign)
664 Result.set(numBits - 1);
665 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000666}
667
668/// getAllOnesValue - This function returns an all-ones value for
669/// an APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000670APInt APInt::getAllOnesValue(uint32_t numBits) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000671 return getMaxValue(numBits, false);
672}
673
674/// getNullValue - This function creates an '0' value for an
675/// APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000676APInt APInt::getNullValue(uint32_t numBits) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000677 return getMinValue(numBits, false);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000678}
679
680/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000681APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000682 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000683}
684
685/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000686APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000687 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
688 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000689}
690
Reid Spencere81d2da2007-02-16 22:36:51 +0000691bool APInt::isPowerOf2() const {
692 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
693}
694
695/// countLeadingZeros - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000696/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000697/// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000698/// the number of zeros from the most significant bit to the first one bit.
699/// @returns numWord() * 64 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000700uint32_t APInt::countLeadingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000701 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000702 return CountLeadingZeros_64(VAL) - (APINT_BITS_PER_WORD - BitWidth);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000703 uint32_t Count = 0;
704 for (uint32_t i = getNumWords(); i > 0u; --i) {
705 uint32_t tmp = CountLeadingZeros_64(pVal[i-1]);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000706 Count += tmp;
Reid Spencer443b5702007-02-18 00:44:22 +0000707 if (tmp != APINT_BITS_PER_WORD)
708 if (i == getNumWords())
709 Count -= (APINT_BITS_PER_WORD - whichBit(BitWidth));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000710 break;
711 }
712 return Count;
713}
714
Reid Spencere81d2da2007-02-16 22:36:51 +0000715/// countTrailingZeros - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000716/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000717/// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000718/// the number of zeros from the least significant bit to the first one bit.
719/// @returns numWord() * 64 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000720uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000721 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000722 return CountTrailingZeros_64(VAL);
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000723 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
Reid Spencere81d2da2007-02-16 22:36:51 +0000724 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000725}
726
Reid Spencere81d2da2007-02-16 22:36:51 +0000727/// countPopulation - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000728/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000729/// countPopulation_{32, 64}. It counts the number of set bits in a value.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000730/// @returns 0 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000731uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000732 if (isSingleWord())
733 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000734 uint32_t Count = 0;
735 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000736 Count += CountPopulation_64(pVal[i]);
737 return Count;
738}
739
740
Reid Spencere81d2da2007-02-16 22:36:51 +0000741/// byteSwap - This function returns a byte-swapped representation of the
Zhou Shengff4304f2007-02-09 07:48:24 +0000742/// this APInt.
Reid Spencere81d2da2007-02-16 22:36:51 +0000743APInt APInt::byteSwap() const {
744 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
745 if (BitWidth == 16)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000746 return APInt(BitWidth, ByteSwap_16(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000747 else if (BitWidth == 32)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000748 return APInt(BitWidth, ByteSwap_32(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000749 else if (BitWidth == 48) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000750 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
751 Tmp1 = ByteSwap_32(Tmp1);
752 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
753 Tmp2 = ByteSwap_16(Tmp2);
754 return
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000755 APInt(BitWidth,
756 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
Reid Spencere81d2da2007-02-16 22:36:51 +0000757 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000758 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000759 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000760 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000761 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000762 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000763 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000764 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
765 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000766 }
767 return Result;
768 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000769}
770
771/// GreatestCommonDivisor - This function returns the greatest common
772/// divisor of the two APInt values using Enclid's algorithm.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000773APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
774 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000775 APInt A = API1, B = API2;
776 while (!!B) {
777 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000778 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000779 A = T;
780 }
781 return A;
782}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000783
Zhou Shengd93f00c2007-02-12 20:02:55 +0000784/// DoubleRoundToAPInt - This function convert a double value to
785/// a APInt value.
Reid Spencere81d2da2007-02-16 22:36:51 +0000786APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000787 union {
788 double D;
789 uint64_t I;
790 } T;
791 T.D = Double;
792 bool isNeg = T.I >> 63;
793 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
794 if (exp < 0)
Reid Spencere81d2da2007-02-16 22:36:51 +0000795 return APInt(64ull, 0u);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000796 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
797 if (exp < 52)
Reid Spencere81d2da2007-02-16 22:36:51 +0000798 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
799 APInt(64u, mantissa >> (52 - exp));
800 APInt Tmp(exp + 1, mantissa);
801 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000802 return isNeg ? -Tmp : Tmp;
803}
804
Reid Spencerdb3faa62007-02-13 22:41:58 +0000805/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000806/// The layout for double is as following (IEEE Standard 754):
807/// --------------------------------------
808/// | Sign Exponent Fraction Bias |
809/// |-------------------------------------- |
810/// | 1[63] 11[62-52] 52[51-00] 1023 |
811/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000812double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000813
814 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000815 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
816 if (isSigned) {
817 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
818 return double(sext);
819 } else
820 return double(VAL);
821 }
822
Reid Spencer9c0696f2007-02-20 08:51:03 +0000823 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000824 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000825
826 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000827 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000828
829 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000830 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000831
Reid Spencer9c0696f2007-02-20 08:51:03 +0000832 // The exponent (without bias normalization) is just the number of bits
833 // we are using. Note that the sign bit is gone since we constructed the
834 // absolute value.
835 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000836
Reid Spencer9c0696f2007-02-20 08:51:03 +0000837 // Return infinity for exponent overflow
838 if (exp > 1023) {
839 if (!isSigned || !isNeg)
840 return double(0x0.0p2047L); // positive infinity
841 else
842 return double(-0x0.0p2047L); // negative infinity
843 }
844 exp += 1023; // Increment for 1023 bias
845
846 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
847 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000848 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000849 unsigned hiWord = whichWord(n-1);
850 if (hiWord == 0) {
851 mantissa = Tmp.pVal[0];
852 if (n > 52)
853 mantissa >>= n - 52; // shift down, we want the top 52 bits.
854 } else {
855 assert(hiWord > 0 && "huh?");
856 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
857 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
858 mantissa = hibits | lobits;
859 }
860
Zhou Shengd93f00c2007-02-12 20:02:55 +0000861 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000862 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000863 union {
864 double D;
865 uint64_t I;
866 } T;
867 T.I = sign | (exp << 52) | mantissa;
868 return T.D;
869}
870
Reid Spencere81d2da2007-02-16 22:36:51 +0000871// Truncate to new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000872void APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000873 assert(width < BitWidth && "Invalid APInt Truncate request");
874}
875
876// Sign extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000877void APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000878 assert(width > BitWidth && "Invalid APInt SignExtend request");
879}
880
881// Zero extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000882void APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000883 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
884}
885
Zhou Shengff4304f2007-02-09 07:48:24 +0000886/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000887/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000888APInt APInt::ashr(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000889 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000890 if (API.isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000891 API.VAL =
892 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
893 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
894 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
Zhou Sheng0b706b12007-02-08 14:35:19 +0000895 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000896 if (shiftAmt >= API.BitWidth) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000897 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
Reid Spencera58f0582007-02-18 20:09:41 +0000898 (API.getNumWords()-1) * APINT_WORD_SIZE);
Reid Spencer443b5702007-02-18 00:44:22 +0000899 API.pVal[API.getNumWords() - 1] =
900 ~uint64_t(0UL) >>
901 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000902 } else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000903 uint32_t i = 0;
Reid Spencere81d2da2007-02-16 22:36:51 +0000904 for (; i < API.BitWidth - shiftAmt; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000905 if (API[i+shiftAmt])
906 API.set(i);
907 else
908 API.clear(i);
Reid Spencere81d2da2007-02-16 22:36:51 +0000909 for (; i < API.BitWidth; ++i)
910 if (API[API.BitWidth-1])
Zhou Shengb04973e2007-02-15 06:36:31 +0000911 API.set(i);
912 else API.clear(i);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000913 }
914 }
915 return API;
916}
917
Zhou Shengff4304f2007-02-09 07:48:24 +0000918/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000919/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000920APInt APInt::lshr(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000921 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000922 if (API.isSingleWord())
923 API.VAL >>= shiftAmt;
924 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000925 if (shiftAmt >= API.BitWidth)
Reid Spencera58f0582007-02-18 20:09:41 +0000926 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000927 uint32_t i = 0;
Reid Spencere81d2da2007-02-16 22:36:51 +0000928 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000929 if (API[i+shiftAmt]) API.set(i);
930 else API.clear(i);
Reid Spencere81d2da2007-02-16 22:36:51 +0000931 for (; i < API.BitWidth; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000932 API.clear(i);
933 }
934 return API;
935}
936
Zhou Shengff4304f2007-02-09 07:48:24 +0000937/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000938/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000939APInt APInt::shl(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000940 APInt API(*this);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000941 if (API.isSingleWord())
942 API.VAL <<= shiftAmt;
Reid Spencere81d2da2007-02-16 22:36:51 +0000943 else if (shiftAmt >= API.BitWidth)
Reid Spencera58f0582007-02-18 20:09:41 +0000944 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000945 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000946 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
947 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
Zhou Shengd93f00c2007-02-12 20:02:55 +0000948 API.pVal[i] = API.pVal[i-offset];
Reid Spencera58f0582007-02-18 20:09:41 +0000949 memset(API.pVal, 0, offset * APINT_WORD_SIZE);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000950 }
Reid Spencer443b5702007-02-18 00:44:22 +0000951 shiftAmt %= APINT_BITS_PER_WORD;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000952 uint32_t i;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000953 for (i = API.getNumWords() - 1; i > 0; --i)
954 API.pVal[i] = (API.pVal[i] << shiftAmt) |
Reid Spencer443b5702007-02-18 00:44:22 +0000955 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
Zhou Shengd93f00c2007-02-12 20:02:55 +0000956 API.pVal[i] <<= shiftAmt;
Zhou Sheng0b706b12007-02-08 14:35:19 +0000957 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000958 API.clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +0000959 return API;
960}
961
Reid Spencer9c0696f2007-02-20 08:51:03 +0000962#if 0
Reid Spencer5e0a8512007-02-17 03:16:00 +0000963/// subMul - This function substracts x[len-1:0] * y from
964/// dest[offset+len-1:offset], and returns the most significant
965/// word of the product, minus the borrow-out from the subtraction.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000966static uint32_t subMul(uint32_t dest[], uint32_t offset,
967 uint32_t x[], uint32_t len, uint32_t y) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000968 uint64_t yl = (uint64_t) y & 0xffffffffL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000969 uint32_t carry = 0;
970 uint32_t j = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000971 do {
Reid Spencerc72f2802007-02-17 22:38:07 +0000972 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000973 uint32_t prod_low = (uint32_t) prod;
974 uint32_t prod_high = (uint32_t) (prod >> 32);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000975 prod_low += carry;
976 carry = (prod_low < carry ? 1 : 0) + prod_high;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000977 uint32_t x_j = dest[offset+j];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000978 prod_low = x_j - prod_low;
979 if (prod_low > x_j) ++carry;
980 dest[offset+j] = prod_low;
981 } while (++j < len);
982 return carry;
983}
984
985/// unitDiv - This function divides N by D,
986/// and returns (remainder << 32) | quotient.
987/// Assumes (N >> 32) < D.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000988static uint64_t unitDiv(uint64_t N, uint32_t D) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000989 uint64_t q, r; // q: quotient, r: remainder.
990 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
991 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
992 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
993 q = N / D;
994 r = N % D;
995 }
996 else {
997 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
998 uint64_t c = N - ((uint64_t) D << 31);
999 // Divide (c1*2^32 + c0) by d
1000 q = c / D;
1001 r = c % D;
1002 // Add 2^31 to quotient
1003 q += 1 << 31;
1004 }
1005
1006 return (r << 32) | (q & 0xFFFFFFFFl);
1007}
1008
Reid Spencer9c0696f2007-02-20 08:51:03 +00001009#endif
1010
Reid Spencer5e0a8512007-02-17 03:16:00 +00001011/// div - This is basically Knuth's formulation of the classical algorithm.
1012/// Correspondance with Knuth's notation:
1013/// Knuth's u[0:m+n] == zds[nx:0].
1014/// Knuth's v[1:n] == y[ny-1:0]
1015/// Knuth's n == ny.
1016/// Knuth's m == nx-ny.
1017/// Our nx == Knuth's m+n.
1018/// Could be re-implemented using gmp's mpn_divrem:
1019/// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
Reid Spencer9c0696f2007-02-20 08:51:03 +00001020
1021/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1022/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1023/// variables here have the same names as in the algorithm. Comments explain
1024/// the algorithm and any deviation from it.
1025static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1026 uint32_t m, uint32_t n) {
1027 assert(u && "Must provide dividend");
1028 assert(v && "Must provide divisor");
1029 assert(q && "Must provide quotient");
1030 assert(n>1 && "n must be > 1");
1031
1032 // Knuth uses the value b as the base of the number system. In our case b
1033 // is 2^31 so we just set it to -1u.
1034 uint64_t b = uint64_t(1) << 32;
1035
1036 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1037 // u and v by d. Note that we have taken Knuth's advice here to use a power
1038 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1039 // 2 allows us to shift instead of multiply and it is easy to determine the
1040 // shift amount from the leading zeros. We are basically normalizing the u
1041 // and v so that its high bits are shifted to the top of v's range without
1042 // overflow. Note that this can require an extra word in u so that u must
1043 // be of length m+n+1.
1044 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1045 uint32_t v_carry = 0;
1046 uint32_t u_carry = 0;
1047 if (shift) {
1048 for (uint32_t i = 0; i < m+n; ++i) {
1049 uint32_t u_tmp = u[i] >> (32 - shift);
1050 u[i] = (u[i] << shift) | u_carry;
1051 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001052 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001053 for (uint32_t i = 0; i < n; ++i) {
1054 uint32_t v_tmp = v[i] >> (32 - shift);
1055 v[i] = (v[i] << shift) | v_carry;
1056 v_carry = v_tmp;
1057 }
1058 }
1059 u[m+n] = u_carry;
1060
1061 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1062 int j = m;
1063 do {
1064 // D3. [Calculate q'.].
1065 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1066 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1067 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1068 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1069 // on v[n-2] determines at high speed most of the cases in which the trial
1070 // value qp is one too large, and it eliminates all cases where qp is two
1071 // too large.
1072 uint64_t qp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) / v[n-1];
1073 uint64_t rp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) % v[n-1];
1074 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1075 qp--;
1076 rp += v[n-1];
1077 }
1078 if (rp < b)
1079 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1080 qp--;
1081 rp += v[n-1];
1082 }
1083
1084 // D4. [Multiply and subtract.] Replace u with u - q*v (for each word).
1085 uint32_t borrow = 0;
1086 for (uint32_t i = 0; i < n; i++) {
1087 uint32_t save = u[j+i];
1088 u[j+i] = uint64_t(u[j+i]) - (qp * v[i]) - borrow;
1089 if (u[j+i] > save) {
1090 borrow = 1;
1091 u[j+i+1] += b;
1092 } else {
1093 borrow = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001094 }
1095 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001096 if (borrow)
1097 u[j+n] += 1;
1098
1099 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1100 // negative, go to step D6; otherwise go on to step D7.
1101 q[j] = qp;
1102 if (borrow) {
1103 // D6. [Add back]. The probability that this step is necessary is very
1104 // small, on the order of only 2/b. Make sure that test data accounts for
1105 // this possibility. Decreate qj by 1 and add v[...] to u[...]. A carry
1106 // will occur to the left of u[j+n], and it should be ignored since it
1107 // cancels with the borrow that occurred in D4.
1108 uint32_t carry = 0;
1109 for (uint32_t i = 0; i < n; i++) {
1110 uint32_t save = u[j+i];
1111 u[j+i] += v[i] + carry;
1112 carry = u[j+i] < save;
1113 }
1114 }
1115
1116 // D7. [Loop on j.] Decreate j by one. Now if j >= 0, go back to D3.
1117 j--;
1118 } while (j >= 0);
1119
1120 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1121 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1122 // compute the remainder (urem uses this).
1123 if (r) {
1124 // The value d is expressed by the "shift" value above since we avoided
1125 // multiplication by d by using a shift left. So, all we have to do is
1126 // shift right here. In order to mak
1127 uint32_t mask = ~0u >> (32 - shift);
1128 uint32_t carry = 0;
1129 for (int i = n-1; i >= 0; i--) {
1130 uint32_t save = u[i] & mask;
1131 r[i] = (u[i] >> shift) | carry;
1132 carry = save;
1133 }
1134 }
1135}
1136
1137// This function makes calling KnuthDiv a little more convenient. It uses
1138// APInt parameters instead of uint32_t* parameters. It can also divide APInt
1139// values of different widths.
1140void APInt::divide(const APInt LHS, uint32_t lhsWords,
1141 const APInt &RHS, uint32_t rhsWords,
1142 APInt *Quotient, APInt *Remainder)
1143{
1144 assert(lhsWords >= rhsWords && "Fractional result");
1145
1146 // First, compose the values into an array of 32-bit words instead of
1147 // 64-bit words. This is a necessity of both the "short division" algorithm
1148 // and the the Knuth "classical algorithm" which requires there to be native
1149 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1150 // can't use 64-bit operands here because we don't have native results of
1151 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1152 // work on large-endian machines.
1153 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1154 uint32_t n = rhsWords * 2;
1155 uint32_t m = (lhsWords * 2) - n;
1156 // FIXME: allocate space on stack if m and n are sufficiently small.
1157 uint32_t *U = new uint32_t[m + n + 1];
1158 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1159 for (unsigned i = 0; i < lhsWords; ++i) {
1160 uint64_t tmp = (lhsWords == 1 ? LHS.VAL : LHS.pVal[i]);
1161 U[i * 2] = tmp & mask;
1162 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1163 }
1164 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1165
1166 uint32_t *V = new uint32_t[n];
1167 memset(V, 0, (n)*sizeof(uint32_t));
1168 for (unsigned i = 0; i < rhsWords; ++i) {
1169 uint64_t tmp = (rhsWords == 1 ? RHS.VAL : RHS.pVal[i]);
1170 V[i * 2] = tmp & mask;
1171 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1172 }
1173
1174 // Set up the quotient and remainder
1175 uint32_t *Q = new uint32_t[m+n];
1176 memset(Q, 0, (m+n) * sizeof(uint32_t));
1177 uint32_t *R = 0;
1178 if (Remainder) {
1179 R = new uint32_t[n];
1180 memset(R, 0, n * sizeof(uint32_t));
1181 }
1182
1183 // Now, adjust m and n for the Knuth division. n is the number of words in
1184 // the divisor. m is the number of words by which the dividend exceeds the
1185 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1186 // contain any zero words or the Knuth algorithm fails.
1187 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1188 n--;
1189 m++;
1190 }
1191 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1192 m--;
1193
1194 // If we're left with only a single word for the divisor, Knuth doesn't work
1195 // so we implement the short division algorithm here. This is much simpler
1196 // and faster because we are certain that we can divide a 64-bit quantity
1197 // by a 32-bit quantity at hardware speed and short division is simply a
1198 // series of such operations. This is just like doing short division but we
1199 // are using base 2^32 instead of base 10.
1200 assert(n != 0 && "Divide by zero?");
1201 if (n == 1) {
1202 uint32_t divisor = V[0];
1203 uint32_t remainder = 0;
1204 for (int i = m+n-1; i >= 0; i--) {
1205 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1206 if (partial_dividend == 0) {
1207 Q[i] = 0;
1208 remainder = 0;
1209 } else if (partial_dividend < divisor) {
1210 Q[i] = 0;
1211 remainder = partial_dividend;
1212 } else if (partial_dividend == divisor) {
1213 Q[i] = 1;
1214 remainder = 0;
1215 } else {
1216 Q[i] = partial_dividend / divisor;
1217 remainder = partial_dividend - (Q[i] * divisor);
1218 }
1219 }
1220 if (R)
1221 R[0] = remainder;
1222 } else {
1223 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1224 // case n > 1.
1225 KnuthDiv(U, V, Q, R, m, n);
1226 }
1227
1228 // If the caller wants the quotient
1229 if (Quotient) {
1230 // Set up the Quotient value's memory.
1231 if (Quotient->BitWidth != LHS.BitWidth) {
1232 if (Quotient->isSingleWord())
1233 Quotient->VAL = 0;
1234 else
1235 delete Quotient->pVal;
1236 Quotient->BitWidth = LHS.BitWidth;
1237 if (!Quotient->isSingleWord())
1238 Quotient->pVal = getClearedMemory(lhsWords);
1239 } else
1240 Quotient->clear();
1241
1242 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1243 // order words.
1244 if (lhsWords == 1) {
1245 uint64_t tmp =
1246 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1247 if (Quotient->isSingleWord())
1248 Quotient->VAL = tmp;
1249 else
1250 Quotient->pVal[0] = tmp;
1251 } else {
1252 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1253 for (unsigned i = 0; i < lhsWords; ++i)
1254 Quotient->pVal[i] =
1255 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1256 }
1257 }
1258
1259 // If the caller wants the remainder
1260 if (Remainder) {
1261 // Set up the Remainder value's memory.
1262 if (Remainder->BitWidth != RHS.BitWidth) {
1263 if (Remainder->isSingleWord())
1264 Remainder->VAL = 0;
1265 else
1266 delete Remainder->pVal;
1267 Remainder->BitWidth = RHS.BitWidth;
1268 if (!Remainder->isSingleWord())
1269 Remainder->pVal = getClearedMemory(rhsWords);
1270 } else
1271 Remainder->clear();
1272
1273 // The remainder is in R. Reconstitute the remainder into Remainder's low
1274 // order words.
1275 if (rhsWords == 1) {
1276 uint64_t tmp =
1277 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1278 if (Remainder->isSingleWord())
1279 Remainder->VAL = tmp;
1280 else
1281 Remainder->pVal[0] = tmp;
1282 } else {
1283 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1284 for (unsigned i = 0; i < rhsWords; ++i)
1285 Remainder->pVal[i] =
1286 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1287 }
1288 }
1289
1290 // Clean up the memory we allocated.
1291 delete [] U;
1292 delete [] V;
1293 delete [] Q;
1294 delete [] R;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001295}
1296
Zhou Shengff4304f2007-02-09 07:48:24 +00001297/// Unsigned divide this APInt by APInt RHS.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001298/// @brief Unsigned division function for APInt.
Reid Spencere81d2da2007-02-16 22:36:51 +00001299APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001300 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001301
1302 // First, deal with the easy case
1303 if (isSingleWord()) {
1304 assert(RHS.VAL != 0 && "Divide by zero?");
1305 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001306 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001307
Reid Spencer71bd08f2007-02-17 02:07:07 +00001308 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001309 uint32_t rhsBits = RHS.getActiveBits();
1310 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001311 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001312 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001313 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001314
Reid Spencer9c0696f2007-02-20 08:51:03 +00001315 // Make a temporary to hold the result
1316 APInt Result(*this);
1317
Reid Spencer71bd08f2007-02-17 02:07:07 +00001318 // Deal with some degenerate cases
1319 if (!lhsWords)
1320 return Result; // 0 / X == 0
Reid Spencer9c0696f2007-02-20 08:51:03 +00001321 else if (lhsWords < rhsWords || Result.ult(RHS)) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001322 // X / Y with X < Y == 0
Reid Spencera58f0582007-02-18 20:09:41 +00001323 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001324 return Result;
1325 } else if (Result == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001326 // X / X == 1
Reid Spencera58f0582007-02-18 20:09:41 +00001327 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001328 Result.pVal[0] = 1;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001329 return Result;
1330 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001331 // All high words are zero, just use native divide
1332 Result.pVal[0] /= RHS.pVal[0];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001333 return Result;
Reid Spencer71bd08f2007-02-17 02:07:07 +00001334 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001335
1336 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1337 APInt Quotient(1,0); // to hold result.
1338 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1339 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001340}
1341
1342/// Unsigned remainder operation on APInt.
1343/// @brief Function for unsigned remainder operation.
Reid Spencere81d2da2007-02-16 22:36:51 +00001344APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001345 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001346 if (isSingleWord()) {
1347 assert(RHS.VAL != 0 && "Remainder by zero?");
1348 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001349 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001350
1351 // Make a temporary to hold the result
1352 APInt Result(*this);
1353
1354 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001355 uint32_t rhsBits = RHS.getActiveBits();
1356 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001357 assert(rhsWords && "Performing remainder operation by zero ???");
1358
1359 // Get some facts about the LHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001360 uint32_t lhsBits = Result.getActiveBits();
1361 uint32_t lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001362
1363 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001364 if (lhsWords == 0) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001365 // 0 % Y == 0
Reid Spencera58f0582007-02-18 20:09:41 +00001366 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001367 return Result;
1368 } else if (lhsWords < rhsWords || Result.ult(RHS)) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001369 // X % Y == X iff X < Y
1370 return Result;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001371 } else if (Result == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001372 // X % X == 0;
Reid Spencera58f0582007-02-18 20:09:41 +00001373 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001374 return Result;
1375 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001376 // All high words are zero, just use native remainder
1377 Result.pVal[0] %= RHS.pVal[0];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001378 return Result;
Reid Spencer71bd08f2007-02-17 02:07:07 +00001379 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001380
1381 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1382 APInt Remainder(1,0);
1383 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1384 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001385}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001386
1387/// @brief Converts a char array into an integer.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001388void APInt::fromString(uint32_t numbits, const char *StrStart, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001389 uint8_t radix) {
1390 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1391 "Radix should be 2, 8, 10, or 16!");
1392 assert(StrStart && "String is null?");
Reid Spenceraf0e9562007-02-18 18:38:44 +00001393 uint32_t size = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001394 // If the radix is a power of 2, read the input
1395 // from most significant to least significant.
1396 if ((radix & (radix - 1)) == 0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +00001397 uint32_t nextBitPos = 0;
1398 uint32_t bits_per_digit = radix / 8 + 2;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001399 uint64_t resDigit = 0;
1400 BitWidth = slen * bits_per_digit;
1401 if (getNumWords() > 1)
Reid Spenceraf0e9562007-02-18 18:38:44 +00001402 pVal = getMemory(getNumWords());
Reid Spencer5e0a8512007-02-17 03:16:00 +00001403 for (int i = slen - 1; i >= 0; --i) {
Reid Spencer443b5702007-02-18 00:44:22 +00001404 uint64_t digit = StrStart[i] - '0';
Reid Spencer5e0a8512007-02-17 03:16:00 +00001405 resDigit |= digit << nextBitPos;
1406 nextBitPos += bits_per_digit;
Reid Spencer443b5702007-02-18 00:44:22 +00001407 if (nextBitPos >= APINT_BITS_PER_WORD) {
Reid Spencer5e0a8512007-02-17 03:16:00 +00001408 if (isSingleWord()) {
1409 VAL = resDigit;
1410 break;
1411 }
1412 pVal[size++] = resDigit;
Reid Spencer443b5702007-02-18 00:44:22 +00001413 nextBitPos -= APINT_BITS_PER_WORD;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001414 resDigit = digit >> (bits_per_digit - nextBitPos);
1415 }
1416 }
1417 if (!isSingleWord() && size <= getNumWords())
1418 pVal[size] = resDigit;
1419 } else { // General case. The radix is not a power of 2.
1420 // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
1421 // and its digits number is 20.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001422 const uint32_t chars_per_word = 20;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001423 if (slen < chars_per_word ||
1424 (slen == chars_per_word && // In case the value <= 2^64 - 1
1425 strcmp(StrStart, "18446744073709551615") <= 0)) {
Reid Spencer443b5702007-02-18 00:44:22 +00001426 BitWidth = APINT_BITS_PER_WORD;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001427 VAL = strtoull(StrStart, 0, 10);
1428 } else { // In case the value > 2^64 - 1
Reid Spencer443b5702007-02-18 00:44:22 +00001429 BitWidth = (slen / chars_per_word + 1) * APINT_BITS_PER_WORD;
Reid Spenceraf0e9562007-02-18 18:38:44 +00001430 pVal = getClearedMemory(getNumWords());
1431 uint32_t str_pos = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001432 while (str_pos < slen) {
Reid Spenceraf0e9562007-02-18 18:38:44 +00001433 uint32_t chunk = slen - str_pos;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001434 if (chunk > chars_per_word - 1)
1435 chunk = chars_per_word - 1;
Reid Spencer443b5702007-02-18 00:44:22 +00001436 uint64_t resDigit = StrStart[str_pos++] - '0';
Reid Spencer5e0a8512007-02-17 03:16:00 +00001437 uint64_t big_base = radix;
1438 while (--chunk > 0) {
Reid Spencer443b5702007-02-18 00:44:22 +00001439 resDigit = resDigit * radix + StrStart[str_pos++] - '0';
Reid Spencer5e0a8512007-02-17 03:16:00 +00001440 big_base *= radix;
1441 }
1442
1443 uint64_t carry;
1444 if (!size)
1445 carry = resDigit;
1446 else {
1447 carry = mul_1(pVal, pVal, size, big_base);
1448 carry += add_1(pVal, pVal, size, resDigit);
1449 }
1450
1451 if (carry) pVal[size++] = carry;
1452 }
1453 }
1454 }
1455}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001456
1457/// to_string - This function translates the APInt into a string.
1458std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1459 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1460 "Radix should be 2, 8, 10, or 16!");
1461 static const char *digits[] = {
1462 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1463 };
1464 std::string result;
1465 uint32_t bits_used = getActiveBits();
1466 if (isSingleWord()) {
1467 char buf[65];
1468 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1469 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1470 if (format) {
1471 if (wantSigned) {
1472 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1473 (APINT_BITS_PER_WORD-BitWidth);
1474 sprintf(buf, format, sextVal);
1475 } else
1476 sprintf(buf, format, VAL);
1477 } else {
1478 memset(buf, 0, 65);
1479 uint64_t v = VAL;
1480 while (bits_used) {
1481 uint32_t bit = v & 1;
1482 bits_used--;
1483 buf[bits_used] = digits[bit][0];
1484 v >>=1;
1485 }
1486 }
1487 result = buf;
1488 return result;
1489 }
1490
1491 if (radix != 10) {
1492 uint64_t mask = radix - 1;
1493 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1494 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1495 for (uint32_t i = 0; i < getNumWords(); ++i) {
1496 uint64_t value = pVal[i];
1497 for (uint32_t j = 0; j < nibbles; ++j) {
1498 result.insert(0, digits[ value & mask ]);
1499 value >>= shift;
1500 }
1501 }
1502 return result;
1503 }
1504
1505 APInt tmp(*this);
1506 APInt divisor(4, radix);
1507 APInt zero(tmp.getBitWidth(), 0);
1508 size_t insert_at = 0;
1509 if (wantSigned && tmp[BitWidth-1]) {
1510 // They want to print the signed version and it is a negative value
1511 // Flip the bits and add one to turn it into the equivalent positive
1512 // value and put a '-' in the result.
1513 tmp.flip();
1514 tmp++;
1515 result = "-";
1516 insert_at = 1;
1517 }
1518 if (tmp == 0)
1519 result = "0";
1520 else while (tmp.ne(zero)) {
1521 APInt APdigit(1,0);
1522 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), 0, &APdigit);
1523 uint32_t digit = APdigit.getValue();
1524 assert(digit < radix && "urem failed");
1525 result.insert(insert_at,digits[digit]);
1526 APInt tmp2(tmp.getBitWidth(), 0);
1527 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2, 0);
1528 tmp = tmp2;
1529 }
1530
1531 return result;
1532}
1533