blob: 8bde3cc2842e1ae0ecc007f33d398d8750fe8ceb [file] [log] [blame]
Chris Lattner10f2d132009-11-11 00:22:30 +00001//===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interface for lazy computation of value constraint
11// information.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnerb8c124c2009-11-12 01:22:16 +000015#define DEBUG_TYPE "lazy-value-info"
Chris Lattner10f2d132009-11-11 00:22:30 +000016#include "llvm/Analysis/LazyValueInfo.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000017#include "llvm/Analysis/ValueTracking.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000018#include "llvm/Constants.h"
19#include "llvm/Instructions.h"
Nick Lewycky786c7cd2011-01-15 09:16:12 +000020#include "llvm/IntrinsicInst.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000021#include "llvm/Analysis/ConstantFolding.h"
22#include "llvm/Target/TargetData.h"
Chris Lattner16976522009-11-11 22:48:44 +000023#include "llvm/Support/CFG.h"
Owen Anderson5be2e782010-08-05 22:59:19 +000024#include "llvm/Support/ConstantRange.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000025#include "llvm/Support/Debug.h"
Chris Lattner16976522009-11-11 22:48:44 +000026#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000027#include "llvm/Support/ValueHandle.h"
Chris Lattner16976522009-11-11 22:48:44 +000028#include "llvm/ADT/DenseMap.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000029#include "llvm/ADT/DenseSet.h"
Chris Lattnere5642812009-11-15 20:00:52 +000030#include "llvm/ADT/STLExtras.h"
Owen Anderson6bcd3a02010-09-07 19:16:25 +000031#include <map>
32#include <set>
Nick Lewycky90862ee2010-12-18 01:00:40 +000033#include <stack>
Chris Lattner10f2d132009-11-11 00:22:30 +000034using namespace llvm;
35
36char LazyValueInfo::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000037INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
Owen Andersonce665bd2010-10-07 22:25:06 +000038 "Lazy Value Information Analysis", false, true)
Chris Lattner10f2d132009-11-11 00:22:30 +000039
40namespace llvm {
41 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
42}
43
Chris Lattnercc4d3b22009-11-11 02:08:33 +000044
45//===----------------------------------------------------------------------===//
46// LVILatticeVal
47//===----------------------------------------------------------------------===//
48
49/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
50/// value.
51///
52/// FIXME: This is basically just for bringup, this can be made a lot more rich
53/// in the future.
54///
55namespace {
56class LVILatticeVal {
57 enum LatticeValueTy {
Nick Lewycky69bfdf52010-12-15 18:57:18 +000058 /// undefined - This Value has no known value yet.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000059 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000060
Nick Lewycky69bfdf52010-12-15 18:57:18 +000061 /// constant - This Value has a specific constant value.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000062 constant,
Nick Lewycky69bfdf52010-12-15 18:57:18 +000063 /// notconstant - This Value is known to not have the specified value.
Chris Lattnerb52675b2009-11-12 04:36:58 +000064 notconstant,
65
Nick Lewycky69bfdf52010-12-15 18:57:18 +000066 /// constantrange - The Value falls within this range.
Owen Anderson5be2e782010-08-05 22:59:19 +000067 constantrange,
68
Nick Lewycky69bfdf52010-12-15 18:57:18 +000069 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnercc4d3b22009-11-11 02:08:33 +000070 /// it has a value.
71 overdefined
72 };
73
74 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000075 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000076 LatticeValueTy Tag;
77 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000078 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000079
80public:
Owen Anderson5be2e782010-08-05 22:59:19 +000081 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000082
Chris Lattner16976522009-11-11 22:48:44 +000083 static LVILatticeVal get(Constant *C) {
84 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000085 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000086 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000087 return Res;
88 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000089 static LVILatticeVal getNot(Constant *C) {
90 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000091 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000092 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000093 return Res;
94 }
Owen Anderson625051b2010-08-10 23:20:01 +000095 static LVILatticeVal getRange(ConstantRange CR) {
96 LVILatticeVal Res;
97 Res.markConstantRange(CR);
98 return Res;
99 }
Chris Lattner16976522009-11-11 22:48:44 +0000100
Owen Anderson5be2e782010-08-05 22:59:19 +0000101 bool isUndefined() const { return Tag == undefined; }
102 bool isConstant() const { return Tag == constant; }
103 bool isNotConstant() const { return Tag == notconstant; }
104 bool isConstantRange() const { return Tag == constantrange; }
105 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000106
107 Constant *getConstant() const {
108 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000109 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000110 }
111
Chris Lattnerb52675b2009-11-12 04:36:58 +0000112 Constant *getNotConstant() const {
113 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000114 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000115 }
116
Owen Anderson5be2e782010-08-05 22:59:19 +0000117 ConstantRange getConstantRange() const {
118 assert(isConstantRange() &&
119 "Cannot get the constant-range of a non-constant-range!");
120 return Range;
121 }
122
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000123 /// markOverdefined - Return true if this is a change in status.
124 bool markOverdefined() {
125 if (isOverdefined())
126 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000127 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000128 return true;
129 }
130
131 /// markConstant - Return true if this is a change in status.
132 bool markConstant(Constant *V) {
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000133 assert(V && "Marking constant with NULL");
134 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
135 return markConstantRange(ConstantRange(CI->getValue()));
136 if (isa<UndefValue>(V))
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000137 return false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000138
139 assert((!isConstant() || getConstant() == V) &&
140 "Marking constant with different value");
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000141 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000142 Tag = constant;
Owen Andersondb78d732010-08-05 22:10:46 +0000143 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000144 return true;
145 }
146
Chris Lattnerb52675b2009-11-12 04:36:58 +0000147 /// markNotConstant - Return true if this is a change in status.
148 bool markNotConstant(Constant *V) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000149 assert(V && "Marking constant with NULL");
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000150 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
151 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
152 if (isa<UndefValue>(V))
153 return false;
154
155 assert((!isConstant() || getConstant() != V) &&
156 "Marking constant !constant with same value");
157 assert((!isNotConstant() || getNotConstant() == V) &&
158 "Marking !constant with different value");
159 assert(isUndefined() || isConstant());
160 Tag = notconstant;
Owen Andersondb78d732010-08-05 22:10:46 +0000161 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000162 return true;
163 }
164
Owen Anderson5be2e782010-08-05 22:59:19 +0000165 /// markConstantRange - Return true if this is a change in status.
166 bool markConstantRange(const ConstantRange NewR) {
167 if (isConstantRange()) {
168 if (NewR.isEmptySet())
169 return markOverdefined();
170
Owen Anderson5be2e782010-08-05 22:59:19 +0000171 bool changed = Range == NewR;
172 Range = NewR;
173 return changed;
174 }
175
176 assert(isUndefined());
177 if (NewR.isEmptySet())
178 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000179
180 Tag = constantrange;
181 Range = NewR;
182 return true;
183 }
184
Chris Lattner16976522009-11-11 22:48:44 +0000185 /// mergeIn - Merge the specified lattice value into this one, updating this
186 /// one and returning true if anything changed.
187 bool mergeIn(const LVILatticeVal &RHS) {
188 if (RHS.isUndefined() || isOverdefined()) return false;
189 if (RHS.isOverdefined()) return markOverdefined();
190
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000191 if (isUndefined()) {
192 Tag = RHS.Tag;
193 Val = RHS.Val;
194 Range = RHS.Range;
195 return true;
Chris Lattnerf496e792009-11-12 04:57:13 +0000196 }
197
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000198 if (isConstant()) {
199 if (RHS.isConstant()) {
200 if (Val == RHS.Val)
201 return false;
202 return markOverdefined();
203 }
204
205 if (RHS.isNotConstant()) {
206 if (Val == RHS.Val)
207 return markOverdefined();
208
209 // Unless we can prove that the two Constants are different, we must
210 // move to overdefined.
211 // FIXME: use TargetData for smarter constant folding.
212 if (ConstantInt *Res = dyn_cast<ConstantInt>(
213 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
214 getConstant(),
215 RHS.getNotConstant())))
216 if (Res->isOne())
217 return markNotConstant(RHS.getNotConstant());
218
219 return markOverdefined();
220 }
221
222 // RHS is a ConstantRange, LHS is a non-integer Constant.
223
224 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
225 // a function. The correct result is to pick up RHS.
226
Chris Lattner16976522009-11-11 22:48:44 +0000227 return markOverdefined();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000228 }
229
230 if (isNotConstant()) {
231 if (RHS.isConstant()) {
232 if (Val == RHS.Val)
233 return markOverdefined();
234
235 // Unless we can prove that the two Constants are different, we must
236 // move to overdefined.
237 // FIXME: use TargetData for smarter constant folding.
238 if (ConstantInt *Res = dyn_cast<ConstantInt>(
239 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
240 getNotConstant(),
241 RHS.getConstant())))
242 if (Res->isOne())
243 return false;
244
245 return markOverdefined();
246 }
247
248 if (RHS.isNotConstant()) {
249 if (Val == RHS.Val)
250 return false;
251 return markOverdefined();
252 }
253
254 return markOverdefined();
255 }
256
257 assert(isConstantRange() && "New LVILattice type?");
258 if (!RHS.isConstantRange())
259 return markOverdefined();
260
261 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
262 if (NewR.isFullSet())
263 return markOverdefined();
264 return markConstantRange(NewR);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000265 }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000266};
267
268} // end anonymous namespace.
269
Chris Lattner16976522009-11-11 22:48:44 +0000270namespace llvm {
Chandler Carruth3b55a372011-04-18 18:49:44 +0000271raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
272 LLVM_ATTRIBUTE_USED;
Chris Lattner16976522009-11-11 22:48:44 +0000273raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
274 if (Val.isUndefined())
275 return OS << "undefined";
276 if (Val.isOverdefined())
277 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000278
279 if (Val.isNotConstant())
280 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000281 else if (Val.isConstantRange())
282 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
283 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000284 return OS << "constant<" << *Val.getConstant() << '>';
285}
286}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000287
288//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000289// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000290//===----------------------------------------------------------------------===//
291
Chris Lattner2c5adf82009-11-15 19:59:49 +0000292namespace {
Owen Anderson89778462011-01-05 21:15:29 +0000293 /// LVIValueHandle - A callback value handle update the cache when
294 /// values are erased.
295 class LazyValueInfoCache;
296 struct LVIValueHandle : public CallbackVH {
297 LazyValueInfoCache *Parent;
298
299 LVIValueHandle(Value *V, LazyValueInfoCache *P)
300 : CallbackVH(V), Parent(P) { }
301
302 void deleted();
303 void allUsesReplacedWith(Value *V) {
304 deleted();
305 }
306 };
307}
308
309namespace llvm {
310 template<>
311 struct DenseMapInfo<LVIValueHandle> {
312 typedef DenseMapInfo<Value*> PointerInfo;
313 static inline LVIValueHandle getEmptyKey() {
314 return LVIValueHandle(PointerInfo::getEmptyKey(),
315 static_cast<LazyValueInfoCache*>(0));
316 }
317 static inline LVIValueHandle getTombstoneKey() {
318 return LVIValueHandle(PointerInfo::getTombstoneKey(),
319 static_cast<LazyValueInfoCache*>(0));
320 }
321 static unsigned getHashValue(const LVIValueHandle &Val) {
322 return PointerInfo::getHashValue(Val);
323 }
324 static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
325 return LHS == RHS;
326 }
327 };
328
329 template<>
330 struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
331 typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
332 typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
333 typedef DenseMapInfo<Value*> BPointerInfo;
334 static inline PairTy getEmptyKey() {
335 return std::make_pair(APointerInfo::getEmptyKey(),
336 BPointerInfo::getEmptyKey());
337 }
338 static inline PairTy getTombstoneKey() {
339 return std::make_pair(APointerInfo::getTombstoneKey(),
340 BPointerInfo::getTombstoneKey());
341 }
342 static unsigned getHashValue( const PairTy &Val) {
343 return APointerInfo::getHashValue(Val.first) ^
344 BPointerInfo::getHashValue(Val.second);
345 }
346 static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
347 return APointerInfo::isEqual(LHS.first, RHS.first) &&
348 BPointerInfo::isEqual(LHS.second, RHS.second);
349 }
350 };
351}
352
353namespace {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000354 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
355 /// maintains information about queries across the clients' queries.
356 class LazyValueInfoCache {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000357 /// ValueCacheEntryTy - This is all of the cached block information for
358 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
359 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000360 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000361
Owen Andersone68713a2011-01-05 23:26:22 +0000362 /// ValueCache - This is all of the cached information for all values,
363 /// mapped from Value* to key information.
364 DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
365
366 /// OverDefinedCache - This tracks, on a per-block basis, the set of
367 /// values that are over-defined at the end of that block. This is required
368 /// for cache updating.
369 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
370 DenseSet<OverDefinedPairTy> OverDefinedCache;
371
372 /// BlockValueStack - This stack holds the state of the value solver
373 /// during a query. It basically emulates the callstack of the naive
374 /// recursive value lookup process.
375 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
376
Owen Anderson89778462011-01-05 21:15:29 +0000377 friend struct LVIValueHandle;
Owen Anderson87790ab2010-12-20 19:33:41 +0000378
379 /// OverDefinedCacheUpdater - A helper object that ensures that the
380 /// OverDefinedCache is updated whenever solveBlockValue returns.
381 struct OverDefinedCacheUpdater {
382 LazyValueInfoCache *Parent;
383 Value *Val;
384 BasicBlock *BB;
385 LVILatticeVal &BBLV;
386
387 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
388 LazyValueInfoCache *P)
389 : Parent(P), Val(V), BB(B), BBLV(LV) { }
390
391 bool markResult(bool changed) {
392 if (changed && BBLV.isOverdefined())
393 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
394 return changed;
395 }
396 };
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000397
Owen Andersone68713a2011-01-05 23:26:22 +0000398
Owen Anderson7f9cb742010-07-30 23:59:40 +0000399
Owen Andersonf33b3022010-12-09 06:14:58 +0000400 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000401 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
402 LVILatticeVal &Result);
403 bool hasBlockValue(Value *Val, BasicBlock *BB);
404
405 // These methods process one work item and may add more. A false value
406 // returned means that the work item was not completely processed and must
407 // be revisited after going through the new items.
408 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson61863942010-12-20 18:18:16 +0000409 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
410 Value *Val, BasicBlock *BB);
411 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
412 PHINode *PN, BasicBlock *BB);
413 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
414 Instruction *BBI, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000415
416 void solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000417
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000418 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonf33b3022010-12-09 06:14:58 +0000419 return ValueCache[LVIValueHandle(V, this)];
420 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000421
Chris Lattner2c5adf82009-11-15 19:59:49 +0000422 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000423 /// getValueInBlock - This is the query interface to determine the lattice
424 /// value for the specified Value* at the end of the specified block.
425 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
426
427 /// getValueOnEdge - This is the query interface to determine the lattice
428 /// value for the specified Value* that is true on the specified edge.
429 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000430
431 /// threadEdge - This is the update interface to inform the cache that an
432 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
433 /// NewSucc.
434 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000435
436 /// eraseBlock - This is part of the update interface to inform the cache
437 /// that a block has been deleted.
438 void eraseBlock(BasicBlock *BB);
439
440 /// clear - Empty the cache.
441 void clear() {
442 ValueCache.clear();
443 OverDefinedCache.clear();
444 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000445 };
446} // end anonymous namespace
447
Owen Anderson89778462011-01-05 21:15:29 +0000448void LVIValueHandle::deleted() {
449 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
450
451 SmallVector<OverDefinedPairTy, 4> ToErase;
452 for (DenseSet<OverDefinedPairTy>::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000453 I = Parent->OverDefinedCache.begin(),
454 E = Parent->OverDefinedCache.end();
Owen Anderson89778462011-01-05 21:15:29 +0000455 I != E; ++I) {
456 if (I->second == getValPtr())
457 ToErase.push_back(*I);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000458 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000459
Owen Anderson89778462011-01-05 21:15:29 +0000460 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
461 E = ToErase.end(); I != E; ++I)
462 Parent->OverDefinedCache.erase(*I);
463
Owen Andersoncf6abd22010-08-11 22:36:04 +0000464 // This erasure deallocates *this, so it MUST happen after we're done
465 // using any and all members of *this.
466 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000467}
468
Owen Anderson00ac77e2010-08-18 18:39:01 +0000469void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Owen Anderson89778462011-01-05 21:15:29 +0000470 SmallVector<OverDefinedPairTy, 4> ToErase;
471 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
472 E = OverDefinedCache.end(); I != E; ++I) {
473 if (I->first == BB)
474 ToErase.push_back(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000475 }
Owen Anderson89778462011-01-05 21:15:29 +0000476
477 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
478 E = ToErase.end(); I != E; ++I)
479 OverDefinedCache.erase(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000480
Owen Anderson89778462011-01-05 21:15:29 +0000481 for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson00ac77e2010-08-18 18:39:01 +0000482 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
483 I->second.erase(BB);
484}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000485
Nick Lewycky90862ee2010-12-18 01:00:40 +0000486void LazyValueInfoCache::solve() {
Owen Andersone68713a2011-01-05 23:26:22 +0000487 while (!BlockValueStack.empty()) {
488 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Owen Anderson87790ab2010-12-20 19:33:41 +0000489 if (solveBlockValue(e.second, e.first))
Owen Andersone68713a2011-01-05 23:26:22 +0000490 BlockValueStack.pop();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000491 }
492}
493
494bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
495 // If already a constant, there is nothing to compute.
496 if (isa<Constant>(Val))
497 return true;
498
Owen Anderson89778462011-01-05 21:15:29 +0000499 LVIValueHandle ValHandle(Val, this);
500 if (!ValueCache.count(ValHandle)) return false;
501 return ValueCache[ValHandle].count(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000502}
503
Owen Andersonf33b3022010-12-09 06:14:58 +0000504LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000505 // If already a constant, there is nothing to compute.
506 if (Constant *VC = dyn_cast<Constant>(Val))
507 return LVILatticeVal::get(VC);
508
509 return lookup(Val)[BB];
510}
511
512bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
513 if (isa<Constant>(Val))
514 return true;
515
Owen Andersonf33b3022010-12-09 06:14:58 +0000516 ValueCacheEntryTy &Cache = lookup(Val);
517 LVILatticeVal &BBLV = Cache[BB];
Owen Anderson87790ab2010-12-20 19:33:41 +0000518
519 // OverDefinedCacheUpdater is a helper object that will update
520 // the OverDefinedCache for us when this method exits. Make sure to
521 // call markResult on it as we exist, passing a bool to indicate if the
522 // cache needs updating, i.e. if we have solve a new value or not.
523 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000524
Chris Lattner2c5adf82009-11-15 19:59:49 +0000525 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000526 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000527 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Owen Anderson87790ab2010-12-20 19:33:41 +0000528
529 // Since we're reusing a cached value here, we don't need to update the
530 // OverDefinedCahce. The cache will have been properly updated
531 // whenever the cached value was inserted.
532 ODCacheUpdater.markResult(false);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000533 return true;
Chris Lattnere5642812009-11-15 20:00:52 +0000534 }
535
Chris Lattner2c5adf82009-11-15 19:59:49 +0000536 // Otherwise, this is the first time we're seeing this block. Reset the
537 // lattice value to overdefined, so that cycles will terminate and be
538 // conservatively correct.
539 BBLV.markOverdefined();
540
Chris Lattner2c5adf82009-11-15 19:59:49 +0000541 Instruction *BBI = dyn_cast<Instruction>(Val);
542 if (BBI == 0 || BBI->getParent() != BB) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000543 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000544 }
Chris Lattnere5642812009-11-15 20:00:52 +0000545
Nick Lewycky90862ee2010-12-18 01:00:40 +0000546 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000547 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000548 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000549
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000550 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
551 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
552 return ODCacheUpdater.markResult(true);
553 }
554
Owen Andersonb81fd622010-08-18 21:11:37 +0000555 // We can only analyze the definitions of certain classes of instructions
556 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000557 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000558 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
559 !BBI->getType()->isIntegerTy()) {
560 DEBUG(dbgs() << " compute BB '" << BB->getName()
561 << "' - overdefined because inst def found.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000562 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000563 return ODCacheUpdater.markResult(true);
Owen Andersonb81fd622010-08-18 21:11:37 +0000564 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000565
Owen Andersonb81fd622010-08-18 21:11:37 +0000566 // FIXME: We're currently limited to binops with a constant RHS. This should
567 // be improved.
568 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
569 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
570 DEBUG(dbgs() << " compute BB '" << BB->getName()
571 << "' - overdefined because inst def found.\n");
572
Owen Anderson61863942010-12-20 18:18:16 +0000573 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000574 return ODCacheUpdater.markResult(true);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000575 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000576
Owen Anderson87790ab2010-12-20 19:33:41 +0000577 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000578}
579
580static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
581 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
582 return L->getPointerAddressSpace() == 0 &&
583 GetUnderlyingObject(L->getPointerOperand()) ==
584 GetUnderlyingObject(Ptr);
585 }
586 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
587 return S->getPointerAddressSpace() == 0 &&
588 GetUnderlyingObject(S->getPointerOperand()) ==
589 GetUnderlyingObject(Ptr);
590 }
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000591 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
592 if (MI->isVolatile()) return false;
593 if (MI->getAddressSpace() != 0) return false;
594
595 // FIXME: check whether it has a valuerange that excludes zero?
596 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
597 if (!Len || Len->isZero()) return false;
598
599 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
600 return true;
601 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
602 return MTI->getRawSource() == Ptr || MTI->getSource() == Ptr;
603 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000604 return false;
605}
606
Owen Anderson61863942010-12-20 18:18:16 +0000607bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
608 Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000609 LVILatticeVal Result; // Start Undefined.
610
611 // If this is a pointer, and there's a load from that pointer in this BB,
612 // then we know that the pointer can't be NULL.
613 bool NotNull = false;
614 if (Val->getType()->isPointerTy()) {
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000615 if (isa<AllocaInst>(Val)) {
616 NotNull = true;
617 } else {
618 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
619 if (InstructionDereferencesPointer(BI, Val)) {
620 NotNull = true;
621 break;
622 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000623 }
624 }
625 }
626
627 // If this is the entry block, we must be asking about an argument. The
628 // value is overdefined.
629 if (BB == &BB->getParent()->getEntryBlock()) {
630 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
631 if (NotNull) {
632 const PointerType *PTy = cast<PointerType>(Val->getType());
633 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
634 } else {
635 Result.markOverdefined();
636 }
Owen Anderson61863942010-12-20 18:18:16 +0000637 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000638 return true;
639 }
640
641 // Loop over all of our predecessors, merging what we know from them into
642 // result.
643 bool EdgesMissing = false;
644 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
645 LVILatticeVal EdgeResult;
646 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
647 if (EdgesMissing)
648 continue;
649
650 Result.mergeIn(EdgeResult);
651
652 // If we hit overdefined, exit early. The BlockVals entry is already set
653 // to overdefined.
654 if (Result.isOverdefined()) {
655 DEBUG(dbgs() << " compute BB '" << BB->getName()
656 << "' - overdefined because of pred.\n");
657 // If we previously determined that this is a pointer that can't be null
658 // then return that rather than giving up entirely.
659 if (NotNull) {
660 const PointerType *PTy = cast<PointerType>(Val->getType());
661 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
662 }
Owen Anderson61863942010-12-20 18:18:16 +0000663
664 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000665 return true;
666 }
667 }
668 if (EdgesMissing)
669 return false;
670
671 // Return the merged value, which is more precise than 'overdefined'.
672 assert(!Result.isOverdefined());
Owen Anderson61863942010-12-20 18:18:16 +0000673 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000674 return true;
675}
676
Owen Anderson61863942010-12-20 18:18:16 +0000677bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
678 PHINode *PN, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000679 LVILatticeVal Result; // Start Undefined.
680
681 // Loop over all of our predecessors, merging what we know from them into
682 // result.
683 bool EdgesMissing = false;
684 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
685 BasicBlock *PhiBB = PN->getIncomingBlock(i);
686 Value *PhiVal = PN->getIncomingValue(i);
687 LVILatticeVal EdgeResult;
688 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
689 if (EdgesMissing)
690 continue;
691
692 Result.mergeIn(EdgeResult);
693
694 // If we hit overdefined, exit early. The BlockVals entry is already set
695 // to overdefined.
696 if (Result.isOverdefined()) {
697 DEBUG(dbgs() << " compute BB '" << BB->getName()
698 << "' - overdefined because of pred.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000699
700 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000701 return true;
702 }
703 }
704 if (EdgesMissing)
705 return false;
706
707 // Return the merged value, which is more precise than 'overdefined'.
708 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson61863942010-12-20 18:18:16 +0000709 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000710 return true;
711}
712
Owen Anderson61863942010-12-20 18:18:16 +0000713bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
714 Instruction *BBI,
Nick Lewycky90862ee2010-12-18 01:00:40 +0000715 BasicBlock *BB) {
Owen Andersonb81fd622010-08-18 21:11:37 +0000716 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000717 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000718 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000719 return false;
720 }
721
Nick Lewycky90862ee2010-12-18 01:00:40 +0000722 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Owen Andersonb81fd622010-08-18 21:11:37 +0000723 if (!LHSVal.isConstantRange()) {
Owen Anderson61863942010-12-20 18:18:16 +0000724 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000725 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000726 }
727
Owen Andersonb81fd622010-08-18 21:11:37 +0000728 ConstantRange LHSRange = LHSVal.getConstantRange();
729 ConstantRange RHSRange(1);
730 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
731 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000732 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
733 RHSRange = ConstantRange(RHS->getValue());
734 } else {
Owen Anderson61863942010-12-20 18:18:16 +0000735 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000736 return true;
Owen Anderson59b06dc2010-08-24 07:55:44 +0000737 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000738 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000739
Owen Andersonb81fd622010-08-18 21:11:37 +0000740 // NOTE: We're currently limited by the set of operations that ConstantRange
741 // can evaluate symbolically. Enhancing that set will allows us to analyze
742 // more definitions.
Owen Anderson61863942010-12-20 18:18:16 +0000743 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000744 switch (BBI->getOpcode()) {
745 case Instruction::Add:
746 Result.markConstantRange(LHSRange.add(RHSRange));
747 break;
748 case Instruction::Sub:
749 Result.markConstantRange(LHSRange.sub(RHSRange));
750 break;
751 case Instruction::Mul:
752 Result.markConstantRange(LHSRange.multiply(RHSRange));
753 break;
754 case Instruction::UDiv:
755 Result.markConstantRange(LHSRange.udiv(RHSRange));
756 break;
757 case Instruction::Shl:
758 Result.markConstantRange(LHSRange.shl(RHSRange));
759 break;
760 case Instruction::LShr:
761 Result.markConstantRange(LHSRange.lshr(RHSRange));
762 break;
763 case Instruction::Trunc:
764 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
765 break;
766 case Instruction::SExt:
767 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
768 break;
769 case Instruction::ZExt:
770 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
771 break;
772 case Instruction::BitCast:
773 Result.markConstantRange(LHSRange);
774 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000775 case Instruction::And:
776 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
777 break;
778 case Instruction::Or:
779 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
780 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000781
782 // Unhandled instructions are overdefined.
783 default:
784 DEBUG(dbgs() << " compute BB '" << BB->getName()
785 << "' - overdefined because inst def found.\n");
786 Result.markOverdefined();
787 break;
788 }
789
Owen Anderson61863942010-12-20 18:18:16 +0000790 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000791 return true;
Chris Lattner10f2d132009-11-11 00:22:30 +0000792}
793
Chris Lattner800c47e2009-11-15 20:02:12 +0000794/// getEdgeValue - This method attempts to infer more complex
Nick Lewycky90862ee2010-12-18 01:00:40 +0000795bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
796 BasicBlock *BBTo, LVILatticeVal &Result) {
797 // If already a constant, there is nothing to compute.
798 if (Constant *VC = dyn_cast<Constant>(Val)) {
799 Result = LVILatticeVal::get(VC);
800 return true;
801 }
802
Chris Lattner800c47e2009-11-15 20:02:12 +0000803 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
804 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000805 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
806 // If this is a conditional branch and only one successor goes to BBTo, then
807 // we maybe able to infer something from the condition.
808 if (BI->isConditional() &&
809 BI->getSuccessor(0) != BI->getSuccessor(1)) {
810 bool isTrueDest = BI->getSuccessor(0) == BBTo;
811 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
812 "BBTo isn't a successor of BBFrom");
813
814 // If V is the condition of the branch itself, then we know exactly what
815 // it is.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000816 if (BI->getCondition() == Val) {
817 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000818 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000819 return true;
820 }
Chris Lattner16976522009-11-11 22:48:44 +0000821
822 // If the condition of the branch is an equality comparison, we may be
823 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000824 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
825 if (ICI && ICI->getOperand(0) == Val &&
826 isa<Constant>(ICI->getOperand(1))) {
827 if (ICI->isEquality()) {
828 // We know that V has the RHS constant if this is a true SETEQ or
829 // false SETNE.
830 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000831 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
832 else
833 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
834 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000835 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000836
Owen Anderson2d0f2472010-08-11 04:24:25 +0000837 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
838 // Calculate the range of values that would satisfy the comparison.
839 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
840 ConstantRange TrueValues =
841 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000842
Owen Anderson2d0f2472010-08-11 04:24:25 +0000843 // If we're interested in the false dest, invert the condition.
844 if (!isTrueDest) TrueValues = TrueValues.inverse();
845
846 // Figure out the possible values of the query BEFORE this branch.
Owen Andersonbe419012011-01-05 21:37:18 +0000847 if (!hasBlockValue(Val, BBFrom)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000848 BlockValueStack.push(std::make_pair(BBFrom, Val));
Owen Andersonbe419012011-01-05 21:37:18 +0000849 return false;
850 }
851
Owen Andersonf33b3022010-12-09 06:14:58 +0000852 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000853 if (!InBlock.isConstantRange()) {
854 Result = LVILatticeVal::getRange(TrueValues);
855 return true;
856 }
857
Owen Anderson2d0f2472010-08-11 04:24:25 +0000858 // Find all potential values that satisfy both the input and output
859 // conditions.
860 ConstantRange PossibleValues =
861 TrueValues.intersectWith(InBlock.getConstantRange());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000862
863 Result = LVILatticeVal::getRange(PossibleValues);
864 return true;
Owen Anderson2d0f2472010-08-11 04:24:25 +0000865 }
866 }
Chris Lattner16976522009-11-11 22:48:44 +0000867 }
868 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000869
870 // If the edge was formed by a switch on the value, then we may know exactly
871 // what it is.
872 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000873 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000874 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000875 if (SI->getDefaultDest() == BBTo) {
Owen Anderson4caef602010-09-02 22:16:52 +0000876 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000877 return true;
Owen Andersondae90c62010-08-24 21:59:42 +0000878 }
879
Chris Lattner800c47e2009-11-15 20:02:12 +0000880 // We only know something if there is exactly one value that goes from
881 // BBFrom to BBTo.
882 unsigned NumEdges = 0;
883 ConstantInt *EdgeVal = 0;
884 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
885 if (SI->getSuccessor(i) != BBTo) continue;
886 if (NumEdges++) break;
887 EdgeVal = SI->getCaseValue(i);
888 }
889 assert(EdgeVal && "Missing successor?");
Nick Lewycky90862ee2010-12-18 01:00:40 +0000890 if (NumEdges == 1) {
891 Result = LVILatticeVal::get(EdgeVal);
892 return true;
893 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000894 }
895 }
Chris Lattner16976522009-11-11 22:48:44 +0000896
897 // Otherwise see if the value is known in the block.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000898 if (hasBlockValue(Val, BBFrom)) {
899 Result = getBlockValue(Val, BBFrom);
900 return true;
901 }
Owen Andersone68713a2011-01-05 23:26:22 +0000902 BlockValueStack.push(std::make_pair(BBFrom, Val));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000903 return false;
Chris Lattner16976522009-11-11 22:48:44 +0000904}
905
Chris Lattner2c5adf82009-11-15 19:59:49 +0000906LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000907 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000908 << BB->getName() << "'\n");
909
Owen Andersone68713a2011-01-05 23:26:22 +0000910 BlockValueStack.push(std::make_pair(BB, V));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000911 solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000912 LVILatticeVal Result = getBlockValue(V, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000913
David Greene5d93a1f2009-12-23 20:43:58 +0000914 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000915 return Result;
916}
Chris Lattner16976522009-11-11 22:48:44 +0000917
Chris Lattner2c5adf82009-11-15 19:59:49 +0000918LVILatticeVal LazyValueInfoCache::
919getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000920 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000921 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000922
Nick Lewycky90862ee2010-12-18 01:00:40 +0000923 LVILatticeVal Result;
924 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
925 solve();
926 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
927 (void)WasFastQuery;
928 assert(WasFastQuery && "More work to do after problem solved?");
929 }
930
David Greene5d93a1f2009-12-23 20:43:58 +0000931 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000932 return Result;
933}
934
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000935void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
936 BasicBlock *NewSucc) {
937 // When an edge in the graph has been threaded, values that we could not
938 // determine a value for before (i.e. were marked overdefined) may be possible
939 // to solve now. We do NOT try to proactively update these values. Instead,
940 // we clear their entries from the cache, and allow lazy updating to recompute
941 // them when needed.
942
943 // The updating process is fairly simple: we need to dropped cached info
944 // for all values that were marked overdefined in OldSucc, and for those same
945 // values in any successor of OldSucc (except NewSucc) in which they were
946 // also marked overdefined.
947 std::vector<BasicBlock*> worklist;
948 worklist.push_back(OldSucc);
949
Owen Anderson9a65dc92010-07-27 23:58:11 +0000950 DenseSet<Value*> ClearSet;
Owen Anderson89778462011-01-05 21:15:29 +0000951 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
952 E = OverDefinedCache.end(); I != E; ++I) {
Owen Anderson9a65dc92010-07-27 23:58:11 +0000953 if (I->first == OldSucc)
954 ClearSet.insert(I->second);
955 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000956
957 // Use a worklist to perform a depth-first search of OldSucc's successors.
958 // NOTE: We do not need a visited list since any blocks we have already
959 // visited will have had their overdefined markers cleared already, and we
960 // thus won't loop to their successors.
961 while (!worklist.empty()) {
962 BasicBlock *ToUpdate = worklist.back();
963 worklist.pop_back();
964
965 // Skip blocks only accessible through NewSucc.
966 if (ToUpdate == NewSucc) continue;
967
968 bool changed = false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000969 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000970 I != E; ++I) {
971 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson89778462011-01-05 21:15:29 +0000972 DenseSet<OverDefinedPairTy>::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000973 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
974 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000975
Owen Anderson9a65dc92010-07-27 23:58:11 +0000976 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000977 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000978 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000979
Owen Anderson9a65dc92010-07-27 23:58:11 +0000980 assert(CI != Entry.end() && "Couldn't find entry to update?");
981 Entry.erase(CI);
982 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000983
Owen Anderson9a65dc92010-07-27 23:58:11 +0000984 // If we removed anything, then we potentially need to update
985 // blocks successors too.
986 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000987 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000988
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000989 if (!changed) continue;
990
991 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
992 }
993}
994
Chris Lattner2c5adf82009-11-15 19:59:49 +0000995//===----------------------------------------------------------------------===//
996// LazyValueInfo Impl
997//===----------------------------------------------------------------------===//
998
Chris Lattner2c5adf82009-11-15 19:59:49 +0000999/// getCache - This lazily constructs the LazyValueInfoCache.
1000static LazyValueInfoCache &getCache(void *&PImpl) {
1001 if (!PImpl)
1002 PImpl = new LazyValueInfoCache();
1003 return *static_cast<LazyValueInfoCache*>(PImpl);
1004}
1005
Owen Anderson00ac77e2010-08-18 18:39:01 +00001006bool LazyValueInfo::runOnFunction(Function &F) {
1007 if (PImpl)
1008 getCache(PImpl).clear();
1009
1010 TD = getAnalysisIfAvailable<TargetData>();
1011 // Fully lazy.
1012 return false;
1013}
1014
Chris Lattner2c5adf82009-11-15 19:59:49 +00001015void LazyValueInfo::releaseMemory() {
1016 // If the cache was allocated, free it.
1017 if (PImpl) {
1018 delete &getCache(PImpl);
1019 PImpl = 0;
1020 }
1021}
1022
1023Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1024 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1025
Chris Lattner16976522009-11-11 22:48:44 +00001026 if (Result.isConstant())
1027 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001028 if (Result.isConstantRange()) {
Owen Andersonee61fcf2010-08-27 23:29:38 +00001029 ConstantRange CR = Result.getConstantRange();
1030 if (const APInt *SingleVal = CR.getSingleElement())
1031 return ConstantInt::get(V->getContext(), *SingleVal);
1032 }
Chris Lattner16976522009-11-11 22:48:44 +00001033 return 0;
1034}
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001035
Chris Lattner38392bb2009-11-12 01:29:10 +00001036/// getConstantOnEdge - Determine whether the specified value is known to be a
1037/// constant on the specified edge. Return null if not.
1038Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1039 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001040 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +00001041
1042 if (Result.isConstant())
1043 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001044 if (Result.isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +00001045 ConstantRange CR = Result.getConstantRange();
1046 if (const APInt *SingleVal = CR.getSingleElement())
1047 return ConstantInt::get(V->getContext(), *SingleVal);
1048 }
Chris Lattner38392bb2009-11-12 01:29:10 +00001049 return 0;
1050}
1051
Chris Lattnerb52675b2009-11-12 04:36:58 +00001052/// getPredicateOnEdge - Determine whether the specified value comparison
1053/// with a constant is known to be true or false on the specified CFG edge.
1054/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001055LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +00001056LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1057 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001058 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001059
Chris Lattnerb52675b2009-11-12 04:36:58 +00001060 // If we know the value is a constant, evaluate the conditional.
1061 Constant *Res = 0;
1062 if (Result.isConstant()) {
1063 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001064 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Chris Lattnerb52675b2009-11-12 04:36:58 +00001065 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +00001066 return Unknown;
1067 }
1068
Owen Anderson9f014062010-08-10 20:03:09 +00001069 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +00001070 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1071 if (!CI) return Unknown;
1072
Owen Anderson9f014062010-08-10 20:03:09 +00001073 ConstantRange CR = Result.getConstantRange();
1074 if (Pred == ICmpInst::ICMP_EQ) {
1075 if (!CR.contains(CI->getValue()))
1076 return False;
1077
1078 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1079 return True;
1080 } else if (Pred == ICmpInst::ICMP_NE) {
1081 if (!CR.contains(CI->getValue()))
1082 return True;
1083
1084 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1085 return False;
1086 }
1087
1088 // Handle more complex predicates.
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001089 ConstantRange TrueValues =
1090 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1091 if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +00001092 return True;
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001093 if (TrueValues.inverse().contains(CR))
1094 return False;
Owen Anderson9f014062010-08-10 20:03:09 +00001095 return Unknown;
1096 }
1097
Chris Lattner2c5adf82009-11-15 19:59:49 +00001098 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +00001099 // If this is an equality comparison, we can try to fold it knowing that
1100 // "V != C1".
1101 if (Pred == ICmpInst::ICMP_EQ) {
1102 // !C1 == C -> false iff C1 == C.
1103 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1104 Result.getNotConstant(), C, TD);
1105 if (Res->isNullValue())
1106 return False;
1107 } else if (Pred == ICmpInst::ICMP_NE) {
1108 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +00001109 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +00001110 Result.getNotConstant(), C, TD);
1111 if (Res->isNullValue())
1112 return True;
1113 }
Chris Lattner2c5adf82009-11-15 19:59:49 +00001114 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +00001115 }
1116
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001117 return Unknown;
1118}
1119
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001120void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001121 BasicBlock *NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +00001122 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1123}
1124
1125void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1126 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001127}