blob: 63bde6c426274aeb1808b5e826caa8022eaa53b8 [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#include <iomanip>
Reid Spencer385f7542007-02-21 03:55:44 +000025
Zhou Shengfd43dcf2007-02-06 03:00:16 +000026using namespace llvm;
27
Reid Spencer5d0d05c2007-02-25 19:32:03 +000028/// A utility function for allocating memory, checking for allocation failures,
29/// and ensuring the contents are zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000030inline static uint64_t* getClearedMemory(uint32_t numWords) {
31 uint64_t * result = new uint64_t[numWords];
32 assert(result && "APInt memory allocation fails!");
33 memset(result, 0, numWords * sizeof(uint64_t));
34 return result;
Zhou Sheng353815d2007-02-06 06:04:53 +000035}
36
Reid Spencer5d0d05c2007-02-25 19:32:03 +000037/// A utility function for allocating memory and checking for allocation
38/// failure. The content is not zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000039inline static uint64_t* getMemory(uint32_t numWords) {
40 uint64_t * result = new uint64_t[numWords];
41 assert(result && "APInt memory allocation fails!");
42 return result;
43}
44
Reid Spenceradf2a202007-03-19 21:19:02 +000045APInt::APInt(uint32_t numBits, uint64_t val, bool isSigned)
Reid Spencer3a341372007-03-19 20:37:47 +000046 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000047 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
48 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Reid Spencer5d0d05c2007-02-25 19:32:03 +000049 if (isSingleWord())
50 VAL = val;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000051 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000052 pVal = getClearedMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000053 pVal[0] = val;
Reid Spencer3a341372007-03-19 20:37:47 +000054 if (isSigned && int64_t(val) < 0)
55 for (unsigned i = 1; i < getNumWords(); ++i)
56 pVal[i] = -1ULL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000057 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +000058 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000059}
60
Dale Johannesen910993e2007-09-21 22:09:37 +000061APInt::APInt(uint32_t numBits, uint32_t numWords, const uint64_t bigVal[])
Reid Spencer385f7542007-02-21 03:55:44 +000062 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000063 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
64 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000065 assert(bigVal && "Null pointer detected!");
66 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +000067 VAL = bigVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +000068 else {
Reid Spencer610fad82007-02-24 10:01:42 +000069 // Get memory, cleared to 0
70 pVal = getClearedMemory(getNumWords());
71 // Calculate the number of words to copy
72 uint32_t words = std::min<uint32_t>(numWords, getNumWords());
73 // Copy the words from bigVal to pVal
74 memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000075 }
Reid Spencer610fad82007-02-24 10:01:42 +000076 // Make sure unused high bits are cleared
77 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000078}
79
Reid Spenceraf0e9562007-02-18 18:38:44 +000080APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000081 uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000082 : BitWidth(numbits), VAL(0) {
Reid Spencer19dc32a2007-05-13 23:44:59 +000083 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
84 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Reid Spencere81d2da2007-02-16 22:36:51 +000085 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000086}
87
Reid Spencer9c0696f2007-02-20 08:51:03 +000088APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000089 : BitWidth(numbits), VAL(0) {
Reid Spencer19dc32a2007-05-13 23:44:59 +000090 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
91 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shenga3832fd2007-02-07 06:14:53 +000092 assert(!Val.empty() && "String empty?");
Reid Spencere81d2da2007-02-16 22:36:51 +000093 fromString(numbits, Val.c_str(), Val.size(), radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000094}
95
Reid Spencer54362ca2007-02-20 23:40:25 +000096APInt::APInt(const APInt& that)
Reid Spencer385f7542007-02-21 03:55:44 +000097 : BitWidth(that.BitWidth), VAL(0) {
Reid Spencer19dc32a2007-05-13 23:44:59 +000098 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
99 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000100 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000101 VAL = that.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000102 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000103 pVal = getMemory(getNumWords());
Reid Spencer54362ca2007-02-20 23:40:25 +0000104 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000105 }
106}
107
108APInt::~APInt() {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000109 if (!isSingleWord() && pVal)
Reid Spencer9ac44112007-02-26 23:38:21 +0000110 delete [] pVal;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000111}
112
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000113APInt& APInt::operator=(const APInt& RHS) {
Reid Spencer9ac44112007-02-26 23:38:21 +0000114 // Don't do anything for X = X
115 if (this == &RHS)
116 return *this;
117
118 // If the bitwidths are the same, we can avoid mucking with memory
119 if (BitWidth == RHS.getBitWidth()) {
120 if (isSingleWord())
121 VAL = RHS.VAL;
122 else
123 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
124 return *this;
125 }
126
127 if (isSingleWord())
128 if (RHS.isSingleWord())
129 VAL = RHS.VAL;
130 else {
131 VAL = 0;
132 pVal = getMemory(RHS.getNumWords());
133 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
134 }
135 else if (getNumWords() == RHS.getNumWords())
136 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
137 else if (RHS.isSingleWord()) {
138 delete [] pVal;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000139 VAL = RHS.VAL;
Reid Spencer9ac44112007-02-26 23:38:21 +0000140 } else {
141 delete [] pVal;
142 pVal = getMemory(RHS.getNumWords());
143 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
144 }
145 BitWidth = RHS.BitWidth;
146 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000147}
148
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000149APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000150 if (isSingleWord())
151 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000152 else {
153 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000154 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000155 }
Reid Spencer9ac44112007-02-26 23:38:21 +0000156 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000157}
158
Reid Spenceraf0e9562007-02-18 18:38:44 +0000159/// add_1 - This function adds a single "digit" integer, y, to the multiple
160/// "digit" integer array, x[]. x[] is modified to reflect the addition and
161/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000162/// @returns the carry of the addition.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000163static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000164 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000165 dest[i] = y + x[i];
166 if (dest[i] < y)
Reid Spencer610fad82007-02-24 10:01:42 +0000167 y = 1; // Carry one to next digit.
Reid Spencerf2c521c2007-02-18 06:39:42 +0000168 else {
Reid Spencer610fad82007-02-24 10:01:42 +0000169 y = 0; // No need to carry so exit early
Reid Spencerf2c521c2007-02-18 06:39:42 +0000170 break;
171 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000172 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000173 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000174}
175
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000176/// @brief Prefix increment operator. Increments the APInt by one.
177APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000178 if (isSingleWord())
179 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000180 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000181 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000182 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000183}
184
Reid Spenceraf0e9562007-02-18 18:38:44 +0000185/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
186/// the multi-digit integer array, x[], propagating the borrowed 1 value until
187/// no further borrowing is neeeded or it runs out of "digits" in x. The result
188/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
189/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000190/// @returns the borrow out of the subtraction
191static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000192 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000193 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000194 x[i] -= y;
195 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000196 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000197 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000198 y = 0; // No need to borrow
199 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000200 }
201 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000202 return bool(y);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000203}
204
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000205/// @brief Prefix decrement operator. Decrements the APInt by one.
206APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000207 if (isSingleWord())
208 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000209 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000210 sub_1(pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000211 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000212}
213
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000214/// add - This function adds the integer array x to the integer array Y and
215/// places the result in dest.
216/// @returns the carry out from the addition
217/// @brief General addition of 64-bit integer arrays
Reid Spencer9d6c9192007-02-24 03:58:46 +0000218static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
219 uint32_t len) {
220 bool carry = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000221 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer92904632007-02-23 01:57:13 +0000222 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer54362ca2007-02-20 23:40:25 +0000223 dest[i] = x[i] + y[i] + carry;
Reid Spencer60c0a6a2007-02-21 05:44:56 +0000224 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000225 }
226 return carry;
227}
228
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000229/// Adds the RHS APint to this APInt.
230/// @returns this, after addition of RHS.
231/// @brief Addition assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000232APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000233 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000234 if (isSingleWord())
235 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000236 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000237 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000238 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000239 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000240}
241
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000242/// Subtracts the integer array y from the integer array x
243/// @returns returns the borrow out.
244/// @brief Generalized subtraction of 64-bit integer arrays.
Reid Spencer9d6c9192007-02-24 03:58:46 +0000245static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
246 uint32_t len) {
Reid Spencer385f7542007-02-21 03:55:44 +0000247 bool borrow = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000248 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer385f7542007-02-21 03:55:44 +0000249 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
250 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
251 dest[i] = x_tmp - y[i];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000252 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000253 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000254}
255
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000256/// Subtracts the RHS APInt from this APInt
257/// @returns this, after subtraction
258/// @brief Subtraction assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000259APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000260 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000261 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000262 VAL -= RHS.VAL;
263 else
264 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000265 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000266}
267
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000268/// Multiplies an integer array, x by a a uint64_t integer and places the result
269/// into dest.
270/// @returns the carry out of the multiplication.
271/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Reid Spencer610fad82007-02-24 10:01:42 +0000272static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
273 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer5e0a8512007-02-17 03:16:00 +0000274 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000275 uint64_t carry = 0;
276
277 // For each digit of x.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000278 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000279 // Split x into high and low words
280 uint64_t lx = x[i] & 0xffffffffULL;
281 uint64_t hx = x[i] >> 32;
282 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000283 // hasCarry == 0, no carry
284 // hasCarry == 1, has carry
285 // hasCarry == 2, no carry and the calculation result == 0.
286 uint8_t hasCarry = 0;
287 dest[i] = carry + lx * ly;
288 // Determine if the add above introduces carry.
289 hasCarry = (dest[i] < carry) ? 1 : 0;
290 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
291 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
292 // (2^32 - 1) + 2^32 = 2^64.
293 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
294
295 carry += (lx * hy) & 0xffffffffULL;
296 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
297 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
298 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
299 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000300 return carry;
301}
302
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000303/// Multiplies integer array x by integer array y and stores the result into
304/// the integer array dest. Note that dest's size must be >= xlen + ylen.
305/// @brief Generalized multiplicate of integer arrays.
Reid Spencer610fad82007-02-24 10:01:42 +0000306static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[],
307 uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000308 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000309 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000310 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencere0cdd332007-02-21 08:21:52 +0000311 uint64_t carry = 0, lx = 0, hx = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000312 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000313 lx = x[j] & 0xffffffffULL;
314 hx = x[j] >> 32;
315 // hasCarry - A flag to indicate if has carry.
316 // hasCarry == 0, no carry
317 // hasCarry == 1, has carry
318 // hasCarry == 2, no carry and the calculation result == 0.
319 uint8_t hasCarry = 0;
320 uint64_t resul = carry + lx * ly;
321 hasCarry = (resul < carry) ? 1 : 0;
322 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
323 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
324
325 carry += (lx * hy) & 0xffffffffULL;
326 resul = (carry << 32) | (resul & 0xffffffffULL);
327 dest[i+j] += resul;
328 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
329 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
330 ((lx * hy) >> 32) + hx * hy;
331 }
332 dest[i+xlen] = carry;
333 }
334}
335
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000336APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000337 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencere0cdd332007-02-21 08:21:52 +0000338 if (isSingleWord()) {
Reid Spencer61eb1802007-02-20 20:42:10 +0000339 VAL *= RHS.VAL;
Reid Spencere0cdd332007-02-21 08:21:52 +0000340 clearUnusedBits();
341 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000342 }
Reid Spencere0cdd332007-02-21 08:21:52 +0000343
344 // Get some bit facts about LHS and check for zero
345 uint32_t lhsBits = getActiveBits();
346 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
347 if (!lhsWords)
348 // 0 * X ===> 0
349 return *this;
350
351 // Get some bit facts about RHS and check for zero
352 uint32_t rhsBits = RHS.getActiveBits();
353 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
354 if (!rhsWords) {
355 // X * 0 ===> 0
356 clear();
357 return *this;
358 }
359
360 // Allocate space for the result
361 uint32_t destWords = rhsWords + lhsWords;
362 uint64_t *dest = getMemory(destWords);
363
364 // Perform the long multiply
365 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
366
367 // Copy result back into *this
368 clear();
369 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
370 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
371
372 // delete dest array and return
373 delete[] dest;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000374 return *this;
375}
376
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000377APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000378 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000379 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000380 VAL &= RHS.VAL;
381 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000382 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000383 uint32_t numWords = getNumWords();
384 for (uint32_t i = 0; i < numWords; ++i)
385 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000386 return *this;
387}
388
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000389APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000390 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000391 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000392 VAL |= RHS.VAL;
393 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000394 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000395 uint32_t numWords = getNumWords();
396 for (uint32_t i = 0; i < numWords; ++i)
397 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000398 return *this;
399}
400
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000401APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000402 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000403 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000404 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000405 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000406 return *this;
407 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000408 uint32_t numWords = getNumWords();
409 for (uint32_t i = 0; i < numWords; ++i)
410 pVal[i] ^= RHS.pVal[i];
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000411 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000412}
413
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000414APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000415 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000416 if (isSingleWord())
417 return APInt(getBitWidth(), VAL & RHS.VAL);
418
Reid Spenceraf0e9562007-02-18 18:38:44 +0000419 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000420 uint64_t* val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000421 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000422 val[i] = pVal[i] & RHS.pVal[i];
423 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000424}
425
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000426APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000427 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000428 if (isSingleWord())
429 return APInt(getBitWidth(), VAL | RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000430
Reid Spenceraf0e9562007-02-18 18:38:44 +0000431 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000432 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000433 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000434 val[i] = pVal[i] | RHS.pVal[i];
435 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000436}
437
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000438APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000439 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000440 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000441 return APInt(BitWidth, VAL ^ RHS.VAL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000442
Reid Spenceraf0e9562007-02-18 18:38:44 +0000443 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000444 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000445 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000446 val[i] = pVal[i] ^ RHS.pVal[i];
447
448 // 0^0==1 so clear the high bits in case they got set.
449 return APInt(val, getBitWidth()).clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000450}
451
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000452bool APInt::operator !() const {
453 if (isSingleWord())
454 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000455
456 for (uint32_t i = 0; i < getNumWords(); ++i)
457 if (pVal[i])
458 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000459 return true;
460}
461
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000462APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000463 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000464 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000465 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer61eb1802007-02-20 20:42:10 +0000466 APInt Result(*this);
467 Result *= RHS;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000468 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000469}
470
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000471APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000472 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000473 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000474 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000475 APInt Result(BitWidth, 0);
476 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000477 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000478}
479
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000480APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000481 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000482 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000483 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000484 APInt Result(BitWidth, 0);
485 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000486 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000487}
488
Reid Spenceraf0e9562007-02-18 18:38:44 +0000489bool APInt::operator[](uint32_t bitPosition) const {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000490 return (maskBit(bitPosition) &
491 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000492}
493
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000494bool APInt::operator==(const APInt& RHS) const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000495 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
Reid Spencer54362ca2007-02-20 23:40:25 +0000496 if (isSingleWord())
497 return VAL == RHS.VAL;
498
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000499 // Get some facts about the number of bits used in the two operands.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000500 uint32_t n1 = getActiveBits();
501 uint32_t n2 = RHS.getActiveBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000502
503 // If the number of bits isn't the same, they aren't equal
Reid Spencer54362ca2007-02-20 23:40:25 +0000504 if (n1 != n2)
505 return false;
506
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000507 // If the number of bits fits in a word, we only need to compare the low word.
Reid Spencer54362ca2007-02-20 23:40:25 +0000508 if (n1 <= APINT_BITS_PER_WORD)
509 return pVal[0] == RHS.pVal[0];
510
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000511 // Otherwise, compare everything
Reid Spencer54362ca2007-02-20 23:40:25 +0000512 for (int i = whichWord(n1 - 1); i >= 0; --i)
513 if (pVal[i] != RHS.pVal[i])
514 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000515 return true;
516}
517
Zhou Shenga3832fd2007-02-07 06:14:53 +0000518bool APInt::operator==(uint64_t Val) const {
519 if (isSingleWord())
520 return VAL == Val;
Reid Spencer54362ca2007-02-20 23:40:25 +0000521
522 uint32_t n = getActiveBits();
523 if (n <= APINT_BITS_PER_WORD)
524 return pVal[0] == Val;
525 else
526 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000527}
528
Reid Spencere81d2da2007-02-16 22:36:51 +0000529bool APInt::ult(const APInt& RHS) const {
530 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
531 if (isSingleWord())
532 return VAL < RHS.VAL;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000533
534 // Get active bit length of both operands
535 uint32_t n1 = getActiveBits();
536 uint32_t n2 = RHS.getActiveBits();
537
538 // If magnitude of LHS is less than RHS, return true.
539 if (n1 < n2)
540 return true;
541
542 // If magnitude of RHS is greather than LHS, return false.
543 if (n2 < n1)
544 return false;
545
546 // If they bot fit in a word, just compare the low order word
547 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
548 return pVal[0] < RHS.pVal[0];
549
550 // Otherwise, compare all words
Reid Spencer1fa111e2007-02-27 18:23:40 +0000551 uint32_t topWord = whichWord(std::max(n1,n2)-1);
552 for (int i = topWord; i >= 0; --i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000553 if (pVal[i] > RHS.pVal[i])
Reid Spencere81d2da2007-02-16 22:36:51 +0000554 return false;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000555 if (pVal[i] < RHS.pVal[i])
556 return true;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000557 }
558 return false;
559}
560
Reid Spencere81d2da2007-02-16 22:36:51 +0000561bool APInt::slt(const APInt& RHS) const {
562 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000563 if (isSingleWord()) {
564 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
565 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
566 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000567 }
Reid Spencera58f0582007-02-18 20:09:41 +0000568
569 APInt lhs(*this);
Reid Spencer1fa111e2007-02-27 18:23:40 +0000570 APInt rhs(RHS);
571 bool lhsNeg = isNegative();
572 bool rhsNeg = rhs.isNegative();
573 if (lhsNeg) {
574 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000575 lhs.flip();
576 lhs++;
577 }
Reid Spencer1fa111e2007-02-27 18:23:40 +0000578 if (rhsNeg) {
579 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000580 rhs.flip();
581 rhs++;
582 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000583
584 // Now we have unsigned values to compare so do the comparison if necessary
585 // based on the negativeness of the values.
Reid Spencer1fa111e2007-02-27 18:23:40 +0000586 if (lhsNeg)
587 if (rhsNeg)
588 return lhs.ugt(rhs);
Reid Spencera58f0582007-02-18 20:09:41 +0000589 else
590 return true;
Reid Spencer1fa111e2007-02-27 18:23:40 +0000591 else if (rhsNeg)
Reid Spencera58f0582007-02-18 20:09:41 +0000592 return false;
593 else
594 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000595}
596
Reid Spenceraf0e9562007-02-18 18:38:44 +0000597APInt& APInt::set(uint32_t bitPosition) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000598 if (isSingleWord())
599 VAL |= maskBit(bitPosition);
600 else
601 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000602 return *this;
603}
604
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000605APInt& APInt::set() {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000606 if (isSingleWord()) {
607 VAL = -1ULL;
608 return clearUnusedBits();
Zhou Shengb04973e2007-02-15 06:36:31 +0000609 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000610
611 // Set all the bits in all the words.
Zhou Sheng6dbe2332007-03-21 04:34:37 +0000612 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000613 pVal[i] = -1ULL;
614 // Clear the unused ones
615 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000616}
617
618/// Set the given bit to 0 whose position is given as "bitPosition".
619/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000620APInt& APInt::clear(uint32_t bitPosition) {
621 if (isSingleWord())
622 VAL &= ~maskBit(bitPosition);
623 else
624 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000625 return *this;
626}
627
628/// @brief Set every bit to 0.
629APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000630 if (isSingleWord())
631 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000632 else
Reid Spencera58f0582007-02-18 20:09:41 +0000633 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000634 return *this;
635}
636
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000637/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
638/// this APInt.
639APInt APInt::operator~() const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000640 APInt Result(*this);
641 Result.flip();
642 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000643}
644
645/// @brief Toggle every bit to its opposite value.
646APInt& APInt::flip() {
Reid Spencer9eec2412007-02-25 23:44:53 +0000647 if (isSingleWord()) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000648 VAL ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000649 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000650 }
Reid Spencer9eec2412007-02-25 23:44:53 +0000651 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000652 pVal[i] ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000653 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000654}
655
656/// Toggle a given bit to its opposite value whose position is given
657/// as "bitPosition".
658/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000659APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000660 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000661 if ((*this)[bitPosition]) clear(bitPosition);
662 else set(bitPosition);
663 return *this;
664}
665
Reid Spencer57ae4f52007-04-13 19:19:07 +0000666uint32_t APInt::getBitsNeeded(const char* str, uint32_t slen, uint8_t radix) {
667 assert(str != 0 && "Invalid value string");
668 assert(slen > 0 && "Invalid string length");
669
670 // Each computation below needs to know if its negative
671 uint32_t isNegative = str[0] == '-';
672 if (isNegative) {
673 slen--;
674 str++;
675 }
676 // For radixes of power-of-two values, the bits required is accurately and
677 // easily computed
678 if (radix == 2)
679 return slen + isNegative;
680 if (radix == 8)
681 return slen * 3 + isNegative;
682 if (radix == 16)
683 return slen * 4 + isNegative;
684
685 // Otherwise it must be radix == 10, the hard case
686 assert(radix == 10 && "Invalid radix");
687
688 // This is grossly inefficient but accurate. We could probably do something
689 // with a computation of roughly slen*64/20 and then adjust by the value of
690 // the first few digits. But, I'm not sure how accurate that could be.
691
692 // Compute a sufficient number of bits that is always large enough but might
693 // be too large. This avoids the assertion in the constructor.
694 uint32_t sufficient = slen*64/18;
695
696 // Convert to the actual binary value.
697 APInt tmp(sufficient, str, slen, radix);
698
699 // Compute how many bits are required.
Reid Spencer0468ab32007-04-14 00:00:10 +0000700 return isNegative + tmp.logBase2() + 1;
Reid Spencer57ae4f52007-04-13 19:19:07 +0000701}
702
Reid Spencer794f4722007-02-26 21:02:27 +0000703uint64_t APInt::getHashValue() const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000704 // Put the bit width into the low order bits.
705 uint64_t hash = BitWidth;
Reid Spencer794f4722007-02-26 21:02:27 +0000706
707 // Add the sum of the words to the hash.
708 if (isSingleWord())
Reid Spencer9ac44112007-02-26 23:38:21 +0000709 hash += VAL << 6; // clear separation of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000710 else
711 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer9ac44112007-02-26 23:38:21 +0000712 hash += pVal[i] << 6; // clear sepration of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000713 return hash;
714}
715
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000716/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000717APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000718 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000719}
720
721/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000722APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000723 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
724 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000725}
726
Reid Spencere81d2da2007-02-16 22:36:51 +0000727bool APInt::isPowerOf2() const {
728 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
729}
730
Reid Spenceraf0e9562007-02-18 18:38:44 +0000731uint32_t APInt::countLeadingZeros() const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000732 uint32_t Count = 0;
Reid Spencere549c492007-02-21 00:29:48 +0000733 if (isSingleWord())
734 Count = CountLeadingZeros_64(VAL);
735 else {
736 for (uint32_t i = getNumWords(); i > 0u; --i) {
737 if (pVal[i-1] == 0)
738 Count += APINT_BITS_PER_WORD;
739 else {
740 Count += CountLeadingZeros_64(pVal[i-1]);
741 break;
742 }
743 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000744 }
Reid Spencerab2b2c82007-02-22 00:22:00 +0000745 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
746 if (remainder)
747 Count -= APINT_BITS_PER_WORD - remainder;
748 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000749}
750
Reid Spencer681dcd12007-02-27 21:59:26 +0000751static uint32_t countLeadingOnes_64(uint64_t V, uint32_t skip) {
752 uint32_t Count = 0;
753 if (skip)
754 V <<= skip;
755 while (V && (V & (1ULL << 63))) {
756 Count++;
757 V <<= 1;
758 }
759 return Count;
760}
761
762uint32_t APInt::countLeadingOnes() const {
763 if (isSingleWord())
764 return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth);
765
766 uint32_t highWordBits = BitWidth % APINT_BITS_PER_WORD;
767 uint32_t shift = (highWordBits == 0 ? 0 : APINT_BITS_PER_WORD - highWordBits);
768 int i = getNumWords() - 1;
769 uint32_t Count = countLeadingOnes_64(pVal[i], shift);
770 if (Count == highWordBits) {
771 for (i--; i >= 0; --i) {
772 if (pVal[i] == -1ULL)
773 Count += APINT_BITS_PER_WORD;
774 else {
775 Count += countLeadingOnes_64(pVal[i], 0);
776 break;
777 }
778 }
779 }
780 return Count;
781}
782
Reid Spenceraf0e9562007-02-18 18:38:44 +0000783uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000784 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000785 return CountTrailingZeros_64(VAL);
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000786 uint32_t Count = 0;
787 uint32_t i = 0;
788 for (; i < getNumWords() && pVal[i] == 0; ++i)
789 Count += APINT_BITS_PER_WORD;
790 if (i < getNumWords())
791 Count += CountTrailingZeros_64(pVal[i]);
792 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000793}
794
Reid Spenceraf0e9562007-02-18 18:38:44 +0000795uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000796 if (isSingleWord())
797 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000798 uint32_t Count = 0;
799 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000800 Count += CountPopulation_64(pVal[i]);
801 return Count;
802}
803
Reid Spencere81d2da2007-02-16 22:36:51 +0000804APInt APInt::byteSwap() const {
805 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
806 if (BitWidth == 16)
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000807 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Reid Spencere81d2da2007-02-16 22:36:51 +0000808 else if (BitWidth == 32)
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000809 return APInt(BitWidth, ByteSwap_32(uint32_t(VAL)));
Reid Spencere81d2da2007-02-16 22:36:51 +0000810 else if (BitWidth == 48) {
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000811 uint32_t Tmp1 = uint32_t(VAL >> 16);
Zhou Shengb04973e2007-02-15 06:36:31 +0000812 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000813 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengb04973e2007-02-15 06:36:31 +0000814 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000815 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000816 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000817 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000818 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000819 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000820 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000821 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000822 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000823 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
824 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000825 }
826 return Result;
827 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000828}
829
Zhou Sheng0b706b12007-02-08 14:35:19 +0000830APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
831 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000832 APInt A = API1, B = API2;
833 while (!!B) {
834 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000835 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000836 A = T;
837 }
838 return A;
839}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000840
Reid Spencer1fa111e2007-02-27 18:23:40 +0000841APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, uint32_t width) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000842 union {
843 double D;
844 uint64_t I;
845 } T;
846 T.D = Double;
Reid Spencer30f44f32007-02-27 01:28:10 +0000847
848 // Get the sign bit from the highest order bit
Zhou Shengd93f00c2007-02-12 20:02:55 +0000849 bool isNeg = T.I >> 63;
Reid Spencer30f44f32007-02-27 01:28:10 +0000850
851 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd93f00c2007-02-12 20:02:55 +0000852 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer30f44f32007-02-27 01:28:10 +0000853
854 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000855 if (exp < 0)
Reid Spencerff605762007-02-28 01:30:08 +0000856 return APInt(width, 0u);
Reid Spencer30f44f32007-02-27 01:28:10 +0000857
858 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
859 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
860
861 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd93f00c2007-02-12 20:02:55 +0000862 if (exp < 52)
Reid Spencer1fa111e2007-02-27 18:23:40 +0000863 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
864 APInt(width, mantissa >> (52 - exp));
865
866 // If the client didn't provide enough bits for us to shift the mantissa into
867 // then the result is undefined, just return 0
868 if (width <= exp - 52)
869 return APInt(width, 0);
Reid Spencer30f44f32007-02-27 01:28:10 +0000870
871 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer1fa111e2007-02-27 18:23:40 +0000872 APInt Tmp(width, mantissa);
Reid Spencere81d2da2007-02-16 22:36:51 +0000873 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000874 return isNeg ? -Tmp : Tmp;
875}
876
Reid Spencerdb3faa62007-02-13 22:41:58 +0000877/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000878/// The layout for double is as following (IEEE Standard 754):
879/// --------------------------------------
880/// | Sign Exponent Fraction Bias |
881/// |-------------------------------------- |
882/// | 1[63] 11[62-52] 52[51-00] 1023 |
883/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000884double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000885
886 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000887 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
888 if (isSigned) {
889 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
890 return double(sext);
891 } else
892 return double(VAL);
893 }
894
Reid Spencer9c0696f2007-02-20 08:51:03 +0000895 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000896 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000897
898 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000899 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000900
901 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000902 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000903
Reid Spencer9c0696f2007-02-20 08:51:03 +0000904 // The exponent (without bias normalization) is just the number of bits
905 // we are using. Note that the sign bit is gone since we constructed the
906 // absolute value.
907 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000908
Reid Spencer9c0696f2007-02-20 08:51:03 +0000909 // Return infinity for exponent overflow
910 if (exp > 1023) {
911 if (!isSigned || !isNeg)
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000912 return std::numeric_limits<double>::infinity();
Reid Spencer9c0696f2007-02-20 08:51:03 +0000913 else
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000914 return -std::numeric_limits<double>::infinity();
Reid Spencer9c0696f2007-02-20 08:51:03 +0000915 }
916 exp += 1023; // Increment for 1023 bias
917
918 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
919 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000920 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000921 unsigned hiWord = whichWord(n-1);
922 if (hiWord == 0) {
923 mantissa = Tmp.pVal[0];
924 if (n > 52)
925 mantissa >>= n - 52; // shift down, we want the top 52 bits.
926 } else {
927 assert(hiWord > 0 && "huh?");
928 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
929 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
930 mantissa = hibits | lobits;
931 }
932
Zhou Shengd93f00c2007-02-12 20:02:55 +0000933 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000934 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000935 union {
936 double D;
937 uint64_t I;
938 } T;
939 T.I = sign | (exp << 52) | mantissa;
940 return T.D;
941}
942
Reid Spencere81d2da2007-02-16 22:36:51 +0000943// Truncate to new width.
Reid Spencer94900772007-02-28 17:34:32 +0000944APInt &APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000945 assert(width < BitWidth && "Invalid APInt Truncate request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000946 assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
947 uint32_t wordsBefore = getNumWords();
948 BitWidth = width;
949 uint32_t wordsAfter = getNumWords();
950 if (wordsBefore != wordsAfter) {
951 if (wordsAfter == 1) {
952 uint64_t *tmp = pVal;
953 VAL = pVal[0];
Reid Spencer9ac44112007-02-26 23:38:21 +0000954 delete [] tmp;
Reid Spencer9eec2412007-02-25 23:44:53 +0000955 } else {
956 uint64_t *newVal = getClearedMemory(wordsAfter);
957 for (uint32_t i = 0; i < wordsAfter; ++i)
958 newVal[i] = pVal[i];
Reid Spencer9ac44112007-02-26 23:38:21 +0000959 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000960 pVal = newVal;
961 }
962 }
Reid Spencer94900772007-02-28 17:34:32 +0000963 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000964}
965
966// Sign extend to a new width.
Reid Spencer94900772007-02-28 17:34:32 +0000967APInt &APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000968 assert(width > BitWidth && "Invalid APInt SignExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000969 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
Reid Spencer9eec2412007-02-25 23:44:53 +0000970 // If the sign bit isn't set, this is the same as zext.
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000971 if (!isNegative()) {
Reid Spencer9eec2412007-02-25 23:44:53 +0000972 zext(width);
Reid Spencer94900772007-02-28 17:34:32 +0000973 return *this;
Reid Spencer9eec2412007-02-25 23:44:53 +0000974 }
975
976 // The sign bit is set. First, get some facts
977 uint32_t wordsBefore = getNumWords();
978 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
979 BitWidth = width;
980 uint32_t wordsAfter = getNumWords();
981
982 // Mask the high order word appropriately
983 if (wordsBefore == wordsAfter) {
984 uint32_t newWordBits = width % APINT_BITS_PER_WORD;
985 // The extension is contained to the wordsBefore-1th word.
Reid Spencer36184ed2007-03-02 01:19:42 +0000986 uint64_t mask = ~0ULL;
987 if (newWordBits)
988 mask >>= APINT_BITS_PER_WORD - newWordBits;
989 mask <<= wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +0000990 if (wordsBefore == 1)
991 VAL |= mask;
992 else
993 pVal[wordsBefore-1] |= mask;
Reid Spencer295e40a2007-03-01 23:30:25 +0000994 return clearUnusedBits();
Reid Spencer9eec2412007-02-25 23:44:53 +0000995 }
996
Reid Spencerf30b1882007-02-25 23:54:00 +0000997 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +0000998 uint64_t *newVal = getMemory(wordsAfter);
999 if (wordsBefore == 1)
1000 newVal[0] = VAL | mask;
1001 else {
1002 for (uint32_t i = 0; i < wordsBefore; ++i)
1003 newVal[i] = pVal[i];
1004 newVal[wordsBefore-1] |= mask;
1005 }
1006 for (uint32_t i = wordsBefore; i < wordsAfter; i++)
1007 newVal[i] = -1ULL;
1008 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +00001009 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +00001010 pVal = newVal;
Reid Spencer94900772007-02-28 17:34:32 +00001011 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +00001012}
1013
1014// Zero extend to a new width.
Reid Spencer94900772007-02-28 17:34:32 +00001015APInt &APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +00001016 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +00001017 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
1018 uint32_t wordsBefore = getNumWords();
1019 BitWidth = width;
1020 uint32_t wordsAfter = getNumWords();
1021 if (wordsBefore != wordsAfter) {
1022 uint64_t *newVal = getClearedMemory(wordsAfter);
1023 if (wordsBefore == 1)
1024 newVal[0] = VAL;
1025 else
1026 for (uint32_t i = 0; i < wordsBefore; ++i)
1027 newVal[i] = pVal[i];
1028 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +00001029 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +00001030 pVal = newVal;
1031 }
Reid Spencer94900772007-02-28 17:34:32 +00001032 return *this;
Reid Spencere81d2da2007-02-16 22:36:51 +00001033}
1034
Reid Spencer68e23002007-03-01 17:15:32 +00001035APInt &APInt::zextOrTrunc(uint32_t width) {
1036 if (BitWidth < width)
1037 return zext(width);
1038 if (BitWidth > width)
1039 return trunc(width);
1040 return *this;
1041}
1042
1043APInt &APInt::sextOrTrunc(uint32_t width) {
1044 if (BitWidth < width)
1045 return sext(width);
1046 if (BitWidth > width)
1047 return trunc(width);
1048 return *this;
1049}
1050
Zhou Shengff4304f2007-02-09 07:48:24 +00001051/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001052/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001053APInt APInt::ashr(uint32_t shiftAmt) const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001054 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer46f9c942007-03-02 22:39:11 +00001055 // Handle a degenerate case
1056 if (shiftAmt == 0)
1057 return *this;
1058
1059 // Handle single word shifts with built-in ashr
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001060 if (isSingleWord()) {
1061 if (shiftAmt == BitWidth)
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001062 return APInt(BitWidth, 0); // undefined
1063 else {
1064 uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001065 return APInt(BitWidth,
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001066 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1067 }
Zhou Sheng0b706b12007-02-08 14:35:19 +00001068 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001069
Reid Spencer46f9c942007-03-02 22:39:11 +00001070 // If all the bits were shifted out, the result is, technically, undefined.
1071 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1072 // issues in the algorithm below.
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001073 if (shiftAmt == BitWidth) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001074 if (isNegative())
1075 return APInt(BitWidth, -1ULL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001076 else
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001077 return APInt(BitWidth, 0);
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001078 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001079
1080 // Create some space for the result.
1081 uint64_t * val = new uint64_t[getNumWords()];
1082
Reid Spencer46f9c942007-03-02 22:39:11 +00001083 // Compute some values needed by the following shift algorithms
1084 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1085 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1086 uint32_t breakWord = getNumWords() - 1 - offset; // last word affected
1087 uint32_t bitsInWord = whichBit(BitWidth); // how many bits in last word?
1088 if (bitsInWord == 0)
1089 bitsInWord = APINT_BITS_PER_WORD;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001090
1091 // If we are shifting whole words, just move whole words
1092 if (wordShift == 0) {
Reid Spencer46f9c942007-03-02 22:39:11 +00001093 // Move the words containing significant bits
1094 for (uint32_t i = 0; i <= breakWord; ++i)
1095 val[i] = pVal[i+offset]; // move whole word
1096
1097 // Adjust the top significant word for sign bit fill, if negative
1098 if (isNegative())
1099 if (bitsInWord < APINT_BITS_PER_WORD)
1100 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1101 } else {
1102 // Shift the low order words
1103 for (uint32_t i = 0; i < breakWord; ++i) {
1104 // This combines the shifted corresponding word with the low bits from
1105 // the next word (shifted into this word's high bits).
1106 val[i] = (pVal[i+offset] >> wordShift) |
1107 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1108 }
1109
1110 // Shift the break word. In this case there are no bits from the next word
1111 // to include in this word.
1112 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1113
1114 // Deal with sign extenstion in the break word, and possibly the word before
1115 // it.
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001116 if (isNegative()) {
Reid Spencer46f9c942007-03-02 22:39:11 +00001117 if (wordShift > bitsInWord) {
1118 if (breakWord > 0)
1119 val[breakWord-1] |=
1120 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1121 val[breakWord] |= ~0ULL;
1122 } else
1123 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001124 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001125 }
1126
Reid Spencer46f9c942007-03-02 22:39:11 +00001127 // Remaining words are 0 or -1, just assign them.
1128 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001129 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer46f9c942007-03-02 22:39:11 +00001130 val[i] = fillValue;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001131 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001132}
1133
Zhou Shengff4304f2007-02-09 07:48:24 +00001134/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001135/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001136APInt APInt::lshr(uint32_t shiftAmt) const {
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001137 if (isSingleWord()) {
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001138 if (shiftAmt == BitWidth)
1139 return APInt(BitWidth, 0);
1140 else
1141 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001142 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001143
Reid Spencerba81c2b2007-02-26 01:19:48 +00001144 // If all the bits were shifted out, the result is 0. This avoids issues
1145 // with shifting by the size of the integer type, which produces undefined
1146 // results. We define these "undefined results" to always be 0.
1147 if (shiftAmt == BitWidth)
1148 return APInt(BitWidth, 0);
1149
Reid Spencer02ae8b72007-05-17 06:26:29 +00001150 // If none of the bits are shifted out, the result is *this. This avoids
1151 // issues with shifting byt he size of the integer type, which produces
1152 // undefined results in the code below. This is also an optimization.
1153 if (shiftAmt == 0)
1154 return *this;
1155
Reid Spencerba81c2b2007-02-26 01:19:48 +00001156 // Create some space for the result.
1157 uint64_t * val = new uint64_t[getNumWords()];
1158
1159 // If we are shifting less than a word, compute the shift with a simple carry
1160 if (shiftAmt < APINT_BITS_PER_WORD) {
1161 uint64_t carry = 0;
1162 for (int i = getNumWords()-1; i >= 0; --i) {
Reid Spenceraf8fb192007-03-01 05:39:56 +00001163 val[i] = (pVal[i] >> shiftAmt) | carry;
Reid Spencerba81c2b2007-02-26 01:19:48 +00001164 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1165 }
1166 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001167 }
1168
Reid Spencerba81c2b2007-02-26 01:19:48 +00001169 // Compute some values needed by the remaining shift algorithms
1170 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1171 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1172
1173 // If we are shifting whole words, just move whole words
1174 if (wordShift == 0) {
1175 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1176 val[i] = pVal[i+offset];
1177 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1178 val[i] = 0;
1179 return APInt(val,BitWidth).clearUnusedBits();
1180 }
1181
1182 // Shift the low order words
1183 uint32_t breakWord = getNumWords() - offset -1;
1184 for (uint32_t i = 0; i < breakWord; ++i)
Reid Spenceraf8fb192007-03-01 05:39:56 +00001185 val[i] = (pVal[i+offset] >> wordShift) |
1186 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencerba81c2b2007-02-26 01:19:48 +00001187 // Shift the break word.
1188 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1189
1190 // Remaining words are 0
1191 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1192 val[i] = 0;
1193 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001194}
1195
Zhou Shengff4304f2007-02-09 07:48:24 +00001196/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001197/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001198APInt APInt::shl(uint32_t shiftAmt) const {
Reid Spencer5bce8542007-02-24 20:19:37 +00001199 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer87553802007-02-25 00:56:44 +00001200 if (isSingleWord()) {
Reid Spencer5bce8542007-02-24 20:19:37 +00001201 if (shiftAmt == BitWidth)
Reid Spencer87553802007-02-25 00:56:44 +00001202 return APInt(BitWidth, 0); // avoid undefined shift results
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001203 return APInt(BitWidth, VAL << shiftAmt);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001204 }
Reid Spencer5bce8542007-02-24 20:19:37 +00001205
Reid Spencer87553802007-02-25 00:56:44 +00001206 // If all the bits were shifted out, the result is 0. This avoids issues
1207 // with shifting by the size of the integer type, which produces undefined
1208 // results. We define these "undefined results" to always be 0.
1209 if (shiftAmt == BitWidth)
1210 return APInt(BitWidth, 0);
1211
Reid Spencer92c72832007-05-12 18:01:57 +00001212 // If none of the bits are shifted out, the result is *this. This avoids a
1213 // lshr by the words size in the loop below which can produce incorrect
1214 // results. It also avoids the expensive computation below for a common case.
1215 if (shiftAmt == 0)
1216 return *this;
1217
Reid Spencer87553802007-02-25 00:56:44 +00001218 // Create some space for the result.
1219 uint64_t * val = new uint64_t[getNumWords()];
1220
1221 // If we are shifting less than a word, do it the easy way
1222 if (shiftAmt < APINT_BITS_PER_WORD) {
1223 uint64_t carry = 0;
Reid Spencer87553802007-02-25 00:56:44 +00001224 for (uint32_t i = 0; i < getNumWords(); i++) {
1225 val[i] = pVal[i] << shiftAmt | carry;
1226 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1227 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001228 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001229 }
1230
Reid Spencer87553802007-02-25 00:56:44 +00001231 // Compute some values needed by the remaining shift algorithms
1232 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1233 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1234
1235 // If we are shifting whole words, just move whole words
1236 if (wordShift == 0) {
1237 for (uint32_t i = 0; i < offset; i++)
1238 val[i] = 0;
1239 for (uint32_t i = offset; i < getNumWords(); i++)
1240 val[i] = pVal[i-offset];
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001241 return APInt(val,BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001242 }
Reid Spencer87553802007-02-25 00:56:44 +00001243
1244 // Copy whole words from this to Result.
1245 uint32_t i = getNumWords() - 1;
1246 for (; i > offset; --i)
1247 val[i] = pVal[i-offset] << wordShift |
1248 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencer438d71e2007-02-25 01:08:58 +00001249 val[offset] = pVal[0] << wordShift;
Reid Spencer87553802007-02-25 00:56:44 +00001250 for (i = 0; i < offset; ++i)
1251 val[i] = 0;
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001252 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001253}
1254
Reid Spencer19dc32a2007-05-13 23:44:59 +00001255APInt APInt::rotl(uint32_t rotateAmt) const {
Reid Spencer69944e82007-05-14 00:15:28 +00001256 if (rotateAmt == 0)
1257 return *this;
Reid Spencer19dc32a2007-05-13 23:44:59 +00001258 // Don't get too fancy, just use existing shift/or facilities
1259 APInt hi(*this);
1260 APInt lo(*this);
1261 hi.shl(rotateAmt);
1262 lo.lshr(BitWidth - rotateAmt);
1263 return hi | lo;
1264}
1265
1266APInt APInt::rotr(uint32_t rotateAmt) const {
Reid Spencer69944e82007-05-14 00:15:28 +00001267 if (rotateAmt == 0)
1268 return *this;
Reid Spencer19dc32a2007-05-13 23:44:59 +00001269 // Don't get too fancy, just use existing shift/or facilities
1270 APInt hi(*this);
1271 APInt lo(*this);
1272 lo.lshr(rotateAmt);
1273 hi.shl(BitWidth - rotateAmt);
1274 return hi | lo;
1275}
Reid Spenceraf8fb192007-03-01 05:39:56 +00001276
1277// Square Root - this method computes and returns the square root of "this".
1278// Three mechanisms are used for computation. For small values (<= 5 bits),
1279// a table lookup is done. This gets some performance for common cases. For
1280// values using less than 52 bits, the value is converted to double and then
1281// the libc sqrt function is called. The result is rounded and then converted
1282// back to a uint64_t which is then used to construct the result. Finally,
1283// the Babylonian method for computing square roots is used.
1284APInt APInt::sqrt() const {
1285
1286 // Determine the magnitude of the value.
1287 uint32_t magnitude = getActiveBits();
1288
1289 // Use a fast table for some small values. This also gets rid of some
1290 // rounding errors in libc sqrt for small values.
1291 if (magnitude <= 5) {
Reid Spencer4e1e87f2007-03-01 17:47:31 +00001292 static const uint8_t results[32] = {
Reid Spencerb5ca2cd2007-03-01 06:23:32 +00001293 /* 0 */ 0,
1294 /* 1- 2 */ 1, 1,
1295 /* 3- 6 */ 2, 2, 2, 2,
1296 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1297 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1298 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1299 /* 31 */ 6
1300 };
1301 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spenceraf8fb192007-03-01 05:39:56 +00001302 }
1303
1304 // If the magnitude of the value fits in less than 52 bits (the precision of
1305 // an IEEE double precision floating point value), then we can use the
1306 // libc sqrt function which will probably use a hardware sqrt computation.
1307 // This should be faster than the algorithm below.
Jeff Cohenca5183d2007-03-05 00:00:42 +00001308 if (magnitude < 52) {
1309#ifdef _MSC_VER
1310 // Amazingly, VC++ doesn't have round().
1311 return APInt(BitWidth,
1312 uint64_t(::sqrt(double(isSingleWord()?VAL:pVal[0]))) + 0.5);
1313#else
Reid Spenceraf8fb192007-03-01 05:39:56 +00001314 return APInt(BitWidth,
1315 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenca5183d2007-03-05 00:00:42 +00001316#endif
1317 }
Reid Spenceraf8fb192007-03-01 05:39:56 +00001318
1319 // Okay, all the short cuts are exhausted. We must compute it. The following
1320 // is a classical Babylonian method for computing the square root. This code
1321 // was adapted to APINt from a wikipedia article on such computations.
1322 // See http://www.wikipedia.org/ and go to the page named
1323 // Calculate_an_integer_square_root.
1324 uint32_t nbits = BitWidth, i = 4;
1325 APInt testy(BitWidth, 16);
1326 APInt x_old(BitWidth, 1);
1327 APInt x_new(BitWidth, 0);
1328 APInt two(BitWidth, 2);
1329
1330 // Select a good starting value using binary logarithms.
1331 for (;; i += 2, testy = testy.shl(2))
1332 if (i >= nbits || this->ule(testy)) {
1333 x_old = x_old.shl(i / 2);
1334 break;
1335 }
1336
1337 // Use the Babylonian method to arrive at the integer square root:
1338 for (;;) {
1339 x_new = (this->udiv(x_old) + x_old).udiv(two);
1340 if (x_old.ule(x_new))
1341 break;
1342 x_old = x_new;
1343 }
1344
1345 // Make sure we return the closest approximation
Reid Spencerf09aef72007-03-02 04:21:55 +00001346 // NOTE: The rounding calculation below is correct. It will produce an
1347 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
1348 // determined to be a rounding issue with pari/gp as it begins to use a
1349 // floating point representation after 192 bits. There are no discrepancies
1350 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spenceraf8fb192007-03-01 05:39:56 +00001351 APInt square(x_old * x_old);
1352 APInt nextSquare((x_old + 1) * (x_old +1));
1353 if (this->ult(square))
1354 return x_old;
Reid Spencerf09aef72007-03-02 04:21:55 +00001355 else if (this->ule(nextSquare)) {
1356 APInt midpoint((nextSquare - square).udiv(two));
1357 APInt offset(*this - square);
1358 if (offset.ult(midpoint))
Reid Spenceraf8fb192007-03-01 05:39:56 +00001359 return x_old;
Reid Spencerf09aef72007-03-02 04:21:55 +00001360 else
1361 return x_old + 1;
1362 } else
Reid Spenceraf8fb192007-03-01 05:39:56 +00001363 assert(0 && "Error in APInt::sqrt computation");
1364 return x_old + 1;
1365}
1366
Reid Spencer9c0696f2007-02-20 08:51:03 +00001367/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1368/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1369/// variables here have the same names as in the algorithm. Comments explain
1370/// the algorithm and any deviation from it.
1371static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1372 uint32_t m, uint32_t n) {
1373 assert(u && "Must provide dividend");
1374 assert(v && "Must provide divisor");
1375 assert(q && "Must provide quotient");
Reid Spencer9d6c9192007-02-24 03:58:46 +00001376 assert(u != v && u != q && v != q && "Must us different memory");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001377 assert(n>1 && "n must be > 1");
1378
1379 // Knuth uses the value b as the base of the number system. In our case b
1380 // is 2^31 so we just set it to -1u.
1381 uint64_t b = uint64_t(1) << 32;
1382
Reid Spencer9d6c9192007-02-24 03:58:46 +00001383 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1384 DEBUG(cerr << "KnuthDiv: original:");
1385 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1386 DEBUG(cerr << " by");
1387 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1388 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001389 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1390 // u and v by d. Note that we have taken Knuth's advice here to use a power
1391 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1392 // 2 allows us to shift instead of multiply and it is easy to determine the
1393 // shift amount from the leading zeros. We are basically normalizing the u
1394 // and v so that its high bits are shifted to the top of v's range without
1395 // overflow. Note that this can require an extra word in u so that u must
1396 // be of length m+n+1.
1397 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1398 uint32_t v_carry = 0;
1399 uint32_t u_carry = 0;
1400 if (shift) {
1401 for (uint32_t i = 0; i < m+n; ++i) {
1402 uint32_t u_tmp = u[i] >> (32 - shift);
1403 u[i] = (u[i] << shift) | u_carry;
1404 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001405 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001406 for (uint32_t i = 0; i < n; ++i) {
1407 uint32_t v_tmp = v[i] >> (32 - shift);
1408 v[i] = (v[i] << shift) | v_carry;
1409 v_carry = v_tmp;
1410 }
1411 }
1412 u[m+n] = u_carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001413 DEBUG(cerr << "KnuthDiv: normal:");
1414 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1415 DEBUG(cerr << " by");
1416 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1417 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001418
1419 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1420 int j = m;
1421 do {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001422 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001423 // D3. [Calculate q'.].
1424 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1425 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1426 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1427 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1428 // on v[n-2] determines at high speed most of the cases in which the trial
1429 // value qp is one too large, and it eliminates all cases where qp is two
1430 // too large.
Reid Spencer92904632007-02-23 01:57:13 +00001431 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001432 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencer92904632007-02-23 01:57:13 +00001433 uint64_t qp = dividend / v[n-1];
1434 uint64_t rp = dividend % v[n-1];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001435 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1436 qp--;
1437 rp += v[n-1];
Reid Spencer610fad82007-02-24 10:01:42 +00001438 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencer9d6c9192007-02-24 03:58:46 +00001439 qp--;
Reid Spencer92904632007-02-23 01:57:13 +00001440 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001441 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001442
Reid Spencer92904632007-02-23 01:57:13 +00001443 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1444 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1445 // consists of a simple multiplication by a one-place number, combined with
Reid Spencer610fad82007-02-24 10:01:42 +00001446 // a subtraction.
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001447 bool isNeg = false;
Reid Spencer92904632007-02-23 01:57:13 +00001448 for (uint32_t i = 0; i < n; ++i) {
Reid Spencer610fad82007-02-24 10:01:42 +00001449 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001450 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
Reid Spencer610fad82007-02-24 10:01:42 +00001451 bool borrow = subtrahend > u_tmp;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001452 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
Reid Spencer610fad82007-02-24 10:01:42 +00001453 << ", subtrahend == " << subtrahend
1454 << ", borrow = " << borrow << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001455
Reid Spencer610fad82007-02-24 10:01:42 +00001456 uint64_t result = u_tmp - subtrahend;
1457 uint32_t k = j + i;
1458 u[k++] = result & (b-1); // subtract low word
1459 u[k++] = result >> 32; // subtract high word
1460 while (borrow && k <= m+n) { // deal with borrow to the left
1461 borrow = u[k] == 0;
1462 u[k]--;
1463 k++;
1464 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001465 isNeg |= borrow;
Reid Spencer610fad82007-02-24 10:01:42 +00001466 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1467 u[j+i+1] << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001468 }
1469 DEBUG(cerr << "KnuthDiv: after subtraction:");
1470 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1471 DEBUG(cerr << '\n');
Reid Spencer610fad82007-02-24 10:01:42 +00001472 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1473 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1474 // true value plus b**(n+1), namely as the b's complement of
Reid Spencer92904632007-02-23 01:57:13 +00001475 // the true value, and a "borrow" to the left should be remembered.
1476 //
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001477 if (isNeg) {
Reid Spencer610fad82007-02-24 10:01:42 +00001478 bool carry = true; // true because b's complement is "complement + 1"
1479 for (uint32_t i = 0; i <= m+n; ++i) {
1480 u[i] = ~u[i] + carry; // b's complement
1481 carry = carry && u[i] == 0;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001482 }
Reid Spencer92904632007-02-23 01:57:13 +00001483 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001484 DEBUG(cerr << "KnuthDiv: after complement:");
1485 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1486 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001487
1488 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1489 // negative, go to step D6; otherwise go on to step D7.
1490 q[j] = qp;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001491 if (isNeg) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001492 // D6. [Add back]. The probability that this step is necessary is very
1493 // small, on the order of only 2/b. Make sure that test data accounts for
Reid Spencer92904632007-02-23 01:57:13 +00001494 // this possibility. Decrease q[j] by 1
1495 q[j]--;
1496 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1497 // A carry will occur to the left of u[j+n], and it should be ignored
1498 // since it cancels with the borrow that occurred in D4.
1499 bool carry = false;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001500 for (uint32_t i = 0; i < n; i++) {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001501 uint32_t limit = std::min(u[j+i],v[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001502 u[j+i] += v[i] + carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001503 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001504 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001505 u[j+n] += carry;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001506 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001507 DEBUG(cerr << "KnuthDiv: after correction:");
1508 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1509 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001510
Reid Spencer92904632007-02-23 01:57:13 +00001511 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1512 } while (--j >= 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001513
Reid Spencer9d6c9192007-02-24 03:58:46 +00001514 DEBUG(cerr << "KnuthDiv: quotient:");
1515 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1516 DEBUG(cerr << '\n');
1517
Reid Spencer9c0696f2007-02-20 08:51:03 +00001518 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1519 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1520 // compute the remainder (urem uses this).
1521 if (r) {
1522 // The value d is expressed by the "shift" value above since we avoided
1523 // multiplication by d by using a shift left. So, all we have to do is
1524 // shift right here. In order to mak
Reid Spencer1050ec52007-02-24 20:38:01 +00001525 if (shift) {
1526 uint32_t carry = 0;
1527 DEBUG(cerr << "KnuthDiv: remainder:");
1528 for (int i = n-1; i >= 0; i--) {
1529 r[i] = (u[i] >> shift) | carry;
1530 carry = u[i] << (32 - shift);
1531 DEBUG(cerr << " " << r[i]);
1532 }
1533 } else {
1534 for (int i = n-1; i >= 0; i--) {
1535 r[i] = u[i];
1536 DEBUG(cerr << " " << r[i]);
1537 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001538 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001539 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001540 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001541 DEBUG(cerr << std::setbase(10) << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001542}
1543
Reid Spencer9c0696f2007-02-20 08:51:03 +00001544void APInt::divide(const APInt LHS, uint32_t lhsWords,
1545 const APInt &RHS, uint32_t rhsWords,
1546 APInt *Quotient, APInt *Remainder)
1547{
1548 assert(lhsWords >= rhsWords && "Fractional result");
1549
1550 // First, compose the values into an array of 32-bit words instead of
1551 // 64-bit words. This is a necessity of both the "short division" algorithm
1552 // and the the Knuth "classical algorithm" which requires there to be native
1553 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1554 // can't use 64-bit operands here because we don't have native results of
1555 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1556 // work on large-endian machines.
1557 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1558 uint32_t n = rhsWords * 2;
1559 uint32_t m = (lhsWords * 2) - n;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001560
1561 // Allocate space for the temporary values we need either on the stack, if
1562 // it will fit, or on the heap if it won't.
1563 uint32_t SPACE[128];
1564 uint32_t *U = 0;
1565 uint32_t *V = 0;
1566 uint32_t *Q = 0;
1567 uint32_t *R = 0;
1568 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1569 U = &SPACE[0];
1570 V = &SPACE[m+n+1];
1571 Q = &SPACE[(m+n+1) + n];
1572 if (Remainder)
1573 R = &SPACE[(m+n+1) + n + (m+n)];
1574 } else {
1575 U = new uint32_t[m + n + 1];
1576 V = new uint32_t[n];
1577 Q = new uint32_t[m+n];
1578 if (Remainder)
1579 R = new uint32_t[n];
1580 }
1581
1582 // Initialize the dividend
Reid Spencer9c0696f2007-02-20 08:51:03 +00001583 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1584 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001585 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001586 U[i * 2] = tmp & mask;
1587 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1588 }
1589 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1590
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001591 // Initialize the divisor
Reid Spencer9c0696f2007-02-20 08:51:03 +00001592 memset(V, 0, (n)*sizeof(uint32_t));
1593 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001594 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001595 V[i * 2] = tmp & mask;
1596 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1597 }
1598
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001599 // initialize the quotient and remainder
Reid Spencer9c0696f2007-02-20 08:51:03 +00001600 memset(Q, 0, (m+n) * sizeof(uint32_t));
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001601 if (Remainder)
Reid Spencer9c0696f2007-02-20 08:51:03 +00001602 memset(R, 0, n * sizeof(uint32_t));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001603
1604 // Now, adjust m and n for the Knuth division. n is the number of words in
1605 // the divisor. m is the number of words by which the dividend exceeds the
1606 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1607 // contain any zero words or the Knuth algorithm fails.
1608 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1609 n--;
1610 m++;
1611 }
1612 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1613 m--;
1614
1615 // If we're left with only a single word for the divisor, Knuth doesn't work
1616 // so we implement the short division algorithm here. This is much simpler
1617 // and faster because we are certain that we can divide a 64-bit quantity
1618 // by a 32-bit quantity at hardware speed and short division is simply a
1619 // series of such operations. This is just like doing short division but we
1620 // are using base 2^32 instead of base 10.
1621 assert(n != 0 && "Divide by zero?");
1622 if (n == 1) {
1623 uint32_t divisor = V[0];
1624 uint32_t remainder = 0;
1625 for (int i = m+n-1; i >= 0; i--) {
1626 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1627 if (partial_dividend == 0) {
1628 Q[i] = 0;
1629 remainder = 0;
1630 } else if (partial_dividend < divisor) {
1631 Q[i] = 0;
1632 remainder = partial_dividend;
1633 } else if (partial_dividend == divisor) {
1634 Q[i] = 1;
1635 remainder = 0;
1636 } else {
1637 Q[i] = partial_dividend / divisor;
1638 remainder = partial_dividend - (Q[i] * divisor);
1639 }
1640 }
1641 if (R)
1642 R[0] = remainder;
1643 } else {
1644 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1645 // case n > 1.
1646 KnuthDiv(U, V, Q, R, m, n);
1647 }
1648
1649 // If the caller wants the quotient
1650 if (Quotient) {
1651 // Set up the Quotient value's memory.
1652 if (Quotient->BitWidth != LHS.BitWidth) {
1653 if (Quotient->isSingleWord())
1654 Quotient->VAL = 0;
1655 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001656 delete [] Quotient->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001657 Quotient->BitWidth = LHS.BitWidth;
1658 if (!Quotient->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001659 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001660 } else
1661 Quotient->clear();
1662
1663 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1664 // order words.
1665 if (lhsWords == 1) {
1666 uint64_t tmp =
1667 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1668 if (Quotient->isSingleWord())
1669 Quotient->VAL = tmp;
1670 else
1671 Quotient->pVal[0] = tmp;
1672 } else {
1673 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1674 for (unsigned i = 0; i < lhsWords; ++i)
1675 Quotient->pVal[i] =
1676 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1677 }
1678 }
1679
1680 // If the caller wants the remainder
1681 if (Remainder) {
1682 // Set up the Remainder value's memory.
1683 if (Remainder->BitWidth != RHS.BitWidth) {
1684 if (Remainder->isSingleWord())
1685 Remainder->VAL = 0;
1686 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001687 delete [] Remainder->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001688 Remainder->BitWidth = RHS.BitWidth;
1689 if (!Remainder->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001690 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001691 } else
1692 Remainder->clear();
1693
1694 // The remainder is in R. Reconstitute the remainder into Remainder's low
1695 // order words.
1696 if (rhsWords == 1) {
1697 uint64_t tmp =
1698 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1699 if (Remainder->isSingleWord())
1700 Remainder->VAL = tmp;
1701 else
1702 Remainder->pVal[0] = tmp;
1703 } else {
1704 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1705 for (unsigned i = 0; i < rhsWords; ++i)
1706 Remainder->pVal[i] =
1707 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1708 }
1709 }
1710
1711 // Clean up the memory we allocated.
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001712 if (U != &SPACE[0]) {
1713 delete [] U;
1714 delete [] V;
1715 delete [] Q;
1716 delete [] R;
1717 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001718}
1719
Reid Spencere81d2da2007-02-16 22:36:51 +00001720APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001721 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001722
1723 // First, deal with the easy case
1724 if (isSingleWord()) {
1725 assert(RHS.VAL != 0 && "Divide by zero?");
1726 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001727 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001728
Reid Spencer71bd08f2007-02-17 02:07:07 +00001729 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001730 uint32_t rhsBits = RHS.getActiveBits();
1731 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001732 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001733 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001734 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001735
1736 // Deal with some degenerate cases
1737 if (!lhsWords)
Reid Spencere0cdd332007-02-21 08:21:52 +00001738 // 0 / X ===> 0
1739 return APInt(BitWidth, 0);
1740 else if (lhsWords < rhsWords || this->ult(RHS)) {
1741 // X / Y ===> 0, iff X < Y
1742 return APInt(BitWidth, 0);
1743 } else if (*this == RHS) {
1744 // X / X ===> 1
1745 return APInt(BitWidth, 1);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001746 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001747 // All high words are zero, just use native divide
Reid Spencere0cdd332007-02-21 08:21:52 +00001748 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001749 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001750
1751 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1752 APInt Quotient(1,0); // to hold result.
1753 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1754 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001755}
1756
Reid Spencere81d2da2007-02-16 22:36:51 +00001757APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001758 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001759 if (isSingleWord()) {
1760 assert(RHS.VAL != 0 && "Remainder by zero?");
1761 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001762 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001763
Reid Spencere0cdd332007-02-21 08:21:52 +00001764 // Get some facts about the LHS
1765 uint32_t lhsBits = getActiveBits();
1766 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001767
1768 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001769 uint32_t rhsBits = RHS.getActiveBits();
1770 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001771 assert(rhsWords && "Performing remainder operation by zero ???");
1772
Reid Spencer71bd08f2007-02-17 02:07:07 +00001773 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001774 if (lhsWords == 0) {
Reid Spencere0cdd332007-02-21 08:21:52 +00001775 // 0 % Y ===> 0
1776 return APInt(BitWidth, 0);
1777 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1778 // X % Y ===> X, iff X < Y
1779 return *this;
1780 } else if (*this == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001781 // X % X == 0;
Reid Spencere0cdd332007-02-21 08:21:52 +00001782 return APInt(BitWidth, 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001783 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001784 // All high words are zero, just use native remainder
Reid Spencere0cdd332007-02-21 08:21:52 +00001785 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001786 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001787
Reid Spencer19dc32a2007-05-13 23:44:59 +00001788 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencer9c0696f2007-02-20 08:51:03 +00001789 APInt Remainder(1,0);
1790 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1791 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001792}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001793
Reid Spencer19dc32a2007-05-13 23:44:59 +00001794void APInt::udivrem(const APInt &LHS, const APInt &RHS,
1795 APInt &Quotient, APInt &Remainder) {
1796 // Get some size facts about the dividend and divisor
1797 uint32_t lhsBits = LHS.getActiveBits();
1798 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1799 uint32_t rhsBits = RHS.getActiveBits();
1800 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1801
1802 // Check the degenerate cases
1803 if (lhsWords == 0) {
1804 Quotient = 0; // 0 / Y ===> 0
1805 Remainder = 0; // 0 % Y ===> 0
1806 return;
1807 }
1808
1809 if (lhsWords < rhsWords || LHS.ult(RHS)) {
1810 Quotient = 0; // X / Y ===> 0, iff X < Y
1811 Remainder = LHS; // X % Y ===> X, iff X < Y
1812 return;
1813 }
1814
1815 if (LHS == RHS) {
1816 Quotient = 1; // X / X ===> 1
1817 Remainder = 0; // X % X ===> 0;
1818 return;
1819 }
1820
1821 if (lhsWords == 1 && rhsWords == 1) {
1822 // There is only one word to consider so use the native versions.
1823 if (LHS.isSingleWord()) {
1824 Quotient = APInt(LHS.getBitWidth(), LHS.VAL / RHS.VAL);
1825 Remainder = APInt(LHS.getBitWidth(), LHS.VAL % RHS.VAL);
1826 } else {
1827 Quotient = APInt(LHS.getBitWidth(), LHS.pVal[0] / RHS.pVal[0]);
1828 Remainder = APInt(LHS.getBitWidth(), LHS.pVal[0] % RHS.pVal[0]);
1829 }
1830 return;
1831 }
1832
1833 // Okay, lets do it the long way
1834 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
1835}
1836
Reid Spencer385f7542007-02-21 03:55:44 +00001837void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001838 uint8_t radix) {
Reid Spencer385f7542007-02-21 03:55:44 +00001839 // Check our assumptions here
Reid Spencer5e0a8512007-02-17 03:16:00 +00001840 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1841 "Radix should be 2, 8, 10, or 16!");
Reid Spencer385f7542007-02-21 03:55:44 +00001842 assert(str && "String is null?");
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001843 bool isNeg = str[0] == '-';
1844 if (isNeg)
Reid Spencer9eec2412007-02-25 23:44:53 +00001845 str++, slen--;
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001846 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
1847 assert((slen*3 <= numbits || radix != 8) && "Insufficient bit width");
1848 assert((slen*4 <= numbits || radix != 16) && "Insufficient bit width");
1849 assert(((slen*64)/22 <= numbits || radix != 10) && "Insufficient bit width");
Reid Spencer385f7542007-02-21 03:55:44 +00001850
1851 // Allocate memory
1852 if (!isSingleWord())
1853 pVal = getClearedMemory(getNumWords());
1854
1855 // Figure out if we can shift instead of multiply
1856 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1857
1858 // Set up an APInt for the digit to add outside the loop so we don't
1859 // constantly construct/destruct it.
1860 APInt apdigit(getBitWidth(), 0);
1861 APInt apradix(getBitWidth(), radix);
1862
1863 // Enter digit traversal loop
1864 for (unsigned i = 0; i < slen; i++) {
1865 // Get a digit
1866 uint32_t digit = 0;
1867 char cdigit = str[i];
Reid Spencer6551dcd2007-05-16 19:18:22 +00001868 if (radix == 16) {
1869 if (!isxdigit(cdigit))
1870 assert(0 && "Invalid hex digit in string");
1871 if (isdigit(cdigit))
1872 digit = cdigit - '0';
1873 else if (cdigit >= 'a')
Reid Spencer385f7542007-02-21 03:55:44 +00001874 digit = cdigit - 'a' + 10;
1875 else if (cdigit >= 'A')
1876 digit = cdigit - 'A' + 10;
1877 else
Reid Spencer6551dcd2007-05-16 19:18:22 +00001878 assert(0 && "huh? we shouldn't get here");
1879 } else if (isdigit(cdigit)) {
1880 digit = cdigit - '0';
1881 } else {
Reid Spencer385f7542007-02-21 03:55:44 +00001882 assert(0 && "Invalid character in digit string");
Reid Spencer6551dcd2007-05-16 19:18:22 +00001883 }
Reid Spencer385f7542007-02-21 03:55:44 +00001884
Reid Spencer6551dcd2007-05-16 19:18:22 +00001885 // Shift or multiply the value by the radix
Reid Spencer385f7542007-02-21 03:55:44 +00001886 if (shift)
Reid Spencer6551dcd2007-05-16 19:18:22 +00001887 *this <<= shift;
Reid Spencer385f7542007-02-21 03:55:44 +00001888 else
1889 *this *= apradix;
1890
1891 // Add in the digit we just interpreted
Reid Spencer5bce8542007-02-24 20:19:37 +00001892 if (apdigit.isSingleWord())
1893 apdigit.VAL = digit;
1894 else
1895 apdigit.pVal[0] = digit;
Reid Spencer385f7542007-02-21 03:55:44 +00001896 *this += apdigit;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001897 }
Reid Spencer9eec2412007-02-25 23:44:53 +00001898 // If its negative, put it in two's complement form
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001899 if (isNeg) {
1900 (*this)--;
Reid Spencer9eec2412007-02-25 23:44:53 +00001901 this->flip();
Reid Spencer9eec2412007-02-25 23:44:53 +00001902 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001903}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001904
Reid Spencer9c0696f2007-02-20 08:51:03 +00001905std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1906 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1907 "Radix should be 2, 8, 10, or 16!");
1908 static const char *digits[] = {
1909 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1910 };
1911 std::string result;
1912 uint32_t bits_used = getActiveBits();
1913 if (isSingleWord()) {
1914 char buf[65];
1915 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1916 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1917 if (format) {
1918 if (wantSigned) {
1919 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1920 (APINT_BITS_PER_WORD-BitWidth);
1921 sprintf(buf, format, sextVal);
1922 } else
1923 sprintf(buf, format, VAL);
1924 } else {
1925 memset(buf, 0, 65);
1926 uint64_t v = VAL;
1927 while (bits_used) {
1928 uint32_t bit = v & 1;
1929 bits_used--;
1930 buf[bits_used] = digits[bit][0];
1931 v >>=1;
1932 }
1933 }
1934 result = buf;
1935 return result;
1936 }
1937
1938 if (radix != 10) {
Reid Spencerfb0709a2007-05-17 19:23:02 +00001939 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
1940 // because the number of bits per digit (1,3 and 4 respectively) divides
1941 // equaly. We just shift until there value is zero.
1942
1943 // First, check for a zero value and just short circuit the logic below.
1944 if (*this == 0)
1945 result = "0";
1946 else {
1947 APInt tmp(*this);
1948 size_t insert_at = 0;
1949 if (wantSigned && this->isNegative()) {
1950 // They want to print the signed version and it is a negative value
1951 // Flip the bits and add one to turn it into the equivalent positive
1952 // value and put a '-' in the result.
1953 tmp.flip();
1954 tmp++;
1955 result = "-";
1956 insert_at = 1;
1957 }
1958 // Just shift tmp right for each digit width until it becomes zero
1959 uint32_t shift = (radix == 16 ? 4 : (radix == 8 ? 3 : 1));
1960 uint64_t mask = radix - 1;
1961 APInt zero(tmp.getBitWidth(), 0);
1962 while (tmp.ne(zero)) {
Reid Spencer20a4c232007-05-19 00:29:55 +00001963 unsigned digit = (tmp.isSingleWord() ? tmp.VAL : tmp.pVal[0]) & mask;
Reid Spencerfb0709a2007-05-17 19:23:02 +00001964 result.insert(insert_at, digits[digit]);
Reid Spencer20a4c232007-05-19 00:29:55 +00001965 tmp = tmp.lshr(shift);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001966 }
1967 }
1968 return result;
1969 }
1970
1971 APInt tmp(*this);
1972 APInt divisor(4, radix);
1973 APInt zero(tmp.getBitWidth(), 0);
1974 size_t insert_at = 0;
1975 if (wantSigned && tmp[BitWidth-1]) {
1976 // They want to print the signed version and it is a negative value
1977 // Flip the bits and add one to turn it into the equivalent positive
1978 // value and put a '-' in the result.
1979 tmp.flip();
1980 tmp++;
1981 result = "-";
1982 insert_at = 1;
1983 }
Reid Spencere549c492007-02-21 00:29:48 +00001984 if (tmp == APInt(tmp.getBitWidth(), 0))
Reid Spencer9c0696f2007-02-20 08:51:03 +00001985 result = "0";
1986 else while (tmp.ne(zero)) {
1987 APInt APdigit(1,0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001988 APInt tmp2(tmp.getBitWidth(), 0);
Reid Spencer385f7542007-02-21 03:55:44 +00001989 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1990 &APdigit);
Reid Spencer794f4722007-02-26 21:02:27 +00001991 uint32_t digit = APdigit.getZExtValue();
Reid Spencer385f7542007-02-21 03:55:44 +00001992 assert(digit < radix && "divide failed");
1993 result.insert(insert_at,digits[digit]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001994 tmp = tmp2;
1995 }
1996
1997 return result;
1998}
1999
Reid Spencer385f7542007-02-21 03:55:44 +00002000void APInt::dump() const
2001{
Reid Spencer610fad82007-02-24 10:01:42 +00002002 cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
Reid Spencer385f7542007-02-21 03:55:44 +00002003 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +00002004 cerr << VAL;
Reid Spencer385f7542007-02-21 03:55:44 +00002005 else for (unsigned i = getNumWords(); i > 0; i--) {
Reid Spencer610fad82007-02-24 10:01:42 +00002006 cerr << pVal[i-1] << " ";
Reid Spencer385f7542007-02-21 03:55:44 +00002007 }
Chris Lattner9132a2b2007-08-23 05:15:32 +00002008 cerr << " U(" << this->toStringUnsigned(10) << ") S("
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002009 << this->toStringSigned(10) << ")" << std::setbase(10);
Reid Spencer385f7542007-02-21 03:55:44 +00002010}
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002011
2012// This implements a variety of operations on a representation of
2013// arbitrary precision, two's-complement, bignum integer values.
2014
2015/* Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2016 and unrestricting assumption. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002017COMPILE_TIME_ASSERT(integerPartWidth % 2 == 0);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002018
2019/* Some handy functions local to this file. */
2020namespace {
2021
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002022 /* Returns the integer part with the least significant BITS set.
2023 BITS cannot be zero. */
2024 inline integerPart
2025 lowBitMask(unsigned int bits)
2026 {
2027 assert (bits != 0 && bits <= integerPartWidth);
2028
2029 return ~(integerPart) 0 >> (integerPartWidth - bits);
2030 }
2031
2032 /* Returns the value of the lower nibble of PART. */
2033 inline integerPart
2034 lowHalf(integerPart part)
2035 {
2036 return part & lowBitMask(integerPartWidth / 2);
2037 }
2038
2039 /* Returns the value of the upper nibble of PART. */
2040 inline integerPart
2041 highHalf(integerPart part)
2042 {
2043 return part >> (integerPartWidth / 2);
2044 }
2045
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002046 /* Returns the bit number of the most significant bit of a part. If
2047 the input number has no bits set -1U is returned. */
2048 unsigned int
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002049 partMSB(integerPart value)
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002050 {
2051 unsigned int n, msb;
2052
2053 if (value == 0)
2054 return -1U;
2055
2056 n = integerPartWidth / 2;
2057
2058 msb = 0;
2059 do {
2060 if (value >> n) {
2061 value >>= n;
2062 msb += n;
2063 }
2064
2065 n >>= 1;
2066 } while (n);
2067
2068 return msb;
2069 }
2070
2071 /* Returns the bit number of the least significant bit of a part.
2072 If the input number has no bits set -1U is returned. */
2073 unsigned int
2074 partLSB(integerPart value)
2075 {
2076 unsigned int n, lsb;
2077
2078 if (value == 0)
2079 return -1U;
2080
2081 lsb = integerPartWidth - 1;
2082 n = integerPartWidth / 2;
2083
2084 do {
2085 if (value << n) {
2086 value <<= n;
2087 lsb -= n;
2088 }
2089
2090 n >>= 1;
2091 } while (n);
2092
2093 return lsb;
2094 }
2095}
2096
2097/* Sets the least significant part of a bignum to the input value, and
2098 zeroes out higher parts. */
2099void
2100APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts)
2101{
2102 unsigned int i;
2103
2104 dst[0] = part;
2105 for(i = 1; i < parts; i++)
2106 dst[i] = 0;
2107}
2108
2109/* Assign one bignum to another. */
2110void
2111APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts)
2112{
2113 unsigned int i;
2114
2115 for(i = 0; i < parts; i++)
2116 dst[i] = src[i];
2117}
2118
2119/* Returns true if a bignum is zero, false otherwise. */
2120bool
2121APInt::tcIsZero(const integerPart *src, unsigned int parts)
2122{
2123 unsigned int i;
2124
2125 for(i = 0; i < parts; i++)
2126 if (src[i])
2127 return false;
2128
2129 return true;
2130}
2131
2132/* Extract the given bit of a bignum; returns 0 or 1. */
2133int
2134APInt::tcExtractBit(const integerPart *parts, unsigned int bit)
2135{
2136 return(parts[bit / integerPartWidth]
2137 & ((integerPart) 1 << bit % integerPartWidth)) != 0;
2138}
2139
2140/* Set the given bit of a bignum. */
2141void
2142APInt::tcSetBit(integerPart *parts, unsigned int bit)
2143{
2144 parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
2145}
2146
2147/* Returns the bit number of the least significant bit of a number.
2148 If the input number has no bits set -1U is returned. */
2149unsigned int
2150APInt::tcLSB(const integerPart *parts, unsigned int n)
2151{
2152 unsigned int i, lsb;
2153
2154 for(i = 0; i < n; i++) {
2155 if (parts[i] != 0) {
2156 lsb = partLSB(parts[i]);
2157
2158 return lsb + i * integerPartWidth;
2159 }
2160 }
2161
2162 return -1U;
2163}
2164
2165/* Returns the bit number of the most significant bit of a number. If
2166 the input number has no bits set -1U is returned. */
2167unsigned int
2168APInt::tcMSB(const integerPart *parts, unsigned int n)
2169{
2170 unsigned int msb;
2171
2172 do {
2173 --n;
2174
2175 if (parts[n] != 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002176 msb = partMSB(parts[n]);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002177
2178 return msb + n * integerPartWidth;
2179 }
2180 } while (n);
2181
2182 return -1U;
2183}
2184
2185/* DST += RHS + C where C is zero or one. Returns the carry flag. */
2186integerPart
2187APInt::tcAdd(integerPart *dst, const integerPart *rhs,
2188 integerPart c, unsigned int parts)
2189{
2190 unsigned int i;
2191
2192 assert(c <= 1);
2193
2194 for(i = 0; i < parts; i++) {
2195 integerPart l;
2196
2197 l = dst[i];
2198 if (c) {
2199 dst[i] += rhs[i] + 1;
2200 c = (dst[i] <= l);
2201 } else {
2202 dst[i] += rhs[i];
2203 c = (dst[i] < l);
2204 }
2205 }
2206
2207 return c;
2208}
2209
2210/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
2211integerPart
2212APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
2213 integerPart c, unsigned int parts)
2214{
2215 unsigned int i;
2216
2217 assert(c <= 1);
2218
2219 for(i = 0; i < parts; i++) {
2220 integerPart l;
2221
2222 l = dst[i];
2223 if (c) {
2224 dst[i] -= rhs[i] + 1;
2225 c = (dst[i] >= l);
2226 } else {
2227 dst[i] -= rhs[i];
2228 c = (dst[i] > l);
2229 }
2230 }
2231
2232 return c;
2233}
2234
2235/* Negate a bignum in-place. */
2236void
2237APInt::tcNegate(integerPart *dst, unsigned int parts)
2238{
2239 tcComplement(dst, parts);
2240 tcIncrement(dst, parts);
2241}
2242
2243/* DST += SRC * MULTIPLIER + PART if add is true
2244 DST = SRC * MULTIPLIER + PART if add is false
2245
2246 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2247 they must start at the same point, i.e. DST == SRC.
2248
2249 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2250 returned. Otherwise DST is filled with the least significant
2251 DSTPARTS parts of the result, and if all of the omitted higher
2252 parts were zero return zero, otherwise overflow occurred and
2253 return one. */
2254int
2255APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
2256 integerPart multiplier, integerPart carry,
2257 unsigned int srcParts, unsigned int dstParts,
2258 bool add)
2259{
2260 unsigned int i, n;
2261
2262 /* Otherwise our writes of DST kill our later reads of SRC. */
2263 assert(dst <= src || dst >= src + srcParts);
2264 assert(dstParts <= srcParts + 1);
2265
2266 /* N loops; minimum of dstParts and srcParts. */
2267 n = dstParts < srcParts ? dstParts: srcParts;
2268
2269 for(i = 0; i < n; i++) {
2270 integerPart low, mid, high, srcPart;
2271
2272 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2273
2274 This cannot overflow, because
2275
2276 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2277
2278 which is less than n^2. */
2279
2280 srcPart = src[i];
2281
2282 if (multiplier == 0 || srcPart == 0) {
2283 low = carry;
2284 high = 0;
2285 } else {
2286 low = lowHalf(srcPart) * lowHalf(multiplier);
2287 high = highHalf(srcPart) * highHalf(multiplier);
2288
2289 mid = lowHalf(srcPart) * highHalf(multiplier);
2290 high += highHalf(mid);
2291 mid <<= integerPartWidth / 2;
2292 if (low + mid < low)
2293 high++;
2294 low += mid;
2295
2296 mid = highHalf(srcPart) * lowHalf(multiplier);
2297 high += highHalf(mid);
2298 mid <<= integerPartWidth / 2;
2299 if (low + mid < low)
2300 high++;
2301 low += mid;
2302
2303 /* Now add carry. */
2304 if (low + carry < low)
2305 high++;
2306 low += carry;
2307 }
2308
2309 if (add) {
2310 /* And now DST[i], and store the new low part there. */
2311 if (low + dst[i] < low)
2312 high++;
2313 dst[i] += low;
2314 } else
2315 dst[i] = low;
2316
2317 carry = high;
2318 }
2319
2320 if (i < dstParts) {
2321 /* Full multiplication, there is no overflow. */
2322 assert(i + 1 == dstParts);
2323 dst[i] = carry;
2324 return 0;
2325 } else {
2326 /* We overflowed if there is carry. */
2327 if (carry)
2328 return 1;
2329
2330 /* We would overflow if any significant unwritten parts would be
2331 non-zero. This is true if any remaining src parts are non-zero
2332 and the multiplier is non-zero. */
2333 if (multiplier)
2334 for(; i < srcParts; i++)
2335 if (src[i])
2336 return 1;
2337
2338 /* We fitted in the narrow destination. */
2339 return 0;
2340 }
2341}
2342
2343/* DST = LHS * RHS, where DST has the same width as the operands and
2344 is filled with the least significant parts of the result. Returns
2345 one if overflow occurred, otherwise zero. DST must be disjoint
2346 from both operands. */
2347int
2348APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
2349 const integerPart *rhs, unsigned int parts)
2350{
2351 unsigned int i;
2352 int overflow;
2353
2354 assert(dst != lhs && dst != rhs);
2355
2356 overflow = 0;
2357 tcSet(dst, 0, parts);
2358
2359 for(i = 0; i < parts; i++)
2360 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2361 parts - i, true);
2362
2363 return overflow;
2364}
2365
2366/* DST = LHS * RHS, where DST has twice the width as the operands. No
2367 overflow occurs. DST must be disjoint from both operands. */
2368void
2369APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
2370 const integerPart *rhs, unsigned int parts)
2371{
2372 unsigned int i;
2373 int overflow;
2374
2375 assert(dst != lhs && dst != rhs);
2376
2377 overflow = 0;
2378 tcSet(dst, 0, parts);
2379
2380 for(i = 0; i < parts; i++)
2381 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2382 parts + 1, true);
2383
2384 assert(!overflow);
2385}
2386
2387/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2388 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2389 set REMAINDER to the remainder, return zero. i.e.
2390
2391 OLD_LHS = RHS * LHS + REMAINDER
2392
2393 SCRATCH is a bignum of the same size as the operands and result for
2394 use by the routine; its contents need not be initialized and are
2395 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2396*/
2397int
2398APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
2399 integerPart *remainder, integerPart *srhs,
2400 unsigned int parts)
2401{
2402 unsigned int n, shiftCount;
2403 integerPart mask;
2404
2405 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2406
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002407 shiftCount = tcMSB(rhs, parts) + 1;
2408 if (shiftCount == 0)
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002409 return true;
2410
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002411 shiftCount = parts * integerPartWidth - shiftCount;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002412 n = shiftCount / integerPartWidth;
2413 mask = (integerPart) 1 << (shiftCount % integerPartWidth);
2414
2415 tcAssign(srhs, rhs, parts);
2416 tcShiftLeft(srhs, parts, shiftCount);
2417 tcAssign(remainder, lhs, parts);
2418 tcSet(lhs, 0, parts);
2419
2420 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2421 the total. */
2422 for(;;) {
2423 int compare;
2424
2425 compare = tcCompare(remainder, srhs, parts);
2426 if (compare >= 0) {
2427 tcSubtract(remainder, srhs, 0, parts);
2428 lhs[n] |= mask;
2429 }
2430
2431 if (shiftCount == 0)
2432 break;
2433 shiftCount--;
2434 tcShiftRight(srhs, parts, 1);
2435 if ((mask >>= 1) == 0)
2436 mask = (integerPart) 1 << (integerPartWidth - 1), n--;
2437 }
2438
2439 return false;
2440}
2441
2442/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2443 There are no restrictions on COUNT. */
2444void
2445APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count)
2446{
2447 unsigned int jump, shift;
2448
2449 /* Jump is the inter-part jump; shift is is intra-part shift. */
2450 jump = count / integerPartWidth;
2451 shift = count % integerPartWidth;
2452
2453 while (parts > jump) {
2454 integerPart part;
2455
2456 parts--;
2457
2458 /* dst[i] comes from the two parts src[i - jump] and, if we have
2459 an intra-part shift, src[i - jump - 1]. */
2460 part = dst[parts - jump];
2461 if (shift) {
2462 part <<= shift;
2463 if (parts >= jump + 1)
2464 part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
2465 }
2466
2467 dst[parts] = part;
2468 }
2469
2470 while (parts > 0)
2471 dst[--parts] = 0;
2472}
2473
2474/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2475 zero. There are no restrictions on COUNT. */
2476void
2477APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count)
2478{
2479 unsigned int i, jump, shift;
2480
2481 /* Jump is the inter-part jump; shift is is intra-part shift. */
2482 jump = count / integerPartWidth;
2483 shift = count % integerPartWidth;
2484
2485 /* Perform the shift. This leaves the most significant COUNT bits
2486 of the result at zero. */
2487 for(i = 0; i < parts; i++) {
2488 integerPart part;
2489
2490 if (i + jump >= parts) {
2491 part = 0;
2492 } else {
2493 part = dst[i + jump];
2494 if (shift) {
2495 part >>= shift;
2496 if (i + jump + 1 < parts)
2497 part |= dst[i + jump + 1] << (integerPartWidth - shift);
2498 }
2499 }
2500
2501 dst[i] = part;
2502 }
2503}
2504
2505/* Bitwise and of two bignums. */
2506void
2507APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts)
2508{
2509 unsigned int i;
2510
2511 for(i = 0; i < parts; i++)
2512 dst[i] &= rhs[i];
2513}
2514
2515/* Bitwise inclusive or of two bignums. */
2516void
2517APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts)
2518{
2519 unsigned int i;
2520
2521 for(i = 0; i < parts; i++)
2522 dst[i] |= rhs[i];
2523}
2524
2525/* Bitwise exclusive or of two bignums. */
2526void
2527APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts)
2528{
2529 unsigned int i;
2530
2531 for(i = 0; i < parts; i++)
2532 dst[i] ^= rhs[i];
2533}
2534
2535/* Complement a bignum in-place. */
2536void
2537APInt::tcComplement(integerPart *dst, unsigned int parts)
2538{
2539 unsigned int i;
2540
2541 for(i = 0; i < parts; i++)
2542 dst[i] = ~dst[i];
2543}
2544
2545/* Comparison (unsigned) of two bignums. */
2546int
2547APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
2548 unsigned int parts)
2549{
2550 while (parts) {
2551 parts--;
2552 if (lhs[parts] == rhs[parts])
2553 continue;
2554
2555 if (lhs[parts] > rhs[parts])
2556 return 1;
2557 else
2558 return -1;
2559 }
2560
2561 return 0;
2562}
2563
2564/* Increment a bignum in-place, return the carry flag. */
2565integerPart
2566APInt::tcIncrement(integerPart *dst, unsigned int parts)
2567{
2568 unsigned int i;
2569
2570 for(i = 0; i < parts; i++)
2571 if (++dst[i] != 0)
2572 break;
2573
2574 return i == parts;
2575}
2576
2577/* Set the least significant BITS bits of a bignum, clear the
2578 rest. */
2579void
2580APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts,
2581 unsigned int bits)
2582{
2583 unsigned int i;
2584
2585 i = 0;
2586 while (bits > integerPartWidth) {
2587 dst[i++] = ~(integerPart) 0;
2588 bits -= integerPartWidth;
2589 }
2590
2591 if (bits)
2592 dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
2593
2594 while (i < parts)
2595 dst[i++] = 0;
2596}