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