xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/LazyValueInfo.cpp (revision 8a4dda33d67586ca2624f2a38417baa03a533a7f)
10b57cec5SDimitry Andric //===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines the interface for lazy computation of value constraint
100b57cec5SDimitry Andric // information.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/Analysis/LazyValueInfo.h"
150b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
160b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
170b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/ValueLattice.h"
22480093f4SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
230b57cec5SDimitry Andric #include "llvm/IR/AssemblyAnnotationWriter.h"
240b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
250b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h"
260b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
270b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
280b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
290b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
300b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
310b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
320b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
330b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
340b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
35480093f4SDimitry Andric #include "llvm/InitializePasses.h"
360b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
370b57cec5SDimitry Andric #include "llvm/Support/FormattedStream.h"
38e8d8bef9SDimitry Andric #include "llvm/Support/KnownBits.h"
390b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
40bdd1243dSDimitry Andric #include <optional>
410b57cec5SDimitry Andric using namespace llvm;
420b57cec5SDimitry Andric using namespace PatternMatch;
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric #define DEBUG_TYPE "lazy-value-info"
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric // This is the number of worklist items we will process to try to discover an
470b57cec5SDimitry Andric // answer for a given value.
480b57cec5SDimitry Andric static const unsigned MaxProcessedPerValue = 500;
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric char LazyValueInfoWrapperPass::ID = 0;
51480093f4SDimitry Andric LazyValueInfoWrapperPass::LazyValueInfoWrapperPass() : FunctionPass(ID) {
52480093f4SDimitry Andric   initializeLazyValueInfoWrapperPassPass(*PassRegistry::getPassRegistry());
53480093f4SDimitry Andric }
540b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
550b57cec5SDimitry Andric                 "Lazy Value Information Analysis", false, true)
560b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
570b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
580b57cec5SDimitry Andric INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
590b57cec5SDimitry Andric                 "Lazy Value Information Analysis", false, true)
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric namespace llvm {
620b57cec5SDimitry Andric   FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
630b57cec5SDimitry Andric }
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric AnalysisKey LazyValueAnalysis::Key;
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric /// Returns true if this lattice value represents at most one possible value.
680b57cec5SDimitry Andric /// This is as precise as any lattice value can get while still representing
690b57cec5SDimitry Andric /// reachable code.
700b57cec5SDimitry Andric static bool hasSingleValue(const ValueLatticeElement &Val) {
710b57cec5SDimitry Andric   if (Val.isConstantRange() &&
720b57cec5SDimitry Andric       Val.getConstantRange().isSingleElement())
730b57cec5SDimitry Andric     // Integer constants are single element ranges
740b57cec5SDimitry Andric     return true;
750b57cec5SDimitry Andric   if (Val.isConstant())
760b57cec5SDimitry Andric     // Non integer constants
770b57cec5SDimitry Andric     return true;
780b57cec5SDimitry Andric   return false;
790b57cec5SDimitry Andric }
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric /// Combine two sets of facts about the same value into a single set of
820b57cec5SDimitry Andric /// facts.  Note that this method is not suitable for merging facts along
830b57cec5SDimitry Andric /// different paths in a CFG; that's what the mergeIn function is for.  This
840b57cec5SDimitry Andric /// is for merging facts gathered about the same value at the same location
850b57cec5SDimitry Andric /// through two independent means.
860b57cec5SDimitry Andric /// Notes:
870b57cec5SDimitry Andric /// * This method does not promise to return the most precise possible lattice
880b57cec5SDimitry Andric ///   value implied by A and B.  It is allowed to return any lattice element
890b57cec5SDimitry Andric ///   which is at least as strong as *either* A or B (unless our facts
900b57cec5SDimitry Andric ///   conflict, see below).
910b57cec5SDimitry Andric /// * Due to unreachable code, the intersection of two lattice values could be
920b57cec5SDimitry Andric ///   contradictory.  If this happens, we return some valid lattice value so as
930b57cec5SDimitry Andric ///   not confuse the rest of LVI.  Ideally, we'd always return Undefined, but
940b57cec5SDimitry Andric ///   we do not make this guarantee.  TODO: This would be a useful enhancement.
950b57cec5SDimitry Andric static ValueLatticeElement intersect(const ValueLatticeElement &A,
960b57cec5SDimitry Andric                                      const ValueLatticeElement &B) {
970b57cec5SDimitry Andric   // Undefined is the strongest state.  It means the value is known to be along
980b57cec5SDimitry Andric   // an unreachable path.
99d65cd7a5SDimitry Andric   if (A.isUnknown())
1000b57cec5SDimitry Andric     return A;
101d65cd7a5SDimitry Andric   if (B.isUnknown())
1020b57cec5SDimitry Andric     return B;
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric   // If we gave up for one, but got a useable fact from the other, use it.
1050b57cec5SDimitry Andric   if (A.isOverdefined())
1060b57cec5SDimitry Andric     return B;
1070b57cec5SDimitry Andric   if (B.isOverdefined())
1080b57cec5SDimitry Andric     return A;
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   // Can't get any more precise than constants.
1110b57cec5SDimitry Andric   if (hasSingleValue(A))
1120b57cec5SDimitry Andric     return A;
1130b57cec5SDimitry Andric   if (hasSingleValue(B))
1140b57cec5SDimitry Andric     return B;
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric   // Could be either constant range or not constant here.
1170b57cec5SDimitry Andric   if (!A.isConstantRange() || !B.isConstantRange()) {
1180b57cec5SDimitry Andric     // TODO: Arbitrary choice, could be improved
1190b57cec5SDimitry Andric     return A;
1200b57cec5SDimitry Andric   }
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric   // Intersect two constant ranges
1230b57cec5SDimitry Andric   ConstantRange Range =
1240b57cec5SDimitry Andric       A.getConstantRange().intersectWith(B.getConstantRange());
1255ffd83dbSDimitry Andric   // Note: An empty range is implicitly converted to unknown or undef depending
1265ffd83dbSDimitry Andric   // on MayIncludeUndef internally.
1275ffd83dbSDimitry Andric   return ValueLatticeElement::getRange(
128349cc55cSDimitry Andric       std::move(Range), /*MayIncludeUndef=*/A.isConstantRangeIncludingUndef() ||
1295ffd83dbSDimitry Andric                             B.isConstantRangeIncludingUndef());
1300b57cec5SDimitry Andric }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1330b57cec5SDimitry Andric //                          LazyValueInfoCache Decl
1340b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric namespace {
1370b57cec5SDimitry Andric   /// A callback value handle updates the cache when values are erased.
1380b57cec5SDimitry Andric   class LazyValueInfoCache;
1390b57cec5SDimitry Andric   struct LVIValueHandle final : public CallbackVH {
1400b57cec5SDimitry Andric     LazyValueInfoCache *Parent;
1410b57cec5SDimitry Andric 
1425ffd83dbSDimitry Andric     LVIValueHandle(Value *V, LazyValueInfoCache *P = nullptr)
1430b57cec5SDimitry Andric       : CallbackVH(V), Parent(P) { }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric     void deleted() override;
1460b57cec5SDimitry Andric     void allUsesReplacedWith(Value *V) override {
1470b57cec5SDimitry Andric       deleted();
1480b57cec5SDimitry Andric     }
1490b57cec5SDimitry Andric   };
1500b57cec5SDimitry Andric } // end anonymous namespace
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric namespace {
153e8d8bef9SDimitry Andric   using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
154e8d8bef9SDimitry Andric 
1550b57cec5SDimitry Andric   /// This is the cache kept by LazyValueInfo which
1560b57cec5SDimitry Andric   /// maintains information about queries across the clients' queries.
1570b57cec5SDimitry Andric   class LazyValueInfoCache {
1585ffd83dbSDimitry Andric     /// This is all of the cached information for one basic block. It contains
1595ffd83dbSDimitry Andric     /// the per-value lattice elements, as well as a separate set for
160e8d8bef9SDimitry Andric     /// overdefined values to reduce memory usage. Additionally pointers
161e8d8bef9SDimitry Andric     /// dereferenced in the block are cached for nullability queries.
1625ffd83dbSDimitry Andric     struct BlockCacheEntry {
1635ffd83dbSDimitry Andric       SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
1645ffd83dbSDimitry Andric       SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
16506c3fb27SDimitry Andric       // std::nullopt indicates that the nonnull pointers for this basic block
166e8d8bef9SDimitry Andric       // block have not been computed yet.
167bdd1243dSDimitry Andric       std::optional<NonNullPointerSet> NonNullPointers;
1680b57cec5SDimitry Andric     };
1690b57cec5SDimitry Andric 
1705ffd83dbSDimitry Andric     /// Cached information per basic block.
1715ffd83dbSDimitry Andric     DenseMap<PoisoningVH<BasicBlock>, std::unique_ptr<BlockCacheEntry>>
1725ffd83dbSDimitry Andric         BlockCache;
1735ffd83dbSDimitry Andric     /// Set of value handles used to erase values from the cache on deletion.
1745ffd83dbSDimitry Andric     DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
1750b57cec5SDimitry Andric 
1765ffd83dbSDimitry Andric     const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
1775ffd83dbSDimitry Andric       auto It = BlockCache.find_as(BB);
1785ffd83dbSDimitry Andric       if (It == BlockCache.end())
1795ffd83dbSDimitry Andric         return nullptr;
1805ffd83dbSDimitry Andric       return It->second.get();
1815ffd83dbSDimitry Andric     }
1820b57cec5SDimitry Andric 
1835ffd83dbSDimitry Andric     BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
1845ffd83dbSDimitry Andric       auto It = BlockCache.find_as(BB);
1855ffd83dbSDimitry Andric       if (It == BlockCache.end())
1865ffd83dbSDimitry Andric         It = BlockCache.insert({ BB, std::make_unique<BlockCacheEntry>() })
1875ffd83dbSDimitry Andric                        .first;
1885ffd83dbSDimitry Andric 
1895ffd83dbSDimitry Andric       return It->second.get();
1905ffd83dbSDimitry Andric     }
1915ffd83dbSDimitry Andric 
1925ffd83dbSDimitry Andric     void addValueHandle(Value *Val) {
1935ffd83dbSDimitry Andric       auto HandleIt = ValueHandles.find_as(Val);
1945ffd83dbSDimitry Andric       if (HandleIt == ValueHandles.end())
1955ffd83dbSDimitry Andric         ValueHandles.insert({ Val, this });
1965ffd83dbSDimitry Andric     }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric   public:
1990b57cec5SDimitry Andric     void insertResult(Value *Val, BasicBlock *BB,
2000b57cec5SDimitry Andric                       const ValueLatticeElement &Result) {
2015ffd83dbSDimitry Andric       BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric       // Insert over-defined values into their own cache to reduce memory
2040b57cec5SDimitry Andric       // overhead.
2050b57cec5SDimitry Andric       if (Result.isOverdefined())
2065ffd83dbSDimitry Andric         Entry->OverDefined.insert(Val);
2075ffd83dbSDimitry Andric       else
2085ffd83dbSDimitry Andric         Entry->LatticeElements.insert({ Val, Result });
2095ffd83dbSDimitry Andric 
2105ffd83dbSDimitry Andric       addValueHandle(Val);
2110b57cec5SDimitry Andric     }
2120b57cec5SDimitry Andric 
213bdd1243dSDimitry Andric     std::optional<ValueLatticeElement>
214bdd1243dSDimitry Andric     getCachedValueInfo(Value *V, BasicBlock *BB) const {
2155ffd83dbSDimitry Andric       const BlockCacheEntry *Entry = getBlockEntry(BB);
2165ffd83dbSDimitry Andric       if (!Entry)
217bdd1243dSDimitry Andric         return std::nullopt;
2180b57cec5SDimitry Andric 
2195ffd83dbSDimitry Andric       if (Entry->OverDefined.count(V))
2200b57cec5SDimitry Andric         return ValueLatticeElement::getOverdefined();
2210b57cec5SDimitry Andric 
2225ffd83dbSDimitry Andric       auto LatticeIt = Entry->LatticeElements.find_as(V);
2235ffd83dbSDimitry Andric       if (LatticeIt == Entry->LatticeElements.end())
224bdd1243dSDimitry Andric         return std::nullopt;
2255ffd83dbSDimitry Andric 
2265ffd83dbSDimitry Andric       return LatticeIt->second;
2270b57cec5SDimitry Andric     }
2280b57cec5SDimitry Andric 
229e8d8bef9SDimitry Andric     bool isNonNullAtEndOfBlock(
230e8d8bef9SDimitry Andric         Value *V, BasicBlock *BB,
231e8d8bef9SDimitry Andric         function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
232e8d8bef9SDimitry Andric       BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
233e8d8bef9SDimitry Andric       if (!Entry->NonNullPointers) {
234e8d8bef9SDimitry Andric         Entry->NonNullPointers = InitFn(BB);
235e8d8bef9SDimitry Andric         for (Value *V : *Entry->NonNullPointers)
236e8d8bef9SDimitry Andric           addValueHandle(V);
237e8d8bef9SDimitry Andric       }
238e8d8bef9SDimitry Andric 
239e8d8bef9SDimitry Andric       return Entry->NonNullPointers->count(V);
240e8d8bef9SDimitry Andric     }
241e8d8bef9SDimitry Andric 
2420b57cec5SDimitry Andric     /// clear - Empty the cache.
2430b57cec5SDimitry Andric     void clear() {
2445ffd83dbSDimitry Andric       BlockCache.clear();
2455ffd83dbSDimitry Andric       ValueHandles.clear();
2460b57cec5SDimitry Andric     }
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric     /// Inform the cache that a given value has been deleted.
2490b57cec5SDimitry Andric     void eraseValue(Value *V);
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric     /// This is part of the update interface to inform the cache
2520b57cec5SDimitry Andric     /// that a block has been deleted.
2530b57cec5SDimitry Andric     void eraseBlock(BasicBlock *BB);
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric     /// Updates the cache to remove any influence an overdefined value in
2560b57cec5SDimitry Andric     /// OldSucc might have (unless also overdefined in NewSucc).  This just
2570b57cec5SDimitry Andric     /// flushes elements from the cache and does not add any.
2580b57cec5SDimitry Andric     void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
2590b57cec5SDimitry Andric   };
2600b57cec5SDimitry Andric }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric void LazyValueInfoCache::eraseValue(Value *V) {
2635ffd83dbSDimitry Andric   for (auto &Pair : BlockCache) {
2645ffd83dbSDimitry Andric     Pair.second->LatticeElements.erase(V);
2655ffd83dbSDimitry Andric     Pair.second->OverDefined.erase(V);
266e8d8bef9SDimitry Andric     if (Pair.second->NonNullPointers)
267e8d8bef9SDimitry Andric       Pair.second->NonNullPointers->erase(V);
2680b57cec5SDimitry Andric   }
2690b57cec5SDimitry Andric 
2705ffd83dbSDimitry Andric   auto HandleIt = ValueHandles.find_as(V);
2715ffd83dbSDimitry Andric   if (HandleIt != ValueHandles.end())
2725ffd83dbSDimitry Andric     ValueHandles.erase(HandleIt);
2730b57cec5SDimitry Andric }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric void LVIValueHandle::deleted() {
2760b57cec5SDimitry Andric   // This erasure deallocates *this, so it MUST happen after we're done
2770b57cec5SDimitry Andric   // using any and all members of *this.
2780b57cec5SDimitry Andric   Parent->eraseValue(*this);
2790b57cec5SDimitry Andric }
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
2825ffd83dbSDimitry Andric   BlockCache.erase(BB);
2830b57cec5SDimitry Andric }
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
2860b57cec5SDimitry Andric                                         BasicBlock *NewSucc) {
2870b57cec5SDimitry Andric   // When an edge in the graph has been threaded, values that we could not
2880b57cec5SDimitry Andric   // determine a value for before (i.e. were marked overdefined) may be
2890b57cec5SDimitry Andric   // possible to solve now. We do NOT try to proactively update these values.
2900b57cec5SDimitry Andric   // Instead, we clear their entries from the cache, and allow lazy updating to
2910b57cec5SDimitry Andric   // recompute them when needed.
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric   // The updating process is fairly simple: we need to drop cached info
2940b57cec5SDimitry Andric   // for all values that were marked overdefined in OldSucc, and for those same
2950b57cec5SDimitry Andric   // values in any successor of OldSucc (except NewSucc) in which they were
2960b57cec5SDimitry Andric   // also marked overdefined.
2970b57cec5SDimitry Andric   std::vector<BasicBlock*> worklist;
2980b57cec5SDimitry Andric   worklist.push_back(OldSucc);
2990b57cec5SDimitry Andric 
3005ffd83dbSDimitry Andric   const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
3015ffd83dbSDimitry Andric   if (!Entry || Entry->OverDefined.empty())
3020b57cec5SDimitry Andric     return; // Nothing to process here.
3035ffd83dbSDimitry Andric   SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
3045ffd83dbSDimitry Andric                                       Entry->OverDefined.end());
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric   // Use a worklist to perform a depth-first search of OldSucc's successors.
3070b57cec5SDimitry Andric   // NOTE: We do not need a visited list since any blocks we have already
3080b57cec5SDimitry Andric   // visited will have had their overdefined markers cleared already, and we
3090b57cec5SDimitry Andric   // thus won't loop to their successors.
3100b57cec5SDimitry Andric   while (!worklist.empty()) {
3110b57cec5SDimitry Andric     BasicBlock *ToUpdate = worklist.back();
3120b57cec5SDimitry Andric     worklist.pop_back();
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric     // Skip blocks only accessible through NewSucc.
3150b57cec5SDimitry Andric     if (ToUpdate == NewSucc) continue;
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric     // If a value was marked overdefined in OldSucc, and is here too...
3185ffd83dbSDimitry Andric     auto OI = BlockCache.find_as(ToUpdate);
3195ffd83dbSDimitry Andric     if (OI == BlockCache.end() || OI->second->OverDefined.empty())
3200b57cec5SDimitry Andric       continue;
3215ffd83dbSDimitry Andric     auto &ValueSet = OI->second->OverDefined;
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric     bool changed = false;
3240b57cec5SDimitry Andric     for (Value *V : ValsToClear) {
3250b57cec5SDimitry Andric       if (!ValueSet.erase(V))
3260b57cec5SDimitry Andric         continue;
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric       // If we removed anything, then we potentially need to update
3290b57cec5SDimitry Andric       // blocks successors too.
3300b57cec5SDimitry Andric       changed = true;
3310b57cec5SDimitry Andric     }
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric     if (!changed) continue;
3340b57cec5SDimitry Andric 
335e8d8bef9SDimitry Andric     llvm::append_range(worklist, successors(ToUpdate));
3360b57cec5SDimitry Andric   }
3370b57cec5SDimitry Andric }
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric namespace {
3410b57cec5SDimitry Andric /// An assembly annotator class to print LazyValueCache information in
3420b57cec5SDimitry Andric /// comments.
3430b57cec5SDimitry Andric class LazyValueInfoImpl;
3440b57cec5SDimitry Andric class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
3450b57cec5SDimitry Andric   LazyValueInfoImpl *LVIImpl;
3460b57cec5SDimitry Andric   // While analyzing which blocks we can solve values for, we need the dominator
3475ffd83dbSDimitry Andric   // information.
3480b57cec5SDimitry Andric   DominatorTree &DT;
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric public:
3510b57cec5SDimitry Andric   LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
3520b57cec5SDimitry Andric       : LVIImpl(L), DT(DTree) {}
3530b57cec5SDimitry Andric 
3545ffd83dbSDimitry Andric   void emitBasicBlockStartAnnot(const BasicBlock *BB,
3555ffd83dbSDimitry Andric                                 formatted_raw_ostream &OS) override;
3560b57cec5SDimitry Andric 
3575ffd83dbSDimitry Andric   void emitInstructionAnnot(const Instruction *I,
3585ffd83dbSDimitry Andric                             formatted_raw_ostream &OS) override;
3590b57cec5SDimitry Andric };
3600b57cec5SDimitry Andric }
3610b57cec5SDimitry Andric namespace {
3620b57cec5SDimitry Andric // The actual implementation of the lazy analysis and update.  Note that the
3630b57cec5SDimitry Andric // inheritance from LazyValueInfoCache is intended to be temporary while
3640b57cec5SDimitry Andric // splitting the code and then transitioning to a has-a relationship.
3650b57cec5SDimitry Andric class LazyValueInfoImpl {
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   /// Cached results from previous queries
3680b57cec5SDimitry Andric   LazyValueInfoCache TheCache;
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric   /// This stack holds the state of the value solver during a query.
3710b57cec5SDimitry Andric   /// It basically emulates the callstack of the naive
3720b57cec5SDimitry Andric   /// recursive value lookup process.
3730b57cec5SDimitry Andric   SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   /// Keeps track of which block-value pairs are in BlockValueStack.
3760b57cec5SDimitry Andric   DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   /// Push BV onto BlockValueStack unless it's already in there.
3790b57cec5SDimitry Andric   /// Returns true on success.
3800b57cec5SDimitry Andric   bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
3810b57cec5SDimitry Andric     if (!BlockValueSet.insert(BV).second)
3820b57cec5SDimitry Andric       return false;  // It's already in the stack.
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "
3850b57cec5SDimitry Andric                       << BV.first->getName() << "\n");
3860b57cec5SDimitry Andric     BlockValueStack.push_back(BV);
3870b57cec5SDimitry Andric     return true;
3880b57cec5SDimitry Andric   }
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   AssumptionCache *AC;  ///< A pointer to the cache of @llvm.assume calls.
3910b57cec5SDimitry Andric   const DataLayout &DL; ///< A mandatory DataLayout
3920b57cec5SDimitry Andric 
3935ffd83dbSDimitry Andric   /// Declaration of the llvm.experimental.guard() intrinsic,
3945ffd83dbSDimitry Andric   /// if it exists in the module.
3955ffd83dbSDimitry Andric   Function *GuardDecl;
3965ffd83dbSDimitry Andric 
397bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> getBlockValue(Value *Val, BasicBlock *BB,
39804eeddc0SDimitry Andric                                                    Instruction *CxtI);
399bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
400bdd1243dSDimitry Andric                                                   BasicBlock *T,
401bdd1243dSDimitry Andric                                                   Instruction *CxtI = nullptr);
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric   // These methods process one work item and may add more. A false value
4040b57cec5SDimitry Andric   // returned means that the work item was not completely processed and must
4050b57cec5SDimitry Andric   // be revisited after going through the new items.
4060b57cec5SDimitry Andric   bool solveBlockValue(Value *Val, BasicBlock *BB);
407bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueImpl(Value *Val,
4080b57cec5SDimitry Andric                                                          BasicBlock *BB);
409bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
4100b57cec5SDimitry Andric                                                              BasicBlock *BB);
411bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
4120b57cec5SDimitry Andric                                                             BasicBlock *BB);
413bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
4140b57cec5SDimitry Andric                                                            BasicBlock *BB);
415bdd1243dSDimitry Andric   std::optional<ConstantRange> getRangeFor(Value *V, Instruction *CxtI,
416bdd1243dSDimitry Andric                                            BasicBlock *BB);
417bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
4185ffd83dbSDimitry Andric       Instruction *I, BasicBlock *BB,
419bdd1243dSDimitry Andric       std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
420bdd1243dSDimitry Andric           OpFn);
421bdd1243dSDimitry Andric   std::optional<ValueLatticeElement>
422bdd1243dSDimitry Andric   solveBlockValueBinaryOp(BinaryOperator *BBI, BasicBlock *BB);
423bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
4240b57cec5SDimitry Andric                                                          BasicBlock *BB);
425bdd1243dSDimitry Andric   std::optional<ValueLatticeElement>
426bdd1243dSDimitry Andric   solveBlockValueOverflowIntrinsic(WithOverflowInst *WO, BasicBlock *BB);
427bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
4280b57cec5SDimitry Andric                                                               BasicBlock *BB);
429bdd1243dSDimitry Andric   std::optional<ValueLatticeElement>
430bdd1243dSDimitry Andric   solveBlockValueExtractValue(ExtractValueInst *EVI, BasicBlock *BB);
431e8d8bef9SDimitry Andric   bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
4320b57cec5SDimitry Andric   void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
4330b57cec5SDimitry Andric                                                      ValueLatticeElement &BBLV,
4340b57cec5SDimitry Andric                                                      Instruction *BBI);
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric   void solve();
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric public:
439e8d8bef9SDimitry Andric   /// This is the query interface to determine the lattice value for the
440e8d8bef9SDimitry Andric   /// specified Value* at the context instruction (if specified) or at the
441e8d8bef9SDimitry Andric   /// start of the block.
4420b57cec5SDimitry Andric   ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB,
4430b57cec5SDimitry Andric                                       Instruction *CxtI = nullptr);
4440b57cec5SDimitry Andric 
445e8d8bef9SDimitry Andric   /// This is the query interface to determine the lattice value for the
446e8d8bef9SDimitry Andric   /// specified Value* at the specified instruction using only information
447e8d8bef9SDimitry Andric   /// from assumes/guards and range metadata. Unlike getValueInBlock(), no
448e8d8bef9SDimitry Andric   /// recursive query is performed.
4490b57cec5SDimitry Andric   ValueLatticeElement getValueAt(Value *V, Instruction *CxtI);
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric   /// This is the query interface to determine the lattice
4520b57cec5SDimitry Andric   /// value for the specified Value* that is true on the specified edge.
4530b57cec5SDimitry Andric   ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB,
4540b57cec5SDimitry Andric                                      BasicBlock *ToBB,
4550b57cec5SDimitry Andric                                      Instruction *CxtI = nullptr);
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric   /// Complete flush all previously computed values
4580b57cec5SDimitry Andric   void clear() {
4590b57cec5SDimitry Andric     TheCache.clear();
4600b57cec5SDimitry Andric   }
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   /// Printing the LazyValueInfo Analysis.
4630b57cec5SDimitry Andric   void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
4640b57cec5SDimitry Andric     LazyValueInfoAnnotatedWriter Writer(this, DTree);
4650b57cec5SDimitry Andric     F.print(OS, &Writer);
4660b57cec5SDimitry Andric   }
4670b57cec5SDimitry Andric 
468*8a4dda33SDimitry Andric   /// This is part of the update interface to remove information related to this
469*8a4dda33SDimitry Andric   /// value from the cache.
470*8a4dda33SDimitry Andric   void forgetValue(Value *V) { TheCache.eraseValue(V); }
471*8a4dda33SDimitry Andric 
4720b57cec5SDimitry Andric   /// This is part of the update interface to inform the cache
4730b57cec5SDimitry Andric   /// that a block has been deleted.
4740b57cec5SDimitry Andric   void eraseBlock(BasicBlock *BB) {
4750b57cec5SDimitry Andric     TheCache.eraseBlock(BB);
4760b57cec5SDimitry Andric   }
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   /// This is the update interface to inform the cache that an edge from
4790b57cec5SDimitry Andric   /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
4800b57cec5SDimitry Andric   void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric   LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
4835ffd83dbSDimitry Andric                     Function *GuardDecl)
4845ffd83dbSDimitry Andric       : AC(AC), DL(DL), GuardDecl(GuardDecl) {}
4850b57cec5SDimitry Andric };
4860b57cec5SDimitry Andric } // end anonymous namespace
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric void LazyValueInfoImpl::solve() {
4900b57cec5SDimitry Andric   SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
4910b57cec5SDimitry Andric       BlockValueStack.begin(), BlockValueStack.end());
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   unsigned processedCount = 0;
4940b57cec5SDimitry Andric   while (!BlockValueStack.empty()) {
4950b57cec5SDimitry Andric     processedCount++;
4960b57cec5SDimitry Andric     // Abort if we have to process too many values to get a result for this one.
4970b57cec5SDimitry Andric     // Because of the design of the overdefined cache currently being per-block
4980b57cec5SDimitry Andric     // to avoid naming-related issues (IE it wants to try to give different
4990b57cec5SDimitry Andric     // results for the same name in different blocks), overdefined results don't
5000b57cec5SDimitry Andric     // get cached globally, which in turn means we will often try to rediscover
5010b57cec5SDimitry Andric     // the same overdefined result again and again.  Once something like
5020b57cec5SDimitry Andric     // PredicateInfo is used in LVI or CVP, we should be able to make the
5030b57cec5SDimitry Andric     // overdefined cache global, and remove this throttle.
5040b57cec5SDimitry Andric     if (processedCount > MaxProcessedPerValue) {
5050b57cec5SDimitry Andric       LLVM_DEBUG(
5060b57cec5SDimitry Andric           dbgs() << "Giving up on stack because we are getting too deep\n");
5070b57cec5SDimitry Andric       // Fill in the original values
5080b57cec5SDimitry Andric       while (!StartingStack.empty()) {
5090b57cec5SDimitry Andric         std::pair<BasicBlock *, Value *> &e = StartingStack.back();
5100b57cec5SDimitry Andric         TheCache.insertResult(e.second, e.first,
5110b57cec5SDimitry Andric                               ValueLatticeElement::getOverdefined());
5120b57cec5SDimitry Andric         StartingStack.pop_back();
5130b57cec5SDimitry Andric       }
5140b57cec5SDimitry Andric       BlockValueSet.clear();
5150b57cec5SDimitry Andric       BlockValueStack.clear();
5160b57cec5SDimitry Andric       return;
5170b57cec5SDimitry Andric     }
5180b57cec5SDimitry Andric     std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
5190b57cec5SDimitry Andric     assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric     if (solveBlockValue(e.second, e.first)) {
5220b57cec5SDimitry Andric       // The work item was completely processed.
5230b57cec5SDimitry Andric       assert(BlockValueStack.back() == e && "Nothing should have been pushed!");
5245ffd83dbSDimitry Andric #ifndef NDEBUG
525bdd1243dSDimitry Andric       std::optional<ValueLatticeElement> BBLV =
5265ffd83dbSDimitry Andric           TheCache.getCachedValueInfo(e.second, e.first);
5275ffd83dbSDimitry Andric       assert(BBLV && "Result should be in cache!");
5280b57cec5SDimitry Andric       LLVM_DEBUG(
5290b57cec5SDimitry Andric           dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
5305ffd83dbSDimitry Andric                  << *BBLV << "\n");
5315ffd83dbSDimitry Andric #endif
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric       BlockValueStack.pop_back();
5340b57cec5SDimitry Andric       BlockValueSet.erase(e);
5350b57cec5SDimitry Andric     } else {
5360b57cec5SDimitry Andric       // More work needs to be done before revisiting.
5370b57cec5SDimitry Andric       assert(BlockValueStack.back() != e && "Stack should have been pushed!");
5380b57cec5SDimitry Andric     }
5390b57cec5SDimitry Andric   }
5400b57cec5SDimitry Andric }
5410b57cec5SDimitry Andric 
542bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
543bdd1243dSDimitry Andric LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB,
544bdd1243dSDimitry Andric                                  Instruction *CxtI) {
5450b57cec5SDimitry Andric   // If already a constant, there is nothing to compute.
5460b57cec5SDimitry Andric   if (Constant *VC = dyn_cast<Constant>(Val))
5470b57cec5SDimitry Andric     return ValueLatticeElement::get(VC);
5480b57cec5SDimitry Andric 
549bdd1243dSDimitry Andric   if (std::optional<ValueLatticeElement> OptLatticeVal =
55004eeddc0SDimitry Andric           TheCache.getCachedValueInfo(Val, BB)) {
55104eeddc0SDimitry Andric     intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CxtI);
5525ffd83dbSDimitry Andric     return OptLatticeVal;
55304eeddc0SDimitry Andric   }
5545ffd83dbSDimitry Andric 
5555ffd83dbSDimitry Andric   // We have hit a cycle, assume overdefined.
5565ffd83dbSDimitry Andric   if (!pushBlockValue({ BB, Val }))
5575ffd83dbSDimitry Andric     return ValueLatticeElement::getOverdefined();
5585ffd83dbSDimitry Andric 
5595ffd83dbSDimitry Andric   // Yet to be resolved.
560bdd1243dSDimitry Andric   return std::nullopt;
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric static ValueLatticeElement getFromRangeMetadata(Instruction *BBI) {
5640b57cec5SDimitry Andric   switch (BBI->getOpcode()) {
5650b57cec5SDimitry Andric   default: break;
5660b57cec5SDimitry Andric   case Instruction::Load:
5670b57cec5SDimitry Andric   case Instruction::Call:
5680b57cec5SDimitry Andric   case Instruction::Invoke:
5690b57cec5SDimitry Andric     if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
5700b57cec5SDimitry Andric       if (isa<IntegerType>(BBI->getType())) {
5710b57cec5SDimitry Andric         return ValueLatticeElement::getRange(
5720b57cec5SDimitry Andric             getConstantRangeFromMetadata(*Ranges));
5730b57cec5SDimitry Andric       }
5740b57cec5SDimitry Andric     break;
5750b57cec5SDimitry Andric   };
5760b57cec5SDimitry Andric   // Nothing known - will be intersected with other facts
5770b57cec5SDimitry Andric   return ValueLatticeElement::getOverdefined();
5780b57cec5SDimitry Andric }
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
5815ffd83dbSDimitry Andric   assert(!isa<Constant>(Val) && "Value should not be constant");
5825ffd83dbSDimitry Andric   assert(!TheCache.getCachedValueInfo(Val, BB) &&
5835ffd83dbSDimitry Andric          "Value should not be in cache");
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric   // Hold off inserting this value into the Cache in case we have to return
5860b57cec5SDimitry Andric   // false and come back later.
587bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
5885ffd83dbSDimitry Andric   if (!Res)
5890b57cec5SDimitry Andric     // Work pushed, will revisit
5900b57cec5SDimitry Andric     return false;
5910b57cec5SDimitry Andric 
5925ffd83dbSDimitry Andric   TheCache.insertResult(Val, BB, *Res);
5930b57cec5SDimitry Andric   return true;
5940b57cec5SDimitry Andric }
5950b57cec5SDimitry Andric 
596bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
597bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueImpl(Value *Val, BasicBlock *BB) {
5980b57cec5SDimitry Andric   Instruction *BBI = dyn_cast<Instruction>(Val);
5990b57cec5SDimitry Andric   if (!BBI || BBI->getParent() != BB)
6005ffd83dbSDimitry Andric     return solveBlockValueNonLocal(Val, BB);
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric   if (PHINode *PN = dyn_cast<PHINode>(BBI))
6035ffd83dbSDimitry Andric     return solveBlockValuePHINode(PN, BB);
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric   if (auto *SI = dyn_cast<SelectInst>(BBI))
6065ffd83dbSDimitry Andric     return solveBlockValueSelect(SI, BB);
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   // If this value is a nonnull pointer, record it's range and bailout.  Note
6090b57cec5SDimitry Andric   // that for all other pointer typed values, we terminate the search at the
6100b57cec5SDimitry Andric   // definition.  We could easily extend this to look through geps, bitcasts,
6110b57cec5SDimitry Andric   // and the like to prove non-nullness, but it's not clear that's worth it
6120b57cec5SDimitry Andric   // compile time wise.  The context-insensitive value walk done inside
6130b57cec5SDimitry Andric   // isKnownNonZero gets most of the profitable cases at much less expense.
6140b57cec5SDimitry Andric   // This does mean that we have a sensitivity to where the defining
6150b57cec5SDimitry Andric   // instruction is placed, even if it could legally be hoisted much higher.
6160b57cec5SDimitry Andric   // That is unfortunate.
6170b57cec5SDimitry Andric   PointerType *PT = dyn_cast<PointerType>(BBI->getType());
6185ffd83dbSDimitry Andric   if (PT && isKnownNonZero(BBI, DL))
6195ffd83dbSDimitry Andric     return ValueLatticeElement::getNot(ConstantPointerNull::get(PT));
6205ffd83dbSDimitry Andric 
6210b57cec5SDimitry Andric   if (BBI->getType()->isIntegerTy()) {
6220b57cec5SDimitry Andric     if (auto *CI = dyn_cast<CastInst>(BBI))
6235ffd83dbSDimitry Andric       return solveBlockValueCast(CI, BB);
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
6265ffd83dbSDimitry Andric       return solveBlockValueBinaryOp(BO, BB);
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric     if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
6295ffd83dbSDimitry Andric       return solveBlockValueExtractValue(EVI, BB);
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric     if (auto *II = dyn_cast<IntrinsicInst>(BBI))
6325ffd83dbSDimitry Andric       return solveBlockValueIntrinsic(II, BB);
6330b57cec5SDimitry Andric   }
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
6360b57cec5SDimitry Andric                     << "' - unknown inst def found.\n");
6375ffd83dbSDimitry Andric   return getFromRangeMetadata(BBI);
6380b57cec5SDimitry Andric }
6390b57cec5SDimitry Andric 
640e8d8bef9SDimitry Andric static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet) {
641e8d8bef9SDimitry Andric   // TODO: Use NullPointerIsDefined instead.
642e8d8bef9SDimitry Andric   if (Ptr->getType()->getPointerAddressSpace() == 0)
643e8d8bef9SDimitry Andric     PtrSet.insert(getUnderlyingObject(Ptr));
644e8d8bef9SDimitry Andric }
645e8d8bef9SDimitry Andric 
646e8d8bef9SDimitry Andric static void AddNonNullPointersByInstruction(
647e8d8bef9SDimitry Andric     Instruction *I, NonNullPointerSet &PtrSet) {
6480b57cec5SDimitry Andric   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
649e8d8bef9SDimitry Andric     AddNonNullPointer(L->getPointerOperand(), PtrSet);
650e8d8bef9SDimitry Andric   } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
651e8d8bef9SDimitry Andric     AddNonNullPointer(S->getPointerOperand(), PtrSet);
652e8d8bef9SDimitry Andric   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
653e8d8bef9SDimitry Andric     if (MI->isVolatile()) return;
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric     // FIXME: check whether it has a valuerange that excludes zero?
6560b57cec5SDimitry Andric     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
657e8d8bef9SDimitry Andric     if (!Len || Len->isZero()) return;
6580b57cec5SDimitry Andric 
659e8d8bef9SDimitry Andric     AddNonNullPointer(MI->getRawDest(), PtrSet);
6600b57cec5SDimitry Andric     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
661e8d8bef9SDimitry Andric       AddNonNullPointer(MTI->getRawSource(), PtrSet);
6620b57cec5SDimitry Andric   }
663e8d8bef9SDimitry Andric }
664e8d8bef9SDimitry Andric 
665e8d8bef9SDimitry Andric bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
666e8d8bef9SDimitry Andric   if (NullPointerIsDefined(BB->getParent(),
667e8d8bef9SDimitry Andric                            Val->getType()->getPointerAddressSpace()))
6680b57cec5SDimitry Andric     return false;
6690b57cec5SDimitry Andric 
670fe6060f1SDimitry Andric   Val = Val->stripInBoundsOffsets();
671e8d8bef9SDimitry Andric   return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
672e8d8bef9SDimitry Andric     NonNullPointerSet NonNullPointers;
6730b57cec5SDimitry Andric     for (Instruction &I : *BB)
674e8d8bef9SDimitry Andric       AddNonNullPointersByInstruction(&I, NonNullPointers);
675e8d8bef9SDimitry Andric     return NonNullPointers;
676e8d8bef9SDimitry Andric   });
6770b57cec5SDimitry Andric }
6780b57cec5SDimitry Andric 
679bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
680bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueNonLocal(Value *Val, BasicBlock *BB) {
6810b57cec5SDimitry Andric   ValueLatticeElement Result;  // Start Undefined.
6820b57cec5SDimitry Andric 
6830b57cec5SDimitry Andric   // If this is the entry block, we must be asking about an argument.  The
6840b57cec5SDimitry Andric   // value is overdefined.
685fe6060f1SDimitry Andric   if (BB->isEntryBlock()) {
6860b57cec5SDimitry Andric     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
6875ffd83dbSDimitry Andric     return ValueLatticeElement::getOverdefined();
6880b57cec5SDimitry Andric   }
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric   // Loop over all of our predecessors, merging what we know from them into
6910b57cec5SDimitry Andric   // result.  If we encounter an unexplored predecessor, we eagerly explore it
6920b57cec5SDimitry Andric   // in a depth first manner.  In practice, this has the effect of discovering
6930b57cec5SDimitry Andric   // paths we can't analyze eagerly without spending compile times analyzing
6940b57cec5SDimitry Andric   // other paths.  This heuristic benefits from the fact that predecessors are
6950b57cec5SDimitry Andric   // frequently arranged such that dominating ones come first and we quickly
6960b57cec5SDimitry Andric   // find a path to function entry.  TODO: We should consider explicitly
6970b57cec5SDimitry Andric   // canonicalizing to make this true rather than relying on this happy
6980b57cec5SDimitry Andric   // accident.
699fe6060f1SDimitry Andric   for (BasicBlock *Pred : predecessors(BB)) {
700bdd1243dSDimitry Andric     std::optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
7015ffd83dbSDimitry Andric     if (!EdgeResult)
7020b57cec5SDimitry Andric       // Explore that input, then return here
703bdd1243dSDimitry Andric       return std::nullopt;
7040b57cec5SDimitry Andric 
7055ffd83dbSDimitry Andric     Result.mergeIn(*EdgeResult);
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric     // If we hit overdefined, exit early.  The BlockVals entry is already set
7080b57cec5SDimitry Andric     // to overdefined.
7090b57cec5SDimitry Andric     if (Result.isOverdefined()) {
7100b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
711bdd1243dSDimitry Andric                         << "' - overdefined because of pred '"
712bdd1243dSDimitry Andric                         << Pred->getName() << "' (non local).\n");
7135ffd83dbSDimitry Andric       return Result;
7140b57cec5SDimitry Andric     }
7150b57cec5SDimitry Andric   }
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric   // Return the merged value, which is more precise than 'overdefined'.
7180b57cec5SDimitry Andric   assert(!Result.isOverdefined());
7195ffd83dbSDimitry Andric   return Result;
7200b57cec5SDimitry Andric }
7210b57cec5SDimitry Andric 
722bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
723bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValuePHINode(PHINode *PN, BasicBlock *BB) {
7240b57cec5SDimitry Andric   ValueLatticeElement Result;  // Start Undefined.
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   // Loop over all of our predecessors, merging what we know from them into
7270b57cec5SDimitry Andric   // result.  See the comment about the chosen traversal order in
7280b57cec5SDimitry Andric   // solveBlockValueNonLocal; the same reasoning applies here.
7290b57cec5SDimitry Andric   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7300b57cec5SDimitry Andric     BasicBlock *PhiBB = PN->getIncomingBlock(i);
7310b57cec5SDimitry Andric     Value *PhiVal = PN->getIncomingValue(i);
7320b57cec5SDimitry Andric     // Note that we can provide PN as the context value to getEdgeValue, even
7330b57cec5SDimitry Andric     // though the results will be cached, because PN is the value being used as
7340b57cec5SDimitry Andric     // the cache key in the caller.
735bdd1243dSDimitry Andric     std::optional<ValueLatticeElement> EdgeResult =
7365ffd83dbSDimitry Andric         getEdgeValue(PhiVal, PhiBB, BB, PN);
7375ffd83dbSDimitry Andric     if (!EdgeResult)
7380b57cec5SDimitry Andric       // Explore that input, then return here
739bdd1243dSDimitry Andric       return std::nullopt;
7400b57cec5SDimitry Andric 
7415ffd83dbSDimitry Andric     Result.mergeIn(*EdgeResult);
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric     // If we hit overdefined, exit early.  The BlockVals entry is already set
7440b57cec5SDimitry Andric     // to overdefined.
7450b57cec5SDimitry Andric     if (Result.isOverdefined()) {
7460b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
7470b57cec5SDimitry Andric                         << "' - overdefined because of pred (local).\n");
7480b57cec5SDimitry Andric 
7495ffd83dbSDimitry Andric       return Result;
7500b57cec5SDimitry Andric     }
7510b57cec5SDimitry Andric   }
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   // Return the merged value, which is more precise than 'overdefined'.
7540b57cec5SDimitry Andric   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
7555ffd83dbSDimitry Andric   return Result;
7560b57cec5SDimitry Andric }
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric static ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
7590b57cec5SDimitry Andric                                                  bool isTrueDest = true);
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric // If we can determine a constraint on the value given conditions assumed by
7620b57cec5SDimitry Andric // the program, intersect those constraints with BBLV
7630b57cec5SDimitry Andric void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
7640b57cec5SDimitry Andric         Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
7650b57cec5SDimitry Andric   BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
7660b57cec5SDimitry Andric   if (!BBI)
7670b57cec5SDimitry Andric     return;
7680b57cec5SDimitry Andric 
7695ffd83dbSDimitry Andric   BasicBlock *BB = BBI->getParent();
7700b57cec5SDimitry Andric   for (auto &AssumeVH : AC->assumptionsFor(Val)) {
7710b57cec5SDimitry Andric     if (!AssumeVH)
7720b57cec5SDimitry Andric       continue;
7735ffd83dbSDimitry Andric 
7745ffd83dbSDimitry Andric     // Only check assumes in the block of the context instruction. Other
7755ffd83dbSDimitry Andric     // assumes will have already been taken into account when the value was
7765ffd83dbSDimitry Andric     // propagated from predecessor blocks.
7770b57cec5SDimitry Andric     auto *I = cast<CallInst>(AssumeVH);
7785ffd83dbSDimitry Andric     if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
7790b57cec5SDimitry Andric       continue;
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric     BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
7820b57cec5SDimitry Andric   }
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   // If guards are not used in the module, don't spend time looking for them
785e8d8bef9SDimitry Andric   if (GuardDecl && !GuardDecl->use_empty() &&
786e8d8bef9SDimitry Andric       BBI->getIterator() != BB->begin()) {
7870b57cec5SDimitry Andric     for (Instruction &I : make_range(std::next(BBI->getIterator().getReverse()),
7885ffd83dbSDimitry Andric                                      BB->rend())) {
7890b57cec5SDimitry Andric       Value *Cond = nullptr;
7900b57cec5SDimitry Andric       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
7910b57cec5SDimitry Andric         BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
7920b57cec5SDimitry Andric     }
7930b57cec5SDimitry Andric   }
7940b57cec5SDimitry Andric 
795e8d8bef9SDimitry Andric   if (BBLV.isOverdefined()) {
796e8d8bef9SDimitry Andric     // Check whether we're checking at the terminator, and the pointer has
797e8d8bef9SDimitry Andric     // been dereferenced in this block.
798e8d8bef9SDimitry Andric     PointerType *PTy = dyn_cast<PointerType>(Val->getType());
799e8d8bef9SDimitry Andric     if (PTy && BB->getTerminator() == BBI &&
800e8d8bef9SDimitry Andric         isNonNullAtEndOfBlock(Val, BB))
801e8d8bef9SDimitry Andric       BBLV = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
802e8d8bef9SDimitry Andric   }
803e8d8bef9SDimitry Andric }
804e8d8bef9SDimitry Andric 
80504eeddc0SDimitry Andric static ConstantRange getConstantRangeOrFull(const ValueLatticeElement &Val,
80604eeddc0SDimitry Andric                                             Type *Ty, const DataLayout &DL) {
80704eeddc0SDimitry Andric   if (Val.isConstantRange())
80804eeddc0SDimitry Andric     return Val.getConstantRange();
80904eeddc0SDimitry Andric   return ConstantRange::getFull(DL.getTypeSizeInBits(Ty));
81004eeddc0SDimitry Andric }
81104eeddc0SDimitry Andric 
812bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
813bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueSelect(SelectInst *SI, BasicBlock *BB) {
8140b57cec5SDimitry Andric   // Recurse on our inputs if needed
815bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> OptTrueVal =
81604eeddc0SDimitry Andric       getBlockValue(SI->getTrueValue(), BB, SI);
8175ffd83dbSDimitry Andric   if (!OptTrueVal)
818bdd1243dSDimitry Andric     return std::nullopt;
8195ffd83dbSDimitry Andric   ValueLatticeElement &TrueVal = *OptTrueVal;
8200b57cec5SDimitry Andric 
821bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> OptFalseVal =
82204eeddc0SDimitry Andric       getBlockValue(SI->getFalseValue(), BB, SI);
8235ffd83dbSDimitry Andric   if (!OptFalseVal)
824bdd1243dSDimitry Andric     return std::nullopt;
8255ffd83dbSDimitry Andric   ValueLatticeElement &FalseVal = *OptFalseVal;
8265ffd83dbSDimitry Andric 
82704eeddc0SDimitry Andric   if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
82804eeddc0SDimitry Andric     const ConstantRange &TrueCR =
82904eeddc0SDimitry Andric         getConstantRangeOrFull(TrueVal, SI->getType(), DL);
83004eeddc0SDimitry Andric     const ConstantRange &FalseCR =
83104eeddc0SDimitry Andric         getConstantRangeOrFull(FalseVal, SI->getType(), DL);
8320b57cec5SDimitry Andric     Value *LHS = nullptr;
8330b57cec5SDimitry Andric     Value *RHS = nullptr;
8340b57cec5SDimitry Andric     SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
8350b57cec5SDimitry Andric     // Is this a min specifically of our two inputs?  (Avoid the risk of
8360b57cec5SDimitry Andric     // ValueTracking getting smarter looking back past our immediate inputs.)
8370b57cec5SDimitry Andric     if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
83804eeddc0SDimitry Andric         ((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
83904eeddc0SDimitry Andric          (RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
8400b57cec5SDimitry Andric       ConstantRange ResultCR = [&]() {
8410b57cec5SDimitry Andric         switch (SPR.Flavor) {
8420b57cec5SDimitry Andric         default:
8430b57cec5SDimitry Andric           llvm_unreachable("unexpected minmax type!");
8440b57cec5SDimitry Andric         case SPF_SMIN:                   /// Signed minimum
8450b57cec5SDimitry Andric           return TrueCR.smin(FalseCR);
8460b57cec5SDimitry Andric         case SPF_UMIN:                   /// Unsigned minimum
8470b57cec5SDimitry Andric           return TrueCR.umin(FalseCR);
8480b57cec5SDimitry Andric         case SPF_SMAX:                   /// Signed maximum
8490b57cec5SDimitry Andric           return TrueCR.smax(FalseCR);
8500b57cec5SDimitry Andric         case SPF_UMAX:                   /// Unsigned maximum
8510b57cec5SDimitry Andric           return TrueCR.umax(FalseCR);
8520b57cec5SDimitry Andric         };
8530b57cec5SDimitry Andric       }();
8545ffd83dbSDimitry Andric       return ValueLatticeElement::getRange(
855349cc55cSDimitry Andric           ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
8565ffd83dbSDimitry Andric                         FalseVal.isConstantRangeIncludingUndef());
8570b57cec5SDimitry Andric     }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric     if (SPR.Flavor == SPF_ABS) {
8605ffd83dbSDimitry Andric       if (LHS == SI->getTrueValue())
8615ffd83dbSDimitry Andric         return ValueLatticeElement::getRange(
8625ffd83dbSDimitry Andric             TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
8635ffd83dbSDimitry Andric       if (LHS == SI->getFalseValue())
8645ffd83dbSDimitry Andric         return ValueLatticeElement::getRange(
8655ffd83dbSDimitry Andric             FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
8660b57cec5SDimitry Andric     }
8670b57cec5SDimitry Andric 
8680b57cec5SDimitry Andric     if (SPR.Flavor == SPF_NABS) {
869349cc55cSDimitry Andric       ConstantRange Zero(APInt::getZero(TrueCR.getBitWidth()));
8705ffd83dbSDimitry Andric       if (LHS == SI->getTrueValue())
8715ffd83dbSDimitry Andric         return ValueLatticeElement::getRange(
8725ffd83dbSDimitry Andric             Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
8735ffd83dbSDimitry Andric       if (LHS == SI->getFalseValue())
8745ffd83dbSDimitry Andric         return ValueLatticeElement::getRange(
8755ffd83dbSDimitry Andric             Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
8760b57cec5SDimitry Andric     }
8770b57cec5SDimitry Andric   }
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric   // Can we constrain the facts about the true and false values by using the
8800b57cec5SDimitry Andric   // condition itself?  This shows up with idioms like e.g. select(a > 5, a, 5).
8810b57cec5SDimitry Andric   // TODO: We could potentially refine an overdefined true value above.
8820b57cec5SDimitry Andric   Value *Cond = SI->getCondition();
88306c3fb27SDimitry Andric   // If the value is undef, a different value may be chosen in
88406c3fb27SDimitry Andric   // the select condition.
88506c3fb27SDimitry Andric   if (isGuaranteedNotToBeUndefOrPoison(Cond, AC)) {
8860b57cec5SDimitry Andric     TrueVal = intersect(TrueVal,
8870b57cec5SDimitry Andric                         getValueFromCondition(SI->getTrueValue(), Cond, true));
88806c3fb27SDimitry Andric     FalseVal = intersect(
88906c3fb27SDimitry Andric         FalseVal, getValueFromCondition(SI->getFalseValue(), Cond, false));
89006c3fb27SDimitry Andric   }
8910b57cec5SDimitry Andric 
8925ffd83dbSDimitry Andric   ValueLatticeElement Result = TrueVal;
8935ffd83dbSDimitry Andric   Result.mergeIn(FalseVal);
8945ffd83dbSDimitry Andric   return Result;
8950b57cec5SDimitry Andric }
8960b57cec5SDimitry Andric 
897bdd1243dSDimitry Andric std::optional<ConstantRange>
898bdd1243dSDimitry Andric LazyValueInfoImpl::getRangeFor(Value *V, Instruction *CxtI, BasicBlock *BB) {
899bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CxtI);
9005ffd83dbSDimitry Andric   if (!OptVal)
901bdd1243dSDimitry Andric     return std::nullopt;
90204eeddc0SDimitry Andric   return getConstantRangeOrFull(*OptVal, V->getType(), DL);
9030b57cec5SDimitry Andric }
9040b57cec5SDimitry Andric 
905bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
906bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueCast(CastInst *CI, BasicBlock *BB) {
9070b57cec5SDimitry Andric   // Without knowing how wide the input is, we can't analyze it in any useful
9080b57cec5SDimitry Andric   // way.
9095ffd83dbSDimitry Andric   if (!CI->getOperand(0)->getType()->isSized())
9105ffd83dbSDimitry Andric     return ValueLatticeElement::getOverdefined();
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric   // Filter out casts we don't know how to reason about before attempting to
9130b57cec5SDimitry Andric   // recurse on our operand.  This can cut a long search short if we know we're
9140b57cec5SDimitry Andric   // not going to be able to get any useful information anways.
9150b57cec5SDimitry Andric   switch (CI->getOpcode()) {
9160b57cec5SDimitry Andric   case Instruction::Trunc:
9170b57cec5SDimitry Andric   case Instruction::SExt:
9180b57cec5SDimitry Andric   case Instruction::ZExt:
9190b57cec5SDimitry Andric   case Instruction::BitCast:
9200b57cec5SDimitry Andric     break;
9210b57cec5SDimitry Andric   default:
9220b57cec5SDimitry Andric     // Unhandled instructions are overdefined.
9230b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
9240b57cec5SDimitry Andric                       << "' - overdefined (unknown cast).\n");
9255ffd83dbSDimitry Andric     return ValueLatticeElement::getOverdefined();
9260b57cec5SDimitry Andric   }
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric   // Figure out the range of the LHS.  If that fails, we still apply the
9290b57cec5SDimitry Andric   // transfer rule on the full set since we may be able to locally infer
9300b57cec5SDimitry Andric   // interesting facts.
931bdd1243dSDimitry Andric   std::optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
93281ad6265SDimitry Andric   if (!LHSRes)
9330b57cec5SDimitry Andric     // More work to do before applying this transfer rule.
934bdd1243dSDimitry Andric     return std::nullopt;
935bdd1243dSDimitry Andric   const ConstantRange &LHSRange = *LHSRes;
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric   const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   // NOTE: We're currently limited by the set of operations that ConstantRange
9400b57cec5SDimitry Andric   // can evaluate symbolically.  Enhancing that set will allows us to analyze
9410b57cec5SDimitry Andric   // more definitions.
9425ffd83dbSDimitry Andric   return ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
9430b57cec5SDimitry Andric                                                        ResultBitWidth));
9440b57cec5SDimitry Andric }
9450b57cec5SDimitry Andric 
946bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
947bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
9485ffd83dbSDimitry Andric     Instruction *I, BasicBlock *BB,
949bdd1243dSDimitry Andric     std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
950bdd1243dSDimitry Andric         OpFn) {
9510b57cec5SDimitry Andric   // Figure out the ranges of the operands.  If that fails, use a
9520b57cec5SDimitry Andric   // conservative range, but apply the transfer rule anyways.  This
9530b57cec5SDimitry Andric   // lets us pick up facts from expressions like "and i32 (call i32
9540b57cec5SDimitry Andric   // @foo()), 32"
955bdd1243dSDimitry Andric   std::optional<ConstantRange> LHSRes = getRangeFor(I->getOperand(0), I, BB);
956bdd1243dSDimitry Andric   std::optional<ConstantRange> RHSRes = getRangeFor(I->getOperand(1), I, BB);
95781ad6265SDimitry Andric   if (!LHSRes || !RHSRes)
9580b57cec5SDimitry Andric     // More work to do before applying this transfer rule.
959bdd1243dSDimitry Andric     return std::nullopt;
9600b57cec5SDimitry Andric 
961bdd1243dSDimitry Andric   const ConstantRange &LHSRange = *LHSRes;
962bdd1243dSDimitry Andric   const ConstantRange &RHSRange = *RHSRes;
9635ffd83dbSDimitry Andric   return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
9640b57cec5SDimitry Andric }
9650b57cec5SDimitry Andric 
966bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
967bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueBinaryOp(BinaryOperator *BO, BasicBlock *BB) {
9680b57cec5SDimitry Andric   assert(BO->getOperand(0)->getType()->isSized() &&
9690b57cec5SDimitry Andric          "all operands to binary operators are sized");
970480093f4SDimitry Andric   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
971480093f4SDimitry Andric     unsigned NoWrapKind = 0;
972480093f4SDimitry Andric     if (OBO->hasNoUnsignedWrap())
973480093f4SDimitry Andric       NoWrapKind |= OverflowingBinaryOperator::NoUnsignedWrap;
974480093f4SDimitry Andric     if (OBO->hasNoSignedWrap())
975480093f4SDimitry Andric       NoWrapKind |= OverflowingBinaryOperator::NoSignedWrap;
976480093f4SDimitry Andric 
977480093f4SDimitry Andric     return solveBlockValueBinaryOpImpl(
9785ffd83dbSDimitry Andric         BO, BB,
979480093f4SDimitry Andric         [BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
980480093f4SDimitry Andric           return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
981480093f4SDimitry Andric         });
982480093f4SDimitry Andric   }
983480093f4SDimitry Andric 
984480093f4SDimitry Andric   return solveBlockValueBinaryOpImpl(
9855ffd83dbSDimitry Andric       BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
9860b57cec5SDimitry Andric         return CR1.binaryOp(BO->getOpcode(), CR2);
9870b57cec5SDimitry Andric       });
9880b57cec5SDimitry Andric }
9890b57cec5SDimitry Andric 
990bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
9915ffd83dbSDimitry Andric LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
9925ffd83dbSDimitry Andric                                                     BasicBlock *BB) {
9935ffd83dbSDimitry Andric   return solveBlockValueBinaryOpImpl(
9945ffd83dbSDimitry Andric       WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
9950b57cec5SDimitry Andric         return CR1.binaryOp(WO->getBinaryOp(), CR2);
9960b57cec5SDimitry Andric       });
9970b57cec5SDimitry Andric }
9980b57cec5SDimitry Andric 
999bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
1000bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueIntrinsic(IntrinsicInst *II, BasicBlock *BB) {
100106c3fb27SDimitry Andric   ValueLatticeElement MetadataVal = getFromRangeMetadata(II);
1002e8d8bef9SDimitry Andric   if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
10030b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1004fe6060f1SDimitry Andric                       << "' - unknown intrinsic.\n");
100506c3fb27SDimitry Andric     return MetadataVal;
10060b57cec5SDimitry Andric   }
10070b57cec5SDimitry Andric 
1008e8d8bef9SDimitry Andric   SmallVector<ConstantRange, 2> OpRanges;
1009e8d8bef9SDimitry Andric   for (Value *Op : II->args()) {
1010bdd1243dSDimitry Andric     std::optional<ConstantRange> Range = getRangeFor(Op, II, BB);
1011e8d8bef9SDimitry Andric     if (!Range)
1012bdd1243dSDimitry Andric       return std::nullopt;
1013e8d8bef9SDimitry Andric     OpRanges.push_back(*Range);
1014e8d8bef9SDimitry Andric   }
1015e8d8bef9SDimitry Andric 
101606c3fb27SDimitry Andric   return intersect(ValueLatticeElement::getRange(ConstantRange::intrinsic(
101706c3fb27SDimitry Andric                        II->getIntrinsicID(), OpRanges)),
101806c3fb27SDimitry Andric                    MetadataVal);
1019e8d8bef9SDimitry Andric }
1020e8d8bef9SDimitry Andric 
1021bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
1022bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueExtractValue(ExtractValueInst *EVI,
1023bdd1243dSDimitry Andric                                                BasicBlock *BB) {
10248bcb0991SDimitry Andric   if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
10258bcb0991SDimitry Andric     if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
10265ffd83dbSDimitry Andric       return solveBlockValueOverflowIntrinsic(WO, BB);
10278bcb0991SDimitry Andric 
10288bcb0991SDimitry Andric   // Handle extractvalue of insertvalue to allow further simplification
10298bcb0991SDimitry Andric   // based on replaced with.overflow intrinsics.
103081ad6265SDimitry Andric   if (Value *V = simplifyExtractValueInst(
10318bcb0991SDimitry Andric           EVI->getAggregateOperand(), EVI->getIndices(),
10325ffd83dbSDimitry Andric           EVI->getModule()->getDataLayout()))
103304eeddc0SDimitry Andric     return getBlockValue(V, BB, EVI);
10348bcb0991SDimitry Andric 
10358bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
10368bcb0991SDimitry Andric                     << "' - overdefined (unknown extractvalue).\n");
10375ffd83dbSDimitry Andric   return ValueLatticeElement::getOverdefined();
10385ffd83dbSDimitry Andric }
10395ffd83dbSDimitry Andric 
1040fe6060f1SDimitry Andric static bool matchICmpOperand(APInt &Offset, Value *LHS, Value *Val,
10415ffd83dbSDimitry Andric                              ICmpInst::Predicate Pred) {
10425ffd83dbSDimitry Andric   if (LHS == Val)
10438bcb0991SDimitry Andric     return true;
10445ffd83dbSDimitry Andric 
10455ffd83dbSDimitry Andric   // Handle range checking idiom produced by InstCombine. We will subtract the
10465ffd83dbSDimitry Andric   // offset from the allowed range for RHS in this case.
1047fe6060f1SDimitry Andric   const APInt *C;
1048fe6060f1SDimitry Andric   if (match(LHS, m_Add(m_Specific(Val), m_APInt(C)))) {
1049fe6060f1SDimitry Andric     Offset = *C;
10505ffd83dbSDimitry Andric     return true;
1051fe6060f1SDimitry Andric   }
1052fe6060f1SDimitry Andric 
1053fe6060f1SDimitry Andric   // Handle the symmetric case. This appears in saturation patterns like
1054fe6060f1SDimitry Andric   // (x == 16) ? 16 : (x + 1).
1055fe6060f1SDimitry Andric   if (match(Val, m_Add(m_Specific(LHS), m_APInt(C)))) {
1056fe6060f1SDimitry Andric     Offset = -*C;
1057fe6060f1SDimitry Andric     return true;
1058fe6060f1SDimitry Andric   }
10595ffd83dbSDimitry Andric 
10605ffd83dbSDimitry Andric   // If (x | y) < C, then (x < C) && (y < C).
10615ffd83dbSDimitry Andric   if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
10625ffd83dbSDimitry Andric       (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE))
10635ffd83dbSDimitry Andric     return true;
10645ffd83dbSDimitry Andric 
10655ffd83dbSDimitry Andric   // If (x & y) > C, then (x > C) && (y > C).
10665ffd83dbSDimitry Andric   if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
10675ffd83dbSDimitry Andric       (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE))
10685ffd83dbSDimitry Andric     return true;
10695ffd83dbSDimitry Andric 
10705ffd83dbSDimitry Andric   return false;
10718bcb0991SDimitry Andric }
10728bcb0991SDimitry Andric 
1073e8d8bef9SDimitry Andric /// Get value range for a "(Val + Offset) Pred RHS" condition.
1074e8d8bef9SDimitry Andric static ValueLatticeElement getValueFromSimpleICmpCondition(
1075fe6060f1SDimitry Andric     CmpInst::Predicate Pred, Value *RHS, const APInt &Offset) {
1076e8d8bef9SDimitry Andric   ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1077e8d8bef9SDimitry Andric                          /*isFullSet=*/true);
1078e8d8bef9SDimitry Andric   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1079e8d8bef9SDimitry Andric     RHSRange = ConstantRange(CI->getValue());
1080e8d8bef9SDimitry Andric   else if (Instruction *I = dyn_cast<Instruction>(RHS))
1081e8d8bef9SDimitry Andric     if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1082e8d8bef9SDimitry Andric       RHSRange = getConstantRangeFromMetadata(*Ranges);
1083e8d8bef9SDimitry Andric 
1084e8d8bef9SDimitry Andric   ConstantRange TrueValues =
1085e8d8bef9SDimitry Andric       ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1086fe6060f1SDimitry Andric   return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
1087e8d8bef9SDimitry Andric }
1088e8d8bef9SDimitry Andric 
10890b57cec5SDimitry Andric static ValueLatticeElement getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
10900b57cec5SDimitry Andric                                                      bool isTrueDest) {
10910b57cec5SDimitry Andric   Value *LHS = ICI->getOperand(0);
10920b57cec5SDimitry Andric   Value *RHS = ICI->getOperand(1);
10935ffd83dbSDimitry Andric 
10945ffd83dbSDimitry Andric   // Get the predicate that must hold along the considered edge.
10955ffd83dbSDimitry Andric   CmpInst::Predicate EdgePred =
10965ffd83dbSDimitry Andric       isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric   if (isa<Constant>(RHS)) {
10990b57cec5SDimitry Andric     if (ICI->isEquality() && LHS == Val) {
11005ffd83dbSDimitry Andric       if (EdgePred == ICmpInst::ICMP_EQ)
11010b57cec5SDimitry Andric         return ValueLatticeElement::get(cast<Constant>(RHS));
1102d65cd7a5SDimitry Andric       else if (!isa<UndefValue>(RHS))
11030b57cec5SDimitry Andric         return ValueLatticeElement::getNot(cast<Constant>(RHS));
11040b57cec5SDimitry Andric     }
11050b57cec5SDimitry Andric   }
11060b57cec5SDimitry Andric 
1107fe6060f1SDimitry Andric   Type *Ty = Val->getType();
1108fe6060f1SDimitry Andric   if (!Ty->isIntegerTy())
11090b57cec5SDimitry Andric     return ValueLatticeElement::getOverdefined();
11100b57cec5SDimitry Andric 
11114824e7fdSDimitry Andric   unsigned BitWidth = Ty->getScalarSizeInBits();
11124824e7fdSDimitry Andric   APInt Offset(BitWidth, 0);
1113e8d8bef9SDimitry Andric   if (matchICmpOperand(Offset, LHS, Val, EdgePred))
1114e8d8bef9SDimitry Andric     return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset);
1115e8d8bef9SDimitry Andric 
1116e8d8bef9SDimitry Andric   CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
1117e8d8bef9SDimitry Andric   if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
1118e8d8bef9SDimitry Andric     return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset);
1119e8d8bef9SDimitry Andric 
1120e8d8bef9SDimitry Andric   const APInt *Mask, *C;
1121fe6060f1SDimitry Andric   if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
1122e8d8bef9SDimitry Andric       match(RHS, m_APInt(C))) {
1123fe6060f1SDimitry Andric     // If (Val & Mask) == C then all the masked bits are known and we can
1124fe6060f1SDimitry Andric     // compute a value range based on that.
1125fe6060f1SDimitry Andric     if (EdgePred == ICmpInst::ICMP_EQ) {
1126e8d8bef9SDimitry Andric       KnownBits Known;
1127e8d8bef9SDimitry Andric       Known.Zero = ~*C & *Mask;
1128e8d8bef9SDimitry Andric       Known.One = *C & *Mask;
1129e8d8bef9SDimitry Andric       return ValueLatticeElement::getRange(
1130e8d8bef9SDimitry Andric           ConstantRange::fromKnownBits(Known, /*IsSigned*/ false));
11310b57cec5SDimitry Andric     }
1132fe6060f1SDimitry Andric     // If (Val & Mask) != 0 then the value must be larger than the lowest set
1133fe6060f1SDimitry Andric     // bit of Mask.
1134349cc55cSDimitry Andric     if (EdgePred == ICmpInst::ICMP_NE && !Mask->isZero() && C->isZero()) {
1135fe6060f1SDimitry Andric       return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
113606c3fb27SDimitry Andric           APInt::getOneBitSet(BitWidth, Mask->countr_zero()),
1137349cc55cSDimitry Andric           APInt::getZero(BitWidth)));
1138fe6060f1SDimitry Andric     }
1139fe6060f1SDimitry Andric   }
11400b57cec5SDimitry Andric 
11414824e7fdSDimitry Andric   // If (X urem Modulus) >= C, then X >= C.
114204eeddc0SDimitry Andric   // If trunc X >= C, then X >= C.
11434824e7fdSDimitry Andric   // TODO: An upper bound could be computed as well.
114404eeddc0SDimitry Andric   if (match(LHS, m_CombineOr(m_URem(m_Specific(Val), m_Value()),
114504eeddc0SDimitry Andric                              m_Trunc(m_Specific(Val)))) &&
11464824e7fdSDimitry Andric       match(RHS, m_APInt(C))) {
11474824e7fdSDimitry Andric     // Use the icmp region so we don't have to deal with different predicates.
11484824e7fdSDimitry Andric     ConstantRange CR = ConstantRange::makeExactICmpRegion(EdgePred, *C);
11494824e7fdSDimitry Andric     if (!CR.isEmptySet())
11504824e7fdSDimitry Andric       return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
115181ad6265SDimitry Andric           CR.getUnsignedMin().zext(BitWidth), APInt(BitWidth, 0)));
11524824e7fdSDimitry Andric   }
11534824e7fdSDimitry Andric 
1154e8d8bef9SDimitry Andric   return ValueLatticeElement::getOverdefined();
11550b57cec5SDimitry Andric }
11560b57cec5SDimitry Andric 
11570b57cec5SDimitry Andric // Handle conditions of the form
11580b57cec5SDimitry Andric // extractvalue(op.with.overflow(%x, C), 1).
11590b57cec5SDimitry Andric static ValueLatticeElement getValueFromOverflowCondition(
11600b57cec5SDimitry Andric     Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
11610b57cec5SDimitry Andric   // TODO: This only works with a constant RHS for now. We could also compute
11620b57cec5SDimitry Andric   // the range of the RHS, but this doesn't fit into the current structure of
11630b57cec5SDimitry Andric   // the edge value calculation.
11640b57cec5SDimitry Andric   const APInt *C;
11650b57cec5SDimitry Andric   if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
11660b57cec5SDimitry Andric     return ValueLatticeElement::getOverdefined();
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric   // Calculate the possible values of %x for which no overflow occurs.
11690b57cec5SDimitry Andric   ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
11700b57cec5SDimitry Andric       WO->getBinaryOp(), *C, WO->getNoWrapKind());
11710b57cec5SDimitry Andric 
11720b57cec5SDimitry Andric   // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
11730b57cec5SDimitry Andric   // constrained to it's inverse (all values that might cause overflow).
11740b57cec5SDimitry Andric   if (IsTrueDest)
11750b57cec5SDimitry Andric     NWR = NWR.inverse();
11760b57cec5SDimitry Andric   return ValueLatticeElement::getRange(NWR);
11770b57cec5SDimitry Andric }
11780b57cec5SDimitry Andric 
1179bdd1243dSDimitry Andric // Tracks a Value * condition and whether we're interested in it or its inverse
1180bdd1243dSDimitry Andric typedef PointerIntPair<Value *, 1, bool> CondValue;
1181bdd1243dSDimitry Andric 
1182bdd1243dSDimitry Andric static std::optional<ValueLatticeElement> getValueFromConditionImpl(
1183bdd1243dSDimitry Andric     Value *Val, CondValue CondVal, bool isRevisit,
1184bdd1243dSDimitry Andric     SmallDenseMap<CondValue, ValueLatticeElement> &Visited,
1185bdd1243dSDimitry Andric     SmallVectorImpl<CondValue> &Worklist) {
1186bdd1243dSDimitry Andric 
1187bdd1243dSDimitry Andric   Value *Cond = CondVal.getPointer();
1188bdd1243dSDimitry Andric   bool isTrueDest = CondVal.getInt();
1189fe6060f1SDimitry Andric   if (!isRevisit) {
11900b57cec5SDimitry Andric     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
11910b57cec5SDimitry Andric       return getValueFromICmpCondition(Val, ICI, isTrueDest);
11920b57cec5SDimitry Andric 
11930b57cec5SDimitry Andric     if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
11940b57cec5SDimitry Andric       if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
11950b57cec5SDimitry Andric         if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
11960b57cec5SDimitry Andric           return getValueFromOverflowCondition(Val, WO, isTrueDest);
1197fe6060f1SDimitry Andric   }
11980b57cec5SDimitry Andric 
1199bdd1243dSDimitry Andric   Value *N;
1200bdd1243dSDimitry Andric   if (match(Cond, m_Not(m_Value(N)))) {
1201bdd1243dSDimitry Andric     CondValue NKey(N, !isTrueDest);
1202bdd1243dSDimitry Andric     auto NV = Visited.find(NKey);
1203bdd1243dSDimitry Andric     if (NV == Visited.end()) {
1204bdd1243dSDimitry Andric       Worklist.push_back(NKey);
1205bdd1243dSDimitry Andric       return std::nullopt;
1206bdd1243dSDimitry Andric     }
1207bdd1243dSDimitry Andric     return NV->second;
1208bdd1243dSDimitry Andric   }
1209bdd1243dSDimitry Andric 
1210e8d8bef9SDimitry Andric   Value *L, *R;
1211e8d8bef9SDimitry Andric   bool IsAnd;
1212e8d8bef9SDimitry Andric   if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
1213e8d8bef9SDimitry Andric     IsAnd = true;
1214e8d8bef9SDimitry Andric   else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1215e8d8bef9SDimitry Andric     IsAnd = false;
1216e8d8bef9SDimitry Andric   else
12170b57cec5SDimitry Andric     return ValueLatticeElement::getOverdefined();
12180b57cec5SDimitry Andric 
1219bdd1243dSDimitry Andric   auto LV = Visited.find(CondValue(L, isTrueDest));
1220bdd1243dSDimitry Andric   auto RV = Visited.find(CondValue(R, isTrueDest));
12210b57cec5SDimitry Andric 
1222e8d8bef9SDimitry Andric   // if (L && R) -> intersect L and R
1223bdd1243dSDimitry Andric   // if (!(L || R)) -> intersect !L and !R
1224e8d8bef9SDimitry Andric   // if (L || R) -> union L and R
1225bdd1243dSDimitry Andric   // if (!(L && R)) -> union !L and !R
1226fe6060f1SDimitry Andric   if ((isTrueDest ^ IsAnd) && (LV != Visited.end())) {
1227fe6060f1SDimitry Andric     ValueLatticeElement V = LV->second;
1228e8d8bef9SDimitry Andric     if (V.isOverdefined())
1229e8d8bef9SDimitry Andric       return V;
1230fe6060f1SDimitry Andric     if (RV != Visited.end()) {
1231fe6060f1SDimitry Andric       V.mergeIn(RV->second);
1232e8d8bef9SDimitry Andric       return V;
1233e8d8bef9SDimitry Andric     }
12340b57cec5SDimitry Andric   }
12350b57cec5SDimitry Andric 
1236fe6060f1SDimitry Andric   if (LV == Visited.end() || RV == Visited.end()) {
1237fe6060f1SDimitry Andric     assert(!isRevisit);
1238fe6060f1SDimitry Andric     if (LV == Visited.end())
1239bdd1243dSDimitry Andric       Worklist.push_back(CondValue(L, isTrueDest));
1240fe6060f1SDimitry Andric     if (RV == Visited.end())
1241bdd1243dSDimitry Andric       Worklist.push_back(CondValue(R, isTrueDest));
1242bdd1243dSDimitry Andric     return std::nullopt;
1243fe6060f1SDimitry Andric   }
12440b57cec5SDimitry Andric 
1245fe6060f1SDimitry Andric   return intersect(LV->second, RV->second);
12460b57cec5SDimitry Andric }
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
12490b57cec5SDimitry Andric                                           bool isTrueDest) {
12500b57cec5SDimitry Andric   assert(Cond && "precondition");
1251bdd1243dSDimitry Andric   SmallDenseMap<CondValue, ValueLatticeElement> Visited;
1252bdd1243dSDimitry Andric   SmallVector<CondValue> Worklist;
1253fe6060f1SDimitry Andric 
1254bdd1243dSDimitry Andric   CondValue CondKey(Cond, isTrueDest);
1255bdd1243dSDimitry Andric   Worklist.push_back(CondKey);
1256fe6060f1SDimitry Andric   do {
1257bdd1243dSDimitry Andric     CondValue CurrentCond = Worklist.back();
1258fe6060f1SDimitry Andric     // Insert an Overdefined placeholder into the set to prevent
1259fe6060f1SDimitry Andric     // infinite recursion if there exists IRs that use not
1260fe6060f1SDimitry Andric     // dominated by its def as in this example:
1261fe6060f1SDimitry Andric     //   "%tmp3 = or i1 undef, %tmp4"
1262fe6060f1SDimitry Andric     //   "%tmp4 = or i1 undef, %tmp3"
1263fe6060f1SDimitry Andric     auto Iter =
1264fe6060f1SDimitry Andric         Visited.try_emplace(CurrentCond, ValueLatticeElement::getOverdefined());
1265fe6060f1SDimitry Andric     bool isRevisit = !Iter.second;
1266bdd1243dSDimitry Andric     std::optional<ValueLatticeElement> Result = getValueFromConditionImpl(
1267bdd1243dSDimitry Andric         Val, CurrentCond, isRevisit, Visited, Worklist);
1268fe6060f1SDimitry Andric     if (Result) {
1269fe6060f1SDimitry Andric       Visited[CurrentCond] = *Result;
1270fe6060f1SDimitry Andric       Worklist.pop_back();
1271fe6060f1SDimitry Andric     }
1272fe6060f1SDimitry Andric   } while (!Worklist.empty());
1273fe6060f1SDimitry Andric 
1274bdd1243dSDimitry Andric   auto Result = Visited.find(CondKey);
1275fe6060f1SDimitry Andric   assert(Result != Visited.end());
1276fe6060f1SDimitry Andric   return Result->second;
12770b57cec5SDimitry Andric }
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric // Return true if Usr has Op as an operand, otherwise false.
12800b57cec5SDimitry Andric static bool usesOperand(User *Usr, Value *Op) {
1281e8d8bef9SDimitry Andric   return is_contained(Usr->operands(), Op);
12820b57cec5SDimitry Andric }
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric // Return true if the instruction type of Val is supported by
1285e8d8bef9SDimitry Andric // constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1286e8d8bef9SDimitry Andric // Call this before calling constantFoldUser() to find out if it's even worth
1287e8d8bef9SDimitry Andric // attempting to call it.
12880b57cec5SDimitry Andric static bool isOperationFoldable(User *Usr) {
1289e8d8bef9SDimitry Andric   return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
12900b57cec5SDimitry Andric }
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric // Check if Usr can be simplified to an integer constant when the value of one
12930b57cec5SDimitry Andric // of its operands Op is an integer constant OpConstVal. If so, return it as an
12940b57cec5SDimitry Andric // lattice value range with a single element or otherwise return an overdefined
12950b57cec5SDimitry Andric // lattice value.
12960b57cec5SDimitry Andric static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
12970b57cec5SDimitry Andric                                             const APInt &OpConstVal,
12980b57cec5SDimitry Andric                                             const DataLayout &DL) {
12990b57cec5SDimitry Andric   assert(isOperationFoldable(Usr) && "Precondition");
13000b57cec5SDimitry Andric   Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
13010b57cec5SDimitry Andric   // Check if Usr can be simplified to a constant.
13020b57cec5SDimitry Andric   if (auto *CI = dyn_cast<CastInst>(Usr)) {
13030b57cec5SDimitry Andric     assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
13040b57cec5SDimitry Andric     if (auto *C = dyn_cast_or_null<ConstantInt>(
130581ad6265SDimitry Andric             simplifyCastInst(CI->getOpcode(), OpConst,
13060b57cec5SDimitry Andric                              CI->getDestTy(), DL))) {
13070b57cec5SDimitry Andric       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
13080b57cec5SDimitry Andric     }
13090b57cec5SDimitry Andric   } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
13100b57cec5SDimitry Andric     bool Op0Match = BO->getOperand(0) == Op;
13110b57cec5SDimitry Andric     bool Op1Match = BO->getOperand(1) == Op;
13120b57cec5SDimitry Andric     assert((Op0Match || Op1Match) &&
13130b57cec5SDimitry Andric            "Operand 0 nor Operand 1 isn't a match");
13140b57cec5SDimitry Andric     Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
13150b57cec5SDimitry Andric     Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
13160b57cec5SDimitry Andric     if (auto *C = dyn_cast_or_null<ConstantInt>(
131781ad6265SDimitry Andric             simplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
13180b57cec5SDimitry Andric       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
13190b57cec5SDimitry Andric     }
1320e8d8bef9SDimitry Andric   } else if (isa<FreezeInst>(Usr)) {
1321e8d8bef9SDimitry Andric     assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op");
1322e8d8bef9SDimitry Andric     return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
13230b57cec5SDimitry Andric   }
13240b57cec5SDimitry Andric   return ValueLatticeElement::getOverdefined();
13250b57cec5SDimitry Andric }
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric /// Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
13280b57cec5SDimitry Andric /// Val is not constrained on the edge.  Result is unspecified if return value
13290b57cec5SDimitry Andric /// is false.
1330bdd1243dSDimitry Andric static std::optional<ValueLatticeElement> getEdgeValueLocal(Value *Val,
13315ffd83dbSDimitry Andric                                                        BasicBlock *BBFrom,
13325ffd83dbSDimitry Andric                                                        BasicBlock *BBTo) {
13330b57cec5SDimitry Andric   // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
13340b57cec5SDimitry Andric   // know that v != 0.
13350b57cec5SDimitry Andric   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
13360b57cec5SDimitry Andric     // If this is a conditional branch and only one successor goes to BBTo, then
13370b57cec5SDimitry Andric     // we may be able to infer something from the condition.
13380b57cec5SDimitry Andric     if (BI->isConditional() &&
13390b57cec5SDimitry Andric         BI->getSuccessor(0) != BI->getSuccessor(1)) {
13400b57cec5SDimitry Andric       bool isTrueDest = BI->getSuccessor(0) == BBTo;
13410b57cec5SDimitry Andric       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
13420b57cec5SDimitry Andric              "BBTo isn't a successor of BBFrom");
13430b57cec5SDimitry Andric       Value *Condition = BI->getCondition();
13440b57cec5SDimitry Andric 
13450b57cec5SDimitry Andric       // If V is the condition of the branch itself, then we know exactly what
13460b57cec5SDimitry Andric       // it is.
13475ffd83dbSDimitry Andric       if (Condition == Val)
13485ffd83dbSDimitry Andric         return ValueLatticeElement::get(ConstantInt::get(
13490b57cec5SDimitry Andric                               Type::getInt1Ty(Val->getContext()), isTrueDest));
13500b57cec5SDimitry Andric 
13510b57cec5SDimitry Andric       // If the condition of the branch is an equality comparison, we may be
13520b57cec5SDimitry Andric       // able to infer the value.
13535ffd83dbSDimitry Andric       ValueLatticeElement Result = getValueFromCondition(Val, Condition,
13545ffd83dbSDimitry Andric                                                          isTrueDest);
13550b57cec5SDimitry Andric       if (!Result.isOverdefined())
13565ffd83dbSDimitry Andric         return Result;
13570b57cec5SDimitry Andric 
13580b57cec5SDimitry Andric       if (User *Usr = dyn_cast<User>(Val)) {
13590b57cec5SDimitry Andric         assert(Result.isOverdefined() && "Result isn't overdefined");
13600b57cec5SDimitry Andric         // Check with isOperationFoldable() first to avoid linearly iterating
13610b57cec5SDimitry Andric         // over the operands unnecessarily which can be expensive for
13620b57cec5SDimitry Andric         // instructions with many operands.
13630b57cec5SDimitry Andric         if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
13640b57cec5SDimitry Andric           const DataLayout &DL = BBTo->getModule()->getDataLayout();
13650b57cec5SDimitry Andric           if (usesOperand(Usr, Condition)) {
13660b57cec5SDimitry Andric             // If Val has Condition as an operand and Val can be folded into a
13670b57cec5SDimitry Andric             // constant with either Condition == true or Condition == false,
13680b57cec5SDimitry Andric             // propagate the constant.
13690b57cec5SDimitry Andric             // eg.
13700b57cec5SDimitry Andric             //   ; %Val is true on the edge to %then.
13710b57cec5SDimitry Andric             //   %Val = and i1 %Condition, true.
13720b57cec5SDimitry Andric             //   br %Condition, label %then, label %else
13730b57cec5SDimitry Andric             APInt ConditionVal(1, isTrueDest ? 1 : 0);
13740b57cec5SDimitry Andric             Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
13750b57cec5SDimitry Andric           } else {
13760b57cec5SDimitry Andric             // If one of Val's operand has an inferred value, we may be able to
13770b57cec5SDimitry Andric             // infer the value of Val.
13780b57cec5SDimitry Andric             // eg.
13790b57cec5SDimitry Andric             //    ; %Val is 94 on the edge to %then.
13800b57cec5SDimitry Andric             //    %Val = add i8 %Op, 1
13810b57cec5SDimitry Andric             //    %Condition = icmp eq i8 %Op, 93
13820b57cec5SDimitry Andric             //    br i1 %Condition, label %then, label %else
13830b57cec5SDimitry Andric             for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
13840b57cec5SDimitry Andric               Value *Op = Usr->getOperand(i);
13850b57cec5SDimitry Andric               ValueLatticeElement OpLatticeVal =
13860b57cec5SDimitry Andric                   getValueFromCondition(Op, Condition, isTrueDest);
1387bdd1243dSDimitry Andric               if (std::optional<APInt> OpConst =
1388bdd1243dSDimitry Andric                       OpLatticeVal.asConstantInteger()) {
138981ad6265SDimitry Andric                 Result = constantFoldUser(Usr, Op, *OpConst, DL);
13900b57cec5SDimitry Andric                 break;
13910b57cec5SDimitry Andric               }
13920b57cec5SDimitry Andric             }
13930b57cec5SDimitry Andric           }
13940b57cec5SDimitry Andric         }
13950b57cec5SDimitry Andric       }
13960b57cec5SDimitry Andric       if (!Result.isOverdefined())
13975ffd83dbSDimitry Andric         return Result;
13980b57cec5SDimitry Andric     }
13990b57cec5SDimitry Andric   }
14000b57cec5SDimitry Andric 
14010b57cec5SDimitry Andric   // If the edge was formed by a switch on the value, then we may know exactly
14020b57cec5SDimitry Andric   // what it is.
14030b57cec5SDimitry Andric   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
14040b57cec5SDimitry Andric     Value *Condition = SI->getCondition();
14050b57cec5SDimitry Andric     if (!isa<IntegerType>(Val->getType()))
1406bdd1243dSDimitry Andric       return std::nullopt;
14070b57cec5SDimitry Andric     bool ValUsesConditionAndMayBeFoldable = false;
14080b57cec5SDimitry Andric     if (Condition != Val) {
14090b57cec5SDimitry Andric       // Check if Val has Condition as an operand.
14100b57cec5SDimitry Andric       if (User *Usr = dyn_cast<User>(Val))
14110b57cec5SDimitry Andric         ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
14120b57cec5SDimitry Andric             usesOperand(Usr, Condition);
14130b57cec5SDimitry Andric       if (!ValUsesConditionAndMayBeFoldable)
1414bdd1243dSDimitry Andric         return std::nullopt;
14150b57cec5SDimitry Andric     }
14160b57cec5SDimitry Andric     assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
14170b57cec5SDimitry Andric            "Condition != Val nor Val doesn't use Condition");
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric     bool DefaultCase = SI->getDefaultDest() == BBTo;
14200b57cec5SDimitry Andric     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
14210b57cec5SDimitry Andric     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
14220b57cec5SDimitry Andric 
14230b57cec5SDimitry Andric     for (auto Case : SI->cases()) {
14240b57cec5SDimitry Andric       APInt CaseValue = Case.getCaseValue()->getValue();
14250b57cec5SDimitry Andric       ConstantRange EdgeVal(CaseValue);
14260b57cec5SDimitry Andric       if (ValUsesConditionAndMayBeFoldable) {
14270b57cec5SDimitry Andric         User *Usr = cast<User>(Val);
14280b57cec5SDimitry Andric         const DataLayout &DL = BBTo->getModule()->getDataLayout();
14290b57cec5SDimitry Andric         ValueLatticeElement EdgeLatticeVal =
14300b57cec5SDimitry Andric             constantFoldUser(Usr, Condition, CaseValue, DL);
14310b57cec5SDimitry Andric         if (EdgeLatticeVal.isOverdefined())
1432bdd1243dSDimitry Andric           return std::nullopt;
14330b57cec5SDimitry Andric         EdgeVal = EdgeLatticeVal.getConstantRange();
14340b57cec5SDimitry Andric       }
14350b57cec5SDimitry Andric       if (DefaultCase) {
14360b57cec5SDimitry Andric         // It is possible that the default destination is the destination of
14370b57cec5SDimitry Andric         // some cases. We cannot perform difference for those cases.
14380b57cec5SDimitry Andric         // We know Condition != CaseValue in BBTo.  In some cases we can use
14390b57cec5SDimitry Andric         // this to infer Val == f(Condition) is != f(CaseValue).  For now, we
14400b57cec5SDimitry Andric         // only do this when f is identity (i.e. Val == Condition), but we
14410b57cec5SDimitry Andric         // should be able to do this for any injective f.
14420b57cec5SDimitry Andric         if (Case.getCaseSuccessor() != BBTo && Condition == Val)
14430b57cec5SDimitry Andric           EdgesVals = EdgesVals.difference(EdgeVal);
14440b57cec5SDimitry Andric       } else if (Case.getCaseSuccessor() == BBTo)
14450b57cec5SDimitry Andric         EdgesVals = EdgesVals.unionWith(EdgeVal);
14460b57cec5SDimitry Andric     }
14475ffd83dbSDimitry Andric     return ValueLatticeElement::getRange(std::move(EdgesVals));
14480b57cec5SDimitry Andric   }
1449bdd1243dSDimitry Andric   return std::nullopt;
14500b57cec5SDimitry Andric }
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric /// Compute the value of Val on the edge BBFrom -> BBTo or the value at
14530b57cec5SDimitry Andric /// the basic block if the edge does not constrain Val.
1454bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
1455bdd1243dSDimitry Andric LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1456bdd1243dSDimitry Andric                                 BasicBlock *BBTo, Instruction *CxtI) {
14570b57cec5SDimitry Andric   // If already a constant, there is nothing to compute.
14585ffd83dbSDimitry Andric   if (Constant *VC = dyn_cast<Constant>(Val))
14595ffd83dbSDimitry Andric     return ValueLatticeElement::get(VC);
14600b57cec5SDimitry Andric 
146181ad6265SDimitry Andric   ValueLatticeElement LocalResult =
146281ad6265SDimitry Andric       getEdgeValueLocal(Val, BBFrom, BBTo)
146381ad6265SDimitry Andric           .value_or(ValueLatticeElement::getOverdefined());
14645ffd83dbSDimitry Andric   if (hasSingleValue(LocalResult))
14650b57cec5SDimitry Andric     // Can't get any more precise here
14665ffd83dbSDimitry Andric     return LocalResult;
14670b57cec5SDimitry Andric 
1468bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> OptInBlock =
146904eeddc0SDimitry Andric       getBlockValue(Val, BBFrom, BBFrom->getTerminator());
14705ffd83dbSDimitry Andric   if (!OptInBlock)
1471bdd1243dSDimitry Andric     return std::nullopt;
14725ffd83dbSDimitry Andric   ValueLatticeElement &InBlock = *OptInBlock;
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric   // We can use the context instruction (generically the ultimate instruction
14750b57cec5SDimitry Andric   // the calling pass is trying to simplify) here, even though the result of
14760b57cec5SDimitry Andric   // this function is generally cached when called from the solve* functions
14770b57cec5SDimitry Andric   // (and that cached result might be used with queries using a different
14780b57cec5SDimitry Andric   // context instruction), because when this function is called from the solve*
14790b57cec5SDimitry Andric   // functions, the context instruction is not provided. When called from
14800b57cec5SDimitry Andric   // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
14810b57cec5SDimitry Andric   // but then the result is not cached.
14820b57cec5SDimitry Andric   intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
14830b57cec5SDimitry Andric 
14845ffd83dbSDimitry Andric   return intersect(LocalResult, InBlock);
14850b57cec5SDimitry Andric }
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric ValueLatticeElement LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
14880b57cec5SDimitry Andric                                                        Instruction *CxtI) {
14890b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
14900b57cec5SDimitry Andric                     << BB->getName() << "'\n");
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric   assert(BlockValueStack.empty() && BlockValueSet.empty());
1493bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CxtI);
14945ffd83dbSDimitry Andric   if (!OptResult) {
14950b57cec5SDimitry Andric     solve();
149604eeddc0SDimitry Andric     OptResult = getBlockValue(V, BB, CxtI);
14975ffd83dbSDimitry Andric     assert(OptResult && "Value not available after solving");
14980b57cec5SDimitry Andric   }
14990b57cec5SDimitry Andric 
150004eeddc0SDimitry Andric   ValueLatticeElement Result = *OptResult;
15010b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
15020b57cec5SDimitry Andric   return Result;
15030b57cec5SDimitry Andric }
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric ValueLatticeElement LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
15060b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()
15070b57cec5SDimitry Andric                     << "'\n");
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric   if (auto *C = dyn_cast<Constant>(V))
15100b57cec5SDimitry Andric     return ValueLatticeElement::get(C);
15110b57cec5SDimitry Andric 
15120b57cec5SDimitry Andric   ValueLatticeElement Result = ValueLatticeElement::getOverdefined();
15130b57cec5SDimitry Andric   if (auto *I = dyn_cast<Instruction>(V))
15140b57cec5SDimitry Andric     Result = getFromRangeMetadata(I);
15150b57cec5SDimitry Andric   intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
15160b57cec5SDimitry Andric 
15170b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
15180b57cec5SDimitry Andric   return Result;
15190b57cec5SDimitry Andric }
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric ValueLatticeElement LazyValueInfoImpl::
15220b57cec5SDimitry Andric getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
15230b57cec5SDimitry Andric                Instruction *CxtI) {
15240b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
15250b57cec5SDimitry Andric                     << FromBB->getName() << "' to '" << ToBB->getName()
15260b57cec5SDimitry Andric                     << "'\n");
15270b57cec5SDimitry Andric 
1528bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> Result =
1529bdd1243dSDimitry Andric       getEdgeValue(V, FromBB, ToBB, CxtI);
15305ffd83dbSDimitry Andric   if (!Result) {
15310b57cec5SDimitry Andric     solve();
15325ffd83dbSDimitry Andric     Result = getEdgeValue(V, FromBB, ToBB, CxtI);
15335ffd83dbSDimitry Andric     assert(Result && "More work to do after problem solved?");
15340b57cec5SDimitry Andric   }
15350b57cec5SDimitry Andric 
15365ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "  Result = " << *Result << "\n");
15375ffd83dbSDimitry Andric   return *Result;
15380b57cec5SDimitry Andric }
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
15410b57cec5SDimitry Andric                                    BasicBlock *NewSucc) {
15420b57cec5SDimitry Andric   TheCache.threadEdgeImpl(OldSucc, NewSucc);
15430b57cec5SDimitry Andric }
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
15460b57cec5SDimitry Andric //                            LazyValueInfo Impl
15470b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
15480b57cec5SDimitry Andric 
15490b57cec5SDimitry Andric /// This lazily constructs the LazyValueInfoImpl.
15500b57cec5SDimitry Andric static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
15515ffd83dbSDimitry Andric                                   const Module *M) {
15520b57cec5SDimitry Andric   if (!PImpl) {
15535ffd83dbSDimitry Andric     assert(M && "getCache() called with a null Module");
15545ffd83dbSDimitry Andric     const DataLayout &DL = M->getDataLayout();
15555ffd83dbSDimitry Andric     Function *GuardDecl = M->getFunction(
15565ffd83dbSDimitry Andric         Intrinsic::getName(Intrinsic::experimental_guard));
15575ffd83dbSDimitry Andric     PImpl = new LazyValueInfoImpl(AC, DL, GuardDecl);
15580b57cec5SDimitry Andric   }
15590b57cec5SDimitry Andric   return *static_cast<LazyValueInfoImpl*>(PImpl);
15600b57cec5SDimitry Andric }
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
15630b57cec5SDimitry Andric   Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
15648bcb0991SDimitry Andric   Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
15650b57cec5SDimitry Andric 
15660b57cec5SDimitry Andric   if (Info.PImpl)
15675ffd83dbSDimitry Andric     getImpl(Info.PImpl, Info.AC, F.getParent()).clear();
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric   // Fully lazy.
15700b57cec5SDimitry Andric   return false;
15710b57cec5SDimitry Andric }
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
15740b57cec5SDimitry Andric   AU.setPreservesAll();
15750b57cec5SDimitry Andric   AU.addRequired<AssumptionCacheTracker>();
15760b57cec5SDimitry Andric   AU.addRequired<TargetLibraryInfoWrapperPass>();
15770b57cec5SDimitry Andric }
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
15800b57cec5SDimitry Andric 
15810b57cec5SDimitry Andric LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric void LazyValueInfo::releaseMemory() {
15840b57cec5SDimitry Andric   // If the cache was allocated, free it.
15850b57cec5SDimitry Andric   if (PImpl) {
15860b57cec5SDimitry Andric     delete &getImpl(PImpl, AC, nullptr);
15870b57cec5SDimitry Andric     PImpl = nullptr;
15880b57cec5SDimitry Andric   }
15890b57cec5SDimitry Andric }
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
15920b57cec5SDimitry Andric                                FunctionAnalysisManager::Invalidator &Inv) {
15930b57cec5SDimitry Andric   // We need to invalidate if we have either failed to preserve this analyses
15940b57cec5SDimitry Andric   // result directly or if any of its dependencies have been invalidated.
15950b57cec5SDimitry Andric   auto PAC = PA.getChecker<LazyValueAnalysis>();
15965ffd83dbSDimitry Andric   if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
15970b57cec5SDimitry Andric     return true;
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric   return false;
16000b57cec5SDimitry Andric }
16010b57cec5SDimitry Andric 
16020b57cec5SDimitry Andric void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric LazyValueInfo LazyValueAnalysis::run(Function &F,
16050b57cec5SDimitry Andric                                      FunctionAnalysisManager &FAM) {
16060b57cec5SDimitry Andric   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
16070b57cec5SDimitry Andric   auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
16080b57cec5SDimitry Andric 
16095ffd83dbSDimitry Andric   return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI);
16100b57cec5SDimitry Andric }
16110b57cec5SDimitry Andric 
16120b57cec5SDimitry Andric /// Returns true if we can statically tell that this value will never be a
16130b57cec5SDimitry Andric /// "useful" constant.  In practice, this means we've got something like an
16140b57cec5SDimitry Andric /// alloca or a malloc call for which a comparison against a constant can
16150b57cec5SDimitry Andric /// only be guarding dead code.  Note that we are potentially giving up some
16160b57cec5SDimitry Andric /// precision in dead code (a constant result) in favour of avoiding a
16170b57cec5SDimitry Andric /// expensive search for a easily answered common query.
16180b57cec5SDimitry Andric static bool isKnownNonConstant(Value *V) {
16190b57cec5SDimitry Andric   V = V->stripPointerCasts();
16200b57cec5SDimitry Andric   // The return val of alloc cannot be a Constant.
16210b57cec5SDimitry Andric   if (isa<AllocaInst>(V))
16220b57cec5SDimitry Andric     return true;
16230b57cec5SDimitry Andric   return false;
16240b57cec5SDimitry Andric }
16250b57cec5SDimitry Andric 
1626e8d8bef9SDimitry Andric Constant *LazyValueInfo::getConstant(Value *V, Instruction *CxtI) {
16270b57cec5SDimitry Andric   // Bail out early if V is known not to be a Constant.
16280b57cec5SDimitry Andric   if (isKnownNonConstant(V))
16290b57cec5SDimitry Andric     return nullptr;
16300b57cec5SDimitry Andric 
1631e8d8bef9SDimitry Andric   BasicBlock *BB = CxtI->getParent();
16320b57cec5SDimitry Andric   ValueLatticeElement Result =
16335ffd83dbSDimitry Andric       getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
16340b57cec5SDimitry Andric 
16350b57cec5SDimitry Andric   if (Result.isConstant())
16360b57cec5SDimitry Andric     return Result.getConstant();
16370b57cec5SDimitry Andric   if (Result.isConstantRange()) {
16380b57cec5SDimitry Andric     const ConstantRange &CR = Result.getConstantRange();
16390b57cec5SDimitry Andric     if (const APInt *SingleVal = CR.getSingleElement())
16400b57cec5SDimitry Andric       return ConstantInt::get(V->getContext(), *SingleVal);
16410b57cec5SDimitry Andric   }
16420b57cec5SDimitry Andric   return nullptr;
16430b57cec5SDimitry Andric }
16440b57cec5SDimitry Andric 
1645e8d8bef9SDimitry Andric ConstantRange LazyValueInfo::getConstantRange(Value *V, Instruction *CxtI,
16465ffd83dbSDimitry Andric                                               bool UndefAllowed) {
16470b57cec5SDimitry Andric   assert(V->getType()->isIntegerTy());
16480b57cec5SDimitry Andric   unsigned Width = V->getType()->getIntegerBitWidth();
1649e8d8bef9SDimitry Andric   BasicBlock *BB = CxtI->getParent();
16500b57cec5SDimitry Andric   ValueLatticeElement Result =
16515ffd83dbSDimitry Andric       getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
1652d65cd7a5SDimitry Andric   if (Result.isUnknown())
16530b57cec5SDimitry Andric     return ConstantRange::getEmpty(Width);
16545ffd83dbSDimitry Andric   if (Result.isConstantRange(UndefAllowed))
16555ffd83dbSDimitry Andric     return Result.getConstantRange(UndefAllowed);
16560b57cec5SDimitry Andric   // We represent ConstantInt constants as constant ranges but other kinds
16570b57cec5SDimitry Andric   // of integer constants, i.e. ConstantExpr will be tagged as constants
16580b57cec5SDimitry Andric   assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
16590b57cec5SDimitry Andric          "ConstantInt value must be represented as constantrange");
16600b57cec5SDimitry Andric   return ConstantRange::getFull(Width);
16610b57cec5SDimitry Andric }
16620b57cec5SDimitry Andric 
1663bdd1243dSDimitry Andric ConstantRange LazyValueInfo::getConstantRangeAtUse(const Use &U,
1664bdd1243dSDimitry Andric                                                    bool UndefAllowed) {
1665bdd1243dSDimitry Andric   Value *V = U.get();
1666bdd1243dSDimitry Andric   ConstantRange CR =
1667bdd1243dSDimitry Andric       getConstantRange(V, cast<Instruction>(U.getUser()), UndefAllowed);
1668bdd1243dSDimitry Andric 
1669bdd1243dSDimitry Andric   // Check whether the only (possibly transitive) use of the value is in a
1670bdd1243dSDimitry Andric   // position where V can be constrained by a select or branch condition.
1671bdd1243dSDimitry Andric   const Use *CurrU = &U;
1672bdd1243dSDimitry Andric   // TODO: Increase limit?
1673bdd1243dSDimitry Andric   const unsigned MaxUsesToInspect = 3;
1674bdd1243dSDimitry Andric   for (unsigned I = 0; I < MaxUsesToInspect; ++I) {
1675bdd1243dSDimitry Andric     std::optional<ValueLatticeElement> CondVal;
1676bdd1243dSDimitry Andric     auto *CurrI = cast<Instruction>(CurrU->getUser());
1677bdd1243dSDimitry Andric     if (auto *SI = dyn_cast<SelectInst>(CurrI)) {
167806c3fb27SDimitry Andric       // If the value is undef, a different value may be chosen in
167906c3fb27SDimitry Andric       // the select condition and at use.
168006c3fb27SDimitry Andric       if (!isGuaranteedNotToBeUndefOrPoison(SI->getCondition(), AC))
168106c3fb27SDimitry Andric         break;
1682bdd1243dSDimitry Andric       if (CurrU->getOperandNo() == 1)
1683bdd1243dSDimitry Andric         CondVal = getValueFromCondition(V, SI->getCondition(), true);
1684bdd1243dSDimitry Andric       else if (CurrU->getOperandNo() == 2)
1685bdd1243dSDimitry Andric         CondVal = getValueFromCondition(V, SI->getCondition(), false);
1686bdd1243dSDimitry Andric     } else if (auto *PHI = dyn_cast<PHINode>(CurrI)) {
1687bdd1243dSDimitry Andric       // TODO: Use non-local query?
1688bdd1243dSDimitry Andric       CondVal =
1689bdd1243dSDimitry Andric           getEdgeValueLocal(V, PHI->getIncomingBlock(*CurrU), PHI->getParent());
1690bdd1243dSDimitry Andric     }
1691bdd1243dSDimitry Andric     if (CondVal && CondVal->isConstantRange())
1692bdd1243dSDimitry Andric       CR = CR.intersectWith(CondVal->getConstantRange());
1693bdd1243dSDimitry Andric 
1694bdd1243dSDimitry Andric     // Only follow one-use chain, to allow direct intersection of conditions.
1695bdd1243dSDimitry Andric     // If there are multiple uses, we would have to intersect with the union of
1696bdd1243dSDimitry Andric     // all conditions at different uses.
16971ac55f4cSDimitry Andric     // Stop walking if we hit a non-speculatable instruction. Even if the
16981ac55f4cSDimitry Andric     // result is only used under a specific condition, executing the
16991ac55f4cSDimitry Andric     // instruction itself may cause side effects or UB already.
17001ac55f4cSDimitry Andric     // This also disallows looking through phi nodes: If the phi node is part
17011ac55f4cSDimitry Andric     // of a cycle, we might end up reasoning about values from different cycle
17021ac55f4cSDimitry Andric     // iterations (PR60629).
17031ac55f4cSDimitry Andric     if (!CurrI->hasOneUse() || !isSafeToSpeculativelyExecute(CurrI))
1704bdd1243dSDimitry Andric       break;
1705bdd1243dSDimitry Andric     CurrU = &*CurrI->use_begin();
1706bdd1243dSDimitry Andric   }
1707bdd1243dSDimitry Andric   return CR;
1708bdd1243dSDimitry Andric }
1709bdd1243dSDimitry Andric 
17100b57cec5SDimitry Andric /// Determine whether the specified value is known to be a
17110b57cec5SDimitry Andric /// constant on the specified edge. Return null if not.
17120b57cec5SDimitry Andric Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
17130b57cec5SDimitry Andric                                            BasicBlock *ToBB,
17140b57cec5SDimitry Andric                                            Instruction *CxtI) {
17155ffd83dbSDimitry Andric   Module *M = FromBB->getModule();
17160b57cec5SDimitry Andric   ValueLatticeElement Result =
17175ffd83dbSDimitry Andric       getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
17180b57cec5SDimitry Andric 
17190b57cec5SDimitry Andric   if (Result.isConstant())
17200b57cec5SDimitry Andric     return Result.getConstant();
17210b57cec5SDimitry Andric   if (Result.isConstantRange()) {
17220b57cec5SDimitry Andric     const ConstantRange &CR = Result.getConstantRange();
17230b57cec5SDimitry Andric     if (const APInt *SingleVal = CR.getSingleElement())
17240b57cec5SDimitry Andric       return ConstantInt::get(V->getContext(), *SingleVal);
17250b57cec5SDimitry Andric   }
17260b57cec5SDimitry Andric   return nullptr;
17270b57cec5SDimitry Andric }
17280b57cec5SDimitry Andric 
17290b57cec5SDimitry Andric ConstantRange LazyValueInfo::getConstantRangeOnEdge(Value *V,
17300b57cec5SDimitry Andric                                                     BasicBlock *FromBB,
17310b57cec5SDimitry Andric                                                     BasicBlock *ToBB,
17320b57cec5SDimitry Andric                                                     Instruction *CxtI) {
17330b57cec5SDimitry Andric   unsigned Width = V->getType()->getIntegerBitWidth();
17345ffd83dbSDimitry Andric   Module *M = FromBB->getModule();
17350b57cec5SDimitry Andric   ValueLatticeElement Result =
17365ffd83dbSDimitry Andric       getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
17370b57cec5SDimitry Andric 
1738d65cd7a5SDimitry Andric   if (Result.isUnknown())
17390b57cec5SDimitry Andric     return ConstantRange::getEmpty(Width);
17400b57cec5SDimitry Andric   if (Result.isConstantRange())
17410b57cec5SDimitry Andric     return Result.getConstantRange();
17420b57cec5SDimitry Andric   // We represent ConstantInt constants as constant ranges but other kinds
17430b57cec5SDimitry Andric   // of integer constants, i.e. ConstantExpr will be tagged as constants
17440b57cec5SDimitry Andric   assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
17450b57cec5SDimitry Andric          "ConstantInt value must be represented as constantrange");
17460b57cec5SDimitry Andric   return ConstantRange::getFull(Width);
17470b57cec5SDimitry Andric }
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric static LazyValueInfo::Tristate
17500b57cec5SDimitry Andric getPredicateResult(unsigned Pred, Constant *C, const ValueLatticeElement &Val,
17510b57cec5SDimitry Andric                    const DataLayout &DL, TargetLibraryInfo *TLI) {
17520b57cec5SDimitry Andric   // If we know the value is a constant, evaluate the conditional.
17530b57cec5SDimitry Andric   Constant *Res = nullptr;
17540b57cec5SDimitry Andric   if (Val.isConstant()) {
17550b57cec5SDimitry Andric     Res = ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL, TLI);
175606c3fb27SDimitry Andric     if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
17570b57cec5SDimitry Andric       return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
17580b57cec5SDimitry Andric     return LazyValueInfo::Unknown;
17590b57cec5SDimitry Andric   }
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric   if (Val.isConstantRange()) {
17620b57cec5SDimitry Andric     ConstantInt *CI = dyn_cast<ConstantInt>(C);
17630b57cec5SDimitry Andric     if (!CI) return LazyValueInfo::Unknown;
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric     const ConstantRange &CR = Val.getConstantRange();
17660b57cec5SDimitry Andric     if (Pred == ICmpInst::ICMP_EQ) {
17670b57cec5SDimitry Andric       if (!CR.contains(CI->getValue()))
17680b57cec5SDimitry Andric         return LazyValueInfo::False;
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric       if (CR.isSingleElement())
17710b57cec5SDimitry Andric         return LazyValueInfo::True;
17720b57cec5SDimitry Andric     } else if (Pred == ICmpInst::ICMP_NE) {
17730b57cec5SDimitry Andric       if (!CR.contains(CI->getValue()))
17740b57cec5SDimitry Andric         return LazyValueInfo::True;
17750b57cec5SDimitry Andric 
17760b57cec5SDimitry Andric       if (CR.isSingleElement())
17770b57cec5SDimitry Andric         return LazyValueInfo::False;
17780b57cec5SDimitry Andric     } else {
17790b57cec5SDimitry Andric       // Handle more complex predicates.
17800b57cec5SDimitry Andric       ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
17810b57cec5SDimitry Andric           (ICmpInst::Predicate)Pred, CI->getValue());
17820b57cec5SDimitry Andric       if (TrueValues.contains(CR))
17830b57cec5SDimitry Andric         return LazyValueInfo::True;
17840b57cec5SDimitry Andric       if (TrueValues.inverse().contains(CR))
17850b57cec5SDimitry Andric         return LazyValueInfo::False;
17860b57cec5SDimitry Andric     }
17870b57cec5SDimitry Andric     return LazyValueInfo::Unknown;
17880b57cec5SDimitry Andric   }
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric   if (Val.isNotConstant()) {
17910b57cec5SDimitry Andric     // If this is an equality comparison, we can try to fold it knowing that
17920b57cec5SDimitry Andric     // "V != C1".
17930b57cec5SDimitry Andric     if (Pred == ICmpInst::ICMP_EQ) {
17940b57cec5SDimitry Andric       // !C1 == C -> false iff C1 == C.
17950b57cec5SDimitry Andric       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
17960b57cec5SDimitry Andric                                             Val.getNotConstant(), C, DL,
17970b57cec5SDimitry Andric                                             TLI);
179806c3fb27SDimitry Andric       if (Res && Res->isNullValue())
17990b57cec5SDimitry Andric         return LazyValueInfo::False;
18000b57cec5SDimitry Andric     } else if (Pred == ICmpInst::ICMP_NE) {
18010b57cec5SDimitry Andric       // !C1 != C -> true iff C1 == C.
18020b57cec5SDimitry Andric       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
18030b57cec5SDimitry Andric                                             Val.getNotConstant(), C, DL,
18040b57cec5SDimitry Andric                                             TLI);
180506c3fb27SDimitry Andric       if (Res && Res->isNullValue())
18060b57cec5SDimitry Andric         return LazyValueInfo::True;
18070b57cec5SDimitry Andric     }
18080b57cec5SDimitry Andric     return LazyValueInfo::Unknown;
18090b57cec5SDimitry Andric   }
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric   return LazyValueInfo::Unknown;
18120b57cec5SDimitry Andric }
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric /// Determine whether the specified value comparison with a constant is known to
18150b57cec5SDimitry Andric /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
18160b57cec5SDimitry Andric LazyValueInfo::Tristate
18170b57cec5SDimitry Andric LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
18180b57cec5SDimitry Andric                                   BasicBlock *FromBB, BasicBlock *ToBB,
18190b57cec5SDimitry Andric                                   Instruction *CxtI) {
18205ffd83dbSDimitry Andric   Module *M = FromBB->getModule();
18210b57cec5SDimitry Andric   ValueLatticeElement Result =
18225ffd83dbSDimitry Andric       getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
18230b57cec5SDimitry Andric 
18245ffd83dbSDimitry Andric   return getPredicateResult(Pred, C, Result, M->getDataLayout(), TLI);
18250b57cec5SDimitry Andric }
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric LazyValueInfo::Tristate
18280b57cec5SDimitry Andric LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1829e8d8bef9SDimitry Andric                               Instruction *CxtI, bool UseBlockValue) {
18300b57cec5SDimitry Andric   // Is or is not NonNull are common predicates being queried. If
18310b57cec5SDimitry Andric   // isKnownNonZero can tell us the result of the predicate, we can
18320b57cec5SDimitry Andric   // return it quickly. But this is only a fastpath, and falling
18330b57cec5SDimitry Andric   // through would still be correct.
18345ffd83dbSDimitry Andric   Module *M = CxtI->getModule();
18355ffd83dbSDimitry Andric   const DataLayout &DL = M->getDataLayout();
18360b57cec5SDimitry Andric   if (V->getType()->isPointerTy() && C->isNullValue() &&
18370b57cec5SDimitry Andric       isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
18380b57cec5SDimitry Andric     if (Pred == ICmpInst::ICMP_EQ)
18390b57cec5SDimitry Andric       return LazyValueInfo::False;
18400b57cec5SDimitry Andric     else if (Pred == ICmpInst::ICMP_NE)
18410b57cec5SDimitry Andric       return LazyValueInfo::True;
18420b57cec5SDimitry Andric   }
1843e8d8bef9SDimitry Andric 
1844e8d8bef9SDimitry Andric   ValueLatticeElement Result = UseBlockValue
1845e8d8bef9SDimitry Andric       ? getImpl(PImpl, AC, M).getValueInBlock(V, CxtI->getParent(), CxtI)
1846e8d8bef9SDimitry Andric       : getImpl(PImpl, AC, M).getValueAt(V, CxtI);
18470b57cec5SDimitry Andric   Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
18480b57cec5SDimitry Andric   if (Ret != Unknown)
18490b57cec5SDimitry Andric     return Ret;
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric   // Note: The following bit of code is somewhat distinct from the rest of LVI;
18520b57cec5SDimitry Andric   // LVI as a whole tries to compute a lattice value which is conservatively
18530b57cec5SDimitry Andric   // correct at a given location.  In this case, we have a predicate which we
18540b57cec5SDimitry Andric   // weren't able to prove about the merged result, and we're pushing that
18550b57cec5SDimitry Andric   // predicate back along each incoming edge to see if we can prove it
18560b57cec5SDimitry Andric   // separately for each input.  As a motivating example, consider:
18570b57cec5SDimitry Andric   // bb1:
18580b57cec5SDimitry Andric   //   %v1 = ... ; constantrange<1, 5>
18590b57cec5SDimitry Andric   //   br label %merge
18600b57cec5SDimitry Andric   // bb2:
18610b57cec5SDimitry Andric   //   %v2 = ... ; constantrange<10, 20>
18620b57cec5SDimitry Andric   //   br label %merge
18630b57cec5SDimitry Andric   // merge:
18640b57cec5SDimitry Andric   //   %phi = phi [%v1, %v2] ; constantrange<1,20>
18650b57cec5SDimitry Andric   //   %pred = icmp eq i32 %phi, 8
18660b57cec5SDimitry Andric   // We can't tell from the lattice value for '%phi' that '%pred' is false
18670b57cec5SDimitry Andric   // along each path, but by checking the predicate over each input separately,
18680b57cec5SDimitry Andric   // we can.
18690b57cec5SDimitry Andric   // We limit the search to one step backwards from the current BB and value.
18700b57cec5SDimitry Andric   // We could consider extending this to search further backwards through the
18710b57cec5SDimitry Andric   // CFG and/or value graph, but there are non-obvious compile time vs quality
18720b57cec5SDimitry Andric   // tradeoffs.
18730b57cec5SDimitry Andric   BasicBlock *BB = CxtI->getParent();
18740b57cec5SDimitry Andric 
18750b57cec5SDimitry Andric   // Function entry or an unreachable block.  Bail to avoid confusing
18760b57cec5SDimitry Andric   // analysis below.
18770b57cec5SDimitry Andric   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
18780b57cec5SDimitry Andric   if (PI == PE)
18790b57cec5SDimitry Andric     return Unknown;
18800b57cec5SDimitry Andric 
18810b57cec5SDimitry Andric   // If V is a PHI node in the same block as the context, we need to ask
18820b57cec5SDimitry Andric   // questions about the predicate as applied to the incoming value along
18830b57cec5SDimitry Andric   // each edge. This is useful for eliminating cases where the predicate is
18840b57cec5SDimitry Andric   // known along all incoming edges.
18850b57cec5SDimitry Andric   if (auto *PHI = dyn_cast<PHINode>(V))
18860b57cec5SDimitry Andric     if (PHI->getParent() == BB) {
18870b57cec5SDimitry Andric       Tristate Baseline = Unknown;
18880b57cec5SDimitry Andric       for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
18890b57cec5SDimitry Andric         Value *Incoming = PHI->getIncomingValue(i);
18900b57cec5SDimitry Andric         BasicBlock *PredBB = PHI->getIncomingBlock(i);
18910b57cec5SDimitry Andric         // Note that PredBB may be BB itself.
1892349cc55cSDimitry Andric         Tristate Result =
1893349cc55cSDimitry Andric             getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CxtI);
18940b57cec5SDimitry Andric 
18950b57cec5SDimitry Andric         // Keep going as long as we've seen a consistent known result for
18960b57cec5SDimitry Andric         // all inputs.
18970b57cec5SDimitry Andric         Baseline = (i == 0) ? Result /* First iteration */
1898349cc55cSDimitry Andric                             : (Baseline == Result ? Baseline
1899349cc55cSDimitry Andric                                                   : Unknown); /* All others */
19000b57cec5SDimitry Andric         if (Baseline == Unknown)
19010b57cec5SDimitry Andric           break;
19020b57cec5SDimitry Andric       }
19030b57cec5SDimitry Andric       if (Baseline != Unknown)
19040b57cec5SDimitry Andric         return Baseline;
19050b57cec5SDimitry Andric     }
19060b57cec5SDimitry Andric 
19070b57cec5SDimitry Andric   // For a comparison where the V is outside this block, it's possible
19080b57cec5SDimitry Andric   // that we've branched on it before. Look to see if the value is known
19090b57cec5SDimitry Andric   // on all incoming edges.
1910349cc55cSDimitry Andric   if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
19110b57cec5SDimitry Andric     // For predecessor edge, determine if the comparison is true or false
19120b57cec5SDimitry Andric     // on that edge. If they're all true or all false, we can conclude
19130b57cec5SDimitry Andric     // the value of the comparison in this block.
19140b57cec5SDimitry Andric     Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
19150b57cec5SDimitry Andric     if (Baseline != Unknown) {
19160b57cec5SDimitry Andric       // Check that all remaining incoming values match the first one.
19170b57cec5SDimitry Andric       while (++PI != PE) {
19180b57cec5SDimitry Andric         Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1919349cc55cSDimitry Andric         if (Ret != Baseline)
1920349cc55cSDimitry Andric           break;
19210b57cec5SDimitry Andric       }
19220b57cec5SDimitry Andric       // If we terminated early, then one of the values didn't match.
19230b57cec5SDimitry Andric       if (PI == PE) {
19240b57cec5SDimitry Andric         return Baseline;
19250b57cec5SDimitry Andric       }
19260b57cec5SDimitry Andric     }
19270b57cec5SDimitry Andric   }
1928349cc55cSDimitry Andric 
19290b57cec5SDimitry Andric   return Unknown;
19300b57cec5SDimitry Andric }
19310b57cec5SDimitry Andric 
1932fe6060f1SDimitry Andric LazyValueInfo::Tristate LazyValueInfo::getPredicateAt(unsigned P, Value *LHS,
1933fe6060f1SDimitry Andric                                                       Value *RHS,
1934fe6060f1SDimitry Andric                                                       Instruction *CxtI,
1935fe6060f1SDimitry Andric                                                       bool UseBlockValue) {
1936fe6060f1SDimitry Andric   CmpInst::Predicate Pred = (CmpInst::Predicate)P;
1937fe6060f1SDimitry Andric 
1938fe6060f1SDimitry Andric   if (auto *C = dyn_cast<Constant>(RHS))
1939fe6060f1SDimitry Andric     return getPredicateAt(P, LHS, C, CxtI, UseBlockValue);
1940fe6060f1SDimitry Andric   if (auto *C = dyn_cast<Constant>(LHS))
1941fe6060f1SDimitry Andric     return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CxtI,
1942fe6060f1SDimitry Andric                           UseBlockValue);
1943fe6060f1SDimitry Andric 
1944bdd1243dSDimitry Andric   // Got two non-Constant values. Try to determine the comparison results based
1945bdd1243dSDimitry Andric   // on the block values of the two operands, e.g. because they have
1946bdd1243dSDimitry Andric   // non-overlapping ranges.
1947bdd1243dSDimitry Andric   if (UseBlockValue) {
1948bdd1243dSDimitry Andric     Module *M = CxtI->getModule();
1949bdd1243dSDimitry Andric     ValueLatticeElement L =
1950bdd1243dSDimitry Andric         getImpl(PImpl, AC, M).getValueInBlock(LHS, CxtI->getParent(), CxtI);
1951bdd1243dSDimitry Andric     if (L.isOverdefined())
1952bdd1243dSDimitry Andric       return LazyValueInfo::Unknown;
1953bdd1243dSDimitry Andric 
1954bdd1243dSDimitry Andric     ValueLatticeElement R =
1955bdd1243dSDimitry Andric         getImpl(PImpl, AC, M).getValueInBlock(RHS, CxtI->getParent(), CxtI);
1956bdd1243dSDimitry Andric     Type *Ty = CmpInst::makeCmpResultType(LHS->getType());
1957bdd1243dSDimitry Andric     if (Constant *Res = L.getCompare((CmpInst::Predicate)P, Ty, R,
1958bdd1243dSDimitry Andric                                      M->getDataLayout())) {
1959bdd1243dSDimitry Andric       if (Res->isNullValue())
1960bdd1243dSDimitry Andric         return LazyValueInfo::False;
1961bdd1243dSDimitry Andric       if (Res->isOneValue())
1962bdd1243dSDimitry Andric         return LazyValueInfo::True;
1963bdd1243dSDimitry Andric     }
1964bdd1243dSDimitry Andric   }
1965fe6060f1SDimitry Andric   return LazyValueInfo::Unknown;
1966fe6060f1SDimitry Andric }
1967fe6060f1SDimitry Andric 
19680b57cec5SDimitry Andric void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
19690b57cec5SDimitry Andric                                BasicBlock *NewSucc) {
19700b57cec5SDimitry Andric   if (PImpl) {
19715ffd83dbSDimitry Andric     getImpl(PImpl, AC, PredBB->getModule())
19725ffd83dbSDimitry Andric         .threadEdge(PredBB, OldSucc, NewSucc);
19730b57cec5SDimitry Andric   }
19740b57cec5SDimitry Andric }
19750b57cec5SDimitry Andric 
1976*8a4dda33SDimitry Andric void LazyValueInfo::forgetValue(Value *V) {
1977*8a4dda33SDimitry Andric   if (PImpl)
1978*8a4dda33SDimitry Andric     getImpl(PImpl, AC, nullptr).forgetValue(V);
1979*8a4dda33SDimitry Andric }
1980*8a4dda33SDimitry Andric 
19810b57cec5SDimitry Andric void LazyValueInfo::eraseBlock(BasicBlock *BB) {
19820b57cec5SDimitry Andric   if (PImpl) {
19835ffd83dbSDimitry Andric     getImpl(PImpl, AC, BB->getModule()).eraseBlock(BB);
19840b57cec5SDimitry Andric   }
19850b57cec5SDimitry Andric }
19860b57cec5SDimitry Andric 
198781ad6265SDimitry Andric void LazyValueInfo::clear(const Module *M) {
198881ad6265SDimitry Andric   if (PImpl) {
198981ad6265SDimitry Andric     getImpl(PImpl, AC, M).clear();
199081ad6265SDimitry Andric   }
199181ad6265SDimitry Andric }
19920b57cec5SDimitry Andric 
19930b57cec5SDimitry Andric void LazyValueInfo::printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
19940b57cec5SDimitry Andric   if (PImpl) {
19955ffd83dbSDimitry Andric     getImpl(PImpl, AC, F.getParent()).printLVI(F, DTree, OS);
19960b57cec5SDimitry Andric   }
19970b57cec5SDimitry Andric }
19980b57cec5SDimitry Andric 
19990b57cec5SDimitry Andric // Print the LVI for the function arguments at the start of each basic block.
20000b57cec5SDimitry Andric void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
20010b57cec5SDimitry Andric     const BasicBlock *BB, formatted_raw_ostream &OS) {
20020b57cec5SDimitry Andric   // Find if there are latticevalues defined for arguments of the function.
20030b57cec5SDimitry Andric   auto *F = BB->getParent();
2004fcaf7f86SDimitry Andric   for (const auto &Arg : F->args()) {
20050b57cec5SDimitry Andric     ValueLatticeElement Result = LVIImpl->getValueInBlock(
20060b57cec5SDimitry Andric         const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
2007d65cd7a5SDimitry Andric     if (Result.isUnknown())
20080b57cec5SDimitry Andric       continue;
20090b57cec5SDimitry Andric     OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
20100b57cec5SDimitry Andric   }
20110b57cec5SDimitry Andric }
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric // This function prints the LVI analysis for the instruction I at the beginning
20140b57cec5SDimitry Andric // of various basic blocks. It relies on calculated values that are stored in
20150b57cec5SDimitry Andric // the LazyValueInfoCache, and in the absence of cached values, recalculate the
20160b57cec5SDimitry Andric // LazyValueInfo for `I`, and print that info.
20170b57cec5SDimitry Andric void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
20180b57cec5SDimitry Andric     const Instruction *I, formatted_raw_ostream &OS) {
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric   auto *ParentBB = I->getParent();
20210b57cec5SDimitry Andric   SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
20220b57cec5SDimitry Andric   // We can generate (solve) LVI values only for blocks that are dominated by
20230b57cec5SDimitry Andric   // the I's parent. However, to avoid generating LVI for all dominating blocks,
20240b57cec5SDimitry Andric   // that contain redundant/uninteresting information, we print LVI for
20250b57cec5SDimitry Andric   // blocks that may use this LVI information (such as immediate successor
20260b57cec5SDimitry Andric   // blocks, and blocks that contain uses of `I`).
20270b57cec5SDimitry Andric   auto printResult = [&](const BasicBlock *BB) {
20280b57cec5SDimitry Andric     if (!BlocksContainingLVI.insert(BB).second)
20290b57cec5SDimitry Andric       return;
20300b57cec5SDimitry Andric     ValueLatticeElement Result = LVIImpl->getValueInBlock(
20310b57cec5SDimitry Andric         const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
20320b57cec5SDimitry Andric       OS << "; LatticeVal for: '" << *I << "' in BB: '";
20330b57cec5SDimitry Andric       BB->printAsOperand(OS, false);
20340b57cec5SDimitry Andric       OS << "' is: " << Result << "\n";
20350b57cec5SDimitry Andric   };
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric   printResult(ParentBB);
20380b57cec5SDimitry Andric   // Print the LVI analysis results for the immediate successor blocks, that
20390b57cec5SDimitry Andric   // are dominated by `ParentBB`.
2040fcaf7f86SDimitry Andric   for (const auto *BBSucc : successors(ParentBB))
20410b57cec5SDimitry Andric     if (DT.dominates(ParentBB, BBSucc))
20420b57cec5SDimitry Andric       printResult(BBSucc);
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric   // Print LVI in blocks where `I` is used.
2045fcaf7f86SDimitry Andric   for (const auto *U : I->users())
20460b57cec5SDimitry Andric     if (auto *UseI = dyn_cast<Instruction>(U))
20470b57cec5SDimitry Andric       if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
20480b57cec5SDimitry Andric         printResult(UseI->getParent());
20490b57cec5SDimitry Andric 
20500b57cec5SDimitry Andric }
20510b57cec5SDimitry Andric 
20520b57cec5SDimitry Andric namespace {
20530b57cec5SDimitry Andric // Printer class for LazyValueInfo results.
20540b57cec5SDimitry Andric class LazyValueInfoPrinter : public FunctionPass {
20550b57cec5SDimitry Andric public:
20560b57cec5SDimitry Andric   static char ID; // Pass identification, replacement for typeid
20570b57cec5SDimitry Andric   LazyValueInfoPrinter() : FunctionPass(ID) {
20580b57cec5SDimitry Andric     initializeLazyValueInfoPrinterPass(*PassRegistry::getPassRegistry());
20590b57cec5SDimitry Andric   }
20600b57cec5SDimitry Andric 
20610b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
20620b57cec5SDimitry Andric     AU.setPreservesAll();
20630b57cec5SDimitry Andric     AU.addRequired<LazyValueInfoWrapperPass>();
20640b57cec5SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
20650b57cec5SDimitry Andric   }
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric   // Get the mandatory dominator tree analysis and pass this in to the
20680b57cec5SDimitry Andric   // LVIPrinter. We cannot rely on the LVI's DT, since it's optional.
20690b57cec5SDimitry Andric   bool runOnFunction(Function &F) override {
20700b57cec5SDimitry Andric     dbgs() << "LVI for function '" << F.getName() << "':\n";
20710b57cec5SDimitry Andric     auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
20720b57cec5SDimitry Andric     auto &DTree = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
20730b57cec5SDimitry Andric     LVI.printLVI(F, DTree, dbgs());
20740b57cec5SDimitry Andric     return false;
20750b57cec5SDimitry Andric   }
20760b57cec5SDimitry Andric };
20770b57cec5SDimitry Andric }
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric char LazyValueInfoPrinter::ID = 0;
20800b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(LazyValueInfoPrinter, "print-lazy-value-info",
20810b57cec5SDimitry Andric                 "Lazy Value Info Printer Pass", false, false)
20820b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
20830b57cec5SDimitry Andric INITIALIZE_PASS_END(LazyValueInfoPrinter, "print-lazy-value-info",
20840b57cec5SDimitry Andric                 "Lazy Value Info Printer Pass", false, false)
2085