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