Mark some functions as used which are used within debug-only code. This
[oota-llvm.git] / lib / Analysis / LazyValueInfo.cpp
1 //===- 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
15 #define DEBUG_TYPE "lazy-value-info"
16 #include "llvm/Analysis/LazyValueInfo.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/ValueHandle.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include <map>
32 #include <set>
33 #include <stack>
34 using namespace llvm;
35
36 char LazyValueInfo::ID = 0;
37 INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
38                 "Lazy Value Information Analysis", false, true)
39
40 namespace llvm {
41   FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
42 }
43
44
45 //===----------------------------------------------------------------------===//
46 //                               LVILatticeVal
47 //===----------------------------------------------------------------------===//
48
49 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
50 /// value.
51 ///
52 /// FIXME: This is basically just for bringup, this can be made a lot more rich
53 /// in the future.
54 ///
55 namespace {
56 class LVILatticeVal {
57   enum LatticeValueTy {
58     /// undefined - This Value has no known value yet.
59     undefined,
60     
61     /// constant - This Value has a specific constant value.
62     constant,
63     /// notconstant - This Value is known to not have the specified value.
64     notconstant,
65     
66     /// constantrange - The Value falls within this range.
67     constantrange,
68     
69     /// overdefined - This value is not known to be constant, and we know that
70     /// it has a value.
71     overdefined
72   };
73   
74   /// Val: This stores the current lattice value along with the Constant* for
75   /// the constant if this is a 'constant' or 'notconstant' value.
76   LatticeValueTy Tag;
77   Constant *Val;
78   ConstantRange Range;
79   
80 public:
81   LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
82
83   static LVILatticeVal get(Constant *C) {
84     LVILatticeVal Res;
85     if (!isa<UndefValue>(C))
86       Res.markConstant(C);
87     return Res;
88   }
89   static LVILatticeVal getNot(Constant *C) {
90     LVILatticeVal Res;
91     if (!isa<UndefValue>(C))
92       Res.markNotConstant(C);
93     return Res;
94   }
95   static LVILatticeVal getRange(ConstantRange CR) {
96     LVILatticeVal Res;
97     Res.markConstantRange(CR);
98     return Res;
99   }
100   
101   bool isUndefined() const     { return Tag == undefined; }
102   bool isConstant() const      { return Tag == constant; }
103   bool isNotConstant() const   { return Tag == notconstant; }
104   bool isConstantRange() const { return Tag == constantrange; }
105   bool isOverdefined() const   { return Tag == overdefined; }
106   
107   Constant *getConstant() const {
108     assert(isConstant() && "Cannot get the constant of a non-constant!");
109     return Val;
110   }
111   
112   Constant *getNotConstant() const {
113     assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
114     return Val;
115   }
116   
117   ConstantRange getConstantRange() const {
118     assert(isConstantRange() &&
119            "Cannot get the constant-range of a non-constant-range!");
120     return Range;
121   }
122   
123   /// markOverdefined - Return true if this is a change in status.
124   bool markOverdefined() {
125     if (isOverdefined())
126       return false;
127     Tag = overdefined;
128     return true;
129   }
130
131   /// markConstant - Return true if this is a change in status.
132   bool markConstant(Constant *V) {
133     assert(V && "Marking constant with NULL");
134     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
135       return markConstantRange(ConstantRange(CI->getValue()));
136     if (isa<UndefValue>(V))
137       return false;
138
139     assert((!isConstant() || getConstant() == V) &&
140            "Marking constant with different value");
141     assert(isUndefined());
142     Tag = constant;
143     Val = V;
144     return true;
145   }
146   
147   /// markNotConstant - Return true if this is a change in status.
148   bool markNotConstant(Constant *V) {
149     assert(V && "Marking constant with NULL");
150     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
151       return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
152     if (isa<UndefValue>(V))
153       return false;
154
155     assert((!isConstant() || getConstant() != V) &&
156            "Marking constant !constant with same value");
157     assert((!isNotConstant() || getNotConstant() == V) &&
158            "Marking !constant with different value");
159     assert(isUndefined() || isConstant());
160     Tag = notconstant;
161     Val = V;
162     return true;
163   }
164   
165   /// markConstantRange - Return true if this is a change in status.
166   bool markConstantRange(const ConstantRange NewR) {
167     if (isConstantRange()) {
168       if (NewR.isEmptySet())
169         return markOverdefined();
170       
171       bool changed = Range == NewR;
172       Range = NewR;
173       return changed;
174     }
175     
176     assert(isUndefined());
177     if (NewR.isEmptySet())
178       return markOverdefined();
179     
180     Tag = constantrange;
181     Range = NewR;
182     return true;
183   }
184   
185   /// mergeIn - Merge the specified lattice value into this one, updating this
186   /// one and returning true if anything changed.
187   bool mergeIn(const LVILatticeVal &RHS) {
188     if (RHS.isUndefined() || isOverdefined()) return false;
189     if (RHS.isOverdefined()) return markOverdefined();
190
191     if (isUndefined()) {
192       Tag = RHS.Tag;
193       Val = RHS.Val;
194       Range = RHS.Range;
195       return true;
196     }
197
198     if (isConstant()) {
199       if (RHS.isConstant()) {
200         if (Val == RHS.Val)
201           return false;
202         return markOverdefined();
203       }
204
205       if (RHS.isNotConstant()) {
206         if (Val == RHS.Val)
207           return markOverdefined();
208
209         // Unless we can prove that the two Constants are different, we must
210         // move to overdefined.
211         // FIXME: use TargetData for smarter constant folding.
212         if (ConstantInt *Res = dyn_cast<ConstantInt>(
213                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
214                                                 getConstant(),
215                                                 RHS.getNotConstant())))
216           if (Res->isOne())
217             return markNotConstant(RHS.getNotConstant());
218
219         return markOverdefined();
220       }
221
222       // RHS is a ConstantRange, LHS is a non-integer Constant.
223
224       // FIXME: consider the case where RHS is a range [1, 0) and LHS is
225       // a function. The correct result is to pick up RHS.
226
227       return markOverdefined();
228     }
229
230     if (isNotConstant()) {
231       if (RHS.isConstant()) {
232         if (Val == RHS.Val)
233           return markOverdefined();
234
235         // Unless we can prove that the two Constants are different, we must
236         // move to overdefined.
237         // FIXME: use TargetData for smarter constant folding.
238         if (ConstantInt *Res = dyn_cast<ConstantInt>(
239                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
240                                                 getNotConstant(),
241                                                 RHS.getConstant())))
242           if (Res->isOne())
243             return false;
244
245         return markOverdefined();
246       }
247
248       if (RHS.isNotConstant()) {
249         if (Val == RHS.Val)
250           return false;
251         return markOverdefined();
252       }
253
254       return markOverdefined();
255     }
256
257     assert(isConstantRange() && "New LVILattice type?");
258     if (!RHS.isConstantRange())
259       return markOverdefined();
260
261     ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
262     if (NewR.isFullSet())
263       return markOverdefined();
264     return markConstantRange(NewR);
265   }
266 };
267   
268 } // end anonymous namespace.
269
270 namespace llvm {
271 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
272     LLVM_ATTRIBUTE_USED;
273 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
274   if (Val.isUndefined())
275     return OS << "undefined";
276   if (Val.isOverdefined())
277     return OS << "overdefined";
278
279   if (Val.isNotConstant())
280     return OS << "notconstant<" << *Val.getNotConstant() << '>';
281   else if (Val.isConstantRange())
282     return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
283               << Val.getConstantRange().getUpper() << '>';
284   return OS << "constant<" << *Val.getConstant() << '>';
285 }
286 }
287
288 //===----------------------------------------------------------------------===//
289 //                          LazyValueInfoCache Decl
290 //===----------------------------------------------------------------------===//
291
292 namespace {
293   /// LVIValueHandle - A callback value handle update the cache when
294   /// values are erased.
295   class LazyValueInfoCache;
296   struct LVIValueHandle : public CallbackVH {
297     LazyValueInfoCache *Parent;
298       
299     LVIValueHandle(Value *V, LazyValueInfoCache *P)
300       : CallbackVH(V), Parent(P) { }
301       
302     void deleted();
303     void allUsesReplacedWith(Value *V) {
304       deleted();
305     }
306   };
307 }
308
309 namespace llvm {
310   template<>
311   struct DenseMapInfo<LVIValueHandle> {
312     typedef DenseMapInfo<Value*> PointerInfo;
313     static inline LVIValueHandle getEmptyKey() {
314       return LVIValueHandle(PointerInfo::getEmptyKey(),
315                             static_cast<LazyValueInfoCache*>(0));
316     }
317     static inline LVIValueHandle getTombstoneKey() {
318       return LVIValueHandle(PointerInfo::getTombstoneKey(),
319                             static_cast<LazyValueInfoCache*>(0));
320     }
321     static unsigned getHashValue(const LVIValueHandle &Val) {
322       return PointerInfo::getHashValue(Val);
323     }
324     static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
325       return LHS == RHS;
326     }
327   };
328   
329   template<>
330   struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
331     typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
332     typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
333     typedef DenseMapInfo<Value*> BPointerInfo;
334     static inline PairTy getEmptyKey() {
335       return std::make_pair(APointerInfo::getEmptyKey(),
336                             BPointerInfo::getEmptyKey());
337     }
338     static inline PairTy getTombstoneKey() {
339       return std::make_pair(APointerInfo::getTombstoneKey(), 
340                             BPointerInfo::getTombstoneKey());
341     }
342     static unsigned getHashValue( const PairTy &Val) {
343       return APointerInfo::getHashValue(Val.first) ^ 
344              BPointerInfo::getHashValue(Val.second);
345     }
346     static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
347       return APointerInfo::isEqual(LHS.first, RHS.first) &&
348              BPointerInfo::isEqual(LHS.second, RHS.second);
349     }
350   };
351 }
352
353 namespace { 
354   /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
355   /// maintains information about queries across the clients' queries.
356   class LazyValueInfoCache {
357     /// ValueCacheEntryTy - This is all of the cached block information for
358     /// exactly one Value*.  The entries are sorted by the BasicBlock* of the
359     /// entries, allowing us to do a lookup with a binary search.
360     typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
361
362     /// ValueCache - This is all of the cached information for all values,
363     /// mapped from Value* to key information.
364     DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
365     
366     /// OverDefinedCache - This tracks, on a per-block basis, the set of 
367     /// values that are over-defined at the end of that block.  This is required
368     /// for cache updating.
369     typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
370     DenseSet<OverDefinedPairTy> OverDefinedCache;
371     
372     /// BlockValueStack - This stack holds the state of the value solver
373     /// during a query.  It basically emulates the callstack of the naive
374     /// recursive value lookup process.
375     std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
376     
377     friend struct LVIValueHandle;
378     
379     /// OverDefinedCacheUpdater - A helper object that ensures that the
380     /// OverDefinedCache is updated whenever solveBlockValue returns.
381     struct OverDefinedCacheUpdater {
382       LazyValueInfoCache *Parent;
383       Value *Val;
384       BasicBlock *BB;
385       LVILatticeVal &BBLV;
386       
387       OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
388                        LazyValueInfoCache *P)
389         : Parent(P), Val(V), BB(B), BBLV(LV) { }
390       
391       bool markResult(bool changed) { 
392         if (changed && BBLV.isOverdefined())
393           Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
394         return changed;
395       }
396     };
397     
398
399
400     LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
401     bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
402                       LVILatticeVal &Result);
403     bool hasBlockValue(Value *Val, BasicBlock *BB);
404
405     // These methods process one work item and may add more. A false value
406     // returned means that the work item was not completely processed and must
407     // be revisited after going through the new items.
408     bool solveBlockValue(Value *Val, BasicBlock *BB);
409     bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
410                                  Value *Val, BasicBlock *BB);
411     bool solveBlockValuePHINode(LVILatticeVal &BBLV,
412                                 PHINode *PN, BasicBlock *BB);
413     bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
414                                       Instruction *BBI, BasicBlock *BB);
415
416     void solve();
417     
418     ValueCacheEntryTy &lookup(Value *V) {
419       return ValueCache[LVIValueHandle(V, this)];
420     }
421
422   public:
423     /// getValueInBlock - This is the query interface to determine the lattice
424     /// value for the specified Value* at the end of the specified block.
425     LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
426
427     /// getValueOnEdge - This is the query interface to determine the lattice
428     /// value for the specified Value* that is true on the specified edge.
429     LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
430     
431     /// threadEdge - This is the update interface to inform the cache that an
432     /// edge from PredBB to OldSucc has been threaded to be from PredBB to
433     /// NewSucc.
434     void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
435     
436     /// eraseBlock - This is part of the update interface to inform the cache
437     /// that a block has been deleted.
438     void eraseBlock(BasicBlock *BB);
439     
440     /// clear - Empty the cache.
441     void clear() {
442       ValueCache.clear();
443       OverDefinedCache.clear();
444     }
445   };
446 } // end anonymous namespace
447
448 void LVIValueHandle::deleted() {
449   typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
450   
451   SmallVector<OverDefinedPairTy, 4> ToErase;
452   for (DenseSet<OverDefinedPairTy>::iterator 
453        I = Parent->OverDefinedCache.begin(),
454        E = Parent->OverDefinedCache.end();
455        I != E; ++I) {
456     if (I->second == getValPtr())
457       ToErase.push_back(*I);
458   }
459   
460   for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
461        E = ToErase.end(); I != E; ++I)
462     Parent->OverDefinedCache.erase(*I);
463   
464   // This erasure deallocates *this, so it MUST happen after we're done
465   // using any and all members of *this.
466   Parent->ValueCache.erase(*this);
467 }
468
469 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
470   SmallVector<OverDefinedPairTy, 4> ToErase;
471   for (DenseSet<OverDefinedPairTy>::iterator  I = OverDefinedCache.begin(),
472        E = OverDefinedCache.end(); I != E; ++I) {
473     if (I->first == BB)
474       ToErase.push_back(*I);
475   }
476   
477   for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
478        E = ToErase.end(); I != E; ++I)
479     OverDefinedCache.erase(*I);
480
481   for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
482        I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
483     I->second.erase(BB);
484 }
485
486 void LazyValueInfoCache::solve() {
487   while (!BlockValueStack.empty()) {
488     std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
489     if (solveBlockValue(e.second, e.first))
490       BlockValueStack.pop();
491   }
492 }
493
494 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
495   // If already a constant, there is nothing to compute.
496   if (isa<Constant>(Val))
497     return true;
498
499   LVIValueHandle ValHandle(Val, this);
500   if (!ValueCache.count(ValHandle)) return false;
501   return ValueCache[ValHandle].count(BB);
502 }
503
504 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
505   // If already a constant, there is nothing to compute.
506   if (Constant *VC = dyn_cast<Constant>(Val))
507     return LVILatticeVal::get(VC);
508
509   return lookup(Val)[BB];
510 }
511
512 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
513   if (isa<Constant>(Val))
514     return true;
515
516   ValueCacheEntryTy &Cache = lookup(Val);
517   LVILatticeVal &BBLV = Cache[BB];
518   
519   // OverDefinedCacheUpdater is a helper object that will update
520   // the OverDefinedCache for us when this method exits.  Make sure to
521   // call markResult on it as we exist, passing a bool to indicate if the
522   // cache needs updating, i.e. if we have solve a new value or not.
523   OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
524
525   // If we've already computed this block's value, return it.
526   if (!BBLV.isUndefined()) {
527     DEBUG(dbgs() << "  reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
528     
529     // Since we're reusing a cached value here, we don't need to update the 
530     // OverDefinedCahce.  The cache will have been properly updated 
531     // whenever the cached value was inserted.
532     ODCacheUpdater.markResult(false);
533     return true;
534   }
535
536   // Otherwise, this is the first time we're seeing this block.  Reset the
537   // lattice value to overdefined, so that cycles will terminate and be
538   // conservatively correct.
539   BBLV.markOverdefined();
540   
541   Instruction *BBI = dyn_cast<Instruction>(Val);
542   if (BBI == 0 || BBI->getParent() != BB) {
543     return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
544   }
545
546   if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
547     return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
548   }
549
550   if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
551     BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
552     return ODCacheUpdater.markResult(true);
553   }
554
555   // We can only analyze the definitions of certain classes of instructions
556   // (integral binops and casts at the moment), so bail if this isn't one.
557   LVILatticeVal Result;
558   if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
559      !BBI->getType()->isIntegerTy()) {
560     DEBUG(dbgs() << " compute BB '" << BB->getName()
561                  << "' - overdefined because inst def found.\n");
562     BBLV.markOverdefined();
563     return ODCacheUpdater.markResult(true);
564   }
565
566   // FIXME: We're currently limited to binops with a constant RHS.  This should
567   // be improved.
568   BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
569   if (BO && !isa<ConstantInt>(BO->getOperand(1))) { 
570     DEBUG(dbgs() << " compute BB '" << BB->getName()
571                  << "' - overdefined because inst def found.\n");
572
573     BBLV.markOverdefined();
574     return ODCacheUpdater.markResult(true);
575   }
576
577   return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
578 }
579
580 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
581   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
582     return L->getPointerAddressSpace() == 0 &&
583         GetUnderlyingObject(L->getPointerOperand()) ==
584         GetUnderlyingObject(Ptr);
585   }
586   if (StoreInst *S = dyn_cast<StoreInst>(I)) {
587     return S->getPointerAddressSpace() == 0 &&
588         GetUnderlyingObject(S->getPointerOperand()) ==
589         GetUnderlyingObject(Ptr);
590   }
591   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
592     if (MI->isVolatile()) return false;
593     if (MI->getAddressSpace() != 0) return false;
594
595     // FIXME: check whether it has a valuerange that excludes zero?
596     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
597     if (!Len || Len->isZero()) return false;
598
599     if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
600       return true;
601     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
602       return MTI->getRawSource() == Ptr || MTI->getSource() == Ptr;
603   }
604   return false;
605 }
606
607 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
608                                                  Value *Val, BasicBlock *BB) {
609   LVILatticeVal Result;  // Start Undefined.
610
611   // If this is a pointer, and there's a load from that pointer in this BB,
612   // then we know that the pointer can't be NULL.
613   bool NotNull = false;
614   if (Val->getType()->isPointerTy()) {
615     if (isa<AllocaInst>(Val)) {
616       NotNull = true;
617     } else {
618       for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
619         if (InstructionDereferencesPointer(BI, Val)) {
620           NotNull = true;
621           break;
622         }
623       }
624     }
625   }
626
627   // If this is the entry block, we must be asking about an argument.  The
628   // value is overdefined.
629   if (BB == &BB->getParent()->getEntryBlock()) {
630     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
631     if (NotNull) {
632       const PointerType *PTy = cast<PointerType>(Val->getType());
633       Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
634     } else {
635       Result.markOverdefined();
636     }
637     BBLV = Result;
638     return true;
639   }
640
641   // Loop over all of our predecessors, merging what we know from them into
642   // result.
643   bool EdgesMissing = false;
644   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
645     LVILatticeVal EdgeResult;
646     EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
647     if (EdgesMissing)
648       continue;
649
650     Result.mergeIn(EdgeResult);
651
652     // If we hit overdefined, exit early.  The BlockVals entry is already set
653     // to overdefined.
654     if (Result.isOverdefined()) {
655       DEBUG(dbgs() << " compute BB '" << BB->getName()
656             << "' - overdefined because of pred.\n");
657       // If we previously determined that this is a pointer that can't be null
658       // then return that rather than giving up entirely.
659       if (NotNull) {
660         const PointerType *PTy = cast<PointerType>(Val->getType());
661         Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
662       }
663       
664       BBLV = Result;
665       return true;
666     }
667   }
668   if (EdgesMissing)
669     return false;
670
671   // Return the merged value, which is more precise than 'overdefined'.
672   assert(!Result.isOverdefined());
673   BBLV = Result;
674   return true;
675 }
676   
677 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
678                                                 PHINode *PN, BasicBlock *BB) {
679   LVILatticeVal Result;  // Start Undefined.
680
681   // Loop over all of our predecessors, merging what we know from them into
682   // result.
683   bool EdgesMissing = false;
684   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
685     BasicBlock *PhiBB = PN->getIncomingBlock(i);
686     Value *PhiVal = PN->getIncomingValue(i);
687     LVILatticeVal EdgeResult;
688     EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
689     if (EdgesMissing)
690       continue;
691
692     Result.mergeIn(EdgeResult);
693
694     // If we hit overdefined, exit early.  The BlockVals entry is already set
695     // to overdefined.
696     if (Result.isOverdefined()) {
697       DEBUG(dbgs() << " compute BB '" << BB->getName()
698             << "' - overdefined because of pred.\n");
699       
700       BBLV = Result;
701       return true;
702     }
703   }
704   if (EdgesMissing)
705     return false;
706
707   // Return the merged value, which is more precise than 'overdefined'.
708   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
709   BBLV = Result;
710   return true;
711 }
712
713 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
714                                                       Instruction *BBI,
715                                                       BasicBlock *BB) {
716   // Figure out the range of the LHS.  If that fails, bail.
717   if (!hasBlockValue(BBI->getOperand(0), BB)) {
718     BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
719     return false;
720   }
721
722   LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
723   if (!LHSVal.isConstantRange()) {
724     BBLV.markOverdefined();
725     return true;
726   }
727   
728   ConstantRange LHSRange = LHSVal.getConstantRange();
729   ConstantRange RHSRange(1);
730   const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
731   if (isa<BinaryOperator>(BBI)) {
732     if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
733       RHSRange = ConstantRange(RHS->getValue());
734     } else {
735       BBLV.markOverdefined();
736       return true;
737     }
738   }
739
740   // NOTE: We're currently limited by the set of operations that ConstantRange
741   // can evaluate symbolically.  Enhancing that set will allows us to analyze
742   // more definitions.
743   LVILatticeVal Result;
744   switch (BBI->getOpcode()) {
745   case Instruction::Add:
746     Result.markConstantRange(LHSRange.add(RHSRange));
747     break;
748   case Instruction::Sub:
749     Result.markConstantRange(LHSRange.sub(RHSRange));
750     break;
751   case Instruction::Mul:
752     Result.markConstantRange(LHSRange.multiply(RHSRange));
753     break;
754   case Instruction::UDiv:
755     Result.markConstantRange(LHSRange.udiv(RHSRange));
756     break;
757   case Instruction::Shl:
758     Result.markConstantRange(LHSRange.shl(RHSRange));
759     break;
760   case Instruction::LShr:
761     Result.markConstantRange(LHSRange.lshr(RHSRange));
762     break;
763   case Instruction::Trunc:
764     Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
765     break;
766   case Instruction::SExt:
767     Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
768     break;
769   case Instruction::ZExt:
770     Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
771     break;
772   case Instruction::BitCast:
773     Result.markConstantRange(LHSRange);
774     break;
775   case Instruction::And:
776     Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
777     break;
778   case Instruction::Or:
779     Result.markConstantRange(LHSRange.binaryOr(RHSRange));
780     break;
781   
782   // Unhandled instructions are overdefined.
783   default:
784     DEBUG(dbgs() << " compute BB '" << BB->getName()
785                  << "' - overdefined because inst def found.\n");
786     Result.markOverdefined();
787     break;
788   }
789   
790   BBLV = Result;
791   return true;
792 }
793
794 /// getEdgeValue - This method attempts to infer more complex 
795 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
796                                       BasicBlock *BBTo, LVILatticeVal &Result) {
797   // If already a constant, there is nothing to compute.
798   if (Constant *VC = dyn_cast<Constant>(Val)) {
799     Result = LVILatticeVal::get(VC);
800     return true;
801   }
802   
803   // TODO: Handle more complex conditionals.  If (v == 0 || v2 < 1) is false, we
804   // know that v != 0.
805   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
806     // If this is a conditional branch and only one successor goes to BBTo, then
807     // we maybe able to infer something from the condition. 
808     if (BI->isConditional() &&
809         BI->getSuccessor(0) != BI->getSuccessor(1)) {
810       bool isTrueDest = BI->getSuccessor(0) == BBTo;
811       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
812              "BBTo isn't a successor of BBFrom");
813       
814       // If V is the condition of the branch itself, then we know exactly what
815       // it is.
816       if (BI->getCondition() == Val) {
817         Result = LVILatticeVal::get(ConstantInt::get(
818                               Type::getInt1Ty(Val->getContext()), isTrueDest));
819         return true;
820       }
821       
822       // If the condition of the branch is an equality comparison, we may be
823       // able to infer the value.
824       ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
825       if (ICI && ICI->getOperand(0) == Val &&
826           isa<Constant>(ICI->getOperand(1))) {
827         if (ICI->isEquality()) {
828           // We know that V has the RHS constant if this is a true SETEQ or
829           // false SETNE. 
830           if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
831             Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
832           else
833             Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
834           return true;
835         }
836
837         if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
838           // Calculate the range of values that would satisfy the comparison.
839           ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
840           ConstantRange TrueValues =
841             ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
842
843           // If we're interested in the false dest, invert the condition.
844           if (!isTrueDest) TrueValues = TrueValues.inverse();
845           
846           // Figure out the possible values of the query BEFORE this branch.  
847           if (!hasBlockValue(Val, BBFrom)) {
848             BlockValueStack.push(std::make_pair(BBFrom, Val));
849             return false;
850           }
851           
852           LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
853           if (!InBlock.isConstantRange()) {
854             Result = LVILatticeVal::getRange(TrueValues);
855             return true;
856           }
857
858           // Find all potential values that satisfy both the input and output
859           // conditions.
860           ConstantRange PossibleValues =
861             TrueValues.intersectWith(InBlock.getConstantRange());
862
863           Result = LVILatticeVal::getRange(PossibleValues);
864           return true;
865         }
866       }
867     }
868   }
869
870   // If the edge was formed by a switch on the value, then we may know exactly
871   // what it is.
872   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
873     if (SI->getCondition() == Val) {
874       // We don't know anything in the default case.
875       if (SI->getDefaultDest() == BBTo) {
876         Result.markOverdefined();
877         return true;
878       }
879       
880       // We only know something if there is exactly one value that goes from
881       // BBFrom to BBTo.
882       unsigned NumEdges = 0;
883       ConstantInt *EdgeVal = 0;
884       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
885         if (SI->getSuccessor(i) != BBTo) continue;
886         if (NumEdges++) break;
887         EdgeVal = SI->getCaseValue(i);
888       }
889       assert(EdgeVal && "Missing successor?");
890       if (NumEdges == 1) {
891         Result = LVILatticeVal::get(EdgeVal);
892         return true;
893       }
894     }
895   }
896   
897   // Otherwise see if the value is known in the block.
898   if (hasBlockValue(Val, BBFrom)) {
899     Result = getBlockValue(Val, BBFrom);
900     return true;
901   }
902   BlockValueStack.push(std::make_pair(BBFrom, Val));
903   return false;
904 }
905
906 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
907   DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
908         << BB->getName() << "'\n");
909   
910   BlockValueStack.push(std::make_pair(BB, V));
911   solve();
912   LVILatticeVal Result = getBlockValue(V, BB);
913
914   DEBUG(dbgs() << "  Result = " << Result << "\n");
915   return Result;
916 }
917
918 LVILatticeVal LazyValueInfoCache::
919 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
920   DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
921         << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
922   
923   LVILatticeVal Result;
924   if (!getEdgeValue(V, FromBB, ToBB, Result)) {
925     solve();
926     bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
927     (void)WasFastQuery;
928     assert(WasFastQuery && "More work to do after problem solved?");
929   }
930
931   DEBUG(dbgs() << "  Result = " << Result << "\n");
932   return Result;
933 }
934
935 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
936                                     BasicBlock *NewSucc) {
937   // When an edge in the graph has been threaded, values that we could not 
938   // determine a value for before (i.e. were marked overdefined) may be possible
939   // to solve now.  We do NOT try to proactively update these values.  Instead,
940   // we clear their entries from the cache, and allow lazy updating to recompute
941   // them when needed.
942   
943   // The updating process is fairly simple: we need to dropped cached info
944   // for all values that were marked overdefined in OldSucc, and for those same
945   // values in any successor of OldSucc (except NewSucc) in which they were
946   // also marked overdefined.
947   std::vector<BasicBlock*> worklist;
948   worklist.push_back(OldSucc);
949   
950   DenseSet<Value*> ClearSet;
951   for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
952        E = OverDefinedCache.end(); I != E; ++I) {
953     if (I->first == OldSucc)
954       ClearSet.insert(I->second);
955   }
956   
957   // Use a worklist to perform a depth-first search of OldSucc's successors.
958   // NOTE: We do not need a visited list since any blocks we have already
959   // visited will have had their overdefined markers cleared already, and we
960   // thus won't loop to their successors.
961   while (!worklist.empty()) {
962     BasicBlock *ToUpdate = worklist.back();
963     worklist.pop_back();
964     
965     // Skip blocks only accessible through NewSucc.
966     if (ToUpdate == NewSucc) continue;
967     
968     bool changed = false;
969     for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
970          I != E; ++I) {
971       // If a value was marked overdefined in OldSucc, and is here too...
972       DenseSet<OverDefinedPairTy>::iterator OI =
973         OverDefinedCache.find(std::make_pair(ToUpdate, *I));
974       if (OI == OverDefinedCache.end()) continue;
975
976       // Remove it from the caches.
977       ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
978       ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
979
980       assert(CI != Entry.end() && "Couldn't find entry to update?");
981       Entry.erase(CI);
982       OverDefinedCache.erase(OI);
983
984       // If we removed anything, then we potentially need to update 
985       // blocks successors too.
986       changed = true;
987     }
988
989     if (!changed) continue;
990     
991     worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
992   }
993 }
994
995 //===----------------------------------------------------------------------===//
996 //                            LazyValueInfo Impl
997 //===----------------------------------------------------------------------===//
998
999 /// getCache - This lazily constructs the LazyValueInfoCache.
1000 static LazyValueInfoCache &getCache(void *&PImpl) {
1001   if (!PImpl)
1002     PImpl = new LazyValueInfoCache();
1003   return *static_cast<LazyValueInfoCache*>(PImpl);
1004 }
1005
1006 bool LazyValueInfo::runOnFunction(Function &F) {
1007   if (PImpl)
1008     getCache(PImpl).clear();
1009   
1010   TD = getAnalysisIfAvailable<TargetData>();
1011   // Fully lazy.
1012   return false;
1013 }
1014
1015 void LazyValueInfo::releaseMemory() {
1016   // If the cache was allocated, free it.
1017   if (PImpl) {
1018     delete &getCache(PImpl);
1019     PImpl = 0;
1020   }
1021 }
1022
1023 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1024   LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1025   
1026   if (Result.isConstant())
1027     return Result.getConstant();
1028   if (Result.isConstantRange()) {
1029     ConstantRange CR = Result.getConstantRange();
1030     if (const APInt *SingleVal = CR.getSingleElement())
1031       return ConstantInt::get(V->getContext(), *SingleVal);
1032   }
1033   return 0;
1034 }
1035
1036 /// getConstantOnEdge - Determine whether the specified value is known to be a
1037 /// constant on the specified edge.  Return null if not.
1038 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1039                                            BasicBlock *ToBB) {
1040   LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1041   
1042   if (Result.isConstant())
1043     return Result.getConstant();
1044   if (Result.isConstantRange()) {
1045     ConstantRange CR = Result.getConstantRange();
1046     if (const APInt *SingleVal = CR.getSingleElement())
1047       return ConstantInt::get(V->getContext(), *SingleVal);
1048   }
1049   return 0;
1050 }
1051
1052 /// getPredicateOnEdge - Determine whether the specified value comparison
1053 /// with a constant is known to be true or false on the specified CFG edge.
1054 /// Pred is a CmpInst predicate.
1055 LazyValueInfo::Tristate
1056 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1057                                   BasicBlock *FromBB, BasicBlock *ToBB) {
1058   LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1059   
1060   // If we know the value is a constant, evaluate the conditional.
1061   Constant *Res = 0;
1062   if (Result.isConstant()) {
1063     Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
1064     if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1065       return ResCI->isZero() ? False : True;
1066     return Unknown;
1067   }
1068   
1069   if (Result.isConstantRange()) {
1070     ConstantInt *CI = dyn_cast<ConstantInt>(C);
1071     if (!CI) return Unknown;
1072     
1073     ConstantRange CR = Result.getConstantRange();
1074     if (Pred == ICmpInst::ICMP_EQ) {
1075       if (!CR.contains(CI->getValue()))
1076         return False;
1077       
1078       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1079         return True;
1080     } else if (Pred == ICmpInst::ICMP_NE) {
1081       if (!CR.contains(CI->getValue()))
1082         return True;
1083       
1084       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1085         return False;
1086     }
1087     
1088     // Handle more complex predicates.
1089     ConstantRange TrueValues =
1090         ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1091     if (TrueValues.contains(CR))
1092       return True;
1093     if (TrueValues.inverse().contains(CR))
1094       return False;
1095     return Unknown;
1096   }
1097   
1098   if (Result.isNotConstant()) {
1099     // If this is an equality comparison, we can try to fold it knowing that
1100     // "V != C1".
1101     if (Pred == ICmpInst::ICMP_EQ) {
1102       // !C1 == C -> false iff C1 == C.
1103       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1104                                             Result.getNotConstant(), C, TD);
1105       if (Res->isNullValue())
1106         return False;
1107     } else if (Pred == ICmpInst::ICMP_NE) {
1108       // !C1 != C -> true iff C1 == C.
1109       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1110                                             Result.getNotConstant(), C, TD);
1111       if (Res->isNullValue())
1112         return True;
1113     }
1114     return Unknown;
1115   }
1116   
1117   return Unknown;
1118 }
1119
1120 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1121                                BasicBlock *NewSucc) {
1122   if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1123 }
1124
1125 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1126   if (PImpl) getCache(PImpl).eraseBlock(BB);
1127 }