blob: 44aed755491fca2100ea22dc9d8b58aae79acdb0 [file] [log] [blame]
Zhou Shengfd43dcf2007-02-06 03:00:16 +00001//===-- APInt.cpp - Implement APInt class ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Reid Spencer610fad82007-02-24 10:01:42 +00005// This file was developed by Sheng Zhou and Reid Spencer and is distributed
6// under the // University of Illinois Open Source License. See LICENSE.TXT
7// for details.
Zhou Shengfd43dcf2007-02-06 03:00:16 +00008//
9//===----------------------------------------------------------------------===//
10//
Reid Spencer5d0d05c2007-02-25 19:32:03 +000011// This file implements a class to represent arbitrary precision integer
12// constant values and provide a variety of arithmetic operations on them.
Zhou Shengfd43dcf2007-02-06 03:00:16 +000013//
14//===----------------------------------------------------------------------===//
15
Reid Spencer9d6c9192007-02-24 03:58:46 +000016#define DEBUG_TYPE "apint"
Zhou Shengfd43dcf2007-02-06 03:00:16 +000017#include "llvm/ADT/APInt.h"
18#include "llvm/DerivedTypes.h"
Reid Spencer9d6c9192007-02-24 03:58:46 +000019#include "llvm/Support/Debug.h"
Zhou Shengfd43dcf2007-02-06 03:00:16 +000020#include "llvm/Support/MathExtras.h"
Zhou Shenga3832fd2007-02-07 06:14:53 +000021#include <cstring>
Zhou Shengfd43dcf2007-02-06 03:00:16 +000022#include <cstdlib>
Reid Spencer385f7542007-02-21 03:55:44 +000023#ifndef NDEBUG
Reid Spencer385f7542007-02-21 03:55:44 +000024#include <iomanip>
25#endif
26
Zhou Shengfd43dcf2007-02-06 03:00:16 +000027using namespace llvm;
28
Reid Spencer5d0d05c2007-02-25 19:32:03 +000029/// A utility function for allocating memory, checking for allocation failures,
30/// and ensuring the contents are zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000031inline 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 Spencer5d0d05c2007-02-25 19:32:03 +000038/// A utility function for allocating memory and checking for allocation
39/// failure. The content is not zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000040inline static uint64_t* getMemory(uint32_t numWords) {
41 uint64_t * result = new uint64_t[numWords];
42 assert(result && "APInt memory allocation fails!");
43 return result;
44}
45
46APInt::APInt(uint32_t numBits, uint64_t val)
Reid Spencer385f7542007-02-21 03:55:44 +000047 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000048 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
49 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Reid Spencer5d0d05c2007-02-25 19:32:03 +000050 if (isSingleWord())
51 VAL = val;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000052 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000053 pVal = getClearedMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000054 pVal[0] = val;
55 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +000056 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000057}
58
Reid Spenceraf0e9562007-02-18 18:38:44 +000059APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
Reid Spencer385f7542007-02-21 03:55:44 +000060 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000061 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
62 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000063 assert(bigVal && "Null pointer detected!");
64 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +000065 VAL = bigVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +000066 else {
Reid Spencer610fad82007-02-24 10:01:42 +000067 // Get memory, cleared to 0
68 pVal = getClearedMemory(getNumWords());
69 // Calculate the number of words to copy
70 uint32_t words = std::min<uint32_t>(numWords, getNumWords());
71 // Copy the words from bigVal to pVal
72 memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000073 }
Reid Spencer610fad82007-02-24 10:01:42 +000074 // Make sure unused high bits are cleared
75 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000076}
77
Reid Spenceraf0e9562007-02-18 18:38:44 +000078APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000079 uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000080 : BitWidth(numbits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000081 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000082}
83
Reid Spencer9c0696f2007-02-20 08:51:03 +000084APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000085 : BitWidth(numbits), VAL(0) {
Zhou Shenga3832fd2007-02-07 06:14:53 +000086 assert(!Val.empty() && "String empty?");
Reid Spencere81d2da2007-02-16 22:36:51 +000087 fromString(numbits, Val.c_str(), Val.size(), radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000088}
89
Reid Spencer54362ca2007-02-20 23:40:25 +000090APInt::APInt(const APInt& that)
Reid Spencer385f7542007-02-21 03:55:44 +000091 : BitWidth(that.BitWidth), VAL(0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +000092 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +000093 VAL = that.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000094 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000095 pVal = getMemory(getNumWords());
Reid Spencer54362ca2007-02-20 23:40:25 +000096 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000097 }
98}
99
100APInt::~APInt() {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000101 if (!isSingleWord() && pVal)
102 delete[] pVal;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000103}
104
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000105APInt& 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
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000114APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000115 if (isSingleWord())
116 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000117 else {
118 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000119 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000120 }
121 return *this;
122}
123
Reid Spenceraf0e9562007-02-18 18:38:44 +0000124/// add_1 - This function adds a single "digit" integer, y, to the multiple
125/// "digit" integer array, x[]. x[] is modified to reflect the addition and
126/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000127/// @returns the carry of the addition.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000128static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000129 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000130 dest[i] = y + x[i];
131 if (dest[i] < y)
Reid Spencer610fad82007-02-24 10:01:42 +0000132 y = 1; // Carry one to next digit.
Reid Spencerf2c521c2007-02-18 06:39:42 +0000133 else {
Reid Spencer610fad82007-02-24 10:01:42 +0000134 y = 0; // No need to carry so exit early
Reid Spencerf2c521c2007-02-18 06:39:42 +0000135 break;
136 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000137 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000138 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000139}
140
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000141/// @brief Prefix increment operator. Increments the APInt by one.
142APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000143 if (isSingleWord())
144 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000145 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000146 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000147 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000148}
149
Reid Spenceraf0e9562007-02-18 18:38:44 +0000150/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
151/// the multi-digit integer array, x[], propagating the borrowed 1 value until
152/// no further borrowing is neeeded or it runs out of "digits" in x. The result
153/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
154/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000155/// @returns the borrow out of the subtraction
156static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000157 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000158 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000159 x[i] -= y;
160 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000161 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000162 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000163 y = 0; // No need to borrow
164 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000165 }
166 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000167 return bool(y);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000168}
169
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000170/// @brief Prefix decrement operator. Decrements the APInt by one.
171APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000172 if (isSingleWord())
173 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000174 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000175 sub_1(pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000176 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000177}
178
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000179/// add - This function adds the integer array x to the integer array Y and
180/// places the result in dest.
181/// @returns the carry out from the addition
182/// @brief General addition of 64-bit integer arrays
Reid Spencer9d6c9192007-02-24 03:58:46 +0000183static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
184 uint32_t len) {
185 bool carry = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000186 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer92904632007-02-23 01:57:13 +0000187 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer54362ca2007-02-20 23:40:25 +0000188 dest[i] = x[i] + y[i] + carry;
Reid Spencer60c0a6a2007-02-21 05:44:56 +0000189 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000190 }
191 return carry;
192}
193
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000194/// Adds the RHS APint to this APInt.
195/// @returns this, after addition of RHS.
196/// @brief Addition assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000197APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000198 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000199 if (isSingleWord())
200 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000201 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000202 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000203 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000204 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000205}
206
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000207/// Subtracts the integer array y from the integer array x
208/// @returns returns the borrow out.
209/// @brief Generalized subtraction of 64-bit integer arrays.
Reid Spencer9d6c9192007-02-24 03:58:46 +0000210static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
211 uint32_t len) {
Reid Spencer385f7542007-02-21 03:55:44 +0000212 bool borrow = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000213 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer385f7542007-02-21 03:55:44 +0000214 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
215 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
216 dest[i] = x_tmp - y[i];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000217 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000218 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000219}
220
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000221/// Subtracts the RHS APInt from this APInt
222/// @returns this, after subtraction
223/// @brief Subtraction assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000224APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000225 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000226 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000227 VAL -= RHS.VAL;
228 else
229 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000230 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000231}
232
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000233/// Multiplies an integer array, x by a a uint64_t integer and places the result
234/// into dest.
235/// @returns the carry out of the multiplication.
236/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Reid Spencer610fad82007-02-24 10:01:42 +0000237static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
238 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer5e0a8512007-02-17 03:16:00 +0000239 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000240 uint64_t carry = 0;
241
242 // For each digit of x.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000243 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000244 // Split x into high and low words
245 uint64_t lx = x[i] & 0xffffffffULL;
246 uint64_t hx = x[i] >> 32;
247 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000248 // hasCarry == 0, no carry
249 // hasCarry == 1, has carry
250 // hasCarry == 2, no carry and the calculation result == 0.
251 uint8_t hasCarry = 0;
252 dest[i] = carry + lx * ly;
253 // Determine if the add above introduces carry.
254 hasCarry = (dest[i] < carry) ? 1 : 0;
255 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
256 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
257 // (2^32 - 1) + 2^32 = 2^64.
258 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
259
260 carry += (lx * hy) & 0xffffffffULL;
261 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
262 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
263 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
264 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000265 return carry;
266}
267
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000268/// Multiplies integer array x by integer array y and stores the result into
269/// the integer array dest. Note that dest's size must be >= xlen + ylen.
270/// @brief Generalized multiplicate of integer arrays.
Reid Spencer610fad82007-02-24 10:01:42 +0000271static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[],
272 uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000273 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000274 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000275 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencere0cdd332007-02-21 08:21:52 +0000276 uint64_t carry = 0, lx = 0, hx = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000277 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000278 lx = x[j] & 0xffffffffULL;
279 hx = x[j] >> 32;
280 // hasCarry - A flag to indicate if has carry.
281 // hasCarry == 0, no carry
282 // hasCarry == 1, has carry
283 // hasCarry == 2, no carry and the calculation result == 0.
284 uint8_t hasCarry = 0;
285 uint64_t resul = carry + lx * ly;
286 hasCarry = (resul < carry) ? 1 : 0;
287 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
288 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
289
290 carry += (lx * hy) & 0xffffffffULL;
291 resul = (carry << 32) | (resul & 0xffffffffULL);
292 dest[i+j] += resul;
293 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
294 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
295 ((lx * hy) >> 32) + hx * hy;
296 }
297 dest[i+xlen] = carry;
298 }
299}
300
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000301APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000302 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencere0cdd332007-02-21 08:21:52 +0000303 if (isSingleWord()) {
Reid Spencer61eb1802007-02-20 20:42:10 +0000304 VAL *= RHS.VAL;
Reid Spencere0cdd332007-02-21 08:21:52 +0000305 clearUnusedBits();
306 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000307 }
Reid Spencere0cdd332007-02-21 08:21:52 +0000308
309 // Get some bit facts about LHS and check for zero
310 uint32_t lhsBits = getActiveBits();
311 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
312 if (!lhsWords)
313 // 0 * X ===> 0
314 return *this;
315
316 // Get some bit facts about RHS and check for zero
317 uint32_t rhsBits = RHS.getActiveBits();
318 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
319 if (!rhsWords) {
320 // X * 0 ===> 0
321 clear();
322 return *this;
323 }
324
325 // Allocate space for the result
326 uint32_t destWords = rhsWords + lhsWords;
327 uint64_t *dest = getMemory(destWords);
328
329 // Perform the long multiply
330 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
331
332 // Copy result back into *this
333 clear();
334 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
335 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
336
337 // delete dest array and return
338 delete[] dest;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000339 return *this;
340}
341
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000342APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000343 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000344 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000345 VAL &= RHS.VAL;
346 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000347 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000348 uint32_t numWords = getNumWords();
349 for (uint32_t i = 0; i < numWords; ++i)
350 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000351 return *this;
352}
353
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000354APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000355 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000356 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000357 VAL |= RHS.VAL;
358 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000359 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000360 uint32_t numWords = getNumWords();
361 for (uint32_t i = 0; i < numWords; ++i)
362 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000363 return *this;
364}
365
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000366APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000367 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000368 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000369 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000370 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000371 return *this;
372 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000373 uint32_t numWords = getNumWords();
374 for (uint32_t i = 0; i < numWords; ++i)
375 pVal[i] ^= RHS.pVal[i];
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000376 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000377}
378
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000379APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000380 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000381 if (isSingleWord())
382 return APInt(getBitWidth(), VAL & RHS.VAL);
383
Reid Spenceraf0e9562007-02-18 18:38:44 +0000384 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000385 uint64_t* val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000386 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000387 val[i] = pVal[i] & RHS.pVal[i];
388 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000389}
390
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000391APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000392 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000393 if (isSingleWord())
394 return APInt(getBitWidth(), VAL | RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000395
Reid Spenceraf0e9562007-02-18 18:38:44 +0000396 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000397 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000398 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000399 val[i] = pVal[i] | RHS.pVal[i];
400 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000401}
402
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000403APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000404 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000405 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000406 return APInt(BitWidth, VAL ^ RHS.VAL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000407
Reid Spenceraf0e9562007-02-18 18:38:44 +0000408 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000409 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000410 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000411 val[i] = pVal[i] ^ RHS.pVal[i];
412
413 // 0^0==1 so clear the high bits in case they got set.
414 return APInt(val, getBitWidth()).clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000415}
416
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000417bool APInt::operator !() const {
418 if (isSingleWord())
419 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000420
421 for (uint32_t i = 0; i < getNumWords(); ++i)
422 if (pVal[i])
423 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000424 return true;
425}
426
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000427APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000428 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000429 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000430 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer61eb1802007-02-20 20:42:10 +0000431 APInt Result(*this);
432 Result *= RHS;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000433 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000434}
435
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000436APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000437 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000438 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000439 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000440 APInt Result(BitWidth, 0);
441 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000442 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000443}
444
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000445APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000446 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000447 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000448 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000449 APInt Result(BitWidth, 0);
450 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000451 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000452}
453
Reid Spenceraf0e9562007-02-18 18:38:44 +0000454bool APInt::operator[](uint32_t bitPosition) const {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000455 return (maskBit(bitPosition) &
456 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000457}
458
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000459bool APInt::operator==(const APInt& RHS) const {
Reid Spencer54362ca2007-02-20 23:40:25 +0000460 if (isSingleWord())
461 return VAL == RHS.VAL;
462
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000463 // Get some facts about the number of bits used in the two operands.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000464 uint32_t n1 = getActiveBits();
465 uint32_t n2 = RHS.getActiveBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000466
467 // If the number of bits isn't the same, they aren't equal
Reid Spencer54362ca2007-02-20 23:40:25 +0000468 if (n1 != n2)
469 return false;
470
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000471 // If the number of bits fits in a word, we only need to compare the low word.
Reid Spencer54362ca2007-02-20 23:40:25 +0000472 if (n1 <= APINT_BITS_PER_WORD)
473 return pVal[0] == RHS.pVal[0];
474
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000475 // Otherwise, compare everything
Reid Spencer54362ca2007-02-20 23:40:25 +0000476 for (int i = whichWord(n1 - 1); i >= 0; --i)
477 if (pVal[i] != RHS.pVal[i])
478 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000479 return true;
480}
481
Zhou Shenga3832fd2007-02-07 06:14:53 +0000482bool APInt::operator==(uint64_t Val) const {
483 if (isSingleWord())
484 return VAL == Val;
Reid Spencer54362ca2007-02-20 23:40:25 +0000485
486 uint32_t n = getActiveBits();
487 if (n <= APINT_BITS_PER_WORD)
488 return pVal[0] == Val;
489 else
490 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000491}
492
Reid Spencere81d2da2007-02-16 22:36:51 +0000493bool APInt::ult(const APInt& RHS) const {
494 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
495 if (isSingleWord())
496 return VAL < RHS.VAL;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000497
498 // Get active bit length of both operands
499 uint32_t n1 = getActiveBits();
500 uint32_t n2 = RHS.getActiveBits();
501
502 // If magnitude of LHS is less than RHS, return true.
503 if (n1 < n2)
504 return true;
505
506 // If magnitude of RHS is greather than LHS, return false.
507 if (n2 < n1)
508 return false;
509
510 // If they bot fit in a word, just compare the low order word
511 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
512 return pVal[0] < RHS.pVal[0];
513
514 // Otherwise, compare all words
515 for (int i = whichWord(n1 - 1); i >= 0; --i) {
516 if (pVal[i] > RHS.pVal[i])
Reid Spencere81d2da2007-02-16 22:36:51 +0000517 return false;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000518 if (pVal[i] < RHS.pVal[i])
519 return true;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000520 }
521 return false;
522}
523
Reid Spencere81d2da2007-02-16 22:36:51 +0000524bool APInt::slt(const APInt& RHS) const {
525 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000526 if (isSingleWord()) {
527 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
528 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
529 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000530 }
Reid Spencera58f0582007-02-18 20:09:41 +0000531
532 APInt lhs(*this);
533 APInt rhs(*this);
534 bool lhsNegative = false;
535 bool rhsNegative = false;
536 if (lhs[BitWidth-1]) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000537 // Sign bit is set so make a note of it and perform two's complement
Reid Spencera58f0582007-02-18 20:09:41 +0000538 lhsNegative = true;
539 lhs.flip();
540 lhs++;
541 }
542 if (rhs[BitWidth-1]) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000543 // Sign bit is set so make a note of it and perform two's complement
Reid Spencera58f0582007-02-18 20:09:41 +0000544 rhsNegative = true;
545 rhs.flip();
546 rhs++;
547 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000548
549 // Now we have unsigned values to compare so do the comparison if necessary
550 // based on the negativeness of the values.
Reid Spencera58f0582007-02-18 20:09:41 +0000551 if (lhsNegative)
552 if (rhsNegative)
553 return !lhs.ult(rhs);
554 else
555 return true;
556 else if (rhsNegative)
557 return false;
558 else
559 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000560}
561
Reid Spenceraf0e9562007-02-18 18:38:44 +0000562APInt& APInt::set(uint32_t bitPosition) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000563 if (isSingleWord())
564 VAL |= maskBit(bitPosition);
565 else
566 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000567 return *this;
568}
569
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000570APInt& APInt::set() {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000571 if (isSingleWord()) {
572 VAL = -1ULL;
573 return clearUnusedBits();
Zhou Shengb04973e2007-02-15 06:36:31 +0000574 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000575
576 // Set all the bits in all the words.
577 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
578 pVal[i] = -1ULL;
579 // Clear the unused ones
580 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000581}
582
583/// Set the given bit to 0 whose position is given as "bitPosition".
584/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000585APInt& APInt::clear(uint32_t bitPosition) {
586 if (isSingleWord())
587 VAL &= ~maskBit(bitPosition);
588 else
589 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000590 return *this;
591}
592
593/// @brief Set every bit to 0.
594APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000595 if (isSingleWord())
596 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000597 else
Reid Spencera58f0582007-02-18 20:09:41 +0000598 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000599 return *this;
600}
601
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000602/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
603/// this APInt.
604APInt APInt::operator~() const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000605 APInt Result(*this);
606 Result.flip();
607 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000608}
609
610/// @brief Toggle every bit to its opposite value.
611APInt& APInt::flip() {
Reid Spencer9eec2412007-02-25 23:44:53 +0000612 if (isSingleWord()) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000613 VAL ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000614 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000615 }
Reid Spencer9eec2412007-02-25 23:44:53 +0000616 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000617 pVal[i] ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000618 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000619}
620
621/// Toggle a given bit to its opposite value whose position is given
622/// as "bitPosition".
623/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000624APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000625 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000626 if ((*this)[bitPosition]) clear(bitPosition);
627 else set(bitPosition);
628 return *this;
629}
630
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000631/// getMaxValue - This function returns the largest value
632/// for an APInt of the specified bit-width and if isSign == true,
633/// it should be largest signed value, otherwise unsigned value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000634APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000635 APInt Result(numBits, 0);
636 Result.set();
637 if (isSign)
638 Result.clear(numBits - 1);
639 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000640}
641
642/// getMinValue - This function returns the smallest value for
643/// an APInt of the given bit-width and if isSign == true,
644/// it should be smallest signed value, otherwise zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000645APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000646 APInt Result(numBits, 0);
647 if (isSign)
648 Result.set(numBits - 1);
649 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000650}
651
652/// getAllOnesValue - This function returns an all-ones value for
653/// an APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000654APInt APInt::getAllOnesValue(uint32_t numBits) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000655 return getMaxValue(numBits, false);
656}
657
658/// getNullValue - This function creates an '0' value for an
659/// APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000660APInt APInt::getNullValue(uint32_t numBits) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000661 return getMinValue(numBits, false);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000662}
663
Reid Spencer794f4722007-02-26 21:02:27 +0000664uint64_t APInt::getHashValue() const {
665 // LLVM only supports bit widths up to 2^23 so shift the bitwidth into the
666 // high range. This makes the hash unique for integer values < 2^41 bits and
667 // doesn't hurt for larger values.
668 uint64_t hash = uint64_t(BitWidth) << (APINT_BITS_PER_WORD - 23);
669
670 // Add the sum of the words to the hash.
671 if (isSingleWord())
672 hash += VAL;
673 else
674 for (uint32_t i = 0; i < getNumWords(); ++i)
675 hash += pVal[i];
676 return hash;
677}
678
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000679/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000680APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000681 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000682}
683
684/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000685APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000686 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
687 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000688}
689
Reid Spencere81d2da2007-02-16 22:36:51 +0000690bool APInt::isPowerOf2() const {
691 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
692}
693
Reid Spenceraf0e9562007-02-18 18:38:44 +0000694uint32_t APInt::countLeadingZeros() const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000695 uint32_t Count = 0;
Reid Spencere549c492007-02-21 00:29:48 +0000696 if (isSingleWord())
697 Count = CountLeadingZeros_64(VAL);
698 else {
699 for (uint32_t i = getNumWords(); i > 0u; --i) {
700 if (pVal[i-1] == 0)
701 Count += APINT_BITS_PER_WORD;
702 else {
703 Count += CountLeadingZeros_64(pVal[i-1]);
704 break;
705 }
706 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000707 }
Reid Spencerab2b2c82007-02-22 00:22:00 +0000708 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
709 if (remainder)
710 Count -= APINT_BITS_PER_WORD - remainder;
711 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000712}
713
Reid Spenceraf0e9562007-02-18 18:38:44 +0000714uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000715 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000716 return CountTrailingZeros_64(VAL);
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000717 uint32_t Count = 0;
718 uint32_t i = 0;
719 for (; i < getNumWords() && pVal[i] == 0; ++i)
720 Count += APINT_BITS_PER_WORD;
721 if (i < getNumWords())
722 Count += CountTrailingZeros_64(pVal[i]);
723 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000724}
725
Reid Spenceraf0e9562007-02-18 18:38:44 +0000726uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000727 if (isSingleWord())
728 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000729 uint32_t Count = 0;
730 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000731 Count += CountPopulation_64(pVal[i]);
732 return Count;
733}
734
Reid Spencere81d2da2007-02-16 22:36:51 +0000735APInt APInt::byteSwap() const {
736 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
737 if (BitWidth == 16)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000738 return APInt(BitWidth, ByteSwap_16(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000739 else if (BitWidth == 32)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000740 return APInt(BitWidth, ByteSwap_32(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000741 else if (BitWidth == 48) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000742 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
743 Tmp1 = ByteSwap_32(Tmp1);
744 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
745 Tmp2 = ByteSwap_16(Tmp2);
746 return
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000747 APInt(BitWidth,
748 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
Reid Spencere81d2da2007-02-16 22:36:51 +0000749 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000750 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000751 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000752 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000753 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000754 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000755 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000756 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
757 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000758 }
759 return Result;
760 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000761}
762
Zhou Sheng0b706b12007-02-08 14:35:19 +0000763APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
764 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000765 APInt A = API1, B = API2;
766 while (!!B) {
767 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000768 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000769 A = T;
770 }
771 return A;
772}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000773
Reid Spencere81d2da2007-02-16 22:36:51 +0000774APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000775 union {
776 double D;
777 uint64_t I;
778 } T;
779 T.D = Double;
780 bool isNeg = T.I >> 63;
781 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
782 if (exp < 0)
Reid Spencere81d2da2007-02-16 22:36:51 +0000783 return APInt(64ull, 0u);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000784 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
785 if (exp < 52)
Reid Spencere81d2da2007-02-16 22:36:51 +0000786 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
787 APInt(64u, mantissa >> (52 - exp));
788 APInt Tmp(exp + 1, mantissa);
789 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000790 return isNeg ? -Tmp : Tmp;
791}
792
Reid Spencerdb3faa62007-02-13 22:41:58 +0000793/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000794/// The layout for double is as following (IEEE Standard 754):
795/// --------------------------------------
796/// | Sign Exponent Fraction Bias |
797/// |-------------------------------------- |
798/// | 1[63] 11[62-52] 52[51-00] 1023 |
799/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000800double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000801
802 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000803 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
804 if (isSigned) {
805 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
806 return double(sext);
807 } else
808 return double(VAL);
809 }
810
Reid Spencer9c0696f2007-02-20 08:51:03 +0000811 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000812 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000813
814 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000815 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000816
817 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000818 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000819
Reid Spencer9c0696f2007-02-20 08:51:03 +0000820 // The exponent (without bias normalization) is just the number of bits
821 // we are using. Note that the sign bit is gone since we constructed the
822 // absolute value.
823 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000824
Reid Spencer9c0696f2007-02-20 08:51:03 +0000825 // Return infinity for exponent overflow
826 if (exp > 1023) {
827 if (!isSigned || !isNeg)
Reid Spencer61eb1802007-02-20 20:42:10 +0000828 return double(1.0E300 * 1.0E300); // positive infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000829 else
Reid Spencer61eb1802007-02-20 20:42:10 +0000830 return double(-1.0E300 * 1.0E300); // negative infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000831 }
832 exp += 1023; // Increment for 1023 bias
833
834 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
835 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000836 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000837 unsigned hiWord = whichWord(n-1);
838 if (hiWord == 0) {
839 mantissa = Tmp.pVal[0];
840 if (n > 52)
841 mantissa >>= n - 52; // shift down, we want the top 52 bits.
842 } else {
843 assert(hiWord > 0 && "huh?");
844 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
845 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
846 mantissa = hibits | lobits;
847 }
848
Zhou Shengd93f00c2007-02-12 20:02:55 +0000849 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000850 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000851 union {
852 double D;
853 uint64_t I;
854 } T;
855 T.I = sign | (exp << 52) | mantissa;
856 return T.D;
857}
858
Reid Spencere81d2da2007-02-16 22:36:51 +0000859// Truncate to new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000860void APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000861 assert(width < BitWidth && "Invalid APInt Truncate request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000862 assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
863 uint32_t wordsBefore = getNumWords();
864 BitWidth = width;
865 uint32_t wordsAfter = getNumWords();
866 if (wordsBefore != wordsAfter) {
867 if (wordsAfter == 1) {
868 uint64_t *tmp = pVal;
869 VAL = pVal[0];
870 delete tmp;
871 } else {
872 uint64_t *newVal = getClearedMemory(wordsAfter);
873 for (uint32_t i = 0; i < wordsAfter; ++i)
874 newVal[i] = pVal[i];
875 delete pVal;
876 pVal = newVal;
877 }
878 }
879 clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000880}
881
882// Sign extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000883void APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000884 assert(width > BitWidth && "Invalid APInt SignExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000885 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
Reid Spencer9eec2412007-02-25 23:44:53 +0000886 // If the sign bit isn't set, this is the same as zext.
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000887 if (!isNegative()) {
Reid Spencer9eec2412007-02-25 23:44:53 +0000888 zext(width);
889 return;
890 }
891
892 // The sign bit is set. First, get some facts
893 uint32_t wordsBefore = getNumWords();
894 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
895 BitWidth = width;
896 uint32_t wordsAfter = getNumWords();
897
898 // Mask the high order word appropriately
899 if (wordsBefore == wordsAfter) {
900 uint32_t newWordBits = width % APINT_BITS_PER_WORD;
901 // The extension is contained to the wordsBefore-1th word.
902 uint64_t mask = (~0ULL >> (APINT_BITS_PER_WORD - newWordBits)) << wordBits;
903 if (wordsBefore == 1)
904 VAL |= mask;
905 else
906 pVal[wordsBefore-1] |= mask;
907 clearUnusedBits();
908 return;
909 }
910
Reid Spencerf30b1882007-02-25 23:54:00 +0000911 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +0000912 uint64_t *newVal = getMemory(wordsAfter);
913 if (wordsBefore == 1)
914 newVal[0] = VAL | mask;
915 else {
916 for (uint32_t i = 0; i < wordsBefore; ++i)
917 newVal[i] = pVal[i];
918 newVal[wordsBefore-1] |= mask;
919 }
920 for (uint32_t i = wordsBefore; i < wordsAfter; i++)
921 newVal[i] = -1ULL;
922 if (wordsBefore != 1)
923 delete pVal;
924 pVal = newVal;
925 clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000926}
927
928// Zero extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000929void APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000930 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000931 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
932 uint32_t wordsBefore = getNumWords();
933 BitWidth = width;
934 uint32_t wordsAfter = getNumWords();
935 if (wordsBefore != wordsAfter) {
936 uint64_t *newVal = getClearedMemory(wordsAfter);
937 if (wordsBefore == 1)
938 newVal[0] = VAL;
939 else
940 for (uint32_t i = 0; i < wordsBefore; ++i)
941 newVal[i] = pVal[i];
942 if (wordsBefore != 1)
943 delete pVal;
944 pVal = newVal;
945 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000946}
947
Zhou Shengff4304f2007-02-09 07:48:24 +0000948/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000949/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000950APInt APInt::ashr(uint32_t shiftAmt) const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000951 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer24c4a8f2007-02-25 01:56:07 +0000952 if (isSingleWord()) {
953 if (shiftAmt == BitWidth)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000954 return APInt(BitWidth, 0); // undefined
955 else {
956 uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
Reid Spencer24c4a8f2007-02-25 01:56:07 +0000957 return APInt(BitWidth,
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000958 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
959 }
Zhou Sheng0b706b12007-02-08 14:35:19 +0000960 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +0000961
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000962 // If all the bits were shifted out, the result is 0 or -1. This avoids issues
963 // with shifting by the size of the integer type, which produces undefined
964 // results.
965 if (shiftAmt == BitWidth)
966 if (isNegative())
967 return APInt(BitWidth, -1ULL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000968 else
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000969 return APInt(BitWidth, 0);
970
971 // Create some space for the result.
972 uint64_t * val = new uint64_t[getNumWords()];
973
974 // If we are shifting less than a word, compute the shift with a simple carry
975 if (shiftAmt < APINT_BITS_PER_WORD) {
976 uint64_t carry = 0;
977 for (int i = getNumWords()-1; i >= 0; --i) {
978 val[i] = pVal[i] >> shiftAmt | carry;
979 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
980 }
981 return APInt(val, BitWidth).clearUnusedBits();
982 }
983
984 // Compute some values needed by the remaining shift algorithms
985 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
986 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
987
988 // If we are shifting whole words, just move whole words
989 if (wordShift == 0) {
990 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
991 val[i] = pVal[i+offset];
992 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
993 val[i] = (isNegative() ? -1ULL : 0);
994 return APInt(val,BitWidth).clearUnusedBits();
995 }
996
997 // Shift the low order words
998 uint32_t breakWord = getNumWords() - offset -1;
999 for (uint32_t i = 0; i < breakWord; ++i)
1000 val[i] = pVal[i+offset] >> wordShift |
1001 pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift);
1002 // Shift the break word.
1003 uint32_t SignBit = APINT_BITS_PER_WORD - (BitWidth % APINT_BITS_PER_WORD);
1004 val[breakWord] = uint64_t(
1005 (((int64_t(pVal[breakWord+offset]) << SignBit) >> SignBit) >> wordShift));
1006
1007 // Remaining words are 0 or -1
1008 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1009 val[i] = (isNegative() ? -1ULL : 0);
1010 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001011}
1012
Zhou Shengff4304f2007-02-09 07:48:24 +00001013/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001014/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001015APInt APInt::lshr(uint32_t shiftAmt) const {
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001016 if (isSingleWord())
1017 if (shiftAmt == BitWidth)
1018 return APInt(BitWidth, 0);
1019 else
1020 return APInt(BitWidth, this->VAL >> shiftAmt);
1021
Reid Spencerba81c2b2007-02-26 01:19:48 +00001022 // If all the bits were shifted out, the result is 0. This avoids issues
1023 // with shifting by the size of the integer type, which produces undefined
1024 // results. We define these "undefined results" to always be 0.
1025 if (shiftAmt == BitWidth)
1026 return APInt(BitWidth, 0);
1027
1028 // Create some space for the result.
1029 uint64_t * val = new uint64_t[getNumWords()];
1030
1031 // If we are shifting less than a word, compute the shift with a simple carry
1032 if (shiftAmt < APINT_BITS_PER_WORD) {
1033 uint64_t carry = 0;
1034 for (int i = getNumWords()-1; i >= 0; --i) {
1035 val[i] = pVal[i] >> shiftAmt | carry;
1036 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1037 }
1038 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001039 }
1040
Reid Spencerba81c2b2007-02-26 01:19:48 +00001041 // Compute some values needed by the remaining shift algorithms
1042 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1043 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1044
1045 // If we are shifting whole words, just move whole words
1046 if (wordShift == 0) {
1047 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1048 val[i] = pVal[i+offset];
1049 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1050 val[i] = 0;
1051 return APInt(val,BitWidth).clearUnusedBits();
1052 }
1053
1054 // Shift the low order words
1055 uint32_t breakWord = getNumWords() - offset -1;
1056 for (uint32_t i = 0; i < breakWord; ++i)
1057 val[i] = pVal[i+offset] >> wordShift |
1058 pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift);
1059 // Shift the break word.
1060 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1061
1062 // Remaining words are 0
1063 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1064 val[i] = 0;
1065 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001066}
1067
Zhou Shengff4304f2007-02-09 07:48:24 +00001068/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001069/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001070APInt APInt::shl(uint32_t shiftAmt) const {
Reid Spencer5bce8542007-02-24 20:19:37 +00001071 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer87553802007-02-25 00:56:44 +00001072 if (isSingleWord()) {
Reid Spencer5bce8542007-02-24 20:19:37 +00001073 if (shiftAmt == BitWidth)
Reid Spencer87553802007-02-25 00:56:44 +00001074 return APInt(BitWidth, 0); // avoid undefined shift results
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001075 return APInt(BitWidth, VAL << shiftAmt);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001076 }
Reid Spencer5bce8542007-02-24 20:19:37 +00001077
Reid Spencer87553802007-02-25 00:56:44 +00001078 // If all the bits were shifted out, the result is 0. This avoids issues
1079 // with shifting by the size of the integer type, which produces undefined
1080 // results. We define these "undefined results" to always be 0.
1081 if (shiftAmt == BitWidth)
1082 return APInt(BitWidth, 0);
1083
1084 // Create some space for the result.
1085 uint64_t * val = new uint64_t[getNumWords()];
1086
1087 // If we are shifting less than a word, do it the easy way
1088 if (shiftAmt < APINT_BITS_PER_WORD) {
1089 uint64_t carry = 0;
Reid Spencer87553802007-02-25 00:56:44 +00001090 for (uint32_t i = 0; i < getNumWords(); i++) {
1091 val[i] = pVal[i] << shiftAmt | carry;
1092 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1093 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001094 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001095 }
1096
Reid Spencer87553802007-02-25 00:56:44 +00001097 // Compute some values needed by the remaining shift algorithms
1098 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1099 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1100
1101 // If we are shifting whole words, just move whole words
1102 if (wordShift == 0) {
1103 for (uint32_t i = 0; i < offset; i++)
1104 val[i] = 0;
1105 for (uint32_t i = offset; i < getNumWords(); i++)
1106 val[i] = pVal[i-offset];
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001107 return APInt(val,BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001108 }
Reid Spencer87553802007-02-25 00:56:44 +00001109
1110 // Copy whole words from this to Result.
1111 uint32_t i = getNumWords() - 1;
1112 for (; i > offset; --i)
1113 val[i] = pVal[i-offset] << wordShift |
1114 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencer438d71e2007-02-25 01:08:58 +00001115 val[offset] = pVal[0] << wordShift;
Reid Spencer87553802007-02-25 00:56:44 +00001116 for (i = 0; i < offset; ++i)
1117 val[i] = 0;
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001118 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001119}
1120
Reid Spencer9c0696f2007-02-20 08:51:03 +00001121/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1122/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1123/// variables here have the same names as in the algorithm. Comments explain
1124/// the algorithm and any deviation from it.
1125static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1126 uint32_t m, uint32_t n) {
1127 assert(u && "Must provide dividend");
1128 assert(v && "Must provide divisor");
1129 assert(q && "Must provide quotient");
Reid Spencer9d6c9192007-02-24 03:58:46 +00001130 assert(u != v && u != q && v != q && "Must us different memory");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001131 assert(n>1 && "n must be > 1");
1132
1133 // Knuth uses the value b as the base of the number system. In our case b
1134 // is 2^31 so we just set it to -1u.
1135 uint64_t b = uint64_t(1) << 32;
1136
Reid Spencer9d6c9192007-02-24 03:58:46 +00001137 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1138 DEBUG(cerr << "KnuthDiv: original:");
1139 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1140 DEBUG(cerr << " by");
1141 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1142 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001143 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1144 // u and v by d. Note that we have taken Knuth's advice here to use a power
1145 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1146 // 2 allows us to shift instead of multiply and it is easy to determine the
1147 // shift amount from the leading zeros. We are basically normalizing the u
1148 // and v so that its high bits are shifted to the top of v's range without
1149 // overflow. Note that this can require an extra word in u so that u must
1150 // be of length m+n+1.
1151 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1152 uint32_t v_carry = 0;
1153 uint32_t u_carry = 0;
1154 if (shift) {
1155 for (uint32_t i = 0; i < m+n; ++i) {
1156 uint32_t u_tmp = u[i] >> (32 - shift);
1157 u[i] = (u[i] << shift) | u_carry;
1158 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001159 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001160 for (uint32_t i = 0; i < n; ++i) {
1161 uint32_t v_tmp = v[i] >> (32 - shift);
1162 v[i] = (v[i] << shift) | v_carry;
1163 v_carry = v_tmp;
1164 }
1165 }
1166 u[m+n] = u_carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001167 DEBUG(cerr << "KnuthDiv: normal:");
1168 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1169 DEBUG(cerr << " by");
1170 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1171 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001172
1173 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1174 int j = m;
1175 do {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001176 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001177 // D3. [Calculate q'.].
1178 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1179 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1180 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1181 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1182 // on v[n-2] determines at high speed most of the cases in which the trial
1183 // value qp is one too large, and it eliminates all cases where qp is two
1184 // too large.
Reid Spencer92904632007-02-23 01:57:13 +00001185 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001186 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencer92904632007-02-23 01:57:13 +00001187 uint64_t qp = dividend / v[n-1];
1188 uint64_t rp = dividend % v[n-1];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001189 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1190 qp--;
1191 rp += v[n-1];
Reid Spencer610fad82007-02-24 10:01:42 +00001192 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencer9d6c9192007-02-24 03:58:46 +00001193 qp--;
Reid Spencer92904632007-02-23 01:57:13 +00001194 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001195 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001196
Reid Spencer92904632007-02-23 01:57:13 +00001197 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1198 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1199 // consists of a simple multiplication by a one-place number, combined with
Reid Spencer610fad82007-02-24 10:01:42 +00001200 // a subtraction.
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001201 bool isNeg = false;
Reid Spencer92904632007-02-23 01:57:13 +00001202 for (uint32_t i = 0; i < n; ++i) {
Reid Spencer610fad82007-02-24 10:01:42 +00001203 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001204 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
Reid Spencer610fad82007-02-24 10:01:42 +00001205 bool borrow = subtrahend > u_tmp;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001206 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
Reid Spencer610fad82007-02-24 10:01:42 +00001207 << ", subtrahend == " << subtrahend
1208 << ", borrow = " << borrow << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001209
Reid Spencer610fad82007-02-24 10:01:42 +00001210 uint64_t result = u_tmp - subtrahend;
1211 uint32_t k = j + i;
1212 u[k++] = result & (b-1); // subtract low word
1213 u[k++] = result >> 32; // subtract high word
1214 while (borrow && k <= m+n) { // deal with borrow to the left
1215 borrow = u[k] == 0;
1216 u[k]--;
1217 k++;
1218 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001219 isNeg |= borrow;
Reid Spencer610fad82007-02-24 10:01:42 +00001220 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1221 u[j+i+1] << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001222 }
1223 DEBUG(cerr << "KnuthDiv: after subtraction:");
1224 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1225 DEBUG(cerr << '\n');
Reid Spencer610fad82007-02-24 10:01:42 +00001226 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1227 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1228 // true value plus b**(n+1), namely as the b's complement of
Reid Spencer92904632007-02-23 01:57:13 +00001229 // the true value, and a "borrow" to the left should be remembered.
1230 //
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001231 if (isNeg) {
Reid Spencer610fad82007-02-24 10:01:42 +00001232 bool carry = true; // true because b's complement is "complement + 1"
1233 for (uint32_t i = 0; i <= m+n; ++i) {
1234 u[i] = ~u[i] + carry; // b's complement
1235 carry = carry && u[i] == 0;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001236 }
Reid Spencer92904632007-02-23 01:57:13 +00001237 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001238 DEBUG(cerr << "KnuthDiv: after complement:");
1239 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1240 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001241
1242 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1243 // negative, go to step D6; otherwise go on to step D7.
1244 q[j] = qp;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001245 if (isNeg) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001246 // D6. [Add back]. The probability that this step is necessary is very
1247 // small, on the order of only 2/b. Make sure that test data accounts for
Reid Spencer92904632007-02-23 01:57:13 +00001248 // this possibility. Decrease q[j] by 1
1249 q[j]--;
1250 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1251 // A carry will occur to the left of u[j+n], and it should be ignored
1252 // since it cancels with the borrow that occurred in D4.
1253 bool carry = false;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001254 for (uint32_t i = 0; i < n; i++) {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001255 uint32_t limit = std::min(u[j+i],v[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001256 u[j+i] += v[i] + carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001257 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001258 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001259 u[j+n] += carry;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001260 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001261 DEBUG(cerr << "KnuthDiv: after correction:");
1262 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1263 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001264
Reid Spencer92904632007-02-23 01:57:13 +00001265 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1266 } while (--j >= 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001267
Reid Spencer9d6c9192007-02-24 03:58:46 +00001268 DEBUG(cerr << "KnuthDiv: quotient:");
1269 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1270 DEBUG(cerr << '\n');
1271
Reid Spencer9c0696f2007-02-20 08:51:03 +00001272 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1273 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1274 // compute the remainder (urem uses this).
1275 if (r) {
1276 // The value d is expressed by the "shift" value above since we avoided
1277 // multiplication by d by using a shift left. So, all we have to do is
1278 // shift right here. In order to mak
Reid Spencer1050ec52007-02-24 20:38:01 +00001279 if (shift) {
1280 uint32_t carry = 0;
1281 DEBUG(cerr << "KnuthDiv: remainder:");
1282 for (int i = n-1; i >= 0; i--) {
1283 r[i] = (u[i] >> shift) | carry;
1284 carry = u[i] << (32 - shift);
1285 DEBUG(cerr << " " << r[i]);
1286 }
1287 } else {
1288 for (int i = n-1; i >= 0; i--) {
1289 r[i] = u[i];
1290 DEBUG(cerr << " " << r[i]);
1291 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001292 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001293 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001294 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001295 DEBUG(cerr << std::setbase(10) << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001296}
1297
Reid Spencer9c0696f2007-02-20 08:51:03 +00001298void APInt::divide(const APInt LHS, uint32_t lhsWords,
1299 const APInt &RHS, uint32_t rhsWords,
1300 APInt *Quotient, APInt *Remainder)
1301{
1302 assert(lhsWords >= rhsWords && "Fractional result");
1303
1304 // First, compose the values into an array of 32-bit words instead of
1305 // 64-bit words. This is a necessity of both the "short division" algorithm
1306 // and the the Knuth "classical algorithm" which requires there to be native
1307 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1308 // can't use 64-bit operands here because we don't have native results of
1309 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1310 // work on large-endian machines.
1311 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1312 uint32_t n = rhsWords * 2;
1313 uint32_t m = (lhsWords * 2) - n;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001314
1315 // Allocate space for the temporary values we need either on the stack, if
1316 // it will fit, or on the heap if it won't.
1317 uint32_t SPACE[128];
1318 uint32_t *U = 0;
1319 uint32_t *V = 0;
1320 uint32_t *Q = 0;
1321 uint32_t *R = 0;
1322 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1323 U = &SPACE[0];
1324 V = &SPACE[m+n+1];
1325 Q = &SPACE[(m+n+1) + n];
1326 if (Remainder)
1327 R = &SPACE[(m+n+1) + n + (m+n)];
1328 } else {
1329 U = new uint32_t[m + n + 1];
1330 V = new uint32_t[n];
1331 Q = new uint32_t[m+n];
1332 if (Remainder)
1333 R = new uint32_t[n];
1334 }
1335
1336 // Initialize the dividend
Reid Spencer9c0696f2007-02-20 08:51:03 +00001337 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1338 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001339 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001340 U[i * 2] = tmp & mask;
1341 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1342 }
1343 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1344
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001345 // Initialize the divisor
Reid Spencer9c0696f2007-02-20 08:51:03 +00001346 memset(V, 0, (n)*sizeof(uint32_t));
1347 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001348 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001349 V[i * 2] = tmp & mask;
1350 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1351 }
1352
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001353 // initialize the quotient and remainder
Reid Spencer9c0696f2007-02-20 08:51:03 +00001354 memset(Q, 0, (m+n) * sizeof(uint32_t));
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001355 if (Remainder)
Reid Spencer9c0696f2007-02-20 08:51:03 +00001356 memset(R, 0, n * sizeof(uint32_t));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001357
1358 // Now, adjust m and n for the Knuth division. n is the number of words in
1359 // the divisor. m is the number of words by which the dividend exceeds the
1360 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1361 // contain any zero words or the Knuth algorithm fails.
1362 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1363 n--;
1364 m++;
1365 }
1366 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1367 m--;
1368
1369 // If we're left with only a single word for the divisor, Knuth doesn't work
1370 // so we implement the short division algorithm here. This is much simpler
1371 // and faster because we are certain that we can divide a 64-bit quantity
1372 // by a 32-bit quantity at hardware speed and short division is simply a
1373 // series of such operations. This is just like doing short division but we
1374 // are using base 2^32 instead of base 10.
1375 assert(n != 0 && "Divide by zero?");
1376 if (n == 1) {
1377 uint32_t divisor = V[0];
1378 uint32_t remainder = 0;
1379 for (int i = m+n-1; i >= 0; i--) {
1380 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1381 if (partial_dividend == 0) {
1382 Q[i] = 0;
1383 remainder = 0;
1384 } else if (partial_dividend < divisor) {
1385 Q[i] = 0;
1386 remainder = partial_dividend;
1387 } else if (partial_dividend == divisor) {
1388 Q[i] = 1;
1389 remainder = 0;
1390 } else {
1391 Q[i] = partial_dividend / divisor;
1392 remainder = partial_dividend - (Q[i] * divisor);
1393 }
1394 }
1395 if (R)
1396 R[0] = remainder;
1397 } else {
1398 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1399 // case n > 1.
1400 KnuthDiv(U, V, Q, R, m, n);
1401 }
1402
1403 // If the caller wants the quotient
1404 if (Quotient) {
1405 // Set up the Quotient value's memory.
1406 if (Quotient->BitWidth != LHS.BitWidth) {
1407 if (Quotient->isSingleWord())
1408 Quotient->VAL = 0;
1409 else
1410 delete Quotient->pVal;
1411 Quotient->BitWidth = LHS.BitWidth;
1412 if (!Quotient->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001413 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001414 } else
1415 Quotient->clear();
1416
1417 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1418 // order words.
1419 if (lhsWords == 1) {
1420 uint64_t tmp =
1421 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1422 if (Quotient->isSingleWord())
1423 Quotient->VAL = tmp;
1424 else
1425 Quotient->pVal[0] = tmp;
1426 } else {
1427 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1428 for (unsigned i = 0; i < lhsWords; ++i)
1429 Quotient->pVal[i] =
1430 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1431 }
1432 }
1433
1434 // If the caller wants the remainder
1435 if (Remainder) {
1436 // Set up the Remainder value's memory.
1437 if (Remainder->BitWidth != RHS.BitWidth) {
1438 if (Remainder->isSingleWord())
1439 Remainder->VAL = 0;
1440 else
1441 delete Remainder->pVal;
1442 Remainder->BitWidth = RHS.BitWidth;
1443 if (!Remainder->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001444 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001445 } else
1446 Remainder->clear();
1447
1448 // The remainder is in R. Reconstitute the remainder into Remainder's low
1449 // order words.
1450 if (rhsWords == 1) {
1451 uint64_t tmp =
1452 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1453 if (Remainder->isSingleWord())
1454 Remainder->VAL = tmp;
1455 else
1456 Remainder->pVal[0] = tmp;
1457 } else {
1458 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1459 for (unsigned i = 0; i < rhsWords; ++i)
1460 Remainder->pVal[i] =
1461 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1462 }
1463 }
1464
1465 // Clean up the memory we allocated.
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001466 if (U != &SPACE[0]) {
1467 delete [] U;
1468 delete [] V;
1469 delete [] Q;
1470 delete [] R;
1471 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001472}
1473
Reid Spencere81d2da2007-02-16 22:36:51 +00001474APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001475 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001476
1477 // First, deal with the easy case
1478 if (isSingleWord()) {
1479 assert(RHS.VAL != 0 && "Divide by zero?");
1480 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001481 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001482
Reid Spencer71bd08f2007-02-17 02:07:07 +00001483 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001484 uint32_t rhsBits = RHS.getActiveBits();
1485 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001486 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001487 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001488 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001489
1490 // Deal with some degenerate cases
1491 if (!lhsWords)
Reid Spencere0cdd332007-02-21 08:21:52 +00001492 // 0 / X ===> 0
1493 return APInt(BitWidth, 0);
1494 else if (lhsWords < rhsWords || this->ult(RHS)) {
1495 // X / Y ===> 0, iff X < Y
1496 return APInt(BitWidth, 0);
1497 } else if (*this == RHS) {
1498 // X / X ===> 1
1499 return APInt(BitWidth, 1);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001500 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001501 // All high words are zero, just use native divide
Reid Spencere0cdd332007-02-21 08:21:52 +00001502 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001503 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001504
1505 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1506 APInt Quotient(1,0); // to hold result.
1507 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1508 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001509}
1510
Reid Spencere81d2da2007-02-16 22:36:51 +00001511APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001512 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001513 if (isSingleWord()) {
1514 assert(RHS.VAL != 0 && "Remainder by zero?");
1515 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001516 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001517
Reid Spencere0cdd332007-02-21 08:21:52 +00001518 // Get some facts about the LHS
1519 uint32_t lhsBits = getActiveBits();
1520 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001521
1522 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001523 uint32_t rhsBits = RHS.getActiveBits();
1524 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001525 assert(rhsWords && "Performing remainder operation by zero ???");
1526
Reid Spencer71bd08f2007-02-17 02:07:07 +00001527 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001528 if (lhsWords == 0) {
Reid Spencere0cdd332007-02-21 08:21:52 +00001529 // 0 % Y ===> 0
1530 return APInt(BitWidth, 0);
1531 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1532 // X % Y ===> X, iff X < Y
1533 return *this;
1534 } else if (*this == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001535 // X % X == 0;
Reid Spencere0cdd332007-02-21 08:21:52 +00001536 return APInt(BitWidth, 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001537 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001538 // All high words are zero, just use native remainder
Reid Spencere0cdd332007-02-21 08:21:52 +00001539 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001540 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001541
1542 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1543 APInt Remainder(1,0);
1544 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1545 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001546}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001547
Reid Spencer385f7542007-02-21 03:55:44 +00001548void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001549 uint8_t radix) {
Reid Spencer385f7542007-02-21 03:55:44 +00001550 // Check our assumptions here
Reid Spencer5e0a8512007-02-17 03:16:00 +00001551 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1552 "Radix should be 2, 8, 10, or 16!");
Reid Spencer385f7542007-02-21 03:55:44 +00001553 assert(str && "String is null?");
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001554 bool isNeg = str[0] == '-';
1555 if (isNeg)
Reid Spencer9eec2412007-02-25 23:44:53 +00001556 str++, slen--;
Reid Spencer385f7542007-02-21 03:55:44 +00001557 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1558 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1559 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1560 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1561
1562 // Allocate memory
1563 if (!isSingleWord())
1564 pVal = getClearedMemory(getNumWords());
1565
1566 // Figure out if we can shift instead of multiply
1567 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1568
1569 // Set up an APInt for the digit to add outside the loop so we don't
1570 // constantly construct/destruct it.
1571 APInt apdigit(getBitWidth(), 0);
1572 APInt apradix(getBitWidth(), radix);
1573
1574 // Enter digit traversal loop
1575 for (unsigned i = 0; i < slen; i++) {
1576 // Get a digit
1577 uint32_t digit = 0;
1578 char cdigit = str[i];
1579 if (isdigit(cdigit))
1580 digit = cdigit - '0';
1581 else if (isxdigit(cdigit))
1582 if (cdigit >= 'a')
1583 digit = cdigit - 'a' + 10;
1584 else if (cdigit >= 'A')
1585 digit = cdigit - 'A' + 10;
1586 else
1587 assert(0 && "huh?");
1588 else
1589 assert(0 && "Invalid character in digit string");
1590
1591 // Shift or multiple the value by the radix
1592 if (shift)
1593 this->shl(shift);
1594 else
1595 *this *= apradix;
1596
1597 // Add in the digit we just interpreted
Reid Spencer5bce8542007-02-24 20:19:37 +00001598 if (apdigit.isSingleWord())
1599 apdigit.VAL = digit;
1600 else
1601 apdigit.pVal[0] = digit;
Reid Spencer385f7542007-02-21 03:55:44 +00001602 *this += apdigit;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001603 }
Reid Spencer9eec2412007-02-25 23:44:53 +00001604 // If its negative, put it in two's complement form
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001605 if (isNeg) {
1606 (*this)--;
Reid Spencer9eec2412007-02-25 23:44:53 +00001607 this->flip();
Reid Spencer9eec2412007-02-25 23:44:53 +00001608 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001609}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001610
Reid Spencer9c0696f2007-02-20 08:51:03 +00001611std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1612 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1613 "Radix should be 2, 8, 10, or 16!");
1614 static const char *digits[] = {
1615 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1616 };
1617 std::string result;
1618 uint32_t bits_used = getActiveBits();
1619 if (isSingleWord()) {
1620 char buf[65];
1621 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1622 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1623 if (format) {
1624 if (wantSigned) {
1625 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1626 (APINT_BITS_PER_WORD-BitWidth);
1627 sprintf(buf, format, sextVal);
1628 } else
1629 sprintf(buf, format, VAL);
1630 } else {
1631 memset(buf, 0, 65);
1632 uint64_t v = VAL;
1633 while (bits_used) {
1634 uint32_t bit = v & 1;
1635 bits_used--;
1636 buf[bits_used] = digits[bit][0];
1637 v >>=1;
1638 }
1639 }
1640 result = buf;
1641 return result;
1642 }
1643
1644 if (radix != 10) {
1645 uint64_t mask = radix - 1;
1646 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1647 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1648 for (uint32_t i = 0; i < getNumWords(); ++i) {
1649 uint64_t value = pVal[i];
1650 for (uint32_t j = 0; j < nibbles; ++j) {
1651 result.insert(0, digits[ value & mask ]);
1652 value >>= shift;
1653 }
1654 }
1655 return result;
1656 }
1657
1658 APInt tmp(*this);
1659 APInt divisor(4, radix);
1660 APInt zero(tmp.getBitWidth(), 0);
1661 size_t insert_at = 0;
1662 if (wantSigned && tmp[BitWidth-1]) {
1663 // They want to print the signed version and it is a negative value
1664 // Flip the bits and add one to turn it into the equivalent positive
1665 // value and put a '-' in the result.
1666 tmp.flip();
1667 tmp++;
1668 result = "-";
1669 insert_at = 1;
1670 }
Reid Spencere549c492007-02-21 00:29:48 +00001671 if (tmp == APInt(tmp.getBitWidth(), 0))
Reid Spencer9c0696f2007-02-20 08:51:03 +00001672 result = "0";
1673 else while (tmp.ne(zero)) {
1674 APInt APdigit(1,0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001675 APInt tmp2(tmp.getBitWidth(), 0);
Reid Spencer385f7542007-02-21 03:55:44 +00001676 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1677 &APdigit);
Reid Spencer794f4722007-02-26 21:02:27 +00001678 uint32_t digit = APdigit.getZExtValue();
Reid Spencer385f7542007-02-21 03:55:44 +00001679 assert(digit < radix && "divide failed");
1680 result.insert(insert_at,digits[digit]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001681 tmp = tmp2;
1682 }
1683
1684 return result;
1685}
1686
Reid Spencer385f7542007-02-21 03:55:44 +00001687#ifndef NDEBUG
1688void APInt::dump() const
1689{
Reid Spencer610fad82007-02-24 10:01:42 +00001690 cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
Reid Spencer385f7542007-02-21 03:55:44 +00001691 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +00001692 cerr << VAL;
Reid Spencer385f7542007-02-21 03:55:44 +00001693 else for (unsigned i = getNumWords(); i > 0; i--) {
Reid Spencer610fad82007-02-24 10:01:42 +00001694 cerr << pVal[i-1] << " ";
Reid Spencer385f7542007-02-21 03:55:44 +00001695 }
Reid Spencer610fad82007-02-24 10:01:42 +00001696 cerr << " (" << this->toString(10, false) << ")\n" << std::setbase(10);
Reid Spencer385f7542007-02-21 03:55:44 +00001697}
1698#endif