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/raw_ostream.h"
40 #include <map>
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     worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(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   Optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
399                                 BasicBlock *T, Instruction *CxtI = nullptr);
400 
401   // These methods process one work item and may add more. A false value
402   // returned means that the work item was not completely processed and must
403   // be revisited after going through the new items.
404   bool solveBlockValue(Value *Val, BasicBlock *BB);
405   Optional<ValueLatticeElement> solveBlockValueImpl(Value *Val, BasicBlock *BB);
406   Optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
407                                                         BasicBlock *BB);
408   Optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
409                                                        BasicBlock *BB);
410   Optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
411                                                       BasicBlock *BB);
412   Optional<ConstantRange> getRangeFor(Value *V, Instruction *CxtI,
413                                       BasicBlock *BB);
414   Optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
415       Instruction *I, BasicBlock *BB,
416       std::function<ConstantRange(const ConstantRange &,
417                                   const ConstantRange &)> OpFn);
418   Optional<ValueLatticeElement> solveBlockValueBinaryOp(BinaryOperator *BBI,
419                                                         BasicBlock *BB);
420   Optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
421                                                     BasicBlock *BB);
422   Optional<ValueLatticeElement> solveBlockValueOverflowIntrinsic(
423       WithOverflowInst *WO, BasicBlock *BB);
424   Optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
425                                                          BasicBlock *BB);
426   Optional<ValueLatticeElement> solveBlockValueExtractValue(
427       ExtractValueInst *EVI, BasicBlock *BB);
428   bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
429   void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
430                                                      ValueLatticeElement &BBLV,
431                                                      Instruction *BBI);
432 
433   void solve();
434 
435 public:
436   /// This is the query interface to determine the lattice
437   /// value for the specified Value* at the end of the specified block.
438   ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB,
439                                       Instruction *CxtI = nullptr);
440 
441   /// This is the query interface to determine the lattice
442   /// value for the specified Value* at the specified instruction (generally
443   /// from an assume intrinsic).
444   ValueLatticeElement getValueAt(Value *V, Instruction *CxtI);
445 
446   /// This is the query interface to determine the lattice
447   /// value for the specified Value* that is true on the specified edge.
448   ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB,
449                                      BasicBlock *ToBB,
450                                      Instruction *CxtI = nullptr);
451 
452   /// Complete flush all previously computed values
453   void clear() {
454     TheCache.clear();
455   }
456 
457   /// Printing the LazyValueInfo Analysis.
458   void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
459     LazyValueInfoAnnotatedWriter Writer(this, DTree);
460     F.print(OS, &Writer);
461   }
462 
463   /// This is part of the update interface to inform the cache
464   /// that a block has been deleted.
465   void eraseBlock(BasicBlock *BB) {
466     TheCache.eraseBlock(BB);
467   }
468 
469   /// This is the update interface to inform the cache that an edge from
470   /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
471   void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
472 
473   LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
474                     Function *GuardDecl)
475       : AC(AC), DL(DL), GuardDecl(GuardDecl) {}
476 };
477 } // end anonymous namespace
478 
479 
480 void LazyValueInfoImpl::solve() {
481   SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
482       BlockValueStack.begin(), BlockValueStack.end());
483 
484   unsigned processedCount = 0;
485   while (!BlockValueStack.empty()) {
486     processedCount++;
487     // Abort if we have to process too many values to get a result for this one.
488     // Because of the design of the overdefined cache currently being per-block
489     // to avoid naming-related issues (IE it wants to try to give different
490     // results for the same name in different blocks), overdefined results don't
491     // get cached globally, which in turn means we will often try to rediscover
492     // the same overdefined result again and again.  Once something like
493     // PredicateInfo is used in LVI or CVP, we should be able to make the
494     // overdefined cache global, and remove this throttle.
495     if (processedCount > MaxProcessedPerValue) {
496       LLVM_DEBUG(
497           dbgs() << "Giving up on stack because we are getting too deep\n");
498       // Fill in the original values
499       while (!StartingStack.empty()) {
500         std::pair<BasicBlock *, Value *> &e = StartingStack.back();
501         TheCache.insertResult(e.second, e.first,
502                               ValueLatticeElement::getOverdefined());
503         StartingStack.pop_back();
504       }
505       BlockValueSet.clear();
506       BlockValueStack.clear();
507       return;
508     }
509     std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
510     assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
511 
512     if (solveBlockValue(e.second, e.first)) {
513       // The work item was completely processed.
514       assert(BlockValueStack.back() == e && "Nothing should have been pushed!");
515 #ifndef NDEBUG
516       Optional<ValueLatticeElement> BBLV =
517           TheCache.getCachedValueInfo(e.second, e.first);
518       assert(BBLV && "Result should be in cache!");
519       LLVM_DEBUG(
520           dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
521                  << *BBLV << "\n");
522 #endif
523 
524       BlockValueStack.pop_back();
525       BlockValueSet.erase(e);
526     } else {
527       // More work needs to be done before revisiting.
528       assert(BlockValueStack.back() != e && "Stack should have been pushed!");
529     }
530   }
531 }
532 
533 Optional<ValueLatticeElement> LazyValueInfoImpl::getBlockValue(Value *Val,
534                                                                BasicBlock *BB) {
535   // If already a constant, there is nothing to compute.
536   if (Constant *VC = dyn_cast<Constant>(Val))
537     return ValueLatticeElement::get(VC);
538 
539   if (Optional<ValueLatticeElement> OptLatticeVal =
540           TheCache.getCachedValueInfo(Val, BB))
541     return OptLatticeVal;
542 
543   // We have hit a cycle, assume overdefined.
544   if (!pushBlockValue({ BB, Val }))
545     return ValueLatticeElement::getOverdefined();
546 
547   // Yet to be resolved.
548   return None;
549 }
550 
551 static ValueLatticeElement getFromRangeMetadata(Instruction *BBI) {
552   switch (BBI->getOpcode()) {
553   default: break;
554   case Instruction::Load:
555   case Instruction::Call:
556   case Instruction::Invoke:
557     if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
558       if (isa<IntegerType>(BBI->getType())) {
559         return ValueLatticeElement::getRange(
560             getConstantRangeFromMetadata(*Ranges));
561       }
562     break;
563   };
564   // Nothing known - will be intersected with other facts
565   return ValueLatticeElement::getOverdefined();
566 }
567 
568 bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
569   assert(!isa<Constant>(Val) && "Value should not be constant");
570   assert(!TheCache.getCachedValueInfo(Val, BB) &&
571          "Value should not be in cache");
572 
573   // Hold off inserting this value into the Cache in case we have to return
574   // false and come back later.
575   Optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
576   if (!Res)
577     // Work pushed, will revisit
578     return false;
579 
580   TheCache.insertResult(Val, BB, *Res);
581   return true;
582 }
583 
584 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueImpl(
585     Value *Val, BasicBlock *BB) {
586   Instruction *BBI = dyn_cast<Instruction>(Val);
587   if (!BBI || BBI->getParent() != BB)
588     return solveBlockValueNonLocal(Val, BB);
589 
590   if (PHINode *PN = dyn_cast<PHINode>(BBI))
591     return solveBlockValuePHINode(PN, BB);
592 
593   if (auto *SI = dyn_cast<SelectInst>(BBI))
594     return solveBlockValueSelect(SI, BB);
595 
596   // If this value is a nonnull pointer, record it's range and bailout.  Note
597   // that for all other pointer typed values, we terminate the search at the
598   // definition.  We could easily extend this to look through geps, bitcasts,
599   // and the like to prove non-nullness, but it's not clear that's worth it
600   // compile time wise.  The context-insensitive value walk done inside
601   // isKnownNonZero gets most of the profitable cases at much less expense.
602   // This does mean that we have a sensitivity to where the defining
603   // instruction is placed, even if it could legally be hoisted much higher.
604   // That is unfortunate.
605   PointerType *PT = dyn_cast<PointerType>(BBI->getType());
606   if (PT && isKnownNonZero(BBI, DL))
607     return ValueLatticeElement::getNot(ConstantPointerNull::get(PT));
608 
609   if (BBI->getType()->isIntegerTy()) {
610     if (auto *CI = dyn_cast<CastInst>(BBI))
611       return solveBlockValueCast(CI, BB);
612 
613     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
614       return solveBlockValueBinaryOp(BO, BB);
615 
616     if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
617       return solveBlockValueExtractValue(EVI, BB);
618 
619     if (auto *II = dyn_cast<IntrinsicInst>(BBI))
620       return solveBlockValueIntrinsic(II, BB);
621   }
622 
623   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
624                     << "' - unknown inst def found.\n");
625   return getFromRangeMetadata(BBI);
626 }
627 
628 static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet) {
629   // TODO: Use NullPointerIsDefined instead.
630   if (Ptr->getType()->getPointerAddressSpace() == 0)
631     PtrSet.insert(getUnderlyingObject(Ptr));
632 }
633 
634 static void AddNonNullPointersByInstruction(
635     Instruction *I, NonNullPointerSet &PtrSet) {
636   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
637     AddNonNullPointer(L->getPointerOperand(), PtrSet);
638   } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
639     AddNonNullPointer(S->getPointerOperand(), PtrSet);
640   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
641     if (MI->isVolatile()) return;
642 
643     // FIXME: check whether it has a valuerange that excludes zero?
644     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
645     if (!Len || Len->isZero()) return;
646 
647     AddNonNullPointer(MI->getRawDest(), PtrSet);
648     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
649       AddNonNullPointer(MTI->getRawSource(), PtrSet);
650   }
651 }
652 
653 bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
654   if (NullPointerIsDefined(BB->getParent(),
655                            Val->getType()->getPointerAddressSpace()))
656     return false;
657 
658   Val = getUnderlyingObject(Val);
659   return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
660     NonNullPointerSet NonNullPointers;
661     for (Instruction &I : *BB)
662       AddNonNullPointersByInstruction(&I, NonNullPointers);
663     return NonNullPointers;
664   });
665 }
666 
667 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueNonLocal(
668     Value *Val, BasicBlock *BB) {
669   ValueLatticeElement Result;  // Start Undefined.
670 
671   // If this is the entry block, we must be asking about an argument.  The
672   // value is overdefined.
673   if (BB == &BB->getParent()->getEntryBlock()) {
674     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
675     return ValueLatticeElement::getOverdefined();
676   }
677 
678   // Loop over all of our predecessors, merging what we know from them into
679   // result.  If we encounter an unexplored predecessor, we eagerly explore it
680   // in a depth first manner.  In practice, this has the effect of discovering
681   // paths we can't analyze eagerly without spending compile times analyzing
682   // other paths.  This heuristic benefits from the fact that predecessors are
683   // frequently arranged such that dominating ones come first and we quickly
684   // find a path to function entry.  TODO: We should consider explicitly
685   // canonicalizing to make this true rather than relying on this happy
686   // accident.
687   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
688     Optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, *PI, BB);
689     if (!EdgeResult)
690       // Explore that input, then return here
691       return None;
692 
693     Result.mergeIn(*EdgeResult);
694 
695     // If we hit overdefined, exit early.  The BlockVals entry is already set
696     // to overdefined.
697     if (Result.isOverdefined()) {
698       LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
699                         << "' - overdefined because of pred (non local).\n");
700       return Result;
701     }
702   }
703 
704   // Return the merged value, which is more precise than 'overdefined'.
705   assert(!Result.isOverdefined());
706   return Result;
707 }
708 
709 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValuePHINode(
710     PHINode *PN, BasicBlock *BB) {
711   ValueLatticeElement Result;  // Start Undefined.
712 
713   // Loop over all of our predecessors, merging what we know from them into
714   // result.  See the comment about the chosen traversal order in
715   // solveBlockValueNonLocal; the same reasoning applies here.
716   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
717     BasicBlock *PhiBB = PN->getIncomingBlock(i);
718     Value *PhiVal = PN->getIncomingValue(i);
719     // Note that we can provide PN as the context value to getEdgeValue, even
720     // though the results will be cached, because PN is the value being used as
721     // the cache key in the caller.
722     Optional<ValueLatticeElement> EdgeResult =
723         getEdgeValue(PhiVal, PhiBB, BB, PN);
724     if (!EdgeResult)
725       // Explore that input, then return here
726       return None;
727 
728     Result.mergeIn(*EdgeResult);
729 
730     // If we hit overdefined, exit early.  The BlockVals entry is already set
731     // to overdefined.
732     if (Result.isOverdefined()) {
733       LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
734                         << "' - overdefined because of pred (local).\n");
735 
736       return Result;
737     }
738   }
739 
740   // Return the merged value, which is more precise than 'overdefined'.
741   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
742   return Result;
743 }
744 
745 static ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
746                                                  bool isTrueDest = true);
747 
748 // If we can determine a constraint on the value given conditions assumed by
749 // the program, intersect those constraints with BBLV
750 void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
751         Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
752   BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
753   if (!BBI)
754     return;
755 
756   BasicBlock *BB = BBI->getParent();
757   for (auto &AssumeVH : AC->assumptionsFor(Val)) {
758     if (!AssumeVH)
759       continue;
760 
761     // Only check assumes in the block of the context instruction. Other
762     // assumes will have already been taken into account when the value was
763     // propagated from predecessor blocks.
764     auto *I = cast<CallInst>(AssumeVH);
765     if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
766       continue;
767 
768     BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
769   }
770 
771   // If guards are not used in the module, don't spend time looking for them
772   if (GuardDecl && !GuardDecl->use_empty() &&
773       BBI->getIterator() != BB->begin()) {
774     for (Instruction &I : make_range(std::next(BBI->getIterator().getReverse()),
775                                      BB->rend())) {
776       Value *Cond = nullptr;
777       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
778         BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
779     }
780   }
781 
782   if (BBLV.isOverdefined()) {
783     // Check whether we're checking at the terminator, and the pointer has
784     // been dereferenced in this block.
785     PointerType *PTy = dyn_cast<PointerType>(Val->getType());
786     if (PTy && BB->getTerminator() == BBI &&
787         isNonNullAtEndOfBlock(Val, BB))
788       BBLV = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
789   }
790 }
791 
792 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueSelect(
793     SelectInst *SI, BasicBlock *BB) {
794   // Recurse on our inputs if needed
795   Optional<ValueLatticeElement> OptTrueVal =
796       getBlockValue(SI->getTrueValue(), BB);
797   if (!OptTrueVal)
798     return None;
799   ValueLatticeElement &TrueVal = *OptTrueVal;
800 
801   // If we hit overdefined, don't ask more queries.  We want to avoid poisoning
802   // extra slots in the table if we can.
803   if (TrueVal.isOverdefined())
804     return ValueLatticeElement::getOverdefined();
805 
806   Optional<ValueLatticeElement> OptFalseVal =
807       getBlockValue(SI->getFalseValue(), BB);
808   if (!OptFalseVal)
809     return None;
810   ValueLatticeElement &FalseVal = *OptFalseVal;
811 
812   // If we hit overdefined, don't ask more queries.  We want to avoid poisoning
813   // extra slots in the table if we can.
814   if (FalseVal.isOverdefined())
815     return ValueLatticeElement::getOverdefined();
816 
817   if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
818     const ConstantRange &TrueCR = TrueVal.getConstantRange();
819     const ConstantRange &FalseCR = FalseVal.getConstantRange();
820     Value *LHS = nullptr;
821     Value *RHS = nullptr;
822     SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
823     // Is this a min specifically of our two inputs?  (Avoid the risk of
824     // ValueTracking getting smarter looking back past our immediate inputs.)
825     if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
826         LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
827       ConstantRange ResultCR = [&]() {
828         switch (SPR.Flavor) {
829         default:
830           llvm_unreachable("unexpected minmax type!");
831         case SPF_SMIN:                   /// Signed minimum
832           return TrueCR.smin(FalseCR);
833         case SPF_UMIN:                   /// Unsigned minimum
834           return TrueCR.umin(FalseCR);
835         case SPF_SMAX:                   /// Signed maximum
836           return TrueCR.smax(FalseCR);
837         case SPF_UMAX:                   /// Unsigned maximum
838           return TrueCR.umax(FalseCR);
839         };
840       }();
841       return ValueLatticeElement::getRange(
842           ResultCR, TrueVal.isConstantRangeIncludingUndef() |
843                         FalseVal.isConstantRangeIncludingUndef());
844     }
845 
846     if (SPR.Flavor == SPF_ABS) {
847       if (LHS == SI->getTrueValue())
848         return ValueLatticeElement::getRange(
849             TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
850       if (LHS == SI->getFalseValue())
851         return ValueLatticeElement::getRange(
852             FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
853     }
854 
855     if (SPR.Flavor == SPF_NABS) {
856       ConstantRange Zero(APInt::getNullValue(TrueCR.getBitWidth()));
857       if (LHS == SI->getTrueValue())
858         return ValueLatticeElement::getRange(
859             Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
860       if (LHS == SI->getFalseValue())
861         return ValueLatticeElement::getRange(
862             Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
863     }
864   }
865 
866   // Can we constrain the facts about the true and false values by using the
867   // condition itself?  This shows up with idioms like e.g. select(a > 5, a, 5).
868   // TODO: We could potentially refine an overdefined true value above.
869   Value *Cond = SI->getCondition();
870   TrueVal = intersect(TrueVal,
871                       getValueFromCondition(SI->getTrueValue(), Cond, true));
872   FalseVal = intersect(FalseVal,
873                        getValueFromCondition(SI->getFalseValue(), Cond, false));
874 
875   // Handle clamp idioms such as:
876   //   %24 = constantrange<0, 17>
877   //   %39 = icmp eq i32 %24, 0
878   //   %40 = add i32 %24, -1
879   //   %siv.next = select i1 %39, i32 16, i32 %40
880   //   %siv.next = constantrange<0, 17> not <-1, 17>
881   // In general, this can handle any clamp idiom which tests the edge
882   // condition via an equality or inequality.
883   if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
884     ICmpInst::Predicate Pred = ICI->getPredicate();
885     Value *A = ICI->getOperand(0);
886     if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
887       auto addConstants = [](ConstantInt *A, ConstantInt *B) {
888         assert(A->getType() == B->getType());
889         return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
890       };
891       // See if either input is A + C2, subject to the constraint from the
892       // condition that A != C when that input is used.  We can assume that
893       // that input doesn't include C + C2.
894       ConstantInt *CIAdded;
895       switch (Pred) {
896       default: break;
897       case ICmpInst::ICMP_EQ:
898         if (match(SI->getFalseValue(), m_Add(m_Specific(A),
899                                              m_ConstantInt(CIAdded)))) {
900           auto ResNot = addConstants(CIBase, CIAdded);
901           FalseVal = intersect(FalseVal,
902                                ValueLatticeElement::getNot(ResNot));
903         }
904         break;
905       case ICmpInst::ICMP_NE:
906         if (match(SI->getTrueValue(), m_Add(m_Specific(A),
907                                             m_ConstantInt(CIAdded)))) {
908           auto ResNot = addConstants(CIBase, CIAdded);
909           TrueVal = intersect(TrueVal,
910                               ValueLatticeElement::getNot(ResNot));
911         }
912         break;
913       };
914     }
915   }
916 
917   ValueLatticeElement Result = TrueVal;
918   Result.mergeIn(FalseVal);
919   return Result;
920 }
921 
922 Optional<ConstantRange> LazyValueInfoImpl::getRangeFor(Value *V,
923                                                        Instruction *CxtI,
924                                                        BasicBlock *BB) {
925   Optional<ValueLatticeElement> OptVal = getBlockValue(V, BB);
926   if (!OptVal)
927     return None;
928 
929   ValueLatticeElement &Val = *OptVal;
930   intersectAssumeOrGuardBlockValueConstantRange(V, Val, CxtI);
931   if (Val.isConstantRange())
932     return Val.getConstantRange();
933 
934   const unsigned OperandBitWidth = DL.getTypeSizeInBits(V->getType());
935   return ConstantRange::getFull(OperandBitWidth);
936 }
937 
938 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueCast(
939     CastInst *CI, BasicBlock *BB) {
940   // Without knowing how wide the input is, we can't analyze it in any useful
941   // way.
942   if (!CI->getOperand(0)->getType()->isSized())
943     return ValueLatticeElement::getOverdefined();
944 
945   // Filter out casts we don't know how to reason about before attempting to
946   // recurse on our operand.  This can cut a long search short if we know we're
947   // not going to be able to get any useful information anways.
948   switch (CI->getOpcode()) {
949   case Instruction::Trunc:
950   case Instruction::SExt:
951   case Instruction::ZExt:
952   case Instruction::BitCast:
953     break;
954   default:
955     // Unhandled instructions are overdefined.
956     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
957                       << "' - overdefined (unknown cast).\n");
958     return ValueLatticeElement::getOverdefined();
959   }
960 
961   // Figure out the range of the LHS.  If that fails, we still apply the
962   // transfer rule on the full set since we may be able to locally infer
963   // interesting facts.
964   Optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
965   if (!LHSRes.hasValue())
966     // More work to do before applying this transfer rule.
967     return None;
968   const ConstantRange &LHSRange = LHSRes.getValue();
969 
970   const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
971 
972   // NOTE: We're currently limited by the set of operations that ConstantRange
973   // can evaluate symbolically.  Enhancing that set will allows us to analyze
974   // more definitions.
975   return ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
976                                                        ResultBitWidth));
977 }
978 
979 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
980     Instruction *I, BasicBlock *BB,
981     std::function<ConstantRange(const ConstantRange &,
982                                 const ConstantRange &)> OpFn) {
983   // Figure out the ranges of the operands.  If that fails, use a
984   // conservative range, but apply the transfer rule anyways.  This
985   // lets us pick up facts from expressions like "and i32 (call i32
986   // @foo()), 32"
987   Optional<ConstantRange> LHSRes = getRangeFor(I->getOperand(0), I, BB);
988   Optional<ConstantRange> RHSRes = getRangeFor(I->getOperand(1), I, BB);
989   if (!LHSRes.hasValue() || !RHSRes.hasValue())
990     // More work to do before applying this transfer rule.
991     return None;
992 
993   const ConstantRange &LHSRange = LHSRes.getValue();
994   const ConstantRange &RHSRange = RHSRes.getValue();
995   return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
996 }
997 
998 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOp(
999     BinaryOperator *BO, BasicBlock *BB) {
1000   assert(BO->getOperand(0)->getType()->isSized() &&
1001          "all operands to binary operators are sized");
1002   if (BO->getOpcode() == Instruction::Xor) {
1003     // Xor is the only operation not supported by ConstantRange::binaryOp().
1004     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1005                       << "' - overdefined (unknown binary operator).\n");
1006     return ValueLatticeElement::getOverdefined();
1007   }
1008 
1009   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
1010     unsigned NoWrapKind = 0;
1011     if (OBO->hasNoUnsignedWrap())
1012       NoWrapKind |= OverflowingBinaryOperator::NoUnsignedWrap;
1013     if (OBO->hasNoSignedWrap())
1014       NoWrapKind |= OverflowingBinaryOperator::NoSignedWrap;
1015 
1016     return solveBlockValueBinaryOpImpl(
1017         BO, BB,
1018         [BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
1019           return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
1020         });
1021   }
1022 
1023   return solveBlockValueBinaryOpImpl(
1024       BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
1025         return CR1.binaryOp(BO->getOpcode(), CR2);
1026       });
1027 }
1028 
1029 Optional<ValueLatticeElement>
1030 LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
1031                                                     BasicBlock *BB) {
1032   return solveBlockValueBinaryOpImpl(
1033       WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
1034         return CR1.binaryOp(WO->getBinaryOp(), CR2);
1035       });
1036 }
1037 
1038 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueIntrinsic(
1039     IntrinsicInst *II, BasicBlock *BB) {
1040   if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
1041     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1042                       << "' - overdefined (unknown intrinsic).\n");
1043     return ValueLatticeElement::getOverdefined();
1044   }
1045 
1046   SmallVector<ConstantRange, 2> OpRanges;
1047   for (Value *Op : II->args()) {
1048     Optional<ConstantRange> Range = getRangeFor(Op, II, BB);
1049     if (!Range)
1050       return None;
1051     OpRanges.push_back(*Range);
1052   }
1053 
1054   return ValueLatticeElement::getRange(
1055       ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges));
1056 }
1057 
1058 Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueExtractValue(
1059     ExtractValueInst *EVI, BasicBlock *BB) {
1060   if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1061     if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
1062       return solveBlockValueOverflowIntrinsic(WO, BB);
1063 
1064   // Handle extractvalue of insertvalue to allow further simplification
1065   // based on replaced with.overflow intrinsics.
1066   if (Value *V = SimplifyExtractValueInst(
1067           EVI->getAggregateOperand(), EVI->getIndices(),
1068           EVI->getModule()->getDataLayout()))
1069     return getBlockValue(V, BB);
1070 
1071   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1072                     << "' - overdefined (unknown extractvalue).\n");
1073   return ValueLatticeElement::getOverdefined();
1074 }
1075 
1076 static bool matchICmpOperand(const APInt *&Offset, Value *LHS, Value *Val,
1077                              ICmpInst::Predicate Pred) {
1078   if (LHS == Val)
1079     return true;
1080 
1081   // Handle range checking idiom produced by InstCombine. We will subtract the
1082   // offset from the allowed range for RHS in this case.
1083   if (match(LHS, m_Add(m_Specific(Val), m_APInt(Offset))))
1084     return true;
1085 
1086   // If (x | y) < C, then (x < C) && (y < C).
1087   if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
1088       (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE))
1089     return true;
1090 
1091   // If (x & y) > C, then (x > C) && (y > C).
1092   if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
1093       (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE))
1094     return true;
1095 
1096   return false;
1097 }
1098 
1099 static ValueLatticeElement getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1100                                                      bool isTrueDest) {
1101   Value *LHS = ICI->getOperand(0);
1102   Value *RHS = ICI->getOperand(1);
1103 
1104   // Get the predicate that must hold along the considered edge.
1105   CmpInst::Predicate EdgePred =
1106       isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
1107 
1108   if (isa<Constant>(RHS)) {
1109     if (ICI->isEquality() && LHS == Val) {
1110       if (EdgePred == ICmpInst::ICMP_EQ)
1111         return ValueLatticeElement::get(cast<Constant>(RHS));
1112       else if (!isa<UndefValue>(RHS))
1113         return ValueLatticeElement::getNot(cast<Constant>(RHS));
1114     }
1115   }
1116 
1117   if (!Val->getType()->isIntegerTy())
1118     return ValueLatticeElement::getOverdefined();
1119 
1120   const APInt *Offset = nullptr;
1121   if (!matchICmpOperand(Offset, LHS, Val, EdgePred)) {
1122     std::swap(LHS, RHS);
1123     EdgePred = CmpInst::getSwappedPredicate(EdgePred);
1124     if (!matchICmpOperand(Offset, LHS, Val, EdgePred))
1125       return ValueLatticeElement::getOverdefined();
1126   }
1127 
1128   // Calculate the range of values that are allowed by the comparison.
1129   ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1130                          /*isFullSet=*/true);
1131   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1132     RHSRange = ConstantRange(CI->getValue());
1133   else if (Instruction *I = dyn_cast<Instruction>(RHS))
1134     if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1135       RHSRange = getConstantRangeFromMetadata(*Ranges);
1136 
1137   // If we're interested in the false dest, invert the condition
1138   ConstantRange TrueValues =
1139       ConstantRange::makeAllowedICmpRegion(EdgePred, RHSRange);
1140 
1141   if (Offset) // Apply the offset from above.
1142     TrueValues = TrueValues.subtract(*Offset);
1143 
1144   return ValueLatticeElement::getRange(std::move(TrueValues));
1145 }
1146 
1147 // Handle conditions of the form
1148 // extractvalue(op.with.overflow(%x, C), 1).
1149 static ValueLatticeElement getValueFromOverflowCondition(
1150     Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1151   // TODO: This only works with a constant RHS for now. We could also compute
1152   // the range of the RHS, but this doesn't fit into the current structure of
1153   // the edge value calculation.
1154   const APInt *C;
1155   if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1156     return ValueLatticeElement::getOverdefined();
1157 
1158   // Calculate the possible values of %x for which no overflow occurs.
1159   ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
1160       WO->getBinaryOp(), *C, WO->getNoWrapKind());
1161 
1162   // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1163   // constrained to it's inverse (all values that might cause overflow).
1164   if (IsTrueDest)
1165     NWR = NWR.inverse();
1166   return ValueLatticeElement::getRange(NWR);
1167 }
1168 
1169 static ValueLatticeElement
1170 getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1171                       SmallDenseMap<Value*, ValueLatticeElement> &Visited);
1172 
1173 static ValueLatticeElement
1174 getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1175                           SmallDenseMap<Value*, ValueLatticeElement> &Visited) {
1176   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1177     return getValueFromICmpCondition(Val, ICI, isTrueDest);
1178 
1179   if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1180     if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1181       if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1182         return getValueFromOverflowCondition(Val, WO, isTrueDest);
1183 
1184   // Handle conditions in the form of (cond1 && cond2), we know that on the
1185   // true dest path both of the conditions hold. Similarly for conditions of
1186   // the form (cond1 || cond2), we know that on the false dest path neither
1187   // condition holds.
1188   BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
1189   if (!BO || (isTrueDest && BO->getOpcode() != BinaryOperator::And) ||
1190              (!isTrueDest && BO->getOpcode() != BinaryOperator::Or))
1191     return ValueLatticeElement::getOverdefined();
1192 
1193   // Prevent infinite recursion if Cond references itself as in this example:
1194   //  Cond: "%tmp4 = and i1 %tmp4, undef"
1195   //    BL: "%tmp4 = and i1 %tmp4, undef"
1196   //    BR: "i1 undef"
1197   Value *BL = BO->getOperand(0);
1198   Value *BR = BO->getOperand(1);
1199   if (BL == Cond || BR == Cond)
1200     return ValueLatticeElement::getOverdefined();
1201 
1202   return intersect(getValueFromCondition(Val, BL, isTrueDest, Visited),
1203                    getValueFromCondition(Val, BR, isTrueDest, Visited));
1204 }
1205 
1206 static ValueLatticeElement
1207 getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1208                       SmallDenseMap<Value*, ValueLatticeElement> &Visited) {
1209   auto I = Visited.find(Cond);
1210   if (I != Visited.end())
1211     return I->second;
1212 
1213   auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited);
1214   Visited[Cond] = Result;
1215   return Result;
1216 }
1217 
1218 ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
1219                                           bool isTrueDest) {
1220   assert(Cond && "precondition");
1221   SmallDenseMap<Value*, ValueLatticeElement> Visited;
1222   return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1223 }
1224 
1225 // Return true if Usr has Op as an operand, otherwise false.
1226 static bool usesOperand(User *Usr, Value *Op) {
1227   return find(Usr->operands(), Op) != Usr->op_end();
1228 }
1229 
1230 // Return true if the instruction type of Val is supported by
1231 // constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1232 // Call this before calling constantFoldUser() to find out if it's even worth
1233 // attempting to call it.
1234 static bool isOperationFoldable(User *Usr) {
1235   return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
1236 }
1237 
1238 // Check if Usr can be simplified to an integer constant when the value of one
1239 // of its operands Op is an integer constant OpConstVal. If so, return it as an
1240 // lattice value range with a single element or otherwise return an overdefined
1241 // lattice value.
1242 static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
1243                                             const APInt &OpConstVal,
1244                                             const DataLayout &DL) {
1245   assert(isOperationFoldable(Usr) && "Precondition");
1246   Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1247   // Check if Usr can be simplified to a constant.
1248   if (auto *CI = dyn_cast<CastInst>(Usr)) {
1249     assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
1250     if (auto *C = dyn_cast_or_null<ConstantInt>(
1251             SimplifyCastInst(CI->getOpcode(), OpConst,
1252                              CI->getDestTy(), DL))) {
1253       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1254     }
1255   } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1256     bool Op0Match = BO->getOperand(0) == Op;
1257     bool Op1Match = BO->getOperand(1) == Op;
1258     assert((Op0Match || Op1Match) &&
1259            "Operand 0 nor Operand 1 isn't a match");
1260     Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1261     Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1262     if (auto *C = dyn_cast_or_null<ConstantInt>(
1263             SimplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1264       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1265     }
1266   } else if (isa<FreezeInst>(Usr)) {
1267     assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op");
1268     return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
1269   }
1270   return ValueLatticeElement::getOverdefined();
1271 }
1272 
1273 /// Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
1274 /// Val is not constrained on the edge.  Result is unspecified if return value
1275 /// is false.
1276 static Optional<ValueLatticeElement> getEdgeValueLocal(Value *Val,
1277                                                        BasicBlock *BBFrom,
1278                                                        BasicBlock *BBTo) {
1279   // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1280   // know that v != 0.
1281   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1282     // If this is a conditional branch and only one successor goes to BBTo, then
1283     // we may be able to infer something from the condition.
1284     if (BI->isConditional() &&
1285         BI->getSuccessor(0) != BI->getSuccessor(1)) {
1286       bool isTrueDest = BI->getSuccessor(0) == BBTo;
1287       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1288              "BBTo isn't a successor of BBFrom");
1289       Value *Condition = BI->getCondition();
1290 
1291       // If V is the condition of the branch itself, then we know exactly what
1292       // it is.
1293       if (Condition == Val)
1294         return ValueLatticeElement::get(ConstantInt::get(
1295                               Type::getInt1Ty(Val->getContext()), isTrueDest));
1296 
1297       // If the condition of the branch is an equality comparison, we may be
1298       // able to infer the value.
1299       ValueLatticeElement Result = getValueFromCondition(Val, Condition,
1300                                                          isTrueDest);
1301       if (!Result.isOverdefined())
1302         return Result;
1303 
1304       if (User *Usr = dyn_cast<User>(Val)) {
1305         assert(Result.isOverdefined() && "Result isn't overdefined");
1306         // Check with isOperationFoldable() first to avoid linearly iterating
1307         // over the operands unnecessarily which can be expensive for
1308         // instructions with many operands.
1309         if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1310           const DataLayout &DL = BBTo->getModule()->getDataLayout();
1311           if (usesOperand(Usr, Condition)) {
1312             // If Val has Condition as an operand and Val can be folded into a
1313             // constant with either Condition == true or Condition == false,
1314             // propagate the constant.
1315             // eg.
1316             //   ; %Val is true on the edge to %then.
1317             //   %Val = and i1 %Condition, true.
1318             //   br %Condition, label %then, label %else
1319             APInt ConditionVal(1, isTrueDest ? 1 : 0);
1320             Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
1321           } else {
1322             // If one of Val's operand has an inferred value, we may be able to
1323             // infer the value of Val.
1324             // eg.
1325             //    ; %Val is 94 on the edge to %then.
1326             //    %Val = add i8 %Op, 1
1327             //    %Condition = icmp eq i8 %Op, 93
1328             //    br i1 %Condition, label %then, label %else
1329             for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1330               Value *Op = Usr->getOperand(i);
1331               ValueLatticeElement OpLatticeVal =
1332                   getValueFromCondition(Op, Condition, isTrueDest);
1333               if (Optional<APInt> OpConst = OpLatticeVal.asConstantInteger()) {
1334                 Result = constantFoldUser(Usr, Op, OpConst.getValue(), DL);
1335                 break;
1336               }
1337             }
1338           }
1339         }
1340       }
1341       if (!Result.isOverdefined())
1342         return Result;
1343     }
1344   }
1345 
1346   // If the edge was formed by a switch on the value, then we may know exactly
1347   // what it is.
1348   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1349     Value *Condition = SI->getCondition();
1350     if (!isa<IntegerType>(Val->getType()))
1351       return None;
1352     bool ValUsesConditionAndMayBeFoldable = false;
1353     if (Condition != Val) {
1354       // Check if Val has Condition as an operand.
1355       if (User *Usr = dyn_cast<User>(Val))
1356         ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1357             usesOperand(Usr, Condition);
1358       if (!ValUsesConditionAndMayBeFoldable)
1359         return None;
1360     }
1361     assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
1362            "Condition != Val nor Val doesn't use Condition");
1363 
1364     bool DefaultCase = SI->getDefaultDest() == BBTo;
1365     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1366     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1367 
1368     for (auto Case : SI->cases()) {
1369       APInt CaseValue = Case.getCaseValue()->getValue();
1370       ConstantRange EdgeVal(CaseValue);
1371       if (ValUsesConditionAndMayBeFoldable) {
1372         User *Usr = cast<User>(Val);
1373         const DataLayout &DL = BBTo->getModule()->getDataLayout();
1374         ValueLatticeElement EdgeLatticeVal =
1375             constantFoldUser(Usr, Condition, CaseValue, DL);
1376         if (EdgeLatticeVal.isOverdefined())
1377           return None;
1378         EdgeVal = EdgeLatticeVal.getConstantRange();
1379       }
1380       if (DefaultCase) {
1381         // It is possible that the default destination is the destination of
1382         // some cases. We cannot perform difference for those cases.
1383         // We know Condition != CaseValue in BBTo.  In some cases we can use
1384         // this to infer Val == f(Condition) is != f(CaseValue).  For now, we
1385         // only do this when f is identity (i.e. Val == Condition), but we
1386         // should be able to do this for any injective f.
1387         if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1388           EdgesVals = EdgesVals.difference(EdgeVal);
1389       } else if (Case.getCaseSuccessor() == BBTo)
1390         EdgesVals = EdgesVals.unionWith(EdgeVal);
1391     }
1392     return ValueLatticeElement::getRange(std::move(EdgesVals));
1393   }
1394   return None;
1395 }
1396 
1397 /// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1398 /// the basic block if the edge does not constrain Val.
1399 Optional<ValueLatticeElement> LazyValueInfoImpl::getEdgeValue(
1400     Value *Val, BasicBlock *BBFrom, BasicBlock *BBTo, Instruction *CxtI) {
1401   // If already a constant, there is nothing to compute.
1402   if (Constant *VC = dyn_cast<Constant>(Val))
1403     return ValueLatticeElement::get(VC);
1404 
1405   ValueLatticeElement LocalResult = getEdgeValueLocal(Val, BBFrom, BBTo)
1406       .getValueOr(ValueLatticeElement::getOverdefined());
1407   if (hasSingleValue(LocalResult))
1408     // Can't get any more precise here
1409     return LocalResult;
1410 
1411   Optional<ValueLatticeElement> OptInBlock = getBlockValue(Val, BBFrom);
1412   if (!OptInBlock)
1413     return None;
1414   ValueLatticeElement &InBlock = *OptInBlock;
1415 
1416   // Try to intersect ranges of the BB and the constraint on the edge.
1417   intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1418                                                 BBFrom->getTerminator());
1419   // We can use the context instruction (generically the ultimate instruction
1420   // the calling pass is trying to simplify) here, even though the result of
1421   // this function is generally cached when called from the solve* functions
1422   // (and that cached result might be used with queries using a different
1423   // context instruction), because when this function is called from the solve*
1424   // functions, the context instruction is not provided. When called from
1425   // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1426   // but then the result is not cached.
1427   intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1428 
1429   return intersect(LocalResult, InBlock);
1430 }
1431 
1432 ValueLatticeElement LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
1433                                                        Instruction *CxtI) {
1434   LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1435                     << BB->getName() << "'\n");
1436 
1437   assert(BlockValueStack.empty() && BlockValueSet.empty());
1438   Optional<ValueLatticeElement> OptResult = getBlockValue(V, BB);
1439   if (!OptResult) {
1440     solve();
1441     OptResult = getBlockValue(V, BB);
1442     assert(OptResult && "Value not available after solving");
1443   }
1444   ValueLatticeElement Result = *OptResult;
1445   intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1446 
1447   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
1448   return Result;
1449 }
1450 
1451 ValueLatticeElement LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
1452   LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()
1453                     << "'\n");
1454 
1455   if (auto *C = dyn_cast<Constant>(V))
1456     return ValueLatticeElement::get(C);
1457 
1458   ValueLatticeElement Result = ValueLatticeElement::getOverdefined();
1459   if (auto *I = dyn_cast<Instruction>(V))
1460     Result = getFromRangeMetadata(I);
1461   intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1462 
1463   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
1464   return Result;
1465 }
1466 
1467 ValueLatticeElement LazyValueInfoImpl::
1468 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1469                Instruction *CxtI) {
1470   LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1471                     << FromBB->getName() << "' to '" << ToBB->getName()
1472                     << "'\n");
1473 
1474   Optional<ValueLatticeElement> Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1475   if (!Result) {
1476     solve();
1477     Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1478     assert(Result && "More work to do after problem solved?");
1479   }
1480 
1481   LLVM_DEBUG(dbgs() << "  Result = " << *Result << "\n");
1482   return *Result;
1483 }
1484 
1485 void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1486                                    BasicBlock *NewSucc) {
1487   TheCache.threadEdgeImpl(OldSucc, NewSucc);
1488 }
1489 
1490 //===----------------------------------------------------------------------===//
1491 //                            LazyValueInfo Impl
1492 //===----------------------------------------------------------------------===//
1493 
1494 /// This lazily constructs the LazyValueInfoImpl.
1495 static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1496                                   const Module *M) {
1497   if (!PImpl) {
1498     assert(M && "getCache() called with a null Module");
1499     const DataLayout &DL = M->getDataLayout();
1500     Function *GuardDecl = M->getFunction(
1501         Intrinsic::getName(Intrinsic::experimental_guard));
1502     PImpl = new LazyValueInfoImpl(AC, DL, GuardDecl);
1503   }
1504   return *static_cast<LazyValueInfoImpl*>(PImpl);
1505 }
1506 
1507 bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1508   Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1509   Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1510 
1511   if (Info.PImpl)
1512     getImpl(Info.PImpl, Info.AC, F.getParent()).clear();
1513 
1514   // Fully lazy.
1515   return false;
1516 }
1517 
1518 void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1519   AU.setPreservesAll();
1520   AU.addRequired<AssumptionCacheTracker>();
1521   AU.addRequired<TargetLibraryInfoWrapperPass>();
1522 }
1523 
1524 LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1525 
1526 LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1527 
1528 void LazyValueInfo::releaseMemory() {
1529   // If the cache was allocated, free it.
1530   if (PImpl) {
1531     delete &getImpl(PImpl, AC, nullptr);
1532     PImpl = nullptr;
1533   }
1534 }
1535 
1536 bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
1537                                FunctionAnalysisManager::Invalidator &Inv) {
1538   // We need to invalidate if we have either failed to preserve this analyses
1539   // result directly or if any of its dependencies have been invalidated.
1540   auto PAC = PA.getChecker<LazyValueAnalysis>();
1541   if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
1542     return true;
1543 
1544   return false;
1545 }
1546 
1547 void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1548 
1549 LazyValueInfo LazyValueAnalysis::run(Function &F,
1550                                      FunctionAnalysisManager &FAM) {
1551   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1552   auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1553 
1554   return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI);
1555 }
1556 
1557 /// Returns true if we can statically tell that this value will never be a
1558 /// "useful" constant.  In practice, this means we've got something like an
1559 /// alloca or a malloc call for which a comparison against a constant can
1560 /// only be guarding dead code.  Note that we are potentially giving up some
1561 /// precision in dead code (a constant result) in favour of avoiding a
1562 /// expensive search for a easily answered common query.
1563 static bool isKnownNonConstant(Value *V) {
1564   V = V->stripPointerCasts();
1565   // The return val of alloc cannot be a Constant.
1566   if (isa<AllocaInst>(V))
1567     return true;
1568   return false;
1569 }
1570 
1571 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1572                                      Instruction *CxtI) {
1573   // Bail out early if V is known not to be a Constant.
1574   if (isKnownNonConstant(V))
1575     return nullptr;
1576 
1577   ValueLatticeElement Result =
1578       getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
1579 
1580   if (Result.isConstant())
1581     return Result.getConstant();
1582   if (Result.isConstantRange()) {
1583     const ConstantRange &CR = Result.getConstantRange();
1584     if (const APInt *SingleVal = CR.getSingleElement())
1585       return ConstantInt::get(V->getContext(), *SingleVal);
1586   }
1587   return nullptr;
1588 }
1589 
1590 ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
1591                                               Instruction *CxtI,
1592                                               bool UndefAllowed) {
1593   assert(V->getType()->isIntegerTy());
1594   unsigned Width = V->getType()->getIntegerBitWidth();
1595   ValueLatticeElement Result =
1596       getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
1597   if (Result.isUnknown())
1598     return ConstantRange::getEmpty(Width);
1599   if (Result.isConstantRange(UndefAllowed))
1600     return Result.getConstantRange(UndefAllowed);
1601   // We represent ConstantInt constants as constant ranges but other kinds
1602   // of integer constants, i.e. ConstantExpr will be tagged as constants
1603   assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1604          "ConstantInt value must be represented as constantrange");
1605   return ConstantRange::getFull(Width);
1606 }
1607 
1608 /// Determine whether the specified value is known to be a
1609 /// constant on the specified edge. Return null if not.
1610 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1611                                            BasicBlock *ToBB,
1612                                            Instruction *CxtI) {
1613   Module *M = FromBB->getModule();
1614   ValueLatticeElement Result =
1615       getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1616 
1617   if (Result.isConstant())
1618     return Result.getConstant();
1619   if (Result.isConstantRange()) {
1620     const ConstantRange &CR = Result.getConstantRange();
1621     if (const APInt *SingleVal = CR.getSingleElement())
1622       return ConstantInt::get(V->getContext(), *SingleVal);
1623   }
1624   return nullptr;
1625 }
1626 
1627 ConstantRange LazyValueInfo::getConstantRangeOnEdge(Value *V,
1628                                                     BasicBlock *FromBB,
1629                                                     BasicBlock *ToBB,
1630                                                     Instruction *CxtI) {
1631   unsigned Width = V->getType()->getIntegerBitWidth();
1632   Module *M = FromBB->getModule();
1633   ValueLatticeElement Result =
1634       getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1635 
1636   if (Result.isUnknown())
1637     return ConstantRange::getEmpty(Width);
1638   if (Result.isConstantRange())
1639     return Result.getConstantRange();
1640   // We represent ConstantInt constants as constant ranges but other kinds
1641   // of integer constants, i.e. ConstantExpr will be tagged as constants
1642   assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1643          "ConstantInt value must be represented as constantrange");
1644   return ConstantRange::getFull(Width);
1645 }
1646 
1647 static LazyValueInfo::Tristate
1648 getPredicateResult(unsigned Pred, Constant *C, const ValueLatticeElement &Val,
1649                    const DataLayout &DL, TargetLibraryInfo *TLI) {
1650   // If we know the value is a constant, evaluate the conditional.
1651   Constant *Res = nullptr;
1652   if (Val.isConstant()) {
1653     Res = ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL, TLI);
1654     if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1655       return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1656     return LazyValueInfo::Unknown;
1657   }
1658 
1659   if (Val.isConstantRange()) {
1660     ConstantInt *CI = dyn_cast<ConstantInt>(C);
1661     if (!CI) return LazyValueInfo::Unknown;
1662 
1663     const ConstantRange &CR = Val.getConstantRange();
1664     if (Pred == ICmpInst::ICMP_EQ) {
1665       if (!CR.contains(CI->getValue()))
1666         return LazyValueInfo::False;
1667 
1668       if (CR.isSingleElement())
1669         return LazyValueInfo::True;
1670     } else if (Pred == ICmpInst::ICMP_NE) {
1671       if (!CR.contains(CI->getValue()))
1672         return LazyValueInfo::True;
1673 
1674       if (CR.isSingleElement())
1675         return LazyValueInfo::False;
1676     } else {
1677       // Handle more complex predicates.
1678       ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1679           (ICmpInst::Predicate)Pred, CI->getValue());
1680       if (TrueValues.contains(CR))
1681         return LazyValueInfo::True;
1682       if (TrueValues.inverse().contains(CR))
1683         return LazyValueInfo::False;
1684     }
1685     return LazyValueInfo::Unknown;
1686   }
1687 
1688   if (Val.isNotConstant()) {
1689     // If this is an equality comparison, we can try to fold it knowing that
1690     // "V != C1".
1691     if (Pred == ICmpInst::ICMP_EQ) {
1692       // !C1 == C -> false iff C1 == C.
1693       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1694                                             Val.getNotConstant(), C, DL,
1695                                             TLI);
1696       if (Res->isNullValue())
1697         return LazyValueInfo::False;
1698     } else if (Pred == ICmpInst::ICMP_NE) {
1699       // !C1 != C -> true iff C1 == C.
1700       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1701                                             Val.getNotConstant(), C, DL,
1702                                             TLI);
1703       if (Res->isNullValue())
1704         return LazyValueInfo::True;
1705     }
1706     return LazyValueInfo::Unknown;
1707   }
1708 
1709   return LazyValueInfo::Unknown;
1710 }
1711 
1712 /// Determine whether the specified value comparison with a constant is known to
1713 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1714 LazyValueInfo::Tristate
1715 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1716                                   BasicBlock *FromBB, BasicBlock *ToBB,
1717                                   Instruction *CxtI) {
1718   Module *M = FromBB->getModule();
1719   ValueLatticeElement Result =
1720       getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1721 
1722   return getPredicateResult(Pred, C, Result, M->getDataLayout(), TLI);
1723 }
1724 
1725 LazyValueInfo::Tristate
1726 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1727                               Instruction *CxtI) {
1728   // Is or is not NonNull are common predicates being queried. If
1729   // isKnownNonZero can tell us the result of the predicate, we can
1730   // return it quickly. But this is only a fastpath, and falling
1731   // through would still be correct.
1732   Module *M = CxtI->getModule();
1733   const DataLayout &DL = M->getDataLayout();
1734   if (V->getType()->isPointerTy() && C->isNullValue() &&
1735       isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
1736     if (Pred == ICmpInst::ICMP_EQ)
1737       return LazyValueInfo::False;
1738     else if (Pred == ICmpInst::ICMP_NE)
1739       return LazyValueInfo::True;
1740   }
1741   ValueLatticeElement Result = getImpl(PImpl, AC, M).getValueAt(V, CxtI);
1742   Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1743   if (Ret != Unknown)
1744     return Ret;
1745 
1746   // Note: The following bit of code is somewhat distinct from the rest of LVI;
1747   // LVI as a whole tries to compute a lattice value which is conservatively
1748   // correct at a given location.  In this case, we have a predicate which we
1749   // weren't able to prove about the merged result, and we're pushing that
1750   // predicate back along each incoming edge to see if we can prove it
1751   // separately for each input.  As a motivating example, consider:
1752   // bb1:
1753   //   %v1 = ... ; constantrange<1, 5>
1754   //   br label %merge
1755   // bb2:
1756   //   %v2 = ... ; constantrange<10, 20>
1757   //   br label %merge
1758   // merge:
1759   //   %phi = phi [%v1, %v2] ; constantrange<1,20>
1760   //   %pred = icmp eq i32 %phi, 8
1761   // We can't tell from the lattice value for '%phi' that '%pred' is false
1762   // along each path, but by checking the predicate over each input separately,
1763   // we can.
1764   // We limit the search to one step backwards from the current BB and value.
1765   // We could consider extending this to search further backwards through the
1766   // CFG and/or value graph, but there are non-obvious compile time vs quality
1767   // tradeoffs.
1768   if (CxtI) {
1769     BasicBlock *BB = CxtI->getParent();
1770 
1771     // Function entry or an unreachable block.  Bail to avoid confusing
1772     // analysis below.
1773     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1774     if (PI == PE)
1775       return Unknown;
1776 
1777     // If V is a PHI node in the same block as the context, we need to ask
1778     // questions about the predicate as applied to the incoming value along
1779     // each edge. This is useful for eliminating cases where the predicate is
1780     // known along all incoming edges.
1781     if (auto *PHI = dyn_cast<PHINode>(V))
1782       if (PHI->getParent() == BB) {
1783         Tristate Baseline = Unknown;
1784         for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1785           Value *Incoming = PHI->getIncomingValue(i);
1786           BasicBlock *PredBB = PHI->getIncomingBlock(i);
1787           // Note that PredBB may be BB itself.
1788           Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1789                                                CxtI);
1790 
1791           // Keep going as long as we've seen a consistent known result for
1792           // all inputs.
1793           Baseline = (i == 0) ? Result /* First iteration */
1794             : (Baseline == Result ? Baseline : Unknown); /* All others */
1795           if (Baseline == Unknown)
1796             break;
1797         }
1798         if (Baseline != Unknown)
1799           return Baseline;
1800       }
1801 
1802     // For a comparison where the V is outside this block, it's possible
1803     // that we've branched on it before. Look to see if the value is known
1804     // on all incoming edges.
1805     if (!isa<Instruction>(V) ||
1806         cast<Instruction>(V)->getParent() != BB) {
1807       // For predecessor edge, determine if the comparison is true or false
1808       // on that edge. If they're all true or all false, we can conclude
1809       // the value of the comparison in this block.
1810       Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1811       if (Baseline != Unknown) {
1812         // Check that all remaining incoming values match the first one.
1813         while (++PI != PE) {
1814           Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1815           if (Ret != Baseline) break;
1816         }
1817         // If we terminated early, then one of the values didn't match.
1818         if (PI == PE) {
1819           return Baseline;
1820         }
1821       }
1822     }
1823   }
1824   return Unknown;
1825 }
1826 
1827 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1828                                BasicBlock *NewSucc) {
1829   if (PImpl) {
1830     getImpl(PImpl, AC, PredBB->getModule())
1831         .threadEdge(PredBB, OldSucc, NewSucc);
1832   }
1833 }
1834 
1835 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1836   if (PImpl) {
1837     getImpl(PImpl, AC, BB->getModule()).eraseBlock(BB);
1838   }
1839 }
1840 
1841 
1842 void LazyValueInfo::printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
1843   if (PImpl) {
1844     getImpl(PImpl, AC, F.getParent()).printLVI(F, DTree, OS);
1845   }
1846 }
1847 
1848 // Print the LVI for the function arguments at the start of each basic block.
1849 void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
1850     const BasicBlock *BB, formatted_raw_ostream &OS) {
1851   // Find if there are latticevalues defined for arguments of the function.
1852   auto *F = BB->getParent();
1853   for (auto &Arg : F->args()) {
1854     ValueLatticeElement Result = LVIImpl->getValueInBlock(
1855         const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
1856     if (Result.isUnknown())
1857       continue;
1858     OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
1859   }
1860 }
1861 
1862 // This function prints the LVI analysis for the instruction I at the beginning
1863 // of various basic blocks. It relies on calculated values that are stored in
1864 // the LazyValueInfoCache, and in the absence of cached values, recalculate the
1865 // LazyValueInfo for `I`, and print that info.
1866 void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
1867     const Instruction *I, formatted_raw_ostream &OS) {
1868 
1869   auto *ParentBB = I->getParent();
1870   SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
1871   // We can generate (solve) LVI values only for blocks that are dominated by
1872   // the I's parent. However, to avoid generating LVI for all dominating blocks,
1873   // that contain redundant/uninteresting information, we print LVI for
1874   // blocks that may use this LVI information (such as immediate successor
1875   // blocks, and blocks that contain uses of `I`).
1876   auto printResult = [&](const BasicBlock *BB) {
1877     if (!BlocksContainingLVI.insert(BB).second)
1878       return;
1879     ValueLatticeElement Result = LVIImpl->getValueInBlock(
1880         const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
1881       OS << "; LatticeVal for: '" << *I << "' in BB: '";
1882       BB->printAsOperand(OS, false);
1883       OS << "' is: " << Result << "\n";
1884   };
1885 
1886   printResult(ParentBB);
1887   // Print the LVI analysis results for the immediate successor blocks, that
1888   // are dominated by `ParentBB`.
1889   for (auto *BBSucc : successors(ParentBB))
1890     if (DT.dominates(ParentBB, BBSucc))
1891       printResult(BBSucc);
1892 
1893   // Print LVI in blocks where `I` is used.
1894   for (auto *U : I->users())
1895     if (auto *UseI = dyn_cast<Instruction>(U))
1896       if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
1897         printResult(UseI->getParent());
1898 
1899 }
1900 
1901 namespace {
1902 // Printer class for LazyValueInfo results.
1903 class LazyValueInfoPrinter : public FunctionPass {
1904 public:
1905   static char ID; // Pass identification, replacement for typeid
1906   LazyValueInfoPrinter() : FunctionPass(ID) {
1907     initializeLazyValueInfoPrinterPass(*PassRegistry::getPassRegistry());
1908   }
1909 
1910   void getAnalysisUsage(AnalysisUsage &AU) const override {
1911     AU.setPreservesAll();
1912     AU.addRequired<LazyValueInfoWrapperPass>();
1913     AU.addRequired<DominatorTreeWrapperPass>();
1914   }
1915 
1916   // Get the mandatory dominator tree analysis and pass this in to the
1917   // LVIPrinter. We cannot rely on the LVI's DT, since it's optional.
1918   bool runOnFunction(Function &F) override {
1919     dbgs() << "LVI for function '" << F.getName() << "':\n";
1920     auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
1921     auto &DTree = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1922     LVI.printLVI(F, DTree, dbgs());
1923     return false;
1924   }
1925 };
1926 }
1927 
1928 char LazyValueInfoPrinter::ID = 0;
1929 INITIALIZE_PASS_BEGIN(LazyValueInfoPrinter, "print-lazy-value-info",
1930                 "Lazy Value Info Printer Pass", false, false)
1931 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
1932 INITIALIZE_PASS_END(LazyValueInfoPrinter, "print-lazy-value-info",
1933                 "Lazy Value Info Printer Pass", false, false)
1934