blob: ad964e2f3c872802199176b2701fe4b1a7f54c7c [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 Topper0085ffb2017-03-20 01:29:52 +000079 VAL = 0;
Chris Lattner1ac3e252008-08-20 17:02:31 +000080 pVal = getClearedMemory(getNumWords());
81 pVal[0] = val;
Eric Christopher820256b2009-08-21 04:06:45 +000082 if (isSigned && int64_t(val) < 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +000083 for (unsigned i = 1; i < getNumWords(); ++i)
84 pVal[i] = -1ULL;
Craig Topperf78a6f02017-03-01 21:06:18 +000085 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +000086}
87
Chris Lattnerd57b7602008-10-11 22:07:19 +000088void APInt::initSlowCase(const APInt& that) {
Craig Topper0085ffb2017-03-20 01:29:52 +000089 VAL = 0;
Chris Lattnerd57b7602008-10-11 22:07:19 +000090 pVal = getMemory(getNumWords());
91 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
92}
93
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000094void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +000095 assert(BitWidth && "Bitwidth too small");
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000096 assert(bigVal.data() && "Null pointer detected!");
Zhou Shengdac63782007-02-06 03:00:16 +000097 if (isSingleWord())
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000098 VAL = bigVal[0];
Zhou Shengdac63782007-02-06 03:00:16 +000099 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000100 // Get memory, cleared to 0
Craig Topper0085ffb2017-03-20 01:29:52 +0000101 VAL = 0;
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000102 pVal = getClearedMemory(getNumWords());
103 // Calculate the number of words to copy
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000104 unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000105 // Copy the words from bigVal to pVal
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000106 memcpy(pVal, bigVal.data(), words * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000107 }
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000108 // Make sure unused high bits are cleared
109 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000110}
111
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000112APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal)
Craig Topper0085ffb2017-03-20 01:29:52 +0000113 : BitWidth(numBits) {
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000114 initFromArray(bigVal);
115}
116
117APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
Craig Topper0085ffb2017-03-20 01:29:52 +0000118 : BitWidth(numBits) {
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000119 initFromArray(makeArrayRef(bigVal, numWords));
120}
121
Benjamin Kramer92d89982010-07-14 22:38:02 +0000122APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
Craig Topper90377de2017-04-13 04:59:11 +0000123 : VAL(0), BitWidth(numbits) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000124 assert(BitWidth && "Bitwidth too small");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000125 fromString(numbits, Str, radix);
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000126}
127
Craig Topperc67fe572017-04-19 17:01:58 +0000128void APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer7c16cd22007-02-26 23:38:21 +0000129 // Don't do anything for X = X
130 if (this == &RHS)
Craig Topperc67fe572017-04-19 17:01:58 +0000131 return;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000132
Reid Spencer7c16cd22007-02-26 23:38:21 +0000133 if (BitWidth == RHS.getBitWidth()) {
Chris Lattner1ac3e252008-08-20 17:02:31 +0000134 // assume same bit-width single-word case is already handled
135 assert(!isSingleWord());
136 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Craig Topperc67fe572017-04-19 17:01:58 +0000137 return;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000138 }
139
Chris Lattner1ac3e252008-08-20 17:02:31 +0000140 if (isSingleWord()) {
141 // assume case where both are single words is already handled
142 assert(!RHS.isSingleWord());
143 VAL = 0;
144 pVal = getMemory(RHS.getNumWords());
145 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
Eric Christopher820256b2009-08-21 04:06:45 +0000146 } else if (getNumWords() == RHS.getNumWords())
Reid Spencer7c16cd22007-02-26 23:38:21 +0000147 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
148 else if (RHS.isSingleWord()) {
149 delete [] pVal;
Reid Spencera856b6e2007-02-18 18:38:44 +0000150 VAL = RHS.VAL;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000151 } else {
152 delete [] pVal;
153 pVal = getMemory(RHS.getNumWords());
154 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
155 }
156 BitWidth = RHS.BitWidth;
Craig Topperc67fe572017-04-19 17:01:58 +0000157 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000158}
159
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000160/// This method 'profiles' an APInt for use with FoldingSet.
Ted Kremenek5c75d542008-01-19 04:23:33 +0000161void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremenek901540f2008-02-19 20:50:41 +0000162 ID.AddInteger(BitWidth);
Eric Christopher820256b2009-08-21 04:06:45 +0000163
Ted Kremenek5c75d542008-01-19 04:23:33 +0000164 if (isSingleWord()) {
165 ID.AddInteger(VAL);
166 return;
167 }
168
Chris Lattner77527f52009-01-21 18:09:24 +0000169 unsigned NumWords = getNumWords();
Ted Kremenek5c75d542008-01-19 04:23:33 +0000170 for (unsigned i = 0; i < NumWords; ++i)
171 ID.AddInteger(pVal[i]);
172}
173
Zhou Shengdac63782007-02-06 03:00:16 +0000174/// @brief Prefix increment operator. Increments the APInt by one.
175APInt& APInt::operator++() {
Eric Christopher820256b2009-08-21 04:06:45 +0000176 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000177 ++VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000178 else
Craig Topper92fc4772017-04-13 04:36:06 +0000179 tcIncrement(pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000180 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000181}
182
Zhou Shengdac63782007-02-06 03:00:16 +0000183/// @brief Prefix decrement operator. Decrements the APInt by one.
184APInt& APInt::operator--() {
Eric Christopher820256b2009-08-21 04:06:45 +0000185 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000186 --VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000187 else
Craig Topper92fc4772017-04-13 04:36:06 +0000188 tcDecrement(pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000189 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000190}
191
Reid Spencera41e93b2007-02-25 19:32:03 +0000192/// Adds the RHS APint to this APInt.
193/// @returns this, after addition of RHS.
Eric Christopher820256b2009-08-21 04:06:45 +0000194/// @brief Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000195APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000196 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000197 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000198 VAL += RHS.VAL;
Craig Topper15e484a2017-04-02 06:59:43 +0000199 else
200 tcAdd(pVal, RHS.pVal, 0, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000201 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000202}
203
Pete Cooperfea21392016-07-22 20:55:46 +0000204APInt& APInt::operator+=(uint64_t RHS) {
205 if (isSingleWord())
206 VAL += RHS;
207 else
Craig Topper92fc4772017-04-13 04:36:06 +0000208 tcAddPart(pVal, RHS, getNumWords());
Pete Cooperfea21392016-07-22 20:55:46 +0000209 return clearUnusedBits();
210}
211
Reid Spencera41e93b2007-02-25 19:32:03 +0000212/// Subtracts the RHS APInt from this APInt
213/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000214/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000215APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000216 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000217 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000218 VAL -= RHS.VAL;
219 else
Craig Topper15e484a2017-04-02 06:59:43 +0000220 tcSubtract(pVal, RHS.pVal, 0, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000221 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000222}
223
Pete Cooperfea21392016-07-22 20:55:46 +0000224APInt& APInt::operator-=(uint64_t RHS) {
225 if (isSingleWord())
226 VAL -= RHS;
227 else
Craig Topper92fc4772017-04-13 04:36:06 +0000228 tcSubtractPart(pVal, RHS, getNumWords());
Pete Cooperfea21392016-07-22 20:55:46 +0000229 return clearUnusedBits();
230}
231
Dan Gohman4a618822010-02-10 16:03:48 +0000232/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000233/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000234/// @returns the carry out of the multiplication.
235/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000236static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000237 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000238 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000239 uint64_t carry = 0;
240
241 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000242 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000243 // Split x into high and low words
244 uint64_t lx = x[i] & 0xffffffffULL;
245 uint64_t hx = x[i] >> 32;
246 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000247 // hasCarry == 0, no carry
248 // hasCarry == 1, has carry
249 // hasCarry == 2, no carry and the calculation result == 0.
250 uint8_t hasCarry = 0;
251 dest[i] = carry + lx * ly;
252 // Determine if the add above introduces carry.
253 hasCarry = (dest[i] < carry) ? 1 : 0;
254 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000255 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000256 // (2^32 - 1) + 2^32 = 2^64.
257 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
258
259 carry += (lx * hy) & 0xffffffffULL;
260 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000261 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000262 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
263 }
Reid Spencer100502d2007-02-17 03:16:00 +0000264 return carry;
265}
266
Eric Christopher820256b2009-08-21 04:06:45 +0000267/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000268/// the integer array dest. Note that dest's size must be >= xlen + ylen.
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000269/// @brief Generalized multiplication of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000270static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
271 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000272 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000273 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000274 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000275 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000276 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000277 lx = x[j] & 0xffffffffULL;
278 hx = x[j] >> 32;
279 // hasCarry - A flag to indicate if has carry.
280 // hasCarry == 0, no carry
281 // hasCarry == 1, has carry
282 // hasCarry == 2, no carry and the calculation result == 0.
283 uint8_t hasCarry = 0;
284 uint64_t resul = carry + lx * ly;
285 hasCarry = (resul < carry) ? 1 : 0;
286 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
287 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
288
289 carry += (lx * hy) & 0xffffffffULL;
290 resul = (carry << 32) | (resul & 0xffffffffULL);
291 dest[i+j] += resul;
292 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000293 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000294 ((lx * hy) >> 32) + hx * hy;
295 }
296 dest[i+xlen] = carry;
297 }
298}
299
Zhou Shengdac63782007-02-06 03:00:16 +0000300APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000301 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000302 if (isSingleWord()) {
Reid Spencer4bb430c2007-02-20 20:42:10 +0000303 VAL *= RHS.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000304 clearUnusedBits();
305 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000306 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000307
308 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000309 unsigned lhsBits = getActiveBits();
310 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000311 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000312 // 0 * X ===> 0
313 return *this;
314
315 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000316 unsigned rhsBits = RHS.getActiveBits();
317 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000318 if (!rhsWords) {
319 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000320 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000321 return *this;
322 }
323
324 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000325 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000326 uint64_t *dest = getMemory(destWords);
327
328 // Perform the long multiply
329 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
330
331 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000332 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000333 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000334 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000335 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000336
337 // delete dest array and return
338 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000339 return *this;
340}
341
Craig Topperc67fe572017-04-19 17:01:58 +0000342void APInt::AndAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000343 tcAnd(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000344}
345
Craig Topperc67fe572017-04-19 17:01:58 +0000346void APInt::OrAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000347 tcOr(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000348}
349
Craig Topperc67fe572017-04-19 17:01:58 +0000350void APInt::XorAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000351 tcXor(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000352}
353
Zhou Shengdac63782007-02-06 03:00:16 +0000354APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000355 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000356 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000357 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000358 APInt Result(*this);
359 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000360 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000361}
362
Chris Lattner1ac3e252008-08-20 17:02:31 +0000363bool APInt::EqualSlowCase(const APInt& RHS) const {
Matthias Braun5117fcd2016-02-15 20:06:19 +0000364 return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000365}
366
Chris Lattner1ac3e252008-08-20 17:02:31 +0000367bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000368 unsigned n = getActiveBits();
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000369 if (n <= APINT_BITS_PER_WORD)
370 return pVal[0] == Val;
371 else
372 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000373}
374
Reid Spencer1d072122007-02-16 22:36:51 +0000375bool APInt::ult(const APInt& RHS) const {
376 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
377 if (isSingleWord())
378 return VAL < RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000379
380 // Get active bit length of both operands
Chris Lattner77527f52009-01-21 18:09:24 +0000381 unsigned n1 = getActiveBits();
382 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000383
384 // If magnitude of LHS is less than RHS, return true.
385 if (n1 < n2)
386 return true;
387
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000388 // If magnitude of RHS is greater than LHS, return false.
Reid Spencera41e93b2007-02-25 19:32:03 +0000389 if (n2 < n1)
390 return false;
391
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000392 // If they both fit in a word, just compare the low order word
Reid Spencera41e93b2007-02-25 19:32:03 +0000393 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
394 return pVal[0] < RHS.pVal[0];
395
396 // Otherwise, compare all words
Chris Lattner77527f52009-01-21 18:09:24 +0000397 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000398 for (int i = topWord; i >= 0; --i) {
Eric Christopher820256b2009-08-21 04:06:45 +0000399 if (pVal[i] > RHS.pVal[i])
Reid Spencer1d072122007-02-16 22:36:51 +0000400 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000401 if (pVal[i] < RHS.pVal[i])
Reid Spencera41e93b2007-02-25 19:32:03 +0000402 return true;
Zhou Shengdac63782007-02-06 03:00:16 +0000403 }
404 return false;
405}
406
Reid Spencer1d072122007-02-16 22:36:51 +0000407bool APInt::slt(const APInt& RHS) const {
408 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000409 if (isSingleWord()) {
David Majnemer5f1c0172016-06-24 20:51:47 +0000410 int64_t lhsSext = SignExtend64(VAL, BitWidth);
411 int64_t rhsSext = SignExtend64(RHS.VAL, BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000412 return lhsSext < rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000413 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000414
Reid Spencer54abdcf2007-02-27 18:23:40 +0000415 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000416 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000417
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000418 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
419 if (lhsNeg != rhsNeg)
420 return lhsNeg;
421
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000422 // Otherwise we can just use an unsigned comparison, because even negative
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000423 // numbers compare correctly this way if both have the same signed-ness.
424 return ult(RHS);
Zhou Shengdac63782007-02-06 03:00:16 +0000425}
426
Jay Foad25a5e4c2010-12-01 08:53:58 +0000427void APInt::setBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000428 if (isSingleWord())
Reid Spencera41e93b2007-02-25 19:32:03 +0000429 VAL |= maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000430 else
Reid Spencera41e93b2007-02-25 19:32:03 +0000431 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000432}
433
Craig Topperbafdd032017-03-07 01:56:01 +0000434void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
435 unsigned loWord = whichWord(loBit);
436 unsigned hiWord = whichWord(hiBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000437
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000438 // Create an initial mask for the low word with zeros below loBit.
Craig Topperbafdd032017-03-07 01:56:01 +0000439 uint64_t loMask = UINT64_MAX << whichBit(loBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000440
Craig Topperbafdd032017-03-07 01:56:01 +0000441 // If hiBit is not aligned, we need a high mask.
442 unsigned hiShiftAmt = whichBit(hiBit);
443 if (hiShiftAmt != 0) {
444 // Create a high mask with zeros above hiBit.
445 uint64_t hiMask = UINT64_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
446 // If loWord and hiWord are equal, then we combine the masks. Otherwise,
447 // set the bits in hiWord.
448 if (hiWord == loWord)
449 loMask &= hiMask;
450 else
Simon Pilgrimaed35222017-02-24 10:15:29 +0000451 pVal[hiWord] |= hiMask;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000452 }
Craig Topperbafdd032017-03-07 01:56:01 +0000453 // Apply the mask to the low word.
454 pVal[loWord] |= loMask;
455
456 // Fill any words between loWord and hiWord with all ones.
457 for (unsigned word = loWord + 1; word < hiWord; ++word)
458 pVal[word] = UINT64_MAX;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000459}
460
Zhou Shengdac63782007-02-06 03:00:16 +0000461/// Set the given bit to 0 whose position is given as "bitPosition".
462/// @brief Set a given bit to 0.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000463void APInt::clearBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000464 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000465 VAL &= ~maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000466 else
Reid Spencera856b6e2007-02-18 18:38:44 +0000467 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000468}
469
Zhou Shengdac63782007-02-06 03:00:16 +0000470/// @brief Toggle every bit to its opposite value.
Craig Topperafc9e352017-03-27 17:10:21 +0000471void APInt::flipAllBitsSlowCase() {
Craig Toppera742cb52017-04-01 21:50:08 +0000472 tcComplement(pVal, getNumWords());
Craig Topperafc9e352017-03-27 17:10:21 +0000473 clearUnusedBits();
474}
Zhou Shengdac63782007-02-06 03:00:16 +0000475
Eric Christopher820256b2009-08-21 04:06:45 +0000476/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000477/// as "bitPosition".
478/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000479void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000480 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000481 if ((*this)[bitPosition]) clearBit(bitPosition);
482 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000483}
484
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000485void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
486 unsigned subBitWidth = subBits.getBitWidth();
487 assert(0 < subBitWidth && (subBitWidth + bitPosition) <= BitWidth &&
488 "Illegal bit insertion");
489
490 // Insertion is a direct copy.
491 if (subBitWidth == BitWidth) {
492 *this = subBits;
493 return;
494 }
495
496 // Single word result can be done as a direct bitmask.
497 if (isSingleWord()) {
498 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
499 VAL &= ~(mask << bitPosition);
500 VAL |= (subBits.VAL << bitPosition);
501 return;
502 }
503
504 unsigned loBit = whichBit(bitPosition);
505 unsigned loWord = whichWord(bitPosition);
506 unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
507
508 // Insertion within a single word can be done as a direct bitmask.
509 if (loWord == hi1Word) {
510 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
511 pVal[loWord] &= ~(mask << loBit);
512 pVal[loWord] |= (subBits.VAL << loBit);
513 return;
514 }
515
516 // Insert on word boundaries.
517 if (loBit == 0) {
518 // Direct copy whole words.
519 unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
520 memcpy(pVal + loWord, subBits.getRawData(),
521 numWholeSubWords * APINT_WORD_SIZE);
522
523 // Mask+insert remaining bits.
524 unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
525 if (remainingBits != 0) {
526 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - remainingBits);
527 pVal[hi1Word] &= ~mask;
528 pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
529 }
530 return;
531 }
532
533 // General case - set/clear individual bits in dst based on src.
534 // TODO - there is scope for optimization here, but at the moment this code
535 // path is barely used so prefer readability over performance.
536 for (unsigned i = 0; i != subBitWidth; ++i) {
537 if (subBits[i])
538 setBit(bitPosition + i);
539 else
540 clearBit(bitPosition + i);
541 }
542}
543
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000544APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
545 assert(numBits > 0 && "Can't extract zero bits");
546 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
547 "Illegal bit extraction");
548
549 if (isSingleWord())
550 return APInt(numBits, VAL >> bitPosition);
551
552 unsigned loBit = whichBit(bitPosition);
553 unsigned loWord = whichWord(bitPosition);
554 unsigned hiWord = whichWord(bitPosition + numBits - 1);
555
556 // Single word result extracting bits from a single word source.
557 if (loWord == hiWord)
558 return APInt(numBits, pVal[loWord] >> loBit);
559
560 // Extracting bits that start on a source word boundary can be done
561 // as a fast memory copy.
562 if (loBit == 0)
563 return APInt(numBits, makeArrayRef(pVal + loWord, 1 + hiWord - loWord));
564
565 // General case - shift + copy source words directly into place.
566 APInt Result(numBits, 0);
567 unsigned NumSrcWords = getNumWords();
568 unsigned NumDstWords = Result.getNumWords();
569
570 for (unsigned word = 0; word < NumDstWords; ++word) {
571 uint64_t w0 = pVal[loWord + word];
572 uint64_t w1 =
573 (loWord + word + 1) < NumSrcWords ? pVal[loWord + word + 1] : 0;
574 Result.pVal[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
575 }
576
577 return Result.clearUnusedBits();
578}
579
Benjamin Kramer92d89982010-07-14 22:38:02 +0000580unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000581 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000582 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +0000583 radix == 36) &&
584 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000585
586 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000587
Eric Christopher43a1dec2009-08-21 04:10:31 +0000588 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000589 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000590 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000591 if (*p == '-' || *p == '+') {
592 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000593 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000594 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000595 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000596
Reid Spencer9329e7b2007-04-13 19:19:07 +0000597 // For radixes of power-of-two values, the bits required is accurately and
598 // easily computed
599 if (radix == 2)
600 return slen + isNegative;
601 if (radix == 8)
602 return slen * 3 + isNegative;
603 if (radix == 16)
604 return slen * 4 + isNegative;
605
Douglas Gregor663c0682011-09-14 15:54:46 +0000606 // FIXME: base 36
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000607
Reid Spencer9329e7b2007-04-13 19:19:07 +0000608 // This is grossly inefficient but accurate. We could probably do something
609 // with a computation of roughly slen*64/20 and then adjust by the value of
610 // the first few digits. But, I'm not sure how accurate that could be.
611
612 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000613 // be too large. This avoids the assertion in the constructor. This
614 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
615 // bits in that case.
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000616 unsigned sufficient
Douglas Gregor663c0682011-09-14 15:54:46 +0000617 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
618 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000619
620 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000621 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000622
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000623 // Compute how many bits are required. If the log is infinite, assume we need
624 // just bit.
625 unsigned log = tmp.logBase2();
626 if (log == (unsigned)-1) {
627 return isNegative + 1;
628 } else {
629 return isNegative + log + 1;
630 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000631}
632
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000633hash_code llvm::hash_value(const APInt &Arg) {
634 if (Arg.isSingleWord())
635 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000636
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000637 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000638}
639
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000640bool APInt::isSplat(unsigned SplatSizeInBits) const {
641 assert(getBitWidth() % SplatSizeInBits == 0 &&
642 "SplatSizeInBits must divide width!");
643 // We can check that all parts of an integer are equal by making use of a
644 // little trick: rotate and check if it's still the same value.
645 return *this == rotl(SplatSizeInBits);
646}
647
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000648/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000649APInt APInt::getHiBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000650 return this->lshr(BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000651}
652
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000653/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000654APInt APInt::getLoBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000655 APInt Result(getLowBitsSet(BitWidth, numBits));
656 Result &= *this;
657 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000658}
659
Chris Lattner77527f52009-01-21 18:09:24 +0000660unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000661 unsigned Count = 0;
662 for (int i = getNumWords()-1; i >= 0; --i) {
Craig Topper55229b72017-04-02 19:17:22 +0000663 uint64_t V = pVal[i];
Matthias Brauna6be4e82016-02-15 20:06:22 +0000664 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000665 Count += APINT_BITS_PER_WORD;
666 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000667 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000668 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000669 }
Zhou Shengdac63782007-02-06 03:00:16 +0000670 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000671 // Adjust for unused bits in the most significant word (they are zero).
672 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
673 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000674 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000675}
676
Chris Lattner77527f52009-01-21 18:09:24 +0000677unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000678 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000679 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000680
Chris Lattner77527f52009-01-21 18:09:24 +0000681 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000682 unsigned shift;
683 if (!highWordBits) {
684 highWordBits = APINT_BITS_PER_WORD;
685 shift = 0;
686 } else {
687 shift = APINT_BITS_PER_WORD - highWordBits;
688 }
Reid Spencer31acef52007-02-27 21:59:26 +0000689 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000690 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000691 if (Count == highWordBits) {
692 for (i--; i >= 0; --i) {
693 if (pVal[i] == -1ULL)
694 Count += APINT_BITS_PER_WORD;
695 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000696 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000697 break;
698 }
699 }
700 }
701 return Count;
702}
703
Chris Lattner77527f52009-01-21 18:09:24 +0000704unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000705 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000706 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000707 unsigned Count = 0;
708 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000709 for (; i < getNumWords() && pVal[i] == 0; ++i)
710 Count += APINT_BITS_PER_WORD;
711 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000712 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000713 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000714}
715
Chris Lattner77527f52009-01-21 18:09:24 +0000716unsigned APInt::countTrailingOnesSlowCase() const {
717 unsigned Count = 0;
718 unsigned i = 0;
Dan Gohmanc354ebd2008-02-14 22:38:45 +0000719 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000720 Count += APINT_BITS_PER_WORD;
721 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000722 Count += llvm::countTrailingOnes(pVal[i]);
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000723 return std::min(Count, BitWidth);
724}
725
Chris Lattner77527f52009-01-21 18:09:24 +0000726unsigned APInt::countPopulationSlowCase() const {
727 unsigned Count = 0;
728 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000729 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000730 return Count;
731}
732
Reid Spencer1d072122007-02-16 22:36:51 +0000733APInt APInt::byteSwap() const {
734 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
735 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000736 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000737 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000738 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000739 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000740 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000741 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000742 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000743 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000744 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000745 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000746 if (BitWidth == 64)
747 return APInt(BitWidth, ByteSwap_64(VAL));
748
749 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
750 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
751 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
752 if (Result.BitWidth != BitWidth) {
Richard Smith55bd3752017-04-13 20:29:59 +0000753 Result.lshrInPlace(Result.BitWidth - BitWidth);
Richard Smith4f9a8082011-11-23 21:33:37 +0000754 Result.BitWidth = BitWidth;
755 }
756 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000757}
758
Matt Arsenault155dda92016-03-21 15:00:35 +0000759APInt APInt::reverseBits() const {
760 switch (BitWidth) {
761 case 64:
762 return APInt(BitWidth, llvm::reverseBits<uint64_t>(VAL));
763 case 32:
764 return APInt(BitWidth, llvm::reverseBits<uint32_t>(VAL));
765 case 16:
766 return APInt(BitWidth, llvm::reverseBits<uint16_t>(VAL));
767 case 8:
768 return APInt(BitWidth, llvm::reverseBits<uint8_t>(VAL));
769 default:
770 break;
771 }
772
773 APInt Val(*this);
Craig Topper9eaef072017-04-18 05:02:21 +0000774 APInt Reversed(BitWidth, 0);
775 unsigned S = BitWidth;
Matt Arsenault155dda92016-03-21 15:00:35 +0000776
Craig Topper9eaef072017-04-18 05:02:21 +0000777 for (; Val != 0; Val.lshrInPlace(1)) {
Matt Arsenault155dda92016-03-21 15:00:35 +0000778 Reversed <<= 1;
Craig Topper9eaef072017-04-18 05:02:21 +0000779 Reversed |= Val[0];
Matt Arsenault155dda92016-03-21 15:00:35 +0000780 --S;
781 }
782
783 Reversed <<= S;
784 return Reversed;
785}
786
Craig Topper278ebd22017-04-01 20:30:57 +0000787APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) {
Richard Smith55bd3752017-04-13 20:29:59 +0000788 // Fast-path a common case.
789 if (A == B) return A;
790
791 // Corner cases: if either operand is zero, the other is the gcd.
792 if (!A) return B;
793 if (!B) return A;
794
795 // Count common powers of 2 and remove all other powers of 2.
796 unsigned Pow2;
797 {
798 unsigned Pow2_A = A.countTrailingZeros();
799 unsigned Pow2_B = B.countTrailingZeros();
800 if (Pow2_A > Pow2_B) {
801 A.lshrInPlace(Pow2_A - Pow2_B);
802 Pow2 = Pow2_B;
803 } else if (Pow2_B > Pow2_A) {
804 B.lshrInPlace(Pow2_B - Pow2_A);
805 Pow2 = Pow2_A;
806 } else {
807 Pow2 = Pow2_A;
808 }
Zhou Shengdac63782007-02-06 03:00:16 +0000809 }
Richard Smith55bd3752017-04-13 20:29:59 +0000810
811 // Both operands are odd multiples of 2^Pow_2:
812 //
813 // gcd(a, b) = gcd(|a - b| / 2^i, min(a, b))
814 //
815 // This is a modified version of Stein's algorithm, taking advantage of
816 // efficient countTrailingZeros().
817 while (A != B) {
818 if (A.ugt(B)) {
819 A -= B;
820 A.lshrInPlace(A.countTrailingZeros() - Pow2);
821 } else {
822 B -= A;
823 B.lshrInPlace(B.countTrailingZeros() - Pow2);
824 }
825 }
826
Zhou Shengdac63782007-02-06 03:00:16 +0000827 return A;
828}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000829
Chris Lattner77527f52009-01-21 18:09:24 +0000830APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000831 union {
832 double D;
833 uint64_t I;
834 } T;
835 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000836
837 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000838 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000839
840 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000841 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000842
843 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000844 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000845 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000846
847 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
848 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
849
850 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000851 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000852 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000853 APInt(width, mantissa >> (52 - exp));
854
855 // If the client didn't provide enough bits for us to shift the mantissa into
856 // then the result is undefined, just return 0
857 if (width <= exp - 52)
858 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000859
860 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000861 APInt Tmp(width, mantissa);
Chris Lattner77527f52009-01-21 18:09:24 +0000862 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd707d632007-02-12 20:02:55 +0000863 return isNeg ? -Tmp : Tmp;
864}
865
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000866/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000867/// The layout for double is as following (IEEE Standard 754):
868/// --------------------------------------
869/// | Sign Exponent Fraction Bias |
870/// |-------------------------------------- |
871/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000872/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000873double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000874
875 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000876 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000877 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
878 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000879 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000880 return double(sext);
881 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000882 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000883 }
884
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000885 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000886 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000887
888 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000889 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000890
891 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000892 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000893
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000894 // The exponent (without bias normalization) is just the number of bits
895 // we are using. Note that the sign bit is gone since we constructed the
896 // absolute value.
897 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000898
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000899 // Return infinity for exponent overflow
900 if (exp > 1023) {
901 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000902 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000903 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000904 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000905 }
906 exp += 1023; // Increment for 1023 bias
907
908 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
909 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000910 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000911 unsigned hiWord = whichWord(n-1);
912 if (hiWord == 0) {
913 mantissa = Tmp.pVal[0];
914 if (n > 52)
915 mantissa >>= n - 52; // shift down, we want the top 52 bits.
916 } else {
917 assert(hiWord > 0 && "huh?");
918 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
919 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
920 mantissa = hibits | lobits;
921 }
922
Zhou Shengd707d632007-02-12 20:02:55 +0000923 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000924 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000925 union {
926 double D;
927 uint64_t I;
928 } T;
929 T.I = sign | (exp << 52) | mantissa;
930 return T.D;
931}
932
Reid Spencer1d072122007-02-16 22:36:51 +0000933// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000934APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000935 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000936 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000937
938 if (width <= APINT_BITS_PER_WORD)
939 return APInt(width, getRawData()[0]);
940
941 APInt Result(getMemory(getNumWords(width)), width);
942
943 // Copy full words.
944 unsigned i;
945 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
946 Result.pVal[i] = pVal[i];
947
948 // Truncate and copy any partial word.
949 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
950 if (bits != 0)
951 Result.pVal[i] = pVal[i] << bits >> bits;
952
953 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000954}
955
956// Sign extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000957APInt APInt::sext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000958 assert(width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000959
960 if (width <= APINT_BITS_PER_WORD) {
961 uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
962 val = (int64_t)val >> (width - BitWidth);
963 return APInt(width, val >> (APINT_BITS_PER_WORD - width));
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000964 }
965
Jay Foad583abbc2010-12-07 08:25:19 +0000966 APInt Result(getMemory(getNumWords(width)), width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000967
Jay Foad583abbc2010-12-07 08:25:19 +0000968 // Copy full words.
969 unsigned i;
970 uint64_t word = 0;
971 for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
972 word = getRawData()[i];
973 Result.pVal[i] = word;
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000974 }
975
Jay Foad583abbc2010-12-07 08:25:19 +0000976 // Read and sign-extend any partial word.
977 unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
978 if (bits != 0)
979 word = (int64_t)getRawData()[i] << bits >> bits;
980 else
981 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
982
983 // Write remaining full words.
984 for (; i != width / APINT_BITS_PER_WORD; i++) {
985 Result.pVal[i] = word;
986 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000987 }
Jay Foad583abbc2010-12-07 08:25:19 +0000988
989 // Write any partial word.
990 bits = (0 - width) % APINT_BITS_PER_WORD;
991 if (bits != 0)
992 Result.pVal[i] = word << bits >> bits;
993
994 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000995}
996
997// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000998APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000999 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +00001000
1001 if (width <= APINT_BITS_PER_WORD)
1002 return APInt(width, VAL);
1003
1004 APInt Result(getMemory(getNumWords(width)), width);
1005
1006 // Copy words.
1007 unsigned i;
1008 for (i = 0; i != getNumWords(); i++)
1009 Result.pVal[i] = getRawData()[i];
1010
1011 // Zero remaining words.
1012 memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
1013
1014 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001015}
1016
Jay Foad583abbc2010-12-07 08:25:19 +00001017APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001018 if (BitWidth < width)
1019 return zext(width);
1020 if (BitWidth > width)
1021 return trunc(width);
1022 return *this;
1023}
1024
Jay Foad583abbc2010-12-07 08:25:19 +00001025APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001026 if (BitWidth < width)
1027 return sext(width);
1028 if (BitWidth > width)
1029 return trunc(width);
1030 return *this;
1031}
1032
Rafael Espindolabb893fe2012-01-27 23:33:07 +00001033APInt APInt::zextOrSelf(unsigned width) const {
1034 if (BitWidth < width)
1035 return zext(width);
1036 return *this;
1037}
1038
1039APInt APInt::sextOrSelf(unsigned width) const {
1040 if (BitWidth < width)
1041 return sext(width);
1042 return *this;
1043}
1044
Zhou Shenge93db8f2007-02-09 07:48:24 +00001045/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001046/// @brief Arithmetic right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001047APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001048 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001049}
1050
1051/// Arithmetic right-shift this APInt by shiftAmt.
1052/// @brief Arithmetic right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001053APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001054 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer1825dd02007-03-02 22:39:11 +00001055 // Handle a degenerate case
1056 if (shiftAmt == 0)
1057 return *this;
1058
1059 // Handle single word shifts with built-in ashr
Reid Spencer522ca7c2007-02-25 01:56:07 +00001060 if (isSingleWord()) {
1061 if (shiftAmt == BitWidth)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001062 return APInt(BitWidth, 0); // undefined
Jonathan Roelofs851b79d2016-08-10 19:50:14 +00001063 return APInt(BitWidth, SignExtend64(VAL, BitWidth) >> shiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001064 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001065
Reid Spencer1825dd02007-03-02 22:39:11 +00001066 // If all the bits were shifted out, the result is, technically, undefined.
1067 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1068 // issues in the algorithm below.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001069 if (shiftAmt == BitWidth) {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001070 if (isNegative())
Zhou Sheng1247c072008-06-05 13:27:38 +00001071 return APInt(BitWidth, -1ULL, true);
Reid Spencera41e93b2007-02-25 19:32:03 +00001072 else
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001073 return APInt(BitWidth, 0);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001074 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001075
1076 // Create some space for the result.
1077 uint64_t * val = new uint64_t[getNumWords()];
1078
Reid Spencer1825dd02007-03-02 22:39:11 +00001079 // Compute some values needed by the following shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001080 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1081 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1082 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1083 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer1825dd02007-03-02 22:39:11 +00001084 if (bitsInWord == 0)
1085 bitsInWord = APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001086
1087 // If we are shifting whole words, just move whole words
1088 if (wordShift == 0) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001089 // Move the words containing significant bits
Chris Lattner77527f52009-01-21 18:09:24 +00001090 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001091 val[i] = pVal[i+offset]; // move whole word
1092
1093 // Adjust the top significant word for sign bit fill, if negative
1094 if (isNegative())
1095 if (bitsInWord < APINT_BITS_PER_WORD)
1096 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1097 } else {
Eric Christopher820256b2009-08-21 04:06:45 +00001098 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001099 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001100 // This combines the shifted corresponding word with the low bits from
1101 // the next word (shifted into this word's high bits).
Eric Christopher820256b2009-08-21 04:06:45 +00001102 val[i] = (pVal[i+offset] >> wordShift) |
Reid Spencer1825dd02007-03-02 22:39:11 +00001103 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1104 }
1105
1106 // Shift the break word. In this case there are no bits from the next word
1107 // to include in this word.
1108 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1109
Alp Tokercb402912014-01-24 17:20:08 +00001110 // Deal with sign extension in the break word, and possibly the word before
Reid Spencer1825dd02007-03-02 22:39:11 +00001111 // it.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001112 if (isNegative()) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001113 if (wordShift > bitsInWord) {
1114 if (breakWord > 0)
Eric Christopher820256b2009-08-21 04:06:45 +00001115 val[breakWord-1] |=
Reid Spencer1825dd02007-03-02 22:39:11 +00001116 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1117 val[breakWord] |= ~0ULL;
Eric Christopher820256b2009-08-21 04:06:45 +00001118 } else
Reid Spencer1825dd02007-03-02 22:39:11 +00001119 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnerdad2d092007-05-03 18:15:36 +00001120 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001121 }
1122
Reid Spencer1825dd02007-03-02 22:39:11 +00001123 // Remaining words are 0 or -1, just assign them.
1124 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner77527f52009-01-21 18:09:24 +00001125 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001126 val[i] = fillValue;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001127 APInt Result(val, BitWidth);
1128 Result.clearUnusedBits();
1129 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001130}
1131
Zhou Shenge93db8f2007-02-09 07:48:24 +00001132/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001133/// @brief Logical right-shift function.
Craig Topperfc947bc2017-04-18 17:14:21 +00001134void APInt::lshrInPlace(const APInt &shiftAmt) {
1135 lshrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001136}
1137
1138/// Logical right-shift this APInt by shiftAmt.
1139/// @brief Logical right-shift function.
Craig Topperae8bd672017-04-18 19:13:27 +00001140void APInt::lshrSlowCase(unsigned ShiftAmt) {
Craig Topperfc947bc2017-04-18 17:14:21 +00001141 tcShiftRight(pVal, getNumWords(), ShiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001142}
1143
Zhou Shenge93db8f2007-02-09 07:48:24 +00001144/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001145/// @brief Left-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001146APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky030c4502009-01-19 17:42:33 +00001147 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner77527f52009-01-21 18:09:24 +00001148 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001149}
1150
Craig Toppera8a4f0d2017-04-18 04:39:48 +00001151void APInt::shlSlowCase(unsigned ShiftAmt) {
1152 tcShiftLeft(pVal, getNumWords(), ShiftAmt);
1153 clearUnusedBits();
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001154}
1155
Joey Gouly51c0ae52017-02-07 11:58:22 +00001156// Calculate the rotate amount modulo the bit width.
1157static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1158 unsigned rotBitWidth = rotateAmt.getBitWidth();
1159 APInt rot = rotateAmt;
1160 if (rotBitWidth < BitWidth) {
1161 // Extend the rotate APInt, so that the urem doesn't divide by 0.
1162 // e.g. APInt(1, 32) would give APInt(1, 0).
1163 rot = rotateAmt.zext(BitWidth);
1164 }
1165 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
1166 return rot.getLimitedValue(BitWidth);
1167}
1168
Dan Gohman105c1d42008-02-29 01:40:47 +00001169APInt APInt::rotl(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001170 return rotl(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001171}
1172
Chris Lattner77527f52009-01-21 18:09:24 +00001173APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001174 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001175 if (rotateAmt == 0)
1176 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001177 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001178}
1179
Dan Gohman105c1d42008-02-29 01:40:47 +00001180APInt APInt::rotr(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001181 return rotr(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001182}
1183
Chris Lattner77527f52009-01-21 18:09:24 +00001184APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001185 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001186 if (rotateAmt == 0)
1187 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001188 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001189}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001190
1191// Square Root - this method computes and returns the square root of "this".
1192// Three mechanisms are used for computation. For small values (<= 5 bits),
1193// a table lookup is done. This gets some performance for common cases. For
1194// values using less than 52 bits, the value is converted to double and then
1195// the libc sqrt function is called. The result is rounded and then converted
1196// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001197// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001198APInt APInt::sqrt() const {
1199
1200 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001201 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001202
1203 // Use a fast table for some small values. This also gets rid of some
1204 // rounding errors in libc sqrt for small values.
1205 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001206 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001207 /* 0 */ 0,
1208 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001209 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001210 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1211 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1212 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1213 /* 31 */ 6
1214 };
1215 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001216 }
1217
1218 // If the magnitude of the value fits in less than 52 bits (the precision of
1219 // an IEEE double precision floating point value), then we can use the
1220 // libc sqrt function which will probably use a hardware sqrt computation.
1221 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001222 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001223 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001224 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001225 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001226
1227 // Okay, all the short cuts are exhausted. We must compute it. The following
1228 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001229 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001230 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001231 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001232 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001233 APInt testy(BitWidth, 16);
1234 APInt x_old(BitWidth, 1);
1235 APInt x_new(BitWidth, 0);
1236 APInt two(BitWidth, 2);
1237
1238 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001239 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001240 if (i >= nbits || this->ule(testy)) {
1241 x_old = x_old.shl(i / 2);
1242 break;
1243 }
1244
Eric Christopher820256b2009-08-21 04:06:45 +00001245 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001246 for (;;) {
1247 x_new = (this->udiv(x_old) + x_old).udiv(two);
1248 if (x_old.ule(x_new))
1249 break;
1250 x_old = x_new;
1251 }
1252
1253 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001254 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001255 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001256 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001257 // floating point representation after 192 bits. There are no discrepancies
1258 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001259 APInt square(x_old * x_old);
1260 APInt nextSquare((x_old + 1) * (x_old +1));
1261 if (this->ult(square))
1262 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001263 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1264 APInt midpoint((nextSquare - square).udiv(two));
1265 APInt offset(*this - square);
1266 if (offset.ult(midpoint))
1267 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001268 return x_old + 1;
1269}
1270
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001271/// Computes the multiplicative inverse of this APInt for a given modulo. The
1272/// iterative extended Euclidean algorithm is used to solve for this value,
1273/// however we simplify it to speed up calculating only the inverse, and take
1274/// advantage of div+rem calculations. We also use some tricks to avoid copying
1275/// (potentially large) APInts around.
1276APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1277 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1278
1279 // Using the properties listed at the following web page (accessed 06/21/08):
1280 // http://www.numbertheory.org/php/euclid.html
1281 // (especially the properties numbered 3, 4 and 9) it can be proved that
1282 // BitWidth bits suffice for all the computations in the algorithm implemented
1283 // below. More precisely, this number of bits suffice if the multiplicative
1284 // inverse exists, but may not suffice for the general extended Euclidean
1285 // algorithm.
1286
1287 APInt r[2] = { modulo, *this };
1288 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1289 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001290
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001291 unsigned i;
1292 for (i = 0; r[i^1] != 0; i ^= 1) {
1293 // An overview of the math without the confusing bit-flipping:
1294 // q = r[i-2] / r[i-1]
1295 // r[i] = r[i-2] % r[i-1]
1296 // t[i] = t[i-2] - t[i-1] * q
1297 udivrem(r[i], r[i^1], q, r[i]);
1298 t[i] -= t[i^1] * q;
1299 }
1300
1301 // If this APInt and the modulo are not coprime, there is no multiplicative
1302 // inverse, so return 0. We check this by looking at the next-to-last
1303 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1304 // algorithm.
1305 if (r[i] != 1)
1306 return APInt(BitWidth, 0);
1307
1308 // The next-to-last t is the multiplicative inverse. However, we are
1309 // interested in a positive inverse. Calcuate a positive one from a negative
1310 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001311 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001312 return t[i].isNegative() ? t[i] + modulo : t[i];
1313}
1314
Jay Foadfe0c6482009-04-30 10:15:35 +00001315/// Calculate the magic numbers required to implement a signed integer division
1316/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1317/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1318/// Warren, Jr., chapter 10.
1319APInt::ms APInt::magic() const {
1320 const APInt& d = *this;
1321 unsigned p;
1322 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001323 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001324 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001325
Jay Foadfe0c6482009-04-30 10:15:35 +00001326 ad = d.abs();
1327 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1328 anc = t - 1 - t.urem(ad); // absolute value of nc
1329 p = d.getBitWidth() - 1; // initialize p
1330 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1331 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1332 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1333 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1334 do {
1335 p = p + 1;
1336 q1 = q1<<1; // update q1 = 2p/abs(nc)
1337 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1338 if (r1.uge(anc)) { // must be unsigned comparison
1339 q1 = q1 + 1;
1340 r1 = r1 - anc;
1341 }
1342 q2 = q2<<1; // update q2 = 2p/abs(d)
1343 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1344 if (r2.uge(ad)) { // must be unsigned comparison
1345 q2 = q2 + 1;
1346 r2 = r2 - ad;
1347 }
1348 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001349 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001350
Jay Foadfe0c6482009-04-30 10:15:35 +00001351 mag.m = q2 + 1;
1352 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1353 mag.s = p - d.getBitWidth(); // resulting shift
1354 return mag;
1355}
1356
1357/// Calculate the magic numbers required to implement an unsigned integer
1358/// division by a constant as a sequence of multiplies, adds and shifts.
1359/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1360/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001361/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001362/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001363APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001364 const APInt& d = *this;
1365 unsigned p;
1366 APInt nc, delta, q1, r1, q2, r2;
1367 struct mu magu;
1368 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001369 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001370 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1371 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1372
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001373 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001374 p = d.getBitWidth() - 1; // initialize p
1375 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1376 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1377 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1378 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1379 do {
1380 p = p + 1;
1381 if (r1.uge(nc - r1)) {
1382 q1 = q1 + q1 + 1; // update q1
1383 r1 = r1 + r1 - nc; // update r1
1384 }
1385 else {
1386 q1 = q1+q1; // update q1
1387 r1 = r1+r1; // update r1
1388 }
1389 if ((r2 + 1).uge(d - r2)) {
1390 if (q2.uge(signedMax)) magu.a = 1;
1391 q2 = q2+q2 + 1; // update q2
1392 r2 = r2+r2 + 1 - d; // update r2
1393 }
1394 else {
1395 if (q2.uge(signedMin)) magu.a = 1;
1396 q2 = q2+q2; // update q2
1397 r2 = r2+r2 + 1; // update r2
1398 }
1399 delta = d - 1 - r2;
1400 } while (p < d.getBitWidth()*2 &&
1401 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1402 magu.m = q2 + 1; // resulting magic number
1403 magu.s = p - d.getBitWidth(); // resulting shift
1404 return magu;
1405}
1406
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001407/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1408/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1409/// variables here have the same names as in the algorithm. Comments explain
1410/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001411static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1412 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001413 assert(u && "Must provide dividend");
1414 assert(v && "Must provide divisor");
1415 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001416 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001417 assert(n>1 && "n must be > 1");
1418
Yaron Keren39fc5a62015-03-26 19:45:19 +00001419 // b denotes the base of the number system. In our case b is 2^32.
George Burgess IV381fc0e2016-08-25 01:05:08 +00001420 const uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001421
David Greenef32fcb42010-01-05 01:28:52 +00001422 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1423 DEBUG(dbgs() << "KnuthDiv: original:");
1424 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1425 DEBUG(dbgs() << " by");
1426 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1427 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001428 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1429 // u and v by d. Note that we have taken Knuth's advice here to use a power
1430 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1431 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001432 // shift amount from the leading zeros. We are basically normalizing the u
1433 // and v so that its high bits are shifted to the top of v's range without
1434 // overflow. Note that this can require an extra word in u so that u must
1435 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001436 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001437 unsigned v_carry = 0;
1438 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001439 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001440 for (unsigned i = 0; i < m+n; ++i) {
1441 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001442 u[i] = (u[i] << shift) | u_carry;
1443 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001444 }
Chris Lattner77527f52009-01-21 18:09:24 +00001445 for (unsigned i = 0; i < n; ++i) {
1446 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001447 v[i] = (v[i] << shift) | v_carry;
1448 v_carry = v_tmp;
1449 }
1450 }
1451 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001452
David Greenef32fcb42010-01-05 01:28:52 +00001453 DEBUG(dbgs() << "KnuthDiv: normal:");
1454 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1455 DEBUG(dbgs() << " by");
1456 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1457 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001458
1459 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1460 int j = m;
1461 do {
David Greenef32fcb42010-01-05 01:28:52 +00001462 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001463 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001464 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1465 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1466 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1467 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1468 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001469 // value qp is one too large, and it eliminates all cases where qp is two
1470 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001471 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001472 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001473 uint64_t qp = dividend / v[n-1];
1474 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001475 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1476 qp--;
1477 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001478 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001479 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001480 }
David Greenef32fcb42010-01-05 01:28:52 +00001481 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001482
Reid Spencercb292e42007-02-23 01:57:13 +00001483 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1484 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1485 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001486 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001487 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1488 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1489 // true value plus b**(n+1), namely as the b's complement of
1490 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001491 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001492 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001493 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1494 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1495 u[j+i] = (unsigned)subres;
1496 borrow = (p >> 32) - (subres >> 32);
1497 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001498 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001499 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001500 bool isNeg = u[j+n] < borrow;
1501 u[j+n] -= (unsigned)borrow;
1502
David Greenef32fcb42010-01-05 01:28:52 +00001503 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1504 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1505 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001506
Eric Christopher820256b2009-08-21 04:06:45 +00001507 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001508 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001509 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001510 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001511 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001512 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001513 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001514 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001515 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1516 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001517 // since it cancels with the borrow that occurred in D4.
1518 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001519 for (unsigned i = 0; i < n; i++) {
1520 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001521 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001522 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001523 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001524 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001525 }
David Greenef32fcb42010-01-05 01:28:52 +00001526 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001527 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001528 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001529
Reid Spencercb292e42007-02-23 01:57:13 +00001530 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1531 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001532
David Greenef32fcb42010-01-05 01:28:52 +00001533 DEBUG(dbgs() << "KnuthDiv: quotient:");
1534 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1535 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001536
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001537 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1538 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1539 // compute the remainder (urem uses this).
1540 if (r) {
1541 // The value d is expressed by the "shift" value above since we avoided
1542 // multiplication by d by using a shift left. So, all we have to do is
Simon Pilgrim0099beb2017-03-09 13:57:04 +00001543 // shift right here.
Reid Spencer468ad9112007-02-24 20:38:01 +00001544 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001545 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001546 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001547 for (int i = n-1; i >= 0; i--) {
1548 r[i] = (u[i] >> shift) | carry;
1549 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001550 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001551 }
1552 } else {
1553 for (int i = n-1; i >= 0; i--) {
1554 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001555 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001556 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001557 }
David Greenef32fcb42010-01-05 01:28:52 +00001558 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001559 }
David Greenef32fcb42010-01-05 01:28:52 +00001560 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001561}
1562
Benjamin Kramerc321e532016-06-08 19:09:22 +00001563void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
1564 unsigned rhsWords, APInt *Quotient, APInt *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001565 assert(lhsWords >= rhsWords && "Fractional result");
1566
Eric Christopher820256b2009-08-21 04:06:45 +00001567 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001568 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001569 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001570 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1571 // can't use 64-bit operands here because we don't have native results of
1572 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001573 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001574 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001575 unsigned n = rhsWords * 2;
1576 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001577
1578 // Allocate space for the temporary values we need either on the stack, if
1579 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001580 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001581 unsigned *U = nullptr;
1582 unsigned *V = nullptr;
1583 unsigned *Q = nullptr;
1584 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001585 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1586 U = &SPACE[0];
1587 V = &SPACE[m+n+1];
1588 Q = &SPACE[(m+n+1) + n];
1589 if (Remainder)
1590 R = &SPACE[(m+n+1) + n + (m+n)];
1591 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001592 U = new unsigned[m + n + 1];
1593 V = new unsigned[n];
1594 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001595 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001596 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001597 }
1598
1599 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001600 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001601 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001602 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001603 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001604 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001605 }
1606 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1607
Reid Spencer522ca7c2007-02-25 01:56:07 +00001608 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001609 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001610 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001611 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001612 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001613 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001614 }
1615
Reid Spencer522ca7c2007-02-25 01:56:07 +00001616 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001617 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001618 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001619 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001620
Eric Christopher820256b2009-08-21 04:06:45 +00001621 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001622 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001623 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001624 // contain any zero words or the Knuth algorithm fails.
1625 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1626 n--;
1627 m++;
1628 }
1629 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1630 m--;
1631
1632 // If we're left with only a single word for the divisor, Knuth doesn't work
1633 // so we implement the short division algorithm here. This is much simpler
1634 // and faster because we are certain that we can divide a 64-bit quantity
1635 // by a 32-bit quantity at hardware speed and short division is simply a
1636 // series of such operations. This is just like doing short division but we
1637 // are using base 2^32 instead of base 10.
1638 assert(n != 0 && "Divide by zero?");
1639 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001640 unsigned divisor = V[0];
1641 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001642 for (int i = m+n-1; i >= 0; i--) {
1643 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1644 if (partial_dividend == 0) {
1645 Q[i] = 0;
1646 remainder = 0;
1647 } else if (partial_dividend < divisor) {
1648 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001649 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001650 } else if (partial_dividend == divisor) {
1651 Q[i] = 1;
1652 remainder = 0;
1653 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001654 Q[i] = (unsigned)(partial_dividend / divisor);
1655 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001656 }
1657 }
1658 if (R)
1659 R[0] = remainder;
1660 } else {
1661 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1662 // case n > 1.
1663 KnuthDiv(U, V, Q, R, m, n);
1664 }
1665
1666 // If the caller wants the quotient
1667 if (Quotient) {
1668 // Set up the Quotient value's memory.
1669 if (Quotient->BitWidth != LHS.BitWidth) {
1670 if (Quotient->isSingleWord())
1671 Quotient->VAL = 0;
1672 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001673 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001674 Quotient->BitWidth = LHS.BitWidth;
1675 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001676 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001677 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001678 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001679
Eric Christopher820256b2009-08-21 04:06:45 +00001680 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001681 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001682 // This case is currently dead as all users of divide() handle trivial cases
1683 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001684 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001685 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001686 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1687 if (Quotient->isSingleWord())
1688 Quotient->VAL = tmp;
1689 else
1690 Quotient->pVal[0] = tmp;
1691 } else {
1692 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1693 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001694 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001695 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1696 }
1697 }
1698
1699 // If the caller wants the remainder
1700 if (Remainder) {
1701 // Set up the Remainder value's memory.
1702 if (Remainder->BitWidth != RHS.BitWidth) {
1703 if (Remainder->isSingleWord())
1704 Remainder->VAL = 0;
1705 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001706 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001707 Remainder->BitWidth = RHS.BitWidth;
1708 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001709 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001710 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001711 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001712
1713 // The remainder is in R. Reconstitute the remainder into Remainder's low
1714 // order words.
1715 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001716 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001717 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1718 if (Remainder->isSingleWord())
1719 Remainder->VAL = tmp;
1720 else
1721 Remainder->pVal[0] = tmp;
1722 } else {
1723 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1724 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001725 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001726 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1727 }
1728 }
1729
1730 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001731 if (U != &SPACE[0]) {
1732 delete [] U;
1733 delete [] V;
1734 delete [] Q;
1735 delete [] R;
1736 }
Reid Spencer100502d2007-02-17 03:16:00 +00001737}
1738
Reid Spencer1d072122007-02-16 22:36:51 +00001739APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001740 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001741
1742 // First, deal with the easy case
1743 if (isSingleWord()) {
1744 assert(RHS.VAL != 0 && "Divide by zero?");
1745 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001746 }
Reid Spencer39867762007-02-17 02:07:07 +00001747
Reid Spencer39867762007-02-17 02:07:07 +00001748 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001749 unsigned rhsBits = RHS.getActiveBits();
1750 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001751 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001752 unsigned lhsBits = this->getActiveBits();
1753 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001754
1755 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001756 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001757 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001758 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001759 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001760 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001761 return APInt(BitWidth, 0);
1762 } else if (*this == RHS) {
1763 // X / X ===> 1
1764 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001765 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001766 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001767 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001768 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001769
1770 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1771 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001772 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001773 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001774}
1775
Jakub Staszak6605c602013-02-20 00:17:42 +00001776APInt APInt::sdiv(const APInt &RHS) const {
1777 if (isNegative()) {
1778 if (RHS.isNegative())
1779 return (-(*this)).udiv(-RHS);
1780 return -((-(*this)).udiv(RHS));
1781 }
1782 if (RHS.isNegative())
1783 return -(this->udiv(-RHS));
1784 return this->udiv(RHS);
1785}
1786
Reid Spencer1d072122007-02-16 22:36:51 +00001787APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001788 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001789 if (isSingleWord()) {
1790 assert(RHS.VAL != 0 && "Remainder by zero?");
1791 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001792 }
Reid Spencer39867762007-02-17 02:07:07 +00001793
Reid Spencer58a6a432007-02-21 08:21:52 +00001794 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001795 unsigned lhsBits = getActiveBits();
1796 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001797
1798 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001799 unsigned rhsBits = RHS.getActiveBits();
1800 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001801 assert(rhsWords && "Performing remainder operation by zero ???");
1802
Reid Spencer39867762007-02-17 02:07:07 +00001803 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001804 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001805 // 0 % Y ===> 0
1806 return APInt(BitWidth, 0);
1807 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001808 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001809 return *this;
1810 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001811 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001812 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001813 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001814 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00001815 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001816 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001817
Reid Spencer4c50b522007-05-13 23:44:59 +00001818 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001819 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001820 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001821 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001822}
Reid Spencer100502d2007-02-17 03:16:00 +00001823
Jakub Staszak6605c602013-02-20 00:17:42 +00001824APInt APInt::srem(const APInt &RHS) const {
1825 if (isNegative()) {
1826 if (RHS.isNegative())
1827 return -((-(*this)).urem(-RHS));
1828 return -((-(*this)).urem(RHS));
1829 }
1830 if (RHS.isNegative())
1831 return this->urem(-RHS);
1832 return this->urem(RHS);
1833}
1834
Eric Christopher820256b2009-08-21 04:06:45 +00001835void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001836 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001837 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1838
1839 // First, deal with the easy case
1840 if (LHS.isSingleWord()) {
1841 assert(RHS.VAL != 0 && "Divide by zero?");
1842 uint64_t QuotVal = LHS.VAL / RHS.VAL;
1843 uint64_t RemVal = LHS.VAL % RHS.VAL;
1844 Quotient = APInt(LHS.BitWidth, QuotVal);
1845 Remainder = APInt(LHS.BitWidth, RemVal);
1846 return;
1847 }
1848
Reid Spencer4c50b522007-05-13 23:44:59 +00001849 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001850 unsigned lhsBits = LHS.getActiveBits();
1851 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1852 unsigned rhsBits = RHS.getActiveBits();
1853 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00001854
1855 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001856 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00001857 Quotient = 0; // 0 / Y ===> 0
1858 Remainder = 0; // 0 % Y ===> 0
1859 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001860 }
1861
1862 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001863 Remainder = LHS; // X % Y ===> X, iff X < Y
1864 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00001865 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001866 }
1867
Reid Spencer4c50b522007-05-13 23:44:59 +00001868 if (LHS == RHS) {
1869 Quotient = 1; // X / X ===> 1
1870 Remainder = 0; // X % X ===> 0;
1871 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001872 }
1873
Reid Spencer4c50b522007-05-13 23:44:59 +00001874 if (lhsWords == 1 && rhsWords == 1) {
1875 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001876 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
1877 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1878 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
1879 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00001880 return;
1881 }
1882
1883 // Okay, lets do it the long way
1884 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
1885}
1886
Jakub Staszak6605c602013-02-20 00:17:42 +00001887void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
1888 APInt &Quotient, APInt &Remainder) {
1889 if (LHS.isNegative()) {
1890 if (RHS.isNegative())
1891 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
1892 else {
1893 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
1894 Quotient = -Quotient;
1895 }
1896 Remainder = -Remainder;
1897 } else if (RHS.isNegative()) {
1898 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
1899 Quotient = -Quotient;
1900 } else {
1901 APInt::udivrem(LHS, RHS, Quotient, Remainder);
1902 }
1903}
1904
Chris Lattner2c819b02010-10-13 23:54:10 +00001905APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001906 APInt Res = *this+RHS;
1907 Overflow = isNonNegative() == RHS.isNonNegative() &&
1908 Res.isNonNegative() != isNonNegative();
1909 return Res;
1910}
1911
Chris Lattner698661c2010-10-14 00:05:07 +00001912APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
1913 APInt Res = *this+RHS;
1914 Overflow = Res.ult(RHS);
1915 return Res;
1916}
1917
Chris Lattner2c819b02010-10-13 23:54:10 +00001918APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001919 APInt Res = *this - RHS;
1920 Overflow = isNonNegative() != RHS.isNonNegative() &&
1921 Res.isNonNegative() != isNonNegative();
1922 return Res;
1923}
1924
Chris Lattner698661c2010-10-14 00:05:07 +00001925APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00001926 APInt Res = *this-RHS;
1927 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00001928 return Res;
1929}
1930
Chris Lattner2c819b02010-10-13 23:54:10 +00001931APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001932 // MININT/-1 --> overflow.
1933 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
1934 return sdiv(RHS);
1935}
1936
Chris Lattner2c819b02010-10-13 23:54:10 +00001937APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001938 APInt Res = *this * RHS;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001939
Chris Lattner79bdd882010-10-13 23:46:33 +00001940 if (*this != 0 && RHS != 0)
1941 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
1942 else
1943 Overflow = false;
1944 return Res;
1945}
1946
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001947APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
1948 APInt Res = *this * RHS;
1949
1950 if (*this != 0 && RHS != 0)
1951 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
1952 else
1953 Overflow = false;
1954 return Res;
1955}
1956
David Majnemera2521382014-10-13 21:48:30 +00001957APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
1958 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00001959 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00001960 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00001961
1962 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00001963 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00001964 else
David Majnemera2521382014-10-13 21:48:30 +00001965 Overflow = ShAmt.uge(countLeadingOnes());
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001966
Chris Lattner79bdd882010-10-13 23:46:33 +00001967 return *this << ShAmt;
1968}
1969
David Majnemera2521382014-10-13 21:48:30 +00001970APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
1971 Overflow = ShAmt.uge(getBitWidth());
1972 if (Overflow)
1973 return APInt(BitWidth, 0);
1974
1975 Overflow = ShAmt.ugt(countLeadingZeros());
1976
1977 return *this << ShAmt;
1978}
1979
Chris Lattner79bdd882010-10-13 23:46:33 +00001980
1981
1982
Benjamin Kramer92d89982010-07-14 22:38:02 +00001983void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00001984 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001985 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001986 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00001987 radix == 36) &&
1988 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001989
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001990 StringRef::iterator p = str.begin();
1991 size_t slen = str.size();
1992 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001993 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001994 p++;
1995 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00001996 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001997 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00001998 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00001999 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2000 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002001 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2002 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00002003
2004 // Allocate memory
2005 if (!isSingleWord())
2006 pVal = getClearedMemory(getNumWords());
2007
2008 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00002009 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00002010
Craig Topperb7d8faa2017-04-02 06:59:38 +00002011 // Set up an APInt for the radix multiplier outside the loop so we don't
Reid Spencer1ba83352007-02-21 03:55:44 +00002012 // constantly construct/destruct it.
Reid Spencer1ba83352007-02-21 03:55:44 +00002013 APInt apradix(getBitWidth(), radix);
2014
2015 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002016 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00002017 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00002018 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00002019
Reid Spencera93c9812007-05-16 19:18:22 +00002020 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002021 if (slen > 1) {
2022 if (shift)
2023 *this <<= shift;
2024 else
2025 *this *= apradix;
2026 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002027
2028 // Add in the digit we just interpreted
Craig Topperb7d8faa2017-04-02 06:59:38 +00002029 *this += digit;
Reid Spencer100502d2007-02-17 03:16:00 +00002030 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002031 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00002032 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00002033 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002034 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002035 }
Reid Spencer100502d2007-02-17 03:16:00 +00002036}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002037
Chris Lattner17f71652008-08-17 07:19:36 +00002038void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002039 bool Signed, bool formatAsCLiteral) const {
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002040 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002041 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002042 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002043
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002044 const char *Prefix = "";
2045 if (formatAsCLiteral) {
2046 switch (Radix) {
2047 case 2:
2048 // Binary literals are a non-standard extension added in gcc 4.3:
2049 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2050 Prefix = "0b";
2051 break;
2052 case 8:
2053 Prefix = "0";
2054 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002055 case 10:
2056 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002057 case 16:
2058 Prefix = "0x";
2059 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002060 default:
2061 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002062 }
2063 }
2064
Chris Lattner17f71652008-08-17 07:19:36 +00002065 // First, check for a zero value and just short circuit the logic below.
2066 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002067 while (*Prefix) {
2068 Str.push_back(*Prefix);
2069 ++Prefix;
2070 };
Chris Lattner17f71652008-08-17 07:19:36 +00002071 Str.push_back('0');
2072 return;
2073 }
Eric Christopher820256b2009-08-21 04:06:45 +00002074
Douglas Gregor663c0682011-09-14 15:54:46 +00002075 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002076
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002077 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002078 char Buffer[65];
2079 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002080
Chris Lattner17f71652008-08-17 07:19:36 +00002081 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002082 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002083 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002084 } else {
2085 int64_t I = getSExtValue();
2086 if (I >= 0) {
2087 N = I;
2088 } else {
2089 Str.push_back('-');
2090 N = -(uint64_t)I;
2091 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002092 }
Eric Christopher820256b2009-08-21 04:06:45 +00002093
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002094 while (*Prefix) {
2095 Str.push_back(*Prefix);
2096 ++Prefix;
2097 };
2098
Chris Lattner17f71652008-08-17 07:19:36 +00002099 while (N) {
2100 *--BufPtr = Digits[N % Radix];
2101 N /= Radix;
2102 }
2103 Str.append(BufPtr, Buffer+65);
2104 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002105 }
2106
Chris Lattner17f71652008-08-17 07:19:36 +00002107 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002108
Chris Lattner17f71652008-08-17 07:19:36 +00002109 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002110 // They want to print the signed version and it is a negative value
2111 // Flip the bits and add one to turn it into the equivalent positive
2112 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002113 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002114 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002115 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002116 }
Eric Christopher820256b2009-08-21 04:06:45 +00002117
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002118 while (*Prefix) {
2119 Str.push_back(*Prefix);
2120 ++Prefix;
2121 };
2122
Chris Lattner17f71652008-08-17 07:19:36 +00002123 // We insert the digits backward, then reverse them to get the right order.
2124 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002125
2126 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2127 // because the number of bits per digit (1, 3 and 4 respectively) divides
Craig Topperd7ed50d2017-04-02 06:59:36 +00002128 // equally. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002129 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002130 // Just shift tmp right for each digit width until it becomes zero
2131 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2132 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002133
Chris Lattner17f71652008-08-17 07:19:36 +00002134 while (Tmp != 0) {
2135 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2136 Str.push_back(Digits[Digit]);
Craig Topperfc947bc2017-04-18 17:14:21 +00002137 Tmp.lshrInPlace(ShiftAmt);
Chris Lattner17f71652008-08-17 07:19:36 +00002138 }
2139 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002140 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002141 while (Tmp != 0) {
2142 APInt APdigit(1, 0);
2143 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002144 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002145 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002146 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002147 assert(Digit < Radix && "divide failed");
2148 Str.push_back(Digits[Digit]);
2149 Tmp = tmp2;
2150 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002151 }
Eric Christopher820256b2009-08-21 04:06:45 +00002152
Chris Lattner17f71652008-08-17 07:19:36 +00002153 // Reverse the digits before returning.
2154 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002155}
2156
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002157/// Returns the APInt as a std::string. Note that this is an inefficient method.
2158/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002159std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2160 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002161 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002162 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002163}
Chris Lattner6b695682007-08-16 15:56:55 +00002164
Matthias Braun8c209aa2017-01-28 02:02:38 +00002165#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002166LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002167 SmallString<40> S, U;
2168 this->toStringUnsigned(U);
2169 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002170 dbgs() << "APInt(" << BitWidth << "b, "
Davide Italiano5a473d22017-01-31 21:26:18 +00002171 << U << "u " << S << "s)\n";
Chris Lattner17f71652008-08-17 07:19:36 +00002172}
Matthias Braun8c209aa2017-01-28 02:02:38 +00002173#endif
Chris Lattner17f71652008-08-17 07:19:36 +00002174
Chris Lattner0c19df42008-08-23 22:23:09 +00002175void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002176 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002177 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002178 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002179}
2180
Chris Lattner6b695682007-08-16 15:56:55 +00002181// This implements a variety of operations on a representation of
2182// arbitrary precision, two's-complement, bignum integer values.
2183
Chris Lattner96cffa62009-08-23 23:11:28 +00002184// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2185// and unrestricting assumption.
Craig Topper55229b72017-04-02 19:17:22 +00002186static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
2187 "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002188
2189/* Some handy functions local to this file. */
Chris Lattner6b695682007-08-16 15:56:55 +00002190
Craig Topper76f42462017-03-28 05:32:53 +00002191/* Returns the integer part with the least significant BITS set.
2192 BITS cannot be zero. */
Craig Topper55229b72017-04-02 19:17:22 +00002193static inline APInt::WordType lowBitMask(unsigned bits) {
2194 assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002195
Craig Topper55229b72017-04-02 19:17:22 +00002196 return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
Craig Topper76f42462017-03-28 05:32:53 +00002197}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002198
Craig Topper76f42462017-03-28 05:32:53 +00002199/* Returns the value of the lower half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002200static inline APInt::WordType lowHalf(APInt::WordType part) {
2201 return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002202}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002203
Craig Topper76f42462017-03-28 05:32:53 +00002204/* Returns the value of the upper half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002205static inline APInt::WordType highHalf(APInt::WordType part) {
2206 return part >> (APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002207}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002208
Craig Topper76f42462017-03-28 05:32:53 +00002209/* Returns the bit number of the most significant set bit of a part.
2210 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002211static unsigned partMSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002212 return findLastSet(value, ZB_Max);
2213}
Chris Lattner6b695682007-08-16 15:56:55 +00002214
Craig Topper76f42462017-03-28 05:32:53 +00002215/* Returns the bit number of the least significant set bit of a
2216 part. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002217static unsigned partLSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002218 return findFirstSet(value, ZB_Max);
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002219}
Chris Lattner6b695682007-08-16 15:56:55 +00002220
2221/* Sets the least significant part of a bignum to the input value, and
2222 zeroes out higher parts. */
Craig Topper55229b72017-04-02 19:17:22 +00002223void APInt::tcSet(WordType *dst, WordType part, unsigned parts) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002224 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002225
Chris Lattner6b695682007-08-16 15:56:55 +00002226 dst[0] = part;
Craig Topperb0038162017-03-28 05:32:52 +00002227 for (unsigned i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002228 dst[i] = 0;
2229}
2230
2231/* Assign one bignum to another. */
Craig Topper55229b72017-04-02 19:17:22 +00002232void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002233 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002234 dst[i] = src[i];
2235}
2236
2237/* Returns true if a bignum is zero, false otherwise. */
Craig Topper55229b72017-04-02 19:17:22 +00002238bool APInt::tcIsZero(const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002239 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002240 if (src[i])
2241 return false;
2242
2243 return true;
2244}
2245
2246/* Extract the given bit of a bignum; returns 0 or 1. */
Craig Topper55229b72017-04-02 19:17:22 +00002247int APInt::tcExtractBit(const WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002248 return (parts[whichWord(bit)] & maskBit(bit)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002249}
2250
John McCalldcb9a7a2010-02-28 02:51:25 +00002251/* Set the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002252void APInt::tcSetBit(WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002253 parts[whichWord(bit)] |= maskBit(bit);
Chris Lattner6b695682007-08-16 15:56:55 +00002254}
2255
John McCalldcb9a7a2010-02-28 02:51:25 +00002256/* Clears the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002257void APInt::tcClearBit(WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002258 parts[whichWord(bit)] &= ~maskBit(bit);
John McCalldcb9a7a2010-02-28 02:51:25 +00002259}
2260
Neil Boothc8b650a2007-10-06 00:43:45 +00002261/* Returns the bit number of the least significant set bit of a
2262 number. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002263unsigned APInt::tcLSB(const WordType *parts, unsigned n) {
Craig Topperb0038162017-03-28 05:32:52 +00002264 for (unsigned i = 0; i < n; i++) {
2265 if (parts[i] != 0) {
2266 unsigned lsb = partLSB(parts[i]);
Chris Lattner6b695682007-08-16 15:56:55 +00002267
Craig Topper55229b72017-04-02 19:17:22 +00002268 return lsb + i * APINT_BITS_PER_WORD;
Craig Topperb0038162017-03-28 05:32:52 +00002269 }
Chris Lattner6b695682007-08-16 15:56:55 +00002270 }
2271
2272 return -1U;
2273}
2274
Neil Boothc8b650a2007-10-06 00:43:45 +00002275/* Returns the bit number of the most significant set bit of a number.
2276 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002277unsigned APInt::tcMSB(const WordType *parts, unsigned n) {
Chris Lattner6b695682007-08-16 15:56:55 +00002278 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002279 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002280
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002281 if (parts[n] != 0) {
Craig Topperb0038162017-03-28 05:32:52 +00002282 unsigned msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002283
Craig Topper55229b72017-04-02 19:17:22 +00002284 return msb + n * APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002285 }
Chris Lattner6b695682007-08-16 15:56:55 +00002286 } while (n);
2287
2288 return -1U;
2289}
2290
Neil Boothb6182162007-10-08 13:47:12 +00002291/* Copy the bit vector of width srcBITS from SRC, starting at bit
2292 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2293 the least significant bit of DST. All high bits above srcBITS in
2294 DST are zero-filled. */
2295void
Craig Topper55229b72017-04-02 19:17:22 +00002296APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src,
Craig Topper6a8518082017-03-28 05:32:55 +00002297 unsigned srcBits, unsigned srcLSB) {
Craig Topper55229b72017-04-02 19:17:22 +00002298 unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002299 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002300
Craig Topper55229b72017-04-02 19:17:22 +00002301 unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002302 tcAssign (dst, src + firstSrcPart, dstParts);
2303
Craig Topper55229b72017-04-02 19:17:22 +00002304 unsigned shift = srcLSB % APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002305 tcShiftRight (dst, dstParts, shift);
2306
Craig Topper55229b72017-04-02 19:17:22 +00002307 /* We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC
Neil Boothb6182162007-10-08 13:47:12 +00002308 in DST. If this is less that srcBits, append the rest, else
2309 clear the high bits. */
Craig Topper55229b72017-04-02 19:17:22 +00002310 unsigned n = dstParts * APINT_BITS_PER_WORD - shift;
Neil Boothb6182162007-10-08 13:47:12 +00002311 if (n < srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002312 WordType mask = lowBitMask (srcBits - n);
Neil Boothb6182162007-10-08 13:47:12 +00002313 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
Craig Topper55229b72017-04-02 19:17:22 +00002314 << n % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002315 } else if (n > srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002316 if (srcBits % APINT_BITS_PER_WORD)
2317 dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002318 }
2319
2320 /* Clear high parts. */
2321 while (dstParts < dstCount)
2322 dst[dstParts++] = 0;
2323}
2324
Chris Lattner6b695682007-08-16 15:56:55 +00002325/* DST += RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002326APInt::WordType APInt::tcAdd(WordType *dst, const WordType *rhs,
2327 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002328 assert(c <= 1);
2329
Craig Topperb0038162017-03-28 05:32:52 +00002330 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002331 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002332 if (c) {
2333 dst[i] += rhs[i] + 1;
2334 c = (dst[i] <= l);
2335 } else {
2336 dst[i] += rhs[i];
2337 c = (dst[i] < l);
2338 }
2339 }
2340
2341 return c;
2342}
2343
Craig Topper92fc4772017-04-13 04:36:06 +00002344/// This function adds a single "word" integer, src, to the multiple
2345/// "word" integer array, dst[]. dst[] is modified to reflect the addition and
2346/// 1 is returned if there is a carry out, otherwise 0 is returned.
2347/// @returns the carry of the addition.
2348APInt::WordType APInt::tcAddPart(WordType *dst, WordType src,
2349 unsigned parts) {
2350 for (unsigned i = 0; i < parts; ++i) {
2351 dst[i] += src;
2352 if (dst[i] >= src)
2353 return 0; // No need to carry so exit early.
2354 src = 1; // Carry one to next digit.
2355 }
2356
2357 return 1;
2358}
2359
Chris Lattner6b695682007-08-16 15:56:55 +00002360/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002361APInt::WordType APInt::tcSubtract(WordType *dst, const WordType *rhs,
2362 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002363 assert(c <= 1);
2364
Craig Topperb0038162017-03-28 05:32:52 +00002365 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002366 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002367 if (c) {
2368 dst[i] -= rhs[i] + 1;
2369 c = (dst[i] >= l);
2370 } else {
2371 dst[i] -= rhs[i];
2372 c = (dst[i] > l);
2373 }
2374 }
2375
2376 return c;
2377}
2378
Craig Topper92fc4772017-04-13 04:36:06 +00002379/// This function subtracts a single "word" (64-bit word), src, from
2380/// the multi-word integer array, dst[], propagating the borrowed 1 value until
2381/// no further borrowing is needed or it runs out of "words" in dst. The result
2382/// is 1 if "borrowing" exhausted the digits in dst, or 0 if dst was not
2383/// exhausted. In other words, if src > dst then this function returns 1,
2384/// otherwise 0.
2385/// @returns the borrow out of the subtraction
2386APInt::WordType APInt::tcSubtractPart(WordType *dst, WordType src,
2387 unsigned parts) {
2388 for (unsigned i = 0; i < parts; ++i) {
2389 WordType Dst = dst[i];
2390 dst[i] -= src;
2391 if (src <= Dst)
2392 return 0; // No need to borrow so exit early.
2393 src = 1; // We have to "borrow 1" from next "word"
2394 }
2395
2396 return 1;
2397}
2398
Chris Lattner6b695682007-08-16 15:56:55 +00002399/* Negate a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002400void APInt::tcNegate(WordType *dst, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002401 tcComplement(dst, parts);
2402 tcIncrement(dst, parts);
2403}
2404
Neil Boothc8b650a2007-10-06 00:43:45 +00002405/* DST += SRC * MULTIPLIER + CARRY if add is true
2406 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002407
2408 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2409 they must start at the same point, i.e. DST == SRC.
2410
2411 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2412 returned. Otherwise DST is filled with the least significant
2413 DSTPARTS parts of the result, and if all of the omitted higher
2414 parts were zero return zero, otherwise overflow occurred and
2415 return one. */
Craig Topper55229b72017-04-02 19:17:22 +00002416int APInt::tcMultiplyPart(WordType *dst, const WordType *src,
2417 WordType multiplier, WordType carry,
Craig Topper6a8518082017-03-28 05:32:55 +00002418 unsigned srcParts, unsigned dstParts,
2419 bool add) {
Chris Lattner6b695682007-08-16 15:56:55 +00002420 /* Otherwise our writes of DST kill our later reads of SRC. */
2421 assert(dst <= src || dst >= src + srcParts);
2422 assert(dstParts <= srcParts + 1);
2423
2424 /* N loops; minimum of dstParts and srcParts. */
Craig Topperb0038162017-03-28 05:32:52 +00002425 unsigned n = dstParts < srcParts ? dstParts: srcParts;
Chris Lattner6b695682007-08-16 15:56:55 +00002426
Craig Topperb0038162017-03-28 05:32:52 +00002427 unsigned i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002428 for (i = 0; i < n; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002429 WordType low, mid, high, srcPart;
Chris Lattner6b695682007-08-16 15:56:55 +00002430
2431 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2432
2433 This cannot overflow, because
2434
2435 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2436
2437 which is less than n^2. */
2438
2439 srcPart = src[i];
2440
Craig Topper6a8518082017-03-28 05:32:55 +00002441 if (multiplier == 0 || srcPart == 0) {
Chris Lattner6b695682007-08-16 15:56:55 +00002442 low = carry;
2443 high = 0;
2444 } else {
2445 low = lowHalf(srcPart) * lowHalf(multiplier);
2446 high = highHalf(srcPart) * highHalf(multiplier);
2447
2448 mid = lowHalf(srcPart) * highHalf(multiplier);
2449 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002450 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002451 if (low + mid < low)
2452 high++;
2453 low += mid;
2454
2455 mid = highHalf(srcPart) * lowHalf(multiplier);
2456 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002457 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002458 if (low + mid < low)
2459 high++;
2460 low += mid;
2461
2462 /* Now add carry. */
2463 if (low + carry < low)
2464 high++;
2465 low += carry;
2466 }
2467
2468 if (add) {
2469 /* And now DST[i], and store the new low part there. */
2470 if (low + dst[i] < low)
2471 high++;
2472 dst[i] += low;
2473 } else
2474 dst[i] = low;
2475
2476 carry = high;
2477 }
2478
2479 if (i < dstParts) {
2480 /* Full multiplication, there is no overflow. */
2481 assert(i + 1 == dstParts);
2482 dst[i] = carry;
2483 return 0;
2484 } else {
2485 /* We overflowed if there is carry. */
2486 if (carry)
2487 return 1;
2488
2489 /* We would overflow if any significant unwritten parts would be
2490 non-zero. This is true if any remaining src parts are non-zero
2491 and the multiplier is non-zero. */
2492 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002493 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002494 if (src[i])
2495 return 1;
2496
2497 /* We fitted in the narrow destination. */
2498 return 0;
2499 }
2500}
2501
2502/* DST = LHS * RHS, where DST has the same width as the operands and
2503 is filled with the least significant parts of the result. Returns
2504 one if overflow occurred, otherwise zero. DST must be disjoint
2505 from both operands. */
Craig Topper55229b72017-04-02 19:17:22 +00002506int APInt::tcMultiply(WordType *dst, const WordType *lhs,
2507 const WordType *rhs, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002508 assert(dst != lhs && dst != rhs);
2509
Craig Topperb0038162017-03-28 05:32:52 +00002510 int overflow = 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002511 tcSet(dst, 0, parts);
2512
Craig Topperb0038162017-03-28 05:32:52 +00002513 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002514 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2515 parts - i, true);
2516
2517 return overflow;
2518}
2519
Neil Booth0ea72a92007-10-06 00:24:48 +00002520/* DST = LHS * RHS, where DST has width the sum of the widths of the
2521 operands. No overflow occurs. DST must be disjoint from both
2522 operands. Returns the number of parts required to hold the
2523 result. */
Craig Topper55229b72017-04-02 19:17:22 +00002524unsigned APInt::tcFullMultiply(WordType *dst, const WordType *lhs,
2525 const WordType *rhs, unsigned lhsParts,
Craig Topper6a8518082017-03-28 05:32:55 +00002526 unsigned rhsParts) {
Neil Booth0ea72a92007-10-06 00:24:48 +00002527 /* Put the narrower number on the LHS for less loops below. */
2528 if (lhsParts > rhsParts) {
2529 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2530 } else {
Neil Booth0ea72a92007-10-06 00:24:48 +00002531 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002532
Neil Booth0ea72a92007-10-06 00:24:48 +00002533 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002534
Craig Topperb0038162017-03-28 05:32:52 +00002535 for (unsigned i = 0; i < lhsParts; i++)
2536 tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002537
Craig Topperb0038162017-03-28 05:32:52 +00002538 unsigned n = lhsParts + rhsParts;
Neil Booth0ea72a92007-10-06 00:24:48 +00002539
2540 return n - (dst[n - 1] == 0);
2541 }
Chris Lattner6b695682007-08-16 15:56:55 +00002542}
2543
2544/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2545 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2546 set REMAINDER to the remainder, return zero. i.e.
2547
2548 OLD_LHS = RHS * LHS + REMAINDER
2549
2550 SCRATCH is a bignum of the same size as the operands and result for
2551 use by the routine; its contents need not be initialized and are
2552 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2553*/
Craig Topper55229b72017-04-02 19:17:22 +00002554int APInt::tcDivide(WordType *lhs, const WordType *rhs,
2555 WordType *remainder, WordType *srhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002556 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002557 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2558
Craig Topperb0038162017-03-28 05:32:52 +00002559 unsigned shiftCount = tcMSB(rhs, parts) + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002560 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002561 return true;
2562
Craig Topper55229b72017-04-02 19:17:22 +00002563 shiftCount = parts * APINT_BITS_PER_WORD - shiftCount;
2564 unsigned n = shiftCount / APINT_BITS_PER_WORD;
2565 WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD);
Chris Lattner6b695682007-08-16 15:56:55 +00002566
2567 tcAssign(srhs, rhs, parts);
2568 tcShiftLeft(srhs, parts, shiftCount);
2569 tcAssign(remainder, lhs, parts);
2570 tcSet(lhs, 0, parts);
2571
2572 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2573 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002574 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002575 int compare;
2576
2577 compare = tcCompare(remainder, srhs, parts);
2578 if (compare >= 0) {
2579 tcSubtract(remainder, srhs, 0, parts);
2580 lhs[n] |= mask;
2581 }
2582
2583 if (shiftCount == 0)
2584 break;
2585 shiftCount--;
2586 tcShiftRight(srhs, parts, 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002587 if ((mask >>= 1) == 0) {
Craig Topper55229b72017-04-02 19:17:22 +00002588 mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002589 n--;
2590 }
Chris Lattner6b695682007-08-16 15:56:55 +00002591 }
2592
2593 return false;
2594}
2595
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002596/// Shift a bignum left Cound bits in-place. Shifted in bits are zero. There are
2597/// no restrictions on Count.
2598void APInt::tcShiftLeft(WordType *Dst, unsigned Words, unsigned Count) {
2599 // Don't bother performing a no-op shift.
2600 if (!Count)
2601 return;
Chris Lattner6b695682007-08-16 15:56:55 +00002602
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002603 /* WordShift is the inter-part shift; BitShift is is intra-part shift. */
2604 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2605 unsigned BitShift = Count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002606
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002607 // Fastpath for moving by whole words.
2608 if (BitShift == 0) {
2609 std::memmove(Dst + WordShift, Dst, (Words - WordShift) * APINT_WORD_SIZE);
2610 } else {
2611 while (Words-- > WordShift) {
2612 Dst[Words] = Dst[Words - WordShift] << BitShift;
2613 if (Words > WordShift)
2614 Dst[Words] |=
2615 Dst[Words - WordShift - 1] >> (APINT_BITS_PER_WORD - BitShift);
Neil Boothb6182162007-10-08 13:47:12 +00002616 }
Neil Boothb6182162007-10-08 13:47:12 +00002617 }
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002618
2619 // Fill in the remainder with 0s.
2620 std::memset(Dst, 0, WordShift * APINT_WORD_SIZE);
Chris Lattner6b695682007-08-16 15:56:55 +00002621}
2622
Craig Topper9575d8f2017-04-17 21:43:43 +00002623/// Shift a bignum right Count bits in-place. Shifted in bits are zero. There
2624/// are no restrictions on Count.
2625void APInt::tcShiftRight(WordType *Dst, unsigned Words, unsigned Count) {
2626 // Don't bother performing a no-op shift.
2627 if (!Count)
2628 return;
Chris Lattner6b695682007-08-16 15:56:55 +00002629
Craig Topper9575d8f2017-04-17 21:43:43 +00002630 // WordShift is the inter-part shift; BitShift is is intra-part shift.
2631 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2632 unsigned BitShift = Count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002633
Craig Topper9575d8f2017-04-17 21:43:43 +00002634 unsigned WordsToMove = Words - WordShift;
2635 // Fastpath for moving by whole words.
2636 if (BitShift == 0) {
2637 std::memmove(Dst, Dst + WordShift, WordsToMove * APINT_WORD_SIZE);
2638 } else {
2639 for (unsigned i = 0; i != WordsToMove; ++i) {
2640 Dst[i] = Dst[i + WordShift] >> BitShift;
2641 if (i + 1 != WordsToMove)
2642 Dst[i] |= Dst[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift);
Neil Boothb6182162007-10-08 13:47:12 +00002643 }
Chris Lattner6b695682007-08-16 15:56:55 +00002644 }
Craig Topper9575d8f2017-04-17 21:43:43 +00002645
2646 // Fill in the remainder with 0s.
2647 std::memset(Dst + WordsToMove, 0, WordShift * APINT_WORD_SIZE);
Chris Lattner6b695682007-08-16 15:56:55 +00002648}
2649
2650/* Bitwise and of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002651void APInt::tcAnd(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002652 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002653 dst[i] &= rhs[i];
2654}
2655
2656/* Bitwise inclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002657void APInt::tcOr(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002658 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002659 dst[i] |= rhs[i];
2660}
2661
2662/* Bitwise exclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002663void APInt::tcXor(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002664 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002665 dst[i] ^= rhs[i];
2666}
2667
2668/* Complement a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002669void APInt::tcComplement(WordType *dst, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002670 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002671 dst[i] = ~dst[i];
2672}
2673
2674/* Comparison (unsigned) of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002675int APInt::tcCompare(const WordType *lhs, const WordType *rhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002676 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002677 while (parts) {
Craig Topper99cfe4f2017-04-01 21:50:06 +00002678 parts--;
2679 if (lhs[parts] == rhs[parts])
2680 continue;
Chris Lattner6b695682007-08-16 15:56:55 +00002681
Craig Topper68a3ed22017-04-01 21:50:10 +00002682 return (lhs[parts] > rhs[parts]) ? 1 : -1;
Craig Topper99cfe4f2017-04-01 21:50:06 +00002683 }
Chris Lattner6b695682007-08-16 15:56:55 +00002684
2685 return 0;
2686}
2687
Chris Lattner6b695682007-08-16 15:56:55 +00002688/* Set the least significant BITS bits of a bignum, clear the
2689 rest. */
Craig Topper55229b72017-04-02 19:17:22 +00002690void APInt::tcSetLeastSignificantBits(WordType *dst, unsigned parts,
Craig Topper6a8518082017-03-28 05:32:55 +00002691 unsigned bits) {
Craig Topperb0038162017-03-28 05:32:52 +00002692 unsigned i = 0;
Craig Topper55229b72017-04-02 19:17:22 +00002693 while (bits > APINT_BITS_PER_WORD) {
2694 dst[i++] = ~(WordType) 0;
2695 bits -= APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002696 }
2697
2698 if (bits)
Craig Topper55229b72017-04-02 19:17:22 +00002699 dst[i++] = ~(WordType) 0 >> (APINT_BITS_PER_WORD - bits);
Chris Lattner6b695682007-08-16 15:56:55 +00002700
2701 while (i < parts)
2702 dst[i++] = 0;
2703}