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