blob: 961fb0f7aef9937f0edb23534d47107c0d28e4d3 [file] [log] [blame]
Chris Lattner741c94c2009-11-11 00:22:30 +00001//===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interface for lazy computation of value constraint
11// information.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
Hal Finkel7e184492014-09-07 20:29:59 +000018#include "llvm/Analysis/AssumptionTracker.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000020#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000021#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000022#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
27#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000028#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000029#include "llvm/IR/ValueHandle.h"
Jiangning Liucd1d79e2014-09-22 02:23:05 +000030#include "llvm/Support/CommandLine.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000031#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Support/raw_ostream.h"
33#include "llvm/Target/TargetLibraryInfo.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000034#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000035#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000036using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000037using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000038
Chandler Carruthf1221bd2014-04-22 02:48:03 +000039#define DEBUG_TYPE "lazy-value-info"
40
Jiangning Liucd1d79e2014-09-22 02:23:05 +000041// Experimentally derived threshold for the number of basic blocks lowered for
42// lattice value overdefined.
43static cl::opt<unsigned>
44OverdefinedBBThreshold("lvi-overdefined-BB-threshold",
45 cl::init(1500), cl::Hidden,
46 cl::desc("Threshold of the number of basic blocks lowered for lattice value"
47 "'overdefined'."));
48
49// Experimentally derived threshold for additional lowering lattice values
50// overdefined per block.
51static cl::opt<unsigned>
52OverdefinedThreshold("lvi-overdefined-threshold", cl::init(10), cl::Hidden,
53 cl::desc("Threshold of lowering lattice value 'overdefined'."));
54
Chris Lattner741c94c2009-11-11 00:22:30 +000055char LazyValueInfo::ID = 0;
Chad Rosier43a33062011-12-02 01:26:24 +000056INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
57 "Lazy Value Information Analysis", false, true)
Hal Finkel7e184492014-09-07 20:29:59 +000058INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Chad Rosier43a33062011-12-02 01:26:24 +000059INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
60INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000061 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000062
63namespace llvm {
64 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
65}
66
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000067
68//===----------------------------------------------------------------------===//
69// LVILatticeVal
70//===----------------------------------------------------------------------===//
71
72/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
73/// value.
74///
75/// FIXME: This is basically just for bringup, this can be made a lot more rich
76/// in the future.
77///
78namespace {
79class LVILatticeVal {
80 enum LatticeValueTy {
Nick Lewycky11678bd2010-12-15 18:57:18 +000081 /// undefined - This Value has no known value yet.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000082 undefined,
Owen Anderson0f306a42010-08-05 22:59:19 +000083
Nick Lewycky11678bd2010-12-15 18:57:18 +000084 /// constant - This Value has a specific constant value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000085 constant,
Nick Lewycky11678bd2010-12-15 18:57:18 +000086 /// notconstant - This Value is known to not have the specified value.
Chris Lattner565ee2f2009-11-12 04:36:58 +000087 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000088
Nick Lewycky11678bd2010-12-15 18:57:18 +000089 /// constantrange - The Value falls within this range.
Owen Anderson0f306a42010-08-05 22:59:19 +000090 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000091
Nick Lewycky11678bd2010-12-15 18:57:18 +000092 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000093 /// it has a value.
94 overdefined
95 };
96
97 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000098 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000099 LatticeValueTy Tag;
100 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +0000101 ConstantRange Range;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000102
103public:
Craig Topper9f008862014-04-15 04:59:12 +0000104 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000105
Chris Lattner19019ea2009-11-11 22:48:44 +0000106 static LVILatticeVal get(Constant *C) {
107 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000108 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000109 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +0000110 return Res;
111 }
Chris Lattner565ee2f2009-11-12 04:36:58 +0000112 static LVILatticeVal getNot(Constant *C) {
113 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000114 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000115 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000116 return Res;
117 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000118 static LVILatticeVal getRange(ConstantRange CR) {
119 LVILatticeVal Res;
120 Res.markConstantRange(CR);
121 return Res;
122 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000123
Owen Anderson0f306a42010-08-05 22:59:19 +0000124 bool isUndefined() const { return Tag == undefined; }
125 bool isConstant() const { return Tag == constant; }
126 bool isNotConstant() const { return Tag == notconstant; }
127 bool isConstantRange() const { return Tag == constantrange; }
128 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000129
130 Constant *getConstant() const {
131 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000132 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000133 }
134
Chris Lattner565ee2f2009-11-12 04:36:58 +0000135 Constant *getNotConstant() const {
136 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000137 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000138 }
139
Owen Anderson0f306a42010-08-05 22:59:19 +0000140 ConstantRange getConstantRange() const {
141 assert(isConstantRange() &&
142 "Cannot get the constant-range of a non-constant-range!");
143 return Range;
144 }
145
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000146 /// markOverdefined - Return true if this is a change in status.
147 bool markOverdefined() {
148 if (isOverdefined())
149 return false;
Owen Andersonc3a14132010-08-05 22:10:46 +0000150 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000151 return true;
152 }
153
154 /// markConstant - Return true if this is a change in status.
155 bool markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000156 assert(V && "Marking constant with NULL");
157 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
158 return markConstantRange(ConstantRange(CI->getValue()));
159 if (isa<UndefValue>(V))
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000160 return false;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000161
162 assert((!isConstant() || getConstant() == V) &&
163 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000164 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000165 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000166 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000167 return true;
168 }
169
Chris Lattner565ee2f2009-11-12 04:36:58 +0000170 /// markNotConstant - Return true if this is a change in status.
171 bool markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000172 assert(V && "Marking constant with NULL");
Nick Lewycky11678bd2010-12-15 18:57:18 +0000173 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
174 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
175 if (isa<UndefValue>(V))
176 return false;
177
178 assert((!isConstant() || getConstant() != V) &&
179 "Marking constant !constant with same value");
180 assert((!isNotConstant() || getNotConstant() == V) &&
181 "Marking !constant with different value");
182 assert(isUndefined() || isConstant());
183 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000184 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000185 return true;
186 }
187
Owen Anderson0f306a42010-08-05 22:59:19 +0000188 /// markConstantRange - Return true if this is a change in status.
189 bool markConstantRange(const ConstantRange NewR) {
190 if (isConstantRange()) {
191 if (NewR.isEmptySet())
192 return markOverdefined();
193
Nuno Lopese6e04902012-06-28 01:16:18 +0000194 bool changed = Range != NewR;
Owen Anderson0f306a42010-08-05 22:59:19 +0000195 Range = NewR;
196 return changed;
197 }
198
199 assert(isUndefined());
200 if (NewR.isEmptySet())
201 return markOverdefined();
Owen Anderson0f306a42010-08-05 22:59:19 +0000202
203 Tag = constantrange;
204 Range = NewR;
205 return true;
206 }
207
Chris Lattner19019ea2009-11-11 22:48:44 +0000208 /// mergeIn - Merge the specified lattice value into this one, updating this
209 /// one and returning true if anything changed.
210 bool mergeIn(const LVILatticeVal &RHS) {
211 if (RHS.isUndefined() || isOverdefined()) return false;
212 if (RHS.isOverdefined()) return markOverdefined();
213
Nick Lewycky11678bd2010-12-15 18:57:18 +0000214 if (isUndefined()) {
215 Tag = RHS.Tag;
216 Val = RHS.Val;
217 Range = RHS.Range;
218 return true;
Chris Lattner22db4b52009-11-12 04:57:13 +0000219 }
220
Nick Lewycky11678bd2010-12-15 18:57:18 +0000221 if (isConstant()) {
222 if (RHS.isConstant()) {
223 if (Val == RHS.Val)
224 return false;
225 return markOverdefined();
226 }
227
228 if (RHS.isNotConstant()) {
229 if (Val == RHS.Val)
230 return markOverdefined();
231
232 // Unless we can prove that the two Constants are different, we must
233 // move to overdefined.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000234 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
Nick Lewycky11678bd2010-12-15 18:57:18 +0000235 if (ConstantInt *Res = dyn_cast<ConstantInt>(
236 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
237 getConstant(),
238 RHS.getNotConstant())))
239 if (Res->isOne())
240 return markNotConstant(RHS.getNotConstant());
241
242 return markOverdefined();
243 }
244
245 // RHS is a ConstantRange, LHS is a non-integer Constant.
246
247 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
248 // a function. The correct result is to pick up RHS.
249
Chris Lattner19019ea2009-11-11 22:48:44 +0000250 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000251 }
252
253 if (isNotConstant()) {
254 if (RHS.isConstant()) {
255 if (Val == RHS.Val)
256 return markOverdefined();
257
258 // Unless we can prove that the two Constants are different, we must
259 // move to overdefined.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000260 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
Nick Lewycky11678bd2010-12-15 18:57:18 +0000261 if (ConstantInt *Res = dyn_cast<ConstantInt>(
262 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
263 getNotConstant(),
264 RHS.getConstant())))
265 if (Res->isOne())
266 return false;
267
268 return markOverdefined();
269 }
270
271 if (RHS.isNotConstant()) {
272 if (Val == RHS.Val)
273 return false;
274 return markOverdefined();
275 }
276
277 return markOverdefined();
278 }
279
280 assert(isConstantRange() && "New LVILattice type?");
281 if (!RHS.isConstantRange())
282 return markOverdefined();
283
284 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
285 if (NewR.isFullSet())
286 return markOverdefined();
287 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000288 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000289};
290
291} // end anonymous namespace.
292
Chris Lattner19019ea2009-11-11 22:48:44 +0000293namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000294raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
295 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000296raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
297 if (Val.isUndefined())
298 return OS << "undefined";
299 if (Val.isOverdefined())
300 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000301
302 if (Val.isNotConstant())
303 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson8afac042010-08-09 20:50:46 +0000304 else if (Val.isConstantRange())
305 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
306 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000307 return OS << "constant<" << *Val.getConstant() << '>';
308}
309}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000310
311//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000312// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000313//===----------------------------------------------------------------------===//
314
Chris Lattneraf025d32009-11-15 19:59:49 +0000315namespace {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000316 /// LVIValueHandle - A callback value handle updates the cache when
Owen Anderson118ac802011-01-05 21:15:29 +0000317 /// values are erased.
318 class LazyValueInfoCache;
319 struct LVIValueHandle : public CallbackVH {
320 LazyValueInfoCache *Parent;
321
322 LVIValueHandle(Value *V, LazyValueInfoCache *P)
323 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000324
325 void deleted() override;
326 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000327 deleted();
328 }
329 };
330}
331
Owen Anderson118ac802011-01-05 21:15:29 +0000332namespace {
Chris Lattneraf025d32009-11-15 19:59:49 +0000333 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
334 /// maintains information about queries across the clients' queries.
335 class LazyValueInfoCache {
Chris Lattneraf025d32009-11-15 19:59:49 +0000336 /// ValueCacheEntryTy - This is all of the cached block information for
337 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
338 /// entries, allowing us to do a lookup with a binary search.
Bill Wendling4ec081a2012-01-11 23:43:34 +0000339 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattneraf025d32009-11-15 19:59:49 +0000340
Owen Anderson6f060af2011-01-05 23:26:22 +0000341 /// ValueCache - This is all of the cached information for all values,
342 /// mapped from Value* to key information.
Bill Wendling58c75692012-01-12 01:41:03 +0000343 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Anderson6f060af2011-01-05 23:26:22 +0000344
345 /// OverDefinedCache - This tracks, on a per-block basis, the set of
346 /// values that are over-defined at the end of that block. This is required
347 /// for cache updating.
348 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
349 DenseSet<OverDefinedPairTy> OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000350
351 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
352 /// don't spend time removing unused blocks from our caches.
353 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
354
Owen Anderson6f060af2011-01-05 23:26:22 +0000355 /// BlockValueStack - This stack holds the state of the value solver
356 /// during a query. It basically emulates the callstack of the naive
357 /// recursive value lookup process.
358 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
Hal Finkel7e184492014-09-07 20:29:59 +0000359
360 /// A pointer to the cache of @llvm.assume calls.
361 AssumptionTracker *AT;
362 /// An optional DL pointer.
363 const DataLayout *DL;
364 /// An optional DT pointer.
365 DominatorTree *DT;
Jiangning Liucd1d79e2014-09-22 02:23:05 +0000366 /// A counter to record how many times Overdefined has been tried to be
367 /// lowered.
368 DenseMap<BasicBlock *, unsigned> LoweringOverdefinedTimes;
Owen Anderson6f060af2011-01-05 23:26:22 +0000369
Owen Anderson118ac802011-01-05 21:15:29 +0000370 friend struct LVIValueHandle;
Owen Andersond83f98a2010-12-20 19:33:41 +0000371
372 /// OverDefinedCacheUpdater - A helper object that ensures that the
373 /// OverDefinedCache is updated whenever solveBlockValue returns.
374 struct OverDefinedCacheUpdater {
375 LazyValueInfoCache *Parent;
376 Value *Val;
377 BasicBlock *BB;
378 LVILatticeVal &BBLV;
379
380 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
381 LazyValueInfoCache *P)
382 : Parent(P), Val(V), BB(B), BBLV(LV) { }
383
384 bool markResult(bool changed) {
385 if (changed && BBLV.isOverdefined())
386 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
387 return changed;
388 }
389 };
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000390
Owen Anderson6f060af2011-01-05 23:26:22 +0000391
Owen Andersonc1561b82010-07-30 23:59:40 +0000392
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000393 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000394 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
Hal Finkel7e184492014-09-07 20:29:59 +0000395 LVILatticeVal &Result,
396 Instruction *CxtI = nullptr);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000397 bool hasBlockValue(Value *Val, BasicBlock *BB);
398
399 // These methods process one work item and may add more. A false value
400 // returned means that the work item was not completely processed and must
401 // be revisited after going through the new items.
402 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000403 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
404 Value *Val, BasicBlock *BB);
405 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
406 PHINode *PN, BasicBlock *BB);
407 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
408 Instruction *BBI, BasicBlock *BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000409 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
410 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000411
412 void solve();
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000413
Nick Lewycky11678bd2010-12-15 18:57:18 +0000414 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000415 return ValueCache[LVIValueHandle(V, this)];
416 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000417
Chris Lattneraf025d32009-11-15 19:59:49 +0000418 public:
Chris Lattneraf025d32009-11-15 19:59:49 +0000419 /// getValueInBlock - This is the query interface to determine the lattice
420 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000421 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
422 Instruction *CxtI = nullptr);
423
424 /// getValueAt - This is the query interface to determine the lattice
425 /// value for the specified Value* at the specified instruction (generally
426 /// from an assume intrinsic).
427 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000428
429 /// getValueOnEdge - This is the query interface to determine the lattice
430 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000431 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
432 Instruction *CxtI = nullptr);
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000433
434 /// threadEdge - This is the update interface to inform the cache that an
435 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
436 /// NewSucc.
437 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson208636f2010-08-18 18:39:01 +0000438
439 /// eraseBlock - This is part of the update interface to inform the cache
440 /// that a block has been deleted.
441 void eraseBlock(BasicBlock *BB);
442
443 /// clear - Empty the cache.
444 void clear() {
Benjamin Kramerbbf3c602011-12-03 15:19:55 +0000445 SeenBlocks.clear();
Owen Anderson208636f2010-08-18 18:39:01 +0000446 ValueCache.clear();
447 OverDefinedCache.clear();
448 }
Hal Finkel7e184492014-09-07 20:29:59 +0000449
450 LazyValueInfoCache(AssumptionTracker *AT,
451 const DataLayout *DL = nullptr,
452 DominatorTree *DT = nullptr) : AT(AT), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000453 };
454} // end anonymous namespace
455
Owen Anderson118ac802011-01-05 21:15:29 +0000456void LVIValueHandle::deleted() {
457 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
458
459 SmallVector<OverDefinedPairTy, 4> ToErase;
460 for (DenseSet<OverDefinedPairTy>::iterator
Owen Andersonc1561b82010-07-30 23:59:40 +0000461 I = Parent->OverDefinedCache.begin(),
462 E = Parent->OverDefinedCache.end();
Owen Anderson118ac802011-01-05 21:15:29 +0000463 I != E; ++I) {
464 if (I->second == getValPtr())
465 ToErase.push_back(*I);
Owen Andersonc1561b82010-07-30 23:59:40 +0000466 }
Craig Topperaf0dea12013-07-04 01:31:24 +0000467
468 for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(),
Owen Anderson118ac802011-01-05 21:15:29 +0000469 E = ToErase.end(); I != E; ++I)
470 Parent->OverDefinedCache.erase(*I);
471
Owen Anderson7b974a42010-08-11 22:36:04 +0000472 // This erasure deallocates *this, so it MUST happen after we're done
473 // using any and all members of *this.
474 Parent->ValueCache.erase(*this);
Owen Andersonc1561b82010-07-30 23:59:40 +0000475}
476
Owen Anderson208636f2010-08-18 18:39:01 +0000477void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramer36647082011-12-03 15:16:45 +0000478 // Shortcut if we have never seen this block.
479 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
480 if (I == SeenBlocks.end())
481 return;
482 SeenBlocks.erase(I);
483
Owen Anderson118ac802011-01-05 21:15:29 +0000484 SmallVector<OverDefinedPairTy, 4> ToErase;
485 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
486 E = OverDefinedCache.end(); I != E; ++I) {
487 if (I->first == BB)
488 ToErase.push_back(*I);
Owen Anderson208636f2010-08-18 18:39:01 +0000489 }
Craig Topperaf0dea12013-07-04 01:31:24 +0000490
491 for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(),
Owen Anderson118ac802011-01-05 21:15:29 +0000492 E = ToErase.end(); I != E; ++I)
493 OverDefinedCache.erase(*I);
Owen Anderson208636f2010-08-18 18:39:01 +0000494
Bill Wendling58c75692012-01-12 01:41:03 +0000495 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson208636f2010-08-18 18:39:01 +0000496 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
497 I->second.erase(BB);
498}
Owen Andersonc1561b82010-07-30 23:59:40 +0000499
Nick Lewycky55a700b2010-12-18 01:00:40 +0000500void LazyValueInfoCache::solve() {
Jiangning Liucd1d79e2014-09-22 02:23:05 +0000501 // Reset the counter of lowering overdefined value.
502 LoweringOverdefinedTimes.clear();
503
Owen Anderson6f060af2011-01-05 23:26:22 +0000504 while (!BlockValueStack.empty()) {
505 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Nuno Lopese6e04902012-06-28 01:16:18 +0000506 if (solveBlockValue(e.second, e.first)) {
507 assert(BlockValueStack.top() == e);
Owen Anderson6f060af2011-01-05 23:26:22 +0000508 BlockValueStack.pop();
Nuno Lopese6e04902012-06-28 01:16:18 +0000509 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000510 }
511}
512
513bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
514 // If already a constant, there is nothing to compute.
515 if (isa<Constant>(Val))
516 return true;
517
Owen Anderson118ac802011-01-05 21:15:29 +0000518 LVIValueHandle ValHandle(Val, this);
Benjamin Kramerf29db272012-08-22 15:37:57 +0000519 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
520 ValueCache.find(ValHandle);
521 if (I == ValueCache.end()) return false;
522 return I->second.count(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000523}
524
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000525LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000526 // If already a constant, there is nothing to compute.
527 if (Constant *VC = dyn_cast<Constant>(Val))
528 return LVILatticeVal::get(VC);
529
Benjamin Kramer36647082011-12-03 15:16:45 +0000530 SeenBlocks.insert(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000531 return lookup(Val)[BB];
532}
533
534bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
535 if (isa<Constant>(Val))
536 return true;
537
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000538 ValueCacheEntryTy &Cache = lookup(Val);
Benjamin Kramer36647082011-12-03 15:16:45 +0000539 SeenBlocks.insert(BB);
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000540 LVILatticeVal &BBLV = Cache[BB];
Owen Andersond83f98a2010-12-20 19:33:41 +0000541
542 // OverDefinedCacheUpdater is a helper object that will update
543 // the OverDefinedCache for us when this method exits. Make sure to
544 // call markResult on it as we exist, passing a bool to indicate if the
545 // cache needs updating, i.e. if we have solve a new value or not.
546 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000547
Jiangning Liu40b04fd2014-08-11 05:02:04 +0000548 // Once this BB is encountered, Val's value for this BB will not be Undefined
549 // any longer. When we encounter this BB again, if Val's value is Overdefined,
550 // we need to compute its value again.
551 //
552 // For example, considering this control flow,
553 // BB1->BB2, BB1->BB3, BB2->BB3, BB2->BB4
554 //
555 // Suppose we have "icmp slt %v, 0" in BB1, and "icmp sgt %v, 0" in BB3. At
556 // the very beginning, when analyzing edge BB2->BB3, we don't know %v's value
557 // in BB2, and the data flow algorithm tries to compute BB2's predecessors, so
558 // then we know %v has negative value on edge BB1->BB2. And then we return to
559 // check BB2 again, and at this moment BB2 has Overdefined value for %v in
560 // BB2. So we should have to follow data flow propagation algorithm to get the
561 // value on edge BB1->BB2 propagated to BB2, and finally %v on BB2 has a
562 // constant range describing a negative value.
Jiangning Liucd1d79e2014-09-22 02:23:05 +0000563 //
564 // In the mean time, limit the number of additional lowering lattice value to
565 // avoid unjustified memory grows.
Jiangning Liu40b04fd2014-08-11 05:02:04 +0000566
Jiangning Liucd1d79e2014-09-22 02:23:05 +0000567 if (LoweringOverdefinedTimes.count(BB) == 0)
568 LoweringOverdefinedTimes.insert(std::make_pair(BB, 0));
569 if ((!BBLV.isUndefined() && !BBLV.isOverdefined()) ||
570 (BBLV.isOverdefined() &&
571 (LoweringOverdefinedTimes[BB] > OverdefinedThreshold ||
572 LoweringOverdefinedTimes.size() > OverdefinedBBThreshold))) {
David Greene37e98092009-12-23 20:43:58 +0000573 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Owen Andersond83f98a2010-12-20 19:33:41 +0000574
575 // Since we're reusing a cached value here, we don't need to update the
576 // OverDefinedCahce. The cache will have been properly updated
577 // whenever the cached value was inserted.
578 ODCacheUpdater.markResult(false);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000579 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000580 }
581
Chris Lattneraf025d32009-11-15 19:59:49 +0000582 // Otherwise, this is the first time we're seeing this block. Reset the
583 // lattice value to overdefined, so that cycles will terminate and be
584 // conservatively correct.
585 BBLV.markOverdefined();
Jiangning Liucd1d79e2014-09-22 02:23:05 +0000586 ++LoweringOverdefinedTimes[BB];
Chris Lattneraf025d32009-11-15 19:59:49 +0000587
Chris Lattneraf025d32009-11-15 19:59:49 +0000588 Instruction *BBI = dyn_cast<Instruction>(Val);
Craig Topper9f008862014-04-15 04:59:12 +0000589 if (!BBI || BBI->getParent() != BB) {
Owen Andersond83f98a2010-12-20 19:33:41 +0000590 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
Chris Lattneraf025d32009-11-15 19:59:49 +0000591 }
Chris Lattner2c708562009-11-15 20:00:52 +0000592
Nick Lewycky55a700b2010-12-18 01:00:40 +0000593 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Andersond83f98a2010-12-20 19:33:41 +0000594 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000595 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000596
Nick Lewycky367f98f2011-01-15 09:16:12 +0000597 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
598 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
599 return ODCacheUpdater.markResult(true);
600 }
601
Owen Anderson80d19f02010-08-18 21:11:37 +0000602 // We can only analyze the definitions of certain classes of instructions
603 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattneraf025d32009-11-15 19:59:49 +0000604 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000605 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
606 !BBI->getType()->isIntegerTy()) {
607 DEBUG(dbgs() << " compute BB '" << BB->getName()
608 << "' - overdefined because inst def found.\n");
Owen Anderson64c2c572010-12-20 18:18:16 +0000609 BBLV.markOverdefined();
Owen Andersond83f98a2010-12-20 19:33:41 +0000610 return ODCacheUpdater.markResult(true);
Owen Anderson80d19f02010-08-18 21:11:37 +0000611 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000612
Owen Anderson80d19f02010-08-18 21:11:37 +0000613 // FIXME: We're currently limited to binops with a constant RHS. This should
614 // be improved.
615 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
616 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
617 DEBUG(dbgs() << " compute BB '" << BB->getName()
618 << "' - overdefined because inst def found.\n");
619
Owen Anderson64c2c572010-12-20 18:18:16 +0000620 BBLV.markOverdefined();
Owen Andersond83f98a2010-12-20 19:33:41 +0000621 return ODCacheUpdater.markResult(true);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000622 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000623
Owen Andersond83f98a2010-12-20 19:33:41 +0000624 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000625}
626
627static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
628 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
629 return L->getPointerAddressSpace() == 0 &&
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000630 GetUnderlyingObject(L->getPointerOperand()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000631 }
632 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
633 return S->getPointerAddressSpace() == 0 &&
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000634 GetUnderlyingObject(S->getPointerOperand()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000635 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000636 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
637 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000638
639 // FIXME: check whether it has a valuerange that excludes zero?
640 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
641 if (!Len || Len->isZero()) return false;
642
Eli Friedman7a5fc692011-05-31 20:40:16 +0000643 if (MI->getDestAddressSpace() == 0)
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000644 if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000645 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000646 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000647 if (MTI->getSourceAddressSpace() == 0)
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000648 if (GetUnderlyingObject(MTI->getRawSource()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000649 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000650 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000651 return false;
652}
653
Owen Anderson64c2c572010-12-20 18:18:16 +0000654bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
655 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000656 LVILatticeVal Result; // Start Undefined.
657
658 // If this is a pointer, and there's a load from that pointer in this BB,
659 // then we know that the pointer can't be NULL.
660 bool NotNull = false;
661 if (Val->getType()->isPointerTy()) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000662 if (isKnownNonNull(Val)) {
Nick Lewycky367f98f2011-01-15 09:16:12 +0000663 NotNull = true;
664 } else {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000665 Value *UnderlyingVal = GetUnderlyingObject(Val);
666 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
667 // inside InstructionDereferencesPointer either.
Craig Topper9f008862014-04-15 04:59:12 +0000668 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000669 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
670 BI != BE; ++BI) {
671 if (InstructionDereferencesPointer(BI, UnderlyingVal)) {
672 NotNull = true;
673 break;
674 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000675 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000676 }
677 }
678 }
679
680 // If this is the entry block, we must be asking about an argument. The
681 // value is overdefined.
682 if (BB == &BB->getParent()->getEntryBlock()) {
683 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
684 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000685 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000686 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
687 } else {
688 Result.markOverdefined();
689 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000690 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000691 return true;
692 }
693
694 // Loop over all of our predecessors, merging what we know from them into
695 // result.
696 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000697 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000698 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000699 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000700 if (EdgesMissing)
701 continue;
702
703 Result.mergeIn(EdgeResult);
704
705 // If we hit overdefined, exit early. The BlockVals entry is already set
706 // to overdefined.
707 if (Result.isOverdefined()) {
708 DEBUG(dbgs() << " compute BB '" << BB->getName()
709 << "' - overdefined because of pred.\n");
710 // If we previously determined that this is a pointer that can't be null
711 // then return that rather than giving up entirely.
712 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000713 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000714 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
715 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000716
717 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000718 return true;
719 }
720 }
721 if (EdgesMissing)
722 return false;
723
724 // Return the merged value, which is more precise than 'overdefined'.
725 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000726 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000727 return true;
728}
729
Owen Anderson64c2c572010-12-20 18:18:16 +0000730bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
731 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000732 LVILatticeVal Result; // Start Undefined.
733
734 // Loop over all of our predecessors, merging what we know from them into
735 // result.
736 bool EdgesMissing = false;
737 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
738 BasicBlock *PhiBB = PN->getIncomingBlock(i);
739 Value *PhiVal = PN->getIncomingValue(i);
740 LVILatticeVal EdgeResult;
Hal Finkel7e184492014-09-07 20:29:59 +0000741 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000742 if (EdgesMissing)
743 continue;
744
745 Result.mergeIn(EdgeResult);
746
747 // If we hit overdefined, exit early. The BlockVals entry is already set
748 // to overdefined.
749 if (Result.isOverdefined()) {
750 DEBUG(dbgs() << " compute BB '" << BB->getName()
751 << "' - overdefined because of pred.\n");
Owen Anderson64c2c572010-12-20 18:18:16 +0000752
753 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000754 return true;
755 }
756 }
757 if (EdgesMissing)
758 return false;
759
760 // Return the merged value, which is more precise than 'overdefined'.
761 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000762 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000763 return true;
764}
765
Hal Finkel7e184492014-09-07 20:29:59 +0000766static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
767 LVILatticeVal &Result,
768 bool isTrueDest = true);
769
770// If we can determine a constant range for the value Val at the context
771// provided by the instruction BBI, then merge it into BBLV. If we did find a
772// constant range, return true.
773void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(
774 Value *Val, LVILatticeVal &BBLV, Instruction *BBI) {
775 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
776 if (!BBI)
777 return;
778
779 for (auto &I : AT->assumptions(BBI->getParent()->getParent())) {
780 if (!isValidAssumeForContext(I, BBI, DL, DT))
781 continue;
782
783 Value *C = I->getArgOperand(0);
784 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
785 LVILatticeVal Result;
786 if (getValueFromFromCondition(Val, ICI, Result)) {
787 if (BBLV.isOverdefined())
788 BBLV = Result;
789 else
790 BBLV.mergeIn(Result);
791 }
792 }
793 }
794}
795
Owen Anderson64c2c572010-12-20 18:18:16 +0000796bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
797 Instruction *BBI,
Nick Lewycky55a700b2010-12-18 01:00:40 +0000798 BasicBlock *BB) {
Owen Anderson80d19f02010-08-18 21:11:37 +0000799 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000800 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Owen Anderson6f060af2011-01-05 23:26:22 +0000801 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000802 return false;
803 }
804
Nick Lewycky55a700b2010-12-18 01:00:40 +0000805 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000806 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
Owen Anderson80d19f02010-08-18 21:11:37 +0000807 if (!LHSVal.isConstantRange()) {
Owen Anderson64c2c572010-12-20 18:18:16 +0000808 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000809 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000810 }
811
Owen Anderson80d19f02010-08-18 21:11:37 +0000812 ConstantRange LHSRange = LHSVal.getConstantRange();
813 ConstantRange RHSRange(1);
Chris Lattner229907c2011-07-18 04:54:35 +0000814 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Anderson80d19f02010-08-18 21:11:37 +0000815 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000816 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
817 RHSRange = ConstantRange(RHS->getValue());
818 } else {
Owen Anderson64c2c572010-12-20 18:18:16 +0000819 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000820 return true;
Owen Andersonc62f7042010-08-24 07:55:44 +0000821 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000822 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000823
Owen Anderson80d19f02010-08-18 21:11:37 +0000824 // NOTE: We're currently limited by the set of operations that ConstantRange
825 // can evaluate symbolically. Enhancing that set will allows us to analyze
826 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +0000827 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000828 switch (BBI->getOpcode()) {
829 case Instruction::Add:
830 Result.markConstantRange(LHSRange.add(RHSRange));
831 break;
832 case Instruction::Sub:
833 Result.markConstantRange(LHSRange.sub(RHSRange));
834 break;
835 case Instruction::Mul:
836 Result.markConstantRange(LHSRange.multiply(RHSRange));
837 break;
838 case Instruction::UDiv:
839 Result.markConstantRange(LHSRange.udiv(RHSRange));
840 break;
841 case Instruction::Shl:
842 Result.markConstantRange(LHSRange.shl(RHSRange));
843 break;
844 case Instruction::LShr:
845 Result.markConstantRange(LHSRange.lshr(RHSRange));
846 break;
847 case Instruction::Trunc:
848 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
849 break;
850 case Instruction::SExt:
851 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
852 break;
853 case Instruction::ZExt:
854 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
855 break;
856 case Instruction::BitCast:
857 Result.markConstantRange(LHSRange);
858 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +0000859 case Instruction::And:
860 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
861 break;
862 case Instruction::Or:
863 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
864 break;
Owen Anderson80d19f02010-08-18 21:11:37 +0000865
866 // Unhandled instructions are overdefined.
867 default:
868 DEBUG(dbgs() << " compute BB '" << BB->getName()
869 << "' - overdefined because inst def found.\n");
870 Result.markOverdefined();
871 break;
872 }
873
Owen Anderson64c2c572010-12-20 18:18:16 +0000874 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000875 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +0000876}
877
Hal Finkel7e184492014-09-07 20:29:59 +0000878bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
879 LVILatticeVal &Result, bool isTrueDest) {
880 if (ICI && isa<Constant>(ICI->getOperand(1))) {
881 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
882 // We know that V has the RHS constant if this is a true SETEQ or
883 // false SETNE.
884 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
885 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
886 else
887 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
888 return true;
889 }
890
891 // Recognize the range checking idiom that InstCombine produces.
892 // (X-C1) u< C2 --> [C1, C1+C2)
893 ConstantInt *NegOffset = nullptr;
894 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
895 match(ICI->getOperand(0), m_Add(m_Specific(Val),
896 m_ConstantInt(NegOffset)));
897
898 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
899 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
900 // Calculate the range of values that would satisfy the comparison.
901 ConstantRange CmpRange(CI->getValue());
902 ConstantRange TrueValues =
903 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
904
905 if (NegOffset) // Apply the offset from above.
906 TrueValues = TrueValues.subtract(NegOffset->getValue());
907
908 // If we're interested in the false dest, invert the condition.
909 if (!isTrueDest) TrueValues = TrueValues.inverse();
910
911 Result = LVILatticeVal::getRange(TrueValues);
912 return true;
913 }
914 }
915
916 return false;
917}
918
Nuno Lopese6e04902012-06-28 01:16:18 +0000919/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
920/// Val is not constrained on the edge.
921static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
922 BasicBlock *BBTo, LVILatticeVal &Result) {
Chris Lattner77358782009-11-15 20:02:12 +0000923 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
924 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +0000925 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
926 // If this is a conditional branch and only one successor goes to BBTo, then
927 // we maybe able to infer something from the condition.
928 if (BI->isConditional() &&
929 BI->getSuccessor(0) != BI->getSuccessor(1)) {
930 bool isTrueDest = BI->getSuccessor(0) == BBTo;
931 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
932 "BBTo isn't a successor of BBFrom");
933
934 // If V is the condition of the branch itself, then we know exactly what
935 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000936 if (BI->getCondition() == Val) {
937 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +0000938 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000939 return true;
940 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000941
942 // If the condition of the branch is an equality comparison, we may be
943 // able to infer the value.
Owen Anderson0bd61242010-08-11 04:24:25 +0000944 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
Hal Finkel7e184492014-09-07 20:29:59 +0000945 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
946 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +0000947 }
948 }
Chris Lattner77358782009-11-15 20:02:12 +0000949
950 // If the edge was formed by a switch on the value, then we may know exactly
951 // what it is.
952 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +0000953 if (SI->getCondition() != Val)
954 return false;
955
956 bool DefaultCase = SI->getDefaultDest() == BBTo;
957 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
958 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
959
960 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
961 i != e; ++i) {
962 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +0000963 if (DefaultCase) {
964 // It is possible that the default destination is the destination of
965 // some cases. There is no need to perform difference for those cases.
966 if (i.getCaseSuccessor() != BBTo)
967 EdgesVals = EdgesVals.difference(EdgeVal);
968 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +0000969 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +0000970 }
Nuno Lopes8650fb82012-06-28 16:13:37 +0000971 Result = LVILatticeVal::getRange(EdgesVals);
972 return true;
Chris Lattner77358782009-11-15 20:02:12 +0000973 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000974 return false;
975}
976
977/// \brief Compute the value of Val on the edge BBFrom -> BBTo, or the value at
978/// the basic block if the edge does not constraint Val.
979bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +0000980 BasicBlock *BBTo, LVILatticeVal &Result,
981 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +0000982 // If already a constant, there is nothing to compute.
983 if (Constant *VC = dyn_cast<Constant>(Val)) {
984 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000985 return true;
986 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000987
988 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
989 if (!Result.isConstantRange() ||
990 Result.getConstantRange().getSingleElement())
991 return true;
992
993 // FIXME: this check should be moved to the beginning of the function when
994 // LVI better supports recursive values. Even for the single value case, we
995 // can intersect to detect dead code (an empty range).
996 if (!hasBlockValue(Val, BBFrom)) {
997 BlockValueStack.push(std::make_pair(BBFrom, Val));
998 return false;
999 }
1000
1001 // Try to intersect ranges of the BB and the constraint on the edge.
1002 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Hal Finkel7e184492014-09-07 20:29:59 +00001003 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +00001004 if (!InBlock.isConstantRange())
1005 return true;
1006
1007 ConstantRange Range =
1008 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
1009 Result = LVILatticeVal::getRange(Range);
1010 return true;
1011 }
1012
1013 if (!hasBlockValue(Val, BBFrom)) {
1014 BlockValueStack.push(std::make_pair(BBFrom, Val));
1015 return false;
1016 }
1017
1018 // if we couldn't compute the value on the edge, use the value from the BB
1019 Result = getBlockValue(Val, BBFrom);
Hal Finkel7e184492014-09-07 20:29:59 +00001020 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +00001021 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001022}
1023
Hal Finkel7e184492014-09-07 20:29:59 +00001024LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1025 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001026 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001027 << BB->getName() << "'\n");
1028
Owen Anderson6f060af2011-01-05 23:26:22 +00001029 BlockValueStack.push(std::make_pair(BB, V));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001030 solve();
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001031 LVILatticeVal Result = getBlockValue(V, BB);
Hal Finkel7e184492014-09-07 20:29:59 +00001032 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1033
1034 DEBUG(dbgs() << " Result = " << Result << "\n");
1035 return Result;
1036}
1037
1038LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1039 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1040 << CxtI->getName() << "'\n");
1041
1042 LVILatticeVal Result;
1043 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001044
David Greene37e98092009-12-23 20:43:58 +00001045 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001046 return Result;
1047}
Chris Lattner19019ea2009-11-11 22:48:44 +00001048
Chris Lattneraf025d32009-11-15 19:59:49 +00001049LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001050getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1051 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001052 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001053 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001054
Nick Lewycky55a700b2010-12-18 01:00:40 +00001055 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001056 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001057 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001058 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001059 (void)WasFastQuery;
1060 assert(WasFastQuery && "More work to do after problem solved?");
1061 }
1062
David Greene37e98092009-12-23 20:43:58 +00001063 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001064 return Result;
1065}
1066
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001067void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1068 BasicBlock *NewSucc) {
1069 // When an edge in the graph has been threaded, values that we could not
1070 // determine a value for before (i.e. were marked overdefined) may be possible
1071 // to solve now. We do NOT try to proactively update these values. Instead,
1072 // we clear their entries from the cache, and allow lazy updating to recompute
1073 // them when needed.
1074
1075 // The updating process is fairly simple: we need to dropped cached info
1076 // for all values that were marked overdefined in OldSucc, and for those same
1077 // values in any successor of OldSucc (except NewSucc) in which they were
1078 // also marked overdefined.
1079 std::vector<BasicBlock*> worklist;
1080 worklist.push_back(OldSucc);
1081
Owen Andersonaac5a722010-07-27 23:58:11 +00001082 DenseSet<Value*> ClearSet;
Owen Anderson118ac802011-01-05 21:15:29 +00001083 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
1084 E = OverDefinedCache.end(); I != E; ++I) {
Owen Andersonaac5a722010-07-27 23:58:11 +00001085 if (I->first == OldSucc)
1086 ClearSet.insert(I->second);
1087 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001088
1089 // Use a worklist to perform a depth-first search of OldSucc's successors.
1090 // NOTE: We do not need a visited list since any blocks we have already
1091 // visited will have had their overdefined markers cleared already, and we
1092 // thus won't loop to their successors.
1093 while (!worklist.empty()) {
1094 BasicBlock *ToUpdate = worklist.back();
1095 worklist.pop_back();
1096
1097 // Skip blocks only accessible through NewSucc.
1098 if (ToUpdate == NewSucc) continue;
1099
1100 bool changed = false;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001101 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001102 I != E; ++I) {
1103 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson118ac802011-01-05 21:15:29 +00001104 DenseSet<OverDefinedPairTy>::iterator OI =
Owen Andersonaac5a722010-07-27 23:58:11 +00001105 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
1106 if (OI == OverDefinedCache.end()) continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001107
Owen Andersonaac5a722010-07-27 23:58:11 +00001108 // Remove it from the caches.
Owen Andersonc1561b82010-07-30 23:59:40 +00001109 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Andersonaac5a722010-07-27 23:58:11 +00001110 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001111
Owen Andersonaac5a722010-07-27 23:58:11 +00001112 assert(CI != Entry.end() && "Couldn't find entry to update?");
1113 Entry.erase(CI);
1114 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001115
Owen Andersonaac5a722010-07-27 23:58:11 +00001116 // If we removed anything, then we potentially need to update
1117 // blocks successors too.
1118 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001119 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001120
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001121 if (!changed) continue;
1122
1123 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1124 }
1125}
1126
Chris Lattneraf025d32009-11-15 19:59:49 +00001127//===----------------------------------------------------------------------===//
1128// LazyValueInfo Impl
1129//===----------------------------------------------------------------------===//
1130
Chris Lattneraf025d32009-11-15 19:59:49 +00001131/// getCache - This lazily constructs the LazyValueInfoCache.
Hal Finkel7e184492014-09-07 20:29:59 +00001132static LazyValueInfoCache &getCache(void *&PImpl,
1133 AssumptionTracker *AT,
1134 const DataLayout *DL = nullptr,
1135 DominatorTree *DT = nullptr) {
Chris Lattneraf025d32009-11-15 19:59:49 +00001136 if (!PImpl)
Hal Finkel7e184492014-09-07 20:29:59 +00001137 PImpl = new LazyValueInfoCache(AT, DL, DT);
Chris Lattneraf025d32009-11-15 19:59:49 +00001138 return *static_cast<LazyValueInfoCache*>(PImpl);
1139}
1140
Owen Anderson208636f2010-08-18 18:39:01 +00001141bool LazyValueInfo::runOnFunction(Function &F) {
Hal Finkel7e184492014-09-07 20:29:59 +00001142 AT = &getAnalysis<AssumptionTracker>();
1143
1144 DominatorTreeWrapperPass *DTWP =
1145 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1146 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chad Rosier43a33062011-12-02 01:26:24 +00001147
Rafael Espindola93512512014-02-25 17:30:31 +00001148 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topper9f008862014-04-15 04:59:12 +00001149 DL = DLP ? &DLP->getDataLayout() : nullptr;
Chad Rosier43a33062011-12-02 01:26:24 +00001150 TLI = &getAnalysis<TargetLibraryInfo>();
1151
Hal Finkel7e184492014-09-07 20:29:59 +00001152 if (PImpl)
1153 getCache(PImpl, AT, DL, DT).clear();
1154
Owen Anderson208636f2010-08-18 18:39:01 +00001155 // Fully lazy.
1156 return false;
1157}
1158
Chad Rosier43a33062011-12-02 01:26:24 +00001159void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1160 AU.setPreservesAll();
Hal Finkel7e184492014-09-07 20:29:59 +00001161 AU.addRequired<AssumptionTracker>();
Chad Rosier43a33062011-12-02 01:26:24 +00001162 AU.addRequired<TargetLibraryInfo>();
1163}
1164
Chris Lattneraf025d32009-11-15 19:59:49 +00001165void LazyValueInfo::releaseMemory() {
1166 // If the cache was allocated, free it.
1167 if (PImpl) {
Hal Finkel7e184492014-09-07 20:29:59 +00001168 delete &getCache(PImpl, AT);
Craig Topper9f008862014-04-15 04:59:12 +00001169 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001170 }
1171}
1172
Hal Finkel7e184492014-09-07 20:29:59 +00001173Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1174 Instruction *CxtI) {
1175 LVILatticeVal Result =
1176 getCache(PImpl, AT, DL, DT).getValueInBlock(V, BB, CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +00001177
Chris Lattner19019ea2009-11-11 22:48:44 +00001178 if (Result.isConstant())
1179 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001180 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001181 ConstantRange CR = Result.getConstantRange();
1182 if (const APInt *SingleVal = CR.getSingleElement())
1183 return ConstantInt::get(V->getContext(), *SingleVal);
1184 }
Craig Topper9f008862014-04-15 04:59:12 +00001185 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001186}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001187
Chris Lattnerd5e25432009-11-12 01:29:10 +00001188/// getConstantOnEdge - Determine whether the specified value is known to be a
1189/// constant on the specified edge. Return null if not.
1190Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001191 BasicBlock *ToBB,
1192 Instruction *CxtI) {
1193 LVILatticeVal Result =
1194 getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chris Lattnerd5e25432009-11-12 01:29:10 +00001195
1196 if (Result.isConstant())
1197 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001198 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001199 ConstantRange CR = Result.getConstantRange();
1200 if (const APInt *SingleVal = CR.getSingleElement())
1201 return ConstantInt::get(V->getContext(), *SingleVal);
1202 }
Craig Topper9f008862014-04-15 04:59:12 +00001203 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001204}
1205
Hal Finkel7e184492014-09-07 20:29:59 +00001206static LazyValueInfo::Tristate
1207getPredicateResult(unsigned Pred, Constant *C, LVILatticeVal &Result,
1208 const DataLayout *DL, TargetLibraryInfo *TLI) {
1209
Chris Lattner565ee2f2009-11-12 04:36:58 +00001210 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001211 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001212 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001213 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001214 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001215 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001216 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1217 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001218 }
1219
Owen Anderson185fe002010-08-10 20:03:09 +00001220 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001221 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001222 if (!CI) return LazyValueInfo::Unknown;
Owen Andersonc62f7042010-08-24 07:55:44 +00001223
Owen Anderson185fe002010-08-10 20:03:09 +00001224 ConstantRange CR = Result.getConstantRange();
1225 if (Pred == ICmpInst::ICMP_EQ) {
1226 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001227 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001228
1229 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001230 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001231 } else if (Pred == ICmpInst::ICMP_NE) {
1232 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001233 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001234
1235 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001236 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001237 }
1238
1239 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001240 ConstantRange TrueValues =
1241 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1242 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001243 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001244 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001245 return LazyValueInfo::False;
1246 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001247 }
1248
Chris Lattneraf025d32009-11-15 19:59:49 +00001249 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001250 // If this is an equality comparison, we can try to fold it knowing that
1251 // "V != C1".
1252 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001253 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001254 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001255 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001256 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001257 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001258 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001259 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001260 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001261 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001262 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001263 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001264 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001265 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001266 }
Hal Finkel7e184492014-09-07 20:29:59 +00001267 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001268 }
1269
Hal Finkel7e184492014-09-07 20:29:59 +00001270 return LazyValueInfo::Unknown;
1271}
1272
1273/// getPredicateOnEdge - Determine whether the specified value comparison
1274/// with a constant is known to be true or false on the specified CFG edge.
1275/// Pred is a CmpInst predicate.
1276LazyValueInfo::Tristate
1277LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1278 BasicBlock *FromBB, BasicBlock *ToBB,
1279 Instruction *CxtI) {
1280 LVILatticeVal Result =
1281 getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1282
1283 return getPredicateResult(Pred, C, Result, DL, TLI);
1284}
1285
1286LazyValueInfo::Tristate
1287LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1288 Instruction *CxtI) {
1289 LVILatticeVal Result =
1290 getCache(PImpl, AT, DL, DT).getValueAt(V, CxtI);
1291
1292 return getPredicateResult(Pred, C, Result, DL, TLI);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001293}
1294
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001295void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001296 BasicBlock *NewSucc) {
Hal Finkel7e184492014-09-07 20:29:59 +00001297 if (PImpl) getCache(PImpl, AT, DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
Owen Anderson208636f2010-08-18 18:39:01 +00001298}
1299
1300void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Hal Finkel7e184492014-09-07 20:29:59 +00001301 if (PImpl) getCache(PImpl, AT, DL, DT).eraseBlock(BB);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001302}