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