blob: ec618fad22ed690e6dc6983ea13cc2b43da6e0de [file] [log] [blame]
Chris Lattner10f2d132009-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
Chris Lattnerb8c124c2009-11-12 01:22:16 +000015#define DEBUG_TYPE "lazy-value-info"
Chris Lattner10f2d132009-11-11 00:22:30 +000016#include "llvm/Analysis/LazyValueInfo.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000017#include "llvm/Analysis/ValueTracking.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000018#include "llvm/Constants.h"
19#include "llvm/Instructions.h"
Nick Lewycky786c7cd2011-01-15 09:16:12 +000020#include "llvm/IntrinsicInst.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000021#include "llvm/Analysis/ConstantFolding.h"
22#include "llvm/Target/TargetData.h"
Chad Rosieraab8e282011-12-02 01:26:24 +000023#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner16976522009-11-11 22:48:44 +000024#include "llvm/Support/CFG.h"
Owen Anderson5be2e782010-08-05 22:59:19 +000025#include "llvm/Support/ConstantRange.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000026#include "llvm/Support/Debug.h"
Benjamin Kramer8979e5f2012-03-02 15:34:43 +000027#include "llvm/Support/PatternMatch.h"
Chris Lattner16976522009-11-11 22:48:44 +000028#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000029#include "llvm/Support/ValueHandle.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000030#include "llvm/ADT/DenseSet.h"
Chris Lattnere5642812009-11-15 20:00:52 +000031#include "llvm/ADT/STLExtras.h"
Bill Wendlingaa8b9942012-01-11 23:43:34 +000032#include <map>
Nick Lewycky90862ee2010-12-18 01:00:40 +000033#include <stack>
Chris Lattner10f2d132009-11-11 00:22:30 +000034using namespace llvm;
Benjamin Kramer8979e5f2012-03-02 15:34:43 +000035using namespace PatternMatch;
Chris Lattner10f2d132009-11-11 00:22:30 +000036
37char LazyValueInfo::ID = 0;
Chad Rosieraab8e282011-12-02 01:26:24 +000038INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
39 "Lazy Value Information Analysis", false, true)
40INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
41INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
Owen Andersonce665bd2010-10-07 22:25:06 +000042 "Lazy Value Information Analysis", false, true)
Chris Lattner10f2d132009-11-11 00:22:30 +000043
44namespace llvm {
45 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
46}
47
Chris Lattnercc4d3b22009-11-11 02:08:33 +000048
49//===----------------------------------------------------------------------===//
50// LVILatticeVal
51//===----------------------------------------------------------------------===//
52
53/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
54/// value.
55///
56/// FIXME: This is basically just for bringup, this can be made a lot more rich
57/// in the future.
58///
59namespace {
60class LVILatticeVal {
61 enum LatticeValueTy {
Nick Lewycky69bfdf52010-12-15 18:57:18 +000062 /// undefined - This Value has no known value yet.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000063 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000064
Nick Lewycky69bfdf52010-12-15 18:57:18 +000065 /// constant - This Value has a specific constant value.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000066 constant,
Nick Lewycky69bfdf52010-12-15 18:57:18 +000067 /// notconstant - This Value is known to not have the specified value.
Chris Lattnerb52675b2009-11-12 04:36:58 +000068 notconstant,
Chad Rosieraab8e282011-12-02 01:26:24 +000069
Nick Lewycky69bfdf52010-12-15 18:57:18 +000070 /// constantrange - The Value falls within this range.
Owen Anderson5be2e782010-08-05 22:59:19 +000071 constantrange,
Chad Rosieraab8e282011-12-02 01:26:24 +000072
Nick Lewycky69bfdf52010-12-15 18:57:18 +000073 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnercc4d3b22009-11-11 02:08:33 +000074 /// it has a value.
75 overdefined
76 };
77
78 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000079 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000080 LatticeValueTy Tag;
81 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000082 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000083
84public:
Owen Anderson5be2e782010-08-05 22:59:19 +000085 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000086
Chris Lattner16976522009-11-11 22:48:44 +000087 static LVILatticeVal get(Constant *C) {
88 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000089 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000090 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000091 return Res;
92 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000093 static LVILatticeVal getNot(Constant *C) {
94 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000095 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000096 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000097 return Res;
98 }
Owen Anderson625051b2010-08-10 23:20:01 +000099 static LVILatticeVal getRange(ConstantRange CR) {
100 LVILatticeVal Res;
101 Res.markConstantRange(CR);
102 return Res;
103 }
Chris Lattner16976522009-11-11 22:48:44 +0000104
Owen Anderson5be2e782010-08-05 22:59:19 +0000105 bool isUndefined() const { return Tag == undefined; }
106 bool isConstant() const { return Tag == constant; }
107 bool isNotConstant() const { return Tag == notconstant; }
108 bool isConstantRange() const { return Tag == constantrange; }
109 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000110
111 Constant *getConstant() const {
112 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000113 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000114 }
115
Chris Lattnerb52675b2009-11-12 04:36:58 +0000116 Constant *getNotConstant() const {
117 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000118 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000119 }
120
Owen Anderson5be2e782010-08-05 22:59:19 +0000121 ConstantRange getConstantRange() const {
122 assert(isConstantRange() &&
123 "Cannot get the constant-range of a non-constant-range!");
124 return Range;
125 }
126
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000127 /// markOverdefined - Return true if this is a change in status.
128 bool markOverdefined() {
129 if (isOverdefined())
130 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000131 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000132 return true;
133 }
134
135 /// markConstant - Return true if this is a change in status.
136 bool markConstant(Constant *V) {
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000137 assert(V && "Marking constant with NULL");
138 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
139 return markConstantRange(ConstantRange(CI->getValue()));
140 if (isa<UndefValue>(V))
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000141 return false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000142
143 assert((!isConstant() || getConstant() == V) &&
144 "Marking constant with different value");
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000145 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000146 Tag = constant;
Owen Andersondb78d732010-08-05 22:10:46 +0000147 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000148 return true;
149 }
150
Chris Lattnerb52675b2009-11-12 04:36:58 +0000151 /// markNotConstant - Return true if this is a change in status.
152 bool markNotConstant(Constant *V) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000153 assert(V && "Marking constant with NULL");
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000154 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
155 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
156 if (isa<UndefValue>(V))
157 return false;
158
159 assert((!isConstant() || getConstant() != V) &&
160 "Marking constant !constant with same value");
161 assert((!isNotConstant() || getNotConstant() == V) &&
162 "Marking !constant with different value");
163 assert(isUndefined() || isConstant());
164 Tag = notconstant;
Owen Andersondb78d732010-08-05 22:10:46 +0000165 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000166 return true;
167 }
168
Owen Anderson5be2e782010-08-05 22:59:19 +0000169 /// markConstantRange - Return true if this is a change in status.
170 bool markConstantRange(const ConstantRange NewR) {
171 if (isConstantRange()) {
172 if (NewR.isEmptySet())
173 return markOverdefined();
174
Nuno Lopese4413942012-06-28 01:16:18 +0000175 bool changed = Range != NewR;
Owen Anderson5be2e782010-08-05 22:59:19 +0000176 Range = NewR;
177 return changed;
178 }
179
180 assert(isUndefined());
181 if (NewR.isEmptySet())
182 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000183
184 Tag = constantrange;
185 Range = NewR;
186 return true;
187 }
188
Chris Lattner16976522009-11-11 22:48:44 +0000189 /// mergeIn - Merge the specified lattice value into this one, updating this
190 /// one and returning true if anything changed.
191 bool mergeIn(const LVILatticeVal &RHS) {
192 if (RHS.isUndefined() || isOverdefined()) return false;
193 if (RHS.isOverdefined()) return markOverdefined();
194
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000195 if (isUndefined()) {
196 Tag = RHS.Tag;
197 Val = RHS.Val;
198 Range = RHS.Range;
199 return true;
Chris Lattnerf496e792009-11-12 04:57:13 +0000200 }
201
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000202 if (isConstant()) {
203 if (RHS.isConstant()) {
204 if (Val == RHS.Val)
205 return false;
206 return markOverdefined();
207 }
208
209 if (RHS.isNotConstant()) {
210 if (Val == RHS.Val)
211 return markOverdefined();
212
213 // Unless we can prove that the two Constants are different, we must
214 // move to overdefined.
Chad Rosieraab8e282011-12-02 01:26:24 +0000215 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000216 if (ConstantInt *Res = dyn_cast<ConstantInt>(
217 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
218 getConstant(),
219 RHS.getNotConstant())))
220 if (Res->isOne())
221 return markNotConstant(RHS.getNotConstant());
222
223 return markOverdefined();
224 }
225
226 // RHS is a ConstantRange, LHS is a non-integer Constant.
227
228 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
229 // a function. The correct result is to pick up RHS.
230
Chris Lattner16976522009-11-11 22:48:44 +0000231 return markOverdefined();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000232 }
233
234 if (isNotConstant()) {
235 if (RHS.isConstant()) {
236 if (Val == RHS.Val)
237 return markOverdefined();
238
239 // Unless we can prove that the two Constants are different, we must
240 // move to overdefined.
Chad Rosieraab8e282011-12-02 01:26:24 +0000241 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000242 if (ConstantInt *Res = dyn_cast<ConstantInt>(
243 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
244 getNotConstant(),
245 RHS.getConstant())))
246 if (Res->isOne())
247 return false;
248
249 return markOverdefined();
250 }
251
252 if (RHS.isNotConstant()) {
253 if (Val == RHS.Val)
254 return false;
255 return markOverdefined();
256 }
257
258 return markOverdefined();
259 }
260
261 assert(isConstantRange() && "New LVILattice type?");
262 if (!RHS.isConstantRange())
263 return markOverdefined();
264
265 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
266 if (NewR.isFullSet())
267 return markOverdefined();
268 return markConstantRange(NewR);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000269 }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000270};
271
272} // end anonymous namespace.
273
Chris Lattner16976522009-11-11 22:48:44 +0000274namespace llvm {
Chandler Carruth3b55a372011-04-18 18:49:44 +0000275raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
276 LLVM_ATTRIBUTE_USED;
Chris Lattner16976522009-11-11 22:48:44 +0000277raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
278 if (Val.isUndefined())
279 return OS << "undefined";
280 if (Val.isOverdefined())
281 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000282
283 if (Val.isNotConstant())
284 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000285 else if (Val.isConstantRange())
286 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
287 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000288 return OS << "constant<" << *Val.getConstant() << '>';
289}
290}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000291
292//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000293// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000294//===----------------------------------------------------------------------===//
295
Chris Lattner2c5adf82009-11-15 19:59:49 +0000296namespace {
Owen Anderson89778462011-01-05 21:15:29 +0000297 /// LVIValueHandle - A callback value handle update the cache when
298 /// values are erased.
299 class LazyValueInfoCache;
300 struct LVIValueHandle : public CallbackVH {
301 LazyValueInfoCache *Parent;
302
303 LVIValueHandle(Value *V, LazyValueInfoCache *P)
304 : CallbackVH(V), Parent(P) { }
305
306 void deleted();
307 void allUsesReplacedWith(Value *V) {
308 deleted();
309 }
310 };
311}
312
Owen Anderson89778462011-01-05 21:15:29 +0000313namespace {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000314 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
315 /// maintains information about queries across the clients' queries.
316 class LazyValueInfoCache {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000317 /// ValueCacheEntryTy - This is all of the cached block information for
318 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
319 /// entries, allowing us to do a lookup with a binary search.
Bill Wendlingaa8b9942012-01-11 23:43:34 +0000320 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000321
Owen Andersone68713a2011-01-05 23:26:22 +0000322 /// ValueCache - This is all of the cached information for all values,
323 /// mapped from Value* to key information.
Bill Wendling805e2242012-01-12 01:41:03 +0000324 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersone68713a2011-01-05 23:26:22 +0000325
326 /// OverDefinedCache - This tracks, on a per-block basis, the set of
327 /// values that are over-defined at the end of that block. This is required
328 /// for cache updating.
329 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
330 DenseSet<OverDefinedPairTy> OverDefinedCache;
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000331
332 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
333 /// don't spend time removing unused blocks from our caches.
334 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
335
Owen Andersone68713a2011-01-05 23:26:22 +0000336 /// BlockValueStack - This stack holds the state of the value solver
337 /// during a query. It basically emulates the callstack of the naive
338 /// recursive value lookup process.
339 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
340
Owen Anderson89778462011-01-05 21:15:29 +0000341 friend struct LVIValueHandle;
Owen Anderson87790ab2010-12-20 19:33:41 +0000342
343 /// OverDefinedCacheUpdater - A helper object that ensures that the
344 /// OverDefinedCache is updated whenever solveBlockValue returns.
345 struct OverDefinedCacheUpdater {
346 LazyValueInfoCache *Parent;
347 Value *Val;
348 BasicBlock *BB;
349 LVILatticeVal &BBLV;
350
351 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
352 LazyValueInfoCache *P)
353 : Parent(P), Val(V), BB(B), BBLV(LV) { }
354
355 bool markResult(bool changed) {
356 if (changed && BBLV.isOverdefined())
357 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
358 return changed;
359 }
360 };
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000361
Owen Andersone68713a2011-01-05 23:26:22 +0000362
Owen Anderson7f9cb742010-07-30 23:59:40 +0000363
Owen Andersonf33b3022010-12-09 06:14:58 +0000364 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000365 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
366 LVILatticeVal &Result);
367 bool hasBlockValue(Value *Val, BasicBlock *BB);
368
369 // These methods process one work item and may add more. A false value
370 // returned means that the work item was not completely processed and must
371 // be revisited after going through the new items.
372 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson61863942010-12-20 18:18:16 +0000373 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
374 Value *Val, BasicBlock *BB);
375 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
376 PHINode *PN, BasicBlock *BB);
377 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
378 Instruction *BBI, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000379
380 void solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000381
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000382 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonf33b3022010-12-09 06:14:58 +0000383 return ValueCache[LVIValueHandle(V, this)];
384 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000385
Chris Lattner2c5adf82009-11-15 19:59:49 +0000386 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000387 /// getValueInBlock - This is the query interface to determine the lattice
388 /// value for the specified Value* at the end of the specified block.
389 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
390
391 /// getValueOnEdge - This is the query interface to determine the lattice
392 /// value for the specified Value* that is true on the specified edge.
393 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000394
395 /// threadEdge - This is the update interface to inform the cache that an
396 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
397 /// NewSucc.
398 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000399
400 /// eraseBlock - This is part of the update interface to inform the cache
401 /// that a block has been deleted.
402 void eraseBlock(BasicBlock *BB);
403
404 /// clear - Empty the cache.
405 void clear() {
Benjamin Kramerc00c05f2011-12-03 15:19:55 +0000406 SeenBlocks.clear();
Owen Anderson00ac77e2010-08-18 18:39:01 +0000407 ValueCache.clear();
408 OverDefinedCache.clear();
409 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000410 };
411} // end anonymous namespace
412
Owen Anderson89778462011-01-05 21:15:29 +0000413void LVIValueHandle::deleted() {
414 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
415
416 SmallVector<OverDefinedPairTy, 4> ToErase;
417 for (DenseSet<OverDefinedPairTy>::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000418 I = Parent->OverDefinedCache.begin(),
419 E = Parent->OverDefinedCache.end();
Owen Anderson89778462011-01-05 21:15:29 +0000420 I != E; ++I) {
421 if (I->second == getValPtr())
422 ToErase.push_back(*I);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000423 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000424
Owen Anderson89778462011-01-05 21:15:29 +0000425 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
426 E = ToErase.end(); I != E; ++I)
427 Parent->OverDefinedCache.erase(*I);
428
Owen Andersoncf6abd22010-08-11 22:36:04 +0000429 // This erasure deallocates *this, so it MUST happen after we're done
430 // using any and all members of *this.
431 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000432}
433
Owen Anderson00ac77e2010-08-18 18:39:01 +0000434void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000435 // Shortcut if we have never seen this block.
436 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
437 if (I == SeenBlocks.end())
438 return;
439 SeenBlocks.erase(I);
440
Owen Anderson89778462011-01-05 21:15:29 +0000441 SmallVector<OverDefinedPairTy, 4> ToErase;
442 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
443 E = OverDefinedCache.end(); I != E; ++I) {
444 if (I->first == BB)
445 ToErase.push_back(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000446 }
Owen Anderson89778462011-01-05 21:15:29 +0000447
448 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
449 E = ToErase.end(); I != E; ++I)
450 OverDefinedCache.erase(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000451
Bill Wendling805e2242012-01-12 01:41:03 +0000452 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson00ac77e2010-08-18 18:39:01 +0000453 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
454 I->second.erase(BB);
455}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000456
Nick Lewycky90862ee2010-12-18 01:00:40 +0000457void LazyValueInfoCache::solve() {
Owen Andersone68713a2011-01-05 23:26:22 +0000458 while (!BlockValueStack.empty()) {
459 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Nuno Lopese4413942012-06-28 01:16:18 +0000460 if (solveBlockValue(e.second, e.first)) {
461 assert(BlockValueStack.top() == e);
Owen Andersone68713a2011-01-05 23:26:22 +0000462 BlockValueStack.pop();
Nuno Lopese4413942012-06-28 01:16:18 +0000463 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000464 }
465}
466
467bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
468 // If already a constant, there is nothing to compute.
469 if (isa<Constant>(Val))
470 return true;
471
Owen Anderson89778462011-01-05 21:15:29 +0000472 LVIValueHandle ValHandle(Val, this);
Benjamin Kramer05d96f92012-08-22 15:37:57 +0000473 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
474 ValueCache.find(ValHandle);
475 if (I == ValueCache.end()) return false;
476 return I->second.count(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000477}
478
Owen Andersonf33b3022010-12-09 06:14:58 +0000479LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000480 // If already a constant, there is nothing to compute.
481 if (Constant *VC = dyn_cast<Constant>(Val))
482 return LVILatticeVal::get(VC);
483
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000484 SeenBlocks.insert(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000485 return lookup(Val)[BB];
486}
487
488bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
489 if (isa<Constant>(Val))
490 return true;
491
Owen Andersonf33b3022010-12-09 06:14:58 +0000492 ValueCacheEntryTy &Cache = lookup(Val);
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000493 SeenBlocks.insert(BB);
Owen Andersonf33b3022010-12-09 06:14:58 +0000494 LVILatticeVal &BBLV = Cache[BB];
Owen Anderson87790ab2010-12-20 19:33:41 +0000495
496 // OverDefinedCacheUpdater is a helper object that will update
497 // the OverDefinedCache for us when this method exits. Make sure to
498 // call markResult on it as we exist, passing a bool to indicate if the
499 // cache needs updating, i.e. if we have solve a new value or not.
500 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000501
Chris Lattner2c5adf82009-11-15 19:59:49 +0000502 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000503 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000504 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Owen Anderson87790ab2010-12-20 19:33:41 +0000505
506 // Since we're reusing a cached value here, we don't need to update the
507 // OverDefinedCahce. The cache will have been properly updated
508 // whenever the cached value was inserted.
509 ODCacheUpdater.markResult(false);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000510 return true;
Chris Lattnere5642812009-11-15 20:00:52 +0000511 }
512
Chris Lattner2c5adf82009-11-15 19:59:49 +0000513 // Otherwise, this is the first time we're seeing this block. Reset the
514 // lattice value to overdefined, so that cycles will terminate and be
515 // conservatively correct.
516 BBLV.markOverdefined();
517
Chris Lattner2c5adf82009-11-15 19:59:49 +0000518 Instruction *BBI = dyn_cast<Instruction>(Val);
519 if (BBI == 0 || BBI->getParent() != BB) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000520 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000521 }
Chris Lattnere5642812009-11-15 20:00:52 +0000522
Nick Lewycky90862ee2010-12-18 01:00:40 +0000523 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000524 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000525 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000526
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000527 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
528 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
529 return ODCacheUpdater.markResult(true);
530 }
531
Owen Andersonb81fd622010-08-18 21:11:37 +0000532 // We can only analyze the definitions of certain classes of instructions
533 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000534 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000535 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
536 !BBI->getType()->isIntegerTy()) {
537 DEBUG(dbgs() << " compute BB '" << BB->getName()
538 << "' - overdefined because inst def found.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000539 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000540 return ODCacheUpdater.markResult(true);
Owen Andersonb81fd622010-08-18 21:11:37 +0000541 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000542
Owen Andersonb81fd622010-08-18 21:11:37 +0000543 // FIXME: We're currently limited to binops with a constant RHS. This should
544 // be improved.
545 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
546 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
547 DEBUG(dbgs() << " compute BB '" << BB->getName()
548 << "' - overdefined because inst def found.\n");
549
Owen Anderson61863942010-12-20 18:18:16 +0000550 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000551 return ODCacheUpdater.markResult(true);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000552 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000553
Owen Anderson87790ab2010-12-20 19:33:41 +0000554 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000555}
556
557static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
558 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
559 return L->getPointerAddressSpace() == 0 &&
560 GetUnderlyingObject(L->getPointerOperand()) ==
561 GetUnderlyingObject(Ptr);
562 }
563 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
564 return S->getPointerAddressSpace() == 0 &&
565 GetUnderlyingObject(S->getPointerOperand()) ==
566 GetUnderlyingObject(Ptr);
567 }
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000568 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
569 if (MI->isVolatile()) return false;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000570
571 // FIXME: check whether it has a valuerange that excludes zero?
572 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
573 if (!Len || Len->isZero()) return false;
574
Eli Friedman69388e52011-05-31 20:40:16 +0000575 if (MI->getDestAddressSpace() == 0)
576 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
577 return true;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000578 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman69388e52011-05-31 20:40:16 +0000579 if (MTI->getSourceAddressSpace() == 0)
580 if (MTI->getRawSource() == Ptr || MTI->getSource() == Ptr)
581 return true;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000582 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000583 return false;
584}
585
Owen Anderson61863942010-12-20 18:18:16 +0000586bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
587 Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000588 LVILatticeVal Result; // Start Undefined.
589
590 // If this is a pointer, and there's a load from that pointer in this BB,
591 // then we know that the pointer can't be NULL.
592 bool NotNull = false;
593 if (Val->getType()->isPointerTy()) {
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000594 if (isa<AllocaInst>(Val)) {
595 NotNull = true;
596 } else {
597 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
598 if (InstructionDereferencesPointer(BI, Val)) {
599 NotNull = true;
600 break;
601 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000602 }
603 }
604 }
605
606 // If this is the entry block, we must be asking about an argument. The
607 // value is overdefined.
608 if (BB == &BB->getParent()->getEntryBlock()) {
609 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
610 if (NotNull) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000611 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000612 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
613 } else {
614 Result.markOverdefined();
615 }
Owen Anderson61863942010-12-20 18:18:16 +0000616 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000617 return true;
618 }
619
620 // Loop over all of our predecessors, merging what we know from them into
621 // result.
622 bool EdgesMissing = false;
623 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
624 LVILatticeVal EdgeResult;
625 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
626 if (EdgesMissing)
627 continue;
628
629 Result.mergeIn(EdgeResult);
630
631 // If we hit overdefined, exit early. The BlockVals entry is already set
632 // to overdefined.
633 if (Result.isOverdefined()) {
634 DEBUG(dbgs() << " compute BB '" << BB->getName()
635 << "' - overdefined because of pred.\n");
636 // If we previously determined that this is a pointer that can't be null
637 // then return that rather than giving up entirely.
638 if (NotNull) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000639 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000640 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
641 }
Owen Anderson61863942010-12-20 18:18:16 +0000642
643 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000644 return true;
645 }
646 }
647 if (EdgesMissing)
648 return false;
649
650 // Return the merged value, which is more precise than 'overdefined'.
651 assert(!Result.isOverdefined());
Owen Anderson61863942010-12-20 18:18:16 +0000652 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000653 return true;
654}
655
Owen Anderson61863942010-12-20 18:18:16 +0000656bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
657 PHINode *PN, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000658 LVILatticeVal Result; // Start Undefined.
659
660 // Loop over all of our predecessors, merging what we know from them into
661 // result.
662 bool EdgesMissing = false;
663 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
664 BasicBlock *PhiBB = PN->getIncomingBlock(i);
665 Value *PhiVal = PN->getIncomingValue(i);
666 LVILatticeVal EdgeResult;
667 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
668 if (EdgesMissing)
669 continue;
670
671 Result.mergeIn(EdgeResult);
672
673 // If we hit overdefined, exit early. The BlockVals entry is already set
674 // to overdefined.
675 if (Result.isOverdefined()) {
676 DEBUG(dbgs() << " compute BB '" << BB->getName()
677 << "' - overdefined because of pred.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000678
679 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000680 return true;
681 }
682 }
683 if (EdgesMissing)
684 return false;
685
686 // Return the merged value, which is more precise than 'overdefined'.
687 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson61863942010-12-20 18:18:16 +0000688 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000689 return true;
690}
691
Owen Anderson61863942010-12-20 18:18:16 +0000692bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
693 Instruction *BBI,
Nick Lewycky90862ee2010-12-18 01:00:40 +0000694 BasicBlock *BB) {
Owen Andersonb81fd622010-08-18 21:11:37 +0000695 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000696 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000697 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000698 return false;
699 }
700
Nick Lewycky90862ee2010-12-18 01:00:40 +0000701 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Owen Andersonb81fd622010-08-18 21:11:37 +0000702 if (!LHSVal.isConstantRange()) {
Owen Anderson61863942010-12-20 18:18:16 +0000703 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000704 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000705 }
706
Owen Andersonb81fd622010-08-18 21:11:37 +0000707 ConstantRange LHSRange = LHSVal.getConstantRange();
708 ConstantRange RHSRange(1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000709 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Andersonb81fd622010-08-18 21:11:37 +0000710 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000711 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
712 RHSRange = ConstantRange(RHS->getValue());
713 } else {
Owen Anderson61863942010-12-20 18:18:16 +0000714 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000715 return true;
Owen Anderson59b06dc2010-08-24 07:55:44 +0000716 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000717 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000718
Owen Andersonb81fd622010-08-18 21:11:37 +0000719 // NOTE: We're currently limited by the set of operations that ConstantRange
720 // can evaluate symbolically. Enhancing that set will allows us to analyze
721 // more definitions.
Owen Anderson61863942010-12-20 18:18:16 +0000722 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000723 switch (BBI->getOpcode()) {
724 case Instruction::Add:
725 Result.markConstantRange(LHSRange.add(RHSRange));
726 break;
727 case Instruction::Sub:
728 Result.markConstantRange(LHSRange.sub(RHSRange));
729 break;
730 case Instruction::Mul:
731 Result.markConstantRange(LHSRange.multiply(RHSRange));
732 break;
733 case Instruction::UDiv:
734 Result.markConstantRange(LHSRange.udiv(RHSRange));
735 break;
736 case Instruction::Shl:
737 Result.markConstantRange(LHSRange.shl(RHSRange));
738 break;
739 case Instruction::LShr:
740 Result.markConstantRange(LHSRange.lshr(RHSRange));
741 break;
742 case Instruction::Trunc:
743 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
744 break;
745 case Instruction::SExt:
746 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
747 break;
748 case Instruction::ZExt:
749 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
750 break;
751 case Instruction::BitCast:
752 Result.markConstantRange(LHSRange);
753 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000754 case Instruction::And:
755 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
756 break;
757 case Instruction::Or:
758 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
759 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000760
761 // Unhandled instructions are overdefined.
762 default:
763 DEBUG(dbgs() << " compute BB '" << BB->getName()
764 << "' - overdefined because inst def found.\n");
765 Result.markOverdefined();
766 break;
767 }
768
Owen Anderson61863942010-12-20 18:18:16 +0000769 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000770 return true;
Chris Lattner10f2d132009-11-11 00:22:30 +0000771}
772
Nuno Lopese4413942012-06-28 01:16:18 +0000773/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
774/// Val is not constrained on the edge.
775static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
776 BasicBlock *BBTo, LVILatticeVal &Result) {
Chris Lattner800c47e2009-11-15 20:02:12 +0000777 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
778 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000779 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
780 // If this is a conditional branch and only one successor goes to BBTo, then
781 // we maybe able to infer something from the condition.
782 if (BI->isConditional() &&
783 BI->getSuccessor(0) != BI->getSuccessor(1)) {
784 bool isTrueDest = BI->getSuccessor(0) == BBTo;
785 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
786 "BBTo isn't a successor of BBFrom");
787
788 // If V is the condition of the branch itself, then we know exactly what
789 // it is.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000790 if (BI->getCondition() == Val) {
791 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000792 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000793 return true;
794 }
Chris Lattner16976522009-11-11 22:48:44 +0000795
796 // If the condition of the branch is an equality comparison, we may be
797 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000798 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
Benjamin Kramer8979e5f2012-03-02 15:34:43 +0000799 if (ICI && isa<Constant>(ICI->getOperand(1))) {
800 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
Owen Anderson2d0f2472010-08-11 04:24:25 +0000801 // We know that V has the RHS constant if this is a true SETEQ or
802 // false SETNE.
803 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000804 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
805 else
806 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
807 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000808 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000809
Benjamin Kramer8979e5f2012-03-02 15:34:43 +0000810 // Recognize the range checking idiom that InstCombine produces.
811 // (X-C1) u< C2 --> [C1, C1+C2)
812 ConstantInt *NegOffset = 0;
813 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
814 match(ICI->getOperand(0), m_Add(m_Specific(Val),
815 m_ConstantInt(NegOffset)));
816
817 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
818 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
Owen Anderson2d0f2472010-08-11 04:24:25 +0000819 // Calculate the range of values that would satisfy the comparison.
Nuno Lopes97f87ab2012-05-17 23:04:08 +0000820 ConstantRange CmpRange(CI->getValue());
Owen Anderson2d0f2472010-08-11 04:24:25 +0000821 ConstantRange TrueValues =
822 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000823
Benjamin Kramer8979e5f2012-03-02 15:34:43 +0000824 if (NegOffset) // Apply the offset from above.
825 TrueValues = TrueValues.subtract(NegOffset->getValue());
826
Owen Anderson2d0f2472010-08-11 04:24:25 +0000827 // If we're interested in the false dest, invert the condition.
828 if (!isTrueDest) TrueValues = TrueValues.inverse();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000829
Nuno Lopese4413942012-06-28 01:16:18 +0000830 Result = LVILatticeVal::getRange(TrueValues);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000831 return true;
Owen Anderson2d0f2472010-08-11 04:24:25 +0000832 }
833 }
Chris Lattner16976522009-11-11 22:48:44 +0000834 }
835 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000836
837 // If the edge was formed by a switch on the value, then we may know exactly
838 // what it is.
839 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopese5048772012-06-28 16:13:37 +0000840 if (SI->getCondition() != Val)
841 return false;
842
843 bool DefaultCase = SI->getDefaultDest() == BBTo;
844 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
845 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
846
847 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
848 i != e; ++i) {
849 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Ren408853e2012-09-05 23:45:58 +0000850 if (DefaultCase) {
851 // It is possible that the default destination is the destination of
852 // some cases. There is no need to perform difference for those cases.
853 if (i.getCaseSuccessor() != BBTo)
854 EdgesVals = EdgesVals.difference(EdgeVal);
855 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopes90255a82012-05-18 21:02:10 +0000856 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner800c47e2009-11-15 20:02:12 +0000857 }
Nuno Lopese5048772012-06-28 16:13:37 +0000858 Result = LVILatticeVal::getRange(EdgesVals);
859 return true;
Chris Lattner800c47e2009-11-15 20:02:12 +0000860 }
Nuno Lopese4413942012-06-28 01:16:18 +0000861 return false;
862}
863
864/// \brief Compute the value of Val on the edge BBFrom -> BBTo, or the value at
865/// the basic block if the edge does not constraint Val.
866bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
867 BasicBlock *BBTo, LVILatticeVal &Result) {
868 // If already a constant, there is nothing to compute.
869 if (Constant *VC = dyn_cast<Constant>(Val)) {
870 Result = LVILatticeVal::get(VC);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000871 return true;
872 }
Nuno Lopese4413942012-06-28 01:16:18 +0000873
874 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
875 if (!Result.isConstantRange() ||
876 Result.getConstantRange().getSingleElement())
877 return true;
878
879 // FIXME: this check should be moved to the beginning of the function when
880 // LVI better supports recursive values. Even for the single value case, we
881 // can intersect to detect dead code (an empty range).
882 if (!hasBlockValue(Val, BBFrom)) {
883 BlockValueStack.push(std::make_pair(BBFrom, Val));
884 return false;
885 }
886
887 // Try to intersect ranges of the BB and the constraint on the edge.
888 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
889 if (!InBlock.isConstantRange())
890 return true;
891
892 ConstantRange Range =
893 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
894 Result = LVILatticeVal::getRange(Range);
895 return true;
896 }
897
898 if (!hasBlockValue(Val, BBFrom)) {
899 BlockValueStack.push(std::make_pair(BBFrom, Val));
900 return false;
901 }
902
903 // if we couldn't compute the value on the edge, use the value from the BB
904 Result = getBlockValue(Val, BBFrom);
905 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000906}
907
Chris Lattner2c5adf82009-11-15 19:59:49 +0000908LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000909 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000910 << BB->getName() << "'\n");
911
Owen Andersone68713a2011-01-05 23:26:22 +0000912 BlockValueStack.push(std::make_pair(BB, V));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000913 solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000914 LVILatticeVal Result = getBlockValue(V, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000915
David Greene5d93a1f2009-12-23 20:43:58 +0000916 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000917 return Result;
918}
Chris Lattner16976522009-11-11 22:48:44 +0000919
Chris Lattner2c5adf82009-11-15 19:59:49 +0000920LVILatticeVal LazyValueInfoCache::
921getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000922 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000923 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000924
Nick Lewycky90862ee2010-12-18 01:00:40 +0000925 LVILatticeVal Result;
926 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
927 solve();
928 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
929 (void)WasFastQuery;
930 assert(WasFastQuery && "More work to do after problem solved?");
931 }
932
David Greene5d93a1f2009-12-23 20:43:58 +0000933 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000934 return Result;
935}
936
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000937void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
938 BasicBlock *NewSucc) {
939 // When an edge in the graph has been threaded, values that we could not
940 // determine a value for before (i.e. were marked overdefined) may be possible
941 // to solve now. We do NOT try to proactively update these values. Instead,
942 // we clear their entries from the cache, and allow lazy updating to recompute
943 // them when needed.
944
945 // The updating process is fairly simple: we need to dropped cached info
946 // for all values that were marked overdefined in OldSucc, and for those same
947 // values in any successor of OldSucc (except NewSucc) in which they were
948 // also marked overdefined.
949 std::vector<BasicBlock*> worklist;
950 worklist.push_back(OldSucc);
951
Owen Anderson9a65dc92010-07-27 23:58:11 +0000952 DenseSet<Value*> ClearSet;
Owen Anderson89778462011-01-05 21:15:29 +0000953 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
954 E = OverDefinedCache.end(); I != E; ++I) {
Owen Anderson9a65dc92010-07-27 23:58:11 +0000955 if (I->first == OldSucc)
956 ClearSet.insert(I->second);
957 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000958
959 // Use a worklist to perform a depth-first search of OldSucc's successors.
960 // NOTE: We do not need a visited list since any blocks we have already
961 // visited will have had their overdefined markers cleared already, and we
962 // thus won't loop to their successors.
963 while (!worklist.empty()) {
964 BasicBlock *ToUpdate = worklist.back();
965 worklist.pop_back();
966
967 // Skip blocks only accessible through NewSucc.
968 if (ToUpdate == NewSucc) continue;
969
970 bool changed = false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000971 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000972 I != E; ++I) {
973 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson89778462011-01-05 21:15:29 +0000974 DenseSet<OverDefinedPairTy>::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000975 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
976 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000977
Owen Anderson9a65dc92010-07-27 23:58:11 +0000978 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000979 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000980 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000981
Owen Anderson9a65dc92010-07-27 23:58:11 +0000982 assert(CI != Entry.end() && "Couldn't find entry to update?");
983 Entry.erase(CI);
984 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000985
Owen Anderson9a65dc92010-07-27 23:58:11 +0000986 // If we removed anything, then we potentially need to update
987 // blocks successors too.
988 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000989 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000990
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000991 if (!changed) continue;
992
993 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
994 }
995}
996
Chris Lattner2c5adf82009-11-15 19:59:49 +0000997//===----------------------------------------------------------------------===//
998// LazyValueInfo Impl
999//===----------------------------------------------------------------------===//
1000
Chris Lattner2c5adf82009-11-15 19:59:49 +00001001/// getCache - This lazily constructs the LazyValueInfoCache.
1002static LazyValueInfoCache &getCache(void *&PImpl) {
1003 if (!PImpl)
1004 PImpl = new LazyValueInfoCache();
1005 return *static_cast<LazyValueInfoCache*>(PImpl);
1006}
1007
Owen Anderson00ac77e2010-08-18 18:39:01 +00001008bool LazyValueInfo::runOnFunction(Function &F) {
1009 if (PImpl)
1010 getCache(PImpl).clear();
Chad Rosieraab8e282011-12-02 01:26:24 +00001011
Owen Anderson00ac77e2010-08-18 18:39:01 +00001012 TD = getAnalysisIfAvailable<TargetData>();
Chad Rosieraab8e282011-12-02 01:26:24 +00001013 TLI = &getAnalysis<TargetLibraryInfo>();
1014
Owen Anderson00ac77e2010-08-18 18:39:01 +00001015 // Fully lazy.
1016 return false;
1017}
1018
Chad Rosieraab8e282011-12-02 01:26:24 +00001019void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1020 AU.setPreservesAll();
1021 AU.addRequired<TargetLibraryInfo>();
1022}
1023
Chris Lattner2c5adf82009-11-15 19:59:49 +00001024void LazyValueInfo::releaseMemory() {
1025 // If the cache was allocated, free it.
1026 if (PImpl) {
1027 delete &getCache(PImpl);
1028 PImpl = 0;
1029 }
1030}
1031
1032Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1033 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1034
Chris Lattner16976522009-11-11 22:48:44 +00001035 if (Result.isConstant())
1036 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001037 if (Result.isConstantRange()) {
Owen Andersonee61fcf2010-08-27 23:29:38 +00001038 ConstantRange CR = Result.getConstantRange();
1039 if (const APInt *SingleVal = CR.getSingleElement())
1040 return ConstantInt::get(V->getContext(), *SingleVal);
1041 }
Chris Lattner16976522009-11-11 22:48:44 +00001042 return 0;
1043}
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001044
Chris Lattner38392bb2009-11-12 01:29:10 +00001045/// getConstantOnEdge - Determine whether the specified value is known to be a
1046/// constant on the specified edge. Return null if not.
1047Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1048 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001049 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +00001050
1051 if (Result.isConstant())
1052 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001053 if (Result.isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +00001054 ConstantRange CR = Result.getConstantRange();
1055 if (const APInt *SingleVal = CR.getSingleElement())
1056 return ConstantInt::get(V->getContext(), *SingleVal);
1057 }
Chris Lattner38392bb2009-11-12 01:29:10 +00001058 return 0;
1059}
1060
Chris Lattnerb52675b2009-11-12 04:36:58 +00001061/// getPredicateOnEdge - Determine whether the specified value comparison
1062/// with a constant is known to be true or false on the specified CFG edge.
1063/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001064LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +00001065LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1066 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001067 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001068
Chris Lattnerb52675b2009-11-12 04:36:58 +00001069 // If we know the value is a constant, evaluate the conditional.
1070 Constant *Res = 0;
1071 if (Result.isConstant()) {
Chad Rosieraab8e282011-12-02 01:26:24 +00001072 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD,
1073 TLI);
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001074 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Chris Lattnerb52675b2009-11-12 04:36:58 +00001075 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +00001076 return Unknown;
1077 }
1078
Owen Anderson9f014062010-08-10 20:03:09 +00001079 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +00001080 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1081 if (!CI) return Unknown;
1082
Owen Anderson9f014062010-08-10 20:03:09 +00001083 ConstantRange CR = Result.getConstantRange();
1084 if (Pred == ICmpInst::ICMP_EQ) {
1085 if (!CR.contains(CI->getValue()))
1086 return False;
1087
1088 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1089 return True;
1090 } else if (Pred == ICmpInst::ICMP_NE) {
1091 if (!CR.contains(CI->getValue()))
1092 return True;
1093
1094 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1095 return False;
1096 }
1097
1098 // Handle more complex predicates.
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001099 ConstantRange TrueValues =
1100 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1101 if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +00001102 return True;
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001103 if (TrueValues.inverse().contains(CR))
1104 return False;
Owen Anderson9f014062010-08-10 20:03:09 +00001105 return Unknown;
1106 }
1107
Chris Lattner2c5adf82009-11-15 19:59:49 +00001108 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +00001109 // If this is an equality comparison, we can try to fold it knowing that
1110 // "V != C1".
1111 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001112 // !C1 == C -> false iff C1 == C.
Chris Lattnerb52675b2009-11-12 04:36:58 +00001113 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chad Rosieraab8e282011-12-02 01:26:24 +00001114 Result.getNotConstant(), C, TD,
1115 TLI);
Chris Lattnerb52675b2009-11-12 04:36:58 +00001116 if (Res->isNullValue())
1117 return False;
1118 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001119 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +00001120 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chad Rosieraab8e282011-12-02 01:26:24 +00001121 Result.getNotConstant(), C, TD,
1122 TLI);
Chris Lattnerb52675b2009-11-12 04:36:58 +00001123 if (Res->isNullValue())
1124 return True;
1125 }
Chris Lattner2c5adf82009-11-15 19:59:49 +00001126 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +00001127 }
1128
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001129 return Unknown;
1130}
1131
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001132void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001133 BasicBlock *NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +00001134 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1135}
1136
1137void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1138 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001139}