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