blob: 2e834d06af596dc4aded9e6cec267e5c601cf673 [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"
20#include "llvm/Analysis/ConstantFolding.h"
21#include "llvm/Target/TargetData.h"
Chris Lattner16976522009-11-11 22:48:44 +000022#include "llvm/Support/CFG.h"
Owen Anderson5be2e782010-08-05 22:59:19 +000023#include "llvm/Support/ConstantRange.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000024#include "llvm/Support/Debug.h"
Chris Lattner16976522009-11-11 22:48:44 +000025#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000026#include "llvm/Support/ValueHandle.h"
Chris Lattner16976522009-11-11 22:48:44 +000027#include "llvm/ADT/DenseMap.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattnere5642812009-11-15 20:00:52 +000029#include "llvm/ADT/STLExtras.h"
Owen Anderson6bcd3a02010-09-07 19:16:25 +000030#include <map>
31#include <set>
Nick Lewycky90862ee2010-12-18 01:00:40 +000032#include <stack>
Chris Lattner10f2d132009-11-11 00:22:30 +000033using namespace llvm;
34
35char LazyValueInfo::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000036INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
Owen Andersonce665bd2010-10-07 22:25:06 +000037 "Lazy Value Information Analysis", false, true)
Chris Lattner10f2d132009-11-11 00:22:30 +000038
39namespace llvm {
40 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
41}
42
Chris Lattnercc4d3b22009-11-11 02:08:33 +000043
44//===----------------------------------------------------------------------===//
45// LVILatticeVal
46//===----------------------------------------------------------------------===//
47
48/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
49/// value.
50///
51/// FIXME: This is basically just for bringup, this can be made a lot more rich
52/// in the future.
53///
54namespace {
55class LVILatticeVal {
56 enum LatticeValueTy {
Nick Lewycky69bfdf52010-12-15 18:57:18 +000057 /// undefined - This Value has no known value yet.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000058 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000059
Nick Lewycky69bfdf52010-12-15 18:57:18 +000060 /// constant - This Value has a specific constant value.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000061 constant,
Nick Lewycky69bfdf52010-12-15 18:57:18 +000062 /// notconstant - This Value is known to not have the specified value.
Chris Lattnerb52675b2009-11-12 04:36:58 +000063 notconstant,
64
Nick Lewycky69bfdf52010-12-15 18:57:18 +000065 /// constantrange - The Value falls within this range.
Owen Anderson5be2e782010-08-05 22:59:19 +000066 constantrange,
67
Nick Lewycky69bfdf52010-12-15 18:57:18 +000068 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnercc4d3b22009-11-11 02:08:33 +000069 /// it has a value.
70 overdefined
71 };
72
73 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000074 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000075 LatticeValueTy Tag;
76 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000077 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000078
79public:
Owen Anderson5be2e782010-08-05 22:59:19 +000080 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000081
Chris Lattner16976522009-11-11 22:48:44 +000082 static LVILatticeVal get(Constant *C) {
83 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000084 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000085 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000086 return Res;
87 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000088 static LVILatticeVal getNot(Constant *C) {
89 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000090 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000091 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000092 return Res;
93 }
Owen Anderson625051b2010-08-10 23:20:01 +000094 static LVILatticeVal getRange(ConstantRange CR) {
95 LVILatticeVal Res;
96 Res.markConstantRange(CR);
97 return Res;
98 }
Chris Lattner16976522009-11-11 22:48:44 +000099
Owen Anderson5be2e782010-08-05 22:59:19 +0000100 bool isUndefined() const { return Tag == undefined; }
101 bool isConstant() const { return Tag == constant; }
102 bool isNotConstant() const { return Tag == notconstant; }
103 bool isConstantRange() const { return Tag == constantrange; }
104 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000105
106 Constant *getConstant() const {
107 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000108 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000109 }
110
Chris Lattnerb52675b2009-11-12 04:36:58 +0000111 Constant *getNotConstant() const {
112 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000113 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000114 }
115
Owen Anderson5be2e782010-08-05 22:59:19 +0000116 ConstantRange getConstantRange() const {
117 assert(isConstantRange() &&
118 "Cannot get the constant-range of a non-constant-range!");
119 return Range;
120 }
121
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000122 /// markOverdefined - Return true if this is a change in status.
123 bool markOverdefined() {
124 if (isOverdefined())
125 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000126 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000127 return true;
128 }
129
130 /// markConstant - Return true if this is a change in status.
131 bool markConstant(Constant *V) {
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000132 assert(V && "Marking constant with NULL");
133 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
134 return markConstantRange(ConstantRange(CI->getValue()));
135 if (isa<UndefValue>(V))
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000136 return false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000137
138 assert((!isConstant() || getConstant() == V) &&
139 "Marking constant with different value");
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000140 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000141 Tag = constant;
Owen Andersondb78d732010-08-05 22:10:46 +0000142 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000143 return true;
144 }
145
Chris Lattnerb52675b2009-11-12 04:36:58 +0000146 /// markNotConstant - Return true if this is a change in status.
147 bool markNotConstant(Constant *V) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000148 assert(V && "Marking constant with NULL");
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000149 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
150 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
151 if (isa<UndefValue>(V))
152 return false;
153
154 assert((!isConstant() || getConstant() != V) &&
155 "Marking constant !constant with same value");
156 assert((!isNotConstant() || getNotConstant() == V) &&
157 "Marking !constant with different value");
158 assert(isUndefined() || isConstant());
159 Tag = notconstant;
Owen Andersondb78d732010-08-05 22:10:46 +0000160 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000161 return true;
162 }
163
Owen Anderson5be2e782010-08-05 22:59:19 +0000164 /// markConstantRange - Return true if this is a change in status.
165 bool markConstantRange(const ConstantRange NewR) {
166 if (isConstantRange()) {
167 if (NewR.isEmptySet())
168 return markOverdefined();
169
Owen Anderson5be2e782010-08-05 22:59:19 +0000170 bool changed = Range == NewR;
171 Range = NewR;
172 return changed;
173 }
174
175 assert(isUndefined());
176 if (NewR.isEmptySet())
177 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000178
179 Tag = constantrange;
180 Range = NewR;
181 return true;
182 }
183
Chris Lattner16976522009-11-11 22:48:44 +0000184 /// mergeIn - Merge the specified lattice value into this one, updating this
185 /// one and returning true if anything changed.
186 bool mergeIn(const LVILatticeVal &RHS) {
187 if (RHS.isUndefined() || isOverdefined()) return false;
188 if (RHS.isOverdefined()) return markOverdefined();
189
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000190 if (isUndefined()) {
191 Tag = RHS.Tag;
192 Val = RHS.Val;
193 Range = RHS.Range;
194 return true;
Chris Lattnerf496e792009-11-12 04:57:13 +0000195 }
196
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000197 if (isConstant()) {
198 if (RHS.isConstant()) {
199 if (Val == RHS.Val)
200 return false;
201 return markOverdefined();
202 }
203
204 if (RHS.isNotConstant()) {
205 if (Val == RHS.Val)
206 return markOverdefined();
207
208 // Unless we can prove that the two Constants are different, we must
209 // move to overdefined.
210 // FIXME: use TargetData for smarter constant folding.
211 if (ConstantInt *Res = dyn_cast<ConstantInt>(
212 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
213 getConstant(),
214 RHS.getNotConstant())))
215 if (Res->isOne())
216 return markNotConstant(RHS.getNotConstant());
217
218 return markOverdefined();
219 }
220
221 // RHS is a ConstantRange, LHS is a non-integer Constant.
222
223 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
224 // a function. The correct result is to pick up RHS.
225
Chris Lattner16976522009-11-11 22:48:44 +0000226 return markOverdefined();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000227 }
228
229 if (isNotConstant()) {
230 if (RHS.isConstant()) {
231 if (Val == RHS.Val)
232 return markOverdefined();
233
234 // Unless we can prove that the two Constants are different, we must
235 // move to overdefined.
236 // FIXME: use TargetData for smarter constant folding.
237 if (ConstantInt *Res = dyn_cast<ConstantInt>(
238 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
239 getNotConstant(),
240 RHS.getConstant())))
241 if (Res->isOne())
242 return false;
243
244 return markOverdefined();
245 }
246
247 if (RHS.isNotConstant()) {
248 if (Val == RHS.Val)
249 return false;
250 return markOverdefined();
251 }
252
253 return markOverdefined();
254 }
255
256 assert(isConstantRange() && "New LVILattice type?");
257 if (!RHS.isConstantRange())
258 return markOverdefined();
259
260 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
261 if (NewR.isFullSet())
262 return markOverdefined();
263 return markConstantRange(NewR);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000264 }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000265};
266
267} // end anonymous namespace.
268
Chris Lattner16976522009-11-11 22:48:44 +0000269namespace llvm {
270raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
271 if (Val.isUndefined())
272 return OS << "undefined";
273 if (Val.isOverdefined())
274 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000275
276 if (Val.isNotConstant())
277 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000278 else if (Val.isConstantRange())
279 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
280 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000281 return OS << "constant<" << *Val.getConstant() << '>';
282}
283}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000284
285//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000286// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000287//===----------------------------------------------------------------------===//
288
Chris Lattner2c5adf82009-11-15 19:59:49 +0000289namespace {
290 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
291 /// maintains information about queries across the clients' queries.
292 class LazyValueInfoCache {
Owen Anderson81881bc2010-07-30 20:56:07 +0000293 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000294 /// ValueCacheEntryTy - This is all of the cached block information for
295 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
296 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000297 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000298
Owen Anderson81881bc2010-07-30 20:56:07 +0000299 private:
Nick Lewycky90862ee2010-12-18 01:00:40 +0000300 /// LVIValueHandle - A callback value handle update the cache when
301 /// values are erased.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000302 struct LVIValueHandle : public CallbackVH {
303 LazyValueInfoCache *Parent;
304
305 LVIValueHandle(Value *V, LazyValueInfoCache *P)
306 : CallbackVH(V), Parent(P) { }
307
308 void deleted();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000309 void allUsesReplacedWith(Value *V) {
Owen Anderson7f9cb742010-07-30 23:59:40 +0000310 deleted();
311 }
Owen Anderson7f9cb742010-07-30 23:59:40 +0000312 };
313
Chris Lattner2c5adf82009-11-15 19:59:49 +0000314 /// ValueCache - This is all of the cached information for all values,
315 /// mapped from Value* to key information.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000316 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000317
318 /// OverDefinedCache - This tracks, on a per-block basis, the set of
319 /// values that are over-defined at the end of that block. This is required
320 /// for cache updating.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000321 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000322
Owen Andersonf33b3022010-12-09 06:14:58 +0000323 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000324 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
325 LVILatticeVal &Result);
326 bool hasBlockValue(Value *Val, BasicBlock *BB);
327
328 // These methods process one work item and may add more. A false value
329 // returned means that the work item was not completely processed and must
330 // be revisited after going through the new items.
331 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson61863942010-12-20 18:18:16 +0000332 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
333 Value *Val, BasicBlock *BB);
334 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
335 PHINode *PN, BasicBlock *BB);
336 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
337 Instruction *BBI, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000338
339 void solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000340
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000341 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonf33b3022010-12-09 06:14:58 +0000342 return ValueCache[LVIValueHandle(V, this)];
343 }
344
345 LVILatticeVal setBlockValue(Value *V, BasicBlock *BB, LVILatticeVal L,
346 ValueCacheEntryTy &Cache) {
347 if (L.isOverdefined()) OverDefinedCache.insert(std::make_pair(BB, V));
348 return Cache[BB] = L;
349 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000350 LVILatticeVal setBlockValue(Value *V, BasicBlock *BB, LVILatticeVal L) {
351 return setBlockValue(V, BB, L, lookup(V));
352 }
Owen Andersonf33b3022010-12-09 06:14:58 +0000353
Nick Lewycky90862ee2010-12-18 01:00:40 +0000354 struct BlockStackEntry {
355 BlockStackEntry(Value *Val, BasicBlock *BB) : Val(Val), BB(BB) {}
356 Value *Val;
357 BasicBlock *BB;
358 };
359 std::stack<BlockStackEntry> block_value_stack;
360
Chris Lattner2c5adf82009-11-15 19:59:49 +0000361 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000362 /// getValueInBlock - This is the query interface to determine the lattice
363 /// value for the specified Value* at the end of the specified block.
364 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
365
366 /// getValueOnEdge - This is the query interface to determine the lattice
367 /// value for the specified Value* that is true on the specified edge.
368 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000369
370 /// threadEdge - This is the update interface to inform the cache that an
371 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
372 /// NewSucc.
373 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000374
375 /// eraseBlock - This is part of the update interface to inform the cache
376 /// that a block has been deleted.
377 void eraseBlock(BasicBlock *BB);
378
379 /// clear - Empty the cache.
380 void clear() {
381 ValueCache.clear();
382 OverDefinedCache.clear();
383 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000384 };
385} // end anonymous namespace
386
Owen Anderson7f9cb742010-07-30 23:59:40 +0000387void LazyValueInfoCache::LVIValueHandle::deleted() {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000388 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000389 I = Parent->OverDefinedCache.begin(),
390 E = Parent->OverDefinedCache.end();
391 I != E; ) {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000392 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000393 ++I;
394 if (tmp->second == getValPtr())
395 Parent->OverDefinedCache.erase(tmp);
396 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000397
398 // This erasure deallocates *this, so it MUST happen after we're done
399 // using any and all members of *this.
400 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000401}
402
Owen Anderson00ac77e2010-08-18 18:39:01 +0000403void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
404 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
405 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
406 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
407 ++I;
408 if (tmp->first == BB)
409 OverDefinedCache.erase(tmp);
410 }
411
412 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
413 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
414 I->second.erase(BB);
415}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000416
Nick Lewycky90862ee2010-12-18 01:00:40 +0000417void LazyValueInfoCache::solve() {
418 while (!block_value_stack.empty()) {
419 BlockStackEntry &e = block_value_stack.top();
420 if (solveBlockValue(e.Val, e.BB))
421 block_value_stack.pop();
422 }
423}
424
425bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
426 // If already a constant, there is nothing to compute.
427 if (isa<Constant>(Val))
428 return true;
429
430 return lookup(Val).count(BB);
431}
432
Owen Andersonf33b3022010-12-09 06:14:58 +0000433LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000434 // If already a constant, there is nothing to compute.
435 if (Constant *VC = dyn_cast<Constant>(Val))
436 return LVILatticeVal::get(VC);
437
438 return lookup(Val)[BB];
439}
440
441bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
442 if (isa<Constant>(Val))
443 return true;
444
Owen Andersonf33b3022010-12-09 06:14:58 +0000445 ValueCacheEntryTy &Cache = lookup(Val);
446 LVILatticeVal &BBLV = Cache[BB];
Nick Lewycky90862ee2010-12-18 01:00:40 +0000447
Chris Lattner2c5adf82009-11-15 19:59:49 +0000448 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000449 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000450 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Nick Lewycky90862ee2010-12-18 01:00:40 +0000451 return true;
Chris Lattnere5642812009-11-15 20:00:52 +0000452 }
453
Chris Lattner2c5adf82009-11-15 19:59:49 +0000454 // Otherwise, this is the first time we're seeing this block. Reset the
455 // lattice value to overdefined, so that cycles will terminate and be
456 // conservatively correct.
457 BBLV.markOverdefined();
458
Chris Lattner2c5adf82009-11-15 19:59:49 +0000459 Instruction *BBI = dyn_cast<Instruction>(Val);
460 if (BBI == 0 || BBI->getParent() != BB) {
Owen Anderson61863942010-12-20 18:18:16 +0000461 return solveBlockValueNonLocal(BBLV, Val, BB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000462 }
Chris Lattnere5642812009-11-15 20:00:52 +0000463
Nick Lewycky90862ee2010-12-18 01:00:40 +0000464 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson61863942010-12-20 18:18:16 +0000465 return solveBlockValuePHINode(BBLV, PN, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000466 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000467
468 // We can only analyze the definitions of certain classes of instructions
469 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000470 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000471 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
472 !BBI->getType()->isIntegerTy()) {
473 DEBUG(dbgs() << " compute BB '" << BB->getName()
474 << "' - overdefined because inst def found.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000475 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000476 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000477 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000478
Owen Andersonb81fd622010-08-18 21:11:37 +0000479 // FIXME: We're currently limited to binops with a constant RHS. This should
480 // be improved.
481 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
482 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
483 DEBUG(dbgs() << " compute BB '" << BB->getName()
484 << "' - overdefined because inst def found.\n");
485
Owen Anderson61863942010-12-20 18:18:16 +0000486 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000487 return true;
488 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000489
Owen Anderson61863942010-12-20 18:18:16 +0000490 return solveBlockValueConstantRange(BBLV, BBI, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000491}
492
493static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
494 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
495 return L->getPointerAddressSpace() == 0 &&
496 GetUnderlyingObject(L->getPointerOperand()) ==
497 GetUnderlyingObject(Ptr);
498 }
499 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
500 return S->getPointerAddressSpace() == 0 &&
501 GetUnderlyingObject(S->getPointerOperand()) ==
502 GetUnderlyingObject(Ptr);
503 }
504 // FIXME: llvm.memset, etc.
505 return false;
506}
507
Owen Anderson61863942010-12-20 18:18:16 +0000508bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
509 Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000510 LVILatticeVal Result; // Start Undefined.
511
512 // If this is a pointer, and there's a load from that pointer in this BB,
513 // then we know that the pointer can't be NULL.
514 bool NotNull = false;
515 if (Val->getType()->isPointerTy()) {
516 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
517 if (InstructionDereferencesPointer(BI, Val)) {
518 NotNull = true;
519 break;
520 }
521 }
522 }
523
524 // If this is the entry block, we must be asking about an argument. The
525 // value is overdefined.
526 if (BB == &BB->getParent()->getEntryBlock()) {
527 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
528 if (NotNull) {
529 const PointerType *PTy = cast<PointerType>(Val->getType());
530 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
531 } else {
532 Result.markOverdefined();
533 }
Owen Anderson61863942010-12-20 18:18:16 +0000534 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000535 return true;
536 }
537
538 // Loop over all of our predecessors, merging what we know from them into
539 // result.
540 bool EdgesMissing = false;
541 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
542 LVILatticeVal EdgeResult;
543 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
544 if (EdgesMissing)
545 continue;
546
547 Result.mergeIn(EdgeResult);
548
549 // If we hit overdefined, exit early. The BlockVals entry is already set
550 // to overdefined.
551 if (Result.isOverdefined()) {
552 DEBUG(dbgs() << " compute BB '" << BB->getName()
553 << "' - overdefined because of pred.\n");
554 // If we previously determined that this is a pointer that can't be null
555 // then return that rather than giving up entirely.
556 if (NotNull) {
557 const PointerType *PTy = cast<PointerType>(Val->getType());
558 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
559 }
Owen Anderson61863942010-12-20 18:18:16 +0000560
561 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000562 return true;
563 }
564 }
565 if (EdgesMissing)
566 return false;
567
568 // Return the merged value, which is more precise than 'overdefined'.
569 assert(!Result.isOverdefined());
Owen Anderson61863942010-12-20 18:18:16 +0000570 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000571 return true;
572}
573
Owen Anderson61863942010-12-20 18:18:16 +0000574bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
575 PHINode *PN, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000576 LVILatticeVal Result; // Start Undefined.
577
578 // Loop over all of our predecessors, merging what we know from them into
579 // result.
580 bool EdgesMissing = false;
581 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
582 BasicBlock *PhiBB = PN->getIncomingBlock(i);
583 Value *PhiVal = PN->getIncomingValue(i);
584 LVILatticeVal EdgeResult;
585 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
586 if (EdgesMissing)
587 continue;
588
589 Result.mergeIn(EdgeResult);
590
591 // If we hit overdefined, exit early. The BlockVals entry is already set
592 // to overdefined.
593 if (Result.isOverdefined()) {
594 DEBUG(dbgs() << " compute BB '" << BB->getName()
595 << "' - overdefined because of pred.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000596
597 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000598 return true;
599 }
600 }
601 if (EdgesMissing)
602 return false;
603
604 // Return the merged value, which is more precise than 'overdefined'.
605 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson61863942010-12-20 18:18:16 +0000606 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000607 return true;
608}
609
Owen Anderson61863942010-12-20 18:18:16 +0000610bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
611 Instruction *BBI,
Nick Lewycky90862ee2010-12-18 01:00:40 +0000612 BasicBlock *BB) {
Owen Andersonb81fd622010-08-18 21:11:37 +0000613 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000614 if (!hasBlockValue(BBI->getOperand(0), BB)) {
615 block_value_stack.push(BlockStackEntry(BBI->getOperand(0), BB));
616 return false;
617 }
618
Nick Lewycky90862ee2010-12-18 01:00:40 +0000619 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Owen Andersonb81fd622010-08-18 21:11:37 +0000620 if (!LHSVal.isConstantRange()) {
Owen Anderson61863942010-12-20 18:18:16 +0000621 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000622 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000623 }
624
Owen Andersonb81fd622010-08-18 21:11:37 +0000625 ConstantRange LHSRange = LHSVal.getConstantRange();
626 ConstantRange RHSRange(1);
627 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
628 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000629 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
630 RHSRange = ConstantRange(RHS->getValue());
631 } else {
Owen Anderson61863942010-12-20 18:18:16 +0000632 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000633 return true;
Owen Anderson59b06dc2010-08-24 07:55:44 +0000634 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000635 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000636
Owen Andersonb81fd622010-08-18 21:11:37 +0000637 // NOTE: We're currently limited by the set of operations that ConstantRange
638 // can evaluate symbolically. Enhancing that set will allows us to analyze
639 // more definitions.
Owen Anderson61863942010-12-20 18:18:16 +0000640 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000641 switch (BBI->getOpcode()) {
642 case Instruction::Add:
643 Result.markConstantRange(LHSRange.add(RHSRange));
644 break;
645 case Instruction::Sub:
646 Result.markConstantRange(LHSRange.sub(RHSRange));
647 break;
648 case Instruction::Mul:
649 Result.markConstantRange(LHSRange.multiply(RHSRange));
650 break;
651 case Instruction::UDiv:
652 Result.markConstantRange(LHSRange.udiv(RHSRange));
653 break;
654 case Instruction::Shl:
655 Result.markConstantRange(LHSRange.shl(RHSRange));
656 break;
657 case Instruction::LShr:
658 Result.markConstantRange(LHSRange.lshr(RHSRange));
659 break;
660 case Instruction::Trunc:
661 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
662 break;
663 case Instruction::SExt:
664 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
665 break;
666 case Instruction::ZExt:
667 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
668 break;
669 case Instruction::BitCast:
670 Result.markConstantRange(LHSRange);
671 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000672 case Instruction::And:
673 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
674 break;
675 case Instruction::Or:
676 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
677 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000678
679 // Unhandled instructions are overdefined.
680 default:
681 DEBUG(dbgs() << " compute BB '" << BB->getName()
682 << "' - overdefined because inst def found.\n");
683 Result.markOverdefined();
684 break;
685 }
686
Owen Anderson61863942010-12-20 18:18:16 +0000687 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000688 return true;
Chris Lattner10f2d132009-11-11 00:22:30 +0000689}
690
Chris Lattner800c47e2009-11-15 20:02:12 +0000691/// getEdgeValue - This method attempts to infer more complex
Nick Lewycky90862ee2010-12-18 01:00:40 +0000692bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
693 BasicBlock *BBTo, LVILatticeVal &Result) {
694 // If already a constant, there is nothing to compute.
695 if (Constant *VC = dyn_cast<Constant>(Val)) {
696 Result = LVILatticeVal::get(VC);
697 return true;
698 }
699
Chris Lattner800c47e2009-11-15 20:02:12 +0000700 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
701 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000702 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
703 // If this is a conditional branch and only one successor goes to BBTo, then
704 // we maybe able to infer something from the condition.
705 if (BI->isConditional() &&
706 BI->getSuccessor(0) != BI->getSuccessor(1)) {
707 bool isTrueDest = BI->getSuccessor(0) == BBTo;
708 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
709 "BBTo isn't a successor of BBFrom");
710
711 // If V is the condition of the branch itself, then we know exactly what
712 // it is.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000713 if (BI->getCondition() == Val) {
714 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000715 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000716 return true;
717 }
Chris Lattner16976522009-11-11 22:48:44 +0000718
719 // If the condition of the branch is an equality comparison, we may be
720 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000721 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
722 if (ICI && ICI->getOperand(0) == Val &&
723 isa<Constant>(ICI->getOperand(1))) {
724 if (ICI->isEquality()) {
725 // We know that V has the RHS constant if this is a true SETEQ or
726 // false SETNE.
727 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000728 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
729 else
730 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
731 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000732 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000733
Owen Anderson2d0f2472010-08-11 04:24:25 +0000734 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
735 // Calculate the range of values that would satisfy the comparison.
736 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
737 ConstantRange TrueValues =
738 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000739
Owen Anderson2d0f2472010-08-11 04:24:25 +0000740 // If we're interested in the false dest, invert the condition.
741 if (!isTrueDest) TrueValues = TrueValues.inverse();
742
743 // Figure out the possible values of the query BEFORE this branch.
Owen Andersonf33b3022010-12-09 06:14:58 +0000744 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000745 if (!InBlock.isConstantRange()) {
746 Result = LVILatticeVal::getRange(TrueValues);
747 return true;
748 }
749
Owen Anderson2d0f2472010-08-11 04:24:25 +0000750 // Find all potential values that satisfy both the input and output
751 // conditions.
752 ConstantRange PossibleValues =
753 TrueValues.intersectWith(InBlock.getConstantRange());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000754
755 Result = LVILatticeVal::getRange(PossibleValues);
756 return true;
Owen Anderson2d0f2472010-08-11 04:24:25 +0000757 }
758 }
Chris Lattner16976522009-11-11 22:48:44 +0000759 }
760 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000761
762 // If the edge was formed by a switch on the value, then we may know exactly
763 // what it is.
764 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000765 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000766 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000767 if (SI->getDefaultDest() == BBTo) {
Owen Anderson4caef602010-09-02 22:16:52 +0000768 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000769 return true;
Owen Andersondae90c62010-08-24 21:59:42 +0000770 }
771
Chris Lattner800c47e2009-11-15 20:02:12 +0000772 // We only know something if there is exactly one value that goes from
773 // BBFrom to BBTo.
774 unsigned NumEdges = 0;
775 ConstantInt *EdgeVal = 0;
776 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
777 if (SI->getSuccessor(i) != BBTo) continue;
778 if (NumEdges++) break;
779 EdgeVal = SI->getCaseValue(i);
780 }
781 assert(EdgeVal && "Missing successor?");
Nick Lewycky90862ee2010-12-18 01:00:40 +0000782 if (NumEdges == 1) {
783 Result = LVILatticeVal::get(EdgeVal);
784 return true;
785 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000786 }
787 }
Chris Lattner16976522009-11-11 22:48:44 +0000788
789 // Otherwise see if the value is known in the block.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000790 if (hasBlockValue(Val, BBFrom)) {
791 Result = getBlockValue(Val, BBFrom);
792 return true;
793 }
794 block_value_stack.push(BlockStackEntry(Val, BBFrom));
795 return false;
Chris Lattner16976522009-11-11 22:48:44 +0000796}
797
Chris Lattner2c5adf82009-11-15 19:59:49 +0000798LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000799 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000800 << BB->getName() << "'\n");
801
Nick Lewycky90862ee2010-12-18 01:00:40 +0000802 block_value_stack.push(BlockStackEntry(V, BB));
803 solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000804 LVILatticeVal Result = getBlockValue(V, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000805
David Greene5d93a1f2009-12-23 20:43:58 +0000806 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000807 return Result;
808}
Chris Lattner16976522009-11-11 22:48:44 +0000809
Chris Lattner2c5adf82009-11-15 19:59:49 +0000810LVILatticeVal LazyValueInfoCache::
811getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000812 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000813 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000814
Nick Lewycky90862ee2010-12-18 01:00:40 +0000815 LVILatticeVal Result;
816 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
817 solve();
818 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
819 (void)WasFastQuery;
820 assert(WasFastQuery && "More work to do after problem solved?");
821 }
822
David Greene5d93a1f2009-12-23 20:43:58 +0000823 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000824 return Result;
825}
826
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000827void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
828 BasicBlock *NewSucc) {
829 // When an edge in the graph has been threaded, values that we could not
830 // determine a value for before (i.e. were marked overdefined) may be possible
831 // to solve now. We do NOT try to proactively update these values. Instead,
832 // we clear their entries from the cache, and allow lazy updating to recompute
833 // them when needed.
834
835 // The updating process is fairly simple: we need to dropped cached info
836 // for all values that were marked overdefined in OldSucc, and for those same
837 // values in any successor of OldSucc (except NewSucc) in which they were
838 // also marked overdefined.
839 std::vector<BasicBlock*> worklist;
840 worklist.push_back(OldSucc);
841
Owen Anderson9a65dc92010-07-27 23:58:11 +0000842 DenseSet<Value*> ClearSet;
Owen Anderson00ac77e2010-08-18 18:39:01 +0000843 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson9a65dc92010-07-27 23:58:11 +0000844 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
845 if (I->first == OldSucc)
846 ClearSet.insert(I->second);
847 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000848
849 // Use a worklist to perform a depth-first search of OldSucc's successors.
850 // NOTE: We do not need a visited list since any blocks we have already
851 // visited will have had their overdefined markers cleared already, and we
852 // thus won't loop to their successors.
853 while (!worklist.empty()) {
854 BasicBlock *ToUpdate = worklist.back();
855 worklist.pop_back();
856
857 // Skip blocks only accessible through NewSucc.
858 if (ToUpdate == NewSucc) continue;
859
860 bool changed = false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000861 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000862 I != E; ++I) {
863 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson00ac77e2010-08-18 18:39:01 +0000864 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000865 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
866 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000867
Owen Anderson9a65dc92010-07-27 23:58:11 +0000868 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000869 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000870 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000871
Owen Anderson9a65dc92010-07-27 23:58:11 +0000872 assert(CI != Entry.end() && "Couldn't find entry to update?");
873 Entry.erase(CI);
874 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000875
Owen Anderson9a65dc92010-07-27 23:58:11 +0000876 // If we removed anything, then we potentially need to update
877 // blocks successors too.
878 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000879 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000880
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000881 if (!changed) continue;
882
883 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
884 }
885}
886
Chris Lattner2c5adf82009-11-15 19:59:49 +0000887//===----------------------------------------------------------------------===//
888// LazyValueInfo Impl
889//===----------------------------------------------------------------------===//
890
Chris Lattner2c5adf82009-11-15 19:59:49 +0000891/// getCache - This lazily constructs the LazyValueInfoCache.
892static LazyValueInfoCache &getCache(void *&PImpl) {
893 if (!PImpl)
894 PImpl = new LazyValueInfoCache();
895 return *static_cast<LazyValueInfoCache*>(PImpl);
896}
897
Owen Anderson00ac77e2010-08-18 18:39:01 +0000898bool LazyValueInfo::runOnFunction(Function &F) {
899 if (PImpl)
900 getCache(PImpl).clear();
901
902 TD = getAnalysisIfAvailable<TargetData>();
903 // Fully lazy.
904 return false;
905}
906
Chris Lattner2c5adf82009-11-15 19:59:49 +0000907void LazyValueInfo::releaseMemory() {
908 // If the cache was allocated, free it.
909 if (PImpl) {
910 delete &getCache(PImpl);
911 PImpl = 0;
912 }
913}
914
915Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
916 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
917
Chris Lattner16976522009-11-11 22:48:44 +0000918 if (Result.isConstant())
919 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000920 if (Result.isConstantRange()) {
Owen Andersonee61fcf2010-08-27 23:29:38 +0000921 ConstantRange CR = Result.getConstantRange();
922 if (const APInt *SingleVal = CR.getSingleElement())
923 return ConstantInt::get(V->getContext(), *SingleVal);
924 }
Chris Lattner16976522009-11-11 22:48:44 +0000925 return 0;
926}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000927
Chris Lattner38392bb2009-11-12 01:29:10 +0000928/// getConstantOnEdge - Determine whether the specified value is known to be a
929/// constant on the specified edge. Return null if not.
930Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
931 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000932 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +0000933
934 if (Result.isConstant())
935 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000936 if (Result.isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +0000937 ConstantRange CR = Result.getConstantRange();
938 if (const APInt *SingleVal = CR.getSingleElement())
939 return ConstantInt::get(V->getContext(), *SingleVal);
940 }
Chris Lattner38392bb2009-11-12 01:29:10 +0000941 return 0;
942}
943
Chris Lattnerb52675b2009-11-12 04:36:58 +0000944/// getPredicateOnEdge - Determine whether the specified value comparison
945/// with a constant is known to be true or false on the specified CFG edge.
946/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000947LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +0000948LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
949 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000950 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000951
Chris Lattnerb52675b2009-11-12 04:36:58 +0000952 // If we know the value is a constant, evaluate the conditional.
953 Constant *Res = 0;
954 if (Result.isConstant()) {
955 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000956 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Chris Lattnerb52675b2009-11-12 04:36:58 +0000957 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000958 return Unknown;
959 }
960
Owen Anderson9f014062010-08-10 20:03:09 +0000961 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000962 ConstantInt *CI = dyn_cast<ConstantInt>(C);
963 if (!CI) return Unknown;
964
Owen Anderson9f014062010-08-10 20:03:09 +0000965 ConstantRange CR = Result.getConstantRange();
966 if (Pred == ICmpInst::ICMP_EQ) {
967 if (!CR.contains(CI->getValue()))
968 return False;
969
970 if (CR.isSingleElement() && CR.contains(CI->getValue()))
971 return True;
972 } else if (Pred == ICmpInst::ICMP_NE) {
973 if (!CR.contains(CI->getValue()))
974 return True;
975
976 if (CR.isSingleElement() && CR.contains(CI->getValue()))
977 return False;
978 }
979
980 // Handle more complex predicates.
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000981 ConstantRange TrueValues =
982 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
983 if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +0000984 return True;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000985 if (TrueValues.inverse().contains(CR))
986 return False;
Owen Anderson9f014062010-08-10 20:03:09 +0000987 return Unknown;
988 }
989
Chris Lattner2c5adf82009-11-15 19:59:49 +0000990 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000991 // If this is an equality comparison, we can try to fold it knowing that
992 // "V != C1".
993 if (Pred == ICmpInst::ICMP_EQ) {
994 // !C1 == C -> false iff C1 == C.
995 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
996 Result.getNotConstant(), C, TD);
997 if (Res->isNullValue())
998 return False;
999 } else if (Pred == ICmpInst::ICMP_NE) {
1000 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +00001001 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +00001002 Result.getNotConstant(), C, TD);
1003 if (Res->isNullValue())
1004 return True;
1005 }
Chris Lattner2c5adf82009-11-15 19:59:49 +00001006 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +00001007 }
1008
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001009 return Unknown;
1010}
1011
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001012void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001013 BasicBlock *NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +00001014 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1015}
1016
1017void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1018 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001019}