LazyValueInfo: fix some typos and indentation, etc. NFC.
[oota-llvm.git] / lib / Analysis / LazyValueInfo.cpp
1 //===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
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 #include "llvm/Analysis/LazyValueInfo.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Analysis/AssumptionTracker.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/CFG.h"
22 #include "llvm/IR/ConstantRange.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetLibraryInfo.h"
33 #include <map>
34 #include <stack>
35 using namespace llvm;
36 using namespace PatternMatch;
37
38 #define DEBUG_TYPE "lazy-value-info"
39
40 char LazyValueInfo::ID = 0;
41 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
42                 "Lazy Value Information Analysis", false, true)
43 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
44 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
45 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
46                 "Lazy Value Information Analysis", false, true)
47
48 namespace llvm {
49   FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
50 }
51
52
53 //===----------------------------------------------------------------------===//
54 //                               LVILatticeVal
55 //===----------------------------------------------------------------------===//
56
57 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
58 /// value.
59 ///
60 /// FIXME: This is basically just for bringup, this can be made a lot more rich
61 /// in the future.
62 ///
63 namespace {
64 class LVILatticeVal {
65   enum LatticeValueTy {
66     /// undefined - This Value has no known value yet.
67     undefined,
68     
69     /// constant - This Value has a specific constant value.
70     constant,
71     /// notconstant - This Value is known to not have the specified value.
72     notconstant,
73
74     /// constantrange - The Value falls within this range.
75     constantrange,
76
77     /// overdefined - This value is not known to be constant, and we know that
78     /// it has a value.
79     overdefined
80   };
81   
82   /// Val: This stores the current lattice value along with the Constant* for
83   /// the constant if this is a 'constant' or 'notconstant' value.
84   LatticeValueTy Tag;
85   Constant *Val;
86   ConstantRange Range;
87   
88 public:
89   LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
90
91   static LVILatticeVal get(Constant *C) {
92     LVILatticeVal Res;
93     if (!isa<UndefValue>(C))
94       Res.markConstant(C);
95     return Res;
96   }
97   static LVILatticeVal getNot(Constant *C) {
98     LVILatticeVal Res;
99     if (!isa<UndefValue>(C))
100       Res.markNotConstant(C);
101     return Res;
102   }
103   static LVILatticeVal getRange(ConstantRange CR) {
104     LVILatticeVal Res;
105     Res.markConstantRange(CR);
106     return Res;
107   }
108   
109   bool isUndefined() const     { return Tag == undefined; }
110   bool isConstant() const      { return Tag == constant; }
111   bool isNotConstant() const   { return Tag == notconstant; }
112   bool isConstantRange() const { return Tag == constantrange; }
113   bool isOverdefined() const   { return Tag == overdefined; }
114   
115   Constant *getConstant() const {
116     assert(isConstant() && "Cannot get the constant of a non-constant!");
117     return Val;
118   }
119   
120   Constant *getNotConstant() const {
121     assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
122     return Val;
123   }
124   
125   ConstantRange getConstantRange() const {
126     assert(isConstantRange() &&
127            "Cannot get the constant-range of a non-constant-range!");
128     return Range;
129   }
130   
131   /// markOverdefined - Return true if this is a change in status.
132   bool markOverdefined() {
133     if (isOverdefined())
134       return false;
135     Tag = overdefined;
136     return true;
137   }
138
139   /// markConstant - Return true if this is a change in status.
140   bool markConstant(Constant *V) {
141     assert(V && "Marking constant with NULL");
142     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
143       return markConstantRange(ConstantRange(CI->getValue()));
144     if (isa<UndefValue>(V))
145       return false;
146
147     assert((!isConstant() || getConstant() == V) &&
148            "Marking constant with different value");
149     assert(isUndefined());
150     Tag = constant;
151     Val = V;
152     return true;
153   }
154   
155   /// markNotConstant - Return true if this is a change in status.
156   bool markNotConstant(Constant *V) {
157     assert(V && "Marking constant with NULL");
158     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
159       return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
160     if (isa<UndefValue>(V))
161       return false;
162
163     assert((!isConstant() || getConstant() != V) &&
164            "Marking constant !constant with same value");
165     assert((!isNotConstant() || getNotConstant() == V) &&
166            "Marking !constant with different value");
167     assert(isUndefined() || isConstant());
168     Tag = notconstant;
169     Val = V;
170     return true;
171   }
172   
173   /// markConstantRange - Return true if this is a change in status.
174   bool markConstantRange(const ConstantRange NewR) {
175     if (isConstantRange()) {
176       if (NewR.isEmptySet())
177         return markOverdefined();
178       
179       bool changed = Range != NewR;
180       Range = NewR;
181       return changed;
182     }
183     
184     assert(isUndefined());
185     if (NewR.isEmptySet())
186       return markOverdefined();
187     
188     Tag = constantrange;
189     Range = NewR;
190     return true;
191   }
192   
193   /// mergeIn - Merge the specified lattice value into this one, updating this
194   /// one and returning true if anything changed.
195   bool mergeIn(const LVILatticeVal &RHS) {
196     if (RHS.isUndefined() || isOverdefined()) return false;
197     if (RHS.isOverdefined()) return markOverdefined();
198
199     if (isUndefined()) {
200       Tag = RHS.Tag;
201       Val = RHS.Val;
202       Range = RHS.Range;
203       return true;
204     }
205
206     if (isConstant()) {
207       if (RHS.isConstant()) {
208         if (Val == RHS.Val)
209           return false;
210         return markOverdefined();
211       }
212
213       if (RHS.isNotConstant()) {
214         if (Val == RHS.Val)
215           return markOverdefined();
216
217         // Unless we can prove that the two Constants are different, we must
218         // move to overdefined.
219         // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
220         if (ConstantInt *Res = dyn_cast<ConstantInt>(
221                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
222                                                 getConstant(),
223                                                 RHS.getNotConstant())))
224           if (Res->isOne())
225             return markNotConstant(RHS.getNotConstant());
226
227         return markOverdefined();
228       }
229
230       // RHS is a ConstantRange, LHS is a non-integer Constant.
231
232       // FIXME: consider the case where RHS is a range [1, 0) and LHS is
233       // a function. The correct result is to pick up RHS.
234
235       return markOverdefined();
236     }
237
238     if (isNotConstant()) {
239       if (RHS.isConstant()) {
240         if (Val == RHS.Val)
241           return markOverdefined();
242
243         // Unless we can prove that the two Constants are different, we must
244         // move to overdefined.
245         // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
246         if (ConstantInt *Res = dyn_cast<ConstantInt>(
247                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
248                                                 getNotConstant(),
249                                                 RHS.getConstant())))
250           if (Res->isOne())
251             return false;
252
253         return markOverdefined();
254       }
255
256       if (RHS.isNotConstant()) {
257         if (Val == RHS.Val)
258           return false;
259         return markOverdefined();
260       }
261
262       return markOverdefined();
263     }
264
265     assert(isConstantRange() && "New LVILattice type?");
266     if (!RHS.isConstantRange())
267       return markOverdefined();
268
269     ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
270     if (NewR.isFullSet())
271       return markOverdefined();
272     return markConstantRange(NewR);
273   }
274 };
275   
276 } // end anonymous namespace.
277
278 namespace llvm {
279 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
280     LLVM_ATTRIBUTE_USED;
281 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
282   if (Val.isUndefined())
283     return OS << "undefined";
284   if (Val.isOverdefined())
285     return OS << "overdefined";
286
287   if (Val.isNotConstant())
288     return OS << "notconstant<" << *Val.getNotConstant() << '>';
289   else if (Val.isConstantRange())
290     return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
291               << Val.getConstantRange().getUpper() << '>';
292   return OS << "constant<" << *Val.getConstant() << '>';
293 }
294 }
295
296 //===----------------------------------------------------------------------===//
297 //                          LazyValueInfoCache Decl
298 //===----------------------------------------------------------------------===//
299
300 namespace {
301   /// LVIValueHandle - A callback value handle updates the cache when
302   /// values are erased.
303   class LazyValueInfoCache;
304   struct LVIValueHandle : public CallbackVH {
305     LazyValueInfoCache *Parent;
306       
307     LVIValueHandle(Value *V, LazyValueInfoCache *P)
308       : CallbackVH(V), Parent(P) { }
309
310     void deleted() override;
311     void allUsesReplacedWith(Value *V) override {
312       deleted();
313     }
314   };
315 }
316
317 namespace { 
318   /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
319   /// maintains information about queries across the clients' queries.
320   class LazyValueInfoCache {
321     /// ValueCacheEntryTy - This is all of the cached block information for
322     /// exactly one Value*.  The entries are sorted by the BasicBlock* of the
323     /// entries, allowing us to do a lookup with a binary search.
324     typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
325
326     /// ValueCache - This is all of the cached information for all values,
327     /// mapped from Value* to key information.
328     std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
329     
330     /// OverDefinedCache - This tracks, on a per-block basis, the set of 
331     /// values that are over-defined at the end of that block.  This is required
332     /// for cache updating.
333     typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
334     DenseSet<OverDefinedPairTy> OverDefinedCache;
335
336     /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
337     /// don't spend time removing unused blocks from our caches.
338     DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
339
340     /// BlockValueStack - This stack holds the state of the value solver
341     /// during a query.  It basically emulates the callstack of the naive
342     /// recursive value lookup process.
343     std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
344
345     /// A pointer to the cache of @llvm.assume calls.
346     AssumptionTracker *AT;
347     /// An optional DL pointer.
348     const DataLayout *DL;
349     /// An optional DT pointer.
350     DominatorTree *DT;
351     
352     friend struct LVIValueHandle;
353     
354     /// OverDefinedCacheUpdater - A helper object that ensures that the
355     /// OverDefinedCache is updated whenever solveBlockValue returns.
356     struct OverDefinedCacheUpdater {
357       LazyValueInfoCache *Parent;
358       Value *Val;
359       BasicBlock *BB;
360       LVILatticeVal &BBLV;
361       
362       OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
363                        LazyValueInfoCache *P)
364         : Parent(P), Val(V), BB(B), BBLV(LV) { }
365       
366       bool markResult(bool changed) { 
367         if (changed && BBLV.isOverdefined())
368           Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
369         return changed;
370       }
371     };
372     
373
374
375     LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
376     bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
377                       LVILatticeVal &Result,
378                       Instruction *CxtI = nullptr);
379     bool hasBlockValue(Value *Val, BasicBlock *BB);
380
381     // These methods process one work item and may add more. A false value
382     // returned means that the work item was not completely processed and must
383     // be revisited after going through the new items.
384     bool solveBlockValue(Value *Val, BasicBlock *BB);
385     bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
386                                  Value *Val, BasicBlock *BB);
387     bool solveBlockValuePHINode(LVILatticeVal &BBLV,
388                                 PHINode *PN, BasicBlock *BB);
389     bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
390                                       Instruction *BBI, BasicBlock *BB);
391     void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
392                                             Instruction *BBI);
393
394     void solve();
395     
396     ValueCacheEntryTy &lookup(Value *V) {
397       return ValueCache[LVIValueHandle(V, this)];
398     }
399
400   public:
401     /// getValueInBlock - This is the query interface to determine the lattice
402     /// value for the specified Value* at the end of the specified block.
403     LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
404                                   Instruction *CxtI = nullptr);
405
406     /// getValueAt - This is the query interface to determine the lattice
407     /// value for the specified Value* at the specified instruction (generally
408     /// from an assume intrinsic).
409     LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
410
411     /// getValueOnEdge - This is the query interface to determine the lattice
412     /// value for the specified Value* that is true on the specified edge.
413     LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
414                                  Instruction *CxtI = nullptr);
415     
416     /// threadEdge - This is the update interface to inform the cache that an
417     /// edge from PredBB to OldSucc has been threaded to be from PredBB to
418     /// NewSucc.
419     void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
420     
421     /// eraseBlock - This is part of the update interface to inform the cache
422     /// that a block has been deleted.
423     void eraseBlock(BasicBlock *BB);
424     
425     /// clear - Empty the cache.
426     void clear() {
427       SeenBlocks.clear();
428       ValueCache.clear();
429       OverDefinedCache.clear();
430     }
431
432     LazyValueInfoCache(AssumptionTracker *AT,
433                        const DataLayout *DL = nullptr,
434                        DominatorTree *DT = nullptr) : AT(AT), DL(DL), DT(DT) {}
435   };
436 } // end anonymous namespace
437
438 void LVIValueHandle::deleted() {
439   typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
440   
441   SmallVector<OverDefinedPairTy, 4> ToErase;
442   for (DenseSet<OverDefinedPairTy>::iterator 
443        I = Parent->OverDefinedCache.begin(),
444        E = Parent->OverDefinedCache.end();
445        I != E; ++I) {
446     if (I->second == getValPtr())
447       ToErase.push_back(*I);
448   }
449
450   for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(),
451        E = ToErase.end(); I != E; ++I)
452     Parent->OverDefinedCache.erase(*I);
453   
454   // This erasure deallocates *this, so it MUST happen after we're done
455   // using any and all members of *this.
456   Parent->ValueCache.erase(*this);
457 }
458
459 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
460   // Shortcut if we have never seen this block.
461   DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
462   if (I == SeenBlocks.end())
463     return;
464   SeenBlocks.erase(I);
465
466   SmallVector<OverDefinedPairTy, 4> ToErase;
467   for (DenseSet<OverDefinedPairTy>::iterator  I = OverDefinedCache.begin(),
468        E = OverDefinedCache.end(); I != E; ++I) {
469     if (I->first == BB)
470       ToErase.push_back(*I);
471   }
472
473   for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(),
474        E = ToErase.end(); I != E; ++I)
475     OverDefinedCache.erase(*I);
476
477   for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
478        I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
479     I->second.erase(BB);
480 }
481
482 void LazyValueInfoCache::solve() {
483   while (!BlockValueStack.empty()) {
484     std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
485     if (solveBlockValue(e.second, e.first)) {
486       assert(BlockValueStack.top() == e);
487       BlockValueStack.pop();
488     }
489   }
490 }
491
492 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
493   // If already a constant, there is nothing to compute.
494   if (isa<Constant>(Val))
495     return true;
496
497   LVIValueHandle ValHandle(Val, this);
498   std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
499     ValueCache.find(ValHandle);
500   if (I == ValueCache.end()) return false;
501   return I->second.count(BB);
502 }
503
504 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
505   // If already a constant, there is nothing to compute.
506   if (Constant *VC = dyn_cast<Constant>(Val))
507     return LVILatticeVal::get(VC);
508
509   SeenBlocks.insert(BB);
510   return lookup(Val)[BB];
511 }
512
513 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
514   if (isa<Constant>(Val))
515     return true;
516
517   ValueCacheEntryTy &Cache = lookup(Val);
518   SeenBlocks.insert(BB);
519   LVILatticeVal &BBLV = Cache[BB];
520   
521   // OverDefinedCacheUpdater is a helper object that will update
522   // the OverDefinedCache for us when this method exits.  Make sure to
523   // call markResult on it as we exit, passing a bool to indicate if the
524   // cache needs updating, i.e. if we have solved a new value or not.
525   OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
526
527   if (!BBLV.isUndefined()) {
528     DEBUG(dbgs() << "  reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
529     
530     // Since we're reusing a cached value here, we don't need to update the 
531     // OverDefinedCache.  The cache will have been properly updated
532     // whenever the cached value was inserted.
533     ODCacheUpdater.markResult(false);
534     return true;
535   }
536
537   // Otherwise, this is the first time we're seeing this block.  Reset the
538   // lattice value to overdefined, so that cycles will terminate and be
539   // conservatively correct.
540   BBLV.markOverdefined();
541   
542   Instruction *BBI = dyn_cast<Instruction>(Val);
543   if (!BBI || BBI->getParent() != BB) {
544     return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
545   }
546
547   if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
548     return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
549   }
550
551   if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
552     BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
553     return ODCacheUpdater.markResult(true);
554   }
555
556   // We can only analyze the definitions of certain classes of instructions
557   // (integral binops and casts at the moment), so bail if this isn't one.
558   LVILatticeVal Result;
559   if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
560      !BBI->getType()->isIntegerTy()) {
561     DEBUG(dbgs() << " compute BB '" << BB->getName()
562                  << "' - overdefined because inst def found.\n");
563     BBLV.markOverdefined();
564     return ODCacheUpdater.markResult(true);
565   }
566
567   // FIXME: We're currently limited to binops with a constant RHS.  This should
568   // be improved.
569   BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
570   if (BO && !isa<ConstantInt>(BO->getOperand(1))) { 
571     DEBUG(dbgs() << " compute BB '" << BB->getName()
572                  << "' - overdefined because inst def found.\n");
573
574     BBLV.markOverdefined();
575     return ODCacheUpdater.markResult(true);
576   }
577
578   return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
579 }
580
581 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
582   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
583     return L->getPointerAddressSpace() == 0 &&
584         GetUnderlyingObject(L->getPointerOperand()) == Ptr;
585   }
586   if (StoreInst *S = dyn_cast<StoreInst>(I)) {
587     return S->getPointerAddressSpace() == 0 &&
588         GetUnderlyingObject(S->getPointerOperand()) == Ptr;
589   }
590   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
591     if (MI->isVolatile()) return false;
592
593     // FIXME: check whether it has a valuerange that excludes zero?
594     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
595     if (!Len || Len->isZero()) return false;
596
597     if (MI->getDestAddressSpace() == 0)
598       if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
599         return true;
600     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
601       if (MTI->getSourceAddressSpace() == 0)
602         if (GetUnderlyingObject(MTI->getRawSource()) == Ptr)
603           return true;
604   }
605   return false;
606 }
607
608 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
609                                                  Value *Val, BasicBlock *BB) {
610   LVILatticeVal Result;  // Start Undefined.
611
612   // If this is a pointer, and there's a load from that pointer in this BB,
613   // then we know that the pointer can't be NULL.
614   bool NotNull = false;
615   if (Val->getType()->isPointerTy()) {
616     if (isKnownNonNull(Val)) {
617       NotNull = true;
618     } else {
619       Value *UnderlyingVal = GetUnderlyingObject(Val);
620       // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
621       // inside InstructionDereferencesPointer either.
622       if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
623         for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
624              BI != BE; ++BI) {
625           if (InstructionDereferencesPointer(BI, UnderlyingVal)) {
626             NotNull = true;
627             break;
628           }
629         }
630       }
631     }
632   }
633
634   // If this is the entry block, we must be asking about an argument.  The
635   // value is overdefined.
636   if (BB == &BB->getParent()->getEntryBlock()) {
637     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
638     if (NotNull) {
639       PointerType *PTy = cast<PointerType>(Val->getType());
640       Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
641     } else {
642       Result.markOverdefined();
643     }
644     BBLV = Result;
645     return true;
646   }
647
648   // Loop over all of our predecessors, merging what we know from them into
649   // result.
650   bool EdgesMissing = false;
651   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
652     LVILatticeVal EdgeResult;
653     EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
654     if (EdgesMissing)
655       continue;
656
657     Result.mergeIn(EdgeResult);
658
659     // If we hit overdefined, exit early.  The BlockVals entry is already set
660     // to overdefined.
661     if (Result.isOverdefined()) {
662       DEBUG(dbgs() << " compute BB '" << BB->getName()
663             << "' - overdefined because of pred.\n");
664       // If we previously determined that this is a pointer that can't be null
665       // then return that rather than giving up entirely.
666       if (NotNull) {
667         PointerType *PTy = cast<PointerType>(Val->getType());
668         Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
669       }
670       
671       BBLV = Result;
672       return true;
673     }
674   }
675   if (EdgesMissing)
676     return false;
677
678   // Return the merged value, which is more precise than 'overdefined'.
679   assert(!Result.isOverdefined());
680   BBLV = Result;
681   return true;
682 }
683   
684 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
685                                                 PHINode *PN, BasicBlock *BB) {
686   LVILatticeVal Result;  // Start Undefined.
687
688   // Loop over all of our predecessors, merging what we know from them into
689   // result.
690   bool EdgesMissing = false;
691   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
692     BasicBlock *PhiBB = PN->getIncomingBlock(i);
693     Value *PhiVal = PN->getIncomingValue(i);
694     LVILatticeVal EdgeResult;
695     // Note that we can provide PN as the context value to getEdgeValue, even
696     // though the results will be cached, because PN is the value being used as
697     // the cache key in the caller.
698     EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
699     if (EdgesMissing)
700       continue;
701
702     Result.mergeIn(EdgeResult);
703
704     // If we hit overdefined, exit early.  The BlockVals entry is already set
705     // to overdefined.
706     if (Result.isOverdefined()) {
707       DEBUG(dbgs() << " compute BB '" << BB->getName()
708             << "' - overdefined because of pred.\n");
709       
710       BBLV = Result;
711       return true;
712     }
713   }
714   if (EdgesMissing)
715     return false;
716
717   // Return the merged value, which is more precise than 'overdefined'.
718   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
719   BBLV = Result;
720   return true;
721 }
722
723 static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
724                                       LVILatticeVal &Result,
725                                       bool isTrueDest = true);
726
727 // If we can determine a constant range for the value Val in the context
728 // provided by the instruction BBI, then merge it into BBLV. If we did find a
729 // constant range, return true.
730 void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
731                                                             LVILatticeVal &BBLV,
732                                                             Instruction *BBI) {
733   BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
734   if (!BBI)
735     return;
736
737   for (auto &I : AT->assumptions(BBI->getParent()->getParent())) {
738     if (!isValidAssumeForContext(I, BBI, DL, DT))
739       continue;
740
741     Value *C = I->getArgOperand(0);
742     if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
743       LVILatticeVal Result;
744       if (getValueFromFromCondition(Val, ICI, Result)) {
745         if (BBLV.isOverdefined())
746           BBLV = Result;
747         else
748           BBLV.mergeIn(Result);
749       }
750     }
751   }
752 }
753
754 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
755                                                       Instruction *BBI,
756                                                       BasicBlock *BB) {
757   // Figure out the range of the LHS.  If that fails, bail.
758   if (!hasBlockValue(BBI->getOperand(0), BB)) {
759     BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
760     return false;
761   }
762
763   LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
764   mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
765   if (!LHSVal.isConstantRange()) {
766     BBLV.markOverdefined();
767     return true;
768   }
769   
770   ConstantRange LHSRange = LHSVal.getConstantRange();
771   ConstantRange RHSRange(1);
772   IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
773   if (isa<BinaryOperator>(BBI)) {
774     if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
775       RHSRange = ConstantRange(RHS->getValue());
776     } else {
777       BBLV.markOverdefined();
778       return true;
779     }
780   }
781
782   // NOTE: We're currently limited by the set of operations that ConstantRange
783   // can evaluate symbolically.  Enhancing that set will allows us to analyze
784   // more definitions.
785   LVILatticeVal Result;
786   switch (BBI->getOpcode()) {
787   case Instruction::Add:
788     Result.markConstantRange(LHSRange.add(RHSRange));
789     break;
790   case Instruction::Sub:
791     Result.markConstantRange(LHSRange.sub(RHSRange));
792     break;
793   case Instruction::Mul:
794     Result.markConstantRange(LHSRange.multiply(RHSRange));
795     break;
796   case Instruction::UDiv:
797     Result.markConstantRange(LHSRange.udiv(RHSRange));
798     break;
799   case Instruction::Shl:
800     Result.markConstantRange(LHSRange.shl(RHSRange));
801     break;
802   case Instruction::LShr:
803     Result.markConstantRange(LHSRange.lshr(RHSRange));
804     break;
805   case Instruction::Trunc:
806     Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
807     break;
808   case Instruction::SExt:
809     Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
810     break;
811   case Instruction::ZExt:
812     Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
813     break;
814   case Instruction::BitCast:
815     Result.markConstantRange(LHSRange);
816     break;
817   case Instruction::And:
818     Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
819     break;
820   case Instruction::Or:
821     Result.markConstantRange(LHSRange.binaryOr(RHSRange));
822     break;
823   
824   // Unhandled instructions are overdefined.
825   default:
826     DEBUG(dbgs() << " compute BB '" << BB->getName()
827                  << "' - overdefined because inst def found.\n");
828     Result.markOverdefined();
829     break;
830   }
831   
832   BBLV = Result;
833   return true;
834 }
835
836 bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
837                                LVILatticeVal &Result, bool isTrueDest) {
838   if (ICI && isa<Constant>(ICI->getOperand(1))) {
839     if (ICI->isEquality() && ICI->getOperand(0) == Val) {
840       // We know that V has the RHS constant if this is a true SETEQ or
841       // false SETNE. 
842       if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
843         Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
844       else
845         Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
846       return true;
847     }
848
849     // Recognize the range checking idiom that InstCombine produces.
850     // (X-C1) u< C2 --> [C1, C1+C2)
851     ConstantInt *NegOffset = nullptr;
852     if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
853       match(ICI->getOperand(0), m_Add(m_Specific(Val),
854                                       m_ConstantInt(NegOffset)));
855
856     ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
857     if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
858       // Calculate the range of values that would satisfy the comparison.
859       ConstantRange CmpRange(CI->getValue());
860       ConstantRange TrueValues =
861         ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
862
863       if (NegOffset) // Apply the offset from above.
864         TrueValues = TrueValues.subtract(NegOffset->getValue());
865
866       // If we're interested in the false dest, invert the condition.
867       if (!isTrueDest) TrueValues = TrueValues.inverse();
868
869       Result = LVILatticeVal::getRange(TrueValues);
870       return true;
871     }
872   }
873
874   return false;
875 }
876
877 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
878 /// Val is not constrained on the edge.
879 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
880                               BasicBlock *BBTo, LVILatticeVal &Result) {
881   // TODO: Handle more complex conditionals.  If (v == 0 || v2 < 1) is false, we
882   // know that v != 0.
883   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
884     // If this is a conditional branch and only one successor goes to BBTo, then
885     // we maybe able to infer something from the condition. 
886     if (BI->isConditional() &&
887         BI->getSuccessor(0) != BI->getSuccessor(1)) {
888       bool isTrueDest = BI->getSuccessor(0) == BBTo;
889       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
890              "BBTo isn't a successor of BBFrom");
891       
892       // If V is the condition of the branch itself, then we know exactly what
893       // it is.
894       if (BI->getCondition() == Val) {
895         Result = LVILatticeVal::get(ConstantInt::get(
896                               Type::getInt1Ty(Val->getContext()), isTrueDest));
897         return true;
898       }
899       
900       // If the condition of the branch is an equality comparison, we may be
901       // able to infer the value.
902       ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
903       if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
904         return true;
905     }
906   }
907
908   // If the edge was formed by a switch on the value, then we may know exactly
909   // what it is.
910   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
911     if (SI->getCondition() != Val)
912       return false;
913
914     bool DefaultCase = SI->getDefaultDest() == BBTo;
915     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
916     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
917
918     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
919          i != e; ++i) {
920       ConstantRange EdgeVal(i.getCaseValue()->getValue());
921       if (DefaultCase) {
922         // It is possible that the default destination is the destination of
923         // some cases. There is no need to perform difference for those cases.
924         if (i.getCaseSuccessor() != BBTo)
925           EdgesVals = EdgesVals.difference(EdgeVal);
926       } else if (i.getCaseSuccessor() == BBTo)
927         EdgesVals = EdgesVals.unionWith(EdgeVal);
928     }
929     Result = LVILatticeVal::getRange(EdgesVals);
930     return true;
931   }
932   return false;
933 }
934
935 /// \brief Compute the value of Val on the edge BBFrom -> BBTo, or the value at
936 /// the basic block if the edge does not constraint Val.
937 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
938                                       BasicBlock *BBTo, LVILatticeVal &Result,
939                                       Instruction *CxtI) {
940   // If already a constant, there is nothing to compute.
941   if (Constant *VC = dyn_cast<Constant>(Val)) {
942     Result = LVILatticeVal::get(VC);
943     return true;
944   }
945
946   if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
947     if (!Result.isConstantRange() ||
948         Result.getConstantRange().getSingleElement())
949       return true;
950
951     // FIXME: this check should be moved to the beginning of the function when
952     // LVI better supports recursive values. Even for the single value case, we
953     // can intersect to detect dead code (an empty range).
954     if (!hasBlockValue(Val, BBFrom)) {
955       BlockValueStack.push(std::make_pair(BBFrom, Val));
956       return false;
957     }
958
959     // Try to intersect ranges of the BB and the constraint on the edge.
960     LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
961     mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
962     // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
963     // and caching, below.
964     mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
965     if (!InBlock.isConstantRange())
966       return true;
967
968     ConstantRange Range =
969       Result.getConstantRange().intersectWith(InBlock.getConstantRange());
970     Result = LVILatticeVal::getRange(Range);
971     return true;
972   }
973
974   if (!hasBlockValue(Val, BBFrom)) {
975     BlockValueStack.push(std::make_pair(BBFrom, Val));
976     return false;
977   }
978
979   // If we couldn't compute the value on the edge, use the value from the BB.
980   Result = getBlockValue(Val, BBFrom);
981   mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
982   // We can use the context instruction (generically the ultimate instruction
983   // the calling pass is trying to simplify) here, even though the result of
984   // this function is generally cached when called from the solve* functions
985   // (and that cached result might be used with queries using a different
986   // context instruction), because when this function is called from the solve*
987   // functions, the context instruction is not provided. When called from
988   // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
989   // but then the result is not cached.
990   mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
991   return true;
992 }
993
994 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
995                                                   Instruction *CxtI) {
996   DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
997         << BB->getName() << "'\n");
998   
999   BlockValueStack.push(std::make_pair(BB, V));
1000   solve();
1001   LVILatticeVal Result = getBlockValue(V, BB);
1002   mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1003
1004   DEBUG(dbgs() << "  Result = " << Result << "\n");
1005   return Result;
1006 }
1007
1008 LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1009   DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1010         << CxtI->getName() << "'\n");
1011
1012   LVILatticeVal Result;
1013   mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1014
1015   DEBUG(dbgs() << "  Result = " << Result << "\n");
1016   return Result;
1017 }
1018
1019 LVILatticeVal LazyValueInfoCache::
1020 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1021                Instruction *CxtI) {
1022   DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1023         << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
1024   
1025   LVILatticeVal Result;
1026   if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1027     solve();
1028     bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1029     (void)WasFastQuery;
1030     assert(WasFastQuery && "More work to do after problem solved?");
1031   }
1032
1033   DEBUG(dbgs() << "  Result = " << Result << "\n");
1034   return Result;
1035 }
1036
1037 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1038                                     BasicBlock *NewSucc) {
1039   // When an edge in the graph has been threaded, values that we could not 
1040   // determine a value for before (i.e. were marked overdefined) may be possible
1041   // to solve now.  We do NOT try to proactively update these values.  Instead,
1042   // we clear their entries from the cache, and allow lazy updating to recompute
1043   // them when needed.
1044   
1045   // The updating process is fairly simple: we need to drop cached info
1046   // for all values that were marked overdefined in OldSucc, and for those same
1047   // values in any successor of OldSucc (except NewSucc) in which they were
1048   // also marked overdefined.
1049   std::vector<BasicBlock*> worklist;
1050   worklist.push_back(OldSucc);
1051   
1052   DenseSet<Value*> ClearSet;
1053   for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
1054        E = OverDefinedCache.end(); I != E; ++I) {
1055     if (I->first == OldSucc)
1056       ClearSet.insert(I->second);
1057   }
1058   
1059   // Use a worklist to perform a depth-first search of OldSucc's successors.
1060   // NOTE: We do not need a visited list since any blocks we have already
1061   // visited will have had their overdefined markers cleared already, and we
1062   // thus won't loop to their successors.
1063   while (!worklist.empty()) {
1064     BasicBlock *ToUpdate = worklist.back();
1065     worklist.pop_back();
1066     
1067     // Skip blocks only accessible through NewSucc.
1068     if (ToUpdate == NewSucc) continue;
1069     
1070     bool changed = false;
1071     for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
1072          I != E; ++I) {
1073       // If a value was marked overdefined in OldSucc, and is here too...
1074       DenseSet<OverDefinedPairTy>::iterator OI =
1075         OverDefinedCache.find(std::make_pair(ToUpdate, *I));
1076       if (OI == OverDefinedCache.end()) continue;
1077
1078       // Remove it from the caches.
1079       ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
1080       ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
1081
1082       assert(CI != Entry.end() && "Couldn't find entry to update?");
1083       Entry.erase(CI);
1084       OverDefinedCache.erase(OI);
1085
1086       // If we removed anything, then we potentially need to update 
1087       // blocks successors too.
1088       changed = true;
1089     }
1090
1091     if (!changed) continue;
1092     
1093     worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1094   }
1095 }
1096
1097 //===----------------------------------------------------------------------===//
1098 //                            LazyValueInfo Impl
1099 //===----------------------------------------------------------------------===//
1100
1101 /// getCache - This lazily constructs the LazyValueInfoCache.
1102 static LazyValueInfoCache &getCache(void *&PImpl,
1103                                     AssumptionTracker *AT,
1104                                     const DataLayout *DL = nullptr,
1105                                     DominatorTree *DT = nullptr) {
1106   if (!PImpl)
1107     PImpl = new LazyValueInfoCache(AT, DL, DT);
1108   return *static_cast<LazyValueInfoCache*>(PImpl);
1109 }
1110
1111 bool LazyValueInfo::runOnFunction(Function &F) {
1112   AT = &getAnalysis<AssumptionTracker>();
1113
1114   DominatorTreeWrapperPass *DTWP =
1115       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1116   DT = DTWP ? &DTWP->getDomTree() : nullptr;
1117
1118   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1119   DL = DLP ? &DLP->getDataLayout() : nullptr;
1120
1121   TLI = &getAnalysis<TargetLibraryInfo>();
1122
1123   if (PImpl)
1124     getCache(PImpl, AT, DL, DT).clear();
1125
1126   // Fully lazy.
1127   return false;
1128 }
1129
1130 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1131   AU.setPreservesAll();
1132   AU.addRequired<AssumptionTracker>();
1133   AU.addRequired<TargetLibraryInfo>();
1134 }
1135
1136 void LazyValueInfo::releaseMemory() {
1137   // If the cache was allocated, free it.
1138   if (PImpl) {
1139     delete &getCache(PImpl, AT);
1140     PImpl = nullptr;
1141   }
1142 }
1143
1144 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1145                                      Instruction *CxtI) {
1146   LVILatticeVal Result =
1147     getCache(PImpl, AT, DL, DT).getValueInBlock(V, BB, CxtI);
1148   
1149   if (Result.isConstant())
1150     return Result.getConstant();
1151   if (Result.isConstantRange()) {
1152     ConstantRange CR = Result.getConstantRange();
1153     if (const APInt *SingleVal = CR.getSingleElement())
1154       return ConstantInt::get(V->getContext(), *SingleVal);
1155   }
1156   return nullptr;
1157 }
1158
1159 /// getConstantOnEdge - Determine whether the specified value is known to be a
1160 /// constant on the specified edge.  Return null if not.
1161 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1162                                            BasicBlock *ToBB,
1163                                            Instruction *CxtI) {
1164   LVILatticeVal Result =
1165     getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1166   
1167   if (Result.isConstant())
1168     return Result.getConstant();
1169   if (Result.isConstantRange()) {
1170     ConstantRange CR = Result.getConstantRange();
1171     if (const APInt *SingleVal = CR.getSingleElement())
1172       return ConstantInt::get(V->getContext(), *SingleVal);
1173   }
1174   return nullptr;
1175 }
1176
1177 static LazyValueInfo::Tristate
1178 getPredicateResult(unsigned Pred, Constant *C, LVILatticeVal &Result,
1179                    const DataLayout *DL, TargetLibraryInfo *TLI) {
1180
1181   // If we know the value is a constant, evaluate the conditional.
1182   Constant *Res = nullptr;
1183   if (Result.isConstant()) {
1184     Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
1185                                           TLI);
1186     if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1187       return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1188     return LazyValueInfo::Unknown;
1189   }
1190   
1191   if (Result.isConstantRange()) {
1192     ConstantInt *CI = dyn_cast<ConstantInt>(C);
1193     if (!CI) return LazyValueInfo::Unknown;
1194     
1195     ConstantRange CR = Result.getConstantRange();
1196     if (Pred == ICmpInst::ICMP_EQ) {
1197       if (!CR.contains(CI->getValue()))
1198         return LazyValueInfo::False;
1199       
1200       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1201         return LazyValueInfo::True;
1202     } else if (Pred == ICmpInst::ICMP_NE) {
1203       if (!CR.contains(CI->getValue()))
1204         return LazyValueInfo::True;
1205       
1206       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1207         return LazyValueInfo::False;
1208     }
1209     
1210     // Handle more complex predicates.
1211     ConstantRange TrueValues =
1212         ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1213     if (TrueValues.contains(CR))
1214       return LazyValueInfo::True;
1215     if (TrueValues.inverse().contains(CR))
1216       return LazyValueInfo::False;
1217     return LazyValueInfo::Unknown;
1218   }
1219   
1220   if (Result.isNotConstant()) {
1221     // If this is an equality comparison, we can try to fold it knowing that
1222     // "V != C1".
1223     if (Pred == ICmpInst::ICMP_EQ) {
1224       // !C1 == C -> false iff C1 == C.
1225       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1226                                             Result.getNotConstant(), C, DL,
1227                                             TLI);
1228       if (Res->isNullValue())
1229         return LazyValueInfo::False;
1230     } else if (Pred == ICmpInst::ICMP_NE) {
1231       // !C1 != C -> true iff C1 == C.
1232       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1233                                             Result.getNotConstant(), C, DL,
1234                                             TLI);
1235       if (Res->isNullValue())
1236         return LazyValueInfo::True;
1237     }
1238     return LazyValueInfo::Unknown;
1239   }
1240   
1241   return LazyValueInfo::Unknown;
1242 }
1243
1244 /// getPredicateOnEdge - Determine whether the specified value comparison
1245 /// with a constant is known to be true or false on the specified CFG edge.
1246 /// Pred is a CmpInst predicate.
1247 LazyValueInfo::Tristate
1248 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1249                                   BasicBlock *FromBB, BasicBlock *ToBB,
1250                                   Instruction *CxtI) {
1251   LVILatticeVal Result =
1252     getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1253
1254   return getPredicateResult(Pred, C, Result, DL, TLI);
1255 }
1256
1257 LazyValueInfo::Tristate
1258 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1259                               Instruction *CxtI) {
1260   LVILatticeVal Result =
1261     getCache(PImpl, AT, DL, DT).getValueAt(V, CxtI);
1262
1263   return getPredicateResult(Pred, C, Result, DL, TLI);
1264 }
1265
1266 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1267                                BasicBlock *NewSucc) {
1268   if (PImpl) getCache(PImpl, AT, DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1269 }
1270
1271 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1272   if (PImpl) getCache(PImpl, AT, DL, DT).eraseBlock(BB);
1273 }