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