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