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