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