blob: 121828fdf3de1f0dcdb177803b7b41e5f06fbbe8 [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 };
Owen Anderson87790ab2010-12-20 19:33:41 +0000313
314 /// OverDefinedCacheUpdater - A helper object that ensures that the
315 /// OverDefinedCache is updated whenever solveBlockValue returns.
316 struct OverDefinedCacheUpdater {
317 LazyValueInfoCache *Parent;
318 Value *Val;
319 BasicBlock *BB;
320 LVILatticeVal &BBLV;
321
322 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
323 LazyValueInfoCache *P)
324 : Parent(P), Val(V), BB(B), BBLV(LV) { }
325
326 bool markResult(bool changed) {
327 if (changed && BBLV.isOverdefined())
328 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
329 return changed;
330 }
331 };
Owen Anderson7f9cb742010-07-30 23:59:40 +0000332
Chris Lattner2c5adf82009-11-15 19:59:49 +0000333 /// ValueCache - This is all of the cached information for all values,
334 /// mapped from Value* to key information.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000335 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000336
337 /// OverDefinedCache - This tracks, on a per-block basis, the set of
338 /// values that are over-defined at the end of that block. This is required
339 /// for cache updating.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000340 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000341
Owen Andersonf33b3022010-12-09 06:14:58 +0000342 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000343 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
344 LVILatticeVal &Result);
345 bool hasBlockValue(Value *Val, BasicBlock *BB);
346
347 // These methods process one work item and may add more. A false value
348 // returned means that the work item was not completely processed and must
349 // be revisited after going through the new items.
350 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson61863942010-12-20 18:18:16 +0000351 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
352 Value *Val, BasicBlock *BB);
353 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
354 PHINode *PN, BasicBlock *BB);
355 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
356 Instruction *BBI, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000357
358 void solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000359
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000360 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonf33b3022010-12-09 06:14:58 +0000361 return ValueCache[LVIValueHandle(V, this)];
362 }
363
Owen Anderson87790ab2010-12-20 19:33:41 +0000364 std::stack<std::pair<BasicBlock*, Value*> > block_value_stack;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000365
Chris Lattner2c5adf82009-11-15 19:59:49 +0000366 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000367 /// getValueInBlock - This is the query interface to determine the lattice
368 /// value for the specified Value* at the end of the specified block.
369 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
370
371 /// getValueOnEdge - This is the query interface to determine the lattice
372 /// value for the specified Value* that is true on the specified edge.
373 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000374
375 /// threadEdge - This is the update interface to inform the cache that an
376 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
377 /// NewSucc.
378 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000379
380 /// eraseBlock - This is part of the update interface to inform the cache
381 /// that a block has been deleted.
382 void eraseBlock(BasicBlock *BB);
383
384 /// clear - Empty the cache.
385 void clear() {
386 ValueCache.clear();
387 OverDefinedCache.clear();
388 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000389 };
390} // end anonymous namespace
391
Owen Anderson7f9cb742010-07-30 23:59:40 +0000392void LazyValueInfoCache::LVIValueHandle::deleted() {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000393 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000394 I = Parent->OverDefinedCache.begin(),
395 E = Parent->OverDefinedCache.end();
396 I != E; ) {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000397 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000398 ++I;
399 if (tmp->second == getValPtr())
400 Parent->OverDefinedCache.erase(tmp);
401 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000402
403 // This erasure deallocates *this, so it MUST happen after we're done
404 // using any and all members of *this.
405 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000406}
407
Owen Anderson00ac77e2010-08-18 18:39:01 +0000408void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
409 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
410 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
411 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
412 ++I;
413 if (tmp->first == BB)
414 OverDefinedCache.erase(tmp);
415 }
416
417 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
418 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
419 I->second.erase(BB);
420}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000421
Nick Lewycky90862ee2010-12-18 01:00:40 +0000422void LazyValueInfoCache::solve() {
423 while (!block_value_stack.empty()) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000424 std::pair<BasicBlock*, Value*> &e = block_value_stack.top();
425 if (solveBlockValue(e.second, e.first))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000426 block_value_stack.pop();
427 }
428}
429
430bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
431 // If already a constant, there is nothing to compute.
432 if (isa<Constant>(Val))
433 return true;
434
435 return lookup(Val).count(BB);
436}
437
Owen Andersonf33b3022010-12-09 06:14:58 +0000438LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000439 // If already a constant, there is nothing to compute.
440 if (Constant *VC = dyn_cast<Constant>(Val))
441 return LVILatticeVal::get(VC);
442
443 return lookup(Val)[BB];
444}
445
446bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
447 if (isa<Constant>(Val))
448 return true;
449
Owen Andersonf33b3022010-12-09 06:14:58 +0000450 ValueCacheEntryTy &Cache = lookup(Val);
451 LVILatticeVal &BBLV = Cache[BB];
Owen Anderson87790ab2010-12-20 19:33:41 +0000452
453 // OverDefinedCacheUpdater is a helper object that will update
454 // the OverDefinedCache for us when this method exits. Make sure to
455 // call markResult on it as we exist, passing a bool to indicate if the
456 // cache needs updating, i.e. if we have solve a new value or not.
457 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000458
Chris Lattner2c5adf82009-11-15 19:59:49 +0000459 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000460 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000461 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Owen Anderson87790ab2010-12-20 19:33:41 +0000462
463 // Since we're reusing a cached value here, we don't need to update the
464 // OverDefinedCahce. The cache will have been properly updated
465 // whenever the cached value was inserted.
466 ODCacheUpdater.markResult(false);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000467 return true;
Chris Lattnere5642812009-11-15 20:00:52 +0000468 }
469
Chris Lattner2c5adf82009-11-15 19:59:49 +0000470 // Otherwise, this is the first time we're seeing this block. Reset the
471 // lattice value to overdefined, so that cycles will terminate and be
472 // conservatively correct.
473 BBLV.markOverdefined();
474
Chris Lattner2c5adf82009-11-15 19:59:49 +0000475 Instruction *BBI = dyn_cast<Instruction>(Val);
476 if (BBI == 0 || BBI->getParent() != BB) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000477 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000478 }
Chris Lattnere5642812009-11-15 20:00:52 +0000479
Nick Lewycky90862ee2010-12-18 01:00:40 +0000480 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000481 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000482 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000483
484 // We can only analyze the definitions of certain classes of instructions
485 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000486 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000487 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
488 !BBI->getType()->isIntegerTy()) {
489 DEBUG(dbgs() << " compute BB '" << BB->getName()
490 << "' - overdefined because inst def found.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000491 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000492 return ODCacheUpdater.markResult(true);
Owen Andersonb81fd622010-08-18 21:11:37 +0000493 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000494
Owen Andersonb81fd622010-08-18 21:11:37 +0000495 // FIXME: We're currently limited to binops with a constant RHS. This should
496 // be improved.
497 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
498 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
499 DEBUG(dbgs() << " compute BB '" << BB->getName()
500 << "' - overdefined because inst def found.\n");
501
Owen Anderson61863942010-12-20 18:18:16 +0000502 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000503 return ODCacheUpdater.markResult(true);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000504 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000505
Owen Anderson87790ab2010-12-20 19:33:41 +0000506 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000507}
508
509static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
510 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
511 return L->getPointerAddressSpace() == 0 &&
512 GetUnderlyingObject(L->getPointerOperand()) ==
513 GetUnderlyingObject(Ptr);
514 }
515 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
516 return S->getPointerAddressSpace() == 0 &&
517 GetUnderlyingObject(S->getPointerOperand()) ==
518 GetUnderlyingObject(Ptr);
519 }
520 // FIXME: llvm.memset, etc.
521 return false;
522}
523
Owen Anderson61863942010-12-20 18:18:16 +0000524bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
525 Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000526 LVILatticeVal Result; // Start Undefined.
527
528 // If this is a pointer, and there's a load from that pointer in this BB,
529 // then we know that the pointer can't be NULL.
530 bool NotNull = false;
531 if (Val->getType()->isPointerTy()) {
532 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
533 if (InstructionDereferencesPointer(BI, Val)) {
534 NotNull = true;
535 break;
536 }
537 }
538 }
539
540 // If this is the entry block, we must be asking about an argument. The
541 // value is overdefined.
542 if (BB == &BB->getParent()->getEntryBlock()) {
543 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
544 if (NotNull) {
545 const PointerType *PTy = cast<PointerType>(Val->getType());
546 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
547 } else {
548 Result.markOverdefined();
549 }
Owen Anderson61863942010-12-20 18:18:16 +0000550 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000551 return true;
552 }
553
554 // Loop over all of our predecessors, merging what we know from them into
555 // result.
556 bool EdgesMissing = false;
557 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
558 LVILatticeVal EdgeResult;
559 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
560 if (EdgesMissing)
561 continue;
562
563 Result.mergeIn(EdgeResult);
564
565 // If we hit overdefined, exit early. The BlockVals entry is already set
566 // to overdefined.
567 if (Result.isOverdefined()) {
568 DEBUG(dbgs() << " compute BB '" << BB->getName()
569 << "' - overdefined because of pred.\n");
570 // If we previously determined that this is a pointer that can't be null
571 // then return that rather than giving up entirely.
572 if (NotNull) {
573 const PointerType *PTy = cast<PointerType>(Val->getType());
574 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
575 }
Owen Anderson61863942010-12-20 18:18:16 +0000576
577 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000578 return true;
579 }
580 }
581 if (EdgesMissing)
582 return false;
583
584 // Return the merged value, which is more precise than 'overdefined'.
585 assert(!Result.isOverdefined());
Owen Anderson61863942010-12-20 18:18:16 +0000586 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000587 return true;
588}
589
Owen Anderson61863942010-12-20 18:18:16 +0000590bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
591 PHINode *PN, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000592 LVILatticeVal Result; // Start Undefined.
593
594 // Loop over all of our predecessors, merging what we know from them into
595 // result.
596 bool EdgesMissing = false;
597 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
598 BasicBlock *PhiBB = PN->getIncomingBlock(i);
599 Value *PhiVal = PN->getIncomingValue(i);
600 LVILatticeVal EdgeResult;
601 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
602 if (EdgesMissing)
603 continue;
604
605 Result.mergeIn(EdgeResult);
606
607 // If we hit overdefined, exit early. The BlockVals entry is already set
608 // to overdefined.
609 if (Result.isOverdefined()) {
610 DEBUG(dbgs() << " compute BB '" << BB->getName()
611 << "' - overdefined because of pred.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000612
613 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000614 return true;
615 }
616 }
617 if (EdgesMissing)
618 return false;
619
620 // Return the merged value, which is more precise than 'overdefined'.
621 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson61863942010-12-20 18:18:16 +0000622 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000623 return true;
624}
625
Owen Anderson61863942010-12-20 18:18:16 +0000626bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
627 Instruction *BBI,
Nick Lewycky90862ee2010-12-18 01:00:40 +0000628 BasicBlock *BB) {
Owen Andersonb81fd622010-08-18 21:11:37 +0000629 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000630 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000631 block_value_stack.push(std::make_pair(BB, BBI->getOperand(0)));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000632 return false;
633 }
634
Nick Lewycky90862ee2010-12-18 01:00:40 +0000635 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Owen Andersonb81fd622010-08-18 21:11:37 +0000636 if (!LHSVal.isConstantRange()) {
Owen Anderson61863942010-12-20 18:18:16 +0000637 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000638 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000639 }
640
Owen Andersonb81fd622010-08-18 21:11:37 +0000641 ConstantRange LHSRange = LHSVal.getConstantRange();
642 ConstantRange RHSRange(1);
643 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
644 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000645 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
646 RHSRange = ConstantRange(RHS->getValue());
647 } else {
Owen Anderson61863942010-12-20 18:18:16 +0000648 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000649 return true;
Owen Anderson59b06dc2010-08-24 07:55:44 +0000650 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000651 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000652
Owen Andersonb81fd622010-08-18 21:11:37 +0000653 // NOTE: We're currently limited by the set of operations that ConstantRange
654 // can evaluate symbolically. Enhancing that set will allows us to analyze
655 // more definitions.
Owen Anderson61863942010-12-20 18:18:16 +0000656 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000657 switch (BBI->getOpcode()) {
658 case Instruction::Add:
659 Result.markConstantRange(LHSRange.add(RHSRange));
660 break;
661 case Instruction::Sub:
662 Result.markConstantRange(LHSRange.sub(RHSRange));
663 break;
664 case Instruction::Mul:
665 Result.markConstantRange(LHSRange.multiply(RHSRange));
666 break;
667 case Instruction::UDiv:
668 Result.markConstantRange(LHSRange.udiv(RHSRange));
669 break;
670 case Instruction::Shl:
671 Result.markConstantRange(LHSRange.shl(RHSRange));
672 break;
673 case Instruction::LShr:
674 Result.markConstantRange(LHSRange.lshr(RHSRange));
675 break;
676 case Instruction::Trunc:
677 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
678 break;
679 case Instruction::SExt:
680 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
681 break;
682 case Instruction::ZExt:
683 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
684 break;
685 case Instruction::BitCast:
686 Result.markConstantRange(LHSRange);
687 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000688 case Instruction::And:
689 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
690 break;
691 case Instruction::Or:
692 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
693 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000694
695 // Unhandled instructions are overdefined.
696 default:
697 DEBUG(dbgs() << " compute BB '" << BB->getName()
698 << "' - overdefined because inst def found.\n");
699 Result.markOverdefined();
700 break;
701 }
702
Owen Anderson61863942010-12-20 18:18:16 +0000703 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000704 return true;
Chris Lattner10f2d132009-11-11 00:22:30 +0000705}
706
Chris Lattner800c47e2009-11-15 20:02:12 +0000707/// getEdgeValue - This method attempts to infer more complex
Nick Lewycky90862ee2010-12-18 01:00:40 +0000708bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
709 BasicBlock *BBTo, LVILatticeVal &Result) {
710 // If already a constant, there is nothing to compute.
711 if (Constant *VC = dyn_cast<Constant>(Val)) {
712 Result = LVILatticeVal::get(VC);
713 return true;
714 }
715
Chris Lattner800c47e2009-11-15 20:02:12 +0000716 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
717 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000718 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
719 // If this is a conditional branch and only one successor goes to BBTo, then
720 // we maybe able to infer something from the condition.
721 if (BI->isConditional() &&
722 BI->getSuccessor(0) != BI->getSuccessor(1)) {
723 bool isTrueDest = BI->getSuccessor(0) == BBTo;
724 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
725 "BBTo isn't a successor of BBFrom");
726
727 // If V is the condition of the branch itself, then we know exactly what
728 // it is.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000729 if (BI->getCondition() == Val) {
730 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000731 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000732 return true;
733 }
Chris Lattner16976522009-11-11 22:48:44 +0000734
735 // If the condition of the branch is an equality comparison, we may be
736 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000737 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
738 if (ICI && ICI->getOperand(0) == Val &&
739 isa<Constant>(ICI->getOperand(1))) {
740 if (ICI->isEquality()) {
741 // We know that V has the RHS constant if this is a true SETEQ or
742 // false SETNE.
743 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000744 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
745 else
746 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
747 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000748 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000749
Owen Anderson2d0f2472010-08-11 04:24:25 +0000750 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
751 // Calculate the range of values that would satisfy the comparison.
752 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
753 ConstantRange TrueValues =
754 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000755
Owen Anderson2d0f2472010-08-11 04:24:25 +0000756 // If we're interested in the false dest, invert the condition.
757 if (!isTrueDest) TrueValues = TrueValues.inverse();
758
759 // Figure out the possible values of the query BEFORE this branch.
Owen Andersonf33b3022010-12-09 06:14:58 +0000760 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000761 if (!InBlock.isConstantRange()) {
762 Result = LVILatticeVal::getRange(TrueValues);
763 return true;
764 }
765
Owen Anderson2d0f2472010-08-11 04:24:25 +0000766 // Find all potential values that satisfy both the input and output
767 // conditions.
768 ConstantRange PossibleValues =
769 TrueValues.intersectWith(InBlock.getConstantRange());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000770
771 Result = LVILatticeVal::getRange(PossibleValues);
772 return true;
Owen Anderson2d0f2472010-08-11 04:24:25 +0000773 }
774 }
Chris Lattner16976522009-11-11 22:48:44 +0000775 }
776 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000777
778 // If the edge was formed by a switch on the value, then we may know exactly
779 // what it is.
780 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000781 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000782 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000783 if (SI->getDefaultDest() == BBTo) {
Owen Anderson4caef602010-09-02 22:16:52 +0000784 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000785 return true;
Owen Andersondae90c62010-08-24 21:59:42 +0000786 }
787
Chris Lattner800c47e2009-11-15 20:02:12 +0000788 // We only know something if there is exactly one value that goes from
789 // BBFrom to BBTo.
790 unsigned NumEdges = 0;
791 ConstantInt *EdgeVal = 0;
792 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
793 if (SI->getSuccessor(i) != BBTo) continue;
794 if (NumEdges++) break;
795 EdgeVal = SI->getCaseValue(i);
796 }
797 assert(EdgeVal && "Missing successor?");
Nick Lewycky90862ee2010-12-18 01:00:40 +0000798 if (NumEdges == 1) {
799 Result = LVILatticeVal::get(EdgeVal);
800 return true;
801 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000802 }
803 }
Chris Lattner16976522009-11-11 22:48:44 +0000804
805 // Otherwise see if the value is known in the block.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000806 if (hasBlockValue(Val, BBFrom)) {
807 Result = getBlockValue(Val, BBFrom);
808 return true;
809 }
Owen Anderson87790ab2010-12-20 19:33:41 +0000810 block_value_stack.push(std::make_pair(BBFrom, Val));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000811 return false;
Chris Lattner16976522009-11-11 22:48:44 +0000812}
813
Chris Lattner2c5adf82009-11-15 19:59:49 +0000814LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000815 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000816 << BB->getName() << "'\n");
817
Owen Anderson87790ab2010-12-20 19:33:41 +0000818 block_value_stack.push(std::make_pair(BB, V));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000819 solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000820 LVILatticeVal Result = getBlockValue(V, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000821
David Greene5d93a1f2009-12-23 20:43:58 +0000822 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000823 return Result;
824}
Chris Lattner16976522009-11-11 22:48:44 +0000825
Chris Lattner2c5adf82009-11-15 19:59:49 +0000826LVILatticeVal LazyValueInfoCache::
827getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000828 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000829 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000830
Nick Lewycky90862ee2010-12-18 01:00:40 +0000831 LVILatticeVal Result;
832 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
833 solve();
834 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
835 (void)WasFastQuery;
836 assert(WasFastQuery && "More work to do after problem solved?");
837 }
838
David Greene5d93a1f2009-12-23 20:43:58 +0000839 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000840 return Result;
841}
842
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000843void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
844 BasicBlock *NewSucc) {
845 // When an edge in the graph has been threaded, values that we could not
846 // determine a value for before (i.e. were marked overdefined) may be possible
847 // to solve now. We do NOT try to proactively update these values. Instead,
848 // we clear their entries from the cache, and allow lazy updating to recompute
849 // them when needed.
850
851 // The updating process is fairly simple: we need to dropped cached info
852 // for all values that were marked overdefined in OldSucc, and for those same
853 // values in any successor of OldSucc (except NewSucc) in which they were
854 // also marked overdefined.
855 std::vector<BasicBlock*> worklist;
856 worklist.push_back(OldSucc);
857
Owen Anderson9a65dc92010-07-27 23:58:11 +0000858 DenseSet<Value*> ClearSet;
Owen Anderson00ac77e2010-08-18 18:39:01 +0000859 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson9a65dc92010-07-27 23:58:11 +0000860 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
861 if (I->first == OldSucc)
862 ClearSet.insert(I->second);
863 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000864
865 // Use a worklist to perform a depth-first search of OldSucc's successors.
866 // NOTE: We do not need a visited list since any blocks we have already
867 // visited will have had their overdefined markers cleared already, and we
868 // thus won't loop to their successors.
869 while (!worklist.empty()) {
870 BasicBlock *ToUpdate = worklist.back();
871 worklist.pop_back();
872
873 // Skip blocks only accessible through NewSucc.
874 if (ToUpdate == NewSucc) continue;
875
876 bool changed = false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000877 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000878 I != E; ++I) {
879 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson00ac77e2010-08-18 18:39:01 +0000880 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000881 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
882 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000883
Owen Anderson9a65dc92010-07-27 23:58:11 +0000884 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000885 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000886 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000887
Owen Anderson9a65dc92010-07-27 23:58:11 +0000888 assert(CI != Entry.end() && "Couldn't find entry to update?");
889 Entry.erase(CI);
890 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000891
Owen Anderson9a65dc92010-07-27 23:58:11 +0000892 // If we removed anything, then we potentially need to update
893 // blocks successors too.
894 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000895 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000896
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000897 if (!changed) continue;
898
899 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
900 }
901}
902
Chris Lattner2c5adf82009-11-15 19:59:49 +0000903//===----------------------------------------------------------------------===//
904// LazyValueInfo Impl
905//===----------------------------------------------------------------------===//
906
Chris Lattner2c5adf82009-11-15 19:59:49 +0000907/// getCache - This lazily constructs the LazyValueInfoCache.
908static LazyValueInfoCache &getCache(void *&PImpl) {
909 if (!PImpl)
910 PImpl = new LazyValueInfoCache();
911 return *static_cast<LazyValueInfoCache*>(PImpl);
912}
913
Owen Anderson00ac77e2010-08-18 18:39:01 +0000914bool LazyValueInfo::runOnFunction(Function &F) {
915 if (PImpl)
916 getCache(PImpl).clear();
917
918 TD = getAnalysisIfAvailable<TargetData>();
919 // Fully lazy.
920 return false;
921}
922
Chris Lattner2c5adf82009-11-15 19:59:49 +0000923void LazyValueInfo::releaseMemory() {
924 // If the cache was allocated, free it.
925 if (PImpl) {
926 delete &getCache(PImpl);
927 PImpl = 0;
928 }
929}
930
931Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
932 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
933
Chris Lattner16976522009-11-11 22:48:44 +0000934 if (Result.isConstant())
935 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000936 if (Result.isConstantRange()) {
Owen Andersonee61fcf2010-08-27 23:29:38 +0000937 ConstantRange CR = Result.getConstantRange();
938 if (const APInt *SingleVal = CR.getSingleElement())
939 return ConstantInt::get(V->getContext(), *SingleVal);
940 }
Chris Lattner16976522009-11-11 22:48:44 +0000941 return 0;
942}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000943
Chris Lattner38392bb2009-11-12 01:29:10 +0000944/// getConstantOnEdge - Determine whether the specified value is known to be a
945/// constant on the specified edge. Return null if not.
946Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
947 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000948 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +0000949
950 if (Result.isConstant())
951 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000952 if (Result.isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +0000953 ConstantRange CR = Result.getConstantRange();
954 if (const APInt *SingleVal = CR.getSingleElement())
955 return ConstantInt::get(V->getContext(), *SingleVal);
956 }
Chris Lattner38392bb2009-11-12 01:29:10 +0000957 return 0;
958}
959
Chris Lattnerb52675b2009-11-12 04:36:58 +0000960/// getPredicateOnEdge - Determine whether the specified value comparison
961/// with a constant is known to be true or false on the specified CFG edge.
962/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000963LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +0000964LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
965 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000966 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000967
Chris Lattnerb52675b2009-11-12 04:36:58 +0000968 // If we know the value is a constant, evaluate the conditional.
969 Constant *Res = 0;
970 if (Result.isConstant()) {
971 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000972 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Chris Lattnerb52675b2009-11-12 04:36:58 +0000973 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000974 return Unknown;
975 }
976
Owen Anderson9f014062010-08-10 20:03:09 +0000977 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000978 ConstantInt *CI = dyn_cast<ConstantInt>(C);
979 if (!CI) return Unknown;
980
Owen Anderson9f014062010-08-10 20:03:09 +0000981 ConstantRange CR = Result.getConstantRange();
982 if (Pred == ICmpInst::ICMP_EQ) {
983 if (!CR.contains(CI->getValue()))
984 return False;
985
986 if (CR.isSingleElement() && CR.contains(CI->getValue()))
987 return True;
988 } else if (Pred == ICmpInst::ICMP_NE) {
989 if (!CR.contains(CI->getValue()))
990 return True;
991
992 if (CR.isSingleElement() && CR.contains(CI->getValue()))
993 return False;
994 }
995
996 // Handle more complex predicates.
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000997 ConstantRange TrueValues =
998 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
999 if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +00001000 return True;
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001001 if (TrueValues.inverse().contains(CR))
1002 return False;
Owen Anderson9f014062010-08-10 20:03:09 +00001003 return Unknown;
1004 }
1005
Chris Lattner2c5adf82009-11-15 19:59:49 +00001006 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +00001007 // If this is an equality comparison, we can try to fold it knowing that
1008 // "V != C1".
1009 if (Pred == ICmpInst::ICMP_EQ) {
1010 // !C1 == C -> false iff C1 == C.
1011 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1012 Result.getNotConstant(), C, TD);
1013 if (Res->isNullValue())
1014 return False;
1015 } else if (Pred == ICmpInst::ICMP_NE) {
1016 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +00001017 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +00001018 Result.getNotConstant(), C, TD);
1019 if (Res->isNullValue())
1020 return True;
1021 }
Chris Lattner2c5adf82009-11-15 19:59:49 +00001022 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +00001023 }
1024
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001025 return Unknown;
1026}
1027
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001028void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001029 BasicBlock *NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +00001030 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1031}
1032
1033void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1034 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001035}