blob: 77ecd7a9077130774e462ed439d5eeccbc731958 [file] [log] [blame]
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001//===- ConstantRange.cpp - ConstantRange implementation -------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner113f2ae2002-09-01 23:53:36 +00009//
10// Represent a range of possible values that may occur when the program is run
11// for an integral value. This keeps track of a lower and upper bound for the
12// constant, which MAY wrap around the end of the numeric range. To do this, it
13// keeps track of a [lower, upper) bound, which specifies an interval just like
14// STL iterators. When used with boolean values, the following are important
15// ranges (other integral ranges use min/max values for special range values):
16//
17// [F, F) = {} = Empty set
18// [T, F) = {T}
19// [F, T) = {F}
20// [T, T) = {F, T} = Full set
21//
22//===----------------------------------------------------------------------===//
23
Eugene Zelenkode6cce22017-06-19 22:05:08 +000024#include "llvm/ADT/APInt.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000025#include "llvm/IR/ConstantRange.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000026#include "llvm/IR/Constants.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000027#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000029#include "llvm/IR/Metadata.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000030#include "llvm/IR/Operator.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000031#include "llvm/Support/Compiler.h"
David Greenede7b3532010-01-05 01:28:32 +000032#include "llvm/Support/Debug.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000034#include "llvm/Support/raw_ostream.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000035#include <algorithm>
36#include <cassert>
37#include <cstdint>
38
Chris Lattnerc9499b62003-12-14 21:35:53 +000039using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000040
Craig Topperee4f22d2017-04-29 05:08:52 +000041ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
42 : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
43 Upper(Lower) {}
Chris Lattner113f2ae2002-09-01 23:53:36 +000044
Craig Topper37df0182017-04-13 00:20:31 +000045ConstantRange::ConstantRange(APInt V)
Chandler Carruth002da5d2014-03-02 04:08:41 +000046 : Lower(std::move(V)), Upper(Lower + 1) {}
Chris Lattner113f2ae2002-09-01 23:53:36 +000047
Craig Topper37df0182017-04-13 00:20:31 +000048ConstantRange::ConstantRange(APInt L, APInt U)
Chandler Carruth002da5d2014-03-02 04:08:41 +000049 : Lower(std::move(L)), Upper(std::move(U)) {
Benjamin Kramercce97be2013-07-11 15:37:27 +000050 assert(Lower.getBitWidth() == Upper.getBitWidth() &&
Dan Gohmandc33ae22009-07-09 23:16:10 +000051 "ConstantRange with unequal bit widths");
Benjamin Kramercce97be2013-07-11 15:37:27 +000052 assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
Reid Spencere1f3f192007-02-28 17:36:23 +000053 "Lower == Upper, but they aren't min or max value!");
54}
55
Sanjoy Das7182d362015-03-18 00:41:24 +000056ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
57 const ConstantRange &CR) {
Nick Lewycky5154ee02010-09-28 18:18:36 +000058 if (CR.isEmptySet())
59 return CR;
60
Nick Lewyckydcfdce92009-07-11 06:15:39 +000061 uint32_t W = CR.getBitWidth();
62 switch (Pred) {
Sanjoy Das7182d362015-03-18 00:41:24 +000063 default:
64 llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000065 case CmpInst::ICMP_EQ:
66 return CR;
67 case CmpInst::ICMP_NE:
68 if (CR.isSingleElement())
69 return ConstantRange(CR.getUpper(), CR.getLower());
70 return ConstantRange(W);
71 case CmpInst::ICMP_ULT: {
72 APInt UMax(CR.getUnsignedMax());
73 if (UMax.isMinValue())
74 return ConstantRange(W, /* empty */ false);
Craig Topperb7920252017-04-29 06:40:47 +000075 return ConstantRange(APInt::getMinValue(W), std::move(UMax));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000076 }
77 case CmpInst::ICMP_SLT: {
78 APInt SMax(CR.getSignedMax());
79 if (SMax.isMinSignedValue())
80 return ConstantRange(W, /* empty */ false);
Craig Topperb7920252017-04-29 06:40:47 +000081 return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000082 }
83 case CmpInst::ICMP_ULE: {
84 APInt UMax(CR.getUnsignedMax());
85 if (UMax.isMaxValue())
Nick Lewyckydcfdce92009-07-11 06:15:39 +000086 return ConstantRange(W);
Craig Topperb7920252017-04-29 06:40:47 +000087 return ConstantRange(APInt::getMinValue(W), std::move(UMax) + 1);
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000088 }
89 case CmpInst::ICMP_SLE: {
90 APInt SMax(CR.getSignedMax());
91 if (SMax.isMaxSignedValue())
92 return ConstantRange(W);
Craig Topperb7920252017-04-29 06:40:47 +000093 return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax) + 1);
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000094 }
95 case CmpInst::ICMP_UGT: {
96 APInt UMin(CR.getUnsignedMin());
97 if (UMin.isMaxValue())
98 return ConstantRange(W, /* empty */ false);
Craig Topperb7920252017-04-29 06:40:47 +000099 return ConstantRange(std::move(UMin) + 1, APInt::getNullValue(W));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000100 }
101 case CmpInst::ICMP_SGT: {
102 APInt SMin(CR.getSignedMin());
103 if (SMin.isMaxSignedValue())
104 return ConstantRange(W, /* empty */ false);
Craig Topperb7920252017-04-29 06:40:47 +0000105 return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000106 }
107 case CmpInst::ICMP_UGE: {
108 APInt UMin(CR.getUnsignedMin());
109 if (UMin.isMinValue())
110 return ConstantRange(W);
Craig Topperb7920252017-04-29 06:40:47 +0000111 return ConstantRange(std::move(UMin), APInt::getNullValue(W));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000112 }
113 case CmpInst::ICMP_SGE: {
114 APInt SMin(CR.getSignedMin());
115 if (SMin.isMinSignedValue())
116 return ConstantRange(W);
Craig Topperb7920252017-04-29 06:40:47 +0000117 return ConstantRange(std::move(SMin), APInt::getSignedMinValue(W));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000118 }
Nick Lewyckydcfdce92009-07-11 06:15:39 +0000119 }
120}
121
Sanjoy Das7182d362015-03-18 00:41:24 +0000122ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
123 const ConstantRange &CR) {
124 // Follows from De-Morgan's laws:
125 //
126 // ~(~A union ~B) == A intersect B.
127 //
128 return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
129 .inverse();
130}
131
Balaram Makam569eaec2016-05-04 21:32:14 +0000132ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
133 const APInt &C) {
134 // Computes the exact range that is equal to both the constant ranges returned
135 // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
136 // when RHS is a singleton such as an APInt and so the assert is valid.
137 // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
138 // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
139 //
140 assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
141 return makeAllowedICmpRegion(Pred, C);
142}
143
Sanjoy Das590614c2016-05-19 03:53:06 +0000144bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
145 APInt &RHS) const {
146 bool Success = false;
147
148 if (isFullSet() || isEmptySet()) {
149 Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
150 RHS = APInt(getBitWidth(), 0);
151 Success = true;
Sanjoy Dasc7d32912016-10-02 20:59:05 +0000152 } else if (auto *OnlyElt = getSingleElement()) {
153 Pred = CmpInst::ICMP_EQ;
154 RHS = *OnlyElt;
155 Success = true;
156 } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
157 Pred = CmpInst::ICMP_NE;
158 RHS = *OnlyMissingElt;
159 Success = true;
Sanjoy Das590614c2016-05-19 03:53:06 +0000160 } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
161 Pred =
162 getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
163 RHS = getUpper();
164 Success = true;
165 } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
166 Pred =
167 getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
168 RHS = getLower();
169 Success = true;
170 }
171
172 assert((!Success || ConstantRange::makeExactICmpRegion(Pred, RHS) == *this) &&
173 "Bad result!");
174
175 return Success;
176}
177
Sanjoy Das5079f622016-02-22 16:13:02 +0000178ConstantRange
179ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
Sanjoy Dasf3867e62016-03-03 18:31:16 +0000180 const ConstantRange &Other,
181 unsigned NoWrapKind) {
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000182 using OBO = OverflowingBinaryOperator;
Sanjoy Das6ed05302015-10-22 03:12:57 +0000183
184 // Computes the intersection of CR0 and CR1. It is different from
185 // intersectWith in that the ConstantRange returned will only contain elements
186 // in both CR0 and CR1 (i.e. SubsetIntersect(X, Y) is a *subset*, proper or
187 // not, of both X and Y).
188 auto SubsetIntersect =
189 [](const ConstantRange &CR0, const ConstantRange &CR1) {
190 return CR0.inverse().unionWith(CR1.inverse()).inverse();
191 };
192
193 assert(BinOp >= Instruction::BinaryOpsBegin &&
194 BinOp < Instruction::BinaryOpsEnd && "Binary operators only!");
195
196 assert((NoWrapKind == OBO::NoSignedWrap ||
197 NoWrapKind == OBO::NoUnsignedWrap ||
198 NoWrapKind == (OBO::NoUnsignedWrap | OBO::NoSignedWrap)) &&
199 "NoWrapKind invalid!");
200
Sanjoy Dasf3867e62016-03-03 18:31:16 +0000201 unsigned BitWidth = Other.getBitWidth();
Joel Galensonc32b0fc2017-12-05 18:14:23 +0000202 ConstantRange Result(BitWidth);
203
204 switch (BinOp) {
205 default:
Sanjoy Das6ed05302015-10-22 03:12:57 +0000206 // Conservative answer: empty set
207 return ConstantRange(BitWidth, false);
208
Joel Galensonc32b0fc2017-12-05 18:14:23 +0000209 case Instruction::Add:
210 if (auto *C = Other.getSingleElement())
211 if (C->isNullValue())
212 // Full set: nothing signed / unsigned wraps when added to 0.
213 return ConstantRange(BitWidth);
214 if (NoWrapKind & OBO::NoUnsignedWrap)
215 Result =
216 SubsetIntersect(Result, ConstantRange(APInt::getNullValue(BitWidth),
217 -Other.getUnsignedMax()));
218 if (NoWrapKind & OBO::NoSignedWrap) {
219 const APInt &SignedMin = Other.getSignedMin();
220 const APInt &SignedMax = Other.getSignedMax();
221 if (SignedMax.isStrictlyPositive())
222 Result = SubsetIntersect(
223 Result,
224 ConstantRange(APInt::getSignedMinValue(BitWidth),
225 APInt::getSignedMinValue(BitWidth) - SignedMax));
226 if (SignedMin.isNegative())
227 Result = SubsetIntersect(
228 Result,
229 ConstantRange(APInt::getSignedMinValue(BitWidth) - SignedMin,
230 APInt::getSignedMinValue(BitWidth)));
231 }
232 return Result;
Sanjoy Das6ed05302015-10-22 03:12:57 +0000233
Joel Galensonc32b0fc2017-12-05 18:14:23 +0000234 case Instruction::Sub:
235 if (auto *C = Other.getSingleElement())
236 if (C->isNullValue())
237 // Full set: nothing signed / unsigned wraps when subtracting 0.
238 return ConstantRange(BitWidth);
239 if (NoWrapKind & OBO::NoUnsignedWrap)
240 Result =
241 SubsetIntersect(Result, ConstantRange(Other.getUnsignedMax(),
242 APInt::getMinValue(BitWidth)));
243 if (NoWrapKind & OBO::NoSignedWrap) {
244 const APInt &SignedMin = Other.getSignedMin();
245 const APInt &SignedMax = Other.getSignedMax();
246 if (SignedMax.isStrictlyPositive())
247 Result = SubsetIntersect(
248 Result,
249 ConstantRange(APInt::getSignedMinValue(BitWidth) + SignedMax,
250 APInt::getSignedMinValue(BitWidth)));
251 if (SignedMin.isNegative())
252 Result = SubsetIntersect(
253 Result,
254 ConstantRange(APInt::getSignedMinValue(BitWidth),
255 APInt::getSignedMinValue(BitWidth) + SignedMin));
256 }
257 return Result;
Sanjoy Das6ed05302015-10-22 03:12:57 +0000258 }
Sanjoy Das6ed05302015-10-22 03:12:57 +0000259}
260
Chris Lattner113f2ae2002-09-01 23:53:36 +0000261bool ConstantRange::isFullSet() const {
Zhou Sheng31787362007-04-26 16:42:07 +0000262 return Lower == Upper && Lower.isMaxValue();
Chris Lattner113f2ae2002-09-01 23:53:36 +0000263}
Misha Brukmanb1c93172005-04-21 23:48:37 +0000264
Chris Lattner113f2ae2002-09-01 23:53:36 +0000265bool ConstantRange::isEmptySet() const {
Zhou Sheng31787362007-04-26 16:42:07 +0000266 return Lower == Upper && Lower.isMinValue();
Chris Lattner113f2ae2002-09-01 23:53:36 +0000267}
268
Reid Spencer6a440332007-03-01 07:54:15 +0000269bool ConstantRange::isWrappedSet() const {
Reid Spencere1f3f192007-02-28 17:36:23 +0000270 return Lower.ugt(Upper);
Chris Lattner113f2ae2002-09-01 23:53:36 +0000271}
272
Nick Lewyckya35462d2010-09-06 23:52:49 +0000273bool ConstantRange::isSignWrappedSet() const {
274 return contains(APInt::getSignedMaxValue(getBitWidth())) &&
275 contains(APInt::getSignedMinValue(getBitWidth()));
276}
277
Reid Spencere1f3f192007-02-28 17:36:23 +0000278APInt ConstantRange::getSetSize() const {
Craig Topper8c5c6fe2017-04-29 17:59:41 +0000279 if (isFullSet())
280 return APInt::getOneBitSet(getBitWidth()+1, getBitWidth());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000281
Nuno Lopes216d5712012-07-17 15:43:59 +0000282 // This is also correct for wrapped sets.
Nuno Lopes99504c52012-07-16 18:08:12 +0000283 return (Upper - Lower).zext(getBitWidth()+1);
Chris Lattner113f2ae2002-09-01 23:53:36 +0000284}
285
Michael Zolotukhinc69955c2017-03-20 06:33:07 +0000286bool
Craig Topperd29549e2017-05-07 21:48:08 +0000287ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
Michael Zolotukhinc69955c2017-03-20 06:33:07 +0000288 assert(getBitWidth() == Other.getBitWidth());
289 if (isFullSet())
290 return false;
291 if (Other.isFullSet())
292 return true;
293 return (Upper - Lower).ult(Other.Upper - Other.Lower);
294}
295
Craig Topper7e3e7af2017-05-07 22:22:11 +0000296bool
297ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
298 assert(MaxSize && "MaxSize can't be 0.");
299 // If this a full set, we need special handling to avoid needing an extra bit
300 // to represent the size.
301 if (isFullSet())
302 return APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
303
304 return (Upper - Lower).ugt(MaxSize);
305}
306
Nick Lewyckye4559372007-03-10 15:54:12 +0000307APInt ConstantRange::getUnsignedMax() const {
308 if (isFullSet() || isWrappedSet())
309 return APInt::getMaxValue(getBitWidth());
Nick Lewycky228f5b42012-01-03 20:33:00 +0000310 return getUpper() - 1;
Nick Lewyckye4559372007-03-10 15:54:12 +0000311}
312
Nick Lewyckye4559372007-03-10 15:54:12 +0000313APInt ConstantRange::getUnsignedMin() const {
Craig Topper61729fd2017-05-09 05:01:29 +0000314 if (isFullSet() || (isWrappedSet() && !getUpper().isNullValue()))
Nick Lewyckye4559372007-03-10 15:54:12 +0000315 return APInt::getMinValue(getBitWidth());
Nick Lewycky228f5b42012-01-03 20:33:00 +0000316 return getLower();
Nick Lewyckye4559372007-03-10 15:54:12 +0000317}
318
Nick Lewyckye4559372007-03-10 15:54:12 +0000319APInt ConstantRange::getSignedMax() const {
Craig Topper61e684a2017-06-16 23:26:23 +0000320 if (isFullSet() || Lower.sgt(Upper))
Craig Topper88c64f32017-04-18 23:02:39 +0000321 return APInt::getSignedMaxValue(getBitWidth());
Nick Lewycky228f5b42012-01-03 20:33:00 +0000322 return getUpper() - 1;
Nick Lewyckye4559372007-03-10 15:54:12 +0000323}
324
Nick Lewyckye4559372007-03-10 15:54:12 +0000325APInt ConstantRange::getSignedMin() const {
Craig Topper61e684a2017-06-16 23:26:23 +0000326 if (isFullSet() || (Lower.sgt(Upper) && !getUpper().isMinSignedValue()))
Craig Topper88c64f32017-04-18 23:02:39 +0000327 return APInt::getSignedMinValue(getBitWidth());
Nick Lewycky228f5b42012-01-03 20:33:00 +0000328 return getLower();
Nick Lewyckye4559372007-03-10 15:54:12 +0000329}
330
Reid Spencer6a440332007-03-01 07:54:15 +0000331bool ConstantRange::contains(const APInt &V) const {
332 if (Lower == Upper)
333 return isFullSet();
Chris Lattner113f2ae2002-09-01 23:53:36 +0000334
Reid Spencer6a440332007-03-01 07:54:15 +0000335 if (!isWrappedSet())
336 return Lower.ule(V) && V.ult(Upper);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000337 return Lower.ule(V) || V.ult(Upper);
Chris Lattner55481f72004-03-30 00:20:08 +0000338}
339
Nick Lewyckydcfdce92009-07-11 06:15:39 +0000340bool ConstantRange::contains(const ConstantRange &Other) const {
Nick Lewyckyd385c222010-08-11 22:04:36 +0000341 if (isFullSet() || Other.isEmptySet()) return true;
342 if (isEmptySet() || Other.isFullSet()) return false;
Nick Lewyckydcfdce92009-07-11 06:15:39 +0000343
344 if (!isWrappedSet()) {
345 if (Other.isWrappedSet())
346 return false;
347
348 return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
349 }
350
351 if (!Other.isWrappedSet())
352 return Other.getUpper().ule(Upper) ||
353 Lower.ule(Other.getLower());
354
355 return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
356}
357
Reid Spencer3a7e9d82007-02-28 19:57:34 +0000358ConstantRange ConstantRange::subtract(const APInt &Val) const {
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000359 assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
Chris Lattner55481f72004-03-30 00:20:08 +0000360 // If the set is empty or full, don't modify the endpoints.
Reid Spencere1f3f192007-02-28 17:36:23 +0000361 if (Lower == Upper)
362 return *this;
Reid Spencere1f3f192007-02-28 17:36:23 +0000363 return ConstantRange(Lower - Val, Upper - Val);
Chris Lattner55481f72004-03-30 00:20:08 +0000364}
Chris Lattner113f2ae2002-09-01 23:53:36 +0000365
Nuno Lopes5020db22012-06-28 16:10:13 +0000366ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
367 return intersectWith(CR.inverse());
368}
369
Reid Spencer6a440332007-03-01 07:54:15 +0000370ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000371 assert(getBitWidth() == CR.getBitWidth() &&
372 "ConstantRange types don't agree!");
Nick Lewycky61b4a262007-07-14 02:51:34 +0000373
374 // Handle common cases.
375 if ( isEmptySet() || CR.isFullSet()) return *this;
376 if (CR.isEmptySet() || isFullSet()) return CR;
377
378 if (!isWrappedSet() && CR.isWrappedSet())
Nick Lewycky0d139032009-07-18 06:34:42 +0000379 return CR.intersectWith(*this);
Nick Lewycky61b4a262007-07-14 02:51:34 +0000380
381 if (!isWrappedSet() && !CR.isWrappedSet()) {
382 if (Lower.ult(CR.Lower)) {
383 if (Upper.ule(CR.Lower))
384 return ConstantRange(getBitWidth(), false);
385
386 if (Upper.ult(CR.Upper))
387 return ConstantRange(CR.Lower, Upper);
388
389 return CR;
Nick Lewycky61b4a262007-07-14 02:51:34 +0000390 }
Nick Lewycky228f5b42012-01-03 20:33:00 +0000391 if (Upper.ult(CR.Upper))
392 return *this;
393
394 if (Lower.ult(CR.Upper))
395 return ConstantRange(Lower, CR.Upper);
396
397 return ConstantRange(getBitWidth(), false);
Nick Lewycky61b4a262007-07-14 02:51:34 +0000398 }
399
400 if (isWrappedSet() && !CR.isWrappedSet()) {
401 if (CR.Lower.ult(Upper)) {
402 if (CR.Upper.ult(Upper))
403 return CR;
404
Nuno Lopes63afc082012-05-18 00:14:36 +0000405 if (CR.Upper.ule(Lower))
Nick Lewycky61b4a262007-07-14 02:51:34 +0000406 return ConstantRange(CR.Lower, Upper);
407
Craig Topperd29549e2017-05-07 21:48:08 +0000408 if (isSizeStrictlySmallerThan(CR))
Nick Lewycky61b4a262007-07-14 02:51:34 +0000409 return *this;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000410 return CR;
411 }
412 if (CR.Lower.ult(Lower)) {
Nick Lewycky61b4a262007-07-14 02:51:34 +0000413 if (CR.Upper.ule(Lower))
414 return ConstantRange(getBitWidth(), false);
415
416 return ConstantRange(Lower, CR.Upper);
417 }
418 return CR;
419 }
420
421 if (CR.Upper.ult(Upper)) {
422 if (CR.Lower.ult(Upper)) {
Craig Topperd29549e2017-05-07 21:48:08 +0000423 if (isSizeStrictlySmallerThan(CR))
Nick Lewycky61b4a262007-07-14 02:51:34 +0000424 return *this;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000425 return CR;
Nick Lewycky61b4a262007-07-14 02:51:34 +0000426 }
427
428 if (CR.Lower.ult(Lower))
429 return ConstantRange(Lower, CR.Upper);
430
431 return CR;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000432 }
Nuno Lopesebb0c942012-06-28 00:59:33 +0000433 if (CR.Upper.ule(Lower)) {
Nick Lewycky61b4a262007-07-14 02:51:34 +0000434 if (CR.Lower.ult(Lower))
435 return *this;
436
437 return ConstantRange(CR.Lower, Upper);
438 }
Craig Topperd29549e2017-05-07 21:48:08 +0000439 if (isSizeStrictlySmallerThan(CR))
Nick Lewycky61b4a262007-07-14 02:51:34 +0000440 return *this;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000441 return CR;
Nick Lewycky61b4a262007-07-14 02:51:34 +0000442}
443
Reid Spencer6a440332007-03-01 07:54:15 +0000444ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000445 assert(getBitWidth() == CR.getBitWidth() &&
446 "ConstantRange types don't agree!");
Chris Lattner113f2ae2002-09-01 23:53:36 +0000447
Nick Lewyckycf87f9e2007-03-02 03:33:05 +0000448 if ( isFullSet() || CR.isEmptySet()) return *this;
449 if (CR.isFullSet() || isEmptySet()) return CR;
Chris Lattner113f2ae2002-09-01 23:53:36 +0000450
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000451 if (!isWrappedSet() && CR.isWrappedSet()) return CR.unionWith(*this);
452
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000453 if (!isWrappedSet() && !CR.isWrappedSet()) {
Nick Lewycky567daf32009-07-19 03:44:35 +0000454 if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower)) {
455 // If the two ranges are disjoint, find the smaller gap and bridge it.
456 APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
457 if (d1.ult(d2))
458 return ConstantRange(Lower, CR.Upper);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000459 return ConstantRange(CR.Lower, Upper);
Nick Lewycky567daf32009-07-19 03:44:35 +0000460 }
461
Craig Topper8fb5a142017-04-29 07:24:13 +0000462 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
463 APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
Nick Lewycky567daf32009-07-19 03:44:35 +0000464
Craig Topper61729fd2017-05-09 05:01:29 +0000465 if (L.isNullValue() && U.isNullValue())
Nick Lewycky567daf32009-07-19 03:44:35 +0000466 return ConstantRange(getBitWidth());
467
Craig Topperb7920252017-04-29 06:40:47 +0000468 return ConstantRange(std::move(L), std::move(U));
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000469 }
470
Nick Lewycky567daf32009-07-19 03:44:35 +0000471 if (!CR.isWrappedSet()) {
472 // ------U L----- and ------U L----- : this
473 // L--U L--U : CR
474 if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000475 return *this;
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000476
Nick Lewycky567daf32009-07-19 03:44:35 +0000477 // ------U L----- : this
478 // L---------U : CR
479 if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000480 return ConstantRange(getBitWidth());
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000481
Nick Lewycky567daf32009-07-19 03:44:35 +0000482 // ----U L---- : this
483 // L---U : CR
484 // <d1> <d2>
485 if (Upper.ule(CR.Lower) && CR.Upper.ule(Lower)) {
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000486 APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
Nick Lewycky567daf32009-07-19 03:44:35 +0000487 if (d1.ult(d2))
488 return ConstantRange(Lower, CR.Upper);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000489 return ConstantRange(CR.Lower, Upper);
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000490 }
491
Nick Lewycky567daf32009-07-19 03:44:35 +0000492 // ----U L----- : this
493 // L----U : CR
494 if (Upper.ult(CR.Lower) && Lower.ult(CR.Upper))
495 return ConstantRange(CR.Lower, Upper);
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000496
Nick Lewycky567daf32009-07-19 03:44:35 +0000497 // ------U L---- : this
498 // L-----U : CR
Nick Lewycky228f5b42012-01-03 20:33:00 +0000499 assert(CR.Lower.ult(Upper) && CR.Upper.ult(Lower) &&
500 "ConstantRange::unionWith missed a case with one range wrapped");
501 return ConstantRange(Lower, CR.Upper);
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000502 }
503
Nick Lewycky567daf32009-07-19 03:44:35 +0000504 // ------U L---- and ------U L---- : this
505 // -U L----------- and ------------U L : CR
506 if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
507 return ConstantRange(getBitWidth());
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000508
Craig Topper8fb5a142017-04-29 07:24:13 +0000509 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
510 APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
Nick Lewyckycf87f9e2007-03-02 03:33:05 +0000511
Craig Topperb7920252017-04-29 06:40:47 +0000512 return ConstantRange(std::move(L), std::move(U));
Chris Lattner113f2ae2002-09-01 23:53:36 +0000513}
Chris Lattnere0bb9eb2002-09-02 00:18:22 +0000514
Philip Reames4d00af12016-12-01 20:08:47 +0000515ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
516 uint32_t ResultBitWidth) const {
517 switch (CastOp) {
518 default:
519 llvm_unreachable("unsupported cast type");
520 case Instruction::Trunc:
521 return truncate(ResultBitWidth);
522 case Instruction::SExt:
523 return signExtend(ResultBitWidth);
524 case Instruction::ZExt:
525 return zeroExtend(ResultBitWidth);
526 case Instruction::BitCast:
527 return *this;
528 case Instruction::FPToUI:
529 case Instruction::FPToSI:
530 if (getBitWidth() == ResultBitWidth)
531 return *this;
532 else
533 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
534 case Instruction::UIToFP: {
535 // TODO: use input range if available
536 auto BW = getBitWidth();
537 APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
538 APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
Craig Topperb7920252017-04-29 06:40:47 +0000539 return ConstantRange(std::move(Min), std::move(Max));
Philip Reames4d00af12016-12-01 20:08:47 +0000540 }
541 case Instruction::SIToFP: {
542 // TODO: use input range if available
543 auto BW = getBitWidth();
544 APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
545 APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
Craig Topperb7920252017-04-29 06:40:47 +0000546 return ConstantRange(std::move(SMin), std::move(SMax));
Philip Reames4d00af12016-12-01 20:08:47 +0000547 }
548 case Instruction::FPTrunc:
549 case Instruction::FPExt:
550 case Instruction::IntToPtr:
551 case Instruction::PtrToInt:
552 case Instruction::AddrSpaceCast:
553 // Conservatively return full set.
554 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
555 };
556}
557
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000558ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
Nick Lewyckya35462d2010-09-06 23:52:49 +0000559 if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
560
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000561 unsigned SrcTySize = getBitWidth();
Reid Spencere1f3f192007-02-28 17:36:23 +0000562 assert(SrcTySize < DstTySize && "Not a value extension");
Nuno Lopeseb9d2752012-07-23 20:33:29 +0000563 if (isFullSet() || isWrappedSet()) {
Nick Lewyckya35462d2010-09-06 23:52:49 +0000564 // Change into [0, 1 << src bit width)
Nuno Lopeseb9d2752012-07-23 20:33:29 +0000565 APInt LowerExt(DstTySize, 0);
566 if (!Upper) // special case: [X, 0) -- not really wrapping around
567 LowerExt = Lower.zext(DstTySize);
Craig Topperb7920252017-04-29 06:40:47 +0000568 return ConstantRange(std::move(LowerExt),
569 APInt::getOneBitSet(DstTySize, SrcTySize));
Nuno Lopeseb9d2752012-07-23 20:33:29 +0000570 }
Chris Lattner55481f72004-03-30 00:20:08 +0000571
Jay Foad583abbc2010-12-07 08:25:19 +0000572 return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
Chris Lattner55481f72004-03-30 00:20:08 +0000573}
574
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000575ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
Nick Lewyckya35462d2010-09-06 23:52:49 +0000576 if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
577
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000578 unsigned SrcTySize = getBitWidth();
579 assert(SrcTySize < DstTySize && "Not a value extension");
Nuno Lopes1112eca2013-10-30 15:36:50 +0000580
581 // special case: [X, INT_MIN) -- not really wrapping around
Nuno Lopes14d4b0c2013-10-31 19:53:53 +0000582 if (Upper.isMinSignedValue())
Nuno Lopes1112eca2013-10-30 15:36:50 +0000583 return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
584
Nick Lewyckya35462d2010-09-06 23:52:49 +0000585 if (isFullSet() || isSignWrappedSet()) {
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000586 return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
Nick Lewycky5edc4592009-07-13 04:17:23 +0000587 APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000588 }
589
Jay Foad583abbc2010-12-07 08:25:19 +0000590 return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000591}
592
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000593ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
Benjamin Kramer6709e052011-11-24 17:24:33 +0000594 assert(getBitWidth() > DstTySize && "Not a value truncation");
Nuno Lopesc14776d2012-07-19 16:27:45 +0000595 if (isEmptySet())
596 return ConstantRange(DstTySize, /*isFullSet=*/false);
597 if (isFullSet())
Nick Lewyckyd385c222010-08-11 22:04:36 +0000598 return ConstantRange(DstTySize, /*isFullSet=*/true);
Chris Lattner55481f72004-03-30 00:20:08 +0000599
Nuno Lopesc14776d2012-07-19 16:27:45 +0000600 APInt LowerDiv(Lower), UpperDiv(Upper);
601 ConstantRange Union(DstTySize, /*isFullSet=*/false);
602
603 // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
604 // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
605 // then we do the union with [MaxValue, Upper)
606 if (isWrappedSet()) {
Craig Topperf6e138d2017-06-05 20:48:05 +0000607 // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
608 // truncated range.
609 if (Upper.getActiveBits() > DstTySize ||
610 Upper.countTrailingOnes() == DstTySize)
Nuno Lopesc14776d2012-07-19 16:27:45 +0000611 return ConstantRange(DstTySize, /*isFullSet=*/true);
612
613 Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
Craig Topper86616532017-04-30 00:44:05 +0000614 UpperDiv.setAllBits();
Nuno Lopesc14776d2012-07-19 16:27:45 +0000615
616 // Union covers the MaxValue case, so return if the remaining range is just
Craig Topperf6e138d2017-06-05 20:48:05 +0000617 // MaxValue(DstTy).
Nuno Lopesc14776d2012-07-19 16:27:45 +0000618 if (LowerDiv == UpperDiv)
619 return Union;
620 }
621
622 // Chop off the most significant bits that are past the destination bitwidth.
Craig Topperf6e138d2017-06-05 20:48:05 +0000623 if (LowerDiv.getActiveBits() > DstTySize) {
624 // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
625 APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
626 LowerDiv -= Adjust;
627 UpperDiv -= Adjust;
Nuno Lopesc14776d2012-07-19 16:27:45 +0000628 }
629
Craig Topperf6e138d2017-06-05 20:48:05 +0000630 unsigned UpperDivWidth = UpperDiv.getActiveBits();
631 if (UpperDivWidth <= DstTySize)
Nuno Lopesc14776d2012-07-19 16:27:45 +0000632 return ConstantRange(LowerDiv.trunc(DstTySize),
633 UpperDiv.trunc(DstTySize)).unionWith(Union);
634
Nick Lewyckybfad0152016-06-06 01:51:23 +0000635 // The truncated value wraps around. Check if we can do better than fullset.
Craig Topperf6e138d2017-06-05 20:48:05 +0000636 if (UpperDivWidth == DstTySize + 1) {
637 // Clear the MSB so that UpperDiv wraps around.
638 UpperDiv.clearBit(DstTySize);
639 if (UpperDiv.ult(LowerDiv))
640 return ConstantRange(LowerDiv.trunc(DstTySize),
641 UpperDiv.trunc(DstTySize)).unionWith(Union);
642 }
Nuno Lopesc14776d2012-07-19 16:27:45 +0000643
644 return ConstantRange(DstTySize, /*isFullSet=*/true);
Chris Lattner55481f72004-03-30 00:20:08 +0000645}
646
Nuno Lopes640eb702009-11-09 15:36:28 +0000647ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
648 unsigned SrcTySize = getBitWidth();
649 if (SrcTySize > DstTySize)
650 return truncate(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000651 if (SrcTySize < DstTySize)
Nuno Lopes640eb702009-11-09 15:36:28 +0000652 return zeroExtend(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000653 return *this;
Nuno Lopes640eb702009-11-09 15:36:28 +0000654}
655
Nuno Lopes640eb702009-11-09 15:36:28 +0000656ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
657 unsigned SrcTySize = getBitWidth();
658 if (SrcTySize > DstTySize)
659 return truncate(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000660 if (SrcTySize < DstTySize)
Nuno Lopes640eb702009-11-09 15:36:28 +0000661 return signExtend(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000662 return *this;
Nuno Lopes640eb702009-11-09 15:36:28 +0000663}
664
Philip Reames4d00af12016-12-01 20:08:47 +0000665ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
666 const ConstantRange &Other) const {
667 assert(BinOp >= Instruction::BinaryOpsBegin &&
668 BinOp < Instruction::BinaryOpsEnd && "Binary operators only!");
669
670 switch (BinOp) {
671 case Instruction::Add:
672 return add(Other);
673 case Instruction::Sub:
674 return sub(Other);
675 case Instruction::Mul:
676 return multiply(Other);
677 case Instruction::UDiv:
678 return udiv(Other);
679 case Instruction::Shl:
680 return shl(Other);
681 case Instruction::LShr:
682 return lshr(Other);
683 case Instruction::And:
684 return binaryAnd(Other);
685 case Instruction::Or:
686 return binaryOr(Other);
687 // Note: floating point operations applied to abstract ranges are just
688 // ideal integer operations with a lossy representation
689 case Instruction::FAdd:
690 return add(Other);
691 case Instruction::FSub:
692 return sub(Other);
693 case Instruction::FMul:
694 return multiply(Other);
695 default:
696 // Conservatively return full set.
697 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
698 }
699}
700
Dan Gohman5035fbf2009-07-09 22:07:27 +0000701ConstantRange
702ConstantRange::add(const ConstantRange &Other) const {
703 if (isEmptySet() || Other.isEmptySet())
704 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nick Lewycky73b704d2009-07-13 02:49:08 +0000705 if (isFullSet() || Other.isFullSet())
706 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Dan Gohman5035fbf2009-07-09 22:07:27 +0000707
Dan Gohman5035fbf2009-07-09 22:07:27 +0000708 APInt NewLower = getLower() + Other.getLower();
709 APInt NewUpper = getUpper() + Other.getUpper() - 1;
710 if (NewLower == NewUpper)
711 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
712
Craig Topperb7920252017-04-29 06:40:47 +0000713 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
Craig Topperd29549e2017-05-07 21:48:08 +0000714 if (X.isSizeStrictlySmallerThan(*this) ||
715 X.isSizeStrictlySmallerThan(Other))
Dan Gohman5035fbf2009-07-09 22:07:27 +0000716 // We've wrapped, therefore, full set.
717 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Dan Gohman5035fbf2009-07-09 22:07:27 +0000718 return X;
Chris Lattnere0bb9eb2002-09-02 00:18:22 +0000719}
720
Artur Pilipenkoed841032016-10-19 14:44:23 +0000721ConstantRange ConstantRange::addWithNoSignedWrap(const APInt &Other) const {
722 // Calculate the subset of this range such that "X + Other" is
723 // guaranteed not to wrap (overflow) for all X in this subset.
724 // makeGuaranteedNoWrapRegion will produce an exact NSW range since we are
725 // passing a single element range.
726 auto NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(BinaryOperator::Add,
727 ConstantRange(Other),
728 OverflowingBinaryOperator::NoSignedWrap);
729 auto NSWConstrainedRange = intersectWith(NSWRange);
730
731 return NSWConstrainedRange.add(ConstantRange(Other));
732}
733
Dan Gohman5035fbf2009-07-09 22:07:27 +0000734ConstantRange
Nick Lewyckyd385c222010-08-11 22:04:36 +0000735ConstantRange::sub(const ConstantRange &Other) const {
736 if (isEmptySet() || Other.isEmptySet())
737 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
738 if (isFullSet() || Other.isFullSet())
739 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
740
Nick Lewycky5dc6b792011-06-22 21:13:46 +0000741 APInt NewLower = getLower() - Other.getUpper() + 1;
742 APInt NewUpper = getUpper() - Other.getLower();
Nick Lewyckyd385c222010-08-11 22:04:36 +0000743 if (NewLower == NewUpper)
744 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
745
Craig Topperb7920252017-04-29 06:40:47 +0000746 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
Craig Topperd29549e2017-05-07 21:48:08 +0000747 if (X.isSizeStrictlySmallerThan(*this) ||
748 X.isSizeStrictlySmallerThan(Other))
Nick Lewyckyd385c222010-08-11 22:04:36 +0000749 // We've wrapped, therefore, full set.
750 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Nick Lewyckyd385c222010-08-11 22:04:36 +0000751 return X;
752}
753
754ConstantRange
Dan Gohman5035fbf2009-07-09 22:07:27 +0000755ConstantRange::multiply(const ConstantRange &Other) const {
Dan Gohman3f8ed9e2010-01-26 15:56:18 +0000756 // TODO: If either operand is a single element and the multiply is known to
757 // be non-wrapping, round the result min and max value to the appropriate
758 // multiple of that element. If wrapping is possible, at least adjust the
759 // range according to the greatest power-of-two factor of the single element.
Dan Gohman5325efc2010-01-26 04:13:15 +0000760
Nick Lewycky2951c992009-07-12 02:19:05 +0000761 if (isEmptySet() || Other.isEmptySet())
762 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nuno Lopes986cc182012-07-16 20:47:16 +0000763
James Molloydcc78ec2015-03-06 15:50:47 +0000764 // Multiplication is signedness-independent. However different ranges can be
765 // obtained depending on how the input ranges are treated. These different
766 // ranges are all conservatively correct, but one might be better than the
767 // other. We calculate two ranges; one treating the inputs as unsigned
768 // and the other signed, then return the smallest of these ranges.
769
770 // Unsigned range first.
Nick Lewycky53023892009-07-13 03:27:41 +0000771 APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
772 APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
773 APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
774 APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
Nick Lewycky2951c992009-07-12 02:19:05 +0000775
Nick Lewycky53023892009-07-13 03:27:41 +0000776 ConstantRange Result_zext = ConstantRange(this_min * Other_min,
777 this_max * Other_max + 1);
James Molloydcc78ec2015-03-06 15:50:47 +0000778 ConstantRange UR = Result_zext.truncate(getBitWidth());
779
Pete Cooper34a7a942016-05-27 17:06:50 +0000780 // If the unsigned range doesn't wrap, and isn't negative then it's a range
781 // from one positive number to another which is as good as we can generate.
782 // In this case, skip the extra work of generating signed ranges which aren't
783 // going to be better than this range.
Craig Topperc51d0532017-05-10 20:01:48 +0000784 if (!UR.isWrappedSet() &&
785 (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
Pete Cooper34a7a942016-05-27 17:06:50 +0000786 return UR;
787
James Molloydcc78ec2015-03-06 15:50:47 +0000788 // Now the signed range. Because we could be dealing with negative numbers
789 // here, the lower bound is the smallest of the cartesian product of the
790 // lower and upper ranges; for example:
791 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
792 // Similarly for the upper bound, swapping min for max.
793
794 this_min = getSignedMin().sext(getBitWidth() * 2);
795 this_max = getSignedMax().sext(getBitWidth() * 2);
796 Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
797 Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
798
799 auto L = {this_min * Other_min, this_min * Other_max,
800 this_max * Other_min, this_max * Other_max};
801 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
802 ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
803 ConstantRange SR = Result_sext.truncate(getBitWidth());
804
Craig Topperd29549e2017-05-07 21:48:08 +0000805 return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
Dan Gohman5035fbf2009-07-09 22:07:27 +0000806}
807
808ConstantRange
809ConstantRange::smax(const ConstantRange &Other) const {
Dan Gohmandc33ae22009-07-09 23:16:10 +0000810 // X smax Y is: range(smax(X_smin, Y_smin),
811 // smax(X_smax, Y_smax))
812 if (isEmptySet() || Other.isEmptySet())
813 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Dan Gohmandc33ae22009-07-09 23:16:10 +0000814 APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
815 APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
816 if (NewU == NewL)
817 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000818 return ConstantRange(std::move(NewL), std::move(NewU));
Dan Gohman5035fbf2009-07-09 22:07:27 +0000819}
820
821ConstantRange
822ConstantRange::umax(const ConstantRange &Other) const {
823 // X umax Y is: range(umax(X_umin, Y_umin),
824 // umax(X_umax, Y_umax))
825 if (isEmptySet() || Other.isEmptySet())
826 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Dan Gohman5035fbf2009-07-09 22:07:27 +0000827 APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
828 APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
829 if (NewU == NewL)
830 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000831 return ConstantRange(std::move(NewL), std::move(NewU));
Dan Gohman5035fbf2009-07-09 22:07:27 +0000832}
833
834ConstantRange
Philip Reamesba313122016-02-26 22:08:18 +0000835ConstantRange::smin(const ConstantRange &Other) const {
836 // X smin Y is: range(smin(X_smin, Y_smin),
837 // smin(X_smax, Y_smax))
838 if (isEmptySet() || Other.isEmptySet())
839 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
840 APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
841 APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
842 if (NewU == NewL)
843 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000844 return ConstantRange(std::move(NewL), std::move(NewU));
Philip Reamesba313122016-02-26 22:08:18 +0000845}
846
847ConstantRange
848ConstantRange::umin(const ConstantRange &Other) const {
849 // X umin Y is: range(umin(X_umin, Y_umin),
850 // umin(X_umax, Y_umax))
851 if (isEmptySet() || Other.isEmptySet())
852 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
853 APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
854 APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
855 if (NewU == NewL)
856 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000857 return ConstantRange(std::move(NewL), std::move(NewU));
Philip Reamesba313122016-02-26 22:08:18 +0000858}
859
860ConstantRange
Nick Lewyckyf1b8cb32009-07-12 05:18:18 +0000861ConstantRange::udiv(const ConstantRange &RHS) const {
Craig Topper61729fd2017-05-09 05:01:29 +0000862 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
Nick Lewyckyf1b8cb32009-07-12 05:18:18 +0000863 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
864 if (RHS.isFullSet())
865 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
866
867 APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
868
869 APInt RHS_umin = RHS.getUnsignedMin();
Craig Topper61729fd2017-05-09 05:01:29 +0000870 if (RHS_umin.isNullValue()) {
Nick Lewyckyf1b8cb32009-07-12 05:18:18 +0000871 // We want the lowest value in RHS excluding zero. Usually that would be 1
872 // except for a range in the form of [X, 1) in which case it would be X.
873 if (RHS.getUpper() == 1)
874 RHS_umin = RHS.getLower();
875 else
Craig Topper86616532017-04-30 00:44:05 +0000876 RHS_umin = 1;
Nick Lewyckyf1b8cb32009-07-12 05:18:18 +0000877 }
878
879 APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
880
881 // If the LHS is Full and the RHS is a wrapped interval containing 1 then
882 // this could occur.
883 if (Lower == Upper)
884 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
885
Craig Topperb7920252017-04-29 06:40:47 +0000886 return ConstantRange(std::move(Lower), std::move(Upper));
Dan Gohman5035fbf2009-07-09 22:07:27 +0000887}
888
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000889ConstantRange
Nick Lewyckyad48e012010-09-07 05:39:02 +0000890ConstantRange::binaryAnd(const ConstantRange &Other) const {
891 if (isEmptySet() || Other.isEmptySet())
892 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
893
894 // TODO: replace this with something less conservative
895
896 APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
897 if (umin.isAllOnesValue())
898 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000899 return ConstantRange(APInt::getNullValue(getBitWidth()), std::move(umin) + 1);
Nick Lewyckyad48e012010-09-07 05:39:02 +0000900}
901
902ConstantRange
903ConstantRange::binaryOr(const ConstantRange &Other) const {
904 if (isEmptySet() || Other.isEmptySet())
905 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
906
907 // TODO: replace this with something less conservative
908
909 APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
Craig Toppere8dea1b2017-04-28 21:48:09 +0000910 if (umax.isNullValue())
Nick Lewyckyad48e012010-09-07 05:39:02 +0000911 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000912 return ConstantRange(std::move(umax), APInt::getNullValue(getBitWidth()));
Nick Lewyckyad48e012010-09-07 05:39:02 +0000913}
914
915ConstantRange
Nick Lewyckyd385c222010-08-11 22:04:36 +0000916ConstantRange::shl(const ConstantRange &Other) const {
917 if (isEmptySet() || Other.isEmptySet())
918 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000919
Craig Topperef028032017-05-09 07:04:04 +0000920 APInt max = getUnsignedMax();
921 APInt Other_umax = Other.getUnsignedMax();
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000922
Craig Topperef028032017-05-09 07:04:04 +0000923 // there's overflow!
924 if (Other_umax.uge(max.countLeadingZeros()))
925 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000926
927 // FIXME: implement the other tricky cases
Craig Topperef028032017-05-09 07:04:04 +0000928
929 APInt min = getUnsignedMin();
930 min <<= Other.getUnsignedMin();
931 max <<= Other_umax;
932
933 return ConstantRange(std::move(min), std::move(max) + 1);
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000934}
935
936ConstantRange
Nick Lewyckyd385c222010-08-11 22:04:36 +0000937ConstantRange::lshr(const ConstantRange &Other) const {
938 if (isEmptySet() || Other.isEmptySet())
939 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Craig Topper79b76662017-05-09 07:04:02 +0000940
941 APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
Nick Lewyckyd385c222010-08-11 22:04:36 +0000942 APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
Craig Topper79b76662017-05-09 07:04:02 +0000943 if (min == max)
Nick Lewyckyd385c222010-08-11 22:04:36 +0000944 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
945
Craig Topper79b76662017-05-09 07:04:02 +0000946 return ConstantRange(std::move(min), std::move(max));
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000947}
948
Owen Anderson1a9078b2010-08-07 05:47:46 +0000949ConstantRange ConstantRange::inverse() const {
Nick Lewycky228f5b42012-01-03 20:33:00 +0000950 if (isFullSet())
Nick Lewyckyd385c222010-08-11 22:04:36 +0000951 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000952 if (isEmptySet())
Nick Lewyckyd385c222010-08-11 22:04:36 +0000953 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Owen Anderson1a9078b2010-08-07 05:47:46 +0000954 return ConstantRange(Upper, Lower);
955}
956
Dan Gohmandc33ae22009-07-09 23:16:10 +0000957void ConstantRange::print(raw_ostream &OS) const {
Dan Gohman837ada72010-01-26 04:12:55 +0000958 if (isFullSet())
959 OS << "full-set";
960 else if (isEmptySet())
961 OS << "empty-set";
962 else
963 OS << "[" << Lower << "," << Upper << ")";
Dan Gohman5035fbf2009-07-09 22:07:27 +0000964}
965
Aaron Ballman615eb472017-10-15 14:32:27 +0000966#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +0000967LLVM_DUMP_METHOD void ConstantRange::dump() const {
David Greenede7b3532010-01-05 01:28:32 +0000968 print(dbgs());
Dan Gohman5035fbf2009-07-09 22:07:27 +0000969}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000970#endif
Peter Collingbourneecdd58f2016-10-21 19:59:26 +0000971
972ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
973 const unsigned NumRanges = Ranges.getNumOperands() / 2;
974 assert(NumRanges >= 1 && "Must have at least one range!");
975 assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
976
977 auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
978 auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
979
980 ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
981
982 for (unsigned i = 1; i < NumRanges; ++i) {
983 auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
984 auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
985
986 // Note: unionWith will potentially create a range that contains values not
987 // contained in any of the original N ranges.
988 CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
989 }
990
991 return CR;
992}