blob: 460cf557610c55751d8967e64708b61c2a648d4f [file] [log] [blame]
Zhou Shengfd43dcf2007-02-06 03:00:16 +00001//===-- APInt.cpp - Implement APInt class ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Reid Spencer96d91372007-02-27 19:31:09 +00005// This file was developed by Sheng Zhou and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Zhou Shengfd43dcf2007-02-06 03:00:16 +00007//
8//===----------------------------------------------------------------------===//
9//
Reid Spencer5d0d05c2007-02-25 19:32:03 +000010// This file implements a class to represent arbitrary precision integer
11// constant values and provide a variety of arithmetic operations on them.
Zhou Shengfd43dcf2007-02-06 03:00:16 +000012//
13//===----------------------------------------------------------------------===//
14
Reid Spencer9d6c9192007-02-24 03:58:46 +000015#define DEBUG_TYPE "apint"
Zhou Shengfd43dcf2007-02-06 03:00:16 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/DerivedTypes.h"
Reid Spencer9d6c9192007-02-24 03:58:46 +000018#include "llvm/Support/Debug.h"
Zhou Shengfd43dcf2007-02-06 03:00:16 +000019#include "llvm/Support/MathExtras.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000020#include <math.h>
Jeff Cohen09dfd8e2007-03-20 20:42:36 +000021#include <limits>
Zhou Shenga3832fd2007-02-07 06:14:53 +000022#include <cstring>
Zhou Shengfd43dcf2007-02-06 03:00:16 +000023#include <cstdlib>
Reid Spencer385f7542007-02-21 03:55:44 +000024#ifndef NDEBUG
Reid Spencer385f7542007-02-21 03:55:44 +000025#include <iomanip>
26#endif
27
Zhou Shengfd43dcf2007-02-06 03:00:16 +000028using namespace llvm;
29
Reid Spencer5d0d05c2007-02-25 19:32:03 +000030/// A utility function for allocating memory, checking for allocation failures,
31/// and ensuring the contents are zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000032inline static uint64_t* getClearedMemory(uint32_t numWords) {
33 uint64_t * result = new uint64_t[numWords];
34 assert(result && "APInt memory allocation fails!");
35 memset(result, 0, numWords * sizeof(uint64_t));
36 return result;
Zhou Sheng353815d2007-02-06 06:04:53 +000037}
38
Reid Spencer5d0d05c2007-02-25 19:32:03 +000039/// A utility function for allocating memory and checking for allocation
40/// failure. The content is not zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000041inline static uint64_t* getMemory(uint32_t numWords) {
42 uint64_t * result = new uint64_t[numWords];
43 assert(result && "APInt memory allocation fails!");
44 return result;
45}
46
Reid Spenceradf2a202007-03-19 21:19:02 +000047APInt::APInt(uint32_t numBits, uint64_t val, bool isSigned)
Reid Spencer3a341372007-03-19 20:37:47 +000048 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000049 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
50 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Reid Spencer5d0d05c2007-02-25 19:32:03 +000051 if (isSingleWord())
52 VAL = val;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000053 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000054 pVal = getClearedMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000055 pVal[0] = val;
Reid Spencer3a341372007-03-19 20:37:47 +000056 if (isSigned && int64_t(val) < 0)
57 for (unsigned i = 1; i < getNumWords(); ++i)
58 pVal[i] = -1ULL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000059 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +000060 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000061}
62
Reid Spenceraf0e9562007-02-18 18:38:44 +000063APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
Reid Spencer385f7542007-02-21 03:55:44 +000064 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000065 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
66 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000067 assert(bigVal && "Null pointer detected!");
68 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +000069 VAL = bigVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +000070 else {
Reid Spencer610fad82007-02-24 10:01:42 +000071 // Get memory, cleared to 0
72 pVal = getClearedMemory(getNumWords());
73 // Calculate the number of words to copy
74 uint32_t words = std::min<uint32_t>(numWords, getNumWords());
75 // Copy the words from bigVal to pVal
76 memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000077 }
Reid Spencer610fad82007-02-24 10:01:42 +000078 // Make sure unused high bits are cleared
79 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000080}
81
Reid Spenceraf0e9562007-02-18 18:38:44 +000082APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000083 uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000084 : BitWidth(numbits), VAL(0) {
Reid Spencer19dc32a2007-05-13 23:44:59 +000085 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
86 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Reid Spencere81d2da2007-02-16 22:36:51 +000087 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000088}
89
Reid Spencer9c0696f2007-02-20 08:51:03 +000090APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000091 : BitWidth(numbits), VAL(0) {
Reid Spencer19dc32a2007-05-13 23:44:59 +000092 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
93 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shenga3832fd2007-02-07 06:14:53 +000094 assert(!Val.empty() && "String empty?");
Reid Spencere81d2da2007-02-16 22:36:51 +000095 fromString(numbits, Val.c_str(), Val.size(), radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000096}
97
Reid Spencer54362ca2007-02-20 23:40:25 +000098APInt::APInt(const APInt& that)
Reid Spencer385f7542007-02-21 03:55:44 +000099 : BitWidth(that.BitWidth), VAL(0) {
Reid Spencer19dc32a2007-05-13 23:44:59 +0000100 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
101 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000102 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000103 VAL = that.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000104 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000105 pVal = getMemory(getNumWords());
Reid Spencer54362ca2007-02-20 23:40:25 +0000106 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000107 }
108}
109
110APInt::~APInt() {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000111 if (!isSingleWord() && pVal)
Reid Spencer9ac44112007-02-26 23:38:21 +0000112 delete [] pVal;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000113}
114
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000115APInt& APInt::operator=(const APInt& RHS) {
Reid Spencer9ac44112007-02-26 23:38:21 +0000116 // Don't do anything for X = X
117 if (this == &RHS)
118 return *this;
119
120 // If the bitwidths are the same, we can avoid mucking with memory
121 if (BitWidth == RHS.getBitWidth()) {
122 if (isSingleWord())
123 VAL = RHS.VAL;
124 else
125 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
126 return *this;
127 }
128
129 if (isSingleWord())
130 if (RHS.isSingleWord())
131 VAL = RHS.VAL;
132 else {
133 VAL = 0;
134 pVal = getMemory(RHS.getNumWords());
135 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
136 }
137 else if (getNumWords() == RHS.getNumWords())
138 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
139 else if (RHS.isSingleWord()) {
140 delete [] pVal;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000141 VAL = RHS.VAL;
Reid Spencer9ac44112007-02-26 23:38:21 +0000142 } else {
143 delete [] pVal;
144 pVal = getMemory(RHS.getNumWords());
145 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
146 }
147 BitWidth = RHS.BitWidth;
148 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000149}
150
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000151APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000152 if (isSingleWord())
153 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000154 else {
155 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000156 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000157 }
Reid Spencer9ac44112007-02-26 23:38:21 +0000158 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000159}
160
Reid Spenceraf0e9562007-02-18 18:38:44 +0000161/// add_1 - This function adds a single "digit" integer, y, to the multiple
162/// "digit" integer array, x[]. x[] is modified to reflect the addition and
163/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000164/// @returns the carry of the addition.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000165static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000166 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000167 dest[i] = y + x[i];
168 if (dest[i] < y)
Reid Spencer610fad82007-02-24 10:01:42 +0000169 y = 1; // Carry one to next digit.
Reid Spencerf2c521c2007-02-18 06:39:42 +0000170 else {
Reid Spencer610fad82007-02-24 10:01:42 +0000171 y = 0; // No need to carry so exit early
Reid Spencerf2c521c2007-02-18 06:39:42 +0000172 break;
173 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000174 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000175 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000176}
177
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000178/// @brief Prefix increment operator. Increments the APInt by one.
179APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000180 if (isSingleWord())
181 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000182 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000183 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000184 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000185}
186
Reid Spenceraf0e9562007-02-18 18:38:44 +0000187/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
188/// the multi-digit integer array, x[], propagating the borrowed 1 value until
189/// no further borrowing is neeeded or it runs out of "digits" in x. The result
190/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
191/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000192/// @returns the borrow out of the subtraction
193static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000194 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000195 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000196 x[i] -= y;
197 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000198 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000199 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000200 y = 0; // No need to borrow
201 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000202 }
203 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000204 return bool(y);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000205}
206
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000207/// @brief Prefix decrement operator. Decrements the APInt by one.
208APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000209 if (isSingleWord())
210 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000211 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000212 sub_1(pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000213 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000214}
215
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000216/// add - This function adds the integer array x to the integer array Y and
217/// places the result in dest.
218/// @returns the carry out from the addition
219/// @brief General addition of 64-bit integer arrays
Reid Spencer9d6c9192007-02-24 03:58:46 +0000220static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
221 uint32_t len) {
222 bool carry = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000223 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer92904632007-02-23 01:57:13 +0000224 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer54362ca2007-02-20 23:40:25 +0000225 dest[i] = x[i] + y[i] + carry;
Reid Spencer60c0a6a2007-02-21 05:44:56 +0000226 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000227 }
228 return carry;
229}
230
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000231/// Adds the RHS APint to this APInt.
232/// @returns this, after addition of RHS.
233/// @brief Addition assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000234APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000235 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000236 if (isSingleWord())
237 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000238 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000239 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000240 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000241 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000242}
243
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000244/// Subtracts the integer array y from the integer array x
245/// @returns returns the borrow out.
246/// @brief Generalized subtraction of 64-bit integer arrays.
Reid Spencer9d6c9192007-02-24 03:58:46 +0000247static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
248 uint32_t len) {
Reid Spencer385f7542007-02-21 03:55:44 +0000249 bool borrow = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000250 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer385f7542007-02-21 03:55:44 +0000251 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
252 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
253 dest[i] = x_tmp - y[i];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000254 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000255 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000256}
257
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000258/// Subtracts the RHS APInt from this APInt
259/// @returns this, after subtraction
260/// @brief Subtraction assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000261APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000262 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000263 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000264 VAL -= RHS.VAL;
265 else
266 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000267 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000268}
269
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000270/// Multiplies an integer array, x by a a uint64_t integer and places the result
271/// into dest.
272/// @returns the carry out of the multiplication.
273/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Reid Spencer610fad82007-02-24 10:01:42 +0000274static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
275 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer5e0a8512007-02-17 03:16:00 +0000276 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000277 uint64_t carry = 0;
278
279 // For each digit of x.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000280 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000281 // Split x into high and low words
282 uint64_t lx = x[i] & 0xffffffffULL;
283 uint64_t hx = x[i] >> 32;
284 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000285 // hasCarry == 0, no carry
286 // hasCarry == 1, has carry
287 // hasCarry == 2, no carry and the calculation result == 0.
288 uint8_t hasCarry = 0;
289 dest[i] = carry + lx * ly;
290 // Determine if the add above introduces carry.
291 hasCarry = (dest[i] < carry) ? 1 : 0;
292 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
293 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
294 // (2^32 - 1) + 2^32 = 2^64.
295 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
296
297 carry += (lx * hy) & 0xffffffffULL;
298 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
299 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
300 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
301 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000302 return carry;
303}
304
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000305/// Multiplies integer array x by integer array y and stores the result into
306/// the integer array dest. Note that dest's size must be >= xlen + ylen.
307/// @brief Generalized multiplicate of integer arrays.
Reid Spencer610fad82007-02-24 10:01:42 +0000308static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[],
309 uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000310 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000311 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000312 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencere0cdd332007-02-21 08:21:52 +0000313 uint64_t carry = 0, lx = 0, hx = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000314 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000315 lx = x[j] & 0xffffffffULL;
316 hx = x[j] >> 32;
317 // hasCarry - A flag to indicate if has carry.
318 // hasCarry == 0, no carry
319 // hasCarry == 1, has carry
320 // hasCarry == 2, no carry and the calculation result == 0.
321 uint8_t hasCarry = 0;
322 uint64_t resul = carry + lx * ly;
323 hasCarry = (resul < carry) ? 1 : 0;
324 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
325 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
326
327 carry += (lx * hy) & 0xffffffffULL;
328 resul = (carry << 32) | (resul & 0xffffffffULL);
329 dest[i+j] += resul;
330 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
331 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
332 ((lx * hy) >> 32) + hx * hy;
333 }
334 dest[i+xlen] = carry;
335 }
336}
337
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000338APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000339 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencere0cdd332007-02-21 08:21:52 +0000340 if (isSingleWord()) {
Reid Spencer61eb1802007-02-20 20:42:10 +0000341 VAL *= RHS.VAL;
Reid Spencere0cdd332007-02-21 08:21:52 +0000342 clearUnusedBits();
343 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000344 }
Reid Spencere0cdd332007-02-21 08:21:52 +0000345
346 // Get some bit facts about LHS and check for zero
347 uint32_t lhsBits = getActiveBits();
348 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
349 if (!lhsWords)
350 // 0 * X ===> 0
351 return *this;
352
353 // Get some bit facts about RHS and check for zero
354 uint32_t rhsBits = RHS.getActiveBits();
355 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
356 if (!rhsWords) {
357 // X * 0 ===> 0
358 clear();
359 return *this;
360 }
361
362 // Allocate space for the result
363 uint32_t destWords = rhsWords + lhsWords;
364 uint64_t *dest = getMemory(destWords);
365
366 // Perform the long multiply
367 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
368
369 // Copy result back into *this
370 clear();
371 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
372 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
373
374 // delete dest array and return
375 delete[] dest;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000376 return *this;
377}
378
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000379APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000380 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000381 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000382 VAL &= RHS.VAL;
383 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000384 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000385 uint32_t numWords = getNumWords();
386 for (uint32_t i = 0; i < numWords; ++i)
387 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000388 return *this;
389}
390
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000391APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000392 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000393 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000394 VAL |= RHS.VAL;
395 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000396 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000397 uint32_t numWords = getNumWords();
398 for (uint32_t i = 0; i < numWords; ++i)
399 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000400 return *this;
401}
402
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000403APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000404 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000405 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000406 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000407 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000408 return *this;
409 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000410 uint32_t numWords = getNumWords();
411 for (uint32_t i = 0; i < numWords; ++i)
412 pVal[i] ^= RHS.pVal[i];
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000413 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000414}
415
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000416APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000417 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000418 if (isSingleWord())
419 return APInt(getBitWidth(), VAL & RHS.VAL);
420
Reid Spenceraf0e9562007-02-18 18:38:44 +0000421 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000422 uint64_t* val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000423 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000424 val[i] = pVal[i] & RHS.pVal[i];
425 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000426}
427
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000428APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000429 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000430 if (isSingleWord())
431 return APInt(getBitWidth(), VAL | RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000432
Reid Spenceraf0e9562007-02-18 18:38:44 +0000433 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000434 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000435 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000436 val[i] = pVal[i] | RHS.pVal[i];
437 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000438}
439
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000440APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000441 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000442 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000443 return APInt(BitWidth, VAL ^ RHS.VAL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000444
Reid Spenceraf0e9562007-02-18 18:38:44 +0000445 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000446 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000447 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000448 val[i] = pVal[i] ^ RHS.pVal[i];
449
450 // 0^0==1 so clear the high bits in case they got set.
451 return APInt(val, getBitWidth()).clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000452}
453
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000454bool APInt::operator !() const {
455 if (isSingleWord())
456 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000457
458 for (uint32_t i = 0; i < getNumWords(); ++i)
459 if (pVal[i])
460 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000461 return true;
462}
463
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000464APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000465 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000466 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000467 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer61eb1802007-02-20 20:42:10 +0000468 APInt Result(*this);
469 Result *= RHS;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000470 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000471}
472
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000473APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000474 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000475 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000476 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000477 APInt Result(BitWidth, 0);
478 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000479 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000480}
481
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000482APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000483 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000484 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000485 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000486 APInt Result(BitWidth, 0);
487 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000488 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000489}
490
Reid Spenceraf0e9562007-02-18 18:38:44 +0000491bool APInt::operator[](uint32_t bitPosition) const {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000492 return (maskBit(bitPosition) &
493 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000494}
495
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000496bool APInt::operator==(const APInt& RHS) const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000497 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
Reid Spencer54362ca2007-02-20 23:40:25 +0000498 if (isSingleWord())
499 return VAL == RHS.VAL;
500
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000501 // Get some facts about the number of bits used in the two operands.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000502 uint32_t n1 = getActiveBits();
503 uint32_t n2 = RHS.getActiveBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000504
505 // If the number of bits isn't the same, they aren't equal
Reid Spencer54362ca2007-02-20 23:40:25 +0000506 if (n1 != n2)
507 return false;
508
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000509 // If the number of bits fits in a word, we only need to compare the low word.
Reid Spencer54362ca2007-02-20 23:40:25 +0000510 if (n1 <= APINT_BITS_PER_WORD)
511 return pVal[0] == RHS.pVal[0];
512
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000513 // Otherwise, compare everything
Reid Spencer54362ca2007-02-20 23:40:25 +0000514 for (int i = whichWord(n1 - 1); i >= 0; --i)
515 if (pVal[i] != RHS.pVal[i])
516 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000517 return true;
518}
519
Zhou Shenga3832fd2007-02-07 06:14:53 +0000520bool APInt::operator==(uint64_t Val) const {
521 if (isSingleWord())
522 return VAL == Val;
Reid Spencer54362ca2007-02-20 23:40:25 +0000523
524 uint32_t n = getActiveBits();
525 if (n <= APINT_BITS_PER_WORD)
526 return pVal[0] == Val;
527 else
528 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000529}
530
Reid Spencere81d2da2007-02-16 22:36:51 +0000531bool APInt::ult(const APInt& RHS) const {
532 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
533 if (isSingleWord())
534 return VAL < RHS.VAL;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000535
536 // Get active bit length of both operands
537 uint32_t n1 = getActiveBits();
538 uint32_t n2 = RHS.getActiveBits();
539
540 // If magnitude of LHS is less than RHS, return true.
541 if (n1 < n2)
542 return true;
543
544 // If magnitude of RHS is greather than LHS, return false.
545 if (n2 < n1)
546 return false;
547
548 // If they bot fit in a word, just compare the low order word
549 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
550 return pVal[0] < RHS.pVal[0];
551
552 // Otherwise, compare all words
Reid Spencer1fa111e2007-02-27 18:23:40 +0000553 uint32_t topWord = whichWord(std::max(n1,n2)-1);
554 for (int i = topWord; i >= 0; --i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000555 if (pVal[i] > RHS.pVal[i])
Reid Spencere81d2da2007-02-16 22:36:51 +0000556 return false;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000557 if (pVal[i] < RHS.pVal[i])
558 return true;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000559 }
560 return false;
561}
562
Reid Spencere81d2da2007-02-16 22:36:51 +0000563bool APInt::slt(const APInt& RHS) const {
564 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000565 if (isSingleWord()) {
566 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
567 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
568 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000569 }
Reid Spencera58f0582007-02-18 20:09:41 +0000570
571 APInt lhs(*this);
Reid Spencer1fa111e2007-02-27 18:23:40 +0000572 APInt rhs(RHS);
573 bool lhsNeg = isNegative();
574 bool rhsNeg = rhs.isNegative();
575 if (lhsNeg) {
576 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000577 lhs.flip();
578 lhs++;
579 }
Reid Spencer1fa111e2007-02-27 18:23:40 +0000580 if (rhsNeg) {
581 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000582 rhs.flip();
583 rhs++;
584 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000585
586 // Now we have unsigned values to compare so do the comparison if necessary
587 // based on the negativeness of the values.
Reid Spencer1fa111e2007-02-27 18:23:40 +0000588 if (lhsNeg)
589 if (rhsNeg)
590 return lhs.ugt(rhs);
Reid Spencera58f0582007-02-18 20:09:41 +0000591 else
592 return true;
Reid Spencer1fa111e2007-02-27 18:23:40 +0000593 else if (rhsNeg)
Reid Spencera58f0582007-02-18 20:09:41 +0000594 return false;
595 else
596 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000597}
598
Reid Spenceraf0e9562007-02-18 18:38:44 +0000599APInt& APInt::set(uint32_t bitPosition) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000600 if (isSingleWord())
601 VAL |= maskBit(bitPosition);
602 else
603 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000604 return *this;
605}
606
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000607APInt& APInt::set() {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000608 if (isSingleWord()) {
609 VAL = -1ULL;
610 return clearUnusedBits();
Zhou Shengb04973e2007-02-15 06:36:31 +0000611 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000612
613 // Set all the bits in all the words.
Zhou Sheng6dbe2332007-03-21 04:34:37 +0000614 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000615 pVal[i] = -1ULL;
616 // Clear the unused ones
617 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000618}
619
620/// Set the given bit to 0 whose position is given as "bitPosition".
621/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000622APInt& APInt::clear(uint32_t bitPosition) {
623 if (isSingleWord())
624 VAL &= ~maskBit(bitPosition);
625 else
626 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000627 return *this;
628}
629
630/// @brief Set every bit to 0.
631APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000632 if (isSingleWord())
633 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000634 else
Reid Spencera58f0582007-02-18 20:09:41 +0000635 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000636 return *this;
637}
638
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000639/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
640/// this APInt.
641APInt APInt::operator~() const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000642 APInt Result(*this);
643 Result.flip();
644 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000645}
646
647/// @brief Toggle every bit to its opposite value.
648APInt& APInt::flip() {
Reid Spencer9eec2412007-02-25 23:44:53 +0000649 if (isSingleWord()) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000650 VAL ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000651 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000652 }
Reid Spencer9eec2412007-02-25 23:44:53 +0000653 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000654 pVal[i] ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000655 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000656}
657
658/// Toggle a given bit to its opposite value whose position is given
659/// as "bitPosition".
660/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000661APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000662 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000663 if ((*this)[bitPosition]) clear(bitPosition);
664 else set(bitPosition);
665 return *this;
666}
667
Reid Spencer57ae4f52007-04-13 19:19:07 +0000668uint32_t APInt::getBitsNeeded(const char* str, uint32_t slen, uint8_t radix) {
669 assert(str != 0 && "Invalid value string");
670 assert(slen > 0 && "Invalid string length");
671
672 // Each computation below needs to know if its negative
673 uint32_t isNegative = str[0] == '-';
674 if (isNegative) {
675 slen--;
676 str++;
677 }
678 // For radixes of power-of-two values, the bits required is accurately and
679 // easily computed
680 if (radix == 2)
681 return slen + isNegative;
682 if (radix == 8)
683 return slen * 3 + isNegative;
684 if (radix == 16)
685 return slen * 4 + isNegative;
686
687 // Otherwise it must be radix == 10, the hard case
688 assert(radix == 10 && "Invalid radix");
689
690 // This is grossly inefficient but accurate. We could probably do something
691 // with a computation of roughly slen*64/20 and then adjust by the value of
692 // the first few digits. But, I'm not sure how accurate that could be.
693
694 // Compute a sufficient number of bits that is always large enough but might
695 // be too large. This avoids the assertion in the constructor.
696 uint32_t sufficient = slen*64/18;
697
698 // Convert to the actual binary value.
699 APInt tmp(sufficient, str, slen, radix);
700
701 // Compute how many bits are required.
Reid Spencer0468ab32007-04-14 00:00:10 +0000702 return isNegative + tmp.logBase2() + 1;
Reid Spencer57ae4f52007-04-13 19:19:07 +0000703}
704
Reid Spencer794f4722007-02-26 21:02:27 +0000705uint64_t APInt::getHashValue() const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000706 // Put the bit width into the low order bits.
707 uint64_t hash = BitWidth;
Reid Spencer794f4722007-02-26 21:02:27 +0000708
709 // Add the sum of the words to the hash.
710 if (isSingleWord())
Reid Spencer9ac44112007-02-26 23:38:21 +0000711 hash += VAL << 6; // clear separation of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000712 else
713 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer9ac44112007-02-26 23:38:21 +0000714 hash += pVal[i] << 6; // clear sepration of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000715 return hash;
716}
717
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000718/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000719APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000720 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000721}
722
723/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000724APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000725 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
726 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000727}
728
Reid Spencere81d2da2007-02-16 22:36:51 +0000729bool APInt::isPowerOf2() const {
730 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
731}
732
Reid Spenceraf0e9562007-02-18 18:38:44 +0000733uint32_t APInt::countLeadingZeros() const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000734 uint32_t Count = 0;
Reid Spencere549c492007-02-21 00:29:48 +0000735 if (isSingleWord())
736 Count = CountLeadingZeros_64(VAL);
737 else {
738 for (uint32_t i = getNumWords(); i > 0u; --i) {
739 if (pVal[i-1] == 0)
740 Count += APINT_BITS_PER_WORD;
741 else {
742 Count += CountLeadingZeros_64(pVal[i-1]);
743 break;
744 }
745 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000746 }
Reid Spencerab2b2c82007-02-22 00:22:00 +0000747 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
748 if (remainder)
749 Count -= APINT_BITS_PER_WORD - remainder;
750 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000751}
752
Reid Spencer681dcd12007-02-27 21:59:26 +0000753static uint32_t countLeadingOnes_64(uint64_t V, uint32_t skip) {
754 uint32_t Count = 0;
755 if (skip)
756 V <<= skip;
757 while (V && (V & (1ULL << 63))) {
758 Count++;
759 V <<= 1;
760 }
761 return Count;
762}
763
764uint32_t APInt::countLeadingOnes() const {
765 if (isSingleWord())
766 return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth);
767
768 uint32_t highWordBits = BitWidth % APINT_BITS_PER_WORD;
769 uint32_t shift = (highWordBits == 0 ? 0 : APINT_BITS_PER_WORD - highWordBits);
770 int i = getNumWords() - 1;
771 uint32_t Count = countLeadingOnes_64(pVal[i], shift);
772 if (Count == highWordBits) {
773 for (i--; i >= 0; --i) {
774 if (pVal[i] == -1ULL)
775 Count += APINT_BITS_PER_WORD;
776 else {
777 Count += countLeadingOnes_64(pVal[i], 0);
778 break;
779 }
780 }
781 }
782 return Count;
783}
784
Reid Spenceraf0e9562007-02-18 18:38:44 +0000785uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000786 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000787 return CountTrailingZeros_64(VAL);
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000788 uint32_t Count = 0;
789 uint32_t i = 0;
790 for (; i < getNumWords() && pVal[i] == 0; ++i)
791 Count += APINT_BITS_PER_WORD;
792 if (i < getNumWords())
793 Count += CountTrailingZeros_64(pVal[i]);
794 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000795}
796
Reid Spenceraf0e9562007-02-18 18:38:44 +0000797uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000798 if (isSingleWord())
799 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000800 uint32_t Count = 0;
801 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000802 Count += CountPopulation_64(pVal[i]);
803 return Count;
804}
805
Reid Spencere81d2da2007-02-16 22:36:51 +0000806APInt APInt::byteSwap() const {
807 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
808 if (BitWidth == 16)
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000809 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Reid Spencere81d2da2007-02-16 22:36:51 +0000810 else if (BitWidth == 32)
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000811 return APInt(BitWidth, ByteSwap_32(uint32_t(VAL)));
Reid Spencere81d2da2007-02-16 22:36:51 +0000812 else if (BitWidth == 48) {
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000813 uint32_t Tmp1 = uint32_t(VAL >> 16);
Zhou Shengb04973e2007-02-15 06:36:31 +0000814 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000815 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengb04973e2007-02-15 06:36:31 +0000816 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000817 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000818 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000819 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000820 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000821 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000822 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000823 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000824 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000825 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
826 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000827 }
828 return Result;
829 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000830}
831
Zhou Sheng0b706b12007-02-08 14:35:19 +0000832APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
833 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000834 APInt A = API1, B = API2;
835 while (!!B) {
836 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000837 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000838 A = T;
839 }
840 return A;
841}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000842
Reid Spencer1fa111e2007-02-27 18:23:40 +0000843APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, uint32_t width) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000844 union {
845 double D;
846 uint64_t I;
847 } T;
848 T.D = Double;
Reid Spencer30f44f32007-02-27 01:28:10 +0000849
850 // Get the sign bit from the highest order bit
Zhou Shengd93f00c2007-02-12 20:02:55 +0000851 bool isNeg = T.I >> 63;
Reid Spencer30f44f32007-02-27 01:28:10 +0000852
853 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd93f00c2007-02-12 20:02:55 +0000854 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer30f44f32007-02-27 01:28:10 +0000855
856 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000857 if (exp < 0)
Reid Spencerff605762007-02-28 01:30:08 +0000858 return APInt(width, 0u);
Reid Spencer30f44f32007-02-27 01:28:10 +0000859
860 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
861 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
862
863 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd93f00c2007-02-12 20:02:55 +0000864 if (exp < 52)
Reid Spencer1fa111e2007-02-27 18:23:40 +0000865 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
866 APInt(width, mantissa >> (52 - exp));
867
868 // If the client didn't provide enough bits for us to shift the mantissa into
869 // then the result is undefined, just return 0
870 if (width <= exp - 52)
871 return APInt(width, 0);
Reid Spencer30f44f32007-02-27 01:28:10 +0000872
873 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer1fa111e2007-02-27 18:23:40 +0000874 APInt Tmp(width, mantissa);
Reid Spencere81d2da2007-02-16 22:36:51 +0000875 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000876 return isNeg ? -Tmp : Tmp;
877}
878
Reid Spencerdb3faa62007-02-13 22:41:58 +0000879/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000880/// The layout for double is as following (IEEE Standard 754):
881/// --------------------------------------
882/// | Sign Exponent Fraction Bias |
883/// |-------------------------------------- |
884/// | 1[63] 11[62-52] 52[51-00] 1023 |
885/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000886double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000887
888 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000889 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
890 if (isSigned) {
891 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
892 return double(sext);
893 } else
894 return double(VAL);
895 }
896
Reid Spencer9c0696f2007-02-20 08:51:03 +0000897 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000898 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000899
900 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000901 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000902
903 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000904 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000905
Reid Spencer9c0696f2007-02-20 08:51:03 +0000906 // The exponent (without bias normalization) is just the number of bits
907 // we are using. Note that the sign bit is gone since we constructed the
908 // absolute value.
909 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000910
Reid Spencer9c0696f2007-02-20 08:51:03 +0000911 // Return infinity for exponent overflow
912 if (exp > 1023) {
913 if (!isSigned || !isNeg)
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000914 return std::numeric_limits<double>::infinity();
Reid Spencer9c0696f2007-02-20 08:51:03 +0000915 else
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000916 return -std::numeric_limits<double>::infinity();
Reid Spencer9c0696f2007-02-20 08:51:03 +0000917 }
918 exp += 1023; // Increment for 1023 bias
919
920 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
921 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000922 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000923 unsigned hiWord = whichWord(n-1);
924 if (hiWord == 0) {
925 mantissa = Tmp.pVal[0];
926 if (n > 52)
927 mantissa >>= n - 52; // shift down, we want the top 52 bits.
928 } else {
929 assert(hiWord > 0 && "huh?");
930 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
931 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
932 mantissa = hibits | lobits;
933 }
934
Zhou Shengd93f00c2007-02-12 20:02:55 +0000935 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000936 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000937 union {
938 double D;
939 uint64_t I;
940 } T;
941 T.I = sign | (exp << 52) | mantissa;
942 return T.D;
943}
944
Reid Spencere81d2da2007-02-16 22:36:51 +0000945// Truncate to new width.
Reid Spencer94900772007-02-28 17:34:32 +0000946APInt &APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000947 assert(width < BitWidth && "Invalid APInt Truncate request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000948 assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
949 uint32_t wordsBefore = getNumWords();
950 BitWidth = width;
951 uint32_t wordsAfter = getNumWords();
952 if (wordsBefore != wordsAfter) {
953 if (wordsAfter == 1) {
954 uint64_t *tmp = pVal;
955 VAL = pVal[0];
Reid Spencer9ac44112007-02-26 23:38:21 +0000956 delete [] tmp;
Reid Spencer9eec2412007-02-25 23:44:53 +0000957 } else {
958 uint64_t *newVal = getClearedMemory(wordsAfter);
959 for (uint32_t i = 0; i < wordsAfter; ++i)
960 newVal[i] = pVal[i];
Reid Spencer9ac44112007-02-26 23:38:21 +0000961 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000962 pVal = newVal;
963 }
964 }
Reid Spencer94900772007-02-28 17:34:32 +0000965 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000966}
967
968// Sign extend to a new width.
Reid Spencer94900772007-02-28 17:34:32 +0000969APInt &APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000970 assert(width > BitWidth && "Invalid APInt SignExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000971 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
Reid Spencer9eec2412007-02-25 23:44:53 +0000972 // If the sign bit isn't set, this is the same as zext.
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000973 if (!isNegative()) {
Reid Spencer9eec2412007-02-25 23:44:53 +0000974 zext(width);
Reid Spencer94900772007-02-28 17:34:32 +0000975 return *this;
Reid Spencer9eec2412007-02-25 23:44:53 +0000976 }
977
978 // The sign bit is set. First, get some facts
979 uint32_t wordsBefore = getNumWords();
980 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
981 BitWidth = width;
982 uint32_t wordsAfter = getNumWords();
983
984 // Mask the high order word appropriately
985 if (wordsBefore == wordsAfter) {
986 uint32_t newWordBits = width % APINT_BITS_PER_WORD;
987 // The extension is contained to the wordsBefore-1th word.
Reid Spencer36184ed2007-03-02 01:19:42 +0000988 uint64_t mask = ~0ULL;
989 if (newWordBits)
990 mask >>= APINT_BITS_PER_WORD - newWordBits;
991 mask <<= wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +0000992 if (wordsBefore == 1)
993 VAL |= mask;
994 else
995 pVal[wordsBefore-1] |= mask;
Reid Spencer295e40a2007-03-01 23:30:25 +0000996 return clearUnusedBits();
Reid Spencer9eec2412007-02-25 23:44:53 +0000997 }
998
Reid Spencerf30b1882007-02-25 23:54:00 +0000999 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +00001000 uint64_t *newVal = getMemory(wordsAfter);
1001 if (wordsBefore == 1)
1002 newVal[0] = VAL | mask;
1003 else {
1004 for (uint32_t i = 0; i < wordsBefore; ++i)
1005 newVal[i] = pVal[i];
1006 newVal[wordsBefore-1] |= mask;
1007 }
1008 for (uint32_t i = wordsBefore; i < wordsAfter; i++)
1009 newVal[i] = -1ULL;
1010 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +00001011 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +00001012 pVal = newVal;
Reid Spencer94900772007-02-28 17:34:32 +00001013 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +00001014}
1015
1016// Zero extend to a new width.
Reid Spencer94900772007-02-28 17:34:32 +00001017APInt &APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +00001018 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +00001019 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
1020 uint32_t wordsBefore = getNumWords();
1021 BitWidth = width;
1022 uint32_t wordsAfter = getNumWords();
1023 if (wordsBefore != wordsAfter) {
1024 uint64_t *newVal = getClearedMemory(wordsAfter);
1025 if (wordsBefore == 1)
1026 newVal[0] = VAL;
1027 else
1028 for (uint32_t i = 0; i < wordsBefore; ++i)
1029 newVal[i] = pVal[i];
1030 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +00001031 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +00001032 pVal = newVal;
1033 }
Reid Spencer94900772007-02-28 17:34:32 +00001034 return *this;
Reid Spencere81d2da2007-02-16 22:36:51 +00001035}
1036
Reid Spencer68e23002007-03-01 17:15:32 +00001037APInt &APInt::zextOrTrunc(uint32_t width) {
1038 if (BitWidth < width)
1039 return zext(width);
1040 if (BitWidth > width)
1041 return trunc(width);
1042 return *this;
1043}
1044
1045APInt &APInt::sextOrTrunc(uint32_t width) {
1046 if (BitWidth < width)
1047 return sext(width);
1048 if (BitWidth > width)
1049 return trunc(width);
1050 return *this;
1051}
1052
Zhou Shengff4304f2007-02-09 07:48:24 +00001053/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001054/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001055APInt APInt::ashr(uint32_t shiftAmt) const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001056 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer46f9c942007-03-02 22:39:11 +00001057 // Handle a degenerate case
1058 if (shiftAmt == 0)
1059 return *this;
1060
1061 // Handle single word shifts with built-in ashr
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001062 if (isSingleWord()) {
1063 if (shiftAmt == BitWidth)
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001064 return APInt(BitWidth, 0); // undefined
1065 else {
1066 uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001067 return APInt(BitWidth,
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001068 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1069 }
Zhou Sheng0b706b12007-02-08 14:35:19 +00001070 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001071
Reid Spencer46f9c942007-03-02 22:39:11 +00001072 // If all the bits were shifted out, the result is, technically, undefined.
1073 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1074 // issues in the algorithm below.
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001075 if (shiftAmt == BitWidth) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001076 if (isNegative())
1077 return APInt(BitWidth, -1ULL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001078 else
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001079 return APInt(BitWidth, 0);
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001080 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001081
1082 // Create some space for the result.
1083 uint64_t * val = new uint64_t[getNumWords()];
1084
Reid Spencer46f9c942007-03-02 22:39:11 +00001085 // Compute some values needed by the following shift algorithms
1086 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1087 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1088 uint32_t breakWord = getNumWords() - 1 - offset; // last word affected
1089 uint32_t bitsInWord = whichBit(BitWidth); // how many bits in last word?
1090 if (bitsInWord == 0)
1091 bitsInWord = APINT_BITS_PER_WORD;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001092
1093 // If we are shifting whole words, just move whole words
1094 if (wordShift == 0) {
Reid Spencer46f9c942007-03-02 22:39:11 +00001095 // Move the words containing significant bits
1096 for (uint32_t i = 0; i <= breakWord; ++i)
1097 val[i] = pVal[i+offset]; // move whole word
1098
1099 // Adjust the top significant word for sign bit fill, if negative
1100 if (isNegative())
1101 if (bitsInWord < APINT_BITS_PER_WORD)
1102 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1103 } else {
1104 // Shift the low order words
1105 for (uint32_t i = 0; i < breakWord; ++i) {
1106 // This combines the shifted corresponding word with the low bits from
1107 // the next word (shifted into this word's high bits).
1108 val[i] = (pVal[i+offset] >> wordShift) |
1109 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1110 }
1111
1112 // Shift the break word. In this case there are no bits from the next word
1113 // to include in this word.
1114 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1115
1116 // Deal with sign extenstion in the break word, and possibly the word before
1117 // it.
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001118 if (isNegative()) {
Reid Spencer46f9c942007-03-02 22:39:11 +00001119 if (wordShift > bitsInWord) {
1120 if (breakWord > 0)
1121 val[breakWord-1] |=
1122 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1123 val[breakWord] |= ~0ULL;
1124 } else
1125 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001126 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001127 }
1128
Reid Spencer46f9c942007-03-02 22:39:11 +00001129 // Remaining words are 0 or -1, just assign them.
1130 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001131 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer46f9c942007-03-02 22:39:11 +00001132 val[i] = fillValue;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001133 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001134}
1135
Zhou Shengff4304f2007-02-09 07:48:24 +00001136/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001137/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001138APInt APInt::lshr(uint32_t shiftAmt) const {
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001139 if (isSingleWord()) {
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001140 if (shiftAmt == BitWidth)
1141 return APInt(BitWidth, 0);
1142 else
1143 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001144 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001145
Reid Spencerba81c2b2007-02-26 01:19:48 +00001146 // If all the bits were shifted out, the result is 0. This avoids issues
1147 // with shifting by the size of the integer type, which produces undefined
1148 // results. We define these "undefined results" to always be 0.
1149 if (shiftAmt == BitWidth)
1150 return APInt(BitWidth, 0);
1151
1152 // Create some space for the result.
1153 uint64_t * val = new uint64_t[getNumWords()];
1154
1155 // If we are shifting less than a word, compute the shift with a simple carry
1156 if (shiftAmt < APINT_BITS_PER_WORD) {
1157 uint64_t carry = 0;
1158 for (int i = getNumWords()-1; i >= 0; --i) {
Reid Spenceraf8fb192007-03-01 05:39:56 +00001159 val[i] = (pVal[i] >> shiftAmt) | carry;
Reid Spencerba81c2b2007-02-26 01:19:48 +00001160 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1161 }
1162 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001163 }
1164
Reid Spencerba81c2b2007-02-26 01:19:48 +00001165 // Compute some values needed by the remaining shift algorithms
1166 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1167 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1168
1169 // If we are shifting whole words, just move whole words
1170 if (wordShift == 0) {
1171 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1172 val[i] = pVal[i+offset];
1173 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1174 val[i] = 0;
1175 return APInt(val,BitWidth).clearUnusedBits();
1176 }
1177
1178 // Shift the low order words
1179 uint32_t breakWord = getNumWords() - offset -1;
1180 for (uint32_t i = 0; i < breakWord; ++i)
Reid Spenceraf8fb192007-03-01 05:39:56 +00001181 val[i] = (pVal[i+offset] >> wordShift) |
1182 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencerba81c2b2007-02-26 01:19:48 +00001183 // Shift the break word.
1184 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1185
1186 // Remaining words are 0
1187 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1188 val[i] = 0;
1189 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001190}
1191
Zhou Shengff4304f2007-02-09 07:48:24 +00001192/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001193/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001194APInt APInt::shl(uint32_t shiftAmt) const {
Reid Spencer5bce8542007-02-24 20:19:37 +00001195 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer87553802007-02-25 00:56:44 +00001196 if (isSingleWord()) {
Reid Spencer5bce8542007-02-24 20:19:37 +00001197 if (shiftAmt == BitWidth)
Reid Spencer87553802007-02-25 00:56:44 +00001198 return APInt(BitWidth, 0); // avoid undefined shift results
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001199 return APInt(BitWidth, VAL << shiftAmt);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001200 }
Reid Spencer5bce8542007-02-24 20:19:37 +00001201
Reid Spencer87553802007-02-25 00:56:44 +00001202 // If all the bits were shifted out, the result is 0. This avoids issues
1203 // with shifting by the size of the integer type, which produces undefined
1204 // results. We define these "undefined results" to always be 0.
1205 if (shiftAmt == BitWidth)
1206 return APInt(BitWidth, 0);
1207
Reid Spencer92c72832007-05-12 18:01:57 +00001208 // If none of the bits are shifted out, the result is *this. This avoids a
1209 // lshr by the words size in the loop below which can produce incorrect
1210 // results. It also avoids the expensive computation below for a common case.
1211 if (shiftAmt == 0)
1212 return *this;
1213
Reid Spencer87553802007-02-25 00:56:44 +00001214 // Create some space for the result.
1215 uint64_t * val = new uint64_t[getNumWords()];
1216
1217 // If we are shifting less than a word, do it the easy way
1218 if (shiftAmt < APINT_BITS_PER_WORD) {
1219 uint64_t carry = 0;
Reid Spencer87553802007-02-25 00:56:44 +00001220 for (uint32_t i = 0; i < getNumWords(); i++) {
1221 val[i] = pVal[i] << shiftAmt | carry;
1222 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1223 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001224 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001225 }
1226
Reid Spencer87553802007-02-25 00:56:44 +00001227 // Compute some values needed by the remaining shift algorithms
1228 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1229 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1230
1231 // If we are shifting whole words, just move whole words
1232 if (wordShift == 0) {
1233 for (uint32_t i = 0; i < offset; i++)
1234 val[i] = 0;
1235 for (uint32_t i = offset; i < getNumWords(); i++)
1236 val[i] = pVal[i-offset];
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001237 return APInt(val,BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001238 }
Reid Spencer87553802007-02-25 00:56:44 +00001239
1240 // Copy whole words from this to Result.
1241 uint32_t i = getNumWords() - 1;
1242 for (; i > offset; --i)
1243 val[i] = pVal[i-offset] << wordShift |
1244 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencer438d71e2007-02-25 01:08:58 +00001245 val[offset] = pVal[0] << wordShift;
Reid Spencer87553802007-02-25 00:56:44 +00001246 for (i = 0; i < offset; ++i)
1247 val[i] = 0;
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001248 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001249}
1250
Reid Spencer19dc32a2007-05-13 23:44:59 +00001251APInt APInt::rotl(uint32_t rotateAmt) const {
Reid Spencer69944e82007-05-14 00:15:28 +00001252 if (rotateAmt == 0)
1253 return *this;
Reid Spencer19dc32a2007-05-13 23:44:59 +00001254 // Don't get too fancy, just use existing shift/or facilities
1255 APInt hi(*this);
1256 APInt lo(*this);
1257 hi.shl(rotateAmt);
1258 lo.lshr(BitWidth - rotateAmt);
1259 return hi | lo;
1260}
1261
1262APInt APInt::rotr(uint32_t rotateAmt) const {
Reid Spencer69944e82007-05-14 00:15:28 +00001263 if (rotateAmt == 0)
1264 return *this;
Reid Spencer19dc32a2007-05-13 23:44:59 +00001265 // Don't get too fancy, just use existing shift/or facilities
1266 APInt hi(*this);
1267 APInt lo(*this);
1268 lo.lshr(rotateAmt);
1269 hi.shl(BitWidth - rotateAmt);
1270 return hi | lo;
1271}
Reid Spenceraf8fb192007-03-01 05:39:56 +00001272
1273// Square Root - this method computes and returns the square root of "this".
1274// Three mechanisms are used for computation. For small values (<= 5 bits),
1275// a table lookup is done. This gets some performance for common cases. For
1276// values using less than 52 bits, the value is converted to double and then
1277// the libc sqrt function is called. The result is rounded and then converted
1278// back to a uint64_t which is then used to construct the result. Finally,
1279// the Babylonian method for computing square roots is used.
1280APInt APInt::sqrt() const {
1281
1282 // Determine the magnitude of the value.
1283 uint32_t magnitude = getActiveBits();
1284
1285 // Use a fast table for some small values. This also gets rid of some
1286 // rounding errors in libc sqrt for small values.
1287 if (magnitude <= 5) {
Reid Spencer4e1e87f2007-03-01 17:47:31 +00001288 static const uint8_t results[32] = {
Reid Spencerb5ca2cd2007-03-01 06:23:32 +00001289 /* 0 */ 0,
1290 /* 1- 2 */ 1, 1,
1291 /* 3- 6 */ 2, 2, 2, 2,
1292 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1293 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1294 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1295 /* 31 */ 6
1296 };
1297 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spenceraf8fb192007-03-01 05:39:56 +00001298 }
1299
1300 // If the magnitude of the value fits in less than 52 bits (the precision of
1301 // an IEEE double precision floating point value), then we can use the
1302 // libc sqrt function which will probably use a hardware sqrt computation.
1303 // This should be faster than the algorithm below.
Jeff Cohenca5183d2007-03-05 00:00:42 +00001304 if (magnitude < 52) {
1305#ifdef _MSC_VER
1306 // Amazingly, VC++ doesn't have round().
1307 return APInt(BitWidth,
1308 uint64_t(::sqrt(double(isSingleWord()?VAL:pVal[0]))) + 0.5);
1309#else
Reid Spenceraf8fb192007-03-01 05:39:56 +00001310 return APInt(BitWidth,
1311 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenca5183d2007-03-05 00:00:42 +00001312#endif
1313 }
Reid Spenceraf8fb192007-03-01 05:39:56 +00001314
1315 // Okay, all the short cuts are exhausted. We must compute it. The following
1316 // is a classical Babylonian method for computing the square root. This code
1317 // was adapted to APINt from a wikipedia article on such computations.
1318 // See http://www.wikipedia.org/ and go to the page named
1319 // Calculate_an_integer_square_root.
1320 uint32_t nbits = BitWidth, i = 4;
1321 APInt testy(BitWidth, 16);
1322 APInt x_old(BitWidth, 1);
1323 APInt x_new(BitWidth, 0);
1324 APInt two(BitWidth, 2);
1325
1326 // Select a good starting value using binary logarithms.
1327 for (;; i += 2, testy = testy.shl(2))
1328 if (i >= nbits || this->ule(testy)) {
1329 x_old = x_old.shl(i / 2);
1330 break;
1331 }
1332
1333 // Use the Babylonian method to arrive at the integer square root:
1334 for (;;) {
1335 x_new = (this->udiv(x_old) + x_old).udiv(two);
1336 if (x_old.ule(x_new))
1337 break;
1338 x_old = x_new;
1339 }
1340
1341 // Make sure we return the closest approximation
Reid Spencerf09aef72007-03-02 04:21:55 +00001342 // NOTE: The rounding calculation below is correct. It will produce an
1343 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
1344 // determined to be a rounding issue with pari/gp as it begins to use a
1345 // floating point representation after 192 bits. There are no discrepancies
1346 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spenceraf8fb192007-03-01 05:39:56 +00001347 APInt square(x_old * x_old);
1348 APInt nextSquare((x_old + 1) * (x_old +1));
1349 if (this->ult(square))
1350 return x_old;
Reid Spencerf09aef72007-03-02 04:21:55 +00001351 else if (this->ule(nextSquare)) {
1352 APInt midpoint((nextSquare - square).udiv(two));
1353 APInt offset(*this - square);
1354 if (offset.ult(midpoint))
Reid Spenceraf8fb192007-03-01 05:39:56 +00001355 return x_old;
Reid Spencerf09aef72007-03-02 04:21:55 +00001356 else
1357 return x_old + 1;
1358 } else
Reid Spenceraf8fb192007-03-01 05:39:56 +00001359 assert(0 && "Error in APInt::sqrt computation");
1360 return x_old + 1;
1361}
1362
Reid Spencer9c0696f2007-02-20 08:51:03 +00001363/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1364/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1365/// variables here have the same names as in the algorithm. Comments explain
1366/// the algorithm and any deviation from it.
1367static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1368 uint32_t m, uint32_t n) {
1369 assert(u && "Must provide dividend");
1370 assert(v && "Must provide divisor");
1371 assert(q && "Must provide quotient");
Reid Spencer9d6c9192007-02-24 03:58:46 +00001372 assert(u != v && u != q && v != q && "Must us different memory");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001373 assert(n>1 && "n must be > 1");
1374
1375 // Knuth uses the value b as the base of the number system. In our case b
1376 // is 2^31 so we just set it to -1u.
1377 uint64_t b = uint64_t(1) << 32;
1378
Reid Spencer9d6c9192007-02-24 03:58:46 +00001379 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1380 DEBUG(cerr << "KnuthDiv: original:");
1381 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1382 DEBUG(cerr << " by");
1383 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1384 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001385 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1386 // u and v by d. Note that we have taken Knuth's advice here to use a power
1387 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1388 // 2 allows us to shift instead of multiply and it is easy to determine the
1389 // shift amount from the leading zeros. We are basically normalizing the u
1390 // and v so that its high bits are shifted to the top of v's range without
1391 // overflow. Note that this can require an extra word in u so that u must
1392 // be of length m+n+1.
1393 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1394 uint32_t v_carry = 0;
1395 uint32_t u_carry = 0;
1396 if (shift) {
1397 for (uint32_t i = 0; i < m+n; ++i) {
1398 uint32_t u_tmp = u[i] >> (32 - shift);
1399 u[i] = (u[i] << shift) | u_carry;
1400 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001401 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001402 for (uint32_t i = 0; i < n; ++i) {
1403 uint32_t v_tmp = v[i] >> (32 - shift);
1404 v[i] = (v[i] << shift) | v_carry;
1405 v_carry = v_tmp;
1406 }
1407 }
1408 u[m+n] = u_carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001409 DEBUG(cerr << "KnuthDiv: normal:");
1410 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1411 DEBUG(cerr << " by");
1412 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1413 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001414
1415 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1416 int j = m;
1417 do {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001418 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001419 // D3. [Calculate q'.].
1420 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1421 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1422 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1423 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1424 // on v[n-2] determines at high speed most of the cases in which the trial
1425 // value qp is one too large, and it eliminates all cases where qp is two
1426 // too large.
Reid Spencer92904632007-02-23 01:57:13 +00001427 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001428 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencer92904632007-02-23 01:57:13 +00001429 uint64_t qp = dividend / v[n-1];
1430 uint64_t rp = dividend % v[n-1];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001431 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1432 qp--;
1433 rp += v[n-1];
Reid Spencer610fad82007-02-24 10:01:42 +00001434 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencer9d6c9192007-02-24 03:58:46 +00001435 qp--;
Reid Spencer92904632007-02-23 01:57:13 +00001436 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001437 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001438
Reid Spencer92904632007-02-23 01:57:13 +00001439 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1440 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1441 // consists of a simple multiplication by a one-place number, combined with
Reid Spencer610fad82007-02-24 10:01:42 +00001442 // a subtraction.
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001443 bool isNeg = false;
Reid Spencer92904632007-02-23 01:57:13 +00001444 for (uint32_t i = 0; i < n; ++i) {
Reid Spencer610fad82007-02-24 10:01:42 +00001445 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001446 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
Reid Spencer610fad82007-02-24 10:01:42 +00001447 bool borrow = subtrahend > u_tmp;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001448 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
Reid Spencer610fad82007-02-24 10:01:42 +00001449 << ", subtrahend == " << subtrahend
1450 << ", borrow = " << borrow << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001451
Reid Spencer610fad82007-02-24 10:01:42 +00001452 uint64_t result = u_tmp - subtrahend;
1453 uint32_t k = j + i;
1454 u[k++] = result & (b-1); // subtract low word
1455 u[k++] = result >> 32; // subtract high word
1456 while (borrow && k <= m+n) { // deal with borrow to the left
1457 borrow = u[k] == 0;
1458 u[k]--;
1459 k++;
1460 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001461 isNeg |= borrow;
Reid Spencer610fad82007-02-24 10:01:42 +00001462 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1463 u[j+i+1] << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001464 }
1465 DEBUG(cerr << "KnuthDiv: after subtraction:");
1466 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1467 DEBUG(cerr << '\n');
Reid Spencer610fad82007-02-24 10:01:42 +00001468 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1469 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1470 // true value plus b**(n+1), namely as the b's complement of
Reid Spencer92904632007-02-23 01:57:13 +00001471 // the true value, and a "borrow" to the left should be remembered.
1472 //
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001473 if (isNeg) {
Reid Spencer610fad82007-02-24 10:01:42 +00001474 bool carry = true; // true because b's complement is "complement + 1"
1475 for (uint32_t i = 0; i <= m+n; ++i) {
1476 u[i] = ~u[i] + carry; // b's complement
1477 carry = carry && u[i] == 0;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001478 }
Reid Spencer92904632007-02-23 01:57:13 +00001479 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001480 DEBUG(cerr << "KnuthDiv: after complement:");
1481 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1482 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001483
1484 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1485 // negative, go to step D6; otherwise go on to step D7.
1486 q[j] = qp;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001487 if (isNeg) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001488 // D6. [Add back]. The probability that this step is necessary is very
1489 // small, on the order of only 2/b. Make sure that test data accounts for
Reid Spencer92904632007-02-23 01:57:13 +00001490 // this possibility. Decrease q[j] by 1
1491 q[j]--;
1492 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1493 // A carry will occur to the left of u[j+n], and it should be ignored
1494 // since it cancels with the borrow that occurred in D4.
1495 bool carry = false;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001496 for (uint32_t i = 0; i < n; i++) {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001497 uint32_t limit = std::min(u[j+i],v[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001498 u[j+i] += v[i] + carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001499 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001500 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001501 u[j+n] += carry;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001502 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001503 DEBUG(cerr << "KnuthDiv: after correction:");
1504 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1505 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001506
Reid Spencer92904632007-02-23 01:57:13 +00001507 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1508 } while (--j >= 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001509
Reid Spencer9d6c9192007-02-24 03:58:46 +00001510 DEBUG(cerr << "KnuthDiv: quotient:");
1511 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1512 DEBUG(cerr << '\n');
1513
Reid Spencer9c0696f2007-02-20 08:51:03 +00001514 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1515 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1516 // compute the remainder (urem uses this).
1517 if (r) {
1518 // The value d is expressed by the "shift" value above since we avoided
1519 // multiplication by d by using a shift left. So, all we have to do is
1520 // shift right here. In order to mak
Reid Spencer1050ec52007-02-24 20:38:01 +00001521 if (shift) {
1522 uint32_t carry = 0;
1523 DEBUG(cerr << "KnuthDiv: remainder:");
1524 for (int i = n-1; i >= 0; i--) {
1525 r[i] = (u[i] >> shift) | carry;
1526 carry = u[i] << (32 - shift);
1527 DEBUG(cerr << " " << r[i]);
1528 }
1529 } else {
1530 for (int i = n-1; i >= 0; i--) {
1531 r[i] = u[i];
1532 DEBUG(cerr << " " << r[i]);
1533 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001534 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001535 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001536 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001537 DEBUG(cerr << std::setbase(10) << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001538}
1539
Reid Spencer9c0696f2007-02-20 08:51:03 +00001540void APInt::divide(const APInt LHS, uint32_t lhsWords,
1541 const APInt &RHS, uint32_t rhsWords,
1542 APInt *Quotient, APInt *Remainder)
1543{
1544 assert(lhsWords >= rhsWords && "Fractional result");
1545
1546 // First, compose the values into an array of 32-bit words instead of
1547 // 64-bit words. This is a necessity of both the "short division" algorithm
1548 // and the the Knuth "classical algorithm" which requires there to be native
1549 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1550 // can't use 64-bit operands here because we don't have native results of
1551 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1552 // work on large-endian machines.
1553 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1554 uint32_t n = rhsWords * 2;
1555 uint32_t m = (lhsWords * 2) - n;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001556
1557 // Allocate space for the temporary values we need either on the stack, if
1558 // it will fit, or on the heap if it won't.
1559 uint32_t SPACE[128];
1560 uint32_t *U = 0;
1561 uint32_t *V = 0;
1562 uint32_t *Q = 0;
1563 uint32_t *R = 0;
1564 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1565 U = &SPACE[0];
1566 V = &SPACE[m+n+1];
1567 Q = &SPACE[(m+n+1) + n];
1568 if (Remainder)
1569 R = &SPACE[(m+n+1) + n + (m+n)];
1570 } else {
1571 U = new uint32_t[m + n + 1];
1572 V = new uint32_t[n];
1573 Q = new uint32_t[m+n];
1574 if (Remainder)
1575 R = new uint32_t[n];
1576 }
1577
1578 // Initialize the dividend
Reid Spencer9c0696f2007-02-20 08:51:03 +00001579 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1580 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001581 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001582 U[i * 2] = tmp & mask;
1583 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1584 }
1585 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1586
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001587 // Initialize the divisor
Reid Spencer9c0696f2007-02-20 08:51:03 +00001588 memset(V, 0, (n)*sizeof(uint32_t));
1589 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001590 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001591 V[i * 2] = tmp & mask;
1592 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1593 }
1594
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001595 // initialize the quotient and remainder
Reid Spencer9c0696f2007-02-20 08:51:03 +00001596 memset(Q, 0, (m+n) * sizeof(uint32_t));
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001597 if (Remainder)
Reid Spencer9c0696f2007-02-20 08:51:03 +00001598 memset(R, 0, n * sizeof(uint32_t));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001599
1600 // Now, adjust m and n for the Knuth division. n is the number of words in
1601 // the divisor. m is the number of words by which the dividend exceeds the
1602 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1603 // contain any zero words or the Knuth algorithm fails.
1604 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1605 n--;
1606 m++;
1607 }
1608 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1609 m--;
1610
1611 // If we're left with only a single word for the divisor, Knuth doesn't work
1612 // so we implement the short division algorithm here. This is much simpler
1613 // and faster because we are certain that we can divide a 64-bit quantity
1614 // by a 32-bit quantity at hardware speed and short division is simply a
1615 // series of such operations. This is just like doing short division but we
1616 // are using base 2^32 instead of base 10.
1617 assert(n != 0 && "Divide by zero?");
1618 if (n == 1) {
1619 uint32_t divisor = V[0];
1620 uint32_t remainder = 0;
1621 for (int i = m+n-1; i >= 0; i--) {
1622 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1623 if (partial_dividend == 0) {
1624 Q[i] = 0;
1625 remainder = 0;
1626 } else if (partial_dividend < divisor) {
1627 Q[i] = 0;
1628 remainder = partial_dividend;
1629 } else if (partial_dividend == divisor) {
1630 Q[i] = 1;
1631 remainder = 0;
1632 } else {
1633 Q[i] = partial_dividend / divisor;
1634 remainder = partial_dividend - (Q[i] * divisor);
1635 }
1636 }
1637 if (R)
1638 R[0] = remainder;
1639 } else {
1640 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1641 // case n > 1.
1642 KnuthDiv(U, V, Q, R, m, n);
1643 }
1644
1645 // If the caller wants the quotient
1646 if (Quotient) {
1647 // Set up the Quotient value's memory.
1648 if (Quotient->BitWidth != LHS.BitWidth) {
1649 if (Quotient->isSingleWord())
1650 Quotient->VAL = 0;
1651 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001652 delete [] Quotient->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001653 Quotient->BitWidth = LHS.BitWidth;
1654 if (!Quotient->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001655 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001656 } else
1657 Quotient->clear();
1658
1659 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1660 // order words.
1661 if (lhsWords == 1) {
1662 uint64_t tmp =
1663 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1664 if (Quotient->isSingleWord())
1665 Quotient->VAL = tmp;
1666 else
1667 Quotient->pVal[0] = tmp;
1668 } else {
1669 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1670 for (unsigned i = 0; i < lhsWords; ++i)
1671 Quotient->pVal[i] =
1672 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1673 }
1674 }
1675
1676 // If the caller wants the remainder
1677 if (Remainder) {
1678 // Set up the Remainder value's memory.
1679 if (Remainder->BitWidth != RHS.BitWidth) {
1680 if (Remainder->isSingleWord())
1681 Remainder->VAL = 0;
1682 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001683 delete [] Remainder->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001684 Remainder->BitWidth = RHS.BitWidth;
1685 if (!Remainder->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001686 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001687 } else
1688 Remainder->clear();
1689
1690 // The remainder is in R. Reconstitute the remainder into Remainder's low
1691 // order words.
1692 if (rhsWords == 1) {
1693 uint64_t tmp =
1694 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1695 if (Remainder->isSingleWord())
1696 Remainder->VAL = tmp;
1697 else
1698 Remainder->pVal[0] = tmp;
1699 } else {
1700 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1701 for (unsigned i = 0; i < rhsWords; ++i)
1702 Remainder->pVal[i] =
1703 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1704 }
1705 }
1706
1707 // Clean up the memory we allocated.
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001708 if (U != &SPACE[0]) {
1709 delete [] U;
1710 delete [] V;
1711 delete [] Q;
1712 delete [] R;
1713 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001714}
1715
Reid Spencere81d2da2007-02-16 22:36:51 +00001716APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001717 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001718
1719 // First, deal with the easy case
1720 if (isSingleWord()) {
1721 assert(RHS.VAL != 0 && "Divide by zero?");
1722 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001723 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001724
Reid Spencer71bd08f2007-02-17 02:07:07 +00001725 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001726 uint32_t rhsBits = RHS.getActiveBits();
1727 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001728 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001729 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001730 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001731
1732 // Deal with some degenerate cases
1733 if (!lhsWords)
Reid Spencere0cdd332007-02-21 08:21:52 +00001734 // 0 / X ===> 0
1735 return APInt(BitWidth, 0);
1736 else if (lhsWords < rhsWords || this->ult(RHS)) {
1737 // X / Y ===> 0, iff X < Y
1738 return APInt(BitWidth, 0);
1739 } else if (*this == RHS) {
1740 // X / X ===> 1
1741 return APInt(BitWidth, 1);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001742 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001743 // All high words are zero, just use native divide
Reid Spencere0cdd332007-02-21 08:21:52 +00001744 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001745 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001746
1747 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1748 APInt Quotient(1,0); // to hold result.
1749 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1750 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001751}
1752
Reid Spencere81d2da2007-02-16 22:36:51 +00001753APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001754 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001755 if (isSingleWord()) {
1756 assert(RHS.VAL != 0 && "Remainder by zero?");
1757 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001758 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001759
Reid Spencere0cdd332007-02-21 08:21:52 +00001760 // Get some facts about the LHS
1761 uint32_t lhsBits = getActiveBits();
1762 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001763
1764 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001765 uint32_t rhsBits = RHS.getActiveBits();
1766 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001767 assert(rhsWords && "Performing remainder operation by zero ???");
1768
Reid Spencer71bd08f2007-02-17 02:07:07 +00001769 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001770 if (lhsWords == 0) {
Reid Spencere0cdd332007-02-21 08:21:52 +00001771 // 0 % Y ===> 0
1772 return APInt(BitWidth, 0);
1773 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1774 // X % Y ===> X, iff X < Y
1775 return *this;
1776 } else if (*this == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001777 // X % X == 0;
Reid Spencere0cdd332007-02-21 08:21:52 +00001778 return APInt(BitWidth, 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001779 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001780 // All high words are zero, just use native remainder
Reid Spencere0cdd332007-02-21 08:21:52 +00001781 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001782 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001783
Reid Spencer19dc32a2007-05-13 23:44:59 +00001784 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencer9c0696f2007-02-20 08:51:03 +00001785 APInt Remainder(1,0);
1786 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1787 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001788}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001789
Reid Spencer19dc32a2007-05-13 23:44:59 +00001790void APInt::udivrem(const APInt &LHS, const APInt &RHS,
1791 APInt &Quotient, APInt &Remainder) {
1792 // Get some size facts about the dividend and divisor
1793 uint32_t lhsBits = LHS.getActiveBits();
1794 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1795 uint32_t rhsBits = RHS.getActiveBits();
1796 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1797
1798 // Check the degenerate cases
1799 if (lhsWords == 0) {
1800 Quotient = 0; // 0 / Y ===> 0
1801 Remainder = 0; // 0 % Y ===> 0
1802 return;
1803 }
1804
1805 if (lhsWords < rhsWords || LHS.ult(RHS)) {
1806 Quotient = 0; // X / Y ===> 0, iff X < Y
1807 Remainder = LHS; // X % Y ===> X, iff X < Y
1808 return;
1809 }
1810
1811 if (LHS == RHS) {
1812 Quotient = 1; // X / X ===> 1
1813 Remainder = 0; // X % X ===> 0;
1814 return;
1815 }
1816
1817 if (lhsWords == 1 && rhsWords == 1) {
1818 // There is only one word to consider so use the native versions.
1819 if (LHS.isSingleWord()) {
1820 Quotient = APInt(LHS.getBitWidth(), LHS.VAL / RHS.VAL);
1821 Remainder = APInt(LHS.getBitWidth(), LHS.VAL % RHS.VAL);
1822 } else {
1823 Quotient = APInt(LHS.getBitWidth(), LHS.pVal[0] / RHS.pVal[0]);
1824 Remainder = APInt(LHS.getBitWidth(), LHS.pVal[0] % RHS.pVal[0]);
1825 }
1826 return;
1827 }
1828
1829 // Okay, lets do it the long way
1830 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
1831}
1832
Reid Spencer385f7542007-02-21 03:55:44 +00001833void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001834 uint8_t radix) {
Reid Spencer385f7542007-02-21 03:55:44 +00001835 // Check our assumptions here
Reid Spencer5e0a8512007-02-17 03:16:00 +00001836 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1837 "Radix should be 2, 8, 10, or 16!");
Reid Spencer385f7542007-02-21 03:55:44 +00001838 assert(str && "String is null?");
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001839 bool isNeg = str[0] == '-';
1840 if (isNeg)
Reid Spencer9eec2412007-02-25 23:44:53 +00001841 str++, slen--;
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001842 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
1843 assert((slen*3 <= numbits || radix != 8) && "Insufficient bit width");
1844 assert((slen*4 <= numbits || radix != 16) && "Insufficient bit width");
1845 assert(((slen*64)/22 <= numbits || radix != 10) && "Insufficient bit width");
Reid Spencer385f7542007-02-21 03:55:44 +00001846
1847 // Allocate memory
1848 if (!isSingleWord())
1849 pVal = getClearedMemory(getNumWords());
1850
1851 // Figure out if we can shift instead of multiply
1852 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1853
1854 // Set up an APInt for the digit to add outside the loop so we don't
1855 // constantly construct/destruct it.
1856 APInt apdigit(getBitWidth(), 0);
1857 APInt apradix(getBitWidth(), radix);
1858
1859 // Enter digit traversal loop
1860 for (unsigned i = 0; i < slen; i++) {
1861 // Get a digit
1862 uint32_t digit = 0;
1863 char cdigit = str[i];
Reid Spencer6551dcd2007-05-16 19:18:22 +00001864 if (radix == 16) {
1865 if (!isxdigit(cdigit))
1866 assert(0 && "Invalid hex digit in string");
1867 if (isdigit(cdigit))
1868 digit = cdigit - '0';
1869 else if (cdigit >= 'a')
Reid Spencer385f7542007-02-21 03:55:44 +00001870 digit = cdigit - 'a' + 10;
1871 else if (cdigit >= 'A')
1872 digit = cdigit - 'A' + 10;
1873 else
Reid Spencer6551dcd2007-05-16 19:18:22 +00001874 assert(0 && "huh? we shouldn't get here");
1875 } else if (isdigit(cdigit)) {
1876 digit = cdigit - '0';
1877 } else {
Reid Spencer385f7542007-02-21 03:55:44 +00001878 assert(0 && "Invalid character in digit string");
Reid Spencer6551dcd2007-05-16 19:18:22 +00001879 }
Reid Spencer385f7542007-02-21 03:55:44 +00001880
Reid Spencer6551dcd2007-05-16 19:18:22 +00001881 // Shift or multiply the value by the radix
Reid Spencer385f7542007-02-21 03:55:44 +00001882 if (shift)
Reid Spencer6551dcd2007-05-16 19:18:22 +00001883 *this <<= shift;
Reid Spencer385f7542007-02-21 03:55:44 +00001884 else
1885 *this *= apradix;
1886
1887 // Add in the digit we just interpreted
Reid Spencer5bce8542007-02-24 20:19:37 +00001888 if (apdigit.isSingleWord())
1889 apdigit.VAL = digit;
1890 else
1891 apdigit.pVal[0] = digit;
Reid Spencer385f7542007-02-21 03:55:44 +00001892 *this += apdigit;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001893 }
Reid Spencer9eec2412007-02-25 23:44:53 +00001894 // If its negative, put it in two's complement form
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001895 if (isNeg) {
1896 (*this)--;
Reid Spencer9eec2412007-02-25 23:44:53 +00001897 this->flip();
Reid Spencer9eec2412007-02-25 23:44:53 +00001898 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001899}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001900
Reid Spencer9c0696f2007-02-20 08:51:03 +00001901std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1902 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1903 "Radix should be 2, 8, 10, or 16!");
1904 static const char *digits[] = {
1905 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1906 };
1907 std::string result;
1908 uint32_t bits_used = getActiveBits();
1909 if (isSingleWord()) {
1910 char buf[65];
1911 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1912 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1913 if (format) {
1914 if (wantSigned) {
1915 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1916 (APINT_BITS_PER_WORD-BitWidth);
1917 sprintf(buf, format, sextVal);
1918 } else
1919 sprintf(buf, format, VAL);
1920 } else {
1921 memset(buf, 0, 65);
1922 uint64_t v = VAL;
1923 while (bits_used) {
1924 uint32_t bit = v & 1;
1925 bits_used--;
1926 buf[bits_used] = digits[bit][0];
1927 v >>=1;
1928 }
1929 }
1930 result = buf;
1931 return result;
1932 }
1933
1934 if (radix != 10) {
1935 uint64_t mask = radix - 1;
1936 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1937 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1938 for (uint32_t i = 0; i < getNumWords(); ++i) {
1939 uint64_t value = pVal[i];
1940 for (uint32_t j = 0; j < nibbles; ++j) {
1941 result.insert(0, digits[ value & mask ]);
1942 value >>= shift;
1943 }
1944 }
1945 return result;
1946 }
1947
1948 APInt tmp(*this);
1949 APInt divisor(4, radix);
1950 APInt zero(tmp.getBitWidth(), 0);
1951 size_t insert_at = 0;
1952 if (wantSigned && tmp[BitWidth-1]) {
1953 // They want to print the signed version and it is a negative value
1954 // Flip the bits and add one to turn it into the equivalent positive
1955 // value and put a '-' in the result.
1956 tmp.flip();
1957 tmp++;
1958 result = "-";
1959 insert_at = 1;
1960 }
Reid Spencere549c492007-02-21 00:29:48 +00001961 if (tmp == APInt(tmp.getBitWidth(), 0))
Reid Spencer9c0696f2007-02-20 08:51:03 +00001962 result = "0";
1963 else while (tmp.ne(zero)) {
1964 APInt APdigit(1,0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001965 APInt tmp2(tmp.getBitWidth(), 0);
Reid Spencer385f7542007-02-21 03:55:44 +00001966 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1967 &APdigit);
Reid Spencer794f4722007-02-26 21:02:27 +00001968 uint32_t digit = APdigit.getZExtValue();
Reid Spencer385f7542007-02-21 03:55:44 +00001969 assert(digit < radix && "divide failed");
1970 result.insert(insert_at,digits[digit]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001971 tmp = tmp2;
1972 }
1973
1974 return result;
1975}
1976
Reid Spencer385f7542007-02-21 03:55:44 +00001977#ifndef NDEBUG
1978void APInt::dump() const
1979{
Reid Spencer610fad82007-02-24 10:01:42 +00001980 cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
Reid Spencer385f7542007-02-21 03:55:44 +00001981 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +00001982 cerr << VAL;
Reid Spencer385f7542007-02-21 03:55:44 +00001983 else for (unsigned i = getNumWords(); i > 0; i--) {
Reid Spencer610fad82007-02-24 10:01:42 +00001984 cerr << pVal[i-1] << " ";
Reid Spencer385f7542007-02-21 03:55:44 +00001985 }
Reid Spencer681dcd12007-02-27 21:59:26 +00001986 cerr << " U(" << this->toString(10) << ") S(" << this->toStringSigned(10)
1987 << ")\n" << std::setbase(10);
Reid Spencer385f7542007-02-21 03:55:44 +00001988}
1989#endif