blob: 1fae0e9b8d6db8a361785037f5d8334e690c2f25 [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"
Nico Weber432a3882018-04-30 14:59:11 +000021#include "llvm/Config/llvm-config.h"
Reid Spencera5e0d202007-02-24 03:58:46 +000022#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000023#include "llvm/Support/ErrorHandling.h"
Zhou Shengdac63782007-02-06 03:00:16 +000024#include "llvm/Support/MathExtras.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000025#include "llvm/Support/raw_ostream.h"
Vassil Vassilev2ec8b152016-09-14 08:55:18 +000026#include <climits>
Chris Lattner17f71652008-08-17 07:19:36 +000027#include <cmath>
Zhou Shengdac63782007-02-06 03:00:16 +000028#include <cstdlib>
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include <cstring>
Zhou Shengdac63782007-02-06 03:00:16 +000030using namespace llvm;
31
Chandler Carruth64648262014-04-22 03:07:47 +000032#define DEBUG_TYPE "apint"
33
Reid Spencera41e93b2007-02-25 19:32:03 +000034/// A utility function for allocating memory, checking for allocation failures,
35/// and ensuring the contents are zeroed.
Chris Lattner77527f52009-01-21 18:09:24 +000036inline static uint64_t* getClearedMemory(unsigned numWords) {
Fangrui Songc244a152018-03-23 17:26:12 +000037 uint64_t *result = new uint64_t[numWords];
Reid Spencera856b6e2007-02-18 18:38:44 +000038 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) {
Fangrui Songc244a152018-03-23 17:26:12 +000045 return new uint64_t[numWords];
Reid Spencera856b6e2007-02-18 18:38:44 +000046}
47
Erick Tryzelaardadb15712009-08-21 03:15:28 +000048/// A utility function that converts a character to a digit.
49inline static unsigned getDigit(char cdigit, uint8_t radix) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000050 unsigned r;
51
Douglas Gregor663c0682011-09-14 15:54:46 +000052 if (radix == 16 || radix == 36) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000053 r = cdigit - '0';
54 if (r <= 9)
55 return r;
56
57 r = cdigit - 'A';
Douglas Gregorc98ac852011-09-20 18:33:29 +000058 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000059 return r + 10;
60
61 r = cdigit - 'a';
Douglas Gregorc98ac852011-09-20 18:33:29 +000062 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000063 return r + 10;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +000064
Douglas Gregore4e20f42011-09-20 18:11:52 +000065 radix = 10;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000066 }
67
Erick Tryzelaar60964092009-08-21 06:48:37 +000068 r = cdigit - '0';
69 if (r < radix)
70 return r;
71
72 return -1U;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000073}
74
75
Pawel Bylica68304012016-06-27 08:31:48 +000076void APInt::initSlowCase(uint64_t val, bool isSigned) {
Craig Topperb339c6d2017-05-03 15:46:24 +000077 U.pVal = getClearedMemory(getNumWords());
78 U.pVal[0] = val;
Eric Christopher820256b2009-08-21 04:06:45 +000079 if (isSigned && int64_t(val) < 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +000080 for (unsigned i = 1; i < getNumWords(); ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +000081 U.pVal[i] = WORD_MAX;
Craig Topperf78a6f02017-03-01 21:06:18 +000082 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +000083}
84
Chris Lattnerd57b7602008-10-11 22:07:19 +000085void APInt::initSlowCase(const APInt& that) {
Craig Topperb339c6d2017-05-03 15:46:24 +000086 U.pVal = getMemory(getNumWords());
87 memcpy(U.pVal, that.U.pVal, getNumWords() * APINT_WORD_SIZE);
Chris Lattnerd57b7602008-10-11 22:07:19 +000088}
89
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000090void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +000091 assert(BitWidth && "Bitwidth too small");
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000092 assert(bigVal.data() && "Null pointer detected!");
Zhou Shengdac63782007-02-06 03:00:16 +000093 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +000094 U.VAL = bigVal[0];
Zhou Shengdac63782007-02-06 03:00:16 +000095 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000096 // Get memory, cleared to 0
Craig Topperb339c6d2017-05-03 15:46:24 +000097 U.pVal = getClearedMemory(getNumWords());
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000098 // Calculate the number of words to copy
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000099 unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000100 // Copy the words from bigVal to pVal
Craig Topperb339c6d2017-05-03 15:46:24 +0000101 memcpy(U.pVal, bigVal.data(), words * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000102 }
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000103 // Make sure unused high bits are cleared
104 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000105}
106
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000107APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal)
Craig Topper0085ffb2017-03-20 01:29:52 +0000108 : BitWidth(numBits) {
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000109 initFromArray(bigVal);
110}
111
112APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
Craig Topper0085ffb2017-03-20 01:29:52 +0000113 : BitWidth(numBits) {
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000114 initFromArray(makeArrayRef(bigVal, numWords));
115}
116
Benjamin Kramer92d89982010-07-14 22:38:02 +0000117APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
Craig Topperb339c6d2017-05-03 15:46:24 +0000118 : BitWidth(numbits) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000119 assert(BitWidth && "Bitwidth too small");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000120 fromString(numbits, Str, radix);
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000121}
122
Craig Toppera92fd0b2017-05-12 01:46:01 +0000123void APInt::reallocate(unsigned NewBitWidth) {
124 // If the number of words is the same we can just change the width and stop.
125 if (getNumWords() == getNumWords(NewBitWidth)) {
126 BitWidth = NewBitWidth;
127 return;
128 }
129
130 // If we have an allocation, delete it.
131 if (!isSingleWord())
132 delete [] U.pVal;
133
134 // Update BitWidth.
135 BitWidth = NewBitWidth;
136
137 // If we are supposed to have an allocation, create it.
138 if (!isSingleWord())
139 U.pVal = getMemory(getNumWords());
140}
141
Craig Topperc67fe572017-04-19 17:01:58 +0000142void APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer7c16cd22007-02-26 23:38:21 +0000143 // Don't do anything for X = X
144 if (this == &RHS)
Craig Topperc67fe572017-04-19 17:01:58 +0000145 return;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000146
Craig Toppera92fd0b2017-05-12 01:46:01 +0000147 // Adjust the bit width and handle allocations as necessary.
148 reallocate(RHS.getBitWidth());
Reid Spencer7c16cd22007-02-26 23:38:21 +0000149
Craig Toppera92fd0b2017-05-12 01:46:01 +0000150 // Copy the data.
151 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000152 U.VAL = RHS.U.VAL;
Craig Toppera92fd0b2017-05-12 01:46:01 +0000153 else
154 memcpy(U.pVal, RHS.U.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000155}
156
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000157/// This method 'profiles' an APInt for use with FoldingSet.
Ted Kremenek5c75d542008-01-19 04:23:33 +0000158void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremenek901540f2008-02-19 20:50:41 +0000159 ID.AddInteger(BitWidth);
Eric Christopher820256b2009-08-21 04:06:45 +0000160
Ted Kremenek5c75d542008-01-19 04:23:33 +0000161 if (isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000162 ID.AddInteger(U.VAL);
Ted Kremenek5c75d542008-01-19 04:23:33 +0000163 return;
164 }
165
Chris Lattner77527f52009-01-21 18:09:24 +0000166 unsigned NumWords = getNumWords();
Ted Kremenek5c75d542008-01-19 04:23:33 +0000167 for (unsigned i = 0; i < NumWords; ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +0000168 ID.AddInteger(U.pVal[i]);
Ted Kremenek5c75d542008-01-19 04:23:33 +0000169}
170
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000171/// Prefix increment operator. Increments the APInt by one.
Zhou Shengdac63782007-02-06 03:00:16 +0000172APInt& APInt::operator++() {
Eric Christopher820256b2009-08-21 04:06:45 +0000173 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000174 ++U.VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000175 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000176 tcIncrement(U.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000177 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000178}
179
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000180/// Prefix decrement operator. Decrements the APInt by one.
Zhou Shengdac63782007-02-06 03:00:16 +0000181APInt& APInt::operator--() {
Eric Christopher820256b2009-08-21 04:06:45 +0000182 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000183 --U.VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000184 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000185 tcDecrement(U.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000186 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000187}
188
Reid Spencera41e93b2007-02-25 19:32:03 +0000189/// Adds the RHS APint to this APInt.
190/// @returns this, after addition of RHS.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000191/// Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000192APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000193 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000194 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000195 U.VAL += RHS.U.VAL;
Craig Topper15e484a2017-04-02 06:59:43 +0000196 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000197 tcAdd(U.pVal, RHS.U.pVal, 0, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000198 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000199}
200
Pete Cooperfea21392016-07-22 20:55:46 +0000201APInt& APInt::operator+=(uint64_t RHS) {
202 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000203 U.VAL += RHS;
Pete Cooperfea21392016-07-22 20:55:46 +0000204 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000205 tcAddPart(U.pVal, RHS, getNumWords());
Pete Cooperfea21392016-07-22 20:55:46 +0000206 return clearUnusedBits();
207}
208
Reid Spencera41e93b2007-02-25 19:32:03 +0000209/// Subtracts the RHS APInt from this APInt
210/// @returns this, after subtraction
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000211/// Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000212APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000213 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000214 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000215 U.VAL -= RHS.U.VAL;
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000216 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000217 tcSubtract(U.pVal, RHS.U.pVal, 0, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000218 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000219}
220
Pete Cooperfea21392016-07-22 20:55:46 +0000221APInt& APInt::operator-=(uint64_t RHS) {
222 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000223 U.VAL -= RHS;
Pete Cooperfea21392016-07-22 20:55:46 +0000224 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000225 tcSubtractPart(U.pVal, RHS, getNumWords());
Pete Cooperfea21392016-07-22 20:55:46 +0000226 return clearUnusedBits();
227}
228
Craig Topper93c68e12017-05-04 17:00:41 +0000229APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000230 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Craig Topper93c68e12017-05-04 17:00:41 +0000231 if (isSingleWord())
232 return APInt(BitWidth, U.VAL * RHS.U.VAL);
Reid Spencer58a6a432007-02-21 08:21:52 +0000233
Craig Topper93c68e12017-05-04 17:00:41 +0000234 APInt Result(getMemory(getNumWords()), getBitWidth());
Reid Spencer58a6a432007-02-21 08:21:52 +0000235
Craig Topper93c68e12017-05-04 17:00:41 +0000236 tcMultiply(Result.U.pVal, U.pVal, RHS.U.pVal, getNumWords());
Reid Spencer58a6a432007-02-21 08:21:52 +0000237
Craig Topper93c68e12017-05-04 17:00:41 +0000238 Result.clearUnusedBits();
239 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000240}
241
Craig Topperc67fe572017-04-19 17:01:58 +0000242void APInt::AndAssignSlowCase(const APInt& RHS) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000243 tcAnd(U.pVal, RHS.U.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000244}
245
Craig Topperc67fe572017-04-19 17:01:58 +0000246void APInt::OrAssignSlowCase(const APInt& RHS) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000247 tcOr(U.pVal, RHS.U.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000248}
249
Craig Topperc67fe572017-04-19 17:01:58 +0000250void APInt::XorAssignSlowCase(const APInt& RHS) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000251 tcXor(U.pVal, RHS.U.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000252}
253
Craig Topper93c68e12017-05-04 17:00:41 +0000254APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000255 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Craig Topper93c68e12017-05-04 17:00:41 +0000256 *this = *this * RHS;
257 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000258}
259
Craig Toppera51941f2017-05-08 04:55:09 +0000260APInt& APInt::operator*=(uint64_t RHS) {
261 if (isSingleWord()) {
262 U.VAL *= RHS;
263 } else {
264 unsigned NumWords = getNumWords();
265 tcMultiplyPart(U.pVal, U.pVal, RHS, 0, NumWords, NumWords, false);
266 }
267 return clearUnusedBits();
268}
269
Chris Lattner1ac3e252008-08-20 17:02:31 +0000270bool APInt::EqualSlowCase(const APInt& RHS) const {
Craig Topperb339c6d2017-05-03 15:46:24 +0000271 return std::equal(U.pVal, U.pVal + getNumWords(), RHS.U.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000272}
273
Craig Topper1dc8fc82017-04-21 16:13:15 +0000274int APInt::compare(const APInt& RHS) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000275 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
276 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000277 return U.VAL < RHS.U.VAL ? -1 : U.VAL > RHS.U.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000278
Craig Topperb339c6d2017-05-03 15:46:24 +0000279 return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000280}
281
Craig Topper1dc8fc82017-04-21 16:13:15 +0000282int APInt::compareSigned(const APInt& RHS) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000283 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000284 if (isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000285 int64_t lhsSext = SignExtend64(U.VAL, BitWidth);
286 int64_t rhsSext = SignExtend64(RHS.U.VAL, BitWidth);
Craig Topper1dc8fc82017-04-21 16:13:15 +0000287 return lhsSext < rhsSext ? -1 : lhsSext > rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000288 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000289
Reid Spencer54abdcf2007-02-27 18:23:40 +0000290 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000291 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000292
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000293 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
294 if (lhsNeg != rhsNeg)
Craig Topper1dc8fc82017-04-21 16:13:15 +0000295 return lhsNeg ? -1 : 1;
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000296
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000297 // Otherwise we can just use an unsigned comparison, because even negative
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000298 // numbers compare correctly this way if both have the same signed-ness.
Craig Topperb339c6d2017-05-03 15:46:24 +0000299 return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000300}
301
Craig Topperbafdd032017-03-07 01:56:01 +0000302void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
303 unsigned loWord = whichWord(loBit);
304 unsigned hiWord = whichWord(hiBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000305
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000306 // Create an initial mask for the low word with zeros below loBit.
Craig Topper5e113742017-04-22 06:31:36 +0000307 uint64_t loMask = WORD_MAX << whichBit(loBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000308
Craig Topperbafdd032017-03-07 01:56:01 +0000309 // If hiBit is not aligned, we need a high mask.
310 unsigned hiShiftAmt = whichBit(hiBit);
311 if (hiShiftAmt != 0) {
312 // Create a high mask with zeros above hiBit.
Craig Topper5e113742017-04-22 06:31:36 +0000313 uint64_t hiMask = WORD_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
Craig Topperbafdd032017-03-07 01:56:01 +0000314 // If loWord and hiWord are equal, then we combine the masks. Otherwise,
315 // set the bits in hiWord.
316 if (hiWord == loWord)
317 loMask &= hiMask;
318 else
Craig Topperb339c6d2017-05-03 15:46:24 +0000319 U.pVal[hiWord] |= hiMask;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000320 }
Craig Topperbafdd032017-03-07 01:56:01 +0000321 // Apply the mask to the low word.
Craig Topperb339c6d2017-05-03 15:46:24 +0000322 U.pVal[loWord] |= loMask;
Craig Topperbafdd032017-03-07 01:56:01 +0000323
324 // Fill any words between loWord and hiWord with all ones.
325 for (unsigned word = loWord + 1; word < hiWord; ++word)
Craig Topperb339c6d2017-05-03 15:46:24 +0000326 U.pVal[word] = WORD_MAX;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000327}
328
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000329/// Toggle every bit to its opposite value.
Craig Topperafc9e352017-03-27 17:10:21 +0000330void APInt::flipAllBitsSlowCase() {
Craig Topperb339c6d2017-05-03 15:46:24 +0000331 tcComplement(U.pVal, getNumWords());
Craig Topperafc9e352017-03-27 17:10:21 +0000332 clearUnusedBits();
333}
Zhou Shengdac63782007-02-06 03:00:16 +0000334
Eric Christopher820256b2009-08-21 04:06:45 +0000335/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000336/// as "bitPosition".
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000337/// Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000338void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000339 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000340 if ((*this)[bitPosition]) clearBit(bitPosition);
341 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000342}
343
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000344void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
345 unsigned subBitWidth = subBits.getBitWidth();
346 assert(0 < subBitWidth && (subBitWidth + bitPosition) <= BitWidth &&
347 "Illegal bit insertion");
348
349 // Insertion is a direct copy.
350 if (subBitWidth == BitWidth) {
351 *this = subBits;
352 return;
353 }
354
355 // Single word result can be done as a direct bitmask.
356 if (isSingleWord()) {
Craig Topper5e113742017-04-22 06:31:36 +0000357 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
Craig Topperb339c6d2017-05-03 15:46:24 +0000358 U.VAL &= ~(mask << bitPosition);
359 U.VAL |= (subBits.U.VAL << bitPosition);
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000360 return;
361 }
362
363 unsigned loBit = whichBit(bitPosition);
364 unsigned loWord = whichWord(bitPosition);
365 unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
366
367 // Insertion within a single word can be done as a direct bitmask.
368 if (loWord == hi1Word) {
Craig Topper5e113742017-04-22 06:31:36 +0000369 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
Craig Topperb339c6d2017-05-03 15:46:24 +0000370 U.pVal[loWord] &= ~(mask << loBit);
371 U.pVal[loWord] |= (subBits.U.VAL << loBit);
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000372 return;
373 }
374
375 // Insert on word boundaries.
376 if (loBit == 0) {
377 // Direct copy whole words.
378 unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
Craig Topperb339c6d2017-05-03 15:46:24 +0000379 memcpy(U.pVal + loWord, subBits.getRawData(),
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000380 numWholeSubWords * APINT_WORD_SIZE);
381
382 // Mask+insert remaining bits.
383 unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
384 if (remainingBits != 0) {
Craig Topper5e113742017-04-22 06:31:36 +0000385 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - remainingBits);
Craig Topperb339c6d2017-05-03 15:46:24 +0000386 U.pVal[hi1Word] &= ~mask;
387 U.pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000388 }
389 return;
390 }
391
392 // General case - set/clear individual bits in dst based on src.
393 // TODO - there is scope for optimization here, but at the moment this code
394 // path is barely used so prefer readability over performance.
395 for (unsigned i = 0; i != subBitWidth; ++i) {
396 if (subBits[i])
397 setBit(bitPosition + i);
398 else
399 clearBit(bitPosition + i);
400 }
401}
402
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000403APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
404 assert(numBits > 0 && "Can't extract zero bits");
405 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
406 "Illegal bit extraction");
407
408 if (isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000409 return APInt(numBits, U.VAL >> bitPosition);
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000410
411 unsigned loBit = whichBit(bitPosition);
412 unsigned loWord = whichWord(bitPosition);
413 unsigned hiWord = whichWord(bitPosition + numBits - 1);
414
415 // Single word result extracting bits from a single word source.
416 if (loWord == hiWord)
Craig Topperb339c6d2017-05-03 15:46:24 +0000417 return APInt(numBits, U.pVal[loWord] >> loBit);
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000418
419 // Extracting bits that start on a source word boundary can be done
420 // as a fast memory copy.
421 if (loBit == 0)
Craig Topperb339c6d2017-05-03 15:46:24 +0000422 return APInt(numBits, makeArrayRef(U.pVal + loWord, 1 + hiWord - loWord));
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000423
424 // General case - shift + copy source words directly into place.
425 APInt Result(numBits, 0);
426 unsigned NumSrcWords = getNumWords();
427 unsigned NumDstWords = Result.getNumWords();
428
Tim Shen89337752018-02-16 01:44:36 +0000429 uint64_t *DestPtr = Result.isSingleWord() ? &Result.U.VAL : Result.U.pVal;
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000430 for (unsigned word = 0; word < NumDstWords; ++word) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000431 uint64_t w0 = U.pVal[loWord + word];
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000432 uint64_t w1 =
Craig Topperb339c6d2017-05-03 15:46:24 +0000433 (loWord + word + 1) < NumSrcWords ? U.pVal[loWord + word + 1] : 0;
Tim Shen89337752018-02-16 01:44:36 +0000434 DestPtr[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000435 }
436
437 return Result.clearUnusedBits();
438}
439
Benjamin Kramer92d89982010-07-14 22:38:02 +0000440unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000441 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000442 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +0000443 radix == 36) &&
444 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000445
446 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000447
Eric Christopher43a1dec2009-08-21 04:10:31 +0000448 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000449 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000450 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000451 if (*p == '-' || *p == '+') {
452 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000453 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000454 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000455 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000456
Reid Spencer9329e7b2007-04-13 19:19:07 +0000457 // For radixes of power-of-two values, the bits required is accurately and
458 // easily computed
459 if (radix == 2)
460 return slen + isNegative;
461 if (radix == 8)
462 return slen * 3 + isNegative;
463 if (radix == 16)
464 return slen * 4 + isNegative;
465
Douglas Gregor663c0682011-09-14 15:54:46 +0000466 // FIXME: base 36
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000467
Reid Spencer9329e7b2007-04-13 19:19:07 +0000468 // This is grossly inefficient but accurate. We could probably do something
469 // with a computation of roughly slen*64/20 and then adjust by the value of
470 // the first few digits. But, I'm not sure how accurate that could be.
471
472 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000473 // be too large. This avoids the assertion in the constructor. This
474 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
475 // bits in that case.
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000476 unsigned sufficient
Douglas Gregor663c0682011-09-14 15:54:46 +0000477 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
478 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000479
480 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000481 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000482
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000483 // Compute how many bits are required. If the log is infinite, assume we need
484 // just bit.
485 unsigned log = tmp.logBase2();
486 if (log == (unsigned)-1) {
487 return isNegative + 1;
488 } else {
489 return isNegative + log + 1;
490 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000491}
492
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000493hash_code llvm::hash_value(const APInt &Arg) {
494 if (Arg.isSingleWord())
Craig Topperb339c6d2017-05-03 15:46:24 +0000495 return hash_combine(Arg.U.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000496
Craig Topperb339c6d2017-05-03 15:46:24 +0000497 return hash_combine_range(Arg.U.pVal, Arg.U.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000498}
499
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000500bool APInt::isSplat(unsigned SplatSizeInBits) const {
501 assert(getBitWidth() % SplatSizeInBits == 0 &&
502 "SplatSizeInBits must divide width!");
503 // We can check that all parts of an integer are equal by making use of a
504 // little trick: rotate and check if it's still the same value.
505 return *this == rotl(SplatSizeInBits);
506}
507
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000508/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000509APInt APInt::getHiBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000510 return this->lshr(BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000511}
512
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000513/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000514APInt APInt::getLoBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000515 APInt Result(getLowBitsSet(BitWidth, numBits));
516 Result &= *this;
517 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000518}
519
Craig Topper9881bd92017-05-02 06:32:27 +0000520/// Return a value containing V broadcasted over NewLen bits.
521APInt APInt::getSplat(unsigned NewLen, const APInt &V) {
522 assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
523
524 APInt Val = V.zextOrSelf(NewLen);
525 for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
526 Val |= Val << I;
527
528 return Val;
529}
530
Chris Lattner77527f52009-01-21 18:09:24 +0000531unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000532 unsigned Count = 0;
533 for (int i = getNumWords()-1; i >= 0; --i) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000534 uint64_t V = U.pVal[i];
Matthias Brauna6be4e82016-02-15 20:06:22 +0000535 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000536 Count += APINT_BITS_PER_WORD;
537 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000538 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000539 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000540 }
Zhou Shengdac63782007-02-06 03:00:16 +0000541 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000542 // Adjust for unused bits in the most significant word (they are zero).
543 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
544 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000545 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000546}
547
Craig Topper40516522017-06-23 20:28:45 +0000548unsigned APInt::countLeadingOnesSlowCase() const {
Chris Lattner77527f52009-01-21 18:09:24 +0000549 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000550 unsigned shift;
551 if (!highWordBits) {
552 highWordBits = APINT_BITS_PER_WORD;
553 shift = 0;
554 } else {
555 shift = APINT_BITS_PER_WORD - highWordBits;
556 }
Reid Spencer31acef52007-02-27 21:59:26 +0000557 int i = getNumWords() - 1;
Craig Topperb339c6d2017-05-03 15:46:24 +0000558 unsigned Count = llvm::countLeadingOnes(U.pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000559 if (Count == highWordBits) {
560 for (i--; i >= 0; --i) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000561 if (U.pVal[i] == WORD_MAX)
Reid Spencer31acef52007-02-27 21:59:26 +0000562 Count += APINT_BITS_PER_WORD;
563 else {
Craig Topperb339c6d2017-05-03 15:46:24 +0000564 Count += llvm::countLeadingOnes(U.pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000565 break;
566 }
567 }
568 }
569 return Count;
570}
571
Craig Topper40516522017-06-23 20:28:45 +0000572unsigned APInt::countTrailingZerosSlowCase() const {
Chris Lattner77527f52009-01-21 18:09:24 +0000573 unsigned Count = 0;
574 unsigned i = 0;
Craig Topperb339c6d2017-05-03 15:46:24 +0000575 for (; i < getNumWords() && U.pVal[i] == 0; ++i)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000576 Count += APINT_BITS_PER_WORD;
577 if (i < getNumWords())
Craig Topperb339c6d2017-05-03 15:46:24 +0000578 Count += llvm::countTrailingZeros(U.pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000579 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000580}
581
Chris Lattner77527f52009-01-21 18:09:24 +0000582unsigned APInt::countTrailingOnesSlowCase() const {
583 unsigned Count = 0;
584 unsigned i = 0;
Craig Topperb339c6d2017-05-03 15:46:24 +0000585 for (; i < getNumWords() && U.pVal[i] == WORD_MAX; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000586 Count += APINT_BITS_PER_WORD;
587 if (i < getNumWords())
Craig Topperb339c6d2017-05-03 15:46:24 +0000588 Count += llvm::countTrailingOnes(U.pVal[i]);
Craig Topper3a29e3b82017-04-22 19:59:11 +0000589 assert(Count <= BitWidth);
590 return Count;
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000591}
592
Chris Lattner77527f52009-01-21 18:09:24 +0000593unsigned APInt::countPopulationSlowCase() const {
594 unsigned Count = 0;
595 for (unsigned i = 0; i < getNumWords(); ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +0000596 Count += llvm::countPopulation(U.pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000597 return Count;
598}
599
Craig Topperbaa392e2017-04-20 02:11:27 +0000600bool APInt::intersectsSlowCase(const APInt &RHS) const {
601 for (unsigned i = 0, e = getNumWords(); i != e; ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +0000602 if ((U.pVal[i] & RHS.U.pVal[i]) != 0)
Craig Topperbaa392e2017-04-20 02:11:27 +0000603 return true;
604
605 return false;
606}
607
Craig Toppera8129a12017-04-20 16:17:13 +0000608bool APInt::isSubsetOfSlowCase(const APInt &RHS) const {
609 for (unsigned i = 0, e = getNumWords(); i != e; ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +0000610 if ((U.pVal[i] & ~RHS.U.pVal[i]) != 0)
Craig Toppera8129a12017-04-20 16:17:13 +0000611 return false;
612
613 return true;
614}
615
Reid Spencer1d072122007-02-16 22:36:51 +0000616APInt APInt::byteSwap() const {
617 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
618 if (BitWidth == 16)
Craig Topperb339c6d2017-05-03 15:46:24 +0000619 return APInt(BitWidth, ByteSwap_16(uint16_t(U.VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000620 if (BitWidth == 32)
Craig Topperb339c6d2017-05-03 15:46:24 +0000621 return APInt(BitWidth, ByteSwap_32(unsigned(U.VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000622 if (BitWidth == 48) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000623 unsigned Tmp1 = unsigned(U.VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000624 Tmp1 = ByteSwap_32(Tmp1);
Craig Topperb339c6d2017-05-03 15:46:24 +0000625 uint16_t Tmp2 = uint16_t(U.VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000626 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000627 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000628 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000629 if (BitWidth == 64)
Craig Topperb339c6d2017-05-03 15:46:24 +0000630 return APInt(BitWidth, ByteSwap_64(U.VAL));
Richard Smith4f9a8082011-11-23 21:33:37 +0000631
632 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
633 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
Craig Topperb339c6d2017-05-03 15:46:24 +0000634 Result.U.pVal[I] = ByteSwap_64(U.pVal[N - I - 1]);
Richard Smith4f9a8082011-11-23 21:33:37 +0000635 if (Result.BitWidth != BitWidth) {
Richard Smith55bd3752017-04-13 20:29:59 +0000636 Result.lshrInPlace(Result.BitWidth - BitWidth);
Richard Smith4f9a8082011-11-23 21:33:37 +0000637 Result.BitWidth = BitWidth;
638 }
639 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000640}
641
Matt Arsenault155dda92016-03-21 15:00:35 +0000642APInt APInt::reverseBits() const {
643 switch (BitWidth) {
644 case 64:
Craig Topperb339c6d2017-05-03 15:46:24 +0000645 return APInt(BitWidth, llvm::reverseBits<uint64_t>(U.VAL));
Matt Arsenault155dda92016-03-21 15:00:35 +0000646 case 32:
Craig Topperb339c6d2017-05-03 15:46:24 +0000647 return APInt(BitWidth, llvm::reverseBits<uint32_t>(U.VAL));
Matt Arsenault155dda92016-03-21 15:00:35 +0000648 case 16:
Craig Topperb339c6d2017-05-03 15:46:24 +0000649 return APInt(BitWidth, llvm::reverseBits<uint16_t>(U.VAL));
Matt Arsenault155dda92016-03-21 15:00:35 +0000650 case 8:
Craig Topperb339c6d2017-05-03 15:46:24 +0000651 return APInt(BitWidth, llvm::reverseBits<uint8_t>(U.VAL));
Matt Arsenault155dda92016-03-21 15:00:35 +0000652 default:
653 break;
654 }
655
656 APInt Val(*this);
Craig Topper9eaef072017-04-18 05:02:21 +0000657 APInt Reversed(BitWidth, 0);
658 unsigned S = BitWidth;
Matt Arsenault155dda92016-03-21 15:00:35 +0000659
Craig Topper9eaef072017-04-18 05:02:21 +0000660 for (; Val != 0; Val.lshrInPlace(1)) {
Matt Arsenault155dda92016-03-21 15:00:35 +0000661 Reversed <<= 1;
Craig Topper9eaef072017-04-18 05:02:21 +0000662 Reversed |= Val[0];
Matt Arsenault155dda92016-03-21 15:00:35 +0000663 --S;
664 }
665
666 Reversed <<= S;
667 return Reversed;
668}
669
Craig Topper278ebd22017-04-01 20:30:57 +0000670APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) {
Richard Smith55bd3752017-04-13 20:29:59 +0000671 // Fast-path a common case.
672 if (A == B) return A;
673
674 // Corner cases: if either operand is zero, the other is the gcd.
675 if (!A) return B;
676 if (!B) return A;
677
678 // Count common powers of 2 and remove all other powers of 2.
679 unsigned Pow2;
680 {
681 unsigned Pow2_A = A.countTrailingZeros();
682 unsigned Pow2_B = B.countTrailingZeros();
683 if (Pow2_A > Pow2_B) {
684 A.lshrInPlace(Pow2_A - Pow2_B);
685 Pow2 = Pow2_B;
686 } else if (Pow2_B > Pow2_A) {
687 B.lshrInPlace(Pow2_B - Pow2_A);
688 Pow2 = Pow2_A;
689 } else {
690 Pow2 = Pow2_A;
691 }
Zhou Shengdac63782007-02-06 03:00:16 +0000692 }
Richard Smith55bd3752017-04-13 20:29:59 +0000693
694 // Both operands are odd multiples of 2^Pow_2:
695 //
696 // gcd(a, b) = gcd(|a - b| / 2^i, min(a, b))
697 //
698 // This is a modified version of Stein's algorithm, taking advantage of
699 // efficient countTrailingZeros().
700 while (A != B) {
701 if (A.ugt(B)) {
702 A -= B;
703 A.lshrInPlace(A.countTrailingZeros() - Pow2);
704 } else {
705 B -= A;
706 B.lshrInPlace(B.countTrailingZeros() - Pow2);
707 }
708 }
709
Zhou Shengdac63782007-02-06 03:00:16 +0000710 return A;
711}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000712
Chris Lattner77527f52009-01-21 18:09:24 +0000713APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000714 union {
715 double D;
716 uint64_t I;
717 } T;
718 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000719
720 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000721 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000722
723 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000724 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000725
726 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000727 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000728 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000729
730 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
731 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
732
733 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000734 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000735 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000736 APInt(width, mantissa >> (52 - exp));
737
738 // If the client didn't provide enough bits for us to shift the mantissa into
739 // then the result is undefined, just return 0
740 if (width <= exp - 52)
741 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000742
743 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000744 APInt Tmp(width, mantissa);
Craig Topper24e71012017-04-28 03:36:24 +0000745 Tmp <<= (unsigned)exp - 52;
Zhou Shengd707d632007-02-12 20:02:55 +0000746 return isNeg ? -Tmp : Tmp;
747}
748
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000749/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000750/// The layout for double is as following (IEEE Standard 754):
751/// --------------------------------------
752/// | Sign Exponent Fraction Bias |
753/// |-------------------------------------- |
754/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000755/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000756double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000757
758 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000759 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000760 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
761 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000762 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000763 return double(sext);
764 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000765 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000766 }
767
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000768 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000769 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000770
771 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000772 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000773
774 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000775 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000776
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000777 // The exponent (without bias normalization) is just the number of bits
778 // we are using. Note that the sign bit is gone since we constructed the
779 // absolute value.
780 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000781
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000782 // Return infinity for exponent overflow
783 if (exp > 1023) {
784 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000785 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000786 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000787 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000788 }
789 exp += 1023; // Increment for 1023 bias
790
791 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
792 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000793 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000794 unsigned hiWord = whichWord(n-1);
795 if (hiWord == 0) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000796 mantissa = Tmp.U.pVal[0];
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000797 if (n > 52)
798 mantissa >>= n - 52; // shift down, we want the top 52 bits.
799 } else {
800 assert(hiWord > 0 && "huh?");
Craig Topperb339c6d2017-05-03 15:46:24 +0000801 uint64_t hibits = Tmp.U.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
802 uint64_t lobits = Tmp.U.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000803 mantissa = hibits | lobits;
804 }
805
Zhou Shengd707d632007-02-12 20:02:55 +0000806 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000807 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000808 union {
809 double D;
810 uint64_t I;
811 } T;
812 T.I = sign | (exp << 52) | mantissa;
813 return T.D;
814}
815
Reid Spencer1d072122007-02-16 22:36:51 +0000816// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000817APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000818 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000819 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000820
821 if (width <= APINT_BITS_PER_WORD)
822 return APInt(width, getRawData()[0]);
823
824 APInt Result(getMemory(getNumWords(width)), width);
825
826 // Copy full words.
827 unsigned i;
828 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
Craig Topperb339c6d2017-05-03 15:46:24 +0000829 Result.U.pVal[i] = U.pVal[i];
Jay Foad583abbc2010-12-07 08:25:19 +0000830
831 // Truncate and copy any partial word.
832 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
833 if (bits != 0)
Craig Topperb339c6d2017-05-03 15:46:24 +0000834 Result.U.pVal[i] = U.pVal[i] << bits >> bits;
Jay Foad583abbc2010-12-07 08:25:19 +0000835
836 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000837}
838
839// Sign extend to a new width.
Craig Topper1dec2812017-04-24 17:37:10 +0000840APInt APInt::sext(unsigned Width) const {
841 assert(Width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000842
Craig Topper1dec2812017-04-24 17:37:10 +0000843 if (Width <= APINT_BITS_PER_WORD)
Craig Topperb339c6d2017-05-03 15:46:24 +0000844 return APInt(Width, SignExtend64(U.VAL, BitWidth));
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000845
Craig Topper1dec2812017-04-24 17:37:10 +0000846 APInt Result(getMemory(getNumWords(Width)), Width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000847
Craig Topper1dec2812017-04-24 17:37:10 +0000848 // Copy words.
Craig Topperb339c6d2017-05-03 15:46:24 +0000849 std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000850
Craig Topper1dec2812017-04-24 17:37:10 +0000851 // Sign extend the last word since there may be unused bits in the input.
Craig Topperb339c6d2017-05-03 15:46:24 +0000852 Result.U.pVal[getNumWords() - 1] =
853 SignExtend64(Result.U.pVal[getNumWords() - 1],
Craig Topper1dec2812017-04-24 17:37:10 +0000854 ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
Jay Foad583abbc2010-12-07 08:25:19 +0000855
Craig Topper1dec2812017-04-24 17:37:10 +0000856 // Fill with sign bits.
Craig Topperb339c6d2017-05-03 15:46:24 +0000857 std::memset(Result.U.pVal + getNumWords(), isNegative() ? -1 : 0,
Craig Topper1dec2812017-04-24 17:37:10 +0000858 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
859 Result.clearUnusedBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000860 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000861}
862
863// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000864APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000865 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000866
867 if (width <= APINT_BITS_PER_WORD)
Craig Topperb339c6d2017-05-03 15:46:24 +0000868 return APInt(width, U.VAL);
Jay Foad583abbc2010-12-07 08:25:19 +0000869
870 APInt Result(getMemory(getNumWords(width)), width);
871
872 // Copy words.
Craig Topperb339c6d2017-05-03 15:46:24 +0000873 std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
Jay Foad583abbc2010-12-07 08:25:19 +0000874
875 // Zero remaining words.
Craig Topperb339c6d2017-05-03 15:46:24 +0000876 std::memset(Result.U.pVal + getNumWords(), 0,
Craig Topper1dec2812017-04-24 17:37:10 +0000877 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
Jay Foad583abbc2010-12-07 08:25:19 +0000878
879 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000880}
881
Jay Foad583abbc2010-12-07 08:25:19 +0000882APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +0000883 if (BitWidth < width)
884 return zext(width);
885 if (BitWidth > width)
886 return trunc(width);
887 return *this;
888}
889
Jay Foad583abbc2010-12-07 08:25:19 +0000890APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +0000891 if (BitWidth < width)
892 return sext(width);
893 if (BitWidth > width)
894 return trunc(width);
895 return *this;
896}
897
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000898APInt APInt::zextOrSelf(unsigned width) const {
899 if (BitWidth < width)
900 return zext(width);
901 return *this;
902}
903
904APInt APInt::sextOrSelf(unsigned width) const {
905 if (BitWidth < width)
906 return sext(width);
907 return *this;
908}
909
Zhou Shenge93db8f2007-02-09 07:48:24 +0000910/// Arithmetic right-shift this APInt by shiftAmt.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000911/// Arithmetic right-shift function.
Craig Topper8b373262017-04-24 17:18:47 +0000912void APInt::ashrInPlace(const APInt &shiftAmt) {
913 ashrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +0000914}
915
916/// Arithmetic right-shift this APInt by shiftAmt.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000917/// Arithmetic right-shift function.
Craig Topper8b373262017-04-24 17:18:47 +0000918void APInt::ashrSlowCase(unsigned ShiftAmt) {
919 // Don't bother performing a no-op shift.
920 if (!ShiftAmt)
921 return;
Reid Spencer1825dd02007-03-02 22:39:11 +0000922
Craig Topper8b373262017-04-24 17:18:47 +0000923 // Save the original sign bit for later.
924 bool Negative = isNegative();
Reid Spencer522ca7c2007-02-25 01:56:07 +0000925
Hiroshi Inoue9ff23802018-04-09 04:37:53 +0000926 // WordShift is the inter-part shift; BitShift is intra-part shift.
Craig Topper8b373262017-04-24 17:18:47 +0000927 unsigned WordShift = ShiftAmt / APINT_BITS_PER_WORD;
928 unsigned BitShift = ShiftAmt % APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000929
Craig Topper8b373262017-04-24 17:18:47 +0000930 unsigned WordsToMove = getNumWords() - WordShift;
931 if (WordsToMove != 0) {
932 // Sign extend the last word to fill in the unused bits.
Craig Topperb339c6d2017-05-03 15:46:24 +0000933 U.pVal[getNumWords() - 1] = SignExtend64(
934 U.pVal[getNumWords() - 1], ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
Renato Golincc4a9122017-04-23 12:02:07 +0000935
Craig Topper8b373262017-04-24 17:18:47 +0000936 // Fastpath for moving by whole words.
937 if (BitShift == 0) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000938 std::memmove(U.pVal, U.pVal + WordShift, WordsToMove * APINT_WORD_SIZE);
Craig Topper8b373262017-04-24 17:18:47 +0000939 } else {
940 // Move the words containing significant bits.
941 for (unsigned i = 0; i != WordsToMove - 1; ++i)
Craig Topperb339c6d2017-05-03 15:46:24 +0000942 U.pVal[i] = (U.pVal[i + WordShift] >> BitShift) |
943 (U.pVal[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift));
Renato Golincc4a9122017-04-23 12:02:07 +0000944
Craig Topper8b373262017-04-24 17:18:47 +0000945 // Handle the last word which has no high bits to copy.
Craig Topperb339c6d2017-05-03 15:46:24 +0000946 U.pVal[WordsToMove - 1] = U.pVal[WordShift + WordsToMove - 1] >> BitShift;
Craig Topper8b373262017-04-24 17:18:47 +0000947 // Sign extend one more time.
Craig Topperb339c6d2017-05-03 15:46:24 +0000948 U.pVal[WordsToMove - 1] =
949 SignExtend64(U.pVal[WordsToMove - 1], APINT_BITS_PER_WORD - BitShift);
Chris Lattnerdad2d092007-05-03 18:15:36 +0000950 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000951 }
952
Craig Topper8b373262017-04-24 17:18:47 +0000953 // Fill in the remainder based on the original sign.
Craig Topperb339c6d2017-05-03 15:46:24 +0000954 std::memset(U.pVal + WordsToMove, Negative ? -1 : 0,
Craig Topper8b373262017-04-24 17:18:47 +0000955 WordShift * APINT_WORD_SIZE);
956 clearUnusedBits();
Zhou Shengfbf61ea2007-02-08 14:35:19 +0000957}
958
Zhou Shenge93db8f2007-02-09 07:48:24 +0000959/// Logical right-shift this APInt by shiftAmt.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000960/// Logical right-shift function.
Craig Topperfc947bc2017-04-18 17:14:21 +0000961void APInt::lshrInPlace(const APInt &shiftAmt) {
962 lshrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +0000963}
964
965/// Logical right-shift this APInt by shiftAmt.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000966/// Logical right-shift function.
Craig Topperae8bd672017-04-18 19:13:27 +0000967void APInt::lshrSlowCase(unsigned ShiftAmt) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000968 tcShiftRight(U.pVal, getNumWords(), ShiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +0000969}
970
Zhou Shenge93db8f2007-02-09 07:48:24 +0000971/// Left-shift this APInt by shiftAmt.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000972/// Left-shift function.
Craig Topper24e71012017-04-28 03:36:24 +0000973APInt &APInt::operator<<=(const APInt &shiftAmt) {
Nick Lewycky030c4502009-01-19 17:42:33 +0000974 // It's undefined behavior in C to shift by BitWidth or greater.
Craig Topper24e71012017-04-28 03:36:24 +0000975 *this <<= (unsigned)shiftAmt.getLimitedValue(BitWidth);
976 return *this;
Dan Gohman105c1d42008-02-29 01:40:47 +0000977}
978
Craig Toppera8a4f0d2017-04-18 04:39:48 +0000979void APInt::shlSlowCase(unsigned ShiftAmt) {
Craig Topperb339c6d2017-05-03 15:46:24 +0000980 tcShiftLeft(U.pVal, getNumWords(), ShiftAmt);
Craig Toppera8a4f0d2017-04-18 04:39:48 +0000981 clearUnusedBits();
Zhou Shengfbf61ea2007-02-08 14:35:19 +0000982}
983
Joey Gouly51c0ae52017-02-07 11:58:22 +0000984// Calculate the rotate amount modulo the bit width.
985static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
986 unsigned rotBitWidth = rotateAmt.getBitWidth();
987 APInt rot = rotateAmt;
988 if (rotBitWidth < BitWidth) {
989 // Extend the rotate APInt, so that the urem doesn't divide by 0.
990 // e.g. APInt(1, 32) would give APInt(1, 0).
991 rot = rotateAmt.zext(BitWidth);
992 }
993 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
994 return rot.getLimitedValue(BitWidth);
995}
996
Dan Gohman105c1d42008-02-29 01:40:47 +0000997APInt APInt::rotl(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +0000998 return rotl(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +0000999}
1000
Chris Lattner77527f52009-01-21 18:09:24 +00001001APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001002 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001003 if (rotateAmt == 0)
1004 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001005 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001006}
1007
Dan Gohman105c1d42008-02-29 01:40:47 +00001008APInt APInt::rotr(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001009 return rotr(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001010}
1011
Chris Lattner77527f52009-01-21 18:09:24 +00001012APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001013 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001014 if (rotateAmt == 0)
1015 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001016 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001017}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001018
1019// Square Root - this method computes and returns the square root of "this".
1020// Three mechanisms are used for computation. For small values (<= 5 bits),
1021// a table lookup is done. This gets some performance for common cases. For
1022// values using less than 52 bits, the value is converted to double and then
1023// the libc sqrt function is called. The result is rounded and then converted
1024// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001025// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001026APInt APInt::sqrt() const {
1027
1028 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001029 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001030
1031 // Use a fast table for some small values. This also gets rid of some
1032 // rounding errors in libc sqrt for small values.
1033 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001034 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001035 /* 0 */ 0,
1036 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001037 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001038 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1039 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1040 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1041 /* 31 */ 6
1042 };
Craig Topperb339c6d2017-05-03 15:46:24 +00001043 return APInt(BitWidth, results[ (isSingleWord() ? U.VAL : U.pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001044 }
1045
1046 // If the magnitude of the value fits in less than 52 bits (the precision of
1047 // an IEEE double precision floating point value), then we can use the
1048 // libc sqrt function which will probably use a hardware sqrt computation.
1049 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001050 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001051 return APInt(BitWidth,
Craig Topperb339c6d2017-05-03 15:46:24 +00001052 uint64_t(::round(::sqrt(double(isSingleWord() ? U.VAL
1053 : U.pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001054 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001055
1056 // Okay, all the short cuts are exhausted. We must compute it. The following
1057 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001058 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001059 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001060 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001061 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001062 APInt testy(BitWidth, 16);
1063 APInt x_old(BitWidth, 1);
1064 APInt x_new(BitWidth, 0);
1065 APInt two(BitWidth, 2);
1066
1067 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001068 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001069 if (i >= nbits || this->ule(testy)) {
1070 x_old = x_old.shl(i / 2);
1071 break;
1072 }
1073
Eric Christopher820256b2009-08-21 04:06:45 +00001074 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001075 for (;;) {
1076 x_new = (this->udiv(x_old) + x_old).udiv(two);
1077 if (x_old.ule(x_new))
1078 break;
1079 x_old = x_new;
1080 }
1081
1082 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001083 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001084 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001085 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001086 // floating point representation after 192 bits. There are no discrepancies
1087 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001088 APInt square(x_old * x_old);
1089 APInt nextSquare((x_old + 1) * (x_old +1));
1090 if (this->ult(square))
1091 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001092 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1093 APInt midpoint((nextSquare - square).udiv(two));
1094 APInt offset(*this - square);
1095 if (offset.ult(midpoint))
1096 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001097 return x_old + 1;
1098}
1099
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001100/// Computes the multiplicative inverse of this APInt for a given modulo. The
1101/// iterative extended Euclidean algorithm is used to solve for this value,
1102/// however we simplify it to speed up calculating only the inverse, and take
1103/// advantage of div+rem calculations. We also use some tricks to avoid copying
1104/// (potentially large) APInts around.
1105APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1106 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1107
1108 // Using the properties listed at the following web page (accessed 06/21/08):
1109 // http://www.numbertheory.org/php/euclid.html
1110 // (especially the properties numbered 3, 4 and 9) it can be proved that
1111 // BitWidth bits suffice for all the computations in the algorithm implemented
1112 // below. More precisely, this number of bits suffice if the multiplicative
1113 // inverse exists, but may not suffice for the general extended Euclidean
1114 // algorithm.
1115
1116 APInt r[2] = { modulo, *this };
1117 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1118 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001119
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001120 unsigned i;
1121 for (i = 0; r[i^1] != 0; i ^= 1) {
1122 // An overview of the math without the confusing bit-flipping:
1123 // q = r[i-2] / r[i-1]
1124 // r[i] = r[i-2] % r[i-1]
1125 // t[i] = t[i-2] - t[i-1] * q
1126 udivrem(r[i], r[i^1], q, r[i]);
1127 t[i] -= t[i^1] * q;
1128 }
1129
1130 // If this APInt and the modulo are not coprime, there is no multiplicative
1131 // inverse, so return 0. We check this by looking at the next-to-last
1132 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1133 // algorithm.
1134 if (r[i] != 1)
1135 return APInt(BitWidth, 0);
1136
1137 // The next-to-last t is the multiplicative inverse. However, we are
Craig Topper3fbecad2017-05-11 17:57:43 +00001138 // interested in a positive inverse. Calculate a positive one from a negative
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001139 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001140 // abs(t[i]) is known to be less than *this/2 (see the link above).
Craig Topperdbd62192017-05-11 18:40:53 +00001141 if (t[i].isNegative())
1142 t[i] += modulo;
1143
1144 return std::move(t[i]);
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001145}
1146
Jay Foadfe0c6482009-04-30 10:15:35 +00001147/// Calculate the magic numbers required to implement a signed integer division
1148/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1149/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1150/// Warren, Jr., chapter 10.
1151APInt::ms APInt::magic() const {
1152 const APInt& d = *this;
1153 unsigned p;
1154 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001155 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001156 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001157
Jay Foadfe0c6482009-04-30 10:15:35 +00001158 ad = d.abs();
1159 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1160 anc = t - 1 - t.urem(ad); // absolute value of nc
1161 p = d.getBitWidth() - 1; // initialize p
1162 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1163 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1164 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1165 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1166 do {
1167 p = p + 1;
1168 q1 = q1<<1; // update q1 = 2p/abs(nc)
1169 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1170 if (r1.uge(anc)) { // must be unsigned comparison
1171 q1 = q1 + 1;
1172 r1 = r1 - anc;
1173 }
1174 q2 = q2<<1; // update q2 = 2p/abs(d)
1175 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1176 if (r2.uge(ad)) { // must be unsigned comparison
1177 q2 = q2 + 1;
1178 r2 = r2 - ad;
1179 }
1180 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001181 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001182
Jay Foadfe0c6482009-04-30 10:15:35 +00001183 mag.m = q2 + 1;
1184 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1185 mag.s = p - d.getBitWidth(); // resulting shift
1186 return mag;
1187}
1188
1189/// Calculate the magic numbers required to implement an unsigned integer
1190/// division by a constant as a sequence of multiplies, adds and shifts.
1191/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1192/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001193/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001194/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001195APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001196 const APInt& d = *this;
1197 unsigned p;
1198 APInt nc, delta, q1, r1, q2, r2;
1199 struct mu magu;
1200 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001201 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001202 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1203 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1204
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001205 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001206 p = d.getBitWidth() - 1; // initialize p
1207 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1208 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1209 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1210 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1211 do {
1212 p = p + 1;
1213 if (r1.uge(nc - r1)) {
1214 q1 = q1 + q1 + 1; // update q1
1215 r1 = r1 + r1 - nc; // update r1
1216 }
1217 else {
1218 q1 = q1+q1; // update q1
1219 r1 = r1+r1; // update r1
1220 }
1221 if ((r2 + 1).uge(d - r2)) {
1222 if (q2.uge(signedMax)) magu.a = 1;
1223 q2 = q2+q2 + 1; // update q2
1224 r2 = r2+r2 + 1 - d; // update r2
1225 }
1226 else {
1227 if (q2.uge(signedMin)) magu.a = 1;
1228 q2 = q2+q2; // update q2
1229 r2 = r2+r2 + 1; // update r2
1230 }
1231 delta = d - 1 - r2;
1232 } while (p < d.getBitWidth()*2 &&
1233 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1234 magu.m = q2 + 1; // resulting magic number
1235 magu.s = p - d.getBitWidth(); // resulting shift
1236 return magu;
1237}
1238
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001239/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1240/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1241/// variables here have the same names as in the algorithm. Comments explain
1242/// the algorithm and any deviation from it.
Craig Topper6271bc72017-05-10 18:15:20 +00001243static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
Chris Lattner77527f52009-01-21 18:09:24 +00001244 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001245 assert(u && "Must provide dividend");
1246 assert(v && "Must provide divisor");
1247 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001248 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001249 assert(n>1 && "n must be > 1");
1250
Yaron Keren39fc5a62015-03-26 19:45:19 +00001251 // b denotes the base of the number system. In our case b is 2^32.
George Burgess IV381fc0e2016-08-25 01:05:08 +00001252 const uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001253
Craig Topper03106bb2017-11-24 20:29:04 +00001254// The DEBUG macros here tend to be spam in the debug output if you're not
1255// debugging this code. Disable them unless KNUTH_DEBUG is defined.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001256#pragma push_macro("LLVM_DEBUG")
Craig Topper03106bb2017-11-24 20:29:04 +00001257#ifndef KNUTH_DEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001258#undef LLVM_DEBUG
1259#define LLVM_DEBUG(X) \
1260 do { \
1261 } while (false)
Craig Topper03106bb2017-11-24 20:29:04 +00001262#endif
1263
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001264 LLVM_DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1265 LLVM_DEBUG(dbgs() << "KnuthDiv: original:");
1266 LLVM_DEBUG(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1267 LLVM_DEBUG(dbgs() << " by");
1268 LLVM_DEBUG(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
1269 LLVM_DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001270 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1271 // u and v by d. Note that we have taken Knuth's advice here to use a power
1272 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1273 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001274 // shift amount from the leading zeros. We are basically normalizing the u
1275 // and v so that its high bits are shifted to the top of v's range without
1276 // overflow. Note that this can require an extra word in u so that u must
1277 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001278 unsigned shift = countLeadingZeros(v[n-1]);
Craig Topper6271bc72017-05-10 18:15:20 +00001279 uint32_t v_carry = 0;
1280 uint32_t u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001281 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001282 for (unsigned i = 0; i < m+n; ++i) {
Craig Topper6271bc72017-05-10 18:15:20 +00001283 uint32_t u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001284 u[i] = (u[i] << shift) | u_carry;
1285 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001286 }
Chris Lattner77527f52009-01-21 18:09:24 +00001287 for (unsigned i = 0; i < n; ++i) {
Craig Topper6271bc72017-05-10 18:15:20 +00001288 uint32_t v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001289 v[i] = (v[i] << shift) | v_carry;
1290 v_carry = v_tmp;
1291 }
1292 }
1293 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001294
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001295 LLVM_DEBUG(dbgs() << "KnuthDiv: normal:");
1296 LLVM_DEBUG(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1297 LLVM_DEBUG(dbgs() << " by");
1298 LLVM_DEBUG(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
1299 LLVM_DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001300
1301 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1302 int j = m;
1303 do {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001304 LLVM_DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001305 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001306 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1307 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1308 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
Craig Topper4b83b4d2017-05-13 00:35:30 +00001309 // qp by 1, increase rp by v[n-1], and repeat this test if rp < b. The test
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001310 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001311 // value qp is one too large, and it eliminates all cases where qp is two
1312 // too large.
Craig Topper2c9a7062017-05-13 07:14:17 +00001313 uint64_t dividend = Make_64(u[j+n], u[j+n-1]);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001314 LLVM_DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001315 uint64_t qp = dividend / v[n-1];
1316 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001317 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1318 qp--;
1319 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001320 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001321 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001322 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001323 LLVM_DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001324
Reid Spencercb292e42007-02-23 01:57:13 +00001325 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1326 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1327 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001328 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001329 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1330 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1331 // true value plus b**(n+1), namely as the b's complement of
1332 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001333 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001334 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001335 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
Craig Topper2c9a7062017-05-13 07:14:17 +00001336 int64_t subres = int64_t(u[j+i]) - borrow - Lo_32(p);
1337 u[j+i] = Lo_32(subres);
1338 borrow = Hi_32(p) - Hi_32(subres);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001339 LLVM_DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j + i]
1340 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001341 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001342 bool isNeg = u[j+n] < borrow;
Craig Topper2c9a7062017-05-13 07:14:17 +00001343 u[j+n] -= Lo_32(borrow);
Pawel Bylica86ac4472015-04-24 07:38:39 +00001344
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001345 LLVM_DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1346 LLVM_DEBUG(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1347 LLVM_DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001348
Eric Christopher820256b2009-08-21 04:06:45 +00001349 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001350 // negative, go to step D6; otherwise go on to step D7.
Craig Topper2c9a7062017-05-13 07:14:17 +00001351 q[j] = Lo_32(qp);
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001352 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001353 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001354 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001355 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001356 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001357 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1358 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001359 // since it cancels with the borrow that occurred in D4.
1360 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001361 for (unsigned i = 0; i < n; i++) {
Craig Topper6271bc72017-05-10 18:15:20 +00001362 uint32_t limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001363 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001364 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001365 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001366 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001367 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001368 LLVM_DEBUG(dbgs() << "KnuthDiv: after correction:");
1369 LLVM_DEBUG(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1370 LLVM_DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001371
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001372 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
Reid Spencercb292e42007-02-23 01:57:13 +00001373 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001374
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001375 LLVM_DEBUG(dbgs() << "KnuthDiv: quotient:");
1376 LLVM_DEBUG(for (int i = m; i >= 0; i--) dbgs() << " " << q[i]);
1377 LLVM_DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001378
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001379 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1380 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1381 // compute the remainder (urem uses this).
1382 if (r) {
1383 // The value d is expressed by the "shift" value above since we avoided
1384 // multiplication by d by using a shift left. So, all we have to do is
Simon Pilgrim0099beb2017-03-09 13:57:04 +00001385 // shift right here.
Reid Spencer468ad9112007-02-24 20:38:01 +00001386 if (shift) {
Craig Topper6271bc72017-05-10 18:15:20 +00001387 uint32_t carry = 0;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001388 LLVM_DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001389 for (int i = n-1; i >= 0; i--) {
1390 r[i] = (u[i] >> shift) | carry;
1391 carry = u[i] << (32 - shift);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001392 LLVM_DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001393 }
1394 } else {
1395 for (int i = n-1; i >= 0; i--) {
1396 r[i] = u[i];
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001397 LLVM_DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001398 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001399 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001400 LLVM_DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001401 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001402 LLVM_DEBUG(dbgs() << '\n');
Craig Topper03106bb2017-11-24 20:29:04 +00001403
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001404#pragma pop_macro("LLVM_DEBUG")
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001405}
1406
Craig Topper8885f932017-05-19 16:43:54 +00001407void APInt::divide(const WordType *LHS, unsigned lhsWords, const WordType *RHS,
1408 unsigned rhsWords, WordType *Quotient, WordType *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001409 assert(lhsWords >= rhsWords && "Fractional result");
1410
Eric Christopher820256b2009-08-21 04:06:45 +00001411 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001412 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001413 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001414 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1415 // can't use 64-bit operands here because we don't have native results of
1416 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001417 // work on large-endian machines.
Chris Lattner77527f52009-01-21 18:09:24 +00001418 unsigned n = rhsWords * 2;
1419 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001420
1421 // Allocate space for the temporary values we need either on the stack, if
1422 // it will fit, or on the heap if it won't.
Craig Topper6271bc72017-05-10 18:15:20 +00001423 uint32_t SPACE[128];
1424 uint32_t *U = nullptr;
1425 uint32_t *V = nullptr;
1426 uint32_t *Q = nullptr;
1427 uint32_t *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001428 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1429 U = &SPACE[0];
1430 V = &SPACE[m+n+1];
1431 Q = &SPACE[(m+n+1) + n];
1432 if (Remainder)
1433 R = &SPACE[(m+n+1) + n + (m+n)];
1434 } else {
Craig Topper6271bc72017-05-10 18:15:20 +00001435 U = new uint32_t[m + n + 1];
1436 V = new uint32_t[n];
1437 Q = new uint32_t[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001438 if (Remainder)
Craig Topper6271bc72017-05-10 18:15:20 +00001439 R = new uint32_t[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001440 }
1441
1442 // Initialize the dividend
Craig Topper6271bc72017-05-10 18:15:20 +00001443 memset(U, 0, (m+n+1)*sizeof(uint32_t));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001444 for (unsigned i = 0; i < lhsWords; ++i) {
Craig Topper8885f932017-05-19 16:43:54 +00001445 uint64_t tmp = LHS[i];
Craig Topper6271bc72017-05-10 18:15:20 +00001446 U[i * 2] = Lo_32(tmp);
1447 U[i * 2 + 1] = Hi_32(tmp);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001448 }
1449 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1450
Reid Spencer522ca7c2007-02-25 01:56:07 +00001451 // Initialize the divisor
Craig Topper6271bc72017-05-10 18:15:20 +00001452 memset(V, 0, (n)*sizeof(uint32_t));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001453 for (unsigned i = 0; i < rhsWords; ++i) {
Craig Topper8885f932017-05-19 16:43:54 +00001454 uint64_t tmp = RHS[i];
Craig Topper6271bc72017-05-10 18:15:20 +00001455 V[i * 2] = Lo_32(tmp);
1456 V[i * 2 + 1] = Hi_32(tmp);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001457 }
1458
Reid Spencer522ca7c2007-02-25 01:56:07 +00001459 // initialize the quotient and remainder
Craig Topper6271bc72017-05-10 18:15:20 +00001460 memset(Q, 0, (m+n) * sizeof(uint32_t));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001461 if (Remainder)
Craig Topper6271bc72017-05-10 18:15:20 +00001462 memset(R, 0, n * sizeof(uint32_t));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001463
Eric Christopher820256b2009-08-21 04:06:45 +00001464 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001465 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001466 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001467 // contain any zero words or the Knuth algorithm fails.
1468 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1469 n--;
1470 m++;
1471 }
1472 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1473 m--;
1474
1475 // If we're left with only a single word for the divisor, Knuth doesn't work
1476 // so we implement the short division algorithm here. This is much simpler
1477 // and faster because we are certain that we can divide a 64-bit quantity
1478 // by a 32-bit quantity at hardware speed and short division is simply a
1479 // series of such operations. This is just like doing short division but we
1480 // are using base 2^32 instead of base 10.
1481 assert(n != 0 && "Divide by zero?");
1482 if (n == 1) {
Craig Topper6271bc72017-05-10 18:15:20 +00001483 uint32_t divisor = V[0];
1484 uint32_t remainder = 0;
Craig Topper6a1d0202017-05-15 22:01:03 +00001485 for (int i = m; i >= 0; i--) {
Craig Topper6271bc72017-05-10 18:15:20 +00001486 uint64_t partial_dividend = Make_64(remainder, U[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001487 if (partial_dividend == 0) {
1488 Q[i] = 0;
1489 remainder = 0;
1490 } else if (partial_dividend < divisor) {
1491 Q[i] = 0;
Craig Topper6271bc72017-05-10 18:15:20 +00001492 remainder = Lo_32(partial_dividend);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001493 } else if (partial_dividend == divisor) {
1494 Q[i] = 1;
1495 remainder = 0;
1496 } else {
Craig Topper6271bc72017-05-10 18:15:20 +00001497 Q[i] = Lo_32(partial_dividend / divisor);
1498 remainder = Lo_32(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001499 }
1500 }
1501 if (R)
1502 R[0] = remainder;
1503 } else {
1504 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1505 // case n > 1.
1506 KnuthDiv(U, V, Q, R, m, n);
1507 }
1508
1509 // If the caller wants the quotient
1510 if (Quotient) {
Craig Topper8885f932017-05-19 16:43:54 +00001511 for (unsigned i = 0; i < lhsWords; ++i)
1512 Quotient[i] = Make_64(Q[i*2+1], Q[i*2]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001513 }
1514
1515 // If the caller wants the remainder
1516 if (Remainder) {
Craig Topper8885f932017-05-19 16:43:54 +00001517 for (unsigned i = 0; i < rhsWords; ++i)
1518 Remainder[i] = Make_64(R[i*2+1], R[i*2]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001519 }
1520
1521 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001522 if (U != &SPACE[0]) {
1523 delete [] U;
1524 delete [] V;
1525 delete [] Q;
1526 delete [] R;
1527 }
Reid Spencer100502d2007-02-17 03:16:00 +00001528}
1529
Craig Topper8885f932017-05-19 16:43:54 +00001530APInt APInt::udiv(const APInt &RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001531 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001532
1533 // First, deal with the easy case
1534 if (isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +00001535 assert(RHS.U.VAL != 0 && "Divide by zero?");
1536 return APInt(BitWidth, U.VAL / RHS.U.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001537 }
Reid Spencer39867762007-02-17 02:07:07 +00001538
Reid Spencer39867762007-02-17 02:07:07 +00001539 // Get some facts about the LHS and RHS number of bits and words
Craig Topper62de0392017-05-10 07:50:15 +00001540 unsigned lhsWords = getNumWords(getActiveBits());
Craig Topperb1a71ca2017-05-12 21:45:50 +00001541 unsigned rhsBits = RHS.getActiveBits();
1542 unsigned rhsWords = getNumWords(rhsBits);
1543 assert(rhsWords && "Divided by zero???");
Reid Spencer39867762007-02-17 02:07:07 +00001544
1545 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001546 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001547 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001548 return APInt(BitWidth, 0);
Craig Topperb1a71ca2017-05-12 21:45:50 +00001549 if (rhsBits == 1)
1550 // X / 1 ===> X
1551 return *this;
Craig Topper24ae6952017-05-08 23:49:49 +00001552 if (lhsWords < rhsWords || this->ult(RHS))
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001553 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001554 return APInt(BitWidth, 0);
Craig Topper24ae6952017-05-08 23:49:49 +00001555 if (*this == RHS)
Reid Spencer58a6a432007-02-21 08:21:52 +00001556 // X / X ===> 1
1557 return APInt(BitWidth, 1);
Craig Topper06da0812017-05-12 18:18:57 +00001558 if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
Reid Spencer39867762007-02-17 02:07:07 +00001559 // All high words are zero, just use native divide
Craig Topperb339c6d2017-05-03 15:46:24 +00001560 return APInt(BitWidth, this->U.pVal[0] / RHS.U.pVal[0]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001561
1562 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Craig Topper8885f932017-05-19 16:43:54 +00001563 APInt Quotient(BitWidth, 0); // to hold result.
1564 divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal, nullptr);
1565 return Quotient;
1566}
1567
1568APInt APInt::udiv(uint64_t RHS) const {
1569 assert(RHS != 0 && "Divide by zero?");
1570
1571 // First, deal with the easy case
1572 if (isSingleWord())
1573 return APInt(BitWidth, U.VAL / RHS);
1574
1575 // Get some facts about the LHS words.
1576 unsigned lhsWords = getNumWords(getActiveBits());
1577
1578 // Deal with some degenerate cases
1579 if (!lhsWords)
1580 // 0 / X ===> 0
1581 return APInt(BitWidth, 0);
1582 if (RHS == 1)
1583 // X / 1 ===> X
1584 return *this;
1585 if (this->ult(RHS))
1586 // X / Y ===> 0, iff X < Y
1587 return APInt(BitWidth, 0);
1588 if (*this == RHS)
1589 // X / X ===> 1
1590 return APInt(BitWidth, 1);
1591 if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
1592 // All high words are zero, just use native divide
1593 return APInt(BitWidth, this->U.pVal[0] / RHS);
1594
1595 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1596 APInt Quotient(BitWidth, 0); // to hold result.
1597 divide(U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001598 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001599}
1600
Jakub Staszak6605c602013-02-20 00:17:42 +00001601APInt APInt::sdiv(const APInt &RHS) const {
1602 if (isNegative()) {
1603 if (RHS.isNegative())
1604 return (-(*this)).udiv(-RHS);
1605 return -((-(*this)).udiv(RHS));
1606 }
1607 if (RHS.isNegative())
1608 return -(this->udiv(-RHS));
1609 return this->udiv(RHS);
1610}
1611
Craig Topper8885f932017-05-19 16:43:54 +00001612APInt APInt::sdiv(int64_t RHS) const {
1613 if (isNegative()) {
1614 if (RHS < 0)
1615 return (-(*this)).udiv(-RHS);
1616 return -((-(*this)).udiv(RHS));
1617 }
1618 if (RHS < 0)
1619 return -(this->udiv(-RHS));
1620 return this->udiv(RHS);
1621}
1622
1623APInt APInt::urem(const APInt &RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001624 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001625 if (isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +00001626 assert(RHS.U.VAL != 0 && "Remainder by zero?");
1627 return APInt(BitWidth, U.VAL % RHS.U.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001628 }
Reid Spencer39867762007-02-17 02:07:07 +00001629
Reid Spencer58a6a432007-02-21 08:21:52 +00001630 // Get some facts about the LHS
Craig Topper62de0392017-05-10 07:50:15 +00001631 unsigned lhsWords = getNumWords(getActiveBits());
Reid Spencer39867762007-02-17 02:07:07 +00001632
1633 // Get some facts about the RHS
Craig Topperb1a71ca2017-05-12 21:45:50 +00001634 unsigned rhsBits = RHS.getActiveBits();
1635 unsigned rhsWords = getNumWords(rhsBits);
Reid Spencer39867762007-02-17 02:07:07 +00001636 assert(rhsWords && "Performing remainder operation by zero ???");
1637
Reid Spencer39867762007-02-17 02:07:07 +00001638 // Check the degenerate cases
Craig Topper24ae6952017-05-08 23:49:49 +00001639 if (lhsWords == 0)
Reid Spencer58a6a432007-02-21 08:21:52 +00001640 // 0 % Y ===> 0
1641 return APInt(BitWidth, 0);
Craig Topperb1a71ca2017-05-12 21:45:50 +00001642 if (rhsBits == 1)
1643 // X % 1 ===> 0
1644 return APInt(BitWidth, 0);
Craig Topper24ae6952017-05-08 23:49:49 +00001645 if (lhsWords < rhsWords || this->ult(RHS))
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001646 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001647 return *this;
Craig Topper24ae6952017-05-08 23:49:49 +00001648 if (*this == RHS)
Reid Spencer39867762007-02-17 02:07:07 +00001649 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001650 return APInt(BitWidth, 0);
Craig Topper24ae6952017-05-08 23:49:49 +00001651 if (lhsWords == 1)
Reid Spencer39867762007-02-17 02:07:07 +00001652 // All high words are zero, just use native remainder
Craig Topperb339c6d2017-05-03 15:46:24 +00001653 return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001654
Reid Spencer4c50b522007-05-13 23:44:59 +00001655 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Craig Topper8885f932017-05-19 16:43:54 +00001656 APInt Remainder(BitWidth, 0);
1657 divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, nullptr, Remainder.U.pVal);
1658 return Remainder;
1659}
1660
1661uint64_t APInt::urem(uint64_t RHS) const {
1662 assert(RHS != 0 && "Remainder by zero?");
1663
1664 if (isSingleWord())
1665 return U.VAL % RHS;
1666
1667 // Get some facts about the LHS
1668 unsigned lhsWords = getNumWords(getActiveBits());
1669
1670 // Check the degenerate cases
1671 if (lhsWords == 0)
1672 // 0 % Y ===> 0
1673 return 0;
1674 if (RHS == 1)
1675 // X % 1 ===> 0
1676 return 0;
1677 if (this->ult(RHS))
1678 // X % Y ===> X, iff X < Y
1679 return getZExtValue();
1680 if (*this == RHS)
1681 // X % X == 0;
1682 return 0;
1683 if (lhsWords == 1)
1684 // All high words are zero, just use native remainder
1685 return U.pVal[0] % RHS;
1686
1687 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1688 uint64_t Remainder;
1689 divide(U.pVal, lhsWords, &RHS, 1, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001690 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001691}
Reid Spencer100502d2007-02-17 03:16:00 +00001692
Jakub Staszak6605c602013-02-20 00:17:42 +00001693APInt APInt::srem(const APInt &RHS) const {
1694 if (isNegative()) {
1695 if (RHS.isNegative())
1696 return -((-(*this)).urem(-RHS));
1697 return -((-(*this)).urem(RHS));
1698 }
1699 if (RHS.isNegative())
1700 return this->urem(-RHS);
1701 return this->urem(RHS);
1702}
1703
Craig Topper8885f932017-05-19 16:43:54 +00001704int64_t APInt::srem(int64_t RHS) const {
1705 if (isNegative()) {
1706 if (RHS < 0)
1707 return -((-(*this)).urem(-RHS));
1708 return -((-(*this)).urem(RHS));
1709 }
1710 if (RHS < 0)
1711 return this->urem(-RHS);
1712 return this->urem(RHS);
1713}
1714
Eric Christopher820256b2009-08-21 04:06:45 +00001715void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001716 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001717 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
Craig Topper2579c7c2017-05-12 21:45:44 +00001718 unsigned BitWidth = LHS.BitWidth;
David Majnemer7f039202014-12-14 09:41:56 +00001719
1720 // First, deal with the easy case
1721 if (LHS.isSingleWord()) {
Craig Topperb339c6d2017-05-03 15:46:24 +00001722 assert(RHS.U.VAL != 0 && "Divide by zero?");
1723 uint64_t QuotVal = LHS.U.VAL / RHS.U.VAL;
1724 uint64_t RemVal = LHS.U.VAL % RHS.U.VAL;
Craig Topper2579c7c2017-05-12 21:45:44 +00001725 Quotient = APInt(BitWidth, QuotVal);
1726 Remainder = APInt(BitWidth, RemVal);
David Majnemer7f039202014-12-14 09:41:56 +00001727 return;
1728 }
1729
Reid Spencer4c50b522007-05-13 23:44:59 +00001730 // Get some size facts about the dividend and divisor
Craig Topper62de0392017-05-10 07:50:15 +00001731 unsigned lhsWords = getNumWords(LHS.getActiveBits());
Craig Topperb1a71ca2017-05-12 21:45:50 +00001732 unsigned rhsBits = RHS.getActiveBits();
1733 unsigned rhsWords = getNumWords(rhsBits);
Craig Topper4bdd6212017-05-12 18:19:01 +00001734 assert(rhsWords && "Performing divrem operation by zero ???");
Reid Spencer4c50b522007-05-13 23:44:59 +00001735
1736 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001737 if (lhsWords == 0) {
Krzysztof Parzyszek55a0dce2018-07-19 18:07:56 +00001738 Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
1739 Remainder = APInt(BitWidth, 0); // 0 % Y ===> 0
Reid Spencer4c50b522007-05-13 23:44:59 +00001740 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001741 }
1742
Craig Topperb1a71ca2017-05-12 21:45:50 +00001743 if (rhsBits == 1) {
Krzysztof Parzyszek55a0dce2018-07-19 18:07:56 +00001744 Quotient = LHS; // X / 1 ===> X
1745 Remainder = APInt(BitWidth, 0); // X % 1 ===> 0
Craig Topperb1a71ca2017-05-12 21:45:50 +00001746 }
1747
Eric Christopher820256b2009-08-21 04:06:45 +00001748 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Krzysztof Parzyszek55a0dce2018-07-19 18:07:56 +00001749 Remainder = LHS; // X % Y ===> X, iff X < Y
1750 Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00001751 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001752 }
1753
Reid Spencer4c50b522007-05-13 23:44:59 +00001754 if (LHS == RHS) {
Krzysztof Parzyszek55a0dce2018-07-19 18:07:56 +00001755 Quotient = APInt(BitWidth, 1); // X / X ===> 1
1756 Remainder = APInt(BitWidth, 0); // X % X ===> 0;
Reid Spencer4c50b522007-05-13 23:44:59 +00001757 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001758 }
1759
Craig Topper8885f932017-05-19 16:43:54 +00001760 // Make sure there is enough space to hold the results.
1761 // NOTE: This assumes that reallocate won't affect any bits if it doesn't
1762 // change the size. This is necessary if Quotient or Remainder is aliased
1763 // with LHS or RHS.
1764 Quotient.reallocate(BitWidth);
1765 Remainder.reallocate(BitWidth);
1766
Craig Topper06da0812017-05-12 18:18:57 +00001767 if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
Reid Spencer4c50b522007-05-13 23:44:59 +00001768 // There is only one word to consider so use the native versions.
Craig Topper93eabae2017-05-10 18:15:14 +00001769 uint64_t lhsValue = LHS.U.pVal[0];
1770 uint64_t rhsValue = RHS.U.pVal[0];
Craig Topper87694032017-05-12 07:21:09 +00001771 Quotient = lhsValue / rhsValue;
1772 Remainder = lhsValue % rhsValue;
Reid Spencer4c50b522007-05-13 23:44:59 +00001773 return;
1774 }
1775
1776 // Okay, lets do it the long way
Craig Topper8885f932017-05-19 16:43:54 +00001777 divide(LHS.U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal,
1778 Remainder.U.pVal);
1779 // Clear the rest of the Quotient and Remainder.
1780 std::memset(Quotient.U.pVal + lhsWords, 0,
1781 (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
1782 std::memset(Remainder.U.pVal + rhsWords, 0,
1783 (getNumWords(BitWidth) - rhsWords) * APINT_WORD_SIZE);
1784}
1785
1786void APInt::udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1787 uint64_t &Remainder) {
1788 assert(RHS != 0 && "Divide by zero?");
1789 unsigned BitWidth = LHS.BitWidth;
1790
1791 // First, deal with the easy case
1792 if (LHS.isSingleWord()) {
1793 uint64_t QuotVal = LHS.U.VAL / RHS;
1794 Remainder = LHS.U.VAL % RHS;
1795 Quotient = APInt(BitWidth, QuotVal);
1796 return;
1797 }
1798
1799 // Get some size facts about the dividend and divisor
1800 unsigned lhsWords = getNumWords(LHS.getActiveBits());
1801
1802 // Check the degenerate cases
1803 if (lhsWords == 0) {
Krzysztof Parzyszek55a0dce2018-07-19 18:07:56 +00001804 Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
1805 Remainder = 0; // 0 % Y ===> 0
Craig Topper8885f932017-05-19 16:43:54 +00001806 return;
1807 }
1808
1809 if (RHS == 1) {
Krzysztof Parzyszek55a0dce2018-07-19 18:07:56 +00001810 Quotient = LHS; // X / 1 ===> X
1811 Remainder = 0; // X % 1 ===> 0
1812 return;
Craig Topper8885f932017-05-19 16:43:54 +00001813 }
1814
1815 if (LHS.ult(RHS)) {
Krzysztof Parzyszek55a0dce2018-07-19 18:07:56 +00001816 Remainder = LHS.getZExtValue(); // X % Y ===> X, iff X < Y
1817 Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
Craig Topper8885f932017-05-19 16:43:54 +00001818 return;
1819 }
1820
1821 if (LHS == RHS) {
Krzysztof Parzyszek55a0dce2018-07-19 18:07:56 +00001822 Quotient = APInt(BitWidth, 1); // X / X ===> 1
1823 Remainder = 0; // X % X ===> 0;
Craig Topper8885f932017-05-19 16:43:54 +00001824 return;
1825 }
1826
1827 // Make sure there is enough space to hold the results.
1828 // NOTE: This assumes that reallocate won't affect any bits if it doesn't
1829 // change the size. This is necessary if Quotient is aliased with LHS.
1830 Quotient.reallocate(BitWidth);
1831
1832 if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
1833 // There is only one word to consider so use the native versions.
1834 uint64_t lhsValue = LHS.U.pVal[0];
1835 Quotient = lhsValue / RHS;
1836 Remainder = lhsValue % RHS;
1837 return;
1838 }
1839
1840 // Okay, lets do it the long way
1841 divide(LHS.U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, &Remainder);
1842 // Clear the rest of the Quotient.
1843 std::memset(Quotient.U.pVal + lhsWords, 0,
1844 (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
Reid Spencer4c50b522007-05-13 23:44:59 +00001845}
1846
Jakub Staszak6605c602013-02-20 00:17:42 +00001847void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
1848 APInt &Quotient, APInt &Remainder) {
1849 if (LHS.isNegative()) {
1850 if (RHS.isNegative())
1851 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
1852 else {
1853 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
Craig Topperb3c1f562017-05-11 07:02:04 +00001854 Quotient.negate();
Jakub Staszak6605c602013-02-20 00:17:42 +00001855 }
Craig Topperb3c1f562017-05-11 07:02:04 +00001856 Remainder.negate();
Jakub Staszak6605c602013-02-20 00:17:42 +00001857 } else if (RHS.isNegative()) {
1858 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
Craig Topperb3c1f562017-05-11 07:02:04 +00001859 Quotient.negate();
Jakub Staszak6605c602013-02-20 00:17:42 +00001860 } else {
1861 APInt::udivrem(LHS, RHS, Quotient, Remainder);
1862 }
1863}
1864
Craig Topper8885f932017-05-19 16:43:54 +00001865void APInt::sdivrem(const APInt &LHS, int64_t RHS,
1866 APInt &Quotient, int64_t &Remainder) {
1867 uint64_t R = Remainder;
1868 if (LHS.isNegative()) {
1869 if (RHS < 0)
1870 APInt::udivrem(-LHS, -RHS, Quotient, R);
1871 else {
1872 APInt::udivrem(-LHS, RHS, Quotient, R);
1873 Quotient.negate();
1874 }
1875 R = -R;
1876 } else if (RHS < 0) {
1877 APInt::udivrem(LHS, -RHS, Quotient, R);
1878 Quotient.negate();
1879 } else {
1880 APInt::udivrem(LHS, RHS, Quotient, R);
1881 }
1882 Remainder = R;
1883}
1884
Chris Lattner2c819b02010-10-13 23:54:10 +00001885APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001886 APInt Res = *this+RHS;
1887 Overflow = isNonNegative() == RHS.isNonNegative() &&
1888 Res.isNonNegative() != isNonNegative();
1889 return Res;
1890}
1891
Chris Lattner698661c2010-10-14 00:05:07 +00001892APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
1893 APInt Res = *this+RHS;
1894 Overflow = Res.ult(RHS);
1895 return Res;
1896}
1897
Chris Lattner2c819b02010-10-13 23:54:10 +00001898APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001899 APInt Res = *this - RHS;
1900 Overflow = isNonNegative() != RHS.isNonNegative() &&
1901 Res.isNonNegative() != isNonNegative();
1902 return Res;
1903}
1904
Chris Lattner698661c2010-10-14 00:05:07 +00001905APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00001906 APInt Res = *this-RHS;
1907 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00001908 return Res;
1909}
1910
Chris Lattner2c819b02010-10-13 23:54:10 +00001911APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001912 // MININT/-1 --> overflow.
1913 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
1914 return sdiv(RHS);
1915}
1916
Chris Lattner2c819b02010-10-13 23:54:10 +00001917APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001918 APInt Res = *this * RHS;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001919
Chris Lattner79bdd882010-10-13 23:46:33 +00001920 if (*this != 0 && RHS != 0)
1921 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
1922 else
1923 Overflow = false;
1924 return Res;
1925}
1926
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001927APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
1928 APInt Res = *this * RHS;
1929
1930 if (*this != 0 && RHS != 0)
1931 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
1932 else
1933 Overflow = false;
1934 return Res;
1935}
1936
David Majnemera2521382014-10-13 21:48:30 +00001937APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
1938 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00001939 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00001940 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00001941
1942 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00001943 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00001944 else
David Majnemera2521382014-10-13 21:48:30 +00001945 Overflow = ShAmt.uge(countLeadingOnes());
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001946
Chris Lattner79bdd882010-10-13 23:46:33 +00001947 return *this << ShAmt;
1948}
1949
David Majnemera2521382014-10-13 21:48:30 +00001950APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
1951 Overflow = ShAmt.uge(getBitWidth());
1952 if (Overflow)
1953 return APInt(BitWidth, 0);
1954
1955 Overflow = ShAmt.ugt(countLeadingZeros());
1956
1957 return *this << ShAmt;
1958}
1959
Chris Lattner79bdd882010-10-13 23:46:33 +00001960
1961
1962
Benjamin Kramer92d89982010-07-14 22:38:02 +00001963void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00001964 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001965 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001966 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00001967 radix == 36) &&
1968 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001969
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001970 StringRef::iterator p = str.begin();
1971 size_t slen = str.size();
1972 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001973 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001974 p++;
1975 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00001976 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001977 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00001978 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00001979 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
1980 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001981 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
1982 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00001983
Craig Topperb339c6d2017-05-03 15:46:24 +00001984 // Allocate memory if needed
1985 if (isSingleWord())
1986 U.VAL = 0;
1987 else
1988 U.pVal = getClearedMemory(getNumWords());
Reid Spencer1ba83352007-02-21 03:55:44 +00001989
1990 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00001991 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00001992
Reid Spencer1ba83352007-02-21 03:55:44 +00001993 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001994 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00001995 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00001996 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00001997
Reid Spencera93c9812007-05-16 19:18:22 +00001998 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00001999 if (slen > 1) {
2000 if (shift)
2001 *this <<= shift;
2002 else
Craig Topperf15bec52017-05-08 04:55:12 +00002003 *this *= radix;
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002004 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002005
2006 // Add in the digit we just interpreted
Craig Topperb7d8faa2017-04-02 06:59:38 +00002007 *this += digit;
Reid Spencer100502d2007-02-17 03:16:00 +00002008 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002009 // If its negative, put it in two's complement form
Craig Topperef0114c2017-05-10 20:01:38 +00002010 if (isNeg)
2011 this->negate();
Reid Spencer100502d2007-02-17 03:16:00 +00002012}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002013
Chris Lattner17f71652008-08-17 07:19:36 +00002014void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002015 bool Signed, bool formatAsCLiteral) const {
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002016 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002017 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002018 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002019
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002020 const char *Prefix = "";
2021 if (formatAsCLiteral) {
2022 switch (Radix) {
2023 case 2:
2024 // Binary literals are a non-standard extension added in gcc 4.3:
2025 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2026 Prefix = "0b";
2027 break;
2028 case 8:
2029 Prefix = "0";
2030 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002031 case 10:
2032 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002033 case 16:
2034 Prefix = "0x";
2035 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002036 default:
2037 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002038 }
2039 }
2040
Chris Lattner17f71652008-08-17 07:19:36 +00002041 // First, check for a zero value and just short circuit the logic below.
2042 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002043 while (*Prefix) {
2044 Str.push_back(*Prefix);
2045 ++Prefix;
2046 };
Chris Lattner17f71652008-08-17 07:19:36 +00002047 Str.push_back('0');
2048 return;
2049 }
Eric Christopher820256b2009-08-21 04:06:45 +00002050
Douglas Gregor663c0682011-09-14 15:54:46 +00002051 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002052
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002053 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002054 char Buffer[65];
Craig Toppere6a23182017-05-24 07:00:55 +00002055 char *BufPtr = std::end(Buffer);
Eric Christopher820256b2009-08-21 04:06:45 +00002056
Chris Lattner17f71652008-08-17 07:19:36 +00002057 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002058 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002059 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002060 } else {
2061 int64_t I = getSExtValue();
2062 if (I >= 0) {
2063 N = I;
2064 } else {
2065 Str.push_back('-');
2066 N = -(uint64_t)I;
2067 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002068 }
Eric Christopher820256b2009-08-21 04:06:45 +00002069
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002070 while (*Prefix) {
2071 Str.push_back(*Prefix);
2072 ++Prefix;
2073 };
2074
Chris Lattner17f71652008-08-17 07:19:36 +00002075 while (N) {
2076 *--BufPtr = Digits[N % Radix];
2077 N /= Radix;
2078 }
Craig Toppere6a23182017-05-24 07:00:55 +00002079 Str.append(BufPtr, std::end(Buffer));
Chris Lattner17f71652008-08-17 07:19:36 +00002080 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002081 }
2082
Chris Lattner17f71652008-08-17 07:19:36 +00002083 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002084
Chris Lattner17f71652008-08-17 07:19:36 +00002085 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002086 // They want to print the signed version and it is a negative value
2087 // Flip the bits and add one to turn it into the equivalent positive
2088 // value and put a '-' in the result.
Craig Topperef0114c2017-05-10 20:01:38 +00002089 Tmp.negate();
Chris Lattner17f71652008-08-17 07:19:36 +00002090 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002091 }
Eric Christopher820256b2009-08-21 04:06:45 +00002092
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002093 while (*Prefix) {
2094 Str.push_back(*Prefix);
2095 ++Prefix;
2096 };
2097
Chris Lattner17f71652008-08-17 07:19:36 +00002098 // We insert the digits backward, then reverse them to get the right order.
2099 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002100
2101 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2102 // because the number of bits per digit (1, 3 and 4 respectively) divides
Craig Topperd7ed50d2017-04-02 06:59:36 +00002103 // equally. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002104 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002105 // Just shift tmp right for each digit width until it becomes zero
2106 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2107 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002108
Craig Topperecb97da2017-05-10 18:15:24 +00002109 while (Tmp.getBoolValue()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002110 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2111 Str.push_back(Digits[Digit]);
Craig Topperfc947bc2017-04-18 17:14:21 +00002112 Tmp.lshrInPlace(ShiftAmt);
Chris Lattner17f71652008-08-17 07:19:36 +00002113 }
2114 } else {
Craig Topperecb97da2017-05-10 18:15:24 +00002115 while (Tmp.getBoolValue()) {
Craig Topper8885f932017-05-19 16:43:54 +00002116 uint64_t Digit;
2117 udivrem(Tmp, Radix, Tmp, Digit);
Chris Lattner17f71652008-08-17 07:19:36 +00002118 assert(Digit < Radix && "divide failed");
2119 Str.push_back(Digits[Digit]);
Chris Lattner17f71652008-08-17 07:19:36 +00002120 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002121 }
Eric Christopher820256b2009-08-21 04:06:45 +00002122
Chris Lattner17f71652008-08-17 07:19:36 +00002123 // Reverse the digits before returning.
2124 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002125}
2126
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002127/// Returns the APInt as a std::string. Note that this is an inefficient method.
2128/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002129std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2130 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002131 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002132 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002133}
Chris Lattner6b695682007-08-16 15:56:55 +00002134
Aaron Ballman615eb472017-10-15 14:32:27 +00002135#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002136LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002137 SmallString<40> S, U;
2138 this->toStringUnsigned(U);
2139 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002140 dbgs() << "APInt(" << BitWidth << "b, "
Davide Italiano5a473d22017-01-31 21:26:18 +00002141 << U << "u " << S << "s)\n";
Chris Lattner17f71652008-08-17 07:19:36 +00002142}
Matthias Braun8c209aa2017-01-28 02:02:38 +00002143#endif
Chris Lattner17f71652008-08-17 07:19:36 +00002144
Chris Lattner0c19df42008-08-23 22:23:09 +00002145void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002146 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002147 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002148 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002149}
2150
Chris Lattner6b695682007-08-16 15:56:55 +00002151// This implements a variety of operations on a representation of
2152// arbitrary precision, two's-complement, bignum integer values.
2153
Chris Lattner96cffa62009-08-23 23:11:28 +00002154// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2155// and unrestricting assumption.
Craig Topper55229b72017-04-02 19:17:22 +00002156static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
2157 "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002158
2159/* Some handy functions local to this file. */
Chris Lattner6b695682007-08-16 15:56:55 +00002160
Craig Topper76f42462017-03-28 05:32:53 +00002161/* Returns the integer part with the least significant BITS set.
2162 BITS cannot be zero. */
Craig Topper55229b72017-04-02 19:17:22 +00002163static inline APInt::WordType lowBitMask(unsigned bits) {
2164 assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002165
Craig Topper55229b72017-04-02 19:17:22 +00002166 return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
Craig Topper76f42462017-03-28 05:32:53 +00002167}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002168
Craig Topper76f42462017-03-28 05:32:53 +00002169/* Returns the value of the lower half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002170static inline APInt::WordType lowHalf(APInt::WordType part) {
2171 return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002172}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002173
Craig Topper76f42462017-03-28 05:32:53 +00002174/* Returns the value of the upper half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002175static inline APInt::WordType highHalf(APInt::WordType part) {
2176 return part >> (APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002177}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002178
Craig Topper76f42462017-03-28 05:32:53 +00002179/* Returns the bit number of the most significant set bit of a part.
2180 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002181static unsigned partMSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002182 return findLastSet(value, ZB_Max);
2183}
Chris Lattner6b695682007-08-16 15:56:55 +00002184
Craig Topper76f42462017-03-28 05:32:53 +00002185/* Returns the bit number of the least significant set bit of a
2186 part. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002187static unsigned partLSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002188 return findFirstSet(value, ZB_Max);
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002189}
Chris Lattner6b695682007-08-16 15:56:55 +00002190
2191/* Sets the least significant part of a bignum to the input value, and
2192 zeroes out higher parts. */
Craig Topper55229b72017-04-02 19:17:22 +00002193void APInt::tcSet(WordType *dst, WordType part, unsigned parts) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002194 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002195
Chris Lattner6b695682007-08-16 15:56:55 +00002196 dst[0] = part;
Craig Topperb0038162017-03-28 05:32:52 +00002197 for (unsigned i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002198 dst[i] = 0;
2199}
2200
2201/* Assign one bignum to another. */
Craig Topper55229b72017-04-02 19:17:22 +00002202void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002203 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002204 dst[i] = src[i];
2205}
2206
2207/* Returns true if a bignum is zero, false otherwise. */
Craig Topper55229b72017-04-02 19:17:22 +00002208bool APInt::tcIsZero(const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002209 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002210 if (src[i])
2211 return false;
2212
2213 return true;
2214}
2215
2216/* Extract the given bit of a bignum; returns 0 or 1. */
Craig Topper55229b72017-04-02 19:17:22 +00002217int APInt::tcExtractBit(const WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002218 return (parts[whichWord(bit)] & maskBit(bit)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002219}
2220
John McCalldcb9a7a2010-02-28 02:51:25 +00002221/* Set the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002222void APInt::tcSetBit(WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002223 parts[whichWord(bit)] |= maskBit(bit);
Chris Lattner6b695682007-08-16 15:56:55 +00002224}
2225
John McCalldcb9a7a2010-02-28 02:51:25 +00002226/* Clears the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002227void APInt::tcClearBit(WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002228 parts[whichWord(bit)] &= ~maskBit(bit);
John McCalldcb9a7a2010-02-28 02:51:25 +00002229}
2230
Neil Boothc8b650a2007-10-06 00:43:45 +00002231/* Returns the bit number of the least significant set bit of a
2232 number. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002233unsigned APInt::tcLSB(const WordType *parts, unsigned n) {
Craig Topperb0038162017-03-28 05:32:52 +00002234 for (unsigned i = 0; i < n; i++) {
2235 if (parts[i] != 0) {
2236 unsigned lsb = partLSB(parts[i]);
Chris Lattner6b695682007-08-16 15:56:55 +00002237
Craig Topper55229b72017-04-02 19:17:22 +00002238 return lsb + i * APINT_BITS_PER_WORD;
Craig Topperb0038162017-03-28 05:32:52 +00002239 }
Chris Lattner6b695682007-08-16 15:56:55 +00002240 }
2241
2242 return -1U;
2243}
2244
Neil Boothc8b650a2007-10-06 00:43:45 +00002245/* Returns the bit number of the most significant set bit of a number.
2246 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002247unsigned APInt::tcMSB(const WordType *parts, unsigned n) {
Chris Lattner6b695682007-08-16 15:56:55 +00002248 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002249 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002250
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002251 if (parts[n] != 0) {
Craig Topperb0038162017-03-28 05:32:52 +00002252 unsigned msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002253
Craig Topper55229b72017-04-02 19:17:22 +00002254 return msb + n * APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002255 }
Chris Lattner6b695682007-08-16 15:56:55 +00002256 } while (n);
2257
2258 return -1U;
2259}
2260
Neil Boothb6182162007-10-08 13:47:12 +00002261/* Copy the bit vector of width srcBITS from SRC, starting at bit
2262 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2263 the least significant bit of DST. All high bits above srcBITS in
2264 DST are zero-filled. */
2265void
Craig Topper55229b72017-04-02 19:17:22 +00002266APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src,
Craig Topper6a8518082017-03-28 05:32:55 +00002267 unsigned srcBits, unsigned srcLSB) {
Craig Topper55229b72017-04-02 19:17:22 +00002268 unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002269 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002270
Craig Topper55229b72017-04-02 19:17:22 +00002271 unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002272 tcAssign (dst, src + firstSrcPart, dstParts);
2273
Craig Topper55229b72017-04-02 19:17:22 +00002274 unsigned shift = srcLSB % APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002275 tcShiftRight (dst, dstParts, shift);
2276
Craig Topper55229b72017-04-02 19:17:22 +00002277 /* We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC
Neil Boothb6182162007-10-08 13:47:12 +00002278 in DST. If this is less that srcBits, append the rest, else
2279 clear the high bits. */
Craig Topper55229b72017-04-02 19:17:22 +00002280 unsigned n = dstParts * APINT_BITS_PER_WORD - shift;
Neil Boothb6182162007-10-08 13:47:12 +00002281 if (n < srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002282 WordType mask = lowBitMask (srcBits - n);
Neil Boothb6182162007-10-08 13:47:12 +00002283 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
Craig Topper55229b72017-04-02 19:17:22 +00002284 << n % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002285 } else if (n > srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002286 if (srcBits % APINT_BITS_PER_WORD)
2287 dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002288 }
2289
2290 /* Clear high parts. */
2291 while (dstParts < dstCount)
2292 dst[dstParts++] = 0;
2293}
2294
Chris Lattner6b695682007-08-16 15:56:55 +00002295/* DST += RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002296APInt::WordType APInt::tcAdd(WordType *dst, const WordType *rhs,
2297 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002298 assert(c <= 1);
2299
Craig Topperb0038162017-03-28 05:32:52 +00002300 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002301 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002302 if (c) {
2303 dst[i] += rhs[i] + 1;
2304 c = (dst[i] <= l);
2305 } else {
2306 dst[i] += rhs[i];
2307 c = (dst[i] < l);
2308 }
2309 }
2310
2311 return c;
2312}
2313
Craig Topper92fc4772017-04-13 04:36:06 +00002314/// This function adds a single "word" integer, src, to the multiple
2315/// "word" integer array, dst[]. dst[] is modified to reflect the addition and
2316/// 1 is returned if there is a carry out, otherwise 0 is returned.
2317/// @returns the carry of the addition.
2318APInt::WordType APInt::tcAddPart(WordType *dst, WordType src,
2319 unsigned parts) {
2320 for (unsigned i = 0; i < parts; ++i) {
2321 dst[i] += src;
2322 if (dst[i] >= src)
2323 return 0; // No need to carry so exit early.
2324 src = 1; // Carry one to next digit.
2325 }
2326
2327 return 1;
2328}
2329
Chris Lattner6b695682007-08-16 15:56:55 +00002330/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002331APInt::WordType APInt::tcSubtract(WordType *dst, const WordType *rhs,
2332 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002333 assert(c <= 1);
2334
Craig Topperb0038162017-03-28 05:32:52 +00002335 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002336 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002337 if (c) {
2338 dst[i] -= rhs[i] + 1;
2339 c = (dst[i] >= l);
2340 } else {
2341 dst[i] -= rhs[i];
2342 c = (dst[i] > l);
2343 }
2344 }
2345
2346 return c;
2347}
2348
Craig Topper92fc4772017-04-13 04:36:06 +00002349/// This function subtracts a single "word" (64-bit word), src, from
2350/// the multi-word integer array, dst[], propagating the borrowed 1 value until
2351/// no further borrowing is needed or it runs out of "words" in dst. The result
2352/// is 1 if "borrowing" exhausted the digits in dst, or 0 if dst was not
2353/// exhausted. In other words, if src > dst then this function returns 1,
2354/// otherwise 0.
2355/// @returns the borrow out of the subtraction
2356APInt::WordType APInt::tcSubtractPart(WordType *dst, WordType src,
2357 unsigned parts) {
2358 for (unsigned i = 0; i < parts; ++i) {
2359 WordType Dst = dst[i];
2360 dst[i] -= src;
2361 if (src <= Dst)
2362 return 0; // No need to borrow so exit early.
2363 src = 1; // We have to "borrow 1" from next "word"
2364 }
2365
2366 return 1;
2367}
2368
Chris Lattner6b695682007-08-16 15:56:55 +00002369/* Negate a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002370void APInt::tcNegate(WordType *dst, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002371 tcComplement(dst, parts);
2372 tcIncrement(dst, parts);
2373}
2374
Neil Boothc8b650a2007-10-06 00:43:45 +00002375/* DST += SRC * MULTIPLIER + CARRY if add is true
2376 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002377
2378 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2379 they must start at the same point, i.e. DST == SRC.
2380
2381 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2382 returned. Otherwise DST is filled with the least significant
2383 DSTPARTS parts of the result, and if all of the omitted higher
2384 parts were zero return zero, otherwise overflow occurred and
2385 return one. */
Craig Topper55229b72017-04-02 19:17:22 +00002386int APInt::tcMultiplyPart(WordType *dst, const WordType *src,
2387 WordType multiplier, WordType carry,
Craig Topper6a8518082017-03-28 05:32:55 +00002388 unsigned srcParts, unsigned dstParts,
2389 bool add) {
Chris Lattner6b695682007-08-16 15:56:55 +00002390 /* Otherwise our writes of DST kill our later reads of SRC. */
2391 assert(dst <= src || dst >= src + srcParts);
2392 assert(dstParts <= srcParts + 1);
2393
2394 /* N loops; minimum of dstParts and srcParts. */
Craig Topper0cbab7c2017-05-08 06:34:39 +00002395 unsigned n = std::min(dstParts, srcParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002396
Craig Topperc96a84d2017-05-08 06:34:41 +00002397 for (unsigned i = 0; i < n; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002398 WordType low, mid, high, srcPart;
Chris Lattner6b695682007-08-16 15:56:55 +00002399
2400 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2401
2402 This cannot overflow, because
2403
2404 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2405
2406 which is less than n^2. */
2407
2408 srcPart = src[i];
2409
Craig Topper6a8518082017-03-28 05:32:55 +00002410 if (multiplier == 0 || srcPart == 0) {
Chris Lattner6b695682007-08-16 15:56:55 +00002411 low = carry;
2412 high = 0;
2413 } else {
2414 low = lowHalf(srcPart) * lowHalf(multiplier);
2415 high = highHalf(srcPart) * highHalf(multiplier);
2416
2417 mid = lowHalf(srcPart) * highHalf(multiplier);
2418 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002419 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002420 if (low + mid < low)
2421 high++;
2422 low += mid;
2423
2424 mid = highHalf(srcPart) * lowHalf(multiplier);
2425 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002426 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002427 if (low + mid < low)
2428 high++;
2429 low += mid;
2430
2431 /* Now add carry. */
2432 if (low + carry < low)
2433 high++;
2434 low += carry;
2435 }
2436
2437 if (add) {
2438 /* And now DST[i], and store the new low part there. */
2439 if (low + dst[i] < low)
2440 high++;
2441 dst[i] += low;
2442 } else
2443 dst[i] = low;
2444
2445 carry = high;
2446 }
2447
Craig Topperc96a84d2017-05-08 06:34:41 +00002448 if (srcParts < dstParts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002449 /* Full multiplication, there is no overflow. */
Craig Topperc96a84d2017-05-08 06:34:41 +00002450 assert(srcParts + 1 == dstParts);
2451 dst[srcParts] = carry;
Chris Lattner6b695682007-08-16 15:56:55 +00002452 return 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002453 }
Craig Toppera6c142a2017-05-08 06:34:36 +00002454
2455 /* We overflowed if there is carry. */
2456 if (carry)
2457 return 1;
2458
2459 /* We would overflow if any significant unwritten parts would be
2460 non-zero. This is true if any remaining src parts are non-zero
2461 and the multiplier is non-zero. */
2462 if (multiplier)
Craig Topperc96a84d2017-05-08 06:34:41 +00002463 for (unsigned i = dstParts; i < srcParts; i++)
Craig Toppera6c142a2017-05-08 06:34:36 +00002464 if (src[i])
2465 return 1;
2466
2467 /* We fitted in the narrow destination. */
2468 return 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002469}
2470
2471/* DST = LHS * RHS, where DST has the same width as the operands and
2472 is filled with the least significant parts of the result. Returns
2473 one if overflow occurred, otherwise zero. DST must be disjoint
2474 from both operands. */
Craig Topper55229b72017-04-02 19:17:22 +00002475int APInt::tcMultiply(WordType *dst, const WordType *lhs,
2476 const WordType *rhs, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002477 assert(dst != lhs && dst != rhs);
2478
Craig Topperb0038162017-03-28 05:32:52 +00002479 int overflow = 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002480 tcSet(dst, 0, parts);
2481
Craig Topperb0038162017-03-28 05:32:52 +00002482 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002483 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2484 parts - i, true);
2485
2486 return overflow;
2487}
2488
Craig Topper0acb6652017-05-09 16:47:33 +00002489/// DST = LHS * RHS, where DST has width the sum of the widths of the
2490/// operands. No overflow occurs. DST must be disjoint from both operands.
2491void APInt::tcFullMultiply(WordType *dst, const WordType *lhs,
2492 const WordType *rhs, unsigned lhsParts,
2493 unsigned rhsParts) {
Neil Booth0ea72a92007-10-06 00:24:48 +00002494 /* Put the narrower number on the LHS for less loops below. */
Craig Toppera6c142a2017-05-08 06:34:36 +00002495 if (lhsParts > rhsParts)
Neil Booth0ea72a92007-10-06 00:24:48 +00002496 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002497
Craig Toppera6c142a2017-05-08 06:34:36 +00002498 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002499
Craig Toppera6c142a2017-05-08 06:34:36 +00002500 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002501
Craig Toppera6c142a2017-05-08 06:34:36 +00002502 for (unsigned i = 0; i < lhsParts; i++)
2503 tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002504}
2505
2506/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2507 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2508 set REMAINDER to the remainder, return zero. i.e.
2509
2510 OLD_LHS = RHS * LHS + REMAINDER
2511
2512 SCRATCH is a bignum of the same size as the operands and result for
2513 use by the routine; its contents need not be initialized and are
2514 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2515*/
Craig Topper55229b72017-04-02 19:17:22 +00002516int APInt::tcDivide(WordType *lhs, const WordType *rhs,
2517 WordType *remainder, WordType *srhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002518 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002519 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2520
Craig Topperb0038162017-03-28 05:32:52 +00002521 unsigned shiftCount = tcMSB(rhs, parts) + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002522 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002523 return true;
2524
Craig Topper55229b72017-04-02 19:17:22 +00002525 shiftCount = parts * APINT_BITS_PER_WORD - shiftCount;
2526 unsigned n = shiftCount / APINT_BITS_PER_WORD;
2527 WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD);
Chris Lattner6b695682007-08-16 15:56:55 +00002528
2529 tcAssign(srhs, rhs, parts);
2530 tcShiftLeft(srhs, parts, shiftCount);
2531 tcAssign(remainder, lhs, parts);
2532 tcSet(lhs, 0, parts);
2533
2534 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2535 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002536 for (;;) {
Craig Toppera584af52017-05-10 07:50:17 +00002537 int compare = tcCompare(remainder, srhs, parts);
2538 if (compare >= 0) {
2539 tcSubtract(remainder, srhs, 0, parts);
2540 lhs[n] |= mask;
2541 }
Chris Lattner6b695682007-08-16 15:56:55 +00002542
Craig Toppera584af52017-05-10 07:50:17 +00002543 if (shiftCount == 0)
2544 break;
2545 shiftCount--;
2546 tcShiftRight(srhs, parts, 1);
2547 if ((mask >>= 1) == 0) {
2548 mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1);
2549 n--;
2550 }
Chris Lattner6b695682007-08-16 15:56:55 +00002551 }
2552
2553 return false;
2554}
2555
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002556/// Shift a bignum left Cound bits in-place. Shifted in bits are zero. There are
2557/// no restrictions on Count.
2558void APInt::tcShiftLeft(WordType *Dst, unsigned Words, unsigned Count) {
2559 // Don't bother performing a no-op shift.
2560 if (!Count)
2561 return;
Chris Lattner6b695682007-08-16 15:56:55 +00002562
Craig Topperc6b05682017-04-24 17:00:22 +00002563 // WordShift is the inter-part shift; BitShift is the intra-part shift.
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002564 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2565 unsigned BitShift = Count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002566
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002567 // Fastpath for moving by whole words.
2568 if (BitShift == 0) {
2569 std::memmove(Dst + WordShift, Dst, (Words - WordShift) * APINT_WORD_SIZE);
2570 } else {
2571 while (Words-- > WordShift) {
2572 Dst[Words] = Dst[Words - WordShift] << BitShift;
2573 if (Words > WordShift)
2574 Dst[Words] |=
2575 Dst[Words - WordShift - 1] >> (APINT_BITS_PER_WORD - BitShift);
Neil Boothb6182162007-10-08 13:47:12 +00002576 }
Neil Boothb6182162007-10-08 13:47:12 +00002577 }
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002578
2579 // Fill in the remainder with 0s.
2580 std::memset(Dst, 0, WordShift * APINT_WORD_SIZE);
Chris Lattner6b695682007-08-16 15:56:55 +00002581}
2582
Craig Topper9575d8f2017-04-17 21:43:43 +00002583/// Shift a bignum right Count bits in-place. Shifted in bits are zero. There
2584/// are no restrictions on Count.
2585void APInt::tcShiftRight(WordType *Dst, unsigned Words, unsigned Count) {
2586 // Don't bother performing a no-op shift.
2587 if (!Count)
2588 return;
Chris Lattner6b695682007-08-16 15:56:55 +00002589
Craig Topperc6b05682017-04-24 17:00:22 +00002590 // WordShift is the inter-part shift; BitShift is the intra-part shift.
Craig Topper9575d8f2017-04-17 21:43:43 +00002591 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2592 unsigned BitShift = Count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002593
Craig Topper9575d8f2017-04-17 21:43:43 +00002594 unsigned WordsToMove = Words - WordShift;
2595 // Fastpath for moving by whole words.
2596 if (BitShift == 0) {
2597 std::memmove(Dst, Dst + WordShift, WordsToMove * APINT_WORD_SIZE);
2598 } else {
2599 for (unsigned i = 0; i != WordsToMove; ++i) {
2600 Dst[i] = Dst[i + WordShift] >> BitShift;
2601 if (i + 1 != WordsToMove)
2602 Dst[i] |= Dst[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift);
Neil Boothb6182162007-10-08 13:47:12 +00002603 }
Chris Lattner6b695682007-08-16 15:56:55 +00002604 }
Craig Topper9575d8f2017-04-17 21:43:43 +00002605
2606 // Fill in the remainder with 0s.
2607 std::memset(Dst + WordsToMove, 0, WordShift * APINT_WORD_SIZE);
Chris Lattner6b695682007-08-16 15:56:55 +00002608}
2609
2610/* Bitwise and of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002611void APInt::tcAnd(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002612 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002613 dst[i] &= rhs[i];
2614}
2615
2616/* Bitwise inclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002617void APInt::tcOr(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002618 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002619 dst[i] |= rhs[i];
2620}
2621
2622/* Bitwise exclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002623void APInt::tcXor(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002624 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002625 dst[i] ^= rhs[i];
2626}
2627
2628/* Complement a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002629void APInt::tcComplement(WordType *dst, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002630 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002631 dst[i] = ~dst[i];
2632}
2633
2634/* Comparison (unsigned) of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002635int APInt::tcCompare(const WordType *lhs, const WordType *rhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002636 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002637 while (parts) {
Craig Topper99cfe4f2017-04-01 21:50:06 +00002638 parts--;
Craig Topper1dc8fc82017-04-21 16:13:15 +00002639 if (lhs[parts] != rhs[parts])
2640 return (lhs[parts] > rhs[parts]) ? 1 : -1;
Craig Topper99cfe4f2017-04-01 21:50:06 +00002641 }
Chris Lattner6b695682007-08-16 15:56:55 +00002642
2643 return 0;
2644}
2645
Chris Lattner6b695682007-08-16 15:56:55 +00002646/* Set the least significant BITS bits of a bignum, clear the
2647 rest. */
Craig Topper55229b72017-04-02 19:17:22 +00002648void APInt::tcSetLeastSignificantBits(WordType *dst, unsigned parts,
Craig Topper6a8518082017-03-28 05:32:55 +00002649 unsigned bits) {
Craig Topperb0038162017-03-28 05:32:52 +00002650 unsigned i = 0;
Craig Topper55229b72017-04-02 19:17:22 +00002651 while (bits > APINT_BITS_PER_WORD) {
2652 dst[i++] = ~(WordType) 0;
2653 bits -= APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002654 }
2655
2656 if (bits)
Craig Topper55229b72017-04-02 19:17:22 +00002657 dst[i++] = ~(WordType) 0 >> (APINT_BITS_PER_WORD - bits);
Chris Lattner6b695682007-08-16 15:56:55 +00002658
2659 while (i < parts)
2660 dst[i++] = 0;
2661}
Tim Shen802c31c2018-06-25 23:49:20 +00002662
2663APInt llvm::APIntOps::RoundingUDiv(const APInt &A, const APInt &B,
2664 APInt::Rounding RM) {
2665 // Currently udivrem always rounds down.
2666 switch (RM) {
2667 case APInt::Rounding::DOWN:
2668 case APInt::Rounding::TOWARD_ZERO:
2669 return A.udiv(B);
2670 case APInt::Rounding::UP: {
2671 APInt Quo, Rem;
2672 APInt::udivrem(A, B, Quo, Rem);
2673 if (Rem == 0)
2674 return Quo;
2675 return Quo + 1;
2676 }
2677 }
Simon Pilgrim9b3b0fe2018-06-26 09:31:18 +00002678 llvm_unreachable("Unknown APInt::Rounding enum");
Tim Shen802c31c2018-06-25 23:49:20 +00002679}
2680
2681APInt llvm::APIntOps::RoundingSDiv(const APInt &A, const APInt &B,
2682 APInt::Rounding RM) {
2683 switch (RM) {
2684 case APInt::Rounding::DOWN:
2685 case APInt::Rounding::UP: {
2686 APInt Quo, Rem;
2687 APInt::sdivrem(A, B, Quo, Rem);
2688 if (Rem == 0)
2689 return Quo;
2690 // This algorithm deals with arbitrary rounding mode used by sdivrem.
2691 // We want to check whether the non-integer part of the mathematical value
2692 // is negative or not. If the non-integer part is negative, we need to round
2693 // down from Quo; otherwise, if it's positive or 0, we return Quo, as it's
2694 // already rounded down.
2695 if (RM == APInt::Rounding::DOWN) {
2696 if (Rem.isNegative() != B.isNegative())
2697 return Quo - 1;
2698 return Quo;
2699 }
2700 if (Rem.isNegative() != B.isNegative())
2701 return Quo;
2702 return Quo + 1;
2703 }
2704 // Currently sdiv rounds twards zero.
2705 case APInt::Rounding::TOWARD_ZERO:
2706 return A.sdiv(B);
2707 }
Simon Pilgrim9b3b0fe2018-06-26 09:31:18 +00002708 llvm_unreachable("Unknown APInt::Rounding enum");
Tim Shen802c31c2018-06-25 23:49:20 +00002709}