blob: 58fa2f53690ac8b89bd730d2a1c77108f3634e96 [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
Zhou Shengdac63782007-02-06 03:00:16 +0000160APInt& APInt::operator=(uint64_t RHS) {
Eric Christopher820256b2009-08-21 04:06:45 +0000161 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000162 VAL = RHS;
Zhou Shengdac63782007-02-06 03:00:16 +0000163 else {
164 pVal[0] = RHS;
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000165 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000166 }
Reid Spencer7c16cd22007-02-26 23:38:21 +0000167 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000168}
169
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000170/// This method 'profiles' an APInt for use with FoldingSet.
Ted Kremenek5c75d542008-01-19 04:23:33 +0000171void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremenek901540f2008-02-19 20:50:41 +0000172 ID.AddInteger(BitWidth);
Eric Christopher820256b2009-08-21 04:06:45 +0000173
Ted Kremenek5c75d542008-01-19 04:23:33 +0000174 if (isSingleWord()) {
175 ID.AddInteger(VAL);
176 return;
177 }
178
Chris Lattner77527f52009-01-21 18:09:24 +0000179 unsigned NumWords = getNumWords();
Ted Kremenek5c75d542008-01-19 04:23:33 +0000180 for (unsigned i = 0; i < NumWords; ++i)
181 ID.AddInteger(pVal[i]);
182}
183
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000184/// This function adds a single "digit" integer, y, to the multiple
Reid Spencera856b6e2007-02-18 18:38:44 +0000185/// "digit" integer array, x[]. x[] is modified to reflect the addition and
186/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer100502d2007-02-17 03:16:00 +0000187/// @returns the carry of the addition.
Chris Lattner77527f52009-01-21 18:09:24 +0000188static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
189 for (unsigned i = 0; i < len; ++i) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000190 dest[i] = y + x[i];
191 if (dest[i] < y)
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000192 y = 1; // Carry one to next digit.
Reid Spenceree0a6852007-02-18 06:39:42 +0000193 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000194 y = 0; // No need to carry so exit early
Reid Spenceree0a6852007-02-18 06:39:42 +0000195 break;
196 }
Reid Spencer100502d2007-02-17 03:16:00 +0000197 }
Reid Spenceree0a6852007-02-18 06:39:42 +0000198 return y;
Reid Spencer100502d2007-02-17 03:16:00 +0000199}
200
Zhou Shengdac63782007-02-06 03:00:16 +0000201/// @brief Prefix increment operator. Increments the APInt by one.
202APInt& APInt::operator++() {
Eric Christopher820256b2009-08-21 04:06:45 +0000203 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000204 ++VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000205 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000206 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000207 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000208}
209
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000210/// This function subtracts a single "digit" (64-bit word), y, from
Eric Christopher820256b2009-08-21 04:06:45 +0000211/// the multi-digit integer array, x[], propagating the borrowed 1 value until
Joerg Sonnenbergerd7baada2017-01-05 17:59:22 +0000212/// no further borrowing is needed or it runs out of "digits" in x. The result
Reid Spencera856b6e2007-02-18 18:38:44 +0000213/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
214/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencera41e93b2007-02-25 19:32:03 +0000215/// @returns the borrow out of the subtraction
Chris Lattner77527f52009-01-21 18:09:24 +0000216static bool sub_1(uint64_t x[], unsigned len, uint64_t y) {
217 for (unsigned i = 0; i < len; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000218 uint64_t X = x[i];
Reid Spenceree0a6852007-02-18 06:39:42 +0000219 x[i] -= y;
Eric Christopher820256b2009-08-21 04:06:45 +0000220 if (y > X)
Reid Spencera856b6e2007-02-18 18:38:44 +0000221 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer100502d2007-02-17 03:16:00 +0000222 else {
Reid Spencera856b6e2007-02-18 18:38:44 +0000223 y = 0; // No need to borrow
224 break; // Remaining digits are unchanged so exit early
Reid Spencer100502d2007-02-17 03:16:00 +0000225 }
226 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000227 return bool(y);
Reid Spencer100502d2007-02-17 03:16:00 +0000228}
229
Zhou Shengdac63782007-02-06 03:00:16 +0000230/// @brief Prefix decrement operator. Decrements the APInt by one.
231APInt& APInt::operator--() {
Eric Christopher820256b2009-08-21 04:06:45 +0000232 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000233 --VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000234 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000235 sub_1(pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000236 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000237}
238
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000239/// This function adds the integer array x to the integer array Y and
Eric Christopher820256b2009-08-21 04:06:45 +0000240/// places the result in dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000241/// @returns the carry out from the addition
242/// @brief General addition of 64-bit integer arrays
Eric Christopher820256b2009-08-21 04:06:45 +0000243static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000244 unsigned len) {
Reid Spencera5e0d202007-02-24 03:58:46 +0000245 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000246 for (unsigned i = 0; i< len; ++i) {
Reid Spencercb292e42007-02-23 01:57:13 +0000247 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000248 dest[i] = x[i] + y[i] + carry;
Reid Spencerdb2abec2007-02-21 05:44:56 +0000249 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer100502d2007-02-17 03:16:00 +0000250 }
251 return carry;
252}
253
Reid Spencera41e93b2007-02-25 19:32:03 +0000254/// Adds the RHS APint to this APInt.
255/// @returns this, after addition of RHS.
Eric Christopher820256b2009-08-21 04:06:45 +0000256/// @brief Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000257APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000258 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000259 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000260 VAL += RHS.VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000261 else {
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000262 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000263 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000264 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000265}
266
Pete Cooperfea21392016-07-22 20:55:46 +0000267APInt& APInt::operator+=(uint64_t RHS) {
268 if (isSingleWord())
269 VAL += RHS;
270 else
271 add_1(pVal, pVal, getNumWords(), RHS);
272 return clearUnusedBits();
273}
274
Eric Christopher820256b2009-08-21 04:06:45 +0000275/// Subtracts the integer array y from the integer array x
Reid Spencera41e93b2007-02-25 19:32:03 +0000276/// @returns returns the borrow out.
277/// @brief Generalized subtraction of 64-bit integer arrays.
Eric Christopher820256b2009-08-21 04:06:45 +0000278static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000279 unsigned len) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000280 bool borrow = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000281 for (unsigned i = 0; i < len; ++i) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000282 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
283 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
284 dest[i] = x_tmp - y[i];
Reid Spencer100502d2007-02-17 03:16:00 +0000285 }
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000286 return borrow;
Reid Spencer100502d2007-02-17 03:16:00 +0000287}
288
Reid Spencera41e93b2007-02-25 19:32:03 +0000289/// Subtracts the RHS APInt from this APInt
290/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000291/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000292APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000293 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000294 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000295 VAL -= RHS.VAL;
296 else
297 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000298 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000299}
300
Pete Cooperfea21392016-07-22 20:55:46 +0000301APInt& APInt::operator-=(uint64_t RHS) {
302 if (isSingleWord())
303 VAL -= RHS;
304 else
305 sub_1(pVal, getNumWords(), RHS);
306 return clearUnusedBits();
307}
308
Dan Gohman4a618822010-02-10 16:03:48 +0000309/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000310/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000311/// @returns the carry out of the multiplication.
312/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000313static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000314 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000315 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000316 uint64_t carry = 0;
317
318 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000319 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000320 // Split x into high and low words
321 uint64_t lx = x[i] & 0xffffffffULL;
322 uint64_t hx = x[i] >> 32;
323 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000324 // hasCarry == 0, no carry
325 // hasCarry == 1, has carry
326 // hasCarry == 2, no carry and the calculation result == 0.
327 uint8_t hasCarry = 0;
328 dest[i] = carry + lx * ly;
329 // Determine if the add above introduces carry.
330 hasCarry = (dest[i] < carry) ? 1 : 0;
331 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000332 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000333 // (2^32 - 1) + 2^32 = 2^64.
334 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
335
336 carry += (lx * hy) & 0xffffffffULL;
337 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000338 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000339 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
340 }
Reid Spencer100502d2007-02-17 03:16:00 +0000341 return carry;
342}
343
Eric Christopher820256b2009-08-21 04:06:45 +0000344/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000345/// the integer array dest. Note that dest's size must be >= xlen + ylen.
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000346/// @brief Generalized multiplication of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000347static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
348 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000349 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000350 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000351 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000352 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000353 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000354 lx = x[j] & 0xffffffffULL;
355 hx = x[j] >> 32;
356 // hasCarry - A flag to indicate if has carry.
357 // hasCarry == 0, no carry
358 // hasCarry == 1, has carry
359 // hasCarry == 2, no carry and the calculation result == 0.
360 uint8_t hasCarry = 0;
361 uint64_t resul = carry + lx * ly;
362 hasCarry = (resul < carry) ? 1 : 0;
363 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
364 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
365
366 carry += (lx * hy) & 0xffffffffULL;
367 resul = (carry << 32) | (resul & 0xffffffffULL);
368 dest[i+j] += resul;
369 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000370 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000371 ((lx * hy) >> 32) + hx * hy;
372 }
373 dest[i+xlen] = carry;
374 }
375}
376
Zhou Shengdac63782007-02-06 03:00:16 +0000377APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000378 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000379 if (isSingleWord()) {
Reid Spencer4bb430c2007-02-20 20:42:10 +0000380 VAL *= RHS.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000381 clearUnusedBits();
382 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000383 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000384
385 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000386 unsigned lhsBits = getActiveBits();
387 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000388 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000389 // 0 * X ===> 0
390 return *this;
391
392 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000393 unsigned rhsBits = RHS.getActiveBits();
394 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000395 if (!rhsWords) {
396 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000397 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000398 return *this;
399 }
400
401 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000402 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000403 uint64_t *dest = getMemory(destWords);
404
405 // Perform the long multiply
406 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
407
408 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000409 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000410 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000411 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000412 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000413
414 // delete dest array and return
415 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000416 return *this;
417}
418
Zhou Shengdac63782007-02-06 03:00:16 +0000419APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000420 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000421 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000422 VAL &= RHS.VAL;
423 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000424 }
Chris Lattner77527f52009-01-21 18:09:24 +0000425 unsigned numWords = getNumWords();
426 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000427 pVal[i] &= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000428 return *this;
429}
430
Amaury Sechetfb1756b2017-02-03 22:54:41 +0000431APInt &APInt::operator&=(uint64_t RHS) {
432 if (isSingleWord()) {
433 VAL &= RHS;
434 return *this;
435 }
436 pVal[0] &= RHS;
437 unsigned numWords = getNumWords();
438 for (unsigned i = 1; i < numWords; ++i)
439 pVal[i] = 0;
440 return *this;
441}
442
Zhou Shengdac63782007-02-06 03:00:16 +0000443APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000444 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000445 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000446 VAL |= RHS.VAL;
447 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000448 }
Chris Lattner77527f52009-01-21 18:09:24 +0000449 unsigned numWords = getNumWords();
450 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000451 pVal[i] |= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000452 return *this;
453}
454
Zhou Shengdac63782007-02-06 03:00:16 +0000455APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000456 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000457 if (isSingleWord()) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000458 VAL ^= RHS.VAL;
459 return *this;
Eric Christopher820256b2009-08-21 04:06:45 +0000460 }
Chris Lattner77527f52009-01-21 18:09:24 +0000461 unsigned numWords = getNumWords();
462 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000463 pVal[i] ^= RHS.pVal[i];
Craig Topper9028f052017-01-24 02:10:15 +0000464 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000465}
466
Zhou Shengdac63782007-02-06 03:00:16 +0000467APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000468 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000469 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000470 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000471 APInt Result(*this);
472 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000473 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000474}
475
Chris Lattner1ac3e252008-08-20 17:02:31 +0000476bool APInt::EqualSlowCase(const APInt& RHS) const {
Matthias Braun5117fcd2016-02-15 20:06:19 +0000477 return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000478}
479
Chris Lattner1ac3e252008-08-20 17:02:31 +0000480bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000481 unsigned n = getActiveBits();
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000482 if (n <= APINT_BITS_PER_WORD)
483 return pVal[0] == Val;
484 else
485 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000486}
487
Reid Spencer1d072122007-02-16 22:36:51 +0000488bool APInt::ult(const APInt& RHS) const {
489 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
490 if (isSingleWord())
491 return VAL < RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000492
493 // Get active bit length of both operands
Chris Lattner77527f52009-01-21 18:09:24 +0000494 unsigned n1 = getActiveBits();
495 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000496
497 // If magnitude of LHS is less than RHS, return true.
498 if (n1 < n2)
499 return true;
500
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000501 // If magnitude of RHS is greater than LHS, return false.
Reid Spencera41e93b2007-02-25 19:32:03 +0000502 if (n2 < n1)
503 return false;
504
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000505 // If they both fit in a word, just compare the low order word
Reid Spencera41e93b2007-02-25 19:32:03 +0000506 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
507 return pVal[0] < RHS.pVal[0];
508
509 // Otherwise, compare all words
Chris Lattner77527f52009-01-21 18:09:24 +0000510 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000511 for (int i = topWord; i >= 0; --i) {
Eric Christopher820256b2009-08-21 04:06:45 +0000512 if (pVal[i] > RHS.pVal[i])
Reid Spencer1d072122007-02-16 22:36:51 +0000513 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000514 if (pVal[i] < RHS.pVal[i])
Reid Spencera41e93b2007-02-25 19:32:03 +0000515 return true;
Zhou Shengdac63782007-02-06 03:00:16 +0000516 }
517 return false;
518}
519
Reid Spencer1d072122007-02-16 22:36:51 +0000520bool APInt::slt(const APInt& RHS) const {
521 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000522 if (isSingleWord()) {
David Majnemer5f1c0172016-06-24 20:51:47 +0000523 int64_t lhsSext = SignExtend64(VAL, BitWidth);
524 int64_t rhsSext = SignExtend64(RHS.VAL, BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000525 return lhsSext < rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000526 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000527
Reid Spencer54abdcf2007-02-27 18:23:40 +0000528 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000529 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000530
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000531 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
532 if (lhsNeg != rhsNeg)
533 return lhsNeg;
534
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000535 // Otherwise we can just use an unsigned comparison, because even negative
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000536 // numbers compare correctly this way if both have the same signed-ness.
537 return ult(RHS);
Zhou Shengdac63782007-02-06 03:00:16 +0000538}
539
Jay Foad25a5e4c2010-12-01 08:53:58 +0000540void APInt::setBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000541 if (isSingleWord())
Reid Spencera41e93b2007-02-25 19:32:03 +0000542 VAL |= maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000543 else
Reid Spencera41e93b2007-02-25 19:32:03 +0000544 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000545}
546
Craig Topperbafdd032017-03-07 01:56:01 +0000547void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
548 unsigned loWord = whichWord(loBit);
549 unsigned hiWord = whichWord(hiBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000550
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000551 // Create an initial mask for the low word with zeros below loBit.
Craig Topperbafdd032017-03-07 01:56:01 +0000552 uint64_t loMask = UINT64_MAX << whichBit(loBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000553
Craig Topperbafdd032017-03-07 01:56:01 +0000554 // If hiBit is not aligned, we need a high mask.
555 unsigned hiShiftAmt = whichBit(hiBit);
556 if (hiShiftAmt != 0) {
557 // Create a high mask with zeros above hiBit.
558 uint64_t hiMask = UINT64_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
559 // If loWord and hiWord are equal, then we combine the masks. Otherwise,
560 // set the bits in hiWord.
561 if (hiWord == loWord)
562 loMask &= hiMask;
563 else
Simon Pilgrimaed35222017-02-24 10:15:29 +0000564 pVal[hiWord] |= hiMask;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000565 }
Craig Topperbafdd032017-03-07 01:56:01 +0000566 // Apply the mask to the low word.
567 pVal[loWord] |= loMask;
568
569 // Fill any words between loWord and hiWord with all ones.
570 for (unsigned word = loWord + 1; word < hiWord; ++word)
571 pVal[word] = UINT64_MAX;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000572}
573
Zhou Shengdac63782007-02-06 03:00:16 +0000574/// Set the given bit to 0 whose position is given as "bitPosition".
575/// @brief Set a given bit to 0.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000576void APInt::clearBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000577 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000578 VAL &= ~maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000579 else
Reid Spencera856b6e2007-02-18 18:38:44 +0000580 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000581}
582
Zhou Shengdac63782007-02-06 03:00:16 +0000583/// @brief Toggle every bit to its opposite value.
Zhou Shengdac63782007-02-06 03:00:16 +0000584
Eric Christopher820256b2009-08-21 04:06:45 +0000585/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000586/// as "bitPosition".
587/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000588void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000589 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000590 if ((*this)[bitPosition]) clearBit(bitPosition);
591 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000592}
593
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000594void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
595 unsigned subBitWidth = subBits.getBitWidth();
596 assert(0 < subBitWidth && (subBitWidth + bitPosition) <= BitWidth &&
597 "Illegal bit insertion");
598
599 // Insertion is a direct copy.
600 if (subBitWidth == BitWidth) {
601 *this = subBits;
602 return;
603 }
604
605 // Single word result can be done as a direct bitmask.
606 if (isSingleWord()) {
607 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
608 VAL &= ~(mask << bitPosition);
609 VAL |= (subBits.VAL << bitPosition);
610 return;
611 }
612
613 unsigned loBit = whichBit(bitPosition);
614 unsigned loWord = whichWord(bitPosition);
615 unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
616
617 // Insertion within a single word can be done as a direct bitmask.
618 if (loWord == hi1Word) {
619 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
620 pVal[loWord] &= ~(mask << loBit);
621 pVal[loWord] |= (subBits.VAL << loBit);
622 return;
623 }
624
625 // Insert on word boundaries.
626 if (loBit == 0) {
627 // Direct copy whole words.
628 unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
629 memcpy(pVal + loWord, subBits.getRawData(),
630 numWholeSubWords * APINT_WORD_SIZE);
631
632 // Mask+insert remaining bits.
633 unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
634 if (remainingBits != 0) {
635 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - remainingBits);
636 pVal[hi1Word] &= ~mask;
637 pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
638 }
639 return;
640 }
641
642 // General case - set/clear individual bits in dst based on src.
643 // TODO - there is scope for optimization here, but at the moment this code
644 // path is barely used so prefer readability over performance.
645 for (unsigned i = 0; i != subBitWidth; ++i) {
646 if (subBits[i])
647 setBit(bitPosition + i);
648 else
649 clearBit(bitPosition + i);
650 }
651}
652
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000653APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
654 assert(numBits > 0 && "Can't extract zero bits");
655 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
656 "Illegal bit extraction");
657
658 if (isSingleWord())
659 return APInt(numBits, VAL >> bitPosition);
660
661 unsigned loBit = whichBit(bitPosition);
662 unsigned loWord = whichWord(bitPosition);
663 unsigned hiWord = whichWord(bitPosition + numBits - 1);
664
665 // Single word result extracting bits from a single word source.
666 if (loWord == hiWord)
667 return APInt(numBits, pVal[loWord] >> loBit);
668
669 // Extracting bits that start on a source word boundary can be done
670 // as a fast memory copy.
671 if (loBit == 0)
672 return APInt(numBits, makeArrayRef(pVal + loWord, 1 + hiWord - loWord));
673
674 // General case - shift + copy source words directly into place.
675 APInt Result(numBits, 0);
676 unsigned NumSrcWords = getNumWords();
677 unsigned NumDstWords = Result.getNumWords();
678
679 for (unsigned word = 0; word < NumDstWords; ++word) {
680 uint64_t w0 = pVal[loWord + word];
681 uint64_t w1 =
682 (loWord + word + 1) < NumSrcWords ? pVal[loWord + word + 1] : 0;
683 Result.pVal[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
684 }
685
686 return Result.clearUnusedBits();
687}
688
Benjamin Kramer92d89982010-07-14 22:38:02 +0000689unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000690 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000691 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +0000692 radix == 36) &&
693 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000694
695 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000696
Eric Christopher43a1dec2009-08-21 04:10:31 +0000697 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000698 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000699 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000700 if (*p == '-' || *p == '+') {
701 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000702 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000703 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000704 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000705
Reid Spencer9329e7b2007-04-13 19:19:07 +0000706 // For radixes of power-of-two values, the bits required is accurately and
707 // easily computed
708 if (radix == 2)
709 return slen + isNegative;
710 if (radix == 8)
711 return slen * 3 + isNegative;
712 if (radix == 16)
713 return slen * 4 + isNegative;
714
Douglas Gregor663c0682011-09-14 15:54:46 +0000715 // FIXME: base 36
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000716
Reid Spencer9329e7b2007-04-13 19:19:07 +0000717 // This is grossly inefficient but accurate. We could probably do something
718 // with a computation of roughly slen*64/20 and then adjust by the value of
719 // the first few digits. But, I'm not sure how accurate that could be.
720
721 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000722 // be too large. This avoids the assertion in the constructor. This
723 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
724 // bits in that case.
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000725 unsigned sufficient
Douglas Gregor663c0682011-09-14 15:54:46 +0000726 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
727 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000728
729 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000730 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000731
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000732 // Compute how many bits are required. If the log is infinite, assume we need
733 // just bit.
734 unsigned log = tmp.logBase2();
735 if (log == (unsigned)-1) {
736 return isNegative + 1;
737 } else {
738 return isNegative + log + 1;
739 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000740}
741
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000742hash_code llvm::hash_value(const APInt &Arg) {
743 if (Arg.isSingleWord())
744 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000745
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000746 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000747}
748
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000749bool APInt::isSplat(unsigned SplatSizeInBits) const {
750 assert(getBitWidth() % SplatSizeInBits == 0 &&
751 "SplatSizeInBits must divide width!");
752 // We can check that all parts of an integer are equal by making use of a
753 // little trick: rotate and check if it's still the same value.
754 return *this == rotl(SplatSizeInBits);
755}
756
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000757/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000758APInt APInt::getHiBits(unsigned numBits) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000759 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000760}
761
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000762/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000763APInt APInt::getLoBits(unsigned numBits) const {
Eric Christopher820256b2009-08-21 04:06:45 +0000764 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
Reid Spencer1d072122007-02-16 22:36:51 +0000765 BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000766}
767
Chris Lattner77527f52009-01-21 18:09:24 +0000768unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000769 unsigned Count = 0;
770 for (int i = getNumWords()-1; i >= 0; --i) {
771 integerPart V = pVal[i];
772 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000773 Count += APINT_BITS_PER_WORD;
774 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000775 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000776 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000777 }
Zhou Shengdac63782007-02-06 03:00:16 +0000778 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000779 // Adjust for unused bits in the most significant word (they are zero).
780 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
781 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000782 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000783}
784
Chris Lattner77527f52009-01-21 18:09:24 +0000785unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000786 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000787 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000788
Chris Lattner77527f52009-01-21 18:09:24 +0000789 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000790 unsigned shift;
791 if (!highWordBits) {
792 highWordBits = APINT_BITS_PER_WORD;
793 shift = 0;
794 } else {
795 shift = APINT_BITS_PER_WORD - highWordBits;
796 }
Reid Spencer31acef52007-02-27 21:59:26 +0000797 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000798 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000799 if (Count == highWordBits) {
800 for (i--; i >= 0; --i) {
801 if (pVal[i] == -1ULL)
802 Count += APINT_BITS_PER_WORD;
803 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000804 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000805 break;
806 }
807 }
808 }
809 return Count;
810}
811
Chris Lattner77527f52009-01-21 18:09:24 +0000812unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000813 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000814 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000815 unsigned Count = 0;
816 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000817 for (; i < getNumWords() && pVal[i] == 0; ++i)
818 Count += APINT_BITS_PER_WORD;
819 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000820 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000821 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000822}
823
Chris Lattner77527f52009-01-21 18:09:24 +0000824unsigned APInt::countTrailingOnesSlowCase() const {
825 unsigned Count = 0;
826 unsigned i = 0;
Dan Gohmanc354ebd2008-02-14 22:38:45 +0000827 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000828 Count += APINT_BITS_PER_WORD;
829 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000830 Count += llvm::countTrailingOnes(pVal[i]);
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000831 return std::min(Count, BitWidth);
832}
833
Chris Lattner77527f52009-01-21 18:09:24 +0000834unsigned APInt::countPopulationSlowCase() const {
835 unsigned Count = 0;
836 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000837 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000838 return Count;
839}
840
Richard Smith4f9a8082011-11-23 21:33:37 +0000841/// Perform a logical right-shift from Src to Dst, which must be equal or
842/// non-overlapping, of Words words, by Shift, which must be less than 64.
843static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
844 unsigned Shift) {
845 uint64_t Carry = 0;
846 for (int I = Words - 1; I >= 0; --I) {
847 uint64_t Tmp = Src[I];
848 Dst[I] = (Tmp >> Shift) | Carry;
849 Carry = Tmp << (64 - Shift);
850 }
851}
852
Reid Spencer1d072122007-02-16 22:36:51 +0000853APInt APInt::byteSwap() const {
854 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
855 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000856 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000857 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000858 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000859 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000860 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000861 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000862 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000863 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000864 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000865 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000866 if (BitWidth == 64)
867 return APInt(BitWidth, ByteSwap_64(VAL));
868
869 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
870 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
871 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
872 if (Result.BitWidth != BitWidth) {
873 lshrNear(Result.pVal, Result.pVal, getNumWords(),
874 Result.BitWidth - BitWidth);
875 Result.BitWidth = BitWidth;
876 }
877 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000878}
879
Matt Arsenault155dda92016-03-21 15:00:35 +0000880APInt APInt::reverseBits() const {
881 switch (BitWidth) {
882 case 64:
883 return APInt(BitWidth, llvm::reverseBits<uint64_t>(VAL));
884 case 32:
885 return APInt(BitWidth, llvm::reverseBits<uint32_t>(VAL));
886 case 16:
887 return APInt(BitWidth, llvm::reverseBits<uint16_t>(VAL));
888 case 8:
889 return APInt(BitWidth, llvm::reverseBits<uint8_t>(VAL));
890 default:
891 break;
892 }
893
894 APInt Val(*this);
895 APInt Reversed(*this);
896 int S = BitWidth - 1;
897
898 const APInt One(BitWidth, 1);
899
900 for ((Val = Val.lshr(1)); Val != 0; (Val = Val.lshr(1))) {
901 Reversed <<= 1;
902 Reversed |= (Val & One);
903 --S;
904 }
905
906 Reversed <<= S;
907 return Reversed;
908}
909
Eric Christopher820256b2009-08-21 04:06:45 +0000910APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
Zhou Shengfbf61ea2007-02-08 14:35:19 +0000911 const APInt& API2) {
Zhou Shengdac63782007-02-06 03:00:16 +0000912 APInt A = API1, B = API2;
913 while (!!B) {
914 APInt T = B;
Reid Spencer1d072122007-02-16 22:36:51 +0000915 B = APIntOps::urem(A, B);
Zhou Shengdac63782007-02-06 03:00:16 +0000916 A = T;
917 }
918 return A;
919}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000920
Chris Lattner77527f52009-01-21 18:09:24 +0000921APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000922 union {
923 double D;
924 uint64_t I;
925 } T;
926 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000927
928 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000929 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000930
931 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000932 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000933
934 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000935 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000936 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000937
938 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
939 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
940
941 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000942 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000943 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000944 APInt(width, mantissa >> (52 - exp));
945
946 // If the client didn't provide enough bits for us to shift the mantissa into
947 // then the result is undefined, just return 0
948 if (width <= exp - 52)
949 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000950
951 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000952 APInt Tmp(width, mantissa);
Chris Lattner77527f52009-01-21 18:09:24 +0000953 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd707d632007-02-12 20:02:55 +0000954 return isNeg ? -Tmp : Tmp;
955}
956
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000957/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000958/// The layout for double is as following (IEEE Standard 754):
959/// --------------------------------------
960/// | Sign Exponent Fraction Bias |
961/// |-------------------------------------- |
962/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000963/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000964double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000965
966 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000967 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000968 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
969 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000970 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000971 return double(sext);
972 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000973 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000974 }
975
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000976 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000977 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000978
979 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000980 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000981
982 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000983 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000984
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000985 // The exponent (without bias normalization) is just the number of bits
986 // we are using. Note that the sign bit is gone since we constructed the
987 // absolute value.
988 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000989
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000990 // Return infinity for exponent overflow
991 if (exp > 1023) {
992 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000993 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000994 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000995 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000996 }
997 exp += 1023; // Increment for 1023 bias
998
999 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
1000 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +00001001 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001002 unsigned hiWord = whichWord(n-1);
1003 if (hiWord == 0) {
1004 mantissa = Tmp.pVal[0];
1005 if (n > 52)
1006 mantissa >>= n - 52; // shift down, we want the top 52 bits.
1007 } else {
1008 assert(hiWord > 0 && "huh?");
1009 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
1010 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
1011 mantissa = hibits | lobits;
1012 }
1013
Zhou Shengd707d632007-02-12 20:02:55 +00001014 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +00001015 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +00001016 union {
1017 double D;
1018 uint64_t I;
1019 } T;
1020 T.I = sign | (exp << 52) | mantissa;
1021 return T.D;
1022}
1023
Reid Spencer1d072122007-02-16 22:36:51 +00001024// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +00001025APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +00001026 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +00001027 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +00001028
1029 if (width <= APINT_BITS_PER_WORD)
1030 return APInt(width, getRawData()[0]);
1031
1032 APInt Result(getMemory(getNumWords(width)), width);
1033
1034 // Copy full words.
1035 unsigned i;
1036 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
1037 Result.pVal[i] = pVal[i];
1038
1039 // Truncate and copy any partial word.
1040 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
1041 if (bits != 0)
1042 Result.pVal[i] = pVal[i] << bits >> bits;
1043
1044 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001045}
1046
1047// Sign extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +00001048APInt APInt::sext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +00001049 assert(width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +00001050
1051 if (width <= APINT_BITS_PER_WORD) {
1052 uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
1053 val = (int64_t)val >> (width - BitWidth);
1054 return APInt(width, val >> (APINT_BITS_PER_WORD - width));
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001055 }
1056
Jay Foad583abbc2010-12-07 08:25:19 +00001057 APInt Result(getMemory(getNumWords(width)), width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001058
Jay Foad583abbc2010-12-07 08:25:19 +00001059 // Copy full words.
1060 unsigned i;
1061 uint64_t word = 0;
1062 for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
1063 word = getRawData()[i];
1064 Result.pVal[i] = word;
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001065 }
1066
Jay Foad583abbc2010-12-07 08:25:19 +00001067 // Read and sign-extend any partial word.
1068 unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
1069 if (bits != 0)
1070 word = (int64_t)getRawData()[i] << bits >> bits;
1071 else
1072 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
1073
1074 // Write remaining full words.
1075 for (; i != width / APINT_BITS_PER_WORD; i++) {
1076 Result.pVal[i] = word;
1077 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001078 }
Jay Foad583abbc2010-12-07 08:25:19 +00001079
1080 // Write any partial word.
1081 bits = (0 - width) % APINT_BITS_PER_WORD;
1082 if (bits != 0)
1083 Result.pVal[i] = word << bits >> bits;
1084
1085 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001086}
1087
1088// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +00001089APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +00001090 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +00001091
1092 if (width <= APINT_BITS_PER_WORD)
1093 return APInt(width, VAL);
1094
1095 APInt Result(getMemory(getNumWords(width)), width);
1096
1097 // Copy words.
1098 unsigned i;
1099 for (i = 0; i != getNumWords(); i++)
1100 Result.pVal[i] = getRawData()[i];
1101
1102 // Zero remaining words.
1103 memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
1104
1105 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001106}
1107
Jay Foad583abbc2010-12-07 08:25:19 +00001108APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001109 if (BitWidth < width)
1110 return zext(width);
1111 if (BitWidth > width)
1112 return trunc(width);
1113 return *this;
1114}
1115
Jay Foad583abbc2010-12-07 08:25:19 +00001116APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001117 if (BitWidth < width)
1118 return sext(width);
1119 if (BitWidth > width)
1120 return trunc(width);
1121 return *this;
1122}
1123
Rafael Espindolabb893fe2012-01-27 23:33:07 +00001124APInt APInt::zextOrSelf(unsigned width) const {
1125 if (BitWidth < width)
1126 return zext(width);
1127 return *this;
1128}
1129
1130APInt APInt::sextOrSelf(unsigned width) const {
1131 if (BitWidth < width)
1132 return sext(width);
1133 return *this;
1134}
1135
Zhou Shenge93db8f2007-02-09 07:48:24 +00001136/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001137/// @brief Arithmetic right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001138APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001139 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001140}
1141
1142/// Arithmetic right-shift this APInt by shiftAmt.
1143/// @brief Arithmetic right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001144APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001145 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer1825dd02007-03-02 22:39:11 +00001146 // Handle a degenerate case
1147 if (shiftAmt == 0)
1148 return *this;
1149
1150 // Handle single word shifts with built-in ashr
Reid Spencer522ca7c2007-02-25 01:56:07 +00001151 if (isSingleWord()) {
1152 if (shiftAmt == BitWidth)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001153 return APInt(BitWidth, 0); // undefined
Jonathan Roelofs851b79d2016-08-10 19:50:14 +00001154 return APInt(BitWidth, SignExtend64(VAL, BitWidth) >> shiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001155 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001156
Reid Spencer1825dd02007-03-02 22:39:11 +00001157 // If all the bits were shifted out, the result is, technically, undefined.
1158 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1159 // issues in the algorithm below.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001160 if (shiftAmt == BitWidth) {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001161 if (isNegative())
Zhou Sheng1247c072008-06-05 13:27:38 +00001162 return APInt(BitWidth, -1ULL, true);
Reid Spencera41e93b2007-02-25 19:32:03 +00001163 else
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001164 return APInt(BitWidth, 0);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001165 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001166
1167 // Create some space for the result.
1168 uint64_t * val = new uint64_t[getNumWords()];
1169
Reid Spencer1825dd02007-03-02 22:39:11 +00001170 // Compute some values needed by the following shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001171 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1172 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1173 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1174 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer1825dd02007-03-02 22:39:11 +00001175 if (bitsInWord == 0)
1176 bitsInWord = APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001177
1178 // If we are shifting whole words, just move whole words
1179 if (wordShift == 0) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001180 // Move the words containing significant bits
Chris Lattner77527f52009-01-21 18:09:24 +00001181 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001182 val[i] = pVal[i+offset]; // move whole word
1183
1184 // Adjust the top significant word for sign bit fill, if negative
1185 if (isNegative())
1186 if (bitsInWord < APINT_BITS_PER_WORD)
1187 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1188 } else {
Eric Christopher820256b2009-08-21 04:06:45 +00001189 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001190 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001191 // This combines the shifted corresponding word with the low bits from
1192 // the next word (shifted into this word's high bits).
Eric Christopher820256b2009-08-21 04:06:45 +00001193 val[i] = (pVal[i+offset] >> wordShift) |
Reid Spencer1825dd02007-03-02 22:39:11 +00001194 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1195 }
1196
1197 // Shift the break word. In this case there are no bits from the next word
1198 // to include in this word.
1199 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1200
Alp Tokercb402912014-01-24 17:20:08 +00001201 // Deal with sign extension in the break word, and possibly the word before
Reid Spencer1825dd02007-03-02 22:39:11 +00001202 // it.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001203 if (isNegative()) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001204 if (wordShift > bitsInWord) {
1205 if (breakWord > 0)
Eric Christopher820256b2009-08-21 04:06:45 +00001206 val[breakWord-1] |=
Reid Spencer1825dd02007-03-02 22:39:11 +00001207 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1208 val[breakWord] |= ~0ULL;
Eric Christopher820256b2009-08-21 04:06:45 +00001209 } else
Reid Spencer1825dd02007-03-02 22:39:11 +00001210 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnerdad2d092007-05-03 18:15:36 +00001211 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001212 }
1213
Reid Spencer1825dd02007-03-02 22:39:11 +00001214 // Remaining words are 0 or -1, just assign them.
1215 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner77527f52009-01-21 18:09:24 +00001216 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001217 val[i] = fillValue;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001218 APInt Result(val, BitWidth);
1219 Result.clearUnusedBits();
1220 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001221}
1222
Zhou Shenge93db8f2007-02-09 07:48:24 +00001223/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001224/// @brief Logical right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001225APInt APInt::lshr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001226 return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001227}
1228
1229/// Logical right-shift this APInt by shiftAmt.
1230/// @brief Logical right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001231APInt APInt::lshr(unsigned shiftAmt) const {
Chris Lattnerdad2d092007-05-03 18:15:36 +00001232 if (isSingleWord()) {
Ahmed Charles0dca5d82012-02-24 19:06:15 +00001233 if (shiftAmt >= BitWidth)
Reid Spencer522ca7c2007-02-25 01:56:07 +00001234 return APInt(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001235 else
Reid Spencer522ca7c2007-02-25 01:56:07 +00001236 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001237 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001238
Reid Spencer44eef162007-02-26 01:19:48 +00001239 // If all the bits were shifted out, the result is 0. This avoids issues
1240 // with shifting by the size of the integer type, which produces undefined
1241 // results. We define these "undefined results" to always be 0.
Chad Rosier3d464d82012-06-08 18:04:52 +00001242 if (shiftAmt >= BitWidth)
Reid Spencer44eef162007-02-26 01:19:48 +00001243 return APInt(BitWidth, 0);
1244
Reid Spencerfffdf102007-05-17 06:26:29 +00001245 // If none of the bits are shifted out, the result is *this. This avoids
Eric Christopher820256b2009-08-21 04:06:45 +00001246 // issues with shifting by the size of the integer type, which produces
Reid Spencerfffdf102007-05-17 06:26:29 +00001247 // undefined results in the code below. This is also an optimization.
1248 if (shiftAmt == 0)
1249 return *this;
1250
Reid Spencer44eef162007-02-26 01:19:48 +00001251 // Create some space for the result.
1252 uint64_t * val = new uint64_t[getNumWords()];
1253
1254 // If we are shifting less than a word, compute the shift with a simple carry
1255 if (shiftAmt < APINT_BITS_PER_WORD) {
Richard Smith4f9a8082011-11-23 21:33:37 +00001256 lshrNear(val, pVal, getNumWords(), shiftAmt);
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001257 APInt Result(val, BitWidth);
1258 Result.clearUnusedBits();
1259 return Result;
Reid Spencera41e93b2007-02-25 19:32:03 +00001260 }
1261
Reid Spencer44eef162007-02-26 01:19:48 +00001262 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001263 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1264 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencer44eef162007-02-26 01:19:48 +00001265
1266 // If we are shifting whole words, just move whole words
1267 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001268 for (unsigned i = 0; i < getNumWords() - offset; ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001269 val[i] = pVal[i+offset];
Chris Lattner77527f52009-01-21 18:09:24 +00001270 for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
Reid Spencer44eef162007-02-26 01:19:48 +00001271 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001272 APInt Result(val, BitWidth);
1273 Result.clearUnusedBits();
1274 return Result;
Reid Spencer44eef162007-02-26 01:19:48 +00001275 }
1276
Eric Christopher820256b2009-08-21 04:06:45 +00001277 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001278 unsigned breakWord = getNumWords() - offset -1;
1279 for (unsigned i = 0; i < breakWord; ++i)
Reid Spencerd99feaf2007-03-01 05:39:56 +00001280 val[i] = (pVal[i+offset] >> wordShift) |
1281 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencer44eef162007-02-26 01:19:48 +00001282 // Shift the break word.
1283 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1284
1285 // Remaining words are 0
Chris Lattner77527f52009-01-21 18:09:24 +00001286 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001287 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001288 APInt Result(val, BitWidth);
1289 Result.clearUnusedBits();
1290 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001291}
1292
Zhou Shenge93db8f2007-02-09 07:48:24 +00001293/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001294/// @brief Left-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001295APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky030c4502009-01-19 17:42:33 +00001296 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner77527f52009-01-21 18:09:24 +00001297 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001298}
1299
Chris Lattner77527f52009-01-21 18:09:24 +00001300APInt APInt::shlSlowCase(unsigned shiftAmt) const {
Reid Spencera5c84d92007-02-25 00:56:44 +00001301 // If all the bits were shifted out, the result is 0. This avoids issues
1302 // with shifting by the size of the integer type, which produces undefined
1303 // results. We define these "undefined results" to always be 0.
1304 if (shiftAmt == BitWidth)
1305 return APInt(BitWidth, 0);
1306
Reid Spencer81ee0202007-05-12 18:01:57 +00001307 // If none of the bits are shifted out, the result is *this. This avoids a
1308 // lshr by the words size in the loop below which can produce incorrect
1309 // results. It also avoids the expensive computation below for a common case.
1310 if (shiftAmt == 0)
1311 return *this;
1312
Reid Spencera5c84d92007-02-25 00:56:44 +00001313 // Create some space for the result.
1314 uint64_t * val = new uint64_t[getNumWords()];
1315
1316 // If we are shifting less than a word, do it the easy way
1317 if (shiftAmt < APINT_BITS_PER_WORD) {
1318 uint64_t carry = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001319 for (unsigned i = 0; i < getNumWords(); i++) {
Reid Spencera5c84d92007-02-25 00:56:44 +00001320 val[i] = pVal[i] << shiftAmt | carry;
1321 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1322 }
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001323 APInt Result(val, BitWidth);
1324 Result.clearUnusedBits();
1325 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001326 }
1327
Reid Spencera5c84d92007-02-25 00:56:44 +00001328 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001329 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1330 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencera5c84d92007-02-25 00:56:44 +00001331
1332 // If we are shifting whole words, just move whole words
1333 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001334 for (unsigned i = 0; i < offset; i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001335 val[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001336 for (unsigned i = offset; i < getNumWords(); i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001337 val[i] = pVal[i-offset];
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001338 APInt Result(val, BitWidth);
1339 Result.clearUnusedBits();
1340 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001341 }
Reid Spencera5c84d92007-02-25 00:56:44 +00001342
1343 // Copy whole words from this to Result.
Chris Lattner77527f52009-01-21 18:09:24 +00001344 unsigned i = getNumWords() - 1;
Reid Spencera5c84d92007-02-25 00:56:44 +00001345 for (; i > offset; --i)
1346 val[i] = pVal[i-offset] << wordShift |
1347 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencerab0e08a2007-02-25 01:08:58 +00001348 val[offset] = pVal[0] << wordShift;
Reid Spencera5c84d92007-02-25 00:56:44 +00001349 for (i = 0; i < offset; ++i)
1350 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001351 APInt Result(val, BitWidth);
1352 Result.clearUnusedBits();
1353 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001354}
1355
Joey Gouly51c0ae52017-02-07 11:58:22 +00001356// Calculate the rotate amount modulo the bit width.
1357static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1358 unsigned rotBitWidth = rotateAmt.getBitWidth();
1359 APInt rot = rotateAmt;
1360 if (rotBitWidth < BitWidth) {
1361 // Extend the rotate APInt, so that the urem doesn't divide by 0.
1362 // e.g. APInt(1, 32) would give APInt(1, 0).
1363 rot = rotateAmt.zext(BitWidth);
1364 }
1365 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
1366 return rot.getLimitedValue(BitWidth);
1367}
1368
Dan Gohman105c1d42008-02-29 01:40:47 +00001369APInt APInt::rotl(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001370 return rotl(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001371}
1372
Chris Lattner77527f52009-01-21 18:09:24 +00001373APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001374 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001375 if (rotateAmt == 0)
1376 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001377 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001378}
1379
Dan Gohman105c1d42008-02-29 01:40:47 +00001380APInt APInt::rotr(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001381 return rotr(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001382}
1383
Chris Lattner77527f52009-01-21 18:09:24 +00001384APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001385 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001386 if (rotateAmt == 0)
1387 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001388 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001389}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001390
1391// Square Root - this method computes and returns the square root of "this".
1392// Three mechanisms are used for computation. For small values (<= 5 bits),
1393// a table lookup is done. This gets some performance for common cases. For
1394// values using less than 52 bits, the value is converted to double and then
1395// the libc sqrt function is called. The result is rounded and then converted
1396// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001397// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001398APInt APInt::sqrt() const {
1399
1400 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001401 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001402
1403 // Use a fast table for some small values. This also gets rid of some
1404 // rounding errors in libc sqrt for small values.
1405 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001406 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001407 /* 0 */ 0,
1408 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001409 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001410 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1411 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1412 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1413 /* 31 */ 6
1414 };
1415 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001416 }
1417
1418 // If the magnitude of the value fits in less than 52 bits (the precision of
1419 // an IEEE double precision floating point value), then we can use the
1420 // libc sqrt function which will probably use a hardware sqrt computation.
1421 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001422 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001423 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001424 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001425 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001426
1427 // Okay, all the short cuts are exhausted. We must compute it. The following
1428 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001429 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001430 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001431 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001432 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001433 APInt testy(BitWidth, 16);
1434 APInt x_old(BitWidth, 1);
1435 APInt x_new(BitWidth, 0);
1436 APInt two(BitWidth, 2);
1437
1438 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001439 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001440 if (i >= nbits || this->ule(testy)) {
1441 x_old = x_old.shl(i / 2);
1442 break;
1443 }
1444
Eric Christopher820256b2009-08-21 04:06:45 +00001445 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001446 for (;;) {
1447 x_new = (this->udiv(x_old) + x_old).udiv(two);
1448 if (x_old.ule(x_new))
1449 break;
1450 x_old = x_new;
1451 }
1452
1453 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001454 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001455 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001456 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001457 // floating point representation after 192 bits. There are no discrepancies
1458 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001459 APInt square(x_old * x_old);
1460 APInt nextSquare((x_old + 1) * (x_old +1));
1461 if (this->ult(square))
1462 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001463 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1464 APInt midpoint((nextSquare - square).udiv(two));
1465 APInt offset(*this - square);
1466 if (offset.ult(midpoint))
1467 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001468 return x_old + 1;
1469}
1470
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001471/// Computes the multiplicative inverse of this APInt for a given modulo. The
1472/// iterative extended Euclidean algorithm is used to solve for this value,
1473/// however we simplify it to speed up calculating only the inverse, and take
1474/// advantage of div+rem calculations. We also use some tricks to avoid copying
1475/// (potentially large) APInts around.
1476APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1477 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1478
1479 // Using the properties listed at the following web page (accessed 06/21/08):
1480 // http://www.numbertheory.org/php/euclid.html
1481 // (especially the properties numbered 3, 4 and 9) it can be proved that
1482 // BitWidth bits suffice for all the computations in the algorithm implemented
1483 // below. More precisely, this number of bits suffice if the multiplicative
1484 // inverse exists, but may not suffice for the general extended Euclidean
1485 // algorithm.
1486
1487 APInt r[2] = { modulo, *this };
1488 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1489 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001490
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001491 unsigned i;
1492 for (i = 0; r[i^1] != 0; i ^= 1) {
1493 // An overview of the math without the confusing bit-flipping:
1494 // q = r[i-2] / r[i-1]
1495 // r[i] = r[i-2] % r[i-1]
1496 // t[i] = t[i-2] - t[i-1] * q
1497 udivrem(r[i], r[i^1], q, r[i]);
1498 t[i] -= t[i^1] * q;
1499 }
1500
1501 // If this APInt and the modulo are not coprime, there is no multiplicative
1502 // inverse, so return 0. We check this by looking at the next-to-last
1503 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1504 // algorithm.
1505 if (r[i] != 1)
1506 return APInt(BitWidth, 0);
1507
1508 // The next-to-last t is the multiplicative inverse. However, we are
1509 // interested in a positive inverse. Calcuate a positive one from a negative
1510 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001511 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001512 return t[i].isNegative() ? t[i] + modulo : t[i];
1513}
1514
Jay Foadfe0c6482009-04-30 10:15:35 +00001515/// Calculate the magic numbers required to implement a signed integer division
1516/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1517/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1518/// Warren, Jr., chapter 10.
1519APInt::ms APInt::magic() const {
1520 const APInt& d = *this;
1521 unsigned p;
1522 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001523 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001524 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001525
Jay Foadfe0c6482009-04-30 10:15:35 +00001526 ad = d.abs();
1527 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1528 anc = t - 1 - t.urem(ad); // absolute value of nc
1529 p = d.getBitWidth() - 1; // initialize p
1530 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1531 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1532 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1533 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1534 do {
1535 p = p + 1;
1536 q1 = q1<<1; // update q1 = 2p/abs(nc)
1537 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1538 if (r1.uge(anc)) { // must be unsigned comparison
1539 q1 = q1 + 1;
1540 r1 = r1 - anc;
1541 }
1542 q2 = q2<<1; // update q2 = 2p/abs(d)
1543 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1544 if (r2.uge(ad)) { // must be unsigned comparison
1545 q2 = q2 + 1;
1546 r2 = r2 - ad;
1547 }
1548 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001549 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001550
Jay Foadfe0c6482009-04-30 10:15:35 +00001551 mag.m = q2 + 1;
1552 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1553 mag.s = p - d.getBitWidth(); // resulting shift
1554 return mag;
1555}
1556
1557/// Calculate the magic numbers required to implement an unsigned integer
1558/// division by a constant as a sequence of multiplies, adds and shifts.
1559/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1560/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001561/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001562/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001563APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001564 const APInt& d = *this;
1565 unsigned p;
1566 APInt nc, delta, q1, r1, q2, r2;
1567 struct mu magu;
1568 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001569 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001570 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1571 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1572
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001573 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001574 p = d.getBitWidth() - 1; // initialize p
1575 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1576 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1577 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1578 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1579 do {
1580 p = p + 1;
1581 if (r1.uge(nc - r1)) {
1582 q1 = q1 + q1 + 1; // update q1
1583 r1 = r1 + r1 - nc; // update r1
1584 }
1585 else {
1586 q1 = q1+q1; // update q1
1587 r1 = r1+r1; // update r1
1588 }
1589 if ((r2 + 1).uge(d - r2)) {
1590 if (q2.uge(signedMax)) magu.a = 1;
1591 q2 = q2+q2 + 1; // update q2
1592 r2 = r2+r2 + 1 - d; // update r2
1593 }
1594 else {
1595 if (q2.uge(signedMin)) magu.a = 1;
1596 q2 = q2+q2; // update q2
1597 r2 = r2+r2 + 1; // update r2
1598 }
1599 delta = d - 1 - r2;
1600 } while (p < d.getBitWidth()*2 &&
1601 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1602 magu.m = q2 + 1; // resulting magic number
1603 magu.s = p - d.getBitWidth(); // resulting shift
1604 return magu;
1605}
1606
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001607/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1608/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1609/// variables here have the same names as in the algorithm. Comments explain
1610/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001611static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1612 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001613 assert(u && "Must provide dividend");
1614 assert(v && "Must provide divisor");
1615 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001616 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001617 assert(n>1 && "n must be > 1");
1618
Yaron Keren39fc5a62015-03-26 19:45:19 +00001619 // b denotes the base of the number system. In our case b is 2^32.
George Burgess IV381fc0e2016-08-25 01:05:08 +00001620 const uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001621
David Greenef32fcb42010-01-05 01:28:52 +00001622 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1623 DEBUG(dbgs() << "KnuthDiv: original:");
1624 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1625 DEBUG(dbgs() << " by");
1626 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1627 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001628 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1629 // u and v by d. Note that we have taken Knuth's advice here to use a power
1630 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1631 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001632 // shift amount from the leading zeros. We are basically normalizing the u
1633 // and v so that its high bits are shifted to the top of v's range without
1634 // overflow. Note that this can require an extra word in u so that u must
1635 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001636 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001637 unsigned v_carry = 0;
1638 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001639 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001640 for (unsigned i = 0; i < m+n; ++i) {
1641 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001642 u[i] = (u[i] << shift) | u_carry;
1643 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001644 }
Chris Lattner77527f52009-01-21 18:09:24 +00001645 for (unsigned i = 0; i < n; ++i) {
1646 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001647 v[i] = (v[i] << shift) | v_carry;
1648 v_carry = v_tmp;
1649 }
1650 }
1651 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001652
David Greenef32fcb42010-01-05 01:28:52 +00001653 DEBUG(dbgs() << "KnuthDiv: normal:");
1654 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1655 DEBUG(dbgs() << " by");
1656 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1657 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001658
1659 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1660 int j = m;
1661 do {
David Greenef32fcb42010-01-05 01:28:52 +00001662 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001663 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001664 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1665 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1666 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1667 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1668 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001669 // value qp is one too large, and it eliminates all cases where qp is two
1670 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001671 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001672 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001673 uint64_t qp = dividend / v[n-1];
1674 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001675 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1676 qp--;
1677 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001678 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001679 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001680 }
David Greenef32fcb42010-01-05 01:28:52 +00001681 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001682
Reid Spencercb292e42007-02-23 01:57:13 +00001683 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1684 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1685 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001686 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001687 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1688 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1689 // true value plus b**(n+1), namely as the b's complement of
1690 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001691 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001692 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001693 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1694 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1695 u[j+i] = (unsigned)subres;
1696 borrow = (p >> 32) - (subres >> 32);
1697 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001698 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001699 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001700 bool isNeg = u[j+n] < borrow;
1701 u[j+n] -= (unsigned)borrow;
1702
David Greenef32fcb42010-01-05 01:28:52 +00001703 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1704 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1705 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001706
Eric Christopher820256b2009-08-21 04:06:45 +00001707 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001708 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001709 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001710 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001711 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001712 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001713 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001714 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001715 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1716 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001717 // since it cancels with the borrow that occurred in D4.
1718 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001719 for (unsigned i = 0; i < n; i++) {
1720 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001721 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001722 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001723 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001724 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001725 }
David Greenef32fcb42010-01-05 01:28:52 +00001726 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001727 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001728 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001729
Reid Spencercb292e42007-02-23 01:57:13 +00001730 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1731 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001732
David Greenef32fcb42010-01-05 01:28:52 +00001733 DEBUG(dbgs() << "KnuthDiv: quotient:");
1734 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1735 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001736
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001737 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1738 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1739 // compute the remainder (urem uses this).
1740 if (r) {
1741 // The value d is expressed by the "shift" value above since we avoided
1742 // multiplication by d by using a shift left. So, all we have to do is
Simon Pilgrim0099beb2017-03-09 13:57:04 +00001743 // shift right here.
Reid Spencer468ad9112007-02-24 20:38:01 +00001744 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001745 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001746 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001747 for (int i = n-1; i >= 0; i--) {
1748 r[i] = (u[i] >> shift) | carry;
1749 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001750 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001751 }
1752 } else {
1753 for (int i = n-1; i >= 0; i--) {
1754 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001755 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001756 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001757 }
David Greenef32fcb42010-01-05 01:28:52 +00001758 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001759 }
David Greenef32fcb42010-01-05 01:28:52 +00001760 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001761}
1762
Benjamin Kramerc321e532016-06-08 19:09:22 +00001763void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
1764 unsigned rhsWords, APInt *Quotient, APInt *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001765 assert(lhsWords >= rhsWords && "Fractional result");
1766
Eric Christopher820256b2009-08-21 04:06:45 +00001767 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001768 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001769 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001770 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1771 // can't use 64-bit operands here because we don't have native results of
1772 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001773 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001774 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001775 unsigned n = rhsWords * 2;
1776 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001777
1778 // Allocate space for the temporary values we need either on the stack, if
1779 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001780 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001781 unsigned *U = nullptr;
1782 unsigned *V = nullptr;
1783 unsigned *Q = nullptr;
1784 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001785 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1786 U = &SPACE[0];
1787 V = &SPACE[m+n+1];
1788 Q = &SPACE[(m+n+1) + n];
1789 if (Remainder)
1790 R = &SPACE[(m+n+1) + n + (m+n)];
1791 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001792 U = new unsigned[m + n + 1];
1793 V = new unsigned[n];
1794 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001795 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001796 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001797 }
1798
1799 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001800 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001801 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001802 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001803 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001804 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001805 }
1806 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1807
Reid Spencer522ca7c2007-02-25 01:56:07 +00001808 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001809 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001810 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001811 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001812 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001813 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001814 }
1815
Reid Spencer522ca7c2007-02-25 01:56:07 +00001816 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001817 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001818 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001819 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001820
Eric Christopher820256b2009-08-21 04:06:45 +00001821 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001822 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001823 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001824 // contain any zero words or the Knuth algorithm fails.
1825 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1826 n--;
1827 m++;
1828 }
1829 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1830 m--;
1831
1832 // If we're left with only a single word for the divisor, Knuth doesn't work
1833 // so we implement the short division algorithm here. This is much simpler
1834 // and faster because we are certain that we can divide a 64-bit quantity
1835 // by a 32-bit quantity at hardware speed and short division is simply a
1836 // series of such operations. This is just like doing short division but we
1837 // are using base 2^32 instead of base 10.
1838 assert(n != 0 && "Divide by zero?");
1839 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001840 unsigned divisor = V[0];
1841 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001842 for (int i = m+n-1; i >= 0; i--) {
1843 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1844 if (partial_dividend == 0) {
1845 Q[i] = 0;
1846 remainder = 0;
1847 } else if (partial_dividend < divisor) {
1848 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001849 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001850 } else if (partial_dividend == divisor) {
1851 Q[i] = 1;
1852 remainder = 0;
1853 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001854 Q[i] = (unsigned)(partial_dividend / divisor);
1855 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001856 }
1857 }
1858 if (R)
1859 R[0] = remainder;
1860 } else {
1861 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1862 // case n > 1.
1863 KnuthDiv(U, V, Q, R, m, n);
1864 }
1865
1866 // If the caller wants the quotient
1867 if (Quotient) {
1868 // Set up the Quotient value's memory.
1869 if (Quotient->BitWidth != LHS.BitWidth) {
1870 if (Quotient->isSingleWord())
1871 Quotient->VAL = 0;
1872 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001873 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001874 Quotient->BitWidth = LHS.BitWidth;
1875 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001876 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001877 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001878 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001879
Eric Christopher820256b2009-08-21 04:06:45 +00001880 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001881 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001882 // This case is currently dead as all users of divide() handle trivial cases
1883 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001884 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001885 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001886 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1887 if (Quotient->isSingleWord())
1888 Quotient->VAL = tmp;
1889 else
1890 Quotient->pVal[0] = tmp;
1891 } else {
1892 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1893 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001894 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001895 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1896 }
1897 }
1898
1899 // If the caller wants the remainder
1900 if (Remainder) {
1901 // Set up the Remainder value's memory.
1902 if (Remainder->BitWidth != RHS.BitWidth) {
1903 if (Remainder->isSingleWord())
1904 Remainder->VAL = 0;
1905 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001906 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001907 Remainder->BitWidth = RHS.BitWidth;
1908 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001909 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001910 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001911 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001912
1913 // The remainder is in R. Reconstitute the remainder into Remainder's low
1914 // order words.
1915 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001916 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001917 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1918 if (Remainder->isSingleWord())
1919 Remainder->VAL = tmp;
1920 else
1921 Remainder->pVal[0] = tmp;
1922 } else {
1923 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1924 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001925 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001926 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1927 }
1928 }
1929
1930 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001931 if (U != &SPACE[0]) {
1932 delete [] U;
1933 delete [] V;
1934 delete [] Q;
1935 delete [] R;
1936 }
Reid Spencer100502d2007-02-17 03:16:00 +00001937}
1938
Reid Spencer1d072122007-02-16 22:36:51 +00001939APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001940 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001941
1942 // First, deal with the easy case
1943 if (isSingleWord()) {
1944 assert(RHS.VAL != 0 && "Divide by zero?");
1945 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001946 }
Reid Spencer39867762007-02-17 02:07:07 +00001947
Reid Spencer39867762007-02-17 02:07:07 +00001948 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001949 unsigned rhsBits = RHS.getActiveBits();
1950 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001951 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001952 unsigned lhsBits = this->getActiveBits();
1953 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001954
1955 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001956 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001957 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001958 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001959 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001960 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001961 return APInt(BitWidth, 0);
1962 } else if (*this == RHS) {
1963 // X / X ===> 1
1964 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001965 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001966 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001967 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001968 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001969
1970 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1971 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001972 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001973 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001974}
1975
Jakub Staszak6605c602013-02-20 00:17:42 +00001976APInt APInt::sdiv(const APInt &RHS) const {
1977 if (isNegative()) {
1978 if (RHS.isNegative())
1979 return (-(*this)).udiv(-RHS);
1980 return -((-(*this)).udiv(RHS));
1981 }
1982 if (RHS.isNegative())
1983 return -(this->udiv(-RHS));
1984 return this->udiv(RHS);
1985}
1986
Reid Spencer1d072122007-02-16 22:36:51 +00001987APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001988 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001989 if (isSingleWord()) {
1990 assert(RHS.VAL != 0 && "Remainder by zero?");
1991 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001992 }
Reid Spencer39867762007-02-17 02:07:07 +00001993
Reid Spencer58a6a432007-02-21 08:21:52 +00001994 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001995 unsigned lhsBits = getActiveBits();
1996 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001997
1998 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001999 unsigned rhsBits = RHS.getActiveBits();
2000 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00002001 assert(rhsWords && "Performing remainder operation by zero ???");
2002
Reid Spencer39867762007-02-17 02:07:07 +00002003 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002004 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00002005 // 0 % Y ===> 0
2006 return APInt(BitWidth, 0);
2007 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002008 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00002009 return *this;
2010 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00002011 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00002012 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002013 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00002014 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00002015 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00002016 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002017
Reid Spencer4c50b522007-05-13 23:44:59 +00002018 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002019 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00002020 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002021 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00002022}
Reid Spencer100502d2007-02-17 03:16:00 +00002023
Jakub Staszak6605c602013-02-20 00:17:42 +00002024APInt APInt::srem(const APInt &RHS) const {
2025 if (isNegative()) {
2026 if (RHS.isNegative())
2027 return -((-(*this)).urem(-RHS));
2028 return -((-(*this)).urem(RHS));
2029 }
2030 if (RHS.isNegative())
2031 return this->urem(-RHS);
2032 return this->urem(RHS);
2033}
2034
Eric Christopher820256b2009-08-21 04:06:45 +00002035void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00002036 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00002037 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
2038
2039 // First, deal with the easy case
2040 if (LHS.isSingleWord()) {
2041 assert(RHS.VAL != 0 && "Divide by zero?");
2042 uint64_t QuotVal = LHS.VAL / RHS.VAL;
2043 uint64_t RemVal = LHS.VAL % RHS.VAL;
2044 Quotient = APInt(LHS.BitWidth, QuotVal);
2045 Remainder = APInt(LHS.BitWidth, RemVal);
2046 return;
2047 }
2048
Reid Spencer4c50b522007-05-13 23:44:59 +00002049 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00002050 unsigned lhsBits = LHS.getActiveBits();
2051 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
2052 unsigned rhsBits = RHS.getActiveBits();
2053 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00002054
2055 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00002056 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00002057 Quotient = 0; // 0 / Y ===> 0
2058 Remainder = 0; // 0 % Y ===> 0
2059 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002060 }
2061
2062 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002063 Remainder = LHS; // X % Y ===> X, iff X < Y
2064 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00002065 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002066 }
2067
Reid Spencer4c50b522007-05-13 23:44:59 +00002068 if (LHS == RHS) {
2069 Quotient = 1; // X / X ===> 1
2070 Remainder = 0; // X % X ===> 0;
2071 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002072 }
2073
Reid Spencer4c50b522007-05-13 23:44:59 +00002074 if (lhsWords == 1 && rhsWords == 1) {
2075 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00002076 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
2077 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
2078 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
2079 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00002080 return;
2081 }
2082
2083 // Okay, lets do it the long way
2084 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
2085}
2086
Jakub Staszak6605c602013-02-20 00:17:42 +00002087void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
2088 APInt &Quotient, APInt &Remainder) {
2089 if (LHS.isNegative()) {
2090 if (RHS.isNegative())
2091 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
2092 else {
2093 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
2094 Quotient = -Quotient;
2095 }
2096 Remainder = -Remainder;
2097 } else if (RHS.isNegative()) {
2098 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
2099 Quotient = -Quotient;
2100 } else {
2101 APInt::udivrem(LHS, RHS, Quotient, Remainder);
2102 }
2103}
2104
Chris Lattner2c819b02010-10-13 23:54:10 +00002105APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002106 APInt Res = *this+RHS;
2107 Overflow = isNonNegative() == RHS.isNonNegative() &&
2108 Res.isNonNegative() != isNonNegative();
2109 return Res;
2110}
2111
Chris Lattner698661c2010-10-14 00:05:07 +00002112APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
2113 APInt Res = *this+RHS;
2114 Overflow = Res.ult(RHS);
2115 return Res;
2116}
2117
Chris Lattner2c819b02010-10-13 23:54:10 +00002118APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002119 APInt Res = *this - RHS;
2120 Overflow = isNonNegative() != RHS.isNonNegative() &&
2121 Res.isNonNegative() != isNonNegative();
2122 return Res;
2123}
2124
Chris Lattner698661c2010-10-14 00:05:07 +00002125APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00002126 APInt Res = *this-RHS;
2127 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00002128 return Res;
2129}
2130
Chris Lattner2c819b02010-10-13 23:54:10 +00002131APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002132 // MININT/-1 --> overflow.
2133 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
2134 return sdiv(RHS);
2135}
2136
Chris Lattner2c819b02010-10-13 23:54:10 +00002137APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002138 APInt Res = *this * RHS;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002139
Chris Lattner79bdd882010-10-13 23:46:33 +00002140 if (*this != 0 && RHS != 0)
2141 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
2142 else
2143 Overflow = false;
2144 return Res;
2145}
2146
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00002147APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
2148 APInt Res = *this * RHS;
2149
2150 if (*this != 0 && RHS != 0)
2151 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
2152 else
2153 Overflow = false;
2154 return Res;
2155}
2156
David Majnemera2521382014-10-13 21:48:30 +00002157APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
2158 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00002159 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00002160 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00002161
2162 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00002163 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00002164 else
David Majnemera2521382014-10-13 21:48:30 +00002165 Overflow = ShAmt.uge(countLeadingOnes());
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002166
Chris Lattner79bdd882010-10-13 23:46:33 +00002167 return *this << ShAmt;
2168}
2169
David Majnemera2521382014-10-13 21:48:30 +00002170APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
2171 Overflow = ShAmt.uge(getBitWidth());
2172 if (Overflow)
2173 return APInt(BitWidth, 0);
2174
2175 Overflow = ShAmt.ugt(countLeadingZeros());
2176
2177 return *this << ShAmt;
2178}
2179
Chris Lattner79bdd882010-10-13 23:46:33 +00002180
2181
2182
Benjamin Kramer92d89982010-07-14 22:38:02 +00002183void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00002184 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002185 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002186 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002187 radix == 36) &&
2188 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002189
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002190 StringRef::iterator p = str.begin();
2191 size_t slen = str.size();
2192 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002193 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002194 p++;
2195 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00002196 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002197 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00002198 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002199 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2200 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002201 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2202 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00002203
2204 // Allocate memory
2205 if (!isSingleWord())
2206 pVal = getClearedMemory(getNumWords());
2207
2208 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00002209 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00002210
2211 // Set up an APInt for the digit to add outside the loop so we don't
2212 // constantly construct/destruct it.
2213 APInt apdigit(getBitWidth(), 0);
2214 APInt apradix(getBitWidth(), radix);
2215
2216 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002217 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00002218 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00002219 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00002220
Reid Spencera93c9812007-05-16 19:18:22 +00002221 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002222 if (slen > 1) {
2223 if (shift)
2224 *this <<= shift;
2225 else
2226 *this *= apradix;
2227 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002228
2229 // Add in the digit we just interpreted
Reid Spencer632ebdf2007-02-24 20:19:37 +00002230 if (apdigit.isSingleWord())
2231 apdigit.VAL = digit;
2232 else
2233 apdigit.pVal[0] = digit;
Reid Spencer1ba83352007-02-21 03:55:44 +00002234 *this += apdigit;
Reid Spencer100502d2007-02-17 03:16:00 +00002235 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002236 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00002237 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00002238 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002239 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002240 }
Reid Spencer100502d2007-02-17 03:16:00 +00002241}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002242
Chris Lattner17f71652008-08-17 07:19:36 +00002243void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002244 bool Signed, bool formatAsCLiteral) const {
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002245 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002246 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002247 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002248
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002249 const char *Prefix = "";
2250 if (formatAsCLiteral) {
2251 switch (Radix) {
2252 case 2:
2253 // Binary literals are a non-standard extension added in gcc 4.3:
2254 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2255 Prefix = "0b";
2256 break;
2257 case 8:
2258 Prefix = "0";
2259 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002260 case 10:
2261 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002262 case 16:
2263 Prefix = "0x";
2264 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002265 default:
2266 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002267 }
2268 }
2269
Chris Lattner17f71652008-08-17 07:19:36 +00002270 // First, check for a zero value and just short circuit the logic below.
2271 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002272 while (*Prefix) {
2273 Str.push_back(*Prefix);
2274 ++Prefix;
2275 };
Chris Lattner17f71652008-08-17 07:19:36 +00002276 Str.push_back('0');
2277 return;
2278 }
Eric Christopher820256b2009-08-21 04:06:45 +00002279
Douglas Gregor663c0682011-09-14 15:54:46 +00002280 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002281
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002282 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002283 char Buffer[65];
2284 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002285
Chris Lattner17f71652008-08-17 07:19:36 +00002286 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002287 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002288 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002289 } else {
2290 int64_t I = getSExtValue();
2291 if (I >= 0) {
2292 N = I;
2293 } else {
2294 Str.push_back('-');
2295 N = -(uint64_t)I;
2296 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002297 }
Eric Christopher820256b2009-08-21 04:06:45 +00002298
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002299 while (*Prefix) {
2300 Str.push_back(*Prefix);
2301 ++Prefix;
2302 };
2303
Chris Lattner17f71652008-08-17 07:19:36 +00002304 while (N) {
2305 *--BufPtr = Digits[N % Radix];
2306 N /= Radix;
2307 }
2308 Str.append(BufPtr, Buffer+65);
2309 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002310 }
2311
Chris Lattner17f71652008-08-17 07:19:36 +00002312 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002313
Chris Lattner17f71652008-08-17 07:19:36 +00002314 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002315 // They want to print the signed version and it is a negative value
2316 // Flip the bits and add one to turn it into the equivalent positive
2317 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002318 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002319 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002320 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002321 }
Eric Christopher820256b2009-08-21 04:06:45 +00002322
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002323 while (*Prefix) {
2324 Str.push_back(*Prefix);
2325 ++Prefix;
2326 };
2327
Chris Lattner17f71652008-08-17 07:19:36 +00002328 // We insert the digits backward, then reverse them to get the right order.
2329 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002330
2331 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2332 // because the number of bits per digit (1, 3 and 4 respectively) divides
Chris Lattner17f71652008-08-17 07:19:36 +00002333 // equaly. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002334 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002335 // Just shift tmp right for each digit width until it becomes zero
2336 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2337 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002338
Chris Lattner17f71652008-08-17 07:19:36 +00002339 while (Tmp != 0) {
2340 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2341 Str.push_back(Digits[Digit]);
2342 Tmp = Tmp.lshr(ShiftAmt);
2343 }
2344 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002345 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002346 while (Tmp != 0) {
2347 APInt APdigit(1, 0);
2348 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002349 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002350 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002351 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002352 assert(Digit < Radix && "divide failed");
2353 Str.push_back(Digits[Digit]);
2354 Tmp = tmp2;
2355 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002356 }
Eric Christopher820256b2009-08-21 04:06:45 +00002357
Chris Lattner17f71652008-08-17 07:19:36 +00002358 // Reverse the digits before returning.
2359 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002360}
2361
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002362/// Returns the APInt as a std::string. Note that this is an inefficient method.
2363/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002364std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2365 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002366 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002367 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002368}
Chris Lattner6b695682007-08-16 15:56:55 +00002369
Matthias Braun8c209aa2017-01-28 02:02:38 +00002370#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002371LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002372 SmallString<40> S, U;
2373 this->toStringUnsigned(U);
2374 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002375 dbgs() << "APInt(" << BitWidth << "b, "
Davide Italiano5a473d22017-01-31 21:26:18 +00002376 << U << "u " << S << "s)\n";
Chris Lattner17f71652008-08-17 07:19:36 +00002377}
Matthias Braun8c209aa2017-01-28 02:02:38 +00002378#endif
Chris Lattner17f71652008-08-17 07:19:36 +00002379
Chris Lattner0c19df42008-08-23 22:23:09 +00002380void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002381 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002382 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002383 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002384}
2385
Chris Lattner6b695682007-08-16 15:56:55 +00002386// This implements a variety of operations on a representation of
2387// arbitrary precision, two's-complement, bignum integer values.
2388
Chris Lattner96cffa62009-08-23 23:11:28 +00002389// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2390// and unrestricting assumption.
Benjamin Kramer7000ca32014-10-12 17:56:40 +00002391static_assert(integerPartWidth % 2 == 0, "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002392
2393/* Some handy functions local to this file. */
2394namespace {
2395
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002396 /* Returns the integer part with the least significant BITS set.
2397 BITS cannot be zero. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002398 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002399 lowBitMask(unsigned int bits)
2400 {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002401 assert(bits != 0 && bits <= integerPartWidth);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002402
2403 return ~(integerPart) 0 >> (integerPartWidth - bits);
2404 }
2405
Neil Boothc8b650a2007-10-06 00:43:45 +00002406 /* Returns the value of the lower half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002407 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002408 lowHalf(integerPart part)
2409 {
2410 return part & lowBitMask(integerPartWidth / 2);
2411 }
2412
Neil Boothc8b650a2007-10-06 00:43:45 +00002413 /* Returns the value of the upper half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002414 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002415 highHalf(integerPart part)
2416 {
2417 return part >> (integerPartWidth / 2);
2418 }
2419
Neil Boothc8b650a2007-10-06 00:43:45 +00002420 /* Returns the bit number of the most significant set bit of a part.
2421 If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002422 static unsigned int
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002423 partMSB(integerPart value)
Chris Lattner6b695682007-08-16 15:56:55 +00002424 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002425 return findLastSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002426 }
2427
Neil Boothc8b650a2007-10-06 00:43:45 +00002428 /* Returns the bit number of the least significant set bit of a
2429 part. If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002430 static unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002431 partLSB(integerPart value)
2432 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002433 return findFirstSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002434 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002435}
Chris Lattner6b695682007-08-16 15:56:55 +00002436
2437/* Sets the least significant part of a bignum to the input value, and
2438 zeroes out higher parts. */
2439void
2440APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts)
2441{
2442 unsigned int i;
2443
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002444 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002445
Chris Lattner6b695682007-08-16 15:56:55 +00002446 dst[0] = part;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002447 for (i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002448 dst[i] = 0;
2449}
2450
2451/* Assign one bignum to another. */
2452void
2453APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts)
2454{
2455 unsigned int i;
2456
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002457 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002458 dst[i] = src[i];
2459}
2460
2461/* Returns true if a bignum is zero, false otherwise. */
2462bool
2463APInt::tcIsZero(const integerPart *src, unsigned int parts)
2464{
2465 unsigned int i;
2466
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002467 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002468 if (src[i])
2469 return false;
2470
2471 return true;
2472}
2473
2474/* Extract the given bit of a bignum; returns 0 or 1. */
2475int
2476APInt::tcExtractBit(const integerPart *parts, unsigned int bit)
2477{
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002478 return (parts[bit / integerPartWidth] &
2479 ((integerPart) 1 << bit % integerPartWidth)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002480}
2481
John McCalldcb9a7a2010-02-28 02:51:25 +00002482/* Set the given bit of a bignum. */
Chris Lattner6b695682007-08-16 15:56:55 +00002483void
2484APInt::tcSetBit(integerPart *parts, unsigned int bit)
2485{
2486 parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
2487}
2488
John McCalldcb9a7a2010-02-28 02:51:25 +00002489/* Clears the given bit of a bignum. */
2490void
2491APInt::tcClearBit(integerPart *parts, unsigned int bit)
2492{
2493 parts[bit / integerPartWidth] &=
2494 ~((integerPart) 1 << (bit % integerPartWidth));
2495}
2496
Neil Boothc8b650a2007-10-06 00:43:45 +00002497/* Returns the bit number of the least significant set bit of a
2498 number. If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002499unsigned int
2500APInt::tcLSB(const integerPart *parts, unsigned int n)
2501{
2502 unsigned int i, lsb;
2503
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002504 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002505 if (parts[i] != 0) {
2506 lsb = partLSB(parts[i]);
2507
2508 return lsb + i * integerPartWidth;
2509 }
2510 }
2511
2512 return -1U;
2513}
2514
Neil Boothc8b650a2007-10-06 00:43:45 +00002515/* Returns the bit number of the most significant set bit of a number.
2516 If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002517unsigned int
2518APInt::tcMSB(const integerPart *parts, unsigned int n)
2519{
2520 unsigned int msb;
2521
2522 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002523 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002524
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002525 if (parts[n] != 0) {
2526 msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002527
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002528 return msb + n * integerPartWidth;
2529 }
Chris Lattner6b695682007-08-16 15:56:55 +00002530 } while (n);
2531
2532 return -1U;
2533}
2534
Neil Boothb6182162007-10-08 13:47:12 +00002535/* Copy the bit vector of width srcBITS from SRC, starting at bit
2536 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2537 the least significant bit of DST. All high bits above srcBITS in
2538 DST are zero-filled. */
2539void
Evan Chengdb338f32009-05-21 23:47:47 +00002540APInt::tcExtract(integerPart *dst, unsigned int dstCount,const integerPart *src,
Neil Boothb6182162007-10-08 13:47:12 +00002541 unsigned int srcBits, unsigned int srcLSB)
2542{
2543 unsigned int firstSrcPart, dstParts, shift, n;
2544
2545 dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002546 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002547
2548 firstSrcPart = srcLSB / integerPartWidth;
2549 tcAssign (dst, src + firstSrcPart, dstParts);
2550
2551 shift = srcLSB % integerPartWidth;
2552 tcShiftRight (dst, dstParts, shift);
2553
2554 /* We now have (dstParts * integerPartWidth - shift) bits from SRC
2555 in DST. If this is less that srcBits, append the rest, else
2556 clear the high bits. */
2557 n = dstParts * integerPartWidth - shift;
2558 if (n < srcBits) {
2559 integerPart mask = lowBitMask (srcBits - n);
2560 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2561 << n % integerPartWidth);
2562 } else if (n > srcBits) {
Neil Booth7e74b172007-10-12 15:31:31 +00002563 if (srcBits % integerPartWidth)
2564 dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
Neil Boothb6182162007-10-08 13:47:12 +00002565 }
2566
2567 /* Clear high parts. */
2568 while (dstParts < dstCount)
2569 dst[dstParts++] = 0;
2570}
2571
Chris Lattner6b695682007-08-16 15:56:55 +00002572/* DST += RHS + C where C is zero or one. Returns the carry flag. */
2573integerPart
2574APInt::tcAdd(integerPart *dst, const integerPart *rhs,
2575 integerPart c, unsigned int parts)
2576{
2577 unsigned int i;
2578
2579 assert(c <= 1);
2580
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002581 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002582 integerPart l;
2583
2584 l = dst[i];
2585 if (c) {
2586 dst[i] += rhs[i] + 1;
2587 c = (dst[i] <= l);
2588 } else {
2589 dst[i] += rhs[i];
2590 c = (dst[i] < l);
2591 }
2592 }
2593
2594 return c;
2595}
2596
2597/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
2598integerPart
2599APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
2600 integerPart c, unsigned int parts)
2601{
2602 unsigned int i;
2603
2604 assert(c <= 1);
2605
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002606 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002607 integerPart l;
2608
2609 l = dst[i];
2610 if (c) {
2611 dst[i] -= rhs[i] + 1;
2612 c = (dst[i] >= l);
2613 } else {
2614 dst[i] -= rhs[i];
2615 c = (dst[i] > l);
2616 }
2617 }
2618
2619 return c;
2620}
2621
2622/* Negate a bignum in-place. */
2623void
2624APInt::tcNegate(integerPart *dst, unsigned int parts)
2625{
2626 tcComplement(dst, parts);
2627 tcIncrement(dst, parts);
2628}
2629
Neil Boothc8b650a2007-10-06 00:43:45 +00002630/* DST += SRC * MULTIPLIER + CARRY if add is true
2631 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002632
2633 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2634 they must start at the same point, i.e. DST == SRC.
2635
2636 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2637 returned. Otherwise DST is filled with the least significant
2638 DSTPARTS parts of the result, and if all of the omitted higher
2639 parts were zero return zero, otherwise overflow occurred and
2640 return one. */
2641int
2642APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
2643 integerPart multiplier, integerPart carry,
2644 unsigned int srcParts, unsigned int dstParts,
2645 bool add)
2646{
2647 unsigned int i, n;
2648
2649 /* Otherwise our writes of DST kill our later reads of SRC. */
2650 assert(dst <= src || dst >= src + srcParts);
2651 assert(dstParts <= srcParts + 1);
2652
2653 /* N loops; minimum of dstParts and srcParts. */
2654 n = dstParts < srcParts ? dstParts: srcParts;
2655
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002656 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002657 integerPart low, mid, high, srcPart;
2658
2659 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2660
2661 This cannot overflow, because
2662
2663 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2664
2665 which is less than n^2. */
2666
2667 srcPart = src[i];
2668
2669 if (multiplier == 0 || srcPart == 0) {
2670 low = carry;
2671 high = 0;
2672 } else {
2673 low = lowHalf(srcPart) * lowHalf(multiplier);
2674 high = highHalf(srcPart) * highHalf(multiplier);
2675
2676 mid = lowHalf(srcPart) * highHalf(multiplier);
2677 high += highHalf(mid);
2678 mid <<= integerPartWidth / 2;
2679 if (low + mid < low)
2680 high++;
2681 low += mid;
2682
2683 mid = highHalf(srcPart) * lowHalf(multiplier);
2684 high += highHalf(mid);
2685 mid <<= integerPartWidth / 2;
2686 if (low + mid < low)
2687 high++;
2688 low += mid;
2689
2690 /* Now add carry. */
2691 if (low + carry < low)
2692 high++;
2693 low += carry;
2694 }
2695
2696 if (add) {
2697 /* And now DST[i], and store the new low part there. */
2698 if (low + dst[i] < low)
2699 high++;
2700 dst[i] += low;
2701 } else
2702 dst[i] = low;
2703
2704 carry = high;
2705 }
2706
2707 if (i < dstParts) {
2708 /* Full multiplication, there is no overflow. */
2709 assert(i + 1 == dstParts);
2710 dst[i] = carry;
2711 return 0;
2712 } else {
2713 /* We overflowed if there is carry. */
2714 if (carry)
2715 return 1;
2716
2717 /* We would overflow if any significant unwritten parts would be
2718 non-zero. This is true if any remaining src parts are non-zero
2719 and the multiplier is non-zero. */
2720 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002721 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002722 if (src[i])
2723 return 1;
2724
2725 /* We fitted in the narrow destination. */
2726 return 0;
2727 }
2728}
2729
2730/* DST = LHS * RHS, where DST has the same width as the operands and
2731 is filled with the least significant parts of the result. Returns
2732 one if overflow occurred, otherwise zero. DST must be disjoint
2733 from both operands. */
2734int
2735APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
2736 const integerPart *rhs, unsigned int parts)
2737{
2738 unsigned int i;
2739 int overflow;
2740
2741 assert(dst != lhs && dst != rhs);
2742
2743 overflow = 0;
2744 tcSet(dst, 0, parts);
2745
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002746 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002747 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2748 parts - i, true);
2749
2750 return overflow;
2751}
2752
Neil Booth0ea72a92007-10-06 00:24:48 +00002753/* DST = LHS * RHS, where DST has width the sum of the widths of the
2754 operands. No overflow occurs. DST must be disjoint from both
2755 operands. Returns the number of parts required to hold the
2756 result. */
2757unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002758APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
Neil Booth0ea72a92007-10-06 00:24:48 +00002759 const integerPart *rhs, unsigned int lhsParts,
2760 unsigned int rhsParts)
Chris Lattner6b695682007-08-16 15:56:55 +00002761{
Neil Booth0ea72a92007-10-06 00:24:48 +00002762 /* Put the narrower number on the LHS for less loops below. */
2763 if (lhsParts > rhsParts) {
2764 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2765 } else {
2766 unsigned int n;
Chris Lattner6b695682007-08-16 15:56:55 +00002767
Neil Booth0ea72a92007-10-06 00:24:48 +00002768 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002769
Neil Booth0ea72a92007-10-06 00:24:48 +00002770 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002771
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002772 for (n = 0; n < lhsParts; n++)
Neil Booth0ea72a92007-10-06 00:24:48 +00002773 tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002774
Neil Booth0ea72a92007-10-06 00:24:48 +00002775 n = lhsParts + rhsParts;
2776
2777 return n - (dst[n - 1] == 0);
2778 }
Chris Lattner6b695682007-08-16 15:56:55 +00002779}
2780
2781/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2782 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2783 set REMAINDER to the remainder, return zero. i.e.
2784
2785 OLD_LHS = RHS * LHS + REMAINDER
2786
2787 SCRATCH is a bignum of the same size as the operands and result for
2788 use by the routine; its contents need not be initialized and are
2789 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2790*/
2791int
2792APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
2793 integerPart *remainder, integerPart *srhs,
2794 unsigned int parts)
2795{
2796 unsigned int n, shiftCount;
2797 integerPart mask;
2798
2799 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2800
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002801 shiftCount = tcMSB(rhs, parts) + 1;
2802 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002803 return true;
2804
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002805 shiftCount = parts * integerPartWidth - shiftCount;
Chris Lattner6b695682007-08-16 15:56:55 +00002806 n = shiftCount / integerPartWidth;
2807 mask = (integerPart) 1 << (shiftCount % integerPartWidth);
2808
2809 tcAssign(srhs, rhs, parts);
2810 tcShiftLeft(srhs, parts, shiftCount);
2811 tcAssign(remainder, lhs, parts);
2812 tcSet(lhs, 0, parts);
2813
2814 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2815 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002816 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002817 int compare;
2818
2819 compare = tcCompare(remainder, srhs, parts);
2820 if (compare >= 0) {
2821 tcSubtract(remainder, srhs, 0, parts);
2822 lhs[n] |= mask;
2823 }
2824
2825 if (shiftCount == 0)
2826 break;
2827 shiftCount--;
2828 tcShiftRight(srhs, parts, 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002829 if ((mask >>= 1) == 0) {
2830 mask = (integerPart) 1 << (integerPartWidth - 1);
2831 n--;
2832 }
Chris Lattner6b695682007-08-16 15:56:55 +00002833 }
2834
2835 return false;
2836}
2837
2838/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2839 There are no restrictions on COUNT. */
2840void
2841APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count)
2842{
Neil Boothb6182162007-10-08 13:47:12 +00002843 if (count) {
2844 unsigned int jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002845
Neil Boothb6182162007-10-08 13:47:12 +00002846 /* Jump is the inter-part jump; shift is is intra-part shift. */
2847 jump = count / integerPartWidth;
2848 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002849
Neil Boothb6182162007-10-08 13:47:12 +00002850 while (parts > jump) {
2851 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002852
Neil Boothb6182162007-10-08 13:47:12 +00002853 parts--;
Chris Lattner6b695682007-08-16 15:56:55 +00002854
Neil Boothb6182162007-10-08 13:47:12 +00002855 /* dst[i] comes from the two parts src[i - jump] and, if we have
2856 an intra-part shift, src[i - jump - 1]. */
2857 part = dst[parts - jump];
2858 if (shift) {
2859 part <<= shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002860 if (parts >= jump + 1)
2861 part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
2862 }
2863
Neil Boothb6182162007-10-08 13:47:12 +00002864 dst[parts] = part;
2865 }
Chris Lattner6b695682007-08-16 15:56:55 +00002866
Neil Boothb6182162007-10-08 13:47:12 +00002867 while (parts > 0)
2868 dst[--parts] = 0;
2869 }
Chris Lattner6b695682007-08-16 15:56:55 +00002870}
2871
2872/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2873 zero. There are no restrictions on COUNT. */
2874void
2875APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count)
2876{
Neil Boothb6182162007-10-08 13:47:12 +00002877 if (count) {
2878 unsigned int i, jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002879
Neil Boothb6182162007-10-08 13:47:12 +00002880 /* Jump is the inter-part jump; shift is is intra-part shift. */
2881 jump = count / integerPartWidth;
2882 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002883
Neil Boothb6182162007-10-08 13:47:12 +00002884 /* Perform the shift. This leaves the most significant COUNT bits
2885 of the result at zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002886 for (i = 0; i < parts; i++) {
Neil Boothb6182162007-10-08 13:47:12 +00002887 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002888
Neil Boothb6182162007-10-08 13:47:12 +00002889 if (i + jump >= parts) {
2890 part = 0;
2891 } else {
2892 part = dst[i + jump];
2893 if (shift) {
2894 part >>= shift;
2895 if (i + jump + 1 < parts)
2896 part |= dst[i + jump + 1] << (integerPartWidth - shift);
2897 }
Chris Lattner6b695682007-08-16 15:56:55 +00002898 }
Chris Lattner6b695682007-08-16 15:56:55 +00002899
Neil Boothb6182162007-10-08 13:47:12 +00002900 dst[i] = part;
2901 }
Chris Lattner6b695682007-08-16 15:56:55 +00002902 }
2903}
2904
2905/* Bitwise and of two bignums. */
2906void
2907APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts)
2908{
2909 unsigned int i;
2910
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002911 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002912 dst[i] &= rhs[i];
2913}
2914
2915/* Bitwise inclusive or of two bignums. */
2916void
2917APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts)
2918{
2919 unsigned int i;
2920
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002921 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002922 dst[i] |= rhs[i];
2923}
2924
2925/* Bitwise exclusive or of two bignums. */
2926void
2927APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts)
2928{
2929 unsigned int i;
2930
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002931 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002932 dst[i] ^= rhs[i];
2933}
2934
2935/* Complement a bignum in-place. */
2936void
2937APInt::tcComplement(integerPart *dst, unsigned int parts)
2938{
2939 unsigned int i;
2940
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002941 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002942 dst[i] = ~dst[i];
2943}
2944
2945/* Comparison (unsigned) of two bignums. */
2946int
2947APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
2948 unsigned int parts)
2949{
2950 while (parts) {
2951 parts--;
2952 if (lhs[parts] == rhs[parts])
2953 continue;
2954
2955 if (lhs[parts] > rhs[parts])
2956 return 1;
2957 else
2958 return -1;
2959 }
2960
2961 return 0;
2962}
2963
2964/* Increment a bignum in-place, return the carry flag. */
2965integerPart
2966APInt::tcIncrement(integerPart *dst, unsigned int parts)
2967{
2968 unsigned int i;
2969
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002970 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002971 if (++dst[i] != 0)
2972 break;
2973
2974 return i == parts;
2975}
2976
Michael Gottesman9d406f42013-05-28 19:50:20 +00002977/* Decrement a bignum in-place, return the borrow flag. */
2978integerPart
2979APInt::tcDecrement(integerPart *dst, unsigned int parts) {
2980 for (unsigned int i = 0; i < parts; i++) {
2981 // If the current word is non-zero, then the decrement has no effect on the
2982 // higher-order words of the integer and no borrow can occur. Exit early.
2983 if (dst[i]--)
2984 return 0;
2985 }
2986 // If every word was zero, then there is a borrow.
2987 return 1;
2988}
2989
2990
Chris Lattner6b695682007-08-16 15:56:55 +00002991/* Set the least significant BITS bits of a bignum, clear the
2992 rest. */
2993void
2994APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts,
2995 unsigned int bits)
2996{
2997 unsigned int i;
2998
2999 i = 0;
3000 while (bits > integerPartWidth) {
3001 dst[i++] = ~(integerPart) 0;
3002 bits -= integerPartWidth;
3003 }
3004
3005 if (bits)
3006 dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
3007
3008 while (i < parts)
3009 dst[i++] = 0;
3010}