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/AssumptionCache.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/CFG.h"
23 #include "llvm/IR/ConstantRange.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <map>
36 #include <stack>
37 using namespace llvm;
38 using namespace PatternMatch;
39 
40 #define DEBUG_TYPE "lazy-value-info"
41 
42 char LazyValueInfoWrapperPass::ID = 0;
43 INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
44                 "Lazy Value Information Analysis", false, true)
45 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
46 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
47 INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
48                 "Lazy Value Information Analysis", false, true)
49 
50 namespace llvm {
51   FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
52 }
53 
54 AnalysisKey LazyValueAnalysis::Key;
55 
56 //===----------------------------------------------------------------------===//
57 //                               LVILatticeVal
58 //===----------------------------------------------------------------------===//
59 
60 /// This is the information tracked by LazyValueInfo for each value.
61 ///
62 /// FIXME: This is basically just for bringup, this can be made a lot more rich
63 /// in the future.
64 ///
65 namespace {
66 class LVILatticeVal {
67   enum LatticeValueTy {
68     /// This Value has no known value yet.  As a result, this implies the
69     /// producing instruction is dead.  Caution: We use this as the starting
70     /// state in our local meet rules.  In this usage, it's taken to mean
71     /// "nothing known yet".
72     undefined,
73 
74     /// This Value has a specific constant value.  (For constant integers,
75     /// constantrange is used instead.  Integer typed constantexprs can appear
76     /// as constant.)
77     constant,
78 
79     /// This Value is known to not have the specified value.  (For constant
80     /// integers, constantrange is used instead.  As above, integer typed
81     /// constantexprs can appear here.)
82     notconstant,
83 
84     /// The Value falls within this range. (Used only for integer typed values.)
85     constantrange,
86 
87     /// We can not precisely model the dynamic values this value might take.
88     overdefined
89   };
90 
91   /// Val: This stores the current lattice value along with the Constant* for
92   /// the constant if this is a 'constant' or 'notconstant' value.
93   LatticeValueTy Tag;
94   Constant *Val;
95   ConstantRange Range;
96 
97 public:
98   LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
99 
100   static LVILatticeVal get(Constant *C) {
101     LVILatticeVal Res;
102     if (!isa<UndefValue>(C))
103       Res.markConstant(C);
104     return Res;
105   }
106   static LVILatticeVal getNot(Constant *C) {
107     LVILatticeVal Res;
108     if (!isa<UndefValue>(C))
109       Res.markNotConstant(C);
110     return Res;
111   }
112   static LVILatticeVal getRange(ConstantRange CR) {
113     LVILatticeVal Res;
114     Res.markConstantRange(std::move(CR));
115     return Res;
116   }
117   static LVILatticeVal getOverdefined() {
118     LVILatticeVal Res;
119     Res.markOverdefined();
120     return Res;
121   }
122 
123   bool isUndefined() const     { return Tag == undefined; }
124   bool isConstant() const      { return Tag == constant; }
125   bool isNotConstant() const   { return Tag == notconstant; }
126   bool isConstantRange() const { return Tag == constantrange; }
127   bool isOverdefined() const   { return Tag == overdefined; }
128 
129   Constant *getConstant() const {
130     assert(isConstant() && "Cannot get the constant of a non-constant!");
131     return Val;
132   }
133 
134   Constant *getNotConstant() const {
135     assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
136     return Val;
137   }
138 
139   ConstantRange getConstantRange() const {
140     assert(isConstantRange() &&
141            "Cannot get the constant-range of a non-constant-range!");
142     return Range;
143   }
144 
145 private:
146   void markOverdefined() {
147     if (isOverdefined())
148       return;
149     Tag = overdefined;
150   }
151 
152   void markConstant(Constant *V) {
153     assert(V && "Marking constant with NULL");
154     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
155       markConstantRange(ConstantRange(CI->getValue()));
156       return;
157     }
158     if (isa<UndefValue>(V))
159       return;
160 
161     assert((!isConstant() || getConstant() == V) &&
162            "Marking constant with different value");
163     assert(isUndefined());
164     Tag = constant;
165     Val = V;
166   }
167 
168   void markNotConstant(Constant *V) {
169     assert(V && "Marking constant with NULL");
170     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
171       markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
172       return;
173     }
174     if (isa<UndefValue>(V))
175       return;
176 
177     assert((!isConstant() || getConstant() != V) &&
178            "Marking constant !constant with same value");
179     assert((!isNotConstant() || getNotConstant() == V) &&
180            "Marking !constant with different value");
181     assert(isUndefined() || isConstant());
182     Tag = notconstant;
183     Val = V;
184   }
185 
186   void markConstantRange(ConstantRange NewR) {
187     if (isConstantRange()) {
188       if (NewR.isEmptySet())
189         markOverdefined();
190       else {
191         Range = std::move(NewR);
192       }
193       return;
194     }
195 
196     assert(isUndefined());
197     if (NewR.isEmptySet())
198       markOverdefined();
199     else {
200       Tag = constantrange;
201       Range = std::move(NewR);
202     }
203   }
204 
205 public:
206 
207   /// Merge the specified lattice value into this one, updating this
208   /// one and returning true if anything changed.
209   void mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
210     if (RHS.isUndefined() || isOverdefined())
211       return;
212     if (RHS.isOverdefined()) {
213       markOverdefined();
214       return;
215     }
216 
217     if (isUndefined()) {
218       *this = RHS;
219       return;
220     }
221 
222     if (isConstant()) {
223       if (RHS.isConstant() && Val == RHS.Val)
224           return;
225       markOverdefined();
226       return;
227     }
228 
229     if (isNotConstant()) {
230       if (RHS.isNotConstant() && Val == RHS.Val)
231           return;
232       markOverdefined();
233       return;
234     }
235 
236     assert(isConstantRange() && "New LVILattice type?");
237     if (!RHS.isConstantRange()) {
238       // We can get here if we've encountered a constantexpr of integer type
239       // and merge it with a constantrange.
240       markOverdefined();
241       return;
242     }
243     ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
244     if (NewR.isFullSet())
245       markOverdefined();
246     else
247       markConstantRange(NewR);
248   }
249 };
250 
251 } // end anonymous namespace.
252 
253 namespace llvm {
254 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
255     LLVM_ATTRIBUTE_USED;
256 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
257   if (Val.isUndefined())
258     return OS << "undefined";
259   if (Val.isOverdefined())
260     return OS << "overdefined";
261 
262   if (Val.isNotConstant())
263     return OS << "notconstant<" << *Val.getNotConstant() << '>';
264   if (Val.isConstantRange())
265     return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
266               << Val.getConstantRange().getUpper() << '>';
267   return OS << "constant<" << *Val.getConstant() << '>';
268 }
269 }
270 
271 /// Returns true if this lattice value represents at most one possible value.
272 /// This is as precise as any lattice value can get while still representing
273 /// reachable code.
274 static bool hasSingleValue(const LVILatticeVal &Val) {
275   if (Val.isConstantRange() &&
276       Val.getConstantRange().isSingleElement())
277     // Integer constants are single element ranges
278     return true;
279   if (Val.isConstant())
280     // Non integer constants
281     return true;
282   return false;
283 }
284 
285 /// Combine two sets of facts about the same value into a single set of
286 /// facts.  Note that this method is not suitable for merging facts along
287 /// different paths in a CFG; that's what the mergeIn function is for.  This
288 /// is for merging facts gathered about the same value at the same location
289 /// through two independent means.
290 /// Notes:
291 /// * This method does not promise to return the most precise possible lattice
292 ///   value implied by A and B.  It is allowed to return any lattice element
293 ///   which is at least as strong as *either* A or B (unless our facts
294 ///   conflict, see below).
295 /// * Due to unreachable code, the intersection of two lattice values could be
296 ///   contradictory.  If this happens, we return some valid lattice value so as
297 ///   not confuse the rest of LVI.  Ideally, we'd always return Undefined, but
298 ///   we do not make this guarantee.  TODO: This would be a useful enhancement.
299 static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
300   // Undefined is the strongest state.  It means the value is known to be along
301   // an unreachable path.
302   if (A.isUndefined())
303     return A;
304   if (B.isUndefined())
305     return B;
306 
307   // If we gave up for one, but got a useable fact from the other, use it.
308   if (A.isOverdefined())
309     return B;
310   if (B.isOverdefined())
311     return A;
312 
313   // Can't get any more precise than constants.
314   if (hasSingleValue(A))
315     return A;
316   if (hasSingleValue(B))
317     return B;
318 
319   // Could be either constant range or not constant here.
320   if (!A.isConstantRange() || !B.isConstantRange()) {
321     // TODO: Arbitrary choice, could be improved
322     return A;
323   }
324 
325   // Intersect two constant ranges
326   ConstantRange Range =
327     A.getConstantRange().intersectWith(B.getConstantRange());
328   // Note: An empty range is implicitly converted to overdefined internally.
329   // TODO: We could instead use Undefined here since we've proven a conflict
330   // and thus know this path must be unreachable.
331   return LVILatticeVal::getRange(std::move(Range));
332 }
333 
334 //===----------------------------------------------------------------------===//
335 //                          LazyValueInfoCache Decl
336 //===----------------------------------------------------------------------===//
337 
338 namespace {
339   /// A callback value handle updates the cache when values are erased.
340   class LazyValueInfoCache;
341   struct LVIValueHandle final : public CallbackVH {
342     // Needs to access getValPtr(), which is protected.
343     friend struct DenseMapInfo<LVIValueHandle>;
344 
345     LazyValueInfoCache *Parent;
346 
347     LVIValueHandle(Value *V, LazyValueInfoCache *P)
348       : CallbackVH(V), Parent(P) { }
349 
350     void deleted() override;
351     void allUsesReplacedWith(Value *V) override {
352       deleted();
353     }
354   };
355 } // end anonymous namespace
356 
357 namespace {
358   /// This is the cache kept by LazyValueInfo which
359   /// maintains information about queries across the clients' queries.
360   class LazyValueInfoCache {
361     /// This is all of the cached block information for exactly one Value*.
362     /// The entries are sorted by the BasicBlock* of the
363     /// entries, allowing us to do a lookup with a binary search.
364     /// Over-defined lattice values are recorded in OverDefinedCache to reduce
365     /// memory overhead.
366     struct ValueCacheEntryTy {
367       ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {}
368       LVIValueHandle Handle;
369       SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4> BlockVals;
370     };
371 
372     /// This is all of the cached information for all values,
373     /// mapped from Value* to key information.
374     DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache;
375 
376     /// This tracks, on a per-block basis, the set of values that are
377     /// over-defined at the end of that block.
378     typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
379         OverDefinedCacheTy;
380     OverDefinedCacheTy OverDefinedCache;
381 
382     /// Keep track of all blocks that we have ever seen, so we
383     /// don't spend time removing unused blocks from our caches.
384     DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
385 
386   public:
387     void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
388       SeenBlocks.insert(BB);
389 
390       // Insert over-defined values into their own cache to reduce memory
391       // overhead.
392       if (Result.isOverdefined())
393         OverDefinedCache[BB].insert(Val);
394       else {
395         auto It = ValueCache.find_as(Val);
396         if (It == ValueCache.end()) {
397           ValueCache[Val] = make_unique<ValueCacheEntryTy>(Val, this);
398           It = ValueCache.find_as(Val);
399           assert(It != ValueCache.end() && "Val was just added to the map!");
400         }
401         It->second->BlockVals[BB] = Result;
402       }
403     }
404 
405     bool isOverdefined(Value *V, BasicBlock *BB) const {
406       auto ODI = OverDefinedCache.find(BB);
407 
408       if (ODI == OverDefinedCache.end())
409         return false;
410 
411       return ODI->second.count(V);
412     }
413 
414     bool hasCachedValueInfo(Value *V, BasicBlock *BB) const {
415       if (isOverdefined(V, BB))
416         return true;
417 
418       auto I = ValueCache.find_as(V);
419       if (I == ValueCache.end())
420         return false;
421 
422       return I->second->BlockVals.count(BB);
423     }
424 
425     LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) const {
426       if (isOverdefined(V, BB))
427         return LVILatticeVal::getOverdefined();
428 
429       auto I = ValueCache.find_as(V);
430       if (I == ValueCache.end())
431         return LVILatticeVal();
432       auto BBI = I->second->BlockVals.find(BB);
433       if (BBI == I->second->BlockVals.end())
434         return LVILatticeVal();
435       return BBI->second;
436     }
437 
438     /// clear - Empty the cache.
439     void clear() {
440       SeenBlocks.clear();
441       ValueCache.clear();
442       OverDefinedCache.clear();
443     }
444 
445     /// Inform the cache that a given value has been deleted.
446     void eraseValue(Value *V);
447 
448     /// This is part of the update interface to inform the cache
449     /// that a block has been deleted.
450     void eraseBlock(BasicBlock *BB);
451 
452     /// Updates the cache to remove any influence an overdefined value in
453     /// OldSucc might have (unless also overdefined in NewSucc).  This just
454     /// flushes elements from the cache and does not add any.
455     void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
456 
457     friend struct LVIValueHandle;
458   };
459 }
460 
461 void LazyValueInfoCache::eraseValue(Value *V) {
462   SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
463   for (auto &I : OverDefinedCache) {
464     SmallPtrSetImpl<Value *> &ValueSet = I.second;
465     if (ValueSet.count(V))
466       ValueSet.erase(V);
467     if (ValueSet.empty())
468       ToErase.push_back(I.first);
469   }
470   for (auto &BB : ToErase)
471     OverDefinedCache.erase(BB);
472 
473   ValueCache.erase(V);
474 }
475 
476 void LVIValueHandle::deleted() {
477   // This erasure deallocates *this, so it MUST happen after we're done
478   // using any and all members of *this.
479   Parent->eraseValue(*this);
480 }
481 
482 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
483   // Shortcut if we have never seen this block.
484   DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
485   if (I == SeenBlocks.end())
486     return;
487   SeenBlocks.erase(I);
488 
489   auto ODI = OverDefinedCache.find(BB);
490   if (ODI != OverDefinedCache.end())
491     OverDefinedCache.erase(ODI);
492 
493   for (auto &I : ValueCache)
494     I.second->BlockVals.erase(BB);
495 }
496 
497 void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
498                                         BasicBlock *NewSucc) {
499   // When an edge in the graph has been threaded, values that we could not
500   // determine a value for before (i.e. were marked overdefined) may be
501   // possible to solve now. We do NOT try to proactively update these values.
502   // Instead, we clear their entries from the cache, and allow lazy updating to
503   // recompute them when needed.
504 
505   // The updating process is fairly simple: we need to drop cached info
506   // for all values that were marked overdefined in OldSucc, and for those same
507   // values in any successor of OldSucc (except NewSucc) in which they were
508   // also marked overdefined.
509   std::vector<BasicBlock*> worklist;
510   worklist.push_back(OldSucc);
511 
512   auto I = OverDefinedCache.find(OldSucc);
513   if (I == OverDefinedCache.end())
514     return; // Nothing to process here.
515   SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
516 
517   // Use a worklist to perform a depth-first search of OldSucc's successors.
518   // NOTE: We do not need a visited list since any blocks we have already
519   // visited will have had their overdefined markers cleared already, and we
520   // thus won't loop to their successors.
521   while (!worklist.empty()) {
522     BasicBlock *ToUpdate = worklist.back();
523     worklist.pop_back();
524 
525     // Skip blocks only accessible through NewSucc.
526     if (ToUpdate == NewSucc) continue;
527 
528     bool changed = false;
529     for (Value *V : ValsToClear) {
530       // If a value was marked overdefined in OldSucc, and is here too...
531       auto OI = OverDefinedCache.find(ToUpdate);
532       if (OI == OverDefinedCache.end())
533         continue;
534       SmallPtrSetImpl<Value *> &ValueSet = OI->second;
535       if (!ValueSet.count(V))
536         continue;
537 
538       ValueSet.erase(V);
539       if (ValueSet.empty())
540         OverDefinedCache.erase(OI);
541 
542       // If we removed anything, then we potentially need to update
543       // blocks successors too.
544       changed = true;
545     }
546 
547     if (!changed) continue;
548 
549     worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
550   }
551 }
552 
553 namespace {
554   // The actual implementation of the lazy analysis and update.  Note that the
555   // inheritance from LazyValueInfoCache is intended to be temporary while
556   // splitting the code and then transitioning to a has-a relationship.
557   class LazyValueInfoImpl {
558 
559     /// Cached results from previous queries
560     LazyValueInfoCache TheCache;
561 
562     /// This stack holds the state of the value solver during a query.
563     /// It basically emulates the callstack of the naive
564     /// recursive value lookup process.
565     std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
566 
567     /// Keeps track of which block-value pairs are in BlockValueStack.
568     DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
569 
570     /// Push BV onto BlockValueStack unless it's already in there.
571     /// Returns true on success.
572     bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
573       if (!BlockValueSet.insert(BV).second)
574         return false;  // It's already in the stack.
575 
576       DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
577                    << "\n");
578       BlockValueStack.push(BV);
579       return true;
580     }
581 
582     AssumptionCache *AC;  ///< A pointer to the cache of @llvm.assume calls.
583     const DataLayout &DL; ///< A mandatory DataLayout
584     DominatorTree *DT;    ///< An optional DT pointer.
585 
586   LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
587   bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
588                     LVILatticeVal &Result, Instruction *CxtI = nullptr);
589   bool hasBlockValue(Value *Val, BasicBlock *BB);
590 
591   // These methods process one work item and may add more. A false value
592   // returned means that the work item was not completely processed and must
593   // be revisited after going through the new items.
594   bool solveBlockValue(Value *Val, BasicBlock *BB);
595   bool solveBlockValueImpl(LVILatticeVal &Res, Value *Val, BasicBlock *BB);
596   bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB);
597   bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB);
598   bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S,
599                              BasicBlock *BB);
600   bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, Instruction *BBI,
601                                BasicBlock *BB);
602   bool solveBlockValueCast(LVILatticeVal &BBLV, Instruction *BBI,
603                            BasicBlock *BB);
604   void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
605                                                      LVILatticeVal &BBLV,
606                                               Instruction *BBI);
607 
608   void solve();
609 
610   public:
611     /// This is the query interface to determine the lattice
612     /// value for the specified Value* at the end of the specified block.
613     LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
614                                   Instruction *CxtI = nullptr);
615 
616     /// This is the query interface to determine the lattice
617     /// value for the specified Value* at the specified instruction (generally
618     /// from an assume intrinsic).
619     LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
620 
621     /// This is the query interface to determine the lattice
622     /// value for the specified Value* that is true on the specified edge.
623     LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
624                                  Instruction *CxtI = nullptr);
625 
626     /// Complete flush all previously computed values
627     void clear() {
628       TheCache.clear();
629     }
630 
631     /// This is part of the update interface to inform the cache
632     /// that a block has been deleted.
633     void eraseBlock(BasicBlock *BB) {
634       TheCache.eraseBlock(BB);
635     }
636 
637     /// This is the update interface to inform the cache that an edge from
638     /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
639     void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
640 
641     LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
642                        DominatorTree *DT = nullptr)
643         : AC(AC), DL(DL), DT(DT) {}
644   };
645 } // end anonymous namespace
646 
647 void LazyValueInfoImpl::solve() {
648   while (!BlockValueStack.empty()) {
649     std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
650     assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
651 
652     if (solveBlockValue(e.second, e.first)) {
653       // The work item was completely processed.
654       assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
655       assert(TheCache.hasCachedValueInfo(e.second, e.first) &&
656              "Result should be in cache!");
657 
658       DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
659                    << " = " << TheCache.getCachedValueInfo(e.second, e.first) << "\n");
660 
661       BlockValueStack.pop();
662       BlockValueSet.erase(e);
663     } else {
664       // More work needs to be done before revisiting.
665       assert(BlockValueStack.top() != e && "Stack should have been pushed!");
666     }
667   }
668 }
669 
670 bool LazyValueInfoImpl::hasBlockValue(Value *Val, BasicBlock *BB) {
671   // If already a constant, there is nothing to compute.
672   if (isa<Constant>(Val))
673     return true;
674 
675   return TheCache.hasCachedValueInfo(Val, BB);
676 }
677 
678 LVILatticeVal LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB) {
679   // If already a constant, there is nothing to compute.
680   if (Constant *VC = dyn_cast<Constant>(Val))
681     return LVILatticeVal::get(VC);
682 
683   return TheCache.getCachedValueInfo(Val, BB);
684 }
685 
686 static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
687   switch (BBI->getOpcode()) {
688   default: break;
689   case Instruction::Load:
690   case Instruction::Call:
691   case Instruction::Invoke:
692     if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
693       if (isa<IntegerType>(BBI->getType())) {
694         return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
695       }
696     break;
697   };
698   // Nothing known - will be intersected with other facts
699   return LVILatticeVal::getOverdefined();
700 }
701 
702 bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
703   if (isa<Constant>(Val))
704     return true;
705 
706   if (TheCache.hasCachedValueInfo(Val, BB)) {
707     // If we have a cached value, use that.
708     DEBUG(dbgs() << "  reuse BB '" << BB->getName()
709                  << "' val=" << TheCache.getCachedValueInfo(Val, BB) << '\n');
710 
711     // Since we're reusing a cached value, we don't need to update the
712     // OverDefinedCache. The cache will have been properly updated whenever the
713     // cached value was inserted.
714     return true;
715   }
716 
717   // Hold off inserting this value into the Cache in case we have to return
718   // false and come back later.
719   LVILatticeVal Res;
720   if (!solveBlockValueImpl(Res, Val, BB))
721     // Work pushed, will revisit
722     return false;
723 
724   TheCache.insertResult(Val, BB, Res);
725   return true;
726 }
727 
728 bool LazyValueInfoImpl::solveBlockValueImpl(LVILatticeVal &Res,
729                                             Value *Val, BasicBlock *BB) {
730 
731   Instruction *BBI = dyn_cast<Instruction>(Val);
732   if (!BBI || BBI->getParent() != BB)
733     return solveBlockValueNonLocal(Res, Val, BB);
734 
735   if (PHINode *PN = dyn_cast<PHINode>(BBI))
736     return solveBlockValuePHINode(Res, PN, BB);
737 
738   if (auto *SI = dyn_cast<SelectInst>(BBI))
739     return solveBlockValueSelect(Res, SI, BB);
740 
741   // If this value is a nonnull pointer, record it's range and bailout.  Note
742   // that for all other pointer typed values, we terminate the search at the
743   // definition.  We could easily extend this to look through geps, bitcasts,
744   // and the like to prove non-nullness, but it's not clear that's worth it
745   // compile time wise.  The context-insensative value walk done inside
746   // isKnownNonNull gets most of the profitable cases at much less expense.
747   // This does mean that we have a sensativity to where the defining
748   // instruction is placed, even if it could legally be hoisted much higher.
749   // That is unfortunate.
750   PointerType *PT = dyn_cast<PointerType>(BBI->getType());
751   if (PT && isKnownNonNull(BBI)) {
752     Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
753     return true;
754   }
755   if (BBI->getType()->isIntegerTy()) {
756     if (isa<CastInst>(BBI))
757       return solveBlockValueCast(Res, BBI, BB);
758 
759     BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
760     if (BO && isa<ConstantInt>(BO->getOperand(1)))
761       return solveBlockValueBinaryOp(Res, BBI, BB);
762   }
763 
764   DEBUG(dbgs() << " compute BB '" << BB->getName()
765                  << "' - unknown inst def found.\n");
766   Res = getFromRangeMetadata(BBI);
767   return true;
768 }
769 
770 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
771   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
772     return L->getPointerAddressSpace() == 0 &&
773            GetUnderlyingObject(L->getPointerOperand(),
774                                L->getModule()->getDataLayout()) == Ptr;
775   }
776   if (StoreInst *S = dyn_cast<StoreInst>(I)) {
777     return S->getPointerAddressSpace() == 0 &&
778            GetUnderlyingObject(S->getPointerOperand(),
779                                S->getModule()->getDataLayout()) == Ptr;
780   }
781   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
782     if (MI->isVolatile()) return false;
783 
784     // FIXME: check whether it has a valuerange that excludes zero?
785     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
786     if (!Len || Len->isZero()) return false;
787 
788     if (MI->getDestAddressSpace() == 0)
789       if (GetUnderlyingObject(MI->getRawDest(),
790                               MI->getModule()->getDataLayout()) == Ptr)
791         return true;
792     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
793       if (MTI->getSourceAddressSpace() == 0)
794         if (GetUnderlyingObject(MTI->getRawSource(),
795                                 MTI->getModule()->getDataLayout()) == Ptr)
796           return true;
797   }
798   return false;
799 }
800 
801 /// Return true if the allocation associated with Val is ever dereferenced
802 /// within the given basic block.  This establishes the fact Val is not null,
803 /// but does not imply that the memory at Val is dereferenceable.  (Val may
804 /// point off the end of the dereferenceable part of the object.)
805 static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
806   assert(Val->getType()->isPointerTy());
807 
808   const DataLayout &DL = BB->getModule()->getDataLayout();
809   Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
810   // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
811   // inside InstructionDereferencesPointer either.
812   if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
813     for (Instruction &I : *BB)
814       if (InstructionDereferencesPointer(&I, UnderlyingVal))
815         return true;
816   return false;
817 }
818 
819 bool LazyValueInfoImpl::solveBlockValueNonLocal(LVILatticeVal &BBLV,
820                                                  Value *Val, BasicBlock *BB) {
821   LVILatticeVal Result;  // Start Undefined.
822 
823   // If this is the entry block, we must be asking about an argument.  The
824   // value is overdefined.
825   if (BB == &BB->getParent()->getEntryBlock()) {
826     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
827     // Bofore giving up, see if we can prove the pointer non-null local to
828     // this particular block.
829     if (Val->getType()->isPointerTy() &&
830         (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
831       PointerType *PTy = cast<PointerType>(Val->getType());
832       Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
833     } else {
834       Result = LVILatticeVal::getOverdefined();
835     }
836     BBLV = Result;
837     return true;
838   }
839 
840   // Loop over all of our predecessors, merging what we know from them into
841   // result.
842   bool EdgesMissing = false;
843   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
844     LVILatticeVal EdgeResult;
845     EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
846     if (EdgesMissing)
847       continue;
848 
849     Result.mergeIn(EdgeResult, DL);
850 
851     // If we hit overdefined, exit early.  The BlockVals entry is already set
852     // to overdefined.
853     if (Result.isOverdefined()) {
854       DEBUG(dbgs() << " compute BB '" << BB->getName()
855             << "' - overdefined because of pred (non local).\n");
856       // Before giving up, see if we can prove the pointer non-null local to
857       // this particular block.
858       if (Val->getType()->isPointerTy() &&
859           isObjectDereferencedInBlock(Val, BB)) {
860         PointerType *PTy = cast<PointerType>(Val->getType());
861         Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
862       }
863 
864       BBLV = Result;
865       return true;
866     }
867   }
868   if (EdgesMissing)
869     return false;
870 
871   // Return the merged value, which is more precise than 'overdefined'.
872   assert(!Result.isOverdefined());
873   BBLV = Result;
874   return true;
875 }
876 
877 bool LazyValueInfoImpl::solveBlockValuePHINode(LVILatticeVal &BBLV,
878                                                 PHINode *PN, BasicBlock *BB) {
879   LVILatticeVal Result;  // Start Undefined.
880 
881   // Loop over all of our predecessors, merging what we know from them into
882   // result.
883   bool EdgesMissing = false;
884   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
885     BasicBlock *PhiBB = PN->getIncomingBlock(i);
886     Value *PhiVal = PN->getIncomingValue(i);
887     LVILatticeVal EdgeResult;
888     // Note that we can provide PN as the context value to getEdgeValue, even
889     // though the results will be cached, because PN is the value being used as
890     // the cache key in the caller.
891     EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
892     if (EdgesMissing)
893       continue;
894 
895     Result.mergeIn(EdgeResult, DL);
896 
897     // If we hit overdefined, exit early.  The BlockVals entry is already set
898     // to overdefined.
899     if (Result.isOverdefined()) {
900       DEBUG(dbgs() << " compute BB '" << BB->getName()
901             << "' - overdefined because of pred (local).\n");
902 
903       BBLV = Result;
904       return true;
905     }
906   }
907   if (EdgesMissing)
908     return false;
909 
910   // Return the merged value, which is more precise than 'overdefined'.
911   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
912   BBLV = Result;
913   return true;
914 }
915 
916 static LVILatticeVal getValueFromCondition(Value *Val, Value *Cond,
917                                            bool isTrueDest = true);
918 
919 // If we can determine a constraint on the value given conditions assumed by
920 // the program, intersect those constraints with BBLV
921 void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
922         Value *Val, LVILatticeVal &BBLV, Instruction *BBI) {
923   BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
924   if (!BBI)
925     return;
926 
927   for (auto &AssumeVH : AC->assumptions()) {
928     if (!AssumeVH)
929       continue;
930     auto *I = cast<CallInst>(AssumeVH);
931     if (!isValidAssumeForContext(I, BBI, DT))
932       continue;
933 
934     BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
935   }
936 
937   // If guards are not used in the module, don't spend time looking for them
938   auto *GuardDecl = BBI->getModule()->getFunction(
939           Intrinsic::getName(Intrinsic::experimental_guard));
940   if (!GuardDecl || GuardDecl->use_empty())
941     return;
942 
943   for (Instruction &I : make_range(BBI->getIterator().getReverse(),
944                                    BBI->getParent()->rend())) {
945     Value *Cond = nullptr;
946     if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
947       BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
948   }
949 }
950 
951 bool LazyValueInfoImpl::solveBlockValueSelect(LVILatticeVal &BBLV,
952                                                SelectInst *SI, BasicBlock *BB) {
953 
954   // Recurse on our inputs if needed
955   if (!hasBlockValue(SI->getTrueValue(), BB)) {
956     if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
957       return false;
958     BBLV = LVILatticeVal::getOverdefined();
959     return true;
960   }
961   LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
962   // If we hit overdefined, don't ask more queries.  We want to avoid poisoning
963   // extra slots in the table if we can.
964   if (TrueVal.isOverdefined()) {
965     BBLV = LVILatticeVal::getOverdefined();
966     return true;
967   }
968 
969   if (!hasBlockValue(SI->getFalseValue(), BB)) {
970     if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
971       return false;
972     BBLV = LVILatticeVal::getOverdefined();
973     return true;
974   }
975   LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
976   // If we hit overdefined, don't ask more queries.  We want to avoid poisoning
977   // extra slots in the table if we can.
978   if (FalseVal.isOverdefined()) {
979     BBLV = LVILatticeVal::getOverdefined();
980     return true;
981   }
982 
983   if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
984     ConstantRange TrueCR = TrueVal.getConstantRange();
985     ConstantRange FalseCR = FalseVal.getConstantRange();
986     Value *LHS = nullptr;
987     Value *RHS = nullptr;
988     SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
989     // Is this a min specifically of our two inputs?  (Avoid the risk of
990     // ValueTracking getting smarter looking back past our immediate inputs.)
991     if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
992         LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
993       ConstantRange ResultCR = [&]() {
994         switch (SPR.Flavor) {
995         default:
996           llvm_unreachable("unexpected minmax type!");
997         case SPF_SMIN:                   /// Signed minimum
998           return TrueCR.smin(FalseCR);
999         case SPF_UMIN:                   /// Unsigned minimum
1000           return TrueCR.umin(FalseCR);
1001         case SPF_SMAX:                   /// Signed maximum
1002           return TrueCR.smax(FalseCR);
1003         case SPF_UMAX:                   /// Unsigned maximum
1004           return TrueCR.umax(FalseCR);
1005         };
1006       }();
1007       BBLV = LVILatticeVal::getRange(ResultCR);
1008       return true;
1009     }
1010 
1011     // TODO: ABS, NABS from the SelectPatternResult
1012   }
1013 
1014   // Can we constrain the facts about the true and false values by using the
1015   // condition itself?  This shows up with idioms like e.g. select(a > 5, a, 5).
1016   // TODO: We could potentially refine an overdefined true value above.
1017   Value *Cond = SI->getCondition();
1018   TrueVal = intersect(TrueVal,
1019                       getValueFromCondition(SI->getTrueValue(), Cond, true));
1020   FalseVal = intersect(FalseVal,
1021                        getValueFromCondition(SI->getFalseValue(), Cond, false));
1022 
1023   // Handle clamp idioms such as:
1024   //   %24 = constantrange<0, 17>
1025   //   %39 = icmp eq i32 %24, 0
1026   //   %40 = add i32 %24, -1
1027   //   %siv.next = select i1 %39, i32 16, i32 %40
1028   //   %siv.next = constantrange<0, 17> not <-1, 17>
1029   // In general, this can handle any clamp idiom which tests the edge
1030   // condition via an equality or inequality.
1031   if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
1032     ICmpInst::Predicate Pred = ICI->getPredicate();
1033     Value *A = ICI->getOperand(0);
1034     if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
1035       auto addConstants = [](ConstantInt *A, ConstantInt *B) {
1036         assert(A->getType() == B->getType());
1037         return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
1038       };
1039       // See if either input is A + C2, subject to the constraint from the
1040       // condition that A != C when that input is used.  We can assume that
1041       // that input doesn't include C + C2.
1042       ConstantInt *CIAdded;
1043       switch (Pred) {
1044       default: break;
1045       case ICmpInst::ICMP_EQ:
1046         if (match(SI->getFalseValue(), m_Add(m_Specific(A),
1047                                              m_ConstantInt(CIAdded)))) {
1048           auto ResNot = addConstants(CIBase, CIAdded);
1049           FalseVal = intersect(FalseVal,
1050                                LVILatticeVal::getNot(ResNot));
1051         }
1052         break;
1053       case ICmpInst::ICMP_NE:
1054         if (match(SI->getTrueValue(), m_Add(m_Specific(A),
1055                                             m_ConstantInt(CIAdded)))) {
1056           auto ResNot = addConstants(CIBase, CIAdded);
1057           TrueVal = intersect(TrueVal,
1058                               LVILatticeVal::getNot(ResNot));
1059         }
1060         break;
1061       };
1062     }
1063   }
1064 
1065   LVILatticeVal Result;  // Start Undefined.
1066   Result.mergeIn(TrueVal, DL);
1067   Result.mergeIn(FalseVal, DL);
1068   BBLV = Result;
1069   return true;
1070 }
1071 
1072 bool LazyValueInfoImpl::solveBlockValueCast(LVILatticeVal &BBLV,
1073                                              Instruction *BBI,
1074                                              BasicBlock *BB) {
1075   if (!BBI->getOperand(0)->getType()->isSized()) {
1076     // Without knowing how wide the input is, we can't analyze it in any useful
1077     // way.
1078     BBLV = LVILatticeVal::getOverdefined();
1079     return true;
1080   }
1081 
1082   // Filter out casts we don't know how to reason about before attempting to
1083   // recurse on our operand.  This can cut a long search short if we know we're
1084   // not going to be able to get any useful information anways.
1085   switch (BBI->getOpcode()) {
1086   case Instruction::Trunc:
1087   case Instruction::SExt:
1088   case Instruction::ZExt:
1089   case Instruction::BitCast:
1090     break;
1091   default:
1092     // Unhandled instructions are overdefined.
1093     DEBUG(dbgs() << " compute BB '" << BB->getName()
1094                  << "' - overdefined (unknown cast).\n");
1095     BBLV = LVILatticeVal::getOverdefined();
1096     return true;
1097   }
1098 
1099   // Figure out the range of the LHS.  If that fails, we still apply the
1100   // transfer rule on the full set since we may be able to locally infer
1101   // interesting facts.
1102   if (!hasBlockValue(BBI->getOperand(0), BB))
1103     if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1104       // More work to do before applying this transfer rule.
1105       return false;
1106 
1107   const unsigned OperandBitWidth =
1108     DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1109   ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1110   if (hasBlockValue(BBI->getOperand(0), BB)) {
1111     LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1112     intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1113                                                   BBI);
1114     if (LHSVal.isConstantRange())
1115       LHSRange = LHSVal.getConstantRange();
1116   }
1117 
1118   const unsigned ResultBitWidth =
1119     cast<IntegerType>(BBI->getType())->getBitWidth();
1120 
1121   // NOTE: We're currently limited by the set of operations that ConstantRange
1122   // can evaluate symbolically.  Enhancing that set will allows us to analyze
1123   // more definitions.
1124   auto CastOp = (Instruction::CastOps) BBI->getOpcode();
1125   BBLV = LVILatticeVal::getRange(LHSRange.castOp(CastOp, ResultBitWidth));
1126   return true;
1127 }
1128 
1129 bool LazyValueInfoImpl::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
1130                                                  Instruction *BBI,
1131                                                  BasicBlock *BB) {
1132 
1133   assert(BBI->getOperand(0)->getType()->isSized() &&
1134          "all operands to binary operators are sized");
1135 
1136   // Filter out operators we don't know how to reason about before attempting to
1137   // recurse on our operand(s).  This can cut a long search short if we know
1138   // we're not going to be able to get any useful information anways.
1139   switch (BBI->getOpcode()) {
1140   case Instruction::Add:
1141   case Instruction::Sub:
1142   case Instruction::Mul:
1143   case Instruction::UDiv:
1144   case Instruction::Shl:
1145   case Instruction::LShr:
1146   case Instruction::And:
1147   case Instruction::Or:
1148     // continue into the code below
1149     break;
1150   default:
1151     // Unhandled instructions are overdefined.
1152     DEBUG(dbgs() << " compute BB '" << BB->getName()
1153                  << "' - overdefined (unknown binary operator).\n");
1154     BBLV = LVILatticeVal::getOverdefined();
1155     return true;
1156   };
1157 
1158   // Figure out the range of the LHS.  If that fails, use a conservative range,
1159   // but apply the transfer rule anyways.  This lets us pick up facts from
1160   // expressions like "and i32 (call i32 @foo()), 32"
1161   if (!hasBlockValue(BBI->getOperand(0), BB))
1162     if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1163       // More work to do before applying this transfer rule.
1164       return false;
1165 
1166   const unsigned OperandBitWidth =
1167     DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1168   ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1169   if (hasBlockValue(BBI->getOperand(0), BB)) {
1170     LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1171     intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1172                                                   BBI);
1173     if (LHSVal.isConstantRange())
1174       LHSRange = LHSVal.getConstantRange();
1175   }
1176 
1177   ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1));
1178   ConstantRange RHSRange = ConstantRange(RHS->getValue());
1179 
1180   // NOTE: We're currently limited by the set of operations that ConstantRange
1181   // can evaluate symbolically.  Enhancing that set will allows us to analyze
1182   // more definitions.
1183   auto BinOp = (Instruction::BinaryOps) BBI->getOpcode();
1184   BBLV = LVILatticeVal::getRange(LHSRange.binaryOp(BinOp, RHSRange));
1185   return true;
1186 }
1187 
1188 static LVILatticeVal getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1189                                                bool isTrueDest) {
1190   Value *LHS = ICI->getOperand(0);
1191   Value *RHS = ICI->getOperand(1);
1192   CmpInst::Predicate Predicate = ICI->getPredicate();
1193 
1194   if (isa<Constant>(RHS)) {
1195     if (ICI->isEquality() && LHS == Val) {
1196       // We know that V has the RHS constant if this is a true SETEQ or
1197       // false SETNE.
1198       if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ))
1199         return LVILatticeVal::get(cast<Constant>(RHS));
1200       else
1201         return LVILatticeVal::getNot(cast<Constant>(RHS));
1202     }
1203   }
1204 
1205   if (!Val->getType()->isIntegerTy())
1206     return LVILatticeVal::getOverdefined();
1207 
1208   // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible
1209   // range of Val guaranteed by the condition. Recognize comparisons in the from
1210   // of:
1211   //  icmp <pred> Val, ...
1212   //  icmp <pred> (add Val, Offset), ...
1213   // The latter is the range checking idiom that InstCombine produces. Subtract
1214   // the offset from the allowed range for RHS in this case.
1215 
1216   // Val or (add Val, Offset) can be on either hand of the comparison
1217   if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) {
1218     std::swap(LHS, RHS);
1219     Predicate = CmpInst::getSwappedPredicate(Predicate);
1220   }
1221 
1222   ConstantInt *Offset = nullptr;
1223   if (LHS != Val)
1224     match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset)));
1225 
1226   if (LHS == Val || Offset) {
1227     // Calculate the range of values that are allowed by the comparison
1228     ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1229                            /*isFullSet=*/true);
1230     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1231       RHSRange = ConstantRange(CI->getValue());
1232     else if (Instruction *I = dyn_cast<Instruction>(RHS))
1233       if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1234         RHSRange = getConstantRangeFromMetadata(*Ranges);
1235 
1236     // If we're interested in the false dest, invert the condition
1237     CmpInst::Predicate Pred =
1238             isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate);
1239     ConstantRange TrueValues =
1240             ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1241 
1242     if (Offset) // Apply the offset from above.
1243       TrueValues = TrueValues.subtract(Offset->getValue());
1244 
1245     return LVILatticeVal::getRange(std::move(TrueValues));
1246   }
1247 
1248   return LVILatticeVal::getOverdefined();
1249 }
1250 
1251 static LVILatticeVal
1252 getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1253                       DenseMap<Value*, LVILatticeVal> &Visited);
1254 
1255 static LVILatticeVal
1256 getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1257                           DenseMap<Value*, LVILatticeVal> &Visited) {
1258   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1259     return getValueFromICmpCondition(Val, ICI, isTrueDest);
1260 
1261   // Handle conditions in the form of (cond1 && cond2), we know that on the
1262   // true dest path both of the conditions hold.
1263   if (!isTrueDest)
1264     return LVILatticeVal::getOverdefined();
1265 
1266   BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
1267   if (!BO || BO->getOpcode() != BinaryOperator::And)
1268     return LVILatticeVal::getOverdefined();
1269 
1270   auto RHS = getValueFromCondition(Val, BO->getOperand(0), isTrueDest, Visited);
1271   auto LHS = getValueFromCondition(Val, BO->getOperand(1), isTrueDest, Visited);
1272   return intersect(RHS, LHS);
1273 }
1274 
1275 static LVILatticeVal
1276 getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1277                       DenseMap<Value*, LVILatticeVal> &Visited) {
1278   auto I = Visited.find(Cond);
1279   if (I != Visited.end())
1280     return I->second;
1281 
1282   auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited);
1283   Visited[Cond] = Result;
1284   return Result;
1285 }
1286 
1287 LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest) {
1288   assert(Cond && "precondition");
1289   DenseMap<Value*, LVILatticeVal> Visited;
1290   return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1291 }
1292 
1293 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
1294 /// Val is not constrained on the edge.  Result is unspecified if return value
1295 /// is false.
1296 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1297                               BasicBlock *BBTo, LVILatticeVal &Result) {
1298   // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1299   // know that v != 0.
1300   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1301     // If this is a conditional branch and only one successor goes to BBTo, then
1302     // we may be able to infer something from the condition.
1303     if (BI->isConditional() &&
1304         BI->getSuccessor(0) != BI->getSuccessor(1)) {
1305       bool isTrueDest = BI->getSuccessor(0) == BBTo;
1306       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1307              "BBTo isn't a successor of BBFrom");
1308 
1309       // If V is the condition of the branch itself, then we know exactly what
1310       // it is.
1311       if (BI->getCondition() == Val) {
1312         Result = LVILatticeVal::get(ConstantInt::get(
1313                               Type::getInt1Ty(Val->getContext()), isTrueDest));
1314         return true;
1315       }
1316 
1317       // If the condition of the branch is an equality comparison, we may be
1318       // able to infer the value.
1319       Result = getValueFromCondition(Val, BI->getCondition(), isTrueDest);
1320       if (!Result.isOverdefined())
1321         return true;
1322     }
1323   }
1324 
1325   // If the edge was formed by a switch on the value, then we may know exactly
1326   // what it is.
1327   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1328     if (SI->getCondition() != Val)
1329       return false;
1330 
1331     bool DefaultCase = SI->getDefaultDest() == BBTo;
1332     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1333     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1334 
1335     for (SwitchInst::CaseIt i : SI->cases()) {
1336       ConstantRange EdgeVal(i.getCaseValue()->getValue());
1337       if (DefaultCase) {
1338         // It is possible that the default destination is the destination of
1339         // some cases. There is no need to perform difference for those cases.
1340         if (i.getCaseSuccessor() != BBTo)
1341           EdgesVals = EdgesVals.difference(EdgeVal);
1342       } else if (i.getCaseSuccessor() == BBTo)
1343         EdgesVals = EdgesVals.unionWith(EdgeVal);
1344     }
1345     Result = LVILatticeVal::getRange(std::move(EdgesVals));
1346     return true;
1347   }
1348   return false;
1349 }
1350 
1351 /// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1352 /// the basic block if the edge does not constrain Val.
1353 bool LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1354                                       BasicBlock *BBTo, LVILatticeVal &Result,
1355                                       Instruction *CxtI) {
1356   // If already a constant, there is nothing to compute.
1357   if (Constant *VC = dyn_cast<Constant>(Val)) {
1358     Result = LVILatticeVal::get(VC);
1359     return true;
1360   }
1361 
1362   LVILatticeVal LocalResult;
1363   if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1364     // If we couldn't constrain the value on the edge, LocalResult doesn't
1365     // provide any information.
1366     LocalResult = LVILatticeVal::getOverdefined();
1367 
1368   if (hasSingleValue(LocalResult)) {
1369     // Can't get any more precise here
1370     Result = LocalResult;
1371     return true;
1372   }
1373 
1374   if (!hasBlockValue(Val, BBFrom)) {
1375     if (pushBlockValue(std::make_pair(BBFrom, Val)))
1376       return false;
1377     // No new information.
1378     Result = LocalResult;
1379     return true;
1380   }
1381 
1382   // Try to intersect ranges of the BB and the constraint on the edge.
1383   LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
1384   intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1385                                                 BBFrom->getTerminator());
1386   // We can use the context instruction (generically the ultimate instruction
1387   // the calling pass is trying to simplify) here, even though the result of
1388   // this function is generally cached when called from the solve* functions
1389   // (and that cached result might be used with queries using a different
1390   // context instruction), because when this function is called from the solve*
1391   // functions, the context instruction is not provided. When called from
1392   // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1393   // but then the result is not cached.
1394   intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1395 
1396   Result = intersect(LocalResult, InBlock);
1397   return true;
1398 }
1399 
1400 LVILatticeVal LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
1401                                                   Instruction *CxtI) {
1402   DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1403         << BB->getName() << "'\n");
1404 
1405   assert(BlockValueStack.empty() && BlockValueSet.empty());
1406   if (!hasBlockValue(V, BB)) {
1407     pushBlockValue(std::make_pair(BB, V));
1408     solve();
1409   }
1410   LVILatticeVal Result = getBlockValue(V, BB);
1411   intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1412 
1413   DEBUG(dbgs() << "  Result = " << Result << "\n");
1414   return Result;
1415 }
1416 
1417 LVILatticeVal LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
1418   DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1419         << CxtI->getName() << "'\n");
1420 
1421   if (auto *C = dyn_cast<Constant>(V))
1422     return LVILatticeVal::get(C);
1423 
1424   LVILatticeVal Result = LVILatticeVal::getOverdefined();
1425   if (auto *I = dyn_cast<Instruction>(V))
1426     Result = getFromRangeMetadata(I);
1427   intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1428 
1429   DEBUG(dbgs() << "  Result = " << Result << "\n");
1430   return Result;
1431 }
1432 
1433 LVILatticeVal LazyValueInfoImpl::
1434 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1435                Instruction *CxtI) {
1436   DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1437         << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
1438 
1439   LVILatticeVal Result;
1440   if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1441     solve();
1442     bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1443     (void)WasFastQuery;
1444     assert(WasFastQuery && "More work to do after problem solved?");
1445   }
1446 
1447   DEBUG(dbgs() << "  Result = " << Result << "\n");
1448   return Result;
1449 }
1450 
1451 void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1452                                    BasicBlock *NewSucc) {
1453   TheCache.threadEdgeImpl(OldSucc, NewSucc);
1454 }
1455 
1456 //===----------------------------------------------------------------------===//
1457 //                            LazyValueInfo Impl
1458 //===----------------------------------------------------------------------===//
1459 
1460 /// This lazily constructs the LazyValueInfoImpl.
1461 static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1462                                   const DataLayout *DL,
1463                                   DominatorTree *DT = nullptr) {
1464   if (!PImpl) {
1465     assert(DL && "getCache() called with a null DataLayout");
1466     PImpl = new LazyValueInfoImpl(AC, *DL, DT);
1467   }
1468   return *static_cast<LazyValueInfoImpl*>(PImpl);
1469 }
1470 
1471 bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1472   Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1473   const DataLayout &DL = F.getParent()->getDataLayout();
1474 
1475   DominatorTreeWrapperPass *DTWP =
1476       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1477   Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1478   Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1479 
1480   if (Info.PImpl)
1481     getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear();
1482 
1483   // Fully lazy.
1484   return false;
1485 }
1486 
1487 void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1488   AU.setPreservesAll();
1489   AU.addRequired<AssumptionCacheTracker>();
1490   AU.addRequired<TargetLibraryInfoWrapperPass>();
1491 }
1492 
1493 LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1494 
1495 LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1496 
1497 void LazyValueInfo::releaseMemory() {
1498   // If the cache was allocated, free it.
1499   if (PImpl) {
1500     delete &getImpl(PImpl, AC, nullptr);
1501     PImpl = nullptr;
1502   }
1503 }
1504 
1505 void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1506 
1507 LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1508   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1509   auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1510   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1511 
1512   return LazyValueInfo(&AC, &TLI, DT);
1513 }
1514 
1515 /// Returns true if we can statically tell that this value will never be a
1516 /// "useful" constant.  In practice, this means we've got something like an
1517 /// alloca or a malloc call for which a comparison against a constant can
1518 /// only be guarding dead code.  Note that we are potentially giving up some
1519 /// precision in dead code (a constant result) in favour of avoiding a
1520 /// expensive search for a easily answered common query.
1521 static bool isKnownNonConstant(Value *V) {
1522   V = V->stripPointerCasts();
1523   // The return val of alloc cannot be a Constant.
1524   if (isa<AllocaInst>(V))
1525     return true;
1526   return false;
1527 }
1528 
1529 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1530                                      Instruction *CxtI) {
1531   // Bail out early if V is known not to be a Constant.
1532   if (isKnownNonConstant(V))
1533     return nullptr;
1534 
1535   const DataLayout &DL = BB->getModule()->getDataLayout();
1536   LVILatticeVal Result =
1537       getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1538 
1539   if (Result.isConstant())
1540     return Result.getConstant();
1541   if (Result.isConstantRange()) {
1542     ConstantRange CR = Result.getConstantRange();
1543     if (const APInt *SingleVal = CR.getSingleElement())
1544       return ConstantInt::get(V->getContext(), *SingleVal);
1545   }
1546   return nullptr;
1547 }
1548 
1549 ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
1550                                               Instruction *CxtI) {
1551   assert(V->getType()->isIntegerTy());
1552   unsigned Width = V->getType()->getIntegerBitWidth();
1553   const DataLayout &DL = BB->getModule()->getDataLayout();
1554   LVILatticeVal Result =
1555       getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1556   if (Result.isUndefined())
1557     return ConstantRange(Width, /*isFullSet=*/false);
1558   if (Result.isConstantRange())
1559     return Result.getConstantRange();
1560   // We represent ConstantInt constants as constant ranges but other kinds
1561   // of integer constants, i.e. ConstantExpr will be tagged as constants
1562   assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1563          "ConstantInt value must be represented as constantrange");
1564   return ConstantRange(Width, /*isFullSet=*/true);
1565 }
1566 
1567 /// Determine whether the specified value is known to be a
1568 /// constant on the specified edge. Return null if not.
1569 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1570                                            BasicBlock *ToBB,
1571                                            Instruction *CxtI) {
1572   const DataLayout &DL = FromBB->getModule()->getDataLayout();
1573   LVILatticeVal Result =
1574       getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1575 
1576   if (Result.isConstant())
1577     return Result.getConstant();
1578   if (Result.isConstantRange()) {
1579     ConstantRange CR = Result.getConstantRange();
1580     if (const APInt *SingleVal = CR.getSingleElement())
1581       return ConstantInt::get(V->getContext(), *SingleVal);
1582   }
1583   return nullptr;
1584 }
1585 
1586 static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1587                                                   LVILatticeVal &Result,
1588                                                   const DataLayout &DL,
1589                                                   TargetLibraryInfo *TLI) {
1590 
1591   // If we know the value is a constant, evaluate the conditional.
1592   Constant *Res = nullptr;
1593   if (Result.isConstant()) {
1594     Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
1595                                           TLI);
1596     if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1597       return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1598     return LazyValueInfo::Unknown;
1599   }
1600 
1601   if (Result.isConstantRange()) {
1602     ConstantInt *CI = dyn_cast<ConstantInt>(C);
1603     if (!CI) return LazyValueInfo::Unknown;
1604 
1605     ConstantRange CR = Result.getConstantRange();
1606     if (Pred == ICmpInst::ICMP_EQ) {
1607       if (!CR.contains(CI->getValue()))
1608         return LazyValueInfo::False;
1609 
1610       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1611         return LazyValueInfo::True;
1612     } else if (Pred == ICmpInst::ICMP_NE) {
1613       if (!CR.contains(CI->getValue()))
1614         return LazyValueInfo::True;
1615 
1616       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1617         return LazyValueInfo::False;
1618     }
1619 
1620     // Handle more complex predicates.
1621     ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1622         (ICmpInst::Predicate)Pred, CI->getValue());
1623     if (TrueValues.contains(CR))
1624       return LazyValueInfo::True;
1625     if (TrueValues.inverse().contains(CR))
1626       return LazyValueInfo::False;
1627     return LazyValueInfo::Unknown;
1628   }
1629 
1630   if (Result.isNotConstant()) {
1631     // If this is an equality comparison, we can try to fold it knowing that
1632     // "V != C1".
1633     if (Pred == ICmpInst::ICMP_EQ) {
1634       // !C1 == C -> false iff C1 == C.
1635       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1636                                             Result.getNotConstant(), C, DL,
1637                                             TLI);
1638       if (Res->isNullValue())
1639         return LazyValueInfo::False;
1640     } else if (Pred == ICmpInst::ICMP_NE) {
1641       // !C1 != C -> true iff C1 == C.
1642       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1643                                             Result.getNotConstant(), C, DL,
1644                                             TLI);
1645       if (Res->isNullValue())
1646         return LazyValueInfo::True;
1647     }
1648     return LazyValueInfo::Unknown;
1649   }
1650 
1651   return LazyValueInfo::Unknown;
1652 }
1653 
1654 /// Determine whether the specified value comparison with a constant is known to
1655 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1656 LazyValueInfo::Tristate
1657 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1658                                   BasicBlock *FromBB, BasicBlock *ToBB,
1659                                   Instruction *CxtI) {
1660   const DataLayout &DL = FromBB->getModule()->getDataLayout();
1661   LVILatticeVal Result =
1662       getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1663 
1664   return getPredicateResult(Pred, C, Result, DL, TLI);
1665 }
1666 
1667 LazyValueInfo::Tristate
1668 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1669                               Instruction *CxtI) {
1670   // Is or is not NonNull are common predicates being queried. If
1671   // isKnownNonNull can tell us the result of the predicate, we can
1672   // return it quickly. But this is only a fastpath, and falling
1673   // through would still be correct.
1674   if (V->getType()->isPointerTy() && C->isNullValue() &&
1675       isKnownNonNull(V->stripPointerCasts())) {
1676     if (Pred == ICmpInst::ICMP_EQ)
1677       return LazyValueInfo::False;
1678     else if (Pred == ICmpInst::ICMP_NE)
1679       return LazyValueInfo::True;
1680   }
1681   const DataLayout &DL = CxtI->getModule()->getDataLayout();
1682   LVILatticeVal Result = getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
1683   Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1684   if (Ret != Unknown)
1685     return Ret;
1686 
1687   // Note: The following bit of code is somewhat distinct from the rest of LVI;
1688   // LVI as a whole tries to compute a lattice value which is conservatively
1689   // correct at a given location.  In this case, we have a predicate which we
1690   // weren't able to prove about the merged result, and we're pushing that
1691   // predicate back along each incoming edge to see if we can prove it
1692   // separately for each input.  As a motivating example, consider:
1693   // bb1:
1694   //   %v1 = ... ; constantrange<1, 5>
1695   //   br label %merge
1696   // bb2:
1697   //   %v2 = ... ; constantrange<10, 20>
1698   //   br label %merge
1699   // merge:
1700   //   %phi = phi [%v1, %v2] ; constantrange<1,20>
1701   //   %pred = icmp eq i32 %phi, 8
1702   // We can't tell from the lattice value for '%phi' that '%pred' is false
1703   // along each path, but by checking the predicate over each input separately,
1704   // we can.
1705   // We limit the search to one step backwards from the current BB and value.
1706   // We could consider extending this to search further backwards through the
1707   // CFG and/or value graph, but there are non-obvious compile time vs quality
1708   // tradeoffs.
1709   if (CxtI) {
1710     BasicBlock *BB = CxtI->getParent();
1711 
1712     // Function entry or an unreachable block.  Bail to avoid confusing
1713     // analysis below.
1714     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1715     if (PI == PE)
1716       return Unknown;
1717 
1718     // If V is a PHI node in the same block as the context, we need to ask
1719     // questions about the predicate as applied to the incoming value along
1720     // each edge. This is useful for eliminating cases where the predicate is
1721     // known along all incoming edges.
1722     if (auto *PHI = dyn_cast<PHINode>(V))
1723       if (PHI->getParent() == BB) {
1724         Tristate Baseline = Unknown;
1725         for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1726           Value *Incoming = PHI->getIncomingValue(i);
1727           BasicBlock *PredBB = PHI->getIncomingBlock(i);
1728           // Note that PredBB may be BB itself.
1729           Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1730                                                CxtI);
1731 
1732           // Keep going as long as we've seen a consistent known result for
1733           // all inputs.
1734           Baseline = (i == 0) ? Result /* First iteration */
1735             : (Baseline == Result ? Baseline : Unknown); /* All others */
1736           if (Baseline == Unknown)
1737             break;
1738         }
1739         if (Baseline != Unknown)
1740           return Baseline;
1741       }
1742 
1743     // For a comparison where the V is outside this block, it's possible
1744     // that we've branched on it before. Look to see if the value is known
1745     // on all incoming edges.
1746     if (!isa<Instruction>(V) ||
1747         cast<Instruction>(V)->getParent() != BB) {
1748       // For predecessor edge, determine if the comparison is true or false
1749       // on that edge. If they're all true or all false, we can conclude
1750       // the value of the comparison in this block.
1751       Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1752       if (Baseline != Unknown) {
1753         // Check that all remaining incoming values match the first one.
1754         while (++PI != PE) {
1755           Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1756           if (Ret != Baseline) break;
1757         }
1758         // If we terminated early, then one of the values didn't match.
1759         if (PI == PE) {
1760           return Baseline;
1761         }
1762       }
1763     }
1764   }
1765   return Unknown;
1766 }
1767 
1768 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1769                                BasicBlock *NewSucc) {
1770   if (PImpl) {
1771     const DataLayout &DL = PredBB->getModule()->getDataLayout();
1772     getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1773   }
1774 }
1775 
1776 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1777   if (PImpl) {
1778     const DataLayout &DL = BB->getModule()->getDataLayout();
1779     getImpl(PImpl, AC, &DL, DT).eraseBlock(BB);
1780   }
1781 }
1782