blob: 643fe63bc0dafe1afada71d801c8ef68efdfb06d [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;
80 Res.markConstant(C);
81 return Res;
82 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000083 static LVILatticeVal getNot(Constant *C) {
84 LVILatticeVal Res;
85 Res.markNotConstant(C);
86 return Res;
87 }
Chris Lattner16976522009-11-11 22:48:44 +000088
Owen Anderson5be2e782010-08-05 22:59:19 +000089 bool isUndefined() const { return Tag == undefined; }
90 bool isConstant() const { return Tag == constant; }
91 bool isNotConstant() const { return Tag == notconstant; }
92 bool isConstantRange() const { return Tag == constantrange; }
93 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +000094
95 Constant *getConstant() const {
96 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +000097 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000098 }
99
Chris Lattnerb52675b2009-11-12 04:36:58 +0000100 Constant *getNotConstant() const {
101 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000102 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000103 }
104
Owen Anderson5be2e782010-08-05 22:59:19 +0000105 ConstantRange getConstantRange() const {
106 assert(isConstantRange() &&
107 "Cannot get the constant-range of a non-constant-range!");
108 return Range;
109 }
110
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000111 /// markOverdefined - Return true if this is a change in status.
112 bool markOverdefined() {
113 if (isOverdefined())
114 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000115 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000116 return true;
117 }
118
119 /// markConstant - Return true if this is a change in status.
120 bool markConstant(Constant *V) {
121 if (isConstant()) {
122 assert(getConstant() == V && "Marking constant with different value");
123 return false;
124 }
125
126 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000127 Tag = constant;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000128 assert(V && "Marking constant with NULL");
Owen Andersondb78d732010-08-05 22:10:46 +0000129 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000130 return true;
131 }
132
Chris Lattnerb52675b2009-11-12 04:36:58 +0000133 /// markNotConstant - Return true if this is a change in status.
134 bool markNotConstant(Constant *V) {
135 if (isNotConstant()) {
136 assert(getNotConstant() == V && "Marking !constant with different value");
137 return false;
138 }
139
140 if (isConstant())
141 assert(getConstant() != V && "Marking not constant with different value");
142 else
143 assert(isUndefined());
144
Owen Andersondb78d732010-08-05 22:10:46 +0000145 Tag = notconstant;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000146 assert(V && "Marking constant with NULL");
Owen Andersondb78d732010-08-05 22:10:46 +0000147 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000148 return true;
149 }
150
Owen Anderson5be2e782010-08-05 22:59:19 +0000151 /// markConstantRange - Return true if this is a change in status.
152 bool markConstantRange(const ConstantRange NewR) {
153 if (isConstantRange()) {
154 if (NewR.isEmptySet())
155 return markOverdefined();
156
157 assert(Range.contains(NewR) &&
158 "Marking constant range with non-subset range!");
159 bool changed = Range == NewR;
160 Range = NewR;
161 return changed;
162 }
163
164 assert(isUndefined());
165 if (NewR.isEmptySet())
166 return markOverdefined();
167 else if (NewR.isFullSet()) {
168 Tag = undefined;
169 return true;
170 }
171
172 Tag = constantrange;
173 Range = NewR;
174 return true;
175 }
176
Chris Lattner16976522009-11-11 22:48:44 +0000177 /// mergeIn - Merge the specified lattice value into this one, updating this
178 /// one and returning true if anything changed.
179 bool mergeIn(const LVILatticeVal &RHS) {
180 if (RHS.isUndefined() || isOverdefined()) return false;
181 if (RHS.isOverdefined()) return markOverdefined();
182
Chris Lattnerb52675b2009-11-12 04:36:58 +0000183 if (RHS.isNotConstant()) {
184 if (isNotConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000185 if (getNotConstant() != RHS.getNotConstant() ||
186 isa<ConstantExpr>(getNotConstant()) ||
187 isa<ConstantExpr>(RHS.getNotConstant()))
Chris Lattnerb52675b2009-11-12 04:36:58 +0000188 return markOverdefined();
189 return false;
190 }
Chris Lattnerf496e792009-11-12 04:57:13 +0000191 if (isConstant()) {
192 if (getConstant() == RHS.getNotConstant() ||
193 isa<ConstantExpr>(RHS.getNotConstant()) ||
194 isa<ConstantExpr>(getConstant()))
195 return markOverdefined();
196 return markNotConstant(RHS.getNotConstant());
197 }
198
199 assert(isUndefined() && "Unexpected lattice");
Chris Lattnerb52675b2009-11-12 04:36:58 +0000200 return markNotConstant(RHS.getNotConstant());
201 }
202
Owen Anderson5be2e782010-08-05 22:59:19 +0000203 if (RHS.isConstantRange()) {
204 if (isConstantRange()) {
205 ConstantRange NewR = Range.intersectWith(RHS.getConstantRange());
206 if (NewR.isEmptySet())
207 return markOverdefined();
208 else
209 return markConstantRange(NewR);
210 }
211
212 assert(isUndefined() && "Unexpected lattice");
213 return markConstantRange(RHS.getConstantRange());
214 }
215
Chris Lattnerf496e792009-11-12 04:57:13 +0000216 // RHS must be a constant, we must be undef, constant, or notconstant.
Owen Anderson5be2e782010-08-05 22:59:19 +0000217 assert(!isConstantRange() &&
218 "Constant and ConstantRange cannot be merged.");
219
Chris Lattnerf496e792009-11-12 04:57:13 +0000220 if (isUndefined())
221 return markConstant(RHS.getConstant());
222
223 if (isConstant()) {
224 if (getConstant() != RHS.getConstant())
225 return markOverdefined();
226 return false;
227 }
228
229 // If we are known "!=4" and RHS is "==5", stay at "!=4".
230 if (getNotConstant() == RHS.getConstant() ||
231 isa<ConstantExpr>(getNotConstant()) ||
232 isa<ConstantExpr>(RHS.getConstant()))
Chris Lattner16976522009-11-11 22:48:44 +0000233 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000234 return false;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000235 }
236
237};
238
239} // end anonymous namespace.
240
Chris Lattner16976522009-11-11 22:48:44 +0000241namespace llvm {
242raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
243 if (Val.isUndefined())
244 return OS << "undefined";
245 if (Val.isOverdefined())
246 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000247
248 if (Val.isNotConstant())
249 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000250 return OS << "constant<" << *Val.getConstant() << '>';
251}
252}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000253
254//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000255// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000256//===----------------------------------------------------------------------===//
257
Chris Lattner2c5adf82009-11-15 19:59:49 +0000258namespace {
259 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
260 /// maintains information about queries across the clients' queries.
261 class LazyValueInfoCache {
Owen Anderson81881bc2010-07-30 20:56:07 +0000262 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000263 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
264 /// specified basic block for a Value* that depends on context.
265 typedef std::pair<BasicBlock*, LVILatticeVal> BlockCacheEntryTy;
266
267 /// ValueCacheEntryTy - This is all of the cached block information for
268 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
269 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000270 typedef std::map<BasicBlock*, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000271
Owen Anderson81881bc2010-07-30 20:56:07 +0000272 private:
Owen Anderson7f9cb742010-07-30 23:59:40 +0000273 /// LVIValueHandle - A callback value handle update the cache when
274 /// values are erased.
275 struct LVIValueHandle : public CallbackVH {
276 LazyValueInfoCache *Parent;
277
278 LVIValueHandle(Value *V, LazyValueInfoCache *P)
279 : CallbackVH(V), Parent(P) { }
280
281 void deleted();
282 void allUsesReplacedWith(Value* V) {
283 deleted();
284 }
285
286 LVIValueHandle &operator=(Value *V) {
287 return *this = LVIValueHandle(V, Parent);
288 }
289 };
290
Chris Lattner2c5adf82009-11-15 19:59:49 +0000291 /// ValueCache - This is all of the cached information for all values,
292 /// mapped from Value* to key information.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000293 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000294
295 /// OverDefinedCache - This tracks, on a per-block basis, the set of
296 /// values that are over-defined at the end of that block. This is required
297 /// for cache updating.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000298 std::set<std::pair<BasicBlock*, Value*> > OverDefinedCache;
299
Chris Lattner2c5adf82009-11-15 19:59:49 +0000300 public:
301
302 /// getValueInBlock - This is the query interface to determine the lattice
303 /// value for the specified Value* at the end of the specified block.
304 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
305
306 /// getValueOnEdge - This is the query interface to determine the lattice
307 /// value for the specified Value* that is true on the specified edge.
308 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000309
310 /// threadEdge - This is the update interface to inform the cache that an
311 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
312 /// NewSucc.
313 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000314 };
315} // end anonymous namespace
316
Owen Anderson81881bc2010-07-30 20:56:07 +0000317//===----------------------------------------------------------------------===//
318// LVIQuery Impl
319//===----------------------------------------------------------------------===//
320
321namespace {
322 /// LVIQuery - This is a transient object that exists while a query is
323 /// being performed.
324 ///
325 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
326 /// reallocation of the densemap on every query.
327 class LVIQuery {
328 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
329 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
330
331 /// This is the current value being queried for.
332 Value *Val;
333
Owen Anderson7f9cb742010-07-30 23:59:40 +0000334 /// This is a pointer to the owning cache, for recursive queries.
335 LazyValueInfoCache &Parent;
336
Owen Anderson81881bc2010-07-30 20:56:07 +0000337 /// This is all of the cached information about this value.
338 ValueCacheEntryTy &Cache;
339
340 /// This tracks, for each block, what values are overdefined.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000341 std::set<std::pair<BasicBlock*, Value*> > &OverDefinedCache;
Owen Anderson81881bc2010-07-30 20:56:07 +0000342
343 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
344 /// added to cache but that are not in sorted order.
345 DenseSet<BasicBlock*> NewBlockInfo;
346 public:
347
Owen Anderson7f9cb742010-07-30 23:59:40 +0000348 LVIQuery(Value *V, LazyValueInfoCache &P,
349 ValueCacheEntryTy &VC,
350 std::set<std::pair<BasicBlock*, Value*> > &ODC)
351 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000352 }
353
354 ~LVIQuery() {
355 // When the query is done, insert the newly discovered facts into the
356 // cache in sorted order.
357 if (NewBlockInfo.empty()) return;
358
359 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
360 E = NewBlockInfo.end(); I != E; ++I) {
361 if (Cache[*I].isOverdefined())
362 OverDefinedCache.insert(std::make_pair(*I, Val));
363 }
364 }
365
366 LVILatticeVal getBlockValue(BasicBlock *BB);
367 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
368
369 private:
370 LVILatticeVal &getCachedEntryForBlock(BasicBlock *BB);
371 };
372} // end anonymous namespace
Chris Lattner2c5adf82009-11-15 19:59:49 +0000373
Owen Anderson7f9cb742010-07-30 23:59:40 +0000374void LazyValueInfoCache::LVIValueHandle::deleted() {
375 Parent->ValueCache.erase(*this);
376 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
377 I = Parent->OverDefinedCache.begin(),
378 E = Parent->OverDefinedCache.end();
379 I != E; ) {
380 std::set<std::pair<BasicBlock*, Value*> >::iterator tmp = I;
381 ++I;
382 if (tmp->second == getValPtr())
383 Parent->OverDefinedCache.erase(tmp);
384 }
385}
386
387
Chris Lattnere5642812009-11-15 20:00:52 +0000388/// getCachedEntryForBlock - See if we already have a value for this block. If
Owen Anderson9a65dc92010-07-27 23:58:11 +0000389/// so, return it, otherwise create a new entry in the Cache map to use.
Owen Anderson81881bc2010-07-30 20:56:07 +0000390LVILatticeVal &LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
391 NewBlockInfo.insert(BB);
Owen Anderson9a65dc92010-07-27 23:58:11 +0000392 return Cache[BB];
Chris Lattnere5642812009-11-15 20:00:52 +0000393}
Chris Lattner2c5adf82009-11-15 19:59:49 +0000394
Owen Anderson81881bc2010-07-30 20:56:07 +0000395LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000396 // See if we already have a value for this block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000397 LVILatticeVal &BBLV = getCachedEntryForBlock(BB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000398
399 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000400 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000401 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Chris Lattner2c5adf82009-11-15 19:59:49 +0000402 return BBLV;
Chris Lattnere5642812009-11-15 20:00:52 +0000403 }
404
Chris Lattner2c5adf82009-11-15 19:59:49 +0000405 // Otherwise, this is the first time we're seeing this block. Reset the
406 // lattice value to overdefined, so that cycles will terminate and be
407 // conservatively correct.
408 BBLV.markOverdefined();
409
410 // If V is live into BB, see if our predecessors know anything about it.
411 Instruction *BBI = dyn_cast<Instruction>(Val);
412 if (BBI == 0 || BBI->getParent() != BB) {
413 LVILatticeVal Result; // Start Undefined.
414 unsigned NumPreds = 0;
415
416 // Loop over all of our predecessors, merging what we know from them into
417 // result.
418 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000419 Result.mergeIn(getEdgeValue(*PI, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000420
421 // If we hit overdefined, exit early. The BlockVals entry is already set
422 // to overdefined.
Chris Lattnere5642812009-11-15 20:00:52 +0000423 if (Result.isOverdefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000424 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000425 << "' - overdefined because of pred.\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000426 return Result;
Chris Lattnere5642812009-11-15 20:00:52 +0000427 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000428 ++NumPreds;
429 }
430
431 // If this is the entry block, we must be asking about an argument. The
432 // value is overdefined.
433 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
434 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
435 Result.markOverdefined();
436 return Result;
437 }
438
439 // Return the merged value, which is more precise than 'overdefined'.
440 assert(!Result.isOverdefined());
Owen Anderson81881bc2010-07-30 20:56:07 +0000441 return getCachedEntryForBlock(BB) = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000442 }
443
444 // If this value is defined by an instruction in this block, we have to
445 // process it here somehow or return overdefined.
446 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson7f9cb742010-07-30 23:59:40 +0000447 LVILatticeVal Result; // Start Undefined.
448
449 // Loop over all of our predecessors, merging what we know from them into
450 // result.
451 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
452 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
453 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
454
455 // If we hit overdefined, exit early. The BlockVals entry is already set
456 // to overdefined.
457 if (Result.isOverdefined()) {
458 DEBUG(dbgs() << " compute BB '" << BB->getName()
459 << "' - overdefined because of pred.\n");
460 return Result;
461 }
462 }
463
464 // Return the merged value, which is more precise than 'overdefined'.
465 assert(!Result.isOverdefined());
466 return getCachedEntryForBlock(BB) = Result;
467
Chris Lattner2c5adf82009-11-15 19:59:49 +0000468 } else {
469
470 }
471
David Greene5d93a1f2009-12-23 20:43:58 +0000472 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000473 << "' - overdefined because inst def found.\n");
474
Chris Lattner2c5adf82009-11-15 19:59:49 +0000475 LVILatticeVal Result;
476 Result.markOverdefined();
Owen Anderson81881bc2010-07-30 20:56:07 +0000477 return getCachedEntryForBlock(BB) = Result;
Chris Lattner10f2d132009-11-11 00:22:30 +0000478}
479
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000480
Chris Lattner800c47e2009-11-15 20:02:12 +0000481/// getEdgeValue - This method attempts to infer more complex
Owen Anderson81881bc2010-07-30 20:56:07 +0000482LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
Chris Lattner800c47e2009-11-15 20:02:12 +0000483 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
484 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000485 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
486 // If this is a conditional branch and only one successor goes to BBTo, then
487 // we maybe able to infer something from the condition.
488 if (BI->isConditional() &&
489 BI->getSuccessor(0) != BI->getSuccessor(1)) {
490 bool isTrueDest = BI->getSuccessor(0) == BBTo;
491 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
492 "BBTo isn't a successor of BBFrom");
493
494 // If V is the condition of the branch itself, then we know exactly what
495 // it is.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000496 if (BI->getCondition() == Val)
Chris Lattner16976522009-11-11 22:48:44 +0000497 return LVILatticeVal::get(ConstantInt::get(
Chris Lattner2c5adf82009-11-15 19:59:49 +0000498 Type::getInt1Ty(Val->getContext()), isTrueDest));
Chris Lattner16976522009-11-11 22:48:44 +0000499
500 // If the condition of the branch is an equality comparison, we may be
501 // able to infer the value.
502 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
Chris Lattner2c5adf82009-11-15 19:59:49 +0000503 if (ICI->isEquality() && ICI->getOperand(0) == Val &&
Chris Lattner16976522009-11-11 22:48:44 +0000504 isa<Constant>(ICI->getOperand(1))) {
505 // We know that V has the RHS constant if this is a true SETEQ or
506 // false SETNE.
507 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
508 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
Chris Lattnerb52675b2009-11-12 04:36:58 +0000509 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
Chris Lattner16976522009-11-11 22:48:44 +0000510 }
511 }
512 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000513
514 // If the edge was formed by a switch on the value, then we may know exactly
515 // what it is.
516 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
517 // If BBTo is the default destination of the switch, we don't know anything.
518 // Given a more powerful range analysis we could know stuff.
519 if (SI->getCondition() == Val && SI->getDefaultDest() != BBTo) {
520 // We only know something if there is exactly one value that goes from
521 // BBFrom to BBTo.
522 unsigned NumEdges = 0;
523 ConstantInt *EdgeVal = 0;
524 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
525 if (SI->getSuccessor(i) != BBTo) continue;
526 if (NumEdges++) break;
527 EdgeVal = SI->getCaseValue(i);
528 }
529 assert(EdgeVal && "Missing successor?");
530 if (NumEdges == 1)
531 return LVILatticeVal::get(EdgeVal);
532 }
533 }
Chris Lattner16976522009-11-11 22:48:44 +0000534
535 // Otherwise see if the value is known in the block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000536 return getBlockValue(BBFrom);
Chris Lattner16976522009-11-11 22:48:44 +0000537}
538
Owen Anderson81881bc2010-07-30 20:56:07 +0000539
540//===----------------------------------------------------------------------===//
541// LazyValueInfoCache Impl
542//===----------------------------------------------------------------------===//
543
Chris Lattner2c5adf82009-11-15 19:59:49 +0000544LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
545 // If already a constant, there is nothing to compute.
Chris Lattner16976522009-11-11 22:48:44 +0000546 if (Constant *VC = dyn_cast<Constant>(V))
Chris Lattner2c5adf82009-11-15 19:59:49 +0000547 return LVILatticeVal::get(VC);
Chris Lattner16976522009-11-11 22:48:44 +0000548
David Greene5d93a1f2009-12-23 20:43:58 +0000549 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000550 << BB->getName() << "'\n");
551
Owen Anderson7f9cb742010-07-30 23:59:40 +0000552 LVILatticeVal Result = LVIQuery(V, *this,
553 ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000554 OverDefinedCache).getBlockValue(BB);
Chris Lattner16976522009-11-11 22:48:44 +0000555
David Greene5d93a1f2009-12-23 20:43:58 +0000556 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000557 return Result;
558}
Chris Lattner16976522009-11-11 22:48:44 +0000559
Chris Lattner2c5adf82009-11-15 19:59:49 +0000560LVILatticeVal LazyValueInfoCache::
561getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
562 // If already a constant, there is nothing to compute.
563 if (Constant *VC = dyn_cast<Constant>(V))
564 return LVILatticeVal::get(VC);
565
David Greene5d93a1f2009-12-23 20:43:58 +0000566 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000567 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000568
Owen Anderson81881bc2010-07-30 20:56:07 +0000569 LVILatticeVal Result =
Owen Anderson7f9cb742010-07-30 23:59:40 +0000570 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000571 OverDefinedCache).getEdgeValue(FromBB, ToBB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000572
David Greene5d93a1f2009-12-23 20:43:58 +0000573 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000574
575 return Result;
576}
577
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000578void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
579 BasicBlock *NewSucc) {
580 // When an edge in the graph has been threaded, values that we could not
581 // determine a value for before (i.e. were marked overdefined) may be possible
582 // to solve now. We do NOT try to proactively update these values. Instead,
583 // we clear their entries from the cache, and allow lazy updating to recompute
584 // them when needed.
585
586 // The updating process is fairly simple: we need to dropped cached info
587 // for all values that were marked overdefined in OldSucc, and for those same
588 // values in any successor of OldSucc (except NewSucc) in which they were
589 // also marked overdefined.
590 std::vector<BasicBlock*> worklist;
591 worklist.push_back(OldSucc);
592
Owen Anderson9a65dc92010-07-27 23:58:11 +0000593 DenseSet<Value*> ClearSet;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000594 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
Owen Anderson9a65dc92010-07-27 23:58:11 +0000595 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
596 if (I->first == OldSucc)
597 ClearSet.insert(I->second);
598 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000599
600 // Use a worklist to perform a depth-first search of OldSucc's successors.
601 // NOTE: We do not need a visited list since any blocks we have already
602 // visited will have had their overdefined markers cleared already, and we
603 // thus won't loop to their successors.
604 while (!worklist.empty()) {
605 BasicBlock *ToUpdate = worklist.back();
606 worklist.pop_back();
607
608 // Skip blocks only accessible through NewSucc.
609 if (ToUpdate == NewSucc) continue;
610
611 bool changed = false;
Owen Anderson9a65dc92010-07-27 23:58:11 +0000612 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000613 I != E; ++I) {
614 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson7f9cb742010-07-30 23:59:40 +0000615 std::set<std::pair<BasicBlock*, Value*> >::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000616 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
617 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000618
Owen Anderson9a65dc92010-07-27 23:58:11 +0000619 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000620 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000621 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
622
623 assert(CI != Entry.end() && "Couldn't find entry to update?");
624 Entry.erase(CI);
625 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000626
Owen Anderson9a65dc92010-07-27 23:58:11 +0000627 // If we removed anything, then we potentially need to update
628 // blocks successors too.
629 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000630 }
631
632 if (!changed) continue;
633
634 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
635 }
636}
637
Chris Lattner2c5adf82009-11-15 19:59:49 +0000638//===----------------------------------------------------------------------===//
639// LazyValueInfo Impl
640//===----------------------------------------------------------------------===//
641
642bool LazyValueInfo::runOnFunction(Function &F) {
643 TD = getAnalysisIfAvailable<TargetData>();
644 // Fully lazy.
645 return false;
646}
647
648/// getCache - This lazily constructs the LazyValueInfoCache.
649static LazyValueInfoCache &getCache(void *&PImpl) {
650 if (!PImpl)
651 PImpl = new LazyValueInfoCache();
652 return *static_cast<LazyValueInfoCache*>(PImpl);
653}
654
655void LazyValueInfo::releaseMemory() {
656 // If the cache was allocated, free it.
657 if (PImpl) {
658 delete &getCache(PImpl);
659 PImpl = 0;
660 }
661}
662
663Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
664 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
665
Chris Lattner16976522009-11-11 22:48:44 +0000666 if (Result.isConstant())
667 return Result.getConstant();
668 return 0;
669}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000670
Chris Lattner38392bb2009-11-12 01:29:10 +0000671/// getConstantOnEdge - Determine whether the specified value is known to be a
672/// constant on the specified edge. Return null if not.
673Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
674 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000675 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +0000676
677 if (Result.isConstant())
678 return Result.getConstant();
679 return 0;
680}
681
Chris Lattnerb52675b2009-11-12 04:36:58 +0000682/// getPredicateOnEdge - Determine whether the specified value comparison
683/// with a constant is known to be true or false on the specified CFG edge.
684/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000685LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +0000686LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
687 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000688 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000689
Chris Lattnerb52675b2009-11-12 04:36:58 +0000690 // If we know the value is a constant, evaluate the conditional.
691 Constant *Res = 0;
692 if (Result.isConstant()) {
693 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
694 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
695 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000696 return Unknown;
697 }
698
699 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000700 // If this is an equality comparison, we can try to fold it knowing that
701 // "V != C1".
702 if (Pred == ICmpInst::ICMP_EQ) {
703 // !C1 == C -> false iff C1 == C.
704 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
705 Result.getNotConstant(), C, TD);
706 if (Res->isNullValue())
707 return False;
708 } else if (Pred == ICmpInst::ICMP_NE) {
709 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +0000710 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +0000711 Result.getNotConstant(), C, TD);
712 if (Res->isNullValue())
713 return True;
714 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000715 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000716 }
717
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000718 return Unknown;
719}
720
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000721void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
722 BasicBlock* NewSucc) {
723 getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
724}