blob: 6f5df5201dbdc9d46ea1f38884ca7fb429487dab [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)
Reid Spencer1ba83352007-02-21 03:55:44 +0000123 : BitWidth(numbits), VAL(0) {
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
Chris Lattner1ac3e252008-08-20 17:02:31 +0000128APInt& APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer7c16cd22007-02-26 23:38:21 +0000129 // Don't do anything for X = X
130 if (this == &RHS)
131 return *this;
132
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);
Reid Spencer7c16cd22007-02-26 23:38:21 +0000137 return *this;
138 }
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;
157 return 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
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000174/// This function adds a single "digit" integer, y, to the multiple
Reid Spencera856b6e2007-02-18 18:38:44 +0000175/// "digit" integer array, x[]. x[] is modified to reflect the addition and
176/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer100502d2007-02-17 03:16:00 +0000177/// @returns the carry of the addition.
Chris Lattner77527f52009-01-21 18:09:24 +0000178static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
179 for (unsigned i = 0; i < len; ++i) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000180 dest[i] = y + x[i];
181 if (dest[i] < y)
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000182 y = 1; // Carry one to next digit.
Reid Spenceree0a6852007-02-18 06:39:42 +0000183 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000184 y = 0; // No need to carry so exit early
Reid Spenceree0a6852007-02-18 06:39:42 +0000185 break;
186 }
Reid Spencer100502d2007-02-17 03:16:00 +0000187 }
Reid Spenceree0a6852007-02-18 06:39:42 +0000188 return y;
Reid Spencer100502d2007-02-17 03:16:00 +0000189}
190
Zhou Shengdac63782007-02-06 03:00:16 +0000191/// @brief Prefix increment operator. Increments the APInt by one.
192APInt& APInt::operator++() {
Eric Christopher820256b2009-08-21 04:06:45 +0000193 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000194 ++VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000195 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000196 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000197 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000198}
199
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000200/// This function subtracts a single "digit" (64-bit word), y, from
Eric Christopher820256b2009-08-21 04:06:45 +0000201/// the multi-digit integer array, x[], propagating the borrowed 1 value until
Joerg Sonnenbergerd7baada2017-01-05 17:59:22 +0000202/// no further borrowing is needed or it runs out of "digits" in x. The result
Reid Spencera856b6e2007-02-18 18:38:44 +0000203/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
204/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencera41e93b2007-02-25 19:32:03 +0000205/// @returns the borrow out of the subtraction
Chris Lattner77527f52009-01-21 18:09:24 +0000206static bool sub_1(uint64_t x[], unsigned len, uint64_t y) {
207 for (unsigned i = 0; i < len; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000208 uint64_t X = x[i];
Reid Spenceree0a6852007-02-18 06:39:42 +0000209 x[i] -= y;
Eric Christopher820256b2009-08-21 04:06:45 +0000210 if (y > X)
Reid Spencera856b6e2007-02-18 18:38:44 +0000211 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer100502d2007-02-17 03:16:00 +0000212 else {
Reid Spencera856b6e2007-02-18 18:38:44 +0000213 y = 0; // No need to borrow
214 break; // Remaining digits are unchanged so exit early
Reid Spencer100502d2007-02-17 03:16:00 +0000215 }
216 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000217 return bool(y);
Reid Spencer100502d2007-02-17 03:16:00 +0000218}
219
Zhou Shengdac63782007-02-06 03:00:16 +0000220/// @brief Prefix decrement operator. Decrements the APInt by one.
221APInt& APInt::operator--() {
Eric Christopher820256b2009-08-21 04:06:45 +0000222 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000223 --VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000224 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000225 sub_1(pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000226 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000227}
228
Reid Spencera41e93b2007-02-25 19:32:03 +0000229/// Adds the RHS APint to this APInt.
230/// @returns this, after addition of RHS.
Eric Christopher820256b2009-08-21 04:06:45 +0000231/// @brief Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000232APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000233 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000234 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000235 VAL += RHS.VAL;
Craig Topper15e484a2017-04-02 06:59:43 +0000236 else
237 tcAdd(pVal, RHS.pVal, 0, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000238 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000239}
240
Pete Cooperfea21392016-07-22 20:55:46 +0000241APInt& APInt::operator+=(uint64_t RHS) {
242 if (isSingleWord())
243 VAL += RHS;
244 else
245 add_1(pVal, pVal, getNumWords(), RHS);
246 return clearUnusedBits();
247}
248
Reid Spencera41e93b2007-02-25 19:32:03 +0000249/// Subtracts the RHS APInt from this APInt
250/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000251/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000252APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000253 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000254 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000255 VAL -= RHS.VAL;
256 else
Craig Topper15e484a2017-04-02 06:59:43 +0000257 tcSubtract(pVal, RHS.pVal, 0, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000258 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000259}
260
Pete Cooperfea21392016-07-22 20:55:46 +0000261APInt& APInt::operator-=(uint64_t RHS) {
262 if (isSingleWord())
263 VAL -= RHS;
264 else
265 sub_1(pVal, getNumWords(), RHS);
266 return clearUnusedBits();
267}
268
Dan Gohman4a618822010-02-10 16:03:48 +0000269/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000270/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000271/// @returns the carry out of the multiplication.
272/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000273static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000274 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000275 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000276 uint64_t carry = 0;
277
278 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000279 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000280 // Split x into high and low words
281 uint64_t lx = x[i] & 0xffffffffULL;
282 uint64_t hx = x[i] >> 32;
283 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000284 // hasCarry == 0, no carry
285 // hasCarry == 1, has carry
286 // hasCarry == 2, no carry and the calculation result == 0.
287 uint8_t hasCarry = 0;
288 dest[i] = carry + lx * ly;
289 // Determine if the add above introduces carry.
290 hasCarry = (dest[i] < carry) ? 1 : 0;
291 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000292 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000293 // (2^32 - 1) + 2^32 = 2^64.
294 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
295
296 carry += (lx * hy) & 0xffffffffULL;
297 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000298 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000299 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
300 }
Reid Spencer100502d2007-02-17 03:16:00 +0000301 return carry;
302}
303
Eric Christopher820256b2009-08-21 04:06:45 +0000304/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000305/// the integer array dest. Note that dest's size must be >= xlen + ylen.
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000306/// @brief Generalized multiplication of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000307static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
308 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000309 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000310 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000311 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000312 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000313 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000314 lx = x[j] & 0xffffffffULL;
315 hx = x[j] >> 32;
316 // hasCarry - A flag to indicate if has carry.
317 // hasCarry == 0, no carry
318 // hasCarry == 1, has carry
319 // hasCarry == 2, no carry and the calculation result == 0.
320 uint8_t hasCarry = 0;
321 uint64_t resul = carry + lx * ly;
322 hasCarry = (resul < carry) ? 1 : 0;
323 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
324 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
325
326 carry += (lx * hy) & 0xffffffffULL;
327 resul = (carry << 32) | (resul & 0xffffffffULL);
328 dest[i+j] += resul;
329 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000330 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000331 ((lx * hy) >> 32) + hx * hy;
332 }
333 dest[i+xlen] = carry;
334 }
335}
336
Zhou Shengdac63782007-02-06 03:00:16 +0000337APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000338 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000339 if (isSingleWord()) {
Reid Spencer4bb430c2007-02-20 20:42:10 +0000340 VAL *= RHS.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000341 clearUnusedBits();
342 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000343 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000344
345 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000346 unsigned lhsBits = getActiveBits();
347 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000348 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000349 // 0 * X ===> 0
350 return *this;
351
352 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000353 unsigned rhsBits = RHS.getActiveBits();
354 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000355 if (!rhsWords) {
356 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000357 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000358 return *this;
359 }
360
361 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000362 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000363 uint64_t *dest = getMemory(destWords);
364
365 // Perform the long multiply
366 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
367
368 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000369 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000370 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000371 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000372 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000373
374 // delete dest array and return
375 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000376 return *this;
377}
378
Craig Topperf496f9a2017-03-28 04:00:47 +0000379APInt& APInt::AndAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000380 tcAnd(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000381 return *this;
382}
383
Craig Topperf496f9a2017-03-28 04:00:47 +0000384APInt& APInt::OrAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000385 tcOr(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000386 return *this;
387}
388
Craig Topperf496f9a2017-03-28 04:00:47 +0000389APInt& APInt::XorAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000390 tcXor(pVal, RHS.pVal, getNumWords());
Craig Topper9028f052017-01-24 02:10:15 +0000391 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000392}
393
Zhou Shengdac63782007-02-06 03:00:16 +0000394APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000395 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000396 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000397 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000398 APInt Result(*this);
399 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000400 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000401}
402
Chris Lattner1ac3e252008-08-20 17:02:31 +0000403bool APInt::EqualSlowCase(const APInt& RHS) const {
Matthias Braun5117fcd2016-02-15 20:06:19 +0000404 return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000405}
406
Chris Lattner1ac3e252008-08-20 17:02:31 +0000407bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000408 unsigned n = getActiveBits();
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000409 if (n <= APINT_BITS_PER_WORD)
410 return pVal[0] == Val;
411 else
412 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000413}
414
Reid Spencer1d072122007-02-16 22:36:51 +0000415bool APInt::ult(const APInt& RHS) const {
416 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
417 if (isSingleWord())
418 return VAL < RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000419
420 // Get active bit length of both operands
Chris Lattner77527f52009-01-21 18:09:24 +0000421 unsigned n1 = getActiveBits();
422 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000423
424 // If magnitude of LHS is less than RHS, return true.
425 if (n1 < n2)
426 return true;
427
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000428 // If magnitude of RHS is greater than LHS, return false.
Reid Spencera41e93b2007-02-25 19:32:03 +0000429 if (n2 < n1)
430 return false;
431
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000432 // If they both fit in a word, just compare the low order word
Reid Spencera41e93b2007-02-25 19:32:03 +0000433 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
434 return pVal[0] < RHS.pVal[0];
435
436 // Otherwise, compare all words
Chris Lattner77527f52009-01-21 18:09:24 +0000437 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000438 for (int i = topWord; i >= 0; --i) {
Eric Christopher820256b2009-08-21 04:06:45 +0000439 if (pVal[i] > RHS.pVal[i])
Reid Spencer1d072122007-02-16 22:36:51 +0000440 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000441 if (pVal[i] < RHS.pVal[i])
Reid Spencera41e93b2007-02-25 19:32:03 +0000442 return true;
Zhou Shengdac63782007-02-06 03:00:16 +0000443 }
444 return false;
445}
446
Reid Spencer1d072122007-02-16 22:36:51 +0000447bool APInt::slt(const APInt& RHS) const {
448 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000449 if (isSingleWord()) {
David Majnemer5f1c0172016-06-24 20:51:47 +0000450 int64_t lhsSext = SignExtend64(VAL, BitWidth);
451 int64_t rhsSext = SignExtend64(RHS.VAL, BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000452 return lhsSext < rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000453 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000454
Reid Spencer54abdcf2007-02-27 18:23:40 +0000455 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000456 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000457
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000458 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
459 if (lhsNeg != rhsNeg)
460 return lhsNeg;
461
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000462 // Otherwise we can just use an unsigned comparison, because even negative
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000463 // numbers compare correctly this way if both have the same signed-ness.
464 return ult(RHS);
Zhou Shengdac63782007-02-06 03:00:16 +0000465}
466
Jay Foad25a5e4c2010-12-01 08:53:58 +0000467void APInt::setBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000468 if (isSingleWord())
Reid Spencera41e93b2007-02-25 19:32:03 +0000469 VAL |= maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000470 else
Reid Spencera41e93b2007-02-25 19:32:03 +0000471 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000472}
473
Craig Topperbafdd032017-03-07 01:56:01 +0000474void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
475 unsigned loWord = whichWord(loBit);
476 unsigned hiWord = whichWord(hiBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000477
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000478 // Create an initial mask for the low word with zeros below loBit.
Craig Topperbafdd032017-03-07 01:56:01 +0000479 uint64_t loMask = UINT64_MAX << whichBit(loBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000480
Craig Topperbafdd032017-03-07 01:56:01 +0000481 // If hiBit is not aligned, we need a high mask.
482 unsigned hiShiftAmt = whichBit(hiBit);
483 if (hiShiftAmt != 0) {
484 // Create a high mask with zeros above hiBit.
485 uint64_t hiMask = UINT64_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
486 // If loWord and hiWord are equal, then we combine the masks. Otherwise,
487 // set the bits in hiWord.
488 if (hiWord == loWord)
489 loMask &= hiMask;
490 else
Simon Pilgrimaed35222017-02-24 10:15:29 +0000491 pVal[hiWord] |= hiMask;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000492 }
Craig Topperbafdd032017-03-07 01:56:01 +0000493 // Apply the mask to the low word.
494 pVal[loWord] |= loMask;
495
496 // Fill any words between loWord and hiWord with all ones.
497 for (unsigned word = loWord + 1; word < hiWord; ++word)
498 pVal[word] = UINT64_MAX;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000499}
500
Zhou Shengdac63782007-02-06 03:00:16 +0000501/// Set the given bit to 0 whose position is given as "bitPosition".
502/// @brief Set a given bit to 0.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000503void APInt::clearBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000504 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000505 VAL &= ~maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000506 else
Reid Spencera856b6e2007-02-18 18:38:44 +0000507 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000508}
509
Zhou Shengdac63782007-02-06 03:00:16 +0000510/// @brief Toggle every bit to its opposite value.
Craig Topperafc9e352017-03-27 17:10:21 +0000511void APInt::flipAllBitsSlowCase() {
Craig Toppera742cb52017-04-01 21:50:08 +0000512 tcComplement(pVal, getNumWords());
Craig Topperafc9e352017-03-27 17:10:21 +0000513 clearUnusedBits();
514}
Zhou Shengdac63782007-02-06 03:00:16 +0000515
Eric Christopher820256b2009-08-21 04:06:45 +0000516/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000517/// as "bitPosition".
518/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000519void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000520 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000521 if ((*this)[bitPosition]) clearBit(bitPosition);
522 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000523}
524
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000525void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
526 unsigned subBitWidth = subBits.getBitWidth();
527 assert(0 < subBitWidth && (subBitWidth + bitPosition) <= BitWidth &&
528 "Illegal bit insertion");
529
530 // Insertion is a direct copy.
531 if (subBitWidth == BitWidth) {
532 *this = subBits;
533 return;
534 }
535
536 // Single word result can be done as a direct bitmask.
537 if (isSingleWord()) {
538 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
539 VAL &= ~(mask << bitPosition);
540 VAL |= (subBits.VAL << bitPosition);
541 return;
542 }
543
544 unsigned loBit = whichBit(bitPosition);
545 unsigned loWord = whichWord(bitPosition);
546 unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
547
548 // Insertion within a single word can be done as a direct bitmask.
549 if (loWord == hi1Word) {
550 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
551 pVal[loWord] &= ~(mask << loBit);
552 pVal[loWord] |= (subBits.VAL << loBit);
553 return;
554 }
555
556 // Insert on word boundaries.
557 if (loBit == 0) {
558 // Direct copy whole words.
559 unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
560 memcpy(pVal + loWord, subBits.getRawData(),
561 numWholeSubWords * APINT_WORD_SIZE);
562
563 // Mask+insert remaining bits.
564 unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
565 if (remainingBits != 0) {
566 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - remainingBits);
567 pVal[hi1Word] &= ~mask;
568 pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
569 }
570 return;
571 }
572
573 // General case - set/clear individual bits in dst based on src.
574 // TODO - there is scope for optimization here, but at the moment this code
575 // path is barely used so prefer readability over performance.
576 for (unsigned i = 0; i != subBitWidth; ++i) {
577 if (subBits[i])
578 setBit(bitPosition + i);
579 else
580 clearBit(bitPosition + i);
581 }
582}
583
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000584APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
585 assert(numBits > 0 && "Can't extract zero bits");
586 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
587 "Illegal bit extraction");
588
589 if (isSingleWord())
590 return APInt(numBits, VAL >> bitPosition);
591
592 unsigned loBit = whichBit(bitPosition);
593 unsigned loWord = whichWord(bitPosition);
594 unsigned hiWord = whichWord(bitPosition + numBits - 1);
595
596 // Single word result extracting bits from a single word source.
597 if (loWord == hiWord)
598 return APInt(numBits, pVal[loWord] >> loBit);
599
600 // Extracting bits that start on a source word boundary can be done
601 // as a fast memory copy.
602 if (loBit == 0)
603 return APInt(numBits, makeArrayRef(pVal + loWord, 1 + hiWord - loWord));
604
605 // General case - shift + copy source words directly into place.
606 APInt Result(numBits, 0);
607 unsigned NumSrcWords = getNumWords();
608 unsigned NumDstWords = Result.getNumWords();
609
610 for (unsigned word = 0; word < NumDstWords; ++word) {
611 uint64_t w0 = pVal[loWord + word];
612 uint64_t w1 =
613 (loWord + word + 1) < NumSrcWords ? pVal[loWord + word + 1] : 0;
614 Result.pVal[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
615 }
616
617 return Result.clearUnusedBits();
618}
619
Benjamin Kramer92d89982010-07-14 22:38:02 +0000620unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000621 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000622 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +0000623 radix == 36) &&
624 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000625
626 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000627
Eric Christopher43a1dec2009-08-21 04:10:31 +0000628 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000629 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000630 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000631 if (*p == '-' || *p == '+') {
632 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000633 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000634 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000635 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000636
Reid Spencer9329e7b2007-04-13 19:19:07 +0000637 // For radixes of power-of-two values, the bits required is accurately and
638 // easily computed
639 if (radix == 2)
640 return slen + isNegative;
641 if (radix == 8)
642 return slen * 3 + isNegative;
643 if (radix == 16)
644 return slen * 4 + isNegative;
645
Douglas Gregor663c0682011-09-14 15:54:46 +0000646 // FIXME: base 36
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000647
Reid Spencer9329e7b2007-04-13 19:19:07 +0000648 // This is grossly inefficient but accurate. We could probably do something
649 // with a computation of roughly slen*64/20 and then adjust by the value of
650 // the first few digits. But, I'm not sure how accurate that could be.
651
652 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000653 // be too large. This avoids the assertion in the constructor. This
654 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
655 // bits in that case.
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000656 unsigned sufficient
Douglas Gregor663c0682011-09-14 15:54:46 +0000657 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
658 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000659
660 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000661 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000662
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000663 // Compute how many bits are required. If the log is infinite, assume we need
664 // just bit.
665 unsigned log = tmp.logBase2();
666 if (log == (unsigned)-1) {
667 return isNegative + 1;
668 } else {
669 return isNegative + log + 1;
670 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000671}
672
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000673hash_code llvm::hash_value(const APInt &Arg) {
674 if (Arg.isSingleWord())
675 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000676
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000677 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000678}
679
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000680bool APInt::isSplat(unsigned SplatSizeInBits) const {
681 assert(getBitWidth() % SplatSizeInBits == 0 &&
682 "SplatSizeInBits must divide width!");
683 // We can check that all parts of an integer are equal by making use of a
684 // little trick: rotate and check if it's still the same value.
685 return *this == rotl(SplatSizeInBits);
686}
687
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000688/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000689APInt APInt::getHiBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000690 return this->lshr(BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000691}
692
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000693/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000694APInt APInt::getLoBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000695 APInt Result(getLowBitsSet(BitWidth, numBits));
696 Result &= *this;
697 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000698}
699
Chris Lattner77527f52009-01-21 18:09:24 +0000700unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000701 unsigned Count = 0;
702 for (int i = getNumWords()-1; i >= 0; --i) {
Craig Topper55229b72017-04-02 19:17:22 +0000703 uint64_t V = pVal[i];
Matthias Brauna6be4e82016-02-15 20:06:22 +0000704 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000705 Count += APINT_BITS_PER_WORD;
706 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000707 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000708 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000709 }
Zhou Shengdac63782007-02-06 03:00:16 +0000710 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000711 // Adjust for unused bits in the most significant word (they are zero).
712 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
713 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000714 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000715}
716
Chris Lattner77527f52009-01-21 18:09:24 +0000717unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000718 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000719 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000720
Chris Lattner77527f52009-01-21 18:09:24 +0000721 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000722 unsigned shift;
723 if (!highWordBits) {
724 highWordBits = APINT_BITS_PER_WORD;
725 shift = 0;
726 } else {
727 shift = APINT_BITS_PER_WORD - highWordBits;
728 }
Reid Spencer31acef52007-02-27 21:59:26 +0000729 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000730 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000731 if (Count == highWordBits) {
732 for (i--; i >= 0; --i) {
733 if (pVal[i] == -1ULL)
734 Count += APINT_BITS_PER_WORD;
735 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000736 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000737 break;
738 }
739 }
740 }
741 return Count;
742}
743
Chris Lattner77527f52009-01-21 18:09:24 +0000744unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000745 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000746 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000747 unsigned Count = 0;
748 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000749 for (; i < getNumWords() && pVal[i] == 0; ++i)
750 Count += APINT_BITS_PER_WORD;
751 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000752 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000753 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000754}
755
Chris Lattner77527f52009-01-21 18:09:24 +0000756unsigned APInt::countTrailingOnesSlowCase() const {
757 unsigned Count = 0;
758 unsigned i = 0;
Dan Gohmanc354ebd2008-02-14 22:38:45 +0000759 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000760 Count += APINT_BITS_PER_WORD;
761 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000762 Count += llvm::countTrailingOnes(pVal[i]);
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000763 return std::min(Count, BitWidth);
764}
765
Chris Lattner77527f52009-01-21 18:09:24 +0000766unsigned APInt::countPopulationSlowCase() const {
767 unsigned Count = 0;
768 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000769 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000770 return Count;
771}
772
Richard Smith4f9a8082011-11-23 21:33:37 +0000773/// Perform a logical right-shift from Src to Dst, which must be equal or
774/// non-overlapping, of Words words, by Shift, which must be less than 64.
775static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
776 unsigned Shift) {
777 uint64_t Carry = 0;
778 for (int I = Words - 1; I >= 0; --I) {
779 uint64_t Tmp = Src[I];
780 Dst[I] = (Tmp >> Shift) | Carry;
781 Carry = Tmp << (64 - Shift);
782 }
783}
784
Reid Spencer1d072122007-02-16 22:36:51 +0000785APInt APInt::byteSwap() const {
786 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
787 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000788 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000789 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000790 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000791 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000792 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000793 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000794 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000795 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000796 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000797 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000798 if (BitWidth == 64)
799 return APInt(BitWidth, ByteSwap_64(VAL));
800
801 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
802 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
803 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
804 if (Result.BitWidth != BitWidth) {
805 lshrNear(Result.pVal, Result.pVal, getNumWords(),
806 Result.BitWidth - BitWidth);
807 Result.BitWidth = BitWidth;
808 }
809 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000810}
811
Matt Arsenault155dda92016-03-21 15:00:35 +0000812APInt APInt::reverseBits() const {
813 switch (BitWidth) {
814 case 64:
815 return APInt(BitWidth, llvm::reverseBits<uint64_t>(VAL));
816 case 32:
817 return APInt(BitWidth, llvm::reverseBits<uint32_t>(VAL));
818 case 16:
819 return APInt(BitWidth, llvm::reverseBits<uint16_t>(VAL));
820 case 8:
821 return APInt(BitWidth, llvm::reverseBits<uint8_t>(VAL));
822 default:
823 break;
824 }
825
826 APInt Val(*this);
827 APInt Reversed(*this);
828 int S = BitWidth - 1;
829
830 const APInt One(BitWidth, 1);
831
832 for ((Val = Val.lshr(1)); Val != 0; (Val = Val.lshr(1))) {
833 Reversed <<= 1;
834 Reversed |= (Val & One);
835 --S;
836 }
837
838 Reversed <<= S;
839 return Reversed;
840}
841
Craig Topper278ebd22017-04-01 20:30:57 +0000842APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) {
Zhou Shengdac63782007-02-06 03:00:16 +0000843 while (!!B) {
Craig Topper278ebd22017-04-01 20:30:57 +0000844 APInt R = A.urem(B);
845 A = std::move(B);
846 B = std::move(R);
Zhou Shengdac63782007-02-06 03:00:16 +0000847 }
848 return A;
849}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000850
Chris Lattner77527f52009-01-21 18:09:24 +0000851APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000852 union {
853 double D;
854 uint64_t I;
855 } T;
856 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000857
858 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000859 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000860
861 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000862 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000863
864 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000865 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000866 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000867
868 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
869 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
870
871 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000872 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000873 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000874 APInt(width, mantissa >> (52 - exp));
875
876 // If the client didn't provide enough bits for us to shift the mantissa into
877 // then the result is undefined, just return 0
878 if (width <= exp - 52)
879 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000880
881 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000882 APInt Tmp(width, mantissa);
Chris Lattner77527f52009-01-21 18:09:24 +0000883 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd707d632007-02-12 20:02:55 +0000884 return isNeg ? -Tmp : Tmp;
885}
886
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000887/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000888/// The layout for double is as following (IEEE Standard 754):
889/// --------------------------------------
890/// | Sign Exponent Fraction Bias |
891/// |-------------------------------------- |
892/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000893/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000894double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000895
896 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000897 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000898 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
899 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000900 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000901 return double(sext);
902 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000903 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000904 }
905
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000906 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000907 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000908
909 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000910 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000911
912 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000913 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000914
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000915 // The exponent (without bias normalization) is just the number of bits
916 // we are using. Note that the sign bit is gone since we constructed the
917 // absolute value.
918 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000919
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000920 // Return infinity for exponent overflow
921 if (exp > 1023) {
922 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000923 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000924 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000925 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000926 }
927 exp += 1023; // Increment for 1023 bias
928
929 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
930 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000931 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000932 unsigned hiWord = whichWord(n-1);
933 if (hiWord == 0) {
934 mantissa = Tmp.pVal[0];
935 if (n > 52)
936 mantissa >>= n - 52; // shift down, we want the top 52 bits.
937 } else {
938 assert(hiWord > 0 && "huh?");
939 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
940 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
941 mantissa = hibits | lobits;
942 }
943
Zhou Shengd707d632007-02-12 20:02:55 +0000944 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000945 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000946 union {
947 double D;
948 uint64_t I;
949 } T;
950 T.I = sign | (exp << 52) | mantissa;
951 return T.D;
952}
953
Reid Spencer1d072122007-02-16 22:36:51 +0000954// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000955APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000956 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000957 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000958
959 if (width <= APINT_BITS_PER_WORD)
960 return APInt(width, getRawData()[0]);
961
962 APInt Result(getMemory(getNumWords(width)), width);
963
964 // Copy full words.
965 unsigned i;
966 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
967 Result.pVal[i] = pVal[i];
968
969 // Truncate and copy any partial word.
970 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
971 if (bits != 0)
972 Result.pVal[i] = pVal[i] << bits >> bits;
973
974 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000975}
976
977// Sign extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000978APInt APInt::sext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000979 assert(width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000980
981 if (width <= APINT_BITS_PER_WORD) {
982 uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
983 val = (int64_t)val >> (width - BitWidth);
984 return APInt(width, val >> (APINT_BITS_PER_WORD - width));
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000985 }
986
Jay Foad583abbc2010-12-07 08:25:19 +0000987 APInt Result(getMemory(getNumWords(width)), width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000988
Jay Foad583abbc2010-12-07 08:25:19 +0000989 // Copy full words.
990 unsigned i;
991 uint64_t word = 0;
992 for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
993 word = getRawData()[i];
994 Result.pVal[i] = word;
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000995 }
996
Jay Foad583abbc2010-12-07 08:25:19 +0000997 // Read and sign-extend any partial word.
998 unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
999 if (bits != 0)
1000 word = (int64_t)getRawData()[i] << bits >> bits;
1001 else
1002 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
1003
1004 // Write remaining full words.
1005 for (; i != width / APINT_BITS_PER_WORD; i++) {
1006 Result.pVal[i] = word;
1007 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001008 }
Jay Foad583abbc2010-12-07 08:25:19 +00001009
1010 // Write any partial word.
1011 bits = (0 - width) % APINT_BITS_PER_WORD;
1012 if (bits != 0)
1013 Result.pVal[i] = word << bits >> bits;
1014
1015 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001016}
1017
1018// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +00001019APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +00001020 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +00001021
1022 if (width <= APINT_BITS_PER_WORD)
1023 return APInt(width, VAL);
1024
1025 APInt Result(getMemory(getNumWords(width)), width);
1026
1027 // Copy words.
1028 unsigned i;
1029 for (i = 0; i != getNumWords(); i++)
1030 Result.pVal[i] = getRawData()[i];
1031
1032 // Zero remaining words.
1033 memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
1034
1035 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001036}
1037
Jay Foad583abbc2010-12-07 08:25:19 +00001038APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001039 if (BitWidth < width)
1040 return zext(width);
1041 if (BitWidth > width)
1042 return trunc(width);
1043 return *this;
1044}
1045
Jay Foad583abbc2010-12-07 08:25:19 +00001046APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001047 if (BitWidth < width)
1048 return sext(width);
1049 if (BitWidth > width)
1050 return trunc(width);
1051 return *this;
1052}
1053
Rafael Espindolabb893fe2012-01-27 23:33:07 +00001054APInt APInt::zextOrSelf(unsigned width) const {
1055 if (BitWidth < width)
1056 return zext(width);
1057 return *this;
1058}
1059
1060APInt APInt::sextOrSelf(unsigned width) const {
1061 if (BitWidth < width)
1062 return sext(width);
1063 return *this;
1064}
1065
Zhou Shenge93db8f2007-02-09 07:48:24 +00001066/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001067/// @brief Arithmetic right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001068APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001069 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001070}
1071
1072/// Arithmetic right-shift this APInt by shiftAmt.
1073/// @brief Arithmetic right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001074APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001075 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer1825dd02007-03-02 22:39:11 +00001076 // Handle a degenerate case
1077 if (shiftAmt == 0)
1078 return *this;
1079
1080 // Handle single word shifts with built-in ashr
Reid Spencer522ca7c2007-02-25 01:56:07 +00001081 if (isSingleWord()) {
1082 if (shiftAmt == BitWidth)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001083 return APInt(BitWidth, 0); // undefined
Jonathan Roelofs851b79d2016-08-10 19:50:14 +00001084 return APInt(BitWidth, SignExtend64(VAL, BitWidth) >> shiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001085 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001086
Reid Spencer1825dd02007-03-02 22:39:11 +00001087 // If all the bits were shifted out, the result is, technically, undefined.
1088 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1089 // issues in the algorithm below.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001090 if (shiftAmt == BitWidth) {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001091 if (isNegative())
Zhou Sheng1247c072008-06-05 13:27:38 +00001092 return APInt(BitWidth, -1ULL, true);
Reid Spencera41e93b2007-02-25 19:32:03 +00001093 else
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001094 return APInt(BitWidth, 0);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001095 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001096
1097 // Create some space for the result.
1098 uint64_t * val = new uint64_t[getNumWords()];
1099
Reid Spencer1825dd02007-03-02 22:39:11 +00001100 // Compute some values needed by the following shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001101 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1102 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1103 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1104 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer1825dd02007-03-02 22:39:11 +00001105 if (bitsInWord == 0)
1106 bitsInWord = APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001107
1108 // If we are shifting whole words, just move whole words
1109 if (wordShift == 0) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001110 // Move the words containing significant bits
Chris Lattner77527f52009-01-21 18:09:24 +00001111 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001112 val[i] = pVal[i+offset]; // move whole word
1113
1114 // Adjust the top significant word for sign bit fill, if negative
1115 if (isNegative())
1116 if (bitsInWord < APINT_BITS_PER_WORD)
1117 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1118 } else {
Eric Christopher820256b2009-08-21 04:06:45 +00001119 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001120 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001121 // This combines the shifted corresponding word with the low bits from
1122 // the next word (shifted into this word's high bits).
Eric Christopher820256b2009-08-21 04:06:45 +00001123 val[i] = (pVal[i+offset] >> wordShift) |
Reid Spencer1825dd02007-03-02 22:39:11 +00001124 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1125 }
1126
1127 // Shift the break word. In this case there are no bits from the next word
1128 // to include in this word.
1129 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1130
Alp Tokercb402912014-01-24 17:20:08 +00001131 // Deal with sign extension in the break word, and possibly the word before
Reid Spencer1825dd02007-03-02 22:39:11 +00001132 // it.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001133 if (isNegative()) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001134 if (wordShift > bitsInWord) {
1135 if (breakWord > 0)
Eric Christopher820256b2009-08-21 04:06:45 +00001136 val[breakWord-1] |=
Reid Spencer1825dd02007-03-02 22:39:11 +00001137 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1138 val[breakWord] |= ~0ULL;
Eric Christopher820256b2009-08-21 04:06:45 +00001139 } else
Reid Spencer1825dd02007-03-02 22:39:11 +00001140 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnerdad2d092007-05-03 18:15:36 +00001141 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001142 }
1143
Reid Spencer1825dd02007-03-02 22:39:11 +00001144 // Remaining words are 0 or -1, just assign them.
1145 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner77527f52009-01-21 18:09:24 +00001146 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001147 val[i] = fillValue;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001148 APInt Result(val, BitWidth);
1149 Result.clearUnusedBits();
1150 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001151}
1152
Zhou Shenge93db8f2007-02-09 07:48:24 +00001153/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001154/// @brief Logical right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001155APInt APInt::lshr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001156 return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001157}
1158
1159/// Logical right-shift this APInt by shiftAmt.
1160/// @brief Logical right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001161APInt APInt::lshr(unsigned shiftAmt) const {
Chris Lattnerdad2d092007-05-03 18:15:36 +00001162 if (isSingleWord()) {
Ahmed Charles0dca5d82012-02-24 19:06:15 +00001163 if (shiftAmt >= BitWidth)
Reid Spencer522ca7c2007-02-25 01:56:07 +00001164 return APInt(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001165 else
Reid Spencer522ca7c2007-02-25 01:56:07 +00001166 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001167 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001168
Reid Spencer44eef162007-02-26 01:19:48 +00001169 // If all the bits were shifted out, the result is 0. This avoids issues
1170 // with shifting by the size of the integer type, which produces undefined
1171 // results. We define these "undefined results" to always be 0.
Chad Rosier3d464d82012-06-08 18:04:52 +00001172 if (shiftAmt >= BitWidth)
Reid Spencer44eef162007-02-26 01:19:48 +00001173 return APInt(BitWidth, 0);
1174
Reid Spencerfffdf102007-05-17 06:26:29 +00001175 // If none of the bits are shifted out, the result is *this. This avoids
Eric Christopher820256b2009-08-21 04:06:45 +00001176 // issues with shifting by the size of the integer type, which produces
Reid Spencerfffdf102007-05-17 06:26:29 +00001177 // undefined results in the code below. This is also an optimization.
1178 if (shiftAmt == 0)
1179 return *this;
1180
Reid Spencer44eef162007-02-26 01:19:48 +00001181 // Create some space for the result.
1182 uint64_t * val = new uint64_t[getNumWords()];
1183
1184 // If we are shifting less than a word, compute the shift with a simple carry
1185 if (shiftAmt < APINT_BITS_PER_WORD) {
Richard Smith4f9a8082011-11-23 21:33:37 +00001186 lshrNear(val, pVal, getNumWords(), shiftAmt);
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001187 APInt Result(val, BitWidth);
1188 Result.clearUnusedBits();
1189 return Result;
Reid Spencera41e93b2007-02-25 19:32:03 +00001190 }
1191
Reid Spencer44eef162007-02-26 01:19:48 +00001192 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001193 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1194 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencer44eef162007-02-26 01:19:48 +00001195
1196 // If we are shifting whole words, just move whole words
1197 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001198 for (unsigned i = 0; i < getNumWords() - offset; ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001199 val[i] = pVal[i+offset];
Chris Lattner77527f52009-01-21 18:09:24 +00001200 for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
Reid Spencer44eef162007-02-26 01:19:48 +00001201 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001202 APInt Result(val, BitWidth);
1203 Result.clearUnusedBits();
1204 return Result;
Reid Spencer44eef162007-02-26 01:19:48 +00001205 }
1206
Eric Christopher820256b2009-08-21 04:06:45 +00001207 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001208 unsigned breakWord = getNumWords() - offset -1;
1209 for (unsigned i = 0; i < breakWord; ++i)
Reid Spencerd99feaf2007-03-01 05:39:56 +00001210 val[i] = (pVal[i+offset] >> wordShift) |
1211 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencer44eef162007-02-26 01:19:48 +00001212 // Shift the break word.
1213 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1214
1215 // Remaining words are 0
Chris Lattner77527f52009-01-21 18:09:24 +00001216 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001217 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001218 APInt Result(val, BitWidth);
1219 Result.clearUnusedBits();
1220 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001221}
1222
Zhou Shenge93db8f2007-02-09 07:48:24 +00001223/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001224/// @brief Left-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001225APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky030c4502009-01-19 17:42:33 +00001226 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner77527f52009-01-21 18:09:24 +00001227 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001228}
1229
Chris Lattner77527f52009-01-21 18:09:24 +00001230APInt APInt::shlSlowCase(unsigned shiftAmt) const {
Reid Spencera5c84d92007-02-25 00:56:44 +00001231 // If all the bits were shifted out, the result is 0. This avoids issues
1232 // with shifting by the size of the integer type, which produces undefined
1233 // results. We define these "undefined results" to always be 0.
1234 if (shiftAmt == BitWidth)
1235 return APInt(BitWidth, 0);
1236
Reid Spencer81ee0202007-05-12 18:01:57 +00001237 // If none of the bits are shifted out, the result is *this. This avoids a
1238 // lshr by the words size in the loop below which can produce incorrect
1239 // results. It also avoids the expensive computation below for a common case.
1240 if (shiftAmt == 0)
1241 return *this;
1242
Reid Spencera5c84d92007-02-25 00:56:44 +00001243 // Create some space for the result.
1244 uint64_t * val = new uint64_t[getNumWords()];
1245
1246 // If we are shifting less than a word, do it the easy way
1247 if (shiftAmt < APINT_BITS_PER_WORD) {
1248 uint64_t carry = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001249 for (unsigned i = 0; i < getNumWords(); i++) {
Reid Spencera5c84d92007-02-25 00:56:44 +00001250 val[i] = pVal[i] << shiftAmt | carry;
1251 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1252 }
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001253 APInt Result(val, BitWidth);
1254 Result.clearUnusedBits();
1255 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001256 }
1257
Reid Spencera5c84d92007-02-25 00:56:44 +00001258 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001259 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1260 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencera5c84d92007-02-25 00:56:44 +00001261
1262 // If we are shifting whole words, just move whole words
1263 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001264 for (unsigned i = 0; i < offset; i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001265 val[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001266 for (unsigned i = offset; i < getNumWords(); i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001267 val[i] = pVal[i-offset];
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001268 APInt Result(val, BitWidth);
1269 Result.clearUnusedBits();
1270 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001271 }
Reid Spencera5c84d92007-02-25 00:56:44 +00001272
1273 // Copy whole words from this to Result.
Chris Lattner77527f52009-01-21 18:09:24 +00001274 unsigned i = getNumWords() - 1;
Reid Spencera5c84d92007-02-25 00:56:44 +00001275 for (; i > offset; --i)
1276 val[i] = pVal[i-offset] << wordShift |
1277 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencerab0e08a2007-02-25 01:08:58 +00001278 val[offset] = pVal[0] << wordShift;
Reid Spencera5c84d92007-02-25 00:56:44 +00001279 for (i = 0; i < offset; ++i)
1280 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001281 APInt Result(val, BitWidth);
1282 Result.clearUnusedBits();
1283 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001284}
1285
Joey Gouly51c0ae52017-02-07 11:58:22 +00001286// Calculate the rotate amount modulo the bit width.
1287static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1288 unsigned rotBitWidth = rotateAmt.getBitWidth();
1289 APInt rot = rotateAmt;
1290 if (rotBitWidth < BitWidth) {
1291 // Extend the rotate APInt, so that the urem doesn't divide by 0.
1292 // e.g. APInt(1, 32) would give APInt(1, 0).
1293 rot = rotateAmt.zext(BitWidth);
1294 }
1295 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
1296 return rot.getLimitedValue(BitWidth);
1297}
1298
Dan Gohman105c1d42008-02-29 01:40:47 +00001299APInt APInt::rotl(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001300 return rotl(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001301}
1302
Chris Lattner77527f52009-01-21 18:09:24 +00001303APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001304 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001305 if (rotateAmt == 0)
1306 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001307 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001308}
1309
Dan Gohman105c1d42008-02-29 01:40:47 +00001310APInt APInt::rotr(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001311 return rotr(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001312}
1313
Chris Lattner77527f52009-01-21 18:09:24 +00001314APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001315 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001316 if (rotateAmt == 0)
1317 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001318 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001319}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001320
1321// Square Root - this method computes and returns the square root of "this".
1322// Three mechanisms are used for computation. For small values (<= 5 bits),
1323// a table lookup is done. This gets some performance for common cases. For
1324// values using less than 52 bits, the value is converted to double and then
1325// the libc sqrt function is called. The result is rounded and then converted
1326// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001327// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001328APInt APInt::sqrt() const {
1329
1330 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001331 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001332
1333 // Use a fast table for some small values. This also gets rid of some
1334 // rounding errors in libc sqrt for small values.
1335 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001336 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001337 /* 0 */ 0,
1338 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001339 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001340 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1341 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1342 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1343 /* 31 */ 6
1344 };
1345 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001346 }
1347
1348 // If the magnitude of the value fits in less than 52 bits (the precision of
1349 // an IEEE double precision floating point value), then we can use the
1350 // libc sqrt function which will probably use a hardware sqrt computation.
1351 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001352 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001353 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001354 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001355 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001356
1357 // Okay, all the short cuts are exhausted. We must compute it. The following
1358 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001359 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001360 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001361 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001362 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001363 APInt testy(BitWidth, 16);
1364 APInt x_old(BitWidth, 1);
1365 APInt x_new(BitWidth, 0);
1366 APInt two(BitWidth, 2);
1367
1368 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001369 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001370 if (i >= nbits || this->ule(testy)) {
1371 x_old = x_old.shl(i / 2);
1372 break;
1373 }
1374
Eric Christopher820256b2009-08-21 04:06:45 +00001375 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001376 for (;;) {
1377 x_new = (this->udiv(x_old) + x_old).udiv(two);
1378 if (x_old.ule(x_new))
1379 break;
1380 x_old = x_new;
1381 }
1382
1383 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001384 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001385 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001386 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001387 // floating point representation after 192 bits. There are no discrepancies
1388 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001389 APInt square(x_old * x_old);
1390 APInt nextSquare((x_old + 1) * (x_old +1));
1391 if (this->ult(square))
1392 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001393 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1394 APInt midpoint((nextSquare - square).udiv(two));
1395 APInt offset(*this - square);
1396 if (offset.ult(midpoint))
1397 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001398 return x_old + 1;
1399}
1400
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001401/// Computes the multiplicative inverse of this APInt for a given modulo. The
1402/// iterative extended Euclidean algorithm is used to solve for this value,
1403/// however we simplify it to speed up calculating only the inverse, and take
1404/// advantage of div+rem calculations. We also use some tricks to avoid copying
1405/// (potentially large) APInts around.
1406APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1407 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1408
1409 // Using the properties listed at the following web page (accessed 06/21/08):
1410 // http://www.numbertheory.org/php/euclid.html
1411 // (especially the properties numbered 3, 4 and 9) it can be proved that
1412 // BitWidth bits suffice for all the computations in the algorithm implemented
1413 // below. More precisely, this number of bits suffice if the multiplicative
1414 // inverse exists, but may not suffice for the general extended Euclidean
1415 // algorithm.
1416
1417 APInt r[2] = { modulo, *this };
1418 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1419 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001420
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001421 unsigned i;
1422 for (i = 0; r[i^1] != 0; i ^= 1) {
1423 // An overview of the math without the confusing bit-flipping:
1424 // q = r[i-2] / r[i-1]
1425 // r[i] = r[i-2] % r[i-1]
1426 // t[i] = t[i-2] - t[i-1] * q
1427 udivrem(r[i], r[i^1], q, r[i]);
1428 t[i] -= t[i^1] * q;
1429 }
1430
1431 // If this APInt and the modulo are not coprime, there is no multiplicative
1432 // inverse, so return 0. We check this by looking at the next-to-last
1433 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1434 // algorithm.
1435 if (r[i] != 1)
1436 return APInt(BitWidth, 0);
1437
1438 // The next-to-last t is the multiplicative inverse. However, we are
1439 // interested in a positive inverse. Calcuate a positive one from a negative
1440 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001441 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001442 return t[i].isNegative() ? t[i] + modulo : t[i];
1443}
1444
Jay Foadfe0c6482009-04-30 10:15:35 +00001445/// Calculate the magic numbers required to implement a signed integer division
1446/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1447/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1448/// Warren, Jr., chapter 10.
1449APInt::ms APInt::magic() const {
1450 const APInt& d = *this;
1451 unsigned p;
1452 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001453 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001454 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001455
Jay Foadfe0c6482009-04-30 10:15:35 +00001456 ad = d.abs();
1457 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1458 anc = t - 1 - t.urem(ad); // absolute value of nc
1459 p = d.getBitWidth() - 1; // initialize p
1460 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1461 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1462 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1463 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1464 do {
1465 p = p + 1;
1466 q1 = q1<<1; // update q1 = 2p/abs(nc)
1467 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1468 if (r1.uge(anc)) { // must be unsigned comparison
1469 q1 = q1 + 1;
1470 r1 = r1 - anc;
1471 }
1472 q2 = q2<<1; // update q2 = 2p/abs(d)
1473 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1474 if (r2.uge(ad)) { // must be unsigned comparison
1475 q2 = q2 + 1;
1476 r2 = r2 - ad;
1477 }
1478 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001479 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001480
Jay Foadfe0c6482009-04-30 10:15:35 +00001481 mag.m = q2 + 1;
1482 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1483 mag.s = p - d.getBitWidth(); // resulting shift
1484 return mag;
1485}
1486
1487/// Calculate the magic numbers required to implement an unsigned integer
1488/// division by a constant as a sequence of multiplies, adds and shifts.
1489/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1490/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001491/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001492/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001493APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001494 const APInt& d = *this;
1495 unsigned p;
1496 APInt nc, delta, q1, r1, q2, r2;
1497 struct mu magu;
1498 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001499 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001500 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1501 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1502
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001503 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001504 p = d.getBitWidth() - 1; // initialize p
1505 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1506 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1507 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1508 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1509 do {
1510 p = p + 1;
1511 if (r1.uge(nc - r1)) {
1512 q1 = q1 + q1 + 1; // update q1
1513 r1 = r1 + r1 - nc; // update r1
1514 }
1515 else {
1516 q1 = q1+q1; // update q1
1517 r1 = r1+r1; // update r1
1518 }
1519 if ((r2 + 1).uge(d - r2)) {
1520 if (q2.uge(signedMax)) magu.a = 1;
1521 q2 = q2+q2 + 1; // update q2
1522 r2 = r2+r2 + 1 - d; // update r2
1523 }
1524 else {
1525 if (q2.uge(signedMin)) magu.a = 1;
1526 q2 = q2+q2; // update q2
1527 r2 = r2+r2 + 1; // update r2
1528 }
1529 delta = d - 1 - r2;
1530 } while (p < d.getBitWidth()*2 &&
1531 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1532 magu.m = q2 + 1; // resulting magic number
1533 magu.s = p - d.getBitWidth(); // resulting shift
1534 return magu;
1535}
1536
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001537/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1538/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1539/// variables here have the same names as in the algorithm. Comments explain
1540/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001541static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1542 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001543 assert(u && "Must provide dividend");
1544 assert(v && "Must provide divisor");
1545 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001546 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001547 assert(n>1 && "n must be > 1");
1548
Yaron Keren39fc5a62015-03-26 19:45:19 +00001549 // b denotes the base of the number system. In our case b is 2^32.
George Burgess IV381fc0e2016-08-25 01:05:08 +00001550 const uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001551
David Greenef32fcb42010-01-05 01:28:52 +00001552 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1553 DEBUG(dbgs() << "KnuthDiv: original:");
1554 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1555 DEBUG(dbgs() << " by");
1556 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1557 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001558 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1559 // u and v by d. Note that we have taken Knuth's advice here to use a power
1560 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1561 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001562 // shift amount from the leading zeros. We are basically normalizing the u
1563 // and v so that its high bits are shifted to the top of v's range without
1564 // overflow. Note that this can require an extra word in u so that u must
1565 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001566 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001567 unsigned v_carry = 0;
1568 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001569 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001570 for (unsigned i = 0; i < m+n; ++i) {
1571 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001572 u[i] = (u[i] << shift) | u_carry;
1573 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001574 }
Chris Lattner77527f52009-01-21 18:09:24 +00001575 for (unsigned i = 0; i < n; ++i) {
1576 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001577 v[i] = (v[i] << shift) | v_carry;
1578 v_carry = v_tmp;
1579 }
1580 }
1581 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001582
David Greenef32fcb42010-01-05 01:28:52 +00001583 DEBUG(dbgs() << "KnuthDiv: normal:");
1584 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1585 DEBUG(dbgs() << " by");
1586 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1587 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001588
1589 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1590 int j = m;
1591 do {
David Greenef32fcb42010-01-05 01:28:52 +00001592 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001593 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001594 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1595 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1596 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1597 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1598 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001599 // value qp is one too large, and it eliminates all cases where qp is two
1600 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001601 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001602 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001603 uint64_t qp = dividend / v[n-1];
1604 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001605 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1606 qp--;
1607 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001608 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001609 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001610 }
David Greenef32fcb42010-01-05 01:28:52 +00001611 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001612
Reid Spencercb292e42007-02-23 01:57:13 +00001613 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1614 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1615 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001616 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001617 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1618 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1619 // true value plus b**(n+1), namely as the b's complement of
1620 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001621 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001622 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001623 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1624 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1625 u[j+i] = (unsigned)subres;
1626 borrow = (p >> 32) - (subres >> 32);
1627 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001628 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001629 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001630 bool isNeg = u[j+n] < borrow;
1631 u[j+n] -= (unsigned)borrow;
1632
David Greenef32fcb42010-01-05 01:28:52 +00001633 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1634 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1635 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001636
Eric Christopher820256b2009-08-21 04:06:45 +00001637 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001638 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001639 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001640 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001641 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001642 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001643 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001644 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001645 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1646 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001647 // since it cancels with the borrow that occurred in D4.
1648 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001649 for (unsigned i = 0; i < n; i++) {
1650 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001651 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001652 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001653 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001654 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001655 }
David Greenef32fcb42010-01-05 01:28:52 +00001656 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001657 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001658 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001659
Reid Spencercb292e42007-02-23 01:57:13 +00001660 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1661 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001662
David Greenef32fcb42010-01-05 01:28:52 +00001663 DEBUG(dbgs() << "KnuthDiv: quotient:");
1664 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1665 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001666
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001667 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1668 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1669 // compute the remainder (urem uses this).
1670 if (r) {
1671 // The value d is expressed by the "shift" value above since we avoided
1672 // multiplication by d by using a shift left. So, all we have to do is
Simon Pilgrim0099beb2017-03-09 13:57:04 +00001673 // shift right here.
Reid Spencer468ad9112007-02-24 20:38:01 +00001674 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001675 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001676 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001677 for (int i = n-1; i >= 0; i--) {
1678 r[i] = (u[i] >> shift) | carry;
1679 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001680 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001681 }
1682 } else {
1683 for (int i = n-1; i >= 0; i--) {
1684 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001685 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001686 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001687 }
David Greenef32fcb42010-01-05 01:28:52 +00001688 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001689 }
David Greenef32fcb42010-01-05 01:28:52 +00001690 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001691}
1692
Benjamin Kramerc321e532016-06-08 19:09:22 +00001693void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
1694 unsigned rhsWords, APInt *Quotient, APInt *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001695 assert(lhsWords >= rhsWords && "Fractional result");
1696
Eric Christopher820256b2009-08-21 04:06:45 +00001697 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001698 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001699 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001700 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1701 // can't use 64-bit operands here because we don't have native results of
1702 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001703 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001704 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001705 unsigned n = rhsWords * 2;
1706 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001707
1708 // Allocate space for the temporary values we need either on the stack, if
1709 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001710 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001711 unsigned *U = nullptr;
1712 unsigned *V = nullptr;
1713 unsigned *Q = nullptr;
1714 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001715 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1716 U = &SPACE[0];
1717 V = &SPACE[m+n+1];
1718 Q = &SPACE[(m+n+1) + n];
1719 if (Remainder)
1720 R = &SPACE[(m+n+1) + n + (m+n)];
1721 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001722 U = new unsigned[m + n + 1];
1723 V = new unsigned[n];
1724 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001725 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001726 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001727 }
1728
1729 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001730 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001731 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001732 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001733 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001734 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001735 }
1736 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1737
Reid Spencer522ca7c2007-02-25 01:56:07 +00001738 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001739 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001740 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001741 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001742 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001743 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001744 }
1745
Reid Spencer522ca7c2007-02-25 01:56:07 +00001746 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001747 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001748 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001749 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001750
Eric Christopher820256b2009-08-21 04:06:45 +00001751 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001752 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001753 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001754 // contain any zero words or the Knuth algorithm fails.
1755 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1756 n--;
1757 m++;
1758 }
1759 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1760 m--;
1761
1762 // If we're left with only a single word for the divisor, Knuth doesn't work
1763 // so we implement the short division algorithm here. This is much simpler
1764 // and faster because we are certain that we can divide a 64-bit quantity
1765 // by a 32-bit quantity at hardware speed and short division is simply a
1766 // series of such operations. This is just like doing short division but we
1767 // are using base 2^32 instead of base 10.
1768 assert(n != 0 && "Divide by zero?");
1769 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001770 unsigned divisor = V[0];
1771 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001772 for (int i = m+n-1; i >= 0; i--) {
1773 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1774 if (partial_dividend == 0) {
1775 Q[i] = 0;
1776 remainder = 0;
1777 } else if (partial_dividend < divisor) {
1778 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001779 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001780 } else if (partial_dividend == divisor) {
1781 Q[i] = 1;
1782 remainder = 0;
1783 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001784 Q[i] = (unsigned)(partial_dividend / divisor);
1785 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001786 }
1787 }
1788 if (R)
1789 R[0] = remainder;
1790 } else {
1791 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1792 // case n > 1.
1793 KnuthDiv(U, V, Q, R, m, n);
1794 }
1795
1796 // If the caller wants the quotient
1797 if (Quotient) {
1798 // Set up the Quotient value's memory.
1799 if (Quotient->BitWidth != LHS.BitWidth) {
1800 if (Quotient->isSingleWord())
1801 Quotient->VAL = 0;
1802 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001803 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001804 Quotient->BitWidth = LHS.BitWidth;
1805 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001806 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001807 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001808 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001809
Eric Christopher820256b2009-08-21 04:06:45 +00001810 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001811 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001812 // This case is currently dead as all users of divide() handle trivial cases
1813 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001814 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001815 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001816 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1817 if (Quotient->isSingleWord())
1818 Quotient->VAL = tmp;
1819 else
1820 Quotient->pVal[0] = tmp;
1821 } else {
1822 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1823 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001824 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001825 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1826 }
1827 }
1828
1829 // If the caller wants the remainder
1830 if (Remainder) {
1831 // Set up the Remainder value's memory.
1832 if (Remainder->BitWidth != RHS.BitWidth) {
1833 if (Remainder->isSingleWord())
1834 Remainder->VAL = 0;
1835 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001836 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001837 Remainder->BitWidth = RHS.BitWidth;
1838 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001839 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001840 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001841 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001842
1843 // The remainder is in R. Reconstitute the remainder into Remainder's low
1844 // order words.
1845 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001846 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001847 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1848 if (Remainder->isSingleWord())
1849 Remainder->VAL = tmp;
1850 else
1851 Remainder->pVal[0] = tmp;
1852 } else {
1853 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1854 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001855 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001856 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1857 }
1858 }
1859
1860 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001861 if (U != &SPACE[0]) {
1862 delete [] U;
1863 delete [] V;
1864 delete [] Q;
1865 delete [] R;
1866 }
Reid Spencer100502d2007-02-17 03:16:00 +00001867}
1868
Reid Spencer1d072122007-02-16 22:36:51 +00001869APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001870 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001871
1872 // First, deal with the easy case
1873 if (isSingleWord()) {
1874 assert(RHS.VAL != 0 && "Divide by zero?");
1875 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001876 }
Reid Spencer39867762007-02-17 02:07:07 +00001877
Reid Spencer39867762007-02-17 02:07:07 +00001878 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001879 unsigned rhsBits = RHS.getActiveBits();
1880 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001881 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001882 unsigned lhsBits = this->getActiveBits();
1883 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001884
1885 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001886 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001887 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001888 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001889 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001890 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001891 return APInt(BitWidth, 0);
1892 } else if (*this == RHS) {
1893 // X / X ===> 1
1894 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001895 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001896 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001897 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001898 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001899
1900 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1901 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001902 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001903 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001904}
1905
Jakub Staszak6605c602013-02-20 00:17:42 +00001906APInt APInt::sdiv(const APInt &RHS) const {
1907 if (isNegative()) {
1908 if (RHS.isNegative())
1909 return (-(*this)).udiv(-RHS);
1910 return -((-(*this)).udiv(RHS));
1911 }
1912 if (RHS.isNegative())
1913 return -(this->udiv(-RHS));
1914 return this->udiv(RHS);
1915}
1916
Reid Spencer1d072122007-02-16 22:36:51 +00001917APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001918 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001919 if (isSingleWord()) {
1920 assert(RHS.VAL != 0 && "Remainder by zero?");
1921 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001922 }
Reid Spencer39867762007-02-17 02:07:07 +00001923
Reid Spencer58a6a432007-02-21 08:21:52 +00001924 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001925 unsigned lhsBits = getActiveBits();
1926 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001927
1928 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001929 unsigned rhsBits = RHS.getActiveBits();
1930 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001931 assert(rhsWords && "Performing remainder operation by zero ???");
1932
Reid Spencer39867762007-02-17 02:07:07 +00001933 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001934 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001935 // 0 % Y ===> 0
1936 return APInt(BitWidth, 0);
1937 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001938 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001939 return *this;
1940 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001941 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001942 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001943 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001944 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00001945 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001946 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001947
Reid Spencer4c50b522007-05-13 23:44:59 +00001948 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001949 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001950 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001951 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001952}
Reid Spencer100502d2007-02-17 03:16:00 +00001953
Jakub Staszak6605c602013-02-20 00:17:42 +00001954APInt APInt::srem(const APInt &RHS) const {
1955 if (isNegative()) {
1956 if (RHS.isNegative())
1957 return -((-(*this)).urem(-RHS));
1958 return -((-(*this)).urem(RHS));
1959 }
1960 if (RHS.isNegative())
1961 return this->urem(-RHS);
1962 return this->urem(RHS);
1963}
1964
Eric Christopher820256b2009-08-21 04:06:45 +00001965void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001966 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001967 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1968
1969 // First, deal with the easy case
1970 if (LHS.isSingleWord()) {
1971 assert(RHS.VAL != 0 && "Divide by zero?");
1972 uint64_t QuotVal = LHS.VAL / RHS.VAL;
1973 uint64_t RemVal = LHS.VAL % RHS.VAL;
1974 Quotient = APInt(LHS.BitWidth, QuotVal);
1975 Remainder = APInt(LHS.BitWidth, RemVal);
1976 return;
1977 }
1978
Reid Spencer4c50b522007-05-13 23:44:59 +00001979 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001980 unsigned lhsBits = LHS.getActiveBits();
1981 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1982 unsigned rhsBits = RHS.getActiveBits();
1983 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00001984
1985 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001986 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00001987 Quotient = 0; // 0 / Y ===> 0
1988 Remainder = 0; // 0 % Y ===> 0
1989 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001990 }
1991
1992 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001993 Remainder = LHS; // X % Y ===> X, iff X < Y
1994 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00001995 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001996 }
1997
Reid Spencer4c50b522007-05-13 23:44:59 +00001998 if (LHS == RHS) {
1999 Quotient = 1; // X / X ===> 1
2000 Remainder = 0; // X % X ===> 0;
2001 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002002 }
2003
Reid Spencer4c50b522007-05-13 23:44:59 +00002004 if (lhsWords == 1 && rhsWords == 1) {
2005 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00002006 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
2007 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
2008 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
2009 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00002010 return;
2011 }
2012
2013 // Okay, lets do it the long way
2014 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
2015}
2016
Jakub Staszak6605c602013-02-20 00:17:42 +00002017void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
2018 APInt &Quotient, APInt &Remainder) {
2019 if (LHS.isNegative()) {
2020 if (RHS.isNegative())
2021 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
2022 else {
2023 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
2024 Quotient = -Quotient;
2025 }
2026 Remainder = -Remainder;
2027 } else if (RHS.isNegative()) {
2028 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
2029 Quotient = -Quotient;
2030 } else {
2031 APInt::udivrem(LHS, RHS, Quotient, Remainder);
2032 }
2033}
2034
Chris Lattner2c819b02010-10-13 23:54:10 +00002035APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002036 APInt Res = *this+RHS;
2037 Overflow = isNonNegative() == RHS.isNonNegative() &&
2038 Res.isNonNegative() != isNonNegative();
2039 return Res;
2040}
2041
Chris Lattner698661c2010-10-14 00:05:07 +00002042APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
2043 APInt Res = *this+RHS;
2044 Overflow = Res.ult(RHS);
2045 return Res;
2046}
2047
Chris Lattner2c819b02010-10-13 23:54:10 +00002048APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002049 APInt Res = *this - RHS;
2050 Overflow = isNonNegative() != RHS.isNonNegative() &&
2051 Res.isNonNegative() != isNonNegative();
2052 return Res;
2053}
2054
Chris Lattner698661c2010-10-14 00:05:07 +00002055APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00002056 APInt Res = *this-RHS;
2057 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00002058 return Res;
2059}
2060
Chris Lattner2c819b02010-10-13 23:54:10 +00002061APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002062 // MININT/-1 --> overflow.
2063 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
2064 return sdiv(RHS);
2065}
2066
Chris Lattner2c819b02010-10-13 23:54:10 +00002067APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002068 APInt Res = *this * RHS;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002069
Chris Lattner79bdd882010-10-13 23:46:33 +00002070 if (*this != 0 && RHS != 0)
2071 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
2072 else
2073 Overflow = false;
2074 return Res;
2075}
2076
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00002077APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
2078 APInt Res = *this * RHS;
2079
2080 if (*this != 0 && RHS != 0)
2081 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
2082 else
2083 Overflow = false;
2084 return Res;
2085}
2086
David Majnemera2521382014-10-13 21:48:30 +00002087APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
2088 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00002089 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00002090 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00002091
2092 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00002093 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00002094 else
David Majnemera2521382014-10-13 21:48:30 +00002095 Overflow = ShAmt.uge(countLeadingOnes());
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002096
Chris Lattner79bdd882010-10-13 23:46:33 +00002097 return *this << ShAmt;
2098}
2099
David Majnemera2521382014-10-13 21:48:30 +00002100APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
2101 Overflow = ShAmt.uge(getBitWidth());
2102 if (Overflow)
2103 return APInt(BitWidth, 0);
2104
2105 Overflow = ShAmt.ugt(countLeadingZeros());
2106
2107 return *this << ShAmt;
2108}
2109
Chris Lattner79bdd882010-10-13 23:46:33 +00002110
2111
2112
Benjamin Kramer92d89982010-07-14 22:38:02 +00002113void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00002114 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002115 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002116 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002117 radix == 36) &&
2118 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002119
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002120 StringRef::iterator p = str.begin();
2121 size_t slen = str.size();
2122 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002123 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002124 p++;
2125 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00002126 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002127 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00002128 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002129 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2130 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002131 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2132 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00002133
2134 // Allocate memory
2135 if (!isSingleWord())
2136 pVal = getClearedMemory(getNumWords());
2137
2138 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00002139 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00002140
Craig Topperb7d8faa2017-04-02 06:59:38 +00002141 // Set up an APInt for the radix multiplier outside the loop so we don't
Reid Spencer1ba83352007-02-21 03:55:44 +00002142 // constantly construct/destruct it.
Reid Spencer1ba83352007-02-21 03:55:44 +00002143 APInt apradix(getBitWidth(), radix);
2144
2145 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002146 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00002147 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00002148 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00002149
Reid Spencera93c9812007-05-16 19:18:22 +00002150 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002151 if (slen > 1) {
2152 if (shift)
2153 *this <<= shift;
2154 else
2155 *this *= apradix;
2156 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002157
2158 // Add in the digit we just interpreted
Craig Topperb7d8faa2017-04-02 06:59:38 +00002159 *this += digit;
Reid Spencer100502d2007-02-17 03:16:00 +00002160 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002161 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00002162 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00002163 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002164 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002165 }
Reid Spencer100502d2007-02-17 03:16:00 +00002166}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002167
Chris Lattner17f71652008-08-17 07:19:36 +00002168void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002169 bool Signed, bool formatAsCLiteral) const {
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002170 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002171 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002172 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002173
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002174 const char *Prefix = "";
2175 if (formatAsCLiteral) {
2176 switch (Radix) {
2177 case 2:
2178 // Binary literals are a non-standard extension added in gcc 4.3:
2179 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2180 Prefix = "0b";
2181 break;
2182 case 8:
2183 Prefix = "0";
2184 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002185 case 10:
2186 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002187 case 16:
2188 Prefix = "0x";
2189 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002190 default:
2191 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002192 }
2193 }
2194
Chris Lattner17f71652008-08-17 07:19:36 +00002195 // First, check for a zero value and just short circuit the logic below.
2196 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002197 while (*Prefix) {
2198 Str.push_back(*Prefix);
2199 ++Prefix;
2200 };
Chris Lattner17f71652008-08-17 07:19:36 +00002201 Str.push_back('0');
2202 return;
2203 }
Eric Christopher820256b2009-08-21 04:06:45 +00002204
Douglas Gregor663c0682011-09-14 15:54:46 +00002205 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002206
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002207 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002208 char Buffer[65];
2209 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002210
Chris Lattner17f71652008-08-17 07:19:36 +00002211 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002212 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002213 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002214 } else {
2215 int64_t I = getSExtValue();
2216 if (I >= 0) {
2217 N = I;
2218 } else {
2219 Str.push_back('-');
2220 N = -(uint64_t)I;
2221 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002222 }
Eric Christopher820256b2009-08-21 04:06:45 +00002223
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002224 while (*Prefix) {
2225 Str.push_back(*Prefix);
2226 ++Prefix;
2227 };
2228
Chris Lattner17f71652008-08-17 07:19:36 +00002229 while (N) {
2230 *--BufPtr = Digits[N % Radix];
2231 N /= Radix;
2232 }
2233 Str.append(BufPtr, Buffer+65);
2234 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002235 }
2236
Chris Lattner17f71652008-08-17 07:19:36 +00002237 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002238
Chris Lattner17f71652008-08-17 07:19:36 +00002239 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002240 // They want to print the signed version and it is a negative value
2241 // Flip the bits and add one to turn it into the equivalent positive
2242 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002243 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002244 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002245 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002246 }
Eric Christopher820256b2009-08-21 04:06:45 +00002247
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002248 while (*Prefix) {
2249 Str.push_back(*Prefix);
2250 ++Prefix;
2251 };
2252
Chris Lattner17f71652008-08-17 07:19:36 +00002253 // We insert the digits backward, then reverse them to get the right order.
2254 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002255
2256 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2257 // because the number of bits per digit (1, 3 and 4 respectively) divides
Craig Topperd7ed50d2017-04-02 06:59:36 +00002258 // equally. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002259 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002260 // Just shift tmp right for each digit width until it becomes zero
2261 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2262 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002263
Chris Lattner17f71652008-08-17 07:19:36 +00002264 while (Tmp != 0) {
2265 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2266 Str.push_back(Digits[Digit]);
2267 Tmp = Tmp.lshr(ShiftAmt);
2268 }
2269 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002270 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002271 while (Tmp != 0) {
2272 APInt APdigit(1, 0);
2273 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002274 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002275 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002276 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002277 assert(Digit < Radix && "divide failed");
2278 Str.push_back(Digits[Digit]);
2279 Tmp = tmp2;
2280 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002281 }
Eric Christopher820256b2009-08-21 04:06:45 +00002282
Chris Lattner17f71652008-08-17 07:19:36 +00002283 // Reverse the digits before returning.
2284 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002285}
2286
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002287/// Returns the APInt as a std::string. Note that this is an inefficient method.
2288/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002289std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2290 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002291 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002292 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002293}
Chris Lattner6b695682007-08-16 15:56:55 +00002294
Matthias Braun8c209aa2017-01-28 02:02:38 +00002295#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002296LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002297 SmallString<40> S, U;
2298 this->toStringUnsigned(U);
2299 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002300 dbgs() << "APInt(" << BitWidth << "b, "
Davide Italiano5a473d22017-01-31 21:26:18 +00002301 << U << "u " << S << "s)\n";
Chris Lattner17f71652008-08-17 07:19:36 +00002302}
Matthias Braun8c209aa2017-01-28 02:02:38 +00002303#endif
Chris Lattner17f71652008-08-17 07:19:36 +00002304
Chris Lattner0c19df42008-08-23 22:23:09 +00002305void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002306 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002307 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002308 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002309}
2310
Chris Lattner6b695682007-08-16 15:56:55 +00002311// This implements a variety of operations on a representation of
2312// arbitrary precision, two's-complement, bignum integer values.
2313
Chris Lattner96cffa62009-08-23 23:11:28 +00002314// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2315// and unrestricting assumption.
Craig Topper55229b72017-04-02 19:17:22 +00002316static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
2317 "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002318
2319/* Some handy functions local to this file. */
Chris Lattner6b695682007-08-16 15:56:55 +00002320
Craig Topper76f42462017-03-28 05:32:53 +00002321/* Returns the integer part with the least significant BITS set.
2322 BITS cannot be zero. */
Craig Topper55229b72017-04-02 19:17:22 +00002323static inline APInt::WordType lowBitMask(unsigned bits) {
2324 assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002325
Craig Topper55229b72017-04-02 19:17:22 +00002326 return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
Craig Topper76f42462017-03-28 05:32:53 +00002327}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002328
Craig Topper76f42462017-03-28 05:32:53 +00002329/* Returns the value of the lower half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002330static inline APInt::WordType lowHalf(APInt::WordType part) {
2331 return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002332}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002333
Craig Topper76f42462017-03-28 05:32:53 +00002334/* Returns the value of the upper half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002335static inline APInt::WordType highHalf(APInt::WordType part) {
2336 return part >> (APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002337}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002338
Craig Topper76f42462017-03-28 05:32:53 +00002339/* Returns the bit number of the most significant set bit of a part.
2340 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002341static unsigned partMSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002342 return findLastSet(value, ZB_Max);
2343}
Chris Lattner6b695682007-08-16 15:56:55 +00002344
Craig Topper76f42462017-03-28 05:32:53 +00002345/* Returns the bit number of the least significant set bit of a
2346 part. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002347static unsigned partLSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002348 return findFirstSet(value, ZB_Max);
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002349}
Chris Lattner6b695682007-08-16 15:56:55 +00002350
2351/* Sets the least significant part of a bignum to the input value, and
2352 zeroes out higher parts. */
Craig Topper55229b72017-04-02 19:17:22 +00002353void APInt::tcSet(WordType *dst, WordType part, unsigned parts) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002354 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002355
Chris Lattner6b695682007-08-16 15:56:55 +00002356 dst[0] = part;
Craig Topperb0038162017-03-28 05:32:52 +00002357 for (unsigned i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002358 dst[i] = 0;
2359}
2360
2361/* Assign one bignum to another. */
Craig Topper55229b72017-04-02 19:17:22 +00002362void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002363 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002364 dst[i] = src[i];
2365}
2366
2367/* Returns true if a bignum is zero, false otherwise. */
Craig Topper55229b72017-04-02 19:17:22 +00002368bool APInt::tcIsZero(const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002369 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002370 if (src[i])
2371 return false;
2372
2373 return true;
2374}
2375
2376/* Extract the given bit of a bignum; returns 0 or 1. */
Craig Topper55229b72017-04-02 19:17:22 +00002377int APInt::tcExtractBit(const WordType *parts, unsigned bit) {
2378 return (parts[bit / APINT_BITS_PER_WORD] &
2379 ((WordType) 1 << bit % APINT_BITS_PER_WORD)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002380}
2381
John McCalldcb9a7a2010-02-28 02:51:25 +00002382/* Set the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002383void APInt::tcSetBit(WordType *parts, unsigned bit) {
2384 parts[bit / APINT_BITS_PER_WORD] |= (WordType) 1 << (bit % APINT_BITS_PER_WORD);
Chris Lattner6b695682007-08-16 15:56:55 +00002385}
2386
John McCalldcb9a7a2010-02-28 02:51:25 +00002387/* Clears the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002388void APInt::tcClearBit(WordType *parts, unsigned bit) {
2389 parts[bit / APINT_BITS_PER_WORD] &=
2390 ~((WordType) 1 << (bit % APINT_BITS_PER_WORD));
John McCalldcb9a7a2010-02-28 02:51:25 +00002391}
2392
Neil Boothc8b650a2007-10-06 00:43:45 +00002393/* Returns the bit number of the least significant set bit of a
2394 number. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002395unsigned APInt::tcLSB(const WordType *parts, unsigned n) {
Craig Topperb0038162017-03-28 05:32:52 +00002396 for (unsigned i = 0; i < n; i++) {
2397 if (parts[i] != 0) {
2398 unsigned lsb = partLSB(parts[i]);
Chris Lattner6b695682007-08-16 15:56:55 +00002399
Craig Topper55229b72017-04-02 19:17:22 +00002400 return lsb + i * APINT_BITS_PER_WORD;
Craig Topperb0038162017-03-28 05:32:52 +00002401 }
Chris Lattner6b695682007-08-16 15:56:55 +00002402 }
2403
2404 return -1U;
2405}
2406
Neil Boothc8b650a2007-10-06 00:43:45 +00002407/* Returns the bit number of the most significant set bit of a number.
2408 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002409unsigned APInt::tcMSB(const WordType *parts, unsigned n) {
Chris Lattner6b695682007-08-16 15:56:55 +00002410 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002411 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002412
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002413 if (parts[n] != 0) {
Craig Topperb0038162017-03-28 05:32:52 +00002414 unsigned msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002415
Craig Topper55229b72017-04-02 19:17:22 +00002416 return msb + n * APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002417 }
Chris Lattner6b695682007-08-16 15:56:55 +00002418 } while (n);
2419
2420 return -1U;
2421}
2422
Neil Boothb6182162007-10-08 13:47:12 +00002423/* Copy the bit vector of width srcBITS from SRC, starting at bit
2424 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2425 the least significant bit of DST. All high bits above srcBITS in
2426 DST are zero-filled. */
2427void
Craig Topper55229b72017-04-02 19:17:22 +00002428APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src,
Craig Topper6a8518082017-03-28 05:32:55 +00002429 unsigned srcBits, unsigned srcLSB) {
Craig Topper55229b72017-04-02 19:17:22 +00002430 unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002431 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002432
Craig Topper55229b72017-04-02 19:17:22 +00002433 unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002434 tcAssign (dst, src + firstSrcPart, dstParts);
2435
Craig Topper55229b72017-04-02 19:17:22 +00002436 unsigned shift = srcLSB % APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002437 tcShiftRight (dst, dstParts, shift);
2438
Craig Topper55229b72017-04-02 19:17:22 +00002439 /* We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC
Neil Boothb6182162007-10-08 13:47:12 +00002440 in DST. If this is less that srcBits, append the rest, else
2441 clear the high bits. */
Craig Topper55229b72017-04-02 19:17:22 +00002442 unsigned n = dstParts * APINT_BITS_PER_WORD - shift;
Neil Boothb6182162007-10-08 13:47:12 +00002443 if (n < srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002444 WordType mask = lowBitMask (srcBits - n);
Neil Boothb6182162007-10-08 13:47:12 +00002445 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
Craig Topper55229b72017-04-02 19:17:22 +00002446 << n % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002447 } else if (n > srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002448 if (srcBits % APINT_BITS_PER_WORD)
2449 dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002450 }
2451
2452 /* Clear high parts. */
2453 while (dstParts < dstCount)
2454 dst[dstParts++] = 0;
2455}
2456
Chris Lattner6b695682007-08-16 15:56:55 +00002457/* DST += RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002458APInt::WordType APInt::tcAdd(WordType *dst, const WordType *rhs,
2459 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002460 assert(c <= 1);
2461
Craig Topperb0038162017-03-28 05:32:52 +00002462 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002463 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002464 if (c) {
2465 dst[i] += rhs[i] + 1;
2466 c = (dst[i] <= l);
2467 } else {
2468 dst[i] += rhs[i];
2469 c = (dst[i] < l);
2470 }
2471 }
2472
2473 return c;
2474}
2475
2476/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002477APInt::WordType APInt::tcSubtract(WordType *dst, const WordType *rhs,
2478 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002479 assert(c <= 1);
2480
Craig Topperb0038162017-03-28 05:32:52 +00002481 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002482 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002483 if (c) {
2484 dst[i] -= rhs[i] + 1;
2485 c = (dst[i] >= l);
2486 } else {
2487 dst[i] -= rhs[i];
2488 c = (dst[i] > l);
2489 }
2490 }
2491
2492 return c;
2493}
2494
2495/* Negate a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002496void APInt::tcNegate(WordType *dst, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002497 tcComplement(dst, parts);
2498 tcIncrement(dst, parts);
2499}
2500
Neil Boothc8b650a2007-10-06 00:43:45 +00002501/* DST += SRC * MULTIPLIER + CARRY if add is true
2502 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002503
2504 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2505 they must start at the same point, i.e. DST == SRC.
2506
2507 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2508 returned. Otherwise DST is filled with the least significant
2509 DSTPARTS parts of the result, and if all of the omitted higher
2510 parts were zero return zero, otherwise overflow occurred and
2511 return one. */
Craig Topper55229b72017-04-02 19:17:22 +00002512int APInt::tcMultiplyPart(WordType *dst, const WordType *src,
2513 WordType multiplier, WordType carry,
Craig Topper6a8518082017-03-28 05:32:55 +00002514 unsigned srcParts, unsigned dstParts,
2515 bool add) {
Chris Lattner6b695682007-08-16 15:56:55 +00002516 /* Otherwise our writes of DST kill our later reads of SRC. */
2517 assert(dst <= src || dst >= src + srcParts);
2518 assert(dstParts <= srcParts + 1);
2519
2520 /* N loops; minimum of dstParts and srcParts. */
Craig Topperb0038162017-03-28 05:32:52 +00002521 unsigned n = dstParts < srcParts ? dstParts: srcParts;
Chris Lattner6b695682007-08-16 15:56:55 +00002522
Craig Topperb0038162017-03-28 05:32:52 +00002523 unsigned i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002524 for (i = 0; i < n; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002525 WordType low, mid, high, srcPart;
Chris Lattner6b695682007-08-16 15:56:55 +00002526
2527 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2528
2529 This cannot overflow, because
2530
2531 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2532
2533 which is less than n^2. */
2534
2535 srcPart = src[i];
2536
Craig Topper6a8518082017-03-28 05:32:55 +00002537 if (multiplier == 0 || srcPart == 0) {
Chris Lattner6b695682007-08-16 15:56:55 +00002538 low = carry;
2539 high = 0;
2540 } else {
2541 low = lowHalf(srcPart) * lowHalf(multiplier);
2542 high = highHalf(srcPart) * highHalf(multiplier);
2543
2544 mid = lowHalf(srcPart) * highHalf(multiplier);
2545 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002546 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002547 if (low + mid < low)
2548 high++;
2549 low += mid;
2550
2551 mid = highHalf(srcPart) * lowHalf(multiplier);
2552 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002553 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002554 if (low + mid < low)
2555 high++;
2556 low += mid;
2557
2558 /* Now add carry. */
2559 if (low + carry < low)
2560 high++;
2561 low += carry;
2562 }
2563
2564 if (add) {
2565 /* And now DST[i], and store the new low part there. */
2566 if (low + dst[i] < low)
2567 high++;
2568 dst[i] += low;
2569 } else
2570 dst[i] = low;
2571
2572 carry = high;
2573 }
2574
2575 if (i < dstParts) {
2576 /* Full multiplication, there is no overflow. */
2577 assert(i + 1 == dstParts);
2578 dst[i] = carry;
2579 return 0;
2580 } else {
2581 /* We overflowed if there is carry. */
2582 if (carry)
2583 return 1;
2584
2585 /* We would overflow if any significant unwritten parts would be
2586 non-zero. This is true if any remaining src parts are non-zero
2587 and the multiplier is non-zero. */
2588 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002589 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002590 if (src[i])
2591 return 1;
2592
2593 /* We fitted in the narrow destination. */
2594 return 0;
2595 }
2596}
2597
2598/* DST = LHS * RHS, where DST has the same width as the operands and
2599 is filled with the least significant parts of the result. Returns
2600 one if overflow occurred, otherwise zero. DST must be disjoint
2601 from both operands. */
Craig Topper55229b72017-04-02 19:17:22 +00002602int APInt::tcMultiply(WordType *dst, const WordType *lhs,
2603 const WordType *rhs, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002604 assert(dst != lhs && dst != rhs);
2605
Craig Topperb0038162017-03-28 05:32:52 +00002606 int overflow = 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002607 tcSet(dst, 0, parts);
2608
Craig Topperb0038162017-03-28 05:32:52 +00002609 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002610 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2611 parts - i, true);
2612
2613 return overflow;
2614}
2615
Neil Booth0ea72a92007-10-06 00:24:48 +00002616/* DST = LHS * RHS, where DST has width the sum of the widths of the
2617 operands. No overflow occurs. DST must be disjoint from both
2618 operands. Returns the number of parts required to hold the
2619 result. */
Craig Topper55229b72017-04-02 19:17:22 +00002620unsigned APInt::tcFullMultiply(WordType *dst, const WordType *lhs,
2621 const WordType *rhs, unsigned lhsParts,
Craig Topper6a8518082017-03-28 05:32:55 +00002622 unsigned rhsParts) {
Neil Booth0ea72a92007-10-06 00:24:48 +00002623 /* Put the narrower number on the LHS for less loops below. */
2624 if (lhsParts > rhsParts) {
2625 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2626 } else {
Neil Booth0ea72a92007-10-06 00:24:48 +00002627 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002628
Neil Booth0ea72a92007-10-06 00:24:48 +00002629 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002630
Craig Topperb0038162017-03-28 05:32:52 +00002631 for (unsigned i = 0; i < lhsParts; i++)
2632 tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002633
Craig Topperb0038162017-03-28 05:32:52 +00002634 unsigned n = lhsParts + rhsParts;
Neil Booth0ea72a92007-10-06 00:24:48 +00002635
2636 return n - (dst[n - 1] == 0);
2637 }
Chris Lattner6b695682007-08-16 15:56:55 +00002638}
2639
2640/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2641 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2642 set REMAINDER to the remainder, return zero. i.e.
2643
2644 OLD_LHS = RHS * LHS + REMAINDER
2645
2646 SCRATCH is a bignum of the same size as the operands and result for
2647 use by the routine; its contents need not be initialized and are
2648 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2649*/
Craig Topper55229b72017-04-02 19:17:22 +00002650int APInt::tcDivide(WordType *lhs, const WordType *rhs,
2651 WordType *remainder, WordType *srhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002652 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002653 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2654
Craig Topperb0038162017-03-28 05:32:52 +00002655 unsigned shiftCount = tcMSB(rhs, parts) + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002656 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002657 return true;
2658
Craig Topper55229b72017-04-02 19:17:22 +00002659 shiftCount = parts * APINT_BITS_PER_WORD - shiftCount;
2660 unsigned n = shiftCount / APINT_BITS_PER_WORD;
2661 WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD);
Chris Lattner6b695682007-08-16 15:56:55 +00002662
2663 tcAssign(srhs, rhs, parts);
2664 tcShiftLeft(srhs, parts, shiftCount);
2665 tcAssign(remainder, lhs, parts);
2666 tcSet(lhs, 0, parts);
2667
2668 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2669 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002670 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002671 int compare;
2672
2673 compare = tcCompare(remainder, srhs, parts);
2674 if (compare >= 0) {
2675 tcSubtract(remainder, srhs, 0, parts);
2676 lhs[n] |= mask;
2677 }
2678
2679 if (shiftCount == 0)
2680 break;
2681 shiftCount--;
2682 tcShiftRight(srhs, parts, 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002683 if ((mask >>= 1) == 0) {
Craig Topper55229b72017-04-02 19:17:22 +00002684 mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002685 n--;
2686 }
Chris Lattner6b695682007-08-16 15:56:55 +00002687 }
2688
2689 return false;
2690}
2691
2692/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2693 There are no restrictions on COUNT. */
Craig Topper55229b72017-04-02 19:17:22 +00002694void APInt::tcShiftLeft(WordType *dst, unsigned parts, unsigned count) {
Neil Boothb6182162007-10-08 13:47:12 +00002695 if (count) {
Neil Boothb6182162007-10-08 13:47:12 +00002696 /* Jump is the inter-part jump; shift is is intra-part shift. */
Craig Topper55229b72017-04-02 19:17:22 +00002697 unsigned jump = count / APINT_BITS_PER_WORD;
2698 unsigned shift = count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002699
Neil Boothb6182162007-10-08 13:47:12 +00002700 while (parts > jump) {
Craig Topper55229b72017-04-02 19:17:22 +00002701 WordType part;
Chris Lattner6b695682007-08-16 15:56:55 +00002702
Neil Boothb6182162007-10-08 13:47:12 +00002703 parts--;
Chris Lattner6b695682007-08-16 15:56:55 +00002704
Neil Boothb6182162007-10-08 13:47:12 +00002705 /* dst[i] comes from the two parts src[i - jump] and, if we have
2706 an intra-part shift, src[i - jump - 1]. */
2707 part = dst[parts - jump];
2708 if (shift) {
2709 part <<= shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002710 if (parts >= jump + 1)
Craig Topper55229b72017-04-02 19:17:22 +00002711 part |= dst[parts - jump - 1] >> (APINT_BITS_PER_WORD - shift);
Chris Lattner6b695682007-08-16 15:56:55 +00002712 }
2713
Neil Boothb6182162007-10-08 13:47:12 +00002714 dst[parts] = part;
2715 }
Chris Lattner6b695682007-08-16 15:56:55 +00002716
Neil Boothb6182162007-10-08 13:47:12 +00002717 while (parts > 0)
2718 dst[--parts] = 0;
2719 }
Chris Lattner6b695682007-08-16 15:56:55 +00002720}
2721
2722/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2723 zero. There are no restrictions on COUNT. */
Craig Topper55229b72017-04-02 19:17:22 +00002724void APInt::tcShiftRight(WordType *dst, unsigned parts, unsigned count) {
Neil Boothb6182162007-10-08 13:47:12 +00002725 if (count) {
Neil Boothb6182162007-10-08 13:47:12 +00002726 /* Jump is the inter-part jump; shift is is intra-part shift. */
Craig Topper55229b72017-04-02 19:17:22 +00002727 unsigned jump = count / APINT_BITS_PER_WORD;
2728 unsigned shift = count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002729
Neil Boothb6182162007-10-08 13:47:12 +00002730 /* Perform the shift. This leaves the most significant COUNT bits
2731 of the result at zero. */
Craig Topperb0038162017-03-28 05:32:52 +00002732 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002733 WordType part;
Chris Lattner6b695682007-08-16 15:56:55 +00002734
Neil Boothb6182162007-10-08 13:47:12 +00002735 if (i + jump >= parts) {
2736 part = 0;
2737 } else {
2738 part = dst[i + jump];
2739 if (shift) {
2740 part >>= shift;
2741 if (i + jump + 1 < parts)
Craig Topper55229b72017-04-02 19:17:22 +00002742 part |= dst[i + jump + 1] << (APINT_BITS_PER_WORD - shift);
Neil Boothb6182162007-10-08 13:47:12 +00002743 }
Chris Lattner6b695682007-08-16 15:56:55 +00002744 }
Chris Lattner6b695682007-08-16 15:56:55 +00002745
Neil Boothb6182162007-10-08 13:47:12 +00002746 dst[i] = part;
2747 }
Chris Lattner6b695682007-08-16 15:56:55 +00002748 }
2749}
2750
2751/* Bitwise and of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002752void APInt::tcAnd(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002753 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002754 dst[i] &= rhs[i];
2755}
2756
2757/* Bitwise inclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002758void APInt::tcOr(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002759 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002760 dst[i] |= rhs[i];
2761}
2762
2763/* Bitwise exclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002764void APInt::tcXor(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002765 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002766 dst[i] ^= rhs[i];
2767}
2768
2769/* Complement a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002770void APInt::tcComplement(WordType *dst, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002771 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002772 dst[i] = ~dst[i];
2773}
2774
2775/* Comparison (unsigned) of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002776int APInt::tcCompare(const WordType *lhs, const WordType *rhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002777 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002778 while (parts) {
Craig Topper99cfe4f2017-04-01 21:50:06 +00002779 parts--;
2780 if (lhs[parts] == rhs[parts])
2781 continue;
Chris Lattner6b695682007-08-16 15:56:55 +00002782
Craig Topper68a3ed22017-04-01 21:50:10 +00002783 return (lhs[parts] > rhs[parts]) ? 1 : -1;
Craig Topper99cfe4f2017-04-01 21:50:06 +00002784 }
Chris Lattner6b695682007-08-16 15:56:55 +00002785
2786 return 0;
2787}
2788
2789/* Increment a bignum in-place, return the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002790APInt::WordType APInt::tcIncrement(WordType *dst, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002791 unsigned i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002792 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002793 if (++dst[i] != 0)
2794 break;
2795
2796 return i == parts;
2797}
2798
Michael Gottesman9d406f42013-05-28 19:50:20 +00002799/* Decrement a bignum in-place, return the borrow flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002800APInt::WordType APInt::tcDecrement(WordType *dst, unsigned parts) {
Craig Topper592b1342017-03-28 05:32:48 +00002801 for (unsigned i = 0; i < parts; i++) {
Michael Gottesman9d406f42013-05-28 19:50:20 +00002802 // If the current word is non-zero, then the decrement has no effect on the
2803 // higher-order words of the integer and no borrow can occur. Exit early.
2804 if (dst[i]--)
2805 return 0;
2806 }
2807 // If every word was zero, then there is a borrow.
2808 return 1;
2809}
2810
2811
Chris Lattner6b695682007-08-16 15:56:55 +00002812/* Set the least significant BITS bits of a bignum, clear the
2813 rest. */
Craig Topper55229b72017-04-02 19:17:22 +00002814void APInt::tcSetLeastSignificantBits(WordType *dst, unsigned parts,
Craig Topper6a8518082017-03-28 05:32:55 +00002815 unsigned bits) {
Craig Topperb0038162017-03-28 05:32:52 +00002816 unsigned i = 0;
Craig Topper55229b72017-04-02 19:17:22 +00002817 while (bits > APINT_BITS_PER_WORD) {
2818 dst[i++] = ~(WordType) 0;
2819 bits -= APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002820 }
2821
2822 if (bits)
Craig Topper55229b72017-04-02 19:17:22 +00002823 dst[i++] = ~(WordType) 0 >> (APINT_BITS_PER_WORD - bits);
Chris Lattner6b695682007-08-16 15:56:55 +00002824
2825 while (i < parts)
2826 dst[i++] = 0;
2827}