blob: 7ec35cdcc5bdb11c805d47dd8125b00e26f6eb1f [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 }
Chris Lattner16976522009-11-11 22:48:44 +000094
Owen Anderson5be2e782010-08-05 22:59:19 +000095 bool isUndefined() const { return Tag == undefined; }
96 bool isConstant() const { return Tag == constant; }
97 bool isNotConstant() const { return Tag == notconstant; }
98 bool isConstantRange() const { return Tag == constantrange; }
99 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000100
101 Constant *getConstant() const {
102 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000103 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000104 }
105
Chris Lattnerb52675b2009-11-12 04:36:58 +0000106 Constant *getNotConstant() const {
107 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000108 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000109 }
110
Owen Anderson5be2e782010-08-05 22:59:19 +0000111 ConstantRange getConstantRange() const {
112 assert(isConstantRange() &&
113 "Cannot get the constant-range of a non-constant-range!");
114 return Range;
115 }
116
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000117 /// markOverdefined - Return true if this is a change in status.
118 bool markOverdefined() {
119 if (isOverdefined())
120 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000121 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000122 return true;
123 }
124
125 /// markConstant - Return true if this is a change in status.
126 bool markConstant(Constant *V) {
127 if (isConstant()) {
128 assert(getConstant() == V && "Marking constant with different value");
129 return false;
130 }
131
132 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000133 Tag = constant;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000134 assert(V && "Marking constant with NULL");
Owen Andersondb78d732010-08-05 22:10:46 +0000135 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000136 return true;
137 }
138
Chris Lattnerb52675b2009-11-12 04:36:58 +0000139 /// markNotConstant - Return true if this is a change in status.
140 bool markNotConstant(Constant *V) {
141 if (isNotConstant()) {
142 assert(getNotConstant() == V && "Marking !constant with different value");
143 return false;
144 }
145
146 if (isConstant())
147 assert(getConstant() != V && "Marking not constant with different value");
148 else
149 assert(isUndefined());
150
Owen Andersondb78d732010-08-05 22:10:46 +0000151 Tag = notconstant;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000152 assert(V && "Marking constant with NULL");
Owen Andersondb78d732010-08-05 22:10:46 +0000153 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000154 return true;
155 }
156
Owen Anderson5be2e782010-08-05 22:59:19 +0000157 /// markConstantRange - Return true if this is a change in status.
158 bool markConstantRange(const ConstantRange NewR) {
159 if (isConstantRange()) {
160 if (NewR.isEmptySet())
161 return markOverdefined();
162
Owen Anderson5be2e782010-08-05 22:59:19 +0000163 bool changed = Range == NewR;
164 Range = NewR;
165 return changed;
166 }
167
168 assert(isUndefined());
169 if (NewR.isEmptySet())
170 return markOverdefined();
171 else if (NewR.isFullSet()) {
172 Tag = undefined;
173 return true;
174 }
175
176 Tag = constantrange;
177 Range = NewR;
178 return true;
179 }
180
Chris Lattner16976522009-11-11 22:48:44 +0000181 /// mergeIn - Merge the specified lattice value into this one, updating this
182 /// one and returning true if anything changed.
183 bool mergeIn(const LVILatticeVal &RHS) {
184 if (RHS.isUndefined() || isOverdefined()) return false;
185 if (RHS.isOverdefined()) return markOverdefined();
186
Chris Lattnerb52675b2009-11-12 04:36:58 +0000187 if (RHS.isNotConstant()) {
188 if (isNotConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000189 if (getNotConstant() != RHS.getNotConstant() ||
190 isa<ConstantExpr>(getNotConstant()) ||
191 isa<ConstantExpr>(RHS.getNotConstant()))
Chris Lattnerb52675b2009-11-12 04:36:58 +0000192 return markOverdefined();
193 return false;
194 }
Chris Lattnerf496e792009-11-12 04:57:13 +0000195 if (isConstant()) {
196 if (getConstant() == RHS.getNotConstant() ||
197 isa<ConstantExpr>(RHS.getNotConstant()) ||
198 isa<ConstantExpr>(getConstant()))
199 return markOverdefined();
200 return markNotConstant(RHS.getNotConstant());
201 }
202
203 assert(isUndefined() && "Unexpected lattice");
Chris Lattnerb52675b2009-11-12 04:36:58 +0000204 return markNotConstant(RHS.getNotConstant());
205 }
206
Owen Anderson5be2e782010-08-05 22:59:19 +0000207 if (RHS.isConstantRange()) {
208 if (isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +0000209 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
210 if (NewR.isFullSet())
Owen Anderson5be2e782010-08-05 22:59:19 +0000211 return markOverdefined();
212 else
213 return markConstantRange(NewR);
214 }
215
216 assert(isUndefined() && "Unexpected lattice");
217 return markConstantRange(RHS.getConstantRange());
218 }
219
Chris Lattnerf496e792009-11-12 04:57:13 +0000220 // RHS must be a constant, we must be undef, constant, or notconstant.
Owen Anderson5be2e782010-08-05 22:59:19 +0000221 assert(!isConstantRange() &&
222 "Constant and ConstantRange cannot be merged.");
223
Chris Lattnerf496e792009-11-12 04:57:13 +0000224 if (isUndefined())
225 return markConstant(RHS.getConstant());
226
227 if (isConstant()) {
228 if (getConstant() != RHS.getConstant())
229 return markOverdefined();
230 return false;
231 }
232
233 // If we are known "!=4" and RHS is "==5", stay at "!=4".
234 if (getNotConstant() == RHS.getConstant() ||
235 isa<ConstantExpr>(getNotConstant()) ||
236 isa<ConstantExpr>(RHS.getConstant()))
Chris Lattner16976522009-11-11 22:48:44 +0000237 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000238 return false;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000239 }
240
241};
242
243} // end anonymous namespace.
244
Chris Lattner16976522009-11-11 22:48:44 +0000245namespace llvm {
246raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
247 if (Val.isUndefined())
248 return OS << "undefined";
249 if (Val.isOverdefined())
250 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000251
252 if (Val.isNotConstant())
253 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000254 else if (Val.isConstantRange())
255 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
256 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000257 return OS << "constant<" << *Val.getConstant() << '>';
258}
259}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000260
261//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000262// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000263//===----------------------------------------------------------------------===//
264
Chris Lattner2c5adf82009-11-15 19:59:49 +0000265namespace {
266 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
267 /// maintains information about queries across the clients' queries.
268 class LazyValueInfoCache {
Owen Anderson81881bc2010-07-30 20:56:07 +0000269 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000270 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
271 /// specified basic block for a Value* that depends on context.
272 typedef std::pair<BasicBlock*, LVILatticeVal> BlockCacheEntryTy;
273
274 /// ValueCacheEntryTy - This is all of the cached block information for
275 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
276 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000277 typedef std::map<BasicBlock*, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000278
Owen Anderson81881bc2010-07-30 20:56:07 +0000279 private:
Owen Anderson7f9cb742010-07-30 23:59:40 +0000280 /// LVIValueHandle - A callback value handle update the cache when
281 /// values are erased.
282 struct LVIValueHandle : public CallbackVH {
283 LazyValueInfoCache *Parent;
284
285 LVIValueHandle(Value *V, LazyValueInfoCache *P)
286 : CallbackVH(V), Parent(P) { }
287
288 void deleted();
289 void allUsesReplacedWith(Value* V) {
290 deleted();
291 }
292
293 LVIValueHandle &operator=(Value *V) {
294 return *this = LVIValueHandle(V, Parent);
295 }
296 };
297
Chris Lattner2c5adf82009-11-15 19:59:49 +0000298 /// ValueCache - This is all of the cached information for all values,
299 /// mapped from Value* to key information.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000300 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000301
302 /// OverDefinedCache - This tracks, on a per-block basis, the set of
303 /// values that are over-defined at the end of that block. This is required
304 /// for cache updating.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000305 std::set<std::pair<BasicBlock*, Value*> > OverDefinedCache;
306
Chris Lattner2c5adf82009-11-15 19:59:49 +0000307 public:
308
309 /// getValueInBlock - This is the query interface to determine the lattice
310 /// value for the specified Value* at the end of the specified block.
311 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
312
313 /// getValueOnEdge - This is the query interface to determine the lattice
314 /// value for the specified Value* that is true on the specified edge.
315 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000316
317 /// threadEdge - This is the update interface to inform the cache that an
318 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
319 /// NewSucc.
320 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000321 };
322} // end anonymous namespace
323
Owen Anderson81881bc2010-07-30 20:56:07 +0000324//===----------------------------------------------------------------------===//
325// LVIQuery Impl
326//===----------------------------------------------------------------------===//
327
328namespace {
329 /// LVIQuery - This is a transient object that exists while a query is
330 /// being performed.
331 ///
332 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
333 /// reallocation of the densemap on every query.
334 class LVIQuery {
335 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
336 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
337
338 /// This is the current value being queried for.
339 Value *Val;
340
Owen Anderson7f9cb742010-07-30 23:59:40 +0000341 /// This is a pointer to the owning cache, for recursive queries.
342 LazyValueInfoCache &Parent;
343
Owen Anderson81881bc2010-07-30 20:56:07 +0000344 /// This is all of the cached information about this value.
345 ValueCacheEntryTy &Cache;
346
347 /// This tracks, for each block, what values are overdefined.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000348 std::set<std::pair<BasicBlock*, Value*> > &OverDefinedCache;
Owen Anderson81881bc2010-07-30 20:56:07 +0000349
350 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
351 /// added to cache but that are not in sorted order.
352 DenseSet<BasicBlock*> NewBlockInfo;
353 public:
354
Owen Anderson7f9cb742010-07-30 23:59:40 +0000355 LVIQuery(Value *V, LazyValueInfoCache &P,
356 ValueCacheEntryTy &VC,
357 std::set<std::pair<BasicBlock*, Value*> > &ODC)
358 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000359 }
360
361 ~LVIQuery() {
362 // When the query is done, insert the newly discovered facts into the
363 // cache in sorted order.
364 if (NewBlockInfo.empty()) return;
365
366 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
367 E = NewBlockInfo.end(); I != E; ++I) {
368 if (Cache[*I].isOverdefined())
369 OverDefinedCache.insert(std::make_pair(*I, Val));
370 }
371 }
372
373 LVILatticeVal getBlockValue(BasicBlock *BB);
374 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
375
376 private:
377 LVILatticeVal &getCachedEntryForBlock(BasicBlock *BB);
378 };
379} // end anonymous namespace
Chris Lattner2c5adf82009-11-15 19:59:49 +0000380
Owen Anderson7f9cb742010-07-30 23:59:40 +0000381void LazyValueInfoCache::LVIValueHandle::deleted() {
382 Parent->ValueCache.erase(*this);
383 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
384 I = Parent->OverDefinedCache.begin(),
385 E = Parent->OverDefinedCache.end();
386 I != E; ) {
387 std::set<std::pair<BasicBlock*, Value*> >::iterator tmp = I;
388 ++I;
389 if (tmp->second == getValPtr())
390 Parent->OverDefinedCache.erase(tmp);
391 }
392}
393
394
Chris Lattnere5642812009-11-15 20:00:52 +0000395/// getCachedEntryForBlock - See if we already have a value for this block. If
Owen Anderson9a65dc92010-07-27 23:58:11 +0000396/// so, return it, otherwise create a new entry in the Cache map to use.
Owen Anderson81881bc2010-07-30 20:56:07 +0000397LVILatticeVal &LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
398 NewBlockInfo.insert(BB);
Owen Anderson9a65dc92010-07-27 23:58:11 +0000399 return Cache[BB];
Chris Lattnere5642812009-11-15 20:00:52 +0000400}
Chris Lattner2c5adf82009-11-15 19:59:49 +0000401
Owen Anderson81881bc2010-07-30 20:56:07 +0000402LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000403 // See if we already have a value for this block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000404 LVILatticeVal &BBLV = getCachedEntryForBlock(BB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000405
406 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000407 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000408 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Chris Lattner2c5adf82009-11-15 19:59:49 +0000409 return BBLV;
Chris Lattnere5642812009-11-15 20:00:52 +0000410 }
411
Chris Lattner2c5adf82009-11-15 19:59:49 +0000412 // Otherwise, this is the first time we're seeing this block. Reset the
413 // lattice value to overdefined, so that cycles will terminate and be
414 // conservatively correct.
415 BBLV.markOverdefined();
416
417 // If V is live into BB, see if our predecessors know anything about it.
418 Instruction *BBI = dyn_cast<Instruction>(Val);
419 if (BBI == 0 || BBI->getParent() != BB) {
420 LVILatticeVal Result; // Start Undefined.
421 unsigned NumPreds = 0;
422
423 // Loop over all of our predecessors, merging what we know from them into
424 // result.
425 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000426 Result.mergeIn(getEdgeValue(*PI, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000427
428 // If we hit overdefined, exit early. The BlockVals entry is already set
429 // to overdefined.
Chris Lattnere5642812009-11-15 20:00:52 +0000430 if (Result.isOverdefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000431 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000432 << "' - overdefined because of pred.\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000433 return Result;
Chris Lattnere5642812009-11-15 20:00:52 +0000434 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000435 ++NumPreds;
436 }
437
438 // If this is the entry block, we must be asking about an argument. The
439 // value is overdefined.
440 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
441 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
442 Result.markOverdefined();
443 return Result;
444 }
445
446 // Return the merged value, which is more precise than 'overdefined'.
447 assert(!Result.isOverdefined());
Owen Anderson81881bc2010-07-30 20:56:07 +0000448 return getCachedEntryForBlock(BB) = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000449 }
450
451 // If this value is defined by an instruction in this block, we have to
452 // process it here somehow or return overdefined.
453 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson7f9cb742010-07-30 23:59:40 +0000454 LVILatticeVal Result; // Start Undefined.
455
456 // Loop over all of our predecessors, merging what we know from them into
457 // result.
458 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
459 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
460 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
461
462 // If we hit overdefined, exit early. The BlockVals entry is already set
463 // to overdefined.
464 if (Result.isOverdefined()) {
465 DEBUG(dbgs() << " compute BB '" << BB->getName()
466 << "' - overdefined because of pred.\n");
467 return Result;
468 }
469 }
470
471 // Return the merged value, which is more precise than 'overdefined'.
472 assert(!Result.isOverdefined());
473 return getCachedEntryForBlock(BB) = Result;
474
Chris Lattner2c5adf82009-11-15 19:59:49 +0000475 } else {
476
477 }
478
David Greene5d93a1f2009-12-23 20:43:58 +0000479 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000480 << "' - overdefined because inst def found.\n");
481
Chris Lattner2c5adf82009-11-15 19:59:49 +0000482 LVILatticeVal Result;
483 Result.markOverdefined();
Owen Anderson81881bc2010-07-30 20:56:07 +0000484 return getCachedEntryForBlock(BB) = Result;
Chris Lattner10f2d132009-11-11 00:22:30 +0000485}
486
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000487
Chris Lattner800c47e2009-11-15 20:02:12 +0000488/// getEdgeValue - This method attempts to infer more complex
Owen Anderson81881bc2010-07-30 20:56:07 +0000489LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
Chris Lattner800c47e2009-11-15 20:02:12 +0000490 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
491 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000492 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
493 // If this is a conditional branch and only one successor goes to BBTo, then
494 // we maybe able to infer something from the condition.
495 if (BI->isConditional() &&
496 BI->getSuccessor(0) != BI->getSuccessor(1)) {
497 bool isTrueDest = BI->getSuccessor(0) == BBTo;
498 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
499 "BBTo isn't a successor of BBFrom");
500
501 // If V is the condition of the branch itself, then we know exactly what
502 // it is.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000503 if (BI->getCondition() == Val)
Chris Lattner16976522009-11-11 22:48:44 +0000504 return LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000505 Type::getInt1Ty(Val->getContext()), isTrueDest));
Chris Lattner16976522009-11-11 22:48:44 +0000506
507 // If the condition of the branch is an equality comparison, we may be
508 // able to infer the value.
509 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
Chris Lattner2c5adf82009-11-15 19:59:49 +0000510 if (ICI->isEquality() && ICI->getOperand(0) == Val &&
Chris Lattner16976522009-11-11 22:48:44 +0000511 isa<Constant>(ICI->getOperand(1))) {
512 // We know that V has the RHS constant if this is a true SETEQ or
513 // false SETNE.
514 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
515 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
Chris Lattnerb52675b2009-11-12 04:36:58 +0000516 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
Chris Lattner16976522009-11-11 22:48:44 +0000517 }
518 }
519 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000520
521 // If the edge was formed by a switch on the value, then we may know exactly
522 // what it is.
523 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
524 // If BBTo is the default destination of the switch, we don't know anything.
525 // Given a more powerful range analysis we could know stuff.
526 if (SI->getCondition() == Val && SI->getDefaultDest() != BBTo) {
527 // We only know something if there is exactly one value that goes from
528 // BBFrom to BBTo.
529 unsigned NumEdges = 0;
530 ConstantInt *EdgeVal = 0;
531 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
532 if (SI->getSuccessor(i) != BBTo) continue;
533 if (NumEdges++) break;
534 EdgeVal = SI->getCaseValue(i);
535 }
536 assert(EdgeVal && "Missing successor?");
537 if (NumEdges == 1)
538 return LVILatticeVal::get(EdgeVal);
539 }
540 }
Chris Lattner16976522009-11-11 22:48:44 +0000541
542 // Otherwise see if the value is known in the block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000543 return getBlockValue(BBFrom);
Chris Lattner16976522009-11-11 22:48:44 +0000544}
545
Owen Anderson81881bc2010-07-30 20:56:07 +0000546
547//===----------------------------------------------------------------------===//
548// LazyValueInfoCache Impl
549//===----------------------------------------------------------------------===//
550
Chris Lattner2c5adf82009-11-15 19:59:49 +0000551LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
552 // If already a constant, there is nothing to compute.
Chris Lattner16976522009-11-11 22:48:44 +0000553 if (Constant *VC = dyn_cast<Constant>(V))
Chris Lattner2c5adf82009-11-15 19:59:49 +0000554 return LVILatticeVal::get(VC);
Chris Lattner16976522009-11-11 22:48:44 +0000555
David Greene5d93a1f2009-12-23 20:43:58 +0000556 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000557 << BB->getName() << "'\n");
558
Owen Anderson7f9cb742010-07-30 23:59:40 +0000559 LVILatticeVal Result = LVIQuery(V, *this,
560 ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000561 OverDefinedCache).getBlockValue(BB);
Chris Lattner16976522009-11-11 22:48:44 +0000562
David Greene5d93a1f2009-12-23 20:43:58 +0000563 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000564 return Result;
565}
Chris Lattner16976522009-11-11 22:48:44 +0000566
Chris Lattner2c5adf82009-11-15 19:59:49 +0000567LVILatticeVal LazyValueInfoCache::
568getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
569 // If already a constant, there is nothing to compute.
570 if (Constant *VC = dyn_cast<Constant>(V))
571 return LVILatticeVal::get(VC);
572
David Greene5d93a1f2009-12-23 20:43:58 +0000573 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000574 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000575
Owen Anderson81881bc2010-07-30 20:56:07 +0000576 LVILatticeVal Result =
Owen Anderson7f9cb742010-07-30 23:59:40 +0000577 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000578 OverDefinedCache).getEdgeValue(FromBB, ToBB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000579
David Greene5d93a1f2009-12-23 20:43:58 +0000580 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000581
582 return Result;
583}
584
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000585void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
586 BasicBlock *NewSucc) {
587 // When an edge in the graph has been threaded, values that we could not
588 // determine a value for before (i.e. were marked overdefined) may be possible
589 // to solve now. We do NOT try to proactively update these values. Instead,
590 // we clear their entries from the cache, and allow lazy updating to recompute
591 // them when needed.
592
593 // The updating process is fairly simple: we need to dropped cached info
594 // for all values that were marked overdefined in OldSucc, and for those same
595 // values in any successor of OldSucc (except NewSucc) in which they were
596 // also marked overdefined.
597 std::vector<BasicBlock*> worklist;
598 worklist.push_back(OldSucc);
599
Owen Anderson9a65dc92010-07-27 23:58:11 +0000600 DenseSet<Value*> ClearSet;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000601 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
Owen Anderson9a65dc92010-07-27 23:58:11 +0000602 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
603 if (I->first == OldSucc)
604 ClearSet.insert(I->second);
605 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000606
607 // Use a worklist to perform a depth-first search of OldSucc's successors.
608 // NOTE: We do not need a visited list since any blocks we have already
609 // visited will have had their overdefined markers cleared already, and we
610 // thus won't loop to their successors.
611 while (!worklist.empty()) {
612 BasicBlock *ToUpdate = worklist.back();
613 worklist.pop_back();
614
615 // Skip blocks only accessible through NewSucc.
616 if (ToUpdate == NewSucc) continue;
617
618 bool changed = false;
Owen Anderson9a65dc92010-07-27 23:58:11 +0000619 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000620 I != E; ++I) {
621 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson7f9cb742010-07-30 23:59:40 +0000622 std::set<std::pair<BasicBlock*, Value*> >::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000623 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
624 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000625
Owen Anderson9a65dc92010-07-27 23:58:11 +0000626 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000627 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000628 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
629
630 assert(CI != Entry.end() && "Couldn't find entry to update?");
631 Entry.erase(CI);
632 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000633
Owen Anderson9a65dc92010-07-27 23:58:11 +0000634 // If we removed anything, then we potentially need to update
635 // blocks successors too.
636 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000637 }
638
639 if (!changed) continue;
640
641 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
642 }
643}
644
Chris Lattner2c5adf82009-11-15 19:59:49 +0000645//===----------------------------------------------------------------------===//
646// LazyValueInfo Impl
647//===----------------------------------------------------------------------===//
648
649bool LazyValueInfo::runOnFunction(Function &F) {
650 TD = getAnalysisIfAvailable<TargetData>();
651 // Fully lazy.
652 return false;
653}
654
655/// getCache - This lazily constructs the LazyValueInfoCache.
656static LazyValueInfoCache &getCache(void *&PImpl) {
657 if (!PImpl)
658 PImpl = new LazyValueInfoCache();
659 return *static_cast<LazyValueInfoCache*>(PImpl);
660}
661
662void LazyValueInfo::releaseMemory() {
663 // If the cache was allocated, free it.
664 if (PImpl) {
665 delete &getCache(PImpl);
666 PImpl = 0;
667 }
668}
669
670Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
671 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
672
Chris Lattner16976522009-11-11 22:48:44 +0000673 if (Result.isConstant())
674 return Result.getConstant();
675 return 0;
676}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000677
Chris Lattner38392bb2009-11-12 01:29:10 +0000678/// getConstantOnEdge - Determine whether the specified value is known to be a
679/// constant on the specified edge. Return null if not.
680Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
681 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000682 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +0000683
684 if (Result.isConstant())
685 return Result.getConstant();
Owen Anderson9f014062010-08-10 20:03:09 +0000686 else if (Result.isConstantRange()) {
687 ConstantRange CR = Result.getConstantRange();
688 if (const APInt *SingleVal = CR.getSingleElement())
689 return ConstantInt::get(V->getContext(), *SingleVal);
690 }
Chris Lattner38392bb2009-11-12 01:29:10 +0000691 return 0;
692}
693
Chris Lattnerb52675b2009-11-12 04:36:58 +0000694/// getPredicateOnEdge - Determine whether the specified value comparison
695/// with a constant is known to be true or false on the specified CFG edge.
696/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000697LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +0000698LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
699 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000700 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000701
Chris Lattnerb52675b2009-11-12 04:36:58 +0000702 // If we know the value is a constant, evaluate the conditional.
703 Constant *Res = 0;
704 if (Result.isConstant()) {
705 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
706 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
707 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000708 return Unknown;
709 }
710
Owen Anderson9f014062010-08-10 20:03:09 +0000711 if (Result.isConstantRange()) {
712 ConstantInt *CI = cast<ConstantInt>(C);
713 ConstantRange CR = Result.getConstantRange();
714 if (Pred == ICmpInst::ICMP_EQ) {
715 if (!CR.contains(CI->getValue()))
716 return False;
717
718 if (CR.isSingleElement() && CR.contains(CI->getValue()))
719 return True;
720 } else if (Pred == ICmpInst::ICMP_NE) {
721 if (!CR.contains(CI->getValue()))
722 return True;
723
724 if (CR.isSingleElement() && CR.contains(CI->getValue()))
725 return False;
726 }
727
728 // Handle more complex predicates.
729 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
730 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
731 if (CR.intersectWith(TrueValues).isEmptySet())
732 return False;
733 else if (CR.intersectWith(TrueValues) == CR)
734 return True;
735
736 return Unknown;
737 }
738
Chris Lattner2c5adf82009-11-15 19:59:49 +0000739 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000740 // If this is an equality comparison, we can try to fold it knowing that
741 // "V != C1".
742 if (Pred == ICmpInst::ICMP_EQ) {
743 // !C1 == C -> false iff C1 == C.
744 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
745 Result.getNotConstant(), C, TD);
746 if (Res->isNullValue())
747 return False;
748 } else if (Pred == ICmpInst::ICMP_NE) {
749 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +0000750 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +0000751 Result.getNotConstant(), C, TD);
752 if (Res->isNullValue())
753 return True;
754 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000755 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000756 }
757
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000758 return Unknown;
759}
760
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000761void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
762 BasicBlock* NewSucc) {
763 getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
764}