1 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements an analysis that determines, for a given memory
11 // operation, what preceding memory operations it depends on.  It builds on
12 // alias analysis information, and tries to provide a lazy, caching interface to
13 // a common kind of alias information query.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/AssumptionCache.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Analysis/MemoryLocation.h"
27 #include "llvm/Analysis/OrderedBasicBlock.h"
28 #include "llvm/Analysis/PHITransAddr.h"
29 #include "llvm/Analysis/PhiValues.h"
30 #include "llvm/Analysis/TargetLibraryInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/IR/Attributes.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/InstrTypes.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/IntrinsicInst.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Metadata.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/IR/PredIteratorCache.h"
48 #include "llvm/IR/Type.h"
49 #include "llvm/IR/Use.h"
50 #include "llvm/IR/User.h"
51 #include "llvm/IR/Value.h"
52 #include "llvm/Pass.h"
53 #include "llvm/Support/AtomicOrdering.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/MathExtras.h"
59 #include <algorithm>
60 #include <cassert>
61 #include <cstdint>
62 #include <iterator>
63 #include <utility>
64 
65 using namespace llvm;
66 
67 #define DEBUG_TYPE "memdep"
68 
69 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
70 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
71 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
72 
73 STATISTIC(NumCacheNonLocalPtr,
74           "Number of fully cached non-local ptr responses");
75 STATISTIC(NumCacheDirtyNonLocalPtr,
76           "Number of cached, but dirty, non-local ptr responses");
77 STATISTIC(NumUncacheNonLocalPtr, "Number of uncached non-local ptr responses");
78 STATISTIC(NumCacheCompleteNonLocalPtr,
79           "Number of block queries that were completely cached");
80 
81 // Limit for the number of instructions to scan in a block.
82 
83 static cl::opt<unsigned> BlockScanLimit(
84     "memdep-block-scan-limit", cl::Hidden, cl::init(100),
85     cl::desc("The number of instructions to scan in a block in memory "
86              "dependency analysis (default = 100)"));
87 
88 static cl::opt<unsigned>
89     BlockNumberLimit("memdep-block-number-limit", cl::Hidden, cl::init(1000),
90                      cl::desc("The number of blocks to scan during memory "
91                               "dependency analysis (default = 1000)"));
92 
93 // Limit on the number of memdep results to process.
94 static const unsigned int NumResultsLimit = 100;
95 
96 /// This is a helper function that removes Val from 'Inst's set in ReverseMap.
97 ///
98 /// If the set becomes empty, remove Inst's entry.
99 template <typename KeyTy>
100 static void
101 RemoveFromReverseMap(DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>> &ReverseMap,
102                      Instruction *Inst, KeyTy Val) {
103   typename DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>>::iterator InstIt =
104       ReverseMap.find(Inst);
105   assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
106   bool Found = InstIt->second.erase(Val);
107   assert(Found && "Invalid reverse map!");
108   (void)Found;
109   if (InstIt->second.empty())
110     ReverseMap.erase(InstIt);
111 }
112 
113 /// If the given instruction references a specific memory location, fill in Loc
114 /// with the details, otherwise set Loc.Ptr to null.
115 ///
116 /// Returns a ModRefInfo value describing the general behavior of the
117 /// instruction.
118 static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc,
119                               const TargetLibraryInfo &TLI) {
120   if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
121     if (LI->isUnordered()) {
122       Loc = MemoryLocation::get(LI);
123       return ModRefInfo::Ref;
124     }
125     if (LI->getOrdering() == AtomicOrdering::Monotonic) {
126       Loc = MemoryLocation::get(LI);
127       return ModRefInfo::ModRef;
128     }
129     Loc = MemoryLocation();
130     return ModRefInfo::ModRef;
131   }
132 
133   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
134     if (SI->isUnordered()) {
135       Loc = MemoryLocation::get(SI);
136       return ModRefInfo::Mod;
137     }
138     if (SI->getOrdering() == AtomicOrdering::Monotonic) {
139       Loc = MemoryLocation::get(SI);
140       return ModRefInfo::ModRef;
141     }
142     Loc = MemoryLocation();
143     return ModRefInfo::ModRef;
144   }
145 
146   if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
147     Loc = MemoryLocation::get(V);
148     return ModRefInfo::ModRef;
149   }
150 
151   if (const CallInst *CI = isFreeCall(Inst, &TLI)) {
152     // calls to free() deallocate the entire structure
153     Loc = MemoryLocation(CI->getArgOperand(0));
154     return ModRefInfo::Mod;
155   }
156 
157   if (const MemSetInst *MI = dyn_cast<MemSetInst>(Inst)) {
158     Loc = MemoryLocation::getForDest(MI);
159     // Conversatively assume ModRef for volatile memset.
160     return MI->isVolatile() ? ModRefInfo::ModRef : ModRefInfo::Mod;
161   }
162 
163   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
164     switch (II->getIntrinsicID()) {
165     case Intrinsic::lifetime_start:
166     case Intrinsic::lifetime_end:
167     case Intrinsic::invariant_start:
168       Loc = MemoryLocation::getForArgument(II, 1, TLI);
169       // These intrinsics don't really modify the memory, but returning Mod
170       // will allow them to be handled conservatively.
171       return ModRefInfo::Mod;
172     case Intrinsic::invariant_end:
173       Loc = MemoryLocation::getForArgument(II, 2, TLI);
174       // These intrinsics don't really modify the memory, but returning Mod
175       // will allow them to be handled conservatively.
176       return ModRefInfo::Mod;
177     default:
178       break;
179     }
180   }
181 
182   // Otherwise, just do the coarse-grained thing that always works.
183   if (Inst->mayWriteToMemory())
184     return ModRefInfo::ModRef;
185   if (Inst->mayReadFromMemory())
186     return ModRefInfo::Ref;
187   return ModRefInfo::NoModRef;
188 }
189 
190 /// Private helper for finding the local dependencies of a call site.
191 MemDepResult MemoryDependenceResults::getCallSiteDependencyFrom(
192     CallSite CS, bool isReadOnlyCall, BasicBlock::iterator ScanIt,
193     BasicBlock *BB) {
194   unsigned Limit = BlockScanLimit;
195 
196   // Walk backwards through the block, looking for dependencies.
197   while (ScanIt != BB->begin()) {
198     Instruction *Inst = &*--ScanIt;
199     // Debug intrinsics don't cause dependences and should not affect Limit
200     if (isa<DbgInfoIntrinsic>(Inst))
201       continue;
202 
203     // Limit the amount of scanning we do so we don't end up with quadratic
204     // running time on extreme testcases.
205     --Limit;
206     if (!Limit)
207       return MemDepResult::getUnknown();
208 
209     // If this inst is a memory op, get the pointer it accessed
210     MemoryLocation Loc;
211     ModRefInfo MR = GetLocation(Inst, Loc, TLI);
212     if (Loc.Ptr) {
213       // A simple instruction.
214       if (isModOrRefSet(AA.getModRefInfo(CS, Loc)))
215         return MemDepResult::getClobber(Inst);
216       continue;
217     }
218 
219     if (auto InstCS = CallSite(Inst)) {
220       // If these two calls do not interfere, look past it.
221       if (isNoModRef(AA.getModRefInfo(CS, InstCS))) {
222         // If the two calls are the same, return InstCS as a Def, so that
223         // CS can be found redundant and eliminated.
224         if (isReadOnlyCall && !isModSet(MR) &&
225             CS.getInstruction()->isIdenticalToWhenDefined(Inst))
226           return MemDepResult::getDef(Inst);
227 
228         // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
229         // keep scanning.
230         continue;
231       } else
232         return MemDepResult::getClobber(Inst);
233     }
234 
235     // If we could not obtain a pointer for the instruction and the instruction
236     // touches memory then assume that this is a dependency.
237     if (isModOrRefSet(MR))
238       return MemDepResult::getClobber(Inst);
239   }
240 
241   // No dependence found.  If this is the entry block of the function, it is
242   // unknown, otherwise it is non-local.
243   if (BB != &BB->getParent()->getEntryBlock())
244     return MemDepResult::getNonLocal();
245   return MemDepResult::getNonFuncLocal();
246 }
247 
248 unsigned MemoryDependenceResults::getLoadLoadClobberFullWidthSize(
249     const Value *MemLocBase, int64_t MemLocOffs, unsigned MemLocSize,
250     const LoadInst *LI) {
251   // We can only extend simple integer loads.
252   if (!isa<IntegerType>(LI->getType()) || !LI->isSimple())
253     return 0;
254 
255   // Load widening is hostile to ThreadSanitizer: it may cause false positives
256   // or make the reports more cryptic (access sizes are wrong).
257   if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
258     return 0;
259 
260   const DataLayout &DL = LI->getModule()->getDataLayout();
261 
262   // Get the base of this load.
263   int64_t LIOffs = 0;
264   const Value *LIBase =
265       GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, DL);
266 
267   // If the two pointers are not based on the same pointer, we can't tell that
268   // they are related.
269   if (LIBase != MemLocBase)
270     return 0;
271 
272   // Okay, the two values are based on the same pointer, but returned as
273   // no-alias.  This happens when we have things like two byte loads at "P+1"
274   // and "P+3".  Check to see if increasing the size of the "LI" load up to its
275   // alignment (or the largest native integer type) will allow us to load all
276   // the bits required by MemLoc.
277 
278   // If MemLoc is before LI, then no widening of LI will help us out.
279   if (MemLocOffs < LIOffs)
280     return 0;
281 
282   // Get the alignment of the load in bytes.  We assume that it is safe to load
283   // any legal integer up to this size without a problem.  For example, if we're
284   // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
285   // widen it up to an i32 load.  If it is known 2-byte aligned, we can widen it
286   // to i16.
287   unsigned LoadAlign = LI->getAlignment();
288 
289   int64_t MemLocEnd = MemLocOffs + MemLocSize;
290 
291   // If no amount of rounding up will let MemLoc fit into LI, then bail out.
292   if (LIOffs + LoadAlign < MemLocEnd)
293     return 0;
294 
295   // This is the size of the load to try.  Start with the next larger power of
296   // two.
297   unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits() / 8U;
298   NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
299 
300   while (true) {
301     // If this load size is bigger than our known alignment or would not fit
302     // into a native integer register, then we fail.
303     if (NewLoadByteSize > LoadAlign ||
304         !DL.fitsInLegalInteger(NewLoadByteSize * 8))
305       return 0;
306 
307     if (LIOffs + NewLoadByteSize > MemLocEnd &&
308         (LI->getParent()->getParent()->hasFnAttribute(
309              Attribute::SanitizeAddress) ||
310          LI->getParent()->getParent()->hasFnAttribute(
311              Attribute::SanitizeHWAddress)))
312       // We will be reading past the location accessed by the original program.
313       // While this is safe in a regular build, Address Safety analysis tools
314       // may start reporting false warnings. So, don't do widening.
315       return 0;
316 
317     // If a load of this width would include all of MemLoc, then we succeed.
318     if (LIOffs + NewLoadByteSize >= MemLocEnd)
319       return NewLoadByteSize;
320 
321     NewLoadByteSize <<= 1;
322   }
323 }
324 
325 static bool isVolatile(Instruction *Inst) {
326   if (auto *LI = dyn_cast<LoadInst>(Inst))
327     return LI->isVolatile();
328   if (auto *SI = dyn_cast<StoreInst>(Inst))
329     return SI->isVolatile();
330   if (auto *AI = dyn_cast<AtomicCmpXchgInst>(Inst))
331     return AI->isVolatile();
332   return false;
333 }
334 
335 MemDepResult MemoryDependenceResults::getPointerDependencyFrom(
336     const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
337     BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) {
338   MemDepResult InvariantGroupDependency = MemDepResult::getUnknown();
339   if (QueryInst != nullptr) {
340     if (auto *LI = dyn_cast<LoadInst>(QueryInst)) {
341       InvariantGroupDependency = getInvariantGroupPointerDependency(LI, BB);
342 
343       if (InvariantGroupDependency.isDef())
344         return InvariantGroupDependency;
345     }
346   }
347   MemDepResult SimpleDep = getSimplePointerDependencyFrom(
348       MemLoc, isLoad, ScanIt, BB, QueryInst, Limit);
349   if (SimpleDep.isDef())
350     return SimpleDep;
351   // Non-local invariant group dependency indicates there is non local Def
352   // (it only returns nonLocal if it finds nonLocal def), which is better than
353   // local clobber and everything else.
354   if (InvariantGroupDependency.isNonLocal())
355     return InvariantGroupDependency;
356 
357   assert(InvariantGroupDependency.isUnknown() &&
358          "InvariantGroupDependency should be only unknown at this point");
359   return SimpleDep;
360 }
361 
362 MemDepResult
363 MemoryDependenceResults::getInvariantGroupPointerDependency(LoadInst *LI,
364                                                             BasicBlock *BB) {
365 
366   if (!LI->getMetadata(LLVMContext::MD_invariant_group))
367     return MemDepResult::getUnknown();
368 
369   // Take the ptr operand after all casts and geps 0. This way we can search
370   // cast graph down only.
371   Value *LoadOperand = LI->getPointerOperand()->stripPointerCasts();
372 
373   // It's is not safe to walk the use list of global value, because function
374   // passes aren't allowed to look outside their functions.
375   // FIXME: this could be fixed by filtering instructions from outside
376   // of current function.
377   if (isa<GlobalValue>(LoadOperand))
378     return MemDepResult::getUnknown();
379 
380   // Queue to process all pointers that are equivalent to load operand.
381   SmallVector<const Value *, 8> LoadOperandsQueue;
382   LoadOperandsQueue.push_back(LoadOperand);
383 
384   Instruction *ClosestDependency = nullptr;
385   // Order of instructions in uses list is unpredictible. In order to always
386   // get the same result, we will look for the closest dominance.
387   auto GetClosestDependency = [this](Instruction *Best, Instruction *Other) {
388     assert(Other && "Must call it with not null instruction");
389     if (Best == nullptr || DT.dominates(Best, Other))
390       return Other;
391     return Best;
392   };
393 
394   // FIXME: This loop is O(N^2) because dominates can be O(n) and in worst case
395   // we will see all the instructions. This should be fixed in MSSA.
396   while (!LoadOperandsQueue.empty()) {
397     const Value *Ptr = LoadOperandsQueue.pop_back_val();
398     assert(Ptr && !isa<GlobalValue>(Ptr) &&
399            "Null or GlobalValue should not be inserted");
400 
401     for (const Use &Us : Ptr->uses()) {
402       auto *U = dyn_cast<Instruction>(Us.getUser());
403       if (!U || U == LI || !DT.dominates(U, LI))
404         continue;
405 
406       // Bitcast or gep with zeros are using Ptr. Add to queue to check it's
407       // users.      U = bitcast Ptr
408       if (isa<BitCastInst>(U)) {
409         LoadOperandsQueue.push_back(U);
410         continue;
411       }
412       // Gep with zeros is equivalent to bitcast.
413       // FIXME: we are not sure if some bitcast should be canonicalized to gep 0
414       // or gep 0 to bitcast because of SROA, so there are 2 forms. When
415       // typeless pointers will be ready then both cases will be gone
416       // (and this BFS also won't be needed).
417       if (auto *GEP = dyn_cast<GetElementPtrInst>(U))
418         if (GEP->hasAllZeroIndices()) {
419           LoadOperandsQueue.push_back(U);
420           continue;
421         }
422 
423       // If we hit load/store with the same invariant.group metadata (and the
424       // same pointer operand) we can assume that value pointed by pointer
425       // operand didn't change.
426       if ((isa<LoadInst>(U) || isa<StoreInst>(U)) &&
427           U->getMetadata(LLVMContext::MD_invariant_group) != nullptr)
428         ClosestDependency = GetClosestDependency(ClosestDependency, U);
429     }
430   }
431 
432   if (!ClosestDependency)
433     return MemDepResult::getUnknown();
434   if (ClosestDependency->getParent() == BB)
435     return MemDepResult::getDef(ClosestDependency);
436   // Def(U) can't be returned here because it is non-local. If local
437   // dependency won't be found then return nonLocal counting that the
438   // user will call getNonLocalPointerDependency, which will return cached
439   // result.
440   NonLocalDefsCache.try_emplace(
441       LI, NonLocalDepResult(ClosestDependency->getParent(),
442                             MemDepResult::getDef(ClosestDependency), nullptr));
443   ReverseNonLocalDefsCache[ClosestDependency].insert(LI);
444   return MemDepResult::getNonLocal();
445 }
446 
447 MemDepResult MemoryDependenceResults::getSimplePointerDependencyFrom(
448     const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
449     BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) {
450   bool isInvariantLoad = false;
451 
452   if (!Limit) {
453     unsigned DefaultLimit = BlockScanLimit;
454     return getSimplePointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst,
455                                           &DefaultLimit);
456   }
457 
458   // We must be careful with atomic accesses, as they may allow another thread
459   //   to touch this location, clobbering it. We are conservative: if the
460   //   QueryInst is not a simple (non-atomic) memory access, we automatically
461   //   return getClobber.
462   // If it is simple, we know based on the results of
463   // "Compiler testing via a theory of sound optimisations in the C11/C++11
464   //   memory model" in PLDI 2013, that a non-atomic location can only be
465   //   clobbered between a pair of a release and an acquire action, with no
466   //   access to the location in between.
467   // Here is an example for giving the general intuition behind this rule.
468   // In the following code:
469   //   store x 0;
470   //   release action; [1]
471   //   acquire action; [4]
472   //   %val = load x;
473   // It is unsafe to replace %val by 0 because another thread may be running:
474   //   acquire action; [2]
475   //   store x 42;
476   //   release action; [3]
477   // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
478   // being 42. A key property of this program however is that if either
479   // 1 or 4 were missing, there would be a race between the store of 42
480   // either the store of 0 or the load (making the whole program racy).
481   // The paper mentioned above shows that the same property is respected
482   // by every program that can detect any optimization of that kind: either
483   // it is racy (undefined) or there is a release followed by an acquire
484   // between the pair of accesses under consideration.
485 
486   // If the load is invariant, we "know" that it doesn't alias *any* write. We
487   // do want to respect mustalias results since defs are useful for value
488   // forwarding, but any mayalias write can be assumed to be noalias.
489   // Arguably, this logic should be pushed inside AliasAnalysis itself.
490   if (isLoad && QueryInst) {
491     LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
492     if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr)
493       isInvariantLoad = true;
494   }
495 
496   const DataLayout &DL = BB->getModule()->getDataLayout();
497 
498   // Create a numbered basic block to lazily compute and cache instruction
499   // positions inside a BB. This is used to provide fast queries for relative
500   // position between two instructions in a BB and can be used by
501   // AliasAnalysis::callCapturesBefore.
502   OrderedBasicBlock OBB(BB);
503 
504   // Return "true" if and only if the instruction I is either a non-simple
505   // load or a non-simple store.
506   auto isNonSimpleLoadOrStore = [](Instruction *I) -> bool {
507     if (auto *LI = dyn_cast<LoadInst>(I))
508       return !LI->isSimple();
509     if (auto *SI = dyn_cast<StoreInst>(I))
510       return !SI->isSimple();
511     return false;
512   };
513 
514   // Return "true" if I is not a load and not a store, but it does access
515   // memory.
516   auto isOtherMemAccess = [](Instruction *I) -> bool {
517     return !isa<LoadInst>(I) && !isa<StoreInst>(I) && I->mayReadOrWriteMemory();
518   };
519 
520   // Walk backwards through the basic block, looking for dependencies.
521   while (ScanIt != BB->begin()) {
522     Instruction *Inst = &*--ScanIt;
523 
524     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
525       // Debug intrinsics don't (and can't) cause dependencies.
526       if (isa<DbgInfoIntrinsic>(II))
527         continue;
528 
529     // Limit the amount of scanning we do so we don't end up with quadratic
530     // running time on extreme testcases.
531     --*Limit;
532     if (!*Limit)
533       return MemDepResult::getUnknown();
534 
535     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
536       // If we reach a lifetime begin or end marker, then the query ends here
537       // because the value is undefined.
538       if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
539         // FIXME: This only considers queries directly on the invariant-tagged
540         // pointer, not on query pointers that are indexed off of them.  It'd
541         // be nice to handle that at some point (the right approach is to use
542         // GetPointerBaseWithConstantOffset).
543         if (AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), MemLoc))
544           return MemDepResult::getDef(II);
545         continue;
546       }
547     }
548 
549     // Values depend on loads if the pointers are must aliased.  This means
550     // that a load depends on another must aliased load from the same value.
551     // One exception is atomic loads: a value can depend on an atomic load that
552     // it does not alias with when this atomic load indicates that another
553     // thread may be accessing the location.
554     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
555       // While volatile access cannot be eliminated, they do not have to clobber
556       // non-aliasing locations, as normal accesses, for example, can be safely
557       // reordered with volatile accesses.
558       if (LI->isVolatile()) {
559         if (!QueryInst)
560           // Original QueryInst *may* be volatile
561           return MemDepResult::getClobber(LI);
562         if (isVolatile(QueryInst))
563           // Ordering required if QueryInst is itself volatile
564           return MemDepResult::getClobber(LI);
565         // Otherwise, volatile doesn't imply any special ordering
566       }
567 
568       // Atomic loads have complications involved.
569       // A Monotonic (or higher) load is OK if the query inst is itself not
570       // atomic.
571       // FIXME: This is overly conservative.
572       if (LI->isAtomic() && isStrongerThanUnordered(LI->getOrdering())) {
573         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
574             isOtherMemAccess(QueryInst))
575           return MemDepResult::getClobber(LI);
576         if (LI->getOrdering() != AtomicOrdering::Monotonic)
577           return MemDepResult::getClobber(LI);
578       }
579 
580       MemoryLocation LoadLoc = MemoryLocation::get(LI);
581 
582       // If we found a pointer, check if it could be the same as our pointer.
583       AliasResult R = AA.alias(LoadLoc, MemLoc);
584 
585       if (isLoad) {
586         if (R == NoAlias)
587           continue;
588 
589         // Must aliased loads are defs of each other.
590         if (R == MustAlias)
591           return MemDepResult::getDef(Inst);
592 
593 #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
594       // in terms of clobbering loads, but since it does this by looking
595       // at the clobbering load directly, it doesn't know about any
596       // phi translation that may have happened along the way.
597 
598         // If we have a partial alias, then return this as a clobber for the
599         // client to handle.
600         if (R == PartialAlias)
601           return MemDepResult::getClobber(Inst);
602 #endif
603 
604         // Random may-alias loads don't depend on each other without a
605         // dependence.
606         continue;
607       }
608 
609       // Stores don't depend on other no-aliased accesses.
610       if (R == NoAlias)
611         continue;
612 
613       // Stores don't alias loads from read-only memory.
614       if (AA.pointsToConstantMemory(LoadLoc))
615         continue;
616 
617       // Stores depend on may/must aliased loads.
618       return MemDepResult::getDef(Inst);
619     }
620 
621     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
622       // Atomic stores have complications involved.
623       // A Monotonic store is OK if the query inst is itself not atomic.
624       // FIXME: This is overly conservative.
625       if (!SI->isUnordered() && SI->isAtomic()) {
626         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
627             isOtherMemAccess(QueryInst))
628           return MemDepResult::getClobber(SI);
629         if (SI->getOrdering() != AtomicOrdering::Monotonic)
630           return MemDepResult::getClobber(SI);
631       }
632 
633       // FIXME: this is overly conservative.
634       // While volatile access cannot be eliminated, they do not have to clobber
635       // non-aliasing locations, as normal accesses can for example be reordered
636       // with volatile accesses.
637       if (SI->isVolatile())
638         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
639             isOtherMemAccess(QueryInst))
640           return MemDepResult::getClobber(SI);
641 
642       // If alias analysis can tell that this store is guaranteed to not modify
643       // the query pointer, ignore it.  Use getModRefInfo to handle cases where
644       // the query pointer points to constant memory etc.
645       if (!isModOrRefSet(AA.getModRefInfo(SI, MemLoc)))
646         continue;
647 
648       // Ok, this store might clobber the query pointer.  Check to see if it is
649       // a must alias: in this case, we want to return this as a def.
650       // FIXME: Use ModRefInfo::Must bit from getModRefInfo call above.
651       MemoryLocation StoreLoc = MemoryLocation::get(SI);
652 
653       // If we found a pointer, check if it could be the same as our pointer.
654       AliasResult R = AA.alias(StoreLoc, MemLoc);
655 
656       if (R == NoAlias)
657         continue;
658       if (R == MustAlias)
659         return MemDepResult::getDef(Inst);
660       if (isInvariantLoad)
661         continue;
662       return MemDepResult::getClobber(Inst);
663     }
664 
665     // If this is an allocation, and if we know that the accessed pointer is to
666     // the allocation, return Def.  This means that there is no dependence and
667     // the access can be optimized based on that.  For example, a load could
668     // turn into undef.  Note that we can bypass the allocation itself when
669     // looking for a clobber in many cases; that's an alias property and is
670     // handled by BasicAA.
671     if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, &TLI)) {
672       const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL);
673       if (AccessPtr == Inst || AA.isMustAlias(Inst, AccessPtr))
674         return MemDepResult::getDef(Inst);
675     }
676 
677     if (isInvariantLoad)
678       continue;
679 
680     // A release fence requires that all stores complete before it, but does
681     // not prevent the reordering of following loads or stores 'before' the
682     // fence.  As a result, we look past it when finding a dependency for
683     // loads.  DSE uses this to find preceeding stores to delete and thus we
684     // can't bypass the fence if the query instruction is a store.
685     if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
686       if (isLoad && FI->getOrdering() == AtomicOrdering::Release)
687         continue;
688 
689     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
690     ModRefInfo MR = AA.getModRefInfo(Inst, MemLoc);
691     // If necessary, perform additional analysis.
692     if (isModAndRefSet(MR))
693       MR = AA.callCapturesBefore(Inst, MemLoc, &DT, &OBB);
694     switch (clearMust(MR)) {
695     case ModRefInfo::NoModRef:
696       // If the call has no effect on the queried pointer, just ignore it.
697       continue;
698     case ModRefInfo::Mod:
699       return MemDepResult::getClobber(Inst);
700     case ModRefInfo::Ref:
701       // If the call is known to never store to the pointer, and if this is a
702       // load query, we can safely ignore it (scan past it).
703       if (isLoad)
704         continue;
705       LLVM_FALLTHROUGH;
706     default:
707       // Otherwise, there is a potential dependence.  Return a clobber.
708       return MemDepResult::getClobber(Inst);
709     }
710   }
711 
712   // No dependence found.  If this is the entry block of the function, it is
713   // unknown, otherwise it is non-local.
714   if (BB != &BB->getParent()->getEntryBlock())
715     return MemDepResult::getNonLocal();
716   return MemDepResult::getNonFuncLocal();
717 }
718 
719 MemDepResult MemoryDependenceResults::getDependency(Instruction *QueryInst) {
720   Instruction *ScanPos = QueryInst;
721 
722   // Check for a cached result
723   MemDepResult &LocalCache = LocalDeps[QueryInst];
724 
725   // If the cached entry is non-dirty, just return it.  Note that this depends
726   // on MemDepResult's default constructing to 'dirty'.
727   if (!LocalCache.isDirty())
728     return LocalCache;
729 
730   // Otherwise, if we have a dirty entry, we know we can start the scan at that
731   // instruction, which may save us some work.
732   if (Instruction *Inst = LocalCache.getInst()) {
733     ScanPos = Inst;
734 
735     RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
736   }
737 
738   BasicBlock *QueryParent = QueryInst->getParent();
739 
740   // Do the scan.
741   if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
742     // No dependence found. If this is the entry block of the function, it is
743     // unknown, otherwise it is non-local.
744     if (QueryParent != &QueryParent->getParent()->getEntryBlock())
745       LocalCache = MemDepResult::getNonLocal();
746     else
747       LocalCache = MemDepResult::getNonFuncLocal();
748   } else {
749     MemoryLocation MemLoc;
750     ModRefInfo MR = GetLocation(QueryInst, MemLoc, TLI);
751     if (MemLoc.Ptr) {
752       // If we can do a pointer scan, make it happen.
753       bool isLoad = !isModSet(MR);
754       if (auto *II = dyn_cast<IntrinsicInst>(QueryInst))
755         isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
756 
757       LocalCache = getPointerDependencyFrom(
758           MemLoc, isLoad, ScanPos->getIterator(), QueryParent, QueryInst);
759     } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
760       CallSite QueryCS(QueryInst);
761       bool isReadOnly = AA.onlyReadsMemory(QueryCS);
762       LocalCache = getCallSiteDependencyFrom(
763           QueryCS, isReadOnly, ScanPos->getIterator(), QueryParent);
764     } else
765       // Non-memory instruction.
766       LocalCache = MemDepResult::getUnknown();
767   }
768 
769   // Remember the result!
770   if (Instruction *I = LocalCache.getInst())
771     ReverseLocalDeps[I].insert(QueryInst);
772 
773   return LocalCache;
774 }
775 
776 #ifndef NDEBUG
777 /// This method is used when -debug is specified to verify that cache arrays
778 /// are properly kept sorted.
779 static void AssertSorted(MemoryDependenceResults::NonLocalDepInfo &Cache,
780                          int Count = -1) {
781   if (Count == -1)
782     Count = Cache.size();
783   assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) &&
784          "Cache isn't sorted!");
785 }
786 #endif
787 
788 const MemoryDependenceResults::NonLocalDepInfo &
789 MemoryDependenceResults::getNonLocalCallDependency(CallSite QueryCS) {
790   assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
791          "getNonLocalCallDependency should only be used on calls with "
792          "non-local deps!");
793   PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
794   NonLocalDepInfo &Cache = CacheP.first;
795 
796   // This is the set of blocks that need to be recomputed.  In the cached case,
797   // this can happen due to instructions being deleted etc. In the uncached
798   // case, this starts out as the set of predecessors we care about.
799   SmallVector<BasicBlock *, 32> DirtyBlocks;
800 
801   if (!Cache.empty()) {
802     // Okay, we have a cache entry.  If we know it is not dirty, just return it
803     // with no computation.
804     if (!CacheP.second) {
805       ++NumCacheNonLocal;
806       return Cache;
807     }
808 
809     // If we already have a partially computed set of results, scan them to
810     // determine what is dirty, seeding our initial DirtyBlocks worklist.
811     for (auto &Entry : Cache)
812       if (Entry.getResult().isDirty())
813         DirtyBlocks.push_back(Entry.getBB());
814 
815     // Sort the cache so that we can do fast binary search lookups below.
816     llvm::sort(Cache);
817 
818     ++NumCacheDirtyNonLocal;
819     // cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
820     //     << Cache.size() << " cached: " << *QueryInst;
821   } else {
822     // Seed DirtyBlocks with each of the preds of QueryInst's block.
823     BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
824     for (BasicBlock *Pred : PredCache.get(QueryBB))
825       DirtyBlocks.push_back(Pred);
826     ++NumUncacheNonLocal;
827   }
828 
829   // isReadonlyCall - If this is a read-only call, we can be more aggressive.
830   bool isReadonlyCall = AA.onlyReadsMemory(QueryCS);
831 
832   SmallPtrSet<BasicBlock *, 32> Visited;
833 
834   unsigned NumSortedEntries = Cache.size();
835   LLVM_DEBUG(AssertSorted(Cache));
836 
837   // Iterate while we still have blocks to update.
838   while (!DirtyBlocks.empty()) {
839     BasicBlock *DirtyBB = DirtyBlocks.back();
840     DirtyBlocks.pop_back();
841 
842     // Already processed this block?
843     if (!Visited.insert(DirtyBB).second)
844       continue;
845 
846     // Do a binary search to see if we already have an entry for this block in
847     // the cache set.  If so, find it.
848     LLVM_DEBUG(AssertSorted(Cache, NumSortedEntries));
849     NonLocalDepInfo::iterator Entry =
850         std::upper_bound(Cache.begin(), Cache.begin() + NumSortedEntries,
851                          NonLocalDepEntry(DirtyBB));
852     if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
853       --Entry;
854 
855     NonLocalDepEntry *ExistingResult = nullptr;
856     if (Entry != Cache.begin() + NumSortedEntries &&
857         Entry->getBB() == DirtyBB) {
858       // If we already have an entry, and if it isn't already dirty, the block
859       // is done.
860       if (!Entry->getResult().isDirty())
861         continue;
862 
863       // Otherwise, remember this slot so we can update the value.
864       ExistingResult = &*Entry;
865     }
866 
867     // If the dirty entry has a pointer, start scanning from it so we don't have
868     // to rescan the entire block.
869     BasicBlock::iterator ScanPos = DirtyBB->end();
870     if (ExistingResult) {
871       if (Instruction *Inst = ExistingResult->getResult().getInst()) {
872         ScanPos = Inst->getIterator();
873         // We're removing QueryInst's use of Inst.
874         RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
875                              QueryCS.getInstruction());
876       }
877     }
878 
879     // Find out if this block has a local dependency for QueryInst.
880     MemDepResult Dep;
881 
882     if (ScanPos != DirtyBB->begin()) {
883       Dep =
884           getCallSiteDependencyFrom(QueryCS, isReadonlyCall, ScanPos, DirtyBB);
885     } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
886       // No dependence found.  If this is the entry block of the function, it is
887       // a clobber, otherwise it is unknown.
888       Dep = MemDepResult::getNonLocal();
889     } else {
890       Dep = MemDepResult::getNonFuncLocal();
891     }
892 
893     // If we had a dirty entry for the block, update it.  Otherwise, just add
894     // a new entry.
895     if (ExistingResult)
896       ExistingResult->setResult(Dep);
897     else
898       Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
899 
900     // If the block has a dependency (i.e. it isn't completely transparent to
901     // the value), remember the association!
902     if (!Dep.isNonLocal()) {
903       // Keep the ReverseNonLocalDeps map up to date so we can efficiently
904       // update this when we remove instructions.
905       if (Instruction *Inst = Dep.getInst())
906         ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
907     } else {
908 
909       // If the block *is* completely transparent to the load, we need to check
910       // the predecessors of this block.  Add them to our worklist.
911       for (BasicBlock *Pred : PredCache.get(DirtyBB))
912         DirtyBlocks.push_back(Pred);
913     }
914   }
915 
916   return Cache;
917 }
918 
919 void MemoryDependenceResults::getNonLocalPointerDependency(
920     Instruction *QueryInst, SmallVectorImpl<NonLocalDepResult> &Result) {
921   const MemoryLocation Loc = MemoryLocation::get(QueryInst);
922   bool isLoad = isa<LoadInst>(QueryInst);
923   BasicBlock *FromBB = QueryInst->getParent();
924   assert(FromBB);
925 
926   assert(Loc.Ptr->getType()->isPointerTy() &&
927          "Can't get pointer deps of a non-pointer!");
928   Result.clear();
929   {
930     // Check if there is cached Def with invariant.group.
931     auto NonLocalDefIt = NonLocalDefsCache.find(QueryInst);
932     if (NonLocalDefIt != NonLocalDefsCache.end()) {
933       Result.push_back(NonLocalDefIt->second);
934       ReverseNonLocalDefsCache[NonLocalDefIt->second.getResult().getInst()]
935           .erase(QueryInst);
936       NonLocalDefsCache.erase(NonLocalDefIt);
937       return;
938     }
939   }
940   // This routine does not expect to deal with volatile instructions.
941   // Doing so would require piping through the QueryInst all the way through.
942   // TODO: volatiles can't be elided, but they can be reordered with other
943   // non-volatile accesses.
944 
945   // We currently give up on any instruction which is ordered, but we do handle
946   // atomic instructions which are unordered.
947   // TODO: Handle ordered instructions
948   auto isOrdered = [](Instruction *Inst) {
949     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
950       return !LI->isUnordered();
951     } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
952       return !SI->isUnordered();
953     }
954     return false;
955   };
956   if (isVolatile(QueryInst) || isOrdered(QueryInst)) {
957     Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
958                                        const_cast<Value *>(Loc.Ptr)));
959     return;
960   }
961   const DataLayout &DL = FromBB->getModule()->getDataLayout();
962   PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC);
963 
964   // This is the set of blocks we've inspected, and the pointer we consider in
965   // each block.  Because of critical edges, we currently bail out if querying
966   // a block with multiple different pointers.  This can happen during PHI
967   // translation.
968   DenseMap<BasicBlock *, Value *> Visited;
969   if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
970                                    Result, Visited, true))
971     return;
972   Result.clear();
973   Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
974                                      const_cast<Value *>(Loc.Ptr)));
975 }
976 
977 /// Compute the memdep value for BB with Pointer/PointeeSize using either
978 /// cached information in Cache or by doing a lookup (which may use dirty cache
979 /// info if available).
980 ///
981 /// If we do a lookup, add the result to the cache.
982 MemDepResult MemoryDependenceResults::GetNonLocalInfoForBlock(
983     Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad,
984     BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
985 
986   // Do a binary search to see if we already have an entry for this block in
987   // the cache set.  If so, find it.
988   NonLocalDepInfo::iterator Entry = std::upper_bound(
989       Cache->begin(), Cache->begin() + NumSortedEntries, NonLocalDepEntry(BB));
990   if (Entry != Cache->begin() && (Entry - 1)->getBB() == BB)
991     --Entry;
992 
993   NonLocalDepEntry *ExistingResult = nullptr;
994   if (Entry != Cache->begin() + NumSortedEntries && Entry->getBB() == BB)
995     ExistingResult = &*Entry;
996 
997   // If we have a cached entry, and it is non-dirty, use it as the value for
998   // this dependency.
999   if (ExistingResult && !ExistingResult->getResult().isDirty()) {
1000     ++NumCacheNonLocalPtr;
1001     return ExistingResult->getResult();
1002   }
1003 
1004   // Otherwise, we have to scan for the value.  If we have a dirty cache
1005   // entry, start scanning from its position, otherwise we scan from the end
1006   // of the block.
1007   BasicBlock::iterator ScanPos = BB->end();
1008   if (ExistingResult && ExistingResult->getResult().getInst()) {
1009     assert(ExistingResult->getResult().getInst()->getParent() == BB &&
1010            "Instruction invalidated?");
1011     ++NumCacheDirtyNonLocalPtr;
1012     ScanPos = ExistingResult->getResult().getInst()->getIterator();
1013 
1014     // Eliminating the dirty entry from 'Cache', so update the reverse info.
1015     ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
1016     RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey);
1017   } else {
1018     ++NumUncacheNonLocalPtr;
1019   }
1020 
1021   // Scan the block for the dependency.
1022   MemDepResult Dep =
1023       getPointerDependencyFrom(Loc, isLoad, ScanPos, BB, QueryInst);
1024 
1025   // If we had a dirty entry for the block, update it.  Otherwise, just add
1026   // a new entry.
1027   if (ExistingResult)
1028     ExistingResult->setResult(Dep);
1029   else
1030     Cache->push_back(NonLocalDepEntry(BB, Dep));
1031 
1032   // If the block has a dependency (i.e. it isn't completely transparent to
1033   // the value), remember the reverse association because we just added it
1034   // to Cache!
1035   if (!Dep.isDef() && !Dep.isClobber())
1036     return Dep;
1037 
1038   // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
1039   // update MemDep when we remove instructions.
1040   Instruction *Inst = Dep.getInst();
1041   assert(Inst && "Didn't depend on anything?");
1042   ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
1043   ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
1044   return Dep;
1045 }
1046 
1047 /// Sort the NonLocalDepInfo cache, given a certain number of elements in the
1048 /// array that are already properly ordered.
1049 ///
1050 /// This is optimized for the case when only a few entries are added.
1051 static void
1052 SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache,
1053                          unsigned NumSortedEntries) {
1054   switch (Cache.size() - NumSortedEntries) {
1055   case 0:
1056     // done, no new entries.
1057     break;
1058   case 2: {
1059     // Two new entries, insert the last one into place.
1060     NonLocalDepEntry Val = Cache.back();
1061     Cache.pop_back();
1062     MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
1063         std::upper_bound(Cache.begin(), Cache.end() - 1, Val);
1064     Cache.insert(Entry, Val);
1065     LLVM_FALLTHROUGH;
1066   }
1067   case 1:
1068     // One new entry, Just insert the new value at the appropriate position.
1069     if (Cache.size() != 1) {
1070       NonLocalDepEntry Val = Cache.back();
1071       Cache.pop_back();
1072       MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
1073           std::upper_bound(Cache.begin(), Cache.end(), Val);
1074       Cache.insert(Entry, Val);
1075     }
1076     break;
1077   default:
1078     // Added many values, do a full scale sort.
1079     llvm::sort(Cache);
1080     break;
1081   }
1082 }
1083 
1084 /// Perform a dependency query based on pointer/pointeesize starting at the end
1085 /// of StartBB.
1086 ///
1087 /// Add any clobber/def results to the results vector and keep track of which
1088 /// blocks are visited in 'Visited'.
1089 ///
1090 /// This has special behavior for the first block queries (when SkipFirstBlock
1091 /// is true).  In this special case, it ignores the contents of the specified
1092 /// block and starts returning dependence info for its predecessors.
1093 ///
1094 /// This function returns true on success, or false to indicate that it could
1095 /// not compute dependence information for some reason.  This should be treated
1096 /// as a clobber dependence on the first instruction in the predecessor block.
1097 bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
1098     Instruction *QueryInst, const PHITransAddr &Pointer,
1099     const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB,
1100     SmallVectorImpl<NonLocalDepResult> &Result,
1101     DenseMap<BasicBlock *, Value *> &Visited, bool SkipFirstBlock) {
1102   // Look up the cached info for Pointer.
1103   ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
1104 
1105   // Set up a temporary NLPI value. If the map doesn't yet have an entry for
1106   // CacheKey, this value will be inserted as the associated value. Otherwise,
1107   // it'll be ignored, and we'll have to check to see if the cached size and
1108   // aa tags are consistent with the current query.
1109   NonLocalPointerInfo InitialNLPI;
1110   InitialNLPI.Size = Loc.Size;
1111   InitialNLPI.AATags = Loc.AATags;
1112 
1113   // Get the NLPI for CacheKey, inserting one into the map if it doesn't
1114   // already have one.
1115   std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
1116       NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
1117   NonLocalPointerInfo *CacheInfo = &Pair.first->second;
1118 
1119   // If we already have a cache entry for this CacheKey, we may need to do some
1120   // work to reconcile the cache entry and the current query.
1121   if (!Pair.second) {
1122     if (CacheInfo->Size != Loc.Size) {
1123       bool ThrowOutEverything;
1124       if (CacheInfo->Size.hasValue() && Loc.Size.hasValue()) {
1125         // FIXME: We may be able to do better in the face of results with mixed
1126         // precision. We don't appear to get them in practice, though, so just
1127         // be conservative.
1128         ThrowOutEverything =
1129             CacheInfo->Size.isPrecise() != Loc.Size.isPrecise() ||
1130             CacheInfo->Size.getValue() < Loc.Size.getValue();
1131       } else {
1132         // For our purposes, unknown size > all others.
1133         ThrowOutEverything = !Loc.Size.hasValue();
1134       }
1135 
1136       if (ThrowOutEverything) {
1137         // The query's Size is greater than the cached one. Throw out the
1138         // cached data and proceed with the query at the greater size.
1139         CacheInfo->Pair = BBSkipFirstBlockPair();
1140         CacheInfo->Size = Loc.Size;
1141         for (auto &Entry : CacheInfo->NonLocalDeps)
1142           if (Instruction *Inst = Entry.getResult().getInst())
1143             RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1144         CacheInfo->NonLocalDeps.clear();
1145       } else {
1146         // This query's Size is less than the cached one. Conservatively restart
1147         // the query using the greater size.
1148         return getNonLocalPointerDepFromBB(
1149             QueryInst, Pointer, Loc.getWithNewSize(CacheInfo->Size), isLoad,
1150             StartBB, Result, Visited, SkipFirstBlock);
1151       }
1152     }
1153 
1154     // If the query's AATags are inconsistent with the cached one,
1155     // conservatively throw out the cached data and restart the query with
1156     // no tag if needed.
1157     if (CacheInfo->AATags != Loc.AATags) {
1158       if (CacheInfo->AATags) {
1159         CacheInfo->Pair = BBSkipFirstBlockPair();
1160         CacheInfo->AATags = AAMDNodes();
1161         for (auto &Entry : CacheInfo->NonLocalDeps)
1162           if (Instruction *Inst = Entry.getResult().getInst())
1163             RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1164         CacheInfo->NonLocalDeps.clear();
1165       }
1166       if (Loc.AATags)
1167         return getNonLocalPointerDepFromBB(
1168             QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result,
1169             Visited, SkipFirstBlock);
1170     }
1171   }
1172 
1173   NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
1174 
1175   // If we have valid cached information for exactly the block we are
1176   // investigating, just return it with no recomputation.
1177   if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
1178     // We have a fully cached result for this query then we can just return the
1179     // cached results and populate the visited set.  However, we have to verify
1180     // that we don't already have conflicting results for these blocks.  Check
1181     // to ensure that if a block in the results set is in the visited set that
1182     // it was for the same pointer query.
1183     if (!Visited.empty()) {
1184       for (auto &Entry : *Cache) {
1185         DenseMap<BasicBlock *, Value *>::iterator VI =
1186             Visited.find(Entry.getBB());
1187         if (VI == Visited.end() || VI->second == Pointer.getAddr())
1188           continue;
1189 
1190         // We have a pointer mismatch in a block.  Just return false, saying
1191         // that something was clobbered in this result.  We could also do a
1192         // non-fully cached query, but there is little point in doing this.
1193         return false;
1194       }
1195     }
1196 
1197     Value *Addr = Pointer.getAddr();
1198     for (auto &Entry : *Cache) {
1199       Visited.insert(std::make_pair(Entry.getBB(), Addr));
1200       if (Entry.getResult().isNonLocal()) {
1201         continue;
1202       }
1203 
1204       if (DT.isReachableFromEntry(Entry.getBB())) {
1205         Result.push_back(
1206             NonLocalDepResult(Entry.getBB(), Entry.getResult(), Addr));
1207       }
1208     }
1209     ++NumCacheCompleteNonLocalPtr;
1210     return true;
1211   }
1212 
1213   // Otherwise, either this is a new block, a block with an invalid cache
1214   // pointer or one that we're about to invalidate by putting more info into it
1215   // than its valid cache info.  If empty, the result will be valid cache info,
1216   // otherwise it isn't.
1217   if (Cache->empty())
1218     CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
1219   else
1220     CacheInfo->Pair = BBSkipFirstBlockPair();
1221 
1222   SmallVector<BasicBlock *, 32> Worklist;
1223   Worklist.push_back(StartBB);
1224 
1225   // PredList used inside loop.
1226   SmallVector<std::pair<BasicBlock *, PHITransAddr>, 16> PredList;
1227 
1228   // Keep track of the entries that we know are sorted.  Previously cached
1229   // entries will all be sorted.  The entries we add we only sort on demand (we
1230   // don't insert every element into its sorted position).  We know that we
1231   // won't get any reuse from currently inserted values, because we don't
1232   // revisit blocks after we insert info for them.
1233   unsigned NumSortedEntries = Cache->size();
1234   unsigned WorklistEntries = BlockNumberLimit;
1235   bool GotWorklistLimit = false;
1236   LLVM_DEBUG(AssertSorted(*Cache));
1237 
1238   while (!Worklist.empty()) {
1239     BasicBlock *BB = Worklist.pop_back_val();
1240 
1241     // If we do process a large number of blocks it becomes very expensive and
1242     // likely it isn't worth worrying about
1243     if (Result.size() > NumResultsLimit) {
1244       Worklist.clear();
1245       // Sort it now (if needed) so that recursive invocations of
1246       // getNonLocalPointerDepFromBB and other routines that could reuse the
1247       // cache value will only see properly sorted cache arrays.
1248       if (Cache && NumSortedEntries != Cache->size()) {
1249         SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1250       }
1251       // Since we bail out, the "Cache" set won't contain all of the
1252       // results for the query.  This is ok (we can still use it to accelerate
1253       // specific block queries) but we can't do the fastpath "return all
1254       // results from the set".  Clear out the indicator for this.
1255       CacheInfo->Pair = BBSkipFirstBlockPair();
1256       return false;
1257     }
1258 
1259     // Skip the first block if we have it.
1260     if (!SkipFirstBlock) {
1261       // Analyze the dependency of *Pointer in FromBB.  See if we already have
1262       // been here.
1263       assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
1264 
1265       // Get the dependency info for Pointer in BB.  If we have cached
1266       // information, we will use it, otherwise we compute it.
1267       LLVM_DEBUG(AssertSorted(*Cache, NumSortedEntries));
1268       MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst, Loc, isLoad, BB,
1269                                                  Cache, NumSortedEntries);
1270 
1271       // If we got a Def or Clobber, add this to the list of results.
1272       if (!Dep.isNonLocal()) {
1273         if (DT.isReachableFromEntry(BB)) {
1274           Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
1275           continue;
1276         }
1277       }
1278     }
1279 
1280     // If 'Pointer' is an instruction defined in this block, then we need to do
1281     // phi translation to change it into a value live in the predecessor block.
1282     // If not, we just add the predecessors to the worklist and scan them with
1283     // the same Pointer.
1284     if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
1285       SkipFirstBlock = false;
1286       SmallVector<BasicBlock *, 16> NewBlocks;
1287       for (BasicBlock *Pred : PredCache.get(BB)) {
1288         // Verify that we haven't looked at this block yet.
1289         std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
1290             Visited.insert(std::make_pair(Pred, Pointer.getAddr()));
1291         if (InsertRes.second) {
1292           // First time we've looked at *PI.
1293           NewBlocks.push_back(Pred);
1294           continue;
1295         }
1296 
1297         // If we have seen this block before, but it was with a different
1298         // pointer then we have a phi translation failure and we have to treat
1299         // this as a clobber.
1300         if (InsertRes.first->second != Pointer.getAddr()) {
1301           // Make sure to clean up the Visited map before continuing on to
1302           // PredTranslationFailure.
1303           for (unsigned i = 0; i < NewBlocks.size(); i++)
1304             Visited.erase(NewBlocks[i]);
1305           goto PredTranslationFailure;
1306         }
1307       }
1308       if (NewBlocks.size() > WorklistEntries) {
1309         // Make sure to clean up the Visited map before continuing on to
1310         // PredTranslationFailure.
1311         for (unsigned i = 0; i < NewBlocks.size(); i++)
1312           Visited.erase(NewBlocks[i]);
1313         GotWorklistLimit = true;
1314         goto PredTranslationFailure;
1315       }
1316       WorklistEntries -= NewBlocks.size();
1317       Worklist.append(NewBlocks.begin(), NewBlocks.end());
1318       continue;
1319     }
1320 
1321     // We do need to do phi translation, if we know ahead of time we can't phi
1322     // translate this value, don't even try.
1323     if (!Pointer.IsPotentiallyPHITranslatable())
1324       goto PredTranslationFailure;
1325 
1326     // We may have added values to the cache list before this PHI translation.
1327     // If so, we haven't done anything to ensure that the cache remains sorted.
1328     // Sort it now (if needed) so that recursive invocations of
1329     // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1330     // value will only see properly sorted cache arrays.
1331     if (Cache && NumSortedEntries != Cache->size()) {
1332       SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1333       NumSortedEntries = Cache->size();
1334     }
1335     Cache = nullptr;
1336 
1337     PredList.clear();
1338     for (BasicBlock *Pred : PredCache.get(BB)) {
1339       PredList.push_back(std::make_pair(Pred, Pointer));
1340 
1341       // Get the PHI translated pointer in this predecessor.  This can fail if
1342       // not translatable, in which case the getAddr() returns null.
1343       PHITransAddr &PredPointer = PredList.back().second;
1344       PredPointer.PHITranslateValue(BB, Pred, &DT, /*MustDominate=*/false);
1345       Value *PredPtrVal = PredPointer.getAddr();
1346 
1347       // Check to see if we have already visited this pred block with another
1348       // pointer.  If so, we can't do this lookup.  This failure can occur
1349       // with PHI translation when a critical edge exists and the PHI node in
1350       // the successor translates to a pointer value different than the
1351       // pointer the block was first analyzed with.
1352       std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
1353           Visited.insert(std::make_pair(Pred, PredPtrVal));
1354 
1355       if (!InsertRes.second) {
1356         // We found the pred; take it off the list of preds to visit.
1357         PredList.pop_back();
1358 
1359         // If the predecessor was visited with PredPtr, then we already did
1360         // the analysis and can ignore it.
1361         if (InsertRes.first->second == PredPtrVal)
1362           continue;
1363 
1364         // Otherwise, the block was previously analyzed with a different
1365         // pointer.  We can't represent the result of this case, so we just
1366         // treat this as a phi translation failure.
1367 
1368         // Make sure to clean up the Visited map before continuing on to
1369         // PredTranslationFailure.
1370         for (unsigned i = 0, n = PredList.size(); i < n; ++i)
1371           Visited.erase(PredList[i].first);
1372 
1373         goto PredTranslationFailure;
1374       }
1375     }
1376 
1377     // Actually process results here; this need to be a separate loop to avoid
1378     // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1379     // any results for.  (getNonLocalPointerDepFromBB will modify our
1380     // datastructures in ways the code after the PredTranslationFailure label
1381     // doesn't expect.)
1382     for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
1383       BasicBlock *Pred = PredList[i].first;
1384       PHITransAddr &PredPointer = PredList[i].second;
1385       Value *PredPtrVal = PredPointer.getAddr();
1386 
1387       bool CanTranslate = true;
1388       // If PHI translation was unable to find an available pointer in this
1389       // predecessor, then we have to assume that the pointer is clobbered in
1390       // that predecessor.  We can still do PRE of the load, which would insert
1391       // a computation of the pointer in this predecessor.
1392       if (!PredPtrVal)
1393         CanTranslate = false;
1394 
1395       // FIXME: it is entirely possible that PHI translating will end up with
1396       // the same value.  Consider PHI translating something like:
1397       // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
1398       // to recurse here, pedantically speaking.
1399 
1400       // If getNonLocalPointerDepFromBB fails here, that means the cached
1401       // result conflicted with the Visited list; we have to conservatively
1402       // assume it is unknown, but this also does not block PRE of the load.
1403       if (!CanTranslate ||
1404           !getNonLocalPointerDepFromBB(QueryInst, PredPointer,
1405                                       Loc.getWithNewPtr(PredPtrVal), isLoad,
1406                                       Pred, Result, Visited)) {
1407         // Add the entry to the Result list.
1408         NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
1409         Result.push_back(Entry);
1410 
1411         // Since we had a phi translation failure, the cache for CacheKey won't
1412         // include all of the entries that we need to immediately satisfy future
1413         // queries.  Mark this in NonLocalPointerDeps by setting the
1414         // BBSkipFirstBlockPair pointer to null.  This requires reuse of the
1415         // cached value to do more work but not miss the phi trans failure.
1416         NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1417         NLPI.Pair = BBSkipFirstBlockPair();
1418         continue;
1419       }
1420     }
1421 
1422     // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1423     CacheInfo = &NonLocalPointerDeps[CacheKey];
1424     Cache = &CacheInfo->NonLocalDeps;
1425     NumSortedEntries = Cache->size();
1426 
1427     // Since we did phi translation, the "Cache" set won't contain all of the
1428     // results for the query.  This is ok (we can still use it to accelerate
1429     // specific block queries) but we can't do the fastpath "return all
1430     // results from the set"  Clear out the indicator for this.
1431     CacheInfo->Pair = BBSkipFirstBlockPair();
1432     SkipFirstBlock = false;
1433     continue;
1434 
1435   PredTranslationFailure:
1436     // The following code is "failure"; we can't produce a sane translation
1437     // for the given block.  It assumes that we haven't modified any of
1438     // our datastructures while processing the current block.
1439 
1440     if (!Cache) {
1441       // Refresh the CacheInfo/Cache pointer if it got invalidated.
1442       CacheInfo = &NonLocalPointerDeps[CacheKey];
1443       Cache = &CacheInfo->NonLocalDeps;
1444       NumSortedEntries = Cache->size();
1445     }
1446 
1447     // Since we failed phi translation, the "Cache" set won't contain all of the
1448     // results for the query.  This is ok (we can still use it to accelerate
1449     // specific block queries) but we can't do the fastpath "return all
1450     // results from the set".  Clear out the indicator for this.
1451     CacheInfo->Pair = BBSkipFirstBlockPair();
1452 
1453     // If *nothing* works, mark the pointer as unknown.
1454     //
1455     // If this is the magic first block, return this as a clobber of the whole
1456     // incoming value.  Since we can't phi translate to one of the predecessors,
1457     // we have to bail out.
1458     if (SkipFirstBlock)
1459       return false;
1460 
1461     bool foundBlock = false;
1462     for (NonLocalDepEntry &I : llvm::reverse(*Cache)) {
1463       if (I.getBB() != BB)
1464         continue;
1465 
1466       assert((GotWorklistLimit || I.getResult().isNonLocal() ||
1467               !DT.isReachableFromEntry(BB)) &&
1468              "Should only be here with transparent block");
1469       foundBlock = true;
1470       I.setResult(MemDepResult::getUnknown());
1471       Result.push_back(
1472           NonLocalDepResult(I.getBB(), I.getResult(), Pointer.getAddr()));
1473       break;
1474     }
1475     (void)foundBlock; (void)GotWorklistLimit;
1476     assert((foundBlock || GotWorklistLimit) && "Current block not in cache?");
1477   }
1478 
1479   // Okay, we're done now.  If we added new values to the cache, re-sort it.
1480   SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1481   LLVM_DEBUG(AssertSorted(*Cache));
1482   return true;
1483 }
1484 
1485 /// If P exists in CachedNonLocalPointerInfo or NonLocalDefsCache, remove it.
1486 void MemoryDependenceResults::RemoveCachedNonLocalPointerDependencies(
1487     ValueIsLoadPair P) {
1488 
1489   // Most of the time this cache is empty.
1490   if (!NonLocalDefsCache.empty()) {
1491     auto it = NonLocalDefsCache.find(P.getPointer());
1492     if (it != NonLocalDefsCache.end()) {
1493       RemoveFromReverseMap(ReverseNonLocalDefsCache,
1494                            it->second.getResult().getInst(), P.getPointer());
1495       NonLocalDefsCache.erase(it);
1496     }
1497 
1498     if (auto *I = dyn_cast<Instruction>(P.getPointer())) {
1499       auto toRemoveIt = ReverseNonLocalDefsCache.find(I);
1500       if (toRemoveIt != ReverseNonLocalDefsCache.end()) {
1501         for (const auto &entry : toRemoveIt->second)
1502           NonLocalDefsCache.erase(entry);
1503         ReverseNonLocalDefsCache.erase(toRemoveIt);
1504       }
1505     }
1506   }
1507 
1508   CachedNonLocalPointerInfo::iterator It = NonLocalPointerDeps.find(P);
1509   if (It == NonLocalPointerDeps.end())
1510     return;
1511 
1512   // Remove all of the entries in the BB->val map.  This involves removing
1513   // instructions from the reverse map.
1514   NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1515 
1516   for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1517     Instruction *Target = PInfo[i].getResult().getInst();
1518     if (!Target)
1519       continue; // Ignore non-local dep results.
1520     assert(Target->getParent() == PInfo[i].getBB());
1521 
1522     // Eliminating the dirty entry from 'Cache', so update the reverse info.
1523     RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1524   }
1525 
1526   // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1527   NonLocalPointerDeps.erase(It);
1528 }
1529 
1530 void MemoryDependenceResults::invalidateCachedPointerInfo(Value *Ptr) {
1531   // If Ptr isn't really a pointer, just ignore it.
1532   if (!Ptr->getType()->isPointerTy())
1533     return;
1534   // Flush store info for the pointer.
1535   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1536   // Flush load info for the pointer.
1537   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1538   // Invalidate phis that use the pointer.
1539   PV.invalidateValue(Ptr);
1540 }
1541 
1542 void MemoryDependenceResults::invalidateCachedPredecessors() {
1543   PredCache.clear();
1544 }
1545 
1546 void MemoryDependenceResults::removeInstruction(Instruction *RemInst) {
1547   // Walk through the Non-local dependencies, removing this one as the value
1548   // for any cached queries.
1549   NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1550   if (NLDI != NonLocalDeps.end()) {
1551     NonLocalDepInfo &BlockMap = NLDI->second.first;
1552     for (auto &Entry : BlockMap)
1553       if (Instruction *Inst = Entry.getResult().getInst())
1554         RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1555     NonLocalDeps.erase(NLDI);
1556   }
1557 
1558   // If we have a cached local dependence query for this instruction, remove it.
1559   LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1560   if (LocalDepEntry != LocalDeps.end()) {
1561     // Remove us from DepInst's reverse set now that the local dep info is gone.
1562     if (Instruction *Inst = LocalDepEntry->second.getInst())
1563       RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1564 
1565     // Remove this local dependency info.
1566     LocalDeps.erase(LocalDepEntry);
1567   }
1568 
1569   // If we have any cached pointer dependencies on this instruction, remove
1570   // them.  If the instruction has non-pointer type, then it can't be a pointer
1571   // base.
1572 
1573   // Remove it from both the load info and the store info.  The instruction
1574   // can't be in either of these maps if it is non-pointer.
1575   if (RemInst->getType()->isPointerTy()) {
1576     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1577     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1578   }
1579 
1580   // Loop over all of the things that depend on the instruction we're removing.
1581   SmallVector<std::pair<Instruction *, Instruction *>, 8> ReverseDepsToAdd;
1582 
1583   // If we find RemInst as a clobber or Def in any of the maps for other values,
1584   // we need to replace its entry with a dirty version of the instruction after
1585   // it.  If RemInst is a terminator, we use a null dirty value.
1586   //
1587   // Using a dirty version of the instruction after RemInst saves having to scan
1588   // the entire block to get to this point.
1589   MemDepResult NewDirtyVal;
1590   if (!RemInst->isTerminator())
1591     NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator());
1592 
1593   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1594   if (ReverseDepIt != ReverseLocalDeps.end()) {
1595     // RemInst can't be the terminator if it has local stuff depending on it.
1596     assert(!ReverseDepIt->second.empty() && !RemInst->isTerminator() &&
1597            "Nothing can locally depend on a terminator");
1598 
1599     for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
1600       assert(InstDependingOnRemInst != RemInst &&
1601              "Already removed our local dep info");
1602 
1603       LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1604 
1605       // Make sure to remember that new things depend on NewDepInst.
1606       assert(NewDirtyVal.getInst() &&
1607              "There is no way something else can have "
1608              "a local dep on this if it is a terminator!");
1609       ReverseDepsToAdd.push_back(
1610           std::make_pair(NewDirtyVal.getInst(), InstDependingOnRemInst));
1611     }
1612 
1613     ReverseLocalDeps.erase(ReverseDepIt);
1614 
1615     // Add new reverse deps after scanning the set, to avoid invalidating the
1616     // 'ReverseDeps' reference.
1617     while (!ReverseDepsToAdd.empty()) {
1618       ReverseLocalDeps[ReverseDepsToAdd.back().first].insert(
1619           ReverseDepsToAdd.back().second);
1620       ReverseDepsToAdd.pop_back();
1621     }
1622   }
1623 
1624   ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1625   if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1626     for (Instruction *I : ReverseDepIt->second) {
1627       assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
1628 
1629       PerInstNLInfo &INLD = NonLocalDeps[I];
1630       // The information is now dirty!
1631       INLD.second = true;
1632 
1633       for (auto &Entry : INLD.first) {
1634         if (Entry.getResult().getInst() != RemInst)
1635           continue;
1636 
1637         // Convert to a dirty entry for the subsequent instruction.
1638         Entry.setResult(NewDirtyVal);
1639 
1640         if (Instruction *NextI = NewDirtyVal.getInst())
1641           ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
1642       }
1643     }
1644 
1645     ReverseNonLocalDeps.erase(ReverseDepIt);
1646 
1647     // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1648     while (!ReverseDepsToAdd.empty()) {
1649       ReverseNonLocalDeps[ReverseDepsToAdd.back().first].insert(
1650           ReverseDepsToAdd.back().second);
1651       ReverseDepsToAdd.pop_back();
1652     }
1653   }
1654 
1655   // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1656   // value in the NonLocalPointerDeps info.
1657   ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1658       ReverseNonLocalPtrDeps.find(RemInst);
1659   if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1660     SmallVector<std::pair<Instruction *, ValueIsLoadPair>, 8>
1661         ReversePtrDepsToAdd;
1662 
1663     for (ValueIsLoadPair P : ReversePtrDepIt->second) {
1664       assert(P.getPointer() != RemInst &&
1665              "Already removed NonLocalPointerDeps info for RemInst");
1666 
1667       NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1668 
1669       // The cache is not valid for any specific block anymore.
1670       NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1671 
1672       // Update any entries for RemInst to use the instruction after it.
1673       for (auto &Entry : NLPDI) {
1674         if (Entry.getResult().getInst() != RemInst)
1675           continue;
1676 
1677         // Convert to a dirty entry for the subsequent instruction.
1678         Entry.setResult(NewDirtyVal);
1679 
1680         if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1681           ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1682       }
1683 
1684       // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
1685       // subsequent value may invalidate the sortedness.
1686       llvm::sort(NLPDI);
1687     }
1688 
1689     ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1690 
1691     while (!ReversePtrDepsToAdd.empty()) {
1692       ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first].insert(
1693           ReversePtrDepsToAdd.back().second);
1694       ReversePtrDepsToAdd.pop_back();
1695     }
1696   }
1697 
1698   // Invalidate phis that use the removed instruction.
1699   PV.invalidateValue(RemInst);
1700 
1701   assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1702   LLVM_DEBUG(verifyRemoved(RemInst));
1703 }
1704 
1705 /// Verify that the specified instruction does not occur in our internal data
1706 /// structures.
1707 ///
1708 /// This function verifies by asserting in debug builds.
1709 void MemoryDependenceResults::verifyRemoved(Instruction *D) const {
1710 #ifndef NDEBUG
1711   for (const auto &DepKV : LocalDeps) {
1712     assert(DepKV.first != D && "Inst occurs in data structures");
1713     assert(DepKV.second.getInst() != D && "Inst occurs in data structures");
1714   }
1715 
1716   for (const auto &DepKV : NonLocalPointerDeps) {
1717     assert(DepKV.first.getPointer() != D && "Inst occurs in NLPD map key");
1718     for (const auto &Entry : DepKV.second.NonLocalDeps)
1719       assert(Entry.getResult().getInst() != D && "Inst occurs as NLPD value");
1720   }
1721 
1722   for (const auto &DepKV : NonLocalDeps) {
1723     assert(DepKV.first != D && "Inst occurs in data structures");
1724     const PerInstNLInfo &INLD = DepKV.second;
1725     for (const auto &Entry : INLD.first)
1726       assert(Entry.getResult().getInst() != D &&
1727              "Inst occurs in data structures");
1728   }
1729 
1730   for (const auto &DepKV : ReverseLocalDeps) {
1731     assert(DepKV.first != D && "Inst occurs in data structures");
1732     for (Instruction *Inst : DepKV.second)
1733       assert(Inst != D && "Inst occurs in data structures");
1734   }
1735 
1736   for (const auto &DepKV : ReverseNonLocalDeps) {
1737     assert(DepKV.first != D && "Inst occurs in data structures");
1738     for (Instruction *Inst : DepKV.second)
1739       assert(Inst != D && "Inst occurs in data structures");
1740   }
1741 
1742   for (const auto &DepKV : ReverseNonLocalPtrDeps) {
1743     assert(DepKV.first != D && "Inst occurs in rev NLPD map");
1744 
1745     for (ValueIsLoadPair P : DepKV.second)
1746       assert(P != ValueIsLoadPair(D, false) && P != ValueIsLoadPair(D, true) &&
1747              "Inst occurs in ReverseNonLocalPtrDeps map");
1748   }
1749 #endif
1750 }
1751 
1752 AnalysisKey MemoryDependenceAnalysis::Key;
1753 
1754 MemoryDependenceResults
1755 MemoryDependenceAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
1756   auto &AA = AM.getResult<AAManager>(F);
1757   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1758   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1759   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1760   auto &PV = AM.getResult<PhiValuesAnalysis>(F);
1761   return MemoryDependenceResults(AA, AC, TLI, DT, PV);
1762 }
1763 
1764 char MemoryDependenceWrapperPass::ID = 0;
1765 
1766 INITIALIZE_PASS_BEGIN(MemoryDependenceWrapperPass, "memdep",
1767                       "Memory Dependence Analysis", false, true)
1768 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1769 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1770 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1771 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1772 INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass)
1773 INITIALIZE_PASS_END(MemoryDependenceWrapperPass, "memdep",
1774                     "Memory Dependence Analysis", false, true)
1775 
1776 MemoryDependenceWrapperPass::MemoryDependenceWrapperPass() : FunctionPass(ID) {
1777   initializeMemoryDependenceWrapperPassPass(*PassRegistry::getPassRegistry());
1778 }
1779 
1780 MemoryDependenceWrapperPass::~MemoryDependenceWrapperPass() = default;
1781 
1782 void MemoryDependenceWrapperPass::releaseMemory() {
1783   MemDep.reset();
1784 }
1785 
1786 void MemoryDependenceWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1787   AU.setPreservesAll();
1788   AU.addRequired<AssumptionCacheTracker>();
1789   AU.addRequired<DominatorTreeWrapperPass>();
1790   AU.addRequired<PhiValuesWrapperPass>();
1791   AU.addRequiredTransitive<AAResultsWrapperPass>();
1792   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
1793 }
1794 
1795 bool MemoryDependenceResults::invalidate(Function &F, const PreservedAnalyses &PA,
1796                                FunctionAnalysisManager::Invalidator &Inv) {
1797   // Check whether our analysis is preserved.
1798   auto PAC = PA.getChecker<MemoryDependenceAnalysis>();
1799   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
1800     // If not, give up now.
1801     return true;
1802 
1803   // Check whether the analyses we depend on became invalid for any reason.
1804   if (Inv.invalidate<AAManager>(F, PA) ||
1805       Inv.invalidate<AssumptionAnalysis>(F, PA) ||
1806       Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
1807       Inv.invalidate<PhiValuesAnalysis>(F, PA))
1808     return true;
1809 
1810   // Otherwise this analysis result remains valid.
1811   return false;
1812 }
1813 
1814 unsigned MemoryDependenceResults::getDefaultBlockScanLimit() const {
1815   return BlockScanLimit;
1816 }
1817 
1818 bool MemoryDependenceWrapperPass::runOnFunction(Function &F) {
1819   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1820   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1821   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1822   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1823   auto &PV = getAnalysis<PhiValuesWrapperPass>().getResult();
1824   MemDep.emplace(AA, AC, TLI, DT, PV);
1825   return false;
1826 }
1827