Fix another iterator invalidation that caused a *really* nasty miscompilation in...
[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       }
220       
221       assert(isUndefined() && "Unexpected lattice");
222       return markConstantRange(RHS.getConstantRange());
223     }
224     
225     // RHS must be a constant, we must be undef, constant, or notconstant.
226     assert(!isConstantRange() &&
227            "Constant and ConstantRange cannot be merged.");
228     
229     if (isUndefined())
230       return markConstant(RHS.getConstant());
231     
232     if (isConstant()) {
233       if (getConstant() != RHS.getConstant())
234         return markOverdefined();
235       return false;
236     }
237
238     // If we are known "!=4" and RHS is "==5", stay at "!=4".
239     if (getNotConstant() == RHS.getConstant() ||
240         isa<ConstantExpr>(getNotConstant()) ||
241         isa<ConstantExpr>(RHS.getConstant()))
242       return markOverdefined();
243     return false;
244   }
245   
246 };
247   
248 } // end anonymous namespace.
249
250 namespace llvm {
251 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
252   if (Val.isUndefined())
253     return OS << "undefined";
254   if (Val.isOverdefined())
255     return OS << "overdefined";
256
257   if (Val.isNotConstant())
258     return OS << "notconstant<" << *Val.getNotConstant() << '>';
259   else if (Val.isConstantRange())
260     return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
261               << Val.getConstantRange().getUpper() << '>';
262   return OS << "constant<" << *Val.getConstant() << '>';
263 }
264 }
265
266 //===----------------------------------------------------------------------===//
267 //                          LazyValueInfoCache Decl
268 //===----------------------------------------------------------------------===//
269
270 namespace {
271   /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
272   /// maintains information about queries across the clients' queries.
273   class LazyValueInfoCache {
274   public:
275     /// BlockCacheEntryTy - This is a computed lattice value at the end of the
276     /// specified basic block for a Value* that depends on context.
277     typedef std::pair<BasicBlock*, LVILatticeVal> BlockCacheEntryTy;
278     
279     /// ValueCacheEntryTy - This is all of the cached block information for
280     /// exactly one Value*.  The entries are sorted by the BasicBlock* of the
281     /// entries, allowing us to do a lookup with a binary search.
282     typedef std::map<BasicBlock*, LVILatticeVal> ValueCacheEntryTy;
283
284   private:
285      /// LVIValueHandle - A callback value handle update the cache when
286      /// values are erased.
287     struct LVIValueHandle : public CallbackVH {
288       LazyValueInfoCache *Parent;
289       
290       LVIValueHandle(Value *V, LazyValueInfoCache *P)
291         : CallbackVH(V), Parent(P) { }
292       
293       void deleted();
294       void allUsesReplacedWith(Value* V) {
295         deleted();
296       }
297
298       LVIValueHandle &operator=(Value *V) {
299         return *this = LVIValueHandle(V, Parent);
300       }
301     };
302
303     /// ValueCache - This is all of the cached information for all values,
304     /// mapped from Value* to key information.
305     std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
306     
307     /// OverDefinedCache - This tracks, on a per-block basis, the set of 
308     /// values that are over-defined at the end of that block.  This is required
309     /// for cache updating.
310     std::set<std::pair<BasicBlock*, Value*> > OverDefinedCache;
311
312   public:
313     
314     /// getValueInBlock - This is the query interface to determine the lattice
315     /// value for the specified Value* at the end of the specified block.
316     LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
317
318     /// getValueOnEdge - This is the query interface to determine the lattice
319     /// value for the specified Value* that is true on the specified edge.
320     LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
321     
322     /// threadEdge - This is the update interface to inform the cache that an
323     /// edge from PredBB to OldSucc has been threaded to be from PredBB to
324     /// NewSucc.
325     void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
326   };
327 } // end anonymous namespace
328
329 //===----------------------------------------------------------------------===//
330 //                              LVIQuery Impl
331 //===----------------------------------------------------------------------===//
332
333 namespace {
334   /// LVIQuery - This is a transient object that exists while a query is
335   /// being performed.
336   ///
337   /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
338   /// reallocation of the densemap on every query.
339   class LVIQuery {
340     typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
341     typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
342     
343     /// This is the current value being queried for.
344     Value *Val;
345     
346     /// This is a pointer to the owning cache, for recursive queries.
347     LazyValueInfoCache &Parent;
348
349     /// This is all of the cached information about this value.
350     ValueCacheEntryTy &Cache;
351     
352     /// This tracks, for each block, what values are overdefined.
353     std::set<std::pair<BasicBlock*, Value*> > &OverDefinedCache;
354     
355     ///  NewBlocks - This is a mapping of the new BasicBlocks which have been
356     /// added to cache but that are not in sorted order.
357     DenseSet<BasicBlock*> NewBlockInfo;
358   public:
359     
360     LVIQuery(Value *V, LazyValueInfoCache &P,
361              ValueCacheEntryTy &VC,
362              std::set<std::pair<BasicBlock*, Value*> > &ODC)
363       : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
364     }
365
366     ~LVIQuery() {
367       // When the query is done, insert the newly discovered facts into the
368       // cache in sorted order.
369       if (NewBlockInfo.empty()) return;
370       
371       for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
372            E = NewBlockInfo.end(); I != E; ++I) {
373         if (Cache[*I].isOverdefined())
374           OverDefinedCache.insert(std::make_pair(*I, Val));
375       }
376     }
377
378     LVILatticeVal getBlockValue(BasicBlock *BB);
379     LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
380
381   private:
382     LVILatticeVal getCachedEntryForBlock(BasicBlock *BB);
383   };
384 } // end anonymous namespace
385
386 void LazyValueInfoCache::LVIValueHandle::deleted() {
387   for (std::set<std::pair<BasicBlock*, Value*> >::iterator
388        I = Parent->OverDefinedCache.begin(),
389        E = Parent->OverDefinedCache.end();
390        I != E; ) {
391     std::set<std::pair<BasicBlock*, Value*> >::iterator tmp = I;
392     ++I;
393     if (tmp->second == getValPtr())
394       Parent->OverDefinedCache.erase(tmp);
395   }
396   
397   // This erasure deallocates *this, so it MUST happen after we're done
398   // using any and all members of *this.
399   Parent->ValueCache.erase(*this);
400 }
401
402
403 /// getCachedEntryForBlock - See if we already have a value for this block.  If
404 /// so, return it, otherwise create a new entry in the Cache map to use.
405 LVILatticeVal LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
406   NewBlockInfo.insert(BB);
407   return Cache[BB];
408 }
409
410 LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
411   // See if we already have a value for this block.
412   LVILatticeVal BBLV = getCachedEntryForBlock(BB);
413   
414   // If we've already computed this block's value, return it.
415   if (!BBLV.isUndefined()) {
416     DEBUG(dbgs() << "  reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
417     return BBLV;
418   }
419
420   // Otherwise, this is the first time we're seeing this block.  Reset the
421   // lattice value to overdefined, so that cycles will terminate and be
422   // conservatively correct.
423   BBLV.markOverdefined();
424   Cache[BB] = BBLV;
425   
426   // If V is live into BB, see if our predecessors know anything about it.
427   Instruction *BBI = dyn_cast<Instruction>(Val);
428   if (BBI == 0 || BBI->getParent() != BB) {
429     LVILatticeVal Result;  // Start Undefined.
430     unsigned NumPreds = 0;
431     
432     // Loop over all of our predecessors, merging what we know from them into
433     // result.
434     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
435       Result.mergeIn(getEdgeValue(*PI, BB));
436       
437       // If we hit overdefined, exit early.  The BlockVals entry is already set
438       // to overdefined.
439       if (Result.isOverdefined()) {
440         DEBUG(dbgs() << " compute BB '" << BB->getName()
441                      << "' - overdefined because of pred.\n");
442         return Result;
443       }
444       ++NumPreds;
445     }
446     
447     // If this is the entry block, we must be asking about an argument.  The
448     // value is overdefined.
449     if (NumPreds == 0 && BB == &BB->getParent()->front()) {
450       assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
451       Result.markOverdefined();
452       return Result;
453     }
454     
455     // Return the merged value, which is more precise than 'overdefined'.
456     assert(!Result.isOverdefined());
457     return Cache[BB] = Result;
458   }
459   
460   // If this value is defined by an instruction in this block, we have to
461   // process it here somehow or return overdefined.
462   if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
463     LVILatticeVal Result;  // Start Undefined.
464     
465     // Loop over all of our predecessors, merging what we know from them into
466     // result.
467     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
468       Value* PhiVal = PN->getIncomingValueForBlock(*PI);
469       Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
470       
471       // If we hit overdefined, exit early.  The BlockVals entry is already set
472       // to overdefined.
473       if (Result.isOverdefined()) {
474         DEBUG(dbgs() << " compute BB '" << BB->getName()
475                      << "' - overdefined because of pred.\n");
476         return Result;
477       }
478     }
479     
480     // Return the merged value, which is more precise than 'overdefined'.
481     assert(!Result.isOverdefined());
482     Cache[BB] = Result;
483
484   } else {
485     
486   }
487   
488   DEBUG(dbgs() << " compute BB '" << BB->getName()
489                << "' - overdefined because inst def found.\n");
490
491   LVILatticeVal Result;
492   Result.markOverdefined();
493   return Result;
494 }
495
496
497 /// getEdgeValue - This method attempts to infer more complex 
498 LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
499   // TODO: Handle more complex conditionals.  If (v == 0 || v2 < 1) is false, we
500   // know that v != 0.
501   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
502     // If this is a conditional branch and only one successor goes to BBTo, then
503     // we maybe able to infer something from the condition. 
504     if (BI->isConditional() &&
505         BI->getSuccessor(0) != BI->getSuccessor(1)) {
506       bool isTrueDest = BI->getSuccessor(0) == BBTo;
507       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
508              "BBTo isn't a successor of BBFrom");
509       
510       // If V is the condition of the branch itself, then we know exactly what
511       // it is.
512       if (BI->getCondition() == Val)
513         return LVILatticeVal::get(ConstantInt::get(
514                               Type::getInt1Ty(Val->getContext()), isTrueDest));
515       
516       // If the condition of the branch is an equality comparison, we may be
517       // able to infer the value.
518       ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
519       if (ICI && ICI->getOperand(0) == Val &&
520           isa<Constant>(ICI->getOperand(1))) {
521         if (ICI->isEquality()) {
522           // We know that V has the RHS constant if this is a true SETEQ or
523           // false SETNE. 
524           if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
525             return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
526           return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
527         }
528           
529         if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
530           // Calculate the range of values that would satisfy the comparison.
531           ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
532           ConstantRange TrueValues =
533             ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
534             
535           // If we're interested in the false dest, invert the condition.
536           if (!isTrueDest) TrueValues = TrueValues.inverse();
537           
538           // Figure out the possible values of the query BEFORE this branch.  
539           LVILatticeVal InBlock = getBlockValue(BBFrom);
540           if (!InBlock.isConstantRange()) return InBlock;
541             
542           // Find all potential values that satisfy both the input and output
543           // conditions.
544           ConstantRange PossibleValues =
545             TrueValues.intersectWith(InBlock.getConstantRange());
546             
547           return LVILatticeVal::getRange(PossibleValues);
548         }
549       }
550     }
551   }
552
553   // If the edge was formed by a switch on the value, then we may know exactly
554   // what it is.
555   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
556     // If BBTo is the default destination of the switch, we don't know anything.
557     // Given a more powerful range analysis we could know stuff.
558     if (SI->getCondition() == Val && SI->getDefaultDest() != BBTo) {
559       // We only know something if there is exactly one value that goes from
560       // BBFrom to BBTo.
561       unsigned NumEdges = 0;
562       ConstantInt *EdgeVal = 0;
563       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
564         if (SI->getSuccessor(i) != BBTo) continue;
565         if (NumEdges++) break;
566         EdgeVal = SI->getCaseValue(i);
567       }
568       assert(EdgeVal && "Missing successor?");
569       if (NumEdges == 1)
570         return LVILatticeVal::get(EdgeVal);
571     }
572   }
573   
574   // Otherwise see if the value is known in the block.
575   return getBlockValue(BBFrom);
576 }
577
578
579 //===----------------------------------------------------------------------===//
580 //                         LazyValueInfoCache Impl
581 //===----------------------------------------------------------------------===//
582
583 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
584   // If already a constant, there is nothing to compute.
585   if (Constant *VC = dyn_cast<Constant>(V))
586     return LVILatticeVal::get(VC);
587   
588   DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
589         << BB->getName() << "'\n");
590   
591   LVILatticeVal Result = LVIQuery(V, *this,
592                                   ValueCache[LVIValueHandle(V, this)], 
593                                   OverDefinedCache).getBlockValue(BB);
594   
595   DEBUG(dbgs() << "  Result = " << Result << "\n");
596   return Result;
597 }
598
599 LVILatticeVal LazyValueInfoCache::
600 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
601   // If already a constant, there is nothing to compute.
602   if (Constant *VC = dyn_cast<Constant>(V))
603     return LVILatticeVal::get(VC);
604   
605   DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
606         << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
607   
608   LVILatticeVal Result =
609     LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
610              OverDefinedCache).getEdgeValue(FromBB, ToBB);
611   
612   DEBUG(dbgs() << "  Result = " << Result << "\n");
613   
614   return Result;
615 }
616
617 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
618                                     BasicBlock *NewSucc) {
619   // When an edge in the graph has been threaded, values that we could not 
620   // determine a value for before (i.e. were marked overdefined) may be possible
621   // to solve now.  We do NOT try to proactively update these values.  Instead,
622   // we clear their entries from the cache, and allow lazy updating to recompute
623   // them when needed.
624   
625   // The updating process is fairly simple: we need to dropped cached info
626   // for all values that were marked overdefined in OldSucc, and for those same
627   // values in any successor of OldSucc (except NewSucc) in which they were
628   // also marked overdefined.
629   std::vector<BasicBlock*> worklist;
630   worklist.push_back(OldSucc);
631   
632   DenseSet<Value*> ClearSet;
633   for (std::set<std::pair<BasicBlock*, Value*> >::iterator
634        I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
635     if (I->first == OldSucc)
636       ClearSet.insert(I->second);
637   }
638   
639   // Use a worklist to perform a depth-first search of OldSucc's successors.
640   // NOTE: We do not need a visited list since any blocks we have already
641   // visited will have had their overdefined markers cleared already, and we
642   // thus won't loop to their successors.
643   while (!worklist.empty()) {
644     BasicBlock *ToUpdate = worklist.back();
645     worklist.pop_back();
646     
647     // Skip blocks only accessible through NewSucc.
648     if (ToUpdate == NewSucc) continue;
649     
650     bool changed = false;
651     for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
652          I != E; ++I) {
653       // If a value was marked overdefined in OldSucc, and is here too...
654       std::set<std::pair<BasicBlock*, Value*> >::iterator OI =
655         OverDefinedCache.find(std::make_pair(ToUpdate, *I));
656       if (OI == OverDefinedCache.end()) continue;
657
658       // Remove it from the caches.
659       ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
660       ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
661         
662       assert(CI != Entry.end() && "Couldn't find entry to update?");
663       Entry.erase(CI);
664       OverDefinedCache.erase(OI);
665
666       // If we removed anything, then we potentially need to update 
667       // blocks successors too.
668       changed = true;
669     }
670         
671     if (!changed) continue;
672     
673     worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
674   }
675 }
676
677 //===----------------------------------------------------------------------===//
678 //                            LazyValueInfo Impl
679 //===----------------------------------------------------------------------===//
680
681 bool LazyValueInfo::runOnFunction(Function &F) {
682   TD = getAnalysisIfAvailable<TargetData>();
683   // Fully lazy.
684   return false;
685 }
686
687 /// getCache - This lazily constructs the LazyValueInfoCache.
688 static LazyValueInfoCache &getCache(void *&PImpl) {
689   if (!PImpl)
690     PImpl = new LazyValueInfoCache();
691   return *static_cast<LazyValueInfoCache*>(PImpl);
692 }
693
694 void LazyValueInfo::releaseMemory() {
695   // If the cache was allocated, free it.
696   if (PImpl) {
697     delete &getCache(PImpl);
698     PImpl = 0;
699   }
700 }
701
702 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
703   LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
704   
705   if (Result.isConstant())
706     return Result.getConstant();
707   return 0;
708 }
709
710 /// getConstantOnEdge - Determine whether the specified value is known to be a
711 /// constant on the specified edge.  Return null if not.
712 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
713                                            BasicBlock *ToBB) {
714   LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
715   
716   if (Result.isConstant())
717     return Result.getConstant();
718   else if (Result.isConstantRange()) {
719     ConstantRange CR = Result.getConstantRange();
720     if (const APInt *SingleVal = CR.getSingleElement())
721       return ConstantInt::get(V->getContext(), *SingleVal);
722   }
723   return 0;
724 }
725
726 /// getPredicateOnEdge - Determine whether the specified value comparison
727 /// with a constant is known to be true or false on the specified CFG edge.
728 /// Pred is a CmpInst predicate.
729 LazyValueInfo::Tristate
730 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
731                                   BasicBlock *FromBB, BasicBlock *ToBB) {
732   LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
733   
734   // If we know the value is a constant, evaluate the conditional.
735   Constant *Res = 0;
736   if (Result.isConstant()) {
737     Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
738     if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
739       return ResCI->isZero() ? False : True;
740     return Unknown;
741   }
742   
743   if (Result.isConstantRange()) {
744     ConstantInt *CI = cast<ConstantInt>(C);
745     ConstantRange CR = Result.getConstantRange();
746     if (Pred == ICmpInst::ICMP_EQ) {
747       if (!CR.contains(CI->getValue()))
748         return False;
749       
750       if (CR.isSingleElement() && CR.contains(CI->getValue()))
751         return True;
752     } else if (Pred == ICmpInst::ICMP_NE) {
753       if (!CR.contains(CI->getValue()))
754         return True;
755       
756       if (CR.isSingleElement() && CR.contains(CI->getValue()))
757         return False;
758     }
759     
760     // Handle more complex predicates.
761     ConstantRange RHS(CI->getValue(), CI->getValue()+1);
762     ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
763     if (CR.intersectWith(TrueValues).isEmptySet())
764       return False;
765     else if (TrueValues.contains(CR))
766       return True;
767     
768     return Unknown;
769   }
770   
771   if (Result.isNotConstant()) {
772     // If this is an equality comparison, we can try to fold it knowing that
773     // "V != C1".
774     if (Pred == ICmpInst::ICMP_EQ) {
775       // !C1 == C -> false iff C1 == C.
776       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
777                                             Result.getNotConstant(), C, TD);
778       if (Res->isNullValue())
779         return False;
780     } else if (Pred == ICmpInst::ICMP_NE) {
781       // !C1 != C -> true iff C1 == C.
782       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
783                                             Result.getNotConstant(), C, TD);
784       if (Res->isNullValue())
785         return True;
786     }
787     return Unknown;
788   }
789   
790   return Unknown;
791 }
792
793 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
794                                BasicBlock* NewSucc) {
795   getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
796 }