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() == 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() == 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() && LI->getOrdering() > Unordered) {
522         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
523             isOtherMemAccess(QueryInst))
524           return MemDepResult::getClobber(LI);
525         if (LI->getOrdering() != 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() != 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     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
642     ModRefInfo MR = AA.getModRefInfo(Inst, MemLoc);
643     // If necessary, perform additional analysis.
644     if (MR == MRI_ModRef)
645       MR = AA.callCapturesBefore(Inst, MemLoc, &DT, &OBB);
646     switch (MR) {
647     case MRI_NoModRef:
648       // If the call has no effect on the queried pointer, just ignore it.
649       continue;
650     case MRI_Mod:
651       return MemDepResult::getClobber(Inst);
652     case MRI_Ref:
653       // If the call is known to never store to the pointer, and if this is a
654       // load query, we can safely ignore it (scan past it).
655       if (isLoad)
656         continue;
657     default:
658       // Otherwise, there is a potential dependence.  Return a clobber.
659       return MemDepResult::getClobber(Inst);
660     }
661   }
662 
663   // No dependence found.  If this is the entry block of the function, it is
664   // unknown, otherwise it is non-local.
665   if (BB != &BB->getParent()->getEntryBlock())
666     return MemDepResult::getNonLocal();
667   return MemDepResult::getNonFuncLocal();
668 }
669 
670 MemDepResult MemoryDependenceResults::getDependency(Instruction *QueryInst) {
671   Instruction *ScanPos = QueryInst;
672 
673   // Check for a cached result
674   MemDepResult &LocalCache = LocalDeps[QueryInst];
675 
676   // If the cached entry is non-dirty, just return it.  Note that this depends
677   // on MemDepResult's default constructing to 'dirty'.
678   if (!LocalCache.isDirty())
679     return LocalCache;
680 
681   // Otherwise, if we have a dirty entry, we know we can start the scan at that
682   // instruction, which may save us some work.
683   if (Instruction *Inst = LocalCache.getInst()) {
684     ScanPos = Inst;
685 
686     RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
687   }
688 
689   BasicBlock *QueryParent = QueryInst->getParent();
690 
691   // Do the scan.
692   if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
693     // No dependence found.  If this is the entry block of the function, it is
694     // unknown, otherwise it is non-local.
695     if (QueryParent != &QueryParent->getParent()->getEntryBlock())
696       LocalCache = MemDepResult::getNonLocal();
697     else
698       LocalCache = MemDepResult::getNonFuncLocal();
699   } else {
700     MemoryLocation MemLoc;
701     ModRefInfo MR = GetLocation(QueryInst, MemLoc, TLI);
702     if (MemLoc.Ptr) {
703       // If we can do a pointer scan, make it happen.
704       bool isLoad = !(MR & MRI_Mod);
705       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
706         isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
707 
708       LocalCache = getPointerDependencyFrom(
709           MemLoc, isLoad, ScanPos->getIterator(), QueryParent, QueryInst);
710     } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
711       CallSite QueryCS(QueryInst);
712       bool isReadOnly = AA.onlyReadsMemory(QueryCS);
713       LocalCache = getCallSiteDependencyFrom(
714           QueryCS, isReadOnly, ScanPos->getIterator(), QueryParent);
715     } else
716       // Non-memory instruction.
717       LocalCache = MemDepResult::getUnknown();
718   }
719 
720   // Remember the result!
721   if (Instruction *I = LocalCache.getInst())
722     ReverseLocalDeps[I].insert(QueryInst);
723 
724   return LocalCache;
725 }
726 
727 #ifndef NDEBUG
728 /// This method is used when -debug is specified to verify that cache arrays
729 /// are properly kept sorted.
730 static void AssertSorted(MemoryDependenceResults::NonLocalDepInfo &Cache,
731                          int Count = -1) {
732   if (Count == -1)
733     Count = Cache.size();
734   assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) &&
735          "Cache isn't sorted!");
736 }
737 #endif
738 
739 const MemoryDependenceResults::NonLocalDepInfo &
740 MemoryDependenceResults::getNonLocalCallDependency(CallSite QueryCS) {
741   assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
742          "getNonLocalCallDependency should only be used on calls with "
743          "non-local deps!");
744   PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
745   NonLocalDepInfo &Cache = CacheP.first;
746 
747   // This is the set of blocks that need to be recomputed.  In the cached case,
748   // this can happen due to instructions being deleted etc. In the uncached
749   // case, this starts out as the set of predecessors we care about.
750   SmallVector<BasicBlock *, 32> DirtyBlocks;
751 
752   if (!Cache.empty()) {
753     // Okay, we have a cache entry.  If we know it is not dirty, just return it
754     // with no computation.
755     if (!CacheP.second) {
756       ++NumCacheNonLocal;
757       return Cache;
758     }
759 
760     // If we already have a partially computed set of results, scan them to
761     // determine what is dirty, seeding our initial DirtyBlocks worklist.
762     for (auto &Entry : Cache)
763       if (Entry.getResult().isDirty())
764         DirtyBlocks.push_back(Entry.getBB());
765 
766     // Sort the cache so that we can do fast binary search lookups below.
767     std::sort(Cache.begin(), Cache.end());
768 
769     ++NumCacheDirtyNonLocal;
770     // cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
771     //     << Cache.size() << " cached: " << *QueryInst;
772   } else {
773     // Seed DirtyBlocks with each of the preds of QueryInst's block.
774     BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
775     for (BasicBlock *Pred : PredCache.get(QueryBB))
776       DirtyBlocks.push_back(Pred);
777     ++NumUncacheNonLocal;
778   }
779 
780   // isReadonlyCall - If this is a read-only call, we can be more aggressive.
781   bool isReadonlyCall = AA.onlyReadsMemory(QueryCS);
782 
783   SmallPtrSet<BasicBlock *, 32> Visited;
784 
785   unsigned NumSortedEntries = Cache.size();
786   DEBUG(AssertSorted(Cache));
787 
788   // Iterate while we still have blocks to update.
789   while (!DirtyBlocks.empty()) {
790     BasicBlock *DirtyBB = DirtyBlocks.back();
791     DirtyBlocks.pop_back();
792 
793     // Already processed this block?
794     if (!Visited.insert(DirtyBB).second)
795       continue;
796 
797     // Do a binary search to see if we already have an entry for this block in
798     // the cache set.  If so, find it.
799     DEBUG(AssertSorted(Cache, NumSortedEntries));
800     NonLocalDepInfo::iterator Entry =
801         std::upper_bound(Cache.begin(), Cache.begin() + NumSortedEntries,
802                          NonLocalDepEntry(DirtyBB));
803     if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
804       --Entry;
805 
806     NonLocalDepEntry *ExistingResult = nullptr;
807     if (Entry != Cache.begin() + NumSortedEntries &&
808         Entry->getBB() == DirtyBB) {
809       // If we already have an entry, and if it isn't already dirty, the block
810       // is done.
811       if (!Entry->getResult().isDirty())
812         continue;
813 
814       // Otherwise, remember this slot so we can update the value.
815       ExistingResult = &*Entry;
816     }
817 
818     // If the dirty entry has a pointer, start scanning from it so we don't have
819     // to rescan the entire block.
820     BasicBlock::iterator ScanPos = DirtyBB->end();
821     if (ExistingResult) {
822       if (Instruction *Inst = ExistingResult->getResult().getInst()) {
823         ScanPos = Inst->getIterator();
824         // We're removing QueryInst's use of Inst.
825         RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
826                              QueryCS.getInstruction());
827       }
828     }
829 
830     // Find out if this block has a local dependency for QueryInst.
831     MemDepResult Dep;
832 
833     if (ScanPos != DirtyBB->begin()) {
834       Dep =
835           getCallSiteDependencyFrom(QueryCS, isReadonlyCall, ScanPos, DirtyBB);
836     } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
837       // No dependence found.  If this is the entry block of the function, it is
838       // a clobber, otherwise it is unknown.
839       Dep = MemDepResult::getNonLocal();
840     } else {
841       Dep = MemDepResult::getNonFuncLocal();
842     }
843 
844     // If we had a dirty entry for the block, update it.  Otherwise, just add
845     // a new entry.
846     if (ExistingResult)
847       ExistingResult->setResult(Dep);
848     else
849       Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
850 
851     // If the block has a dependency (i.e. it isn't completely transparent to
852     // the value), remember the association!
853     if (!Dep.isNonLocal()) {
854       // Keep the ReverseNonLocalDeps map up to date so we can efficiently
855       // update this when we remove instructions.
856       if (Instruction *Inst = Dep.getInst())
857         ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
858     } else {
859 
860       // If the block *is* completely transparent to the load, we need to check
861       // the predecessors of this block.  Add them to our worklist.
862       for (BasicBlock *Pred : PredCache.get(DirtyBB))
863         DirtyBlocks.push_back(Pred);
864     }
865   }
866 
867   return Cache;
868 }
869 
870 void MemoryDependenceResults::getNonLocalPointerDependency(
871     Instruction *QueryInst, SmallVectorImpl<NonLocalDepResult> &Result) {
872   const MemoryLocation Loc = MemoryLocation::get(QueryInst);
873   bool isLoad = isa<LoadInst>(QueryInst);
874   BasicBlock *FromBB = QueryInst->getParent();
875   assert(FromBB);
876 
877   assert(Loc.Ptr->getType()->isPointerTy() &&
878          "Can't get pointer deps of a non-pointer!");
879   Result.clear();
880 
881   // This routine does not expect to deal with volatile instructions.
882   // Doing so would require piping through the QueryInst all the way through.
883   // TODO: volatiles can't be elided, but they can be reordered with other
884   // non-volatile accesses.
885 
886   // We currently give up on any instruction which is ordered, but we do handle
887   // atomic instructions which are unordered.
888   // TODO: Handle ordered instructions
889   auto isOrdered = [](Instruction *Inst) {
890     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
891       return !LI->isUnordered();
892     } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
893       return !SI->isUnordered();
894     }
895     return false;
896   };
897   if (isVolatile(QueryInst) || isOrdered(QueryInst)) {
898     Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
899                                        const_cast<Value *>(Loc.Ptr)));
900     return;
901   }
902   const DataLayout &DL = FromBB->getModule()->getDataLayout();
903   PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC);
904 
905   // This is the set of blocks we've inspected, and the pointer we consider in
906   // each block.  Because of critical edges, we currently bail out if querying
907   // a block with multiple different pointers.  This can happen during PHI
908   // translation.
909   DenseMap<BasicBlock *, Value *> Visited;
910   if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
911                                    Result, Visited, true))
912     return;
913   Result.clear();
914   Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
915                                      const_cast<Value *>(Loc.Ptr)));
916 }
917 
918 /// Compute the memdep value for BB with Pointer/PointeeSize using either
919 /// cached information in Cache or by doing a lookup (which may use dirty cache
920 /// info if available).
921 ///
922 /// If we do a lookup, add the result to the cache.
923 MemDepResult MemoryDependenceResults::GetNonLocalInfoForBlock(
924     Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad,
925     BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
926 
927   // Do a binary search to see if we already have an entry for this block in
928   // the cache set.  If so, find it.
929   NonLocalDepInfo::iterator Entry = std::upper_bound(
930       Cache->begin(), Cache->begin() + NumSortedEntries, NonLocalDepEntry(BB));
931   if (Entry != Cache->begin() && (Entry - 1)->getBB() == BB)
932     --Entry;
933 
934   NonLocalDepEntry *ExistingResult = nullptr;
935   if (Entry != Cache->begin() + NumSortedEntries && Entry->getBB() == BB)
936     ExistingResult = &*Entry;
937 
938   // If we have a cached entry, and it is non-dirty, use it as the value for
939   // this dependency.
940   if (ExistingResult && !ExistingResult->getResult().isDirty()) {
941     ++NumCacheNonLocalPtr;
942     return ExistingResult->getResult();
943   }
944 
945   // Otherwise, we have to scan for the value.  If we have a dirty cache
946   // entry, start scanning from its position, otherwise we scan from the end
947   // of the block.
948   BasicBlock::iterator ScanPos = BB->end();
949   if (ExistingResult && ExistingResult->getResult().getInst()) {
950     assert(ExistingResult->getResult().getInst()->getParent() == BB &&
951            "Instruction invalidated?");
952     ++NumCacheDirtyNonLocalPtr;
953     ScanPos = ExistingResult->getResult().getInst()->getIterator();
954 
955     // Eliminating the dirty entry from 'Cache', so update the reverse info.
956     ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
957     RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey);
958   } else {
959     ++NumUncacheNonLocalPtr;
960   }
961 
962   // Scan the block for the dependency.
963   MemDepResult Dep =
964       getPointerDependencyFrom(Loc, isLoad, ScanPos, BB, QueryInst);
965 
966   // If we had a dirty entry for the block, update it.  Otherwise, just add
967   // a new entry.
968   if (ExistingResult)
969     ExistingResult->setResult(Dep);
970   else
971     Cache->push_back(NonLocalDepEntry(BB, Dep));
972 
973   // If the block has a dependency (i.e. it isn't completely transparent to
974   // the value), remember the reverse association because we just added it
975   // to Cache!
976   if (!Dep.isDef() && !Dep.isClobber())
977     return Dep;
978 
979   // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
980   // update MemDep when we remove instructions.
981   Instruction *Inst = Dep.getInst();
982   assert(Inst && "Didn't depend on anything?");
983   ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
984   ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
985   return Dep;
986 }
987 
988 /// Sort the NonLocalDepInfo cache, given a certain number of elements in the
989 /// array that are already properly ordered.
990 ///
991 /// This is optimized for the case when only a few entries are added.
992 static void
993 SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache,
994                          unsigned NumSortedEntries) {
995   switch (Cache.size() - NumSortedEntries) {
996   case 0:
997     // done, no new entries.
998     break;
999   case 2: {
1000     // Two new entries, insert the last one into place.
1001     NonLocalDepEntry Val = Cache.back();
1002     Cache.pop_back();
1003     MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
1004         std::upper_bound(Cache.begin(), Cache.end() - 1, Val);
1005     Cache.insert(Entry, Val);
1006     // FALL THROUGH.
1007   }
1008   case 1:
1009     // One new entry, Just insert the new value at the appropriate position.
1010     if (Cache.size() != 1) {
1011       NonLocalDepEntry Val = Cache.back();
1012       Cache.pop_back();
1013       MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
1014           std::upper_bound(Cache.begin(), Cache.end(), Val);
1015       Cache.insert(Entry, Val);
1016     }
1017     break;
1018   default:
1019     // Added many values, do a full scale sort.
1020     std::sort(Cache.begin(), Cache.end());
1021     break;
1022   }
1023 }
1024 
1025 /// Perform a dependency query based on pointer/pointeesize starting at the end
1026 /// of StartBB.
1027 ///
1028 /// Add any clobber/def results to the results vector and keep track of which
1029 /// blocks are visited in 'Visited'.
1030 ///
1031 /// This has special behavior for the first block queries (when SkipFirstBlock
1032 /// is true).  In this special case, it ignores the contents of the specified
1033 /// block and starts returning dependence info for its predecessors.
1034 ///
1035 /// This function returns true on success, or false to indicate that it could
1036 /// not compute dependence information for some reason.  This should be treated
1037 /// as a clobber dependence on the first instruction in the predecessor block.
1038 bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
1039     Instruction *QueryInst, const PHITransAddr &Pointer,
1040     const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB,
1041     SmallVectorImpl<NonLocalDepResult> &Result,
1042     DenseMap<BasicBlock *, Value *> &Visited, bool SkipFirstBlock) {
1043   // Look up the cached info for Pointer.
1044   ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
1045 
1046   // Set up a temporary NLPI value. If the map doesn't yet have an entry for
1047   // CacheKey, this value will be inserted as the associated value. Otherwise,
1048   // it'll be ignored, and we'll have to check to see if the cached size and
1049   // aa tags are consistent with the current query.
1050   NonLocalPointerInfo InitialNLPI;
1051   InitialNLPI.Size = Loc.Size;
1052   InitialNLPI.AATags = Loc.AATags;
1053 
1054   // Get the NLPI for CacheKey, inserting one into the map if it doesn't
1055   // already have one.
1056   std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
1057       NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
1058   NonLocalPointerInfo *CacheInfo = &Pair.first->second;
1059 
1060   // If we already have a cache entry for this CacheKey, we may need to do some
1061   // work to reconcile the cache entry and the current query.
1062   if (!Pair.second) {
1063     if (CacheInfo->Size < Loc.Size) {
1064       // The query's Size is greater than the cached one. Throw out the
1065       // cached data and proceed with the query at the greater size.
1066       CacheInfo->Pair = BBSkipFirstBlockPair();
1067       CacheInfo->Size = Loc.Size;
1068       for (auto &Entry : CacheInfo->NonLocalDeps)
1069         if (Instruction *Inst = Entry.getResult().getInst())
1070           RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1071       CacheInfo->NonLocalDeps.clear();
1072     } else if (CacheInfo->Size > Loc.Size) {
1073       // This query's Size is less than the cached one. Conservatively restart
1074       // the query using the greater size.
1075       return getNonLocalPointerDepFromBB(
1076           QueryInst, Pointer, Loc.getWithNewSize(CacheInfo->Size), isLoad,
1077           StartBB, Result, Visited, SkipFirstBlock);
1078     }
1079 
1080     // If the query's AATags are inconsistent with the cached one,
1081     // conservatively throw out the cached data and restart the query with
1082     // no tag if needed.
1083     if (CacheInfo->AATags != Loc.AATags) {
1084       if (CacheInfo->AATags) {
1085         CacheInfo->Pair = BBSkipFirstBlockPair();
1086         CacheInfo->AATags = AAMDNodes();
1087         for (auto &Entry : CacheInfo->NonLocalDeps)
1088           if (Instruction *Inst = Entry.getResult().getInst())
1089             RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1090         CacheInfo->NonLocalDeps.clear();
1091       }
1092       if (Loc.AATags)
1093         return getNonLocalPointerDepFromBB(
1094             QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result,
1095             Visited, SkipFirstBlock);
1096     }
1097   }
1098 
1099   NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
1100 
1101   // If we have valid cached information for exactly the block we are
1102   // investigating, just return it with no recomputation.
1103   if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
1104     // We have a fully cached result for this query then we can just return the
1105     // cached results and populate the visited set.  However, we have to verify
1106     // that we don't already have conflicting results for these blocks.  Check
1107     // to ensure that if a block in the results set is in the visited set that
1108     // it was for the same pointer query.
1109     if (!Visited.empty()) {
1110       for (auto &Entry : *Cache) {
1111         DenseMap<BasicBlock *, Value *>::iterator VI =
1112             Visited.find(Entry.getBB());
1113         if (VI == Visited.end() || VI->second == Pointer.getAddr())
1114           continue;
1115 
1116         // We have a pointer mismatch in a block.  Just return false, saying
1117         // that something was clobbered in this result.  We could also do a
1118         // non-fully cached query, but there is little point in doing this.
1119         return false;
1120       }
1121     }
1122 
1123     Value *Addr = Pointer.getAddr();
1124     for (auto &Entry : *Cache) {
1125       Visited.insert(std::make_pair(Entry.getBB(), Addr));
1126       if (Entry.getResult().isNonLocal()) {
1127         continue;
1128       }
1129 
1130       if (DT.isReachableFromEntry(Entry.getBB())) {
1131         Result.push_back(
1132             NonLocalDepResult(Entry.getBB(), Entry.getResult(), Addr));
1133       }
1134     }
1135     ++NumCacheCompleteNonLocalPtr;
1136     return true;
1137   }
1138 
1139   // Otherwise, either this is a new block, a block with an invalid cache
1140   // pointer or one that we're about to invalidate by putting more info into it
1141   // than its valid cache info.  If empty, the result will be valid cache info,
1142   // otherwise it isn't.
1143   if (Cache->empty())
1144     CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
1145   else
1146     CacheInfo->Pair = BBSkipFirstBlockPair();
1147 
1148   SmallVector<BasicBlock *, 32> Worklist;
1149   Worklist.push_back(StartBB);
1150 
1151   // PredList used inside loop.
1152   SmallVector<std::pair<BasicBlock *, PHITransAddr>, 16> PredList;
1153 
1154   // Keep track of the entries that we know are sorted.  Previously cached
1155   // entries will all be sorted.  The entries we add we only sort on demand (we
1156   // don't insert every element into its sorted position).  We know that we
1157   // won't get any reuse from currently inserted values, because we don't
1158   // revisit blocks after we insert info for them.
1159   unsigned NumSortedEntries = Cache->size();
1160   unsigned WorklistEntries = BlockNumberLimit;
1161   bool GotWorklistLimit = false;
1162   DEBUG(AssertSorted(*Cache));
1163 
1164   while (!Worklist.empty()) {
1165     BasicBlock *BB = Worklist.pop_back_val();
1166 
1167     // If we do process a large number of blocks it becomes very expensive and
1168     // likely it isn't worth worrying about
1169     if (Result.size() > NumResultsLimit) {
1170       Worklist.clear();
1171       // Sort it now (if needed) so that recursive invocations of
1172       // getNonLocalPointerDepFromBB and other routines that could reuse the
1173       // cache value will only see properly sorted cache arrays.
1174       if (Cache && NumSortedEntries != Cache->size()) {
1175         SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1176       }
1177       // Since we bail out, the "Cache" set won't contain all of the
1178       // results for the query.  This is ok (we can still use it to accelerate
1179       // specific block queries) but we can't do the fastpath "return all
1180       // results from the set".  Clear out the indicator for this.
1181       CacheInfo->Pair = BBSkipFirstBlockPair();
1182       return false;
1183     }
1184 
1185     // Skip the first block if we have it.
1186     if (!SkipFirstBlock) {
1187       // Analyze the dependency of *Pointer in FromBB.  See if we already have
1188       // been here.
1189       assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
1190 
1191       // Get the dependency info for Pointer in BB.  If we have cached
1192       // information, we will use it, otherwise we compute it.
1193       DEBUG(AssertSorted(*Cache, NumSortedEntries));
1194       MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst, Loc, isLoad, BB,
1195                                                  Cache, NumSortedEntries);
1196 
1197       // If we got a Def or Clobber, add this to the list of results.
1198       if (!Dep.isNonLocal()) {
1199         if (DT.isReachableFromEntry(BB)) {
1200           Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
1201           continue;
1202         }
1203       }
1204     }
1205 
1206     // If 'Pointer' is an instruction defined in this block, then we need to do
1207     // phi translation to change it into a value live in the predecessor block.
1208     // If not, we just add the predecessors to the worklist and scan them with
1209     // the same Pointer.
1210     if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
1211       SkipFirstBlock = false;
1212       SmallVector<BasicBlock *, 16> NewBlocks;
1213       for (BasicBlock *Pred : PredCache.get(BB)) {
1214         // Verify that we haven't looked at this block yet.
1215         std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
1216             Visited.insert(std::make_pair(Pred, Pointer.getAddr()));
1217         if (InsertRes.second) {
1218           // First time we've looked at *PI.
1219           NewBlocks.push_back(Pred);
1220           continue;
1221         }
1222 
1223         // If we have seen this block before, but it was with a different
1224         // pointer then we have a phi translation failure and we have to treat
1225         // this as a clobber.
1226         if (InsertRes.first->second != Pointer.getAddr()) {
1227           // Make sure to clean up the Visited map before continuing on to
1228           // PredTranslationFailure.
1229           for (unsigned i = 0; i < NewBlocks.size(); i++)
1230             Visited.erase(NewBlocks[i]);
1231           goto PredTranslationFailure;
1232         }
1233       }
1234       if (NewBlocks.size() > WorklistEntries) {
1235         // Make sure to clean up the Visited map before continuing on to
1236         // PredTranslationFailure.
1237         for (unsigned i = 0; i < NewBlocks.size(); i++)
1238           Visited.erase(NewBlocks[i]);
1239         GotWorklistLimit = true;
1240         goto PredTranslationFailure;
1241       }
1242       WorklistEntries -= NewBlocks.size();
1243       Worklist.append(NewBlocks.begin(), NewBlocks.end());
1244       continue;
1245     }
1246 
1247     // We do need to do phi translation, if we know ahead of time we can't phi
1248     // translate this value, don't even try.
1249     if (!Pointer.IsPotentiallyPHITranslatable())
1250       goto PredTranslationFailure;
1251 
1252     // We may have added values to the cache list before this PHI translation.
1253     // If so, we haven't done anything to ensure that the cache remains sorted.
1254     // Sort it now (if needed) so that recursive invocations of
1255     // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1256     // value will only see properly sorted cache arrays.
1257     if (Cache && NumSortedEntries != Cache->size()) {
1258       SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1259       NumSortedEntries = Cache->size();
1260     }
1261     Cache = nullptr;
1262 
1263     PredList.clear();
1264     for (BasicBlock *Pred : PredCache.get(BB)) {
1265       PredList.push_back(std::make_pair(Pred, Pointer));
1266 
1267       // Get the PHI translated pointer in this predecessor.  This can fail if
1268       // not translatable, in which case the getAddr() returns null.
1269       PHITransAddr &PredPointer = PredList.back().second;
1270       PredPointer.PHITranslateValue(BB, Pred, &DT, /*MustDominate=*/false);
1271       Value *PredPtrVal = PredPointer.getAddr();
1272 
1273       // Check to see if we have already visited this pred block with another
1274       // pointer.  If so, we can't do this lookup.  This failure can occur
1275       // with PHI translation when a critical edge exists and the PHI node in
1276       // the successor translates to a pointer value different than the
1277       // pointer the block was first analyzed with.
1278       std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
1279           Visited.insert(std::make_pair(Pred, PredPtrVal));
1280 
1281       if (!InsertRes.second) {
1282         // We found the pred; take it off the list of preds to visit.
1283         PredList.pop_back();
1284 
1285         // If the predecessor was visited with PredPtr, then we already did
1286         // the analysis and can ignore it.
1287         if (InsertRes.first->second == PredPtrVal)
1288           continue;
1289 
1290         // Otherwise, the block was previously analyzed with a different
1291         // pointer.  We can't represent the result of this case, so we just
1292         // treat this as a phi translation failure.
1293 
1294         // Make sure to clean up the Visited map before continuing on to
1295         // PredTranslationFailure.
1296         for (unsigned i = 0, n = PredList.size(); i < n; ++i)
1297           Visited.erase(PredList[i].first);
1298 
1299         goto PredTranslationFailure;
1300       }
1301     }
1302 
1303     // Actually process results here; this need to be a separate loop to avoid
1304     // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1305     // any results for.  (getNonLocalPointerDepFromBB will modify our
1306     // datastructures in ways the code after the PredTranslationFailure label
1307     // doesn't expect.)
1308     for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
1309       BasicBlock *Pred = PredList[i].first;
1310       PHITransAddr &PredPointer = PredList[i].second;
1311       Value *PredPtrVal = PredPointer.getAddr();
1312 
1313       bool CanTranslate = true;
1314       // If PHI translation was unable to find an available pointer in this
1315       // predecessor, then we have to assume that the pointer is clobbered in
1316       // that predecessor.  We can still do PRE of the load, which would insert
1317       // a computation of the pointer in this predecessor.
1318       if (!PredPtrVal)
1319         CanTranslate = false;
1320 
1321       // FIXME: it is entirely possible that PHI translating will end up with
1322       // the same value.  Consider PHI translating something like:
1323       // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
1324       // to recurse here, pedantically speaking.
1325 
1326       // If getNonLocalPointerDepFromBB fails here, that means the cached
1327       // result conflicted with the Visited list; we have to conservatively
1328       // assume it is unknown, but this also does not block PRE of the load.
1329       if (!CanTranslate ||
1330           !getNonLocalPointerDepFromBB(QueryInst, PredPointer,
1331                                       Loc.getWithNewPtr(PredPtrVal), isLoad,
1332                                       Pred, Result, Visited)) {
1333         // Add the entry to the Result list.
1334         NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
1335         Result.push_back(Entry);
1336 
1337         // Since we had a phi translation failure, the cache for CacheKey won't
1338         // include all of the entries that we need to immediately satisfy future
1339         // queries.  Mark this in NonLocalPointerDeps by setting the
1340         // BBSkipFirstBlockPair pointer to null.  This requires reuse of the
1341         // cached value to do more work but not miss the phi trans failure.
1342         NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1343         NLPI.Pair = BBSkipFirstBlockPair();
1344         continue;
1345       }
1346     }
1347 
1348     // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1349     CacheInfo = &NonLocalPointerDeps[CacheKey];
1350     Cache = &CacheInfo->NonLocalDeps;
1351     NumSortedEntries = Cache->size();
1352 
1353     // Since we did phi translation, the "Cache" set won't contain all of the
1354     // results for the query.  This is ok (we can still use it to accelerate
1355     // specific block queries) but we can't do the fastpath "return all
1356     // results from the set"  Clear out the indicator for this.
1357     CacheInfo->Pair = BBSkipFirstBlockPair();
1358     SkipFirstBlock = false;
1359     continue;
1360 
1361   PredTranslationFailure:
1362     // The following code is "failure"; we can't produce a sane translation
1363     // for the given block.  It assumes that we haven't modified any of
1364     // our datastructures while processing the current block.
1365 
1366     if (!Cache) {
1367       // Refresh the CacheInfo/Cache pointer if it got invalidated.
1368       CacheInfo = &NonLocalPointerDeps[CacheKey];
1369       Cache = &CacheInfo->NonLocalDeps;
1370       NumSortedEntries = Cache->size();
1371     }
1372 
1373     // Since we failed phi translation, the "Cache" set won't contain all of the
1374     // results for the query.  This is ok (we can still use it to accelerate
1375     // specific block queries) but we can't do the fastpath "return all
1376     // results from the set".  Clear out the indicator for this.
1377     CacheInfo->Pair = BBSkipFirstBlockPair();
1378 
1379     // If *nothing* works, mark the pointer as unknown.
1380     //
1381     // If this is the magic first block, return this as a clobber of the whole
1382     // incoming value.  Since we can't phi translate to one of the predecessors,
1383     // we have to bail out.
1384     if (SkipFirstBlock)
1385       return false;
1386 
1387     bool foundBlock = false;
1388     for (NonLocalDepEntry &I : llvm::reverse(*Cache)) {
1389       if (I.getBB() != BB)
1390         continue;
1391 
1392       assert((GotWorklistLimit || I.getResult().isNonLocal() ||
1393               !DT.isReachableFromEntry(BB)) &&
1394              "Should only be here with transparent block");
1395       foundBlock = true;
1396       I.setResult(MemDepResult::getUnknown());
1397       Result.push_back(
1398           NonLocalDepResult(I.getBB(), I.getResult(), Pointer.getAddr()));
1399       break;
1400     }
1401     (void)foundBlock;
1402     assert((foundBlock || GotWorklistLimit) && "Current block not in cache?");
1403   }
1404 
1405   // Okay, we're done now.  If we added new values to the cache, re-sort it.
1406   SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1407   DEBUG(AssertSorted(*Cache));
1408   return true;
1409 }
1410 
1411 /// If P exists in CachedNonLocalPointerInfo, remove it.
1412 void MemoryDependenceResults::RemoveCachedNonLocalPointerDependencies(
1413     ValueIsLoadPair P) {
1414   CachedNonLocalPointerInfo::iterator It = NonLocalPointerDeps.find(P);
1415   if (It == NonLocalPointerDeps.end())
1416     return;
1417 
1418   // Remove all of the entries in the BB->val map.  This involves removing
1419   // instructions from the reverse map.
1420   NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1421 
1422   for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1423     Instruction *Target = PInfo[i].getResult().getInst();
1424     if (!Target)
1425       continue; // Ignore non-local dep results.
1426     assert(Target->getParent() == PInfo[i].getBB());
1427 
1428     // Eliminating the dirty entry from 'Cache', so update the reverse info.
1429     RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1430   }
1431 
1432   // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1433   NonLocalPointerDeps.erase(It);
1434 }
1435 
1436 void MemoryDependenceResults::invalidateCachedPointerInfo(Value *Ptr) {
1437   // If Ptr isn't really a pointer, just ignore it.
1438   if (!Ptr->getType()->isPointerTy())
1439     return;
1440   // Flush store info for the pointer.
1441   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1442   // Flush load info for the pointer.
1443   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1444 }
1445 
1446 void MemoryDependenceResults::invalidateCachedPredecessors() {
1447   PredCache.clear();
1448 }
1449 
1450 void MemoryDependenceResults::removeInstruction(Instruction *RemInst) {
1451   // Walk through the Non-local dependencies, removing this one as the value
1452   // for any cached queries.
1453   NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1454   if (NLDI != NonLocalDeps.end()) {
1455     NonLocalDepInfo &BlockMap = NLDI->second.first;
1456     for (auto &Entry : BlockMap)
1457       if (Instruction *Inst = Entry.getResult().getInst())
1458         RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1459     NonLocalDeps.erase(NLDI);
1460   }
1461 
1462   // If we have a cached local dependence query for this instruction, remove it.
1463   //
1464   LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1465   if (LocalDepEntry != LocalDeps.end()) {
1466     // Remove us from DepInst's reverse set now that the local dep info is gone.
1467     if (Instruction *Inst = LocalDepEntry->second.getInst())
1468       RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1469 
1470     // Remove this local dependency info.
1471     LocalDeps.erase(LocalDepEntry);
1472   }
1473 
1474   // If we have any cached pointer dependencies on this instruction, remove
1475   // them.  If the instruction has non-pointer type, then it can't be a pointer
1476   // base.
1477 
1478   // Remove it from both the load info and the store info.  The instruction
1479   // can't be in either of these maps if it is non-pointer.
1480   if (RemInst->getType()->isPointerTy()) {
1481     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1482     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1483   }
1484 
1485   // Loop over all of the things that depend on the instruction we're removing.
1486   //
1487   SmallVector<std::pair<Instruction *, Instruction *>, 8> ReverseDepsToAdd;
1488 
1489   // If we find RemInst as a clobber or Def in any of the maps for other values,
1490   // we need to replace its entry with a dirty version of the instruction after
1491   // it.  If RemInst is a terminator, we use a null dirty value.
1492   //
1493   // Using a dirty version of the instruction after RemInst saves having to scan
1494   // the entire block to get to this point.
1495   MemDepResult NewDirtyVal;
1496   if (!RemInst->isTerminator())
1497     NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator());
1498 
1499   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1500   if (ReverseDepIt != ReverseLocalDeps.end()) {
1501     // RemInst can't be the terminator if it has local stuff depending on it.
1502     assert(!ReverseDepIt->second.empty() && !isa<TerminatorInst>(RemInst) &&
1503            "Nothing can locally depend on a terminator");
1504 
1505     for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
1506       assert(InstDependingOnRemInst != RemInst &&
1507              "Already removed our local dep info");
1508 
1509       LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1510 
1511       // Make sure to remember that new things depend on NewDepInst.
1512       assert(NewDirtyVal.getInst() &&
1513              "There is no way something else can have "
1514              "a local dep on this if it is a terminator!");
1515       ReverseDepsToAdd.push_back(
1516           std::make_pair(NewDirtyVal.getInst(), InstDependingOnRemInst));
1517     }
1518 
1519     ReverseLocalDeps.erase(ReverseDepIt);
1520 
1521     // Add new reverse deps after scanning the set, to avoid invalidating the
1522     // 'ReverseDeps' reference.
1523     while (!ReverseDepsToAdd.empty()) {
1524       ReverseLocalDeps[ReverseDepsToAdd.back().first].insert(
1525           ReverseDepsToAdd.back().second);
1526       ReverseDepsToAdd.pop_back();
1527     }
1528   }
1529 
1530   ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1531   if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1532     for (Instruction *I : ReverseDepIt->second) {
1533       assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
1534 
1535       PerInstNLInfo &INLD = NonLocalDeps[I];
1536       // The information is now dirty!
1537       INLD.second = true;
1538 
1539       for (auto &Entry : INLD.first) {
1540         if (Entry.getResult().getInst() != RemInst)
1541           continue;
1542 
1543         // Convert to a dirty entry for the subsequent instruction.
1544         Entry.setResult(NewDirtyVal);
1545 
1546         if (Instruction *NextI = NewDirtyVal.getInst())
1547           ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
1548       }
1549     }
1550 
1551     ReverseNonLocalDeps.erase(ReverseDepIt);
1552 
1553     // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1554     while (!ReverseDepsToAdd.empty()) {
1555       ReverseNonLocalDeps[ReverseDepsToAdd.back().first].insert(
1556           ReverseDepsToAdd.back().second);
1557       ReverseDepsToAdd.pop_back();
1558     }
1559   }
1560 
1561   // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1562   // value in the NonLocalPointerDeps info.
1563   ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1564       ReverseNonLocalPtrDeps.find(RemInst);
1565   if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1566     SmallVector<std::pair<Instruction *, ValueIsLoadPair>, 8>
1567         ReversePtrDepsToAdd;
1568 
1569     for (ValueIsLoadPair P : ReversePtrDepIt->second) {
1570       assert(P.getPointer() != RemInst &&
1571              "Already removed NonLocalPointerDeps info for RemInst");
1572 
1573       NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1574 
1575       // The cache is not valid for any specific block anymore.
1576       NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1577 
1578       // Update any entries for RemInst to use the instruction after it.
1579       for (auto &Entry : NLPDI) {
1580         if (Entry.getResult().getInst() != RemInst)
1581           continue;
1582 
1583         // Convert to a dirty entry for the subsequent instruction.
1584         Entry.setResult(NewDirtyVal);
1585 
1586         if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1587           ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1588       }
1589 
1590       // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
1591       // subsequent value may invalidate the sortedness.
1592       std::sort(NLPDI.begin(), NLPDI.end());
1593     }
1594 
1595     ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1596 
1597     while (!ReversePtrDepsToAdd.empty()) {
1598       ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first].insert(
1599           ReversePtrDepsToAdd.back().second);
1600       ReversePtrDepsToAdd.pop_back();
1601     }
1602   }
1603 
1604   assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1605   DEBUG(verifyRemoved(RemInst));
1606 }
1607 
1608 /// Verify that the specified instruction does not occur in our internal data
1609 /// structures.
1610 ///
1611 /// This function verifies by asserting in debug builds.
1612 void MemoryDependenceResults::verifyRemoved(Instruction *D) const {
1613 #ifndef NDEBUG
1614   for (const auto &DepKV : LocalDeps) {
1615     assert(DepKV.first != D && "Inst occurs in data structures");
1616     assert(DepKV.second.getInst() != D && "Inst occurs in data structures");
1617   }
1618 
1619   for (const auto &DepKV : NonLocalPointerDeps) {
1620     assert(DepKV.first.getPointer() != D && "Inst occurs in NLPD map key");
1621     for (const auto &Entry : DepKV.second.NonLocalDeps)
1622       assert(Entry.getResult().getInst() != D && "Inst occurs as NLPD value");
1623   }
1624 
1625   for (const auto &DepKV : NonLocalDeps) {
1626     assert(DepKV.first != D && "Inst occurs in data structures");
1627     const PerInstNLInfo &INLD = DepKV.second;
1628     for (const auto &Entry : INLD.first)
1629       assert(Entry.getResult().getInst() != D &&
1630              "Inst occurs in data structures");
1631   }
1632 
1633   for (const auto &DepKV : ReverseLocalDeps) {
1634     assert(DepKV.first != D && "Inst occurs in data structures");
1635     for (Instruction *Inst : DepKV.second)
1636       assert(Inst != D && "Inst occurs in data structures");
1637   }
1638 
1639   for (const auto &DepKV : ReverseNonLocalDeps) {
1640     assert(DepKV.first != D && "Inst occurs in data structures");
1641     for (Instruction *Inst : DepKV.second)
1642       assert(Inst != D && "Inst occurs in data structures");
1643   }
1644 
1645   for (const auto &DepKV : ReverseNonLocalPtrDeps) {
1646     assert(DepKV.first != D && "Inst occurs in rev NLPD map");
1647 
1648     for (ValueIsLoadPair P : DepKV.second)
1649       assert(P != ValueIsLoadPair(D, false) && P != ValueIsLoadPair(D, true) &&
1650              "Inst occurs in ReverseNonLocalPtrDeps map");
1651   }
1652 #endif
1653 }
1654 
1655 char MemoryDependenceAnalysis::PassID;
1656 
1657 MemoryDependenceResults
1658 MemoryDependenceAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
1659   auto &AA = AM.getResult<AAManager>(F);
1660   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1661   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1662   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1663   return MemoryDependenceResults(AA, AC, TLI, DT);
1664 }
1665 
1666 char MemoryDependenceWrapperPass::ID = 0;
1667 
1668 INITIALIZE_PASS_BEGIN(MemoryDependenceWrapperPass, "memdep",
1669                       "Memory Dependence Analysis", false, true)
1670 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1671 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1672 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1673 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1674 INITIALIZE_PASS_END(MemoryDependenceWrapperPass, "memdep",
1675                     "Memory Dependence Analysis", false, true)
1676 
1677 MemoryDependenceWrapperPass::MemoryDependenceWrapperPass() : FunctionPass(ID) {
1678   initializeMemoryDependenceWrapperPassPass(*PassRegistry::getPassRegistry());
1679 }
1680 MemoryDependenceWrapperPass::~MemoryDependenceWrapperPass() {}
1681 
1682 void MemoryDependenceWrapperPass::releaseMemory() {
1683   MemDep.reset();
1684 }
1685 
1686 void MemoryDependenceWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1687   AU.setPreservesAll();
1688   AU.addRequired<AssumptionCacheTracker>();
1689   AU.addRequired<DominatorTreeWrapperPass>();
1690   AU.addRequiredTransitive<AAResultsWrapperPass>();
1691   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
1692 }
1693 
1694 bool MemoryDependenceWrapperPass::runOnFunction(Function &F) {
1695   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1696   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1697   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1698   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1699   MemDep.emplace(AA, AC, TLI, DT);
1700   return false;
1701 }
1702 
1703