blob: 965182f5ec44781a76061c250df21224c76ed21f [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)
Reid Spencer9ac44112007-02-26 23:38:21 +0000102 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 Spencer9ac44112007-02-26 23:38:21 +0000106 // Don't do anything for X = X
107 if (this == &RHS)
108 return *this;
109
110 // If the bitwidths are the same, we can avoid mucking with memory
111 if (BitWidth == RHS.getBitWidth()) {
112 if (isSingleWord())
113 VAL = RHS.VAL;
114 else
115 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
116 return *this;
117 }
118
119 if (isSingleWord())
120 if (RHS.isSingleWord())
121 VAL = RHS.VAL;
122 else {
123 VAL = 0;
124 pVal = getMemory(RHS.getNumWords());
125 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
126 }
127 else if (getNumWords() == RHS.getNumWords())
128 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
129 else if (RHS.isSingleWord()) {
130 delete [] pVal;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000131 VAL = RHS.VAL;
Reid Spencer9ac44112007-02-26 23:38:21 +0000132 } else {
133 delete [] pVal;
134 pVal = getMemory(RHS.getNumWords());
135 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
136 }
137 BitWidth = RHS.BitWidth;
138 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000139}
140
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000141APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000142 if (isSingleWord())
143 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000144 else {
145 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000146 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000147 }
Reid Spencer9ac44112007-02-26 23:38:21 +0000148 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000149}
150
Reid Spenceraf0e9562007-02-18 18:38:44 +0000151/// add_1 - This function adds a single "digit" integer, y, to the multiple
152/// "digit" integer array, x[]. x[] is modified to reflect the addition and
153/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000154/// @returns the carry of the addition.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000155static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000156 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000157 dest[i] = y + x[i];
158 if (dest[i] < y)
Reid Spencer610fad82007-02-24 10:01:42 +0000159 y = 1; // Carry one to next digit.
Reid Spencerf2c521c2007-02-18 06:39:42 +0000160 else {
Reid Spencer610fad82007-02-24 10:01:42 +0000161 y = 0; // No need to carry so exit early
Reid Spencerf2c521c2007-02-18 06:39:42 +0000162 break;
163 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000164 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000165 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000166}
167
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000168/// @brief Prefix increment operator. Increments the APInt by one.
169APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000170 if (isSingleWord())
171 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000172 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000173 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000174 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000175}
176
Reid Spenceraf0e9562007-02-18 18:38:44 +0000177/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
178/// the multi-digit integer array, x[], propagating the borrowed 1 value until
179/// no further borrowing is neeeded or it runs out of "digits" in x. The result
180/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
181/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000182/// @returns the borrow out of the subtraction
183static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000184 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000185 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000186 x[i] -= y;
187 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000188 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000189 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000190 y = 0; // No need to borrow
191 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000192 }
193 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000194 return bool(y);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000195}
196
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000197/// @brief Prefix decrement operator. Decrements the APInt by one.
198APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000199 if (isSingleWord())
200 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000201 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000202 sub_1(pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000203 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000204}
205
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000206/// add - This function adds the integer array x to the integer array Y and
207/// places the result in dest.
208/// @returns the carry out from the addition
209/// @brief General addition of 64-bit integer arrays
Reid Spencer9d6c9192007-02-24 03:58:46 +0000210static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
211 uint32_t len) {
212 bool carry = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000213 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer92904632007-02-23 01:57:13 +0000214 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer54362ca2007-02-20 23:40:25 +0000215 dest[i] = x[i] + y[i] + carry;
Reid Spencer60c0a6a2007-02-21 05:44:56 +0000216 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000217 }
218 return carry;
219}
220
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000221/// Adds the RHS APint to this APInt.
222/// @returns this, after addition of RHS.
223/// @brief Addition 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");
Reid Spencer54362ca2007-02-20 23:40:25 +0000226 if (isSingleWord())
227 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000228 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000229 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000230 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000231 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000232}
233
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000234/// Subtracts the integer array y from the integer array x
235/// @returns returns the borrow out.
236/// @brief Generalized subtraction of 64-bit integer arrays.
Reid Spencer9d6c9192007-02-24 03:58:46 +0000237static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
238 uint32_t len) {
Reid Spencer385f7542007-02-21 03:55:44 +0000239 bool borrow = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000240 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer385f7542007-02-21 03:55:44 +0000241 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
242 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
243 dest[i] = x_tmp - y[i];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000244 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000245 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000246}
247
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000248/// Subtracts the RHS APInt from this APInt
249/// @returns this, after subtraction
250/// @brief Subtraction assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000251APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000252 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000253 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000254 VAL -= RHS.VAL;
255 else
256 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000257 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000258}
259
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000260/// Multiplies an integer array, x by a a uint64_t integer and places the result
261/// into dest.
262/// @returns the carry out of the multiplication.
263/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Reid Spencer610fad82007-02-24 10:01:42 +0000264static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
265 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer5e0a8512007-02-17 03:16:00 +0000266 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000267 uint64_t carry = 0;
268
269 // For each digit of x.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000270 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000271 // Split x into high and low words
272 uint64_t lx = x[i] & 0xffffffffULL;
273 uint64_t hx = x[i] >> 32;
274 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000275 // hasCarry == 0, no carry
276 // hasCarry == 1, has carry
277 // hasCarry == 2, no carry and the calculation result == 0.
278 uint8_t hasCarry = 0;
279 dest[i] = carry + lx * ly;
280 // Determine if the add above introduces carry.
281 hasCarry = (dest[i] < carry) ? 1 : 0;
282 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
283 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
284 // (2^32 - 1) + 2^32 = 2^64.
285 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
286
287 carry += (lx * hy) & 0xffffffffULL;
288 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
289 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
290 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
291 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000292 return carry;
293}
294
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000295/// Multiplies integer array x by integer array y and stores the result into
296/// the integer array dest. Note that dest's size must be >= xlen + ylen.
297/// @brief Generalized multiplicate of integer arrays.
Reid Spencer610fad82007-02-24 10:01:42 +0000298static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[],
299 uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000300 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000301 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000302 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencere0cdd332007-02-21 08:21:52 +0000303 uint64_t carry = 0, lx = 0, hx = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000304 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000305 lx = x[j] & 0xffffffffULL;
306 hx = x[j] >> 32;
307 // hasCarry - A flag to indicate if has carry.
308 // hasCarry == 0, no carry
309 // hasCarry == 1, has carry
310 // hasCarry == 2, no carry and the calculation result == 0.
311 uint8_t hasCarry = 0;
312 uint64_t resul = carry + lx * ly;
313 hasCarry = (resul < carry) ? 1 : 0;
314 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
315 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
316
317 carry += (lx * hy) & 0xffffffffULL;
318 resul = (carry << 32) | (resul & 0xffffffffULL);
319 dest[i+j] += resul;
320 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
321 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
322 ((lx * hy) >> 32) + hx * hy;
323 }
324 dest[i+xlen] = carry;
325 }
326}
327
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000328APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000329 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencere0cdd332007-02-21 08:21:52 +0000330 if (isSingleWord()) {
Reid Spencer61eb1802007-02-20 20:42:10 +0000331 VAL *= RHS.VAL;
Reid Spencere0cdd332007-02-21 08:21:52 +0000332 clearUnusedBits();
333 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000334 }
Reid Spencere0cdd332007-02-21 08:21:52 +0000335
336 // Get some bit facts about LHS and check for zero
337 uint32_t lhsBits = getActiveBits();
338 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
339 if (!lhsWords)
340 // 0 * X ===> 0
341 return *this;
342
343 // Get some bit facts about RHS and check for zero
344 uint32_t rhsBits = RHS.getActiveBits();
345 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
346 if (!rhsWords) {
347 // X * 0 ===> 0
348 clear();
349 return *this;
350 }
351
352 // Allocate space for the result
353 uint32_t destWords = rhsWords + lhsWords;
354 uint64_t *dest = getMemory(destWords);
355
356 // Perform the long multiply
357 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
358
359 // Copy result back into *this
360 clear();
361 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
362 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
363
364 // delete dest array and return
365 delete[] dest;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000366 return *this;
367}
368
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000369APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000370 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000371 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000372 VAL &= RHS.VAL;
373 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000374 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000375 uint32_t numWords = getNumWords();
376 for (uint32_t i = 0; i < numWords; ++i)
377 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000378 return *this;
379}
380
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000381APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000382 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000383 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000384 VAL |= RHS.VAL;
385 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000386 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000387 uint32_t numWords = getNumWords();
388 for (uint32_t i = 0; i < numWords; ++i)
389 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000390 return *this;
391}
392
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000393APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000394 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000395 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000396 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000397 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000398 return *this;
399 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000400 uint32_t numWords = getNumWords();
401 for (uint32_t i = 0; i < numWords; ++i)
402 pVal[i] ^= RHS.pVal[i];
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000403 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000404}
405
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000406APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000407 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000408 if (isSingleWord())
409 return APInt(getBitWidth(), VAL & RHS.VAL);
410
Reid Spenceraf0e9562007-02-18 18:38:44 +0000411 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000412 uint64_t* val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000413 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000414 val[i] = pVal[i] & RHS.pVal[i];
415 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000416}
417
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000418APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000419 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000420 if (isSingleWord())
421 return APInt(getBitWidth(), VAL | RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000422
Reid Spenceraf0e9562007-02-18 18:38:44 +0000423 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000424 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000425 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000426 val[i] = pVal[i] | RHS.pVal[i];
427 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000428}
429
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000430APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000431 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000432 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000433 return APInt(BitWidth, VAL ^ RHS.VAL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000434
Reid Spenceraf0e9562007-02-18 18:38:44 +0000435 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000436 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000437 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000438 val[i] = pVal[i] ^ RHS.pVal[i];
439
440 // 0^0==1 so clear the high bits in case they got set.
441 return APInt(val, getBitWidth()).clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000442}
443
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000444bool 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
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000454APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000455 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000456 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000457 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer61eb1802007-02-20 20:42:10 +0000458 APInt Result(*this);
459 Result *= RHS;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000460 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000461}
462
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000463APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000464 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000465 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000466 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000467 APInt Result(BitWidth, 0);
468 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000469 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000470}
471
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000472APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000473 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000474 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000475 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000476 APInt Result(BitWidth, 0);
477 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000478 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000479}
480
Reid Spenceraf0e9562007-02-18 18:38:44 +0000481bool APInt::operator[](uint32_t bitPosition) const {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000482 return (maskBit(bitPosition) &
483 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000484}
485
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000486bool APInt::operator==(const APInt& RHS) const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000487 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
Reid Spencer54362ca2007-02-20 23:40:25 +0000488 if (isSingleWord())
489 return VAL == RHS.VAL;
490
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000491 // Get some facts about the number of bits used in the two operands.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000492 uint32_t n1 = getActiveBits();
493 uint32_t n2 = RHS.getActiveBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000494
495 // If the number of bits isn't the same, they aren't equal
Reid Spencer54362ca2007-02-20 23:40:25 +0000496 if (n1 != n2)
497 return false;
498
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000499 // If the number of bits fits in a word, we only need to compare the low word.
Reid Spencer54362ca2007-02-20 23:40:25 +0000500 if (n1 <= APINT_BITS_PER_WORD)
501 return pVal[0] == RHS.pVal[0];
502
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000503 // Otherwise, compare everything
Reid Spencer54362ca2007-02-20 23:40:25 +0000504 for (int i = whichWord(n1 - 1); i >= 0; --i)
505 if (pVal[i] != RHS.pVal[i])
506 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000507 return true;
508}
509
Zhou Shenga3832fd2007-02-07 06:14:53 +0000510bool APInt::operator==(uint64_t Val) const {
511 if (isSingleWord())
512 return VAL == Val;
Reid Spencer54362ca2007-02-20 23:40:25 +0000513
514 uint32_t n = getActiveBits();
515 if (n <= APINT_BITS_PER_WORD)
516 return pVal[0] == Val;
517 else
518 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000519}
520
Reid Spencere81d2da2007-02-16 22:36:51 +0000521bool APInt::ult(const APInt& RHS) const {
522 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
523 if (isSingleWord())
524 return VAL < RHS.VAL;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000525
526 // Get active bit length of both operands
527 uint32_t n1 = getActiveBits();
528 uint32_t n2 = RHS.getActiveBits();
529
530 // If magnitude of LHS is less than RHS, return true.
531 if (n1 < n2)
532 return true;
533
534 // If magnitude of RHS is greather than LHS, return false.
535 if (n2 < n1)
536 return false;
537
538 // If they bot fit in a word, just compare the low order word
539 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
540 return pVal[0] < RHS.pVal[0];
541
542 // Otherwise, compare all words
543 for (int i = whichWord(n1 - 1); i >= 0; --i) {
544 if (pVal[i] > RHS.pVal[i])
Reid Spencere81d2da2007-02-16 22:36:51 +0000545 return false;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000546 if (pVal[i] < RHS.pVal[i])
547 return true;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000548 }
549 return false;
550}
551
Reid Spencere81d2da2007-02-16 22:36:51 +0000552bool APInt::slt(const APInt& RHS) const {
553 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000554 if (isSingleWord()) {
555 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
556 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
557 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000558 }
Reid Spencera58f0582007-02-18 20:09:41 +0000559
560 APInt lhs(*this);
561 APInt rhs(*this);
562 bool lhsNegative = false;
563 bool rhsNegative = false;
564 if (lhs[BitWidth-1]) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000565 // Sign bit is set so make a note of it and perform two's complement
Reid Spencera58f0582007-02-18 20:09:41 +0000566 lhsNegative = true;
567 lhs.flip();
568 lhs++;
569 }
570 if (rhs[BitWidth-1]) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000571 // Sign bit is set so make a note of it and perform two's complement
Reid Spencera58f0582007-02-18 20:09:41 +0000572 rhsNegative = true;
573 rhs.flip();
574 rhs++;
575 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000576
577 // Now we have unsigned values to compare so do the comparison if necessary
578 // based on the negativeness of the values.
Reid Spencera58f0582007-02-18 20:09:41 +0000579 if (lhsNegative)
580 if (rhsNegative)
581 return !lhs.ult(rhs);
582 else
583 return true;
584 else if (rhsNegative)
585 return false;
586 else
587 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000588}
589
Reid Spenceraf0e9562007-02-18 18:38:44 +0000590APInt& APInt::set(uint32_t bitPosition) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000591 if (isSingleWord())
592 VAL |= maskBit(bitPosition);
593 else
594 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000595 return *this;
596}
597
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000598APInt& APInt::set() {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000599 if (isSingleWord()) {
600 VAL = -1ULL;
601 return clearUnusedBits();
Zhou Shengb04973e2007-02-15 06:36:31 +0000602 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000603
604 // Set all the bits in all the words.
605 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
606 pVal[i] = -1ULL;
607 // Clear the unused ones
608 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000609}
610
611/// Set the given bit to 0 whose position is given as "bitPosition".
612/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000613APInt& APInt::clear(uint32_t bitPosition) {
614 if (isSingleWord())
615 VAL &= ~maskBit(bitPosition);
616 else
617 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000618 return *this;
619}
620
621/// @brief Set every bit to 0.
622APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000623 if (isSingleWord())
624 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000625 else
Reid Spencera58f0582007-02-18 20:09:41 +0000626 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000627 return *this;
628}
629
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000630/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
631/// this APInt.
632APInt APInt::operator~() const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000633 APInt Result(*this);
634 Result.flip();
635 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000636}
637
638/// @brief Toggle every bit to its opposite value.
639APInt& APInt::flip() {
Reid Spencer9eec2412007-02-25 23:44:53 +0000640 if (isSingleWord()) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000641 VAL ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000642 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000643 }
Reid Spencer9eec2412007-02-25 23:44:53 +0000644 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000645 pVal[i] ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000646 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000647}
648
649/// Toggle a given bit to its opposite value whose position is given
650/// as "bitPosition".
651/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000652APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000653 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000654 if ((*this)[bitPosition]) clear(bitPosition);
655 else set(bitPosition);
656 return *this;
657}
658
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000659/// getMaxValue - This function returns the largest value
660/// for an APInt of the specified bit-width and if isSign == true,
661/// it should be largest signed value, otherwise unsigned value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000662APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000663 APInt Result(numBits, 0);
664 Result.set();
665 if (isSign)
666 Result.clear(numBits - 1);
667 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000668}
669
670/// getMinValue - This function returns the smallest value for
671/// an APInt of the given bit-width and if isSign == true,
672/// it should be smallest signed value, otherwise zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000673APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000674 APInt Result(numBits, 0);
675 if (isSign)
676 Result.set(numBits - 1);
677 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000678}
679
680/// getAllOnesValue - This function returns an all-ones value for
681/// an APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000682APInt APInt::getAllOnesValue(uint32_t numBits) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000683 return getMaxValue(numBits, false);
684}
685
686/// getNullValue - This function creates an '0' value for an
687/// APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000688APInt APInt::getNullValue(uint32_t numBits) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000689 return getMinValue(numBits, false);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000690}
691
Reid Spencer794f4722007-02-26 21:02:27 +0000692uint64_t APInt::getHashValue() const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000693 // Put the bit width into the low order bits.
694 uint64_t hash = BitWidth;
Reid Spencer794f4722007-02-26 21:02:27 +0000695
696 // Add the sum of the words to the hash.
697 if (isSingleWord())
Reid Spencer9ac44112007-02-26 23:38:21 +0000698 hash += VAL << 6; // clear separation of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000699 else
700 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer9ac44112007-02-26 23:38:21 +0000701 hash += pVal[i] << 6; // clear sepration of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000702 return hash;
703}
704
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000705/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000706APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000707 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000708}
709
710/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000711APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000712 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
713 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000714}
715
Reid Spencere81d2da2007-02-16 22:36:51 +0000716bool APInt::isPowerOf2() const {
717 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
718}
719
Reid Spenceraf0e9562007-02-18 18:38:44 +0000720uint32_t APInt::countLeadingZeros() const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000721 uint32_t Count = 0;
Reid Spencere549c492007-02-21 00:29:48 +0000722 if (isSingleWord())
723 Count = CountLeadingZeros_64(VAL);
724 else {
725 for (uint32_t i = getNumWords(); i > 0u; --i) {
726 if (pVal[i-1] == 0)
727 Count += APINT_BITS_PER_WORD;
728 else {
729 Count += CountLeadingZeros_64(pVal[i-1]);
730 break;
731 }
732 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000733 }
Reid Spencerab2b2c82007-02-22 00:22:00 +0000734 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
735 if (remainder)
736 Count -= APINT_BITS_PER_WORD - remainder;
737 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000738}
739
Reid Spenceraf0e9562007-02-18 18:38:44 +0000740uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000741 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000742 return CountTrailingZeros_64(VAL);
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000743 uint32_t Count = 0;
744 uint32_t i = 0;
745 for (; i < getNumWords() && pVal[i] == 0; ++i)
746 Count += APINT_BITS_PER_WORD;
747 if (i < getNumWords())
748 Count += CountTrailingZeros_64(pVal[i]);
749 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000750}
751
Reid Spenceraf0e9562007-02-18 18:38:44 +0000752uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000753 if (isSingleWord())
754 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000755 uint32_t Count = 0;
756 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000757 Count += CountPopulation_64(pVal[i]);
758 return Count;
759}
760
Reid Spencere81d2da2007-02-16 22:36:51 +0000761APInt APInt::byteSwap() const {
762 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
763 if (BitWidth == 16)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000764 return APInt(BitWidth, ByteSwap_16(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000765 else if (BitWidth == 32)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000766 return APInt(BitWidth, ByteSwap_32(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000767 else if (BitWidth == 48) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000768 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
769 Tmp1 = ByteSwap_32(Tmp1);
770 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
771 Tmp2 = ByteSwap_16(Tmp2);
772 return
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000773 APInt(BitWidth,
774 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
Reid Spencere81d2da2007-02-16 22:36:51 +0000775 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000776 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000777 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000778 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000779 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000780 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000781 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000782 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
783 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000784 }
785 return Result;
786 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000787}
788
Zhou Sheng0b706b12007-02-08 14:35:19 +0000789APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
790 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000791 APInt A = API1, B = API2;
792 while (!!B) {
793 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000794 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000795 A = T;
796 }
797 return A;
798}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000799
Reid Spencere81d2da2007-02-16 22:36:51 +0000800APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000801 union {
802 double D;
803 uint64_t I;
804 } T;
805 T.D = Double;
Reid Spencer30f44f32007-02-27 01:28:10 +0000806
807 // Get the sign bit from the highest order bit
Zhou Shengd93f00c2007-02-12 20:02:55 +0000808 bool isNeg = T.I >> 63;
Reid Spencer30f44f32007-02-27 01:28:10 +0000809
810 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd93f00c2007-02-12 20:02:55 +0000811 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer30f44f32007-02-27 01:28:10 +0000812
813 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000814 if (exp < 0)
Reid Spencer30f44f32007-02-27 01:28:10 +0000815 return APInt(64u, 0u);
816
817 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
818 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
819
820 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd93f00c2007-02-12 20:02:55 +0000821 if (exp < 52)
Reid Spencere81d2da2007-02-16 22:36:51 +0000822 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
823 APInt(64u, mantissa >> (52 - exp));
Reid Spencer30f44f32007-02-27 01:28:10 +0000824
825 // Otherwise, we have to shift the mantissa bits up to the right location
826 APInt Tmp(exp+1, mantissa);
Reid Spencere81d2da2007-02-16 22:36:51 +0000827 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000828 return isNeg ? -Tmp : Tmp;
829}
830
Reid Spencerdb3faa62007-02-13 22:41:58 +0000831/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000832/// The layout for double is as following (IEEE Standard 754):
833/// --------------------------------------
834/// | Sign Exponent Fraction Bias |
835/// |-------------------------------------- |
836/// | 1[63] 11[62-52] 52[51-00] 1023 |
837/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000838double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000839
840 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000841 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
842 if (isSigned) {
843 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
844 return double(sext);
845 } else
846 return double(VAL);
847 }
848
Reid Spencer9c0696f2007-02-20 08:51:03 +0000849 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000850 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000851
852 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000853 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000854
855 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000856 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000857
Reid Spencer9c0696f2007-02-20 08:51:03 +0000858 // The exponent (without bias normalization) is just the number of bits
859 // we are using. Note that the sign bit is gone since we constructed the
860 // absolute value.
861 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000862
Reid Spencer9c0696f2007-02-20 08:51:03 +0000863 // Return infinity for exponent overflow
864 if (exp > 1023) {
865 if (!isSigned || !isNeg)
Reid Spencer61eb1802007-02-20 20:42:10 +0000866 return double(1.0E300 * 1.0E300); // positive infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000867 else
Reid Spencer61eb1802007-02-20 20:42:10 +0000868 return double(-1.0E300 * 1.0E300); // negative infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000869 }
870 exp += 1023; // Increment for 1023 bias
871
872 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
873 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000874 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000875 unsigned hiWord = whichWord(n-1);
876 if (hiWord == 0) {
877 mantissa = Tmp.pVal[0];
878 if (n > 52)
879 mantissa >>= n - 52; // shift down, we want the top 52 bits.
880 } else {
881 assert(hiWord > 0 && "huh?");
882 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
883 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
884 mantissa = hibits | lobits;
885 }
886
Zhou Shengd93f00c2007-02-12 20:02:55 +0000887 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000888 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000889 union {
890 double D;
891 uint64_t I;
892 } T;
893 T.I = sign | (exp << 52) | mantissa;
894 return T.D;
895}
896
Reid Spencere81d2da2007-02-16 22:36:51 +0000897// Truncate to new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000898void APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000899 assert(width < BitWidth && "Invalid APInt Truncate request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000900 assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
901 uint32_t wordsBefore = getNumWords();
902 BitWidth = width;
903 uint32_t wordsAfter = getNumWords();
904 if (wordsBefore != wordsAfter) {
905 if (wordsAfter == 1) {
906 uint64_t *tmp = pVal;
907 VAL = pVal[0];
Reid Spencer9ac44112007-02-26 23:38:21 +0000908 delete [] tmp;
Reid Spencer9eec2412007-02-25 23:44:53 +0000909 } else {
910 uint64_t *newVal = getClearedMemory(wordsAfter);
911 for (uint32_t i = 0; i < wordsAfter; ++i)
912 newVal[i] = pVal[i];
Reid Spencer9ac44112007-02-26 23:38:21 +0000913 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000914 pVal = newVal;
915 }
916 }
917 clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000918}
919
920// Sign extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000921void APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000922 assert(width > BitWidth && "Invalid APInt SignExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000923 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
Reid Spencer9eec2412007-02-25 23:44:53 +0000924 // If the sign bit isn't set, this is the same as zext.
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000925 if (!isNegative()) {
Reid Spencer9eec2412007-02-25 23:44:53 +0000926 zext(width);
927 return;
928 }
929
930 // The sign bit is set. First, get some facts
931 uint32_t wordsBefore = getNumWords();
932 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
933 BitWidth = width;
934 uint32_t wordsAfter = getNumWords();
935
936 // Mask the high order word appropriately
937 if (wordsBefore == wordsAfter) {
938 uint32_t newWordBits = width % APINT_BITS_PER_WORD;
939 // The extension is contained to the wordsBefore-1th word.
940 uint64_t mask = (~0ULL >> (APINT_BITS_PER_WORD - newWordBits)) << wordBits;
941 if (wordsBefore == 1)
942 VAL |= mask;
943 else
944 pVal[wordsBefore-1] |= mask;
945 clearUnusedBits();
946 return;
947 }
948
Reid Spencerf30b1882007-02-25 23:54:00 +0000949 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +0000950 uint64_t *newVal = getMemory(wordsAfter);
951 if (wordsBefore == 1)
952 newVal[0] = VAL | mask;
953 else {
954 for (uint32_t i = 0; i < wordsBefore; ++i)
955 newVal[i] = pVal[i];
956 newVal[wordsBefore-1] |= mask;
957 }
958 for (uint32_t i = wordsBefore; i < wordsAfter; i++)
959 newVal[i] = -1ULL;
960 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +0000961 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000962 pVal = newVal;
963 clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000964}
965
966// Zero extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000967void APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000968 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000969 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
970 uint32_t wordsBefore = getNumWords();
971 BitWidth = width;
972 uint32_t wordsAfter = getNumWords();
973 if (wordsBefore != wordsAfter) {
974 uint64_t *newVal = getClearedMemory(wordsAfter);
975 if (wordsBefore == 1)
976 newVal[0] = VAL;
977 else
978 for (uint32_t i = 0; i < wordsBefore; ++i)
979 newVal[i] = pVal[i];
980 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +0000981 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000982 pVal = newVal;
983 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000984}
985
Zhou Shengff4304f2007-02-09 07:48:24 +0000986/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000987/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000988APInt APInt::ashr(uint32_t shiftAmt) const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000989 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer24c4a8f2007-02-25 01:56:07 +0000990 if (isSingleWord()) {
991 if (shiftAmt == BitWidth)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000992 return APInt(BitWidth, 0); // undefined
993 else {
994 uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
Reid Spencer24c4a8f2007-02-25 01:56:07 +0000995 return APInt(BitWidth,
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000996 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
997 }
Zhou Sheng0b706b12007-02-08 14:35:19 +0000998 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +0000999
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001000 // If all the bits were shifted out, the result is 0 or -1. This avoids issues
1001 // with shifting by the size of the integer type, which produces undefined
1002 // results.
1003 if (shiftAmt == BitWidth)
1004 if (isNegative())
1005 return APInt(BitWidth, -1ULL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001006 else
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001007 return APInt(BitWidth, 0);
1008
1009 // Create some space for the result.
1010 uint64_t * val = new uint64_t[getNumWords()];
1011
1012 // If we are shifting less than a word, compute the shift with a simple carry
1013 if (shiftAmt < APINT_BITS_PER_WORD) {
1014 uint64_t carry = 0;
1015 for (int i = getNumWords()-1; i >= 0; --i) {
1016 val[i] = pVal[i] >> shiftAmt | carry;
1017 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1018 }
1019 return APInt(val, BitWidth).clearUnusedBits();
1020 }
1021
1022 // Compute some values needed by the remaining shift algorithms
1023 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1024 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1025
1026 // If we are shifting whole words, just move whole words
1027 if (wordShift == 0) {
1028 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1029 val[i] = pVal[i+offset];
1030 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1031 val[i] = (isNegative() ? -1ULL : 0);
1032 return APInt(val,BitWidth).clearUnusedBits();
1033 }
1034
1035 // Shift the low order words
1036 uint32_t breakWord = getNumWords() - offset -1;
1037 for (uint32_t i = 0; i < breakWord; ++i)
1038 val[i] = pVal[i+offset] >> wordShift |
1039 pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift);
1040 // Shift the break word.
1041 uint32_t SignBit = APINT_BITS_PER_WORD - (BitWidth % APINT_BITS_PER_WORD);
1042 val[breakWord] = uint64_t(
1043 (((int64_t(pVal[breakWord+offset]) << SignBit) >> SignBit) >> wordShift));
1044
1045 // Remaining words are 0 or -1
1046 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1047 val[i] = (isNegative() ? -1ULL : 0);
1048 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001049}
1050
Zhou Shengff4304f2007-02-09 07:48:24 +00001051/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001052/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001053APInt APInt::lshr(uint32_t shiftAmt) const {
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001054 if (isSingleWord())
1055 if (shiftAmt == BitWidth)
1056 return APInt(BitWidth, 0);
1057 else
1058 return APInt(BitWidth, this->VAL >> shiftAmt);
1059
Reid Spencerba81c2b2007-02-26 01:19:48 +00001060 // If all the bits were shifted out, the result is 0. This avoids issues
1061 // with shifting by the size of the integer type, which produces undefined
1062 // results. We define these "undefined results" to always be 0.
1063 if (shiftAmt == BitWidth)
1064 return APInt(BitWidth, 0);
1065
1066 // Create some space for the result.
1067 uint64_t * val = new uint64_t[getNumWords()];
1068
1069 // If we are shifting less than a word, compute the shift with a simple carry
1070 if (shiftAmt < APINT_BITS_PER_WORD) {
1071 uint64_t carry = 0;
1072 for (int i = getNumWords()-1; i >= 0; --i) {
1073 val[i] = pVal[i] >> shiftAmt | carry;
1074 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1075 }
1076 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001077 }
1078
Reid Spencerba81c2b2007-02-26 01:19:48 +00001079 // Compute some values needed by the remaining shift algorithms
1080 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1081 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1082
1083 // If we are shifting whole words, just move whole words
1084 if (wordShift == 0) {
1085 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1086 val[i] = pVal[i+offset];
1087 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1088 val[i] = 0;
1089 return APInt(val,BitWidth).clearUnusedBits();
1090 }
1091
1092 // Shift the low order words
1093 uint32_t breakWord = getNumWords() - offset -1;
1094 for (uint32_t i = 0; i < breakWord; ++i)
1095 val[i] = pVal[i+offset] >> wordShift |
1096 pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift);
1097 // Shift the break word.
1098 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1099
1100 // Remaining words are 0
1101 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1102 val[i] = 0;
1103 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001104}
1105
Zhou Shengff4304f2007-02-09 07:48:24 +00001106/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001107/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001108APInt APInt::shl(uint32_t shiftAmt) const {
Reid Spencer5bce8542007-02-24 20:19:37 +00001109 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer87553802007-02-25 00:56:44 +00001110 if (isSingleWord()) {
Reid Spencer5bce8542007-02-24 20:19:37 +00001111 if (shiftAmt == BitWidth)
Reid Spencer87553802007-02-25 00:56:44 +00001112 return APInt(BitWidth, 0); // avoid undefined shift results
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001113 return APInt(BitWidth, VAL << shiftAmt);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001114 }
Reid Spencer5bce8542007-02-24 20:19:37 +00001115
Reid Spencer87553802007-02-25 00:56:44 +00001116 // If all the bits were shifted out, the result is 0. This avoids issues
1117 // with shifting by the size of the integer type, which produces undefined
1118 // results. We define these "undefined results" to always be 0.
1119 if (shiftAmt == BitWidth)
1120 return APInt(BitWidth, 0);
1121
1122 // Create some space for the result.
1123 uint64_t * val = new uint64_t[getNumWords()];
1124
1125 // If we are shifting less than a word, do it the easy way
1126 if (shiftAmt < APINT_BITS_PER_WORD) {
1127 uint64_t carry = 0;
Reid Spencer87553802007-02-25 00:56:44 +00001128 for (uint32_t i = 0; i < getNumWords(); i++) {
1129 val[i] = pVal[i] << shiftAmt | carry;
1130 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1131 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001132 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001133 }
1134
Reid Spencer87553802007-02-25 00:56:44 +00001135 // Compute some values needed by the remaining shift algorithms
1136 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1137 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1138
1139 // If we are shifting whole words, just move whole words
1140 if (wordShift == 0) {
1141 for (uint32_t i = 0; i < offset; i++)
1142 val[i] = 0;
1143 for (uint32_t i = offset; i < getNumWords(); i++)
1144 val[i] = pVal[i-offset];
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001145 return APInt(val,BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001146 }
Reid Spencer87553802007-02-25 00:56:44 +00001147
1148 // Copy whole words from this to Result.
1149 uint32_t i = getNumWords() - 1;
1150 for (; i > offset; --i)
1151 val[i] = pVal[i-offset] << wordShift |
1152 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencer438d71e2007-02-25 01:08:58 +00001153 val[offset] = pVal[0] << wordShift;
Reid Spencer87553802007-02-25 00:56:44 +00001154 for (i = 0; i < offset; ++i)
1155 val[i] = 0;
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001156 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001157}
1158
Reid Spencer9c0696f2007-02-20 08:51:03 +00001159/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1160/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1161/// variables here have the same names as in the algorithm. Comments explain
1162/// the algorithm and any deviation from it.
1163static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1164 uint32_t m, uint32_t n) {
1165 assert(u && "Must provide dividend");
1166 assert(v && "Must provide divisor");
1167 assert(q && "Must provide quotient");
Reid Spencer9d6c9192007-02-24 03:58:46 +00001168 assert(u != v && u != q && v != q && "Must us different memory");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001169 assert(n>1 && "n must be > 1");
1170
1171 // Knuth uses the value b as the base of the number system. In our case b
1172 // is 2^31 so we just set it to -1u.
1173 uint64_t b = uint64_t(1) << 32;
1174
Reid Spencer9d6c9192007-02-24 03:58:46 +00001175 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1176 DEBUG(cerr << "KnuthDiv: original:");
1177 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1178 DEBUG(cerr << " by");
1179 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1180 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001181 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1182 // u and v by d. Note that we have taken Knuth's advice here to use a power
1183 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1184 // 2 allows us to shift instead of multiply and it is easy to determine the
1185 // shift amount from the leading zeros. We are basically normalizing the u
1186 // and v so that its high bits are shifted to the top of v's range without
1187 // overflow. Note that this can require an extra word in u so that u must
1188 // be of length m+n+1.
1189 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1190 uint32_t v_carry = 0;
1191 uint32_t u_carry = 0;
1192 if (shift) {
1193 for (uint32_t i = 0; i < m+n; ++i) {
1194 uint32_t u_tmp = u[i] >> (32 - shift);
1195 u[i] = (u[i] << shift) | u_carry;
1196 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001197 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001198 for (uint32_t i = 0; i < n; ++i) {
1199 uint32_t v_tmp = v[i] >> (32 - shift);
1200 v[i] = (v[i] << shift) | v_carry;
1201 v_carry = v_tmp;
1202 }
1203 }
1204 u[m+n] = u_carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001205 DEBUG(cerr << "KnuthDiv: normal:");
1206 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1207 DEBUG(cerr << " by");
1208 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1209 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001210
1211 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1212 int j = m;
1213 do {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001214 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001215 // D3. [Calculate q'.].
1216 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1217 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1218 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1219 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1220 // on v[n-2] determines at high speed most of the cases in which the trial
1221 // value qp is one too large, and it eliminates all cases where qp is two
1222 // too large.
Reid Spencer92904632007-02-23 01:57:13 +00001223 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001224 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencer92904632007-02-23 01:57:13 +00001225 uint64_t qp = dividend / v[n-1];
1226 uint64_t rp = dividend % v[n-1];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001227 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1228 qp--;
1229 rp += v[n-1];
Reid Spencer610fad82007-02-24 10:01:42 +00001230 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencer9d6c9192007-02-24 03:58:46 +00001231 qp--;
Reid Spencer92904632007-02-23 01:57:13 +00001232 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001233 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001234
Reid Spencer92904632007-02-23 01:57:13 +00001235 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1236 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1237 // consists of a simple multiplication by a one-place number, combined with
Reid Spencer610fad82007-02-24 10:01:42 +00001238 // a subtraction.
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001239 bool isNeg = false;
Reid Spencer92904632007-02-23 01:57:13 +00001240 for (uint32_t i = 0; i < n; ++i) {
Reid Spencer610fad82007-02-24 10:01:42 +00001241 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001242 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
Reid Spencer610fad82007-02-24 10:01:42 +00001243 bool borrow = subtrahend > u_tmp;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001244 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
Reid Spencer610fad82007-02-24 10:01:42 +00001245 << ", subtrahend == " << subtrahend
1246 << ", borrow = " << borrow << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001247
Reid Spencer610fad82007-02-24 10:01:42 +00001248 uint64_t result = u_tmp - subtrahend;
1249 uint32_t k = j + i;
1250 u[k++] = result & (b-1); // subtract low word
1251 u[k++] = result >> 32; // subtract high word
1252 while (borrow && k <= m+n) { // deal with borrow to the left
1253 borrow = u[k] == 0;
1254 u[k]--;
1255 k++;
1256 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001257 isNeg |= borrow;
Reid Spencer610fad82007-02-24 10:01:42 +00001258 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1259 u[j+i+1] << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001260 }
1261 DEBUG(cerr << "KnuthDiv: after subtraction:");
1262 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1263 DEBUG(cerr << '\n');
Reid Spencer610fad82007-02-24 10:01:42 +00001264 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1265 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1266 // true value plus b**(n+1), namely as the b's complement of
Reid Spencer92904632007-02-23 01:57:13 +00001267 // the true value, and a "borrow" to the left should be remembered.
1268 //
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001269 if (isNeg) {
Reid Spencer610fad82007-02-24 10:01:42 +00001270 bool carry = true; // true because b's complement is "complement + 1"
1271 for (uint32_t i = 0; i <= m+n; ++i) {
1272 u[i] = ~u[i] + carry; // b's complement
1273 carry = carry && u[i] == 0;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001274 }
Reid Spencer92904632007-02-23 01:57:13 +00001275 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001276 DEBUG(cerr << "KnuthDiv: after complement:");
1277 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1278 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001279
1280 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1281 // negative, go to step D6; otherwise go on to step D7.
1282 q[j] = qp;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001283 if (isNeg) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001284 // D6. [Add back]. The probability that this step is necessary is very
1285 // small, on the order of only 2/b. Make sure that test data accounts for
Reid Spencer92904632007-02-23 01:57:13 +00001286 // this possibility. Decrease q[j] by 1
1287 q[j]--;
1288 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1289 // A carry will occur to the left of u[j+n], and it should be ignored
1290 // since it cancels with the borrow that occurred in D4.
1291 bool carry = false;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001292 for (uint32_t i = 0; i < n; i++) {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001293 uint32_t limit = std::min(u[j+i],v[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001294 u[j+i] += v[i] + carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001295 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001296 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001297 u[j+n] += carry;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001298 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001299 DEBUG(cerr << "KnuthDiv: after correction:");
1300 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1301 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001302
Reid Spencer92904632007-02-23 01:57:13 +00001303 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1304 } while (--j >= 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001305
Reid Spencer9d6c9192007-02-24 03:58:46 +00001306 DEBUG(cerr << "KnuthDiv: quotient:");
1307 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1308 DEBUG(cerr << '\n');
1309
Reid Spencer9c0696f2007-02-20 08:51:03 +00001310 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1311 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1312 // compute the remainder (urem uses this).
1313 if (r) {
1314 // The value d is expressed by the "shift" value above since we avoided
1315 // multiplication by d by using a shift left. So, all we have to do is
1316 // shift right here. In order to mak
Reid Spencer1050ec52007-02-24 20:38:01 +00001317 if (shift) {
1318 uint32_t carry = 0;
1319 DEBUG(cerr << "KnuthDiv: remainder:");
1320 for (int i = n-1; i >= 0; i--) {
1321 r[i] = (u[i] >> shift) | carry;
1322 carry = u[i] << (32 - shift);
1323 DEBUG(cerr << " " << r[i]);
1324 }
1325 } else {
1326 for (int i = n-1; i >= 0; i--) {
1327 r[i] = u[i];
1328 DEBUG(cerr << " " << r[i]);
1329 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001330 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001331 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001332 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001333 DEBUG(cerr << std::setbase(10) << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001334}
1335
Reid Spencer9c0696f2007-02-20 08:51:03 +00001336void APInt::divide(const APInt LHS, uint32_t lhsWords,
1337 const APInt &RHS, uint32_t rhsWords,
1338 APInt *Quotient, APInt *Remainder)
1339{
1340 assert(lhsWords >= rhsWords && "Fractional result");
1341
1342 // First, compose the values into an array of 32-bit words instead of
1343 // 64-bit words. This is a necessity of both the "short division" algorithm
1344 // and the the Knuth "classical algorithm" which requires there to be native
1345 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1346 // can't use 64-bit operands here because we don't have native results of
1347 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1348 // work on large-endian machines.
1349 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1350 uint32_t n = rhsWords * 2;
1351 uint32_t m = (lhsWords * 2) - n;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001352
1353 // Allocate space for the temporary values we need either on the stack, if
1354 // it will fit, or on the heap if it won't.
1355 uint32_t SPACE[128];
1356 uint32_t *U = 0;
1357 uint32_t *V = 0;
1358 uint32_t *Q = 0;
1359 uint32_t *R = 0;
1360 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1361 U = &SPACE[0];
1362 V = &SPACE[m+n+1];
1363 Q = &SPACE[(m+n+1) + n];
1364 if (Remainder)
1365 R = &SPACE[(m+n+1) + n + (m+n)];
1366 } else {
1367 U = new uint32_t[m + n + 1];
1368 V = new uint32_t[n];
1369 Q = new uint32_t[m+n];
1370 if (Remainder)
1371 R = new uint32_t[n];
1372 }
1373
1374 // Initialize the dividend
Reid Spencer9c0696f2007-02-20 08:51:03 +00001375 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1376 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001377 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001378 U[i * 2] = tmp & mask;
1379 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1380 }
1381 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1382
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001383 // Initialize the divisor
Reid Spencer9c0696f2007-02-20 08:51:03 +00001384 memset(V, 0, (n)*sizeof(uint32_t));
1385 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001386 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001387 V[i * 2] = tmp & mask;
1388 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1389 }
1390
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001391 // initialize the quotient and remainder
Reid Spencer9c0696f2007-02-20 08:51:03 +00001392 memset(Q, 0, (m+n) * sizeof(uint32_t));
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001393 if (Remainder)
Reid Spencer9c0696f2007-02-20 08:51:03 +00001394 memset(R, 0, n * sizeof(uint32_t));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001395
1396 // Now, adjust m and n for the Knuth division. n is the number of words in
1397 // the divisor. m is the number of words by which the dividend exceeds the
1398 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1399 // contain any zero words or the Knuth algorithm fails.
1400 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1401 n--;
1402 m++;
1403 }
1404 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1405 m--;
1406
1407 // If we're left with only a single word for the divisor, Knuth doesn't work
1408 // so we implement the short division algorithm here. This is much simpler
1409 // and faster because we are certain that we can divide a 64-bit quantity
1410 // by a 32-bit quantity at hardware speed and short division is simply a
1411 // series of such operations. This is just like doing short division but we
1412 // are using base 2^32 instead of base 10.
1413 assert(n != 0 && "Divide by zero?");
1414 if (n == 1) {
1415 uint32_t divisor = V[0];
1416 uint32_t remainder = 0;
1417 for (int i = m+n-1; i >= 0; i--) {
1418 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1419 if (partial_dividend == 0) {
1420 Q[i] = 0;
1421 remainder = 0;
1422 } else if (partial_dividend < divisor) {
1423 Q[i] = 0;
1424 remainder = partial_dividend;
1425 } else if (partial_dividend == divisor) {
1426 Q[i] = 1;
1427 remainder = 0;
1428 } else {
1429 Q[i] = partial_dividend / divisor;
1430 remainder = partial_dividend - (Q[i] * divisor);
1431 }
1432 }
1433 if (R)
1434 R[0] = remainder;
1435 } else {
1436 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1437 // case n > 1.
1438 KnuthDiv(U, V, Q, R, m, n);
1439 }
1440
1441 // If the caller wants the quotient
1442 if (Quotient) {
1443 // Set up the Quotient value's memory.
1444 if (Quotient->BitWidth != LHS.BitWidth) {
1445 if (Quotient->isSingleWord())
1446 Quotient->VAL = 0;
1447 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001448 delete [] Quotient->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001449 Quotient->BitWidth = LHS.BitWidth;
1450 if (!Quotient->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001451 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001452 } else
1453 Quotient->clear();
1454
1455 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1456 // order words.
1457 if (lhsWords == 1) {
1458 uint64_t tmp =
1459 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1460 if (Quotient->isSingleWord())
1461 Quotient->VAL = tmp;
1462 else
1463 Quotient->pVal[0] = tmp;
1464 } else {
1465 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1466 for (unsigned i = 0; i < lhsWords; ++i)
1467 Quotient->pVal[i] =
1468 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1469 }
1470 }
1471
1472 // If the caller wants the remainder
1473 if (Remainder) {
1474 // Set up the Remainder value's memory.
1475 if (Remainder->BitWidth != RHS.BitWidth) {
1476 if (Remainder->isSingleWord())
1477 Remainder->VAL = 0;
1478 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001479 delete [] Remainder->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001480 Remainder->BitWidth = RHS.BitWidth;
1481 if (!Remainder->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001482 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001483 } else
1484 Remainder->clear();
1485
1486 // The remainder is in R. Reconstitute the remainder into Remainder's low
1487 // order words.
1488 if (rhsWords == 1) {
1489 uint64_t tmp =
1490 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1491 if (Remainder->isSingleWord())
1492 Remainder->VAL = tmp;
1493 else
1494 Remainder->pVal[0] = tmp;
1495 } else {
1496 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1497 for (unsigned i = 0; i < rhsWords; ++i)
1498 Remainder->pVal[i] =
1499 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1500 }
1501 }
1502
1503 // Clean up the memory we allocated.
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001504 if (U != &SPACE[0]) {
1505 delete [] U;
1506 delete [] V;
1507 delete [] Q;
1508 delete [] R;
1509 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001510}
1511
Reid Spencere81d2da2007-02-16 22:36:51 +00001512APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001513 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001514
1515 // First, deal with the easy case
1516 if (isSingleWord()) {
1517 assert(RHS.VAL != 0 && "Divide by zero?");
1518 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001519 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001520
Reid Spencer71bd08f2007-02-17 02:07:07 +00001521 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001522 uint32_t rhsBits = RHS.getActiveBits();
1523 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001524 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001525 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001526 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001527
1528 // Deal with some degenerate cases
1529 if (!lhsWords)
Reid Spencere0cdd332007-02-21 08:21:52 +00001530 // 0 / X ===> 0
1531 return APInt(BitWidth, 0);
1532 else if (lhsWords < rhsWords || this->ult(RHS)) {
1533 // X / Y ===> 0, iff X < Y
1534 return APInt(BitWidth, 0);
1535 } else if (*this == RHS) {
1536 // X / X ===> 1
1537 return APInt(BitWidth, 1);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001538 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001539 // All high words are zero, just use native divide
Reid Spencere0cdd332007-02-21 08:21:52 +00001540 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001541 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001542
1543 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1544 APInt Quotient(1,0); // to hold result.
1545 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1546 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001547}
1548
Reid Spencere81d2da2007-02-16 22:36:51 +00001549APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001550 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001551 if (isSingleWord()) {
1552 assert(RHS.VAL != 0 && "Remainder by zero?");
1553 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001554 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001555
Reid Spencere0cdd332007-02-21 08:21:52 +00001556 // Get some facts about the LHS
1557 uint32_t lhsBits = getActiveBits();
1558 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001559
1560 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001561 uint32_t rhsBits = RHS.getActiveBits();
1562 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001563 assert(rhsWords && "Performing remainder operation by zero ???");
1564
Reid Spencer71bd08f2007-02-17 02:07:07 +00001565 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001566 if (lhsWords == 0) {
Reid Spencere0cdd332007-02-21 08:21:52 +00001567 // 0 % Y ===> 0
1568 return APInt(BitWidth, 0);
1569 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1570 // X % Y ===> X, iff X < Y
1571 return *this;
1572 } else if (*this == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001573 // X % X == 0;
Reid Spencere0cdd332007-02-21 08:21:52 +00001574 return APInt(BitWidth, 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001575 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001576 // All high words are zero, just use native remainder
Reid Spencere0cdd332007-02-21 08:21:52 +00001577 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001578 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001579
1580 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1581 APInt Remainder(1,0);
1582 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1583 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001584}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001585
Reid Spencer385f7542007-02-21 03:55:44 +00001586void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001587 uint8_t radix) {
Reid Spencer385f7542007-02-21 03:55:44 +00001588 // Check our assumptions here
Reid Spencer5e0a8512007-02-17 03:16:00 +00001589 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1590 "Radix should be 2, 8, 10, or 16!");
Reid Spencer385f7542007-02-21 03:55:44 +00001591 assert(str && "String is null?");
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001592 bool isNeg = str[0] == '-';
1593 if (isNeg)
Reid Spencer9eec2412007-02-25 23:44:53 +00001594 str++, slen--;
Reid Spencer385f7542007-02-21 03:55:44 +00001595 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1596 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1597 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1598 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1599
1600 // Allocate memory
1601 if (!isSingleWord())
1602 pVal = getClearedMemory(getNumWords());
1603
1604 // Figure out if we can shift instead of multiply
1605 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1606
1607 // Set up an APInt for the digit to add outside the loop so we don't
1608 // constantly construct/destruct it.
1609 APInt apdigit(getBitWidth(), 0);
1610 APInt apradix(getBitWidth(), radix);
1611
1612 // Enter digit traversal loop
1613 for (unsigned i = 0; i < slen; i++) {
1614 // Get a digit
1615 uint32_t digit = 0;
1616 char cdigit = str[i];
1617 if (isdigit(cdigit))
1618 digit = cdigit - '0';
1619 else if (isxdigit(cdigit))
1620 if (cdigit >= 'a')
1621 digit = cdigit - 'a' + 10;
1622 else if (cdigit >= 'A')
1623 digit = cdigit - 'A' + 10;
1624 else
1625 assert(0 && "huh?");
1626 else
1627 assert(0 && "Invalid character in digit string");
1628
1629 // Shift or multiple the value by the radix
1630 if (shift)
1631 this->shl(shift);
1632 else
1633 *this *= apradix;
1634
1635 // Add in the digit we just interpreted
Reid Spencer5bce8542007-02-24 20:19:37 +00001636 if (apdigit.isSingleWord())
1637 apdigit.VAL = digit;
1638 else
1639 apdigit.pVal[0] = digit;
Reid Spencer385f7542007-02-21 03:55:44 +00001640 *this += apdigit;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001641 }
Reid Spencer9eec2412007-02-25 23:44:53 +00001642 // If its negative, put it in two's complement form
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001643 if (isNeg) {
1644 (*this)--;
Reid Spencer9eec2412007-02-25 23:44:53 +00001645 this->flip();
Reid Spencer9eec2412007-02-25 23:44:53 +00001646 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001647}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001648
Reid Spencer9c0696f2007-02-20 08:51:03 +00001649std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1650 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1651 "Radix should be 2, 8, 10, or 16!");
1652 static const char *digits[] = {
1653 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1654 };
1655 std::string result;
1656 uint32_t bits_used = getActiveBits();
1657 if (isSingleWord()) {
1658 char buf[65];
1659 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1660 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1661 if (format) {
1662 if (wantSigned) {
1663 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1664 (APINT_BITS_PER_WORD-BitWidth);
1665 sprintf(buf, format, sextVal);
1666 } else
1667 sprintf(buf, format, VAL);
1668 } else {
1669 memset(buf, 0, 65);
1670 uint64_t v = VAL;
1671 while (bits_used) {
1672 uint32_t bit = v & 1;
1673 bits_used--;
1674 buf[bits_used] = digits[bit][0];
1675 v >>=1;
1676 }
1677 }
1678 result = buf;
1679 return result;
1680 }
1681
1682 if (radix != 10) {
1683 uint64_t mask = radix - 1;
1684 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1685 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1686 for (uint32_t i = 0; i < getNumWords(); ++i) {
1687 uint64_t value = pVal[i];
1688 for (uint32_t j = 0; j < nibbles; ++j) {
1689 result.insert(0, digits[ value & mask ]);
1690 value >>= shift;
1691 }
1692 }
1693 return result;
1694 }
1695
1696 APInt tmp(*this);
1697 APInt divisor(4, radix);
1698 APInt zero(tmp.getBitWidth(), 0);
1699 size_t insert_at = 0;
1700 if (wantSigned && tmp[BitWidth-1]) {
1701 // They want to print the signed version and it is a negative value
1702 // Flip the bits and add one to turn it into the equivalent positive
1703 // value and put a '-' in the result.
1704 tmp.flip();
1705 tmp++;
1706 result = "-";
1707 insert_at = 1;
1708 }
Reid Spencere549c492007-02-21 00:29:48 +00001709 if (tmp == APInt(tmp.getBitWidth(), 0))
Reid Spencer9c0696f2007-02-20 08:51:03 +00001710 result = "0";
1711 else while (tmp.ne(zero)) {
1712 APInt APdigit(1,0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001713 APInt tmp2(tmp.getBitWidth(), 0);
Reid Spencer385f7542007-02-21 03:55:44 +00001714 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1715 &APdigit);
Reid Spencer794f4722007-02-26 21:02:27 +00001716 uint32_t digit = APdigit.getZExtValue();
Reid Spencer385f7542007-02-21 03:55:44 +00001717 assert(digit < radix && "divide failed");
1718 result.insert(insert_at,digits[digit]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001719 tmp = tmp2;
1720 }
1721
1722 return result;
1723}
1724
Reid Spencer385f7542007-02-21 03:55:44 +00001725#ifndef NDEBUG
1726void APInt::dump() const
1727{
Reid Spencer610fad82007-02-24 10:01:42 +00001728 cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
Reid Spencer385f7542007-02-21 03:55:44 +00001729 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +00001730 cerr << VAL;
Reid Spencer385f7542007-02-21 03:55:44 +00001731 else for (unsigned i = getNumWords(); i > 0; i--) {
Reid Spencer610fad82007-02-24 10:01:42 +00001732 cerr << pVal[i-1] << " ";
Reid Spencer385f7542007-02-21 03:55:44 +00001733 }
Reid Spencer610fad82007-02-24 10:01:42 +00001734 cerr << " (" << this->toString(10, false) << ")\n" << std::setbase(10);
Reid Spencer385f7542007-02-21 03:55:44 +00001735}
1736#endif