blob: 0d0f9ffca49a0e44573e0b0f0907e5a18c4b32f4 [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>
Zhou Shenga3832fd2007-02-07 06:14:53 +000021#include <cstring>
Zhou Shengfd43dcf2007-02-06 03:00:16 +000022#include <cstdlib>
Reid Spencer385f7542007-02-21 03:55:44 +000023#ifndef NDEBUG
Reid Spencer385f7542007-02-21 03:55:44 +000024#include <iomanip>
25#endif
26
Zhou Shengfd43dcf2007-02-06 03:00:16 +000027using namespace llvm;
28
Reid Spencer5d0d05c2007-02-25 19:32:03 +000029/// A utility function for allocating memory, checking for allocation failures,
30/// and ensuring the contents are zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000031inline static uint64_t* getClearedMemory(uint32_t numWords) {
32 uint64_t * result = new uint64_t[numWords];
33 assert(result && "APInt memory allocation fails!");
34 memset(result, 0, numWords * sizeof(uint64_t));
35 return result;
Zhou Sheng353815d2007-02-06 06:04:53 +000036}
37
Reid Spencer5d0d05c2007-02-25 19:32:03 +000038/// A utility function for allocating memory and checking for allocation
39/// failure. The content is not zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000040inline static uint64_t* getMemory(uint32_t numWords) {
41 uint64_t * result = new uint64_t[numWords];
42 assert(result && "APInt memory allocation fails!");
43 return result;
44}
45
Reid Spencer3a341372007-03-19 20:37:47 +000046APInt::APInt(uint32_t numBits, uint64_t val, bool isSigned )
47 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000048 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
49 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Reid Spencer5d0d05c2007-02-25 19:32:03 +000050 if (isSingleWord())
51 VAL = val;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000052 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000053 pVal = getClearedMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000054 pVal[0] = val;
Reid Spencer3a341372007-03-19 20:37:47 +000055 if (isSigned && int64_t(val) < 0)
56 for (unsigned i = 1; i < getNumWords(); ++i)
57 pVal[i] = -1ULL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000058 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +000059 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000060}
61
Reid Spenceraf0e9562007-02-18 18:38:44 +000062APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
Reid Spencer385f7542007-02-21 03:55:44 +000063 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000064 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
65 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000066 assert(bigVal && "Null pointer detected!");
67 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +000068 VAL = bigVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +000069 else {
Reid Spencer610fad82007-02-24 10:01:42 +000070 // Get memory, cleared to 0
71 pVal = getClearedMemory(getNumWords());
72 // Calculate the number of words to copy
73 uint32_t words = std::min<uint32_t>(numWords, getNumWords());
74 // Copy the words from bigVal to pVal
75 memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000076 }
Reid Spencer610fad82007-02-24 10:01:42 +000077 // Make sure unused high bits are cleared
78 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000079}
80
Reid Spenceraf0e9562007-02-18 18:38:44 +000081APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000082 uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000083 : BitWidth(numbits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000084 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000085}
86
Reid Spencer9c0696f2007-02-20 08:51:03 +000087APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000088 : BitWidth(numbits), VAL(0) {
Zhou Shenga3832fd2007-02-07 06:14:53 +000089 assert(!Val.empty() && "String empty?");
Reid Spencere81d2da2007-02-16 22:36:51 +000090 fromString(numbits, Val.c_str(), Val.size(), radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000091}
92
Reid Spencer54362ca2007-02-20 23:40:25 +000093APInt::APInt(const APInt& that)
Reid Spencer385f7542007-02-21 03:55:44 +000094 : BitWidth(that.BitWidth), VAL(0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +000095 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +000096 VAL = that.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000097 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000098 pVal = getMemory(getNumWords());
Reid Spencer54362ca2007-02-20 23:40:25 +000099 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000100 }
101}
102
103APInt::~APInt() {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000104 if (!isSingleWord() && pVal)
Reid Spencer9ac44112007-02-26 23:38:21 +0000105 delete [] pVal;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000106}
107
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000108APInt& APInt::operator=(const APInt& RHS) {
Reid Spencer9ac44112007-02-26 23:38:21 +0000109 // Don't do anything for X = X
110 if (this == &RHS)
111 return *this;
112
113 // If the bitwidths are the same, we can avoid mucking with memory
114 if (BitWidth == RHS.getBitWidth()) {
115 if (isSingleWord())
116 VAL = RHS.VAL;
117 else
118 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
119 return *this;
120 }
121
122 if (isSingleWord())
123 if (RHS.isSingleWord())
124 VAL = RHS.VAL;
125 else {
126 VAL = 0;
127 pVal = getMemory(RHS.getNumWords());
128 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
129 }
130 else if (getNumWords() == RHS.getNumWords())
131 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
132 else if (RHS.isSingleWord()) {
133 delete [] pVal;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000134 VAL = RHS.VAL;
Reid Spencer9ac44112007-02-26 23:38:21 +0000135 } else {
136 delete [] pVal;
137 pVal = getMemory(RHS.getNumWords());
138 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
139 }
140 BitWidth = RHS.BitWidth;
141 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000142}
143
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000144APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000145 if (isSingleWord())
146 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000147 else {
148 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000149 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000150 }
Reid Spencer9ac44112007-02-26 23:38:21 +0000151 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000152}
153
Reid Spenceraf0e9562007-02-18 18:38:44 +0000154/// add_1 - This function adds a single "digit" integer, y, to the multiple
155/// "digit" integer array, x[]. x[] is modified to reflect the addition and
156/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000157/// @returns the carry of the addition.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000158static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000159 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000160 dest[i] = y + x[i];
161 if (dest[i] < y)
Reid Spencer610fad82007-02-24 10:01:42 +0000162 y = 1; // Carry one to next digit.
Reid Spencerf2c521c2007-02-18 06:39:42 +0000163 else {
Reid Spencer610fad82007-02-24 10:01:42 +0000164 y = 0; // No need to carry so exit early
Reid Spencerf2c521c2007-02-18 06:39:42 +0000165 break;
166 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000167 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000168 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000169}
170
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000171/// @brief Prefix increment operator. Increments the APInt by one.
172APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000173 if (isSingleWord())
174 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000175 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000176 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000177 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000178}
179
Reid Spenceraf0e9562007-02-18 18:38:44 +0000180/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
181/// the multi-digit integer array, x[], propagating the borrowed 1 value until
182/// no further borrowing is neeeded or it runs out of "digits" in x. The result
183/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
184/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000185/// @returns the borrow out of the subtraction
186static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000187 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000188 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000189 x[i] -= y;
190 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000191 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000192 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000193 y = 0; // No need to borrow
194 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000195 }
196 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000197 return bool(y);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000198}
199
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000200/// @brief Prefix decrement operator. Decrements the APInt by one.
201APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000202 if (isSingleWord())
203 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000204 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000205 sub_1(pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000206 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000207}
208
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000209/// add - This function adds the integer array x to the integer array Y and
210/// places the result in dest.
211/// @returns the carry out from the addition
212/// @brief General addition of 64-bit integer arrays
Reid Spencer9d6c9192007-02-24 03:58:46 +0000213static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
214 uint32_t len) {
215 bool carry = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000216 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer92904632007-02-23 01:57:13 +0000217 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer54362ca2007-02-20 23:40:25 +0000218 dest[i] = x[i] + y[i] + carry;
Reid Spencer60c0a6a2007-02-21 05:44:56 +0000219 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000220 }
221 return carry;
222}
223
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000224/// Adds the RHS APint to this APInt.
225/// @returns this, after addition of RHS.
226/// @brief Addition assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000227APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000228 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000229 if (isSingleWord())
230 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000231 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000232 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000233 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000234 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000235}
236
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000237/// Subtracts the integer array y from the integer array x
238/// @returns returns the borrow out.
239/// @brief Generalized subtraction of 64-bit integer arrays.
Reid Spencer9d6c9192007-02-24 03:58:46 +0000240static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
241 uint32_t len) {
Reid Spencer385f7542007-02-21 03:55:44 +0000242 bool borrow = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000243 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer385f7542007-02-21 03:55:44 +0000244 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
245 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
246 dest[i] = x_tmp - y[i];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000247 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000248 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000249}
250
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000251/// Subtracts the RHS APInt from this APInt
252/// @returns this, after subtraction
253/// @brief Subtraction assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000254APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000255 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000256 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000257 VAL -= RHS.VAL;
258 else
259 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000260 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000261}
262
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000263/// Multiplies an integer array, x by a a uint64_t integer and places the result
264/// into dest.
265/// @returns the carry out of the multiplication.
266/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Reid Spencer610fad82007-02-24 10:01:42 +0000267static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
268 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer5e0a8512007-02-17 03:16:00 +0000269 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000270 uint64_t carry = 0;
271
272 // For each digit of x.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000273 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000274 // Split x into high and low words
275 uint64_t lx = x[i] & 0xffffffffULL;
276 uint64_t hx = x[i] >> 32;
277 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000278 // hasCarry == 0, no carry
279 // hasCarry == 1, has carry
280 // hasCarry == 2, no carry and the calculation result == 0.
281 uint8_t hasCarry = 0;
282 dest[i] = carry + lx * ly;
283 // Determine if the add above introduces carry.
284 hasCarry = (dest[i] < carry) ? 1 : 0;
285 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
286 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
287 // (2^32 - 1) + 2^32 = 2^64.
288 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
289
290 carry += (lx * hy) & 0xffffffffULL;
291 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
292 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
293 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
294 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000295 return carry;
296}
297
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000298/// Multiplies integer array x by integer array y and stores the result into
299/// the integer array dest. Note that dest's size must be >= xlen + ylen.
300/// @brief Generalized multiplicate of integer arrays.
Reid Spencer610fad82007-02-24 10:01:42 +0000301static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[],
302 uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000303 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000304 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000305 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencere0cdd332007-02-21 08:21:52 +0000306 uint64_t carry = 0, lx = 0, hx = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000307 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000308 lx = x[j] & 0xffffffffULL;
309 hx = x[j] >> 32;
310 // hasCarry - A flag to indicate if has carry.
311 // hasCarry == 0, no carry
312 // hasCarry == 1, has carry
313 // hasCarry == 2, no carry and the calculation result == 0.
314 uint8_t hasCarry = 0;
315 uint64_t resul = carry + lx * ly;
316 hasCarry = (resul < carry) ? 1 : 0;
317 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
318 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
319
320 carry += (lx * hy) & 0xffffffffULL;
321 resul = (carry << 32) | (resul & 0xffffffffULL);
322 dest[i+j] += resul;
323 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
324 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
325 ((lx * hy) >> 32) + hx * hy;
326 }
327 dest[i+xlen] = carry;
328 }
329}
330
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000331APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000332 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencere0cdd332007-02-21 08:21:52 +0000333 if (isSingleWord()) {
Reid Spencer61eb1802007-02-20 20:42:10 +0000334 VAL *= RHS.VAL;
Reid Spencere0cdd332007-02-21 08:21:52 +0000335 clearUnusedBits();
336 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000337 }
Reid Spencere0cdd332007-02-21 08:21:52 +0000338
339 // Get some bit facts about LHS and check for zero
340 uint32_t lhsBits = getActiveBits();
341 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
342 if (!lhsWords)
343 // 0 * X ===> 0
344 return *this;
345
346 // Get some bit facts about RHS and check for zero
347 uint32_t rhsBits = RHS.getActiveBits();
348 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
349 if (!rhsWords) {
350 // X * 0 ===> 0
351 clear();
352 return *this;
353 }
354
355 // Allocate space for the result
356 uint32_t destWords = rhsWords + lhsWords;
357 uint64_t *dest = getMemory(destWords);
358
359 // Perform the long multiply
360 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
361
362 // Copy result back into *this
363 clear();
364 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
365 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
366
367 // delete dest array and return
368 delete[] dest;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000369 return *this;
370}
371
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000372APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000373 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000374 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000375 VAL &= RHS.VAL;
376 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000377 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000378 uint32_t numWords = getNumWords();
379 for (uint32_t i = 0; i < numWords; ++i)
380 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000381 return *this;
382}
383
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000384APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000385 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000386 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000387 VAL |= RHS.VAL;
388 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000389 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000390 uint32_t numWords = getNumWords();
391 for (uint32_t i = 0; i < numWords; ++i)
392 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000393 return *this;
394}
395
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000396APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000397 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000398 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000399 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000400 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000401 return *this;
402 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000403 uint32_t numWords = getNumWords();
404 for (uint32_t i = 0; i < numWords; ++i)
405 pVal[i] ^= RHS.pVal[i];
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000406 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000407}
408
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000409APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000410 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000411 if (isSingleWord())
412 return APInt(getBitWidth(), VAL & RHS.VAL);
413
Reid Spenceraf0e9562007-02-18 18:38:44 +0000414 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000415 uint64_t* val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000416 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000417 val[i] = pVal[i] & RHS.pVal[i];
418 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000419}
420
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000421APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000422 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000423 if (isSingleWord())
424 return APInt(getBitWidth(), VAL | RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000425
Reid Spenceraf0e9562007-02-18 18:38:44 +0000426 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000427 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000428 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000429 val[i] = pVal[i] | RHS.pVal[i];
430 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000431}
432
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000433APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000434 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000435 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000436 return APInt(BitWidth, VAL ^ RHS.VAL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000437
Reid Spenceraf0e9562007-02-18 18:38:44 +0000438 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000439 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000440 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000441 val[i] = pVal[i] ^ RHS.pVal[i];
442
443 // 0^0==1 so clear the high bits in case they got set.
444 return APInt(val, getBitWidth()).clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000445}
446
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000447bool APInt::operator !() const {
448 if (isSingleWord())
449 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000450
451 for (uint32_t i = 0; i < getNumWords(); ++i)
452 if (pVal[i])
453 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000454 return true;
455}
456
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000457APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000458 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000459 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000460 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer61eb1802007-02-20 20:42:10 +0000461 APInt Result(*this);
462 Result *= RHS;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000463 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000464}
465
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000466APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000467 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000468 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000469 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000470 APInt Result(BitWidth, 0);
471 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000472 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000473}
474
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000475APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000476 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000477 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000478 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000479 APInt Result(BitWidth, 0);
480 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000481 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000482}
483
Reid Spenceraf0e9562007-02-18 18:38:44 +0000484bool APInt::operator[](uint32_t bitPosition) const {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000485 return (maskBit(bitPosition) &
486 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000487}
488
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000489bool APInt::operator==(const APInt& RHS) const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000490 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
Reid Spencer54362ca2007-02-20 23:40:25 +0000491 if (isSingleWord())
492 return VAL == RHS.VAL;
493
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000494 // Get some facts about the number of bits used in the two operands.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000495 uint32_t n1 = getActiveBits();
496 uint32_t n2 = RHS.getActiveBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000497
498 // If the number of bits isn't the same, they aren't equal
Reid Spencer54362ca2007-02-20 23:40:25 +0000499 if (n1 != n2)
500 return false;
501
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000502 // If the number of bits fits in a word, we only need to compare the low word.
Reid Spencer54362ca2007-02-20 23:40:25 +0000503 if (n1 <= APINT_BITS_PER_WORD)
504 return pVal[0] == RHS.pVal[0];
505
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000506 // Otherwise, compare everything
Reid Spencer54362ca2007-02-20 23:40:25 +0000507 for (int i = whichWord(n1 - 1); i >= 0; --i)
508 if (pVal[i] != RHS.pVal[i])
509 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000510 return true;
511}
512
Zhou Shenga3832fd2007-02-07 06:14:53 +0000513bool APInt::operator==(uint64_t Val) const {
514 if (isSingleWord())
515 return VAL == Val;
Reid Spencer54362ca2007-02-20 23:40:25 +0000516
517 uint32_t n = getActiveBits();
518 if (n <= APINT_BITS_PER_WORD)
519 return pVal[0] == Val;
520 else
521 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000522}
523
Reid Spencere81d2da2007-02-16 22:36:51 +0000524bool APInt::ult(const APInt& RHS) const {
525 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
526 if (isSingleWord())
527 return VAL < RHS.VAL;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000528
529 // Get active bit length of both operands
530 uint32_t n1 = getActiveBits();
531 uint32_t n2 = RHS.getActiveBits();
532
533 // If magnitude of LHS is less than RHS, return true.
534 if (n1 < n2)
535 return true;
536
537 // If magnitude of RHS is greather than LHS, return false.
538 if (n2 < n1)
539 return false;
540
541 // If they bot fit in a word, just compare the low order word
542 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
543 return pVal[0] < RHS.pVal[0];
544
545 // Otherwise, compare all words
Reid Spencer1fa111e2007-02-27 18:23:40 +0000546 uint32_t topWord = whichWord(std::max(n1,n2)-1);
547 for (int i = topWord; i >= 0; --i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000548 if (pVal[i] > RHS.pVal[i])
Reid Spencere81d2da2007-02-16 22:36:51 +0000549 return false;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000550 if (pVal[i] < RHS.pVal[i])
551 return true;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000552 }
553 return false;
554}
555
Reid Spencere81d2da2007-02-16 22:36:51 +0000556bool APInt::slt(const APInt& RHS) const {
557 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000558 if (isSingleWord()) {
559 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
560 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
561 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000562 }
Reid Spencera58f0582007-02-18 20:09:41 +0000563
564 APInt lhs(*this);
Reid Spencer1fa111e2007-02-27 18:23:40 +0000565 APInt rhs(RHS);
566 bool lhsNeg = isNegative();
567 bool rhsNeg = rhs.isNegative();
568 if (lhsNeg) {
569 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000570 lhs.flip();
571 lhs++;
572 }
Reid Spencer1fa111e2007-02-27 18:23:40 +0000573 if (rhsNeg) {
574 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000575 rhs.flip();
576 rhs++;
577 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000578
579 // Now we have unsigned values to compare so do the comparison if necessary
580 // based on the negativeness of the values.
Reid Spencer1fa111e2007-02-27 18:23:40 +0000581 if (lhsNeg)
582 if (rhsNeg)
583 return lhs.ugt(rhs);
Reid Spencera58f0582007-02-18 20:09:41 +0000584 else
585 return true;
Reid Spencer1fa111e2007-02-27 18:23:40 +0000586 else if (rhsNeg)
Reid Spencera58f0582007-02-18 20:09:41 +0000587 return false;
588 else
589 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000590}
591
Reid Spenceraf0e9562007-02-18 18:38:44 +0000592APInt& APInt::set(uint32_t bitPosition) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000593 if (isSingleWord())
594 VAL |= maskBit(bitPosition);
595 else
596 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000597 return *this;
598}
599
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000600APInt& APInt::set() {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000601 if (isSingleWord()) {
602 VAL = -1ULL;
603 return clearUnusedBits();
Zhou Shengb04973e2007-02-15 06:36:31 +0000604 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000605
606 // Set all the bits in all the words.
607 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
608 pVal[i] = -1ULL;
609 // Clear the unused ones
610 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000611}
612
613/// Set the given bit to 0 whose position is given as "bitPosition".
614/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000615APInt& APInt::clear(uint32_t bitPosition) {
616 if (isSingleWord())
617 VAL &= ~maskBit(bitPosition);
618 else
619 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000620 return *this;
621}
622
623/// @brief Set every bit to 0.
624APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000625 if (isSingleWord())
626 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000627 else
Reid Spencera58f0582007-02-18 20:09:41 +0000628 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000629 return *this;
630}
631
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000632/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
633/// this APInt.
634APInt APInt::operator~() const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000635 APInt Result(*this);
636 Result.flip();
637 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000638}
639
640/// @brief Toggle every bit to its opposite value.
641APInt& APInt::flip() {
Reid Spencer9eec2412007-02-25 23:44:53 +0000642 if (isSingleWord()) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000643 VAL ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000644 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000645 }
Reid Spencer9eec2412007-02-25 23:44:53 +0000646 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000647 pVal[i] ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000648 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000649}
650
651/// Toggle a given bit to its opposite value whose position is given
652/// as "bitPosition".
653/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000654APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000655 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000656 if ((*this)[bitPosition]) clear(bitPosition);
657 else set(bitPosition);
658 return *this;
659}
660
Reid Spencer794f4722007-02-26 21:02:27 +0000661uint64_t APInt::getHashValue() const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000662 // Put the bit width into the low order bits.
663 uint64_t hash = BitWidth;
Reid Spencer794f4722007-02-26 21:02:27 +0000664
665 // Add the sum of the words to the hash.
666 if (isSingleWord())
Reid Spencer9ac44112007-02-26 23:38:21 +0000667 hash += VAL << 6; // clear separation of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000668 else
669 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer9ac44112007-02-26 23:38:21 +0000670 hash += pVal[i] << 6; // clear sepration of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000671 return hash;
672}
673
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000674/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000675APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000676 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000677}
678
679/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000680APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000681 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
682 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000683}
684
Reid Spencere81d2da2007-02-16 22:36:51 +0000685bool APInt::isPowerOf2() const {
686 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
687}
688
Reid Spenceraf0e9562007-02-18 18:38:44 +0000689uint32_t APInt::countLeadingZeros() const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000690 uint32_t Count = 0;
Reid Spencere549c492007-02-21 00:29:48 +0000691 if (isSingleWord())
692 Count = CountLeadingZeros_64(VAL);
693 else {
694 for (uint32_t i = getNumWords(); i > 0u; --i) {
695 if (pVal[i-1] == 0)
696 Count += APINT_BITS_PER_WORD;
697 else {
698 Count += CountLeadingZeros_64(pVal[i-1]);
699 break;
700 }
701 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000702 }
Reid Spencerab2b2c82007-02-22 00:22:00 +0000703 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
704 if (remainder)
705 Count -= APINT_BITS_PER_WORD - remainder;
706 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000707}
708
Reid Spencer681dcd12007-02-27 21:59:26 +0000709static uint32_t countLeadingOnes_64(uint64_t V, uint32_t skip) {
710 uint32_t Count = 0;
711 if (skip)
712 V <<= skip;
713 while (V && (V & (1ULL << 63))) {
714 Count++;
715 V <<= 1;
716 }
717 return Count;
718}
719
720uint32_t APInt::countLeadingOnes() const {
721 if (isSingleWord())
722 return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth);
723
724 uint32_t highWordBits = BitWidth % APINT_BITS_PER_WORD;
725 uint32_t shift = (highWordBits == 0 ? 0 : APINT_BITS_PER_WORD - highWordBits);
726 int i = getNumWords() - 1;
727 uint32_t Count = countLeadingOnes_64(pVal[i], shift);
728 if (Count == highWordBits) {
729 for (i--; i >= 0; --i) {
730 if (pVal[i] == -1ULL)
731 Count += APINT_BITS_PER_WORD;
732 else {
733 Count += countLeadingOnes_64(pVal[i], 0);
734 break;
735 }
736 }
737 }
738 return Count;
739}
740
Reid Spenceraf0e9562007-02-18 18:38:44 +0000741uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000742 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000743 return CountTrailingZeros_64(VAL);
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000744 uint32_t Count = 0;
745 uint32_t i = 0;
746 for (; i < getNumWords() && pVal[i] == 0; ++i)
747 Count += APINT_BITS_PER_WORD;
748 if (i < getNumWords())
749 Count += CountTrailingZeros_64(pVal[i]);
750 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000751}
752
Reid Spenceraf0e9562007-02-18 18:38:44 +0000753uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000754 if (isSingleWord())
755 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000756 uint32_t Count = 0;
757 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000758 Count += CountPopulation_64(pVal[i]);
759 return Count;
760}
761
Reid Spencere81d2da2007-02-16 22:36:51 +0000762APInt APInt::byteSwap() const {
763 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
764 if (BitWidth == 16)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000765 return APInt(BitWidth, ByteSwap_16(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000766 else if (BitWidth == 32)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000767 return APInt(BitWidth, ByteSwap_32(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000768 else if (BitWidth == 48) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000769 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
770 Tmp1 = ByteSwap_32(Tmp1);
771 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
772 Tmp2 = ByteSwap_16(Tmp2);
773 return
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000774 APInt(BitWidth,
775 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
Reid Spencere81d2da2007-02-16 22:36:51 +0000776 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000777 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000778 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000779 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000780 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000781 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000782 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000783 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
784 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000785 }
786 return Result;
787 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000788}
789
Zhou Sheng0b706b12007-02-08 14:35:19 +0000790APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
791 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000792 APInt A = API1, B = API2;
793 while (!!B) {
794 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000795 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000796 A = T;
797 }
798 return A;
799}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000800
Reid Spencer1fa111e2007-02-27 18:23:40 +0000801APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, uint32_t width) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000802 union {
803 double D;
804 uint64_t I;
805 } T;
806 T.D = Double;
Reid Spencer30f44f32007-02-27 01:28:10 +0000807
808 // Get the sign bit from the highest order bit
Zhou Shengd93f00c2007-02-12 20:02:55 +0000809 bool isNeg = T.I >> 63;
Reid Spencer30f44f32007-02-27 01:28:10 +0000810
811 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd93f00c2007-02-12 20:02:55 +0000812 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer30f44f32007-02-27 01:28:10 +0000813
814 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000815 if (exp < 0)
Reid Spencerff605762007-02-28 01:30:08 +0000816 return APInt(width, 0u);
Reid Spencer30f44f32007-02-27 01:28:10 +0000817
818 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
819 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
820
821 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd93f00c2007-02-12 20:02:55 +0000822 if (exp < 52)
Reid Spencer1fa111e2007-02-27 18:23:40 +0000823 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
824 APInt(width, mantissa >> (52 - exp));
825
826 // If the client didn't provide enough bits for us to shift the mantissa into
827 // then the result is undefined, just return 0
828 if (width <= exp - 52)
829 return APInt(width, 0);
Reid Spencer30f44f32007-02-27 01:28:10 +0000830
831 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer1fa111e2007-02-27 18:23:40 +0000832 APInt Tmp(width, mantissa);
Reid Spencere81d2da2007-02-16 22:36:51 +0000833 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000834 return isNeg ? -Tmp : Tmp;
835}
836
Reid Spencerdb3faa62007-02-13 22:41:58 +0000837/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000838/// The layout for double is as following (IEEE Standard 754):
839/// --------------------------------------
840/// | Sign Exponent Fraction Bias |
841/// |-------------------------------------- |
842/// | 1[63] 11[62-52] 52[51-00] 1023 |
843/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000844double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000845
846 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000847 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
848 if (isSigned) {
849 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
850 return double(sext);
851 } else
852 return double(VAL);
853 }
854
Reid Spencer9c0696f2007-02-20 08:51:03 +0000855 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000856 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000857
858 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000859 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000860
861 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000862 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000863
Reid Spencer9c0696f2007-02-20 08:51:03 +0000864 // The exponent (without bias normalization) is just the number of bits
865 // we are using. Note that the sign bit is gone since we constructed the
866 // absolute value.
867 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000868
Reid Spencer9c0696f2007-02-20 08:51:03 +0000869 // Return infinity for exponent overflow
870 if (exp > 1023) {
871 if (!isSigned || !isNeg)
Reid Spencer61eb1802007-02-20 20:42:10 +0000872 return double(1.0E300 * 1.0E300); // positive infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000873 else
Reid Spencer61eb1802007-02-20 20:42:10 +0000874 return double(-1.0E300 * 1.0E300); // negative infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000875 }
876 exp += 1023; // Increment for 1023 bias
877
878 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
879 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000880 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000881 unsigned hiWord = whichWord(n-1);
882 if (hiWord == 0) {
883 mantissa = Tmp.pVal[0];
884 if (n > 52)
885 mantissa >>= n - 52; // shift down, we want the top 52 bits.
886 } else {
887 assert(hiWord > 0 && "huh?");
888 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
889 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
890 mantissa = hibits | lobits;
891 }
892
Zhou Shengd93f00c2007-02-12 20:02:55 +0000893 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000894 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000895 union {
896 double D;
897 uint64_t I;
898 } T;
899 T.I = sign | (exp << 52) | mantissa;
900 return T.D;
901}
902
Reid Spencere81d2da2007-02-16 22:36:51 +0000903// Truncate to new width.
Reid Spencer94900772007-02-28 17:34:32 +0000904APInt &APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000905 assert(width < BitWidth && "Invalid APInt Truncate request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000906 assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
907 uint32_t wordsBefore = getNumWords();
908 BitWidth = width;
909 uint32_t wordsAfter = getNumWords();
910 if (wordsBefore != wordsAfter) {
911 if (wordsAfter == 1) {
912 uint64_t *tmp = pVal;
913 VAL = pVal[0];
Reid Spencer9ac44112007-02-26 23:38:21 +0000914 delete [] tmp;
Reid Spencer9eec2412007-02-25 23:44:53 +0000915 } else {
916 uint64_t *newVal = getClearedMemory(wordsAfter);
917 for (uint32_t i = 0; i < wordsAfter; ++i)
918 newVal[i] = pVal[i];
Reid Spencer9ac44112007-02-26 23:38:21 +0000919 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000920 pVal = newVal;
921 }
922 }
Reid Spencer94900772007-02-28 17:34:32 +0000923 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000924}
925
926// Sign extend to a new width.
Reid Spencer94900772007-02-28 17:34:32 +0000927APInt &APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000928 assert(width > BitWidth && "Invalid APInt SignExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000929 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
Reid Spencer9eec2412007-02-25 23:44:53 +0000930 // If the sign bit isn't set, this is the same as zext.
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000931 if (!isNegative()) {
Reid Spencer9eec2412007-02-25 23:44:53 +0000932 zext(width);
Reid Spencer94900772007-02-28 17:34:32 +0000933 return *this;
Reid Spencer9eec2412007-02-25 23:44:53 +0000934 }
935
936 // The sign bit is set. First, get some facts
937 uint32_t wordsBefore = getNumWords();
938 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
939 BitWidth = width;
940 uint32_t wordsAfter = getNumWords();
941
942 // Mask the high order word appropriately
943 if (wordsBefore == wordsAfter) {
944 uint32_t newWordBits = width % APINT_BITS_PER_WORD;
945 // The extension is contained to the wordsBefore-1th word.
Reid Spencer36184ed2007-03-02 01:19:42 +0000946 uint64_t mask = ~0ULL;
947 if (newWordBits)
948 mask >>= APINT_BITS_PER_WORD - newWordBits;
949 mask <<= wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +0000950 if (wordsBefore == 1)
951 VAL |= mask;
952 else
953 pVal[wordsBefore-1] |= mask;
Reid Spencer295e40a2007-03-01 23:30:25 +0000954 return clearUnusedBits();
Reid Spencer9eec2412007-02-25 23:44:53 +0000955 }
956
Reid Spencerf30b1882007-02-25 23:54:00 +0000957 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +0000958 uint64_t *newVal = getMemory(wordsAfter);
959 if (wordsBefore == 1)
960 newVal[0] = VAL | mask;
961 else {
962 for (uint32_t i = 0; i < wordsBefore; ++i)
963 newVal[i] = pVal[i];
964 newVal[wordsBefore-1] |= mask;
965 }
966 for (uint32_t i = wordsBefore; i < wordsAfter; i++)
967 newVal[i] = -1ULL;
968 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +0000969 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000970 pVal = newVal;
Reid Spencer94900772007-02-28 17:34:32 +0000971 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000972}
973
974// Zero extend to a new width.
Reid Spencer94900772007-02-28 17:34:32 +0000975APInt &APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000976 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000977 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
978 uint32_t wordsBefore = getNumWords();
979 BitWidth = width;
980 uint32_t wordsAfter = getNumWords();
981 if (wordsBefore != wordsAfter) {
982 uint64_t *newVal = getClearedMemory(wordsAfter);
983 if (wordsBefore == 1)
984 newVal[0] = VAL;
985 else
986 for (uint32_t i = 0; i < wordsBefore; ++i)
987 newVal[i] = pVal[i];
988 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +0000989 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000990 pVal = newVal;
991 }
Reid Spencer94900772007-02-28 17:34:32 +0000992 return *this;
Reid Spencere81d2da2007-02-16 22:36:51 +0000993}
994
Reid Spencer68e23002007-03-01 17:15:32 +0000995APInt &APInt::zextOrTrunc(uint32_t width) {
996 if (BitWidth < width)
997 return zext(width);
998 if (BitWidth > width)
999 return trunc(width);
1000 return *this;
1001}
1002
1003APInt &APInt::sextOrTrunc(uint32_t width) {
1004 if (BitWidth < width)
1005 return sext(width);
1006 if (BitWidth > width)
1007 return trunc(width);
1008 return *this;
1009}
1010
Zhou Shengff4304f2007-02-09 07:48:24 +00001011/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001012/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001013APInt APInt::ashr(uint32_t shiftAmt) const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001014 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer46f9c942007-03-02 22:39:11 +00001015 // Handle a degenerate case
1016 if (shiftAmt == 0)
1017 return *this;
1018
1019 // Handle single word shifts with built-in ashr
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001020 if (isSingleWord()) {
1021 if (shiftAmt == BitWidth)
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001022 return APInt(BitWidth, 0); // undefined
1023 else {
1024 uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001025 return APInt(BitWidth,
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001026 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1027 }
Zhou Sheng0b706b12007-02-08 14:35:19 +00001028 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001029
Reid Spencer46f9c942007-03-02 22:39:11 +00001030 // If all the bits were shifted out, the result is, technically, undefined.
1031 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1032 // issues in the algorithm below.
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001033 if (shiftAmt == BitWidth)
1034 if (isNegative())
1035 return APInt(BitWidth, -1ULL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001036 else
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001037 return APInt(BitWidth, 0);
1038
1039 // Create some space for the result.
1040 uint64_t * val = new uint64_t[getNumWords()];
1041
Reid Spencer46f9c942007-03-02 22:39:11 +00001042 // Compute some values needed by the following shift algorithms
1043 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1044 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1045 uint32_t breakWord = getNumWords() - 1 - offset; // last word affected
1046 uint32_t bitsInWord = whichBit(BitWidth); // how many bits in last word?
1047 if (bitsInWord == 0)
1048 bitsInWord = APINT_BITS_PER_WORD;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001049
1050 // If we are shifting whole words, just move whole words
1051 if (wordShift == 0) {
Reid Spencer46f9c942007-03-02 22:39:11 +00001052 // Move the words containing significant bits
1053 for (uint32_t i = 0; i <= breakWord; ++i)
1054 val[i] = pVal[i+offset]; // move whole word
1055
1056 // Adjust the top significant word for sign bit fill, if negative
1057 if (isNegative())
1058 if (bitsInWord < APINT_BITS_PER_WORD)
1059 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1060 } else {
1061 // Shift the low order words
1062 for (uint32_t i = 0; i < breakWord; ++i) {
1063 // This combines the shifted corresponding word with the low bits from
1064 // the next word (shifted into this word's high bits).
1065 val[i] = (pVal[i+offset] >> wordShift) |
1066 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1067 }
1068
1069 // Shift the break word. In this case there are no bits from the next word
1070 // to include in this word.
1071 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1072
1073 // Deal with sign extenstion in the break word, and possibly the word before
1074 // it.
1075 if (isNegative())
1076 if (wordShift > bitsInWord) {
1077 if (breakWord > 0)
1078 val[breakWord-1] |=
1079 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1080 val[breakWord] |= ~0ULL;
1081 } else
1082 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001083 }
1084
Reid Spencer46f9c942007-03-02 22:39:11 +00001085 // Remaining words are 0 or -1, just assign them.
1086 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001087 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer46f9c942007-03-02 22:39:11 +00001088 val[i] = fillValue;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001089 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001090}
1091
Zhou Shengff4304f2007-02-09 07:48:24 +00001092/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001093/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001094APInt APInt::lshr(uint32_t shiftAmt) const {
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001095 if (isSingleWord())
1096 if (shiftAmt == BitWidth)
1097 return APInt(BitWidth, 0);
1098 else
1099 return APInt(BitWidth, this->VAL >> shiftAmt);
1100
Reid Spencerba81c2b2007-02-26 01:19:48 +00001101 // If all the bits were shifted out, the result is 0. This avoids issues
1102 // with shifting by the size of the integer type, which produces undefined
1103 // results. We define these "undefined results" to always be 0.
1104 if (shiftAmt == BitWidth)
1105 return APInt(BitWidth, 0);
1106
1107 // Create some space for the result.
1108 uint64_t * val = new uint64_t[getNumWords()];
1109
1110 // If we are shifting less than a word, compute the shift with a simple carry
1111 if (shiftAmt < APINT_BITS_PER_WORD) {
1112 uint64_t carry = 0;
1113 for (int i = getNumWords()-1; i >= 0; --i) {
Reid Spenceraf8fb192007-03-01 05:39:56 +00001114 val[i] = (pVal[i] >> shiftAmt) | carry;
Reid Spencerba81c2b2007-02-26 01:19:48 +00001115 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1116 }
1117 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001118 }
1119
Reid Spencerba81c2b2007-02-26 01:19:48 +00001120 // Compute some values needed by the remaining shift algorithms
1121 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1122 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1123
1124 // If we are shifting whole words, just move whole words
1125 if (wordShift == 0) {
1126 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1127 val[i] = pVal[i+offset];
1128 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1129 val[i] = 0;
1130 return APInt(val,BitWidth).clearUnusedBits();
1131 }
1132
1133 // Shift the low order words
1134 uint32_t breakWord = getNumWords() - offset -1;
1135 for (uint32_t i = 0; i < breakWord; ++i)
Reid Spenceraf8fb192007-03-01 05:39:56 +00001136 val[i] = (pVal[i+offset] >> wordShift) |
1137 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencerba81c2b2007-02-26 01:19:48 +00001138 // Shift the break word.
1139 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1140
1141 // Remaining words are 0
1142 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1143 val[i] = 0;
1144 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001145}
1146
Zhou Shengff4304f2007-02-09 07:48:24 +00001147/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001148/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001149APInt APInt::shl(uint32_t shiftAmt) const {
Reid Spencer5bce8542007-02-24 20:19:37 +00001150 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer87553802007-02-25 00:56:44 +00001151 if (isSingleWord()) {
Reid Spencer5bce8542007-02-24 20:19:37 +00001152 if (shiftAmt == BitWidth)
Reid Spencer87553802007-02-25 00:56:44 +00001153 return APInt(BitWidth, 0); // avoid undefined shift results
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001154 return APInt(BitWidth, VAL << shiftAmt);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001155 }
Reid Spencer5bce8542007-02-24 20:19:37 +00001156
Reid Spencer87553802007-02-25 00:56:44 +00001157 // If all the bits were shifted out, the result is 0. This avoids issues
1158 // with shifting by the size of the integer type, which produces undefined
1159 // results. We define these "undefined results" to always be 0.
1160 if (shiftAmt == BitWidth)
1161 return APInt(BitWidth, 0);
1162
1163 // Create some space for the result.
1164 uint64_t * val = new uint64_t[getNumWords()];
1165
1166 // If we are shifting less than a word, do it the easy way
1167 if (shiftAmt < APINT_BITS_PER_WORD) {
1168 uint64_t carry = 0;
Reid Spencer87553802007-02-25 00:56:44 +00001169 for (uint32_t i = 0; i < getNumWords(); i++) {
1170 val[i] = pVal[i] << shiftAmt | carry;
1171 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1172 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001173 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001174 }
1175
Reid Spencer87553802007-02-25 00:56:44 +00001176 // Compute some values needed by the remaining shift algorithms
1177 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1178 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1179
1180 // If we are shifting whole words, just move whole words
1181 if (wordShift == 0) {
1182 for (uint32_t i = 0; i < offset; i++)
1183 val[i] = 0;
1184 for (uint32_t i = offset; i < getNumWords(); i++)
1185 val[i] = pVal[i-offset];
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001186 return APInt(val,BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001187 }
Reid Spencer87553802007-02-25 00:56:44 +00001188
1189 // Copy whole words from this to Result.
1190 uint32_t i = getNumWords() - 1;
1191 for (; i > offset; --i)
1192 val[i] = pVal[i-offset] << wordShift |
1193 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencer438d71e2007-02-25 01:08:58 +00001194 val[offset] = pVal[0] << wordShift;
Reid Spencer87553802007-02-25 00:56:44 +00001195 for (i = 0; i < offset; ++i)
1196 val[i] = 0;
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001197 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001198}
1199
Reid Spenceraf8fb192007-03-01 05:39:56 +00001200
1201// Square Root - this method computes and returns the square root of "this".
1202// Three mechanisms are used for computation. For small values (<= 5 bits),
1203// a table lookup is done. This gets some performance for common cases. For
1204// values using less than 52 bits, the value is converted to double and then
1205// the libc sqrt function is called. The result is rounded and then converted
1206// back to a uint64_t which is then used to construct the result. Finally,
1207// the Babylonian method for computing square roots is used.
1208APInt APInt::sqrt() const {
1209
1210 // Determine the magnitude of the value.
1211 uint32_t magnitude = getActiveBits();
1212
1213 // Use a fast table for some small values. This also gets rid of some
1214 // rounding errors in libc sqrt for small values.
1215 if (magnitude <= 5) {
Reid Spencer4e1e87f2007-03-01 17:47:31 +00001216 static const uint8_t results[32] = {
Reid Spencerb5ca2cd2007-03-01 06:23:32 +00001217 /* 0 */ 0,
1218 /* 1- 2 */ 1, 1,
1219 /* 3- 6 */ 2, 2, 2, 2,
1220 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1221 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1222 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1223 /* 31 */ 6
1224 };
1225 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spenceraf8fb192007-03-01 05:39:56 +00001226 }
1227
1228 // If the magnitude of the value fits in less than 52 bits (the precision of
1229 // an IEEE double precision floating point value), then we can use the
1230 // libc sqrt function which will probably use a hardware sqrt computation.
1231 // This should be faster than the algorithm below.
Jeff Cohenca5183d2007-03-05 00:00:42 +00001232 if (magnitude < 52) {
1233#ifdef _MSC_VER
1234 // Amazingly, VC++ doesn't have round().
1235 return APInt(BitWidth,
1236 uint64_t(::sqrt(double(isSingleWord()?VAL:pVal[0]))) + 0.5);
1237#else
Reid Spenceraf8fb192007-03-01 05:39:56 +00001238 return APInt(BitWidth,
1239 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenca5183d2007-03-05 00:00:42 +00001240#endif
1241 }
Reid Spenceraf8fb192007-03-01 05:39:56 +00001242
1243 // Okay, all the short cuts are exhausted. We must compute it. The following
1244 // is a classical Babylonian method for computing the square root. This code
1245 // was adapted to APINt from a wikipedia article on such computations.
1246 // See http://www.wikipedia.org/ and go to the page named
1247 // Calculate_an_integer_square_root.
1248 uint32_t nbits = BitWidth, i = 4;
1249 APInt testy(BitWidth, 16);
1250 APInt x_old(BitWidth, 1);
1251 APInt x_new(BitWidth, 0);
1252 APInt two(BitWidth, 2);
1253
1254 // Select a good starting value using binary logarithms.
1255 for (;; i += 2, testy = testy.shl(2))
1256 if (i >= nbits || this->ule(testy)) {
1257 x_old = x_old.shl(i / 2);
1258 break;
1259 }
1260
1261 // Use the Babylonian method to arrive at the integer square root:
1262 for (;;) {
1263 x_new = (this->udiv(x_old) + x_old).udiv(two);
1264 if (x_old.ule(x_new))
1265 break;
1266 x_old = x_new;
1267 }
1268
1269 // Make sure we return the closest approximation
Reid Spencerf09aef72007-03-02 04:21:55 +00001270 // NOTE: The rounding calculation below is correct. It will produce an
1271 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
1272 // determined to be a rounding issue with pari/gp as it begins to use a
1273 // floating point representation after 192 bits. There are no discrepancies
1274 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spenceraf8fb192007-03-01 05:39:56 +00001275 APInt square(x_old * x_old);
1276 APInt nextSquare((x_old + 1) * (x_old +1));
1277 if (this->ult(square))
1278 return x_old;
Reid Spencerf09aef72007-03-02 04:21:55 +00001279 else if (this->ule(nextSquare)) {
1280 APInt midpoint((nextSquare - square).udiv(two));
1281 APInt offset(*this - square);
1282 if (offset.ult(midpoint))
Reid Spenceraf8fb192007-03-01 05:39:56 +00001283 return x_old;
Reid Spencerf09aef72007-03-02 04:21:55 +00001284 else
1285 return x_old + 1;
1286 } else
Reid Spenceraf8fb192007-03-01 05:39:56 +00001287 assert(0 && "Error in APInt::sqrt computation");
1288 return x_old + 1;
1289}
1290
Reid Spencer9c0696f2007-02-20 08:51:03 +00001291/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1292/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1293/// variables here have the same names as in the algorithm. Comments explain
1294/// the algorithm and any deviation from it.
1295static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1296 uint32_t m, uint32_t n) {
1297 assert(u && "Must provide dividend");
1298 assert(v && "Must provide divisor");
1299 assert(q && "Must provide quotient");
Reid Spencer9d6c9192007-02-24 03:58:46 +00001300 assert(u != v && u != q && v != q && "Must us different memory");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001301 assert(n>1 && "n must be > 1");
1302
1303 // Knuth uses the value b as the base of the number system. In our case b
1304 // is 2^31 so we just set it to -1u.
1305 uint64_t b = uint64_t(1) << 32;
1306
Reid Spencer9d6c9192007-02-24 03:58:46 +00001307 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1308 DEBUG(cerr << "KnuthDiv: original:");
1309 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1310 DEBUG(cerr << " by");
1311 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1312 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001313 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1314 // u and v by d. Note that we have taken Knuth's advice here to use a power
1315 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1316 // 2 allows us to shift instead of multiply and it is easy to determine the
1317 // shift amount from the leading zeros. We are basically normalizing the u
1318 // and v so that its high bits are shifted to the top of v's range without
1319 // overflow. Note that this can require an extra word in u so that u must
1320 // be of length m+n+1.
1321 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1322 uint32_t v_carry = 0;
1323 uint32_t u_carry = 0;
1324 if (shift) {
1325 for (uint32_t i = 0; i < m+n; ++i) {
1326 uint32_t u_tmp = u[i] >> (32 - shift);
1327 u[i] = (u[i] << shift) | u_carry;
1328 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001329 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001330 for (uint32_t i = 0; i < n; ++i) {
1331 uint32_t v_tmp = v[i] >> (32 - shift);
1332 v[i] = (v[i] << shift) | v_carry;
1333 v_carry = v_tmp;
1334 }
1335 }
1336 u[m+n] = u_carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001337 DEBUG(cerr << "KnuthDiv: normal:");
1338 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1339 DEBUG(cerr << " by");
1340 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1341 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001342
1343 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1344 int j = m;
1345 do {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001346 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001347 // D3. [Calculate q'.].
1348 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1349 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1350 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1351 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1352 // on v[n-2] determines at high speed most of the cases in which the trial
1353 // value qp is one too large, and it eliminates all cases where qp is two
1354 // too large.
Reid Spencer92904632007-02-23 01:57:13 +00001355 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001356 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencer92904632007-02-23 01:57:13 +00001357 uint64_t qp = dividend / v[n-1];
1358 uint64_t rp = dividend % v[n-1];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001359 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1360 qp--;
1361 rp += v[n-1];
Reid Spencer610fad82007-02-24 10:01:42 +00001362 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencer9d6c9192007-02-24 03:58:46 +00001363 qp--;
Reid Spencer92904632007-02-23 01:57:13 +00001364 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001365 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001366
Reid Spencer92904632007-02-23 01:57:13 +00001367 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1368 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1369 // consists of a simple multiplication by a one-place number, combined with
Reid Spencer610fad82007-02-24 10:01:42 +00001370 // a subtraction.
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001371 bool isNeg = false;
Reid Spencer92904632007-02-23 01:57:13 +00001372 for (uint32_t i = 0; i < n; ++i) {
Reid Spencer610fad82007-02-24 10:01:42 +00001373 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001374 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
Reid Spencer610fad82007-02-24 10:01:42 +00001375 bool borrow = subtrahend > u_tmp;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001376 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
Reid Spencer610fad82007-02-24 10:01:42 +00001377 << ", subtrahend == " << subtrahend
1378 << ", borrow = " << borrow << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001379
Reid Spencer610fad82007-02-24 10:01:42 +00001380 uint64_t result = u_tmp - subtrahend;
1381 uint32_t k = j + i;
1382 u[k++] = result & (b-1); // subtract low word
1383 u[k++] = result >> 32; // subtract high word
1384 while (borrow && k <= m+n) { // deal with borrow to the left
1385 borrow = u[k] == 0;
1386 u[k]--;
1387 k++;
1388 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001389 isNeg |= borrow;
Reid Spencer610fad82007-02-24 10:01:42 +00001390 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1391 u[j+i+1] << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001392 }
1393 DEBUG(cerr << "KnuthDiv: after subtraction:");
1394 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1395 DEBUG(cerr << '\n');
Reid Spencer610fad82007-02-24 10:01:42 +00001396 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1397 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1398 // true value plus b**(n+1), namely as the b's complement of
Reid Spencer92904632007-02-23 01:57:13 +00001399 // the true value, and a "borrow" to the left should be remembered.
1400 //
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001401 if (isNeg) {
Reid Spencer610fad82007-02-24 10:01:42 +00001402 bool carry = true; // true because b's complement is "complement + 1"
1403 for (uint32_t i = 0; i <= m+n; ++i) {
1404 u[i] = ~u[i] + carry; // b's complement
1405 carry = carry && u[i] == 0;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001406 }
Reid Spencer92904632007-02-23 01:57:13 +00001407 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001408 DEBUG(cerr << "KnuthDiv: after complement:");
1409 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1410 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001411
1412 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1413 // negative, go to step D6; otherwise go on to step D7.
1414 q[j] = qp;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001415 if (isNeg) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001416 // D6. [Add back]. The probability that this step is necessary is very
1417 // small, on the order of only 2/b. Make sure that test data accounts for
Reid Spencer92904632007-02-23 01:57:13 +00001418 // this possibility. Decrease q[j] by 1
1419 q[j]--;
1420 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1421 // A carry will occur to the left of u[j+n], and it should be ignored
1422 // since it cancels with the borrow that occurred in D4.
1423 bool carry = false;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001424 for (uint32_t i = 0; i < n; i++) {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001425 uint32_t limit = std::min(u[j+i],v[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001426 u[j+i] += v[i] + carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001427 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001428 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001429 u[j+n] += carry;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001430 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001431 DEBUG(cerr << "KnuthDiv: after correction:");
1432 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1433 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001434
Reid Spencer92904632007-02-23 01:57:13 +00001435 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1436 } while (--j >= 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001437
Reid Spencer9d6c9192007-02-24 03:58:46 +00001438 DEBUG(cerr << "KnuthDiv: quotient:");
1439 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1440 DEBUG(cerr << '\n');
1441
Reid Spencer9c0696f2007-02-20 08:51:03 +00001442 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1443 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1444 // compute the remainder (urem uses this).
1445 if (r) {
1446 // The value d is expressed by the "shift" value above since we avoided
1447 // multiplication by d by using a shift left. So, all we have to do is
1448 // shift right here. In order to mak
Reid Spencer1050ec52007-02-24 20:38:01 +00001449 if (shift) {
1450 uint32_t carry = 0;
1451 DEBUG(cerr << "KnuthDiv: remainder:");
1452 for (int i = n-1; i >= 0; i--) {
1453 r[i] = (u[i] >> shift) | carry;
1454 carry = u[i] << (32 - shift);
1455 DEBUG(cerr << " " << r[i]);
1456 }
1457 } else {
1458 for (int i = n-1; i >= 0; i--) {
1459 r[i] = u[i];
1460 DEBUG(cerr << " " << r[i]);
1461 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001462 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001463 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001464 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001465 DEBUG(cerr << std::setbase(10) << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001466}
1467
Reid Spencer9c0696f2007-02-20 08:51:03 +00001468void APInt::divide(const APInt LHS, uint32_t lhsWords,
1469 const APInt &RHS, uint32_t rhsWords,
1470 APInt *Quotient, APInt *Remainder)
1471{
1472 assert(lhsWords >= rhsWords && "Fractional result");
1473
1474 // First, compose the values into an array of 32-bit words instead of
1475 // 64-bit words. This is a necessity of both the "short division" algorithm
1476 // and the the Knuth "classical algorithm" which requires there to be native
1477 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1478 // can't use 64-bit operands here because we don't have native results of
1479 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1480 // work on large-endian machines.
1481 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1482 uint32_t n = rhsWords * 2;
1483 uint32_t m = (lhsWords * 2) - n;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001484
1485 // Allocate space for the temporary values we need either on the stack, if
1486 // it will fit, or on the heap if it won't.
1487 uint32_t SPACE[128];
1488 uint32_t *U = 0;
1489 uint32_t *V = 0;
1490 uint32_t *Q = 0;
1491 uint32_t *R = 0;
1492 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1493 U = &SPACE[0];
1494 V = &SPACE[m+n+1];
1495 Q = &SPACE[(m+n+1) + n];
1496 if (Remainder)
1497 R = &SPACE[(m+n+1) + n + (m+n)];
1498 } else {
1499 U = new uint32_t[m + n + 1];
1500 V = new uint32_t[n];
1501 Q = new uint32_t[m+n];
1502 if (Remainder)
1503 R = new uint32_t[n];
1504 }
1505
1506 // Initialize the dividend
Reid Spencer9c0696f2007-02-20 08:51:03 +00001507 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1508 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001509 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001510 U[i * 2] = tmp & mask;
1511 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1512 }
1513 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1514
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001515 // Initialize the divisor
Reid Spencer9c0696f2007-02-20 08:51:03 +00001516 memset(V, 0, (n)*sizeof(uint32_t));
1517 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001518 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001519 V[i * 2] = tmp & mask;
1520 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1521 }
1522
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001523 // initialize the quotient and remainder
Reid Spencer9c0696f2007-02-20 08:51:03 +00001524 memset(Q, 0, (m+n) * sizeof(uint32_t));
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001525 if (Remainder)
Reid Spencer9c0696f2007-02-20 08:51:03 +00001526 memset(R, 0, n * sizeof(uint32_t));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001527
1528 // Now, adjust m and n for the Knuth division. n is the number of words in
1529 // the divisor. m is the number of words by which the dividend exceeds the
1530 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1531 // contain any zero words or the Knuth algorithm fails.
1532 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1533 n--;
1534 m++;
1535 }
1536 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1537 m--;
1538
1539 // If we're left with only a single word for the divisor, Knuth doesn't work
1540 // so we implement the short division algorithm here. This is much simpler
1541 // and faster because we are certain that we can divide a 64-bit quantity
1542 // by a 32-bit quantity at hardware speed and short division is simply a
1543 // series of such operations. This is just like doing short division but we
1544 // are using base 2^32 instead of base 10.
1545 assert(n != 0 && "Divide by zero?");
1546 if (n == 1) {
1547 uint32_t divisor = V[0];
1548 uint32_t remainder = 0;
1549 for (int i = m+n-1; i >= 0; i--) {
1550 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1551 if (partial_dividend == 0) {
1552 Q[i] = 0;
1553 remainder = 0;
1554 } else if (partial_dividend < divisor) {
1555 Q[i] = 0;
1556 remainder = partial_dividend;
1557 } else if (partial_dividend == divisor) {
1558 Q[i] = 1;
1559 remainder = 0;
1560 } else {
1561 Q[i] = partial_dividend / divisor;
1562 remainder = partial_dividend - (Q[i] * divisor);
1563 }
1564 }
1565 if (R)
1566 R[0] = remainder;
1567 } else {
1568 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1569 // case n > 1.
1570 KnuthDiv(U, V, Q, R, m, n);
1571 }
1572
1573 // If the caller wants the quotient
1574 if (Quotient) {
1575 // Set up the Quotient value's memory.
1576 if (Quotient->BitWidth != LHS.BitWidth) {
1577 if (Quotient->isSingleWord())
1578 Quotient->VAL = 0;
1579 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001580 delete [] Quotient->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001581 Quotient->BitWidth = LHS.BitWidth;
1582 if (!Quotient->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001583 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001584 } else
1585 Quotient->clear();
1586
1587 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1588 // order words.
1589 if (lhsWords == 1) {
1590 uint64_t tmp =
1591 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1592 if (Quotient->isSingleWord())
1593 Quotient->VAL = tmp;
1594 else
1595 Quotient->pVal[0] = tmp;
1596 } else {
1597 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1598 for (unsigned i = 0; i < lhsWords; ++i)
1599 Quotient->pVal[i] =
1600 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1601 }
1602 }
1603
1604 // If the caller wants the remainder
1605 if (Remainder) {
1606 // Set up the Remainder value's memory.
1607 if (Remainder->BitWidth != RHS.BitWidth) {
1608 if (Remainder->isSingleWord())
1609 Remainder->VAL = 0;
1610 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001611 delete [] Remainder->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001612 Remainder->BitWidth = RHS.BitWidth;
1613 if (!Remainder->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001614 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001615 } else
1616 Remainder->clear();
1617
1618 // The remainder is in R. Reconstitute the remainder into Remainder's low
1619 // order words.
1620 if (rhsWords == 1) {
1621 uint64_t tmp =
1622 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1623 if (Remainder->isSingleWord())
1624 Remainder->VAL = tmp;
1625 else
1626 Remainder->pVal[0] = tmp;
1627 } else {
1628 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1629 for (unsigned i = 0; i < rhsWords; ++i)
1630 Remainder->pVal[i] =
1631 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1632 }
1633 }
1634
1635 // Clean up the memory we allocated.
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001636 if (U != &SPACE[0]) {
1637 delete [] U;
1638 delete [] V;
1639 delete [] Q;
1640 delete [] R;
1641 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001642}
1643
Reid Spencere81d2da2007-02-16 22:36:51 +00001644APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001645 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001646
1647 // First, deal with the easy case
1648 if (isSingleWord()) {
1649 assert(RHS.VAL != 0 && "Divide by zero?");
1650 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001651 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001652
Reid Spencer71bd08f2007-02-17 02:07:07 +00001653 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001654 uint32_t rhsBits = RHS.getActiveBits();
1655 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001656 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001657 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001658 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001659
1660 // Deal with some degenerate cases
1661 if (!lhsWords)
Reid Spencere0cdd332007-02-21 08:21:52 +00001662 // 0 / X ===> 0
1663 return APInt(BitWidth, 0);
1664 else if (lhsWords < rhsWords || this->ult(RHS)) {
1665 // X / Y ===> 0, iff X < Y
1666 return APInt(BitWidth, 0);
1667 } else if (*this == RHS) {
1668 // X / X ===> 1
1669 return APInt(BitWidth, 1);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001670 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001671 // All high words are zero, just use native divide
Reid Spencere0cdd332007-02-21 08:21:52 +00001672 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001673 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001674
1675 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1676 APInt Quotient(1,0); // to hold result.
1677 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1678 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001679}
1680
Reid Spencere81d2da2007-02-16 22:36:51 +00001681APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001682 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001683 if (isSingleWord()) {
1684 assert(RHS.VAL != 0 && "Remainder by zero?");
1685 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001686 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001687
Reid Spencere0cdd332007-02-21 08:21:52 +00001688 // Get some facts about the LHS
1689 uint32_t lhsBits = getActiveBits();
1690 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001691
1692 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001693 uint32_t rhsBits = RHS.getActiveBits();
1694 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001695 assert(rhsWords && "Performing remainder operation by zero ???");
1696
Reid Spencer71bd08f2007-02-17 02:07:07 +00001697 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001698 if (lhsWords == 0) {
Reid Spencere0cdd332007-02-21 08:21:52 +00001699 // 0 % Y ===> 0
1700 return APInt(BitWidth, 0);
1701 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1702 // X % Y ===> X, iff X < Y
1703 return *this;
1704 } else if (*this == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001705 // X % X == 0;
Reid Spencere0cdd332007-02-21 08:21:52 +00001706 return APInt(BitWidth, 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001707 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001708 // All high words are zero, just use native remainder
Reid Spencere0cdd332007-02-21 08:21:52 +00001709 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001710 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001711
1712 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1713 APInt Remainder(1,0);
1714 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1715 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001716}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001717
Reid Spencer385f7542007-02-21 03:55:44 +00001718void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001719 uint8_t radix) {
Reid Spencer385f7542007-02-21 03:55:44 +00001720 // Check our assumptions here
Reid Spencer5e0a8512007-02-17 03:16:00 +00001721 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1722 "Radix should be 2, 8, 10, or 16!");
Reid Spencer385f7542007-02-21 03:55:44 +00001723 assert(str && "String is null?");
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001724 bool isNeg = str[0] == '-';
1725 if (isNeg)
Reid Spencer9eec2412007-02-25 23:44:53 +00001726 str++, slen--;
Reid Spencer385f7542007-02-21 03:55:44 +00001727 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1728 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1729 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1730 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1731
1732 // Allocate memory
1733 if (!isSingleWord())
1734 pVal = getClearedMemory(getNumWords());
1735
1736 // Figure out if we can shift instead of multiply
1737 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1738
1739 // Set up an APInt for the digit to add outside the loop so we don't
1740 // constantly construct/destruct it.
1741 APInt apdigit(getBitWidth(), 0);
1742 APInt apradix(getBitWidth(), radix);
1743
1744 // Enter digit traversal loop
1745 for (unsigned i = 0; i < slen; i++) {
1746 // Get a digit
1747 uint32_t digit = 0;
1748 char cdigit = str[i];
1749 if (isdigit(cdigit))
1750 digit = cdigit - '0';
1751 else if (isxdigit(cdigit))
1752 if (cdigit >= 'a')
1753 digit = cdigit - 'a' + 10;
1754 else if (cdigit >= 'A')
1755 digit = cdigit - 'A' + 10;
1756 else
1757 assert(0 && "huh?");
1758 else
1759 assert(0 && "Invalid character in digit string");
1760
1761 // Shift or multiple the value by the radix
1762 if (shift)
1763 this->shl(shift);
1764 else
1765 *this *= apradix;
1766
1767 // Add in the digit we just interpreted
Reid Spencer5bce8542007-02-24 20:19:37 +00001768 if (apdigit.isSingleWord())
1769 apdigit.VAL = digit;
1770 else
1771 apdigit.pVal[0] = digit;
Reid Spencer385f7542007-02-21 03:55:44 +00001772 *this += apdigit;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001773 }
Reid Spencer9eec2412007-02-25 23:44:53 +00001774 // If its negative, put it in two's complement form
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001775 if (isNeg) {
1776 (*this)--;
Reid Spencer9eec2412007-02-25 23:44:53 +00001777 this->flip();
Reid Spencer9eec2412007-02-25 23:44:53 +00001778 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001779}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001780
Reid Spencer9c0696f2007-02-20 08:51:03 +00001781std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1782 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1783 "Radix should be 2, 8, 10, or 16!");
1784 static const char *digits[] = {
1785 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1786 };
1787 std::string result;
1788 uint32_t bits_used = getActiveBits();
1789 if (isSingleWord()) {
1790 char buf[65];
1791 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1792 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1793 if (format) {
1794 if (wantSigned) {
1795 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1796 (APINT_BITS_PER_WORD-BitWidth);
1797 sprintf(buf, format, sextVal);
1798 } else
1799 sprintf(buf, format, VAL);
1800 } else {
1801 memset(buf, 0, 65);
1802 uint64_t v = VAL;
1803 while (bits_used) {
1804 uint32_t bit = v & 1;
1805 bits_used--;
1806 buf[bits_used] = digits[bit][0];
1807 v >>=1;
1808 }
1809 }
1810 result = buf;
1811 return result;
1812 }
1813
1814 if (radix != 10) {
1815 uint64_t mask = radix - 1;
1816 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1817 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1818 for (uint32_t i = 0; i < getNumWords(); ++i) {
1819 uint64_t value = pVal[i];
1820 for (uint32_t j = 0; j < nibbles; ++j) {
1821 result.insert(0, digits[ value & mask ]);
1822 value >>= shift;
1823 }
1824 }
1825 return result;
1826 }
1827
1828 APInt tmp(*this);
1829 APInt divisor(4, radix);
1830 APInt zero(tmp.getBitWidth(), 0);
1831 size_t insert_at = 0;
1832 if (wantSigned && tmp[BitWidth-1]) {
1833 // They want to print the signed version and it is a negative value
1834 // Flip the bits and add one to turn it into the equivalent positive
1835 // value and put a '-' in the result.
1836 tmp.flip();
1837 tmp++;
1838 result = "-";
1839 insert_at = 1;
1840 }
Reid Spencere549c492007-02-21 00:29:48 +00001841 if (tmp == APInt(tmp.getBitWidth(), 0))
Reid Spencer9c0696f2007-02-20 08:51:03 +00001842 result = "0";
1843 else while (tmp.ne(zero)) {
1844 APInt APdigit(1,0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001845 APInt tmp2(tmp.getBitWidth(), 0);
Reid Spencer385f7542007-02-21 03:55:44 +00001846 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1847 &APdigit);
Reid Spencer794f4722007-02-26 21:02:27 +00001848 uint32_t digit = APdigit.getZExtValue();
Reid Spencer385f7542007-02-21 03:55:44 +00001849 assert(digit < radix && "divide failed");
1850 result.insert(insert_at,digits[digit]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001851 tmp = tmp2;
1852 }
1853
1854 return result;
1855}
1856
Reid Spencer385f7542007-02-21 03:55:44 +00001857#ifndef NDEBUG
1858void APInt::dump() const
1859{
Reid Spencer610fad82007-02-24 10:01:42 +00001860 cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
Reid Spencer385f7542007-02-21 03:55:44 +00001861 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +00001862 cerr << VAL;
Reid Spencer385f7542007-02-21 03:55:44 +00001863 else for (unsigned i = getNumWords(); i > 0; i--) {
Reid Spencer610fad82007-02-24 10:01:42 +00001864 cerr << pVal[i-1] << " ";
Reid Spencer385f7542007-02-21 03:55:44 +00001865 }
Reid Spencer681dcd12007-02-27 21:59:26 +00001866 cerr << " U(" << this->toString(10) << ") S(" << this->toStringSigned(10)
1867 << ")\n" << std::setbase(10);
Reid Spencer385f7542007-02-21 03:55:44 +00001868}
1869#endif