1 //===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interface for lazy computation of value constraint
10 // information.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/LazyValueInfo.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/ValueLattice.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/AssemblyAnnotationWriter.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/IR/ValueHandle.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/KnownBits.h"
40 #include "llvm/Support/raw_ostream.h"
41 using namespace llvm;
42 using namespace PatternMatch;
43 
44 #define DEBUG_TYPE "lazy-value-info"
45 
46 // This is the number of worklist items we will process to try to discover an
47 // answer for a given value.
48 static const unsigned MaxProcessedPerValue = 500;
49 
50 char LazyValueInfoWrapperPass::ID = 0;
51 LazyValueInfoWrapperPass::LazyValueInfoWrapperPass() : FunctionPass(ID) {
52   initializeLazyValueInfoWrapperPassPass(*PassRegistry::getPassRegistry());
53 }
54 INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
55                 "Lazy Value Information Analysis", false, true)
56 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
57 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
58 INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
59                 "Lazy Value Information Analysis", false, true)
60 
61 namespace llvm {
62   FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
63 }
64 
65 AnalysisKey LazyValueAnalysis::Key;
66 
67 /// Returns true if this lattice value represents at most one possible value.
68 /// This is as precise as any lattice value can get while still representing
69 /// reachable code.
70 static bool hasSingleValue(const ValueLatticeElement &Val) {
71   if (Val.isConstantRange() &&
72       Val.getConstantRange().isSingleElement())
73     // Integer constants are single element ranges
74     return true;
75   if (Val.isConstant())
76     // Non integer constants
77     return true;
78   return false;
79 }
80 
81 /// Combine two sets of facts about the same value into a single set of
82 /// facts.  Note that this method is not suitable for merging facts along
83 /// different paths in a CFG; that's what the mergeIn function is for.  This
84 /// is for merging facts gathered about the same value at the same location
85 /// through two independent means.
86 /// Notes:
87 /// * This method does not promise to return the most precise possible lattice
88 ///   value implied by A and B.  It is allowed to return any lattice element
89 ///   which is at least as strong as *either* A or B (unless our facts
90 ///   conflict, see below).
91 /// * Due to unreachable code, the intersection of two lattice values could be
92 ///   contradictory.  If this happens, we return some valid lattice value so as
93 ///   not confuse the rest of LVI.  Ideally, we'd always return Undefined, but
94 ///   we do not make this guarantee.  TODO: This would be a useful enhancement.
95 static ValueLatticeElement intersect(const ValueLatticeElement &A,
96                                      const ValueLatticeElement &B) {
97   // Undefined is the strongest state.  It means the value is known to be along
98   // an unreachable path.
99   if (A.isUnknown())
100     return A;
101   if (B.isUnknown())
102     return B;
103 
104   // If we gave up for one, but got a useable fact from the other, use it.
105   if (A.isOverdefined())
106     return B;
107   if (B.isOverdefined())
108     return A;
109 
110   // Can't get any more precise than constants.
111   if (hasSingleValue(A))
112     return A;
113   if (hasSingleValue(B))
114     return B;
115 
116   // Could be either constant range or not constant here.
117   if (!A.isConstantRange() || !B.isConstantRange()) {
118     // TODO: Arbitrary choice, could be improved
119     return A;
120   }
121 
122   // Intersect two constant ranges
123   ConstantRange Range =
124       A.getConstantRange().intersectWith(B.getConstantRange());
125   // Note: An empty range is implicitly converted to unknown or undef depending
126   // on MayIncludeUndef internally.
127   return ValueLatticeElement::getRange(
128       std::move(Range), /*MayIncludeUndef=*/A.isConstantRangeIncludingUndef() ||
129                             B.isConstantRangeIncludingUndef());
130 }
131 
132 //===----------------------------------------------------------------------===//
133 //                          LazyValueInfoCache Decl
134 //===----------------------------------------------------------------------===//
135 
136 namespace {
137   /// A callback value handle updates the cache when values are erased.
138   class LazyValueInfoCache;
139   struct LVIValueHandle final : public CallbackVH {
140     LazyValueInfoCache *Parent;
141 
142     LVIValueHandle(Value *V, LazyValueInfoCache *P = nullptr)
143       : CallbackVH(V), Parent(P) { }
144 
145     void deleted() override;
146     void allUsesReplacedWith(Value *V) override {
147       deleted();
148     }
149   };
150 } // end anonymous namespace
151 
152 namespace {
153   using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
154 
155   /// This is the cache kept by LazyValueInfo which
156   /// maintains information about queries across the clients' queries.
157   class LazyValueInfoCache {
158     /// This is all of the cached information for one basic block. It contains
159     /// the per-value lattice elements, as well as a separate set for
160     /// overdefined values to reduce memory usage. Additionally pointers
161     /// dereferenced in the block are cached for nullability queries.
162     struct BlockCacheEntry {
163       SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
164       SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
165       // None indicates that the nonnull pointers for this basic block
166       // block have not been computed yet.
167       Optional<NonNullPointerSet> NonNullPointers;
168     };
169 
170     /// Cached information per basic block.
171     DenseMap<PoisoningVH<BasicBlock>, std::unique_ptr<BlockCacheEntry>>
172         BlockCache;
173     /// Set of value handles used to erase values from the cache on deletion.
174     DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
175 
176     const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
177       auto It = BlockCache.find_as(BB);
178       if (It == BlockCache.end())
179         return nullptr;
180       return It->second.get();
181     }
182 
183     BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
184       auto It = BlockCache.find_as(BB);
185       if (It == BlockCache.end())
186         It = BlockCache.insert({ BB, std::make_unique<BlockCacheEntry>() })
187                        .first;
188 
189       return It->second.get();
190     }
191 
192     void addValueHandle(Value *Val) {
193       auto HandleIt = ValueHandles.find_as(Val);
194       if (HandleIt == ValueHandles.end())
195         ValueHandles.insert({ Val, this });
196     }
197 
198   public:
199     void insertResult(Value *Val, BasicBlock *BB,
200                       const ValueLatticeElement &Result) {
201       BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
202 
203       // Insert over-defined values into their own cache to reduce memory
204       // overhead.
205       if (Result.isOverdefined())
206         Entry->OverDefined.insert(Val);
207       else
208         Entry->LatticeElements.insert({ Val, Result });
209 
210       addValueHandle(Val);
211     }
212 
213     Optional<ValueLatticeElement> getCachedValueInfo(Value *V,
214                                                      BasicBlock *BB) const {
215       const BlockCacheEntry *Entry = getBlockEntry(BB);
216       if (!Entry)
217         return None;
218 
219       if (Entry->OverDefined.count(V))
220         return ValueLatticeElement::getOverdefined();
221 
222       auto LatticeIt = Entry->LatticeElements.find_as(V);
223       if (LatticeIt == Entry->LatticeElements.end())
224         return None;
225 
226       return LatticeIt->second;
227     }
228 
229     bool isNonNullAtEndOfBlock(
230         Value *V, BasicBlock *BB,
231         function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
232       BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
233       if (!Entry->NonNullPointers) {
234         Entry->NonNullPointers = InitFn(BB);
235         for (Value *V : *Entry->NonNullPointers)
236           addValueHandle(V);
237       }
238 
239       return Entry->NonNullPointers->count(V);
240     }
241 
242     /// clear - Empty the cache.
243     void clear() {
244       BlockCache.clear();
245       ValueHandles.clear();
246     }
247 
248     /// Inform the cache that a given value has been deleted.
249     void eraseValue(Value *V);
250 
251     /// This is part of the update interface to inform the cache
252     /// that a block has been deleted.
253     void eraseBlock(BasicBlock *BB);
254 
255     /// Updates the cache to remove any influence an overdefined value in
256     /// OldSucc might have (unless also overdefined in NewSucc).  This just
257     /// flushes elements from the cache and does not add any.
258     void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
259   };
260 }
261 
262 void LazyValueInfoCache::eraseValue(Value *V) {
263   for (auto &Pair : BlockCache) {
264     Pair.second->LatticeElements.erase(V);
265     Pair.second->OverDefined.erase(V);
266     if (Pair.second->NonNullPointers)
267       Pair.second->NonNullPointers->erase(V);
268   }
269 
270   auto HandleIt = ValueHandles.find_as(V);
271   if (HandleIt != ValueHandles.end())
272     ValueHandles.erase(HandleIt);
273 }
274 
275 void LVIValueHandle::deleted() {
276   // This erasure deallocates *this, so it MUST happen after we're done
277   // using any and all members of *this.
278   Parent->eraseValue(*this);
279 }
280 
281 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
282   BlockCache.erase(BB);
283 }
284 
285 void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
286                                         BasicBlock *NewSucc) {
287   // When an edge in the graph has been threaded, values that we could not
288   // determine a value for before (i.e. were marked overdefined) may be
289   // possible to solve now. We do NOT try to proactively update these values.
290   // Instead, we clear their entries from the cache, and allow lazy updating to
291   // recompute them when needed.
292 
293   // The updating process is fairly simple: we need to drop cached info
294   // for all values that were marked overdefined in OldSucc, and for those same
295   // values in any successor of OldSucc (except NewSucc) in which they were
296   // also marked overdefined.
297   std::vector<BasicBlock*> worklist;
298   worklist.push_back(OldSucc);
299 
300   const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
301   if (!Entry || Entry->OverDefined.empty())
302     return; // Nothing to process here.
303   SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
304                                       Entry->OverDefined.end());
305 
306   // Use a worklist to perform a depth-first search of OldSucc's successors.
307   // NOTE: We do not need a visited list since any blocks we have already
308   // visited will have had their overdefined markers cleared already, and we
309   // thus won't loop to their successors.
310   while (!worklist.empty()) {
311     BasicBlock *ToUpdate = worklist.back();
312     worklist.pop_back();
313 
314     // Skip blocks only accessible through NewSucc.
315     if (ToUpdate == NewSucc) continue;
316 
317     // If a value was marked overdefined in OldSucc, and is here too...
318     auto OI = BlockCache.find_as(ToUpdate);
319     if (OI == BlockCache.end() || OI->second->OverDefined.empty())
320       continue;
321     auto &ValueSet = OI->second->OverDefined;
322 
323     bool changed = false;
324     for (Value *V : ValsToClear) {
325       if (!ValueSet.erase(V))
326         continue;
327 
328       // If we removed anything, then we potentially need to update
329       // blocks successors too.
330       changed = true;
331     }
332 
333     if (!changed) continue;
334 
335     llvm::append_range(worklist, successors(ToUpdate));
336   }
337 }
338 
339 
340 namespace {
341 /// An assembly annotator class to print LazyValueCache information in
342 /// comments.
343 class LazyValueInfoImpl;
344 class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
345   LazyValueInfoImpl *LVIImpl;
346   // While analyzing which blocks we can solve values for, we need the dominator
347   // information.
348   DominatorTree &DT;
349 
350 public:
351   LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
352       : LVIImpl(L), DT(DTree) {}
353 
354   void emitBasicBlockStartAnnot(const BasicBlock *BB,
355                                 formatted_raw_ostream &OS) override;
356 
357   void emitInstructionAnnot(const Instruction *I,
358                             formatted_raw_ostream &OS) override;
359 };
360 }
361 namespace {
362 // The actual implementation of the lazy analysis and update.  Note that the
363 // inheritance from LazyValueInfoCache is intended to be temporary while
364 // splitting the code and then transitioning to a has-a relationship.
365 class LazyValueInfoImpl {
366 
367   /// Cached results from previous queries
368   LazyValueInfoCache TheCache;
369 
370   /// This stack holds the state of the value solver during a query.
371   /// It basically emulates the callstack of the naive
372   /// recursive value lookup process.
373   SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
374 
375   /// Keeps track of which block-value pairs are in BlockValueStack.
376   DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
377 
378   /// Push BV onto BlockValueStack unless it's already in there.
379   /// Returns true on success.
380   bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
381     if (!BlockValueSet.insert(BV).second)
382       return false;  // It's already in the stack.
383 
384     LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "
385                       << BV.first->getName() << "\n");
386     BlockValueStack.push_back(BV);
387     return true;
388   }
389 
390   AssumptionCache *AC;  ///< A pointer to the cache of @llvm.assume calls.
391   const DataLayout &DL; ///< A mandatory DataLayout
392 
393   /// Declaration of the llvm.experimental.guard() intrinsic,
394   /// if it exists in the module.
395   Function *GuardDecl;
396 
397   Optional<ValueLatticeElement> getBlockValue(Value *Val, BasicBlock *BB,
398                                               Instruction *CxtI);
399   Optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
400                                 BasicBlock *T, Instruction *CxtI = nullptr);
401 
402   // These methods process one work item and may add more. A false value
403   // returned means that the work item was not completely processed and must
404   // be revisited after going through the new items.
405   bool solveBlockValue(Value *Val, BasicBlock *BB);
406   Optional<ValueLatticeElement> solveBlockValueImpl(Value *Val, BasicBlock *BB);
407   Optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
408                                                         BasicBlock *BB);
409   Optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
410                                                        BasicBlock *BB);
411   Optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
412                                                       BasicBlock *BB);
413   Optional<ConstantRange> getRangeFor(Value *V, Instruction *CxtI,
414                                       BasicBlock *BB);
415   Optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
416       Instruction *I, BasicBlock *BB,
417       std::function<ConstantRange(const ConstantRange &,
418                                   const ConstantRange &)> OpFn);
419   Optional<ValueLatticeElement> solveBlockValueBinaryOp(BinaryOperator *BBI,
420                                                         BasicBlock *BB);
421   Optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
422                                                     BasicBlock *BB);
423   Optional<ValueLatticeElement> solveBlockValueOverflowIntrinsic(
424       WithOverflowInst *WO, BasicBlock *BB);
425   Optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
426                                                          BasicBlock *BB);
427   Optional<ValueLatticeElement> solveBlockValueExtractValue(
428       ExtractValueInst *EVI, BasicBlock *BB);
429   bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
430   void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
431                                                      ValueLatticeElement &BBLV,
432                                                      Instruction *BBI);
433 
434   void solve();
435 
436 public:
437   /// This is the query interface to determine the lattice value for the
438   /// specified Value* at the context instruction (if specified) or at the
439   /// start of the block.
440   ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB,
441                                       Instruction *CxtI = nullptr);
442 
443   /// This is the query interface to determine the lattice value for the
444   /// specified Value* at the specified instruction using only information
445   /// from assumes/guards and range metadata. Unlike getValueInBlock(), no
446   /// recursive query is performed.
447   ValueLatticeElement getValueAt(Value *V, Instruction *CxtI);
448 
449   /// This is the query interface to determine the lattice
450   /// value for the specified Value* that is true on the specified edge.
451   ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB,
452                                      BasicBlock *ToBB,
453                                      Instruction *CxtI = nullptr);
454 
455   /// Complete flush all previously computed values
456   void clear() {
457     TheCache.clear();
458   }
459 
460   /// Printing the LazyValueInfo Analysis.
461   void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
462     LazyValueInfoAnnotatedWriter Writer(this, DTree);
463     F.print(OS, &Writer);
464   }
465 
466   /// This is part of the update interface to inform the cache
467   /// that a block has been deleted.
468   void eraseBlock(BasicBlock *BB) {
469     TheCache.eraseBlock(BB);
470   }
471 
472   /// This is the update interface to inform the cache that an edge from
473   /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
474   void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
475 
476   LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
477                     Function *GuardDecl)
478       : AC(AC), DL(DL), GuardDecl(GuardDecl) {}
479 };
480 } // end anonymous namespace
481 
482 
483 void LazyValueInfoImpl::solve() {
484   SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
485       BlockValueStack.begin(), BlockValueStack.end());
486 
487   unsigned processedCount = 0;
488   while (!BlockValueStack.empty()) {
489     processedCount++;
490     // Abort if we have to process too many values to get a result for this one.
491     // Because of the design of the overdefined cache currently being per-block
492     // to avoid naming-related issues (IE it wants to try to give different
493     // results for the same name in different blocks), overdefined results don't
494     // get cached globally, which in turn means we will often try to rediscover
495     // the same overdefined result again and again.  Once something like
496     // PredicateInfo is used in LVI or CVP, we should be able to make the
497     // overdefined cache global, and remove this throttle.
498     if (processedCount > MaxProcessedPerValue) {
499       LLVM_DEBUG(
500           dbgs() << "Giving up on stack because we are getting too deep\n");
501       // Fill in the original values
502       while (!StartingStack.empty()) {
503         std::pair<BasicBlock *, Value *> &e = StartingStack.back();
504         TheCache.insertResult(e.second, e.first,
505                               ValueLatticeElement::getOverdefined());
506         StartingStack.pop_back();
507       }
508       BlockValueSet.clear();
509       BlockValueStack.clear();
510       return;
511     }
512     std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
513     assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
514 
515     if (solveBlockValue(e.second, e.first)) {
516       // The work item was completely processed.
517       assert(BlockValueStack.back() == e && "Nothing should have been pushed!");
518 #ifndef NDEBUG
519       Optional<ValueLatticeElement> BBLV =
520           TheCache.getCachedValueInfo(e.second, e.first);
521       assert(BBLV && "Result should be in cache!");
522       LLVM_DEBUG(
523           dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
524                  << *BBLV << "\n");
525 #endif
526 
527       BlockValueStack.pop_back();
528       BlockValueSet.erase(e);
529     } else {
530       // More work needs to be done before revisiting.
531       assert(BlockValueStack.back() != e && "Stack should have been pushed!");
532     }
533   }
534 }
535 
536 Optional<ValueLatticeElement> LazyValueInfoImpl::getBlockValue(
537     Value *Val, BasicBlock *BB, Instruction *CxtI) {
538   // If already a constant, there is nothing to compute.
539   if (Constant *VC = dyn_cast<Constant>(Val))
540     return ValueLatticeElement::get(VC);
541 
542   if (Optional<ValueLatticeElement> OptLatticeVal =
543           TheCache.getCachedValueInfo(Val, BB)) {
544     intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CxtI);
545     return OptLatticeVal;
546   }
547 
548   // We have hit a cycle, assume overdefined.
549   if (!pushBlockValue({ BB, Val }))
550     return ValueLatticeElement::getOverdefined();
551 
552   // Yet to be resolved.
553   return None;
554 }
555 
556 static ValueLatticeElement getFromRangeMetadata(Instruction *BBI) {
557   switch (BBI->getOpcode()) {
558   default: break;
559   case Instruction::Load:
560   case Instruction::Call:
561   case Instruction::Invoke:
562     if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
563       if (isa<IntegerType>(BBI->getType())) {
564         return ValueLatticeElement::getRange(
565             getConstantRangeFromMetadata(*Ranges));
566       }
567     break;
568   };
569   // Nothing known - will be intersected with other facts
570   return ValueLatticeElement::getOverdefined();
571 }
572 
573 bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
574   assert(!isa<Constant>(Val) && "Value should not be constant");
575   assert(!TheCache.getCachedValueInfo(Val, BB) &&
576          "Value should not be in cache");
577 
578   // Hold off inserting this value into the Cache in case we have to return
579   // false and come back later.
580   Optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
581   if (!Res)
582     // Work pushed, will revisit
583     return false;
584 
585   TheCache.insertResult(Val, BB, *Res);
586   return true;
587 }
588 
589 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueImpl(
590     Value *Val, BasicBlock *BB) {
591   Instruction *BBI = dyn_cast<Instruction>(Val);
592   if (!BBI || BBI->getParent() != BB)
593     return solveBlockValueNonLocal(Val, BB);
594 
595   if (PHINode *PN = dyn_cast<PHINode>(BBI))
596     return solveBlockValuePHINode(PN, BB);
597 
598   if (auto *SI = dyn_cast<SelectInst>(BBI))
599     return solveBlockValueSelect(SI, BB);
600 
601   // If this value is a nonnull pointer, record it's range and bailout.  Note
602   // that for all other pointer typed values, we terminate the search at the
603   // definition.  We could easily extend this to look through geps, bitcasts,
604   // and the like to prove non-nullness, but it's not clear that's worth it
605   // compile time wise.  The context-insensitive value walk done inside
606   // isKnownNonZero gets most of the profitable cases at much less expense.
607   // This does mean that we have a sensitivity to where the defining
608   // instruction is placed, even if it could legally be hoisted much higher.
609   // That is unfortunate.
610   PointerType *PT = dyn_cast<PointerType>(BBI->getType());
611   if (PT && isKnownNonZero(BBI, DL))
612     return ValueLatticeElement::getNot(ConstantPointerNull::get(PT));
613 
614   if (BBI->getType()->isIntegerTy()) {
615     if (auto *CI = dyn_cast<CastInst>(BBI))
616       return solveBlockValueCast(CI, BB);
617 
618     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
619       return solveBlockValueBinaryOp(BO, BB);
620 
621     if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
622       return solveBlockValueExtractValue(EVI, BB);
623 
624     if (auto *II = dyn_cast<IntrinsicInst>(BBI))
625       return solveBlockValueIntrinsic(II, BB);
626   }
627 
628   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
629                     << "' - unknown inst def found.\n");
630   return getFromRangeMetadata(BBI);
631 }
632 
633 static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet) {
634   // TODO: Use NullPointerIsDefined instead.
635   if (Ptr->getType()->getPointerAddressSpace() == 0)
636     PtrSet.insert(getUnderlyingObject(Ptr));
637 }
638 
639 static void AddNonNullPointersByInstruction(
640     Instruction *I, NonNullPointerSet &PtrSet) {
641   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
642     AddNonNullPointer(L->getPointerOperand(), PtrSet);
643   } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
644     AddNonNullPointer(S->getPointerOperand(), PtrSet);
645   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
646     if (MI->isVolatile()) return;
647 
648     // FIXME: check whether it has a valuerange that excludes zero?
649     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
650     if (!Len || Len->isZero()) return;
651 
652     AddNonNullPointer(MI->getRawDest(), PtrSet);
653     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
654       AddNonNullPointer(MTI->getRawSource(), PtrSet);
655   }
656 }
657 
658 bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
659   if (NullPointerIsDefined(BB->getParent(),
660                            Val->getType()->getPointerAddressSpace()))
661     return false;
662 
663   Val = Val->stripInBoundsOffsets();
664   return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
665     NonNullPointerSet NonNullPointers;
666     for (Instruction &I : *BB)
667       AddNonNullPointersByInstruction(&I, NonNullPointers);
668     return NonNullPointers;
669   });
670 }
671 
672 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueNonLocal(
673     Value *Val, BasicBlock *BB) {
674   ValueLatticeElement Result;  // Start Undefined.
675 
676   // If this is the entry block, we must be asking about an argument.  The
677   // value is overdefined.
678   if (BB->isEntryBlock()) {
679     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
680     return ValueLatticeElement::getOverdefined();
681   }
682 
683   // Loop over all of our predecessors, merging what we know from them into
684   // result.  If we encounter an unexplored predecessor, we eagerly explore it
685   // in a depth first manner.  In practice, this has the effect of discovering
686   // paths we can't analyze eagerly without spending compile times analyzing
687   // other paths.  This heuristic benefits from the fact that predecessors are
688   // frequently arranged such that dominating ones come first and we quickly
689   // find a path to function entry.  TODO: We should consider explicitly
690   // canonicalizing to make this true rather than relying on this happy
691   // accident.
692   for (BasicBlock *Pred : predecessors(BB)) {
693     Optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
694     if (!EdgeResult)
695       // Explore that input, then return here
696       return None;
697 
698     Result.mergeIn(*EdgeResult);
699 
700     // If we hit overdefined, exit early.  The BlockVals entry is already set
701     // to overdefined.
702     if (Result.isOverdefined()) {
703       LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
704                         << "' - overdefined because of pred (non local).\n");
705       return Result;
706     }
707   }
708 
709   // Return the merged value, which is more precise than 'overdefined'.
710   assert(!Result.isOverdefined());
711   return Result;
712 }
713 
714 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValuePHINode(
715     PHINode *PN, BasicBlock *BB) {
716   ValueLatticeElement Result;  // Start Undefined.
717 
718   // Loop over all of our predecessors, merging what we know from them into
719   // result.  See the comment about the chosen traversal order in
720   // solveBlockValueNonLocal; the same reasoning applies here.
721   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
722     BasicBlock *PhiBB = PN->getIncomingBlock(i);
723     Value *PhiVal = PN->getIncomingValue(i);
724     // Note that we can provide PN as the context value to getEdgeValue, even
725     // though the results will be cached, because PN is the value being used as
726     // the cache key in the caller.
727     Optional<ValueLatticeElement> EdgeResult =
728         getEdgeValue(PhiVal, PhiBB, BB, PN);
729     if (!EdgeResult)
730       // Explore that input, then return here
731       return None;
732 
733     Result.mergeIn(*EdgeResult);
734 
735     // If we hit overdefined, exit early.  The BlockVals entry is already set
736     // to overdefined.
737     if (Result.isOverdefined()) {
738       LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
739                         << "' - overdefined because of pred (local).\n");
740 
741       return Result;
742     }
743   }
744 
745   // Return the merged value, which is more precise than 'overdefined'.
746   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
747   return Result;
748 }
749 
750 static ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
751                                                  bool isTrueDest = true);
752 
753 // If we can determine a constraint on the value given conditions assumed by
754 // the program, intersect those constraints with BBLV
755 void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
756         Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
757   BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
758   if (!BBI)
759     return;
760 
761   BasicBlock *BB = BBI->getParent();
762   for (auto &AssumeVH : AC->assumptionsFor(Val)) {
763     if (!AssumeVH)
764       continue;
765 
766     // Only check assumes in the block of the context instruction. Other
767     // assumes will have already been taken into account when the value was
768     // propagated from predecessor blocks.
769     auto *I = cast<CallInst>(AssumeVH);
770     if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
771       continue;
772 
773     BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
774   }
775 
776   // If guards are not used in the module, don't spend time looking for them
777   if (GuardDecl && !GuardDecl->use_empty() &&
778       BBI->getIterator() != BB->begin()) {
779     for (Instruction &I : make_range(std::next(BBI->getIterator().getReverse()),
780                                      BB->rend())) {
781       Value *Cond = nullptr;
782       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
783         BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
784     }
785   }
786 
787   if (BBLV.isOverdefined()) {
788     // Check whether we're checking at the terminator, and the pointer has
789     // been dereferenced in this block.
790     PointerType *PTy = dyn_cast<PointerType>(Val->getType());
791     if (PTy && BB->getTerminator() == BBI &&
792         isNonNullAtEndOfBlock(Val, BB))
793       BBLV = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
794   }
795 }
796 
797 static ConstantRange getConstantRangeOrFull(const ValueLatticeElement &Val,
798                                             Type *Ty, const DataLayout &DL) {
799   if (Val.isConstantRange())
800     return Val.getConstantRange();
801   return ConstantRange::getFull(DL.getTypeSizeInBits(Ty));
802 }
803 
804 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueSelect(
805     SelectInst *SI, BasicBlock *BB) {
806   // Recurse on our inputs if needed
807   Optional<ValueLatticeElement> OptTrueVal =
808       getBlockValue(SI->getTrueValue(), BB, SI);
809   if (!OptTrueVal)
810     return None;
811   ValueLatticeElement &TrueVal = *OptTrueVal;
812 
813   Optional<ValueLatticeElement> OptFalseVal =
814       getBlockValue(SI->getFalseValue(), BB, SI);
815   if (!OptFalseVal)
816     return None;
817   ValueLatticeElement &FalseVal = *OptFalseVal;
818 
819   if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
820     const ConstantRange &TrueCR =
821         getConstantRangeOrFull(TrueVal, SI->getType(), DL);
822     const ConstantRange &FalseCR =
823         getConstantRangeOrFull(FalseVal, SI->getType(), DL);
824     Value *LHS = nullptr;
825     Value *RHS = nullptr;
826     SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
827     // Is this a min specifically of our two inputs?  (Avoid the risk of
828     // ValueTracking getting smarter looking back past our immediate inputs.)
829     if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
830         ((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
831          (RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
832       ConstantRange ResultCR = [&]() {
833         switch (SPR.Flavor) {
834         default:
835           llvm_unreachable("unexpected minmax type!");
836         case SPF_SMIN:                   /// Signed minimum
837           return TrueCR.smin(FalseCR);
838         case SPF_UMIN:                   /// Unsigned minimum
839           return TrueCR.umin(FalseCR);
840         case SPF_SMAX:                   /// Signed maximum
841           return TrueCR.smax(FalseCR);
842         case SPF_UMAX:                   /// Unsigned maximum
843           return TrueCR.umax(FalseCR);
844         };
845       }();
846       return ValueLatticeElement::getRange(
847           ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
848                         FalseVal.isConstantRangeIncludingUndef());
849     }
850 
851     if (SPR.Flavor == SPF_ABS) {
852       if (LHS == SI->getTrueValue())
853         return ValueLatticeElement::getRange(
854             TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
855       if (LHS == SI->getFalseValue())
856         return ValueLatticeElement::getRange(
857             FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
858     }
859 
860     if (SPR.Flavor == SPF_NABS) {
861       ConstantRange Zero(APInt::getZero(TrueCR.getBitWidth()));
862       if (LHS == SI->getTrueValue())
863         return ValueLatticeElement::getRange(
864             Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
865       if (LHS == SI->getFalseValue())
866         return ValueLatticeElement::getRange(
867             Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
868     }
869   }
870 
871   // Can we constrain the facts about the true and false values by using the
872   // condition itself?  This shows up with idioms like e.g. select(a > 5, a, 5).
873   // TODO: We could potentially refine an overdefined true value above.
874   Value *Cond = SI->getCondition();
875   TrueVal = intersect(TrueVal,
876                       getValueFromCondition(SI->getTrueValue(), Cond, true));
877   FalseVal = intersect(FalseVal,
878                        getValueFromCondition(SI->getFalseValue(), Cond, false));
879 
880   ValueLatticeElement Result = TrueVal;
881   Result.mergeIn(FalseVal);
882   return Result;
883 }
884 
885 Optional<ConstantRange> LazyValueInfoImpl::getRangeFor(Value *V,
886                                                        Instruction *CxtI,
887                                                        BasicBlock *BB) {
888   Optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CxtI);
889   if (!OptVal)
890     return None;
891   return getConstantRangeOrFull(*OptVal, V->getType(), DL);
892 }
893 
894 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueCast(
895     CastInst *CI, BasicBlock *BB) {
896   // Without knowing how wide the input is, we can't analyze it in any useful
897   // way.
898   if (!CI->getOperand(0)->getType()->isSized())
899     return ValueLatticeElement::getOverdefined();
900 
901   // Filter out casts we don't know how to reason about before attempting to
902   // recurse on our operand.  This can cut a long search short if we know we're
903   // not going to be able to get any useful information anways.
904   switch (CI->getOpcode()) {
905   case Instruction::Trunc:
906   case Instruction::SExt:
907   case Instruction::ZExt:
908   case Instruction::BitCast:
909     break;
910   default:
911     // Unhandled instructions are overdefined.
912     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
913                       << "' - overdefined (unknown cast).\n");
914     return ValueLatticeElement::getOverdefined();
915   }
916 
917   // Figure out the range of the LHS.  If that fails, we still apply the
918   // transfer rule on the full set since we may be able to locally infer
919   // interesting facts.
920   Optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
921   if (!LHSRes.hasValue())
922     // More work to do before applying this transfer rule.
923     return None;
924   const ConstantRange &LHSRange = LHSRes.getValue();
925 
926   const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
927 
928   // NOTE: We're currently limited by the set of operations that ConstantRange
929   // can evaluate symbolically.  Enhancing that set will allows us to analyze
930   // more definitions.
931   return ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
932                                                        ResultBitWidth));
933 }
934 
935 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
936     Instruction *I, BasicBlock *BB,
937     std::function<ConstantRange(const ConstantRange &,
938                                 const ConstantRange &)> OpFn) {
939   // Figure out the ranges of the operands.  If that fails, use a
940   // conservative range, but apply the transfer rule anyways.  This
941   // lets us pick up facts from expressions like "and i32 (call i32
942   // @foo()), 32"
943   Optional<ConstantRange> LHSRes = getRangeFor(I->getOperand(0), I, BB);
944   Optional<ConstantRange> RHSRes = getRangeFor(I->getOperand(1), I, BB);
945   if (!LHSRes.hasValue() || !RHSRes.hasValue())
946     // More work to do before applying this transfer rule.
947     return None;
948 
949   const ConstantRange &LHSRange = LHSRes.getValue();
950   const ConstantRange &RHSRange = RHSRes.getValue();
951   return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
952 }
953 
954 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOp(
955     BinaryOperator *BO, BasicBlock *BB) {
956   assert(BO->getOperand(0)->getType()->isSized() &&
957          "all operands to binary operators are sized");
958   if (BO->getOpcode() == Instruction::Xor) {
959     // Xor is the only operation not supported by ConstantRange::binaryOp().
960     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
961                       << "' - overdefined (unknown binary operator).\n");
962     return ValueLatticeElement::getOverdefined();
963   }
964 
965   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
966     unsigned NoWrapKind = 0;
967     if (OBO->hasNoUnsignedWrap())
968       NoWrapKind |= OverflowingBinaryOperator::NoUnsignedWrap;
969     if (OBO->hasNoSignedWrap())
970       NoWrapKind |= OverflowingBinaryOperator::NoSignedWrap;
971 
972     return solveBlockValueBinaryOpImpl(
973         BO, BB,
974         [BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
975           return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
976         });
977   }
978 
979   return solveBlockValueBinaryOpImpl(
980       BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
981         return CR1.binaryOp(BO->getOpcode(), CR2);
982       });
983 }
984 
985 Optional<ValueLatticeElement>
986 LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
987                                                     BasicBlock *BB) {
988   return solveBlockValueBinaryOpImpl(
989       WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
990         return CR1.binaryOp(WO->getBinaryOp(), CR2);
991       });
992 }
993 
994 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueIntrinsic(
995     IntrinsicInst *II, BasicBlock *BB) {
996   if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
997     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
998                       << "' - unknown intrinsic.\n");
999     return getFromRangeMetadata(II);
1000   }
1001 
1002   SmallVector<ConstantRange, 2> OpRanges;
1003   for (Value *Op : II->args()) {
1004     Optional<ConstantRange> Range = getRangeFor(Op, II, BB);
1005     if (!Range)
1006       return None;
1007     OpRanges.push_back(*Range);
1008   }
1009 
1010   return ValueLatticeElement::getRange(
1011       ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges));
1012 }
1013 
1014 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueExtractValue(
1015     ExtractValueInst *EVI, BasicBlock *BB) {
1016   if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1017     if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
1018       return solveBlockValueOverflowIntrinsic(WO, BB);
1019 
1020   // Handle extractvalue of insertvalue to allow further simplification
1021   // based on replaced with.overflow intrinsics.
1022   if (Value *V = SimplifyExtractValueInst(
1023           EVI->getAggregateOperand(), EVI->getIndices(),
1024           EVI->getModule()->getDataLayout()))
1025     return getBlockValue(V, BB, EVI);
1026 
1027   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1028                     << "' - overdefined (unknown extractvalue).\n");
1029   return ValueLatticeElement::getOverdefined();
1030 }
1031 
1032 static bool matchICmpOperand(APInt &Offset, Value *LHS, Value *Val,
1033                              ICmpInst::Predicate Pred) {
1034   if (LHS == Val)
1035     return true;
1036 
1037   // Handle range checking idiom produced by InstCombine. We will subtract the
1038   // offset from the allowed range for RHS in this case.
1039   const APInt *C;
1040   if (match(LHS, m_Add(m_Specific(Val), m_APInt(C)))) {
1041     Offset = *C;
1042     return true;
1043   }
1044 
1045   // Handle the symmetric case. This appears in saturation patterns like
1046   // (x == 16) ? 16 : (x + 1).
1047   if (match(Val, m_Add(m_Specific(LHS), m_APInt(C)))) {
1048     Offset = -*C;
1049     return true;
1050   }
1051 
1052   // If (x | y) < C, then (x < C) && (y < C).
1053   if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
1054       (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE))
1055     return true;
1056 
1057   // If (x & y) > C, then (x > C) && (y > C).
1058   if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
1059       (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE))
1060     return true;
1061 
1062   return false;
1063 }
1064 
1065 /// Get value range for a "(Val + Offset) Pred RHS" condition.
1066 static ValueLatticeElement getValueFromSimpleICmpCondition(
1067     CmpInst::Predicate Pred, Value *RHS, const APInt &Offset) {
1068   ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1069                          /*isFullSet=*/true);
1070   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1071     RHSRange = ConstantRange(CI->getValue());
1072   else if (Instruction *I = dyn_cast<Instruction>(RHS))
1073     if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1074       RHSRange = getConstantRangeFromMetadata(*Ranges);
1075 
1076   ConstantRange TrueValues =
1077       ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1078   return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
1079 }
1080 
1081 static ValueLatticeElement getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1082                                                      bool isTrueDest) {
1083   Value *LHS = ICI->getOperand(0);
1084   Value *RHS = ICI->getOperand(1);
1085 
1086   // Get the predicate that must hold along the considered edge.
1087   CmpInst::Predicate EdgePred =
1088       isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
1089 
1090   if (isa<Constant>(RHS)) {
1091     if (ICI->isEquality() && LHS == Val) {
1092       if (EdgePred == ICmpInst::ICMP_EQ)
1093         return ValueLatticeElement::get(cast<Constant>(RHS));
1094       else if (!isa<UndefValue>(RHS))
1095         return ValueLatticeElement::getNot(cast<Constant>(RHS));
1096     }
1097   }
1098 
1099   Type *Ty = Val->getType();
1100   if (!Ty->isIntegerTy())
1101     return ValueLatticeElement::getOverdefined();
1102 
1103   unsigned BitWidth = Ty->getScalarSizeInBits();
1104   APInt Offset(BitWidth, 0);
1105   if (matchICmpOperand(Offset, LHS, Val, EdgePred))
1106     return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset);
1107 
1108   CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
1109   if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
1110     return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset);
1111 
1112   const APInt *Mask, *C;
1113   if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
1114       match(RHS, m_APInt(C))) {
1115     // If (Val & Mask) == C then all the masked bits are known and we can
1116     // compute a value range based on that.
1117     if (EdgePred == ICmpInst::ICMP_EQ) {
1118       KnownBits Known;
1119       Known.Zero = ~*C & *Mask;
1120       Known.One = *C & *Mask;
1121       return ValueLatticeElement::getRange(
1122           ConstantRange::fromKnownBits(Known, /*IsSigned*/ false));
1123     }
1124     // If (Val & Mask) != 0 then the value must be larger than the lowest set
1125     // bit of Mask.
1126     if (EdgePred == ICmpInst::ICMP_NE && !Mask->isZero() && C->isZero()) {
1127       return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
1128           APInt::getOneBitSet(BitWidth, Mask->countTrailingZeros()),
1129           APInt::getZero(BitWidth)));
1130     }
1131   }
1132 
1133   // If (X urem Modulus) >= C, then X >= C.
1134   // If trunc X >= C, then X >= C.
1135   // TODO: An upper bound could be computed as well.
1136   if (match(LHS, m_CombineOr(m_URem(m_Specific(Val), m_Value()),
1137                              m_Trunc(m_Specific(Val)))) &&
1138       match(RHS, m_APInt(C))) {
1139     // Use the icmp region so we don't have to deal with different predicates.
1140     ConstantRange CR = ConstantRange::makeExactICmpRegion(EdgePred, *C);
1141     if (!CR.isEmptySet())
1142       return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
1143           CR.getUnsignedMin().zextOrSelf(BitWidth), APInt(BitWidth, 0)));
1144   }
1145 
1146   return ValueLatticeElement::getOverdefined();
1147 }
1148 
1149 // Handle conditions of the form
1150 // extractvalue(op.with.overflow(%x, C), 1).
1151 static ValueLatticeElement getValueFromOverflowCondition(
1152     Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1153   // TODO: This only works with a constant RHS for now. We could also compute
1154   // the range of the RHS, but this doesn't fit into the current structure of
1155   // the edge value calculation.
1156   const APInt *C;
1157   if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1158     return ValueLatticeElement::getOverdefined();
1159 
1160   // Calculate the possible values of %x for which no overflow occurs.
1161   ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
1162       WO->getBinaryOp(), *C, WO->getNoWrapKind());
1163 
1164   // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1165   // constrained to it's inverse (all values that might cause overflow).
1166   if (IsTrueDest)
1167     NWR = NWR.inverse();
1168   return ValueLatticeElement::getRange(NWR);
1169 }
1170 
1171 static Optional<ValueLatticeElement>
1172 getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1173                           bool isRevisit,
1174                           SmallDenseMap<Value *, ValueLatticeElement> &Visited,
1175                           SmallVectorImpl<Value *> &Worklist) {
1176   if (!isRevisit) {
1177     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1178       return getValueFromICmpCondition(Val, ICI, isTrueDest);
1179 
1180     if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1181       if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1182         if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1183           return getValueFromOverflowCondition(Val, WO, isTrueDest);
1184   }
1185 
1186   Value *L, *R;
1187   bool IsAnd;
1188   if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
1189     IsAnd = true;
1190   else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1191     IsAnd = false;
1192   else
1193     return ValueLatticeElement::getOverdefined();
1194 
1195   auto LV = Visited.find(L);
1196   auto RV = Visited.find(R);
1197 
1198   // if (L && R) -> intersect L and R
1199   // if (!(L || R)) -> intersect L and R
1200   // if (L || R) -> union L and R
1201   // if (!(L && R)) -> union L and R
1202   if ((isTrueDest ^ IsAnd) && (LV != Visited.end())) {
1203     ValueLatticeElement V = LV->second;
1204     if (V.isOverdefined())
1205       return V;
1206     if (RV != Visited.end()) {
1207       V.mergeIn(RV->second);
1208       return V;
1209     }
1210   }
1211 
1212   if (LV == Visited.end() || RV == Visited.end()) {
1213     assert(!isRevisit);
1214     if (LV == Visited.end())
1215       Worklist.push_back(L);
1216     if (RV == Visited.end())
1217       Worklist.push_back(R);
1218     return None;
1219   }
1220 
1221   return intersect(LV->second, RV->second);
1222 }
1223 
1224 ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
1225                                           bool isTrueDest) {
1226   assert(Cond && "precondition");
1227   SmallDenseMap<Value*, ValueLatticeElement> Visited;
1228   SmallVector<Value *> Worklist;
1229 
1230   Worklist.push_back(Cond);
1231   do {
1232     Value *CurrentCond = Worklist.back();
1233     // Insert an Overdefined placeholder into the set to prevent
1234     // infinite recursion if there exists IRs that use not
1235     // dominated by its def as in this example:
1236     //   "%tmp3 = or i1 undef, %tmp4"
1237     //   "%tmp4 = or i1 undef, %tmp3"
1238     auto Iter =
1239         Visited.try_emplace(CurrentCond, ValueLatticeElement::getOverdefined());
1240     bool isRevisit = !Iter.second;
1241     Optional<ValueLatticeElement> Result = getValueFromConditionImpl(
1242         Val, CurrentCond, isTrueDest, isRevisit, Visited, Worklist);
1243     if (Result) {
1244       Visited[CurrentCond] = *Result;
1245       Worklist.pop_back();
1246     }
1247   } while (!Worklist.empty());
1248 
1249   auto Result = Visited.find(Cond);
1250   assert(Result != Visited.end());
1251   return Result->second;
1252 }
1253 
1254 // Return true if Usr has Op as an operand, otherwise false.
1255 static bool usesOperand(User *Usr, Value *Op) {
1256   return is_contained(Usr->operands(), Op);
1257 }
1258 
1259 // Return true if the instruction type of Val is supported by
1260 // constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1261 // Call this before calling constantFoldUser() to find out if it's even worth
1262 // attempting to call it.
1263 static bool isOperationFoldable(User *Usr) {
1264   return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
1265 }
1266 
1267 // Check if Usr can be simplified to an integer constant when the value of one
1268 // of its operands Op is an integer constant OpConstVal. If so, return it as an
1269 // lattice value range with a single element or otherwise return an overdefined
1270 // lattice value.
1271 static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
1272                                             const APInt &OpConstVal,
1273                                             const DataLayout &DL) {
1274   assert(isOperationFoldable(Usr) && "Precondition");
1275   Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1276   // Check if Usr can be simplified to a constant.
1277   if (auto *CI = dyn_cast<CastInst>(Usr)) {
1278     assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
1279     if (auto *C = dyn_cast_or_null<ConstantInt>(
1280             SimplifyCastInst(CI->getOpcode(), OpConst,
1281                              CI->getDestTy(), DL))) {
1282       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1283     }
1284   } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1285     bool Op0Match = BO->getOperand(0) == Op;
1286     bool Op1Match = BO->getOperand(1) == Op;
1287     assert((Op0Match || Op1Match) &&
1288            "Operand 0 nor Operand 1 isn't a match");
1289     Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1290     Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1291     if (auto *C = dyn_cast_or_null<ConstantInt>(
1292             SimplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1293       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1294     }
1295   } else if (isa<FreezeInst>(Usr)) {
1296     assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op");
1297     return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
1298   }
1299   return ValueLatticeElement::getOverdefined();
1300 }
1301 
1302 /// Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
1303 /// Val is not constrained on the edge.  Result is unspecified if return value
1304 /// is false.
1305 static Optional<ValueLatticeElement> getEdgeValueLocal(Value *Val,
1306                                                        BasicBlock *BBFrom,
1307                                                        BasicBlock *BBTo) {
1308   // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1309   // know that v != 0.
1310   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1311     // If this is a conditional branch and only one successor goes to BBTo, then
1312     // we may be able to infer something from the condition.
1313     if (BI->isConditional() &&
1314         BI->getSuccessor(0) != BI->getSuccessor(1)) {
1315       bool isTrueDest = BI->getSuccessor(0) == BBTo;
1316       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1317              "BBTo isn't a successor of BBFrom");
1318       Value *Condition = BI->getCondition();
1319 
1320       // If V is the condition of the branch itself, then we know exactly what
1321       // it is.
1322       if (Condition == Val)
1323         return ValueLatticeElement::get(ConstantInt::get(
1324                               Type::getInt1Ty(Val->getContext()), isTrueDest));
1325 
1326       // If the condition of the branch is an equality comparison, we may be
1327       // able to infer the value.
1328       ValueLatticeElement Result = getValueFromCondition(Val, Condition,
1329                                                          isTrueDest);
1330       if (!Result.isOverdefined())
1331         return Result;
1332 
1333       if (User *Usr = dyn_cast<User>(Val)) {
1334         assert(Result.isOverdefined() && "Result isn't overdefined");
1335         // Check with isOperationFoldable() first to avoid linearly iterating
1336         // over the operands unnecessarily which can be expensive for
1337         // instructions with many operands.
1338         if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1339           const DataLayout &DL = BBTo->getModule()->getDataLayout();
1340           if (usesOperand(Usr, Condition)) {
1341             // If Val has Condition as an operand and Val can be folded into a
1342             // constant with either Condition == true or Condition == false,
1343             // propagate the constant.
1344             // eg.
1345             //   ; %Val is true on the edge to %then.
1346             //   %Val = and i1 %Condition, true.
1347             //   br %Condition, label %then, label %else
1348             APInt ConditionVal(1, isTrueDest ? 1 : 0);
1349             Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
1350           } else {
1351             // If one of Val's operand has an inferred value, we may be able to
1352             // infer the value of Val.
1353             // eg.
1354             //    ; %Val is 94 on the edge to %then.
1355             //    %Val = add i8 %Op, 1
1356             //    %Condition = icmp eq i8 %Op, 93
1357             //    br i1 %Condition, label %then, label %else
1358             for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1359               Value *Op = Usr->getOperand(i);
1360               ValueLatticeElement OpLatticeVal =
1361                   getValueFromCondition(Op, Condition, isTrueDest);
1362               if (Optional<APInt> OpConst = OpLatticeVal.asConstantInteger()) {
1363                 Result = constantFoldUser(Usr, Op, OpConst.getValue(), DL);
1364                 break;
1365               }
1366             }
1367           }
1368         }
1369       }
1370       if (!Result.isOverdefined())
1371         return Result;
1372     }
1373   }
1374 
1375   // If the edge was formed by a switch on the value, then we may know exactly
1376   // what it is.
1377   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1378     Value *Condition = SI->getCondition();
1379     if (!isa<IntegerType>(Val->getType()))
1380       return None;
1381     bool ValUsesConditionAndMayBeFoldable = false;
1382     if (Condition != Val) {
1383       // Check if Val has Condition as an operand.
1384       if (User *Usr = dyn_cast<User>(Val))
1385         ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1386             usesOperand(Usr, Condition);
1387       if (!ValUsesConditionAndMayBeFoldable)
1388         return None;
1389     }
1390     assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
1391            "Condition != Val nor Val doesn't use Condition");
1392 
1393     bool DefaultCase = SI->getDefaultDest() == BBTo;
1394     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1395     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1396 
1397     for (auto Case : SI->cases()) {
1398       APInt CaseValue = Case.getCaseValue()->getValue();
1399       ConstantRange EdgeVal(CaseValue);
1400       if (ValUsesConditionAndMayBeFoldable) {
1401         User *Usr = cast<User>(Val);
1402         const DataLayout &DL = BBTo->getModule()->getDataLayout();
1403         ValueLatticeElement EdgeLatticeVal =
1404             constantFoldUser(Usr, Condition, CaseValue, DL);
1405         if (EdgeLatticeVal.isOverdefined())
1406           return None;
1407         EdgeVal = EdgeLatticeVal.getConstantRange();
1408       }
1409       if (DefaultCase) {
1410         // It is possible that the default destination is the destination of
1411         // some cases. We cannot perform difference for those cases.
1412         // We know Condition != CaseValue in BBTo.  In some cases we can use
1413         // this to infer Val == f(Condition) is != f(CaseValue).  For now, we
1414         // only do this when f is identity (i.e. Val == Condition), but we
1415         // should be able to do this for any injective f.
1416         if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1417           EdgesVals = EdgesVals.difference(EdgeVal);
1418       } else if (Case.getCaseSuccessor() == BBTo)
1419         EdgesVals = EdgesVals.unionWith(EdgeVal);
1420     }
1421     return ValueLatticeElement::getRange(std::move(EdgesVals));
1422   }
1423   return None;
1424 }
1425 
1426 /// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1427 /// the basic block if the edge does not constrain Val.
1428 Optional<ValueLatticeElement> LazyValueInfoImpl::getEdgeValue(
1429     Value *Val, BasicBlock *BBFrom, BasicBlock *BBTo, Instruction *CxtI) {
1430   // If already a constant, there is nothing to compute.
1431   if (Constant *VC = dyn_cast<Constant>(Val))
1432     return ValueLatticeElement::get(VC);
1433 
1434   ValueLatticeElement LocalResult = getEdgeValueLocal(Val, BBFrom, BBTo)
1435       .getValueOr(ValueLatticeElement::getOverdefined());
1436   if (hasSingleValue(LocalResult))
1437     // Can't get any more precise here
1438     return LocalResult;
1439 
1440   Optional<ValueLatticeElement> OptInBlock =
1441       getBlockValue(Val, BBFrom, BBFrom->getTerminator());
1442   if (!OptInBlock)
1443     return None;
1444   ValueLatticeElement &InBlock = *OptInBlock;
1445 
1446   // We can use the context instruction (generically the ultimate instruction
1447   // the calling pass is trying to simplify) here, even though the result of
1448   // this function is generally cached when called from the solve* functions
1449   // (and that cached result might be used with queries using a different
1450   // context instruction), because when this function is called from the solve*
1451   // functions, the context instruction is not provided. When called from
1452   // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1453   // but then the result is not cached.
1454   intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1455 
1456   return intersect(LocalResult, InBlock);
1457 }
1458 
1459 ValueLatticeElement LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
1460                                                        Instruction *CxtI) {
1461   LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1462                     << BB->getName() << "'\n");
1463 
1464   assert(BlockValueStack.empty() && BlockValueSet.empty());
1465   Optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CxtI);
1466   if (!OptResult) {
1467     solve();
1468     OptResult = getBlockValue(V, BB, CxtI);
1469     assert(OptResult && "Value not available after solving");
1470   }
1471 
1472   ValueLatticeElement Result = *OptResult;
1473   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
1474   return Result;
1475 }
1476 
1477 ValueLatticeElement LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
1478   LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()
1479                     << "'\n");
1480 
1481   if (auto *C = dyn_cast<Constant>(V))
1482     return ValueLatticeElement::get(C);
1483 
1484   ValueLatticeElement Result = ValueLatticeElement::getOverdefined();
1485   if (auto *I = dyn_cast<Instruction>(V))
1486     Result = getFromRangeMetadata(I);
1487   intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1488 
1489   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
1490   return Result;
1491 }
1492 
1493 ValueLatticeElement LazyValueInfoImpl::
1494 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1495                Instruction *CxtI) {
1496   LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1497                     << FromBB->getName() << "' to '" << ToBB->getName()
1498                     << "'\n");
1499 
1500   Optional<ValueLatticeElement> Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1501   if (!Result) {
1502     solve();
1503     Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1504     assert(Result && "More work to do after problem solved?");
1505   }
1506 
1507   LLVM_DEBUG(dbgs() << "  Result = " << *Result << "\n");
1508   return *Result;
1509 }
1510 
1511 void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1512                                    BasicBlock *NewSucc) {
1513   TheCache.threadEdgeImpl(OldSucc, NewSucc);
1514 }
1515 
1516 //===----------------------------------------------------------------------===//
1517 //                            LazyValueInfo Impl
1518 //===----------------------------------------------------------------------===//
1519 
1520 /// This lazily constructs the LazyValueInfoImpl.
1521 static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1522                                   const Module *M) {
1523   if (!PImpl) {
1524     assert(M && "getCache() called with a null Module");
1525     const DataLayout &DL = M->getDataLayout();
1526     Function *GuardDecl = M->getFunction(
1527         Intrinsic::getName(Intrinsic::experimental_guard));
1528     PImpl = new LazyValueInfoImpl(AC, DL, GuardDecl);
1529   }
1530   return *static_cast<LazyValueInfoImpl*>(PImpl);
1531 }
1532 
1533 bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1534   Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1535   Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1536 
1537   if (Info.PImpl)
1538     getImpl(Info.PImpl, Info.AC, F.getParent()).clear();
1539 
1540   // Fully lazy.
1541   return false;
1542 }
1543 
1544 void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1545   AU.setPreservesAll();
1546   AU.addRequired<AssumptionCacheTracker>();
1547   AU.addRequired<TargetLibraryInfoWrapperPass>();
1548 }
1549 
1550 LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1551 
1552 LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1553 
1554 void LazyValueInfo::releaseMemory() {
1555   // If the cache was allocated, free it.
1556   if (PImpl) {
1557     delete &getImpl(PImpl, AC, nullptr);
1558     PImpl = nullptr;
1559   }
1560 }
1561 
1562 bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
1563                                FunctionAnalysisManager::Invalidator &Inv) {
1564   // We need to invalidate if we have either failed to preserve this analyses
1565   // result directly or if any of its dependencies have been invalidated.
1566   auto PAC = PA.getChecker<LazyValueAnalysis>();
1567   if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
1568     return true;
1569 
1570   return false;
1571 }
1572 
1573 void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1574 
1575 LazyValueInfo LazyValueAnalysis::run(Function &F,
1576                                      FunctionAnalysisManager &FAM) {
1577   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1578   auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1579 
1580   return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI);
1581 }
1582 
1583 /// Returns true if we can statically tell that this value will never be a
1584 /// "useful" constant.  In practice, this means we've got something like an
1585 /// alloca or a malloc call for which a comparison against a constant can
1586 /// only be guarding dead code.  Note that we are potentially giving up some
1587 /// precision in dead code (a constant result) in favour of avoiding a
1588 /// expensive search for a easily answered common query.
1589 static bool isKnownNonConstant(Value *V) {
1590   V = V->stripPointerCasts();
1591   // The return val of alloc cannot be a Constant.
1592   if (isa<AllocaInst>(V))
1593     return true;
1594   return false;
1595 }
1596 
1597 Constant *LazyValueInfo::getConstant(Value *V, Instruction *CxtI) {
1598   // Bail out early if V is known not to be a Constant.
1599   if (isKnownNonConstant(V))
1600     return nullptr;
1601 
1602   BasicBlock *BB = CxtI->getParent();
1603   ValueLatticeElement Result =
1604       getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
1605 
1606   if (Result.isConstant())
1607     return Result.getConstant();
1608   if (Result.isConstantRange()) {
1609     const ConstantRange &CR = Result.getConstantRange();
1610     if (const APInt *SingleVal = CR.getSingleElement())
1611       return ConstantInt::get(V->getContext(), *SingleVal);
1612   }
1613   return nullptr;
1614 }
1615 
1616 ConstantRange LazyValueInfo::getConstantRange(Value *V, Instruction *CxtI,
1617                                               bool UndefAllowed) {
1618   assert(V->getType()->isIntegerTy());
1619   unsigned Width = V->getType()->getIntegerBitWidth();
1620   BasicBlock *BB = CxtI->getParent();
1621   ValueLatticeElement Result =
1622       getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
1623   if (Result.isUnknown())
1624     return ConstantRange::getEmpty(Width);
1625   if (Result.isConstantRange(UndefAllowed))
1626     return Result.getConstantRange(UndefAllowed);
1627   // We represent ConstantInt constants as constant ranges but other kinds
1628   // of integer constants, i.e. ConstantExpr will be tagged as constants
1629   assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1630          "ConstantInt value must be represented as constantrange");
1631   return ConstantRange::getFull(Width);
1632 }
1633 
1634 /// Determine whether the specified value is known to be a
1635 /// constant on the specified edge. Return null if not.
1636 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1637                                            BasicBlock *ToBB,
1638                                            Instruction *CxtI) {
1639   Module *M = FromBB->getModule();
1640   ValueLatticeElement Result =
1641       getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1642 
1643   if (Result.isConstant())
1644     return Result.getConstant();
1645   if (Result.isConstantRange()) {
1646     const ConstantRange &CR = Result.getConstantRange();
1647     if (const APInt *SingleVal = CR.getSingleElement())
1648       return ConstantInt::get(V->getContext(), *SingleVal);
1649   }
1650   return nullptr;
1651 }
1652 
1653 ConstantRange LazyValueInfo::getConstantRangeOnEdge(Value *V,
1654                                                     BasicBlock *FromBB,
1655                                                     BasicBlock *ToBB,
1656                                                     Instruction *CxtI) {
1657   unsigned Width = V->getType()->getIntegerBitWidth();
1658   Module *M = FromBB->getModule();
1659   ValueLatticeElement Result =
1660       getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1661 
1662   if (Result.isUnknown())
1663     return ConstantRange::getEmpty(Width);
1664   if (Result.isConstantRange())
1665     return Result.getConstantRange();
1666   // We represent ConstantInt constants as constant ranges but other kinds
1667   // of integer constants, i.e. ConstantExpr will be tagged as constants
1668   assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1669          "ConstantInt value must be represented as constantrange");
1670   return ConstantRange::getFull(Width);
1671 }
1672 
1673 static LazyValueInfo::Tristate
1674 getPredicateResult(unsigned Pred, Constant *C, const ValueLatticeElement &Val,
1675                    const DataLayout &DL, TargetLibraryInfo *TLI) {
1676   // If we know the value is a constant, evaluate the conditional.
1677   Constant *Res = nullptr;
1678   if (Val.isConstant()) {
1679     Res = ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL, TLI);
1680     if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1681       return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1682     return LazyValueInfo::Unknown;
1683   }
1684 
1685   if (Val.isConstantRange()) {
1686     ConstantInt *CI = dyn_cast<ConstantInt>(C);
1687     if (!CI) return LazyValueInfo::Unknown;
1688 
1689     const ConstantRange &CR = Val.getConstantRange();
1690     if (Pred == ICmpInst::ICMP_EQ) {
1691       if (!CR.contains(CI->getValue()))
1692         return LazyValueInfo::False;
1693 
1694       if (CR.isSingleElement())
1695         return LazyValueInfo::True;
1696     } else if (Pred == ICmpInst::ICMP_NE) {
1697       if (!CR.contains(CI->getValue()))
1698         return LazyValueInfo::True;
1699 
1700       if (CR.isSingleElement())
1701         return LazyValueInfo::False;
1702     } else {
1703       // Handle more complex predicates.
1704       ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1705           (ICmpInst::Predicate)Pred, CI->getValue());
1706       if (TrueValues.contains(CR))
1707         return LazyValueInfo::True;
1708       if (TrueValues.inverse().contains(CR))
1709         return LazyValueInfo::False;
1710     }
1711     return LazyValueInfo::Unknown;
1712   }
1713 
1714   if (Val.isNotConstant()) {
1715     // If this is an equality comparison, we can try to fold it knowing that
1716     // "V != C1".
1717     if (Pred == ICmpInst::ICMP_EQ) {
1718       // !C1 == C -> false iff C1 == C.
1719       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1720                                             Val.getNotConstant(), C, DL,
1721                                             TLI);
1722       if (Res->isNullValue())
1723         return LazyValueInfo::False;
1724     } else if (Pred == ICmpInst::ICMP_NE) {
1725       // !C1 != C -> true iff C1 == C.
1726       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1727                                             Val.getNotConstant(), C, DL,
1728                                             TLI);
1729       if (Res->isNullValue())
1730         return LazyValueInfo::True;
1731     }
1732     return LazyValueInfo::Unknown;
1733   }
1734 
1735   return LazyValueInfo::Unknown;
1736 }
1737 
1738 /// Determine whether the specified value comparison with a constant is known to
1739 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1740 LazyValueInfo::Tristate
1741 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1742                                   BasicBlock *FromBB, BasicBlock *ToBB,
1743                                   Instruction *CxtI) {
1744   Module *M = FromBB->getModule();
1745   ValueLatticeElement Result =
1746       getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1747 
1748   return getPredicateResult(Pred, C, Result, M->getDataLayout(), TLI);
1749 }
1750 
1751 LazyValueInfo::Tristate
1752 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1753                               Instruction *CxtI, bool UseBlockValue) {
1754   // Is or is not NonNull are common predicates being queried. If
1755   // isKnownNonZero can tell us the result of the predicate, we can
1756   // return it quickly. But this is only a fastpath, and falling
1757   // through would still be correct.
1758   Module *M = CxtI->getModule();
1759   const DataLayout &DL = M->getDataLayout();
1760   if (V->getType()->isPointerTy() && C->isNullValue() &&
1761       isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
1762     if (Pred == ICmpInst::ICMP_EQ)
1763       return LazyValueInfo::False;
1764     else if (Pred == ICmpInst::ICMP_NE)
1765       return LazyValueInfo::True;
1766   }
1767 
1768   ValueLatticeElement Result = UseBlockValue
1769       ? getImpl(PImpl, AC, M).getValueInBlock(V, CxtI->getParent(), CxtI)
1770       : getImpl(PImpl, AC, M).getValueAt(V, CxtI);
1771   Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1772   if (Ret != Unknown)
1773     return Ret;
1774 
1775   // Note: The following bit of code is somewhat distinct from the rest of LVI;
1776   // LVI as a whole tries to compute a lattice value which is conservatively
1777   // correct at a given location.  In this case, we have a predicate which we
1778   // weren't able to prove about the merged result, and we're pushing that
1779   // predicate back along each incoming edge to see if we can prove it
1780   // separately for each input.  As a motivating example, consider:
1781   // bb1:
1782   //   %v1 = ... ; constantrange<1, 5>
1783   //   br label %merge
1784   // bb2:
1785   //   %v2 = ... ; constantrange<10, 20>
1786   //   br label %merge
1787   // merge:
1788   //   %phi = phi [%v1, %v2] ; constantrange<1,20>
1789   //   %pred = icmp eq i32 %phi, 8
1790   // We can't tell from the lattice value for '%phi' that '%pred' is false
1791   // along each path, but by checking the predicate over each input separately,
1792   // we can.
1793   // We limit the search to one step backwards from the current BB and value.
1794   // We could consider extending this to search further backwards through the
1795   // CFG and/or value graph, but there are non-obvious compile time vs quality
1796   // tradeoffs.
1797   BasicBlock *BB = CxtI->getParent();
1798 
1799   // Function entry or an unreachable block.  Bail to avoid confusing
1800   // analysis below.
1801   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1802   if (PI == PE)
1803     return Unknown;
1804 
1805   // If V is a PHI node in the same block as the context, we need to ask
1806   // questions about the predicate as applied to the incoming value along
1807   // each edge. This is useful for eliminating cases where the predicate is
1808   // known along all incoming edges.
1809   if (auto *PHI = dyn_cast<PHINode>(V))
1810     if (PHI->getParent() == BB) {
1811       Tristate Baseline = Unknown;
1812       for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1813         Value *Incoming = PHI->getIncomingValue(i);
1814         BasicBlock *PredBB = PHI->getIncomingBlock(i);
1815         // Note that PredBB may be BB itself.
1816         Tristate Result =
1817             getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CxtI);
1818 
1819         // Keep going as long as we've seen a consistent known result for
1820         // all inputs.
1821         Baseline = (i == 0) ? Result /* First iteration */
1822                             : (Baseline == Result ? Baseline
1823                                                   : Unknown); /* All others */
1824         if (Baseline == Unknown)
1825           break;
1826       }
1827       if (Baseline != Unknown)
1828         return Baseline;
1829     }
1830 
1831   // For a comparison where the V is outside this block, it's possible
1832   // that we've branched on it before. Look to see if the value is known
1833   // on all incoming edges.
1834   if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
1835     // For predecessor edge, determine if the comparison is true or false
1836     // on that edge. If they're all true or all false, we can conclude
1837     // the value of the comparison in this block.
1838     Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1839     if (Baseline != Unknown) {
1840       // Check that all remaining incoming values match the first one.
1841       while (++PI != PE) {
1842         Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1843         if (Ret != Baseline)
1844           break;
1845       }
1846       // If we terminated early, then one of the values didn't match.
1847       if (PI == PE) {
1848         return Baseline;
1849       }
1850     }
1851   }
1852 
1853   return Unknown;
1854 }
1855 
1856 LazyValueInfo::Tristate LazyValueInfo::getPredicateAt(unsigned P, Value *LHS,
1857                                                       Value *RHS,
1858                                                       Instruction *CxtI,
1859                                                       bool UseBlockValue) {
1860   CmpInst::Predicate Pred = (CmpInst::Predicate)P;
1861 
1862   if (auto *C = dyn_cast<Constant>(RHS))
1863     return getPredicateAt(P, LHS, C, CxtI, UseBlockValue);
1864   if (auto *C = dyn_cast<Constant>(LHS))
1865     return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CxtI,
1866                           UseBlockValue);
1867 
1868   // Got two non-Constant values. While we could handle them somewhat,
1869   // by getting their constant ranges, and applying ConstantRange::icmp(),
1870   // so far it did not appear to be profitable.
1871   return LazyValueInfo::Unknown;
1872 }
1873 
1874 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1875                                BasicBlock *NewSucc) {
1876   if (PImpl) {
1877     getImpl(PImpl, AC, PredBB->getModule())
1878         .threadEdge(PredBB, OldSucc, NewSucc);
1879   }
1880 }
1881 
1882 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1883   if (PImpl) {
1884     getImpl(PImpl, AC, BB->getModule()).eraseBlock(BB);
1885   }
1886 }
1887 
1888 void LazyValueInfo::clear(const Module *M) {
1889   if (PImpl) {
1890     getImpl(PImpl, AC, M).clear();
1891   }
1892 }
1893 
1894 void LazyValueInfo::printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
1895   if (PImpl) {
1896     getImpl(PImpl, AC, F.getParent()).printLVI(F, DTree, OS);
1897   }
1898 }
1899 
1900 // Print the LVI for the function arguments at the start of each basic block.
1901 void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
1902     const BasicBlock *BB, formatted_raw_ostream &OS) {
1903   // Find if there are latticevalues defined for arguments of the function.
1904   auto *F = BB->getParent();
1905   for (auto &Arg : F->args()) {
1906     ValueLatticeElement Result = LVIImpl->getValueInBlock(
1907         const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
1908     if (Result.isUnknown())
1909       continue;
1910     OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
1911   }
1912 }
1913 
1914 // This function prints the LVI analysis for the instruction I at the beginning
1915 // of various basic blocks. It relies on calculated values that are stored in
1916 // the LazyValueInfoCache, and in the absence of cached values, recalculate the
1917 // LazyValueInfo for `I`, and print that info.
1918 void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
1919     const Instruction *I, formatted_raw_ostream &OS) {
1920 
1921   auto *ParentBB = I->getParent();
1922   SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
1923   // We can generate (solve) LVI values only for blocks that are dominated by
1924   // the I's parent. However, to avoid generating LVI for all dominating blocks,
1925   // that contain redundant/uninteresting information, we print LVI for
1926   // blocks that may use this LVI information (such as immediate successor
1927   // blocks, and blocks that contain uses of `I`).
1928   auto printResult = [&](const BasicBlock *BB) {
1929     if (!BlocksContainingLVI.insert(BB).second)
1930       return;
1931     ValueLatticeElement Result = LVIImpl->getValueInBlock(
1932         const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
1933       OS << "; LatticeVal for: '" << *I << "' in BB: '";
1934       BB->printAsOperand(OS, false);
1935       OS << "' is: " << Result << "\n";
1936   };
1937 
1938   printResult(ParentBB);
1939   // Print the LVI analysis results for the immediate successor blocks, that
1940   // are dominated by `ParentBB`.
1941   for (auto *BBSucc : successors(ParentBB))
1942     if (DT.dominates(ParentBB, BBSucc))
1943       printResult(BBSucc);
1944 
1945   // Print LVI in blocks where `I` is used.
1946   for (auto *U : I->users())
1947     if (auto *UseI = dyn_cast<Instruction>(U))
1948       if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
1949         printResult(UseI->getParent());
1950 
1951 }
1952 
1953 namespace {
1954 // Printer class for LazyValueInfo results.
1955 class LazyValueInfoPrinter : public FunctionPass {
1956 public:
1957   static char ID; // Pass identification, replacement for typeid
1958   LazyValueInfoPrinter() : FunctionPass(ID) {
1959     initializeLazyValueInfoPrinterPass(*PassRegistry::getPassRegistry());
1960   }
1961 
1962   void getAnalysisUsage(AnalysisUsage &AU) const override {
1963     AU.setPreservesAll();
1964     AU.addRequired<LazyValueInfoWrapperPass>();
1965     AU.addRequired<DominatorTreeWrapperPass>();
1966   }
1967 
1968   // Get the mandatory dominator tree analysis and pass this in to the
1969   // LVIPrinter. We cannot rely on the LVI's DT, since it's optional.
1970   bool runOnFunction(Function &F) override {
1971     dbgs() << "LVI for function '" << F.getName() << "':\n";
1972     auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
1973     auto &DTree = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1974     LVI.printLVI(F, DTree, dbgs());
1975     return false;
1976   }
1977 };
1978 }
1979 
1980 char LazyValueInfoPrinter::ID = 0;
1981 INITIALIZE_PASS_BEGIN(LazyValueInfoPrinter, "print-lazy-value-info",
1982                 "Lazy Value Info Printer Pass", false, false)
1983 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
1984 INITIALIZE_PASS_END(LazyValueInfoPrinter, "print-lazy-value-info",
1985                 "Lazy Value Info Printer Pass", false, false)
1986