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