blob: c3b3d9d233f5c5a65b158c60cf82200708520c13 [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
Reid Spencer9d6c9192007-02-24 03:58:46 +000015#define DEBUG_TYPE "apint"
Zhou Shengfd43dcf2007-02-06 03:00:16 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/DerivedTypes.h"
Reid Spencer9d6c9192007-02-24 03:58:46 +000018#include "llvm/Support/Debug.h"
Zhou Shengfd43dcf2007-02-06 03:00:16 +000019#include "llvm/Support/MathExtras.h"
Zhou Shenga3832fd2007-02-07 06:14:53 +000020#include <cstring>
Zhou Shengfd43dcf2007-02-06 03:00:16 +000021#include <cstdlib>
Reid Spencer385f7542007-02-21 03:55:44 +000022#ifndef NDEBUG
23#include <iostream>
24#include <iomanip>
25#endif
26
Zhou Shengfd43dcf2007-02-06 03:00:16 +000027using namespace llvm;
28
Reid Spenceraf0e9562007-02-18 18:38:44 +000029// A utility function for allocating memory, checking for allocation failures,
30// and ensuring the contents is zeroed.
31inline static uint64_t* getClearedMemory(uint32_t numWords) {
32 uint64_t * result = new uint64_t[numWords];
33 assert(result && "APInt memory allocation fails!");
34 memset(result, 0, numWords * sizeof(uint64_t));
35 return result;
Zhou Sheng353815d2007-02-06 06:04:53 +000036}
37
Reid Spenceraf0e9562007-02-18 18:38:44 +000038// A utility function for allocating memory and checking for allocation failure.
39inline static uint64_t* getMemory(uint32_t numWords) {
40 uint64_t * result = new uint64_t[numWords];
41 assert(result && "APInt memory allocation fails!");
42 return result;
43}
44
45APInt::APInt(uint32_t numBits, uint64_t val)
Reid Spencer385f7542007-02-21 03:55:44 +000046 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000047 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
48 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000049 if (isSingleWord())
Reid Spencere81d2da2007-02-16 22:36:51 +000050 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
Zhou Shengfd43dcf2007-02-06 03:00:16 +000051 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000052 pVal = getClearedMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000053 pVal[0] = val;
54 }
55}
56
Reid Spenceraf0e9562007-02-18 18:38:44 +000057APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
Reid Spencer385f7542007-02-21 03:55:44 +000058 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000059 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
60 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000061 assert(bigVal && "Null pointer detected!");
62 if (isSingleWord())
Reid Spencere81d2da2007-02-16 22:36:51 +000063 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
Zhou Shengfd43dcf2007-02-06 03:00:16 +000064 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000065 pVal = getMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000066 // Calculate the actual length of bigVal[].
Reid Spenceraf0e9562007-02-18 18:38:44 +000067 uint32_t maxN = std::max<uint32_t>(numWords, getNumWords());
68 uint32_t minN = std::min<uint32_t>(numWords, getNumWords());
Reid Spencera58f0582007-02-18 20:09:41 +000069 memcpy(pVal, bigVal, (minN - 1) * APINT_WORD_SIZE);
Reid Spencer443b5702007-02-18 00:44:22 +000070 pVal[minN-1] = bigVal[minN-1] &
71 (~uint64_t(0ULL) >>
72 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
Zhou Shenga3832fd2007-02-07 06:14:53 +000073 if (maxN == getNumWords())
Reid Spencera58f0582007-02-18 20:09:41 +000074 memset(pVal+numWords, 0, (getNumWords() - numWords) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000075 }
76}
77
Zhou Shenga3832fd2007-02-07 06:14:53 +000078/// @brief Create a new APInt by translating the char array represented
79/// integer value.
Reid Spenceraf0e9562007-02-18 18:38:44 +000080APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000081 uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000082 : BitWidth(numbits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000083 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000084}
85
86/// @brief Create a new APInt by translating the string represented
87/// integer value.
Reid Spencer9c0696f2007-02-20 08:51:03 +000088APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000089 : BitWidth(numbits), VAL(0) {
Zhou Shenga3832fd2007-02-07 06:14:53 +000090 assert(!Val.empty() && "String empty?");
Reid Spencere81d2da2007-02-16 22:36:51 +000091 fromString(numbits, Val.c_str(), Val.size(), radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000092}
93
Reid Spencera58f0582007-02-18 20:09:41 +000094/// @brief Copy constructor
Reid Spencer54362ca2007-02-20 23:40:25 +000095APInt::APInt(const APInt& that)
Reid Spencer385f7542007-02-21 03:55:44 +000096 : BitWidth(that.BitWidth), VAL(0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +000097 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +000098 VAL = that.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000099 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000100 pVal = getMemory(getNumWords());
Reid Spencer54362ca2007-02-20 23:40:25 +0000101 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000102 }
103}
104
105APInt::~APInt() {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000106 if (!isSingleWord() && pVal)
107 delete[] pVal;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000108}
109
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000110/// @brief Copy assignment operator. Create a new object from the given
111/// APInt one by initialization.
112APInt& APInt::operator=(const APInt& RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000113 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
114 if (isSingleWord())
Reid Spenceraf0e9562007-02-18 18:38:44 +0000115 VAL = RHS.VAL;
116 else
Reid Spencera58f0582007-02-18 20:09:41 +0000117 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000118 return *this;
119}
120
121/// @brief Assignment operator. Assigns a common case integer value to
122/// the APInt.
123APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000124 if (isSingleWord())
125 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000126 else {
127 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000128 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000129 }
130 return *this;
131}
132
Reid Spenceraf0e9562007-02-18 18:38:44 +0000133/// add_1 - This function adds a single "digit" integer, y, to the multiple
134/// "digit" integer array, x[]. x[] is modified to reflect the addition and
135/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000136/// @returns the carry of the addition.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000137static uint64_t add_1(uint64_t dest[],
138 uint64_t x[], uint32_t len,
139 uint64_t y) {
140 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000141 dest[i] = y + x[i];
142 if (dest[i] < y)
143 y = 1;
144 else {
145 y = 0;
146 break;
147 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000148 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000149 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000150}
151
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000152/// @brief Prefix increment operator. Increments the APInt by one.
153APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000154 if (isSingleWord())
155 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000156 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000157 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000158 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000159 return *this;
160}
161
Reid Spenceraf0e9562007-02-18 18:38:44 +0000162/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
163/// the multi-digit integer array, x[], propagating the borrowed 1 value until
164/// no further borrowing is neeeded or it runs out of "digits" in x. The result
165/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
166/// In other words, if y > x then this function returns 1, otherwise 0.
167static uint64_t sub_1(uint64_t x[], uint32_t len,
168 uint64_t y) {
169 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000170 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000171 x[i] -= y;
172 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000173 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000174 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000175 y = 0; // No need to borrow
176 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000177 }
178 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000179 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000180}
181
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000182/// @brief Prefix decrement operator. Decrements the APInt by one.
183APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000184 if (isSingleWord())
185 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000186 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000187 sub_1(pVal, getNumWords(), 1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000188 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000189 return *this;
190}
191
Reid Spencer5e0a8512007-02-17 03:16:00 +0000192/// add - This function adds the integer array x[] by integer array
193/// y[] and returns the carry.
Reid Spencer9d6c9192007-02-24 03:58:46 +0000194static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
195 uint32_t len) {
196 bool carry = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000197 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer92904632007-02-23 01:57:13 +0000198 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer54362ca2007-02-20 23:40:25 +0000199 dest[i] = x[i] + y[i] + carry;
Reid Spencer60c0a6a2007-02-21 05:44:56 +0000200 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000201 }
202 return carry;
203}
204
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000205/// @brief Addition assignment operator. Adds this APInt by the given APInt&
206/// RHS and assigns the result to this APInt.
207APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000208 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000209 if (isSingleWord())
210 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000211 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000212 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000213 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000214 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000215 return *this;
216}
217
Reid Spencer5e0a8512007-02-17 03:16:00 +0000218/// sub - This function subtracts the integer array x[] by
219/// integer array y[], and returns the borrow-out carry.
Reid Spencer9d6c9192007-02-24 03:58:46 +0000220static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
221 uint32_t len) {
Reid Spencer385f7542007-02-21 03:55:44 +0000222 bool borrow = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000223 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer385f7542007-02-21 03:55:44 +0000224 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
225 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
226 dest[i] = x_tmp - y[i];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000227 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000228 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000229}
230
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000231/// @brief Subtraction assignment operator. Subtracts this APInt by the given
232/// APInt &RHS and assigns the result to this APInt.
233APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000234 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000235 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000236 VAL -= RHS.VAL;
237 else
238 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencere81d2da2007-02-16 22:36:51 +0000239 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000240 return *this;
241}
242
Reid Spencer5e0a8512007-02-17 03:16:00 +0000243/// mul_1 - This function performs the multiplication operation on a
244/// large integer (represented as an integer array) and a uint64_t integer.
245/// @returns the carry of the multiplication.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000246static uint64_t mul_1(uint64_t dest[],
247 uint64_t x[], uint32_t len,
248 uint64_t y) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000249 // Split y into high 32-bit part and low 32-bit part.
250 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
251 uint64_t carry = 0, lx, hx;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000252 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000253 lx = x[i] & 0xffffffffULL;
254 hx = x[i] >> 32;
255 // hasCarry - A flag to indicate if has carry.
256 // hasCarry == 0, no carry
257 // hasCarry == 1, has carry
258 // hasCarry == 2, no carry and the calculation result == 0.
259 uint8_t hasCarry = 0;
260 dest[i] = carry + lx * ly;
261 // Determine if the add above introduces carry.
262 hasCarry = (dest[i] < carry) ? 1 : 0;
263 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
264 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
265 // (2^32 - 1) + 2^32 = 2^64.
266 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
267
268 carry += (lx * hy) & 0xffffffffULL;
269 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
270 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
271 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
272 }
273
274 return carry;
275}
276
277/// mul - This function multiplies integer array x[] by integer array y[] and
278/// stores the result into integer array dest[].
279/// Note the array dest[]'s size should no less than xlen + ylen.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000280static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
281 uint64_t y[], uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000282 dest[xlen] = mul_1(dest, x, xlen, y[0]);
283
Reid Spenceraf0e9562007-02-18 18:38:44 +0000284 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000285 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencere0cdd332007-02-21 08:21:52 +0000286 uint64_t carry = 0, lx = 0, hx = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000287 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000288 lx = x[j] & 0xffffffffULL;
289 hx = x[j] >> 32;
290 // hasCarry - A flag to indicate if has carry.
291 // hasCarry == 0, no carry
292 // hasCarry == 1, has carry
293 // hasCarry == 2, no carry and the calculation result == 0.
294 uint8_t hasCarry = 0;
295 uint64_t resul = carry + lx * ly;
296 hasCarry = (resul < carry) ? 1 : 0;
297 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
298 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
299
300 carry += (lx * hy) & 0xffffffffULL;
301 resul = (carry << 32) | (resul & 0xffffffffULL);
302 dest[i+j] += resul;
303 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
304 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
305 ((lx * hy) >> 32) + hx * hy;
306 }
307 dest[i+xlen] = carry;
308 }
309}
310
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000311/// @brief Multiplication assignment operator. Multiplies this APInt by the
312/// given APInt& RHS and assigns the result to this APInt.
313APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000314 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencere0cdd332007-02-21 08:21:52 +0000315 if (isSingleWord()) {
Reid Spencer61eb1802007-02-20 20:42:10 +0000316 VAL *= RHS.VAL;
Reid Spencere0cdd332007-02-21 08:21:52 +0000317 clearUnusedBits();
318 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000319 }
Reid Spencere0cdd332007-02-21 08:21:52 +0000320
321 // Get some bit facts about LHS and check for zero
322 uint32_t lhsBits = getActiveBits();
323 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
324 if (!lhsWords)
325 // 0 * X ===> 0
326 return *this;
327
328 // Get some bit facts about RHS and check for zero
329 uint32_t rhsBits = RHS.getActiveBits();
330 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
331 if (!rhsWords) {
332 // X * 0 ===> 0
333 clear();
334 return *this;
335 }
336
337 // Allocate space for the result
338 uint32_t destWords = rhsWords + lhsWords;
339 uint64_t *dest = getMemory(destWords);
340
341 // Perform the long multiply
342 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
343
344 // Copy result back into *this
345 clear();
346 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
347 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
348
349 // delete dest array and return
350 delete[] dest;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000351 return *this;
352}
353
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000354/// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
355/// this APInt and the given APInt& RHS, assigns the result to this APInt.
356APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000357 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000358 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000359 VAL &= RHS.VAL;
360 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000361 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000362 uint32_t numWords = getNumWords();
363 for (uint32_t i = 0; i < numWords; ++i)
364 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000365 return *this;
366}
367
368/// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
369/// this APInt and the given APInt& RHS, assigns the result to this APInt.
370APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000371 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000372 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000373 VAL |= RHS.VAL;
374 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000375 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000376 uint32_t numWords = getNumWords();
377 for (uint32_t i = 0; i < numWords; ++i)
378 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000379 return *this;
380}
381
382/// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
383/// this APInt and the given APInt& RHS, assigns the result to this APInt.
384APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000385 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000386 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000387 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000388 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000389 return *this;
390 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000391 uint32_t numWords = getNumWords();
392 for (uint32_t i = 0; i < numWords; ++i)
393 pVal[i] ^= RHS.pVal[i];
Reid Spencer54362ca2007-02-20 23:40:25 +0000394 this->clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000395 return *this;
396}
397
398/// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
399/// and the given APInt& RHS.
400APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000401 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000402 if (isSingleWord())
403 return APInt(getBitWidth(), VAL & RHS.VAL);
404
405 APInt Result(*this);
406 uint32_t numWords = getNumWords();
407 for (uint32_t i = 0; i < numWords; ++i)
408 Result.pVal[i] &= RHS.pVal[i];
409 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000410}
411
412/// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
413/// and the given APInt& RHS.
414APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000415 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000416 if (isSingleWord())
417 return APInt(getBitWidth(), VAL | RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000418
Reid Spenceraf0e9562007-02-18 18:38:44 +0000419 APInt Result(*this);
420 uint32_t numWords = getNumWords();
421 for (uint32_t i = 0; i < numWords; ++i)
422 Result.pVal[i] |= RHS.pVal[i];
423 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000424}
425
426/// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
427/// and the given APInt& RHS.
428APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000429 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000430 if (isSingleWord()) {
431 APInt Result(BitWidth, VAL ^ RHS.VAL);
432 Result.clearUnusedBits();
433 return Result;
434 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000435 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");
Reid Spencer54362ca2007-02-20 23:40:25 +0000458 if (isSingleWord()) {
459 APInt Result(BitWidth, VAL * RHS.VAL);
460 Result.clearUnusedBits();
461 return Result;
462 }
Reid Spencer61eb1802007-02-20 20:42:10 +0000463 APInt Result(*this);
464 Result *= RHS;
465 Result.clearUnusedBits();
466 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000467}
468
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000469/// @brief Addition operator. Adds this APInt by the given APInt& RHS.
470APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000471 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000472 if (isSingleWord()) {
473 APInt Result(BitWidth, VAL + RHS.VAL);
474 Result.clearUnusedBits();
475 return Result;
476 }
477 APInt Result(BitWidth, 0);
478 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
479 Result.clearUnusedBits();
480 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000481}
482
483/// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
484APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000485 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000486 if (isSingleWord()) {
487 APInt Result(BitWidth, VAL - RHS.VAL);
488 Result.clearUnusedBits();
489 return Result;
490 }
491 APInt Result(BitWidth, 0);
492 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
493 Result.clearUnusedBits();
494 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000495}
496
497/// @brief Array-indexing support.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000498bool APInt::operator[](uint32_t bitPosition) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000499 return (maskBit(bitPosition) & (isSingleWord() ?
500 VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000501}
502
503/// @brief Equality operator. Compare this APInt with the given APInt& RHS
504/// for the validity of the equality relationship.
505bool APInt::operator==(const APInt& RHS) const {
Reid Spencer54362ca2007-02-20 23:40:25 +0000506 if (isSingleWord())
507 return VAL == RHS.VAL;
508
Reid Spenceraf0e9562007-02-18 18:38:44 +0000509 uint32_t n1 = getActiveBits();
510 uint32_t n2 = RHS.getActiveBits();
Reid Spencer54362ca2007-02-20 23:40:25 +0000511 if (n1 != n2)
512 return false;
513
514 if (n1 <= APINT_BITS_PER_WORD)
515 return pVal[0] == RHS.pVal[0];
516
517 for (int i = whichWord(n1 - 1); i >= 0; --i)
518 if (pVal[i] != RHS.pVal[i])
519 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000520 return true;
521}
522
Zhou Shenga3832fd2007-02-07 06:14:53 +0000523/// @brief Equality operator. Compare this APInt with the given uint64_t value
524/// for the validity of the equality relationship.
525bool APInt::operator==(uint64_t Val) const {
526 if (isSingleWord())
527 return VAL == Val;
Reid Spencer54362ca2007-02-20 23:40:25 +0000528
529 uint32_t n = getActiveBits();
530 if (n <= APINT_BITS_PER_WORD)
531 return pVal[0] == Val;
532 else
533 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000534}
535
Reid Spencere81d2da2007-02-16 22:36:51 +0000536/// @brief Unsigned less than comparison
537bool APInt::ult(const APInt& RHS) const {
538 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
539 if (isSingleWord())
540 return VAL < RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000541 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000542 uint32_t n1 = getActiveBits();
543 uint32_t n2 = RHS.getActiveBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000544 if (n1 < n2)
545 return true;
546 else if (n2 < n1)
547 return false;
Reid Spencer443b5702007-02-18 00:44:22 +0000548 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
Reid Spencere81d2da2007-02-16 22:36:51 +0000549 return pVal[0] < RHS.pVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000550 for (int i = whichWord(n1 - 1); i >= 0; --i) {
551 if (pVal[i] > RHS.pVal[i]) return false;
552 else if (pVal[i] < RHS.pVal[i]) return true;
553 }
554 }
555 return false;
556}
557
Reid Spencere81d2da2007-02-16 22:36:51 +0000558/// @brief Signed less than comparison
559bool APInt::slt(const APInt& RHS) const {
560 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000561 if (isSingleWord()) {
562 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
563 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
564 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000565 }
Reid Spencera58f0582007-02-18 20:09:41 +0000566
567 APInt lhs(*this);
568 APInt rhs(*this);
569 bool lhsNegative = false;
570 bool rhsNegative = false;
571 if (lhs[BitWidth-1]) {
572 lhsNegative = true;
573 lhs.flip();
574 lhs++;
575 }
576 if (rhs[BitWidth-1]) {
577 rhsNegative = true;
578 rhs.flip();
579 rhs++;
580 }
581 if (lhsNegative)
582 if (rhsNegative)
583 return !lhs.ult(rhs);
584 else
585 return true;
586 else if (rhsNegative)
587 return false;
588 else
589 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000590}
591
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000592/// Set the given bit to 1 whose poition is given as "bitPosition".
593/// @brief Set a given bit to 1.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000594APInt& APInt::set(uint32_t bitPosition) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000595 if (isSingleWord()) VAL |= maskBit(bitPosition);
596 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
597 return *this;
598}
599
600/// @brief Set every bit to 1.
601APInt& APInt::set() {
Reid Spencer443b5702007-02-18 00:44:22 +0000602 if (isSingleWord())
603 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
Zhou Shengb04973e2007-02-15 06:36:31 +0000604 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000605 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000606 pVal[i] = -1ULL;
Reid Spencer443b5702007-02-18 00:44:22 +0000607 pVal[getNumWords() - 1] = ~0ULL >>
608 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
Zhou Shengb04973e2007-02-15 06:36:31 +0000609 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000610 return *this;
611}
612
613/// Set the given bit to 0 whose position is given as "bitPosition".
614/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000615APInt& APInt::clear(uint32_t bitPosition) {
616 if (isSingleWord())
617 VAL &= ~maskBit(bitPosition);
618 else
619 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000620 return *this;
621}
622
623/// @brief Set every bit to 0.
624APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000625 if (isSingleWord())
626 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000627 else
Reid Spencera58f0582007-02-18 20:09:41 +0000628 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000629 return *this;
630}
631
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000632/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
633/// this APInt.
634APInt APInt::operator~() const {
635 APInt API(*this);
636 API.flip();
637 return API;
638}
639
640/// @brief Toggle every bit to its opposite value.
641APInt& APInt::flip() {
Reid Spencer443b5702007-02-18 00:44:22 +0000642 if (isSingleWord()) VAL = (~(VAL <<
643 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000644 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000645 uint32_t i = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000646 for (; i < getNumWords() - 1; ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000647 pVal[i] = ~pVal[i];
Reid Spenceraf0e9562007-02-18 18:38:44 +0000648 uint32_t offset =
Reid Spencer443b5702007-02-18 00:44:22 +0000649 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000650 pVal[i] = (~(pVal[i] << offset)) >> offset;
651 }
652 return *this;
653}
654
655/// Toggle a given bit to its opposite value whose position is given
656/// as "bitPosition".
657/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000658APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000659 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000660 if ((*this)[bitPosition]) clear(bitPosition);
661 else set(bitPosition);
662 return *this;
663}
664
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000665/// getMaxValue - This function returns the largest value
666/// for an APInt of the specified bit-width and if isSign == true,
667/// it should be largest signed value, otherwise unsigned value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000668APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000669 APInt Result(numBits, 0);
670 Result.set();
671 if (isSign)
672 Result.clear(numBits - 1);
673 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000674}
675
676/// getMinValue - This function returns the smallest value for
677/// an APInt of the given bit-width and if isSign == true,
678/// it should be smallest signed value, otherwise zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000679APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000680 APInt Result(numBits, 0);
681 if (isSign)
682 Result.set(numBits - 1);
683 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000684}
685
686/// getAllOnesValue - This function returns an all-ones value for
687/// an APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000688APInt APInt::getAllOnesValue(uint32_t numBits) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000689 return getMaxValue(numBits, false);
690}
691
692/// getNullValue - This function creates an '0' value for an
693/// APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000694APInt APInt::getNullValue(uint32_t numBits) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000695 return getMinValue(numBits, false);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000696}
697
698/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000699APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000700 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000701}
702
703/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000704APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000705 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
706 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000707}
708
Reid Spencere81d2da2007-02-16 22:36:51 +0000709bool APInt::isPowerOf2() const {
710 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
711}
712
713/// countLeadingZeros - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000714/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000715/// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000716/// the number of zeros from the most significant bit to the first one bit.
717/// @returns numWord() * 64 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000718uint32_t APInt::countLeadingZeros() const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000719 uint32_t Count = 0;
Reid Spencere549c492007-02-21 00:29:48 +0000720 if (isSingleWord())
721 Count = CountLeadingZeros_64(VAL);
722 else {
723 for (uint32_t i = getNumWords(); i > 0u; --i) {
724 if (pVal[i-1] == 0)
725 Count += APINT_BITS_PER_WORD;
726 else {
727 Count += CountLeadingZeros_64(pVal[i-1]);
728 break;
729 }
730 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000731 }
Reid Spencerab2b2c82007-02-22 00:22:00 +0000732 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
733 if (remainder)
734 Count -= APINT_BITS_PER_WORD - remainder;
735 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000736}
737
Reid Spencere81d2da2007-02-16 22:36:51 +0000738/// countTrailingZeros - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000739/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000740/// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000741/// the number of zeros from the least significant bit to the first one bit.
742/// @returns numWord() * 64 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000743uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000744 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000745 return CountTrailingZeros_64(VAL);
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000746 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
Reid Spencere81d2da2007-02-16 22:36:51 +0000747 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000748}
749
Reid Spencere81d2da2007-02-16 22:36:51 +0000750/// countPopulation - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000751/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000752/// countPopulation_{32, 64}. It counts the number of set bits in a value.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000753/// @returns 0 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000754uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000755 if (isSingleWord())
756 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000757 uint32_t Count = 0;
758 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000759 Count += CountPopulation_64(pVal[i]);
760 return Count;
761}
762
763
Reid Spencere81d2da2007-02-16 22:36:51 +0000764/// byteSwap - This function returns a byte-swapped representation of the
Zhou Shengff4304f2007-02-09 07:48:24 +0000765/// this APInt.
Reid Spencere81d2da2007-02-16 22:36:51 +0000766APInt APInt::byteSwap() const {
767 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
768 if (BitWidth == 16)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000769 return APInt(BitWidth, ByteSwap_16(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000770 else if (BitWidth == 32)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000771 return APInt(BitWidth, ByteSwap_32(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000772 else if (BitWidth == 48) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000773 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
774 Tmp1 = ByteSwap_32(Tmp1);
775 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
776 Tmp2 = ByteSwap_16(Tmp2);
777 return
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000778 APInt(BitWidth,
779 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
Reid Spencere81d2da2007-02-16 22:36:51 +0000780 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000781 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000782 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000783 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000784 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000785 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000786 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000787 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
788 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000789 }
790 return Result;
791 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000792}
793
794/// GreatestCommonDivisor - This function returns the greatest common
795/// divisor of the two APInt values using Enclid's algorithm.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000796APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
797 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000798 APInt A = API1, B = API2;
799 while (!!B) {
800 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000801 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000802 A = T;
803 }
804 return A;
805}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000806
Zhou Shengd93f00c2007-02-12 20:02:55 +0000807/// DoubleRoundToAPInt - This function convert a double value to
808/// a APInt value.
Reid Spencere81d2da2007-02-16 22:36:51 +0000809APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000810 union {
811 double D;
812 uint64_t I;
813 } T;
814 T.D = Double;
815 bool isNeg = T.I >> 63;
816 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
817 if (exp < 0)
Reid Spencere81d2da2007-02-16 22:36:51 +0000818 return APInt(64ull, 0u);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000819 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
820 if (exp < 52)
Reid Spencere81d2da2007-02-16 22:36:51 +0000821 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
822 APInt(64u, mantissa >> (52 - exp));
823 APInt Tmp(exp + 1, mantissa);
824 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000825 return isNeg ? -Tmp : Tmp;
826}
827
Reid Spencerdb3faa62007-02-13 22:41:58 +0000828/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000829/// The layout for double is as following (IEEE Standard 754):
830/// --------------------------------------
831/// | Sign Exponent Fraction Bias |
832/// |-------------------------------------- |
833/// | 1[63] 11[62-52] 52[51-00] 1023 |
834/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000835double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000836
837 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000838 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
839 if (isSigned) {
840 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
841 return double(sext);
842 } else
843 return double(VAL);
844 }
845
Reid Spencer9c0696f2007-02-20 08:51:03 +0000846 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000847 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000848
849 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000850 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000851
852 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000853 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000854
Reid Spencer9c0696f2007-02-20 08:51:03 +0000855 // The exponent (without bias normalization) is just the number of bits
856 // we are using. Note that the sign bit is gone since we constructed the
857 // absolute value.
858 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000859
Reid Spencer9c0696f2007-02-20 08:51:03 +0000860 // Return infinity for exponent overflow
861 if (exp > 1023) {
862 if (!isSigned || !isNeg)
Reid Spencer61eb1802007-02-20 20:42:10 +0000863 return double(1.0E300 * 1.0E300); // positive infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000864 else
Reid Spencer61eb1802007-02-20 20:42:10 +0000865 return double(-1.0E300 * 1.0E300); // negative infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000866 }
867 exp += 1023; // Increment for 1023 bias
868
869 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
870 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000871 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000872 unsigned hiWord = whichWord(n-1);
873 if (hiWord == 0) {
874 mantissa = Tmp.pVal[0];
875 if (n > 52)
876 mantissa >>= n - 52; // shift down, we want the top 52 bits.
877 } else {
878 assert(hiWord > 0 && "huh?");
879 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
880 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
881 mantissa = hibits | lobits;
882 }
883
Zhou Shengd93f00c2007-02-12 20:02:55 +0000884 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000885 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000886 union {
887 double D;
888 uint64_t I;
889 } T;
890 T.I = sign | (exp << 52) | mantissa;
891 return T.D;
892}
893
Reid Spencere81d2da2007-02-16 22:36:51 +0000894// Truncate to new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000895void APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000896 assert(width < BitWidth && "Invalid APInt Truncate request");
897}
898
899// Sign extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000900void APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000901 assert(width > BitWidth && "Invalid APInt SignExtend request");
902}
903
904// Zero extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000905void APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000906 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
907}
908
Zhou Shengff4304f2007-02-09 07:48:24 +0000909/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000910/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000911APInt APInt::ashr(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000912 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000913 if (API.isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000914 API.VAL =
915 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
916 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
917 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
Zhou Sheng0b706b12007-02-08 14:35:19 +0000918 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000919 if (shiftAmt >= API.BitWidth) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000920 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
Reid Spencera58f0582007-02-18 20:09:41 +0000921 (API.getNumWords()-1) * APINT_WORD_SIZE);
Reid Spencer443b5702007-02-18 00:44:22 +0000922 API.pVal[API.getNumWords() - 1] =
923 ~uint64_t(0UL) >>
924 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000925 } else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000926 uint32_t i = 0;
Reid Spencere81d2da2007-02-16 22:36:51 +0000927 for (; i < API.BitWidth - shiftAmt; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000928 if (API[i+shiftAmt])
929 API.set(i);
930 else
931 API.clear(i);
Reid Spencere81d2da2007-02-16 22:36:51 +0000932 for (; i < API.BitWidth; ++i)
933 if (API[API.BitWidth-1])
Zhou Shengb04973e2007-02-15 06:36:31 +0000934 API.set(i);
935 else API.clear(i);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000936 }
937 }
938 return API;
939}
940
Zhou Shengff4304f2007-02-09 07:48:24 +0000941/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000942/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000943APInt APInt::lshr(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000944 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000945 if (API.isSingleWord())
946 API.VAL >>= shiftAmt;
947 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000948 if (shiftAmt >= API.BitWidth)
Reid Spencera58f0582007-02-18 20:09:41 +0000949 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000950 uint32_t i = 0;
Reid Spencere81d2da2007-02-16 22:36:51 +0000951 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000952 if (API[i+shiftAmt]) API.set(i);
953 else API.clear(i);
Reid Spencere81d2da2007-02-16 22:36:51 +0000954 for (; i < API.BitWidth; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000955 API.clear(i);
956 }
957 return API;
958}
959
Zhou Shengff4304f2007-02-09 07:48:24 +0000960/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000961/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000962APInt APInt::shl(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000963 APInt API(*this);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000964 if (API.isSingleWord())
965 API.VAL <<= shiftAmt;
Reid Spencere81d2da2007-02-16 22:36:51 +0000966 else if (shiftAmt >= API.BitWidth)
Reid Spencera58f0582007-02-18 20:09:41 +0000967 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000968 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000969 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
970 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
Zhou Shengd93f00c2007-02-12 20:02:55 +0000971 API.pVal[i] = API.pVal[i-offset];
Reid Spencera58f0582007-02-18 20:09:41 +0000972 memset(API.pVal, 0, offset * APINT_WORD_SIZE);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000973 }
Reid Spencer443b5702007-02-18 00:44:22 +0000974 shiftAmt %= APINT_BITS_PER_WORD;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000975 uint32_t i;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000976 for (i = API.getNumWords() - 1; i > 0; --i)
977 API.pVal[i] = (API.pVal[i] << shiftAmt) |
Reid Spencer443b5702007-02-18 00:44:22 +0000978 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
Zhou Shengd93f00c2007-02-12 20:02:55 +0000979 API.pVal[i] <<= shiftAmt;
Zhou Sheng0b706b12007-02-08 14:35:19 +0000980 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000981 API.clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +0000982 return API;
983}
984
Reid Spencer9c0696f2007-02-20 08:51:03 +0000985/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
986/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
987/// variables here have the same names as in the algorithm. Comments explain
988/// the algorithm and any deviation from it.
989static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
990 uint32_t m, uint32_t n) {
991 assert(u && "Must provide dividend");
992 assert(v && "Must provide divisor");
993 assert(q && "Must provide quotient");
Reid Spencer9d6c9192007-02-24 03:58:46 +0000994 assert(u != v && u != q && v != q && "Must us different memory");
Reid Spencer9c0696f2007-02-20 08:51:03 +0000995 assert(n>1 && "n must be > 1");
996
997 // Knuth uses the value b as the base of the number system. In our case b
998 // is 2^31 so we just set it to -1u.
999 uint64_t b = uint64_t(1) << 32;
1000
Reid Spencer9d6c9192007-02-24 03:58:46 +00001001 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1002 DEBUG(cerr << "KnuthDiv: original:");
1003 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1004 DEBUG(cerr << " by");
1005 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1006 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001007 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1008 // u and v by d. Note that we have taken Knuth's advice here to use a power
1009 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1010 // 2 allows us to shift instead of multiply and it is easy to determine the
1011 // shift amount from the leading zeros. We are basically normalizing the u
1012 // and v so that its high bits are shifted to the top of v's range without
1013 // overflow. Note that this can require an extra word in u so that u must
1014 // be of length m+n+1.
1015 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1016 uint32_t v_carry = 0;
1017 uint32_t u_carry = 0;
1018 if (shift) {
1019 for (uint32_t i = 0; i < m+n; ++i) {
1020 uint32_t u_tmp = u[i] >> (32 - shift);
1021 u[i] = (u[i] << shift) | u_carry;
1022 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001023 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001024 for (uint32_t i = 0; i < n; ++i) {
1025 uint32_t v_tmp = v[i] >> (32 - shift);
1026 v[i] = (v[i] << shift) | v_carry;
1027 v_carry = v_tmp;
1028 }
1029 }
1030 u[m+n] = u_carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001031 DEBUG(cerr << "KnuthDiv: normal:");
1032 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1033 DEBUG(cerr << " by");
1034 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1035 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001036
1037 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1038 int j = m;
1039 do {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001040 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001041 // D3. [Calculate q'.].
1042 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1043 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1044 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1045 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1046 // on v[n-2] determines at high speed most of the cases in which the trial
1047 // value qp is one too large, and it eliminates all cases where qp is two
1048 // too large.
Reid Spencer92904632007-02-23 01:57:13 +00001049 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001050 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencer92904632007-02-23 01:57:13 +00001051 uint64_t qp = dividend / v[n-1];
1052 uint64_t rp = dividend % v[n-1];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001053 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1054 qp--;
1055 rp += v[n-1];
Reid Spencer9d6c9192007-02-24 03:58:46 +00001056 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2])) {
1057 qp--;
1058 //rp += v[n-1];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001059 }
Reid Spencer92904632007-02-23 01:57:13 +00001060 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001061 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001062
Reid Spencer92904632007-02-23 01:57:13 +00001063 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1064 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1065 // consists of a simple multiplication by a one-place number, combined with
1066 // a subtraction. The digits (u[j+n]...u[j]) should be kept positive;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001067 bool borrow = false;
Reid Spencer92904632007-02-23 01:57:13 +00001068 for (uint32_t i = 0; i < n; ++i) {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001069 uint64_t u_tmp = borrow ? uint64_t(u[j+i] - 1) : uint64_t(u[j+i]);
1070 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
1071 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
1072 << ", subtrahend == " << subtrahend << '\n');
1073
Reid Spencer92904632007-02-23 01:57:13 +00001074 borrow = subtrahend > u_tmp || (borrow && u[j+i] == 0);
1075 u[j+i] = u_tmp - subtrahend;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001076 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001077 if (borrow) {
1078 borrow = u[j+n] == 0; // Was result negative?
1079 u[j+n]--; // handle the borrow
1080 }
1081 DEBUG(cerr << "KnuthDiv: after subtraction:");
1082 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1083 DEBUG(cerr << '\n');
Reid Spencer92904632007-02-23 01:57:13 +00001084 // if the result of this step is actually negative, (u[j+n]...u[j]) should
Reid Spencer9d6c9192007-02-24 03:58:46 +00001085 // be left as the true value plus b**(n+1), namely as the b's complement of
Reid Spencer92904632007-02-23 01:57:13 +00001086 // the true value, and a "borrow" to the left should be remembered.
1087 //
1088 if (borrow) {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001089 bool carry = true;
1090 for (uint32_t i = 0; i <= n; ++i) {
1091 u[j+i] = ~u[j+i] + carry; // b's complement
1092 carry = u[j+i] == 0;
1093 }
Reid Spencer92904632007-02-23 01:57:13 +00001094 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001095 DEBUG(cerr << "KnuthDiv: after complement:");
1096 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1097 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001098
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
Reid Spencer92904632007-02-23 01:57:13 +00001105 // this possibility. Decrease q[j] by 1
1106 q[j]--;
1107 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1108 // A carry will occur to the left of u[j+n], and it should be ignored
1109 // since it cancels with the borrow that occurred in D4.
1110 bool carry = false;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001111 for (uint32_t i = 0; i < n; i++) {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001112 uint32_t limit = std::min(u[j+i],v[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001113 u[j+i] += v[i] + carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001114 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001115 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001116 u[j+n] += carry;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001117 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001118 DEBUG(cerr << "KnuthDiv: after correction:");
1119 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1120 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001121
Reid Spencer92904632007-02-23 01:57:13 +00001122 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1123 } while (--j >= 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001124
Reid Spencer9d6c9192007-02-24 03:58:46 +00001125 DEBUG(cerr << "KnuthDiv: quotient:");
1126 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1127 DEBUG(cerr << '\n');
1128
Reid Spencer9c0696f2007-02-20 08:51:03 +00001129 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1130 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1131 // compute the remainder (urem uses this).
1132 if (r) {
1133 // The value d is expressed by the "shift" value above since we avoided
1134 // multiplication by d by using a shift left. So, all we have to do is
1135 // shift right here. In order to mak
Reid Spencer9c0696f2007-02-20 08:51:03 +00001136 uint32_t carry = 0;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001137 DEBUG(cerr << "KnuthDiv: remainder:");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001138 for (int i = n-1; i >= 0; i--) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001139 r[i] = (u[i] >> shift) | carry;
Reid Spencer92904632007-02-23 01:57:13 +00001140 carry = u[i] << shift;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001141 DEBUG(cerr << " " << r[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001142 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001143 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001144 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001145 DEBUG(cerr << std::setbase(10) << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001146}
1147
1148// This function makes calling KnuthDiv a little more convenient. It uses
1149// APInt parameters instead of uint32_t* parameters. It can also divide APInt
1150// values of different widths.
1151void APInt::divide(const APInt LHS, uint32_t lhsWords,
1152 const APInt &RHS, uint32_t rhsWords,
1153 APInt *Quotient, APInt *Remainder)
1154{
1155 assert(lhsWords >= rhsWords && "Fractional result");
1156
1157 // First, compose the values into an array of 32-bit words instead of
1158 // 64-bit words. This is a necessity of both the "short division" algorithm
1159 // and the the Knuth "classical algorithm" which requires there to be native
1160 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1161 // can't use 64-bit operands here because we don't have native results of
1162 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1163 // work on large-endian machines.
1164 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1165 uint32_t n = rhsWords * 2;
1166 uint32_t m = (lhsWords * 2) - n;
1167 // FIXME: allocate space on stack if m and n are sufficiently small.
1168 uint32_t *U = new uint32_t[m + n + 1];
1169 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1170 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001171 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001172 U[i * 2] = tmp & mask;
1173 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1174 }
1175 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1176
1177 uint32_t *V = new uint32_t[n];
1178 memset(V, 0, (n)*sizeof(uint32_t));
1179 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001180 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001181 V[i * 2] = tmp & mask;
1182 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1183 }
1184
1185 // Set up the quotient and remainder
1186 uint32_t *Q = new uint32_t[m+n];
1187 memset(Q, 0, (m+n) * sizeof(uint32_t));
1188 uint32_t *R = 0;
1189 if (Remainder) {
1190 R = new uint32_t[n];
1191 memset(R, 0, n * sizeof(uint32_t));
1192 }
1193
1194 // Now, adjust m and n for the Knuth division. n is the number of words in
1195 // the divisor. m is the number of words by which the dividend exceeds the
1196 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1197 // contain any zero words or the Knuth algorithm fails.
1198 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1199 n--;
1200 m++;
1201 }
1202 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1203 m--;
1204
1205 // If we're left with only a single word for the divisor, Knuth doesn't work
1206 // so we implement the short division algorithm here. This is much simpler
1207 // and faster because we are certain that we can divide a 64-bit quantity
1208 // by a 32-bit quantity at hardware speed and short division is simply a
1209 // series of such operations. This is just like doing short division but we
1210 // are using base 2^32 instead of base 10.
1211 assert(n != 0 && "Divide by zero?");
1212 if (n == 1) {
1213 uint32_t divisor = V[0];
1214 uint32_t remainder = 0;
1215 for (int i = m+n-1; i >= 0; i--) {
1216 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1217 if (partial_dividend == 0) {
1218 Q[i] = 0;
1219 remainder = 0;
1220 } else if (partial_dividend < divisor) {
1221 Q[i] = 0;
1222 remainder = partial_dividend;
1223 } else if (partial_dividend == divisor) {
1224 Q[i] = 1;
1225 remainder = 0;
1226 } else {
1227 Q[i] = partial_dividend / divisor;
1228 remainder = partial_dividend - (Q[i] * divisor);
1229 }
1230 }
1231 if (R)
1232 R[0] = remainder;
1233 } else {
1234 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1235 // case n > 1.
1236 KnuthDiv(U, V, Q, R, m, n);
1237 }
1238
1239 // If the caller wants the quotient
1240 if (Quotient) {
1241 // Set up the Quotient value's memory.
1242 if (Quotient->BitWidth != LHS.BitWidth) {
1243 if (Quotient->isSingleWord())
1244 Quotient->VAL = 0;
1245 else
1246 delete Quotient->pVal;
1247 Quotient->BitWidth = LHS.BitWidth;
1248 if (!Quotient->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001249 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001250 } else
1251 Quotient->clear();
1252
1253 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1254 // order words.
1255 if (lhsWords == 1) {
1256 uint64_t tmp =
1257 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1258 if (Quotient->isSingleWord())
1259 Quotient->VAL = tmp;
1260 else
1261 Quotient->pVal[0] = tmp;
1262 } else {
1263 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1264 for (unsigned i = 0; i < lhsWords; ++i)
1265 Quotient->pVal[i] =
1266 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1267 }
1268 }
1269
1270 // If the caller wants the remainder
1271 if (Remainder) {
1272 // Set up the Remainder value's memory.
1273 if (Remainder->BitWidth != RHS.BitWidth) {
1274 if (Remainder->isSingleWord())
1275 Remainder->VAL = 0;
1276 else
1277 delete Remainder->pVal;
1278 Remainder->BitWidth = RHS.BitWidth;
1279 if (!Remainder->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001280 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001281 } else
1282 Remainder->clear();
1283
1284 // The remainder is in R. Reconstitute the remainder into Remainder's low
1285 // order words.
1286 if (rhsWords == 1) {
1287 uint64_t tmp =
1288 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1289 if (Remainder->isSingleWord())
1290 Remainder->VAL = tmp;
1291 else
1292 Remainder->pVal[0] = tmp;
1293 } else {
1294 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1295 for (unsigned i = 0; i < rhsWords; ++i)
1296 Remainder->pVal[i] =
1297 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1298 }
1299 }
1300
1301 // Clean up the memory we allocated.
1302 delete [] U;
1303 delete [] V;
1304 delete [] Q;
1305 delete [] R;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001306}
1307
Zhou Shengff4304f2007-02-09 07:48:24 +00001308/// Unsigned divide this APInt by APInt RHS.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001309/// @brief Unsigned division function for APInt.
Reid Spencere81d2da2007-02-16 22:36:51 +00001310APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001311 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001312
1313 // First, deal with the easy case
1314 if (isSingleWord()) {
1315 assert(RHS.VAL != 0 && "Divide by zero?");
1316 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001317 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001318
Reid Spencer71bd08f2007-02-17 02:07:07 +00001319 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001320 uint32_t rhsBits = RHS.getActiveBits();
1321 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001322 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001323 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001324 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001325
1326 // Deal with some degenerate cases
1327 if (!lhsWords)
Reid Spencere0cdd332007-02-21 08:21:52 +00001328 // 0 / X ===> 0
1329 return APInt(BitWidth, 0);
1330 else if (lhsWords < rhsWords || this->ult(RHS)) {
1331 // X / Y ===> 0, iff X < Y
1332 return APInt(BitWidth, 0);
1333 } else if (*this == RHS) {
1334 // X / X ===> 1
1335 return APInt(BitWidth, 1);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001336 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001337 // All high words are zero, just use native divide
Reid Spencere0cdd332007-02-21 08:21:52 +00001338 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001339 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001340
1341 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1342 APInt Quotient(1,0); // to hold result.
1343 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1344 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001345}
1346
1347/// Unsigned remainder operation on APInt.
1348/// @brief Function for unsigned remainder operation.
Reid Spencere81d2da2007-02-16 22:36:51 +00001349APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001350 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001351 if (isSingleWord()) {
1352 assert(RHS.VAL != 0 && "Remainder by zero?");
1353 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001354 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001355
Reid Spencere0cdd332007-02-21 08:21:52 +00001356 // Get some facts about the LHS
1357 uint32_t lhsBits = getActiveBits();
1358 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001359
1360 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001361 uint32_t rhsBits = RHS.getActiveBits();
1362 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001363 assert(rhsWords && "Performing remainder operation by zero ???");
1364
Reid Spencer71bd08f2007-02-17 02:07:07 +00001365 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001366 if (lhsWords == 0) {
Reid Spencere0cdd332007-02-21 08:21:52 +00001367 // 0 % Y ===> 0
1368 return APInt(BitWidth, 0);
1369 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1370 // X % Y ===> X, iff X < Y
1371 return *this;
1372 } else if (*this == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001373 // X % X == 0;
Reid Spencere0cdd332007-02-21 08:21:52 +00001374 return APInt(BitWidth, 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001375 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001376 // All high words are zero, just use native remainder
Reid Spencere0cdd332007-02-21 08:21:52 +00001377 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001378 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001379
1380 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1381 APInt Remainder(1,0);
1382 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1383 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001384}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001385
1386/// @brief Converts a char array into an integer.
Reid Spencer385f7542007-02-21 03:55:44 +00001387void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001388 uint8_t radix) {
Reid Spencer385f7542007-02-21 03:55:44 +00001389 // Check our assumptions here
Reid Spencer5e0a8512007-02-17 03:16:00 +00001390 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1391 "Radix should be 2, 8, 10, or 16!");
Reid Spencer385f7542007-02-21 03:55:44 +00001392 assert(str && "String is null?");
1393 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1394 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1395 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1396 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1397
1398 // Allocate memory
1399 if (!isSingleWord())
1400 pVal = getClearedMemory(getNumWords());
1401
1402 // Figure out if we can shift instead of multiply
1403 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1404
1405 // Set up an APInt for the digit to add outside the loop so we don't
1406 // constantly construct/destruct it.
1407 APInt apdigit(getBitWidth(), 0);
1408 APInt apradix(getBitWidth(), radix);
1409
1410 // Enter digit traversal loop
1411 for (unsigned i = 0; i < slen; i++) {
1412 // Get a digit
1413 uint32_t digit = 0;
1414 char cdigit = str[i];
1415 if (isdigit(cdigit))
1416 digit = cdigit - '0';
1417 else if (isxdigit(cdigit))
1418 if (cdigit >= 'a')
1419 digit = cdigit - 'a' + 10;
1420 else if (cdigit >= 'A')
1421 digit = cdigit - 'A' + 10;
1422 else
1423 assert(0 && "huh?");
1424 else
1425 assert(0 && "Invalid character in digit string");
1426
1427 // Shift or multiple the value by the radix
1428 if (shift)
1429 this->shl(shift);
1430 else
1431 *this *= apradix;
1432
1433 // Add in the digit we just interpreted
1434 apdigit.pVal[0] = digit;
1435 *this += apdigit;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001436 }
1437}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001438
1439/// to_string - This function translates the APInt into a string.
1440std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1441 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1442 "Radix should be 2, 8, 10, or 16!");
1443 static const char *digits[] = {
1444 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1445 };
1446 std::string result;
1447 uint32_t bits_used = getActiveBits();
1448 if (isSingleWord()) {
1449 char buf[65];
1450 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1451 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1452 if (format) {
1453 if (wantSigned) {
1454 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1455 (APINT_BITS_PER_WORD-BitWidth);
1456 sprintf(buf, format, sextVal);
1457 } else
1458 sprintf(buf, format, VAL);
1459 } else {
1460 memset(buf, 0, 65);
1461 uint64_t v = VAL;
1462 while (bits_used) {
1463 uint32_t bit = v & 1;
1464 bits_used--;
1465 buf[bits_used] = digits[bit][0];
1466 v >>=1;
1467 }
1468 }
1469 result = buf;
1470 return result;
1471 }
1472
1473 if (radix != 10) {
1474 uint64_t mask = radix - 1;
1475 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1476 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1477 for (uint32_t i = 0; i < getNumWords(); ++i) {
1478 uint64_t value = pVal[i];
1479 for (uint32_t j = 0; j < nibbles; ++j) {
1480 result.insert(0, digits[ value & mask ]);
1481 value >>= shift;
1482 }
1483 }
1484 return result;
1485 }
1486
1487 APInt tmp(*this);
1488 APInt divisor(4, radix);
1489 APInt zero(tmp.getBitWidth(), 0);
1490 size_t insert_at = 0;
1491 if (wantSigned && tmp[BitWidth-1]) {
1492 // They want to print the signed version and it is a negative value
1493 // Flip the bits and add one to turn it into the equivalent positive
1494 // value and put a '-' in the result.
1495 tmp.flip();
1496 tmp++;
1497 result = "-";
1498 insert_at = 1;
1499 }
Reid Spencere549c492007-02-21 00:29:48 +00001500 if (tmp == APInt(tmp.getBitWidth(), 0))
Reid Spencer9c0696f2007-02-20 08:51:03 +00001501 result = "0";
1502 else while (tmp.ne(zero)) {
1503 APInt APdigit(1,0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001504 APInt tmp2(tmp.getBitWidth(), 0);
Reid Spencer385f7542007-02-21 03:55:44 +00001505 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1506 &APdigit);
1507 uint32_t digit = APdigit.getValue();
1508 assert(digit < radix && "divide failed");
1509 result.insert(insert_at,digits[digit]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001510 tmp = tmp2;
1511 }
1512
1513 return result;
1514}
1515
Reid Spencer385f7542007-02-21 03:55:44 +00001516#ifndef NDEBUG
1517void APInt::dump() const
1518{
1519 std::cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
1520 if (isSingleWord())
1521 std::cerr << VAL;
1522 else for (unsigned i = getNumWords(); i > 0; i--) {
1523 std::cerr << pVal[i-1] << " ";
1524 }
1525 std::cerr << " (" << this->toString(10, false) << ")\n" << std::setbase(10);
1526}
1527#endif