blob: 621d746e776b4c85edb60b3d28ffc4a4db7b3b19 [file] [log] [blame]
Zhou Shengdac63782007-02-06 03:00:16 +00001//===-- APInt.cpp - Implement APInt class ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Zhou Shengdac63782007-02-06 03:00:16 +00007//
8//===----------------------------------------------------------------------===//
9//
Reid Spencera41e93b2007-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 Shengdac63782007-02-06 03:00:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
Mehdi Amini47b292d2016-04-16 07:51:28 +000016#include "llvm/ADT/ArrayRef.h"
Ted Kremenek5c75d542008-01-19 04:23:33 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
Chris Lattner17f71652008-08-17 07:19:36 +000019#include "llvm/ADT/SmallString.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000020#include "llvm/ADT/StringRef.h"
Reid Spencera5e0d202007-02-24 03:58:46 +000021#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000022#include "llvm/Support/ErrorHandling.h"
Zhou Shengdac63782007-02-06 03:00:16 +000023#include "llvm/Support/MathExtras.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000024#include "llvm/Support/raw_ostream.h"
Vassil Vassilev2ec8b152016-09-14 08:55:18 +000025#include <climits>
Chris Lattner17f71652008-08-17 07:19:36 +000026#include <cmath>
Zhou Shengdac63782007-02-06 03:00:16 +000027#include <cstdlib>
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include <cstring>
Zhou Shengdac63782007-02-06 03:00:16 +000029using namespace llvm;
30
Chandler Carruth64648262014-04-22 03:07:47 +000031#define DEBUG_TYPE "apint"
32
Reid Spencera41e93b2007-02-25 19:32:03 +000033/// A utility function for allocating memory, checking for allocation failures,
34/// and ensuring the contents are zeroed.
Chris Lattner77527f52009-01-21 18:09:24 +000035inline static uint64_t* getClearedMemory(unsigned numWords) {
Reid Spencera856b6e2007-02-18 18:38:44 +000036 uint64_t * result = new uint64_t[numWords];
37 assert(result && "APInt memory allocation fails!");
38 memset(result, 0, numWords * sizeof(uint64_t));
39 return result;
Zhou Sheng94b623a2007-02-06 06:04:53 +000040}
41
Eric Christopher820256b2009-08-21 04:06:45 +000042/// A utility function for allocating memory and checking for allocation
Reid Spencera41e93b2007-02-25 19:32:03 +000043/// failure. The content is not zeroed.
Chris Lattner77527f52009-01-21 18:09:24 +000044inline static uint64_t* getMemory(unsigned numWords) {
Reid Spencera856b6e2007-02-18 18:38:44 +000045 uint64_t * result = new uint64_t[numWords];
46 assert(result && "APInt memory allocation fails!");
47 return result;
48}
49
Erick Tryzelaardadb15712009-08-21 03:15:28 +000050/// A utility function that converts a character to a digit.
51inline static unsigned getDigit(char cdigit, uint8_t radix) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000052 unsigned r;
53
Douglas Gregor663c0682011-09-14 15:54:46 +000054 if (radix == 16 || radix == 36) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000055 r = cdigit - '0';
56 if (r <= 9)
57 return r;
58
59 r = cdigit - 'A';
Douglas Gregorc98ac852011-09-20 18:33:29 +000060 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000061 return r + 10;
62
63 r = cdigit - 'a';
Douglas Gregorc98ac852011-09-20 18:33:29 +000064 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000065 return r + 10;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +000066
Douglas Gregore4e20f42011-09-20 18:11:52 +000067 radix = 10;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000068 }
69
Erick Tryzelaar60964092009-08-21 06:48:37 +000070 r = cdigit - '0';
71 if (r < radix)
72 return r;
73
74 return -1U;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000075}
76
77
Pawel Bylica68304012016-06-27 08:31:48 +000078void APInt::initSlowCase(uint64_t val, bool isSigned) {
Chris Lattner1ac3e252008-08-20 17:02:31 +000079 pVal = getClearedMemory(getNumWords());
80 pVal[0] = val;
Eric Christopher820256b2009-08-21 04:06:45 +000081 if (isSigned && int64_t(val) < 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +000082 for (unsigned i = 1; i < getNumWords(); ++i)
83 pVal[i] = -1ULL;
Craig Topperf78a6f02017-03-01 21:06:18 +000084 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +000085}
86
Chris Lattnerd57b7602008-10-11 22:07:19 +000087void APInt::initSlowCase(const APInt& that) {
88 pVal = getMemory(getNumWords());
89 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
90}
91
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000092void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +000093 assert(BitWidth && "Bitwidth too small");
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000094 assert(bigVal.data() && "Null pointer detected!");
Zhou Shengdac63782007-02-06 03:00:16 +000095 if (isSingleWord())
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000096 VAL = bigVal[0];
Zhou Shengdac63782007-02-06 03:00:16 +000097 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000098 // Get memory, cleared to 0
99 pVal = getClearedMemory(getNumWords());
100 // Calculate the number of words to copy
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000101 unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000102 // Copy the words from bigVal to pVal
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000103 memcpy(pVal, bigVal.data(), words * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000104 }
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000105 // Make sure unused high bits are cleared
106 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000107}
108
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000109APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal)
110 : BitWidth(numBits), VAL(0) {
111 initFromArray(bigVal);
112}
113
114APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
115 : BitWidth(numBits), VAL(0) {
116 initFromArray(makeArrayRef(bigVal, numWords));
117}
118
Benjamin Kramer92d89982010-07-14 22:38:02 +0000119APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
Reid Spencer1ba83352007-02-21 03:55:44 +0000120 : BitWidth(numbits), VAL(0) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000121 assert(BitWidth && "Bitwidth too small");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000122 fromString(numbits, Str, radix);
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000123}
124
Chris Lattner1ac3e252008-08-20 17:02:31 +0000125APInt& APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer7c16cd22007-02-26 23:38:21 +0000126 // Don't do anything for X = X
127 if (this == &RHS)
128 return *this;
129
Reid Spencer7c16cd22007-02-26 23:38:21 +0000130 if (BitWidth == RHS.getBitWidth()) {
Chris Lattner1ac3e252008-08-20 17:02:31 +0000131 // assume same bit-width single-word case is already handled
132 assert(!isSingleWord());
133 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Reid Spencer7c16cd22007-02-26 23:38:21 +0000134 return *this;
135 }
136
Chris Lattner1ac3e252008-08-20 17:02:31 +0000137 if (isSingleWord()) {
138 // assume case where both are single words is already handled
139 assert(!RHS.isSingleWord());
140 VAL = 0;
141 pVal = getMemory(RHS.getNumWords());
142 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
Eric Christopher820256b2009-08-21 04:06:45 +0000143 } else if (getNumWords() == RHS.getNumWords())
Reid Spencer7c16cd22007-02-26 23:38:21 +0000144 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
145 else if (RHS.isSingleWord()) {
146 delete [] pVal;
Reid Spencera856b6e2007-02-18 18:38:44 +0000147 VAL = RHS.VAL;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000148 } else {
149 delete [] pVal;
150 pVal = getMemory(RHS.getNumWords());
151 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
152 }
153 BitWidth = RHS.BitWidth;
154 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000155}
156
Zhou Shengdac63782007-02-06 03:00:16 +0000157APInt& APInt::operator=(uint64_t RHS) {
Eric Christopher820256b2009-08-21 04:06:45 +0000158 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000159 VAL = RHS;
Zhou Shengdac63782007-02-06 03:00:16 +0000160 else {
161 pVal[0] = RHS;
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000162 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000163 }
Reid Spencer7c16cd22007-02-26 23:38:21 +0000164 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000165}
166
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000167/// This method 'profiles' an APInt for use with FoldingSet.
Ted Kremenek5c75d542008-01-19 04:23:33 +0000168void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremenek901540f2008-02-19 20:50:41 +0000169 ID.AddInteger(BitWidth);
Eric Christopher820256b2009-08-21 04:06:45 +0000170
Ted Kremenek5c75d542008-01-19 04:23:33 +0000171 if (isSingleWord()) {
172 ID.AddInteger(VAL);
173 return;
174 }
175
Chris Lattner77527f52009-01-21 18:09:24 +0000176 unsigned NumWords = getNumWords();
Ted Kremenek5c75d542008-01-19 04:23:33 +0000177 for (unsigned i = 0; i < NumWords; ++i)
178 ID.AddInteger(pVal[i]);
179}
180
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000181/// This function adds a single "digit" integer, y, to the multiple
Reid Spencera856b6e2007-02-18 18:38:44 +0000182/// "digit" integer array, x[]. x[] is modified to reflect the addition and
183/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer100502d2007-02-17 03:16:00 +0000184/// @returns the carry of the addition.
Chris Lattner77527f52009-01-21 18:09:24 +0000185static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
186 for (unsigned i = 0; i < len; ++i) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000187 dest[i] = y + x[i];
188 if (dest[i] < y)
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000189 y = 1; // Carry one to next digit.
Reid Spenceree0a6852007-02-18 06:39:42 +0000190 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000191 y = 0; // No need to carry so exit early
Reid Spenceree0a6852007-02-18 06:39:42 +0000192 break;
193 }
Reid Spencer100502d2007-02-17 03:16:00 +0000194 }
Reid Spenceree0a6852007-02-18 06:39:42 +0000195 return y;
Reid Spencer100502d2007-02-17 03:16:00 +0000196}
197
Zhou Shengdac63782007-02-06 03:00:16 +0000198/// @brief Prefix increment operator. Increments the APInt by one.
199APInt& APInt::operator++() {
Eric Christopher820256b2009-08-21 04:06:45 +0000200 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000201 ++VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000202 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000203 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000204 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000205}
206
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000207/// This function subtracts a single "digit" (64-bit word), y, from
Eric Christopher820256b2009-08-21 04:06:45 +0000208/// the multi-digit integer array, x[], propagating the borrowed 1 value until
Joerg Sonnenbergerd7baada2017-01-05 17:59:22 +0000209/// no further borrowing is needed or it runs out of "digits" in x. The result
Reid Spencera856b6e2007-02-18 18:38:44 +0000210/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
211/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencera41e93b2007-02-25 19:32:03 +0000212/// @returns the borrow out of the subtraction
Chris Lattner77527f52009-01-21 18:09:24 +0000213static bool sub_1(uint64_t x[], unsigned len, uint64_t y) {
214 for (unsigned i = 0; i < len; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000215 uint64_t X = x[i];
Reid Spenceree0a6852007-02-18 06:39:42 +0000216 x[i] -= y;
Eric Christopher820256b2009-08-21 04:06:45 +0000217 if (y > X)
Reid Spencera856b6e2007-02-18 18:38:44 +0000218 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer100502d2007-02-17 03:16:00 +0000219 else {
Reid Spencera856b6e2007-02-18 18:38:44 +0000220 y = 0; // No need to borrow
221 break; // Remaining digits are unchanged so exit early
Reid Spencer100502d2007-02-17 03:16:00 +0000222 }
223 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000224 return bool(y);
Reid Spencer100502d2007-02-17 03:16:00 +0000225}
226
Zhou Shengdac63782007-02-06 03:00:16 +0000227/// @brief Prefix decrement operator. Decrements the APInt by one.
228APInt& APInt::operator--() {
Eric Christopher820256b2009-08-21 04:06:45 +0000229 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000230 --VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000231 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000232 sub_1(pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000233 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000234}
235
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000236/// This function adds the integer array x to the integer array Y and
Eric Christopher820256b2009-08-21 04:06:45 +0000237/// places the result in dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000238/// @returns the carry out from the addition
239/// @brief General addition of 64-bit integer arrays
Eric Christopher820256b2009-08-21 04:06:45 +0000240static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000241 unsigned len) {
Reid Spencera5e0d202007-02-24 03:58:46 +0000242 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000243 for (unsigned i = 0; i< len; ++i) {
Reid Spencercb292e42007-02-23 01:57:13 +0000244 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000245 dest[i] = x[i] + y[i] + carry;
Reid Spencerdb2abec2007-02-21 05:44:56 +0000246 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer100502d2007-02-17 03:16:00 +0000247 }
248 return carry;
249}
250
Reid Spencera41e93b2007-02-25 19:32:03 +0000251/// Adds the RHS APint to this APInt.
252/// @returns this, after addition of RHS.
Eric Christopher820256b2009-08-21 04:06:45 +0000253/// @brief Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000254APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000255 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000256 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000257 VAL += RHS.VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000258 else {
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000259 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000260 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000261 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000262}
263
Pete Cooperfea21392016-07-22 20:55:46 +0000264APInt& APInt::operator+=(uint64_t RHS) {
265 if (isSingleWord())
266 VAL += RHS;
267 else
268 add_1(pVal, pVal, getNumWords(), RHS);
269 return clearUnusedBits();
270}
271
Eric Christopher820256b2009-08-21 04:06:45 +0000272/// Subtracts the integer array y from the integer array x
Reid Spencera41e93b2007-02-25 19:32:03 +0000273/// @returns returns the borrow out.
274/// @brief Generalized subtraction of 64-bit integer arrays.
Eric Christopher820256b2009-08-21 04:06:45 +0000275static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000276 unsigned len) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000277 bool borrow = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000278 for (unsigned i = 0; i < len; ++i) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000279 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
280 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
281 dest[i] = x_tmp - y[i];
Reid Spencer100502d2007-02-17 03:16:00 +0000282 }
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000283 return borrow;
Reid Spencer100502d2007-02-17 03:16:00 +0000284}
285
Reid Spencera41e93b2007-02-25 19:32:03 +0000286/// Subtracts the RHS APInt from this APInt
287/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000288/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000289APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000290 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000291 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000292 VAL -= RHS.VAL;
293 else
294 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000295 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000296}
297
Pete Cooperfea21392016-07-22 20:55:46 +0000298APInt& APInt::operator-=(uint64_t RHS) {
299 if (isSingleWord())
300 VAL -= RHS;
301 else
302 sub_1(pVal, getNumWords(), RHS);
303 return clearUnusedBits();
304}
305
Dan Gohman4a618822010-02-10 16:03:48 +0000306/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000307/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000308/// @returns the carry out of the multiplication.
309/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000310static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000311 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000312 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000313 uint64_t carry = 0;
314
315 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000316 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000317 // Split x into high and low words
318 uint64_t lx = x[i] & 0xffffffffULL;
319 uint64_t hx = x[i] >> 32;
320 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000321 // hasCarry == 0, no carry
322 // hasCarry == 1, has carry
323 // hasCarry == 2, no carry and the calculation result == 0.
324 uint8_t hasCarry = 0;
325 dest[i] = carry + lx * ly;
326 // Determine if the add above introduces carry.
327 hasCarry = (dest[i] < carry) ? 1 : 0;
328 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000329 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000330 // (2^32 - 1) + 2^32 = 2^64.
331 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
332
333 carry += (lx * hy) & 0xffffffffULL;
334 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000335 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000336 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
337 }
Reid Spencer100502d2007-02-17 03:16:00 +0000338 return carry;
339}
340
Eric Christopher820256b2009-08-21 04:06:45 +0000341/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000342/// the integer array dest. Note that dest's size must be >= xlen + ylen.
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000343/// @brief Generalized multiplication of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000344static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
345 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000346 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000347 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000348 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000349 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000350 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000351 lx = x[j] & 0xffffffffULL;
352 hx = x[j] >> 32;
353 // hasCarry - A flag to indicate if has carry.
354 // hasCarry == 0, no carry
355 // hasCarry == 1, has carry
356 // hasCarry == 2, no carry and the calculation result == 0.
357 uint8_t hasCarry = 0;
358 uint64_t resul = carry + lx * ly;
359 hasCarry = (resul < carry) ? 1 : 0;
360 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
361 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
362
363 carry += (lx * hy) & 0xffffffffULL;
364 resul = (carry << 32) | (resul & 0xffffffffULL);
365 dest[i+j] += resul;
366 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000367 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000368 ((lx * hy) >> 32) + hx * hy;
369 }
370 dest[i+xlen] = carry;
371 }
372}
373
Zhou Shengdac63782007-02-06 03:00:16 +0000374APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000375 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000376 if (isSingleWord()) {
Reid Spencer4bb430c2007-02-20 20:42:10 +0000377 VAL *= RHS.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000378 clearUnusedBits();
379 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000380 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000381
382 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000383 unsigned lhsBits = getActiveBits();
384 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000385 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000386 // 0 * X ===> 0
387 return *this;
388
389 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000390 unsigned rhsBits = RHS.getActiveBits();
391 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000392 if (!rhsWords) {
393 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000394 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000395 return *this;
396 }
397
398 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000399 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000400 uint64_t *dest = getMemory(destWords);
401
402 // Perform the long multiply
403 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
404
405 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000406 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000407 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000408 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000409 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000410
411 // delete dest array and return
412 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000413 return *this;
414}
415
Zhou Shengdac63782007-02-06 03:00:16 +0000416APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000417 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000418 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000419 VAL &= RHS.VAL;
420 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000421 }
Chris Lattner77527f52009-01-21 18:09:24 +0000422 unsigned numWords = getNumWords();
423 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000424 pVal[i] &= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000425 return *this;
426}
427
Amaury Sechetfb1756b2017-02-03 22:54:41 +0000428APInt &APInt::operator&=(uint64_t RHS) {
429 if (isSingleWord()) {
430 VAL &= RHS;
431 return *this;
432 }
433 pVal[0] &= RHS;
434 unsigned numWords = getNumWords();
435 for (unsigned i = 1; i < numWords; ++i)
436 pVal[i] = 0;
437 return *this;
438}
439
Zhou Shengdac63782007-02-06 03:00:16 +0000440APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000441 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000442 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000443 VAL |= RHS.VAL;
444 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000445 }
Chris Lattner77527f52009-01-21 18:09:24 +0000446 unsigned numWords = getNumWords();
447 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000448 pVal[i] |= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000449 return *this;
450}
451
Zhou Shengdac63782007-02-06 03:00:16 +0000452APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000453 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000454 if (isSingleWord()) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000455 VAL ^= RHS.VAL;
456 return *this;
Eric Christopher820256b2009-08-21 04:06:45 +0000457 }
Chris Lattner77527f52009-01-21 18:09:24 +0000458 unsigned numWords = getNumWords();
459 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000460 pVal[i] ^= RHS.pVal[i];
Craig Topper9028f052017-01-24 02:10:15 +0000461 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000462}
463
Zhou Shengdac63782007-02-06 03:00:16 +0000464APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000465 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000466 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000467 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000468 APInt Result(*this);
469 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000470 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000471}
472
Chris Lattner1ac3e252008-08-20 17:02:31 +0000473bool APInt::EqualSlowCase(const APInt& RHS) const {
Matthias Braun5117fcd2016-02-15 20:06:19 +0000474 return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000475}
476
Chris Lattner1ac3e252008-08-20 17:02:31 +0000477bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000478 unsigned n = getActiveBits();
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000479 if (n <= APINT_BITS_PER_WORD)
480 return pVal[0] == Val;
481 else
482 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000483}
484
Reid Spencer1d072122007-02-16 22:36:51 +0000485bool APInt::ult(const APInt& RHS) const {
486 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
487 if (isSingleWord())
488 return VAL < RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000489
490 // Get active bit length of both operands
Chris Lattner77527f52009-01-21 18:09:24 +0000491 unsigned n1 = getActiveBits();
492 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000493
494 // If magnitude of LHS is less than RHS, return true.
495 if (n1 < n2)
496 return true;
497
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000498 // If magnitude of RHS is greater than LHS, return false.
Reid Spencera41e93b2007-02-25 19:32:03 +0000499 if (n2 < n1)
500 return false;
501
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000502 // If they both fit in a word, just compare the low order word
Reid Spencera41e93b2007-02-25 19:32:03 +0000503 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
504 return pVal[0] < RHS.pVal[0];
505
506 // Otherwise, compare all words
Chris Lattner77527f52009-01-21 18:09:24 +0000507 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000508 for (int i = topWord; i >= 0; --i) {
Eric Christopher820256b2009-08-21 04:06:45 +0000509 if (pVal[i] > RHS.pVal[i])
Reid Spencer1d072122007-02-16 22:36:51 +0000510 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000511 if (pVal[i] < RHS.pVal[i])
Reid Spencera41e93b2007-02-25 19:32:03 +0000512 return true;
Zhou Shengdac63782007-02-06 03:00:16 +0000513 }
514 return false;
515}
516
Reid Spencer1d072122007-02-16 22:36:51 +0000517bool APInt::slt(const APInt& RHS) const {
518 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000519 if (isSingleWord()) {
David Majnemer5f1c0172016-06-24 20:51:47 +0000520 int64_t lhsSext = SignExtend64(VAL, BitWidth);
521 int64_t rhsSext = SignExtend64(RHS.VAL, BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000522 return lhsSext < rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000523 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000524
Reid Spencer54abdcf2007-02-27 18:23:40 +0000525 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000526 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000527
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000528 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
529 if (lhsNeg != rhsNeg)
530 return lhsNeg;
531
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000532 // Otherwise we can just use an unsigned comparison, because even negative
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000533 // numbers compare correctly this way if both have the same signed-ness.
534 return ult(RHS);
Zhou Shengdac63782007-02-06 03:00:16 +0000535}
536
Jay Foad25a5e4c2010-12-01 08:53:58 +0000537void APInt::setBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000538 if (isSingleWord())
Reid Spencera41e93b2007-02-25 19:32:03 +0000539 VAL |= maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000540 else
Reid Spencera41e93b2007-02-25 19:32:03 +0000541 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000542}
543
Craig Topperbafdd032017-03-07 01:56:01 +0000544void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
545 unsigned loWord = whichWord(loBit);
546 unsigned hiWord = whichWord(hiBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000547
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000548 // Create an initial mask for the low word with zeros below loBit.
Craig Topperbafdd032017-03-07 01:56:01 +0000549 uint64_t loMask = UINT64_MAX << whichBit(loBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000550
Craig Topperbafdd032017-03-07 01:56:01 +0000551 // If hiBit is not aligned, we need a high mask.
552 unsigned hiShiftAmt = whichBit(hiBit);
553 if (hiShiftAmt != 0) {
554 // Create a high mask with zeros above hiBit.
555 uint64_t hiMask = UINT64_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
556 // If loWord and hiWord are equal, then we combine the masks. Otherwise,
557 // set the bits in hiWord.
558 if (hiWord == loWord)
559 loMask &= hiMask;
560 else
Simon Pilgrimaed35222017-02-24 10:15:29 +0000561 pVal[hiWord] |= hiMask;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000562 }
Craig Topperbafdd032017-03-07 01:56:01 +0000563 // Apply the mask to the low word.
564 pVal[loWord] |= loMask;
565
566 // Fill any words between loWord and hiWord with all ones.
567 for (unsigned word = loWord + 1; word < hiWord; ++word)
568 pVal[word] = UINT64_MAX;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000569}
570
Zhou Shengdac63782007-02-06 03:00:16 +0000571/// Set the given bit to 0 whose position is given as "bitPosition".
572/// @brief Set a given bit to 0.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000573void APInt::clearBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000574 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000575 VAL &= ~maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000576 else
Reid Spencera856b6e2007-02-18 18:38:44 +0000577 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000578}
579
Zhou Shengdac63782007-02-06 03:00:16 +0000580/// @brief Toggle every bit to its opposite value.
Zhou Shengdac63782007-02-06 03:00:16 +0000581
Eric Christopher820256b2009-08-21 04:06:45 +0000582/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000583/// as "bitPosition".
584/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000585void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000586 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000587 if ((*this)[bitPosition]) clearBit(bitPosition);
588 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000589}
590
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000591APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
592 assert(numBits > 0 && "Can't extract zero bits");
593 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
594 "Illegal bit extraction");
595
596 if (isSingleWord())
597 return APInt(numBits, VAL >> bitPosition);
598
599 unsigned loBit = whichBit(bitPosition);
600 unsigned loWord = whichWord(bitPosition);
601 unsigned hiWord = whichWord(bitPosition + numBits - 1);
602
603 // Single word result extracting bits from a single word source.
604 if (loWord == hiWord)
605 return APInt(numBits, pVal[loWord] >> loBit);
606
607 // Extracting bits that start on a source word boundary can be done
608 // as a fast memory copy.
609 if (loBit == 0)
610 return APInt(numBits, makeArrayRef(pVal + loWord, 1 + hiWord - loWord));
611
612 // General case - shift + copy source words directly into place.
613 APInt Result(numBits, 0);
614 unsigned NumSrcWords = getNumWords();
615 unsigned NumDstWords = Result.getNumWords();
616
617 for (unsigned word = 0; word < NumDstWords; ++word) {
618 uint64_t w0 = pVal[loWord + word];
619 uint64_t w1 =
620 (loWord + word + 1) < NumSrcWords ? pVal[loWord + word + 1] : 0;
621 Result.pVal[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
622 }
623
624 return Result.clearUnusedBits();
625}
626
Benjamin Kramer92d89982010-07-14 22:38:02 +0000627unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000628 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000629 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +0000630 radix == 36) &&
631 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000632
633 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000634
Eric Christopher43a1dec2009-08-21 04:10:31 +0000635 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000636 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000637 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000638 if (*p == '-' || *p == '+') {
639 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000640 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000641 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000642 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000643
Reid Spencer9329e7b2007-04-13 19:19:07 +0000644 // For radixes of power-of-two values, the bits required is accurately and
645 // easily computed
646 if (radix == 2)
647 return slen + isNegative;
648 if (radix == 8)
649 return slen * 3 + isNegative;
650 if (radix == 16)
651 return slen * 4 + isNegative;
652
Douglas Gregor663c0682011-09-14 15:54:46 +0000653 // FIXME: base 36
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000654
Reid Spencer9329e7b2007-04-13 19:19:07 +0000655 // This is grossly inefficient but accurate. We could probably do something
656 // with a computation of roughly slen*64/20 and then adjust by the value of
657 // the first few digits. But, I'm not sure how accurate that could be.
658
659 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000660 // be too large. This avoids the assertion in the constructor. This
661 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
662 // bits in that case.
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000663 unsigned sufficient
Douglas Gregor663c0682011-09-14 15:54:46 +0000664 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
665 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000666
667 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000668 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000669
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000670 // Compute how many bits are required. If the log is infinite, assume we need
671 // just bit.
672 unsigned log = tmp.logBase2();
673 if (log == (unsigned)-1) {
674 return isNegative + 1;
675 } else {
676 return isNegative + log + 1;
677 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000678}
679
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000680hash_code llvm::hash_value(const APInt &Arg) {
681 if (Arg.isSingleWord())
682 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000683
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000684 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000685}
686
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000687bool APInt::isSplat(unsigned SplatSizeInBits) const {
688 assert(getBitWidth() % SplatSizeInBits == 0 &&
689 "SplatSizeInBits must divide width!");
690 // We can check that all parts of an integer are equal by making use of a
691 // little trick: rotate and check if it's still the same value.
692 return *this == rotl(SplatSizeInBits);
693}
694
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000695/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000696APInt APInt::getHiBits(unsigned numBits) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000697 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000698}
699
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000700/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000701APInt APInt::getLoBits(unsigned numBits) const {
Eric Christopher820256b2009-08-21 04:06:45 +0000702 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
Reid Spencer1d072122007-02-16 22:36:51 +0000703 BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000704}
705
Chris Lattner77527f52009-01-21 18:09:24 +0000706unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000707 unsigned Count = 0;
708 for (int i = getNumWords()-1; i >= 0; --i) {
709 integerPart V = pVal[i];
710 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000711 Count += APINT_BITS_PER_WORD;
712 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000713 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000714 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000715 }
Zhou Shengdac63782007-02-06 03:00:16 +0000716 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000717 // Adjust for unused bits in the most significant word (they are zero).
718 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
719 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000720 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000721}
722
Chris Lattner77527f52009-01-21 18:09:24 +0000723unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000724 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000725 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000726
Chris Lattner77527f52009-01-21 18:09:24 +0000727 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000728 unsigned shift;
729 if (!highWordBits) {
730 highWordBits = APINT_BITS_PER_WORD;
731 shift = 0;
732 } else {
733 shift = APINT_BITS_PER_WORD - highWordBits;
734 }
Reid Spencer31acef52007-02-27 21:59:26 +0000735 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000736 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000737 if (Count == highWordBits) {
738 for (i--; i >= 0; --i) {
739 if (pVal[i] == -1ULL)
740 Count += APINT_BITS_PER_WORD;
741 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000742 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000743 break;
744 }
745 }
746 }
747 return Count;
748}
749
Chris Lattner77527f52009-01-21 18:09:24 +0000750unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000751 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000752 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000753 unsigned Count = 0;
754 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000755 for (; i < getNumWords() && pVal[i] == 0; ++i)
756 Count += APINT_BITS_PER_WORD;
757 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000758 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000759 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000760}
761
Chris Lattner77527f52009-01-21 18:09:24 +0000762unsigned APInt::countTrailingOnesSlowCase() const {
763 unsigned Count = 0;
764 unsigned i = 0;
Dan Gohmanc354ebd2008-02-14 22:38:45 +0000765 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000766 Count += APINT_BITS_PER_WORD;
767 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000768 Count += llvm::countTrailingOnes(pVal[i]);
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000769 return std::min(Count, BitWidth);
770}
771
Chris Lattner77527f52009-01-21 18:09:24 +0000772unsigned APInt::countPopulationSlowCase() const {
773 unsigned Count = 0;
774 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000775 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000776 return Count;
777}
778
Richard Smith4f9a8082011-11-23 21:33:37 +0000779/// Perform a logical right-shift from Src to Dst, which must be equal or
780/// non-overlapping, of Words words, by Shift, which must be less than 64.
781static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
782 unsigned Shift) {
783 uint64_t Carry = 0;
784 for (int I = Words - 1; I >= 0; --I) {
785 uint64_t Tmp = Src[I];
786 Dst[I] = (Tmp >> Shift) | Carry;
787 Carry = Tmp << (64 - Shift);
788 }
789}
790
Reid Spencer1d072122007-02-16 22:36:51 +0000791APInt APInt::byteSwap() const {
792 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
793 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000794 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000795 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000796 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000797 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000798 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000799 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000800 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000801 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000802 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000803 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000804 if (BitWidth == 64)
805 return APInt(BitWidth, ByteSwap_64(VAL));
806
807 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
808 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
809 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
810 if (Result.BitWidth != BitWidth) {
811 lshrNear(Result.pVal, Result.pVal, getNumWords(),
812 Result.BitWidth - BitWidth);
813 Result.BitWidth = BitWidth;
814 }
815 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000816}
817
Matt Arsenault155dda92016-03-21 15:00:35 +0000818APInt APInt::reverseBits() const {
819 switch (BitWidth) {
820 case 64:
821 return APInt(BitWidth, llvm::reverseBits<uint64_t>(VAL));
822 case 32:
823 return APInt(BitWidth, llvm::reverseBits<uint32_t>(VAL));
824 case 16:
825 return APInt(BitWidth, llvm::reverseBits<uint16_t>(VAL));
826 case 8:
827 return APInt(BitWidth, llvm::reverseBits<uint8_t>(VAL));
828 default:
829 break;
830 }
831
832 APInt Val(*this);
833 APInt Reversed(*this);
834 int S = BitWidth - 1;
835
836 const APInt One(BitWidth, 1);
837
838 for ((Val = Val.lshr(1)); Val != 0; (Val = Val.lshr(1))) {
839 Reversed <<= 1;
840 Reversed |= (Val & One);
841 --S;
842 }
843
844 Reversed <<= S;
845 return Reversed;
846}
847
Eric Christopher820256b2009-08-21 04:06:45 +0000848APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
Zhou Shengfbf61ea2007-02-08 14:35:19 +0000849 const APInt& API2) {
Zhou Shengdac63782007-02-06 03:00:16 +0000850 APInt A = API1, B = API2;
851 while (!!B) {
852 APInt T = B;
Reid Spencer1d072122007-02-16 22:36:51 +0000853 B = APIntOps::urem(A, B);
Zhou Shengdac63782007-02-06 03:00:16 +0000854 A = T;
855 }
856 return A;
857}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000858
Chris Lattner77527f52009-01-21 18:09:24 +0000859APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000860 union {
861 double D;
862 uint64_t I;
863 } T;
864 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000865
866 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000867 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000868
869 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000870 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000871
872 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000873 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000874 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000875
876 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
877 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
878
879 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000880 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000881 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000882 APInt(width, mantissa >> (52 - exp));
883
884 // If the client didn't provide enough bits for us to shift the mantissa into
885 // then the result is undefined, just return 0
886 if (width <= exp - 52)
887 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000888
889 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000890 APInt Tmp(width, mantissa);
Chris Lattner77527f52009-01-21 18:09:24 +0000891 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd707d632007-02-12 20:02:55 +0000892 return isNeg ? -Tmp : Tmp;
893}
894
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000895/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000896/// The layout for double is as following (IEEE Standard 754):
897/// --------------------------------------
898/// | Sign Exponent Fraction Bias |
899/// |-------------------------------------- |
900/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000901/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000902double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000903
904 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000905 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000906 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
907 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000908 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000909 return double(sext);
910 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000911 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000912 }
913
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000914 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000915 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000916
917 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000918 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000919
920 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000921 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000922
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000923 // The exponent (without bias normalization) is just the number of bits
924 // we are using. Note that the sign bit is gone since we constructed the
925 // absolute value.
926 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000927
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000928 // Return infinity for exponent overflow
929 if (exp > 1023) {
930 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000931 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000932 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000933 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000934 }
935 exp += 1023; // Increment for 1023 bias
936
937 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
938 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000939 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000940 unsigned hiWord = whichWord(n-1);
941 if (hiWord == 0) {
942 mantissa = Tmp.pVal[0];
943 if (n > 52)
944 mantissa >>= n - 52; // shift down, we want the top 52 bits.
945 } else {
946 assert(hiWord > 0 && "huh?");
947 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
948 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
949 mantissa = hibits | lobits;
950 }
951
Zhou Shengd707d632007-02-12 20:02:55 +0000952 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000953 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000954 union {
955 double D;
956 uint64_t I;
957 } T;
958 T.I = sign | (exp << 52) | mantissa;
959 return T.D;
960}
961
Reid Spencer1d072122007-02-16 22:36:51 +0000962// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000963APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000964 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000965 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000966
967 if (width <= APINT_BITS_PER_WORD)
968 return APInt(width, getRawData()[0]);
969
970 APInt Result(getMemory(getNumWords(width)), width);
971
972 // Copy full words.
973 unsigned i;
974 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
975 Result.pVal[i] = pVal[i];
976
977 // Truncate and copy any partial word.
978 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
979 if (bits != 0)
980 Result.pVal[i] = pVal[i] << bits >> bits;
981
982 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000983}
984
985// Sign extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000986APInt APInt::sext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000987 assert(width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000988
989 if (width <= APINT_BITS_PER_WORD) {
990 uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
991 val = (int64_t)val >> (width - BitWidth);
992 return APInt(width, val >> (APINT_BITS_PER_WORD - width));
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000993 }
994
Jay Foad583abbc2010-12-07 08:25:19 +0000995 APInt Result(getMemory(getNumWords(width)), width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000996
Jay Foad583abbc2010-12-07 08:25:19 +0000997 // Copy full words.
998 unsigned i;
999 uint64_t word = 0;
1000 for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
1001 word = getRawData()[i];
1002 Result.pVal[i] = word;
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001003 }
1004
Jay Foad583abbc2010-12-07 08:25:19 +00001005 // Read and sign-extend any partial word.
1006 unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
1007 if (bits != 0)
1008 word = (int64_t)getRawData()[i] << bits >> bits;
1009 else
1010 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
1011
1012 // Write remaining full words.
1013 for (; i != width / APINT_BITS_PER_WORD; i++) {
1014 Result.pVal[i] = word;
1015 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001016 }
Jay Foad583abbc2010-12-07 08:25:19 +00001017
1018 // Write any partial word.
1019 bits = (0 - width) % APINT_BITS_PER_WORD;
1020 if (bits != 0)
1021 Result.pVal[i] = word << bits >> bits;
1022
1023 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001024}
1025
1026// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +00001027APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +00001028 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +00001029
1030 if (width <= APINT_BITS_PER_WORD)
1031 return APInt(width, VAL);
1032
1033 APInt Result(getMemory(getNumWords(width)), width);
1034
1035 // Copy words.
1036 unsigned i;
1037 for (i = 0; i != getNumWords(); i++)
1038 Result.pVal[i] = getRawData()[i];
1039
1040 // Zero remaining words.
1041 memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
1042
1043 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001044}
1045
Jay Foad583abbc2010-12-07 08:25:19 +00001046APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001047 if (BitWidth < width)
1048 return zext(width);
1049 if (BitWidth > width)
1050 return trunc(width);
1051 return *this;
1052}
1053
Jay Foad583abbc2010-12-07 08:25:19 +00001054APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001055 if (BitWidth < width)
1056 return sext(width);
1057 if (BitWidth > width)
1058 return trunc(width);
1059 return *this;
1060}
1061
Rafael Espindolabb893fe2012-01-27 23:33:07 +00001062APInt APInt::zextOrSelf(unsigned width) const {
1063 if (BitWidth < width)
1064 return zext(width);
1065 return *this;
1066}
1067
1068APInt APInt::sextOrSelf(unsigned width) const {
1069 if (BitWidth < width)
1070 return sext(width);
1071 return *this;
1072}
1073
Zhou Shenge93db8f2007-02-09 07:48:24 +00001074/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001075/// @brief Arithmetic right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001076APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001077 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001078}
1079
1080/// Arithmetic right-shift this APInt by shiftAmt.
1081/// @brief Arithmetic right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001082APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001083 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer1825dd02007-03-02 22:39:11 +00001084 // Handle a degenerate case
1085 if (shiftAmt == 0)
1086 return *this;
1087
1088 // Handle single word shifts with built-in ashr
Reid Spencer522ca7c2007-02-25 01:56:07 +00001089 if (isSingleWord()) {
1090 if (shiftAmt == BitWidth)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001091 return APInt(BitWidth, 0); // undefined
Jonathan Roelofs851b79d2016-08-10 19:50:14 +00001092 return APInt(BitWidth, SignExtend64(VAL, BitWidth) >> shiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001093 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001094
Reid Spencer1825dd02007-03-02 22:39:11 +00001095 // If all the bits were shifted out, the result is, technically, undefined.
1096 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1097 // issues in the algorithm below.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001098 if (shiftAmt == BitWidth) {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001099 if (isNegative())
Zhou Sheng1247c072008-06-05 13:27:38 +00001100 return APInt(BitWidth, -1ULL, true);
Reid Spencera41e93b2007-02-25 19:32:03 +00001101 else
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001102 return APInt(BitWidth, 0);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001103 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001104
1105 // Create some space for the result.
1106 uint64_t * val = new uint64_t[getNumWords()];
1107
Reid Spencer1825dd02007-03-02 22:39:11 +00001108 // Compute some values needed by the following shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001109 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1110 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1111 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1112 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer1825dd02007-03-02 22:39:11 +00001113 if (bitsInWord == 0)
1114 bitsInWord = APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001115
1116 // If we are shifting whole words, just move whole words
1117 if (wordShift == 0) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001118 // Move the words containing significant bits
Chris Lattner77527f52009-01-21 18:09:24 +00001119 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001120 val[i] = pVal[i+offset]; // move whole word
1121
1122 // Adjust the top significant word for sign bit fill, if negative
1123 if (isNegative())
1124 if (bitsInWord < APINT_BITS_PER_WORD)
1125 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1126 } else {
Eric Christopher820256b2009-08-21 04:06:45 +00001127 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001128 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001129 // This combines the shifted corresponding word with the low bits from
1130 // the next word (shifted into this word's high bits).
Eric Christopher820256b2009-08-21 04:06:45 +00001131 val[i] = (pVal[i+offset] >> wordShift) |
Reid Spencer1825dd02007-03-02 22:39:11 +00001132 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1133 }
1134
1135 // Shift the break word. In this case there are no bits from the next word
1136 // to include in this word.
1137 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1138
Alp Tokercb402912014-01-24 17:20:08 +00001139 // Deal with sign extension in the break word, and possibly the word before
Reid Spencer1825dd02007-03-02 22:39:11 +00001140 // it.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001141 if (isNegative()) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001142 if (wordShift > bitsInWord) {
1143 if (breakWord > 0)
Eric Christopher820256b2009-08-21 04:06:45 +00001144 val[breakWord-1] |=
Reid Spencer1825dd02007-03-02 22:39:11 +00001145 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1146 val[breakWord] |= ~0ULL;
Eric Christopher820256b2009-08-21 04:06:45 +00001147 } else
Reid Spencer1825dd02007-03-02 22:39:11 +00001148 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnerdad2d092007-05-03 18:15:36 +00001149 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001150 }
1151
Reid Spencer1825dd02007-03-02 22:39:11 +00001152 // Remaining words are 0 or -1, just assign them.
1153 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner77527f52009-01-21 18:09:24 +00001154 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001155 val[i] = fillValue;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001156 APInt Result(val, BitWidth);
1157 Result.clearUnusedBits();
1158 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001159}
1160
Zhou Shenge93db8f2007-02-09 07:48:24 +00001161/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001162/// @brief Logical right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001163APInt APInt::lshr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001164 return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001165}
1166
1167/// Logical right-shift this APInt by shiftAmt.
1168/// @brief Logical right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001169APInt APInt::lshr(unsigned shiftAmt) const {
Chris Lattnerdad2d092007-05-03 18:15:36 +00001170 if (isSingleWord()) {
Ahmed Charles0dca5d82012-02-24 19:06:15 +00001171 if (shiftAmt >= BitWidth)
Reid Spencer522ca7c2007-02-25 01:56:07 +00001172 return APInt(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001173 else
Reid Spencer522ca7c2007-02-25 01:56:07 +00001174 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001175 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001176
Reid Spencer44eef162007-02-26 01:19:48 +00001177 // If all the bits were shifted out, the result is 0. This avoids issues
1178 // with shifting by the size of the integer type, which produces undefined
1179 // results. We define these "undefined results" to always be 0.
Chad Rosier3d464d82012-06-08 18:04:52 +00001180 if (shiftAmt >= BitWidth)
Reid Spencer44eef162007-02-26 01:19:48 +00001181 return APInt(BitWidth, 0);
1182
Reid Spencerfffdf102007-05-17 06:26:29 +00001183 // If none of the bits are shifted out, the result is *this. This avoids
Eric Christopher820256b2009-08-21 04:06:45 +00001184 // issues with shifting by the size of the integer type, which produces
Reid Spencerfffdf102007-05-17 06:26:29 +00001185 // undefined results in the code below. This is also an optimization.
1186 if (shiftAmt == 0)
1187 return *this;
1188
Reid Spencer44eef162007-02-26 01:19:48 +00001189 // Create some space for the result.
1190 uint64_t * val = new uint64_t[getNumWords()];
1191
1192 // If we are shifting less than a word, compute the shift with a simple carry
1193 if (shiftAmt < APINT_BITS_PER_WORD) {
Richard Smith4f9a8082011-11-23 21:33:37 +00001194 lshrNear(val, pVal, getNumWords(), shiftAmt);
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001195 APInt Result(val, BitWidth);
1196 Result.clearUnusedBits();
1197 return Result;
Reid Spencera41e93b2007-02-25 19:32:03 +00001198 }
1199
Reid Spencer44eef162007-02-26 01:19:48 +00001200 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001201 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1202 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencer44eef162007-02-26 01:19:48 +00001203
1204 // If we are shifting whole words, just move whole words
1205 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001206 for (unsigned i = 0; i < getNumWords() - offset; ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001207 val[i] = pVal[i+offset];
Chris Lattner77527f52009-01-21 18:09:24 +00001208 for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
Reid Spencer44eef162007-02-26 01:19:48 +00001209 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001210 APInt Result(val, BitWidth);
1211 Result.clearUnusedBits();
1212 return Result;
Reid Spencer44eef162007-02-26 01:19:48 +00001213 }
1214
Eric Christopher820256b2009-08-21 04:06:45 +00001215 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001216 unsigned breakWord = getNumWords() - offset -1;
1217 for (unsigned i = 0; i < breakWord; ++i)
Reid Spencerd99feaf2007-03-01 05:39:56 +00001218 val[i] = (pVal[i+offset] >> wordShift) |
1219 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencer44eef162007-02-26 01:19:48 +00001220 // Shift the break word.
1221 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1222
1223 // Remaining words are 0
Chris Lattner77527f52009-01-21 18:09:24 +00001224 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001225 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001226 APInt Result(val, BitWidth);
1227 Result.clearUnusedBits();
1228 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001229}
1230
Zhou Shenge93db8f2007-02-09 07:48:24 +00001231/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001232/// @brief Left-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001233APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky030c4502009-01-19 17:42:33 +00001234 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner77527f52009-01-21 18:09:24 +00001235 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001236}
1237
Chris Lattner77527f52009-01-21 18:09:24 +00001238APInt APInt::shlSlowCase(unsigned shiftAmt) const {
Reid Spencera5c84d92007-02-25 00:56:44 +00001239 // If all the bits were shifted out, the result is 0. This avoids issues
1240 // with shifting by the size of the integer type, which produces undefined
1241 // results. We define these "undefined results" to always be 0.
1242 if (shiftAmt == BitWidth)
1243 return APInt(BitWidth, 0);
1244
Reid Spencer81ee0202007-05-12 18:01:57 +00001245 // If none of the bits are shifted out, the result is *this. This avoids a
1246 // lshr by the words size in the loop below which can produce incorrect
1247 // results. It also avoids the expensive computation below for a common case.
1248 if (shiftAmt == 0)
1249 return *this;
1250
Reid Spencera5c84d92007-02-25 00:56:44 +00001251 // Create some space for the result.
1252 uint64_t * val = new uint64_t[getNumWords()];
1253
1254 // If we are shifting less than a word, do it the easy way
1255 if (shiftAmt < APINT_BITS_PER_WORD) {
1256 uint64_t carry = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001257 for (unsigned i = 0; i < getNumWords(); i++) {
Reid Spencera5c84d92007-02-25 00:56:44 +00001258 val[i] = pVal[i] << shiftAmt | carry;
1259 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1260 }
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001261 APInt Result(val, BitWidth);
1262 Result.clearUnusedBits();
1263 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001264 }
1265
Reid Spencera5c84d92007-02-25 00:56:44 +00001266 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001267 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1268 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencera5c84d92007-02-25 00:56:44 +00001269
1270 // If we are shifting whole words, just move whole words
1271 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001272 for (unsigned i = 0; i < offset; i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001273 val[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001274 for (unsigned i = offset; i < getNumWords(); i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001275 val[i] = pVal[i-offset];
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001276 APInt Result(val, BitWidth);
1277 Result.clearUnusedBits();
1278 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001279 }
Reid Spencera5c84d92007-02-25 00:56:44 +00001280
1281 // Copy whole words from this to Result.
Chris Lattner77527f52009-01-21 18:09:24 +00001282 unsigned i = getNumWords() - 1;
Reid Spencera5c84d92007-02-25 00:56:44 +00001283 for (; i > offset; --i)
1284 val[i] = pVal[i-offset] << wordShift |
1285 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencerab0e08a2007-02-25 01:08:58 +00001286 val[offset] = pVal[0] << wordShift;
Reid Spencera5c84d92007-02-25 00:56:44 +00001287 for (i = 0; i < offset; ++i)
1288 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001289 APInt Result(val, BitWidth);
1290 Result.clearUnusedBits();
1291 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001292}
1293
Joey Gouly51c0ae52017-02-07 11:58:22 +00001294// Calculate the rotate amount modulo the bit width.
1295static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1296 unsigned rotBitWidth = rotateAmt.getBitWidth();
1297 APInt rot = rotateAmt;
1298 if (rotBitWidth < BitWidth) {
1299 // Extend the rotate APInt, so that the urem doesn't divide by 0.
1300 // e.g. APInt(1, 32) would give APInt(1, 0).
1301 rot = rotateAmt.zext(BitWidth);
1302 }
1303 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
1304 return rot.getLimitedValue(BitWidth);
1305}
1306
Dan Gohman105c1d42008-02-29 01:40:47 +00001307APInt APInt::rotl(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001308 return rotl(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001309}
1310
Chris Lattner77527f52009-01-21 18:09:24 +00001311APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001312 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001313 if (rotateAmt == 0)
1314 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001315 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001316}
1317
Dan Gohman105c1d42008-02-29 01:40:47 +00001318APInt APInt::rotr(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001319 return rotr(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001320}
1321
Chris Lattner77527f52009-01-21 18:09:24 +00001322APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001323 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001324 if (rotateAmt == 0)
1325 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001326 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001327}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001328
1329// Square Root - this method computes and returns the square root of "this".
1330// Three mechanisms are used for computation. For small values (<= 5 bits),
1331// a table lookup is done. This gets some performance for common cases. For
1332// values using less than 52 bits, the value is converted to double and then
1333// the libc sqrt function is called. The result is rounded and then converted
1334// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001335// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001336APInt APInt::sqrt() const {
1337
1338 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001339 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001340
1341 // Use a fast table for some small values. This also gets rid of some
1342 // rounding errors in libc sqrt for small values.
1343 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001344 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001345 /* 0 */ 0,
1346 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001347 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001348 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1349 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1350 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1351 /* 31 */ 6
1352 };
1353 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001354 }
1355
1356 // If the magnitude of the value fits in less than 52 bits (the precision of
1357 // an IEEE double precision floating point value), then we can use the
1358 // libc sqrt function which will probably use a hardware sqrt computation.
1359 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001360 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001361 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001362 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001363 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001364
1365 // Okay, all the short cuts are exhausted. We must compute it. The following
1366 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001367 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001368 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001369 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001370 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001371 APInt testy(BitWidth, 16);
1372 APInt x_old(BitWidth, 1);
1373 APInt x_new(BitWidth, 0);
1374 APInt two(BitWidth, 2);
1375
1376 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001377 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001378 if (i >= nbits || this->ule(testy)) {
1379 x_old = x_old.shl(i / 2);
1380 break;
1381 }
1382
Eric Christopher820256b2009-08-21 04:06:45 +00001383 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001384 for (;;) {
1385 x_new = (this->udiv(x_old) + x_old).udiv(two);
1386 if (x_old.ule(x_new))
1387 break;
1388 x_old = x_new;
1389 }
1390
1391 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001392 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001393 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001394 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001395 // floating point representation after 192 bits. There are no discrepancies
1396 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001397 APInt square(x_old * x_old);
1398 APInt nextSquare((x_old + 1) * (x_old +1));
1399 if (this->ult(square))
1400 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001401 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1402 APInt midpoint((nextSquare - square).udiv(two));
1403 APInt offset(*this - square);
1404 if (offset.ult(midpoint))
1405 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001406 return x_old + 1;
1407}
1408
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001409/// Computes the multiplicative inverse of this APInt for a given modulo. The
1410/// iterative extended Euclidean algorithm is used to solve for this value,
1411/// however we simplify it to speed up calculating only the inverse, and take
1412/// advantage of div+rem calculations. We also use some tricks to avoid copying
1413/// (potentially large) APInts around.
1414APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1415 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1416
1417 // Using the properties listed at the following web page (accessed 06/21/08):
1418 // http://www.numbertheory.org/php/euclid.html
1419 // (especially the properties numbered 3, 4 and 9) it can be proved that
1420 // BitWidth bits suffice for all the computations in the algorithm implemented
1421 // below. More precisely, this number of bits suffice if the multiplicative
1422 // inverse exists, but may not suffice for the general extended Euclidean
1423 // algorithm.
1424
1425 APInt r[2] = { modulo, *this };
1426 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1427 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001428
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001429 unsigned i;
1430 for (i = 0; r[i^1] != 0; i ^= 1) {
1431 // An overview of the math without the confusing bit-flipping:
1432 // q = r[i-2] / r[i-1]
1433 // r[i] = r[i-2] % r[i-1]
1434 // t[i] = t[i-2] - t[i-1] * q
1435 udivrem(r[i], r[i^1], q, r[i]);
1436 t[i] -= t[i^1] * q;
1437 }
1438
1439 // If this APInt and the modulo are not coprime, there is no multiplicative
1440 // inverse, so return 0. We check this by looking at the next-to-last
1441 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1442 // algorithm.
1443 if (r[i] != 1)
1444 return APInt(BitWidth, 0);
1445
1446 // The next-to-last t is the multiplicative inverse. However, we are
1447 // interested in a positive inverse. Calcuate a positive one from a negative
1448 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001449 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001450 return t[i].isNegative() ? t[i] + modulo : t[i];
1451}
1452
Jay Foadfe0c6482009-04-30 10:15:35 +00001453/// Calculate the magic numbers required to implement a signed integer division
1454/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1455/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1456/// Warren, Jr., chapter 10.
1457APInt::ms APInt::magic() const {
1458 const APInt& d = *this;
1459 unsigned p;
1460 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001461 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001462 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001463
Jay Foadfe0c6482009-04-30 10:15:35 +00001464 ad = d.abs();
1465 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1466 anc = t - 1 - t.urem(ad); // absolute value of nc
1467 p = d.getBitWidth() - 1; // initialize p
1468 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1469 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1470 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1471 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1472 do {
1473 p = p + 1;
1474 q1 = q1<<1; // update q1 = 2p/abs(nc)
1475 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1476 if (r1.uge(anc)) { // must be unsigned comparison
1477 q1 = q1 + 1;
1478 r1 = r1 - anc;
1479 }
1480 q2 = q2<<1; // update q2 = 2p/abs(d)
1481 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1482 if (r2.uge(ad)) { // must be unsigned comparison
1483 q2 = q2 + 1;
1484 r2 = r2 - ad;
1485 }
1486 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001487 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001488
Jay Foadfe0c6482009-04-30 10:15:35 +00001489 mag.m = q2 + 1;
1490 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1491 mag.s = p - d.getBitWidth(); // resulting shift
1492 return mag;
1493}
1494
1495/// Calculate the magic numbers required to implement an unsigned integer
1496/// division by a constant as a sequence of multiplies, adds and shifts.
1497/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1498/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001499/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001500/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001501APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001502 const APInt& d = *this;
1503 unsigned p;
1504 APInt nc, delta, q1, r1, q2, r2;
1505 struct mu magu;
1506 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001507 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001508 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1509 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1510
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001511 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001512 p = d.getBitWidth() - 1; // initialize p
1513 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1514 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1515 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1516 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1517 do {
1518 p = p + 1;
1519 if (r1.uge(nc - r1)) {
1520 q1 = q1 + q1 + 1; // update q1
1521 r1 = r1 + r1 - nc; // update r1
1522 }
1523 else {
1524 q1 = q1+q1; // update q1
1525 r1 = r1+r1; // update r1
1526 }
1527 if ((r2 + 1).uge(d - r2)) {
1528 if (q2.uge(signedMax)) magu.a = 1;
1529 q2 = q2+q2 + 1; // update q2
1530 r2 = r2+r2 + 1 - d; // update r2
1531 }
1532 else {
1533 if (q2.uge(signedMin)) magu.a = 1;
1534 q2 = q2+q2; // update q2
1535 r2 = r2+r2 + 1; // update r2
1536 }
1537 delta = d - 1 - r2;
1538 } while (p < d.getBitWidth()*2 &&
1539 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1540 magu.m = q2 + 1; // resulting magic number
1541 magu.s = p - d.getBitWidth(); // resulting shift
1542 return magu;
1543}
1544
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001545/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1546/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1547/// variables here have the same names as in the algorithm. Comments explain
1548/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001549static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1550 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001551 assert(u && "Must provide dividend");
1552 assert(v && "Must provide divisor");
1553 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001554 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001555 assert(n>1 && "n must be > 1");
1556
Yaron Keren39fc5a62015-03-26 19:45:19 +00001557 // b denotes the base of the number system. In our case b is 2^32.
George Burgess IV381fc0e2016-08-25 01:05:08 +00001558 const uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001559
David Greenef32fcb42010-01-05 01:28:52 +00001560 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1561 DEBUG(dbgs() << "KnuthDiv: original:");
1562 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1563 DEBUG(dbgs() << " by");
1564 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1565 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001566 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1567 // u and v by d. Note that we have taken Knuth's advice here to use a power
1568 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1569 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001570 // shift amount from the leading zeros. We are basically normalizing the u
1571 // and v so that its high bits are shifted to the top of v's range without
1572 // overflow. Note that this can require an extra word in u so that u must
1573 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001574 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001575 unsigned v_carry = 0;
1576 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001577 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001578 for (unsigned i = 0; i < m+n; ++i) {
1579 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001580 u[i] = (u[i] << shift) | u_carry;
1581 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001582 }
Chris Lattner77527f52009-01-21 18:09:24 +00001583 for (unsigned i = 0; i < n; ++i) {
1584 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001585 v[i] = (v[i] << shift) | v_carry;
1586 v_carry = v_tmp;
1587 }
1588 }
1589 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001590
David Greenef32fcb42010-01-05 01:28:52 +00001591 DEBUG(dbgs() << "KnuthDiv: normal:");
1592 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1593 DEBUG(dbgs() << " by");
1594 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1595 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001596
1597 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1598 int j = m;
1599 do {
David Greenef32fcb42010-01-05 01:28:52 +00001600 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001601 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001602 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1603 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1604 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1605 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1606 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001607 // value qp is one too large, and it eliminates all cases where qp is two
1608 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001609 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001610 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001611 uint64_t qp = dividend / v[n-1];
1612 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001613 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1614 qp--;
1615 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001616 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001617 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001618 }
David Greenef32fcb42010-01-05 01:28:52 +00001619 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001620
Reid Spencercb292e42007-02-23 01:57:13 +00001621 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1622 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1623 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001624 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001625 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1626 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1627 // true value plus b**(n+1), namely as the b's complement of
1628 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001629 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001630 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001631 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1632 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1633 u[j+i] = (unsigned)subres;
1634 borrow = (p >> 32) - (subres >> 32);
1635 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001636 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001637 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001638 bool isNeg = u[j+n] < borrow;
1639 u[j+n] -= (unsigned)borrow;
1640
David Greenef32fcb42010-01-05 01:28:52 +00001641 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1642 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1643 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001644
Eric Christopher820256b2009-08-21 04:06:45 +00001645 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001646 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001647 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001648 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001649 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001650 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001651 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001652 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001653 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1654 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001655 // since it cancels with the borrow that occurred in D4.
1656 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001657 for (unsigned i = 0; i < n; i++) {
1658 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001659 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001660 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001661 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001662 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001663 }
David Greenef32fcb42010-01-05 01:28:52 +00001664 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001665 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001666 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001667
Reid Spencercb292e42007-02-23 01:57:13 +00001668 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1669 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001670
David Greenef32fcb42010-01-05 01:28:52 +00001671 DEBUG(dbgs() << "KnuthDiv: quotient:");
1672 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1673 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001674
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001675 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1676 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1677 // compute the remainder (urem uses this).
1678 if (r) {
1679 // The value d is expressed by the "shift" value above since we avoided
1680 // multiplication by d by using a shift left. So, all we have to do is
Simon Pilgrim0099beb2017-03-09 13:57:04 +00001681 // shift right here.
Reid Spencer468ad9112007-02-24 20:38:01 +00001682 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001683 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001684 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001685 for (int i = n-1; i >= 0; i--) {
1686 r[i] = (u[i] >> shift) | carry;
1687 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001688 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001689 }
1690 } else {
1691 for (int i = n-1; i >= 0; i--) {
1692 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001693 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001694 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001695 }
David Greenef32fcb42010-01-05 01:28:52 +00001696 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001697 }
David Greenef32fcb42010-01-05 01:28:52 +00001698 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001699}
1700
Benjamin Kramerc321e532016-06-08 19:09:22 +00001701void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
1702 unsigned rhsWords, APInt *Quotient, APInt *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001703 assert(lhsWords >= rhsWords && "Fractional result");
1704
Eric Christopher820256b2009-08-21 04:06:45 +00001705 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001706 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001707 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001708 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1709 // can't use 64-bit operands here because we don't have native results of
1710 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001711 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001712 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001713 unsigned n = rhsWords * 2;
1714 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001715
1716 // Allocate space for the temporary values we need either on the stack, if
1717 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001718 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001719 unsigned *U = nullptr;
1720 unsigned *V = nullptr;
1721 unsigned *Q = nullptr;
1722 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001723 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1724 U = &SPACE[0];
1725 V = &SPACE[m+n+1];
1726 Q = &SPACE[(m+n+1) + n];
1727 if (Remainder)
1728 R = &SPACE[(m+n+1) + n + (m+n)];
1729 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001730 U = new unsigned[m + n + 1];
1731 V = new unsigned[n];
1732 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001733 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001734 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001735 }
1736
1737 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001738 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001739 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001740 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001741 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001742 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001743 }
1744 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1745
Reid Spencer522ca7c2007-02-25 01:56:07 +00001746 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001747 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001748 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001749 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001750 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001751 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001752 }
1753
Reid Spencer522ca7c2007-02-25 01:56:07 +00001754 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001755 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001756 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001757 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001758
Eric Christopher820256b2009-08-21 04:06:45 +00001759 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001760 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001761 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001762 // contain any zero words or the Knuth algorithm fails.
1763 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1764 n--;
1765 m++;
1766 }
1767 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1768 m--;
1769
1770 // If we're left with only a single word for the divisor, Knuth doesn't work
1771 // so we implement the short division algorithm here. This is much simpler
1772 // and faster because we are certain that we can divide a 64-bit quantity
1773 // by a 32-bit quantity at hardware speed and short division is simply a
1774 // series of such operations. This is just like doing short division but we
1775 // are using base 2^32 instead of base 10.
1776 assert(n != 0 && "Divide by zero?");
1777 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001778 unsigned divisor = V[0];
1779 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001780 for (int i = m+n-1; i >= 0; i--) {
1781 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1782 if (partial_dividend == 0) {
1783 Q[i] = 0;
1784 remainder = 0;
1785 } else if (partial_dividend < divisor) {
1786 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001787 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001788 } else if (partial_dividend == divisor) {
1789 Q[i] = 1;
1790 remainder = 0;
1791 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001792 Q[i] = (unsigned)(partial_dividend / divisor);
1793 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001794 }
1795 }
1796 if (R)
1797 R[0] = remainder;
1798 } else {
1799 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1800 // case n > 1.
1801 KnuthDiv(U, V, Q, R, m, n);
1802 }
1803
1804 // If the caller wants the quotient
1805 if (Quotient) {
1806 // Set up the Quotient value's memory.
1807 if (Quotient->BitWidth != LHS.BitWidth) {
1808 if (Quotient->isSingleWord())
1809 Quotient->VAL = 0;
1810 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001811 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001812 Quotient->BitWidth = LHS.BitWidth;
1813 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001814 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001815 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001816 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001817
Eric Christopher820256b2009-08-21 04:06:45 +00001818 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001819 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001820 // This case is currently dead as all users of divide() handle trivial cases
1821 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001822 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001823 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001824 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1825 if (Quotient->isSingleWord())
1826 Quotient->VAL = tmp;
1827 else
1828 Quotient->pVal[0] = tmp;
1829 } else {
1830 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1831 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001832 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001833 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1834 }
1835 }
1836
1837 // If the caller wants the remainder
1838 if (Remainder) {
1839 // Set up the Remainder value's memory.
1840 if (Remainder->BitWidth != RHS.BitWidth) {
1841 if (Remainder->isSingleWord())
1842 Remainder->VAL = 0;
1843 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001844 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001845 Remainder->BitWidth = RHS.BitWidth;
1846 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001847 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001848 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001849 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001850
1851 // The remainder is in R. Reconstitute the remainder into Remainder's low
1852 // order words.
1853 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001854 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001855 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1856 if (Remainder->isSingleWord())
1857 Remainder->VAL = tmp;
1858 else
1859 Remainder->pVal[0] = tmp;
1860 } else {
1861 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1862 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001863 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001864 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1865 }
1866 }
1867
1868 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001869 if (U != &SPACE[0]) {
1870 delete [] U;
1871 delete [] V;
1872 delete [] Q;
1873 delete [] R;
1874 }
Reid Spencer100502d2007-02-17 03:16:00 +00001875}
1876
Reid Spencer1d072122007-02-16 22:36:51 +00001877APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001878 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001879
1880 // First, deal with the easy case
1881 if (isSingleWord()) {
1882 assert(RHS.VAL != 0 && "Divide by zero?");
1883 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001884 }
Reid Spencer39867762007-02-17 02:07:07 +00001885
Reid Spencer39867762007-02-17 02:07:07 +00001886 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001887 unsigned rhsBits = RHS.getActiveBits();
1888 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001889 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001890 unsigned lhsBits = this->getActiveBits();
1891 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001892
1893 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001894 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001895 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001896 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001897 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001898 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001899 return APInt(BitWidth, 0);
1900 } else if (*this == RHS) {
1901 // X / X ===> 1
1902 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001903 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001904 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001905 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001906 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001907
1908 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1909 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001910 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001911 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001912}
1913
Jakub Staszak6605c602013-02-20 00:17:42 +00001914APInt APInt::sdiv(const APInt &RHS) const {
1915 if (isNegative()) {
1916 if (RHS.isNegative())
1917 return (-(*this)).udiv(-RHS);
1918 return -((-(*this)).udiv(RHS));
1919 }
1920 if (RHS.isNegative())
1921 return -(this->udiv(-RHS));
1922 return this->udiv(RHS);
1923}
1924
Reid Spencer1d072122007-02-16 22:36:51 +00001925APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001926 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001927 if (isSingleWord()) {
1928 assert(RHS.VAL != 0 && "Remainder by zero?");
1929 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001930 }
Reid Spencer39867762007-02-17 02:07:07 +00001931
Reid Spencer58a6a432007-02-21 08:21:52 +00001932 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001933 unsigned lhsBits = getActiveBits();
1934 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001935
1936 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001937 unsigned rhsBits = RHS.getActiveBits();
1938 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001939 assert(rhsWords && "Performing remainder operation by zero ???");
1940
Reid Spencer39867762007-02-17 02:07:07 +00001941 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001942 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001943 // 0 % Y ===> 0
1944 return APInt(BitWidth, 0);
1945 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001946 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001947 return *this;
1948 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001949 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001950 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001951 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001952 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00001953 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001954 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001955
Reid Spencer4c50b522007-05-13 23:44:59 +00001956 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001957 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001958 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001959 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001960}
Reid Spencer100502d2007-02-17 03:16:00 +00001961
Jakub Staszak6605c602013-02-20 00:17:42 +00001962APInt APInt::srem(const APInt &RHS) const {
1963 if (isNegative()) {
1964 if (RHS.isNegative())
1965 return -((-(*this)).urem(-RHS));
1966 return -((-(*this)).urem(RHS));
1967 }
1968 if (RHS.isNegative())
1969 return this->urem(-RHS);
1970 return this->urem(RHS);
1971}
1972
Eric Christopher820256b2009-08-21 04:06:45 +00001973void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001974 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001975 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1976
1977 // First, deal with the easy case
1978 if (LHS.isSingleWord()) {
1979 assert(RHS.VAL != 0 && "Divide by zero?");
1980 uint64_t QuotVal = LHS.VAL / RHS.VAL;
1981 uint64_t RemVal = LHS.VAL % RHS.VAL;
1982 Quotient = APInt(LHS.BitWidth, QuotVal);
1983 Remainder = APInt(LHS.BitWidth, RemVal);
1984 return;
1985 }
1986
Reid Spencer4c50b522007-05-13 23:44:59 +00001987 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001988 unsigned lhsBits = LHS.getActiveBits();
1989 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1990 unsigned rhsBits = RHS.getActiveBits();
1991 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00001992
1993 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001994 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00001995 Quotient = 0; // 0 / Y ===> 0
1996 Remainder = 0; // 0 % Y ===> 0
1997 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001998 }
1999
2000 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002001 Remainder = LHS; // X % Y ===> X, iff X < Y
2002 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00002003 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002004 }
2005
Reid Spencer4c50b522007-05-13 23:44:59 +00002006 if (LHS == RHS) {
2007 Quotient = 1; // X / X ===> 1
2008 Remainder = 0; // X % X ===> 0;
2009 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002010 }
2011
Reid Spencer4c50b522007-05-13 23:44:59 +00002012 if (lhsWords == 1 && rhsWords == 1) {
2013 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00002014 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
2015 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
2016 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
2017 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00002018 return;
2019 }
2020
2021 // Okay, lets do it the long way
2022 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
2023}
2024
Jakub Staszak6605c602013-02-20 00:17:42 +00002025void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
2026 APInt &Quotient, APInt &Remainder) {
2027 if (LHS.isNegative()) {
2028 if (RHS.isNegative())
2029 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
2030 else {
2031 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
2032 Quotient = -Quotient;
2033 }
2034 Remainder = -Remainder;
2035 } else if (RHS.isNegative()) {
2036 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
2037 Quotient = -Quotient;
2038 } else {
2039 APInt::udivrem(LHS, RHS, Quotient, Remainder);
2040 }
2041}
2042
Chris Lattner2c819b02010-10-13 23:54:10 +00002043APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002044 APInt Res = *this+RHS;
2045 Overflow = isNonNegative() == RHS.isNonNegative() &&
2046 Res.isNonNegative() != isNonNegative();
2047 return Res;
2048}
2049
Chris Lattner698661c2010-10-14 00:05:07 +00002050APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
2051 APInt Res = *this+RHS;
2052 Overflow = Res.ult(RHS);
2053 return Res;
2054}
2055
Chris Lattner2c819b02010-10-13 23:54:10 +00002056APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002057 APInt Res = *this - RHS;
2058 Overflow = isNonNegative() != RHS.isNonNegative() &&
2059 Res.isNonNegative() != isNonNegative();
2060 return Res;
2061}
2062
Chris Lattner698661c2010-10-14 00:05:07 +00002063APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00002064 APInt Res = *this-RHS;
2065 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00002066 return Res;
2067}
2068
Chris Lattner2c819b02010-10-13 23:54:10 +00002069APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002070 // MININT/-1 --> overflow.
2071 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
2072 return sdiv(RHS);
2073}
2074
Chris Lattner2c819b02010-10-13 23:54:10 +00002075APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002076 APInt Res = *this * RHS;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002077
Chris Lattner79bdd882010-10-13 23:46:33 +00002078 if (*this != 0 && RHS != 0)
2079 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
2080 else
2081 Overflow = false;
2082 return Res;
2083}
2084
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00002085APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
2086 APInt Res = *this * RHS;
2087
2088 if (*this != 0 && RHS != 0)
2089 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
2090 else
2091 Overflow = false;
2092 return Res;
2093}
2094
David Majnemera2521382014-10-13 21:48:30 +00002095APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
2096 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00002097 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00002098 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00002099
2100 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00002101 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00002102 else
David Majnemera2521382014-10-13 21:48:30 +00002103 Overflow = ShAmt.uge(countLeadingOnes());
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002104
Chris Lattner79bdd882010-10-13 23:46:33 +00002105 return *this << ShAmt;
2106}
2107
David Majnemera2521382014-10-13 21:48:30 +00002108APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
2109 Overflow = ShAmt.uge(getBitWidth());
2110 if (Overflow)
2111 return APInt(BitWidth, 0);
2112
2113 Overflow = ShAmt.ugt(countLeadingZeros());
2114
2115 return *this << ShAmt;
2116}
2117
Chris Lattner79bdd882010-10-13 23:46:33 +00002118
2119
2120
Benjamin Kramer92d89982010-07-14 22:38:02 +00002121void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00002122 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002123 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002124 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002125 radix == 36) &&
2126 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002127
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002128 StringRef::iterator p = str.begin();
2129 size_t slen = str.size();
2130 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002131 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002132 p++;
2133 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00002134 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002135 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00002136 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002137 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2138 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002139 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2140 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00002141
2142 // Allocate memory
2143 if (!isSingleWord())
2144 pVal = getClearedMemory(getNumWords());
2145
2146 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00002147 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00002148
2149 // Set up an APInt for the digit to add outside the loop so we don't
2150 // constantly construct/destruct it.
2151 APInt apdigit(getBitWidth(), 0);
2152 APInt apradix(getBitWidth(), radix);
2153
2154 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002155 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00002156 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00002157 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00002158
Reid Spencera93c9812007-05-16 19:18:22 +00002159 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002160 if (slen > 1) {
2161 if (shift)
2162 *this <<= shift;
2163 else
2164 *this *= apradix;
2165 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002166
2167 // Add in the digit we just interpreted
Reid Spencer632ebdf2007-02-24 20:19:37 +00002168 if (apdigit.isSingleWord())
2169 apdigit.VAL = digit;
2170 else
2171 apdigit.pVal[0] = digit;
Reid Spencer1ba83352007-02-21 03:55:44 +00002172 *this += apdigit;
Reid Spencer100502d2007-02-17 03:16:00 +00002173 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002174 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00002175 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00002176 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002177 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002178 }
Reid Spencer100502d2007-02-17 03:16:00 +00002179}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002180
Chris Lattner17f71652008-08-17 07:19:36 +00002181void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002182 bool Signed, bool formatAsCLiteral) const {
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002183 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002184 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002185 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002186
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002187 const char *Prefix = "";
2188 if (formatAsCLiteral) {
2189 switch (Radix) {
2190 case 2:
2191 // Binary literals are a non-standard extension added in gcc 4.3:
2192 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2193 Prefix = "0b";
2194 break;
2195 case 8:
2196 Prefix = "0";
2197 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002198 case 10:
2199 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002200 case 16:
2201 Prefix = "0x";
2202 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002203 default:
2204 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002205 }
2206 }
2207
Chris Lattner17f71652008-08-17 07:19:36 +00002208 // First, check for a zero value and just short circuit the logic below.
2209 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002210 while (*Prefix) {
2211 Str.push_back(*Prefix);
2212 ++Prefix;
2213 };
Chris Lattner17f71652008-08-17 07:19:36 +00002214 Str.push_back('0');
2215 return;
2216 }
Eric Christopher820256b2009-08-21 04:06:45 +00002217
Douglas Gregor663c0682011-09-14 15:54:46 +00002218 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002219
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002220 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002221 char Buffer[65];
2222 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002223
Chris Lattner17f71652008-08-17 07:19:36 +00002224 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002225 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002226 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002227 } else {
2228 int64_t I = getSExtValue();
2229 if (I >= 0) {
2230 N = I;
2231 } else {
2232 Str.push_back('-');
2233 N = -(uint64_t)I;
2234 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002235 }
Eric Christopher820256b2009-08-21 04:06:45 +00002236
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002237 while (*Prefix) {
2238 Str.push_back(*Prefix);
2239 ++Prefix;
2240 };
2241
Chris Lattner17f71652008-08-17 07:19:36 +00002242 while (N) {
2243 *--BufPtr = Digits[N % Radix];
2244 N /= Radix;
2245 }
2246 Str.append(BufPtr, Buffer+65);
2247 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002248 }
2249
Chris Lattner17f71652008-08-17 07:19:36 +00002250 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002251
Chris Lattner17f71652008-08-17 07:19:36 +00002252 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002253 // They want to print the signed version and it is a negative value
2254 // Flip the bits and add one to turn it into the equivalent positive
2255 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002256 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002257 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002258 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002259 }
Eric Christopher820256b2009-08-21 04:06:45 +00002260
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002261 while (*Prefix) {
2262 Str.push_back(*Prefix);
2263 ++Prefix;
2264 };
2265
Chris Lattner17f71652008-08-17 07:19:36 +00002266 // We insert the digits backward, then reverse them to get the right order.
2267 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002268
2269 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2270 // because the number of bits per digit (1, 3 and 4 respectively) divides
Chris Lattner17f71652008-08-17 07:19:36 +00002271 // equaly. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002272 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002273 // Just shift tmp right for each digit width until it becomes zero
2274 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2275 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002276
Chris Lattner17f71652008-08-17 07:19:36 +00002277 while (Tmp != 0) {
2278 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2279 Str.push_back(Digits[Digit]);
2280 Tmp = Tmp.lshr(ShiftAmt);
2281 }
2282 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002283 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002284 while (Tmp != 0) {
2285 APInt APdigit(1, 0);
2286 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002287 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002288 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002289 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002290 assert(Digit < Radix && "divide failed");
2291 Str.push_back(Digits[Digit]);
2292 Tmp = tmp2;
2293 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002294 }
Eric Christopher820256b2009-08-21 04:06:45 +00002295
Chris Lattner17f71652008-08-17 07:19:36 +00002296 // Reverse the digits before returning.
2297 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002298}
2299
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002300/// Returns the APInt as a std::string. Note that this is an inefficient method.
2301/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002302std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2303 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002304 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002305 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002306}
Chris Lattner6b695682007-08-16 15:56:55 +00002307
Matthias Braun8c209aa2017-01-28 02:02:38 +00002308#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002309LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002310 SmallString<40> S, U;
2311 this->toStringUnsigned(U);
2312 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002313 dbgs() << "APInt(" << BitWidth << "b, "
Davide Italiano5a473d22017-01-31 21:26:18 +00002314 << U << "u " << S << "s)\n";
Chris Lattner17f71652008-08-17 07:19:36 +00002315}
Matthias Braun8c209aa2017-01-28 02:02:38 +00002316#endif
Chris Lattner17f71652008-08-17 07:19:36 +00002317
Chris Lattner0c19df42008-08-23 22:23:09 +00002318void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002319 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002320 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002321 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002322}
2323
Chris Lattner6b695682007-08-16 15:56:55 +00002324// This implements a variety of operations on a representation of
2325// arbitrary precision, two's-complement, bignum integer values.
2326
Chris Lattner96cffa62009-08-23 23:11:28 +00002327// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2328// and unrestricting assumption.
Benjamin Kramer7000ca32014-10-12 17:56:40 +00002329static_assert(integerPartWidth % 2 == 0, "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002330
2331/* Some handy functions local to this file. */
2332namespace {
2333
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002334 /* Returns the integer part with the least significant BITS set.
2335 BITS cannot be zero. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002336 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002337 lowBitMask(unsigned int bits)
2338 {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002339 assert(bits != 0 && bits <= integerPartWidth);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002340
2341 return ~(integerPart) 0 >> (integerPartWidth - bits);
2342 }
2343
Neil Boothc8b650a2007-10-06 00:43:45 +00002344 /* Returns the value of the lower half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002345 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002346 lowHalf(integerPart part)
2347 {
2348 return part & lowBitMask(integerPartWidth / 2);
2349 }
2350
Neil Boothc8b650a2007-10-06 00:43:45 +00002351 /* Returns the value of the upper half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002352 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002353 highHalf(integerPart part)
2354 {
2355 return part >> (integerPartWidth / 2);
2356 }
2357
Neil Boothc8b650a2007-10-06 00:43:45 +00002358 /* Returns the bit number of the most significant set bit of a part.
2359 If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002360 static unsigned int
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002361 partMSB(integerPart value)
Chris Lattner6b695682007-08-16 15:56:55 +00002362 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002363 return findLastSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002364 }
2365
Neil Boothc8b650a2007-10-06 00:43:45 +00002366 /* Returns the bit number of the least significant set bit of a
2367 part. If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002368 static unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002369 partLSB(integerPart value)
2370 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002371 return findFirstSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002372 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002373}
Chris Lattner6b695682007-08-16 15:56:55 +00002374
2375/* Sets the least significant part of a bignum to the input value, and
2376 zeroes out higher parts. */
2377void
2378APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts)
2379{
2380 unsigned int i;
2381
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002382 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002383
Chris Lattner6b695682007-08-16 15:56:55 +00002384 dst[0] = part;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002385 for (i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002386 dst[i] = 0;
2387}
2388
2389/* Assign one bignum to another. */
2390void
2391APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts)
2392{
2393 unsigned int i;
2394
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002395 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002396 dst[i] = src[i];
2397}
2398
2399/* Returns true if a bignum is zero, false otherwise. */
2400bool
2401APInt::tcIsZero(const integerPart *src, unsigned int parts)
2402{
2403 unsigned int i;
2404
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002405 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002406 if (src[i])
2407 return false;
2408
2409 return true;
2410}
2411
2412/* Extract the given bit of a bignum; returns 0 or 1. */
2413int
2414APInt::tcExtractBit(const integerPart *parts, unsigned int bit)
2415{
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002416 return (parts[bit / integerPartWidth] &
2417 ((integerPart) 1 << bit % integerPartWidth)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002418}
2419
John McCalldcb9a7a2010-02-28 02:51:25 +00002420/* Set the given bit of a bignum. */
Chris Lattner6b695682007-08-16 15:56:55 +00002421void
2422APInt::tcSetBit(integerPart *parts, unsigned int bit)
2423{
2424 parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
2425}
2426
John McCalldcb9a7a2010-02-28 02:51:25 +00002427/* Clears the given bit of a bignum. */
2428void
2429APInt::tcClearBit(integerPart *parts, unsigned int bit)
2430{
2431 parts[bit / integerPartWidth] &=
2432 ~((integerPart) 1 << (bit % integerPartWidth));
2433}
2434
Neil Boothc8b650a2007-10-06 00:43:45 +00002435/* Returns the bit number of the least significant set bit of a
2436 number. If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002437unsigned int
2438APInt::tcLSB(const integerPart *parts, unsigned int n)
2439{
2440 unsigned int i, lsb;
2441
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002442 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002443 if (parts[i] != 0) {
2444 lsb = partLSB(parts[i]);
2445
2446 return lsb + i * integerPartWidth;
2447 }
2448 }
2449
2450 return -1U;
2451}
2452
Neil Boothc8b650a2007-10-06 00:43:45 +00002453/* Returns the bit number of the most significant set bit of a number.
2454 If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002455unsigned int
2456APInt::tcMSB(const integerPart *parts, unsigned int n)
2457{
2458 unsigned int msb;
2459
2460 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002461 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002462
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002463 if (parts[n] != 0) {
2464 msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002465
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002466 return msb + n * integerPartWidth;
2467 }
Chris Lattner6b695682007-08-16 15:56:55 +00002468 } while (n);
2469
2470 return -1U;
2471}
2472
Neil Boothb6182162007-10-08 13:47:12 +00002473/* Copy the bit vector of width srcBITS from SRC, starting at bit
2474 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2475 the least significant bit of DST. All high bits above srcBITS in
2476 DST are zero-filled. */
2477void
Evan Chengdb338f32009-05-21 23:47:47 +00002478APInt::tcExtract(integerPart *dst, unsigned int dstCount,const integerPart *src,
Neil Boothb6182162007-10-08 13:47:12 +00002479 unsigned int srcBits, unsigned int srcLSB)
2480{
2481 unsigned int firstSrcPart, dstParts, shift, n;
2482
2483 dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002484 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002485
2486 firstSrcPart = srcLSB / integerPartWidth;
2487 tcAssign (dst, src + firstSrcPart, dstParts);
2488
2489 shift = srcLSB % integerPartWidth;
2490 tcShiftRight (dst, dstParts, shift);
2491
2492 /* We now have (dstParts * integerPartWidth - shift) bits from SRC
2493 in DST. If this is less that srcBits, append the rest, else
2494 clear the high bits. */
2495 n = dstParts * integerPartWidth - shift;
2496 if (n < srcBits) {
2497 integerPart mask = lowBitMask (srcBits - n);
2498 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2499 << n % integerPartWidth);
2500 } else if (n > srcBits) {
Neil Booth7e74b172007-10-12 15:31:31 +00002501 if (srcBits % integerPartWidth)
2502 dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
Neil Boothb6182162007-10-08 13:47:12 +00002503 }
2504
2505 /* Clear high parts. */
2506 while (dstParts < dstCount)
2507 dst[dstParts++] = 0;
2508}
2509
Chris Lattner6b695682007-08-16 15:56:55 +00002510/* DST += RHS + C where C is zero or one. Returns the carry flag. */
2511integerPart
2512APInt::tcAdd(integerPart *dst, const integerPart *rhs,
2513 integerPart c, unsigned int parts)
2514{
2515 unsigned int i;
2516
2517 assert(c <= 1);
2518
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002519 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002520 integerPart l;
2521
2522 l = dst[i];
2523 if (c) {
2524 dst[i] += rhs[i] + 1;
2525 c = (dst[i] <= l);
2526 } else {
2527 dst[i] += rhs[i];
2528 c = (dst[i] < l);
2529 }
2530 }
2531
2532 return c;
2533}
2534
2535/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
2536integerPart
2537APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
2538 integerPart c, unsigned int parts)
2539{
2540 unsigned int i;
2541
2542 assert(c <= 1);
2543
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002544 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002545 integerPart l;
2546
2547 l = dst[i];
2548 if (c) {
2549 dst[i] -= rhs[i] + 1;
2550 c = (dst[i] >= l);
2551 } else {
2552 dst[i] -= rhs[i];
2553 c = (dst[i] > l);
2554 }
2555 }
2556
2557 return c;
2558}
2559
2560/* Negate a bignum in-place. */
2561void
2562APInt::tcNegate(integerPart *dst, unsigned int parts)
2563{
2564 tcComplement(dst, parts);
2565 tcIncrement(dst, parts);
2566}
2567
Neil Boothc8b650a2007-10-06 00:43:45 +00002568/* DST += SRC * MULTIPLIER + CARRY if add is true
2569 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002570
2571 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2572 they must start at the same point, i.e. DST == SRC.
2573
2574 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2575 returned. Otherwise DST is filled with the least significant
2576 DSTPARTS parts of the result, and if all of the omitted higher
2577 parts were zero return zero, otherwise overflow occurred and
2578 return one. */
2579int
2580APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
2581 integerPart multiplier, integerPart carry,
2582 unsigned int srcParts, unsigned int dstParts,
2583 bool add)
2584{
2585 unsigned int i, n;
2586
2587 /* Otherwise our writes of DST kill our later reads of SRC. */
2588 assert(dst <= src || dst >= src + srcParts);
2589 assert(dstParts <= srcParts + 1);
2590
2591 /* N loops; minimum of dstParts and srcParts. */
2592 n = dstParts < srcParts ? dstParts: srcParts;
2593
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002594 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002595 integerPart low, mid, high, srcPart;
2596
2597 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2598
2599 This cannot overflow, because
2600
2601 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2602
2603 which is less than n^2. */
2604
2605 srcPart = src[i];
2606
2607 if (multiplier == 0 || srcPart == 0) {
2608 low = carry;
2609 high = 0;
2610 } else {
2611 low = lowHalf(srcPart) * lowHalf(multiplier);
2612 high = highHalf(srcPart) * highHalf(multiplier);
2613
2614 mid = lowHalf(srcPart) * highHalf(multiplier);
2615 high += highHalf(mid);
2616 mid <<= integerPartWidth / 2;
2617 if (low + mid < low)
2618 high++;
2619 low += mid;
2620
2621 mid = highHalf(srcPart) * lowHalf(multiplier);
2622 high += highHalf(mid);
2623 mid <<= integerPartWidth / 2;
2624 if (low + mid < low)
2625 high++;
2626 low += mid;
2627
2628 /* Now add carry. */
2629 if (low + carry < low)
2630 high++;
2631 low += carry;
2632 }
2633
2634 if (add) {
2635 /* And now DST[i], and store the new low part there. */
2636 if (low + dst[i] < low)
2637 high++;
2638 dst[i] += low;
2639 } else
2640 dst[i] = low;
2641
2642 carry = high;
2643 }
2644
2645 if (i < dstParts) {
2646 /* Full multiplication, there is no overflow. */
2647 assert(i + 1 == dstParts);
2648 dst[i] = carry;
2649 return 0;
2650 } else {
2651 /* We overflowed if there is carry. */
2652 if (carry)
2653 return 1;
2654
2655 /* We would overflow if any significant unwritten parts would be
2656 non-zero. This is true if any remaining src parts are non-zero
2657 and the multiplier is non-zero. */
2658 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002659 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002660 if (src[i])
2661 return 1;
2662
2663 /* We fitted in the narrow destination. */
2664 return 0;
2665 }
2666}
2667
2668/* DST = LHS * RHS, where DST has the same width as the operands and
2669 is filled with the least significant parts of the result. Returns
2670 one if overflow occurred, otherwise zero. DST must be disjoint
2671 from both operands. */
2672int
2673APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
2674 const integerPart *rhs, unsigned int parts)
2675{
2676 unsigned int i;
2677 int overflow;
2678
2679 assert(dst != lhs && dst != rhs);
2680
2681 overflow = 0;
2682 tcSet(dst, 0, parts);
2683
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002684 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002685 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2686 parts - i, true);
2687
2688 return overflow;
2689}
2690
Neil Booth0ea72a92007-10-06 00:24:48 +00002691/* DST = LHS * RHS, where DST has width the sum of the widths of the
2692 operands. No overflow occurs. DST must be disjoint from both
2693 operands. Returns the number of parts required to hold the
2694 result. */
2695unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002696APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
Neil Booth0ea72a92007-10-06 00:24:48 +00002697 const integerPart *rhs, unsigned int lhsParts,
2698 unsigned int rhsParts)
Chris Lattner6b695682007-08-16 15:56:55 +00002699{
Neil Booth0ea72a92007-10-06 00:24:48 +00002700 /* Put the narrower number on the LHS for less loops below. */
2701 if (lhsParts > rhsParts) {
2702 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2703 } else {
2704 unsigned int n;
Chris Lattner6b695682007-08-16 15:56:55 +00002705
Neil Booth0ea72a92007-10-06 00:24:48 +00002706 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002707
Neil Booth0ea72a92007-10-06 00:24:48 +00002708 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002709
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002710 for (n = 0; n < lhsParts; n++)
Neil Booth0ea72a92007-10-06 00:24:48 +00002711 tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002712
Neil Booth0ea72a92007-10-06 00:24:48 +00002713 n = lhsParts + rhsParts;
2714
2715 return n - (dst[n - 1] == 0);
2716 }
Chris Lattner6b695682007-08-16 15:56:55 +00002717}
2718
2719/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2720 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2721 set REMAINDER to the remainder, return zero. i.e.
2722
2723 OLD_LHS = RHS * LHS + REMAINDER
2724
2725 SCRATCH is a bignum of the same size as the operands and result for
2726 use by the routine; its contents need not be initialized and are
2727 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2728*/
2729int
2730APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
2731 integerPart *remainder, integerPart *srhs,
2732 unsigned int parts)
2733{
2734 unsigned int n, shiftCount;
2735 integerPart mask;
2736
2737 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2738
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002739 shiftCount = tcMSB(rhs, parts) + 1;
2740 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002741 return true;
2742
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002743 shiftCount = parts * integerPartWidth - shiftCount;
Chris Lattner6b695682007-08-16 15:56:55 +00002744 n = shiftCount / integerPartWidth;
2745 mask = (integerPart) 1 << (shiftCount % integerPartWidth);
2746
2747 tcAssign(srhs, rhs, parts);
2748 tcShiftLeft(srhs, parts, shiftCount);
2749 tcAssign(remainder, lhs, parts);
2750 tcSet(lhs, 0, parts);
2751
2752 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2753 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002754 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002755 int compare;
2756
2757 compare = tcCompare(remainder, srhs, parts);
2758 if (compare >= 0) {
2759 tcSubtract(remainder, srhs, 0, parts);
2760 lhs[n] |= mask;
2761 }
2762
2763 if (shiftCount == 0)
2764 break;
2765 shiftCount--;
2766 tcShiftRight(srhs, parts, 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002767 if ((mask >>= 1) == 0) {
2768 mask = (integerPart) 1 << (integerPartWidth - 1);
2769 n--;
2770 }
Chris Lattner6b695682007-08-16 15:56:55 +00002771 }
2772
2773 return false;
2774}
2775
2776/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2777 There are no restrictions on COUNT. */
2778void
2779APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count)
2780{
Neil Boothb6182162007-10-08 13:47:12 +00002781 if (count) {
2782 unsigned int jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002783
Neil Boothb6182162007-10-08 13:47:12 +00002784 /* Jump is the inter-part jump; shift is is intra-part shift. */
2785 jump = count / integerPartWidth;
2786 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002787
Neil Boothb6182162007-10-08 13:47:12 +00002788 while (parts > jump) {
2789 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002790
Neil Boothb6182162007-10-08 13:47:12 +00002791 parts--;
Chris Lattner6b695682007-08-16 15:56:55 +00002792
Neil Boothb6182162007-10-08 13:47:12 +00002793 /* dst[i] comes from the two parts src[i - jump] and, if we have
2794 an intra-part shift, src[i - jump - 1]. */
2795 part = dst[parts - jump];
2796 if (shift) {
2797 part <<= shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002798 if (parts >= jump + 1)
2799 part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
2800 }
2801
Neil Boothb6182162007-10-08 13:47:12 +00002802 dst[parts] = part;
2803 }
Chris Lattner6b695682007-08-16 15:56:55 +00002804
Neil Boothb6182162007-10-08 13:47:12 +00002805 while (parts > 0)
2806 dst[--parts] = 0;
2807 }
Chris Lattner6b695682007-08-16 15:56:55 +00002808}
2809
2810/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2811 zero. There are no restrictions on COUNT. */
2812void
2813APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count)
2814{
Neil Boothb6182162007-10-08 13:47:12 +00002815 if (count) {
2816 unsigned int i, jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002817
Neil Boothb6182162007-10-08 13:47:12 +00002818 /* Jump is the inter-part jump; shift is is intra-part shift. */
2819 jump = count / integerPartWidth;
2820 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002821
Neil Boothb6182162007-10-08 13:47:12 +00002822 /* Perform the shift. This leaves the most significant COUNT bits
2823 of the result at zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002824 for (i = 0; i < parts; i++) {
Neil Boothb6182162007-10-08 13:47:12 +00002825 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002826
Neil Boothb6182162007-10-08 13:47:12 +00002827 if (i + jump >= parts) {
2828 part = 0;
2829 } else {
2830 part = dst[i + jump];
2831 if (shift) {
2832 part >>= shift;
2833 if (i + jump + 1 < parts)
2834 part |= dst[i + jump + 1] << (integerPartWidth - shift);
2835 }
Chris Lattner6b695682007-08-16 15:56:55 +00002836 }
Chris Lattner6b695682007-08-16 15:56:55 +00002837
Neil Boothb6182162007-10-08 13:47:12 +00002838 dst[i] = part;
2839 }
Chris Lattner6b695682007-08-16 15:56:55 +00002840 }
2841}
2842
2843/* Bitwise and of two bignums. */
2844void
2845APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts)
2846{
2847 unsigned int i;
2848
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002849 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002850 dst[i] &= rhs[i];
2851}
2852
2853/* Bitwise inclusive or of two bignums. */
2854void
2855APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts)
2856{
2857 unsigned int i;
2858
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002859 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002860 dst[i] |= rhs[i];
2861}
2862
2863/* Bitwise exclusive or of two bignums. */
2864void
2865APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts)
2866{
2867 unsigned int i;
2868
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002869 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002870 dst[i] ^= rhs[i];
2871}
2872
2873/* Complement a bignum in-place. */
2874void
2875APInt::tcComplement(integerPart *dst, unsigned int parts)
2876{
2877 unsigned int i;
2878
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002879 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002880 dst[i] = ~dst[i];
2881}
2882
2883/* Comparison (unsigned) of two bignums. */
2884int
2885APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
2886 unsigned int parts)
2887{
2888 while (parts) {
2889 parts--;
2890 if (lhs[parts] == rhs[parts])
2891 continue;
2892
2893 if (lhs[parts] > rhs[parts])
2894 return 1;
2895 else
2896 return -1;
2897 }
2898
2899 return 0;
2900}
2901
2902/* Increment a bignum in-place, return the carry flag. */
2903integerPart
2904APInt::tcIncrement(integerPart *dst, unsigned int parts)
2905{
2906 unsigned int i;
2907
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002908 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002909 if (++dst[i] != 0)
2910 break;
2911
2912 return i == parts;
2913}
2914
Michael Gottesman9d406f42013-05-28 19:50:20 +00002915/* Decrement a bignum in-place, return the borrow flag. */
2916integerPart
2917APInt::tcDecrement(integerPart *dst, unsigned int parts) {
2918 for (unsigned int i = 0; i < parts; i++) {
2919 // If the current word is non-zero, then the decrement has no effect on the
2920 // higher-order words of the integer and no borrow can occur. Exit early.
2921 if (dst[i]--)
2922 return 0;
2923 }
2924 // If every word was zero, then there is a borrow.
2925 return 1;
2926}
2927
2928
Chris Lattner6b695682007-08-16 15:56:55 +00002929/* Set the least significant BITS bits of a bignum, clear the
2930 rest. */
2931void
2932APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts,
2933 unsigned int bits)
2934{
2935 unsigned int i;
2936
2937 i = 0;
2938 while (bits > integerPartWidth) {
2939 dst[i++] = ~(integerPart) 0;
2940 bits -= integerPartWidth;
2941 }
2942
2943 if (bits)
2944 dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
2945
2946 while (i < parts)
2947 dst[i++] = 0;
2948}