blob: fa81b28cd083b67a994d33826da1c683b4d0922a [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) {
Craig Topperb339c6d2017-05-03 15:46:24 +000079 U.pVal = getClearedMemory(getNumWords());
80 U.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)
Craig Topperb339c6d2017-05-03 15:46:24 +000083 U.pVal[i] = WORD_MAX;
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) {
Craig Topperb339c6d2017-05-03 15:46:24 +000088 U.pVal = getMemory(getNumWords());
89 memcpy(U.pVal, that.U.pVal, getNumWords() * APINT_WORD_SIZE);
Chris Lattnerd57b7602008-10-11 22:07:19 +000090}
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())
Craig Topperb339c6d2017-05-03 15:46:24 +000096 U.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
Craig Topperb339c6d2017-05-03 15:46:24 +000099 U.pVal = getClearedMemory(getNumWords());
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000100 // 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
Craig Topperb339c6d2017-05-03 15:46:24 +0000103 memcpy(U.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)
Craig Topper0085ffb2017-03-20 01:29:52 +0000110 : BitWidth(numBits) {
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000111 initFromArray(bigVal);
112}
113
114APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
Craig Topper0085ffb2017-03-20 01:29:52 +0000115 : BitWidth(numBits) {
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000116 initFromArray(makeArrayRef(bigVal, numWords));
117}
118
Benjamin Kramer92d89982010-07-14 22:38:02 +0000119APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
Craig Topperb339c6d2017-05-03 15:46:24 +0000120 : BitWidth(numbits) {
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
Craig Topperc67fe572017-04-19 17:01:58 +0000125void APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer7c16cd22007-02-26 23:38:21 +0000126 // Don't do anything for X = X
127 if (this == &RHS)
Craig Topperc67fe572017-04-19 17:01:58 +0000128 return;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000129
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());
Craig Topperb339c6d2017-05-03 15:46:24 +0000133 memcpy(U.pVal, RHS.U.pVal, getNumWords() * APINT_WORD_SIZE);
Craig Topperc67fe572017-04-19 17:01:58 +0000134 return;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000135 }
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());
Craig Topperb339c6d2017-05-03 15:46:24 +0000140 U.pVal = getMemory(RHS.getNumWords());
141 memcpy(U.pVal, RHS.U.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
Eric Christopher820256b2009-08-21 04:06:45 +0000142 } else if (getNumWords() == RHS.getNumWords())
Craig Topperb339c6d2017-05-03 15:46:24 +0000143 memcpy(U.pVal, RHS.U.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
Reid Spencer7c16cd22007-02-26 23:38:21 +0000144 else if (RHS.isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000145 delete [] U.pVal;
146 U.VAL = RHS.U.VAL;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000147 } else {
Craig Topperb339c6d2017-05-03 15:46:24 +0000148 delete [] U.pVal;
149 U.pVal = getMemory(RHS.getNumWords());
150 memcpy(U.pVal, RHS.U.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
Reid Spencer7c16cd22007-02-26 23:38:21 +0000151 }
152 BitWidth = RHS.BitWidth;
Craig Topperc67fe572017-04-19 17:01:58 +0000153 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000154}
155
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000156/// This method 'profiles' an APInt for use with FoldingSet.
Ted Kremenek5c75d542008-01-19 04:23:33 +0000157void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremenek901540f2008-02-19 20:50:41 +0000158 ID.AddInteger(BitWidth);
Eric Christopher820256b2009-08-21 04:06:45 +0000159
Ted Kremenek5c75d542008-01-19 04:23:33 +0000160 if (isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000161 ID.AddInteger(U.VAL);
Ted Kremenek5c75d542008-01-19 04:23:33 +0000162 return;
163 }
164
Chris Lattner77527f52009-01-21 18:09:24 +0000165 unsigned NumWords = getNumWords();
Ted Kremenek5c75d542008-01-19 04:23:33 +0000166 for (unsigned i = 0; i < NumWords; ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +0000167 ID.AddInteger(U.pVal[i]);
Ted Kremenek5c75d542008-01-19 04:23:33 +0000168}
169
Zhou Shengdac63782007-02-06 03:00:16 +0000170/// @brief Prefix increment operator. Increments the APInt by one.
171APInt& APInt::operator++() {
Eric Christopher820256b2009-08-21 04:06:45 +0000172 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000173 ++U.VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000174 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000175 tcIncrement(U.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000176 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000177}
178
Zhou Shengdac63782007-02-06 03:00:16 +0000179/// @brief Prefix decrement operator. Decrements the APInt by one.
180APInt& APInt::operator--() {
Eric Christopher820256b2009-08-21 04:06:45 +0000181 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000182 --U.VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000183 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000184 tcDecrement(U.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000185 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000186}
187
Reid Spencera41e93b2007-02-25 19:32:03 +0000188/// Adds the RHS APint to this APInt.
189/// @returns this, after addition of RHS.
Eric Christopher820256b2009-08-21 04:06:45 +0000190/// @brief Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000191APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000192 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000193 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000194 U.VAL += RHS.U.VAL;
Craig Topper15e484a2017-04-02 06:59:43 +0000195 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000196 tcAdd(U.pVal, RHS.U.pVal, 0, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000197 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000198}
199
Pete Cooperfea21392016-07-22 20:55:46 +0000200APInt& APInt::operator+=(uint64_t RHS) {
201 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000202 U.VAL += RHS;
Pete Cooperfea21392016-07-22 20:55:46 +0000203 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000204 tcAddPart(U.pVal, RHS, getNumWords());
Pete Cooperfea21392016-07-22 20:55:46 +0000205 return clearUnusedBits();
206}
207
Reid Spencera41e93b2007-02-25 19:32:03 +0000208/// Subtracts the RHS APInt from this APInt
209/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000210/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000211APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000212 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000213 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000214 U.VAL -= RHS.U.VAL;
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000215 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000216 tcSubtract(U.pVal, RHS.U.pVal, 0, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000217 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000218}
219
Pete Cooperfea21392016-07-22 20:55:46 +0000220APInt& APInt::operator-=(uint64_t RHS) {
221 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000222 U.VAL -= RHS;
Pete Cooperfea21392016-07-22 20:55:46 +0000223 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000224 tcSubtractPart(U.pVal, RHS, getNumWords());
Pete Cooperfea21392016-07-22 20:55:46 +0000225 return clearUnusedBits();
226}
227
Dan Gohman4a618822010-02-10 16:03:48 +0000228/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000229/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000230/// @returns the carry out of the multiplication.
231/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000232static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000233 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000234 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000235 uint64_t carry = 0;
236
237 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000238 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000239 // Split x into high and low words
240 uint64_t lx = x[i] & 0xffffffffULL;
241 uint64_t hx = x[i] >> 32;
242 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000243 // hasCarry == 0, no carry
244 // hasCarry == 1, has carry
245 // hasCarry == 2, no carry and the calculation result == 0.
246 uint8_t hasCarry = 0;
247 dest[i] = carry + lx * ly;
248 // Determine if the add above introduces carry.
249 hasCarry = (dest[i] < carry) ? 1 : 0;
250 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000251 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000252 // (2^32 - 1) + 2^32 = 2^64.
253 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
254
255 carry += (lx * hy) & 0xffffffffULL;
256 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000257 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000258 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
259 }
Reid Spencer100502d2007-02-17 03:16:00 +0000260 return carry;
261}
262
Eric Christopher820256b2009-08-21 04:06:45 +0000263/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000264/// the integer array dest. Note that dest's size must be >= xlen + ylen.
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000265/// @brief Generalized multiplication of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000266static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
267 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000268 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000269 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000270 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000271 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000272 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000273 lx = x[j] & 0xffffffffULL;
274 hx = x[j] >> 32;
275 // hasCarry - A flag to indicate if has carry.
276 // hasCarry == 0, no carry
277 // hasCarry == 1, has carry
278 // hasCarry == 2, no carry and the calculation result == 0.
279 uint8_t hasCarry = 0;
280 uint64_t resul = carry + lx * ly;
281 hasCarry = (resul < carry) ? 1 : 0;
282 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
283 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
284
285 carry += (lx * hy) & 0xffffffffULL;
286 resul = (carry << 32) | (resul & 0xffffffffULL);
287 dest[i+j] += resul;
288 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000289 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000290 ((lx * hy) >> 32) + hx * hy;
291 }
292 dest[i+xlen] = carry;
293 }
294}
295
Zhou Shengdac63782007-02-06 03:00:16 +0000296APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000297 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000298 if (isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000299 U.VAL *= RHS.U.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000300 clearUnusedBits();
301 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000302 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000303
304 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000305 unsigned lhsBits = getActiveBits();
306 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000307 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000308 // 0 * X ===> 0
309 return *this;
310
311 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000312 unsigned rhsBits = RHS.getActiveBits();
313 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000314 if (!rhsWords) {
315 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000316 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000317 return *this;
318 }
319
320 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000321 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000322 uint64_t *dest = getMemory(destWords);
323
324 // Perform the long multiply
Craig Topperb339c6d2017-05-03 15:46:24 +0000325 mul(dest, U.pVal, lhsWords, RHS.U.pVal, rhsWords);
Reid Spencer58a6a432007-02-21 08:21:52 +0000326
327 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000328 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000329 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Craig Topperb339c6d2017-05-03 15:46:24 +0000330 memcpy(U.pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000331 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000332
333 // delete dest array and return
334 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000335 return *this;
336}
337
Craig Topperc67fe572017-04-19 17:01:58 +0000338void APInt::AndAssignSlowCase(const APInt& RHS) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000339 tcAnd(U.pVal, RHS.U.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000340}
341
Craig Topperc67fe572017-04-19 17:01:58 +0000342void APInt::OrAssignSlowCase(const APInt& RHS) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000343 tcOr(U.pVal, RHS.U.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000344}
345
Craig Topperc67fe572017-04-19 17:01:58 +0000346void APInt::XorAssignSlowCase(const APInt& RHS) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000347 tcXor(U.pVal, RHS.U.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000348}
349
Zhou Shengdac63782007-02-06 03:00:16 +0000350APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000351 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000352 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000353 return APInt(BitWidth, U.VAL * RHS.U.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000354 APInt Result(*this);
355 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000356 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000357}
358
Chris Lattner1ac3e252008-08-20 17:02:31 +0000359bool APInt::EqualSlowCase(const APInt& RHS) const {
Craig Topperb339c6d2017-05-03 15:46:24 +0000360 return std::equal(U.pVal, U.pVal + getNumWords(), RHS.U.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000361}
362
Craig Topper1dc8fc82017-04-21 16:13:15 +0000363int APInt::compare(const APInt& RHS) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000364 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
365 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000366 return U.VAL < RHS.U.VAL ? -1 : U.VAL > RHS.U.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000367
Craig Topperb339c6d2017-05-03 15:46:24 +0000368 return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000369}
370
Craig Topper1dc8fc82017-04-21 16:13:15 +0000371int APInt::compareSigned(const APInt& RHS) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000372 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000373 if (isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000374 int64_t lhsSext = SignExtend64(U.VAL, BitWidth);
375 int64_t rhsSext = SignExtend64(RHS.U.VAL, BitWidth);
Craig Topper1dc8fc82017-04-21 16:13:15 +0000376 return lhsSext < rhsSext ? -1 : lhsSext > rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000377 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000378
Reid Spencer54abdcf2007-02-27 18:23:40 +0000379 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000380 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000381
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000382 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
383 if (lhsNeg != rhsNeg)
Craig Topper1dc8fc82017-04-21 16:13:15 +0000384 return lhsNeg ? -1 : 1;
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000385
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000386 // Otherwise we can just use an unsigned comparison, because even negative
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000387 // numbers compare correctly this way if both have the same signed-ness.
Craig Topperb339c6d2017-05-03 15:46:24 +0000388 return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000389}
390
Craig Topperbafdd032017-03-07 01:56:01 +0000391void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
392 unsigned loWord = whichWord(loBit);
393 unsigned hiWord = whichWord(hiBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000394
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000395 // Create an initial mask for the low word with zeros below loBit.
Craig Topper5e113742017-04-22 06:31:36 +0000396 uint64_t loMask = WORD_MAX << whichBit(loBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000397
Craig Topperbafdd032017-03-07 01:56:01 +0000398 // If hiBit is not aligned, we need a high mask.
399 unsigned hiShiftAmt = whichBit(hiBit);
400 if (hiShiftAmt != 0) {
401 // Create a high mask with zeros above hiBit.
Craig Topper5e113742017-04-22 06:31:36 +0000402 uint64_t hiMask = WORD_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
Craig Topperbafdd032017-03-07 01:56:01 +0000403 // If loWord and hiWord are equal, then we combine the masks. Otherwise,
404 // set the bits in hiWord.
405 if (hiWord == loWord)
406 loMask &= hiMask;
407 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000408 U.pVal[hiWord] |= hiMask;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000409 }
Craig Topperbafdd032017-03-07 01:56:01 +0000410 // Apply the mask to the low word.
Craig Topperb339c6d2017-05-03 15:46:24 +0000411 U.pVal[loWord] |= loMask;
Craig Topperbafdd032017-03-07 01:56:01 +0000412
413 // Fill any words between loWord and hiWord with all ones.
414 for (unsigned word = loWord + 1; word < hiWord; ++word)
Craig Topperb339c6d2017-05-03 15:46:24 +0000415 U.pVal[word] = WORD_MAX;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000416}
417
Zhou Shengdac63782007-02-06 03:00:16 +0000418/// @brief Toggle every bit to its opposite value.
Craig Topperafc9e352017-03-27 17:10:21 +0000419void APInt::flipAllBitsSlowCase() {
Craig Topperb339c6d2017-05-03 15:46:24 +0000420 tcComplement(U.pVal, getNumWords());
Craig Topperafc9e352017-03-27 17:10:21 +0000421 clearUnusedBits();
422}
Zhou Shengdac63782007-02-06 03:00:16 +0000423
Eric Christopher820256b2009-08-21 04:06:45 +0000424/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000425/// as "bitPosition".
426/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000427void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000428 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000429 if ((*this)[bitPosition]) clearBit(bitPosition);
430 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000431}
432
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000433void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
434 unsigned subBitWidth = subBits.getBitWidth();
435 assert(0 < subBitWidth && (subBitWidth + bitPosition) <= BitWidth &&
436 "Illegal bit insertion");
437
438 // Insertion is a direct copy.
439 if (subBitWidth == BitWidth) {
440 *this = subBits;
441 return;
442 }
443
444 // Single word result can be done as a direct bitmask.
445 if (isSingleWord()) {
Craig Topper5e113742017-04-22 06:31:36 +0000446 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
Craig Topperb339c6d2017-05-03 15:46:24 +0000447 U.VAL &= ~(mask << bitPosition);
448 U.VAL |= (subBits.U.VAL << bitPosition);
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000449 return;
450 }
451
452 unsigned loBit = whichBit(bitPosition);
453 unsigned loWord = whichWord(bitPosition);
454 unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
455
456 // Insertion within a single word can be done as a direct bitmask.
457 if (loWord == hi1Word) {
Craig Topper5e113742017-04-22 06:31:36 +0000458 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
Craig Topperb339c6d2017-05-03 15:46:24 +0000459 U.pVal[loWord] &= ~(mask << loBit);
460 U.pVal[loWord] |= (subBits.U.VAL << loBit);
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000461 return;
462 }
463
464 // Insert on word boundaries.
465 if (loBit == 0) {
466 // Direct copy whole words.
467 unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
Craig Topperb339c6d2017-05-03 15:46:24 +0000468 memcpy(U.pVal + loWord, subBits.getRawData(),
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000469 numWholeSubWords * APINT_WORD_SIZE);
470
471 // Mask+insert remaining bits.
472 unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
473 if (remainingBits != 0) {
Craig Topper5e113742017-04-22 06:31:36 +0000474 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - remainingBits);
Craig Topperb339c6d2017-05-03 15:46:24 +0000475 U.pVal[hi1Word] &= ~mask;
476 U.pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000477 }
478 return;
479 }
480
481 // General case - set/clear individual bits in dst based on src.
482 // TODO - there is scope for optimization here, but at the moment this code
483 // path is barely used so prefer readability over performance.
484 for (unsigned i = 0; i != subBitWidth; ++i) {
485 if (subBits[i])
486 setBit(bitPosition + i);
487 else
488 clearBit(bitPosition + i);
489 }
490}
491
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000492APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
493 assert(numBits > 0 && "Can't extract zero bits");
494 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
495 "Illegal bit extraction");
496
497 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000498 return APInt(numBits, U.VAL >> bitPosition);
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000499
500 unsigned loBit = whichBit(bitPosition);
501 unsigned loWord = whichWord(bitPosition);
502 unsigned hiWord = whichWord(bitPosition + numBits - 1);
503
504 // Single word result extracting bits from a single word source.
505 if (loWord == hiWord)
Craig Topperb339c6d2017-05-03 15:46:24 +0000506 return APInt(numBits, U.pVal[loWord] >> loBit);
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000507
508 // Extracting bits that start on a source word boundary can be done
509 // as a fast memory copy.
510 if (loBit == 0)
Craig Topperb339c6d2017-05-03 15:46:24 +0000511 return APInt(numBits, makeArrayRef(U.pVal + loWord, 1 + hiWord - loWord));
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000512
513 // General case - shift + copy source words directly into place.
514 APInt Result(numBits, 0);
515 unsigned NumSrcWords = getNumWords();
516 unsigned NumDstWords = Result.getNumWords();
517
518 for (unsigned word = 0; word < NumDstWords; ++word) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000519 uint64_t w0 = U.pVal[loWord + word];
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000520 uint64_t w1 =
Craig Topperb339c6d2017-05-03 15:46:24 +0000521 (loWord + word + 1) < NumSrcWords ? U.pVal[loWord + word + 1] : 0;
522 Result.U.pVal[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000523 }
524
525 return Result.clearUnusedBits();
526}
527
Benjamin Kramer92d89982010-07-14 22:38:02 +0000528unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000529 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000530 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +0000531 radix == 36) &&
532 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000533
534 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000535
Eric Christopher43a1dec2009-08-21 04:10:31 +0000536 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000537 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000538 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000539 if (*p == '-' || *p == '+') {
540 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000541 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000542 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000543 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000544
Reid Spencer9329e7b2007-04-13 19:19:07 +0000545 // For radixes of power-of-two values, the bits required is accurately and
546 // easily computed
547 if (radix == 2)
548 return slen + isNegative;
549 if (radix == 8)
550 return slen * 3 + isNegative;
551 if (radix == 16)
552 return slen * 4 + isNegative;
553
Douglas Gregor663c0682011-09-14 15:54:46 +0000554 // FIXME: base 36
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000555
Reid Spencer9329e7b2007-04-13 19:19:07 +0000556 // This is grossly inefficient but accurate. We could probably do something
557 // with a computation of roughly slen*64/20 and then adjust by the value of
558 // the first few digits. But, I'm not sure how accurate that could be.
559
560 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000561 // be too large. This avoids the assertion in the constructor. This
562 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
563 // bits in that case.
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000564 unsigned sufficient
Douglas Gregor663c0682011-09-14 15:54:46 +0000565 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
566 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000567
568 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000569 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000570
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000571 // Compute how many bits are required. If the log is infinite, assume we need
572 // just bit.
573 unsigned log = tmp.logBase2();
574 if (log == (unsigned)-1) {
575 return isNegative + 1;
576 } else {
577 return isNegative + log + 1;
578 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000579}
580
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000581hash_code llvm::hash_value(const APInt &Arg) {
582 if (Arg.isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000583 return hash_combine(Arg.U.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000584
Craig Topperb339c6d2017-05-03 15:46:24 +0000585 return hash_combine_range(Arg.U.pVal, Arg.U.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000586}
587
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000588bool APInt::isSplat(unsigned SplatSizeInBits) const {
589 assert(getBitWidth() % SplatSizeInBits == 0 &&
590 "SplatSizeInBits must divide width!");
591 // We can check that all parts of an integer are equal by making use of a
592 // little trick: rotate and check if it's still the same value.
593 return *this == rotl(SplatSizeInBits);
594}
595
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000596/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000597APInt APInt::getHiBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000598 return this->lshr(BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000599}
600
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000601/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000602APInt APInt::getLoBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000603 APInt Result(getLowBitsSet(BitWidth, numBits));
604 Result &= *this;
605 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000606}
607
Craig Topper9881bd92017-05-02 06:32:27 +0000608/// Return a value containing V broadcasted over NewLen bits.
609APInt APInt::getSplat(unsigned NewLen, const APInt &V) {
610 assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
611
612 APInt Val = V.zextOrSelf(NewLen);
613 for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
614 Val |= Val << I;
615
616 return Val;
617}
618
Chris Lattner77527f52009-01-21 18:09:24 +0000619unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000620 unsigned Count = 0;
621 for (int i = getNumWords()-1; i >= 0; --i) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000622 uint64_t V = U.pVal[i];
Matthias Brauna6be4e82016-02-15 20:06:22 +0000623 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000624 Count += APINT_BITS_PER_WORD;
625 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000626 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000627 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000628 }
Zhou Shengdac63782007-02-06 03:00:16 +0000629 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000630 // Adjust for unused bits in the most significant word (they are zero).
631 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
632 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000633 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000634}
635
Chris Lattner77527f52009-01-21 18:09:24 +0000636unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000637 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000638 return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000639
Chris Lattner77527f52009-01-21 18:09:24 +0000640 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000641 unsigned shift;
642 if (!highWordBits) {
643 highWordBits = APINT_BITS_PER_WORD;
644 shift = 0;
645 } else {
646 shift = APINT_BITS_PER_WORD - highWordBits;
647 }
Reid Spencer31acef52007-02-27 21:59:26 +0000648 int i = getNumWords() - 1;
Craig Topperb339c6d2017-05-03 15:46:24 +0000649 unsigned Count = llvm::countLeadingOnes(U.pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000650 if (Count == highWordBits) {
651 for (i--; i >= 0; --i) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000652 if (U.pVal[i] == WORD_MAX)
Reid Spencer31acef52007-02-27 21:59:26 +0000653 Count += APINT_BITS_PER_WORD;
654 else {
Craig Topperb339c6d2017-05-03 15:46:24 +0000655 Count += llvm::countLeadingOnes(U.pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000656 break;
657 }
658 }
659 }
660 return Count;
661}
662
Chris Lattner77527f52009-01-21 18:09:24 +0000663unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000664 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000665 return std::min(unsigned(llvm::countTrailingZeros(U.VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000666 unsigned Count = 0;
667 unsigned i = 0;
Craig Topperb339c6d2017-05-03 15:46:24 +0000668 for (; i < getNumWords() && U.pVal[i] == 0; ++i)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000669 Count += APINT_BITS_PER_WORD;
670 if (i < getNumWords())
Craig Topperb339c6d2017-05-03 15:46:24 +0000671 Count += llvm::countTrailingZeros(U.pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000672 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000673}
674
Chris Lattner77527f52009-01-21 18:09:24 +0000675unsigned APInt::countTrailingOnesSlowCase() const {
676 unsigned Count = 0;
677 unsigned i = 0;
Craig Topperb339c6d2017-05-03 15:46:24 +0000678 for (; i < getNumWords() && U.pVal[i] == WORD_MAX; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000679 Count += APINT_BITS_PER_WORD;
680 if (i < getNumWords())
Craig Topperb339c6d2017-05-03 15:46:24 +0000681 Count += llvm::countTrailingOnes(U.pVal[i]);
Craig Topper3a29e3b82017-04-22 19:59:11 +0000682 assert(Count <= BitWidth);
683 return Count;
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000684}
685
Chris Lattner77527f52009-01-21 18:09:24 +0000686unsigned APInt::countPopulationSlowCase() const {
687 unsigned Count = 0;
688 for (unsigned i = 0; i < getNumWords(); ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +0000689 Count += llvm::countPopulation(U.pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000690 return Count;
691}
692
Craig Topperbaa392e2017-04-20 02:11:27 +0000693bool APInt::intersectsSlowCase(const APInt &RHS) const {
694 for (unsigned i = 0, e = getNumWords(); i != e; ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +0000695 if ((U.pVal[i] & RHS.U.pVal[i]) != 0)
Craig Topperbaa392e2017-04-20 02:11:27 +0000696 return true;
697
698 return false;
699}
700
Craig Toppera8129a12017-04-20 16:17:13 +0000701bool APInt::isSubsetOfSlowCase(const APInt &RHS) const {
702 for (unsigned i = 0, e = getNumWords(); i != e; ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +0000703 if ((U.pVal[i] & ~RHS.U.pVal[i]) != 0)
Craig Toppera8129a12017-04-20 16:17:13 +0000704 return false;
705
706 return true;
707}
708
Reid Spencer1d072122007-02-16 22:36:51 +0000709APInt APInt::byteSwap() const {
710 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
711 if (BitWidth == 16)
Craig Topperb339c6d2017-05-03 15:46:24 +0000712 return APInt(BitWidth, ByteSwap_16(uint16_t(U.VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000713 if (BitWidth == 32)
Craig Topperb339c6d2017-05-03 15:46:24 +0000714 return APInt(BitWidth, ByteSwap_32(unsigned(U.VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000715 if (BitWidth == 48) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000716 unsigned Tmp1 = unsigned(U.VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000717 Tmp1 = ByteSwap_32(Tmp1);
Craig Topperb339c6d2017-05-03 15:46:24 +0000718 uint16_t Tmp2 = uint16_t(U.VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000719 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000720 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000721 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000722 if (BitWidth == 64)
Craig Topperb339c6d2017-05-03 15:46:24 +0000723 return APInt(BitWidth, ByteSwap_64(U.VAL));
Richard Smith4f9a8082011-11-23 21:33:37 +0000724
725 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
726 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
Craig Topperb339c6d2017-05-03 15:46:24 +0000727 Result.U.pVal[I] = ByteSwap_64(U.pVal[N - I - 1]);
Richard Smith4f9a8082011-11-23 21:33:37 +0000728 if (Result.BitWidth != BitWidth) {
Richard Smith55bd3752017-04-13 20:29:59 +0000729 Result.lshrInPlace(Result.BitWidth - BitWidth);
Richard Smith4f9a8082011-11-23 21:33:37 +0000730 Result.BitWidth = BitWidth;
731 }
732 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000733}
734
Matt Arsenault155dda92016-03-21 15:00:35 +0000735APInt APInt::reverseBits() const {
736 switch (BitWidth) {
737 case 64:
Craig Topperb339c6d2017-05-03 15:46:24 +0000738 return APInt(BitWidth, llvm::reverseBits<uint64_t>(U.VAL));
Matt Arsenault155dda92016-03-21 15:00:35 +0000739 case 32:
Craig Topperb339c6d2017-05-03 15:46:24 +0000740 return APInt(BitWidth, llvm::reverseBits<uint32_t>(U.VAL));
Matt Arsenault155dda92016-03-21 15:00:35 +0000741 case 16:
Craig Topperb339c6d2017-05-03 15:46:24 +0000742 return APInt(BitWidth, llvm::reverseBits<uint16_t>(U.VAL));
Matt Arsenault155dda92016-03-21 15:00:35 +0000743 case 8:
Craig Topperb339c6d2017-05-03 15:46:24 +0000744 return APInt(BitWidth, llvm::reverseBits<uint8_t>(U.VAL));
Matt Arsenault155dda92016-03-21 15:00:35 +0000745 default:
746 break;
747 }
748
749 APInt Val(*this);
Craig Topper9eaef072017-04-18 05:02:21 +0000750 APInt Reversed(BitWidth, 0);
751 unsigned S = BitWidth;
Matt Arsenault155dda92016-03-21 15:00:35 +0000752
Craig Topper9eaef072017-04-18 05:02:21 +0000753 for (; Val != 0; Val.lshrInPlace(1)) {
Matt Arsenault155dda92016-03-21 15:00:35 +0000754 Reversed <<= 1;
Craig Topper9eaef072017-04-18 05:02:21 +0000755 Reversed |= Val[0];
Matt Arsenault155dda92016-03-21 15:00:35 +0000756 --S;
757 }
758
759 Reversed <<= S;
760 return Reversed;
761}
762
Craig Topper278ebd22017-04-01 20:30:57 +0000763APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) {
Richard Smith55bd3752017-04-13 20:29:59 +0000764 // Fast-path a common case.
765 if (A == B) return A;
766
767 // Corner cases: if either operand is zero, the other is the gcd.
768 if (!A) return B;
769 if (!B) return A;
770
771 // Count common powers of 2 and remove all other powers of 2.
772 unsigned Pow2;
773 {
774 unsigned Pow2_A = A.countTrailingZeros();
775 unsigned Pow2_B = B.countTrailingZeros();
776 if (Pow2_A > Pow2_B) {
777 A.lshrInPlace(Pow2_A - Pow2_B);
778 Pow2 = Pow2_B;
779 } else if (Pow2_B > Pow2_A) {
780 B.lshrInPlace(Pow2_B - Pow2_A);
781 Pow2 = Pow2_A;
782 } else {
783 Pow2 = Pow2_A;
784 }
Zhou Shengdac63782007-02-06 03:00:16 +0000785 }
Richard Smith55bd3752017-04-13 20:29:59 +0000786
787 // Both operands are odd multiples of 2^Pow_2:
788 //
789 // gcd(a, b) = gcd(|a - b| / 2^i, min(a, b))
790 //
791 // This is a modified version of Stein's algorithm, taking advantage of
792 // efficient countTrailingZeros().
793 while (A != B) {
794 if (A.ugt(B)) {
795 A -= B;
796 A.lshrInPlace(A.countTrailingZeros() - Pow2);
797 } else {
798 B -= A;
799 B.lshrInPlace(B.countTrailingZeros() - Pow2);
800 }
801 }
802
Zhou Shengdac63782007-02-06 03:00:16 +0000803 return A;
804}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000805
Chris Lattner77527f52009-01-21 18:09:24 +0000806APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000807 union {
808 double D;
809 uint64_t I;
810 } T;
811 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000812
813 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000814 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000815
816 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000817 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000818
819 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000820 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000821 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000822
823 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
824 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
825
826 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000827 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000828 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000829 APInt(width, mantissa >> (52 - exp));
830
831 // If the client didn't provide enough bits for us to shift the mantissa into
832 // then the result is undefined, just return 0
833 if (width <= exp - 52)
834 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000835
836 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000837 APInt Tmp(width, mantissa);
Craig Topper24e71012017-04-28 03:36:24 +0000838 Tmp <<= (unsigned)exp - 52;
Zhou Shengd707d632007-02-12 20:02:55 +0000839 return isNeg ? -Tmp : Tmp;
840}
841
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000842/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000843/// The layout for double is as following (IEEE Standard 754):
844/// --------------------------------------
845/// | Sign Exponent Fraction Bias |
846/// |-------------------------------------- |
847/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000848/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000849double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000850
851 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000852 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000853 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
854 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000855 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000856 return double(sext);
857 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000858 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000859 }
860
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000861 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000862 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000863
864 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000865 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000866
867 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000868 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000869
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000870 // The exponent (without bias normalization) is just the number of bits
871 // we are using. Note that the sign bit is gone since we constructed the
872 // absolute value.
873 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000874
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000875 // Return infinity for exponent overflow
876 if (exp > 1023) {
877 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000878 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000879 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000880 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000881 }
882 exp += 1023; // Increment for 1023 bias
883
884 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
885 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000886 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000887 unsigned hiWord = whichWord(n-1);
888 if (hiWord == 0) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000889 mantissa = Tmp.U.pVal[0];
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000890 if (n > 52)
891 mantissa >>= n - 52; // shift down, we want the top 52 bits.
892 } else {
893 assert(hiWord > 0 && "huh?");
Craig Topperb339c6d2017-05-03 15:46:24 +0000894 uint64_t hibits = Tmp.U.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
895 uint64_t lobits = Tmp.U.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000896 mantissa = hibits | lobits;
897 }
898
Zhou Shengd707d632007-02-12 20:02:55 +0000899 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000900 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000901 union {
902 double D;
903 uint64_t I;
904 } T;
905 T.I = sign | (exp << 52) | mantissa;
906 return T.D;
907}
908
Reid Spencer1d072122007-02-16 22:36:51 +0000909// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000910APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000911 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000912 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000913
914 if (width <= APINT_BITS_PER_WORD)
915 return APInt(width, getRawData()[0]);
916
917 APInt Result(getMemory(getNumWords(width)), width);
918
919 // Copy full words.
920 unsigned i;
921 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
Craig Topperb339c6d2017-05-03 15:46:24 +0000922 Result.U.pVal[i] = U.pVal[i];
Jay Foad583abbc2010-12-07 08:25:19 +0000923
924 // Truncate and copy any partial word.
925 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
926 if (bits != 0)
Craig Topperb339c6d2017-05-03 15:46:24 +0000927 Result.U.pVal[i] = U.pVal[i] << bits >> bits;
Jay Foad583abbc2010-12-07 08:25:19 +0000928
929 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000930}
931
932// Sign extend to a new width.
Craig Topper1dec2812017-04-24 17:37:10 +0000933APInt APInt::sext(unsigned Width) const {
934 assert(Width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000935
Craig Topper1dec2812017-04-24 17:37:10 +0000936 if (Width <= APINT_BITS_PER_WORD)
Craig Topperb339c6d2017-05-03 15:46:24 +0000937 return APInt(Width, SignExtend64(U.VAL, BitWidth));
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000938
Craig Topper1dec2812017-04-24 17:37:10 +0000939 APInt Result(getMemory(getNumWords(Width)), Width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000940
Craig Topper1dec2812017-04-24 17:37:10 +0000941 // Copy words.
Craig Topperb339c6d2017-05-03 15:46:24 +0000942 std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000943
Craig Topper1dec2812017-04-24 17:37:10 +0000944 // Sign extend the last word since there may be unused bits in the input.
Craig Topperb339c6d2017-05-03 15:46:24 +0000945 Result.U.pVal[getNumWords() - 1] =
946 SignExtend64(Result.U.pVal[getNumWords() - 1],
Craig Topper1dec2812017-04-24 17:37:10 +0000947 ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
Jay Foad583abbc2010-12-07 08:25:19 +0000948
Craig Topper1dec2812017-04-24 17:37:10 +0000949 // Fill with sign bits.
Craig Topperb339c6d2017-05-03 15:46:24 +0000950 std::memset(Result.U.pVal + getNumWords(), isNegative() ? -1 : 0,
Craig Topper1dec2812017-04-24 17:37:10 +0000951 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
952 Result.clearUnusedBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000953 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000954}
955
956// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000957APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000958 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000959
960 if (width <= APINT_BITS_PER_WORD)
Craig Topperb339c6d2017-05-03 15:46:24 +0000961 return APInt(width, U.VAL);
Jay Foad583abbc2010-12-07 08:25:19 +0000962
963 APInt Result(getMemory(getNumWords(width)), width);
964
965 // Copy words.
Craig Topperb339c6d2017-05-03 15:46:24 +0000966 std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
Jay Foad583abbc2010-12-07 08:25:19 +0000967
968 // Zero remaining words.
Craig Topperb339c6d2017-05-03 15:46:24 +0000969 std::memset(Result.U.pVal + getNumWords(), 0,
Craig Topper1dec2812017-04-24 17:37:10 +0000970 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
Jay Foad583abbc2010-12-07 08:25:19 +0000971
972 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000973}
974
Jay Foad583abbc2010-12-07 08:25:19 +0000975APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +0000976 if (BitWidth < width)
977 return zext(width);
978 if (BitWidth > width)
979 return trunc(width);
980 return *this;
981}
982
Jay Foad583abbc2010-12-07 08:25:19 +0000983APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +0000984 if (BitWidth < width)
985 return sext(width);
986 if (BitWidth > width)
987 return trunc(width);
988 return *this;
989}
990
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000991APInt APInt::zextOrSelf(unsigned width) const {
992 if (BitWidth < width)
993 return zext(width);
994 return *this;
995}
996
997APInt APInt::sextOrSelf(unsigned width) const {
998 if (BitWidth < width)
999 return sext(width);
1000 return *this;
1001}
1002
Zhou Shenge93db8f2007-02-09 07:48:24 +00001003/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001004/// @brief Arithmetic right-shift function.
Craig Topper8b373262017-04-24 17:18:47 +00001005void APInt::ashrInPlace(const APInt &shiftAmt) {
1006 ashrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001007}
1008
1009/// Arithmetic right-shift this APInt by shiftAmt.
1010/// @brief Arithmetic right-shift function.
Craig Topper8b373262017-04-24 17:18:47 +00001011void APInt::ashrSlowCase(unsigned ShiftAmt) {
1012 // Don't bother performing a no-op shift.
1013 if (!ShiftAmt)
1014 return;
Reid Spencer1825dd02007-03-02 22:39:11 +00001015
Craig Topper8b373262017-04-24 17:18:47 +00001016 // Save the original sign bit for later.
1017 bool Negative = isNegative();
Reid Spencer522ca7c2007-02-25 01:56:07 +00001018
Craig Topper8b373262017-04-24 17:18:47 +00001019 // WordShift is the inter-part shift; BitShift is is intra-part shift.
1020 unsigned WordShift = ShiftAmt / APINT_BITS_PER_WORD;
1021 unsigned BitShift = ShiftAmt % APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001022
Craig Topper8b373262017-04-24 17:18:47 +00001023 unsigned WordsToMove = getNumWords() - WordShift;
1024 if (WordsToMove != 0) {
1025 // Sign extend the last word to fill in the unused bits.
Craig Topperb339c6d2017-05-03 15:46:24 +00001026 U.pVal[getNumWords() - 1] = SignExtend64(
1027 U.pVal[getNumWords() - 1], ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
Renato Golincc4a9122017-04-23 12:02:07 +00001028
Craig Topper8b373262017-04-24 17:18:47 +00001029 // Fastpath for moving by whole words.
1030 if (BitShift == 0) {
Craig Topperb339c6d2017-05-03 15:46:24 +00001031 std::memmove(U.pVal, U.pVal + WordShift, WordsToMove * APINT_WORD_SIZE);
Craig Topper8b373262017-04-24 17:18:47 +00001032 } else {
1033 // Move the words containing significant bits.
1034 for (unsigned i = 0; i != WordsToMove - 1; ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +00001035 U.pVal[i] = (U.pVal[i + WordShift] >> BitShift) |
1036 (U.pVal[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift));
Renato Golincc4a9122017-04-23 12:02:07 +00001037
Craig Topper8b373262017-04-24 17:18:47 +00001038 // Handle the last word which has no high bits to copy.
Craig Topperb339c6d2017-05-03 15:46:24 +00001039 U.pVal[WordsToMove - 1] = U.pVal[WordShift + WordsToMove - 1] >> BitShift;
Craig Topper8b373262017-04-24 17:18:47 +00001040 // Sign extend one more time.
Craig Topperb339c6d2017-05-03 15:46:24 +00001041 U.pVal[WordsToMove - 1] =
1042 SignExtend64(U.pVal[WordsToMove - 1], APINT_BITS_PER_WORD - BitShift);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001043 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001044 }
1045
Craig Topper8b373262017-04-24 17:18:47 +00001046 // Fill in the remainder based on the original sign.
Craig Topperb339c6d2017-05-03 15:46:24 +00001047 std::memset(U.pVal + WordsToMove, Negative ? -1 : 0,
Craig Topper8b373262017-04-24 17:18:47 +00001048 WordShift * APINT_WORD_SIZE);
1049 clearUnusedBits();
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001050}
1051
Zhou Shenge93db8f2007-02-09 07:48:24 +00001052/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001053/// @brief Logical right-shift function.
Craig Topperfc947bc2017-04-18 17:14:21 +00001054void APInt::lshrInPlace(const APInt &shiftAmt) {
1055 lshrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001056}
1057
1058/// Logical right-shift this APInt by shiftAmt.
1059/// @brief Logical right-shift function.
Craig Topperae8bd672017-04-18 19:13:27 +00001060void APInt::lshrSlowCase(unsigned ShiftAmt) {
Craig Topperb339c6d2017-05-03 15:46:24 +00001061 tcShiftRight(U.pVal, getNumWords(), ShiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001062}
1063
Zhou Shenge93db8f2007-02-09 07:48:24 +00001064/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001065/// @brief Left-shift function.
Craig Topper24e71012017-04-28 03:36:24 +00001066APInt &APInt::operator<<=(const APInt &shiftAmt) {
Nick Lewycky030c4502009-01-19 17:42:33 +00001067 // It's undefined behavior in C to shift by BitWidth or greater.
Craig Topper24e71012017-04-28 03:36:24 +00001068 *this <<= (unsigned)shiftAmt.getLimitedValue(BitWidth);
1069 return *this;
Dan Gohman105c1d42008-02-29 01:40:47 +00001070}
1071
Craig Toppera8a4f0d2017-04-18 04:39:48 +00001072void APInt::shlSlowCase(unsigned ShiftAmt) {
Craig Topperb339c6d2017-05-03 15:46:24 +00001073 tcShiftLeft(U.pVal, getNumWords(), ShiftAmt);
Craig Toppera8a4f0d2017-04-18 04:39:48 +00001074 clearUnusedBits();
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001075}
1076
Joey Gouly51c0ae52017-02-07 11:58:22 +00001077// Calculate the rotate amount modulo the bit width.
1078static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1079 unsigned rotBitWidth = rotateAmt.getBitWidth();
1080 APInt rot = rotateAmt;
1081 if (rotBitWidth < BitWidth) {
1082 // Extend the rotate APInt, so that the urem doesn't divide by 0.
1083 // e.g. APInt(1, 32) would give APInt(1, 0).
1084 rot = rotateAmt.zext(BitWidth);
1085 }
1086 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
1087 return rot.getLimitedValue(BitWidth);
1088}
1089
Dan Gohman105c1d42008-02-29 01:40:47 +00001090APInt APInt::rotl(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001091 return rotl(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001092}
1093
Chris Lattner77527f52009-01-21 18:09:24 +00001094APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001095 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001096 if (rotateAmt == 0)
1097 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001098 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001099}
1100
Dan Gohman105c1d42008-02-29 01:40:47 +00001101APInt APInt::rotr(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001102 return rotr(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001103}
1104
Chris Lattner77527f52009-01-21 18:09:24 +00001105APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001106 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001107 if (rotateAmt == 0)
1108 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001109 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001110}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001111
1112// Square Root - this method computes and returns the square root of "this".
1113// Three mechanisms are used for computation. For small values (<= 5 bits),
1114// a table lookup is done. This gets some performance for common cases. For
1115// values using less than 52 bits, the value is converted to double and then
1116// the libc sqrt function is called. The result is rounded and then converted
1117// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001118// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001119APInt APInt::sqrt() const {
1120
1121 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001122 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001123
1124 // Use a fast table for some small values. This also gets rid of some
1125 // rounding errors in libc sqrt for small values.
1126 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001127 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001128 /* 0 */ 0,
1129 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001130 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001131 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1132 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1133 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1134 /* 31 */ 6
1135 };
Craig Topperb339c6d2017-05-03 15:46:24 +00001136 return APInt(BitWidth, results[ (isSingleWord() ? U.VAL : U.pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001137 }
1138
1139 // If the magnitude of the value fits in less than 52 bits (the precision of
1140 // an IEEE double precision floating point value), then we can use the
1141 // libc sqrt function which will probably use a hardware sqrt computation.
1142 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001143 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001144 return APInt(BitWidth,
Craig Topperb339c6d2017-05-03 15:46:24 +00001145 uint64_t(::round(::sqrt(double(isSingleWord() ? U.VAL
1146 : U.pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001147 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001148
1149 // Okay, all the short cuts are exhausted. We must compute it. The following
1150 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001151 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001152 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001153 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001154 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001155 APInt testy(BitWidth, 16);
1156 APInt x_old(BitWidth, 1);
1157 APInt x_new(BitWidth, 0);
1158 APInt two(BitWidth, 2);
1159
1160 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001161 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001162 if (i >= nbits || this->ule(testy)) {
1163 x_old = x_old.shl(i / 2);
1164 break;
1165 }
1166
Eric Christopher820256b2009-08-21 04:06:45 +00001167 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001168 for (;;) {
1169 x_new = (this->udiv(x_old) + x_old).udiv(two);
1170 if (x_old.ule(x_new))
1171 break;
1172 x_old = x_new;
1173 }
1174
1175 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001176 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001177 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001178 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001179 // floating point representation after 192 bits. There are no discrepancies
1180 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001181 APInt square(x_old * x_old);
1182 APInt nextSquare((x_old + 1) * (x_old +1));
1183 if (this->ult(square))
1184 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001185 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1186 APInt midpoint((nextSquare - square).udiv(two));
1187 APInt offset(*this - square);
1188 if (offset.ult(midpoint))
1189 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001190 return x_old + 1;
1191}
1192
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001193/// Computes the multiplicative inverse of this APInt for a given modulo. The
1194/// iterative extended Euclidean algorithm is used to solve for this value,
1195/// however we simplify it to speed up calculating only the inverse, and take
1196/// advantage of div+rem calculations. We also use some tricks to avoid copying
1197/// (potentially large) APInts around.
1198APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1199 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1200
1201 // Using the properties listed at the following web page (accessed 06/21/08):
1202 // http://www.numbertheory.org/php/euclid.html
1203 // (especially the properties numbered 3, 4 and 9) it can be proved that
1204 // BitWidth bits suffice for all the computations in the algorithm implemented
1205 // below. More precisely, this number of bits suffice if the multiplicative
1206 // inverse exists, but may not suffice for the general extended Euclidean
1207 // algorithm.
1208
1209 APInt r[2] = { modulo, *this };
1210 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1211 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001212
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001213 unsigned i;
1214 for (i = 0; r[i^1] != 0; i ^= 1) {
1215 // An overview of the math without the confusing bit-flipping:
1216 // q = r[i-2] / r[i-1]
1217 // r[i] = r[i-2] % r[i-1]
1218 // t[i] = t[i-2] - t[i-1] * q
1219 udivrem(r[i], r[i^1], q, r[i]);
1220 t[i] -= t[i^1] * q;
1221 }
1222
1223 // If this APInt and the modulo are not coprime, there is no multiplicative
1224 // inverse, so return 0. We check this by looking at the next-to-last
1225 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1226 // algorithm.
1227 if (r[i] != 1)
1228 return APInt(BitWidth, 0);
1229
1230 // The next-to-last t is the multiplicative inverse. However, we are
1231 // interested in a positive inverse. Calcuate a positive one from a negative
1232 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001233 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001234 return t[i].isNegative() ? t[i] + modulo : t[i];
1235}
1236
Jay Foadfe0c6482009-04-30 10:15:35 +00001237/// Calculate the magic numbers required to implement a signed integer division
1238/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1239/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1240/// Warren, Jr., chapter 10.
1241APInt::ms APInt::magic() const {
1242 const APInt& d = *this;
1243 unsigned p;
1244 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001245 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001246 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001247
Jay Foadfe0c6482009-04-30 10:15:35 +00001248 ad = d.abs();
1249 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1250 anc = t - 1 - t.urem(ad); // absolute value of nc
1251 p = d.getBitWidth() - 1; // initialize p
1252 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1253 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1254 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1255 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1256 do {
1257 p = p + 1;
1258 q1 = q1<<1; // update q1 = 2p/abs(nc)
1259 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1260 if (r1.uge(anc)) { // must be unsigned comparison
1261 q1 = q1 + 1;
1262 r1 = r1 - anc;
1263 }
1264 q2 = q2<<1; // update q2 = 2p/abs(d)
1265 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1266 if (r2.uge(ad)) { // must be unsigned comparison
1267 q2 = q2 + 1;
1268 r2 = r2 - ad;
1269 }
1270 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001271 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001272
Jay Foadfe0c6482009-04-30 10:15:35 +00001273 mag.m = q2 + 1;
1274 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1275 mag.s = p - d.getBitWidth(); // resulting shift
1276 return mag;
1277}
1278
1279/// Calculate the magic numbers required to implement an unsigned integer
1280/// division by a constant as a sequence of multiplies, adds and shifts.
1281/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1282/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001283/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001284/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001285APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001286 const APInt& d = *this;
1287 unsigned p;
1288 APInt nc, delta, q1, r1, q2, r2;
1289 struct mu magu;
1290 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001291 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001292 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1293 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1294
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001295 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001296 p = d.getBitWidth() - 1; // initialize p
1297 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1298 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1299 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1300 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1301 do {
1302 p = p + 1;
1303 if (r1.uge(nc - r1)) {
1304 q1 = q1 + q1 + 1; // update q1
1305 r1 = r1 + r1 - nc; // update r1
1306 }
1307 else {
1308 q1 = q1+q1; // update q1
1309 r1 = r1+r1; // update r1
1310 }
1311 if ((r2 + 1).uge(d - r2)) {
1312 if (q2.uge(signedMax)) magu.a = 1;
1313 q2 = q2+q2 + 1; // update q2
1314 r2 = r2+r2 + 1 - d; // update r2
1315 }
1316 else {
1317 if (q2.uge(signedMin)) magu.a = 1;
1318 q2 = q2+q2; // update q2
1319 r2 = r2+r2 + 1; // update r2
1320 }
1321 delta = d - 1 - r2;
1322 } while (p < d.getBitWidth()*2 &&
1323 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1324 magu.m = q2 + 1; // resulting magic number
1325 magu.s = p - d.getBitWidth(); // resulting shift
1326 return magu;
1327}
1328
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001329/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1330/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1331/// variables here have the same names as in the algorithm. Comments explain
1332/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001333static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1334 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001335 assert(u && "Must provide dividend");
1336 assert(v && "Must provide divisor");
1337 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001338 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001339 assert(n>1 && "n must be > 1");
1340
Yaron Keren39fc5a62015-03-26 19:45:19 +00001341 // b denotes the base of the number system. In our case b is 2^32.
George Burgess IV381fc0e2016-08-25 01:05:08 +00001342 const uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001343
David Greenef32fcb42010-01-05 01:28:52 +00001344 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1345 DEBUG(dbgs() << "KnuthDiv: original:");
1346 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1347 DEBUG(dbgs() << " by");
1348 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1349 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001350 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1351 // u and v by d. Note that we have taken Knuth's advice here to use a power
1352 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1353 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001354 // shift amount from the leading zeros. We are basically normalizing the u
1355 // and v so that its high bits are shifted to the top of v's range without
1356 // overflow. Note that this can require an extra word in u so that u must
1357 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001358 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001359 unsigned v_carry = 0;
1360 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001361 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001362 for (unsigned i = 0; i < m+n; ++i) {
1363 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001364 u[i] = (u[i] << shift) | u_carry;
1365 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001366 }
Chris Lattner77527f52009-01-21 18:09:24 +00001367 for (unsigned i = 0; i < n; ++i) {
1368 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001369 v[i] = (v[i] << shift) | v_carry;
1370 v_carry = v_tmp;
1371 }
1372 }
1373 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001374
David Greenef32fcb42010-01-05 01:28:52 +00001375 DEBUG(dbgs() << "KnuthDiv: normal:");
1376 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1377 DEBUG(dbgs() << " by");
1378 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1379 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001380
1381 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1382 int j = m;
1383 do {
David Greenef32fcb42010-01-05 01:28:52 +00001384 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001385 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001386 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1387 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1388 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1389 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1390 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001391 // value qp is one too large, and it eliminates all cases where qp is two
1392 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001393 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001394 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001395 uint64_t qp = dividend / v[n-1];
1396 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001397 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1398 qp--;
1399 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001400 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001401 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001402 }
David Greenef32fcb42010-01-05 01:28:52 +00001403 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001404
Reid Spencercb292e42007-02-23 01:57:13 +00001405 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1406 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1407 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001408 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001409 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1410 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1411 // true value plus b**(n+1), namely as the b's complement of
1412 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001413 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001414 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001415 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1416 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1417 u[j+i] = (unsigned)subres;
1418 borrow = (p >> 32) - (subres >> 32);
1419 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001420 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001421 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001422 bool isNeg = u[j+n] < borrow;
1423 u[j+n] -= (unsigned)borrow;
1424
David Greenef32fcb42010-01-05 01:28:52 +00001425 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1426 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1427 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001428
Eric Christopher820256b2009-08-21 04:06:45 +00001429 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001430 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001431 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001432 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001433 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001434 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001435 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001436 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001437 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1438 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001439 // since it cancels with the borrow that occurred in D4.
1440 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001441 for (unsigned i = 0; i < n; i++) {
1442 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001443 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001444 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001445 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001446 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001447 }
David Greenef32fcb42010-01-05 01:28:52 +00001448 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001449 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001450 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001451
Reid Spencercb292e42007-02-23 01:57:13 +00001452 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1453 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001454
David Greenef32fcb42010-01-05 01:28:52 +00001455 DEBUG(dbgs() << "KnuthDiv: quotient:");
1456 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1457 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001458
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001459 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1460 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1461 // compute the remainder (urem uses this).
1462 if (r) {
1463 // The value d is expressed by the "shift" value above since we avoided
1464 // multiplication by d by using a shift left. So, all we have to do is
Simon Pilgrim0099beb2017-03-09 13:57:04 +00001465 // shift right here.
Reid Spencer468ad9112007-02-24 20:38:01 +00001466 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001467 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001468 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001469 for (int i = n-1; i >= 0; i--) {
1470 r[i] = (u[i] >> shift) | carry;
1471 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001472 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001473 }
1474 } else {
1475 for (int i = n-1; i >= 0; i--) {
1476 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001477 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001478 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001479 }
David Greenef32fcb42010-01-05 01:28:52 +00001480 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001481 }
David Greenef32fcb42010-01-05 01:28:52 +00001482 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001483}
1484
Benjamin Kramerc321e532016-06-08 19:09:22 +00001485void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
1486 unsigned rhsWords, APInt *Quotient, APInt *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001487 assert(lhsWords >= rhsWords && "Fractional result");
1488
Eric Christopher820256b2009-08-21 04:06:45 +00001489 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001490 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001491 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001492 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1493 // can't use 64-bit operands here because we don't have native results of
1494 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001495 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001496 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001497 unsigned n = rhsWords * 2;
1498 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001499
1500 // Allocate space for the temporary values we need either on the stack, if
1501 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001502 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001503 unsigned *U = nullptr;
1504 unsigned *V = nullptr;
1505 unsigned *Q = nullptr;
1506 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001507 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1508 U = &SPACE[0];
1509 V = &SPACE[m+n+1];
1510 Q = &SPACE[(m+n+1) + n];
1511 if (Remainder)
1512 R = &SPACE[(m+n+1) + n + (m+n)];
1513 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001514 U = new unsigned[m + n + 1];
1515 V = new unsigned[n];
1516 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001517 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001518 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001519 }
1520
1521 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001522 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001523 for (unsigned i = 0; i < lhsWords; ++i) {
Craig Topperb339c6d2017-05-03 15:46:24 +00001524 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.U.VAL : LHS.U.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001525 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001526 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001527 }
1528 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1529
Reid Spencer522ca7c2007-02-25 01:56:07 +00001530 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001531 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001532 for (unsigned i = 0; i < rhsWords; ++i) {
Craig Topperb339c6d2017-05-03 15:46:24 +00001533 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.U.VAL : RHS.U.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001534 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001535 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001536 }
1537
Reid Spencer522ca7c2007-02-25 01:56:07 +00001538 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001539 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001540 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001541 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001542
Eric Christopher820256b2009-08-21 04:06:45 +00001543 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001544 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001545 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001546 // contain any zero words or the Knuth algorithm fails.
1547 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1548 n--;
1549 m++;
1550 }
1551 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1552 m--;
1553
1554 // If we're left with only a single word for the divisor, Knuth doesn't work
1555 // so we implement the short division algorithm here. This is much simpler
1556 // and faster because we are certain that we can divide a 64-bit quantity
1557 // by a 32-bit quantity at hardware speed and short division is simply a
1558 // series of such operations. This is just like doing short division but we
1559 // are using base 2^32 instead of base 10.
1560 assert(n != 0 && "Divide by zero?");
1561 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001562 unsigned divisor = V[0];
1563 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001564 for (int i = m+n-1; i >= 0; i--) {
1565 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1566 if (partial_dividend == 0) {
1567 Q[i] = 0;
1568 remainder = 0;
1569 } else if (partial_dividend < divisor) {
1570 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001571 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001572 } else if (partial_dividend == divisor) {
1573 Q[i] = 1;
1574 remainder = 0;
1575 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001576 Q[i] = (unsigned)(partial_dividend / divisor);
1577 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001578 }
1579 }
1580 if (R)
1581 R[0] = remainder;
1582 } else {
1583 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1584 // case n > 1.
1585 KnuthDiv(U, V, Q, R, m, n);
1586 }
1587
1588 // If the caller wants the quotient
1589 if (Quotient) {
1590 // Set up the Quotient value's memory.
1591 if (Quotient->BitWidth != LHS.BitWidth) {
1592 if (Quotient->isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +00001593 Quotient->U.VAL = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001594 else
Craig Topperb339c6d2017-05-03 15:46:24 +00001595 delete [] Quotient->U.pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001596 Quotient->BitWidth = LHS.BitWidth;
1597 if (!Quotient->isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +00001598 Quotient->U.pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001599 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001600 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001601
Eric Christopher820256b2009-08-21 04:06:45 +00001602 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001603 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001604 // This case is currently dead as all users of divide() handle trivial cases
1605 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001606 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001607 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001608 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1609 if (Quotient->isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +00001610 Quotient->U.VAL = tmp;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001611 else
Craig Topperb339c6d2017-05-03 15:46:24 +00001612 Quotient->U.pVal[0] = tmp;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001613 } else {
1614 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1615 for (unsigned i = 0; i < lhsWords; ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +00001616 Quotient->U.pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001617 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1618 }
1619 }
1620
1621 // If the caller wants the remainder
1622 if (Remainder) {
1623 // Set up the Remainder value's memory.
1624 if (Remainder->BitWidth != RHS.BitWidth) {
1625 if (Remainder->isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +00001626 Remainder->U.VAL = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001627 else
Craig Topperb339c6d2017-05-03 15:46:24 +00001628 delete [] Remainder->U.pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001629 Remainder->BitWidth = RHS.BitWidth;
1630 if (!Remainder->isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +00001631 Remainder->U.pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001632 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001633 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001634
1635 // The remainder is in R. Reconstitute the remainder into Remainder's low
1636 // order words.
1637 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001638 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001639 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1640 if (Remainder->isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +00001641 Remainder->U.VAL = tmp;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001642 else
Craig Topperb339c6d2017-05-03 15:46:24 +00001643 Remainder->U.pVal[0] = tmp;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001644 } else {
1645 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1646 for (unsigned i = 0; i < rhsWords; ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +00001647 Remainder->U.pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001648 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1649 }
1650 }
1651
1652 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001653 if (U != &SPACE[0]) {
1654 delete [] U;
1655 delete [] V;
1656 delete [] Q;
1657 delete [] R;
1658 }
Reid Spencer100502d2007-02-17 03:16:00 +00001659}
1660
Reid Spencer1d072122007-02-16 22:36:51 +00001661APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001662 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001663
1664 // First, deal with the easy case
1665 if (isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +00001666 assert(RHS.U.VAL != 0 && "Divide by zero?");
1667 return APInt(BitWidth, U.VAL / RHS.U.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001668 }
Reid Spencer39867762007-02-17 02:07:07 +00001669
Reid Spencer39867762007-02-17 02:07:07 +00001670 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001671 unsigned rhsBits = RHS.getActiveBits();
1672 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001673 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001674 unsigned lhsBits = this->getActiveBits();
1675 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001676
1677 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001678 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001679 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001680 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001681 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001682 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001683 return APInt(BitWidth, 0);
1684 } else if (*this == RHS) {
1685 // X / X ===> 1
1686 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001687 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001688 // All high words are zero, just use native divide
Craig Topperb339c6d2017-05-03 15:46:24 +00001689 return APInt(BitWidth, this->U.pVal[0] / RHS.U.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001690 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001691
1692 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1693 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001694 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001695 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001696}
1697
Jakub Staszak6605c602013-02-20 00:17:42 +00001698APInt APInt::sdiv(const APInt &RHS) const {
1699 if (isNegative()) {
1700 if (RHS.isNegative())
1701 return (-(*this)).udiv(-RHS);
1702 return -((-(*this)).udiv(RHS));
1703 }
1704 if (RHS.isNegative())
1705 return -(this->udiv(-RHS));
1706 return this->udiv(RHS);
1707}
1708
Reid Spencer1d072122007-02-16 22:36:51 +00001709APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001710 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001711 if (isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +00001712 assert(RHS.U.VAL != 0 && "Remainder by zero?");
1713 return APInt(BitWidth, U.VAL % RHS.U.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001714 }
Reid Spencer39867762007-02-17 02:07:07 +00001715
Reid Spencer58a6a432007-02-21 08:21:52 +00001716 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001717 unsigned lhsBits = getActiveBits();
1718 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001719
1720 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001721 unsigned rhsBits = RHS.getActiveBits();
1722 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001723 assert(rhsWords && "Performing remainder operation by zero ???");
1724
Reid Spencer39867762007-02-17 02:07:07 +00001725 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001726 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001727 // 0 % Y ===> 0
1728 return APInt(BitWidth, 0);
1729 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001730 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001731 return *this;
1732 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001733 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001734 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001735 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001736 // All high words are zero, just use native remainder
Craig Topperb339c6d2017-05-03 15:46:24 +00001737 return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001738 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001739
Reid Spencer4c50b522007-05-13 23:44:59 +00001740 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001741 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001742 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001743 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001744}
Reid Spencer100502d2007-02-17 03:16:00 +00001745
Jakub Staszak6605c602013-02-20 00:17:42 +00001746APInt APInt::srem(const APInt &RHS) const {
1747 if (isNegative()) {
1748 if (RHS.isNegative())
1749 return -((-(*this)).urem(-RHS));
1750 return -((-(*this)).urem(RHS));
1751 }
1752 if (RHS.isNegative())
1753 return this->urem(-RHS);
1754 return this->urem(RHS);
1755}
1756
Eric Christopher820256b2009-08-21 04:06:45 +00001757void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001758 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001759 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1760
1761 // First, deal with the easy case
1762 if (LHS.isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +00001763 assert(RHS.U.VAL != 0 && "Divide by zero?");
1764 uint64_t QuotVal = LHS.U.VAL / RHS.U.VAL;
1765 uint64_t RemVal = LHS.U.VAL % RHS.U.VAL;
David Majnemer7f039202014-12-14 09:41:56 +00001766 Quotient = APInt(LHS.BitWidth, QuotVal);
1767 Remainder = APInt(LHS.BitWidth, RemVal);
1768 return;
1769 }
1770
Reid Spencer4c50b522007-05-13 23:44:59 +00001771 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001772 unsigned lhsBits = LHS.getActiveBits();
1773 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1774 unsigned rhsBits = RHS.getActiveBits();
1775 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00001776
1777 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001778 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00001779 Quotient = 0; // 0 / Y ===> 0
1780 Remainder = 0; // 0 % Y ===> 0
1781 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001782 }
1783
1784 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001785 Remainder = LHS; // X % Y ===> X, iff X < Y
1786 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00001787 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001788 }
1789
Reid Spencer4c50b522007-05-13 23:44:59 +00001790 if (LHS == RHS) {
1791 Quotient = 1; // X / X ===> 1
1792 Remainder = 0; // X % X ===> 0;
1793 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001794 }
1795
Reid Spencer4c50b522007-05-13 23:44:59 +00001796 if (lhsWords == 1 && rhsWords == 1) {
1797 // There is only one word to consider so use the native versions.
Craig Topperb339c6d2017-05-03 15:46:24 +00001798 uint64_t lhsValue = LHS.isSingleWord() ? LHS.U.VAL : LHS.U.pVal[0];
1799 uint64_t rhsValue = RHS.isSingleWord() ? RHS.U.VAL : RHS.U.pVal[0];
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001800 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
1801 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00001802 return;
1803 }
1804
1805 // Okay, lets do it the long way
1806 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
1807}
1808
Jakub Staszak6605c602013-02-20 00:17:42 +00001809void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
1810 APInt &Quotient, APInt &Remainder) {
1811 if (LHS.isNegative()) {
1812 if (RHS.isNegative())
1813 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
1814 else {
1815 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
1816 Quotient = -Quotient;
1817 }
1818 Remainder = -Remainder;
1819 } else if (RHS.isNegative()) {
1820 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
1821 Quotient = -Quotient;
1822 } else {
1823 APInt::udivrem(LHS, RHS, Quotient, Remainder);
1824 }
1825}
1826
Chris Lattner2c819b02010-10-13 23:54:10 +00001827APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001828 APInt Res = *this+RHS;
1829 Overflow = isNonNegative() == RHS.isNonNegative() &&
1830 Res.isNonNegative() != isNonNegative();
1831 return Res;
1832}
1833
Chris Lattner698661c2010-10-14 00:05:07 +00001834APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
1835 APInt Res = *this+RHS;
1836 Overflow = Res.ult(RHS);
1837 return Res;
1838}
1839
Chris Lattner2c819b02010-10-13 23:54:10 +00001840APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001841 APInt Res = *this - RHS;
1842 Overflow = isNonNegative() != RHS.isNonNegative() &&
1843 Res.isNonNegative() != isNonNegative();
1844 return Res;
1845}
1846
Chris Lattner698661c2010-10-14 00:05:07 +00001847APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00001848 APInt Res = *this-RHS;
1849 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00001850 return Res;
1851}
1852
Chris Lattner2c819b02010-10-13 23:54:10 +00001853APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001854 // MININT/-1 --> overflow.
1855 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
1856 return sdiv(RHS);
1857}
1858
Chris Lattner2c819b02010-10-13 23:54:10 +00001859APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001860 APInt Res = *this * RHS;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001861
Chris Lattner79bdd882010-10-13 23:46:33 +00001862 if (*this != 0 && RHS != 0)
1863 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
1864 else
1865 Overflow = false;
1866 return Res;
1867}
1868
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001869APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
1870 APInt Res = *this * RHS;
1871
1872 if (*this != 0 && RHS != 0)
1873 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
1874 else
1875 Overflow = false;
1876 return Res;
1877}
1878
David Majnemera2521382014-10-13 21:48:30 +00001879APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
1880 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00001881 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00001882 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00001883
1884 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00001885 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00001886 else
David Majnemera2521382014-10-13 21:48:30 +00001887 Overflow = ShAmt.uge(countLeadingOnes());
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001888
Chris Lattner79bdd882010-10-13 23:46:33 +00001889 return *this << ShAmt;
1890}
1891
David Majnemera2521382014-10-13 21:48:30 +00001892APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
1893 Overflow = ShAmt.uge(getBitWidth());
1894 if (Overflow)
1895 return APInt(BitWidth, 0);
1896
1897 Overflow = ShAmt.ugt(countLeadingZeros());
1898
1899 return *this << ShAmt;
1900}
1901
Chris Lattner79bdd882010-10-13 23:46:33 +00001902
1903
1904
Benjamin Kramer92d89982010-07-14 22:38:02 +00001905void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00001906 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001907 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001908 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00001909 radix == 36) &&
1910 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001911
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001912 StringRef::iterator p = str.begin();
1913 size_t slen = str.size();
1914 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001915 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001916 p++;
1917 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00001918 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001919 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00001920 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00001921 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
1922 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001923 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
1924 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00001925
Craig Topperb339c6d2017-05-03 15:46:24 +00001926 // Allocate memory if needed
1927 if (isSingleWord())
1928 U.VAL = 0;
1929 else
1930 U.pVal = getClearedMemory(getNumWords());
Reid Spencer1ba83352007-02-21 03:55:44 +00001931
1932 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00001933 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00001934
Craig Topperb7d8faa2017-04-02 06:59:38 +00001935 // Set up an APInt for the radix multiplier outside the loop so we don't
Reid Spencer1ba83352007-02-21 03:55:44 +00001936 // constantly construct/destruct it.
Reid Spencer1ba83352007-02-21 03:55:44 +00001937 APInt apradix(getBitWidth(), radix);
1938
1939 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001940 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00001941 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00001942 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00001943
Reid Spencera93c9812007-05-16 19:18:22 +00001944 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00001945 if (slen > 1) {
1946 if (shift)
1947 *this <<= shift;
1948 else
1949 *this *= apradix;
1950 }
Reid Spencer1ba83352007-02-21 03:55:44 +00001951
1952 // Add in the digit we just interpreted
Craig Topperb7d8faa2017-04-02 06:59:38 +00001953 *this += digit;
Reid Spencer100502d2007-02-17 03:16:00 +00001954 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001955 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001956 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00001957 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00001958 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001959 }
Reid Spencer100502d2007-02-17 03:16:00 +00001960}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001961
Chris Lattner17f71652008-08-17 07:19:36 +00001962void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00001963 bool Signed, bool formatAsCLiteral) const {
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001964 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00001965 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00001966 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00001967
Ted Kremenekb05f02e2011-06-15 00:51:55 +00001968 const char *Prefix = "";
1969 if (formatAsCLiteral) {
1970 switch (Radix) {
1971 case 2:
1972 // Binary literals are a non-standard extension added in gcc 4.3:
1973 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
1974 Prefix = "0b";
1975 break;
1976 case 8:
1977 Prefix = "0";
1978 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00001979 case 10:
1980 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00001981 case 16:
1982 Prefix = "0x";
1983 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00001984 default:
1985 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00001986 }
1987 }
1988
Chris Lattner17f71652008-08-17 07:19:36 +00001989 // First, check for a zero value and just short circuit the logic below.
1990 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00001991 while (*Prefix) {
1992 Str.push_back(*Prefix);
1993 ++Prefix;
1994 };
Chris Lattner17f71652008-08-17 07:19:36 +00001995 Str.push_back('0');
1996 return;
1997 }
Eric Christopher820256b2009-08-21 04:06:45 +00001998
Douglas Gregor663c0682011-09-14 15:54:46 +00001999 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002000
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002001 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002002 char Buffer[65];
2003 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002004
Chris Lattner17f71652008-08-17 07:19:36 +00002005 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002006 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002007 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002008 } else {
2009 int64_t I = getSExtValue();
2010 if (I >= 0) {
2011 N = I;
2012 } else {
2013 Str.push_back('-');
2014 N = -(uint64_t)I;
2015 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002016 }
Eric Christopher820256b2009-08-21 04:06:45 +00002017
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002018 while (*Prefix) {
2019 Str.push_back(*Prefix);
2020 ++Prefix;
2021 };
2022
Chris Lattner17f71652008-08-17 07:19:36 +00002023 while (N) {
2024 *--BufPtr = Digits[N % Radix];
2025 N /= Radix;
2026 }
2027 Str.append(BufPtr, Buffer+65);
2028 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002029 }
2030
Chris Lattner17f71652008-08-17 07:19:36 +00002031 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002032
Chris Lattner17f71652008-08-17 07:19:36 +00002033 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002034 // They want to print the signed version and it is a negative value
2035 // Flip the bits and add one to turn it into the equivalent positive
2036 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002037 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002038 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002039 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002040 }
Eric Christopher820256b2009-08-21 04:06:45 +00002041
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002042 while (*Prefix) {
2043 Str.push_back(*Prefix);
2044 ++Prefix;
2045 };
2046
Chris Lattner17f71652008-08-17 07:19:36 +00002047 // We insert the digits backward, then reverse them to get the right order.
2048 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002049
2050 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2051 // because the number of bits per digit (1, 3 and 4 respectively) divides
Craig Topperd7ed50d2017-04-02 06:59:36 +00002052 // equally. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002053 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002054 // Just shift tmp right for each digit width until it becomes zero
2055 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2056 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002057
Chris Lattner17f71652008-08-17 07:19:36 +00002058 while (Tmp != 0) {
2059 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2060 Str.push_back(Digits[Digit]);
Craig Topperfc947bc2017-04-18 17:14:21 +00002061 Tmp.lshrInPlace(ShiftAmt);
Chris Lattner17f71652008-08-17 07:19:36 +00002062 }
2063 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002064 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002065 while (Tmp != 0) {
2066 APInt APdigit(1, 0);
2067 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002068 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002069 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002070 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002071 assert(Digit < Radix && "divide failed");
2072 Str.push_back(Digits[Digit]);
2073 Tmp = tmp2;
2074 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002075 }
Eric Christopher820256b2009-08-21 04:06:45 +00002076
Chris Lattner17f71652008-08-17 07:19:36 +00002077 // Reverse the digits before returning.
2078 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002079}
2080
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002081/// Returns the APInt as a std::string. Note that this is an inefficient method.
2082/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002083std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2084 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002085 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002086 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002087}
Chris Lattner6b695682007-08-16 15:56:55 +00002088
Matthias Braun8c209aa2017-01-28 02:02:38 +00002089#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002090LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002091 SmallString<40> S, U;
2092 this->toStringUnsigned(U);
2093 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002094 dbgs() << "APInt(" << BitWidth << "b, "
Davide Italiano5a473d22017-01-31 21:26:18 +00002095 << U << "u " << S << "s)\n";
Chris Lattner17f71652008-08-17 07:19:36 +00002096}
Matthias Braun8c209aa2017-01-28 02:02:38 +00002097#endif
Chris Lattner17f71652008-08-17 07:19:36 +00002098
Chris Lattner0c19df42008-08-23 22:23:09 +00002099void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002100 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002101 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002102 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002103}
2104
Chris Lattner6b695682007-08-16 15:56:55 +00002105// This implements a variety of operations on a representation of
2106// arbitrary precision, two's-complement, bignum integer values.
2107
Chris Lattner96cffa62009-08-23 23:11:28 +00002108// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2109// and unrestricting assumption.
Craig Topper55229b72017-04-02 19:17:22 +00002110static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
2111 "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002112
2113/* Some handy functions local to this file. */
Chris Lattner6b695682007-08-16 15:56:55 +00002114
Craig Topper76f42462017-03-28 05:32:53 +00002115/* Returns the integer part with the least significant BITS set.
2116 BITS cannot be zero. */
Craig Topper55229b72017-04-02 19:17:22 +00002117static inline APInt::WordType lowBitMask(unsigned bits) {
2118 assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002119
Craig Topper55229b72017-04-02 19:17:22 +00002120 return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
Craig Topper76f42462017-03-28 05:32:53 +00002121}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002122
Craig Topper76f42462017-03-28 05:32:53 +00002123/* Returns the value of the lower half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002124static inline APInt::WordType lowHalf(APInt::WordType part) {
2125 return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002126}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002127
Craig Topper76f42462017-03-28 05:32:53 +00002128/* Returns the value of the upper half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002129static inline APInt::WordType highHalf(APInt::WordType part) {
2130 return part >> (APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002131}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002132
Craig Topper76f42462017-03-28 05:32:53 +00002133/* Returns the bit number of the most significant set bit of a part.
2134 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002135static unsigned partMSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002136 return findLastSet(value, ZB_Max);
2137}
Chris Lattner6b695682007-08-16 15:56:55 +00002138
Craig Topper76f42462017-03-28 05:32:53 +00002139/* Returns the bit number of the least significant set bit of a
2140 part. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002141static unsigned partLSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002142 return findFirstSet(value, ZB_Max);
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002143}
Chris Lattner6b695682007-08-16 15:56:55 +00002144
2145/* Sets the least significant part of a bignum to the input value, and
2146 zeroes out higher parts. */
Craig Topper55229b72017-04-02 19:17:22 +00002147void APInt::tcSet(WordType *dst, WordType part, unsigned parts) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002148 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002149
Chris Lattner6b695682007-08-16 15:56:55 +00002150 dst[0] = part;
Craig Topperb0038162017-03-28 05:32:52 +00002151 for (unsigned i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002152 dst[i] = 0;
2153}
2154
2155/* Assign one bignum to another. */
Craig Topper55229b72017-04-02 19:17:22 +00002156void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002157 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002158 dst[i] = src[i];
2159}
2160
2161/* Returns true if a bignum is zero, false otherwise. */
Craig Topper55229b72017-04-02 19:17:22 +00002162bool APInt::tcIsZero(const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002163 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002164 if (src[i])
2165 return false;
2166
2167 return true;
2168}
2169
2170/* Extract the given bit of a bignum; returns 0 or 1. */
Craig Topper55229b72017-04-02 19:17:22 +00002171int APInt::tcExtractBit(const WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002172 return (parts[whichWord(bit)] & maskBit(bit)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002173}
2174
John McCalldcb9a7a2010-02-28 02:51:25 +00002175/* Set the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002176void APInt::tcSetBit(WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002177 parts[whichWord(bit)] |= maskBit(bit);
Chris Lattner6b695682007-08-16 15:56:55 +00002178}
2179
John McCalldcb9a7a2010-02-28 02:51:25 +00002180/* Clears the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002181void APInt::tcClearBit(WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002182 parts[whichWord(bit)] &= ~maskBit(bit);
John McCalldcb9a7a2010-02-28 02:51:25 +00002183}
2184
Neil Boothc8b650a2007-10-06 00:43:45 +00002185/* Returns the bit number of the least significant set bit of a
2186 number. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002187unsigned APInt::tcLSB(const WordType *parts, unsigned n) {
Craig Topperb0038162017-03-28 05:32:52 +00002188 for (unsigned i = 0; i < n; i++) {
2189 if (parts[i] != 0) {
2190 unsigned lsb = partLSB(parts[i]);
Chris Lattner6b695682007-08-16 15:56:55 +00002191
Craig Topper55229b72017-04-02 19:17:22 +00002192 return lsb + i * APINT_BITS_PER_WORD;
Craig Topperb0038162017-03-28 05:32:52 +00002193 }
Chris Lattner6b695682007-08-16 15:56:55 +00002194 }
2195
2196 return -1U;
2197}
2198
Neil Boothc8b650a2007-10-06 00:43:45 +00002199/* Returns the bit number of the most significant set bit of a number.
2200 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002201unsigned APInt::tcMSB(const WordType *parts, unsigned n) {
Chris Lattner6b695682007-08-16 15:56:55 +00002202 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002203 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002204
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002205 if (parts[n] != 0) {
Craig Topperb0038162017-03-28 05:32:52 +00002206 unsigned msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002207
Craig Topper55229b72017-04-02 19:17:22 +00002208 return msb + n * APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002209 }
Chris Lattner6b695682007-08-16 15:56:55 +00002210 } while (n);
2211
2212 return -1U;
2213}
2214
Neil Boothb6182162007-10-08 13:47:12 +00002215/* Copy the bit vector of width srcBITS from SRC, starting at bit
2216 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2217 the least significant bit of DST. All high bits above srcBITS in
2218 DST are zero-filled. */
2219void
Craig Topper55229b72017-04-02 19:17:22 +00002220APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src,
Craig Topper6a8518082017-03-28 05:32:55 +00002221 unsigned srcBits, unsigned srcLSB) {
Craig Topper55229b72017-04-02 19:17:22 +00002222 unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002223 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002224
Craig Topper55229b72017-04-02 19:17:22 +00002225 unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002226 tcAssign (dst, src + firstSrcPart, dstParts);
2227
Craig Topper55229b72017-04-02 19:17:22 +00002228 unsigned shift = srcLSB % APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002229 tcShiftRight (dst, dstParts, shift);
2230
Craig Topper55229b72017-04-02 19:17:22 +00002231 /* We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC
Neil Boothb6182162007-10-08 13:47:12 +00002232 in DST. If this is less that srcBits, append the rest, else
2233 clear the high bits. */
Craig Topper55229b72017-04-02 19:17:22 +00002234 unsigned n = dstParts * APINT_BITS_PER_WORD - shift;
Neil Boothb6182162007-10-08 13:47:12 +00002235 if (n < srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002236 WordType mask = lowBitMask (srcBits - n);
Neil Boothb6182162007-10-08 13:47:12 +00002237 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
Craig Topper55229b72017-04-02 19:17:22 +00002238 << n % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002239 } else if (n > srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002240 if (srcBits % APINT_BITS_PER_WORD)
2241 dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002242 }
2243
2244 /* Clear high parts. */
2245 while (dstParts < dstCount)
2246 dst[dstParts++] = 0;
2247}
2248
Chris Lattner6b695682007-08-16 15:56:55 +00002249/* DST += RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002250APInt::WordType APInt::tcAdd(WordType *dst, const WordType *rhs,
2251 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002252 assert(c <= 1);
2253
Craig Topperb0038162017-03-28 05:32:52 +00002254 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002255 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002256 if (c) {
2257 dst[i] += rhs[i] + 1;
2258 c = (dst[i] <= l);
2259 } else {
2260 dst[i] += rhs[i];
2261 c = (dst[i] < l);
2262 }
2263 }
2264
2265 return c;
2266}
2267
Craig Topper92fc4772017-04-13 04:36:06 +00002268/// This function adds a single "word" integer, src, to the multiple
2269/// "word" integer array, dst[]. dst[] is modified to reflect the addition and
2270/// 1 is returned if there is a carry out, otherwise 0 is returned.
2271/// @returns the carry of the addition.
2272APInt::WordType APInt::tcAddPart(WordType *dst, WordType src,
2273 unsigned parts) {
2274 for (unsigned i = 0; i < parts; ++i) {
2275 dst[i] += src;
2276 if (dst[i] >= src)
2277 return 0; // No need to carry so exit early.
2278 src = 1; // Carry one to next digit.
2279 }
2280
2281 return 1;
2282}
2283
Chris Lattner6b695682007-08-16 15:56:55 +00002284/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002285APInt::WordType APInt::tcSubtract(WordType *dst, const WordType *rhs,
2286 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002287 assert(c <= 1);
2288
Craig Topperb0038162017-03-28 05:32:52 +00002289 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002290 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002291 if (c) {
2292 dst[i] -= rhs[i] + 1;
2293 c = (dst[i] >= l);
2294 } else {
2295 dst[i] -= rhs[i];
2296 c = (dst[i] > l);
2297 }
2298 }
2299
2300 return c;
2301}
2302
Craig Topper92fc4772017-04-13 04:36:06 +00002303/// This function subtracts a single "word" (64-bit word), src, from
2304/// the multi-word integer array, dst[], propagating the borrowed 1 value until
2305/// no further borrowing is needed or it runs out of "words" in dst. The result
2306/// is 1 if "borrowing" exhausted the digits in dst, or 0 if dst was not
2307/// exhausted. In other words, if src > dst then this function returns 1,
2308/// otherwise 0.
2309/// @returns the borrow out of the subtraction
2310APInt::WordType APInt::tcSubtractPart(WordType *dst, WordType src,
2311 unsigned parts) {
2312 for (unsigned i = 0; i < parts; ++i) {
2313 WordType Dst = dst[i];
2314 dst[i] -= src;
2315 if (src <= Dst)
2316 return 0; // No need to borrow so exit early.
2317 src = 1; // We have to "borrow 1" from next "word"
2318 }
2319
2320 return 1;
2321}
2322
Chris Lattner6b695682007-08-16 15:56:55 +00002323/* Negate a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002324void APInt::tcNegate(WordType *dst, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002325 tcComplement(dst, parts);
2326 tcIncrement(dst, parts);
2327}
2328
Neil Boothc8b650a2007-10-06 00:43:45 +00002329/* DST += SRC * MULTIPLIER + CARRY if add is true
2330 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002331
2332 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2333 they must start at the same point, i.e. DST == SRC.
2334
2335 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2336 returned. Otherwise DST is filled with the least significant
2337 DSTPARTS parts of the result, and if all of the omitted higher
2338 parts were zero return zero, otherwise overflow occurred and
2339 return one. */
Craig Topper55229b72017-04-02 19:17:22 +00002340int APInt::tcMultiplyPart(WordType *dst, const WordType *src,
2341 WordType multiplier, WordType carry,
Craig Topper6a8518082017-03-28 05:32:55 +00002342 unsigned srcParts, unsigned dstParts,
2343 bool add) {
Chris Lattner6b695682007-08-16 15:56:55 +00002344 /* Otherwise our writes of DST kill our later reads of SRC. */
2345 assert(dst <= src || dst >= src + srcParts);
2346 assert(dstParts <= srcParts + 1);
2347
2348 /* N loops; minimum of dstParts and srcParts. */
Craig Topperb0038162017-03-28 05:32:52 +00002349 unsigned n = dstParts < srcParts ? dstParts: srcParts;
Chris Lattner6b695682007-08-16 15:56:55 +00002350
Craig Topperb0038162017-03-28 05:32:52 +00002351 unsigned i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002352 for (i = 0; i < n; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002353 WordType low, mid, high, srcPart;
Chris Lattner6b695682007-08-16 15:56:55 +00002354
2355 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2356
2357 This cannot overflow, because
2358
2359 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2360
2361 which is less than n^2. */
2362
2363 srcPart = src[i];
2364
Craig Topper6a8518082017-03-28 05:32:55 +00002365 if (multiplier == 0 || srcPart == 0) {
Chris Lattner6b695682007-08-16 15:56:55 +00002366 low = carry;
2367 high = 0;
2368 } else {
2369 low = lowHalf(srcPart) * lowHalf(multiplier);
2370 high = highHalf(srcPart) * highHalf(multiplier);
2371
2372 mid = lowHalf(srcPart) * highHalf(multiplier);
2373 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002374 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002375 if (low + mid < low)
2376 high++;
2377 low += mid;
2378
2379 mid = highHalf(srcPart) * lowHalf(multiplier);
2380 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002381 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002382 if (low + mid < low)
2383 high++;
2384 low += mid;
2385
2386 /* Now add carry. */
2387 if (low + carry < low)
2388 high++;
2389 low += carry;
2390 }
2391
2392 if (add) {
2393 /* And now DST[i], and store the new low part there. */
2394 if (low + dst[i] < low)
2395 high++;
2396 dst[i] += low;
2397 } else
2398 dst[i] = low;
2399
2400 carry = high;
2401 }
2402
2403 if (i < dstParts) {
2404 /* Full multiplication, there is no overflow. */
2405 assert(i + 1 == dstParts);
2406 dst[i] = carry;
2407 return 0;
2408 } else {
2409 /* We overflowed if there is carry. */
2410 if (carry)
2411 return 1;
2412
2413 /* We would overflow if any significant unwritten parts would be
2414 non-zero. This is true if any remaining src parts are non-zero
2415 and the multiplier is non-zero. */
2416 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002417 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002418 if (src[i])
2419 return 1;
2420
2421 /* We fitted in the narrow destination. */
2422 return 0;
2423 }
2424}
2425
2426/* DST = LHS * RHS, where DST has the same width as the operands and
2427 is filled with the least significant parts of the result. Returns
2428 one if overflow occurred, otherwise zero. DST must be disjoint
2429 from both operands. */
Craig Topper55229b72017-04-02 19:17:22 +00002430int APInt::tcMultiply(WordType *dst, const WordType *lhs,
2431 const WordType *rhs, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002432 assert(dst != lhs && dst != rhs);
2433
Craig Topperb0038162017-03-28 05:32:52 +00002434 int overflow = 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002435 tcSet(dst, 0, parts);
2436
Craig Topperb0038162017-03-28 05:32:52 +00002437 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002438 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2439 parts - i, true);
2440
2441 return overflow;
2442}
2443
Neil Booth0ea72a92007-10-06 00:24:48 +00002444/* DST = LHS * RHS, where DST has width the sum of the widths of the
2445 operands. No overflow occurs. DST must be disjoint from both
2446 operands. Returns the number of parts required to hold the
2447 result. */
Craig Topper55229b72017-04-02 19:17:22 +00002448unsigned APInt::tcFullMultiply(WordType *dst, const WordType *lhs,
2449 const WordType *rhs, unsigned lhsParts,
Craig Topper6a8518082017-03-28 05:32:55 +00002450 unsigned rhsParts) {
Neil Booth0ea72a92007-10-06 00:24:48 +00002451 /* Put the narrower number on the LHS for less loops below. */
2452 if (lhsParts > rhsParts) {
2453 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2454 } else {
Neil Booth0ea72a92007-10-06 00:24:48 +00002455 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002456
Neil Booth0ea72a92007-10-06 00:24:48 +00002457 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002458
Craig Topperb0038162017-03-28 05:32:52 +00002459 for (unsigned i = 0; i < lhsParts; i++)
2460 tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002461
Craig Topperb0038162017-03-28 05:32:52 +00002462 unsigned n = lhsParts + rhsParts;
Neil Booth0ea72a92007-10-06 00:24:48 +00002463
2464 return n - (dst[n - 1] == 0);
2465 }
Chris Lattner6b695682007-08-16 15:56:55 +00002466}
2467
2468/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2469 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2470 set REMAINDER to the remainder, return zero. i.e.
2471
2472 OLD_LHS = RHS * LHS + REMAINDER
2473
2474 SCRATCH is a bignum of the same size as the operands and result for
2475 use by the routine; its contents need not be initialized and are
2476 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2477*/
Craig Topper55229b72017-04-02 19:17:22 +00002478int APInt::tcDivide(WordType *lhs, const WordType *rhs,
2479 WordType *remainder, WordType *srhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002480 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002481 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2482
Craig Topperb0038162017-03-28 05:32:52 +00002483 unsigned shiftCount = tcMSB(rhs, parts) + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002484 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002485 return true;
2486
Craig Topper55229b72017-04-02 19:17:22 +00002487 shiftCount = parts * APINT_BITS_PER_WORD - shiftCount;
2488 unsigned n = shiftCount / APINT_BITS_PER_WORD;
2489 WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD);
Chris Lattner6b695682007-08-16 15:56:55 +00002490
2491 tcAssign(srhs, rhs, parts);
2492 tcShiftLeft(srhs, parts, shiftCount);
2493 tcAssign(remainder, lhs, parts);
2494 tcSet(lhs, 0, parts);
2495
2496 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2497 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002498 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002499 int compare;
2500
2501 compare = tcCompare(remainder, srhs, parts);
2502 if (compare >= 0) {
2503 tcSubtract(remainder, srhs, 0, parts);
2504 lhs[n] |= mask;
2505 }
2506
2507 if (shiftCount == 0)
2508 break;
2509 shiftCount--;
2510 tcShiftRight(srhs, parts, 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002511 if ((mask >>= 1) == 0) {
Craig Topper55229b72017-04-02 19:17:22 +00002512 mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002513 n--;
2514 }
Chris Lattner6b695682007-08-16 15:56:55 +00002515 }
2516
2517 return false;
2518}
2519
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002520/// Shift a bignum left Cound bits in-place. Shifted in bits are zero. There are
2521/// no restrictions on Count.
2522void APInt::tcShiftLeft(WordType *Dst, unsigned Words, unsigned Count) {
2523 // Don't bother performing a no-op shift.
2524 if (!Count)
2525 return;
Chris Lattner6b695682007-08-16 15:56:55 +00002526
Craig Topperc6b05682017-04-24 17:00:22 +00002527 // WordShift is the inter-part shift; BitShift is the intra-part shift.
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002528 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2529 unsigned BitShift = Count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002530
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002531 // Fastpath for moving by whole words.
2532 if (BitShift == 0) {
2533 std::memmove(Dst + WordShift, Dst, (Words - WordShift) * APINT_WORD_SIZE);
2534 } else {
2535 while (Words-- > WordShift) {
2536 Dst[Words] = Dst[Words - WordShift] << BitShift;
2537 if (Words > WordShift)
2538 Dst[Words] |=
2539 Dst[Words - WordShift - 1] >> (APINT_BITS_PER_WORD - BitShift);
Neil Boothb6182162007-10-08 13:47:12 +00002540 }
Neil Boothb6182162007-10-08 13:47:12 +00002541 }
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002542
2543 // Fill in the remainder with 0s.
2544 std::memset(Dst, 0, WordShift * APINT_WORD_SIZE);
Chris Lattner6b695682007-08-16 15:56:55 +00002545}
2546
Craig Topper9575d8f2017-04-17 21:43:43 +00002547/// Shift a bignum right Count bits in-place. Shifted in bits are zero. There
2548/// are no restrictions on Count.
2549void APInt::tcShiftRight(WordType *Dst, unsigned Words, unsigned Count) {
2550 // Don't bother performing a no-op shift.
2551 if (!Count)
2552 return;
Chris Lattner6b695682007-08-16 15:56:55 +00002553
Craig Topperc6b05682017-04-24 17:00:22 +00002554 // WordShift is the inter-part shift; BitShift is the intra-part shift.
Craig Topper9575d8f2017-04-17 21:43:43 +00002555 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2556 unsigned BitShift = Count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002557
Craig Topper9575d8f2017-04-17 21:43:43 +00002558 unsigned WordsToMove = Words - WordShift;
2559 // Fastpath for moving by whole words.
2560 if (BitShift == 0) {
2561 std::memmove(Dst, Dst + WordShift, WordsToMove * APINT_WORD_SIZE);
2562 } else {
2563 for (unsigned i = 0; i != WordsToMove; ++i) {
2564 Dst[i] = Dst[i + WordShift] >> BitShift;
2565 if (i + 1 != WordsToMove)
2566 Dst[i] |= Dst[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift);
Neil Boothb6182162007-10-08 13:47:12 +00002567 }
Chris Lattner6b695682007-08-16 15:56:55 +00002568 }
Craig Topper9575d8f2017-04-17 21:43:43 +00002569
2570 // Fill in the remainder with 0s.
2571 std::memset(Dst + WordsToMove, 0, WordShift * APINT_WORD_SIZE);
Chris Lattner6b695682007-08-16 15:56:55 +00002572}
2573
2574/* Bitwise and of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002575void APInt::tcAnd(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002576 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002577 dst[i] &= rhs[i];
2578}
2579
2580/* Bitwise inclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002581void APInt::tcOr(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002582 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002583 dst[i] |= rhs[i];
2584}
2585
2586/* Bitwise exclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002587void APInt::tcXor(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002588 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002589 dst[i] ^= rhs[i];
2590}
2591
2592/* Complement a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002593void APInt::tcComplement(WordType *dst, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002594 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002595 dst[i] = ~dst[i];
2596}
2597
2598/* Comparison (unsigned) of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002599int APInt::tcCompare(const WordType *lhs, const WordType *rhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002600 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002601 while (parts) {
Craig Topper99cfe4f2017-04-01 21:50:06 +00002602 parts--;
Craig Topper1dc8fc82017-04-21 16:13:15 +00002603 if (lhs[parts] != rhs[parts])
2604 return (lhs[parts] > rhs[parts]) ? 1 : -1;
Craig Topper99cfe4f2017-04-01 21:50:06 +00002605 }
Chris Lattner6b695682007-08-16 15:56:55 +00002606
2607 return 0;
2608}
2609
Chris Lattner6b695682007-08-16 15:56:55 +00002610/* Set the least significant BITS bits of a bignum, clear the
2611 rest. */
Craig Topper55229b72017-04-02 19:17:22 +00002612void APInt::tcSetLeastSignificantBits(WordType *dst, unsigned parts,
Craig Topper6a8518082017-03-28 05:32:55 +00002613 unsigned bits) {
Craig Topperb0038162017-03-28 05:32:52 +00002614 unsigned i = 0;
Craig Topper55229b72017-04-02 19:17:22 +00002615 while (bits > APINT_BITS_PER_WORD) {
2616 dst[i++] = ~(WordType) 0;
2617 bits -= APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002618 }
2619
2620 if (bits)
Craig Topper55229b72017-04-02 19:17:22 +00002621 dst[i++] = ~(WordType) 0 >> (APINT_BITS_PER_WORD - bits);
Chris Lattner6b695682007-08-16 15:56:55 +00002622
2623 while (i < parts)
2624 dst[i++] = 0;
2625}