blob: f6f715e4df3e0ce74299ae0c5e0bd26b1e960728 [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();
176 else if (NewR.isFullSet()) {
177 Tag = undefined;
178 return true;
179 }
180
181 Tag = constantrange;
182 Range = NewR;
183 return true;
184 }
185
Chris Lattner16976522009-11-11 22:48:44 +0000186 /// mergeIn - Merge the specified lattice value into this one, updating this
187 /// one and returning true if anything changed.
188 bool mergeIn(const LVILatticeVal &RHS) {
189 if (RHS.isUndefined() || isOverdefined()) return false;
190 if (RHS.isOverdefined()) return markOverdefined();
191
Chris Lattnerb52675b2009-11-12 04:36:58 +0000192 if (RHS.isNotConstant()) {
193 if (isNotConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000194 if (getNotConstant() != RHS.getNotConstant() ||
195 isa<ConstantExpr>(getNotConstant()) ||
196 isa<ConstantExpr>(RHS.getNotConstant()))
Chris Lattnerb52675b2009-11-12 04:36:58 +0000197 return markOverdefined();
198 return false;
Owen Anderson39295322010-08-30 17:03:45 +0000199 } else if (isConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000200 if (getConstant() == RHS.getNotConstant() ||
201 isa<ConstantExpr>(RHS.getNotConstant()) ||
202 isa<ConstantExpr>(getConstant()))
203 return markOverdefined();
204 return markNotConstant(RHS.getNotConstant());
Owen Anderson39295322010-08-30 17:03:45 +0000205 } else if (isConstantRange()) {
206 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000207 }
208
209 assert(isUndefined() && "Unexpected lattice");
Chris Lattnerb52675b2009-11-12 04:36:58 +0000210 return markNotConstant(RHS.getNotConstant());
211 }
212
Owen Anderson5be2e782010-08-05 22:59:19 +0000213 if (RHS.isConstantRange()) {
214 if (isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +0000215 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
216 if (NewR.isFullSet())
Owen Anderson5be2e782010-08-05 22:59:19 +0000217 return markOverdefined();
218 else
219 return markConstantRange(NewR);
Owen Anderson59b06dc2010-08-24 07:55:44 +0000220 } else if (!isUndefined()) {
221 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000222 }
223
224 assert(isUndefined() && "Unexpected lattice");
225 return markConstantRange(RHS.getConstantRange());
226 }
227
Chris Lattnerf496e792009-11-12 04:57:13 +0000228 // RHS must be a constant, we must be undef, constant, or notconstant.
Owen Anderson5be2e782010-08-05 22:59:19 +0000229 assert(!isConstantRange() &&
230 "Constant and ConstantRange cannot be merged.");
231
Chris Lattnerf496e792009-11-12 04:57:13 +0000232 if (isUndefined())
233 return markConstant(RHS.getConstant());
234
235 if (isConstant()) {
236 if (getConstant() != RHS.getConstant())
237 return markOverdefined();
238 return false;
239 }
240
241 // If we are known "!=4" and RHS is "==5", stay at "!=4".
242 if (getNotConstant() == RHS.getConstant() ||
243 isa<ConstantExpr>(getNotConstant()) ||
244 isa<ConstantExpr>(RHS.getConstant()))
Chris Lattner16976522009-11-11 22:48:44 +0000245 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000246 return false;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000247 }
248
249};
250
251} // end anonymous namespace.
252
Chris Lattner16976522009-11-11 22:48:44 +0000253namespace llvm {
254raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
255 if (Val.isUndefined())
256 return OS << "undefined";
257 if (Val.isOverdefined())
258 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000259
260 if (Val.isNotConstant())
261 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000262 else if (Val.isConstantRange())
263 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
264 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000265 return OS << "constant<" << *Val.getConstant() << '>';
266}
267}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000268
269//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000270// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000271//===----------------------------------------------------------------------===//
272
Chris Lattner2c5adf82009-11-15 19:59:49 +0000273namespace {
274 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
275 /// maintains information about queries across the clients' queries.
276 class LazyValueInfoCache {
Owen Anderson81881bc2010-07-30 20:56:07 +0000277 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000278 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
279 /// specified basic block for a Value* that depends on context.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000280 typedef std::pair<AssertingVH<BasicBlock>, LVILatticeVal> BlockCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000281
282 /// ValueCacheEntryTy - This is all of the cached block information for
283 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
284 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000285 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000286
Owen Anderson81881bc2010-07-30 20:56:07 +0000287 private:
Owen Anderson7f9cb742010-07-30 23:59:40 +0000288 /// LVIValueHandle - A callback value handle update the cache when
289 /// values are erased.
290 struct LVIValueHandle : public CallbackVH {
291 LazyValueInfoCache *Parent;
292
293 LVIValueHandle(Value *V, LazyValueInfoCache *P)
294 : CallbackVH(V), Parent(P) { }
295
296 void deleted();
297 void allUsesReplacedWith(Value* V) {
298 deleted();
299 }
300
301 LVIValueHandle &operator=(Value *V) {
302 return *this = LVIValueHandle(V, Parent);
303 }
304 };
305
Chris Lattner2c5adf82009-11-15 19:59:49 +0000306 /// ValueCache - This is all of the cached information for all values,
307 /// mapped from Value* to key information.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000308 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000309
310 /// OverDefinedCache - This tracks, on a per-block basis, the set of
311 /// values that are over-defined at the end of that block. This is required
312 /// for cache updating.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000313 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000314
Chris Lattner2c5adf82009-11-15 19:59:49 +0000315 public:
316
317 /// getValueInBlock - This is the query interface to determine the lattice
318 /// value for the specified Value* at the end of the specified block.
319 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
320
321 /// getValueOnEdge - This is the query interface to determine the lattice
322 /// value for the specified Value* that is true on the specified edge.
323 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000324
325 /// threadEdge - This is the update interface to inform the cache that an
326 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
327 /// NewSucc.
328 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000329
330 /// eraseBlock - This is part of the update interface to inform the cache
331 /// that a block has been deleted.
332 void eraseBlock(BasicBlock *BB);
333
334 /// clear - Empty the cache.
335 void clear() {
336 ValueCache.clear();
337 OverDefinedCache.clear();
338 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000339 };
340} // end anonymous namespace
341
Owen Anderson81881bc2010-07-30 20:56:07 +0000342//===----------------------------------------------------------------------===//
343// LVIQuery Impl
344//===----------------------------------------------------------------------===//
345
346namespace {
347 /// LVIQuery - This is a transient object that exists while a query is
348 /// being performed.
349 ///
350 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
351 /// reallocation of the densemap on every query.
352 class LVIQuery {
353 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
354 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
355
356 /// This is the current value being queried for.
357 Value *Val;
358
Owen Anderson7f9cb742010-07-30 23:59:40 +0000359 /// This is a pointer to the owning cache, for recursive queries.
360 LazyValueInfoCache &Parent;
361
Owen Anderson81881bc2010-07-30 20:56:07 +0000362 /// This is all of the cached information about this value.
363 ValueCacheEntryTy &Cache;
364
365 /// This tracks, for each block, what values are overdefined.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000366 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &OverDefinedCache;
Owen Anderson81881bc2010-07-30 20:56:07 +0000367
368 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
369 /// added to cache but that are not in sorted order.
370 DenseSet<BasicBlock*> NewBlockInfo;
Owen Andersonc8ef7502010-08-24 20:47:29 +0000371
Owen Anderson81881bc2010-07-30 20:56:07 +0000372 public:
373
Owen Anderson7f9cb742010-07-30 23:59:40 +0000374 LVIQuery(Value *V, LazyValueInfoCache &P,
375 ValueCacheEntryTy &VC,
Owen Anderson00ac77e2010-08-18 18:39:01 +0000376 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &ODC)
Owen Anderson7f9cb742010-07-30 23:59:40 +0000377 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000378 }
379
380 ~LVIQuery() {
381 // When the query is done, insert the newly discovered facts into the
382 // cache in sorted order.
383 if (NewBlockInfo.empty()) return;
384
385 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
386 E = NewBlockInfo.end(); I != E; ++I) {
387 if (Cache[*I].isOverdefined())
388 OverDefinedCache.insert(std::make_pair(*I, Val));
389 }
390 }
391
392 LVILatticeVal getBlockValue(BasicBlock *BB);
393 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
394
395 private:
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000396 LVILatticeVal getCachedEntryForBlock(BasicBlock *BB);
Owen Anderson81881bc2010-07-30 20:56:07 +0000397 };
398} // end anonymous namespace
Chris Lattner2c5adf82009-11-15 19:59:49 +0000399
Owen Anderson7f9cb742010-07-30 23:59:40 +0000400void LazyValueInfoCache::LVIValueHandle::deleted() {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000401 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000402 I = Parent->OverDefinedCache.begin(),
403 E = Parent->OverDefinedCache.end();
404 I != E; ) {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000405 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000406 ++I;
407 if (tmp->second == getValPtr())
408 Parent->OverDefinedCache.erase(tmp);
409 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000410
411 // This erasure deallocates *this, so it MUST happen after we're done
412 // using any and all members of *this.
413 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000414}
415
Owen Anderson00ac77e2010-08-18 18:39:01 +0000416void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
417 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
418 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
419 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
420 ++I;
421 if (tmp->first == BB)
422 OverDefinedCache.erase(tmp);
423 }
424
425 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
426 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
427 I->second.erase(BB);
428}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000429
Chris Lattnere5642812009-11-15 20:00:52 +0000430/// getCachedEntryForBlock - See if we already have a value for this block. If
Owen Anderson9a65dc92010-07-27 23:58:11 +0000431/// so, return it, otherwise create a new entry in the Cache map to use.
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000432LVILatticeVal LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000433 NewBlockInfo.insert(BB);
Owen Anderson9a65dc92010-07-27 23:58:11 +0000434 return Cache[BB];
Chris Lattnere5642812009-11-15 20:00:52 +0000435}
Chris Lattner2c5adf82009-11-15 19:59:49 +0000436
Owen Anderson81881bc2010-07-30 20:56:07 +0000437LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000438 // See if we already have a value for this block.
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000439 LVILatticeVal BBLV = getCachedEntryForBlock(BB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000440
441 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000442 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000443 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Chris Lattner2c5adf82009-11-15 19:59:49 +0000444 return BBLV;
Chris Lattnere5642812009-11-15 20:00:52 +0000445 }
446
Chris Lattner2c5adf82009-11-15 19:59:49 +0000447 // Otherwise, this is the first time we're seeing this block. Reset the
448 // lattice value to overdefined, so that cycles will terminate and be
449 // conservatively correct.
450 BBLV.markOverdefined();
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000451 Cache[BB] = BBLV;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000452
Chris Lattner2c5adf82009-11-15 19:59:49 +0000453 Instruction *BBI = dyn_cast<Instruction>(Val);
454 if (BBI == 0 || BBI->getParent() != BB) {
455 LVILatticeVal Result; // Start Undefined.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000456
Owen Andersonc8ef7502010-08-24 20:47:29 +0000457 // If this is a pointer, and there's a load from that pointer in this BB,
458 // then we know that the pointer can't be NULL.
459 if (Val->getType()->isPointerTy()) {
460 const PointerType *PTy = cast<PointerType>(Val->getType());
Owen Anderson6cd20752010-08-25 01:16:47 +0000461 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
462 LoadInst *L = dyn_cast<LoadInst>(BI);
463 if (L && L->getPointerAddressSpace() == 0 &&
464 L->getPointerOperand()->getUnderlyingObject() ==
465 Val->getUnderlyingObject()) {
Owen Andersonc8ef7502010-08-24 20:47:29 +0000466 return LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
467 }
468 }
469 }
470
471 unsigned NumPreds = 0;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000472 // Loop over all of our predecessors, merging what we know from them into
473 // result.
474 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000475 Result.mergeIn(getEdgeValue(*PI, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000476
477 // If we hit overdefined, exit early. The BlockVals entry is already set
478 // to overdefined.
Chris Lattnere5642812009-11-15 20:00:52 +0000479 if (Result.isOverdefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000480 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000481 << "' - overdefined because of pred.\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000482 return Result;
Chris Lattnere5642812009-11-15 20:00:52 +0000483 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000484 ++NumPreds;
485 }
486
487 // If this is the entry block, we must be asking about an argument. The
488 // value is overdefined.
489 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
490 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
491 Result.markOverdefined();
492 return Result;
493 }
494
495 // Return the merged value, which is more precise than 'overdefined'.
496 assert(!Result.isOverdefined());
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000497 return Cache[BB] = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000498 }
499
500 // If this value is defined by an instruction in this block, we have to
501 // process it here somehow or return overdefined.
502 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson7f9cb742010-07-30 23:59:40 +0000503 LVILatticeVal Result; // Start Undefined.
504
505 // Loop over all of our predecessors, merging what we know from them into
506 // result.
507 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
508 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
509 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
510
511 // If we hit overdefined, exit early. The BlockVals entry is already set
512 // to overdefined.
513 if (Result.isOverdefined()) {
514 DEBUG(dbgs() << " compute BB '" << BB->getName()
515 << "' - overdefined because of pred.\n");
516 return Result;
517 }
518 }
519
520 // Return the merged value, which is more precise than 'overdefined'.
521 assert(!Result.isOverdefined());
Owen Anderson00ac77e2010-08-18 18:39:01 +0000522 return Cache[BB] = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000523 }
Chris Lattnere5642812009-11-15 20:00:52 +0000524
Owen Andersonb81fd622010-08-18 21:11:37 +0000525 assert(Cache[BB].isOverdefined() && "Recursive query changed our cache?");
526
527 // We can only analyze the definitions of certain classes of instructions
528 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000529 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000530 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
531 !BBI->getType()->isIntegerTy()) {
532 DEBUG(dbgs() << " compute BB '" << BB->getName()
533 << "' - overdefined because inst def found.\n");
534 Result.markOverdefined();
535 return Result;
536 }
537
538 // FIXME: We're currently limited to binops with a constant RHS. This should
539 // be improved.
540 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
541 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
542 DEBUG(dbgs() << " compute BB '" << BB->getName()
543 << "' - overdefined because inst def found.\n");
544
545 Result.markOverdefined();
546 return Result;
547 }
548
549 // Figure out the range of the LHS. If that fails, bail.
550 LVILatticeVal LHSVal = Parent.getValueInBlock(BBI->getOperand(0), BB);
551 if (!LHSVal.isConstantRange()) {
552 Result.markOverdefined();
553 return Result;
554 }
555
556 ConstantInt *RHS = 0;
557 ConstantRange LHSRange = LHSVal.getConstantRange();
558 ConstantRange RHSRange(1);
559 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
560 if (isa<BinaryOperator>(BBI)) {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000561 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
562 if (!RHS) {
563 Result.markOverdefined();
564 return Result;
565 }
566
Owen Andersonb81fd622010-08-18 21:11:37 +0000567 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
568 }
569
570 // NOTE: We're currently limited by the set of operations that ConstantRange
571 // can evaluate symbolically. Enhancing that set will allows us to analyze
572 // more definitions.
573 switch (BBI->getOpcode()) {
574 case Instruction::Add:
575 Result.markConstantRange(LHSRange.add(RHSRange));
576 break;
577 case Instruction::Sub:
578 Result.markConstantRange(LHSRange.sub(RHSRange));
579 break;
580 case Instruction::Mul:
581 Result.markConstantRange(LHSRange.multiply(RHSRange));
582 break;
583 case Instruction::UDiv:
584 Result.markConstantRange(LHSRange.udiv(RHSRange));
585 break;
586 case Instruction::Shl:
587 Result.markConstantRange(LHSRange.shl(RHSRange));
588 break;
589 case Instruction::LShr:
590 Result.markConstantRange(LHSRange.lshr(RHSRange));
591 break;
592 case Instruction::Trunc:
593 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
594 break;
595 case Instruction::SExt:
596 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
597 break;
598 case Instruction::ZExt:
599 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
600 break;
601 case Instruction::BitCast:
602 Result.markConstantRange(LHSRange);
603 break;
604
605 // Unhandled instructions are overdefined.
606 default:
607 DEBUG(dbgs() << " compute BB '" << BB->getName()
608 << "' - overdefined because inst def found.\n");
609 Result.markOverdefined();
610 break;
611 }
612
613 return Cache[BB] = Result;
Chris Lattner10f2d132009-11-11 00:22:30 +0000614}
615
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000616
Chris Lattner800c47e2009-11-15 20:02:12 +0000617/// getEdgeValue - This method attempts to infer more complex
Owen Anderson81881bc2010-07-30 20:56:07 +0000618LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
Chris Lattner800c47e2009-11-15 20:02:12 +0000619 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
620 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000621 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
622 // If this is a conditional branch and only one successor goes to BBTo, then
623 // we maybe able to infer something from the condition.
624 if (BI->isConditional() &&
625 BI->getSuccessor(0) != BI->getSuccessor(1)) {
626 bool isTrueDest = BI->getSuccessor(0) == BBTo;
627 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
628 "BBTo isn't a successor of BBFrom");
629
630 // If V is the condition of the branch itself, then we know exactly what
631 // it is.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000632 if (BI->getCondition() == Val)
Chris Lattner16976522009-11-11 22:48:44 +0000633 return LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000634 Type::getInt1Ty(Val->getContext()), isTrueDest));
Chris Lattner16976522009-11-11 22:48:44 +0000635
636 // If the condition of the branch is an equality comparison, we may be
637 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000638 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
639 if (ICI && ICI->getOperand(0) == Val &&
640 isa<Constant>(ICI->getOperand(1))) {
641 if (ICI->isEquality()) {
642 // We know that V has the RHS constant if this is a true SETEQ or
643 // false SETNE.
644 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
645 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
646 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
Chris Lattner16976522009-11-11 22:48:44 +0000647 }
Owen Anderson2d0f2472010-08-11 04:24:25 +0000648
649 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
650 // Calculate the range of values that would satisfy the comparison.
651 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
652 ConstantRange TrueValues =
653 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
654
655 // If we're interested in the false dest, invert the condition.
656 if (!isTrueDest) TrueValues = TrueValues.inverse();
657
658 // Figure out the possible values of the query BEFORE this branch.
659 LVILatticeVal InBlock = getBlockValue(BBFrom);
Owen Anderson660cab32010-08-27 17:12:29 +0000660 if (!InBlock.isConstantRange())
661 return LVILatticeVal::getRange(TrueValues);
Owen Anderson2d0f2472010-08-11 04:24:25 +0000662
663 // Find all potential values that satisfy both the input and output
664 // conditions.
665 ConstantRange PossibleValues =
666 TrueValues.intersectWith(InBlock.getConstantRange());
667
668 return LVILatticeVal::getRange(PossibleValues);
669 }
670 }
Chris Lattner16976522009-11-11 22:48:44 +0000671 }
672 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000673
674 // If the edge was formed by a switch on the value, then we may know exactly
675 // what it is.
676 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000677 // If BBTo is the default destination of the switch, we know that it
678 // doesn't have the same value as any of the cases.
679 if (SI->getCondition() == Val) {
680 if (SI->getDefaultDest() == BBTo) {
681 const IntegerType *IT = cast<IntegerType>(Val->getType());
682 ConstantRange CR(IT->getBitWidth());
683
684 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
685 const APInt CaseVal = SI->getCaseValue(i)->getValue();
686 ConstantRange CaseRange(CaseVal, CaseVal+1);
687 CaseRange = CaseRange.inverse();
688 CR = CR.intersectWith(CaseRange);
689 }
690
691 LVILatticeVal Result;
692 if (CR.isFullSet() || CR.isEmptySet())
693 Result.markOverdefined();
694 else
695 Result.markConstantRange(CR);
696 return Result;
697 }
698
Chris Lattner800c47e2009-11-15 20:02:12 +0000699 // We only know something if there is exactly one value that goes from
700 // BBFrom to BBTo.
701 unsigned NumEdges = 0;
702 ConstantInt *EdgeVal = 0;
703 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
704 if (SI->getSuccessor(i) != BBTo) continue;
705 if (NumEdges++) break;
706 EdgeVal = SI->getCaseValue(i);
707 }
708 assert(EdgeVal && "Missing successor?");
709 if (NumEdges == 1)
710 return LVILatticeVal::get(EdgeVal);
711 }
712 }
Chris Lattner16976522009-11-11 22:48:44 +0000713
714 // Otherwise see if the value is known in the block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000715 return getBlockValue(BBFrom);
Chris Lattner16976522009-11-11 22:48:44 +0000716}
717
Owen Anderson81881bc2010-07-30 20:56:07 +0000718
719//===----------------------------------------------------------------------===//
720// LazyValueInfoCache Impl
721//===----------------------------------------------------------------------===//
722
Chris Lattner2c5adf82009-11-15 19:59:49 +0000723LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
724 // If already a constant, there is nothing to compute.
Chris Lattner16976522009-11-11 22:48:44 +0000725 if (Constant *VC = dyn_cast<Constant>(V))
Chris Lattner2c5adf82009-11-15 19:59:49 +0000726 return LVILatticeVal::get(VC);
Chris Lattner16976522009-11-11 22:48:44 +0000727
David Greene5d93a1f2009-12-23 20:43:58 +0000728 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000729 << BB->getName() << "'\n");
730
Owen Anderson7f9cb742010-07-30 23:59:40 +0000731 LVILatticeVal Result = LVIQuery(V, *this,
Owen Andersonc8ef7502010-08-24 20:47:29 +0000732 ValueCache[LVIValueHandle(V, this)],
733 OverDefinedCache).getBlockValue(BB);
Chris Lattner16976522009-11-11 22:48:44 +0000734
David Greene5d93a1f2009-12-23 20:43:58 +0000735 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000736 return Result;
737}
Chris Lattner16976522009-11-11 22:48:44 +0000738
Chris Lattner2c5adf82009-11-15 19:59:49 +0000739LVILatticeVal LazyValueInfoCache::
740getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
741 // If already a constant, there is nothing to compute.
742 if (Constant *VC = dyn_cast<Constant>(V))
743 return LVILatticeVal::get(VC);
744
David Greene5d93a1f2009-12-23 20:43:58 +0000745 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000746 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000747
Owen Anderson81881bc2010-07-30 20:56:07 +0000748 LVILatticeVal Result =
Owen Anderson7f9cb742010-07-30 23:59:40 +0000749 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000750 OverDefinedCache).getEdgeValue(FromBB, ToBB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000751
David Greene5d93a1f2009-12-23 20:43:58 +0000752 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000753
754 return Result;
755}
756
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000757void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
758 BasicBlock *NewSucc) {
759 // When an edge in the graph has been threaded, values that we could not
760 // determine a value for before (i.e. were marked overdefined) may be possible
761 // to solve now. We do NOT try to proactively update these values. Instead,
762 // we clear their entries from the cache, and allow lazy updating to recompute
763 // them when needed.
764
765 // The updating process is fairly simple: we need to dropped cached info
766 // for all values that were marked overdefined in OldSucc, and for those same
767 // values in any successor of OldSucc (except NewSucc) in which they were
768 // also marked overdefined.
769 std::vector<BasicBlock*> worklist;
770 worklist.push_back(OldSucc);
771
Owen Anderson9a65dc92010-07-27 23:58:11 +0000772 DenseSet<Value*> ClearSet;
Owen Anderson00ac77e2010-08-18 18:39:01 +0000773 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson9a65dc92010-07-27 23:58:11 +0000774 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
775 if (I->first == OldSucc)
776 ClearSet.insert(I->second);
777 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000778
779 // Use a worklist to perform a depth-first search of OldSucc's successors.
780 // NOTE: We do not need a visited list since any blocks we have already
781 // visited will have had their overdefined markers cleared already, and we
782 // thus won't loop to their successors.
783 while (!worklist.empty()) {
784 BasicBlock *ToUpdate = worklist.back();
785 worklist.pop_back();
786
787 // Skip blocks only accessible through NewSucc.
788 if (ToUpdate == NewSucc) continue;
789
790 bool changed = false;
Owen Anderson9a65dc92010-07-27 23:58:11 +0000791 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000792 I != E; ++I) {
793 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson00ac77e2010-08-18 18:39:01 +0000794 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000795 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
796 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000797
Owen Anderson9a65dc92010-07-27 23:58:11 +0000798 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000799 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000800 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
801
802 assert(CI != Entry.end() && "Couldn't find entry to update?");
803 Entry.erase(CI);
804 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000805
Owen Anderson9a65dc92010-07-27 23:58:11 +0000806 // If we removed anything, then we potentially need to update
807 // blocks successors too.
808 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000809 }
810
811 if (!changed) continue;
812
813 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
814 }
815}
816
Chris Lattner2c5adf82009-11-15 19:59:49 +0000817//===----------------------------------------------------------------------===//
818// LazyValueInfo Impl
819//===----------------------------------------------------------------------===//
820
Chris Lattner2c5adf82009-11-15 19:59:49 +0000821/// getCache - This lazily constructs the LazyValueInfoCache.
822static LazyValueInfoCache &getCache(void *&PImpl) {
823 if (!PImpl)
824 PImpl = new LazyValueInfoCache();
825 return *static_cast<LazyValueInfoCache*>(PImpl);
826}
827
Owen Anderson00ac77e2010-08-18 18:39:01 +0000828bool LazyValueInfo::runOnFunction(Function &F) {
829 if (PImpl)
830 getCache(PImpl).clear();
831
832 TD = getAnalysisIfAvailable<TargetData>();
833 // Fully lazy.
834 return false;
835}
836
Chris Lattner2c5adf82009-11-15 19:59:49 +0000837void LazyValueInfo::releaseMemory() {
838 // If the cache was allocated, free it.
839 if (PImpl) {
840 delete &getCache(PImpl);
841 PImpl = 0;
842 }
843}
844
845Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
846 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
847
Chris Lattner16976522009-11-11 22:48:44 +0000848 if (Result.isConstant())
849 return Result.getConstant();
Owen Andersonee61fcf2010-08-27 23:29:38 +0000850 else if (Result.isConstantRange()) {
851 ConstantRange CR = Result.getConstantRange();
852 if (const APInt *SingleVal = CR.getSingleElement())
853 return ConstantInt::get(V->getContext(), *SingleVal);
854 }
Chris Lattner16976522009-11-11 22:48:44 +0000855 return 0;
856}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000857
Chris Lattner38392bb2009-11-12 01:29:10 +0000858/// getConstantOnEdge - Determine whether the specified value is known to be a
859/// constant on the specified edge. Return null if not.
860Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
861 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000862 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +0000863
864 if (Result.isConstant())
865 return Result.getConstant();
Owen Anderson9f014062010-08-10 20:03:09 +0000866 else if (Result.isConstantRange()) {
867 ConstantRange CR = Result.getConstantRange();
868 if (const APInt *SingleVal = CR.getSingleElement())
869 return ConstantInt::get(V->getContext(), *SingleVal);
870 }
Chris Lattner38392bb2009-11-12 01:29:10 +0000871 return 0;
872}
873
Chris Lattnerb52675b2009-11-12 04:36:58 +0000874/// getPredicateOnEdge - Determine whether the specified value comparison
875/// with a constant is known to be true or false on the specified CFG edge.
876/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000877LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +0000878LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
879 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000880 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000881
Chris Lattnerb52675b2009-11-12 04:36:58 +0000882 // If we know the value is a constant, evaluate the conditional.
883 Constant *Res = 0;
884 if (Result.isConstant()) {
885 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
886 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
887 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000888 return Unknown;
889 }
890
Owen Anderson9f014062010-08-10 20:03:09 +0000891 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000892 ConstantInt *CI = dyn_cast<ConstantInt>(C);
893 if (!CI) return Unknown;
894
Owen Anderson9f014062010-08-10 20:03:09 +0000895 ConstantRange CR = Result.getConstantRange();
896 if (Pred == ICmpInst::ICMP_EQ) {
897 if (!CR.contains(CI->getValue()))
898 return False;
899
900 if (CR.isSingleElement() && CR.contains(CI->getValue()))
901 return True;
902 } else if (Pred == ICmpInst::ICMP_NE) {
903 if (!CR.contains(CI->getValue()))
904 return True;
905
906 if (CR.isSingleElement() && CR.contains(CI->getValue()))
907 return False;
908 }
909
910 // Handle more complex predicates.
911 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
912 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
913 if (CR.intersectWith(TrueValues).isEmptySet())
914 return False;
Owen Anderson625051b2010-08-10 23:20:01 +0000915 else if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +0000916 return True;
917
918 return Unknown;
919 }
920
Chris Lattner2c5adf82009-11-15 19:59:49 +0000921 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000922 // If this is an equality comparison, we can try to fold it knowing that
923 // "V != C1".
924 if (Pred == ICmpInst::ICMP_EQ) {
925 // !C1 == C -> false iff C1 == C.
926 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
927 Result.getNotConstant(), C, TD);
928 if (Res->isNullValue())
929 return False;
930 } else if (Pred == ICmpInst::ICMP_NE) {
931 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +0000932 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +0000933 Result.getNotConstant(), C, TD);
934 if (Res->isNullValue())
935 return True;
936 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000937 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000938 }
939
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000940 return Unknown;
941}
942
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000943void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
944 BasicBlock* NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000945 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
946}
947
948void LazyValueInfo::eraseBlock(BasicBlock *BB) {
949 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000950}