blob: babfbdc21a61a8c43191c8ce0729dde58067b20c [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
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000229/// This function adds the integer array x to the integer array Y and
Eric Christopher820256b2009-08-21 04:06:45 +0000230/// places the result in dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000231/// @returns the carry out from the addition
232/// @brief General addition of 64-bit integer arrays
Eric Christopher820256b2009-08-21 04:06:45 +0000233static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000234 unsigned len) {
Reid Spencera5e0d202007-02-24 03:58:46 +0000235 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000236 for (unsigned i = 0; i< len; ++i) {
Reid Spencercb292e42007-02-23 01:57:13 +0000237 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000238 dest[i] = x[i] + y[i] + carry;
Reid Spencerdb2abec2007-02-21 05:44:56 +0000239 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer100502d2007-02-17 03:16:00 +0000240 }
241 return carry;
242}
243
Reid Spencera41e93b2007-02-25 19:32:03 +0000244/// Adds the RHS APint to this APInt.
245/// @returns this, after addition of RHS.
Eric Christopher820256b2009-08-21 04:06:45 +0000246/// @brief Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000247APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000248 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000249 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000250 VAL += RHS.VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000251 else {
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000252 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000253 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000254 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000255}
256
Pete Cooperfea21392016-07-22 20:55:46 +0000257APInt& APInt::operator+=(uint64_t RHS) {
258 if (isSingleWord())
259 VAL += RHS;
260 else
261 add_1(pVal, pVal, getNumWords(), RHS);
262 return clearUnusedBits();
263}
264
Eric Christopher820256b2009-08-21 04:06:45 +0000265/// Subtracts the integer array y from the integer array x
Reid Spencera41e93b2007-02-25 19:32:03 +0000266/// @returns returns the borrow out.
267/// @brief Generalized subtraction of 64-bit integer arrays.
Eric Christopher820256b2009-08-21 04:06:45 +0000268static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000269 unsigned len) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000270 bool borrow = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000271 for (unsigned i = 0; i < len; ++i) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000272 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
273 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
274 dest[i] = x_tmp - y[i];
Reid Spencer100502d2007-02-17 03:16:00 +0000275 }
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000276 return borrow;
Reid Spencer100502d2007-02-17 03:16:00 +0000277}
278
Reid Spencera41e93b2007-02-25 19:32:03 +0000279/// Subtracts the RHS APInt from this APInt
280/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000281/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000282APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000283 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000284 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000285 VAL -= RHS.VAL;
286 else
287 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000288 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000289}
290
Pete Cooperfea21392016-07-22 20:55:46 +0000291APInt& APInt::operator-=(uint64_t RHS) {
292 if (isSingleWord())
293 VAL -= RHS;
294 else
295 sub_1(pVal, getNumWords(), RHS);
296 return clearUnusedBits();
297}
298
Dan Gohman4a618822010-02-10 16:03:48 +0000299/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000300/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000301/// @returns the carry out of the multiplication.
302/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000303static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000304 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000305 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000306 uint64_t carry = 0;
307
308 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000309 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000310 // Split x into high and low words
311 uint64_t lx = x[i] & 0xffffffffULL;
312 uint64_t hx = x[i] >> 32;
313 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000314 // hasCarry == 0, no carry
315 // hasCarry == 1, has carry
316 // hasCarry == 2, no carry and the calculation result == 0.
317 uint8_t hasCarry = 0;
318 dest[i] = carry + lx * ly;
319 // Determine if the add above introduces carry.
320 hasCarry = (dest[i] < carry) ? 1 : 0;
321 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000322 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000323 // (2^32 - 1) + 2^32 = 2^64.
324 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
325
326 carry += (lx * hy) & 0xffffffffULL;
327 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000328 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000329 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
330 }
Reid Spencer100502d2007-02-17 03:16:00 +0000331 return carry;
332}
333
Eric Christopher820256b2009-08-21 04:06:45 +0000334/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000335/// the integer array dest. Note that dest's size must be >= xlen + ylen.
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000336/// @brief Generalized multiplication of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000337static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
338 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000339 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000340 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000341 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000342 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000343 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000344 lx = x[j] & 0xffffffffULL;
345 hx = x[j] >> 32;
346 // hasCarry - A flag to indicate if has carry.
347 // hasCarry == 0, no carry
348 // hasCarry == 1, has carry
349 // hasCarry == 2, no carry and the calculation result == 0.
350 uint8_t hasCarry = 0;
351 uint64_t resul = carry + lx * ly;
352 hasCarry = (resul < carry) ? 1 : 0;
353 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
354 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
355
356 carry += (lx * hy) & 0xffffffffULL;
357 resul = (carry << 32) | (resul & 0xffffffffULL);
358 dest[i+j] += resul;
359 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000360 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000361 ((lx * hy) >> 32) + hx * hy;
362 }
363 dest[i+xlen] = carry;
364 }
365}
366
Zhou Shengdac63782007-02-06 03:00:16 +0000367APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000368 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000369 if (isSingleWord()) {
Reid Spencer4bb430c2007-02-20 20:42:10 +0000370 VAL *= RHS.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000371 clearUnusedBits();
372 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000373 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000374
375 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000376 unsigned lhsBits = getActiveBits();
377 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000378 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000379 // 0 * X ===> 0
380 return *this;
381
382 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000383 unsigned rhsBits = RHS.getActiveBits();
384 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000385 if (!rhsWords) {
386 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000387 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000388 return *this;
389 }
390
391 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000392 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000393 uint64_t *dest = getMemory(destWords);
394
395 // Perform the long multiply
396 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
397
398 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000399 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000400 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000401 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000402 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000403
404 // delete dest array and return
405 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000406 return *this;
407}
408
Craig Topperf496f9a2017-03-28 04:00:47 +0000409APInt& APInt::AndAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000410 tcAnd(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000411 return *this;
412}
413
Craig Topperf496f9a2017-03-28 04:00:47 +0000414APInt& APInt::OrAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000415 tcOr(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000416 return *this;
417}
418
Craig Topperf496f9a2017-03-28 04:00:47 +0000419APInt& APInt::XorAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000420 tcXor(pVal, RHS.pVal, getNumWords());
Craig Topper9028f052017-01-24 02:10:15 +0000421 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000422}
423
Zhou Shengdac63782007-02-06 03:00:16 +0000424APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000425 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000426 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000427 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000428 APInt Result(*this);
429 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000430 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000431}
432
Chris Lattner1ac3e252008-08-20 17:02:31 +0000433bool APInt::EqualSlowCase(const APInt& RHS) const {
Matthias Braun5117fcd2016-02-15 20:06:19 +0000434 return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000435}
436
Chris Lattner1ac3e252008-08-20 17:02:31 +0000437bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000438 unsigned n = getActiveBits();
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000439 if (n <= APINT_BITS_PER_WORD)
440 return pVal[0] == Val;
441 else
442 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000443}
444
Reid Spencer1d072122007-02-16 22:36:51 +0000445bool APInt::ult(const APInt& RHS) const {
446 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
447 if (isSingleWord())
448 return VAL < RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000449
450 // Get active bit length of both operands
Chris Lattner77527f52009-01-21 18:09:24 +0000451 unsigned n1 = getActiveBits();
452 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000453
454 // If magnitude of LHS is less than RHS, return true.
455 if (n1 < n2)
456 return true;
457
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000458 // If magnitude of RHS is greater than LHS, return false.
Reid Spencera41e93b2007-02-25 19:32:03 +0000459 if (n2 < n1)
460 return false;
461
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000462 // If they both fit in a word, just compare the low order word
Reid Spencera41e93b2007-02-25 19:32:03 +0000463 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
464 return pVal[0] < RHS.pVal[0];
465
466 // Otherwise, compare all words
Chris Lattner77527f52009-01-21 18:09:24 +0000467 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000468 for (int i = topWord; i >= 0; --i) {
Eric Christopher820256b2009-08-21 04:06:45 +0000469 if (pVal[i] > RHS.pVal[i])
Reid Spencer1d072122007-02-16 22:36:51 +0000470 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000471 if (pVal[i] < RHS.pVal[i])
Reid Spencera41e93b2007-02-25 19:32:03 +0000472 return true;
Zhou Shengdac63782007-02-06 03:00:16 +0000473 }
474 return false;
475}
476
Reid Spencer1d072122007-02-16 22:36:51 +0000477bool APInt::slt(const APInt& RHS) const {
478 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000479 if (isSingleWord()) {
David Majnemer5f1c0172016-06-24 20:51:47 +0000480 int64_t lhsSext = SignExtend64(VAL, BitWidth);
481 int64_t rhsSext = SignExtend64(RHS.VAL, BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000482 return lhsSext < rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000483 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000484
Reid Spencer54abdcf2007-02-27 18:23:40 +0000485 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000486 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000487
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000488 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
489 if (lhsNeg != rhsNeg)
490 return lhsNeg;
491
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000492 // Otherwise we can just use an unsigned comparison, because even negative
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000493 // numbers compare correctly this way if both have the same signed-ness.
494 return ult(RHS);
Zhou Shengdac63782007-02-06 03:00:16 +0000495}
496
Jay Foad25a5e4c2010-12-01 08:53:58 +0000497void APInt::setBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000498 if (isSingleWord())
Reid Spencera41e93b2007-02-25 19:32:03 +0000499 VAL |= maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000500 else
Reid Spencera41e93b2007-02-25 19:32:03 +0000501 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000502}
503
Craig Topperbafdd032017-03-07 01:56:01 +0000504void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
505 unsigned loWord = whichWord(loBit);
506 unsigned hiWord = whichWord(hiBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000507
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000508 // Create an initial mask for the low word with zeros below loBit.
Craig Topperbafdd032017-03-07 01:56:01 +0000509 uint64_t loMask = UINT64_MAX << whichBit(loBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000510
Craig Topperbafdd032017-03-07 01:56:01 +0000511 // If hiBit is not aligned, we need a high mask.
512 unsigned hiShiftAmt = whichBit(hiBit);
513 if (hiShiftAmt != 0) {
514 // Create a high mask with zeros above hiBit.
515 uint64_t hiMask = UINT64_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
516 // If loWord and hiWord are equal, then we combine the masks. Otherwise,
517 // set the bits in hiWord.
518 if (hiWord == loWord)
519 loMask &= hiMask;
520 else
Simon Pilgrimaed35222017-02-24 10:15:29 +0000521 pVal[hiWord] |= hiMask;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000522 }
Craig Topperbafdd032017-03-07 01:56:01 +0000523 // Apply the mask to the low word.
524 pVal[loWord] |= loMask;
525
526 // Fill any words between loWord and hiWord with all ones.
527 for (unsigned word = loWord + 1; word < hiWord; ++word)
528 pVal[word] = UINT64_MAX;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000529}
530
Zhou Shengdac63782007-02-06 03:00:16 +0000531/// Set the given bit to 0 whose position is given as "bitPosition".
532/// @brief Set a given bit to 0.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000533void APInt::clearBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000534 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000535 VAL &= ~maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000536 else
Reid Spencera856b6e2007-02-18 18:38:44 +0000537 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000538}
539
Zhou Shengdac63782007-02-06 03:00:16 +0000540/// @brief Toggle every bit to its opposite value.
Craig Topperafc9e352017-03-27 17:10:21 +0000541void APInt::flipAllBitsSlowCase() {
542 for (unsigned i = 0; i < getNumWords(); ++i)
543 pVal[i] ^= UINT64_MAX;
544 clearUnusedBits();
545}
Zhou Shengdac63782007-02-06 03:00:16 +0000546
Eric Christopher820256b2009-08-21 04:06:45 +0000547/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000548/// as "bitPosition".
549/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000550void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000551 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000552 if ((*this)[bitPosition]) clearBit(bitPosition);
553 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000554}
555
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000556void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
557 unsigned subBitWidth = subBits.getBitWidth();
558 assert(0 < subBitWidth && (subBitWidth + bitPosition) <= BitWidth &&
559 "Illegal bit insertion");
560
561 // Insertion is a direct copy.
562 if (subBitWidth == BitWidth) {
563 *this = subBits;
564 return;
565 }
566
567 // Single word result can be done as a direct bitmask.
568 if (isSingleWord()) {
569 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
570 VAL &= ~(mask << bitPosition);
571 VAL |= (subBits.VAL << bitPosition);
572 return;
573 }
574
575 unsigned loBit = whichBit(bitPosition);
576 unsigned loWord = whichWord(bitPosition);
577 unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
578
579 // Insertion within a single word can be done as a direct bitmask.
580 if (loWord == hi1Word) {
581 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
582 pVal[loWord] &= ~(mask << loBit);
583 pVal[loWord] |= (subBits.VAL << loBit);
584 return;
585 }
586
587 // Insert on word boundaries.
588 if (loBit == 0) {
589 // Direct copy whole words.
590 unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
591 memcpy(pVal + loWord, subBits.getRawData(),
592 numWholeSubWords * APINT_WORD_SIZE);
593
594 // Mask+insert remaining bits.
595 unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
596 if (remainingBits != 0) {
597 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - remainingBits);
598 pVal[hi1Word] &= ~mask;
599 pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
600 }
601 return;
602 }
603
604 // General case - set/clear individual bits in dst based on src.
605 // TODO - there is scope for optimization here, but at the moment this code
606 // path is barely used so prefer readability over performance.
607 for (unsigned i = 0; i != subBitWidth; ++i) {
608 if (subBits[i])
609 setBit(bitPosition + i);
610 else
611 clearBit(bitPosition + i);
612 }
613}
614
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000615APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
616 assert(numBits > 0 && "Can't extract zero bits");
617 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
618 "Illegal bit extraction");
619
620 if (isSingleWord())
621 return APInt(numBits, VAL >> bitPosition);
622
623 unsigned loBit = whichBit(bitPosition);
624 unsigned loWord = whichWord(bitPosition);
625 unsigned hiWord = whichWord(bitPosition + numBits - 1);
626
627 // Single word result extracting bits from a single word source.
628 if (loWord == hiWord)
629 return APInt(numBits, pVal[loWord] >> loBit);
630
631 // Extracting bits that start on a source word boundary can be done
632 // as a fast memory copy.
633 if (loBit == 0)
634 return APInt(numBits, makeArrayRef(pVal + loWord, 1 + hiWord - loWord));
635
636 // General case - shift + copy source words directly into place.
637 APInt Result(numBits, 0);
638 unsigned NumSrcWords = getNumWords();
639 unsigned NumDstWords = Result.getNumWords();
640
641 for (unsigned word = 0; word < NumDstWords; ++word) {
642 uint64_t w0 = pVal[loWord + word];
643 uint64_t w1 =
644 (loWord + word + 1) < NumSrcWords ? pVal[loWord + word + 1] : 0;
645 Result.pVal[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
646 }
647
648 return Result.clearUnusedBits();
649}
650
Benjamin Kramer92d89982010-07-14 22:38:02 +0000651unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000652 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000653 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +0000654 radix == 36) &&
655 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000656
657 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000658
Eric Christopher43a1dec2009-08-21 04:10:31 +0000659 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000660 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000661 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000662 if (*p == '-' || *p == '+') {
663 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000664 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000665 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000666 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000667
Reid Spencer9329e7b2007-04-13 19:19:07 +0000668 // For radixes of power-of-two values, the bits required is accurately and
669 // easily computed
670 if (radix == 2)
671 return slen + isNegative;
672 if (radix == 8)
673 return slen * 3 + isNegative;
674 if (radix == 16)
675 return slen * 4 + isNegative;
676
Douglas Gregor663c0682011-09-14 15:54:46 +0000677 // FIXME: base 36
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000678
Reid Spencer9329e7b2007-04-13 19:19:07 +0000679 // This is grossly inefficient but accurate. We could probably do something
680 // with a computation of roughly slen*64/20 and then adjust by the value of
681 // the first few digits. But, I'm not sure how accurate that could be.
682
683 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000684 // be too large. This avoids the assertion in the constructor. This
685 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
686 // bits in that case.
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000687 unsigned sufficient
Douglas Gregor663c0682011-09-14 15:54:46 +0000688 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
689 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000690
691 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000692 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000693
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000694 // Compute how many bits are required. If the log is infinite, assume we need
695 // just bit.
696 unsigned log = tmp.logBase2();
697 if (log == (unsigned)-1) {
698 return isNegative + 1;
699 } else {
700 return isNegative + log + 1;
701 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000702}
703
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000704hash_code llvm::hash_value(const APInt &Arg) {
705 if (Arg.isSingleWord())
706 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000707
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000708 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000709}
710
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000711bool APInt::isSplat(unsigned SplatSizeInBits) const {
712 assert(getBitWidth() % SplatSizeInBits == 0 &&
713 "SplatSizeInBits must divide width!");
714 // We can check that all parts of an integer are equal by making use of a
715 // little trick: rotate and check if it's still the same value.
716 return *this == rotl(SplatSizeInBits);
717}
718
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000719/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000720APInt APInt::getHiBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000721 return this->lshr(BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000722}
723
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000724/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000725APInt APInt::getLoBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000726 APInt Result(getLowBitsSet(BitWidth, numBits));
727 Result &= *this;
728 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000729}
730
Chris Lattner77527f52009-01-21 18:09:24 +0000731unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000732 unsigned Count = 0;
733 for (int i = getNumWords()-1; i >= 0; --i) {
734 integerPart V = pVal[i];
735 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000736 Count += APINT_BITS_PER_WORD;
737 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000738 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000739 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000740 }
Zhou Shengdac63782007-02-06 03:00:16 +0000741 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000742 // Adjust for unused bits in the most significant word (they are zero).
743 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
744 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000745 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000746}
747
Chris Lattner77527f52009-01-21 18:09:24 +0000748unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000749 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000750 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000751
Chris Lattner77527f52009-01-21 18:09:24 +0000752 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000753 unsigned shift;
754 if (!highWordBits) {
755 highWordBits = APINT_BITS_PER_WORD;
756 shift = 0;
757 } else {
758 shift = APINT_BITS_PER_WORD - highWordBits;
759 }
Reid Spencer31acef52007-02-27 21:59:26 +0000760 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000761 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000762 if (Count == highWordBits) {
763 for (i--; i >= 0; --i) {
764 if (pVal[i] == -1ULL)
765 Count += APINT_BITS_PER_WORD;
766 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000767 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000768 break;
769 }
770 }
771 }
772 return Count;
773}
774
Chris Lattner77527f52009-01-21 18:09:24 +0000775unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000776 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000777 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000778 unsigned Count = 0;
779 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000780 for (; i < getNumWords() && pVal[i] == 0; ++i)
781 Count += APINT_BITS_PER_WORD;
782 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000783 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000784 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000785}
786
Chris Lattner77527f52009-01-21 18:09:24 +0000787unsigned APInt::countTrailingOnesSlowCase() const {
788 unsigned Count = 0;
789 unsigned i = 0;
Dan Gohmanc354ebd2008-02-14 22:38:45 +0000790 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000791 Count += APINT_BITS_PER_WORD;
792 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000793 Count += llvm::countTrailingOnes(pVal[i]);
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000794 return std::min(Count, BitWidth);
795}
796
Chris Lattner77527f52009-01-21 18:09:24 +0000797unsigned APInt::countPopulationSlowCase() const {
798 unsigned Count = 0;
799 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000800 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000801 return Count;
802}
803
Richard Smith4f9a8082011-11-23 21:33:37 +0000804/// Perform a logical right-shift from Src to Dst, which must be equal or
805/// non-overlapping, of Words words, by Shift, which must be less than 64.
806static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
807 unsigned Shift) {
808 uint64_t Carry = 0;
809 for (int I = Words - 1; I >= 0; --I) {
810 uint64_t Tmp = Src[I];
811 Dst[I] = (Tmp >> Shift) | Carry;
812 Carry = Tmp << (64 - Shift);
813 }
814}
815
Reid Spencer1d072122007-02-16 22:36:51 +0000816APInt APInt::byteSwap() const {
817 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
818 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000819 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000820 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000821 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000822 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000823 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000824 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000825 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000826 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000827 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000828 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000829 if (BitWidth == 64)
830 return APInt(BitWidth, ByteSwap_64(VAL));
831
832 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
833 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
834 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
835 if (Result.BitWidth != BitWidth) {
836 lshrNear(Result.pVal, Result.pVal, getNumWords(),
837 Result.BitWidth - BitWidth);
838 Result.BitWidth = BitWidth;
839 }
840 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000841}
842
Matt Arsenault155dda92016-03-21 15:00:35 +0000843APInt APInt::reverseBits() const {
844 switch (BitWidth) {
845 case 64:
846 return APInt(BitWidth, llvm::reverseBits<uint64_t>(VAL));
847 case 32:
848 return APInt(BitWidth, llvm::reverseBits<uint32_t>(VAL));
849 case 16:
850 return APInt(BitWidth, llvm::reverseBits<uint16_t>(VAL));
851 case 8:
852 return APInt(BitWidth, llvm::reverseBits<uint8_t>(VAL));
853 default:
854 break;
855 }
856
857 APInt Val(*this);
858 APInt Reversed(*this);
859 int S = BitWidth - 1;
860
861 const APInt One(BitWidth, 1);
862
863 for ((Val = Val.lshr(1)); Val != 0; (Val = Val.lshr(1))) {
864 Reversed <<= 1;
865 Reversed |= (Val & One);
866 --S;
867 }
868
869 Reversed <<= S;
870 return Reversed;
871}
872
Craig Topper278ebd22017-04-01 20:30:57 +0000873APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) {
Zhou Shengdac63782007-02-06 03:00:16 +0000874 while (!!B) {
Craig Topper278ebd22017-04-01 20:30:57 +0000875 APInt R = A.urem(B);
876 A = std::move(B);
877 B = std::move(R);
Zhou Shengdac63782007-02-06 03:00:16 +0000878 }
879 return A;
880}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000881
Chris Lattner77527f52009-01-21 18:09:24 +0000882APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000883 union {
884 double D;
885 uint64_t I;
886 } T;
887 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000888
889 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000890 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000891
892 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000893 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000894
895 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000896 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000897 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000898
899 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
900 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
901
902 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000903 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000904 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000905 APInt(width, mantissa >> (52 - exp));
906
907 // If the client didn't provide enough bits for us to shift the mantissa into
908 // then the result is undefined, just return 0
909 if (width <= exp - 52)
910 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000911
912 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000913 APInt Tmp(width, mantissa);
Chris Lattner77527f52009-01-21 18:09:24 +0000914 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd707d632007-02-12 20:02:55 +0000915 return isNeg ? -Tmp : Tmp;
916}
917
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000918/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000919/// The layout for double is as following (IEEE Standard 754):
920/// --------------------------------------
921/// | Sign Exponent Fraction Bias |
922/// |-------------------------------------- |
923/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000924/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000925double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000926
927 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000928 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000929 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
930 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000931 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000932 return double(sext);
933 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000934 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000935 }
936
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000937 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000938 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000939
940 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000941 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000942
943 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000944 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000945
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000946 // The exponent (without bias normalization) is just the number of bits
947 // we are using. Note that the sign bit is gone since we constructed the
948 // absolute value.
949 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000950
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000951 // Return infinity for exponent overflow
952 if (exp > 1023) {
953 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000954 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000955 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000956 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000957 }
958 exp += 1023; // Increment for 1023 bias
959
960 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
961 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000962 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000963 unsigned hiWord = whichWord(n-1);
964 if (hiWord == 0) {
965 mantissa = Tmp.pVal[0];
966 if (n > 52)
967 mantissa >>= n - 52; // shift down, we want the top 52 bits.
968 } else {
969 assert(hiWord > 0 && "huh?");
970 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
971 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
972 mantissa = hibits | lobits;
973 }
974
Zhou Shengd707d632007-02-12 20:02:55 +0000975 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000976 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000977 union {
978 double D;
979 uint64_t I;
980 } T;
981 T.I = sign | (exp << 52) | mantissa;
982 return T.D;
983}
984
Reid Spencer1d072122007-02-16 22:36:51 +0000985// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000986APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000987 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000988 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000989
990 if (width <= APINT_BITS_PER_WORD)
991 return APInt(width, getRawData()[0]);
992
993 APInt Result(getMemory(getNumWords(width)), width);
994
995 // Copy full words.
996 unsigned i;
997 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
998 Result.pVal[i] = pVal[i];
999
1000 // Truncate and copy any partial word.
1001 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
1002 if (bits != 0)
1003 Result.pVal[i] = pVal[i] << bits >> bits;
1004
1005 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001006}
1007
1008// Sign extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +00001009APInt APInt::sext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +00001010 assert(width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +00001011
1012 if (width <= APINT_BITS_PER_WORD) {
1013 uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
1014 val = (int64_t)val >> (width - BitWidth);
1015 return APInt(width, val >> (APINT_BITS_PER_WORD - width));
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001016 }
1017
Jay Foad583abbc2010-12-07 08:25:19 +00001018 APInt Result(getMemory(getNumWords(width)), width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001019
Jay Foad583abbc2010-12-07 08:25:19 +00001020 // Copy full words.
1021 unsigned i;
1022 uint64_t word = 0;
1023 for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
1024 word = getRawData()[i];
1025 Result.pVal[i] = word;
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001026 }
1027
Jay Foad583abbc2010-12-07 08:25:19 +00001028 // Read and sign-extend any partial word.
1029 unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
1030 if (bits != 0)
1031 word = (int64_t)getRawData()[i] << bits >> bits;
1032 else
1033 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
1034
1035 // Write remaining full words.
1036 for (; i != width / APINT_BITS_PER_WORD; i++) {
1037 Result.pVal[i] = word;
1038 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001039 }
Jay Foad583abbc2010-12-07 08:25:19 +00001040
1041 // Write any partial word.
1042 bits = (0 - width) % APINT_BITS_PER_WORD;
1043 if (bits != 0)
1044 Result.pVal[i] = word << bits >> bits;
1045
1046 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001047}
1048
1049// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +00001050APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +00001051 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +00001052
1053 if (width <= APINT_BITS_PER_WORD)
1054 return APInt(width, VAL);
1055
1056 APInt Result(getMemory(getNumWords(width)), width);
1057
1058 // Copy words.
1059 unsigned i;
1060 for (i = 0; i != getNumWords(); i++)
1061 Result.pVal[i] = getRawData()[i];
1062
1063 // Zero remaining words.
1064 memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
1065
1066 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001067}
1068
Jay Foad583abbc2010-12-07 08:25:19 +00001069APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001070 if (BitWidth < width)
1071 return zext(width);
1072 if (BitWidth > width)
1073 return trunc(width);
1074 return *this;
1075}
1076
Jay Foad583abbc2010-12-07 08:25:19 +00001077APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001078 if (BitWidth < width)
1079 return sext(width);
1080 if (BitWidth > width)
1081 return trunc(width);
1082 return *this;
1083}
1084
Rafael Espindolabb893fe2012-01-27 23:33:07 +00001085APInt APInt::zextOrSelf(unsigned width) const {
1086 if (BitWidth < width)
1087 return zext(width);
1088 return *this;
1089}
1090
1091APInt APInt::sextOrSelf(unsigned width) const {
1092 if (BitWidth < width)
1093 return sext(width);
1094 return *this;
1095}
1096
Zhou Shenge93db8f2007-02-09 07:48:24 +00001097/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001098/// @brief Arithmetic right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001099APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001100 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001101}
1102
1103/// Arithmetic right-shift this APInt by shiftAmt.
1104/// @brief Arithmetic right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001105APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001106 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer1825dd02007-03-02 22:39:11 +00001107 // Handle a degenerate case
1108 if (shiftAmt == 0)
1109 return *this;
1110
1111 // Handle single word shifts with built-in ashr
Reid Spencer522ca7c2007-02-25 01:56:07 +00001112 if (isSingleWord()) {
1113 if (shiftAmt == BitWidth)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001114 return APInt(BitWidth, 0); // undefined
Jonathan Roelofs851b79d2016-08-10 19:50:14 +00001115 return APInt(BitWidth, SignExtend64(VAL, BitWidth) >> shiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001116 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001117
Reid Spencer1825dd02007-03-02 22:39:11 +00001118 // If all the bits were shifted out, the result is, technically, undefined.
1119 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1120 // issues in the algorithm below.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001121 if (shiftAmt == BitWidth) {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001122 if (isNegative())
Zhou Sheng1247c072008-06-05 13:27:38 +00001123 return APInt(BitWidth, -1ULL, true);
Reid Spencera41e93b2007-02-25 19:32:03 +00001124 else
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001125 return APInt(BitWidth, 0);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001126 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001127
1128 // Create some space for the result.
1129 uint64_t * val = new uint64_t[getNumWords()];
1130
Reid Spencer1825dd02007-03-02 22:39:11 +00001131 // Compute some values needed by the following shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001132 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1133 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1134 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1135 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer1825dd02007-03-02 22:39:11 +00001136 if (bitsInWord == 0)
1137 bitsInWord = APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001138
1139 // If we are shifting whole words, just move whole words
1140 if (wordShift == 0) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001141 // Move the words containing significant bits
Chris Lattner77527f52009-01-21 18:09:24 +00001142 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001143 val[i] = pVal[i+offset]; // move whole word
1144
1145 // Adjust the top significant word for sign bit fill, if negative
1146 if (isNegative())
1147 if (bitsInWord < APINT_BITS_PER_WORD)
1148 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1149 } else {
Eric Christopher820256b2009-08-21 04:06:45 +00001150 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001151 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001152 // This combines the shifted corresponding word with the low bits from
1153 // the next word (shifted into this word's high bits).
Eric Christopher820256b2009-08-21 04:06:45 +00001154 val[i] = (pVal[i+offset] >> wordShift) |
Reid Spencer1825dd02007-03-02 22:39:11 +00001155 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1156 }
1157
1158 // Shift the break word. In this case there are no bits from the next word
1159 // to include in this word.
1160 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1161
Alp Tokercb402912014-01-24 17:20:08 +00001162 // Deal with sign extension in the break word, and possibly the word before
Reid Spencer1825dd02007-03-02 22:39:11 +00001163 // it.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001164 if (isNegative()) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001165 if (wordShift > bitsInWord) {
1166 if (breakWord > 0)
Eric Christopher820256b2009-08-21 04:06:45 +00001167 val[breakWord-1] |=
Reid Spencer1825dd02007-03-02 22:39:11 +00001168 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1169 val[breakWord] |= ~0ULL;
Eric Christopher820256b2009-08-21 04:06:45 +00001170 } else
Reid Spencer1825dd02007-03-02 22:39:11 +00001171 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnerdad2d092007-05-03 18:15:36 +00001172 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001173 }
1174
Reid Spencer1825dd02007-03-02 22:39:11 +00001175 // Remaining words are 0 or -1, just assign them.
1176 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner77527f52009-01-21 18:09:24 +00001177 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001178 val[i] = fillValue;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001179 APInt Result(val, BitWidth);
1180 Result.clearUnusedBits();
1181 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001182}
1183
Zhou Shenge93db8f2007-02-09 07:48:24 +00001184/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001185/// @brief Logical right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001186APInt APInt::lshr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001187 return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001188}
1189
1190/// Logical right-shift this APInt by shiftAmt.
1191/// @brief Logical right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001192APInt APInt::lshr(unsigned shiftAmt) const {
Chris Lattnerdad2d092007-05-03 18:15:36 +00001193 if (isSingleWord()) {
Ahmed Charles0dca5d82012-02-24 19:06:15 +00001194 if (shiftAmt >= BitWidth)
Reid Spencer522ca7c2007-02-25 01:56:07 +00001195 return APInt(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001196 else
Reid Spencer522ca7c2007-02-25 01:56:07 +00001197 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001198 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001199
Reid Spencer44eef162007-02-26 01:19:48 +00001200 // If all the bits were shifted out, the result is 0. This avoids issues
1201 // with shifting by the size of the integer type, which produces undefined
1202 // results. We define these "undefined results" to always be 0.
Chad Rosier3d464d82012-06-08 18:04:52 +00001203 if (shiftAmt >= BitWidth)
Reid Spencer44eef162007-02-26 01:19:48 +00001204 return APInt(BitWidth, 0);
1205
Reid Spencerfffdf102007-05-17 06:26:29 +00001206 // If none of the bits are shifted out, the result is *this. This avoids
Eric Christopher820256b2009-08-21 04:06:45 +00001207 // issues with shifting by the size of the integer type, which produces
Reid Spencerfffdf102007-05-17 06:26:29 +00001208 // undefined results in the code below. This is also an optimization.
1209 if (shiftAmt == 0)
1210 return *this;
1211
Reid Spencer44eef162007-02-26 01:19:48 +00001212 // Create some space for the result.
1213 uint64_t * val = new uint64_t[getNumWords()];
1214
1215 // If we are shifting less than a word, compute the shift with a simple carry
1216 if (shiftAmt < APINT_BITS_PER_WORD) {
Richard Smith4f9a8082011-11-23 21:33:37 +00001217 lshrNear(val, pVal, getNumWords(), shiftAmt);
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001218 APInt Result(val, BitWidth);
1219 Result.clearUnusedBits();
1220 return Result;
Reid Spencera41e93b2007-02-25 19:32:03 +00001221 }
1222
Reid Spencer44eef162007-02-26 01:19:48 +00001223 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001224 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1225 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencer44eef162007-02-26 01:19:48 +00001226
1227 // If we are shifting whole words, just move whole words
1228 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001229 for (unsigned i = 0; i < getNumWords() - offset; ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001230 val[i] = pVal[i+offset];
Chris Lattner77527f52009-01-21 18:09:24 +00001231 for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
Reid Spencer44eef162007-02-26 01:19:48 +00001232 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001233 APInt Result(val, BitWidth);
1234 Result.clearUnusedBits();
1235 return Result;
Reid Spencer44eef162007-02-26 01:19:48 +00001236 }
1237
Eric Christopher820256b2009-08-21 04:06:45 +00001238 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001239 unsigned breakWord = getNumWords() - offset -1;
1240 for (unsigned i = 0; i < breakWord; ++i)
Reid Spencerd99feaf2007-03-01 05:39:56 +00001241 val[i] = (pVal[i+offset] >> wordShift) |
1242 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencer44eef162007-02-26 01:19:48 +00001243 // Shift the break word.
1244 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1245
1246 // Remaining words are 0
Chris Lattner77527f52009-01-21 18:09:24 +00001247 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001248 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001249 APInt Result(val, BitWidth);
1250 Result.clearUnusedBits();
1251 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001252}
1253
Zhou Shenge93db8f2007-02-09 07:48:24 +00001254/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001255/// @brief Left-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001256APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky030c4502009-01-19 17:42:33 +00001257 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner77527f52009-01-21 18:09:24 +00001258 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001259}
1260
Chris Lattner77527f52009-01-21 18:09:24 +00001261APInt APInt::shlSlowCase(unsigned shiftAmt) const {
Reid Spencera5c84d92007-02-25 00:56:44 +00001262 // If all the bits were shifted out, the result is 0. This avoids issues
1263 // with shifting by the size of the integer type, which produces undefined
1264 // results. We define these "undefined results" to always be 0.
1265 if (shiftAmt == BitWidth)
1266 return APInt(BitWidth, 0);
1267
Reid Spencer81ee0202007-05-12 18:01:57 +00001268 // If none of the bits are shifted out, the result is *this. This avoids a
1269 // lshr by the words size in the loop below which can produce incorrect
1270 // results. It also avoids the expensive computation below for a common case.
1271 if (shiftAmt == 0)
1272 return *this;
1273
Reid Spencera5c84d92007-02-25 00:56:44 +00001274 // Create some space for the result.
1275 uint64_t * val = new uint64_t[getNumWords()];
1276
1277 // If we are shifting less than a word, do it the easy way
1278 if (shiftAmt < APINT_BITS_PER_WORD) {
1279 uint64_t carry = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001280 for (unsigned i = 0; i < getNumWords(); i++) {
Reid Spencera5c84d92007-02-25 00:56:44 +00001281 val[i] = pVal[i] << shiftAmt | carry;
1282 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1283 }
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001284 APInt Result(val, BitWidth);
1285 Result.clearUnusedBits();
1286 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001287 }
1288
Reid Spencera5c84d92007-02-25 00:56:44 +00001289 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001290 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1291 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencera5c84d92007-02-25 00:56:44 +00001292
1293 // If we are shifting whole words, just move whole words
1294 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001295 for (unsigned i = 0; i < offset; i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001296 val[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001297 for (unsigned i = offset; i < getNumWords(); i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001298 val[i] = pVal[i-offset];
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001299 APInt Result(val, BitWidth);
1300 Result.clearUnusedBits();
1301 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001302 }
Reid Spencera5c84d92007-02-25 00:56:44 +00001303
1304 // Copy whole words from this to Result.
Chris Lattner77527f52009-01-21 18:09:24 +00001305 unsigned i = getNumWords() - 1;
Reid Spencera5c84d92007-02-25 00:56:44 +00001306 for (; i > offset; --i)
1307 val[i] = pVal[i-offset] << wordShift |
1308 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencerab0e08a2007-02-25 01:08:58 +00001309 val[offset] = pVal[0] << wordShift;
Reid Spencera5c84d92007-02-25 00:56:44 +00001310 for (i = 0; i < offset; ++i)
1311 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001312 APInt Result(val, BitWidth);
1313 Result.clearUnusedBits();
1314 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001315}
1316
Joey Gouly51c0ae52017-02-07 11:58:22 +00001317// Calculate the rotate amount modulo the bit width.
1318static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1319 unsigned rotBitWidth = rotateAmt.getBitWidth();
1320 APInt rot = rotateAmt;
1321 if (rotBitWidth < BitWidth) {
1322 // Extend the rotate APInt, so that the urem doesn't divide by 0.
1323 // e.g. APInt(1, 32) would give APInt(1, 0).
1324 rot = rotateAmt.zext(BitWidth);
1325 }
1326 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
1327 return rot.getLimitedValue(BitWidth);
1328}
1329
Dan Gohman105c1d42008-02-29 01:40:47 +00001330APInt APInt::rotl(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001331 return rotl(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001332}
1333
Chris Lattner77527f52009-01-21 18:09:24 +00001334APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001335 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001336 if (rotateAmt == 0)
1337 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001338 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001339}
1340
Dan Gohman105c1d42008-02-29 01:40:47 +00001341APInt APInt::rotr(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001342 return rotr(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001343}
1344
Chris Lattner77527f52009-01-21 18:09:24 +00001345APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001346 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001347 if (rotateAmt == 0)
1348 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001349 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001350}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001351
1352// Square Root - this method computes and returns the square root of "this".
1353// Three mechanisms are used for computation. For small values (<= 5 bits),
1354// a table lookup is done. This gets some performance for common cases. For
1355// values using less than 52 bits, the value is converted to double and then
1356// the libc sqrt function is called. The result is rounded and then converted
1357// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001358// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001359APInt APInt::sqrt() const {
1360
1361 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001362 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001363
1364 // Use a fast table for some small values. This also gets rid of some
1365 // rounding errors in libc sqrt for small values.
1366 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001367 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001368 /* 0 */ 0,
1369 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001370 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001371 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1372 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1373 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1374 /* 31 */ 6
1375 };
1376 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001377 }
1378
1379 // If the magnitude of the value fits in less than 52 bits (the precision of
1380 // an IEEE double precision floating point value), then we can use the
1381 // libc sqrt function which will probably use a hardware sqrt computation.
1382 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001383 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001384 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001385 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001386 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001387
1388 // Okay, all the short cuts are exhausted. We must compute it. The following
1389 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001390 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001391 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001392 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001393 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001394 APInt testy(BitWidth, 16);
1395 APInt x_old(BitWidth, 1);
1396 APInt x_new(BitWidth, 0);
1397 APInt two(BitWidth, 2);
1398
1399 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001400 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001401 if (i >= nbits || this->ule(testy)) {
1402 x_old = x_old.shl(i / 2);
1403 break;
1404 }
1405
Eric Christopher820256b2009-08-21 04:06:45 +00001406 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001407 for (;;) {
1408 x_new = (this->udiv(x_old) + x_old).udiv(two);
1409 if (x_old.ule(x_new))
1410 break;
1411 x_old = x_new;
1412 }
1413
1414 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001415 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001416 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001417 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001418 // floating point representation after 192 bits. There are no discrepancies
1419 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001420 APInt square(x_old * x_old);
1421 APInt nextSquare((x_old + 1) * (x_old +1));
1422 if (this->ult(square))
1423 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001424 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1425 APInt midpoint((nextSquare - square).udiv(two));
1426 APInt offset(*this - square);
1427 if (offset.ult(midpoint))
1428 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001429 return x_old + 1;
1430}
1431
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001432/// Computes the multiplicative inverse of this APInt for a given modulo. The
1433/// iterative extended Euclidean algorithm is used to solve for this value,
1434/// however we simplify it to speed up calculating only the inverse, and take
1435/// advantage of div+rem calculations. We also use some tricks to avoid copying
1436/// (potentially large) APInts around.
1437APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1438 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1439
1440 // Using the properties listed at the following web page (accessed 06/21/08):
1441 // http://www.numbertheory.org/php/euclid.html
1442 // (especially the properties numbered 3, 4 and 9) it can be proved that
1443 // BitWidth bits suffice for all the computations in the algorithm implemented
1444 // below. More precisely, this number of bits suffice if the multiplicative
1445 // inverse exists, but may not suffice for the general extended Euclidean
1446 // algorithm.
1447
1448 APInt r[2] = { modulo, *this };
1449 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1450 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001451
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001452 unsigned i;
1453 for (i = 0; r[i^1] != 0; i ^= 1) {
1454 // An overview of the math without the confusing bit-flipping:
1455 // q = r[i-2] / r[i-1]
1456 // r[i] = r[i-2] % r[i-1]
1457 // t[i] = t[i-2] - t[i-1] * q
1458 udivrem(r[i], r[i^1], q, r[i]);
1459 t[i] -= t[i^1] * q;
1460 }
1461
1462 // If this APInt and the modulo are not coprime, there is no multiplicative
1463 // inverse, so return 0. We check this by looking at the next-to-last
1464 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1465 // algorithm.
1466 if (r[i] != 1)
1467 return APInt(BitWidth, 0);
1468
1469 // The next-to-last t is the multiplicative inverse. However, we are
1470 // interested in a positive inverse. Calcuate a positive one from a negative
1471 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001472 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001473 return t[i].isNegative() ? t[i] + modulo : t[i];
1474}
1475
Jay Foadfe0c6482009-04-30 10:15:35 +00001476/// Calculate the magic numbers required to implement a signed integer division
1477/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1478/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1479/// Warren, Jr., chapter 10.
1480APInt::ms APInt::magic() const {
1481 const APInt& d = *this;
1482 unsigned p;
1483 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001484 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001485 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001486
Jay Foadfe0c6482009-04-30 10:15:35 +00001487 ad = d.abs();
1488 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1489 anc = t - 1 - t.urem(ad); // absolute value of nc
1490 p = d.getBitWidth() - 1; // initialize p
1491 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1492 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1493 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1494 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1495 do {
1496 p = p + 1;
1497 q1 = q1<<1; // update q1 = 2p/abs(nc)
1498 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1499 if (r1.uge(anc)) { // must be unsigned comparison
1500 q1 = q1 + 1;
1501 r1 = r1 - anc;
1502 }
1503 q2 = q2<<1; // update q2 = 2p/abs(d)
1504 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1505 if (r2.uge(ad)) { // must be unsigned comparison
1506 q2 = q2 + 1;
1507 r2 = r2 - ad;
1508 }
1509 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001510 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001511
Jay Foadfe0c6482009-04-30 10:15:35 +00001512 mag.m = q2 + 1;
1513 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1514 mag.s = p - d.getBitWidth(); // resulting shift
1515 return mag;
1516}
1517
1518/// Calculate the magic numbers required to implement an unsigned integer
1519/// division by a constant as a sequence of multiplies, adds and shifts.
1520/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1521/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001522/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001523/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001524APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001525 const APInt& d = *this;
1526 unsigned p;
1527 APInt nc, delta, q1, r1, q2, r2;
1528 struct mu magu;
1529 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001530 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001531 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1532 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1533
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001534 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001535 p = d.getBitWidth() - 1; // initialize p
1536 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1537 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1538 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1539 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1540 do {
1541 p = p + 1;
1542 if (r1.uge(nc - r1)) {
1543 q1 = q1 + q1 + 1; // update q1
1544 r1 = r1 + r1 - nc; // update r1
1545 }
1546 else {
1547 q1 = q1+q1; // update q1
1548 r1 = r1+r1; // update r1
1549 }
1550 if ((r2 + 1).uge(d - r2)) {
1551 if (q2.uge(signedMax)) magu.a = 1;
1552 q2 = q2+q2 + 1; // update q2
1553 r2 = r2+r2 + 1 - d; // update r2
1554 }
1555 else {
1556 if (q2.uge(signedMin)) magu.a = 1;
1557 q2 = q2+q2; // update q2
1558 r2 = r2+r2 + 1; // update r2
1559 }
1560 delta = d - 1 - r2;
1561 } while (p < d.getBitWidth()*2 &&
1562 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1563 magu.m = q2 + 1; // resulting magic number
1564 magu.s = p - d.getBitWidth(); // resulting shift
1565 return magu;
1566}
1567
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001568/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1569/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1570/// variables here have the same names as in the algorithm. Comments explain
1571/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001572static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1573 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001574 assert(u && "Must provide dividend");
1575 assert(v && "Must provide divisor");
1576 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001577 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001578 assert(n>1 && "n must be > 1");
1579
Yaron Keren39fc5a62015-03-26 19:45:19 +00001580 // b denotes the base of the number system. In our case b is 2^32.
George Burgess IV381fc0e2016-08-25 01:05:08 +00001581 const uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001582
David Greenef32fcb42010-01-05 01:28:52 +00001583 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1584 DEBUG(dbgs() << "KnuthDiv: original:");
1585 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1586 DEBUG(dbgs() << " by");
1587 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1588 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001589 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1590 // u and v by d. Note that we have taken Knuth's advice here to use a power
1591 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1592 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001593 // shift amount from the leading zeros. We are basically normalizing the u
1594 // and v so that its high bits are shifted to the top of v's range without
1595 // overflow. Note that this can require an extra word in u so that u must
1596 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001597 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001598 unsigned v_carry = 0;
1599 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001600 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001601 for (unsigned i = 0; i < m+n; ++i) {
1602 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001603 u[i] = (u[i] << shift) | u_carry;
1604 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001605 }
Chris Lattner77527f52009-01-21 18:09:24 +00001606 for (unsigned i = 0; i < n; ++i) {
1607 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001608 v[i] = (v[i] << shift) | v_carry;
1609 v_carry = v_tmp;
1610 }
1611 }
1612 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001613
David Greenef32fcb42010-01-05 01:28:52 +00001614 DEBUG(dbgs() << "KnuthDiv: normal:");
1615 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1616 DEBUG(dbgs() << " by");
1617 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1618 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001619
1620 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1621 int j = m;
1622 do {
David Greenef32fcb42010-01-05 01:28:52 +00001623 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001624 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001625 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1626 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1627 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1628 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1629 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001630 // value qp is one too large, and it eliminates all cases where qp is two
1631 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001632 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001633 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001634 uint64_t qp = dividend / v[n-1];
1635 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001636 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1637 qp--;
1638 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001639 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001640 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001641 }
David Greenef32fcb42010-01-05 01:28:52 +00001642 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001643
Reid Spencercb292e42007-02-23 01:57:13 +00001644 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1645 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1646 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001647 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001648 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1649 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1650 // true value plus b**(n+1), namely as the b's complement of
1651 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001652 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001653 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001654 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1655 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1656 u[j+i] = (unsigned)subres;
1657 borrow = (p >> 32) - (subres >> 32);
1658 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001659 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001660 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001661 bool isNeg = u[j+n] < borrow;
1662 u[j+n] -= (unsigned)borrow;
1663
David Greenef32fcb42010-01-05 01:28:52 +00001664 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1665 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1666 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001667
Eric Christopher820256b2009-08-21 04:06:45 +00001668 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001669 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001670 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001671 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001672 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001673 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001674 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001675 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001676 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1677 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001678 // since it cancels with the borrow that occurred in D4.
1679 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001680 for (unsigned i = 0; i < n; i++) {
1681 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001682 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001683 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001684 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001685 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001686 }
David Greenef32fcb42010-01-05 01:28:52 +00001687 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001688 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001689 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001690
Reid Spencercb292e42007-02-23 01:57:13 +00001691 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1692 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001693
David Greenef32fcb42010-01-05 01:28:52 +00001694 DEBUG(dbgs() << "KnuthDiv: quotient:");
1695 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1696 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001697
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001698 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1699 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1700 // compute the remainder (urem uses this).
1701 if (r) {
1702 // The value d is expressed by the "shift" value above since we avoided
1703 // multiplication by d by using a shift left. So, all we have to do is
Simon Pilgrim0099beb2017-03-09 13:57:04 +00001704 // shift right here.
Reid Spencer468ad9112007-02-24 20:38:01 +00001705 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001706 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001707 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001708 for (int i = n-1; i >= 0; i--) {
1709 r[i] = (u[i] >> shift) | carry;
1710 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001711 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001712 }
1713 } else {
1714 for (int i = n-1; i >= 0; i--) {
1715 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001716 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001717 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001718 }
David Greenef32fcb42010-01-05 01:28:52 +00001719 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001720 }
David Greenef32fcb42010-01-05 01:28:52 +00001721 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001722}
1723
Benjamin Kramerc321e532016-06-08 19:09:22 +00001724void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
1725 unsigned rhsWords, APInt *Quotient, APInt *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001726 assert(lhsWords >= rhsWords && "Fractional result");
1727
Eric Christopher820256b2009-08-21 04:06:45 +00001728 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001729 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001730 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001731 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1732 // can't use 64-bit operands here because we don't have native results of
1733 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001734 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001735 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001736 unsigned n = rhsWords * 2;
1737 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001738
1739 // Allocate space for the temporary values we need either on the stack, if
1740 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001741 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001742 unsigned *U = nullptr;
1743 unsigned *V = nullptr;
1744 unsigned *Q = nullptr;
1745 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001746 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1747 U = &SPACE[0];
1748 V = &SPACE[m+n+1];
1749 Q = &SPACE[(m+n+1) + n];
1750 if (Remainder)
1751 R = &SPACE[(m+n+1) + n + (m+n)];
1752 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001753 U = new unsigned[m + n + 1];
1754 V = new unsigned[n];
1755 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001756 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001757 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001758 }
1759
1760 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001761 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001762 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001763 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001764 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001765 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001766 }
1767 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1768
Reid Spencer522ca7c2007-02-25 01:56:07 +00001769 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001770 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001771 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001772 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001773 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001774 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001775 }
1776
Reid Spencer522ca7c2007-02-25 01:56:07 +00001777 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001778 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001779 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001780 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001781
Eric Christopher820256b2009-08-21 04:06:45 +00001782 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001783 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001784 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001785 // contain any zero words or the Knuth algorithm fails.
1786 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1787 n--;
1788 m++;
1789 }
1790 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1791 m--;
1792
1793 // If we're left with only a single word for the divisor, Knuth doesn't work
1794 // so we implement the short division algorithm here. This is much simpler
1795 // and faster because we are certain that we can divide a 64-bit quantity
1796 // by a 32-bit quantity at hardware speed and short division is simply a
1797 // series of such operations. This is just like doing short division but we
1798 // are using base 2^32 instead of base 10.
1799 assert(n != 0 && "Divide by zero?");
1800 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001801 unsigned divisor = V[0];
1802 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001803 for (int i = m+n-1; i >= 0; i--) {
1804 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1805 if (partial_dividend == 0) {
1806 Q[i] = 0;
1807 remainder = 0;
1808 } else if (partial_dividend < divisor) {
1809 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001810 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001811 } else if (partial_dividend == divisor) {
1812 Q[i] = 1;
1813 remainder = 0;
1814 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001815 Q[i] = (unsigned)(partial_dividend / divisor);
1816 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001817 }
1818 }
1819 if (R)
1820 R[0] = remainder;
1821 } else {
1822 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1823 // case n > 1.
1824 KnuthDiv(U, V, Q, R, m, n);
1825 }
1826
1827 // If the caller wants the quotient
1828 if (Quotient) {
1829 // Set up the Quotient value's memory.
1830 if (Quotient->BitWidth != LHS.BitWidth) {
1831 if (Quotient->isSingleWord())
1832 Quotient->VAL = 0;
1833 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001834 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001835 Quotient->BitWidth = LHS.BitWidth;
1836 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001837 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001838 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001839 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001840
Eric Christopher820256b2009-08-21 04:06:45 +00001841 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001842 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001843 // This case is currently dead as all users of divide() handle trivial cases
1844 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001845 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001846 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001847 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1848 if (Quotient->isSingleWord())
1849 Quotient->VAL = tmp;
1850 else
1851 Quotient->pVal[0] = tmp;
1852 } else {
1853 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1854 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001855 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001856 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1857 }
1858 }
1859
1860 // If the caller wants the remainder
1861 if (Remainder) {
1862 // Set up the Remainder value's memory.
1863 if (Remainder->BitWidth != RHS.BitWidth) {
1864 if (Remainder->isSingleWord())
1865 Remainder->VAL = 0;
1866 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001867 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001868 Remainder->BitWidth = RHS.BitWidth;
1869 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001870 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001871 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001872 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001873
1874 // The remainder is in R. Reconstitute the remainder into Remainder's low
1875 // order words.
1876 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001877 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001878 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1879 if (Remainder->isSingleWord())
1880 Remainder->VAL = tmp;
1881 else
1882 Remainder->pVal[0] = tmp;
1883 } else {
1884 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1885 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001886 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001887 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1888 }
1889 }
1890
1891 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001892 if (U != &SPACE[0]) {
1893 delete [] U;
1894 delete [] V;
1895 delete [] Q;
1896 delete [] R;
1897 }
Reid Spencer100502d2007-02-17 03:16:00 +00001898}
1899
Reid Spencer1d072122007-02-16 22:36:51 +00001900APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001901 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001902
1903 // First, deal with the easy case
1904 if (isSingleWord()) {
1905 assert(RHS.VAL != 0 && "Divide by zero?");
1906 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001907 }
Reid Spencer39867762007-02-17 02:07:07 +00001908
Reid Spencer39867762007-02-17 02:07:07 +00001909 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001910 unsigned rhsBits = RHS.getActiveBits();
1911 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001912 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001913 unsigned lhsBits = this->getActiveBits();
1914 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001915
1916 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001917 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001918 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001919 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001920 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001921 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001922 return APInt(BitWidth, 0);
1923 } else if (*this == RHS) {
1924 // X / X ===> 1
1925 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001926 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001927 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001928 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001929 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001930
1931 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1932 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001933 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001934 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001935}
1936
Jakub Staszak6605c602013-02-20 00:17:42 +00001937APInt APInt::sdiv(const APInt &RHS) const {
1938 if (isNegative()) {
1939 if (RHS.isNegative())
1940 return (-(*this)).udiv(-RHS);
1941 return -((-(*this)).udiv(RHS));
1942 }
1943 if (RHS.isNegative())
1944 return -(this->udiv(-RHS));
1945 return this->udiv(RHS);
1946}
1947
Reid Spencer1d072122007-02-16 22:36:51 +00001948APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001949 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001950 if (isSingleWord()) {
1951 assert(RHS.VAL != 0 && "Remainder by zero?");
1952 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001953 }
Reid Spencer39867762007-02-17 02:07:07 +00001954
Reid Spencer58a6a432007-02-21 08:21:52 +00001955 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001956 unsigned lhsBits = getActiveBits();
1957 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001958
1959 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001960 unsigned rhsBits = RHS.getActiveBits();
1961 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001962 assert(rhsWords && "Performing remainder operation by zero ???");
1963
Reid Spencer39867762007-02-17 02:07:07 +00001964 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001965 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001966 // 0 % Y ===> 0
1967 return APInt(BitWidth, 0);
1968 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001969 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001970 return *this;
1971 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001972 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001973 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001974 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001975 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00001976 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001977 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001978
Reid Spencer4c50b522007-05-13 23:44:59 +00001979 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001980 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001981 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001982 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001983}
Reid Spencer100502d2007-02-17 03:16:00 +00001984
Jakub Staszak6605c602013-02-20 00:17:42 +00001985APInt APInt::srem(const APInt &RHS) const {
1986 if (isNegative()) {
1987 if (RHS.isNegative())
1988 return -((-(*this)).urem(-RHS));
1989 return -((-(*this)).urem(RHS));
1990 }
1991 if (RHS.isNegative())
1992 return this->urem(-RHS);
1993 return this->urem(RHS);
1994}
1995
Eric Christopher820256b2009-08-21 04:06:45 +00001996void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001997 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001998 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1999
2000 // First, deal with the easy case
2001 if (LHS.isSingleWord()) {
2002 assert(RHS.VAL != 0 && "Divide by zero?");
2003 uint64_t QuotVal = LHS.VAL / RHS.VAL;
2004 uint64_t RemVal = LHS.VAL % RHS.VAL;
2005 Quotient = APInt(LHS.BitWidth, QuotVal);
2006 Remainder = APInt(LHS.BitWidth, RemVal);
2007 return;
2008 }
2009
Reid Spencer4c50b522007-05-13 23:44:59 +00002010 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00002011 unsigned lhsBits = LHS.getActiveBits();
2012 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
2013 unsigned rhsBits = RHS.getActiveBits();
2014 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00002015
2016 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00002017 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00002018 Quotient = 0; // 0 / Y ===> 0
2019 Remainder = 0; // 0 % Y ===> 0
2020 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002021 }
2022
2023 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002024 Remainder = LHS; // X % Y ===> X, iff X < Y
2025 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00002026 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002027 }
2028
Reid Spencer4c50b522007-05-13 23:44:59 +00002029 if (LHS == RHS) {
2030 Quotient = 1; // X / X ===> 1
2031 Remainder = 0; // X % X ===> 0;
2032 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002033 }
2034
Reid Spencer4c50b522007-05-13 23:44:59 +00002035 if (lhsWords == 1 && rhsWords == 1) {
2036 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00002037 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
2038 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
2039 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
2040 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00002041 return;
2042 }
2043
2044 // Okay, lets do it the long way
2045 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
2046}
2047
Jakub Staszak6605c602013-02-20 00:17:42 +00002048void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
2049 APInt &Quotient, APInt &Remainder) {
2050 if (LHS.isNegative()) {
2051 if (RHS.isNegative())
2052 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
2053 else {
2054 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
2055 Quotient = -Quotient;
2056 }
2057 Remainder = -Remainder;
2058 } else if (RHS.isNegative()) {
2059 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
2060 Quotient = -Quotient;
2061 } else {
2062 APInt::udivrem(LHS, RHS, Quotient, Remainder);
2063 }
2064}
2065
Chris Lattner2c819b02010-10-13 23:54:10 +00002066APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002067 APInt Res = *this+RHS;
2068 Overflow = isNonNegative() == RHS.isNonNegative() &&
2069 Res.isNonNegative() != isNonNegative();
2070 return Res;
2071}
2072
Chris Lattner698661c2010-10-14 00:05:07 +00002073APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
2074 APInt Res = *this+RHS;
2075 Overflow = Res.ult(RHS);
2076 return Res;
2077}
2078
Chris Lattner2c819b02010-10-13 23:54:10 +00002079APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002080 APInt Res = *this - RHS;
2081 Overflow = isNonNegative() != RHS.isNonNegative() &&
2082 Res.isNonNegative() != isNonNegative();
2083 return Res;
2084}
2085
Chris Lattner698661c2010-10-14 00:05:07 +00002086APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00002087 APInt Res = *this-RHS;
2088 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00002089 return Res;
2090}
2091
Chris Lattner2c819b02010-10-13 23:54:10 +00002092APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002093 // MININT/-1 --> overflow.
2094 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
2095 return sdiv(RHS);
2096}
2097
Chris Lattner2c819b02010-10-13 23:54:10 +00002098APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002099 APInt Res = *this * RHS;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002100
Chris Lattner79bdd882010-10-13 23:46:33 +00002101 if (*this != 0 && RHS != 0)
2102 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
2103 else
2104 Overflow = false;
2105 return Res;
2106}
2107
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00002108APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
2109 APInt Res = *this * RHS;
2110
2111 if (*this != 0 && RHS != 0)
2112 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
2113 else
2114 Overflow = false;
2115 return Res;
2116}
2117
David Majnemera2521382014-10-13 21:48:30 +00002118APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
2119 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00002120 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00002121 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00002122
2123 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00002124 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00002125 else
David Majnemera2521382014-10-13 21:48:30 +00002126 Overflow = ShAmt.uge(countLeadingOnes());
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002127
Chris Lattner79bdd882010-10-13 23:46:33 +00002128 return *this << ShAmt;
2129}
2130
David Majnemera2521382014-10-13 21:48:30 +00002131APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
2132 Overflow = ShAmt.uge(getBitWidth());
2133 if (Overflow)
2134 return APInt(BitWidth, 0);
2135
2136 Overflow = ShAmt.ugt(countLeadingZeros());
2137
2138 return *this << ShAmt;
2139}
2140
Chris Lattner79bdd882010-10-13 23:46:33 +00002141
2142
2143
Benjamin Kramer92d89982010-07-14 22:38:02 +00002144void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00002145 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002146 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002147 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002148 radix == 36) &&
2149 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002150
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002151 StringRef::iterator p = str.begin();
2152 size_t slen = str.size();
2153 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002154 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002155 p++;
2156 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00002157 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002158 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00002159 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002160 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2161 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002162 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2163 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00002164
2165 // Allocate memory
2166 if (!isSingleWord())
2167 pVal = getClearedMemory(getNumWords());
2168
2169 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00002170 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00002171
2172 // Set up an APInt for the digit to add outside the loop so we don't
2173 // constantly construct/destruct it.
2174 APInt apdigit(getBitWidth(), 0);
2175 APInt apradix(getBitWidth(), radix);
2176
2177 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002178 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00002179 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00002180 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00002181
Reid Spencera93c9812007-05-16 19:18:22 +00002182 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002183 if (slen > 1) {
2184 if (shift)
2185 *this <<= shift;
2186 else
2187 *this *= apradix;
2188 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002189
2190 // Add in the digit we just interpreted
Reid Spencer632ebdf2007-02-24 20:19:37 +00002191 if (apdigit.isSingleWord())
2192 apdigit.VAL = digit;
2193 else
2194 apdigit.pVal[0] = digit;
Reid Spencer1ba83352007-02-21 03:55:44 +00002195 *this += apdigit;
Reid Spencer100502d2007-02-17 03:16:00 +00002196 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002197 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00002198 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00002199 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002200 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002201 }
Reid Spencer100502d2007-02-17 03:16:00 +00002202}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002203
Chris Lattner17f71652008-08-17 07:19:36 +00002204void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002205 bool Signed, bool formatAsCLiteral) const {
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002206 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002207 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002208 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002209
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002210 const char *Prefix = "";
2211 if (formatAsCLiteral) {
2212 switch (Radix) {
2213 case 2:
2214 // Binary literals are a non-standard extension added in gcc 4.3:
2215 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2216 Prefix = "0b";
2217 break;
2218 case 8:
2219 Prefix = "0";
2220 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002221 case 10:
2222 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002223 case 16:
2224 Prefix = "0x";
2225 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002226 default:
2227 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002228 }
2229 }
2230
Chris Lattner17f71652008-08-17 07:19:36 +00002231 // First, check for a zero value and just short circuit the logic below.
2232 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002233 while (*Prefix) {
2234 Str.push_back(*Prefix);
2235 ++Prefix;
2236 };
Chris Lattner17f71652008-08-17 07:19:36 +00002237 Str.push_back('0');
2238 return;
2239 }
Eric Christopher820256b2009-08-21 04:06:45 +00002240
Douglas Gregor663c0682011-09-14 15:54:46 +00002241 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002242
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002243 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002244 char Buffer[65];
2245 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002246
Chris Lattner17f71652008-08-17 07:19:36 +00002247 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002248 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002249 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002250 } else {
2251 int64_t I = getSExtValue();
2252 if (I >= 0) {
2253 N = I;
2254 } else {
2255 Str.push_back('-');
2256 N = -(uint64_t)I;
2257 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002258 }
Eric Christopher820256b2009-08-21 04:06:45 +00002259
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002260 while (*Prefix) {
2261 Str.push_back(*Prefix);
2262 ++Prefix;
2263 };
2264
Chris Lattner17f71652008-08-17 07:19:36 +00002265 while (N) {
2266 *--BufPtr = Digits[N % Radix];
2267 N /= Radix;
2268 }
2269 Str.append(BufPtr, Buffer+65);
2270 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002271 }
2272
Chris Lattner17f71652008-08-17 07:19:36 +00002273 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002274
Chris Lattner17f71652008-08-17 07:19:36 +00002275 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002276 // They want to print the signed version and it is a negative value
2277 // Flip the bits and add one to turn it into the equivalent positive
2278 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002279 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002280 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002281 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002282 }
Eric Christopher820256b2009-08-21 04:06:45 +00002283
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002284 while (*Prefix) {
2285 Str.push_back(*Prefix);
2286 ++Prefix;
2287 };
2288
Chris Lattner17f71652008-08-17 07:19:36 +00002289 // We insert the digits backward, then reverse them to get the right order.
2290 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002291
2292 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2293 // because the number of bits per digit (1, 3 and 4 respectively) divides
Chris Lattner17f71652008-08-17 07:19:36 +00002294 // equaly. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002295 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002296 // Just shift tmp right for each digit width until it becomes zero
2297 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2298 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002299
Chris Lattner17f71652008-08-17 07:19:36 +00002300 while (Tmp != 0) {
2301 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2302 Str.push_back(Digits[Digit]);
2303 Tmp = Tmp.lshr(ShiftAmt);
2304 }
2305 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002306 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002307 while (Tmp != 0) {
2308 APInt APdigit(1, 0);
2309 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002310 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002311 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002312 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002313 assert(Digit < Radix && "divide failed");
2314 Str.push_back(Digits[Digit]);
2315 Tmp = tmp2;
2316 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002317 }
Eric Christopher820256b2009-08-21 04:06:45 +00002318
Chris Lattner17f71652008-08-17 07:19:36 +00002319 // Reverse the digits before returning.
2320 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002321}
2322
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002323/// Returns the APInt as a std::string. Note that this is an inefficient method.
2324/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002325std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2326 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002327 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002328 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002329}
Chris Lattner6b695682007-08-16 15:56:55 +00002330
Matthias Braun8c209aa2017-01-28 02:02:38 +00002331#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002332LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002333 SmallString<40> S, U;
2334 this->toStringUnsigned(U);
2335 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002336 dbgs() << "APInt(" << BitWidth << "b, "
Davide Italiano5a473d22017-01-31 21:26:18 +00002337 << U << "u " << S << "s)\n";
Chris Lattner17f71652008-08-17 07:19:36 +00002338}
Matthias Braun8c209aa2017-01-28 02:02:38 +00002339#endif
Chris Lattner17f71652008-08-17 07:19:36 +00002340
Chris Lattner0c19df42008-08-23 22:23:09 +00002341void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002342 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002343 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002344 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002345}
2346
Chris Lattner6b695682007-08-16 15:56:55 +00002347// This implements a variety of operations on a representation of
2348// arbitrary precision, two's-complement, bignum integer values.
2349
Chris Lattner96cffa62009-08-23 23:11:28 +00002350// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2351// and unrestricting assumption.
Benjamin Kramer7000ca32014-10-12 17:56:40 +00002352static_assert(integerPartWidth % 2 == 0, "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002353
2354/* Some handy functions local to this file. */
Chris Lattner6b695682007-08-16 15:56:55 +00002355
Craig Topper76f42462017-03-28 05:32:53 +00002356/* Returns the integer part with the least significant BITS set.
2357 BITS cannot be zero. */
Craig Topper6a8518082017-03-28 05:32:55 +00002358static inline integerPart lowBitMask(unsigned bits) {
Craig Topper76f42462017-03-28 05:32:53 +00002359 assert(bits != 0 && bits <= integerPartWidth);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002360
Craig Topper76f42462017-03-28 05:32:53 +00002361 return ~(integerPart) 0 >> (integerPartWidth - bits);
2362}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002363
Craig Topper76f42462017-03-28 05:32:53 +00002364/* Returns the value of the lower half of PART. */
Craig Topper6a8518082017-03-28 05:32:55 +00002365static inline integerPart lowHalf(integerPart part) {
Craig Topper76f42462017-03-28 05:32:53 +00002366 return part & lowBitMask(integerPartWidth / 2);
2367}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002368
Craig Topper76f42462017-03-28 05:32:53 +00002369/* Returns the value of the upper half of PART. */
Craig Topper6a8518082017-03-28 05:32:55 +00002370static inline integerPart highHalf(integerPart part) {
Craig Topper76f42462017-03-28 05:32:53 +00002371 return part >> (integerPartWidth / 2);
2372}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002373
Craig Topper76f42462017-03-28 05:32:53 +00002374/* Returns the bit number of the most significant set bit of a part.
2375 If the input number has no bits set -1U is returned. */
Craig Topper6a8518082017-03-28 05:32:55 +00002376static unsigned partMSB(integerPart value) {
Craig Topper76f42462017-03-28 05:32:53 +00002377 return findLastSet(value, ZB_Max);
2378}
Chris Lattner6b695682007-08-16 15:56:55 +00002379
Craig Topper76f42462017-03-28 05:32:53 +00002380/* Returns the bit number of the least significant set bit of a
2381 part. If the input number has no bits set -1U is returned. */
Craig Topper6a8518082017-03-28 05:32:55 +00002382static unsigned partLSB(integerPart value) {
Craig Topper76f42462017-03-28 05:32:53 +00002383 return findFirstSet(value, ZB_Max);
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002384}
Chris Lattner6b695682007-08-16 15:56:55 +00002385
2386/* Sets the least significant part of a bignum to the input value, and
2387 zeroes out higher parts. */
Craig Topper6a8518082017-03-28 05:32:55 +00002388void APInt::tcSet(integerPart *dst, integerPart part, unsigned parts) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002389 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002390
Chris Lattner6b695682007-08-16 15:56:55 +00002391 dst[0] = part;
Craig Topperb0038162017-03-28 05:32:52 +00002392 for (unsigned i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002393 dst[i] = 0;
2394}
2395
2396/* Assign one bignum to another. */
Craig Topper6a8518082017-03-28 05:32:55 +00002397void APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002398 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002399 dst[i] = src[i];
2400}
2401
2402/* Returns true if a bignum is zero, false otherwise. */
Craig Topper6a8518082017-03-28 05:32:55 +00002403bool APInt::tcIsZero(const integerPart *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002404 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002405 if (src[i])
2406 return false;
2407
2408 return true;
2409}
2410
2411/* Extract the given bit of a bignum; returns 0 or 1. */
Craig Topper6a8518082017-03-28 05:32:55 +00002412int APInt::tcExtractBit(const integerPart *parts, unsigned bit) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002413 return (parts[bit / integerPartWidth] &
2414 ((integerPart) 1 << bit % integerPartWidth)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002415}
2416
John McCalldcb9a7a2010-02-28 02:51:25 +00002417/* Set the given bit of a bignum. */
Craig Topper6a8518082017-03-28 05:32:55 +00002418void APInt::tcSetBit(integerPart *parts, unsigned bit) {
Chris Lattner6b695682007-08-16 15:56:55 +00002419 parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
2420}
2421
John McCalldcb9a7a2010-02-28 02:51:25 +00002422/* Clears the given bit of a bignum. */
Craig Topper6a8518082017-03-28 05:32:55 +00002423void APInt::tcClearBit(integerPart *parts, unsigned bit) {
John McCalldcb9a7a2010-02-28 02:51:25 +00002424 parts[bit / integerPartWidth] &=
2425 ~((integerPart) 1 << (bit % integerPartWidth));
2426}
2427
Neil Boothc8b650a2007-10-06 00:43:45 +00002428/* Returns the bit number of the least significant set bit of a
2429 number. If the input number has no bits set -1U is returned. */
Craig Topper6a8518082017-03-28 05:32:55 +00002430unsigned APInt::tcLSB(const integerPart *parts, unsigned n) {
Craig Topperb0038162017-03-28 05:32:52 +00002431 for (unsigned i = 0; i < n; i++) {
2432 if (parts[i] != 0) {
2433 unsigned lsb = partLSB(parts[i]);
Chris Lattner6b695682007-08-16 15:56:55 +00002434
Craig Topperb0038162017-03-28 05:32:52 +00002435 return lsb + i * integerPartWidth;
2436 }
Chris Lattner6b695682007-08-16 15:56:55 +00002437 }
2438
2439 return -1U;
2440}
2441
Neil Boothc8b650a2007-10-06 00:43:45 +00002442/* Returns the bit number of the most significant set bit of a number.
2443 If the input number has no bits set -1U is returned. */
Craig Topper6a8518082017-03-28 05:32:55 +00002444unsigned APInt::tcMSB(const integerPart *parts, unsigned n) {
Chris Lattner6b695682007-08-16 15:56:55 +00002445 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002446 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002447
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002448 if (parts[n] != 0) {
Craig Topperb0038162017-03-28 05:32:52 +00002449 unsigned msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002450
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002451 return msb + n * integerPartWidth;
2452 }
Chris Lattner6b695682007-08-16 15:56:55 +00002453 } while (n);
2454
2455 return -1U;
2456}
2457
Neil Boothb6182162007-10-08 13:47:12 +00002458/* Copy the bit vector of width srcBITS from SRC, starting at bit
2459 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2460 the least significant bit of DST. All high bits above srcBITS in
2461 DST are zero-filled. */
2462void
Craig Topper6a8518082017-03-28 05:32:55 +00002463APInt::tcExtract(integerPart *dst, unsigned dstCount, const integerPart *src,
2464 unsigned srcBits, unsigned srcLSB) {
Craig Topperb0038162017-03-28 05:32:52 +00002465 unsigned dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002466 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002467
Craig Topperb0038162017-03-28 05:32:52 +00002468 unsigned firstSrcPart = srcLSB / integerPartWidth;
Neil Boothb6182162007-10-08 13:47:12 +00002469 tcAssign (dst, src + firstSrcPart, dstParts);
2470
Craig Topperb0038162017-03-28 05:32:52 +00002471 unsigned shift = srcLSB % integerPartWidth;
Neil Boothb6182162007-10-08 13:47:12 +00002472 tcShiftRight (dst, dstParts, shift);
2473
2474 /* We now have (dstParts * integerPartWidth - shift) bits from SRC
2475 in DST. If this is less that srcBits, append the rest, else
2476 clear the high bits. */
Craig Topperb0038162017-03-28 05:32:52 +00002477 unsigned n = dstParts * integerPartWidth - shift;
Neil Boothb6182162007-10-08 13:47:12 +00002478 if (n < srcBits) {
2479 integerPart mask = lowBitMask (srcBits - n);
2480 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2481 << n % integerPartWidth);
2482 } else if (n > srcBits) {
Neil Booth7e74b172007-10-12 15:31:31 +00002483 if (srcBits % integerPartWidth)
2484 dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
Neil Boothb6182162007-10-08 13:47:12 +00002485 }
2486
2487 /* Clear high parts. */
2488 while (dstParts < dstCount)
2489 dst[dstParts++] = 0;
2490}
2491
Chris Lattner6b695682007-08-16 15:56:55 +00002492/* DST += RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper6a8518082017-03-28 05:32:55 +00002493integerPart APInt::tcAdd(integerPart *dst, const integerPart *rhs,
2494 integerPart c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002495 assert(c <= 1);
2496
Craig Topperb0038162017-03-28 05:32:52 +00002497 for (unsigned i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002498 integerPart l;
2499
2500 l = dst[i];
2501 if (c) {
2502 dst[i] += rhs[i] + 1;
2503 c = (dst[i] <= l);
2504 } else {
2505 dst[i] += rhs[i];
2506 c = (dst[i] < l);
2507 }
2508 }
2509
2510 return c;
2511}
2512
2513/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper6a8518082017-03-28 05:32:55 +00002514integerPart APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
2515 integerPart c, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002516{
Chris Lattner6b695682007-08-16 15:56:55 +00002517 assert(c <= 1);
2518
Craig Topperb0038162017-03-28 05:32:52 +00002519 for (unsigned i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002520 integerPart l;
2521
2522 l = dst[i];
2523 if (c) {
2524 dst[i] -= rhs[i] + 1;
2525 c = (dst[i] >= l);
2526 } else {
2527 dst[i] -= rhs[i];
2528 c = (dst[i] > l);
2529 }
2530 }
2531
2532 return c;
2533}
2534
2535/* Negate a bignum in-place. */
Craig Topper6a8518082017-03-28 05:32:55 +00002536void APInt::tcNegate(integerPart *dst, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002537 tcComplement(dst, parts);
2538 tcIncrement(dst, parts);
2539}
2540
Neil Boothc8b650a2007-10-06 00:43:45 +00002541/* DST += SRC * MULTIPLIER + CARRY if add is true
2542 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002543
2544 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2545 they must start at the same point, i.e. DST == SRC.
2546
2547 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2548 returned. Otherwise DST is filled with the least significant
2549 DSTPARTS parts of the result, and if all of the omitted higher
2550 parts were zero return zero, otherwise overflow occurred and
2551 return one. */
Craig Topper6a8518082017-03-28 05:32:55 +00002552int APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
2553 integerPart multiplier, integerPart carry,
2554 unsigned srcParts, unsigned dstParts,
2555 bool add) {
Chris Lattner6b695682007-08-16 15:56:55 +00002556 /* Otherwise our writes of DST kill our later reads of SRC. */
2557 assert(dst <= src || dst >= src + srcParts);
2558 assert(dstParts <= srcParts + 1);
2559
2560 /* N loops; minimum of dstParts and srcParts. */
Craig Topperb0038162017-03-28 05:32:52 +00002561 unsigned n = dstParts < srcParts ? dstParts: srcParts;
Chris Lattner6b695682007-08-16 15:56:55 +00002562
Craig Topperb0038162017-03-28 05:32:52 +00002563 unsigned i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002564 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002565 integerPart low, mid, high, srcPart;
2566
2567 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2568
2569 This cannot overflow, because
2570
2571 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2572
2573 which is less than n^2. */
2574
2575 srcPart = src[i];
2576
Craig Topper6a8518082017-03-28 05:32:55 +00002577 if (multiplier == 0 || srcPart == 0) {
Chris Lattner6b695682007-08-16 15:56:55 +00002578 low = carry;
2579 high = 0;
2580 } else {
2581 low = lowHalf(srcPart) * lowHalf(multiplier);
2582 high = highHalf(srcPart) * highHalf(multiplier);
2583
2584 mid = lowHalf(srcPart) * highHalf(multiplier);
2585 high += highHalf(mid);
2586 mid <<= integerPartWidth / 2;
2587 if (low + mid < low)
2588 high++;
2589 low += mid;
2590
2591 mid = highHalf(srcPart) * lowHalf(multiplier);
2592 high += highHalf(mid);
2593 mid <<= integerPartWidth / 2;
2594 if (low + mid < low)
2595 high++;
2596 low += mid;
2597
2598 /* Now add carry. */
2599 if (low + carry < low)
2600 high++;
2601 low += carry;
2602 }
2603
2604 if (add) {
2605 /* And now DST[i], and store the new low part there. */
2606 if (low + dst[i] < low)
2607 high++;
2608 dst[i] += low;
2609 } else
2610 dst[i] = low;
2611
2612 carry = high;
2613 }
2614
2615 if (i < dstParts) {
2616 /* Full multiplication, there is no overflow. */
2617 assert(i + 1 == dstParts);
2618 dst[i] = carry;
2619 return 0;
2620 } else {
2621 /* We overflowed if there is carry. */
2622 if (carry)
2623 return 1;
2624
2625 /* We would overflow if any significant unwritten parts would be
2626 non-zero. This is true if any remaining src parts are non-zero
2627 and the multiplier is non-zero. */
2628 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002629 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002630 if (src[i])
2631 return 1;
2632
2633 /* We fitted in the narrow destination. */
2634 return 0;
2635 }
2636}
2637
2638/* DST = LHS * RHS, where DST has the same width as the operands and
2639 is filled with the least significant parts of the result. Returns
2640 one if overflow occurred, otherwise zero. DST must be disjoint
2641 from both operands. */
Craig Topper6a8518082017-03-28 05:32:55 +00002642int APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
2643 const integerPart *rhs, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002644 assert(dst != lhs && dst != rhs);
2645
Craig Topperb0038162017-03-28 05:32:52 +00002646 int overflow = 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002647 tcSet(dst, 0, parts);
2648
Craig Topperb0038162017-03-28 05:32:52 +00002649 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002650 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2651 parts - i, true);
2652
2653 return overflow;
2654}
2655
Neil Booth0ea72a92007-10-06 00:24:48 +00002656/* DST = LHS * RHS, where DST has width the sum of the widths of the
2657 operands. No overflow occurs. DST must be disjoint from both
2658 operands. Returns the number of parts required to hold the
2659 result. */
Craig Topper6a8518082017-03-28 05:32:55 +00002660unsigned APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
2661 const integerPart *rhs, unsigned lhsParts,
2662 unsigned rhsParts) {
Neil Booth0ea72a92007-10-06 00:24:48 +00002663 /* Put the narrower number on the LHS for less loops below. */
2664 if (lhsParts > rhsParts) {
2665 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2666 } else {
Neil Booth0ea72a92007-10-06 00:24:48 +00002667 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002668
Neil Booth0ea72a92007-10-06 00:24:48 +00002669 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002670
Craig Topperb0038162017-03-28 05:32:52 +00002671 for (unsigned i = 0; i < lhsParts; i++)
2672 tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002673
Craig Topperb0038162017-03-28 05:32:52 +00002674 unsigned n = lhsParts + rhsParts;
Neil Booth0ea72a92007-10-06 00:24:48 +00002675
2676 return n - (dst[n - 1] == 0);
2677 }
Chris Lattner6b695682007-08-16 15:56:55 +00002678}
2679
2680/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2681 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2682 set REMAINDER to the remainder, return zero. i.e.
2683
2684 OLD_LHS = RHS * LHS + REMAINDER
2685
2686 SCRATCH is a bignum of the same size as the operands and result for
2687 use by the routine; its contents need not be initialized and are
2688 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2689*/
Craig Topper6a8518082017-03-28 05:32:55 +00002690int APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
2691 integerPart *remainder, integerPart *srhs,
2692 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002693 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2694
Craig Topperb0038162017-03-28 05:32:52 +00002695 unsigned shiftCount = tcMSB(rhs, parts) + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002696 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002697 return true;
2698
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002699 shiftCount = parts * integerPartWidth - shiftCount;
Craig Topperb0038162017-03-28 05:32:52 +00002700 unsigned n = shiftCount / integerPartWidth;
2701 integerPart mask = (integerPart) 1 << (shiftCount % integerPartWidth);
Chris Lattner6b695682007-08-16 15:56:55 +00002702
2703 tcAssign(srhs, rhs, parts);
2704 tcShiftLeft(srhs, parts, shiftCount);
2705 tcAssign(remainder, lhs, parts);
2706 tcSet(lhs, 0, parts);
2707
2708 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2709 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002710 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002711 int compare;
2712
2713 compare = tcCompare(remainder, srhs, parts);
2714 if (compare >= 0) {
2715 tcSubtract(remainder, srhs, 0, parts);
2716 lhs[n] |= mask;
2717 }
2718
2719 if (shiftCount == 0)
2720 break;
2721 shiftCount--;
2722 tcShiftRight(srhs, parts, 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002723 if ((mask >>= 1) == 0) {
2724 mask = (integerPart) 1 << (integerPartWidth - 1);
2725 n--;
2726 }
Chris Lattner6b695682007-08-16 15:56:55 +00002727 }
2728
2729 return false;
2730}
2731
2732/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2733 There are no restrictions on COUNT. */
Craig Topper6a8518082017-03-28 05:32:55 +00002734void APInt::tcShiftLeft(integerPart *dst, unsigned parts, unsigned count) {
Neil Boothb6182162007-10-08 13:47:12 +00002735 if (count) {
Neil Boothb6182162007-10-08 13:47:12 +00002736 /* Jump is the inter-part jump; shift is is intra-part shift. */
Craig Topperb0038162017-03-28 05:32:52 +00002737 unsigned jump = count / integerPartWidth;
2738 unsigned shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002739
Neil Boothb6182162007-10-08 13:47:12 +00002740 while (parts > jump) {
2741 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002742
Neil Boothb6182162007-10-08 13:47:12 +00002743 parts--;
Chris Lattner6b695682007-08-16 15:56:55 +00002744
Neil Boothb6182162007-10-08 13:47:12 +00002745 /* dst[i] comes from the two parts src[i - jump] and, if we have
2746 an intra-part shift, src[i - jump - 1]. */
2747 part = dst[parts - jump];
2748 if (shift) {
2749 part <<= shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002750 if (parts >= jump + 1)
2751 part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
2752 }
2753
Neil Boothb6182162007-10-08 13:47:12 +00002754 dst[parts] = part;
2755 }
Chris Lattner6b695682007-08-16 15:56:55 +00002756
Neil Boothb6182162007-10-08 13:47:12 +00002757 while (parts > 0)
2758 dst[--parts] = 0;
2759 }
Chris Lattner6b695682007-08-16 15:56:55 +00002760}
2761
2762/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2763 zero. There are no restrictions on COUNT. */
Craig Topper6a8518082017-03-28 05:32:55 +00002764void APInt::tcShiftRight(integerPart *dst, unsigned parts, unsigned count) {
Neil Boothb6182162007-10-08 13:47:12 +00002765 if (count) {
Neil Boothb6182162007-10-08 13:47:12 +00002766 /* Jump is the inter-part jump; shift is is intra-part shift. */
Craig Topperb0038162017-03-28 05:32:52 +00002767 unsigned jump = count / integerPartWidth;
2768 unsigned shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002769
Neil Boothb6182162007-10-08 13:47:12 +00002770 /* Perform the shift. This leaves the most significant COUNT bits
2771 of the result at zero. */
Craig Topperb0038162017-03-28 05:32:52 +00002772 for (unsigned i = 0; i < parts; i++) {
Neil Boothb6182162007-10-08 13:47:12 +00002773 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002774
Neil Boothb6182162007-10-08 13:47:12 +00002775 if (i + jump >= parts) {
2776 part = 0;
2777 } else {
2778 part = dst[i + jump];
2779 if (shift) {
2780 part >>= shift;
2781 if (i + jump + 1 < parts)
2782 part |= dst[i + jump + 1] << (integerPartWidth - shift);
2783 }
Chris Lattner6b695682007-08-16 15:56:55 +00002784 }
Chris Lattner6b695682007-08-16 15:56:55 +00002785
Neil Boothb6182162007-10-08 13:47:12 +00002786 dst[i] = part;
2787 }
Chris Lattner6b695682007-08-16 15:56:55 +00002788 }
2789}
2790
2791/* Bitwise and of two bignums. */
Craig Topper6a8518082017-03-28 05:32:55 +00002792void APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002793 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002794 dst[i] &= rhs[i];
2795}
2796
2797/* Bitwise inclusive or of two bignums. */
Craig Topper6a8518082017-03-28 05:32:55 +00002798void APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002799 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002800 dst[i] |= rhs[i];
2801}
2802
2803/* Bitwise exclusive or of two bignums. */
Craig Topper6a8518082017-03-28 05:32:55 +00002804void APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002805 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002806 dst[i] ^= rhs[i];
2807}
2808
2809/* Complement a bignum in-place. */
Craig Topper6a8518082017-03-28 05:32:55 +00002810void APInt::tcComplement(integerPart *dst, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002811 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002812 dst[i] = ~dst[i];
2813}
2814
2815/* Comparison (unsigned) of two bignums. */
Craig Topper6a8518082017-03-28 05:32:55 +00002816int APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
2817 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002818 while (parts) {
Craig Topper99cfe4f2017-04-01 21:50:06 +00002819 parts--;
2820 if (lhs[parts] == rhs[parts])
2821 continue;
Chris Lattner6b695682007-08-16 15:56:55 +00002822
Craig Topper99cfe4f2017-04-01 21:50:06 +00002823 if (lhs[parts] > rhs[parts])
2824 return 1;
2825 else
2826 return -1;
2827 }
Chris Lattner6b695682007-08-16 15:56:55 +00002828
2829 return 0;
2830}
2831
2832/* Increment a bignum in-place, return the carry flag. */
Craig Topper6a8518082017-03-28 05:32:55 +00002833integerPart APInt::tcIncrement(integerPart *dst, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002834 unsigned i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002835 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002836 if (++dst[i] != 0)
2837 break;
2838
2839 return i == parts;
2840}
2841
Michael Gottesman9d406f42013-05-28 19:50:20 +00002842/* Decrement a bignum in-place, return the borrow flag. */
Craig Topper6a8518082017-03-28 05:32:55 +00002843integerPart APInt::tcDecrement(integerPart *dst, unsigned parts) {
Craig Topper592b1342017-03-28 05:32:48 +00002844 for (unsigned i = 0; i < parts; i++) {
Michael Gottesman9d406f42013-05-28 19:50:20 +00002845 // If the current word is non-zero, then the decrement has no effect on the
2846 // higher-order words of the integer and no borrow can occur. Exit early.
2847 if (dst[i]--)
2848 return 0;
2849 }
2850 // If every word was zero, then there is a borrow.
2851 return 1;
2852}
2853
2854
Chris Lattner6b695682007-08-16 15:56:55 +00002855/* Set the least significant BITS bits of a bignum, clear the
2856 rest. */
Craig Topper6a8518082017-03-28 05:32:55 +00002857void APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned parts,
2858 unsigned bits) {
Craig Topperb0038162017-03-28 05:32:52 +00002859 unsigned i = 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002860 while (bits > integerPartWidth) {
2861 dst[i++] = ~(integerPart) 0;
2862 bits -= integerPartWidth;
2863 }
2864
2865 if (bits)
2866 dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
2867
2868 while (i < parts)
2869 dst[i++] = 0;
2870}