1f785676fSDimitry Andric //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements an analysis that determines, for a given memory
11f22ef01cSRoman Divacky // operation, what preceding memory operations it depends on.  It builds on
12f22ef01cSRoman Divacky // alias analysis information, and tries to provide a lazy, caching interface to
13f22ef01cSRoman Divacky // a common kind of alias information query.
14f22ef01cSRoman Divacky //
15f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
16f22ef01cSRoman Divacky 
17f22ef01cSRoman Divacky #include "llvm/Analysis/MemoryDependenceAnalysis.h"
18139f7f9bSDimitry Andric #include "llvm/ADT/STLExtras.h"
19139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
20f22ef01cSRoman Divacky #include "llvm/Analysis/AliasAnalysis.h"
2139d628a0SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
22f22ef01cSRoman Divacky #include "llvm/Analysis/InstructionSimplify.h"
23f22ef01cSRoman Divacky #include "llvm/Analysis/MemoryBuiltins.h"
24f22ef01cSRoman Divacky #include "llvm/Analysis/PHITransAddr.h"
257d523365SDimitry Andric #include "llvm/Analysis/OrderedBasicBlock.h"
262754fe60SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
277d523365SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
28139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
2991bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
30139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
31139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
32139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
33139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
3491bc56edSDimitry Andric #include "llvm/IR/PredIteratorCache.h"
35f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
36f22ef01cSRoman Divacky using namespace llvm;
37f22ef01cSRoman Divacky 
3891bc56edSDimitry Andric #define DEBUG_TYPE "memdep"
3991bc56edSDimitry Andric 
40f22ef01cSRoman Divacky STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
41f22ef01cSRoman Divacky STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
42f22ef01cSRoman Divacky STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
43f22ef01cSRoman Divacky 
44f22ef01cSRoman Divacky STATISTIC(NumCacheNonLocalPtr,
45f22ef01cSRoman Divacky           "Number of fully cached non-local ptr responses");
46f22ef01cSRoman Divacky STATISTIC(NumCacheDirtyNonLocalPtr,
47f22ef01cSRoman Divacky           "Number of cached, but dirty, non-local ptr responses");
483ca95b02SDimitry Andric STATISTIC(NumUncacheNonLocalPtr, "Number of uncached non-local ptr responses");
49f22ef01cSRoman Divacky STATISTIC(NumCacheCompleteNonLocalPtr,
50f22ef01cSRoman Divacky           "Number of block queries that were completely cached");
51f22ef01cSRoman Divacky 
5217a519f9SDimitry Andric // Limit for the number of instructions to scan in a block.
537d523365SDimitry Andric 
547d523365SDimitry Andric static cl::opt<unsigned> BlockScanLimit(
557d523365SDimitry Andric     "memdep-block-scan-limit", cl::Hidden, cl::init(100),
567d523365SDimitry Andric     cl::desc("The number of instructions to scan in a block in memory "
577d523365SDimitry Andric              "dependency analysis (default = 100)"));
5839d628a0SDimitry Andric 
593ca95b02SDimitry Andric static cl::opt<unsigned>
603ca95b02SDimitry Andric     BlockNumberLimit("memdep-block-number-limit", cl::Hidden, cl::init(1000),
613ca95b02SDimitry Andric                      cl::desc("The number of blocks to scan during memory "
623ca95b02SDimitry Andric                               "dependency analysis (default = 1000)"));
633ca95b02SDimitry Andric 
6439d628a0SDimitry Andric // Limit on the number of memdep results to process.
6539d628a0SDimitry Andric static const unsigned int NumResultsLimit = 100;
6617a519f9SDimitry Andric 
673ca95b02SDimitry Andric /// This is a helper function that removes Val from 'Inst's set in ReverseMap.
68f22ef01cSRoman Divacky ///
693ca95b02SDimitry Andric /// If the set becomes empty, remove Inst's entry.
70f22ef01cSRoman Divacky template <typename KeyTy>
713ca95b02SDimitry Andric static void
723ca95b02SDimitry Andric RemoveFromReverseMap(DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>> &ReverseMap,
73f22ef01cSRoman Divacky                      Instruction *Inst, KeyTy Val) {
743ca95b02SDimitry Andric   typename DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>>::iterator InstIt =
753ca95b02SDimitry Andric       ReverseMap.find(Inst);
76f22ef01cSRoman Divacky   assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
77f22ef01cSRoman Divacky   bool Found = InstIt->second.erase(Val);
783ca95b02SDimitry Andric   assert(Found && "Invalid reverse map!");
793ca95b02SDimitry Andric   (void)Found;
80f22ef01cSRoman Divacky   if (InstIt->second.empty())
81f22ef01cSRoman Divacky     ReverseMap.erase(InstIt);
82f22ef01cSRoman Divacky }
83f22ef01cSRoman Divacky 
843ca95b02SDimitry Andric /// If the given instruction references a specific memory location, fill in Loc
853ca95b02SDimitry Andric /// with the details, otherwise set Loc.Ptr to null.
863ca95b02SDimitry Andric ///
873ca95b02SDimitry Andric /// Returns a ModRefInfo value describing the general behavior of the
882754fe60SDimitry Andric /// instruction.
897d523365SDimitry Andric static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc,
907d523365SDimitry Andric                               const TargetLibraryInfo &TLI) {
912754fe60SDimitry Andric   if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
926122f3e6SDimitry Andric     if (LI->isUnordered()) {
9397bc6c73SDimitry Andric       Loc = MemoryLocation::get(LI);
947d523365SDimitry Andric       return MRI_Ref;
95139f7f9bSDimitry Andric     }
963ca95b02SDimitry Andric     if (LI->getOrdering() == AtomicOrdering::Monotonic) {
9797bc6c73SDimitry Andric       Loc = MemoryLocation::get(LI);
987d523365SDimitry Andric       return MRI_ModRef;
996122f3e6SDimitry Andric     }
1008f0fd8f6SDimitry Andric     Loc = MemoryLocation();
1017d523365SDimitry Andric     return MRI_ModRef;
1022754fe60SDimitry Andric   }
1032754fe60SDimitry Andric 
1042754fe60SDimitry Andric   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1056122f3e6SDimitry Andric     if (SI->isUnordered()) {
10697bc6c73SDimitry Andric       Loc = MemoryLocation::get(SI);
1077d523365SDimitry Andric       return MRI_Mod;
108139f7f9bSDimitry Andric     }
1093ca95b02SDimitry Andric     if (SI->getOrdering() == AtomicOrdering::Monotonic) {
11097bc6c73SDimitry Andric       Loc = MemoryLocation::get(SI);
1117d523365SDimitry Andric       return MRI_ModRef;
1126122f3e6SDimitry Andric     }
1138f0fd8f6SDimitry Andric     Loc = MemoryLocation();
1147d523365SDimitry Andric     return MRI_ModRef;
1152754fe60SDimitry Andric   }
1162754fe60SDimitry Andric 
1172754fe60SDimitry Andric   if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
11897bc6c73SDimitry Andric     Loc = MemoryLocation::get(V);
1197d523365SDimitry Andric     return MRI_ModRef;
1202754fe60SDimitry Andric   }
1212754fe60SDimitry Andric 
1227d523365SDimitry Andric   if (const CallInst *CI = isFreeCall(Inst, &TLI)) {
1232754fe60SDimitry Andric     // calls to free() deallocate the entire structure
1248f0fd8f6SDimitry Andric     Loc = MemoryLocation(CI->getArgOperand(0));
1257d523365SDimitry Andric     return MRI_Mod;
1262754fe60SDimitry Andric   }
1272754fe60SDimitry Andric 
12839d628a0SDimitry Andric   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
12939d628a0SDimitry Andric     AAMDNodes AAInfo;
13039d628a0SDimitry Andric 
1312754fe60SDimitry Andric     switch (II->getIntrinsicID()) {
1322754fe60SDimitry Andric     case Intrinsic::lifetime_start:
1332754fe60SDimitry Andric     case Intrinsic::lifetime_end:
1342754fe60SDimitry Andric     case Intrinsic::invariant_start:
13539d628a0SDimitry Andric       II->getAAMetadata(AAInfo);
1368f0fd8f6SDimitry Andric       Loc = MemoryLocation(
1378f0fd8f6SDimitry Andric           II->getArgOperand(1),
1388f0fd8f6SDimitry Andric           cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(), AAInfo);
1392754fe60SDimitry Andric       // These intrinsics don't really modify the memory, but returning Mod
1402754fe60SDimitry Andric       // will allow them to be handled conservatively.
1417d523365SDimitry Andric       return MRI_Mod;
1422754fe60SDimitry Andric     case Intrinsic::invariant_end:
14339d628a0SDimitry Andric       II->getAAMetadata(AAInfo);
1448f0fd8f6SDimitry Andric       Loc = MemoryLocation(
1458f0fd8f6SDimitry Andric           II->getArgOperand(2),
1468f0fd8f6SDimitry Andric           cast<ConstantInt>(II->getArgOperand(1))->getZExtValue(), AAInfo);
1472754fe60SDimitry Andric       // These intrinsics don't really modify the memory, but returning Mod
1482754fe60SDimitry Andric       // will allow them to be handled conservatively.
1497d523365SDimitry Andric       return MRI_Mod;
1502754fe60SDimitry Andric     default:
1512754fe60SDimitry Andric       break;
1522754fe60SDimitry Andric     }
15339d628a0SDimitry Andric   }
1542754fe60SDimitry Andric 
1552754fe60SDimitry Andric   // Otherwise, just do the coarse-grained thing that always works.
1562754fe60SDimitry Andric   if (Inst->mayWriteToMemory())
1577d523365SDimitry Andric     return MRI_ModRef;
1582754fe60SDimitry Andric   if (Inst->mayReadFromMemory())
1597d523365SDimitry Andric     return MRI_Ref;
1607d523365SDimitry Andric   return MRI_NoModRef;
1612754fe60SDimitry Andric }
162f22ef01cSRoman Divacky 
1633ca95b02SDimitry Andric /// Private helper for finding the local dependencies of a call site.
1643ca95b02SDimitry Andric MemDepResult MemoryDependenceResults::getCallSiteDependencyFrom(
1653ca95b02SDimitry Andric     CallSite CS, bool isReadOnlyCall, BasicBlock::iterator ScanIt,
1663ca95b02SDimitry Andric     BasicBlock *BB) {
16717a519f9SDimitry Andric   unsigned Limit = BlockScanLimit;
16817a519f9SDimitry Andric 
169f22ef01cSRoman Divacky   // Walk backwards through the block, looking for dependencies
170f22ef01cSRoman Divacky   while (ScanIt != BB->begin()) {
17117a519f9SDimitry Andric     // Limit the amount of scanning we do so we don't end up with quadratic
17217a519f9SDimitry Andric     // running time on extreme testcases.
17317a519f9SDimitry Andric     --Limit;
17417a519f9SDimitry Andric     if (!Limit)
17517a519f9SDimitry Andric       return MemDepResult::getUnknown();
17617a519f9SDimitry Andric 
1777d523365SDimitry Andric     Instruction *Inst = &*--ScanIt;
178f22ef01cSRoman Divacky 
179f22ef01cSRoman Divacky     // If this inst is a memory op, get the pointer it accessed
1808f0fd8f6SDimitry Andric     MemoryLocation Loc;
1813ca95b02SDimitry Andric     ModRefInfo MR = GetLocation(Inst, Loc, TLI);
1822754fe60SDimitry Andric     if (Loc.Ptr) {
1832754fe60SDimitry Andric       // A simple instruction.
1843ca95b02SDimitry Andric       if (AA.getModRefInfo(CS, Loc) != MRI_NoModRef)
1852754fe60SDimitry Andric         return MemDepResult::getClobber(Inst);
1862754fe60SDimitry Andric       continue;
1872754fe60SDimitry Andric     }
1882754fe60SDimitry Andric 
189ff0cc061SDimitry Andric     if (auto InstCS = CallSite(Inst)) {
190f22ef01cSRoman Divacky       // Debug intrinsics don't cause dependences.
1913ca95b02SDimitry Andric       if (isa<DbgInfoIntrinsic>(Inst))
1923ca95b02SDimitry Andric         continue;
193f22ef01cSRoman Divacky       // If these two calls do not interfere, look past it.
1943ca95b02SDimitry Andric       switch (AA.getModRefInfo(CS, InstCS)) {
1957d523365SDimitry Andric       case MRI_NoModRef:
196e580952dSDimitry Andric         // If the two calls are the same, return InstCS as a Def, so that
197e580952dSDimitry Andric         // CS can be found redundant and eliminated.
1987d523365SDimitry Andric         if (isReadOnlyCall && !(MR & MRI_Mod) &&
199e580952dSDimitry Andric             CS.getInstruction()->isIdenticalToWhenDefined(Inst))
200f22ef01cSRoman Divacky           return MemDepResult::getDef(Inst);
201e580952dSDimitry Andric 
202e580952dSDimitry Andric         // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
203e580952dSDimitry Andric         // keep scanning.
2047ae0e2c9SDimitry Andric         continue;
205f22ef01cSRoman Divacky       default:
206f22ef01cSRoman Divacky         return MemDepResult::getClobber(Inst);
207f22ef01cSRoman Divacky       }
208f22ef01cSRoman Divacky     }
2097ae0e2c9SDimitry Andric 
2107ae0e2c9SDimitry Andric     // If we could not obtain a pointer for the instruction and the instruction
2117ae0e2c9SDimitry Andric     // touches memory then assume that this is a dependency.
2127d523365SDimitry Andric     if (MR != MRI_NoModRef)
2137ae0e2c9SDimitry Andric       return MemDepResult::getClobber(Inst);
214f22ef01cSRoman Divacky   }
215f22ef01cSRoman Divacky 
21617a519f9SDimitry Andric   // No dependence found.  If this is the entry block of the function, it is
21717a519f9SDimitry Andric   // unknown, otherwise it is non-local.
218f22ef01cSRoman Divacky   if (BB != &BB->getParent()->getEntryBlock())
219f22ef01cSRoman Divacky     return MemDepResult::getNonLocal();
2206122f3e6SDimitry Andric   return MemDepResult::getNonFuncLocal();
221f22ef01cSRoman Divacky }
222f22ef01cSRoman Divacky 
2233ca95b02SDimitry Andric /// Return true if LI is a load that would fully overlap MemLoc if done as
2243ca95b02SDimitry Andric /// a wider legal integer load.
2253b0f4066SDimitry Andric ///
2263b0f4066SDimitry Andric /// MemLocBase, MemLocOffset are lazily computed here the first time the
2273b0f4066SDimitry Andric /// base/offs of memloc is needed.
2288f0fd8f6SDimitry Andric static bool isLoadLoadClobberIfExtendedToFullWidth(const MemoryLocation &MemLoc,
2298f0fd8f6SDimitry Andric                                                    const Value *&MemLocBase,
2308f0fd8f6SDimitry Andric                                                    int64_t &MemLocOffs,
2318f0fd8f6SDimitry Andric                                                    const LoadInst *LI) {
232ff0cc061SDimitry Andric   const DataLayout &DL = LI->getModule()->getDataLayout();
2333b0f4066SDimitry Andric 
2343b0f4066SDimitry Andric   // If we haven't already computed the base/offset of MemLoc, do so now.
23591bc56edSDimitry Andric   if (!MemLocBase)
23691bc56edSDimitry Andric     MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, DL);
2373b0f4066SDimitry Andric 
2383ca95b02SDimitry Andric   unsigned Size = MemoryDependenceResults::getLoadLoadClobberFullWidthSize(
239ff0cc061SDimitry Andric       MemLocBase, MemLocOffs, MemLoc.Size, LI);
2403b0f4066SDimitry Andric   return Size != 0;
2413b0f4066SDimitry Andric }
2423b0f4066SDimitry Andric 
2433ca95b02SDimitry Andric unsigned MemoryDependenceResults::getLoadLoadClobberFullWidthSize(
244ff0cc061SDimitry Andric     const Value *MemLocBase, int64_t MemLocOffs, unsigned MemLocSize,
245ff0cc061SDimitry Andric     const LoadInst *LI) {
2466122f3e6SDimitry Andric   // We can only extend simple integer loads.
2473ca95b02SDimitry Andric   if (!isa<IntegerType>(LI->getType()) || !LI->isSimple())
2483ca95b02SDimitry Andric     return 0;
2493b0f4066SDimitry Andric 
250139f7f9bSDimitry Andric   // Load widening is hostile to ThreadSanitizer: it may cause false positives
251139f7f9bSDimitry Andric   // or make the reports more cryptic (access sizes are wrong).
252ff0cc061SDimitry Andric   if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
253139f7f9bSDimitry Andric     return 0;
254139f7f9bSDimitry Andric 
255ff0cc061SDimitry Andric   const DataLayout &DL = LI->getModule()->getDataLayout();
256ff0cc061SDimitry Andric 
2573b0f4066SDimitry Andric   // Get the base of this load.
2583b0f4066SDimitry Andric   int64_t LIOffs = 0;
2593b0f4066SDimitry Andric   const Value *LIBase =
260ff0cc061SDimitry Andric       GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, DL);
2613b0f4066SDimitry Andric 
2623b0f4066SDimitry Andric   // If the two pointers are not based on the same pointer, we can't tell that
2633b0f4066SDimitry Andric   // they are related.
2643ca95b02SDimitry Andric   if (LIBase != MemLocBase)
2653ca95b02SDimitry Andric     return 0;
2663b0f4066SDimitry Andric 
2673b0f4066SDimitry Andric   // Okay, the two values are based on the same pointer, but returned as
2683b0f4066SDimitry Andric   // no-alias.  This happens when we have things like two byte loads at "P+1"
2693b0f4066SDimitry Andric   // and "P+3".  Check to see if increasing the size of the "LI" load up to its
2703b0f4066SDimitry Andric   // alignment (or the largest native integer type) will allow us to load all
2713b0f4066SDimitry Andric   // the bits required by MemLoc.
2723b0f4066SDimitry Andric 
2733b0f4066SDimitry Andric   // If MemLoc is before LI, then no widening of LI will help us out.
2743ca95b02SDimitry Andric   if (MemLocOffs < LIOffs)
2753ca95b02SDimitry Andric     return 0;
2763b0f4066SDimitry Andric 
2773b0f4066SDimitry Andric   // Get the alignment of the load in bytes.  We assume that it is safe to load
2783b0f4066SDimitry Andric   // any legal integer up to this size without a problem.  For example, if we're
2793b0f4066SDimitry Andric   // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
2803b0f4066SDimitry Andric   // widen it up to an i32 load.  If it is known 2-byte aligned, we can widen it
2813b0f4066SDimitry Andric   // to i16.
2823b0f4066SDimitry Andric   unsigned LoadAlign = LI->getAlignment();
2833b0f4066SDimitry Andric 
2843b0f4066SDimitry Andric   int64_t MemLocEnd = MemLocOffs + MemLocSize;
2853b0f4066SDimitry Andric 
2863b0f4066SDimitry Andric   // If no amount of rounding up will let MemLoc fit into LI, then bail out.
2873ca95b02SDimitry Andric   if (LIOffs + LoadAlign < MemLocEnd)
2883ca95b02SDimitry Andric     return 0;
2893b0f4066SDimitry Andric 
2903b0f4066SDimitry Andric   // This is the size of the load to try.  Start with the next larger power of
2913b0f4066SDimitry Andric   // two.
2923b0f4066SDimitry Andric   unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits() / 8U;
2933b0f4066SDimitry Andric   NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
2943b0f4066SDimitry Andric 
2953b0f4066SDimitry Andric   while (1) {
2963b0f4066SDimitry Andric     // If this load size is bigger than our known alignment or would not fit
2973b0f4066SDimitry Andric     // into a native integer register, then we fail.
2983b0f4066SDimitry Andric     if (NewLoadByteSize > LoadAlign ||
29991bc56edSDimitry Andric         !DL.fitsInLegalInteger(NewLoadByteSize * 8))
3003b0f4066SDimitry Andric       return 0;
3013b0f4066SDimitry Andric 
302dff0c46cSDimitry Andric     if (LIOffs + NewLoadByteSize > MemLocEnd &&
303ff0cc061SDimitry Andric         LI->getParent()->getParent()->hasFnAttribute(
304ff0cc061SDimitry Andric             Attribute::SanitizeAddress))
305dff0c46cSDimitry Andric       // We will be reading past the location accessed by the original program.
306dff0c46cSDimitry Andric       // While this is safe in a regular build, Address Safety analysis tools
307dff0c46cSDimitry Andric       // may start reporting false warnings. So, don't do widening.
308dff0c46cSDimitry Andric       return 0;
309dff0c46cSDimitry Andric 
3103b0f4066SDimitry Andric     // If a load of this width would include all of MemLoc, then we succeed.
3113b0f4066SDimitry Andric     if (LIOffs + NewLoadByteSize >= MemLocEnd)
3123b0f4066SDimitry Andric       return NewLoadByteSize;
3133b0f4066SDimitry Andric 
3143b0f4066SDimitry Andric     NewLoadByteSize <<= 1;
3153b0f4066SDimitry Andric   }
316dff0c46cSDimitry Andric }
3173b0f4066SDimitry Andric 
318ff0cc061SDimitry Andric static bool isVolatile(Instruction *Inst) {
319ff0cc061SDimitry Andric   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
320ff0cc061SDimitry Andric     return LI->isVolatile();
321ff0cc061SDimitry Andric   else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
322ff0cc061SDimitry Andric     return SI->isVolatile();
323ff0cc061SDimitry Andric   else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst))
324ff0cc061SDimitry Andric     return AI->isVolatile();
325ff0cc061SDimitry Andric   return false;
326ff0cc061SDimitry Andric }
327ff0cc061SDimitry Andric 
3283ca95b02SDimitry Andric MemDepResult MemoryDependenceResults::getPointerDependencyFrom(
3298f0fd8f6SDimitry Andric     const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
3308f0fd8f6SDimitry Andric     BasicBlock *BB, Instruction *QueryInst) {
331f22ef01cSRoman Divacky 
3327d523365SDimitry Andric   if (QueryInst != nullptr) {
3337d523365SDimitry Andric     if (auto *LI = dyn_cast<LoadInst>(QueryInst)) {
3347d523365SDimitry Andric       MemDepResult invariantGroupDependency =
3357d523365SDimitry Andric           getInvariantGroupPointerDependency(LI, BB);
3367d523365SDimitry Andric 
3377d523365SDimitry Andric       if (invariantGroupDependency.isDef())
3387d523365SDimitry Andric         return invariantGroupDependency;
3397d523365SDimitry Andric     }
3407d523365SDimitry Andric   }
3417d523365SDimitry Andric   return getSimplePointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst);
3427d523365SDimitry Andric }
3437d523365SDimitry Andric 
3447d523365SDimitry Andric MemDepResult
3453ca95b02SDimitry Andric MemoryDependenceResults::getInvariantGroupPointerDependency(LoadInst *LI,
3467d523365SDimitry Andric                                                              BasicBlock *BB) {
3477d523365SDimitry Andric   Value *LoadOperand = LI->getPointerOperand();
3487d523365SDimitry Andric   // It's is not safe to walk the use list of global value, because function
3497d523365SDimitry Andric   // passes aren't allowed to look outside their functions.
3507d523365SDimitry Andric   if (isa<GlobalValue>(LoadOperand))
3517d523365SDimitry Andric     return MemDepResult::getUnknown();
3527d523365SDimitry Andric 
3537d523365SDimitry Andric   auto *InvariantGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group);
3547d523365SDimitry Andric   if (!InvariantGroupMD)
3557d523365SDimitry Andric     return MemDepResult::getUnknown();
3567d523365SDimitry Andric 
3577d523365SDimitry Andric   MemDepResult Result = MemDepResult::getUnknown();
3587d523365SDimitry Andric   llvm::SmallSet<Value *, 14> Seen;
3597d523365SDimitry Andric   // Queue to process all pointers that are equivalent to load operand.
3607d523365SDimitry Andric   llvm::SmallVector<Value *, 8> LoadOperandsQueue;
3617d523365SDimitry Andric   LoadOperandsQueue.push_back(LoadOperand);
3627d523365SDimitry Andric   while (!LoadOperandsQueue.empty()) {
3637d523365SDimitry Andric     Value *Ptr = LoadOperandsQueue.pop_back_val();
3647d523365SDimitry Andric     if (isa<GlobalValue>(Ptr))
3657d523365SDimitry Andric       continue;
3667d523365SDimitry Andric 
3677d523365SDimitry Andric     if (auto *BCI = dyn_cast<BitCastInst>(Ptr)) {
3683ca95b02SDimitry Andric       if (Seen.insert(BCI->getOperand(0)).second) {
3697d523365SDimitry Andric         LoadOperandsQueue.push_back(BCI->getOperand(0));
3707d523365SDimitry Andric       }
3717d523365SDimitry Andric     }
3727d523365SDimitry Andric 
3737d523365SDimitry Andric     for (Use &Us : Ptr->uses()) {
3747d523365SDimitry Andric       auto *U = dyn_cast<Instruction>(Us.getUser());
3753ca95b02SDimitry Andric       if (!U || U == LI || !DT.dominates(U, LI))
3767d523365SDimitry Andric         continue;
3777d523365SDimitry Andric 
3787d523365SDimitry Andric       if (auto *BCI = dyn_cast<BitCastInst>(U)) {
3793ca95b02SDimitry Andric         if (Seen.insert(BCI).second) {
3807d523365SDimitry Andric           LoadOperandsQueue.push_back(BCI);
3817d523365SDimitry Andric         }
3827d523365SDimitry Andric         continue;
3837d523365SDimitry Andric       }
3847d523365SDimitry Andric       // If we hit load/store with the same invariant.group metadata (and the
3857d523365SDimitry Andric       // same pointer operand) we can assume that value pointed by pointer
3867d523365SDimitry Andric       // operand didn't change.
3877d523365SDimitry Andric       if ((isa<LoadInst>(U) || isa<StoreInst>(U)) && U->getParent() == BB &&
3887d523365SDimitry Andric           U->getMetadata(LLVMContext::MD_invariant_group) == InvariantGroupMD)
3897d523365SDimitry Andric         return MemDepResult::getDef(U);
3907d523365SDimitry Andric     }
3917d523365SDimitry Andric   }
3927d523365SDimitry Andric   return Result;
3937d523365SDimitry Andric }
3947d523365SDimitry Andric 
3953ca95b02SDimitry Andric MemDepResult MemoryDependenceResults::getSimplePointerDependencyFrom(
3967d523365SDimitry Andric     const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
3977d523365SDimitry Andric     BasicBlock *BB, Instruction *QueryInst) {
3987d523365SDimitry Andric 
39991bc56edSDimitry Andric   const Value *MemLocBase = nullptr;
4003b0f4066SDimitry Andric   int64_t MemLocOffset = 0;
40117a519f9SDimitry Andric   unsigned Limit = BlockScanLimit;
402139f7f9bSDimitry Andric   bool isInvariantLoad = false;
40339d628a0SDimitry Andric 
40439d628a0SDimitry Andric   // We must be careful with atomic accesses, as they may allow another thread
4053ca95b02SDimitry Andric   //   to touch this location, clobbering it. We are conservative: if the
40639d628a0SDimitry Andric   //   QueryInst is not a simple (non-atomic) memory access, we automatically
40739d628a0SDimitry Andric   //   return getClobber.
40839d628a0SDimitry Andric   // If it is simple, we know based on the results of
40939d628a0SDimitry Andric   // "Compiler testing via a theory of sound optimisations in the C11/C++11
41039d628a0SDimitry Andric   //   memory model" in PLDI 2013, that a non-atomic location can only be
41139d628a0SDimitry Andric   //   clobbered between a pair of a release and an acquire action, with no
41239d628a0SDimitry Andric   //   access to the location in between.
41339d628a0SDimitry Andric   // Here is an example for giving the general intuition behind this rule.
41439d628a0SDimitry Andric   // In the following code:
41539d628a0SDimitry Andric   //   store x 0;
41639d628a0SDimitry Andric   //   release action; [1]
41739d628a0SDimitry Andric   //   acquire action; [4]
41839d628a0SDimitry Andric   //   %val = load x;
41939d628a0SDimitry Andric   // It is unsafe to replace %val by 0 because another thread may be running:
42039d628a0SDimitry Andric   //   acquire action; [2]
42139d628a0SDimitry Andric   //   store x 42;
42239d628a0SDimitry Andric   //   release action; [3]
42339d628a0SDimitry Andric   // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
42439d628a0SDimitry Andric   // being 42. A key property of this program however is that if either
42539d628a0SDimitry Andric   // 1 or 4 were missing, there would be a race between the store of 42
4263ca95b02SDimitry Andric   // either the store of 0 or the load (making the whole program racy).
4274d0b32cdSDimitry Andric   // The paper mentioned above shows that the same property is respected
4283ca95b02SDimitry Andric   // by every program that can detect any optimization of that kind: either
42939d628a0SDimitry Andric   // it is racy (undefined) or there is a release followed by an acquire
43039d628a0SDimitry Andric   // between the pair of accesses under consideration.
43139d628a0SDimitry Andric 
432ff0cc061SDimitry Andric   // If the load is invariant, we "know" that it doesn't alias *any* write. We
433ff0cc061SDimitry Andric   // do want to respect mustalias results since defs are useful for value
434ff0cc061SDimitry Andric   // forwarding, but any mayalias write can be assumed to be noalias.
435ff0cc061SDimitry Andric   // Arguably, this logic should be pushed inside AliasAnalysis itself.
436139f7f9bSDimitry Andric   if (isLoad && QueryInst) {
437139f7f9bSDimitry Andric     LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
43891bc56edSDimitry Andric     if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr)
439139f7f9bSDimitry Andric       isInvariantLoad = true;
440139f7f9bSDimitry Andric   }
44117a519f9SDimitry Andric 
442ff0cc061SDimitry Andric   const DataLayout &DL = BB->getModule()->getDataLayout();
443ff0cc061SDimitry Andric 
4447d523365SDimitry Andric   // Create a numbered basic block to lazily compute and cache instruction
4457d523365SDimitry Andric   // positions inside a BB. This is used to provide fast queries for relative
4467d523365SDimitry Andric   // position between two instructions in a BB and can be used by
4477d523365SDimitry Andric   // AliasAnalysis::callCapturesBefore.
4487d523365SDimitry Andric   OrderedBasicBlock OBB(BB);
4497d523365SDimitry Andric 
4503ca95b02SDimitry Andric   // Return "true" if and only if the instruction I is either a non-simple
4513ca95b02SDimitry Andric   // load or a non-simple store.
4523ca95b02SDimitry Andric   auto isNonSimpleLoadOrStore = [](Instruction *I) -> bool {
4533ca95b02SDimitry Andric     if (auto *LI = dyn_cast<LoadInst>(I))
4543ca95b02SDimitry Andric       return !LI->isSimple();
4553ca95b02SDimitry Andric     if (auto *SI = dyn_cast<StoreInst>(I))
4563ca95b02SDimitry Andric       return !SI->isSimple();
4573ca95b02SDimitry Andric     return false;
4583ca95b02SDimitry Andric   };
4593ca95b02SDimitry Andric 
4603ca95b02SDimitry Andric   // Return "true" if I is not a load and not a store, but it does access
4613ca95b02SDimitry Andric   // memory.
4623ca95b02SDimitry Andric   auto isOtherMemAccess = [](Instruction *I) -> bool {
4633ca95b02SDimitry Andric     return !isa<LoadInst>(I) && !isa<StoreInst>(I) && I->mayReadOrWriteMemory();
4643ca95b02SDimitry Andric   };
4653ca95b02SDimitry Andric 
466f22ef01cSRoman Divacky   // Walk backwards through the basic block, looking for dependencies.
467f22ef01cSRoman Divacky   while (ScanIt != BB->begin()) {
4687d523365SDimitry Andric     Instruction *Inst = &*--ScanIt;
469f785676fSDimitry Andric 
470f785676fSDimitry Andric     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
471f785676fSDimitry Andric       // Debug intrinsics don't (and can't) cause dependencies.
4723ca95b02SDimitry Andric       if (isa<DbgInfoIntrinsic>(II))
4733ca95b02SDimitry Andric         continue;
474f785676fSDimitry Andric 
47517a519f9SDimitry Andric     // Limit the amount of scanning we do so we don't end up with quadratic
47617a519f9SDimitry Andric     // running time on extreme testcases.
47717a519f9SDimitry Andric     --Limit;
47817a519f9SDimitry Andric     if (!Limit)
47917a519f9SDimitry Andric       return MemDepResult::getUnknown();
48017a519f9SDimitry Andric 
481f22ef01cSRoman Divacky     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
482f22ef01cSRoman Divacky       // If we reach a lifetime begin or end marker, then the query ends here
483f22ef01cSRoman Divacky       // because the value is undefined.
4842754fe60SDimitry Andric       if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
485f22ef01cSRoman Divacky         // FIXME: This only considers queries directly on the invariant-tagged
486f22ef01cSRoman Divacky         // pointer, not on query pointers that are indexed off of them.  It'd
4873b0f4066SDimitry Andric         // be nice to handle that at some point (the right approach is to use
4883b0f4066SDimitry Andric         // GetPointerBaseWithConstantOffset).
4893ca95b02SDimitry Andric         if (AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), MemLoc))
490f22ef01cSRoman Divacky           return MemDepResult::getDef(II);
4912754fe60SDimitry Andric         continue;
492f22ef01cSRoman Divacky       }
493f22ef01cSRoman Divacky     }
494f22ef01cSRoman Divacky 
4953ca95b02SDimitry Andric     // Values depend on loads if the pointers are must aliased.  This means
4963ca95b02SDimitry Andric     // that a load depends on another must aliased load from the same value.
4973ca95b02SDimitry Andric     // One exception is atomic loads: a value can depend on an atomic load that
4983ca95b02SDimitry Andric     // it does not alias with when this atomic load indicates that another
4993ca95b02SDimitry Andric     // thread may be accessing the location.
500f22ef01cSRoman Divacky     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
501ff0cc061SDimitry Andric 
502ff0cc061SDimitry Andric       // While volatile access cannot be eliminated, they do not have to clobber
503ff0cc061SDimitry Andric       // non-aliasing locations, as normal accesses, for example, can be safely
504ff0cc061SDimitry Andric       // reordered with volatile accesses.
505ff0cc061SDimitry Andric       if (LI->isVolatile()) {
506ff0cc061SDimitry Andric         if (!QueryInst)
507ff0cc061SDimitry Andric           // Original QueryInst *may* be volatile
508ff0cc061SDimitry Andric           return MemDepResult::getClobber(LI);
509ff0cc061SDimitry Andric         if (isVolatile(QueryInst))
510ff0cc061SDimitry Andric           // Ordering required if QueryInst is itself volatile
511ff0cc061SDimitry Andric           return MemDepResult::getClobber(LI);
512ff0cc061SDimitry Andric         // Otherwise, volatile doesn't imply any special ordering
513ff0cc061SDimitry Andric       }
514ff0cc061SDimitry Andric 
5156122f3e6SDimitry Andric       // Atomic loads have complications involved.
5163ca95b02SDimitry Andric       // A Monotonic (or higher) load is OK if the query inst is itself not
5173ca95b02SDimitry Andric       // atomic.
5186122f3e6SDimitry Andric       // FIXME: This is overly conservative.
5193ca95b02SDimitry Andric       if (LI->isAtomic() && isStrongerThanUnordered(LI->getOrdering())) {
5203ca95b02SDimitry Andric         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
5213ca95b02SDimitry Andric             isOtherMemAccess(QueryInst))
52239d628a0SDimitry Andric           return MemDepResult::getClobber(LI);
5233ca95b02SDimitry Andric         if (LI->getOrdering() != AtomicOrdering::Monotonic)
524ff0cc061SDimitry Andric           return MemDepResult::getClobber(LI);
52539d628a0SDimitry Andric       }
52639d628a0SDimitry Andric 
5278f0fd8f6SDimitry Andric       MemoryLocation LoadLoc = MemoryLocation::get(LI);
528f22ef01cSRoman Divacky 
529f22ef01cSRoman Divacky       // If we found a pointer, check if it could be the same as our pointer.
5303ca95b02SDimitry Andric       AliasResult R = AA.alias(LoadLoc, MemLoc);
5313b0f4066SDimitry Andric 
5323b0f4066SDimitry Andric       if (isLoad) {
5333dac3a9bSDimitry Andric         if (R == NoAlias) {
5343b0f4066SDimitry Andric           // If this is an over-aligned integer load (for example,
5353b0f4066SDimitry Andric           // "load i8* %P, align 4") see if it would obviously overlap with the
5363b0f4066SDimitry Andric           // queried location if widened to a larger load (e.g. if the queried
5373b0f4066SDimitry Andric           // location is 1 byte at P+1).  If so, return it as a load/load
5383b0f4066SDimitry Andric           // clobber result, allowing the client to decide to widen the load if
5393b0f4066SDimitry Andric           // it wants to.
540ff0cc061SDimitry Andric           if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
5413b0f4066SDimitry Andric             if (LI->getAlignment() * 8 > ITy->getPrimitiveSizeInBits() &&
5423b0f4066SDimitry Andric                 isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase,
543ff0cc061SDimitry Andric                                                        MemLocOffset, LI))
5443b0f4066SDimitry Andric               return MemDepResult::getClobber(Inst);
545ff0cc061SDimitry Andric           }
5463b0f4066SDimitry Andric           continue;
5473b0f4066SDimitry Andric         }
5483b0f4066SDimitry Andric 
5493b0f4066SDimitry Andric         // Must aliased loads are defs of each other.
5503dac3a9bSDimitry Andric         if (R == MustAlias)
5513b0f4066SDimitry Andric           return MemDepResult::getDef(Inst);
5523b0f4066SDimitry Andric 
553bd5abe19SDimitry Andric #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
554bd5abe19SDimitry Andric       // in terms of clobbering loads, but since it does this by looking
555bd5abe19SDimitry Andric       // at the clobbering load directly, it doesn't know about any
556bd5abe19SDimitry Andric       // phi translation that may have happened along the way.
557bd5abe19SDimitry Andric 
5583b0f4066SDimitry Andric         // If we have a partial alias, then return this as a clobber for the
5593b0f4066SDimitry Andric         // client to handle.
5603dac3a9bSDimitry Andric         if (R == PartialAlias)
5613b0f4066SDimitry Andric           return MemDepResult::getClobber(Inst);
562bd5abe19SDimitry Andric #endif
5633b0f4066SDimitry Andric 
5643b0f4066SDimitry Andric         // Random may-alias loads don't depend on each other without a
5653b0f4066SDimitry Andric         // dependence.
5663b0f4066SDimitry Andric         continue;
5673b0f4066SDimitry Andric       }
5683b0f4066SDimitry Andric 
5693b0f4066SDimitry Andric       // Stores don't depend on other no-aliased accesses.
5703dac3a9bSDimitry Andric       if (R == NoAlias)
571f22ef01cSRoman Divacky         continue;
572f22ef01cSRoman Divacky 
5732754fe60SDimitry Andric       // Stores don't alias loads from read-only memory.
5743ca95b02SDimitry Andric       if (AA.pointsToConstantMemory(LoadLoc))
5752754fe60SDimitry Andric         continue;
5762754fe60SDimitry Andric 
5773b0f4066SDimitry Andric       // Stores depend on may/must aliased loads.
578f22ef01cSRoman Divacky       return MemDepResult::getDef(Inst);
579f22ef01cSRoman Divacky     }
580f22ef01cSRoman Divacky 
581f22ef01cSRoman Divacky     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
5826122f3e6SDimitry Andric       // Atomic stores have complications involved.
58339d628a0SDimitry Andric       // A Monotonic store is OK if the query inst is itself not atomic.
5846122f3e6SDimitry Andric       // FIXME: This is overly conservative.
5853ca95b02SDimitry Andric       if (!SI->isUnordered() && SI->isAtomic()) {
5863ca95b02SDimitry Andric         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
5873ca95b02SDimitry Andric             isOtherMemAccess(QueryInst))
58839d628a0SDimitry Andric           return MemDepResult::getClobber(SI);
5893ca95b02SDimitry Andric         if (SI->getOrdering() != AtomicOrdering::Monotonic)
590ff0cc061SDimitry Andric           return MemDepResult::getClobber(SI);
59139d628a0SDimitry Andric       }
59239d628a0SDimitry Andric 
59339d628a0SDimitry Andric       // FIXME: this is overly conservative.
59439d628a0SDimitry Andric       // While volatile access cannot be eliminated, they do not have to clobber
59539d628a0SDimitry Andric       // non-aliasing locations, as normal accesses can for example be reordered
59639d628a0SDimitry Andric       // with volatile accesses.
59739d628a0SDimitry Andric       if (SI->isVolatile())
5983ca95b02SDimitry Andric         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
5993ca95b02SDimitry Andric             isOtherMemAccess(QueryInst))
6006122f3e6SDimitry Andric           return MemDepResult::getClobber(SI);
6016122f3e6SDimitry Andric 
602f22ef01cSRoman Divacky       // If alias analysis can tell that this store is guaranteed to not modify
603f22ef01cSRoman Divacky       // the query pointer, ignore it.  Use getModRefInfo to handle cases where
604f22ef01cSRoman Divacky       // the query pointer points to constant memory etc.
6053ca95b02SDimitry Andric       if (AA.getModRefInfo(SI, MemLoc) == MRI_NoModRef)
606f22ef01cSRoman Divacky         continue;
607f22ef01cSRoman Divacky 
608f22ef01cSRoman Divacky       // Ok, this store might clobber the query pointer.  Check to see if it is
609f22ef01cSRoman Divacky       // a must alias: in this case, we want to return this as a def.
6108f0fd8f6SDimitry Andric       MemoryLocation StoreLoc = MemoryLocation::get(SI);
611f22ef01cSRoman Divacky 
612f22ef01cSRoman Divacky       // If we found a pointer, check if it could be the same as our pointer.
6133ca95b02SDimitry Andric       AliasResult R = AA.alias(StoreLoc, MemLoc);
614f22ef01cSRoman Divacky 
6153dac3a9bSDimitry Andric       if (R == NoAlias)
616f22ef01cSRoman Divacky         continue;
6173dac3a9bSDimitry Andric       if (R == MustAlias)
618f22ef01cSRoman Divacky         return MemDepResult::getDef(Inst);
619139f7f9bSDimitry Andric       if (isInvariantLoad)
620139f7f9bSDimitry Andric         continue;
6212754fe60SDimitry Andric       return MemDepResult::getClobber(Inst);
622f22ef01cSRoman Divacky     }
623f22ef01cSRoman Divacky 
624f22ef01cSRoman Divacky     // If this is an allocation, and if we know that the accessed pointer is to
625f22ef01cSRoman Divacky     // the allocation, return Def.  This means that there is no dependence and
626f22ef01cSRoman Divacky     // the access can be optimized based on that.  For example, a load could
6273ca95b02SDimitry Andric     // turn into undef.  Note that we can bypass the allocation itself when
6283ca95b02SDimitry Andric     // looking for a clobber in many cases; that's an alias property and is
6293ca95b02SDimitry Andric     // handled by BasicAA.
6303ca95b02SDimitry Andric     if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, &TLI)) {
63191bc56edSDimitry Andric       const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL);
6323ca95b02SDimitry Andric       if (AccessPtr == Inst || AA.isMustAlias(Inst, AccessPtr))
633f22ef01cSRoman Divacky         return MemDepResult::getDef(Inst);
634f22ef01cSRoman Divacky     }
635f22ef01cSRoman Divacky 
636ff0cc061SDimitry Andric     if (isInvariantLoad)
637ff0cc061SDimitry Andric       continue;
638ff0cc061SDimitry Andric 
6393ca95b02SDimitry Andric     // A release fence requires that all stores complete before it, but does
6403ca95b02SDimitry Andric     // not prevent the reordering of following loads or stores 'before' the
6413ca95b02SDimitry Andric     // fence.  As a result, we look past it when finding a dependency for
6423ca95b02SDimitry Andric     // loads.  DSE uses this to find preceeding stores to delete and thus we
6433ca95b02SDimitry Andric     // can't bypass the fence if the query instruction is a store.
6443ca95b02SDimitry Andric     if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
6453ca95b02SDimitry Andric       if (isLoad && FI->getOrdering() == AtomicOrdering::Release)
6463ca95b02SDimitry Andric         continue;
6473ca95b02SDimitry Andric 
648f22ef01cSRoman Divacky     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
6493ca95b02SDimitry Andric     ModRefInfo MR = AA.getModRefInfo(Inst, MemLoc);
6507ae0e2c9SDimitry Andric     // If necessary, perform additional analysis.
6517d523365SDimitry Andric     if (MR == MRI_ModRef)
6523ca95b02SDimitry Andric       MR = AA.callCapturesBefore(Inst, MemLoc, &DT, &OBB);
6537ae0e2c9SDimitry Andric     switch (MR) {
6547d523365SDimitry Andric     case MRI_NoModRef:
655f22ef01cSRoman Divacky       // If the call has no effect on the queried pointer, just ignore it.
656f22ef01cSRoman Divacky       continue;
6577d523365SDimitry Andric     case MRI_Mod:
658f22ef01cSRoman Divacky       return MemDepResult::getClobber(Inst);
6597d523365SDimitry Andric     case MRI_Ref:
660f22ef01cSRoman Divacky       // If the call is known to never store to the pointer, and if this is a
661f22ef01cSRoman Divacky       // load query, we can safely ignore it (scan past it).
662f22ef01cSRoman Divacky       if (isLoad)
663f22ef01cSRoman Divacky         continue;
664f22ef01cSRoman Divacky     default:
665f22ef01cSRoman Divacky       // Otherwise, there is a potential dependence.  Return a clobber.
666f22ef01cSRoman Divacky       return MemDepResult::getClobber(Inst);
667f22ef01cSRoman Divacky     }
668f22ef01cSRoman Divacky   }
669f22ef01cSRoman Divacky 
67017a519f9SDimitry Andric   // No dependence found.  If this is the entry block of the function, it is
67117a519f9SDimitry Andric   // unknown, otherwise it is non-local.
672f22ef01cSRoman Divacky   if (BB != &BB->getParent()->getEntryBlock())
673f22ef01cSRoman Divacky     return MemDepResult::getNonLocal();
6746122f3e6SDimitry Andric   return MemDepResult::getNonFuncLocal();
675f22ef01cSRoman Divacky }
676f22ef01cSRoman Divacky 
6773ca95b02SDimitry Andric MemDepResult MemoryDependenceResults::getDependency(Instruction *QueryInst) {
678f22ef01cSRoman Divacky   Instruction *ScanPos = QueryInst;
679f22ef01cSRoman Divacky 
680f22ef01cSRoman Divacky   // Check for a cached result
681f22ef01cSRoman Divacky   MemDepResult &LocalCache = LocalDeps[QueryInst];
682f22ef01cSRoman Divacky 
683f22ef01cSRoman Divacky   // If the cached entry is non-dirty, just return it.  Note that this depends
684f22ef01cSRoman Divacky   // on MemDepResult's default constructing to 'dirty'.
685f22ef01cSRoman Divacky   if (!LocalCache.isDirty())
686f22ef01cSRoman Divacky     return LocalCache;
687f22ef01cSRoman Divacky 
688f22ef01cSRoman Divacky   // Otherwise, if we have a dirty entry, we know we can start the scan at that
689f22ef01cSRoman Divacky   // instruction, which may save us some work.
690f22ef01cSRoman Divacky   if (Instruction *Inst = LocalCache.getInst()) {
691f22ef01cSRoman Divacky     ScanPos = Inst;
692f22ef01cSRoman Divacky 
693f22ef01cSRoman Divacky     RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
694f22ef01cSRoman Divacky   }
695f22ef01cSRoman Divacky 
696f22ef01cSRoman Divacky   BasicBlock *QueryParent = QueryInst->getParent();
697f22ef01cSRoman Divacky 
698f22ef01cSRoman Divacky   // Do the scan.
699f22ef01cSRoman Divacky   if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
70017a519f9SDimitry Andric     // No dependence found.  If this is the entry block of the function, it is
70117a519f9SDimitry Andric     // unknown, otherwise it is non-local.
702f22ef01cSRoman Divacky     if (QueryParent != &QueryParent->getParent()->getEntryBlock())
703f22ef01cSRoman Divacky       LocalCache = MemDepResult::getNonLocal();
704f22ef01cSRoman Divacky     else
7056122f3e6SDimitry Andric       LocalCache = MemDepResult::getNonFuncLocal();
7062754fe60SDimitry Andric   } else {
7078f0fd8f6SDimitry Andric     MemoryLocation MemLoc;
7083ca95b02SDimitry Andric     ModRefInfo MR = GetLocation(QueryInst, MemLoc, TLI);
7092754fe60SDimitry Andric     if (MemLoc.Ptr) {
7102754fe60SDimitry Andric       // If we can do a pointer scan, make it happen.
7117d523365SDimitry Andric       bool isLoad = !(MR & MRI_Mod);
7122754fe60SDimitry Andric       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
713bd5abe19SDimitry Andric         isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
714f22ef01cSRoman Divacky 
7157d523365SDimitry Andric       LocalCache = getPointerDependencyFrom(
7167d523365SDimitry Andric           MemLoc, isLoad, ScanPos->getIterator(), QueryParent, QueryInst);
7172754fe60SDimitry Andric     } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
718e580952dSDimitry Andric       CallSite QueryCS(QueryInst);
7193ca95b02SDimitry Andric       bool isReadOnly = AA.onlyReadsMemory(QueryCS);
7207d523365SDimitry Andric       LocalCache = getCallSiteDependencyFrom(
7217d523365SDimitry Andric           QueryCS, isReadOnly, ScanPos->getIterator(), QueryParent);
7222754fe60SDimitry Andric     } else
723f22ef01cSRoman Divacky       // Non-memory instruction.
72417a519f9SDimitry Andric       LocalCache = MemDepResult::getUnknown();
725f22ef01cSRoman Divacky   }
726f22ef01cSRoman Divacky 
727f22ef01cSRoman Divacky   // Remember the result!
728f22ef01cSRoman Divacky   if (Instruction *I = LocalCache.getInst())
729f22ef01cSRoman Divacky     ReverseLocalDeps[I].insert(QueryInst);
730f22ef01cSRoman Divacky 
731f22ef01cSRoman Divacky   return LocalCache;
732f22ef01cSRoman Divacky }
733f22ef01cSRoman Divacky 
734f22ef01cSRoman Divacky #ifndef NDEBUG
7353ca95b02SDimitry Andric /// This method is used when -debug is specified to verify that cache arrays
7363ca95b02SDimitry Andric /// are properly kept sorted.
7373ca95b02SDimitry Andric static void AssertSorted(MemoryDependenceResults::NonLocalDepInfo &Cache,
738f22ef01cSRoman Divacky                          int Count = -1) {
7393ca95b02SDimitry Andric   if (Count == -1)
7403ca95b02SDimitry Andric     Count = Cache.size();
7414d0b32cdSDimitry Andric   assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) &&
7424d0b32cdSDimitry Andric          "Cache isn't sorted!");
743f22ef01cSRoman Divacky }
744f22ef01cSRoman Divacky #endif
745f22ef01cSRoman Divacky 
7463ca95b02SDimitry Andric const MemoryDependenceResults::NonLocalDepInfo &
7473ca95b02SDimitry Andric MemoryDependenceResults::getNonLocalCallDependency(CallSite QueryCS) {
748f22ef01cSRoman Divacky   assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
7493ca95b02SDimitry Andric          "getNonLocalCallDependency should only be used on calls with "
7503ca95b02SDimitry Andric          "non-local deps!");
751f22ef01cSRoman Divacky   PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
752f22ef01cSRoman Divacky   NonLocalDepInfo &Cache = CacheP.first;
753f22ef01cSRoman Divacky 
7543ca95b02SDimitry Andric   // This is the set of blocks that need to be recomputed.  In the cached case,
7553ca95b02SDimitry Andric   // this can happen due to instructions being deleted etc. In the uncached
7563ca95b02SDimitry Andric   // case, this starts out as the set of predecessors we care about.
757f22ef01cSRoman Divacky   SmallVector<BasicBlock *, 32> DirtyBlocks;
758f22ef01cSRoman Divacky 
759f22ef01cSRoman Divacky   if (!Cache.empty()) {
760f22ef01cSRoman Divacky     // Okay, we have a cache entry.  If we know it is not dirty, just return it
761f22ef01cSRoman Divacky     // with no computation.
762f22ef01cSRoman Divacky     if (!CacheP.second) {
763ffd1746dSEd Schouten       ++NumCacheNonLocal;
764f22ef01cSRoman Divacky       return Cache;
765f22ef01cSRoman Divacky     }
766f22ef01cSRoman Divacky 
767f22ef01cSRoman Divacky     // If we already have a partially computed set of results, scan them to
768f22ef01cSRoman Divacky     // determine what is dirty, seeding our initial DirtyBlocks worklist.
7693ca95b02SDimitry Andric     for (auto &Entry : Cache)
7703ca95b02SDimitry Andric       if (Entry.getResult().isDirty())
7713ca95b02SDimitry Andric         DirtyBlocks.push_back(Entry.getBB());
772f22ef01cSRoman Divacky 
773f22ef01cSRoman Divacky     // Sort the cache so that we can do fast binary search lookups below.
774f22ef01cSRoman Divacky     std::sort(Cache.begin(), Cache.end());
775f22ef01cSRoman Divacky 
776f22ef01cSRoman Divacky     ++NumCacheDirtyNonLocal;
777f22ef01cSRoman Divacky     // cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
778f22ef01cSRoman Divacky     //     << Cache.size() << " cached: " << *QueryInst;
779f22ef01cSRoman Divacky   } else {
780f22ef01cSRoman Divacky     // Seed DirtyBlocks with each of the preds of QueryInst's block.
781f22ef01cSRoman Divacky     BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
782ff0cc061SDimitry Andric     for (BasicBlock *Pred : PredCache.get(QueryBB))
783ff0cc061SDimitry Andric       DirtyBlocks.push_back(Pred);
784ffd1746dSEd Schouten     ++NumUncacheNonLocal;
785f22ef01cSRoman Divacky   }
786f22ef01cSRoman Divacky 
787f22ef01cSRoman Divacky   // isReadonlyCall - If this is a read-only call, we can be more aggressive.
7883ca95b02SDimitry Andric   bool isReadonlyCall = AA.onlyReadsMemory(QueryCS);
789f22ef01cSRoman Divacky 
7903ca95b02SDimitry Andric   SmallPtrSet<BasicBlock *, 32> Visited;
791f22ef01cSRoman Divacky 
792f22ef01cSRoman Divacky   unsigned NumSortedEntries = Cache.size();
793f22ef01cSRoman Divacky   DEBUG(AssertSorted(Cache));
794f22ef01cSRoman Divacky 
795f22ef01cSRoman Divacky   // Iterate while we still have blocks to update.
796f22ef01cSRoman Divacky   while (!DirtyBlocks.empty()) {
797f22ef01cSRoman Divacky     BasicBlock *DirtyBB = DirtyBlocks.back();
798f22ef01cSRoman Divacky     DirtyBlocks.pop_back();
799f22ef01cSRoman Divacky 
800f22ef01cSRoman Divacky     // Already processed this block?
80139d628a0SDimitry Andric     if (!Visited.insert(DirtyBB).second)
802f22ef01cSRoman Divacky       continue;
803f22ef01cSRoman Divacky 
804f22ef01cSRoman Divacky     // Do a binary search to see if we already have an entry for this block in
805f22ef01cSRoman Divacky     // the cache set.  If so, find it.
806f22ef01cSRoman Divacky     DEBUG(AssertSorted(Cache, NumSortedEntries));
807f22ef01cSRoman Divacky     NonLocalDepInfo::iterator Entry =
808f22ef01cSRoman Divacky         std::upper_bound(Cache.begin(), Cache.begin() + NumSortedEntries,
809f22ef01cSRoman Divacky                          NonLocalDepEntry(DirtyBB));
81091bc56edSDimitry Andric     if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
811f22ef01cSRoman Divacky       --Entry;
812f22ef01cSRoman Divacky 
81391bc56edSDimitry Andric     NonLocalDepEntry *ExistingResult = nullptr;
814f22ef01cSRoman Divacky     if (Entry != Cache.begin() + NumSortedEntries &&
815f22ef01cSRoman Divacky         Entry->getBB() == DirtyBB) {
816f22ef01cSRoman Divacky       // If we already have an entry, and if it isn't already dirty, the block
817f22ef01cSRoman Divacky       // is done.
818f22ef01cSRoman Divacky       if (!Entry->getResult().isDirty())
819f22ef01cSRoman Divacky         continue;
820f22ef01cSRoman Divacky 
821f22ef01cSRoman Divacky       // Otherwise, remember this slot so we can update the value.
822f22ef01cSRoman Divacky       ExistingResult = &*Entry;
823f22ef01cSRoman Divacky     }
824f22ef01cSRoman Divacky 
825f22ef01cSRoman Divacky     // If the dirty entry has a pointer, start scanning from it so we don't have
826f22ef01cSRoman Divacky     // to rescan the entire block.
827f22ef01cSRoman Divacky     BasicBlock::iterator ScanPos = DirtyBB->end();
828f22ef01cSRoman Divacky     if (ExistingResult) {
829f22ef01cSRoman Divacky       if (Instruction *Inst = ExistingResult->getResult().getInst()) {
8307d523365SDimitry Andric         ScanPos = Inst->getIterator();
831f22ef01cSRoman Divacky         // We're removing QueryInst's use of Inst.
832f22ef01cSRoman Divacky         RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
833f22ef01cSRoman Divacky                              QueryCS.getInstruction());
834f22ef01cSRoman Divacky       }
835f22ef01cSRoman Divacky     }
836f22ef01cSRoman Divacky 
837f22ef01cSRoman Divacky     // Find out if this block has a local dependency for QueryInst.
838f22ef01cSRoman Divacky     MemDepResult Dep;
839f22ef01cSRoman Divacky 
840f22ef01cSRoman Divacky     if (ScanPos != DirtyBB->begin()) {
8413ca95b02SDimitry Andric       Dep =
8423ca95b02SDimitry Andric           getCallSiteDependencyFrom(QueryCS, isReadonlyCall, ScanPos, DirtyBB);
843f22ef01cSRoman Divacky     } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
844f22ef01cSRoman Divacky       // No dependence found.  If this is the entry block of the function, it is
84517a519f9SDimitry Andric       // a clobber, otherwise it is unknown.
846f22ef01cSRoman Divacky       Dep = MemDepResult::getNonLocal();
847f22ef01cSRoman Divacky     } else {
8486122f3e6SDimitry Andric       Dep = MemDepResult::getNonFuncLocal();
849f22ef01cSRoman Divacky     }
850f22ef01cSRoman Divacky 
851f22ef01cSRoman Divacky     // If we had a dirty entry for the block, update it.  Otherwise, just add
852f22ef01cSRoman Divacky     // a new entry.
853f22ef01cSRoman Divacky     if (ExistingResult)
854f22ef01cSRoman Divacky       ExistingResult->setResult(Dep);
855f22ef01cSRoman Divacky     else
856f22ef01cSRoman Divacky       Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
857f22ef01cSRoman Divacky 
858f22ef01cSRoman Divacky     // If the block has a dependency (i.e. it isn't completely transparent to
859f22ef01cSRoman Divacky     // the value), remember the association!
860f22ef01cSRoman Divacky     if (!Dep.isNonLocal()) {
861f22ef01cSRoman Divacky       // Keep the ReverseNonLocalDeps map up to date so we can efficiently
862f22ef01cSRoman Divacky       // update this when we remove instructions.
863f22ef01cSRoman Divacky       if (Instruction *Inst = Dep.getInst())
864f22ef01cSRoman Divacky         ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
865f22ef01cSRoman Divacky     } else {
866f22ef01cSRoman Divacky 
867f22ef01cSRoman Divacky       // If the block *is* completely transparent to the load, we need to check
868f22ef01cSRoman Divacky       // the predecessors of this block.  Add them to our worklist.
869ff0cc061SDimitry Andric       for (BasicBlock *Pred : PredCache.get(DirtyBB))
870ff0cc061SDimitry Andric         DirtyBlocks.push_back(Pred);
871f22ef01cSRoman Divacky     }
872f22ef01cSRoman Divacky   }
873f22ef01cSRoman Divacky 
874f22ef01cSRoman Divacky   return Cache;
875f22ef01cSRoman Divacky }
876f22ef01cSRoman Divacky 
8773ca95b02SDimitry Andric void MemoryDependenceResults::getNonLocalPointerDependency(
8783ca95b02SDimitry Andric     Instruction *QueryInst, SmallVectorImpl<NonLocalDepResult> &Result) {
8798f0fd8f6SDimitry Andric   const MemoryLocation Loc = MemoryLocation::get(QueryInst);
88039d628a0SDimitry Andric   bool isLoad = isa<LoadInst>(QueryInst);
88139d628a0SDimitry Andric   BasicBlock *FromBB = QueryInst->getParent();
88239d628a0SDimitry Andric   assert(FromBB);
88339d628a0SDimitry Andric 
8842754fe60SDimitry Andric   assert(Loc.Ptr->getType()->isPointerTy() &&
885f22ef01cSRoman Divacky          "Can't get pointer deps of a non-pointer!");
886f22ef01cSRoman Divacky   Result.clear();
887f22ef01cSRoman Divacky 
88839d628a0SDimitry Andric   // This routine does not expect to deal with volatile instructions.
88939d628a0SDimitry Andric   // Doing so would require piping through the QueryInst all the way through.
89039d628a0SDimitry Andric   // TODO: volatiles can't be elided, but they can be reordered with other
89139d628a0SDimitry Andric   // non-volatile accesses.
892ff0cc061SDimitry Andric 
89339d628a0SDimitry Andric   // We currently give up on any instruction which is ordered, but we do handle
89439d628a0SDimitry Andric   // atomic instructions which are unordered.
89539d628a0SDimitry Andric   // TODO: Handle ordered instructions
89639d628a0SDimitry Andric   auto isOrdered = [](Instruction *Inst) {
89739d628a0SDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
89839d628a0SDimitry Andric       return !LI->isUnordered();
89939d628a0SDimitry Andric     } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
90039d628a0SDimitry Andric       return !SI->isUnordered();
90139d628a0SDimitry Andric     }
90239d628a0SDimitry Andric     return false;
90339d628a0SDimitry Andric   };
90439d628a0SDimitry Andric   if (isVolatile(QueryInst) || isOrdered(QueryInst)) {
9053ca95b02SDimitry Andric     Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
90639d628a0SDimitry Andric                                        const_cast<Value *>(Loc.Ptr)));
90739d628a0SDimitry Andric     return;
90839d628a0SDimitry Andric   }
909ff0cc061SDimitry Andric   const DataLayout &DL = FromBB->getModule()->getDataLayout();
9103ca95b02SDimitry Andric   PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC);
911f22ef01cSRoman Divacky 
912f22ef01cSRoman Divacky   // This is the set of blocks we've inspected, and the pointer we consider in
913f22ef01cSRoman Divacky   // each block.  Because of critical edges, we currently bail out if querying
914f22ef01cSRoman Divacky   // a block with multiple different pointers.  This can happen during PHI
915f22ef01cSRoman Divacky   // translation.
916f22ef01cSRoman Divacky   DenseMap<BasicBlock *, Value *> Visited;
9173ca95b02SDimitry Andric   if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
918f22ef01cSRoman Divacky                                    Result, Visited, true))
919f22ef01cSRoman Divacky     return;
920f22ef01cSRoman Divacky   Result.clear();
9213ca95b02SDimitry Andric   Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
9222754fe60SDimitry Andric                                      const_cast<Value *>(Loc.Ptr)));
923f22ef01cSRoman Divacky }
924f22ef01cSRoman Divacky 
9253ca95b02SDimitry Andric /// Compute the memdep value for BB with Pointer/PointeeSize using either
9263ca95b02SDimitry Andric /// cached information in Cache or by doing a lookup (which may use dirty cache
9273ca95b02SDimitry Andric /// info if available).
9283ca95b02SDimitry Andric ///
9293ca95b02SDimitry Andric /// If we do a lookup, add the result to the cache.
9303ca95b02SDimitry Andric MemDepResult MemoryDependenceResults::GetNonLocalInfoForBlock(
9318f0fd8f6SDimitry Andric     Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad,
9328f0fd8f6SDimitry Andric     BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
933f22ef01cSRoman Divacky 
934f22ef01cSRoman Divacky   // Do a binary search to see if we already have an entry for this block in
935f22ef01cSRoman Divacky   // the cache set.  If so, find it.
9363ca95b02SDimitry Andric   NonLocalDepInfo::iterator Entry = std::upper_bound(
9373ca95b02SDimitry Andric       Cache->begin(), Cache->begin() + NumSortedEntries, NonLocalDepEntry(BB));
938f22ef01cSRoman Divacky   if (Entry != Cache->begin() && (Entry - 1)->getBB() == BB)
939f22ef01cSRoman Divacky     --Entry;
940f22ef01cSRoman Divacky 
94191bc56edSDimitry Andric   NonLocalDepEntry *ExistingResult = nullptr;
942f22ef01cSRoman Divacky   if (Entry != Cache->begin() + NumSortedEntries && Entry->getBB() == BB)
943f22ef01cSRoman Divacky     ExistingResult = &*Entry;
944f22ef01cSRoman Divacky 
945f22ef01cSRoman Divacky   // If we have a cached entry, and it is non-dirty, use it as the value for
946f22ef01cSRoman Divacky   // this dependency.
947f22ef01cSRoman Divacky   if (ExistingResult && !ExistingResult->getResult().isDirty()) {
948f22ef01cSRoman Divacky     ++NumCacheNonLocalPtr;
949f22ef01cSRoman Divacky     return ExistingResult->getResult();
950f22ef01cSRoman Divacky   }
951f22ef01cSRoman Divacky 
952f22ef01cSRoman Divacky   // Otherwise, we have to scan for the value.  If we have a dirty cache
953f22ef01cSRoman Divacky   // entry, start scanning from its position, otherwise we scan from the end
954f22ef01cSRoman Divacky   // of the block.
955f22ef01cSRoman Divacky   BasicBlock::iterator ScanPos = BB->end();
956f22ef01cSRoman Divacky   if (ExistingResult && ExistingResult->getResult().getInst()) {
957f22ef01cSRoman Divacky     assert(ExistingResult->getResult().getInst()->getParent() == BB &&
958f22ef01cSRoman Divacky            "Instruction invalidated?");
959f22ef01cSRoman Divacky     ++NumCacheDirtyNonLocalPtr;
9607d523365SDimitry Andric     ScanPos = ExistingResult->getResult().getInst()->getIterator();
961f22ef01cSRoman Divacky 
962f22ef01cSRoman Divacky     // Eliminating the dirty entry from 'Cache', so update the reverse info.
9632754fe60SDimitry Andric     ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
9647d523365SDimitry Andric     RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey);
965f22ef01cSRoman Divacky   } else {
966f22ef01cSRoman Divacky     ++NumUncacheNonLocalPtr;
967f22ef01cSRoman Divacky   }
968f22ef01cSRoman Divacky 
969f22ef01cSRoman Divacky   // Scan the block for the dependency.
9703ca95b02SDimitry Andric   MemDepResult Dep =
9713ca95b02SDimitry Andric       getPointerDependencyFrom(Loc, isLoad, ScanPos, BB, QueryInst);
972f22ef01cSRoman Divacky 
973f22ef01cSRoman Divacky   // If we had a dirty entry for the block, update it.  Otherwise, just add
974f22ef01cSRoman Divacky   // a new entry.
975f22ef01cSRoman Divacky   if (ExistingResult)
976f22ef01cSRoman Divacky     ExistingResult->setResult(Dep);
977f22ef01cSRoman Divacky   else
978f22ef01cSRoman Divacky     Cache->push_back(NonLocalDepEntry(BB, Dep));
979f22ef01cSRoman Divacky 
980f22ef01cSRoman Divacky   // If the block has a dependency (i.e. it isn't completely transparent to
981f22ef01cSRoman Divacky   // the value), remember the reverse association because we just added it
982f22ef01cSRoman Divacky   // to Cache!
9836122f3e6SDimitry Andric   if (!Dep.isDef() && !Dep.isClobber())
984f22ef01cSRoman Divacky     return Dep;
985f22ef01cSRoman Divacky 
986f22ef01cSRoman Divacky   // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
987f22ef01cSRoman Divacky   // update MemDep when we remove instructions.
988f22ef01cSRoman Divacky   Instruction *Inst = Dep.getInst();
989f22ef01cSRoman Divacky   assert(Inst && "Didn't depend on anything?");
9902754fe60SDimitry Andric   ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
991f22ef01cSRoman Divacky   ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
992f22ef01cSRoman Divacky   return Dep;
993f22ef01cSRoman Divacky }
994f22ef01cSRoman Divacky 
9953ca95b02SDimitry Andric /// Sort the NonLocalDepInfo cache, given a certain number of elements in the
9963ca95b02SDimitry Andric /// array that are already properly ordered.
9973ca95b02SDimitry Andric ///
9983ca95b02SDimitry Andric /// This is optimized for the case when only a few entries are added.
999f22ef01cSRoman Divacky static void
10003ca95b02SDimitry Andric SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache,
1001f22ef01cSRoman Divacky                          unsigned NumSortedEntries) {
1002f22ef01cSRoman Divacky   switch (Cache.size() - NumSortedEntries) {
1003f22ef01cSRoman Divacky   case 0:
1004f22ef01cSRoman Divacky     // done, no new entries.
1005f22ef01cSRoman Divacky     break;
1006f22ef01cSRoman Divacky   case 2: {
1007f22ef01cSRoman Divacky     // Two new entries, insert the last one into place.
1008f22ef01cSRoman Divacky     NonLocalDepEntry Val = Cache.back();
1009f22ef01cSRoman Divacky     Cache.pop_back();
10103ca95b02SDimitry Andric     MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
1011f22ef01cSRoman Divacky         std::upper_bound(Cache.begin(), Cache.end() - 1, Val);
1012f22ef01cSRoman Divacky     Cache.insert(Entry, Val);
1013f22ef01cSRoman Divacky     // FALL THROUGH.
1014f22ef01cSRoman Divacky   }
1015f22ef01cSRoman Divacky   case 1:
1016f22ef01cSRoman Divacky     // One new entry, Just insert the new value at the appropriate position.
1017f22ef01cSRoman Divacky     if (Cache.size() != 1) {
1018f22ef01cSRoman Divacky       NonLocalDepEntry Val = Cache.back();
1019f22ef01cSRoman Divacky       Cache.pop_back();
10203ca95b02SDimitry Andric       MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
1021f22ef01cSRoman Divacky           std::upper_bound(Cache.begin(), Cache.end(), Val);
1022f22ef01cSRoman Divacky       Cache.insert(Entry, Val);
1023f22ef01cSRoman Divacky     }
1024f22ef01cSRoman Divacky     break;
1025f22ef01cSRoman Divacky   default:
1026f22ef01cSRoman Divacky     // Added many values, do a full scale sort.
1027f22ef01cSRoman Divacky     std::sort(Cache.begin(), Cache.end());
1028f22ef01cSRoman Divacky     break;
1029f22ef01cSRoman Divacky   }
1030f22ef01cSRoman Divacky }
1031f22ef01cSRoman Divacky 
10323ca95b02SDimitry Andric /// Perform a dependency query based on pointer/pointeesize starting at the end
10333ca95b02SDimitry Andric /// of StartBB.
10343ca95b02SDimitry Andric ///
10353ca95b02SDimitry Andric /// Add any clobber/def results to the results vector and keep track of which
10363ca95b02SDimitry Andric /// blocks are visited in 'Visited'.
1037f22ef01cSRoman Divacky ///
1038f22ef01cSRoman Divacky /// This has special behavior for the first block queries (when SkipFirstBlock
1039f22ef01cSRoman Divacky /// is true).  In this special case, it ignores the contents of the specified
1040f22ef01cSRoman Divacky /// block and starts returning dependence info for its predecessors.
1041f22ef01cSRoman Divacky ///
10423ca95b02SDimitry Andric /// This function returns true on success, or false to indicate that it could
1043f22ef01cSRoman Divacky /// not compute dependence information for some reason.  This should be treated
1044f22ef01cSRoman Divacky /// as a clobber dependence on the first instruction in the predecessor block.
10453ca95b02SDimitry Andric bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
10468f0fd8f6SDimitry Andric     Instruction *QueryInst, const PHITransAddr &Pointer,
10478f0fd8f6SDimitry Andric     const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB,
1048f22ef01cSRoman Divacky     SmallVectorImpl<NonLocalDepResult> &Result,
10498f0fd8f6SDimitry Andric     DenseMap<BasicBlock *, Value *> &Visited, bool SkipFirstBlock) {
1050f22ef01cSRoman Divacky   // Look up the cached info for Pointer.
1051f22ef01cSRoman Divacky   ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
1052f22ef01cSRoman Divacky 
10532754fe60SDimitry Andric   // Set up a temporary NLPI value. If the map doesn't yet have an entry for
10542754fe60SDimitry Andric   // CacheKey, this value will be inserted as the associated value. Otherwise,
10552754fe60SDimitry Andric   // it'll be ignored, and we'll have to check to see if the cached size and
105639d628a0SDimitry Andric   // aa tags are consistent with the current query.
10572754fe60SDimitry Andric   NonLocalPointerInfo InitialNLPI;
10582754fe60SDimitry Andric   InitialNLPI.Size = Loc.Size;
105939d628a0SDimitry Andric   InitialNLPI.AATags = Loc.AATags;
10602754fe60SDimitry Andric 
10612754fe60SDimitry Andric   // Get the NLPI for CacheKey, inserting one into the map if it doesn't
10622754fe60SDimitry Andric   // already have one.
10632754fe60SDimitry Andric   std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
10642754fe60SDimitry Andric       NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
10652754fe60SDimitry Andric   NonLocalPointerInfo *CacheInfo = &Pair.first->second;
10662754fe60SDimitry Andric 
10672754fe60SDimitry Andric   // If we already have a cache entry for this CacheKey, we may need to do some
10682754fe60SDimitry Andric   // work to reconcile the cache entry and the current query.
10692754fe60SDimitry Andric   if (!Pair.second) {
10702754fe60SDimitry Andric     if (CacheInfo->Size < Loc.Size) {
10712754fe60SDimitry Andric       // The query's Size is greater than the cached one. Throw out the
10727ae0e2c9SDimitry Andric       // cached data and proceed with the query at the greater size.
10732754fe60SDimitry Andric       CacheInfo->Pair = BBSkipFirstBlockPair();
10742754fe60SDimitry Andric       CacheInfo->Size = Loc.Size;
10753ca95b02SDimitry Andric       for (auto &Entry : CacheInfo->NonLocalDeps)
10763ca95b02SDimitry Andric         if (Instruction *Inst = Entry.getResult().getInst())
10772754fe60SDimitry Andric           RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
10782754fe60SDimitry Andric       CacheInfo->NonLocalDeps.clear();
10792754fe60SDimitry Andric     } else if (CacheInfo->Size > Loc.Size) {
10802754fe60SDimitry Andric       // This query's Size is less than the cached one. Conservatively restart
10812754fe60SDimitry Andric       // the query using the greater size.
10823ca95b02SDimitry Andric       return getNonLocalPointerDepFromBB(
10833ca95b02SDimitry Andric           QueryInst, Pointer, Loc.getWithNewSize(CacheInfo->Size), isLoad,
10843ca95b02SDimitry Andric           StartBB, Result, Visited, SkipFirstBlock);
10852754fe60SDimitry Andric     }
10862754fe60SDimitry Andric 
108739d628a0SDimitry Andric     // If the query's AATags are inconsistent with the cached one,
10882754fe60SDimitry Andric     // conservatively throw out the cached data and restart the query with
10892754fe60SDimitry Andric     // no tag if needed.
109039d628a0SDimitry Andric     if (CacheInfo->AATags != Loc.AATags) {
109139d628a0SDimitry Andric       if (CacheInfo->AATags) {
10922754fe60SDimitry Andric         CacheInfo->Pair = BBSkipFirstBlockPair();
109339d628a0SDimitry Andric         CacheInfo->AATags = AAMDNodes();
10943ca95b02SDimitry Andric         for (auto &Entry : CacheInfo->NonLocalDeps)
10953ca95b02SDimitry Andric           if (Instruction *Inst = Entry.getResult().getInst())
10962754fe60SDimitry Andric             RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
10972754fe60SDimitry Andric         CacheInfo->NonLocalDeps.clear();
10982754fe60SDimitry Andric       }
109939d628a0SDimitry Andric       if (Loc.AATags)
11003ca95b02SDimitry Andric         return getNonLocalPointerDepFromBB(
11013ca95b02SDimitry Andric             QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result,
11023ca95b02SDimitry Andric             Visited, SkipFirstBlock);
11032754fe60SDimitry Andric     }
11042754fe60SDimitry Andric   }
11052754fe60SDimitry Andric 
11062754fe60SDimitry Andric   NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
1107f22ef01cSRoman Divacky 
1108f22ef01cSRoman Divacky   // If we have valid cached information for exactly the block we are
1109f22ef01cSRoman Divacky   // investigating, just return it with no recomputation.
11102754fe60SDimitry Andric   if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
1111f22ef01cSRoman Divacky     // We have a fully cached result for this query then we can just return the
1112f22ef01cSRoman Divacky     // cached results and populate the visited set.  However, we have to verify
1113f22ef01cSRoman Divacky     // that we don't already have conflicting results for these blocks.  Check
1114f22ef01cSRoman Divacky     // to ensure that if a block in the results set is in the visited set that
1115f22ef01cSRoman Divacky     // it was for the same pointer query.
1116f22ef01cSRoman Divacky     if (!Visited.empty()) {
11173ca95b02SDimitry Andric       for (auto &Entry : *Cache) {
11183ca95b02SDimitry Andric         DenseMap<BasicBlock *, Value *>::iterator VI =
11193ca95b02SDimitry Andric             Visited.find(Entry.getBB());
1120f22ef01cSRoman Divacky         if (VI == Visited.end() || VI->second == Pointer.getAddr())
1121f22ef01cSRoman Divacky           continue;
1122f22ef01cSRoman Divacky 
11233ca95b02SDimitry Andric         // We have a pointer mismatch in a block.  Just return false, saying
1124f22ef01cSRoman Divacky         // that something was clobbered in this result.  We could also do a
1125f22ef01cSRoman Divacky         // non-fully cached query, but there is little point in doing this.
11263ca95b02SDimitry Andric         return false;
1127f22ef01cSRoman Divacky       }
1128f22ef01cSRoman Divacky     }
1129f22ef01cSRoman Divacky 
1130f22ef01cSRoman Divacky     Value *Addr = Pointer.getAddr();
11313ca95b02SDimitry Andric     for (auto &Entry : *Cache) {
11323ca95b02SDimitry Andric       Visited.insert(std::make_pair(Entry.getBB(), Addr));
11333ca95b02SDimitry Andric       if (Entry.getResult().isNonLocal()) {
1134284c1978SDimitry Andric         continue;
1135284c1978SDimitry Andric       }
1136284c1978SDimitry Andric 
11373ca95b02SDimitry Andric       if (DT.isReachableFromEntry(Entry.getBB())) {
11383ca95b02SDimitry Andric         Result.push_back(
11393ca95b02SDimitry Andric             NonLocalDepResult(Entry.getBB(), Entry.getResult(), Addr));
1140f22ef01cSRoman Divacky       }
1141284c1978SDimitry Andric     }
1142f22ef01cSRoman Divacky     ++NumCacheCompleteNonLocalPtr;
11433ca95b02SDimitry Andric     return true;
1144f22ef01cSRoman Divacky   }
1145f22ef01cSRoman Divacky 
1146f22ef01cSRoman Divacky   // Otherwise, either this is a new block, a block with an invalid cache
1147f22ef01cSRoman Divacky   // pointer or one that we're about to invalidate by putting more info into it
1148f22ef01cSRoman Divacky   // than its valid cache info.  If empty, the result will be valid cache info,
1149f22ef01cSRoman Divacky   // otherwise it isn't.
1150f22ef01cSRoman Divacky   if (Cache->empty())
11512754fe60SDimitry Andric     CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
1152f22ef01cSRoman Divacky   else
11532754fe60SDimitry Andric     CacheInfo->Pair = BBSkipFirstBlockPair();
1154f22ef01cSRoman Divacky 
1155f22ef01cSRoman Divacky   SmallVector<BasicBlock *, 32> Worklist;
1156f22ef01cSRoman Divacky   Worklist.push_back(StartBB);
1157f22ef01cSRoman Divacky 
1158bd5abe19SDimitry Andric   // PredList used inside loop.
1159bd5abe19SDimitry Andric   SmallVector<std::pair<BasicBlock *, PHITransAddr>, 16> PredList;
1160bd5abe19SDimitry Andric 
1161f22ef01cSRoman Divacky   // Keep track of the entries that we know are sorted.  Previously cached
1162f22ef01cSRoman Divacky   // entries will all be sorted.  The entries we add we only sort on demand (we
1163f22ef01cSRoman Divacky   // don't insert every element into its sorted position).  We know that we
1164f22ef01cSRoman Divacky   // won't get any reuse from currently inserted values, because we don't
1165f22ef01cSRoman Divacky   // revisit blocks after we insert info for them.
1166f22ef01cSRoman Divacky   unsigned NumSortedEntries = Cache->size();
11673ca95b02SDimitry Andric   unsigned WorklistEntries = BlockNumberLimit;
11683ca95b02SDimitry Andric   bool GotWorklistLimit = false;
1169f22ef01cSRoman Divacky   DEBUG(AssertSorted(*Cache));
1170f22ef01cSRoman Divacky 
1171f22ef01cSRoman Divacky   while (!Worklist.empty()) {
1172f22ef01cSRoman Divacky     BasicBlock *BB = Worklist.pop_back_val();
1173f22ef01cSRoman Divacky 
117439d628a0SDimitry Andric     // If we do process a large number of blocks it becomes very expensive and
117539d628a0SDimitry Andric     // likely it isn't worth worrying about
117639d628a0SDimitry Andric     if (Result.size() > NumResultsLimit) {
117739d628a0SDimitry Andric       Worklist.clear();
117839d628a0SDimitry Andric       // Sort it now (if needed) so that recursive invocations of
117939d628a0SDimitry Andric       // getNonLocalPointerDepFromBB and other routines that could reuse the
118039d628a0SDimitry Andric       // cache value will only see properly sorted cache arrays.
118139d628a0SDimitry Andric       if (Cache && NumSortedEntries != Cache->size()) {
118239d628a0SDimitry Andric         SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
118339d628a0SDimitry Andric       }
118439d628a0SDimitry Andric       // Since we bail out, the "Cache" set won't contain all of the
118539d628a0SDimitry Andric       // results for the query.  This is ok (we can still use it to accelerate
118639d628a0SDimitry Andric       // specific block queries) but we can't do the fastpath "return all
118739d628a0SDimitry Andric       // results from the set".  Clear out the indicator for this.
118839d628a0SDimitry Andric       CacheInfo->Pair = BBSkipFirstBlockPair();
11893ca95b02SDimitry Andric       return false;
119039d628a0SDimitry Andric     }
119139d628a0SDimitry Andric 
1192f22ef01cSRoman Divacky     // Skip the first block if we have it.
1193f22ef01cSRoman Divacky     if (!SkipFirstBlock) {
1194f22ef01cSRoman Divacky       // Analyze the dependency of *Pointer in FromBB.  See if we already have
1195f22ef01cSRoman Divacky       // been here.
1196f22ef01cSRoman Divacky       assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
1197f22ef01cSRoman Divacky 
1198f22ef01cSRoman Divacky       // Get the dependency info for Pointer in BB.  If we have cached
1199f22ef01cSRoman Divacky       // information, we will use it, otherwise we compute it.
1200f22ef01cSRoman Divacky       DEBUG(AssertSorted(*Cache, NumSortedEntries));
12013ca95b02SDimitry Andric       MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst, Loc, isLoad, BB,
12023ca95b02SDimitry Andric                                                  Cache, NumSortedEntries);
1203f22ef01cSRoman Divacky 
1204f22ef01cSRoman Divacky       // If we got a Def or Clobber, add this to the list of results.
1205284c1978SDimitry Andric       if (!Dep.isNonLocal()) {
12063ca95b02SDimitry Andric         if (DT.isReachableFromEntry(BB)) {
1207f22ef01cSRoman Divacky           Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
1208f22ef01cSRoman Divacky           continue;
1209f22ef01cSRoman Divacky         }
1210f22ef01cSRoman Divacky       }
1211284c1978SDimitry Andric     }
1212f22ef01cSRoman Divacky 
1213f22ef01cSRoman Divacky     // If 'Pointer' is an instruction defined in this block, then we need to do
1214f22ef01cSRoman Divacky     // phi translation to change it into a value live in the predecessor block.
1215f22ef01cSRoman Divacky     // If not, we just add the predecessors to the worklist and scan them with
1216f22ef01cSRoman Divacky     // the same Pointer.
1217f22ef01cSRoman Divacky     if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
1218f22ef01cSRoman Divacky       SkipFirstBlock = false;
1219bd5abe19SDimitry Andric       SmallVector<BasicBlock *, 16> NewBlocks;
1220ff0cc061SDimitry Andric       for (BasicBlock *Pred : PredCache.get(BB)) {
1221f22ef01cSRoman Divacky         // Verify that we haven't looked at this block yet.
12223ca95b02SDimitry Andric         std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
12233ca95b02SDimitry Andric             Visited.insert(std::make_pair(Pred, Pointer.getAddr()));
1224f22ef01cSRoman Divacky         if (InsertRes.second) {
1225f22ef01cSRoman Divacky           // First time we've looked at *PI.
1226ff0cc061SDimitry Andric           NewBlocks.push_back(Pred);
1227f22ef01cSRoman Divacky           continue;
1228f22ef01cSRoman Divacky         }
1229f22ef01cSRoman Divacky 
1230f22ef01cSRoman Divacky         // If we have seen this block before, but it was with a different
1231f22ef01cSRoman Divacky         // pointer then we have a phi translation failure and we have to treat
1232f22ef01cSRoman Divacky         // this as a clobber.
1233bd5abe19SDimitry Andric         if (InsertRes.first->second != Pointer.getAddr()) {
1234bd5abe19SDimitry Andric           // Make sure to clean up the Visited map before continuing on to
1235bd5abe19SDimitry Andric           // PredTranslationFailure.
1236bd5abe19SDimitry Andric           for (unsigned i = 0; i < NewBlocks.size(); i++)
1237bd5abe19SDimitry Andric             Visited.erase(NewBlocks[i]);
1238f22ef01cSRoman Divacky           goto PredTranslationFailure;
1239f22ef01cSRoman Divacky         }
1240bd5abe19SDimitry Andric       }
12413ca95b02SDimitry Andric       if (NewBlocks.size() > WorklistEntries) {
12423ca95b02SDimitry Andric         // Make sure to clean up the Visited map before continuing on to
12433ca95b02SDimitry Andric         // PredTranslationFailure.
12443ca95b02SDimitry Andric         for (unsigned i = 0; i < NewBlocks.size(); i++)
12453ca95b02SDimitry Andric           Visited.erase(NewBlocks[i]);
12463ca95b02SDimitry Andric         GotWorklistLimit = true;
12473ca95b02SDimitry Andric         goto PredTranslationFailure;
12483ca95b02SDimitry Andric       }
12493ca95b02SDimitry Andric       WorklistEntries -= NewBlocks.size();
1250bd5abe19SDimitry Andric       Worklist.append(NewBlocks.begin(), NewBlocks.end());
1251f22ef01cSRoman Divacky       continue;
1252f22ef01cSRoman Divacky     }
1253f22ef01cSRoman Divacky 
1254f22ef01cSRoman Divacky     // We do need to do phi translation, if we know ahead of time we can't phi
1255f22ef01cSRoman Divacky     // translate this value, don't even try.
1256f22ef01cSRoman Divacky     if (!Pointer.IsPotentiallyPHITranslatable())
1257f22ef01cSRoman Divacky       goto PredTranslationFailure;
1258f22ef01cSRoman Divacky 
1259f22ef01cSRoman Divacky     // We may have added values to the cache list before this PHI translation.
1260f22ef01cSRoman Divacky     // If so, we haven't done anything to ensure that the cache remains sorted.
1261f22ef01cSRoman Divacky     // Sort it now (if needed) so that recursive invocations of
1262f22ef01cSRoman Divacky     // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1263f22ef01cSRoman Divacky     // value will only see properly sorted cache arrays.
1264f22ef01cSRoman Divacky     if (Cache && NumSortedEntries != Cache->size()) {
1265f22ef01cSRoman Divacky       SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1266f22ef01cSRoman Divacky       NumSortedEntries = Cache->size();
1267f22ef01cSRoman Divacky     }
126891bc56edSDimitry Andric     Cache = nullptr;
1269f22ef01cSRoman Divacky 
1270bd5abe19SDimitry Andric     PredList.clear();
1271ff0cc061SDimitry Andric     for (BasicBlock *Pred : PredCache.get(BB)) {
1272bd5abe19SDimitry Andric       PredList.push_back(std::make_pair(Pred, Pointer));
1273f22ef01cSRoman Divacky 
1274f22ef01cSRoman Divacky       // Get the PHI translated pointer in this predecessor.  This can fail if
1275f22ef01cSRoman Divacky       // not translatable, in which case the getAddr() returns null.
1276bd5abe19SDimitry Andric       PHITransAddr &PredPointer = PredList.back().second;
12773ca95b02SDimitry Andric       PredPointer.PHITranslateValue(BB, Pred, &DT, /*MustDominate=*/false);
1278f22ef01cSRoman Divacky       Value *PredPtrVal = PredPointer.getAddr();
1279f22ef01cSRoman Divacky 
1280f22ef01cSRoman Divacky       // Check to see if we have already visited this pred block with another
1281f22ef01cSRoman Divacky       // pointer.  If so, we can't do this lookup.  This failure can occur
1282f22ef01cSRoman Divacky       // with PHI translation when a critical edge exists and the PHI node in
1283f22ef01cSRoman Divacky       // the successor translates to a pointer value different than the
1284f22ef01cSRoman Divacky       // pointer the block was first analyzed with.
12853ca95b02SDimitry Andric       std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
12863ca95b02SDimitry Andric           Visited.insert(std::make_pair(Pred, PredPtrVal));
1287f22ef01cSRoman Divacky 
1288f22ef01cSRoman Divacky       if (!InsertRes.second) {
1289bd5abe19SDimitry Andric         // We found the pred; take it off the list of preds to visit.
1290bd5abe19SDimitry Andric         PredList.pop_back();
1291bd5abe19SDimitry Andric 
1292f22ef01cSRoman Divacky         // If the predecessor was visited with PredPtr, then we already did
1293f22ef01cSRoman Divacky         // the analysis and can ignore it.
1294f22ef01cSRoman Divacky         if (InsertRes.first->second == PredPtrVal)
1295f22ef01cSRoman Divacky           continue;
1296f22ef01cSRoman Divacky 
1297f22ef01cSRoman Divacky         // Otherwise, the block was previously analyzed with a different
1298f22ef01cSRoman Divacky         // pointer.  We can't represent the result of this case, so we just
1299f22ef01cSRoman Divacky         // treat this as a phi translation failure.
1300bd5abe19SDimitry Andric 
1301bd5abe19SDimitry Andric         // Make sure to clean up the Visited map before continuing on to
1302bd5abe19SDimitry Andric         // PredTranslationFailure.
1303139f7f9bSDimitry Andric         for (unsigned i = 0, n = PredList.size(); i < n; ++i)
1304bd5abe19SDimitry Andric           Visited.erase(PredList[i].first);
1305bd5abe19SDimitry Andric 
1306f22ef01cSRoman Divacky         goto PredTranslationFailure;
1307f22ef01cSRoman Divacky       }
1308bd5abe19SDimitry Andric     }
1309f22ef01cSRoman Divacky 
1310bd5abe19SDimitry Andric     // Actually process results here; this need to be a separate loop to avoid
1311bd5abe19SDimitry Andric     // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1312bd5abe19SDimitry Andric     // any results for.  (getNonLocalPointerDepFromBB will modify our
1313bd5abe19SDimitry Andric     // datastructures in ways the code after the PredTranslationFailure label
1314bd5abe19SDimitry Andric     // doesn't expect.)
1315139f7f9bSDimitry Andric     for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
1316bd5abe19SDimitry Andric       BasicBlock *Pred = PredList[i].first;
1317bd5abe19SDimitry Andric       PHITransAddr &PredPointer = PredList[i].second;
1318bd5abe19SDimitry Andric       Value *PredPtrVal = PredPointer.getAddr();
1319bd5abe19SDimitry Andric 
1320bd5abe19SDimitry Andric       bool CanTranslate = true;
1321f22ef01cSRoman Divacky       // If PHI translation was unable to find an available pointer in this
1322f22ef01cSRoman Divacky       // predecessor, then we have to assume that the pointer is clobbered in
1323f22ef01cSRoman Divacky       // that predecessor.  We can still do PRE of the load, which would insert
1324f22ef01cSRoman Divacky       // a computation of the pointer in this predecessor.
132591bc56edSDimitry Andric       if (!PredPtrVal)
1326bd5abe19SDimitry Andric         CanTranslate = false;
1327bd5abe19SDimitry Andric 
1328bd5abe19SDimitry Andric       // FIXME: it is entirely possible that PHI translating will end up with
1329bd5abe19SDimitry Andric       // the same value.  Consider PHI translating something like:
1330bd5abe19SDimitry Andric       // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
1331bd5abe19SDimitry Andric       // to recurse here, pedantically speaking.
1332bd5abe19SDimitry Andric 
1333bd5abe19SDimitry Andric       // If getNonLocalPointerDepFromBB fails here, that means the cached
1334bd5abe19SDimitry Andric       // result conflicted with the Visited list; we have to conservatively
133517a519f9SDimitry Andric       // assume it is unknown, but this also does not block PRE of the load.
1336bd5abe19SDimitry Andric       if (!CanTranslate ||
13373ca95b02SDimitry Andric           !getNonLocalPointerDepFromBB(QueryInst, PredPointer,
13383ca95b02SDimitry Andric                                       Loc.getWithNewPtr(PredPtrVal), isLoad,
13393ca95b02SDimitry Andric                                       Pred, Result, Visited)) {
1340f22ef01cSRoman Divacky         // Add the entry to the Result list.
134117a519f9SDimitry Andric         NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
1342f22ef01cSRoman Divacky         Result.push_back(Entry);
1343f22ef01cSRoman Divacky 
1344f22ef01cSRoman Divacky         // Since we had a phi translation failure, the cache for CacheKey won't
1345f22ef01cSRoman Divacky         // include all of the entries that we need to immediately satisfy future
1346f22ef01cSRoman Divacky         // queries.  Mark this in NonLocalPointerDeps by setting the
1347f22ef01cSRoman Divacky         // BBSkipFirstBlockPair pointer to null.  This requires reuse of the
1348f22ef01cSRoman Divacky         // cached value to do more work but not miss the phi trans failure.
13492754fe60SDimitry Andric         NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
13502754fe60SDimitry Andric         NLPI.Pair = BBSkipFirstBlockPair();
1351f22ef01cSRoman Divacky         continue;
1352f22ef01cSRoman Divacky       }
1353f22ef01cSRoman Divacky     }
1354f22ef01cSRoman Divacky 
1355f22ef01cSRoman Divacky     // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1356f22ef01cSRoman Divacky     CacheInfo = &NonLocalPointerDeps[CacheKey];
13572754fe60SDimitry Andric     Cache = &CacheInfo->NonLocalDeps;
1358f22ef01cSRoman Divacky     NumSortedEntries = Cache->size();
1359f22ef01cSRoman Divacky 
1360f22ef01cSRoman Divacky     // Since we did phi translation, the "Cache" set won't contain all of the
1361f22ef01cSRoman Divacky     // results for the query.  This is ok (we can still use it to accelerate
1362f22ef01cSRoman Divacky     // specific block queries) but we can't do the fastpath "return all
1363f22ef01cSRoman Divacky     // results from the set"  Clear out the indicator for this.
13642754fe60SDimitry Andric     CacheInfo->Pair = BBSkipFirstBlockPair();
1365f22ef01cSRoman Divacky     SkipFirstBlock = false;
1366f22ef01cSRoman Divacky     continue;
1367f22ef01cSRoman Divacky 
1368f22ef01cSRoman Divacky   PredTranslationFailure:
1369bd5abe19SDimitry Andric     // The following code is "failure"; we can't produce a sane translation
1370bd5abe19SDimitry Andric     // for the given block.  It assumes that we haven't modified any of
1371bd5abe19SDimitry Andric     // our datastructures while processing the current block.
1372f22ef01cSRoman Divacky 
137391bc56edSDimitry Andric     if (!Cache) {
1374f22ef01cSRoman Divacky       // Refresh the CacheInfo/Cache pointer if it got invalidated.
1375f22ef01cSRoman Divacky       CacheInfo = &NonLocalPointerDeps[CacheKey];
13762754fe60SDimitry Andric       Cache = &CacheInfo->NonLocalDeps;
1377f22ef01cSRoman Divacky       NumSortedEntries = Cache->size();
1378f22ef01cSRoman Divacky     }
1379f22ef01cSRoman Divacky 
1380f22ef01cSRoman Divacky     // Since we failed phi translation, the "Cache" set won't contain all of the
1381f22ef01cSRoman Divacky     // results for the query.  This is ok (we can still use it to accelerate
1382f22ef01cSRoman Divacky     // specific block queries) but we can't do the fastpath "return all
1383f22ef01cSRoman Divacky     // results from the set".  Clear out the indicator for this.
13842754fe60SDimitry Andric     CacheInfo->Pair = BBSkipFirstBlockPair();
1385f22ef01cSRoman Divacky 
138617a519f9SDimitry Andric     // If *nothing* works, mark the pointer as unknown.
1387f22ef01cSRoman Divacky     //
1388f22ef01cSRoman Divacky     // If this is the magic first block, return this as a clobber of the whole
1389f22ef01cSRoman Divacky     // incoming value.  Since we can't phi translate to one of the predecessors,
1390f22ef01cSRoman Divacky     // we have to bail out.
1391f22ef01cSRoman Divacky     if (SkipFirstBlock)
13923ca95b02SDimitry Andric       return false;
1393f22ef01cSRoman Divacky 
13943ca95b02SDimitry Andric     bool foundBlock = false;
13953ca95b02SDimitry Andric     for (NonLocalDepEntry &I : llvm::reverse(*Cache)) {
13963ca95b02SDimitry Andric       if (I.getBB() != BB)
1397f22ef01cSRoman Divacky         continue;
1398f22ef01cSRoman Divacky 
13993ca95b02SDimitry Andric       assert((GotWorklistLimit || I.getResult().isNonLocal() ||
14003ca95b02SDimitry Andric               !DT.isReachableFromEntry(BB)) &&
1401f22ef01cSRoman Divacky              "Should only be here with transparent block");
14023ca95b02SDimitry Andric       foundBlock = true;
14033ca95b02SDimitry Andric       I.setResult(MemDepResult::getUnknown());
14043ca95b02SDimitry Andric       Result.push_back(
14053ca95b02SDimitry Andric           NonLocalDepResult(I.getBB(), I.getResult(), Pointer.getAddr()));
1406f22ef01cSRoman Divacky       break;
1407f22ef01cSRoman Divacky     }
14083ca95b02SDimitry Andric     (void)foundBlock; (void)GotWorklistLimit;
14093ca95b02SDimitry Andric     assert((foundBlock || GotWorklistLimit) && "Current block not in cache?");
1410f22ef01cSRoman Divacky   }
1411f22ef01cSRoman Divacky 
1412f22ef01cSRoman Divacky   // Okay, we're done now.  If we added new values to the cache, re-sort it.
1413f22ef01cSRoman Divacky   SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1414f22ef01cSRoman Divacky   DEBUG(AssertSorted(*Cache));
14153ca95b02SDimitry Andric   return true;
1416f22ef01cSRoman Divacky }
1417f22ef01cSRoman Divacky 
14183ca95b02SDimitry Andric /// If P exists in CachedNonLocalPointerInfo, remove it.
14193ca95b02SDimitry Andric void MemoryDependenceResults::RemoveCachedNonLocalPointerDependencies(
14203ca95b02SDimitry Andric     ValueIsLoadPair P) {
14213ca95b02SDimitry Andric   CachedNonLocalPointerInfo::iterator It = NonLocalPointerDeps.find(P);
14223ca95b02SDimitry Andric   if (It == NonLocalPointerDeps.end())
14233ca95b02SDimitry Andric     return;
1424f22ef01cSRoman Divacky 
1425f22ef01cSRoman Divacky   // Remove all of the entries in the BB->val map.  This involves removing
1426f22ef01cSRoman Divacky   // instructions from the reverse map.
14272754fe60SDimitry Andric   NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1428f22ef01cSRoman Divacky 
1429f22ef01cSRoman Divacky   for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1430f22ef01cSRoman Divacky     Instruction *Target = PInfo[i].getResult().getInst();
14313ca95b02SDimitry Andric     if (!Target)
14323ca95b02SDimitry Andric       continue; // Ignore non-local dep results.
1433f22ef01cSRoman Divacky     assert(Target->getParent() == PInfo[i].getBB());
1434f22ef01cSRoman Divacky 
1435f22ef01cSRoman Divacky     // Eliminating the dirty entry from 'Cache', so update the reverse info.
1436f22ef01cSRoman Divacky     RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1437f22ef01cSRoman Divacky   }
1438f22ef01cSRoman Divacky 
1439f22ef01cSRoman Divacky   // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1440f22ef01cSRoman Divacky   NonLocalPointerDeps.erase(It);
1441f22ef01cSRoman Divacky }
1442f22ef01cSRoman Divacky 
14433ca95b02SDimitry Andric void MemoryDependenceResults::invalidateCachedPointerInfo(Value *Ptr) {
1444f22ef01cSRoman Divacky   // If Ptr isn't really a pointer, just ignore it.
14453ca95b02SDimitry Andric   if (!Ptr->getType()->isPointerTy())
14463ca95b02SDimitry Andric     return;
1447f22ef01cSRoman Divacky   // Flush store info for the pointer.
1448f22ef01cSRoman Divacky   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1449f22ef01cSRoman Divacky   // Flush load info for the pointer.
1450f22ef01cSRoman Divacky   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1451f22ef01cSRoman Divacky }
1452f22ef01cSRoman Divacky 
14533ca95b02SDimitry Andric void MemoryDependenceResults::invalidateCachedPredecessors() {
1454ff0cc061SDimitry Andric   PredCache.clear();
1455f22ef01cSRoman Divacky }
1456f22ef01cSRoman Divacky 
14573ca95b02SDimitry Andric void MemoryDependenceResults::removeInstruction(Instruction *RemInst) {
1458f22ef01cSRoman Divacky   // Walk through the Non-local dependencies, removing this one as the value
1459f22ef01cSRoman Divacky   // for any cached queries.
1460f22ef01cSRoman Divacky   NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1461f22ef01cSRoman Divacky   if (NLDI != NonLocalDeps.end()) {
1462f22ef01cSRoman Divacky     NonLocalDepInfo &BlockMap = NLDI->second.first;
14633ca95b02SDimitry Andric     for (auto &Entry : BlockMap)
14643ca95b02SDimitry Andric       if (Instruction *Inst = Entry.getResult().getInst())
1465f22ef01cSRoman Divacky         RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1466f22ef01cSRoman Divacky     NonLocalDeps.erase(NLDI);
1467f22ef01cSRoman Divacky   }
1468f22ef01cSRoman Divacky 
1469f22ef01cSRoman Divacky   // If we have a cached local dependence query for this instruction, remove it.
1470f22ef01cSRoman Divacky   //
1471f22ef01cSRoman Divacky   LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1472f22ef01cSRoman Divacky   if (LocalDepEntry != LocalDeps.end()) {
1473f22ef01cSRoman Divacky     // Remove us from DepInst's reverse set now that the local dep info is gone.
1474f22ef01cSRoman Divacky     if (Instruction *Inst = LocalDepEntry->second.getInst())
1475f22ef01cSRoman Divacky       RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1476f22ef01cSRoman Divacky 
1477f22ef01cSRoman Divacky     // Remove this local dependency info.
1478f22ef01cSRoman Divacky     LocalDeps.erase(LocalDepEntry);
1479f22ef01cSRoman Divacky   }
1480f22ef01cSRoman Divacky 
1481f22ef01cSRoman Divacky   // If we have any cached pointer dependencies on this instruction, remove
1482f22ef01cSRoman Divacky   // them.  If the instruction has non-pointer type, then it can't be a pointer
1483f22ef01cSRoman Divacky   // base.
1484f22ef01cSRoman Divacky 
1485f22ef01cSRoman Divacky   // Remove it from both the load info and the store info.  The instruction
1486f22ef01cSRoman Divacky   // can't be in either of these maps if it is non-pointer.
1487f22ef01cSRoman Divacky   if (RemInst->getType()->isPointerTy()) {
1488f22ef01cSRoman Divacky     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1489f22ef01cSRoman Divacky     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1490f22ef01cSRoman Divacky   }
1491f22ef01cSRoman Divacky 
1492f22ef01cSRoman Divacky   // Loop over all of the things that depend on the instruction we're removing.
1493f22ef01cSRoman Divacky   //
1494f22ef01cSRoman Divacky   SmallVector<std::pair<Instruction *, Instruction *>, 8> ReverseDepsToAdd;
1495f22ef01cSRoman Divacky 
1496f22ef01cSRoman Divacky   // If we find RemInst as a clobber or Def in any of the maps for other values,
1497f22ef01cSRoman Divacky   // we need to replace its entry with a dirty version of the instruction after
1498f22ef01cSRoman Divacky   // it.  If RemInst is a terminator, we use a null dirty value.
1499f22ef01cSRoman Divacky   //
1500f22ef01cSRoman Divacky   // Using a dirty version of the instruction after RemInst saves having to scan
1501f22ef01cSRoman Divacky   // the entire block to get to this point.
1502f22ef01cSRoman Divacky   MemDepResult NewDirtyVal;
1503f22ef01cSRoman Divacky   if (!RemInst->isTerminator())
15047d523365SDimitry Andric     NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator());
1505f22ef01cSRoman Divacky 
1506f22ef01cSRoman Divacky   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1507f22ef01cSRoman Divacky   if (ReverseDepIt != ReverseLocalDeps.end()) {
1508f22ef01cSRoman Divacky     // RemInst can't be the terminator if it has local stuff depending on it.
150939d628a0SDimitry Andric     assert(!ReverseDepIt->second.empty() && !isa<TerminatorInst>(RemInst) &&
1510f22ef01cSRoman Divacky            "Nothing can locally depend on a terminator");
1511f22ef01cSRoman Divacky 
151239d628a0SDimitry Andric     for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
1513f22ef01cSRoman Divacky       assert(InstDependingOnRemInst != RemInst &&
1514f22ef01cSRoman Divacky              "Already removed our local dep info");
1515f22ef01cSRoman Divacky 
1516f22ef01cSRoman Divacky       LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1517f22ef01cSRoman Divacky 
1518f22ef01cSRoman Divacky       // Make sure to remember that new things depend on NewDepInst.
15193ca95b02SDimitry Andric       assert(NewDirtyVal.getInst() &&
15203ca95b02SDimitry Andric              "There is no way something else can have "
1521f22ef01cSRoman Divacky              "a local dep on this if it is a terminator!");
15223ca95b02SDimitry Andric       ReverseDepsToAdd.push_back(
15233ca95b02SDimitry Andric           std::make_pair(NewDirtyVal.getInst(), InstDependingOnRemInst));
1524f22ef01cSRoman Divacky     }
1525f22ef01cSRoman Divacky 
1526f22ef01cSRoman Divacky     ReverseLocalDeps.erase(ReverseDepIt);
1527f22ef01cSRoman Divacky 
1528f22ef01cSRoman Divacky     // Add new reverse deps after scanning the set, to avoid invalidating the
1529f22ef01cSRoman Divacky     // 'ReverseDeps' reference.
1530f22ef01cSRoman Divacky     while (!ReverseDepsToAdd.empty()) {
15313ca95b02SDimitry Andric       ReverseLocalDeps[ReverseDepsToAdd.back().first].insert(
15323ca95b02SDimitry Andric           ReverseDepsToAdd.back().second);
1533f22ef01cSRoman Divacky       ReverseDepsToAdd.pop_back();
1534f22ef01cSRoman Divacky     }
1535f22ef01cSRoman Divacky   }
1536f22ef01cSRoman Divacky 
1537f22ef01cSRoman Divacky   ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1538f22ef01cSRoman Divacky   if (ReverseDepIt != ReverseNonLocalDeps.end()) {
153939d628a0SDimitry Andric     for (Instruction *I : ReverseDepIt->second) {
154039d628a0SDimitry Andric       assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
1541f22ef01cSRoman Divacky 
154239d628a0SDimitry Andric       PerInstNLInfo &INLD = NonLocalDeps[I];
1543f22ef01cSRoman Divacky       // The information is now dirty!
1544f22ef01cSRoman Divacky       INLD.second = true;
1545f22ef01cSRoman Divacky 
15463ca95b02SDimitry Andric       for (auto &Entry : INLD.first) {
15473ca95b02SDimitry Andric         if (Entry.getResult().getInst() != RemInst)
15483ca95b02SDimitry Andric           continue;
1549f22ef01cSRoman Divacky 
1550f22ef01cSRoman Divacky         // Convert to a dirty entry for the subsequent instruction.
15513ca95b02SDimitry Andric         Entry.setResult(NewDirtyVal);
1552f22ef01cSRoman Divacky 
1553f22ef01cSRoman Divacky         if (Instruction *NextI = NewDirtyVal.getInst())
155439d628a0SDimitry Andric           ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
1555f22ef01cSRoman Divacky       }
1556f22ef01cSRoman Divacky     }
1557f22ef01cSRoman Divacky 
1558f22ef01cSRoman Divacky     ReverseNonLocalDeps.erase(ReverseDepIt);
1559f22ef01cSRoman Divacky 
1560f22ef01cSRoman Divacky     // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1561f22ef01cSRoman Divacky     while (!ReverseDepsToAdd.empty()) {
15623ca95b02SDimitry Andric       ReverseNonLocalDeps[ReverseDepsToAdd.back().first].insert(
15633ca95b02SDimitry Andric           ReverseDepsToAdd.back().second);
1564f22ef01cSRoman Divacky       ReverseDepsToAdd.pop_back();
1565f22ef01cSRoman Divacky     }
1566f22ef01cSRoman Divacky   }
1567f22ef01cSRoman Divacky 
1568f22ef01cSRoman Divacky   // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1569f22ef01cSRoman Divacky   // value in the NonLocalPointerDeps info.
1570f22ef01cSRoman Divacky   ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1571f22ef01cSRoman Divacky       ReverseNonLocalPtrDeps.find(RemInst);
1572f22ef01cSRoman Divacky   if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
15733ca95b02SDimitry Andric     SmallVector<std::pair<Instruction *, ValueIsLoadPair>, 8>
15743ca95b02SDimitry Andric         ReversePtrDepsToAdd;
1575f22ef01cSRoman Divacky 
157639d628a0SDimitry Andric     for (ValueIsLoadPair P : ReversePtrDepIt->second) {
1577f22ef01cSRoman Divacky       assert(P.getPointer() != RemInst &&
1578f22ef01cSRoman Divacky              "Already removed NonLocalPointerDeps info for RemInst");
1579f22ef01cSRoman Divacky 
15802754fe60SDimitry Andric       NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1581f22ef01cSRoman Divacky 
1582f22ef01cSRoman Divacky       // The cache is not valid for any specific block anymore.
15832754fe60SDimitry Andric       NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1584f22ef01cSRoman Divacky 
1585f22ef01cSRoman Divacky       // Update any entries for RemInst to use the instruction after it.
15863ca95b02SDimitry Andric       for (auto &Entry : NLPDI) {
15873ca95b02SDimitry Andric         if (Entry.getResult().getInst() != RemInst)
15883ca95b02SDimitry Andric           continue;
1589f22ef01cSRoman Divacky 
1590f22ef01cSRoman Divacky         // Convert to a dirty entry for the subsequent instruction.
15913ca95b02SDimitry Andric         Entry.setResult(NewDirtyVal);
1592f22ef01cSRoman Divacky 
1593f22ef01cSRoman Divacky         if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1594f22ef01cSRoman Divacky           ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1595f22ef01cSRoman Divacky       }
1596f22ef01cSRoman Divacky 
1597f22ef01cSRoman Divacky       // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
1598f22ef01cSRoman Divacky       // subsequent value may invalidate the sortedness.
1599f22ef01cSRoman Divacky       std::sort(NLPDI.begin(), NLPDI.end());
1600f22ef01cSRoman Divacky     }
1601f22ef01cSRoman Divacky 
1602f22ef01cSRoman Divacky     ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1603f22ef01cSRoman Divacky 
1604f22ef01cSRoman Divacky     while (!ReversePtrDepsToAdd.empty()) {
16053ca95b02SDimitry Andric       ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first].insert(
16063ca95b02SDimitry Andric           ReversePtrDepsToAdd.back().second);
1607f22ef01cSRoman Divacky       ReversePtrDepsToAdd.pop_back();
1608f22ef01cSRoman Divacky     }
1609f22ef01cSRoman Divacky   }
1610f22ef01cSRoman Divacky 
1611f22ef01cSRoman Divacky   assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1612f22ef01cSRoman Divacky   DEBUG(verifyRemoved(RemInst));
1613f22ef01cSRoman Divacky }
16143ca95b02SDimitry Andric 
16153ca95b02SDimitry Andric /// Verify that the specified instruction does not occur in our internal data
16163ca95b02SDimitry Andric /// structures.
16173ca95b02SDimitry Andric ///
16183ca95b02SDimitry Andric /// This function verifies by asserting in debug builds.
16193ca95b02SDimitry Andric void MemoryDependenceResults::verifyRemoved(Instruction *D) const {
162039d628a0SDimitry Andric #ifndef NDEBUG
16213ca95b02SDimitry Andric   for (const auto &DepKV : LocalDeps) {
16223ca95b02SDimitry Andric     assert(DepKV.first != D && "Inst occurs in data structures");
16233ca95b02SDimitry Andric     assert(DepKV.second.getInst() != D && "Inst occurs in data structures");
16243ca95b02SDimitry Andric   }
16253ca95b02SDimitry Andric 
16263ca95b02SDimitry Andric   for (const auto &DepKV : NonLocalPointerDeps) {
16273ca95b02SDimitry Andric     assert(DepKV.first.getPointer() != D && "Inst occurs in NLPD map key");
16283ca95b02SDimitry Andric     for (const auto &Entry : DepKV.second.NonLocalDeps)
16293ca95b02SDimitry Andric       assert(Entry.getResult().getInst() != D && "Inst occurs as NLPD value");
16303ca95b02SDimitry Andric   }
16313ca95b02SDimitry Andric 
16323ca95b02SDimitry Andric   for (const auto &DepKV : NonLocalDeps) {
16333ca95b02SDimitry Andric     assert(DepKV.first != D && "Inst occurs in data structures");
16343ca95b02SDimitry Andric     const PerInstNLInfo &INLD = DepKV.second;
16353ca95b02SDimitry Andric     for (const auto &Entry : INLD.first)
16363ca95b02SDimitry Andric       assert(Entry.getResult().getInst() != D &&
1637f22ef01cSRoman Divacky              "Inst occurs in data structures");
1638f22ef01cSRoman Divacky   }
1639f22ef01cSRoman Divacky 
16403ca95b02SDimitry Andric   for (const auto &DepKV : ReverseLocalDeps) {
16413ca95b02SDimitry Andric     assert(DepKV.first != D && "Inst occurs in data structures");
16423ca95b02SDimitry Andric     for (Instruction *Inst : DepKV.second)
164339d628a0SDimitry Andric       assert(Inst != D && "Inst occurs in data structures");
1644f22ef01cSRoman Divacky   }
1645f22ef01cSRoman Divacky 
16463ca95b02SDimitry Andric   for (const auto &DepKV : ReverseNonLocalDeps) {
16473ca95b02SDimitry Andric     assert(DepKV.first != D && "Inst occurs in data structures");
16483ca95b02SDimitry Andric     for (Instruction *Inst : DepKV.second)
164939d628a0SDimitry Andric       assert(Inst != D && "Inst occurs in data structures");
1650f22ef01cSRoman Divacky   }
1651f22ef01cSRoman Divacky 
16523ca95b02SDimitry Andric   for (const auto &DepKV : ReverseNonLocalPtrDeps) {
16533ca95b02SDimitry Andric     assert(DepKV.first != D && "Inst occurs in rev NLPD map");
1654f22ef01cSRoman Divacky 
16553ca95b02SDimitry Andric     for (ValueIsLoadPair P : DepKV.second)
16563ca95b02SDimitry Andric       assert(P != ValueIsLoadPair(D, false) && P != ValueIsLoadPair(D, true) &&
1657f22ef01cSRoman Divacky              "Inst occurs in ReverseNonLocalPtrDeps map");
1658f22ef01cSRoman Divacky   }
165939d628a0SDimitry Andric #endif
1660f22ef01cSRoman Divacky }
16613ca95b02SDimitry Andric 
16623ca95b02SDimitry Andric char MemoryDependenceAnalysis::PassID;
16633ca95b02SDimitry Andric 
16643ca95b02SDimitry Andric MemoryDependenceResults
16653ca95b02SDimitry Andric MemoryDependenceAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
16663ca95b02SDimitry Andric   auto &AA = AM.getResult<AAManager>(F);
16673ca95b02SDimitry Andric   auto &AC = AM.getResult<AssumptionAnalysis>(F);
16683ca95b02SDimitry Andric   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
16693ca95b02SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
16703ca95b02SDimitry Andric   return MemoryDependenceResults(AA, AC, TLI, DT);
16713ca95b02SDimitry Andric }
16723ca95b02SDimitry Andric 
16733ca95b02SDimitry Andric char MemoryDependenceWrapperPass::ID = 0;
16743ca95b02SDimitry Andric 
16753ca95b02SDimitry Andric INITIALIZE_PASS_BEGIN(MemoryDependenceWrapperPass, "memdep",
16763ca95b02SDimitry Andric                       "Memory Dependence Analysis", false, true)
16773ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
16783ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
16793ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
16803ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
16813ca95b02SDimitry Andric INITIALIZE_PASS_END(MemoryDependenceWrapperPass, "memdep",
16823ca95b02SDimitry Andric                     "Memory Dependence Analysis", false, true)
16833ca95b02SDimitry Andric 
16843ca95b02SDimitry Andric MemoryDependenceWrapperPass::MemoryDependenceWrapperPass() : FunctionPass(ID) {
16853ca95b02SDimitry Andric   initializeMemoryDependenceWrapperPassPass(*PassRegistry::getPassRegistry());
16863ca95b02SDimitry Andric }
16873ca95b02SDimitry Andric MemoryDependenceWrapperPass::~MemoryDependenceWrapperPass() {}
16883ca95b02SDimitry Andric 
16893ca95b02SDimitry Andric void MemoryDependenceWrapperPass::releaseMemory() {
16903ca95b02SDimitry Andric   MemDep.reset();
16913ca95b02SDimitry Andric }
16923ca95b02SDimitry Andric 
16933ca95b02SDimitry Andric void MemoryDependenceWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
16943ca95b02SDimitry Andric   AU.setPreservesAll();
16953ca95b02SDimitry Andric   AU.addRequired<AssumptionCacheTracker>();
16963ca95b02SDimitry Andric   AU.addRequired<DominatorTreeWrapperPass>();
16973ca95b02SDimitry Andric   AU.addRequiredTransitive<AAResultsWrapperPass>();
16983ca95b02SDimitry Andric   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
16993ca95b02SDimitry Andric }
17003ca95b02SDimitry Andric 
17013ca95b02SDimitry Andric bool MemoryDependenceWrapperPass::runOnFunction(Function &F) {
17023ca95b02SDimitry Andric   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
17033ca95b02SDimitry Andric   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
17043ca95b02SDimitry Andric   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
17053ca95b02SDimitry Andric   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
17063ca95b02SDimitry Andric   MemDep.emplace(AA, AC, TLI, DT);
17073ca95b02SDimitry Andric   return false;
17083ca95b02SDimitry Andric }
1709