blob: 50b0dc34fea0576c527375a1c489b8062c3ecd19 [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"
Zhou Shenga3832fd2007-02-07 06:14:53 +000020#include <cstring>
Zhou Shengfd43dcf2007-02-06 03:00:16 +000021#include <cstdlib>
Reid Spencer385f7542007-02-21 03:55:44 +000022#ifndef NDEBUG
Reid Spencer385f7542007-02-21 03:55:44 +000023#include <iomanip>
24#endif
25
Zhou Shengfd43dcf2007-02-06 03:00:16 +000026using namespace llvm;
27
Reid Spencer5d0d05c2007-02-25 19:32:03 +000028/// A utility function for allocating memory, checking for allocation failures,
29/// and ensuring the contents are zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000030inline static uint64_t* getClearedMemory(uint32_t numWords) {
31 uint64_t * result = new uint64_t[numWords];
32 assert(result && "APInt memory allocation fails!");
33 memset(result, 0, numWords * sizeof(uint64_t));
34 return result;
Zhou Sheng353815d2007-02-06 06:04:53 +000035}
36
Reid Spencer5d0d05c2007-02-25 19:32:03 +000037/// A utility function for allocating memory and checking for allocation
38/// failure. The content is not zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000039inline static uint64_t* getMemory(uint32_t numWords) {
40 uint64_t * result = new uint64_t[numWords];
41 assert(result && "APInt memory allocation fails!");
42 return result;
43}
44
Reid Spencerf5c0fd92007-02-27 23:49:07 +000045APInt::APInt(uint32_t numBits, uint64_t val) : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000046 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
47 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Reid Spencer5d0d05c2007-02-25 19:32:03 +000048 if (isSingleWord())
49 VAL = val;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000050 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000051 pVal = getClearedMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000052 pVal[0] = val;
53 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +000054 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000055}
56
Reid Spenceraf0e9562007-02-18 18:38:44 +000057APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
Reid Spencer385f7542007-02-21 03:55:44 +000058 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000059 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
60 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000061 assert(bigVal && "Null pointer detected!");
62 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +000063 VAL = bigVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +000064 else {
Reid Spencer610fad82007-02-24 10:01:42 +000065 // Get memory, cleared to 0
66 pVal = getClearedMemory(getNumWords());
67 // Calculate the number of words to copy
68 uint32_t words = std::min<uint32_t>(numWords, getNumWords());
69 // Copy the words from bigVal to pVal
70 memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000071 }
Reid Spencer610fad82007-02-24 10:01:42 +000072 // Make sure unused high bits are cleared
73 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000074}
75
Reid Spenceraf0e9562007-02-18 18:38:44 +000076APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000077 uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000078 : BitWidth(numbits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000079 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000080}
81
Reid Spencer9c0696f2007-02-20 08:51:03 +000082APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000083 : BitWidth(numbits), VAL(0) {
Zhou Shenga3832fd2007-02-07 06:14:53 +000084 assert(!Val.empty() && "String empty?");
Reid Spencere81d2da2007-02-16 22:36:51 +000085 fromString(numbits, Val.c_str(), Val.size(), radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000086}
87
Reid Spencer54362ca2007-02-20 23:40:25 +000088APInt::APInt(const APInt& that)
Reid Spencer385f7542007-02-21 03:55:44 +000089 : BitWidth(that.BitWidth), VAL(0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +000090 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +000091 VAL = that.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000092 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000093 pVal = getMemory(getNumWords());
Reid Spencer54362ca2007-02-20 23:40:25 +000094 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000095 }
96}
97
98APInt::~APInt() {
Reid Spencer9c0696f2007-02-20 08:51:03 +000099 if (!isSingleWord() && pVal)
Reid Spencer9ac44112007-02-26 23:38:21 +0000100 delete [] pVal;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000101}
102
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000103APInt& APInt::operator=(const APInt& RHS) {
Reid Spencer9ac44112007-02-26 23:38:21 +0000104 // Don't do anything for X = X
105 if (this == &RHS)
106 return *this;
107
108 // If the bitwidths are the same, we can avoid mucking with memory
109 if (BitWidth == RHS.getBitWidth()) {
110 if (isSingleWord())
111 VAL = RHS.VAL;
112 else
113 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
114 return *this;
115 }
116
117 if (isSingleWord())
118 if (RHS.isSingleWord())
119 VAL = RHS.VAL;
120 else {
121 VAL = 0;
122 pVal = getMemory(RHS.getNumWords());
123 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
124 }
125 else if (getNumWords() == RHS.getNumWords())
126 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
127 else if (RHS.isSingleWord()) {
128 delete [] pVal;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000129 VAL = RHS.VAL;
Reid Spencer9ac44112007-02-26 23:38:21 +0000130 } else {
131 delete [] pVal;
132 pVal = getMemory(RHS.getNumWords());
133 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
134 }
135 BitWidth = RHS.BitWidth;
136 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000137}
138
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000139APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000140 if (isSingleWord())
141 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000142 else {
143 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000144 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000145 }
Reid Spencer9ac44112007-02-26 23:38:21 +0000146 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000147}
148
Reid Spenceraf0e9562007-02-18 18:38:44 +0000149/// add_1 - This function adds a single "digit" integer, y, to the multiple
150/// "digit" integer array, x[]. x[] is modified to reflect the addition and
151/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000152/// @returns the carry of the addition.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000153static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000154 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000155 dest[i] = y + x[i];
156 if (dest[i] < y)
Reid Spencer610fad82007-02-24 10:01:42 +0000157 y = 1; // Carry one to next digit.
Reid Spencerf2c521c2007-02-18 06:39:42 +0000158 else {
Reid Spencer610fad82007-02-24 10:01:42 +0000159 y = 0; // No need to carry so exit early
Reid Spencerf2c521c2007-02-18 06:39:42 +0000160 break;
161 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000162 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000163 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000164}
165
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000166/// @brief Prefix increment operator. Increments the APInt by one.
167APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000168 if (isSingleWord())
169 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000170 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000171 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000172 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000173}
174
Reid Spenceraf0e9562007-02-18 18:38:44 +0000175/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
176/// the multi-digit integer array, x[], propagating the borrowed 1 value until
177/// no further borrowing is neeeded or it runs out of "digits" in x. The result
178/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
179/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000180/// @returns the borrow out of the subtraction
181static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000182 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000183 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000184 x[i] -= y;
185 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000186 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000187 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000188 y = 0; // No need to borrow
189 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000190 }
191 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000192 return bool(y);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000193}
194
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000195/// @brief Prefix decrement operator. Decrements the APInt by one.
196APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000197 if (isSingleWord())
198 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000199 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000200 sub_1(pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000201 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000202}
203
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000204/// add - This function adds the integer array x to the integer array Y and
205/// places the result in dest.
206/// @returns the carry out from the addition
207/// @brief General addition of 64-bit integer arrays
Reid Spencer9d6c9192007-02-24 03:58:46 +0000208static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
209 uint32_t len) {
210 bool carry = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000211 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer92904632007-02-23 01:57:13 +0000212 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer54362ca2007-02-20 23:40:25 +0000213 dest[i] = x[i] + y[i] + carry;
Reid Spencer60c0a6a2007-02-21 05:44:56 +0000214 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000215 }
216 return carry;
217}
218
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000219/// Adds the RHS APint to this APInt.
220/// @returns this, after addition of RHS.
221/// @brief Addition assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000222APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000223 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000224 if (isSingleWord())
225 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000226 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000227 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000228 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000229 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000230}
231
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000232/// Subtracts the integer array y from the integer array x
233/// @returns returns the borrow out.
234/// @brief Generalized subtraction of 64-bit integer arrays.
Reid Spencer9d6c9192007-02-24 03:58:46 +0000235static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
236 uint32_t len) {
Reid Spencer385f7542007-02-21 03:55:44 +0000237 bool borrow = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000238 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer385f7542007-02-21 03:55:44 +0000239 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
240 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
241 dest[i] = x_tmp - y[i];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000242 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000243 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000244}
245
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000246/// Subtracts the RHS APInt from this APInt
247/// @returns this, after subtraction
248/// @brief Subtraction assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000249APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000250 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000251 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000252 VAL -= RHS.VAL;
253 else
254 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000255 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000256}
257
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000258/// Multiplies an integer array, x by a a uint64_t integer and places the result
259/// into dest.
260/// @returns the carry out of the multiplication.
261/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Reid Spencer610fad82007-02-24 10:01:42 +0000262static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
263 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer5e0a8512007-02-17 03:16:00 +0000264 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000265 uint64_t carry = 0;
266
267 // For each digit of x.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000268 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000269 // Split x into high and low words
270 uint64_t lx = x[i] & 0xffffffffULL;
271 uint64_t hx = x[i] >> 32;
272 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000273 // hasCarry == 0, no carry
274 // hasCarry == 1, has carry
275 // hasCarry == 2, no carry and the calculation result == 0.
276 uint8_t hasCarry = 0;
277 dest[i] = carry + lx * ly;
278 // Determine if the add above introduces carry.
279 hasCarry = (dest[i] < carry) ? 1 : 0;
280 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
281 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
282 // (2^32 - 1) + 2^32 = 2^64.
283 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
284
285 carry += (lx * hy) & 0xffffffffULL;
286 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
287 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
288 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
289 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000290 return carry;
291}
292
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000293/// Multiplies integer array x by integer array y and stores the result into
294/// the integer array dest. Note that dest's size must be >= xlen + ylen.
295/// @brief Generalized multiplicate of integer arrays.
Reid Spencer610fad82007-02-24 10:01:42 +0000296static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[],
297 uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000298 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000299 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000300 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencere0cdd332007-02-21 08:21:52 +0000301 uint64_t carry = 0, lx = 0, hx = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000302 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000303 lx = x[j] & 0xffffffffULL;
304 hx = x[j] >> 32;
305 // hasCarry - A flag to indicate if has carry.
306 // hasCarry == 0, no carry
307 // hasCarry == 1, has carry
308 // hasCarry == 2, no carry and the calculation result == 0.
309 uint8_t hasCarry = 0;
310 uint64_t resul = carry + lx * ly;
311 hasCarry = (resul < carry) ? 1 : 0;
312 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
313 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
314
315 carry += (lx * hy) & 0xffffffffULL;
316 resul = (carry << 32) | (resul & 0xffffffffULL);
317 dest[i+j] += resul;
318 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
319 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
320 ((lx * hy) >> 32) + hx * hy;
321 }
322 dest[i+xlen] = carry;
323 }
324}
325
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000326APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000327 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencere0cdd332007-02-21 08:21:52 +0000328 if (isSingleWord()) {
Reid Spencer61eb1802007-02-20 20:42:10 +0000329 VAL *= RHS.VAL;
Reid Spencere0cdd332007-02-21 08:21:52 +0000330 clearUnusedBits();
331 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000332 }
Reid Spencere0cdd332007-02-21 08:21:52 +0000333
334 // Get some bit facts about LHS and check for zero
335 uint32_t lhsBits = getActiveBits();
336 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
337 if (!lhsWords)
338 // 0 * X ===> 0
339 return *this;
340
341 // Get some bit facts about RHS and check for zero
342 uint32_t rhsBits = RHS.getActiveBits();
343 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
344 if (!rhsWords) {
345 // X * 0 ===> 0
346 clear();
347 return *this;
348 }
349
350 // Allocate space for the result
351 uint32_t destWords = rhsWords + lhsWords;
352 uint64_t *dest = getMemory(destWords);
353
354 // Perform the long multiply
355 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
356
357 // Copy result back into *this
358 clear();
359 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
360 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
361
362 // delete dest array and return
363 delete[] dest;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000364 return *this;
365}
366
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000367APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000368 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000369 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000370 VAL &= RHS.VAL;
371 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000372 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000373 uint32_t numWords = getNumWords();
374 for (uint32_t i = 0; i < numWords; ++i)
375 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000376 return *this;
377}
378
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000379APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000380 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000381 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000382 VAL |= RHS.VAL;
383 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000384 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000385 uint32_t numWords = getNumWords();
386 for (uint32_t i = 0; i < numWords; ++i)
387 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000388 return *this;
389}
390
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000391APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000392 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000393 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000394 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000395 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000396 return *this;
397 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000398 uint32_t numWords = getNumWords();
399 for (uint32_t i = 0; i < numWords; ++i)
400 pVal[i] ^= RHS.pVal[i];
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000401 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000402}
403
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000404APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000405 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000406 if (isSingleWord())
407 return APInt(getBitWidth(), VAL & RHS.VAL);
408
Reid Spenceraf0e9562007-02-18 18:38:44 +0000409 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000410 uint64_t* val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000411 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000412 val[i] = pVal[i] & RHS.pVal[i];
413 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000414}
415
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000416APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000417 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000418 if (isSingleWord())
419 return APInt(getBitWidth(), VAL | RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000420
Reid Spenceraf0e9562007-02-18 18:38:44 +0000421 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000422 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000423 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000424 val[i] = pVal[i] | RHS.pVal[i];
425 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000426}
427
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000428APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000429 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000430 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000431 return APInt(BitWidth, VAL ^ RHS.VAL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000432
Reid Spenceraf0e9562007-02-18 18:38:44 +0000433 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000434 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000435 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000436 val[i] = pVal[i] ^ RHS.pVal[i];
437
438 // 0^0==1 so clear the high bits in case they got set.
439 return APInt(val, getBitWidth()).clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000440}
441
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000442bool APInt::operator !() const {
443 if (isSingleWord())
444 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000445
446 for (uint32_t i = 0; i < getNumWords(); ++i)
447 if (pVal[i])
448 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000449 return true;
450}
451
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000452APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000453 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000454 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000455 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer61eb1802007-02-20 20:42:10 +0000456 APInt Result(*this);
457 Result *= RHS;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000458 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000459}
460
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000461APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000462 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000463 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000464 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000465 APInt Result(BitWidth, 0);
466 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000467 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000468}
469
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000470APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000471 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000472 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000473 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000474 APInt Result(BitWidth, 0);
475 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000476 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000477}
478
Reid Spenceraf0e9562007-02-18 18:38:44 +0000479bool APInt::operator[](uint32_t bitPosition) const {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000480 return (maskBit(bitPosition) &
481 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000482}
483
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000484bool APInt::operator==(const APInt& RHS) const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000485 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
Reid Spencer54362ca2007-02-20 23:40:25 +0000486 if (isSingleWord())
487 return VAL == RHS.VAL;
488
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000489 // Get some facts about the number of bits used in the two operands.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000490 uint32_t n1 = getActiveBits();
491 uint32_t n2 = RHS.getActiveBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000492
493 // If the number of bits isn't the same, they aren't equal
Reid Spencer54362ca2007-02-20 23:40:25 +0000494 if (n1 != n2)
495 return false;
496
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000497 // If the number of bits fits in a word, we only need to compare the low word.
Reid Spencer54362ca2007-02-20 23:40:25 +0000498 if (n1 <= APINT_BITS_PER_WORD)
499 return pVal[0] == RHS.pVal[0];
500
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000501 // Otherwise, compare everything
Reid Spencer54362ca2007-02-20 23:40:25 +0000502 for (int i = whichWord(n1 - 1); i >= 0; --i)
503 if (pVal[i] != RHS.pVal[i])
504 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000505 return true;
506}
507
Zhou Shenga3832fd2007-02-07 06:14:53 +0000508bool APInt::operator==(uint64_t Val) const {
509 if (isSingleWord())
510 return VAL == Val;
Reid Spencer54362ca2007-02-20 23:40:25 +0000511
512 uint32_t n = getActiveBits();
513 if (n <= APINT_BITS_PER_WORD)
514 return pVal[0] == Val;
515 else
516 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000517}
518
Reid Spencere81d2da2007-02-16 22:36:51 +0000519bool APInt::ult(const APInt& RHS) const {
520 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
521 if (isSingleWord())
522 return VAL < RHS.VAL;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000523
524 // Get active bit length of both operands
525 uint32_t n1 = getActiveBits();
526 uint32_t n2 = RHS.getActiveBits();
527
528 // If magnitude of LHS is less than RHS, return true.
529 if (n1 < n2)
530 return true;
531
532 // If magnitude of RHS is greather than LHS, return false.
533 if (n2 < n1)
534 return false;
535
536 // If they bot fit in a word, just compare the low order word
537 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
538 return pVal[0] < RHS.pVal[0];
539
540 // Otherwise, compare all words
Reid Spencer1fa111e2007-02-27 18:23:40 +0000541 uint32_t topWord = whichWord(std::max(n1,n2)-1);
542 for (int i = topWord; i >= 0; --i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000543 if (pVal[i] > RHS.pVal[i])
Reid Spencere81d2da2007-02-16 22:36:51 +0000544 return false;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000545 if (pVal[i] < RHS.pVal[i])
546 return true;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000547 }
548 return false;
549}
550
Reid Spencere81d2da2007-02-16 22:36:51 +0000551bool APInt::slt(const APInt& RHS) const {
552 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000553 if (isSingleWord()) {
554 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
555 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
556 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000557 }
Reid Spencera58f0582007-02-18 20:09:41 +0000558
559 APInt lhs(*this);
Reid Spencer1fa111e2007-02-27 18:23:40 +0000560 APInt rhs(RHS);
561 bool lhsNeg = isNegative();
562 bool rhsNeg = rhs.isNegative();
563 if (lhsNeg) {
564 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000565 lhs.flip();
566 lhs++;
567 }
Reid Spencer1fa111e2007-02-27 18:23:40 +0000568 if (rhsNeg) {
569 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000570 rhs.flip();
571 rhs++;
572 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000573
574 // Now we have unsigned values to compare so do the comparison if necessary
575 // based on the negativeness of the values.
Reid Spencer1fa111e2007-02-27 18:23:40 +0000576 if (lhsNeg)
577 if (rhsNeg)
578 return lhs.ugt(rhs);
Reid Spencera58f0582007-02-18 20:09:41 +0000579 else
580 return true;
Reid Spencer1fa111e2007-02-27 18:23:40 +0000581 else if (rhsNeg)
Reid Spencera58f0582007-02-18 20:09:41 +0000582 return false;
583 else
584 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000585}
586
Reid Spenceraf0e9562007-02-18 18:38:44 +0000587APInt& APInt::set(uint32_t bitPosition) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000588 if (isSingleWord())
589 VAL |= maskBit(bitPosition);
590 else
591 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000592 return *this;
593}
594
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000595APInt& APInt::set() {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000596 if (isSingleWord()) {
597 VAL = -1ULL;
598 return clearUnusedBits();
Zhou Shengb04973e2007-02-15 06:36:31 +0000599 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000600
601 // Set all the bits in all the words.
602 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
603 pVal[i] = -1ULL;
604 // Clear the unused ones
605 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000606}
607
608/// Set the given bit to 0 whose position is given as "bitPosition".
609/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000610APInt& APInt::clear(uint32_t bitPosition) {
611 if (isSingleWord())
612 VAL &= ~maskBit(bitPosition);
613 else
614 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000615 return *this;
616}
617
618/// @brief Set every bit to 0.
619APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000620 if (isSingleWord())
621 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000622 else
Reid Spencera58f0582007-02-18 20:09:41 +0000623 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000624 return *this;
625}
626
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000627/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
628/// this APInt.
629APInt APInt::operator~() const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000630 APInt Result(*this);
631 Result.flip();
632 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000633}
634
635/// @brief Toggle every bit to its opposite value.
636APInt& APInt::flip() {
Reid Spencer9eec2412007-02-25 23:44:53 +0000637 if (isSingleWord()) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000638 VAL ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000639 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000640 }
Reid Spencer9eec2412007-02-25 23:44:53 +0000641 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000642 pVal[i] ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000643 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000644}
645
646/// Toggle a given bit to its opposite value whose position is given
647/// as "bitPosition".
648/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000649APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000650 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000651 if ((*this)[bitPosition]) clear(bitPosition);
652 else set(bitPosition);
653 return *this;
654}
655
Reid Spencer794f4722007-02-26 21:02:27 +0000656uint64_t APInt::getHashValue() const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000657 // Put the bit width into the low order bits.
658 uint64_t hash = BitWidth;
Reid Spencer794f4722007-02-26 21:02:27 +0000659
660 // Add the sum of the words to the hash.
661 if (isSingleWord())
Reid Spencer9ac44112007-02-26 23:38:21 +0000662 hash += VAL << 6; // clear separation of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000663 else
664 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer9ac44112007-02-26 23:38:21 +0000665 hash += pVal[i] << 6; // clear sepration of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000666 return hash;
667}
668
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000669/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000670APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000671 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000672}
673
674/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000675APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000676 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
677 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000678}
679
Reid Spencere81d2da2007-02-16 22:36:51 +0000680bool APInt::isPowerOf2() const {
681 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
682}
683
Reid Spenceraf0e9562007-02-18 18:38:44 +0000684uint32_t APInt::countLeadingZeros() const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000685 uint32_t Count = 0;
Reid Spencere549c492007-02-21 00:29:48 +0000686 if (isSingleWord())
687 Count = CountLeadingZeros_64(VAL);
688 else {
689 for (uint32_t i = getNumWords(); i > 0u; --i) {
690 if (pVal[i-1] == 0)
691 Count += APINT_BITS_PER_WORD;
692 else {
693 Count += CountLeadingZeros_64(pVal[i-1]);
694 break;
695 }
696 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000697 }
Reid Spencerab2b2c82007-02-22 00:22:00 +0000698 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
699 if (remainder)
700 Count -= APINT_BITS_PER_WORD - remainder;
701 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000702}
703
Reid Spencer681dcd12007-02-27 21:59:26 +0000704static uint32_t countLeadingOnes_64(uint64_t V, uint32_t skip) {
705 uint32_t Count = 0;
706 if (skip)
707 V <<= skip;
708 while (V && (V & (1ULL << 63))) {
709 Count++;
710 V <<= 1;
711 }
712 return Count;
713}
714
715uint32_t APInt::countLeadingOnes() const {
716 if (isSingleWord())
717 return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth);
718
719 uint32_t highWordBits = BitWidth % APINT_BITS_PER_WORD;
720 uint32_t shift = (highWordBits == 0 ? 0 : APINT_BITS_PER_WORD - highWordBits);
721 int i = getNumWords() - 1;
722 uint32_t Count = countLeadingOnes_64(pVal[i], shift);
723 if (Count == highWordBits) {
724 for (i--; i >= 0; --i) {
725 if (pVal[i] == -1ULL)
726 Count += APINT_BITS_PER_WORD;
727 else {
728 Count += countLeadingOnes_64(pVal[i], 0);
729 break;
730 }
731 }
732 }
733 return Count;
734}
735
Reid Spenceraf0e9562007-02-18 18:38:44 +0000736uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000737 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000738 return CountTrailingZeros_64(VAL);
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000739 uint32_t Count = 0;
740 uint32_t i = 0;
741 for (; i < getNumWords() && pVal[i] == 0; ++i)
742 Count += APINT_BITS_PER_WORD;
743 if (i < getNumWords())
744 Count += CountTrailingZeros_64(pVal[i]);
745 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000746}
747
Reid Spenceraf0e9562007-02-18 18:38:44 +0000748uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000749 if (isSingleWord())
750 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000751 uint32_t Count = 0;
752 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000753 Count += CountPopulation_64(pVal[i]);
754 return Count;
755}
756
Reid Spencere81d2da2007-02-16 22:36:51 +0000757APInt APInt::byteSwap() const {
758 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
759 if (BitWidth == 16)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000760 return APInt(BitWidth, ByteSwap_16(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000761 else if (BitWidth == 32)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000762 return APInt(BitWidth, ByteSwap_32(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000763 else if (BitWidth == 48) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000764 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
765 Tmp1 = ByteSwap_32(Tmp1);
766 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
767 Tmp2 = ByteSwap_16(Tmp2);
768 return
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000769 APInt(BitWidth,
770 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
Reid Spencere81d2da2007-02-16 22:36:51 +0000771 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000772 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000773 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000774 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000775 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000776 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000777 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000778 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
779 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000780 }
781 return Result;
782 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000783}
784
Zhou Sheng0b706b12007-02-08 14:35:19 +0000785APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
786 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000787 APInt A = API1, B = API2;
788 while (!!B) {
789 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000790 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000791 A = T;
792 }
793 return A;
794}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000795
Reid Spencer1fa111e2007-02-27 18:23:40 +0000796APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, uint32_t width) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000797 union {
798 double D;
799 uint64_t I;
800 } T;
801 T.D = Double;
Reid Spencer30f44f32007-02-27 01:28:10 +0000802
803 // Get the sign bit from the highest order bit
Zhou Shengd93f00c2007-02-12 20:02:55 +0000804 bool isNeg = T.I >> 63;
Reid Spencer30f44f32007-02-27 01:28:10 +0000805
806 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd93f00c2007-02-12 20:02:55 +0000807 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer30f44f32007-02-27 01:28:10 +0000808
809 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000810 if (exp < 0)
Reid Spencerff605762007-02-28 01:30:08 +0000811 return APInt(width, 0u);
Reid Spencer30f44f32007-02-27 01:28:10 +0000812
813 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
814 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
815
816 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd93f00c2007-02-12 20:02:55 +0000817 if (exp < 52)
Reid Spencer1fa111e2007-02-27 18:23:40 +0000818 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
819 APInt(width, mantissa >> (52 - exp));
820
821 // If the client didn't provide enough bits for us to shift the mantissa into
822 // then the result is undefined, just return 0
823 if (width <= exp - 52)
824 return APInt(width, 0);
Reid Spencer30f44f32007-02-27 01:28:10 +0000825
826 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer1fa111e2007-02-27 18:23:40 +0000827 APInt Tmp(width, mantissa);
Reid Spencere81d2da2007-02-16 22:36:51 +0000828 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000829 return isNeg ? -Tmp : Tmp;
830}
831
Reid Spencerdb3faa62007-02-13 22:41:58 +0000832/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000833/// The layout for double is as following (IEEE Standard 754):
834/// --------------------------------------
835/// | Sign Exponent Fraction Bias |
836/// |-------------------------------------- |
837/// | 1[63] 11[62-52] 52[51-00] 1023 |
838/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000839double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000840
841 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000842 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
843 if (isSigned) {
844 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
845 return double(sext);
846 } else
847 return double(VAL);
848 }
849
Reid Spencer9c0696f2007-02-20 08:51:03 +0000850 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000851 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000852
853 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000854 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000855
856 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000857 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000858
Reid Spencer9c0696f2007-02-20 08:51:03 +0000859 // The exponent (without bias normalization) is just the number of bits
860 // we are using. Note that the sign bit is gone since we constructed the
861 // absolute value.
862 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000863
Reid Spencer9c0696f2007-02-20 08:51:03 +0000864 // Return infinity for exponent overflow
865 if (exp > 1023) {
866 if (!isSigned || !isNeg)
Reid Spencer61eb1802007-02-20 20:42:10 +0000867 return double(1.0E300 * 1.0E300); // positive infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000868 else
Reid Spencer61eb1802007-02-20 20:42:10 +0000869 return double(-1.0E300 * 1.0E300); // negative infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000870 }
871 exp += 1023; // Increment for 1023 bias
872
873 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
874 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000875 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000876 unsigned hiWord = whichWord(n-1);
877 if (hiWord == 0) {
878 mantissa = Tmp.pVal[0];
879 if (n > 52)
880 mantissa >>= n - 52; // shift down, we want the top 52 bits.
881 } else {
882 assert(hiWord > 0 && "huh?");
883 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
884 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
885 mantissa = hibits | lobits;
886 }
887
Zhou Shengd93f00c2007-02-12 20:02:55 +0000888 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000889 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000890 union {
891 double D;
892 uint64_t I;
893 } T;
894 T.I = sign | (exp << 52) | mantissa;
895 return T.D;
896}
897
Reid Spencere81d2da2007-02-16 22:36:51 +0000898// Truncate to new width.
Reid Spencer94900772007-02-28 17:34:32 +0000899APInt &APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000900 assert(width < BitWidth && "Invalid APInt Truncate request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000901 assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
902 uint32_t wordsBefore = getNumWords();
903 BitWidth = width;
904 uint32_t wordsAfter = getNumWords();
905 if (wordsBefore != wordsAfter) {
906 if (wordsAfter == 1) {
907 uint64_t *tmp = pVal;
908 VAL = pVal[0];
Reid Spencer9ac44112007-02-26 23:38:21 +0000909 delete [] tmp;
Reid Spencer9eec2412007-02-25 23:44:53 +0000910 } else {
911 uint64_t *newVal = getClearedMemory(wordsAfter);
912 for (uint32_t i = 0; i < wordsAfter; ++i)
913 newVal[i] = pVal[i];
Reid Spencer9ac44112007-02-26 23:38:21 +0000914 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000915 pVal = newVal;
916 }
917 }
Reid Spencer94900772007-02-28 17:34:32 +0000918 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000919}
920
921// Sign extend to a new width.
Reid Spencer94900772007-02-28 17:34:32 +0000922APInt &APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000923 assert(width > BitWidth && "Invalid APInt SignExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000924 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
Reid Spencer9eec2412007-02-25 23:44:53 +0000925 // If the sign bit isn't set, this is the same as zext.
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000926 if (!isNegative()) {
Reid Spencer9eec2412007-02-25 23:44:53 +0000927 zext(width);
Reid Spencer94900772007-02-28 17:34:32 +0000928 return *this;
Reid Spencer9eec2412007-02-25 23:44:53 +0000929 }
930
931 // The sign bit is set. First, get some facts
932 uint32_t wordsBefore = getNumWords();
933 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
934 BitWidth = width;
935 uint32_t wordsAfter = getNumWords();
936
937 // Mask the high order word appropriately
938 if (wordsBefore == wordsAfter) {
939 uint32_t newWordBits = width % APINT_BITS_PER_WORD;
940 // The extension is contained to the wordsBefore-1th word.
941 uint64_t mask = (~0ULL >> (APINT_BITS_PER_WORD - newWordBits)) << wordBits;
942 if (wordsBefore == 1)
943 VAL |= mask;
944 else
945 pVal[wordsBefore-1] |= mask;
946 clearUnusedBits();
Reid Spencer94900772007-02-28 17:34:32 +0000947 return *this;
Reid Spencer9eec2412007-02-25 23:44:53 +0000948 }
949
Reid Spencerf30b1882007-02-25 23:54:00 +0000950 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +0000951 uint64_t *newVal = getMemory(wordsAfter);
952 if (wordsBefore == 1)
953 newVal[0] = VAL | mask;
954 else {
955 for (uint32_t i = 0; i < wordsBefore; ++i)
956 newVal[i] = pVal[i];
957 newVal[wordsBefore-1] |= mask;
958 }
959 for (uint32_t i = wordsBefore; i < wordsAfter; i++)
960 newVal[i] = -1ULL;
961 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +0000962 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000963 pVal = newVal;
Reid Spencer94900772007-02-28 17:34:32 +0000964 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000965}
966
967// Zero extend to a new width.
Reid Spencer94900772007-02-28 17:34:32 +0000968APInt &APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000969 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000970 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
971 uint32_t wordsBefore = getNumWords();
972 BitWidth = width;
973 uint32_t wordsAfter = getNumWords();
974 if (wordsBefore != wordsAfter) {
975 uint64_t *newVal = getClearedMemory(wordsAfter);
976 if (wordsBefore == 1)
977 newVal[0] = VAL;
978 else
979 for (uint32_t i = 0; i < wordsBefore; ++i)
980 newVal[i] = pVal[i];
981 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +0000982 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000983 pVal = newVal;
984 }
Reid Spencer94900772007-02-28 17:34:32 +0000985 return *this;
Reid Spencere81d2da2007-02-16 22:36:51 +0000986}
987
Reid Spencer68e23002007-03-01 17:15:32 +0000988APInt &APInt::zextOrTrunc(uint32_t width) {
989 if (BitWidth < width)
990 return zext(width);
991 if (BitWidth > width)
992 return trunc(width);
993 return *this;
994}
995
996APInt &APInt::sextOrTrunc(uint32_t width) {
997 if (BitWidth < width)
998 return sext(width);
999 if (BitWidth > width)
1000 return trunc(width);
1001 return *this;
1002}
1003
Zhou Shengff4304f2007-02-09 07:48:24 +00001004/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001005/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001006APInt APInt::ashr(uint32_t shiftAmt) const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001007 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001008 if (isSingleWord()) {
1009 if (shiftAmt == BitWidth)
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001010 return APInt(BitWidth, 0); // undefined
1011 else {
1012 uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001013 return APInt(BitWidth,
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001014 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1015 }
Zhou Sheng0b706b12007-02-08 14:35:19 +00001016 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001017
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001018 // If all the bits were shifted out, the result is 0 or -1. This avoids issues
1019 // with shifting by the size of the integer type, which produces undefined
1020 // results.
1021 if (shiftAmt == BitWidth)
1022 if (isNegative())
1023 return APInt(BitWidth, -1ULL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001024 else
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001025 return APInt(BitWidth, 0);
1026
1027 // Create some space for the result.
1028 uint64_t * val = new uint64_t[getNumWords()];
1029
1030 // If we are shifting less than a word, compute the shift with a simple carry
1031 if (shiftAmt < APINT_BITS_PER_WORD) {
1032 uint64_t carry = 0;
1033 for (int i = getNumWords()-1; i >= 0; --i) {
Reid Spenceraf8fb192007-03-01 05:39:56 +00001034 val[i] = (pVal[i] >> shiftAmt) | carry;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001035 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1036 }
1037 return APInt(val, BitWidth).clearUnusedBits();
1038 }
1039
1040 // Compute some values needed by the remaining shift algorithms
1041 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1042 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1043
1044 // If we are shifting whole words, just move whole words
1045 if (wordShift == 0) {
1046 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1047 val[i] = pVal[i+offset];
1048 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1049 val[i] = (isNegative() ? -1ULL : 0);
1050 return APInt(val,BitWidth).clearUnusedBits();
1051 }
1052
1053 // Shift the low order words
1054 uint32_t breakWord = getNumWords() - offset -1;
1055 for (uint32_t i = 0; i < breakWord; ++i)
Reid Spenceraf8fb192007-03-01 05:39:56 +00001056 val[i] = (pVal[i+offset] >> wordShift) |
1057 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001058 // Shift the break word.
1059 uint32_t SignBit = APINT_BITS_PER_WORD - (BitWidth % APINT_BITS_PER_WORD);
1060 val[breakWord] = uint64_t(
1061 (((int64_t(pVal[breakWord+offset]) << SignBit) >> SignBit) >> wordShift));
1062
1063 // Remaining words are 0 or -1
1064 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1065 val[i] = (isNegative() ? -1ULL : 0);
1066 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001067}
1068
Zhou Shengff4304f2007-02-09 07:48:24 +00001069/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001070/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001071APInt APInt::lshr(uint32_t shiftAmt) const {
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001072 if (isSingleWord())
1073 if (shiftAmt == BitWidth)
1074 return APInt(BitWidth, 0);
1075 else
1076 return APInt(BitWidth, this->VAL >> shiftAmt);
1077
Reid Spencerba81c2b2007-02-26 01:19:48 +00001078 // If all the bits were shifted out, the result is 0. This avoids issues
1079 // with shifting by the size of the integer type, which produces undefined
1080 // results. We define these "undefined results" to always be 0.
1081 if (shiftAmt == BitWidth)
1082 return APInt(BitWidth, 0);
1083
1084 // Create some space for the result.
1085 uint64_t * val = new uint64_t[getNumWords()];
1086
1087 // If we are shifting less than a word, compute the shift with a simple carry
1088 if (shiftAmt < APINT_BITS_PER_WORD) {
1089 uint64_t carry = 0;
1090 for (int i = getNumWords()-1; i >= 0; --i) {
Reid Spenceraf8fb192007-03-01 05:39:56 +00001091 val[i] = (pVal[i] >> shiftAmt) | carry;
Reid Spencerba81c2b2007-02-26 01:19:48 +00001092 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1093 }
1094 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001095 }
1096
Reid Spencerba81c2b2007-02-26 01:19:48 +00001097 // Compute some values needed by the remaining shift algorithms
1098 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1099 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1100
1101 // If we are shifting whole words, just move whole words
1102 if (wordShift == 0) {
1103 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1104 val[i] = pVal[i+offset];
1105 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1106 val[i] = 0;
1107 return APInt(val,BitWidth).clearUnusedBits();
1108 }
1109
1110 // Shift the low order words
1111 uint32_t breakWord = getNumWords() - offset -1;
1112 for (uint32_t i = 0; i < breakWord; ++i)
Reid Spenceraf8fb192007-03-01 05:39:56 +00001113 val[i] = (pVal[i+offset] >> wordShift) |
1114 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencerba81c2b2007-02-26 01:19:48 +00001115 // Shift the break word.
1116 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1117
1118 // Remaining words are 0
1119 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1120 val[i] = 0;
1121 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001122}
1123
Zhou Shengff4304f2007-02-09 07:48:24 +00001124/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001125/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001126APInt APInt::shl(uint32_t shiftAmt) const {
Reid Spencer5bce8542007-02-24 20:19:37 +00001127 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer87553802007-02-25 00:56:44 +00001128 if (isSingleWord()) {
Reid Spencer5bce8542007-02-24 20:19:37 +00001129 if (shiftAmt == BitWidth)
Reid Spencer87553802007-02-25 00:56:44 +00001130 return APInt(BitWidth, 0); // avoid undefined shift results
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001131 return APInt(BitWidth, VAL << shiftAmt);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001132 }
Reid Spencer5bce8542007-02-24 20:19:37 +00001133
Reid Spencer87553802007-02-25 00:56:44 +00001134 // If all the bits were shifted out, the result is 0. This avoids issues
1135 // with shifting by the size of the integer type, which produces undefined
1136 // results. We define these "undefined results" to always be 0.
1137 if (shiftAmt == BitWidth)
1138 return APInt(BitWidth, 0);
1139
1140 // Create some space for the result.
1141 uint64_t * val = new uint64_t[getNumWords()];
1142
1143 // If we are shifting less than a word, do it the easy way
1144 if (shiftAmt < APINT_BITS_PER_WORD) {
1145 uint64_t carry = 0;
Reid Spencer87553802007-02-25 00:56:44 +00001146 for (uint32_t i = 0; i < getNumWords(); i++) {
1147 val[i] = pVal[i] << shiftAmt | carry;
1148 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1149 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001150 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001151 }
1152
Reid Spencer87553802007-02-25 00:56:44 +00001153 // Compute some values needed by the remaining shift algorithms
1154 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1155 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1156
1157 // If we are shifting whole words, just move whole words
1158 if (wordShift == 0) {
1159 for (uint32_t i = 0; i < offset; i++)
1160 val[i] = 0;
1161 for (uint32_t i = offset; i < getNumWords(); i++)
1162 val[i] = pVal[i-offset];
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001163 return APInt(val,BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001164 }
Reid Spencer87553802007-02-25 00:56:44 +00001165
1166 // Copy whole words from this to Result.
1167 uint32_t i = getNumWords() - 1;
1168 for (; i > offset; --i)
1169 val[i] = pVal[i-offset] << wordShift |
1170 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencer438d71e2007-02-25 01:08:58 +00001171 val[offset] = pVal[0] << wordShift;
Reid Spencer87553802007-02-25 00:56:44 +00001172 for (i = 0; i < offset; ++i)
1173 val[i] = 0;
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001174 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001175}
1176
Reid Spenceraf8fb192007-03-01 05:39:56 +00001177
1178// Square Root - this method computes and returns the square root of "this".
1179// Three mechanisms are used for computation. For small values (<= 5 bits),
1180// a table lookup is done. This gets some performance for common cases. For
1181// values using less than 52 bits, the value is converted to double and then
1182// the libc sqrt function is called. The result is rounded and then converted
1183// back to a uint64_t which is then used to construct the result. Finally,
1184// the Babylonian method for computing square roots is used.
1185APInt APInt::sqrt() const {
1186
1187 // Determine the magnitude of the value.
1188 uint32_t magnitude = getActiveBits();
1189
1190 // Use a fast table for some small values. This also gets rid of some
1191 // rounding errors in libc sqrt for small values.
1192 if (magnitude <= 5) {
Reid Spencerb5ca2cd2007-03-01 06:23:32 +00001193 static uint8_t results[32] = {
1194 /* 0 */ 0,
1195 /* 1- 2 */ 1, 1,
1196 /* 3- 6 */ 2, 2, 2, 2,
1197 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1198 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1199 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1200 /* 31 */ 6
1201 };
1202 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spenceraf8fb192007-03-01 05:39:56 +00001203 }
1204
1205 // If the magnitude of the value fits in less than 52 bits (the precision of
1206 // an IEEE double precision floating point value), then we can use the
1207 // libc sqrt function which will probably use a hardware sqrt computation.
1208 // This should be faster than the algorithm below.
1209 if (magnitude < 52)
1210 return APInt(BitWidth,
1211 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
1212
1213 // Okay, all the short cuts are exhausted. We must compute it. The following
1214 // is a classical Babylonian method for computing the square root. This code
1215 // was adapted to APINt from a wikipedia article on such computations.
1216 // See http://www.wikipedia.org/ and go to the page named
1217 // Calculate_an_integer_square_root.
1218 uint32_t nbits = BitWidth, i = 4;
1219 APInt testy(BitWidth, 16);
1220 APInt x_old(BitWidth, 1);
1221 APInt x_new(BitWidth, 0);
1222 APInt two(BitWidth, 2);
1223
1224 // Select a good starting value using binary logarithms.
1225 for (;; i += 2, testy = testy.shl(2))
1226 if (i >= nbits || this->ule(testy)) {
1227 x_old = x_old.shl(i / 2);
1228 break;
1229 }
1230
1231 // Use the Babylonian method to arrive at the integer square root:
1232 for (;;) {
1233 x_new = (this->udiv(x_old) + x_old).udiv(two);
1234 if (x_old.ule(x_new))
1235 break;
1236 x_old = x_new;
1237 }
1238
1239 // Make sure we return the closest approximation
1240 APInt square(x_old * x_old);
1241 APInt nextSquare((x_old + 1) * (x_old +1));
1242 if (this->ult(square))
1243 return x_old;
1244 else if (this->ule(nextSquare))
1245 if ((nextSquare - *this).ult(*this - square))
1246 return x_old + 1;
1247 else
1248 return x_old;
1249 else
1250 assert(0 && "Error in APInt::sqrt computation");
1251 return x_old + 1;
1252}
1253
Reid Spencer9c0696f2007-02-20 08:51:03 +00001254/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1255/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1256/// variables here have the same names as in the algorithm. Comments explain
1257/// the algorithm and any deviation from it.
1258static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1259 uint32_t m, uint32_t n) {
1260 assert(u && "Must provide dividend");
1261 assert(v && "Must provide divisor");
1262 assert(q && "Must provide quotient");
Reid Spencer9d6c9192007-02-24 03:58:46 +00001263 assert(u != v && u != q && v != q && "Must us different memory");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001264 assert(n>1 && "n must be > 1");
1265
1266 // Knuth uses the value b as the base of the number system. In our case b
1267 // is 2^31 so we just set it to -1u.
1268 uint64_t b = uint64_t(1) << 32;
1269
Reid Spencer9d6c9192007-02-24 03:58:46 +00001270 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1271 DEBUG(cerr << "KnuthDiv: original:");
1272 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1273 DEBUG(cerr << " by");
1274 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1275 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001276 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1277 // u and v by d. Note that we have taken Knuth's advice here to use a power
1278 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1279 // 2 allows us to shift instead of multiply and it is easy to determine the
1280 // shift amount from the leading zeros. We are basically normalizing the u
1281 // and v so that its high bits are shifted to the top of v's range without
1282 // overflow. Note that this can require an extra word in u so that u must
1283 // be of length m+n+1.
1284 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1285 uint32_t v_carry = 0;
1286 uint32_t u_carry = 0;
1287 if (shift) {
1288 for (uint32_t i = 0; i < m+n; ++i) {
1289 uint32_t u_tmp = u[i] >> (32 - shift);
1290 u[i] = (u[i] << shift) | u_carry;
1291 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001292 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001293 for (uint32_t i = 0; i < n; ++i) {
1294 uint32_t v_tmp = v[i] >> (32 - shift);
1295 v[i] = (v[i] << shift) | v_carry;
1296 v_carry = v_tmp;
1297 }
1298 }
1299 u[m+n] = u_carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001300 DEBUG(cerr << "KnuthDiv: normal:");
1301 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1302 DEBUG(cerr << " by");
1303 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1304 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001305
1306 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1307 int j = m;
1308 do {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001309 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001310 // D3. [Calculate q'.].
1311 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1312 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1313 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1314 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1315 // on v[n-2] determines at high speed most of the cases in which the trial
1316 // value qp is one too large, and it eliminates all cases where qp is two
1317 // too large.
Reid Spencer92904632007-02-23 01:57:13 +00001318 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001319 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencer92904632007-02-23 01:57:13 +00001320 uint64_t qp = dividend / v[n-1];
1321 uint64_t rp = dividend % v[n-1];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001322 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1323 qp--;
1324 rp += v[n-1];
Reid Spencer610fad82007-02-24 10:01:42 +00001325 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencer9d6c9192007-02-24 03:58:46 +00001326 qp--;
Reid Spencer92904632007-02-23 01:57:13 +00001327 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001328 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001329
Reid Spencer92904632007-02-23 01:57:13 +00001330 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1331 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1332 // consists of a simple multiplication by a one-place number, combined with
Reid Spencer610fad82007-02-24 10:01:42 +00001333 // a subtraction.
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001334 bool isNeg = false;
Reid Spencer92904632007-02-23 01:57:13 +00001335 for (uint32_t i = 0; i < n; ++i) {
Reid Spencer610fad82007-02-24 10:01:42 +00001336 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001337 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
Reid Spencer610fad82007-02-24 10:01:42 +00001338 bool borrow = subtrahend > u_tmp;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001339 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
Reid Spencer610fad82007-02-24 10:01:42 +00001340 << ", subtrahend == " << subtrahend
1341 << ", borrow = " << borrow << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001342
Reid Spencer610fad82007-02-24 10:01:42 +00001343 uint64_t result = u_tmp - subtrahend;
1344 uint32_t k = j + i;
1345 u[k++] = result & (b-1); // subtract low word
1346 u[k++] = result >> 32; // subtract high word
1347 while (borrow && k <= m+n) { // deal with borrow to the left
1348 borrow = u[k] == 0;
1349 u[k]--;
1350 k++;
1351 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001352 isNeg |= borrow;
Reid Spencer610fad82007-02-24 10:01:42 +00001353 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1354 u[j+i+1] << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001355 }
1356 DEBUG(cerr << "KnuthDiv: after subtraction:");
1357 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1358 DEBUG(cerr << '\n');
Reid Spencer610fad82007-02-24 10:01:42 +00001359 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1360 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1361 // true value plus b**(n+1), namely as the b's complement of
Reid Spencer92904632007-02-23 01:57:13 +00001362 // the true value, and a "borrow" to the left should be remembered.
1363 //
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001364 if (isNeg) {
Reid Spencer610fad82007-02-24 10:01:42 +00001365 bool carry = true; // true because b's complement is "complement + 1"
1366 for (uint32_t i = 0; i <= m+n; ++i) {
1367 u[i] = ~u[i] + carry; // b's complement
1368 carry = carry && u[i] == 0;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001369 }
Reid Spencer92904632007-02-23 01:57:13 +00001370 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001371 DEBUG(cerr << "KnuthDiv: after complement:");
1372 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1373 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001374
1375 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1376 // negative, go to step D6; otherwise go on to step D7.
1377 q[j] = qp;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001378 if (isNeg) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001379 // D6. [Add back]. The probability that this step is necessary is very
1380 // small, on the order of only 2/b. Make sure that test data accounts for
Reid Spencer92904632007-02-23 01:57:13 +00001381 // this possibility. Decrease q[j] by 1
1382 q[j]--;
1383 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1384 // A carry will occur to the left of u[j+n], and it should be ignored
1385 // since it cancels with the borrow that occurred in D4.
1386 bool carry = false;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001387 for (uint32_t i = 0; i < n; i++) {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001388 uint32_t limit = std::min(u[j+i],v[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001389 u[j+i] += v[i] + carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001390 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001391 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001392 u[j+n] += carry;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001393 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001394 DEBUG(cerr << "KnuthDiv: after correction:");
1395 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1396 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001397
Reid Spencer92904632007-02-23 01:57:13 +00001398 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1399 } while (--j >= 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001400
Reid Spencer9d6c9192007-02-24 03:58:46 +00001401 DEBUG(cerr << "KnuthDiv: quotient:");
1402 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1403 DEBUG(cerr << '\n');
1404
Reid Spencer9c0696f2007-02-20 08:51:03 +00001405 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1406 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1407 // compute the remainder (urem uses this).
1408 if (r) {
1409 // The value d is expressed by the "shift" value above since we avoided
1410 // multiplication by d by using a shift left. So, all we have to do is
1411 // shift right here. In order to mak
Reid Spencer1050ec52007-02-24 20:38:01 +00001412 if (shift) {
1413 uint32_t carry = 0;
1414 DEBUG(cerr << "KnuthDiv: remainder:");
1415 for (int i = n-1; i >= 0; i--) {
1416 r[i] = (u[i] >> shift) | carry;
1417 carry = u[i] << (32 - shift);
1418 DEBUG(cerr << " " << r[i]);
1419 }
1420 } else {
1421 for (int i = n-1; i >= 0; i--) {
1422 r[i] = u[i];
1423 DEBUG(cerr << " " << r[i]);
1424 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001425 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001426 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001427 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001428 DEBUG(cerr << std::setbase(10) << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001429}
1430
Reid Spencer9c0696f2007-02-20 08:51:03 +00001431void APInt::divide(const APInt LHS, uint32_t lhsWords,
1432 const APInt &RHS, uint32_t rhsWords,
1433 APInt *Quotient, APInt *Remainder)
1434{
1435 assert(lhsWords >= rhsWords && "Fractional result");
1436
1437 // First, compose the values into an array of 32-bit words instead of
1438 // 64-bit words. This is a necessity of both the "short division" algorithm
1439 // and the the Knuth "classical algorithm" which requires there to be native
1440 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1441 // can't use 64-bit operands here because we don't have native results of
1442 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1443 // work on large-endian machines.
1444 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1445 uint32_t n = rhsWords * 2;
1446 uint32_t m = (lhsWords * 2) - n;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001447
1448 // Allocate space for the temporary values we need either on the stack, if
1449 // it will fit, or on the heap if it won't.
1450 uint32_t SPACE[128];
1451 uint32_t *U = 0;
1452 uint32_t *V = 0;
1453 uint32_t *Q = 0;
1454 uint32_t *R = 0;
1455 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1456 U = &SPACE[0];
1457 V = &SPACE[m+n+1];
1458 Q = &SPACE[(m+n+1) + n];
1459 if (Remainder)
1460 R = &SPACE[(m+n+1) + n + (m+n)];
1461 } else {
1462 U = new uint32_t[m + n + 1];
1463 V = new uint32_t[n];
1464 Q = new uint32_t[m+n];
1465 if (Remainder)
1466 R = new uint32_t[n];
1467 }
1468
1469 // Initialize the dividend
Reid Spencer9c0696f2007-02-20 08:51:03 +00001470 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1471 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001472 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001473 U[i * 2] = tmp & mask;
1474 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1475 }
1476 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1477
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001478 // Initialize the divisor
Reid Spencer9c0696f2007-02-20 08:51:03 +00001479 memset(V, 0, (n)*sizeof(uint32_t));
1480 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001481 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001482 V[i * 2] = tmp & mask;
1483 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1484 }
1485
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001486 // initialize the quotient and remainder
Reid Spencer9c0696f2007-02-20 08:51:03 +00001487 memset(Q, 0, (m+n) * sizeof(uint32_t));
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001488 if (Remainder)
Reid Spencer9c0696f2007-02-20 08:51:03 +00001489 memset(R, 0, n * sizeof(uint32_t));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001490
1491 // Now, adjust m and n for the Knuth division. n is the number of words in
1492 // the divisor. m is the number of words by which the dividend exceeds the
1493 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1494 // contain any zero words or the Knuth algorithm fails.
1495 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1496 n--;
1497 m++;
1498 }
1499 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1500 m--;
1501
1502 // If we're left with only a single word for the divisor, Knuth doesn't work
1503 // so we implement the short division algorithm here. This is much simpler
1504 // and faster because we are certain that we can divide a 64-bit quantity
1505 // by a 32-bit quantity at hardware speed and short division is simply a
1506 // series of such operations. This is just like doing short division but we
1507 // are using base 2^32 instead of base 10.
1508 assert(n != 0 && "Divide by zero?");
1509 if (n == 1) {
1510 uint32_t divisor = V[0];
1511 uint32_t remainder = 0;
1512 for (int i = m+n-1; i >= 0; i--) {
1513 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1514 if (partial_dividend == 0) {
1515 Q[i] = 0;
1516 remainder = 0;
1517 } else if (partial_dividend < divisor) {
1518 Q[i] = 0;
1519 remainder = partial_dividend;
1520 } else if (partial_dividend == divisor) {
1521 Q[i] = 1;
1522 remainder = 0;
1523 } else {
1524 Q[i] = partial_dividend / divisor;
1525 remainder = partial_dividend - (Q[i] * divisor);
1526 }
1527 }
1528 if (R)
1529 R[0] = remainder;
1530 } else {
1531 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1532 // case n > 1.
1533 KnuthDiv(U, V, Q, R, m, n);
1534 }
1535
1536 // If the caller wants the quotient
1537 if (Quotient) {
1538 // Set up the Quotient value's memory.
1539 if (Quotient->BitWidth != LHS.BitWidth) {
1540 if (Quotient->isSingleWord())
1541 Quotient->VAL = 0;
1542 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001543 delete [] Quotient->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001544 Quotient->BitWidth = LHS.BitWidth;
1545 if (!Quotient->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001546 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001547 } else
1548 Quotient->clear();
1549
1550 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1551 // order words.
1552 if (lhsWords == 1) {
1553 uint64_t tmp =
1554 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1555 if (Quotient->isSingleWord())
1556 Quotient->VAL = tmp;
1557 else
1558 Quotient->pVal[0] = tmp;
1559 } else {
1560 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1561 for (unsigned i = 0; i < lhsWords; ++i)
1562 Quotient->pVal[i] =
1563 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1564 }
1565 }
1566
1567 // If the caller wants the remainder
1568 if (Remainder) {
1569 // Set up the Remainder value's memory.
1570 if (Remainder->BitWidth != RHS.BitWidth) {
1571 if (Remainder->isSingleWord())
1572 Remainder->VAL = 0;
1573 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001574 delete [] Remainder->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001575 Remainder->BitWidth = RHS.BitWidth;
1576 if (!Remainder->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001577 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001578 } else
1579 Remainder->clear();
1580
1581 // The remainder is in R. Reconstitute the remainder into Remainder's low
1582 // order words.
1583 if (rhsWords == 1) {
1584 uint64_t tmp =
1585 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1586 if (Remainder->isSingleWord())
1587 Remainder->VAL = tmp;
1588 else
1589 Remainder->pVal[0] = tmp;
1590 } else {
1591 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1592 for (unsigned i = 0; i < rhsWords; ++i)
1593 Remainder->pVal[i] =
1594 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1595 }
1596 }
1597
1598 // Clean up the memory we allocated.
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001599 if (U != &SPACE[0]) {
1600 delete [] U;
1601 delete [] V;
1602 delete [] Q;
1603 delete [] R;
1604 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001605}
1606
Reid Spencere81d2da2007-02-16 22:36:51 +00001607APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001608 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001609
1610 // First, deal with the easy case
1611 if (isSingleWord()) {
1612 assert(RHS.VAL != 0 && "Divide by zero?");
1613 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001614 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001615
Reid Spencer71bd08f2007-02-17 02:07:07 +00001616 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001617 uint32_t rhsBits = RHS.getActiveBits();
1618 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001619 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001620 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001621 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001622
1623 // Deal with some degenerate cases
1624 if (!lhsWords)
Reid Spencere0cdd332007-02-21 08:21:52 +00001625 // 0 / X ===> 0
1626 return APInt(BitWidth, 0);
1627 else if (lhsWords < rhsWords || this->ult(RHS)) {
1628 // X / Y ===> 0, iff X < Y
1629 return APInt(BitWidth, 0);
1630 } else if (*this == RHS) {
1631 // X / X ===> 1
1632 return APInt(BitWidth, 1);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001633 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001634 // All high words are zero, just use native divide
Reid Spencere0cdd332007-02-21 08:21:52 +00001635 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001636 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001637
1638 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1639 APInt Quotient(1,0); // to hold result.
1640 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1641 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001642}
1643
Reid Spencere81d2da2007-02-16 22:36:51 +00001644APInt APInt::urem(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 if (isSingleWord()) {
1647 assert(RHS.VAL != 0 && "Remainder by zero?");
1648 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001649 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001650
Reid Spencere0cdd332007-02-21 08:21:52 +00001651 // Get some facts about the LHS
1652 uint32_t lhsBits = getActiveBits();
1653 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001654
1655 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001656 uint32_t rhsBits = RHS.getActiveBits();
1657 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001658 assert(rhsWords && "Performing remainder operation by zero ???");
1659
Reid Spencer71bd08f2007-02-17 02:07:07 +00001660 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001661 if (lhsWords == 0) {
Reid Spencere0cdd332007-02-21 08:21:52 +00001662 // 0 % Y ===> 0
1663 return APInt(BitWidth, 0);
1664 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1665 // X % Y ===> X, iff X < Y
1666 return *this;
1667 } else if (*this == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001668 // X % X == 0;
Reid Spencere0cdd332007-02-21 08:21:52 +00001669 return APInt(BitWidth, 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001670 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001671 // All high words are zero, just use native remainder
Reid Spencere0cdd332007-02-21 08:21:52 +00001672 return APInt(BitWidth, 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 Knute divide algorithm.
1676 APInt Remainder(1,0);
1677 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1678 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001679}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001680
Reid Spencer385f7542007-02-21 03:55:44 +00001681void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001682 uint8_t radix) {
Reid Spencer385f7542007-02-21 03:55:44 +00001683 // Check our assumptions here
Reid Spencer5e0a8512007-02-17 03:16:00 +00001684 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1685 "Radix should be 2, 8, 10, or 16!");
Reid Spencer385f7542007-02-21 03:55:44 +00001686 assert(str && "String is null?");
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001687 bool isNeg = str[0] == '-';
1688 if (isNeg)
Reid Spencer9eec2412007-02-25 23:44:53 +00001689 str++, slen--;
Reid Spencer385f7542007-02-21 03:55:44 +00001690 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1691 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1692 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1693 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1694
1695 // Allocate memory
1696 if (!isSingleWord())
1697 pVal = getClearedMemory(getNumWords());
1698
1699 // Figure out if we can shift instead of multiply
1700 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1701
1702 // Set up an APInt for the digit to add outside the loop so we don't
1703 // constantly construct/destruct it.
1704 APInt apdigit(getBitWidth(), 0);
1705 APInt apradix(getBitWidth(), radix);
1706
1707 // Enter digit traversal loop
1708 for (unsigned i = 0; i < slen; i++) {
1709 // Get a digit
1710 uint32_t digit = 0;
1711 char cdigit = str[i];
1712 if (isdigit(cdigit))
1713 digit = cdigit - '0';
1714 else if (isxdigit(cdigit))
1715 if (cdigit >= 'a')
1716 digit = cdigit - 'a' + 10;
1717 else if (cdigit >= 'A')
1718 digit = cdigit - 'A' + 10;
1719 else
1720 assert(0 && "huh?");
1721 else
1722 assert(0 && "Invalid character in digit string");
1723
1724 // Shift or multiple the value by the radix
1725 if (shift)
1726 this->shl(shift);
1727 else
1728 *this *= apradix;
1729
1730 // Add in the digit we just interpreted
Reid Spencer5bce8542007-02-24 20:19:37 +00001731 if (apdigit.isSingleWord())
1732 apdigit.VAL = digit;
1733 else
1734 apdigit.pVal[0] = digit;
Reid Spencer385f7542007-02-21 03:55:44 +00001735 *this += apdigit;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001736 }
Reid Spencer9eec2412007-02-25 23:44:53 +00001737 // If its negative, put it in two's complement form
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001738 if (isNeg) {
1739 (*this)--;
Reid Spencer9eec2412007-02-25 23:44:53 +00001740 this->flip();
Reid Spencer9eec2412007-02-25 23:44:53 +00001741 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001742}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001743
Reid Spencer9c0696f2007-02-20 08:51:03 +00001744std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1745 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1746 "Radix should be 2, 8, 10, or 16!");
1747 static const char *digits[] = {
1748 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1749 };
1750 std::string result;
1751 uint32_t bits_used = getActiveBits();
1752 if (isSingleWord()) {
1753 char buf[65];
1754 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1755 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1756 if (format) {
1757 if (wantSigned) {
1758 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1759 (APINT_BITS_PER_WORD-BitWidth);
1760 sprintf(buf, format, sextVal);
1761 } else
1762 sprintf(buf, format, VAL);
1763 } else {
1764 memset(buf, 0, 65);
1765 uint64_t v = VAL;
1766 while (bits_used) {
1767 uint32_t bit = v & 1;
1768 bits_used--;
1769 buf[bits_used] = digits[bit][0];
1770 v >>=1;
1771 }
1772 }
1773 result = buf;
1774 return result;
1775 }
1776
1777 if (radix != 10) {
1778 uint64_t mask = radix - 1;
1779 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1780 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1781 for (uint32_t i = 0; i < getNumWords(); ++i) {
1782 uint64_t value = pVal[i];
1783 for (uint32_t j = 0; j < nibbles; ++j) {
1784 result.insert(0, digits[ value & mask ]);
1785 value >>= shift;
1786 }
1787 }
1788 return result;
1789 }
1790
1791 APInt tmp(*this);
1792 APInt divisor(4, radix);
1793 APInt zero(tmp.getBitWidth(), 0);
1794 size_t insert_at = 0;
1795 if (wantSigned && tmp[BitWidth-1]) {
1796 // They want to print the signed version and it is a negative value
1797 // Flip the bits and add one to turn it into the equivalent positive
1798 // value and put a '-' in the result.
1799 tmp.flip();
1800 tmp++;
1801 result = "-";
1802 insert_at = 1;
1803 }
Reid Spencere549c492007-02-21 00:29:48 +00001804 if (tmp == APInt(tmp.getBitWidth(), 0))
Reid Spencer9c0696f2007-02-20 08:51:03 +00001805 result = "0";
1806 else while (tmp.ne(zero)) {
1807 APInt APdigit(1,0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001808 APInt tmp2(tmp.getBitWidth(), 0);
Reid Spencer385f7542007-02-21 03:55:44 +00001809 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1810 &APdigit);
Reid Spencer794f4722007-02-26 21:02:27 +00001811 uint32_t digit = APdigit.getZExtValue();
Reid Spencer385f7542007-02-21 03:55:44 +00001812 assert(digit < radix && "divide failed");
1813 result.insert(insert_at,digits[digit]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001814 tmp = tmp2;
1815 }
1816
1817 return result;
1818}
1819
Reid Spencer385f7542007-02-21 03:55:44 +00001820#ifndef NDEBUG
1821void APInt::dump() const
1822{
Reid Spencer610fad82007-02-24 10:01:42 +00001823 cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
Reid Spencer385f7542007-02-21 03:55:44 +00001824 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +00001825 cerr << VAL;
Reid Spencer385f7542007-02-21 03:55:44 +00001826 else for (unsigned i = getNumWords(); i > 0; i--) {
Reid Spencer610fad82007-02-24 10:01:42 +00001827 cerr << pVal[i-1] << " ";
Reid Spencer385f7542007-02-21 03:55:44 +00001828 }
Reid Spencer681dcd12007-02-27 21:59:26 +00001829 cerr << " U(" << this->toString(10) << ") S(" << this->toStringSigned(10)
1830 << ")\n" << std::setbase(10);
Reid Spencer385f7542007-02-21 03:55:44 +00001831}
1832#endif