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