blob: e32dbc444713543474922870fe861998046d2f0e [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"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000017#include "llvm/Constants.h"
18#include "llvm/Instructions.h"
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Target/TargetData.h"
Chris Lattner16976522009-11-11 22:48:44 +000021#include "llvm/Support/CFG.h"
Owen Anderson5be2e782010-08-05 22:59:19 +000022#include "llvm/Support/ConstantRange.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000023#include "llvm/Support/Debug.h"
Chris Lattner16976522009-11-11 22:48:44 +000024#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000025#include "llvm/Support/ValueHandle.h"
Chris Lattner16976522009-11-11 22:48:44 +000026#include "llvm/ADT/DenseMap.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000027#include "llvm/ADT/DenseSet.h"
Chris Lattnere5642812009-11-15 20:00:52 +000028#include "llvm/ADT/STLExtras.h"
Chris Lattner10f2d132009-11-11 00:22:30 +000029using namespace llvm;
30
31char LazyValueInfo::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000032INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
33 "Lazy Value Information Analysis", false, true);
Chris Lattner10f2d132009-11-11 00:22:30 +000034
35namespace llvm {
36 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
37}
38
Chris Lattnercc4d3b22009-11-11 02:08:33 +000039
40//===----------------------------------------------------------------------===//
41// LVILatticeVal
42//===----------------------------------------------------------------------===//
43
44/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
45/// value.
46///
47/// FIXME: This is basically just for bringup, this can be made a lot more rich
48/// in the future.
49///
50namespace {
51class LVILatticeVal {
52 enum LatticeValueTy {
53 /// undefined - This LLVM Value has no known value yet.
54 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000055
Chris Lattnercc4d3b22009-11-11 02:08:33 +000056 /// constant - This LLVM Value has a specific constant value.
57 constant,
Chris Lattnerb52675b2009-11-12 04:36:58 +000058 /// notconstant - This LLVM value is known to not have the specified value.
59 notconstant,
60
Owen Anderson5be2e782010-08-05 22:59:19 +000061 /// constantrange
62 constantrange,
63
Chris Lattnercc4d3b22009-11-11 02:08:33 +000064 /// overdefined - This instruction is not known to be constant, and we know
65 /// it has a value.
66 overdefined
67 };
68
69 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000070 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000071 LatticeValueTy Tag;
72 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000073 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000074
75public:
Owen Anderson5be2e782010-08-05 22:59:19 +000076 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000077
Chris Lattner16976522009-11-11 22:48:44 +000078 static LVILatticeVal get(Constant *C) {
79 LVILatticeVal Res;
Owen Anderson9f014062010-08-10 20:03:09 +000080 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
81 Res.markConstantRange(ConstantRange(CI->getValue(), CI->getValue()+1));
82 else if (!isa<UndefValue>(C))
83 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000084 return Res;
85 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000086 static LVILatticeVal getNot(Constant *C) {
87 LVILatticeVal Res;
Owen Anderson9f014062010-08-10 20:03:09 +000088 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
89 Res.markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
90 else
91 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) {
132 if (isConstant()) {
133 assert(getConstant() == V && "Marking constant with different value");
134 return false;
135 }
136
137 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000138 Tag = constant;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000139 assert(V && "Marking constant with NULL");
Owen Andersondb78d732010-08-05 22:10:46 +0000140 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000141 return true;
142 }
143
Chris Lattnerb52675b2009-11-12 04:36:58 +0000144 /// markNotConstant - Return true if this is a change in status.
145 bool markNotConstant(Constant *V) {
146 if (isNotConstant()) {
147 assert(getNotConstant() == V && "Marking !constant with different value");
148 return false;
149 }
150
151 if (isConstant())
152 assert(getConstant() != V && "Marking not constant with different value");
153 else
154 assert(isUndefined());
155
Owen Andersondb78d732010-08-05 22:10:46 +0000156 Tag = notconstant;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000157 assert(V && "Marking constant with NULL");
Owen Andersondb78d732010-08-05 22:10:46 +0000158 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000159 return true;
160 }
161
Owen Anderson5be2e782010-08-05 22:59:19 +0000162 /// markConstantRange - Return true if this is a change in status.
163 bool markConstantRange(const ConstantRange NewR) {
164 if (isConstantRange()) {
165 if (NewR.isEmptySet())
166 return markOverdefined();
167
Owen Anderson5be2e782010-08-05 22:59:19 +0000168 bool changed = Range == NewR;
169 Range = NewR;
170 return changed;
171 }
172
173 assert(isUndefined());
174 if (NewR.isEmptySet())
175 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000176
177 Tag = constantrange;
178 Range = NewR;
179 return true;
180 }
181
Chris Lattner16976522009-11-11 22:48:44 +0000182 /// mergeIn - Merge the specified lattice value into this one, updating this
183 /// one and returning true if anything changed.
184 bool mergeIn(const LVILatticeVal &RHS) {
185 if (RHS.isUndefined() || isOverdefined()) return false;
186 if (RHS.isOverdefined()) return markOverdefined();
187
Chris Lattnerb52675b2009-11-12 04:36:58 +0000188 if (RHS.isNotConstant()) {
189 if (isNotConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000190 if (getNotConstant() != RHS.getNotConstant() ||
191 isa<ConstantExpr>(getNotConstant()) ||
192 isa<ConstantExpr>(RHS.getNotConstant()))
Chris Lattnerb52675b2009-11-12 04:36:58 +0000193 return markOverdefined();
194 return false;
Owen Anderson39295322010-08-30 17:03:45 +0000195 } else if (isConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000196 if (getConstant() == RHS.getNotConstant() ||
197 isa<ConstantExpr>(RHS.getNotConstant()) ||
198 isa<ConstantExpr>(getConstant()))
199 return markOverdefined();
200 return markNotConstant(RHS.getNotConstant());
Owen Anderson39295322010-08-30 17:03:45 +0000201 } else if (isConstantRange()) {
202 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000203 }
204
205 assert(isUndefined() && "Unexpected lattice");
Chris Lattnerb52675b2009-11-12 04:36:58 +0000206 return markNotConstant(RHS.getNotConstant());
207 }
208
Owen Anderson5be2e782010-08-05 22:59:19 +0000209 if (RHS.isConstantRange()) {
210 if (isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +0000211 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
212 if (NewR.isFullSet())
Owen Anderson5be2e782010-08-05 22:59:19 +0000213 return markOverdefined();
214 else
215 return markConstantRange(NewR);
Owen Anderson59b06dc2010-08-24 07:55:44 +0000216 } else if (!isUndefined()) {
217 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000218 }
219
220 assert(isUndefined() && "Unexpected lattice");
221 return markConstantRange(RHS.getConstantRange());
222 }
223
Chris Lattnerf496e792009-11-12 04:57:13 +0000224 // RHS must be a constant, we must be undef, constant, or notconstant.
Owen Anderson5be2e782010-08-05 22:59:19 +0000225 assert(!isConstantRange() &&
226 "Constant and ConstantRange cannot be merged.");
227
Chris Lattnerf496e792009-11-12 04:57:13 +0000228 if (isUndefined())
229 return markConstant(RHS.getConstant());
230
231 if (isConstant()) {
232 if (getConstant() != RHS.getConstant())
233 return markOverdefined();
234 return false;
235 }
236
237 // If we are known "!=4" and RHS is "==5", stay at "!=4".
238 if (getNotConstant() == RHS.getConstant() ||
239 isa<ConstantExpr>(getNotConstant()) ||
240 isa<ConstantExpr>(RHS.getConstant()))
Chris Lattner16976522009-11-11 22:48:44 +0000241 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000242 return false;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000243 }
244
245};
246
247} // end anonymous namespace.
248
Chris Lattner16976522009-11-11 22:48:44 +0000249namespace llvm {
250raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
251 if (Val.isUndefined())
252 return OS << "undefined";
253 if (Val.isOverdefined())
254 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000255
256 if (Val.isNotConstant())
257 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000258 else if (Val.isConstantRange())
259 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
260 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000261 return OS << "constant<" << *Val.getConstant() << '>';
262}
263}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000264
265//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000266// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000267//===----------------------------------------------------------------------===//
268
Chris Lattner2c5adf82009-11-15 19:59:49 +0000269namespace {
270 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
271 /// maintains information about queries across the clients' queries.
272 class LazyValueInfoCache {
Owen Anderson81881bc2010-07-30 20:56:07 +0000273 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000274 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
275 /// specified basic block for a Value* that depends on context.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000276 typedef std::pair<AssertingVH<BasicBlock>, LVILatticeVal> BlockCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000277
278 /// ValueCacheEntryTy - This is all of the cached block information for
279 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
280 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000281 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000282
Owen Anderson81881bc2010-07-30 20:56:07 +0000283 private:
Owen Anderson7f9cb742010-07-30 23:59:40 +0000284 /// LVIValueHandle - A callback value handle update the cache when
285 /// values are erased.
286 struct LVIValueHandle : public CallbackVH {
287 LazyValueInfoCache *Parent;
288
289 LVIValueHandle(Value *V, LazyValueInfoCache *P)
290 : CallbackVH(V), Parent(P) { }
291
292 void deleted();
293 void allUsesReplacedWith(Value* V) {
294 deleted();
295 }
296
297 LVIValueHandle &operator=(Value *V) {
298 return *this = LVIValueHandle(V, Parent);
299 }
300 };
301
Chris Lattner2c5adf82009-11-15 19:59:49 +0000302 /// ValueCache - This is all of the cached information for all values,
303 /// mapped from Value* to key information.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000304 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000305
306 /// OverDefinedCache - This tracks, on a per-block basis, the set of
307 /// values that are over-defined at the end of that block. This is required
308 /// for cache updating.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000309 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000310
Chris Lattner2c5adf82009-11-15 19:59:49 +0000311 public:
312
313 /// getValueInBlock - This is the query interface to determine the lattice
314 /// value for the specified Value* at the end of the specified block.
315 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
316
317 /// getValueOnEdge - This is the query interface to determine the lattice
318 /// value for the specified Value* that is true on the specified edge.
319 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000320
321 /// threadEdge - This is the update interface to inform the cache that an
322 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
323 /// NewSucc.
324 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000325
326 /// eraseBlock - This is part of the update interface to inform the cache
327 /// that a block has been deleted.
328 void eraseBlock(BasicBlock *BB);
329
330 /// clear - Empty the cache.
331 void clear() {
332 ValueCache.clear();
333 OverDefinedCache.clear();
334 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000335 };
336} // end anonymous namespace
337
Owen Anderson81881bc2010-07-30 20:56:07 +0000338//===----------------------------------------------------------------------===//
339// LVIQuery Impl
340//===----------------------------------------------------------------------===//
341
342namespace {
343 /// LVIQuery - This is a transient object that exists while a query is
344 /// being performed.
345 ///
346 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
347 /// reallocation of the densemap on every query.
348 class LVIQuery {
349 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
350 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
351
352 /// This is the current value being queried for.
353 Value *Val;
354
Owen Anderson7f9cb742010-07-30 23:59:40 +0000355 /// This is a pointer to the owning cache, for recursive queries.
356 LazyValueInfoCache &Parent;
357
Owen Anderson81881bc2010-07-30 20:56:07 +0000358 /// This is all of the cached information about this value.
359 ValueCacheEntryTy &Cache;
360
361 /// This tracks, for each block, what values are overdefined.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000362 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &OverDefinedCache;
Owen Anderson81881bc2010-07-30 20:56:07 +0000363
364 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
365 /// added to cache but that are not in sorted order.
366 DenseSet<BasicBlock*> NewBlockInfo;
Owen Andersonc8ef7502010-08-24 20:47:29 +0000367
Owen Anderson81881bc2010-07-30 20:56:07 +0000368 public:
369
Owen Anderson7f9cb742010-07-30 23:59:40 +0000370 LVIQuery(Value *V, LazyValueInfoCache &P,
371 ValueCacheEntryTy &VC,
Owen Anderson00ac77e2010-08-18 18:39:01 +0000372 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &ODC)
Owen Anderson7f9cb742010-07-30 23:59:40 +0000373 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000374 }
375
376 ~LVIQuery() {
377 // When the query is done, insert the newly discovered facts into the
378 // cache in sorted order.
379 if (NewBlockInfo.empty()) return;
380
381 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
382 E = NewBlockInfo.end(); I != E; ++I) {
383 if (Cache[*I].isOverdefined())
384 OverDefinedCache.insert(std::make_pair(*I, Val));
385 }
386 }
387
388 LVILatticeVal getBlockValue(BasicBlock *BB);
389 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
390
391 private:
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000392 LVILatticeVal getCachedEntryForBlock(BasicBlock *BB);
Owen Anderson81881bc2010-07-30 20:56:07 +0000393 };
394} // end anonymous namespace
Chris Lattner2c5adf82009-11-15 19:59:49 +0000395
Owen Anderson7f9cb742010-07-30 23:59:40 +0000396void LazyValueInfoCache::LVIValueHandle::deleted() {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000397 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000398 I = Parent->OverDefinedCache.begin(),
399 E = Parent->OverDefinedCache.end();
400 I != E; ) {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000401 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000402 ++I;
403 if (tmp->second == getValPtr())
404 Parent->OverDefinedCache.erase(tmp);
405 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000406
407 // This erasure deallocates *this, so it MUST happen after we're done
408 // using any and all members of *this.
409 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000410}
411
Owen Anderson00ac77e2010-08-18 18:39:01 +0000412void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
413 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
414 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
415 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
416 ++I;
417 if (tmp->first == BB)
418 OverDefinedCache.erase(tmp);
419 }
420
421 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
422 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
423 I->second.erase(BB);
424}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000425
Chris Lattnere5642812009-11-15 20:00:52 +0000426/// getCachedEntryForBlock - See if we already have a value for this block. If
Owen Anderson9a65dc92010-07-27 23:58:11 +0000427/// so, return it, otherwise create a new entry in the Cache map to use.
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000428LVILatticeVal LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000429 NewBlockInfo.insert(BB);
Owen Anderson9a65dc92010-07-27 23:58:11 +0000430 return Cache[BB];
Chris Lattnere5642812009-11-15 20:00:52 +0000431}
Chris Lattner2c5adf82009-11-15 19:59:49 +0000432
Owen Anderson81881bc2010-07-30 20:56:07 +0000433LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000434 // See if we already have a value for this block.
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000435 LVILatticeVal BBLV = getCachedEntryForBlock(BB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000436
437 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000438 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000439 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Chris Lattner2c5adf82009-11-15 19:59:49 +0000440 return BBLV;
Chris Lattnere5642812009-11-15 20:00:52 +0000441 }
442
Chris Lattner2c5adf82009-11-15 19:59:49 +0000443 // Otherwise, this is the first time we're seeing this block. Reset the
444 // lattice value to overdefined, so that cycles will terminate and be
445 // conservatively correct.
446 BBLV.markOverdefined();
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000447 Cache[BB] = BBLV;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000448
Chris Lattner2c5adf82009-11-15 19:59:49 +0000449 Instruction *BBI = dyn_cast<Instruction>(Val);
450 if (BBI == 0 || BBI->getParent() != BB) {
451 LVILatticeVal Result; // Start Undefined.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000452
Owen Andersonc8ef7502010-08-24 20:47:29 +0000453 // If this is a pointer, and there's a load from that pointer in this BB,
454 // then we know that the pointer can't be NULL.
Owen Anderson1593dd62010-09-03 19:08:37 +0000455 bool NotNull = false;
Owen Andersonc8ef7502010-08-24 20:47:29 +0000456 if (Val->getType()->isPointerTy()) {
Owen Anderson6cd20752010-08-25 01:16:47 +0000457 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
458 LoadInst *L = dyn_cast<LoadInst>(BI);
459 if (L && L->getPointerAddressSpace() == 0 &&
460 L->getPointerOperand()->getUnderlyingObject() ==
461 Val->getUnderlyingObject()) {
Owen Anderson1593dd62010-09-03 19:08:37 +0000462 NotNull = true;
463 break;
Owen Andersonc8ef7502010-08-24 20:47:29 +0000464 }
465 }
466 }
467
468 unsigned NumPreds = 0;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000469 // Loop over all of our predecessors, merging what we know from them into
470 // result.
471 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000472 Result.mergeIn(getEdgeValue(*PI, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000473
474 // If we hit overdefined, exit early. The BlockVals entry is already set
475 // to overdefined.
Chris Lattnere5642812009-11-15 20:00:52 +0000476 if (Result.isOverdefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000477 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000478 << "' - overdefined because of pred.\n");
Owen Anderson1593dd62010-09-03 19:08:37 +0000479 // If we previously determined that this is a pointer that can't be null
480 // then return that rather than giving up entirely.
481 if (NotNull) {
482 const PointerType *PTy = cast<PointerType>(Val->getType());
483 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
484 }
485
Chris Lattner2c5adf82009-11-15 19:59:49 +0000486 return Result;
Chris Lattnere5642812009-11-15 20:00:52 +0000487 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000488 ++NumPreds;
489 }
490
Owen Anderson1593dd62010-09-03 19:08:37 +0000491
Chris Lattner2c5adf82009-11-15 19:59:49 +0000492 // If this is the entry block, we must be asking about an argument. The
493 // value is overdefined.
494 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
495 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
496 Result.markOverdefined();
497 return Result;
498 }
499
500 // Return the merged value, which is more precise than 'overdefined'.
501 assert(!Result.isOverdefined());
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000502 return Cache[BB] = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000503 }
504
505 // If this value is defined by an instruction in this block, we have to
506 // process it here somehow or return overdefined.
507 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson7f9cb742010-07-30 23:59:40 +0000508 LVILatticeVal Result; // Start Undefined.
509
510 // Loop over all of our predecessors, merging what we know from them into
511 // result.
512 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
513 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
514 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
515
516 // If we hit overdefined, exit early. The BlockVals entry is already set
517 // to overdefined.
518 if (Result.isOverdefined()) {
519 DEBUG(dbgs() << " compute BB '" << BB->getName()
520 << "' - overdefined because of pred.\n");
521 return Result;
522 }
523 }
524
525 // Return the merged value, which is more precise than 'overdefined'.
526 assert(!Result.isOverdefined());
Owen Anderson00ac77e2010-08-18 18:39:01 +0000527 return Cache[BB] = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000528 }
Chris Lattnere5642812009-11-15 20:00:52 +0000529
Owen Andersonb81fd622010-08-18 21:11:37 +0000530 assert(Cache[BB].isOverdefined() && "Recursive query changed our cache?");
531
532 // We can only analyze the definitions of certain classes of instructions
533 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000534 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000535 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
536 !BBI->getType()->isIntegerTy()) {
537 DEBUG(dbgs() << " compute BB '" << BB->getName()
538 << "' - overdefined because inst def found.\n");
539 Result.markOverdefined();
540 return Result;
541 }
542
543 // FIXME: We're currently limited to binops with a constant RHS. This should
544 // be improved.
545 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
546 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
547 DEBUG(dbgs() << " compute BB '" << BB->getName()
548 << "' - overdefined because inst def found.\n");
549
550 Result.markOverdefined();
551 return Result;
552 }
553
554 // Figure out the range of the LHS. If that fails, bail.
555 LVILatticeVal LHSVal = Parent.getValueInBlock(BBI->getOperand(0), BB);
556 if (!LHSVal.isConstantRange()) {
557 Result.markOverdefined();
558 return Result;
559 }
560
561 ConstantInt *RHS = 0;
562 ConstantRange LHSRange = LHSVal.getConstantRange();
563 ConstantRange RHSRange(1);
564 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
565 if (isa<BinaryOperator>(BBI)) {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000566 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
567 if (!RHS) {
568 Result.markOverdefined();
569 return Result;
570 }
571
Owen Andersonb81fd622010-08-18 21:11:37 +0000572 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
573 }
574
575 // NOTE: We're currently limited by the set of operations that ConstantRange
576 // can evaluate symbolically. Enhancing that set will allows us to analyze
577 // more definitions.
578 switch (BBI->getOpcode()) {
579 case Instruction::Add:
580 Result.markConstantRange(LHSRange.add(RHSRange));
581 break;
582 case Instruction::Sub:
583 Result.markConstantRange(LHSRange.sub(RHSRange));
584 break;
585 case Instruction::Mul:
586 Result.markConstantRange(LHSRange.multiply(RHSRange));
587 break;
588 case Instruction::UDiv:
589 Result.markConstantRange(LHSRange.udiv(RHSRange));
590 break;
591 case Instruction::Shl:
592 Result.markConstantRange(LHSRange.shl(RHSRange));
593 break;
594 case Instruction::LShr:
595 Result.markConstantRange(LHSRange.lshr(RHSRange));
596 break;
597 case Instruction::Trunc:
598 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
599 break;
600 case Instruction::SExt:
601 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
602 break;
603 case Instruction::ZExt:
604 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
605 break;
606 case Instruction::BitCast:
607 Result.markConstantRange(LHSRange);
608 break;
609
610 // Unhandled instructions are overdefined.
611 default:
612 DEBUG(dbgs() << " compute BB '" << BB->getName()
613 << "' - overdefined because inst def found.\n");
614 Result.markOverdefined();
615 break;
616 }
617
618 return Cache[BB] = Result;
Chris Lattner10f2d132009-11-11 00:22:30 +0000619}
620
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000621
Chris Lattner800c47e2009-11-15 20:02:12 +0000622/// getEdgeValue - This method attempts to infer more complex
Owen Anderson81881bc2010-07-30 20:56:07 +0000623LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
Chris Lattner800c47e2009-11-15 20:02:12 +0000624 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
625 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000626 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
627 // If this is a conditional branch and only one successor goes to BBTo, then
628 // we maybe able to infer something from the condition.
629 if (BI->isConditional() &&
630 BI->getSuccessor(0) != BI->getSuccessor(1)) {
631 bool isTrueDest = BI->getSuccessor(0) == BBTo;
632 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
633 "BBTo isn't a successor of BBFrom");
634
635 // If V is the condition of the branch itself, then we know exactly what
636 // it is.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000637 if (BI->getCondition() == Val)
Chris Lattner16976522009-11-11 22:48:44 +0000638 return LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000639 Type::getInt1Ty(Val->getContext()), isTrueDest));
Chris Lattner16976522009-11-11 22:48:44 +0000640
641 // If the condition of the branch is an equality comparison, we may be
642 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000643 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
644 if (ICI && ICI->getOperand(0) == Val &&
645 isa<Constant>(ICI->getOperand(1))) {
646 if (ICI->isEquality()) {
647 // We know that V has the RHS constant if this is a true SETEQ or
648 // false SETNE.
649 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
650 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
651 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
Chris Lattner16976522009-11-11 22:48:44 +0000652 }
Owen Anderson2d0f2472010-08-11 04:24:25 +0000653
654 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
655 // Calculate the range of values that would satisfy the comparison.
656 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
657 ConstantRange TrueValues =
658 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
659
660 // If we're interested in the false dest, invert the condition.
661 if (!isTrueDest) TrueValues = TrueValues.inverse();
662
663 // Figure out the possible values of the query BEFORE this branch.
664 LVILatticeVal InBlock = getBlockValue(BBFrom);
Owen Anderson660cab32010-08-27 17:12:29 +0000665 if (!InBlock.isConstantRange())
666 return LVILatticeVal::getRange(TrueValues);
Owen Anderson2d0f2472010-08-11 04:24:25 +0000667
668 // Find all potential values that satisfy both the input and output
669 // conditions.
670 ConstantRange PossibleValues =
671 TrueValues.intersectWith(InBlock.getConstantRange());
672
673 return LVILatticeVal::getRange(PossibleValues);
674 }
675 }
Chris Lattner16976522009-11-11 22:48:44 +0000676 }
677 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000678
679 // If the edge was formed by a switch on the value, then we may know exactly
680 // what it is.
681 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000682 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000683 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000684 if (SI->getDefaultDest() == BBTo) {
Owen Andersondae90c62010-08-24 21:59:42 +0000685 LVILatticeVal Result;
Owen Anderson4caef602010-09-02 22:16:52 +0000686 Result.markOverdefined();
Owen Andersondae90c62010-08-24 21:59:42 +0000687 return Result;
688 }
689
Chris Lattner800c47e2009-11-15 20:02:12 +0000690 // We only know something if there is exactly one value that goes from
691 // BBFrom to BBTo.
692 unsigned NumEdges = 0;
693 ConstantInt *EdgeVal = 0;
694 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
695 if (SI->getSuccessor(i) != BBTo) continue;
696 if (NumEdges++) break;
697 EdgeVal = SI->getCaseValue(i);
698 }
699 assert(EdgeVal && "Missing successor?");
700 if (NumEdges == 1)
701 return LVILatticeVal::get(EdgeVal);
702 }
703 }
Chris Lattner16976522009-11-11 22:48:44 +0000704
705 // Otherwise see if the value is known in the block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000706 return getBlockValue(BBFrom);
Chris Lattner16976522009-11-11 22:48:44 +0000707}
708
Owen Anderson81881bc2010-07-30 20:56:07 +0000709
710//===----------------------------------------------------------------------===//
711// LazyValueInfoCache Impl
712//===----------------------------------------------------------------------===//
713
Chris Lattner2c5adf82009-11-15 19:59:49 +0000714LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
715 // If already a constant, there is nothing to compute.
Chris Lattner16976522009-11-11 22:48:44 +0000716 if (Constant *VC = dyn_cast<Constant>(V))
Chris Lattner2c5adf82009-11-15 19:59:49 +0000717 return LVILatticeVal::get(VC);
Chris Lattner16976522009-11-11 22:48:44 +0000718
David Greene5d93a1f2009-12-23 20:43:58 +0000719 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000720 << BB->getName() << "'\n");
721
Owen Anderson7f9cb742010-07-30 23:59:40 +0000722 LVILatticeVal Result = LVIQuery(V, *this,
Owen Andersonc8ef7502010-08-24 20:47:29 +0000723 ValueCache[LVIValueHandle(V, this)],
724 OverDefinedCache).getBlockValue(BB);
Chris Lattner16976522009-11-11 22:48:44 +0000725
David Greene5d93a1f2009-12-23 20:43:58 +0000726 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000727 return Result;
728}
Chris Lattner16976522009-11-11 22:48:44 +0000729
Chris Lattner2c5adf82009-11-15 19:59:49 +0000730LVILatticeVal LazyValueInfoCache::
731getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
732 // If already a constant, there is nothing to compute.
733 if (Constant *VC = dyn_cast<Constant>(V))
734 return LVILatticeVal::get(VC);
735
David Greene5d93a1f2009-12-23 20:43:58 +0000736 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000737 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000738
Owen Anderson81881bc2010-07-30 20:56:07 +0000739 LVILatticeVal Result =
Owen Anderson7f9cb742010-07-30 23:59:40 +0000740 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000741 OverDefinedCache).getEdgeValue(FromBB, ToBB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000742
David Greene5d93a1f2009-12-23 20:43:58 +0000743 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000744
745 return Result;
746}
747
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000748void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
749 BasicBlock *NewSucc) {
750 // When an edge in the graph has been threaded, values that we could not
751 // determine a value for before (i.e. were marked overdefined) may be possible
752 // to solve now. We do NOT try to proactively update these values. Instead,
753 // we clear their entries from the cache, and allow lazy updating to recompute
754 // them when needed.
755
756 // The updating process is fairly simple: we need to dropped cached info
757 // for all values that were marked overdefined in OldSucc, and for those same
758 // values in any successor of OldSucc (except NewSucc) in which they were
759 // also marked overdefined.
760 std::vector<BasicBlock*> worklist;
761 worklist.push_back(OldSucc);
762
Owen Anderson9a65dc92010-07-27 23:58:11 +0000763 DenseSet<Value*> ClearSet;
Owen Anderson00ac77e2010-08-18 18:39:01 +0000764 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson9a65dc92010-07-27 23:58:11 +0000765 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
766 if (I->first == OldSucc)
767 ClearSet.insert(I->second);
768 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000769
770 // Use a worklist to perform a depth-first search of OldSucc's successors.
771 // NOTE: We do not need a visited list since any blocks we have already
772 // visited will have had their overdefined markers cleared already, and we
773 // thus won't loop to their successors.
774 while (!worklist.empty()) {
775 BasicBlock *ToUpdate = worklist.back();
776 worklist.pop_back();
777
778 // Skip blocks only accessible through NewSucc.
779 if (ToUpdate == NewSucc) continue;
780
781 bool changed = false;
Owen Anderson9a65dc92010-07-27 23:58:11 +0000782 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000783 I != E; ++I) {
784 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson00ac77e2010-08-18 18:39:01 +0000785 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000786 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
787 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000788
Owen Anderson9a65dc92010-07-27 23:58:11 +0000789 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000790 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000791 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
792
793 assert(CI != Entry.end() && "Couldn't find entry to update?");
794 Entry.erase(CI);
795 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000796
Owen Anderson9a65dc92010-07-27 23:58:11 +0000797 // If we removed anything, then we potentially need to update
798 // blocks successors too.
799 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000800 }
801
802 if (!changed) continue;
803
804 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
805 }
806}
807
Chris Lattner2c5adf82009-11-15 19:59:49 +0000808//===----------------------------------------------------------------------===//
809// LazyValueInfo Impl
810//===----------------------------------------------------------------------===//
811
Chris Lattner2c5adf82009-11-15 19:59:49 +0000812/// getCache - This lazily constructs the LazyValueInfoCache.
813static LazyValueInfoCache &getCache(void *&PImpl) {
814 if (!PImpl)
815 PImpl = new LazyValueInfoCache();
816 return *static_cast<LazyValueInfoCache*>(PImpl);
817}
818
Owen Anderson00ac77e2010-08-18 18:39:01 +0000819bool LazyValueInfo::runOnFunction(Function &F) {
820 if (PImpl)
821 getCache(PImpl).clear();
822
823 TD = getAnalysisIfAvailable<TargetData>();
824 // Fully lazy.
825 return false;
826}
827
Chris Lattner2c5adf82009-11-15 19:59:49 +0000828void LazyValueInfo::releaseMemory() {
829 // If the cache was allocated, free it.
830 if (PImpl) {
831 delete &getCache(PImpl);
832 PImpl = 0;
833 }
834}
835
836Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
837 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
838
Chris Lattner16976522009-11-11 22:48:44 +0000839 if (Result.isConstant())
840 return Result.getConstant();
Owen Andersonee61fcf2010-08-27 23:29:38 +0000841 else if (Result.isConstantRange()) {
842 ConstantRange CR = Result.getConstantRange();
843 if (const APInt *SingleVal = CR.getSingleElement())
844 return ConstantInt::get(V->getContext(), *SingleVal);
845 }
Chris Lattner16976522009-11-11 22:48:44 +0000846 return 0;
847}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000848
Chris Lattner38392bb2009-11-12 01:29:10 +0000849/// getConstantOnEdge - Determine whether the specified value is known to be a
850/// constant on the specified edge. Return null if not.
851Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
852 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000853 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +0000854
855 if (Result.isConstant())
856 return Result.getConstant();
Owen Anderson9f014062010-08-10 20:03:09 +0000857 else if (Result.isConstantRange()) {
858 ConstantRange CR = Result.getConstantRange();
859 if (const APInt *SingleVal = CR.getSingleElement())
860 return ConstantInt::get(V->getContext(), *SingleVal);
861 }
Chris Lattner38392bb2009-11-12 01:29:10 +0000862 return 0;
863}
864
Chris Lattnerb52675b2009-11-12 04:36:58 +0000865/// getPredicateOnEdge - Determine whether the specified value comparison
866/// with a constant is known to be true or false on the specified CFG edge.
867/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000868LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +0000869LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
870 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000871 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000872
Chris Lattnerb52675b2009-11-12 04:36:58 +0000873 // If we know the value is a constant, evaluate the conditional.
874 Constant *Res = 0;
875 if (Result.isConstant()) {
876 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
877 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
878 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000879 return Unknown;
880 }
881
Owen Anderson9f014062010-08-10 20:03:09 +0000882 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000883 ConstantInt *CI = dyn_cast<ConstantInt>(C);
884 if (!CI) return Unknown;
885
Owen Anderson9f014062010-08-10 20:03:09 +0000886 ConstantRange CR = Result.getConstantRange();
887 if (Pred == ICmpInst::ICMP_EQ) {
888 if (!CR.contains(CI->getValue()))
889 return False;
890
891 if (CR.isSingleElement() && CR.contains(CI->getValue()))
892 return True;
893 } else if (Pred == ICmpInst::ICMP_NE) {
894 if (!CR.contains(CI->getValue()))
895 return True;
896
897 if (CR.isSingleElement() && CR.contains(CI->getValue()))
898 return False;
899 }
900
901 // Handle more complex predicates.
902 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
903 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
904 if (CR.intersectWith(TrueValues).isEmptySet())
905 return False;
Owen Anderson625051b2010-08-10 23:20:01 +0000906 else if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +0000907 return True;
908
909 return Unknown;
910 }
911
Chris Lattner2c5adf82009-11-15 19:59:49 +0000912 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000913 // If this is an equality comparison, we can try to fold it knowing that
914 // "V != C1".
915 if (Pred == ICmpInst::ICMP_EQ) {
916 // !C1 == C -> false iff C1 == C.
917 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
918 Result.getNotConstant(), C, TD);
919 if (Res->isNullValue())
920 return False;
921 } else if (Pred == ICmpInst::ICMP_NE) {
922 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +0000923 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +0000924 Result.getNotConstant(), C, TD);
925 if (Res->isNullValue())
926 return True;
927 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000928 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000929 }
930
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000931 return Unknown;
932}
933
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000934void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
935 BasicBlock* NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000936 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
937}
938
939void LazyValueInfo::eraseBlock(BasicBlock *BB) {
940 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000941}