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