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/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/AssumptionCache.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/PHITransAddr.h"
26 #include "llvm/Analysis/OrderedBasicBlock.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Instruction.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/PredIteratorCache.h"
40 #include "llvm/Support/AtomicOrdering.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/MathExtras.h"
46 #include <algorithm>
47 #include <cassert>
48 #include <iterator>
49 
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "memdep"
53 
54 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
55 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
56 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
57 
58 STATISTIC(NumCacheNonLocalPtr,
59           "Number of fully cached non-local ptr responses");
60 STATISTIC(NumCacheDirtyNonLocalPtr,
61           "Number of cached, but dirty, non-local ptr responses");
62 STATISTIC(NumUncacheNonLocalPtr, "Number of uncached non-local ptr responses");
63 STATISTIC(NumCacheCompleteNonLocalPtr,
64           "Number of block queries that were completely cached");
65 
66 // Limit for the number of instructions to scan in a block.
67 
68 static cl::opt<unsigned> BlockScanLimit(
69     "memdep-block-scan-limit", cl::Hidden, cl::init(100),
70     cl::desc("The number of instructions to scan in a block in memory "
71              "dependency analysis (default = 100)"));
72 
73 static cl::opt<unsigned>
74     BlockNumberLimit("memdep-block-number-limit", cl::Hidden, cl::init(1000),
75                      cl::desc("The number of blocks to scan during memory "
76                               "dependency analysis (default = 1000)"));
77 
78 // Limit on the number of memdep results to process.
79 static const unsigned int NumResultsLimit = 100;
80 
81 /// This is a helper function that removes Val from 'Inst's set in ReverseMap.
82 ///
83 /// If the set becomes empty, remove Inst's entry.
84 template <typename KeyTy>
85 static void
86 RemoveFromReverseMap(DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>> &ReverseMap,
87                      Instruction *Inst, KeyTy Val) {
88   typename DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>>::iterator InstIt =
89       ReverseMap.find(Inst);
90   assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
91   bool Found = InstIt->second.erase(Val);
92   assert(Found && "Invalid reverse map!");
93   (void)Found;
94   if (InstIt->second.empty())
95     ReverseMap.erase(InstIt);
96 }
97 
98 /// If the given instruction references a specific memory location, fill in Loc
99 /// with the details, otherwise set Loc.Ptr to null.
100 ///
101 /// Returns a ModRefInfo value describing the general behavior of the
102 /// instruction.
103 static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc,
104                               const TargetLibraryInfo &TLI) {
105   if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
106     if (LI->isUnordered()) {
107       Loc = MemoryLocation::get(LI);
108       return MRI_Ref;
109     }
110     if (LI->getOrdering() == AtomicOrdering::Monotonic) {
111       Loc = MemoryLocation::get(LI);
112       return MRI_ModRef;
113     }
114     Loc = MemoryLocation();
115     return MRI_ModRef;
116   }
117 
118   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
119     if (SI->isUnordered()) {
120       Loc = MemoryLocation::get(SI);
121       return MRI_Mod;
122     }
123     if (SI->getOrdering() == AtomicOrdering::Monotonic) {
124       Loc = MemoryLocation::get(SI);
125       return MRI_ModRef;
126     }
127     Loc = MemoryLocation();
128     return MRI_ModRef;
129   }
130 
131   if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
132     Loc = MemoryLocation::get(V);
133     return MRI_ModRef;
134   }
135 
136   if (const CallInst *CI = isFreeCall(Inst, &TLI)) {
137     // calls to free() deallocate the entire structure
138     Loc = MemoryLocation(CI->getArgOperand(0));
139     return MRI_Mod;
140   }
141 
142   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
143     AAMDNodes AAInfo;
144 
145     switch (II->getIntrinsicID()) {
146     case Intrinsic::lifetime_start:
147     case Intrinsic::lifetime_end:
148     case Intrinsic::invariant_start:
149       II->getAAMetadata(AAInfo);
150       Loc = MemoryLocation(
151           II->getArgOperand(1),
152           cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(), AAInfo);
153       // These intrinsics don't really modify the memory, but returning Mod
154       // will allow them to be handled conservatively.
155       return MRI_Mod;
156     case Intrinsic::invariant_end:
157       II->getAAMetadata(AAInfo);
158       Loc = MemoryLocation(
159           II->getArgOperand(2),
160           cast<ConstantInt>(II->getArgOperand(1))->getZExtValue(), AAInfo);
161       // These intrinsics don't really modify the memory, but returning Mod
162       // will allow them to be handled conservatively.
163       return MRI_Mod;
164     default:
165       break;
166     }
167   }
168 
169   // Otherwise, just do the coarse-grained thing that always works.
170   if (Inst->mayWriteToMemory())
171     return MRI_ModRef;
172   if (Inst->mayReadFromMemory())
173     return MRI_Ref;
174   return MRI_NoModRef;
175 }
176 
177 /// Private helper for finding the local dependencies of a call site.
178 MemDepResult MemoryDependenceResults::getCallSiteDependencyFrom(
179     CallSite CS, bool isReadOnlyCall, BasicBlock::iterator ScanIt,
180     BasicBlock *BB) {
181   unsigned Limit = BlockScanLimit;
182 
183   // Walk backwards through the block, looking for dependencies.
184   while (ScanIt != BB->begin()) {
185     // Limit the amount of scanning we do so we don't end up with quadratic
186     // running time on extreme testcases.
187     --Limit;
188     if (!Limit)
189       return MemDepResult::getUnknown();
190 
191     Instruction *Inst = &*--ScanIt;
192 
193     // If this inst is a memory op, get the pointer it accessed
194     MemoryLocation Loc;
195     ModRefInfo MR = GetLocation(Inst, Loc, TLI);
196     if (Loc.Ptr) {
197       // A simple instruction.
198       if (AA.getModRefInfo(CS, Loc) != MRI_NoModRef)
199         return MemDepResult::getClobber(Inst);
200       continue;
201     }
202 
203     if (auto InstCS = CallSite(Inst)) {
204       // Debug intrinsics don't cause dependences.
205       if (isa<DbgInfoIntrinsic>(Inst))
206         continue;
207       // If these two calls do not interfere, look past it.
208       switch (AA.getModRefInfo(CS, InstCS)) {
209       case MRI_NoModRef:
210         // If the two calls are the same, return InstCS as a Def, so that
211         // CS can be found redundant and eliminated.
212         if (isReadOnlyCall && !(MR & MRI_Mod) &&
213             CS.getInstruction()->isIdenticalToWhenDefined(Inst))
214           return MemDepResult::getDef(Inst);
215 
216         // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
217         // keep scanning.
218         continue;
219       default:
220         return MemDepResult::getClobber(Inst);
221       }
222     }
223 
224     // If we could not obtain a pointer for the instruction and the instruction
225     // touches memory then assume that this is a dependency.
226     if (MR != MRI_NoModRef)
227       return MemDepResult::getClobber(Inst);
228   }
229 
230   // No dependence found.  If this is the entry block of the function, it is
231   // unknown, otherwise it is non-local.
232   if (BB != &BB->getParent()->getEntryBlock())
233     return MemDepResult::getNonLocal();
234   return MemDepResult::getNonFuncLocal();
235 }
236 
237 unsigned MemoryDependenceResults::getLoadLoadClobberFullWidthSize(
238     const Value *MemLocBase, int64_t MemLocOffs, unsigned MemLocSize,
239     const LoadInst *LI) {
240   // We can only extend simple integer loads.
241   if (!isa<IntegerType>(LI->getType()) || !LI->isSimple())
242     return 0;
243 
244   // Load widening is hostile to ThreadSanitizer: it may cause false positives
245   // or make the reports more cryptic (access sizes are wrong).
246   if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
247     return 0;
248 
249   const DataLayout &DL = LI->getModule()->getDataLayout();
250 
251   // Get the base of this load.
252   int64_t LIOffs = 0;
253   const Value *LIBase =
254       GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, DL);
255 
256   // If the two pointers are not based on the same pointer, we can't tell that
257   // they are related.
258   if (LIBase != MemLocBase)
259     return 0;
260 
261   // Okay, the two values are based on the same pointer, but returned as
262   // no-alias.  This happens when we have things like two byte loads at "P+1"
263   // and "P+3".  Check to see if increasing the size of the "LI" load up to its
264   // alignment (or the largest native integer type) will allow us to load all
265   // the bits required by MemLoc.
266 
267   // If MemLoc is before LI, then no widening of LI will help us out.
268   if (MemLocOffs < LIOffs)
269     return 0;
270 
271   // Get the alignment of the load in bytes.  We assume that it is safe to load
272   // any legal integer up to this size without a problem.  For example, if we're
273   // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
274   // widen it up to an i32 load.  If it is known 2-byte aligned, we can widen it
275   // to i16.
276   unsigned LoadAlign = LI->getAlignment();
277 
278   int64_t MemLocEnd = MemLocOffs + MemLocSize;
279 
280   // If no amount of rounding up will let MemLoc fit into LI, then bail out.
281   if (LIOffs + LoadAlign < MemLocEnd)
282     return 0;
283 
284   // This is the size of the load to try.  Start with the next larger power of
285   // two.
286   unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits() / 8U;
287   NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
288 
289   while (true) {
290     // If this load size is bigger than our known alignment or would not fit
291     // into a native integer register, then we fail.
292     if (NewLoadByteSize > LoadAlign ||
293         !DL.fitsInLegalInteger(NewLoadByteSize * 8))
294       return 0;
295 
296     if (LIOffs + NewLoadByteSize > MemLocEnd &&
297         LI->getParent()->getParent()->hasFnAttribute(
298             Attribute::SanitizeAddress))
299       // We will be reading past the location accessed by the original program.
300       // While this is safe in a regular build, Address Safety analysis tools
301       // may start reporting false warnings. So, don't do widening.
302       return 0;
303 
304     // If a load of this width would include all of MemLoc, then we succeed.
305     if (LIOffs + NewLoadByteSize >= MemLocEnd)
306       return NewLoadByteSize;
307 
308     NewLoadByteSize <<= 1;
309   }
310 }
311 
312 static bool isVolatile(Instruction *Inst) {
313   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
314     return LI->isVolatile();
315   else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
316     return SI->isVolatile();
317   else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst))
318     return AI->isVolatile();
319   return false;
320 }
321 
322 MemDepResult MemoryDependenceResults::getPointerDependencyFrom(
323     const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
324     BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) {
325 
326   if (QueryInst != nullptr) {
327     if (auto *LI = dyn_cast<LoadInst>(QueryInst)) {
328       MemDepResult invariantGroupDependency =
329           getInvariantGroupPointerDependency(LI, BB);
330 
331       if (invariantGroupDependency.isDef())
332         return invariantGroupDependency;
333     }
334   }
335   return getSimplePointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst,
336                                         Limit);
337 }
338 
339 MemDepResult
340 MemoryDependenceResults::getInvariantGroupPointerDependency(LoadInst *LI,
341                                                             BasicBlock *BB) {
342 
343   auto *InvariantGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group);
344   if (!InvariantGroupMD)
345     return MemDepResult::getUnknown();
346 
347   // Take the ptr operand after all casts and geps 0. This way we can search
348   // cast graph down only.
349   Value *LoadOperand = LI->getPointerOperand()->stripPointerCasts();
350 
351   // It's is not safe to walk the use list of global value, because function
352   // passes aren't allowed to look outside their functions.
353   // FIXME: this could be fixed by filtering instructions from outside
354   // of current function.
355   if (isa<GlobalValue>(LoadOperand))
356     return MemDepResult::getUnknown();
357 
358   // Queue to process all pointers that are equivalent to load operand.
359   SmallVector<const Value *, 8> LoadOperandsQueue;
360   LoadOperandsQueue.push_back(LoadOperand);
361   while (!LoadOperandsQueue.empty()) {
362     const Value *Ptr = LoadOperandsQueue.pop_back_val();
363     assert(Ptr && !isa<GlobalValue>(Ptr) &&
364            "Null or GlobalValue should not be inserted");
365 
366     for (const Use &Us : Ptr->uses()) {
367       auto *U = dyn_cast<Instruction>(Us.getUser());
368       if (!U || U == LI || !DT.dominates(U, LI))
369         continue;
370 
371       // Bitcast or gep with zeros are using Ptr. Add to queue to check it's
372       // users.      U = bitcast Ptr
373       if (isa<BitCastInst>(U)) {
374         LoadOperandsQueue.push_back(U);
375         continue;
376       }
377       // Gep with zeros is equivalent to bitcast.
378       // FIXME: we are not sure if some bitcast should be canonicalized to gep 0
379       // or gep 0 to bitcast because of SROA, so there are 2 forms. When
380       // typeless pointers will be ready then both cases will be gone
381       // (and this BFS also won't be needed).
382       if (auto *GEP = dyn_cast<GetElementPtrInst>(U))
383         if (GEP->hasAllZeroIndices()) {
384           LoadOperandsQueue.push_back(U);
385           continue;
386         }
387 
388       // If we hit load/store with the same invariant.group metadata (and the
389       // same pointer operand) we can assume that value pointed by pointer
390       // operand didn't change.
391       if ((isa<LoadInst>(U) || isa<StoreInst>(U)) && U->getParent() == BB &&
392           U->getMetadata(LLVMContext::MD_invariant_group) == InvariantGroupMD)
393         return MemDepResult::getDef(U);
394     }
395   }
396   return MemDepResult::getUnknown();
397 }
398 
399 MemDepResult MemoryDependenceResults::getSimplePointerDependencyFrom(
400     const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
401     BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) {
402   bool isInvariantLoad = false;
403 
404   if (!Limit) {
405     unsigned DefaultLimit = BlockScanLimit;
406     return getSimplePointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst,
407                                           &DefaultLimit);
408   }
409 
410   // We must be careful with atomic accesses, as they may allow another thread
411   //   to touch this location, clobbering it. We are conservative: if the
412   //   QueryInst is not a simple (non-atomic) memory access, we automatically
413   //   return getClobber.
414   // If it is simple, we know based on the results of
415   // "Compiler testing via a theory of sound optimisations in the C11/C++11
416   //   memory model" in PLDI 2013, that a non-atomic location can only be
417   //   clobbered between a pair of a release and an acquire action, with no
418   //   access to the location in between.
419   // Here is an example for giving the general intuition behind this rule.
420   // In the following code:
421   //   store x 0;
422   //   release action; [1]
423   //   acquire action; [4]
424   //   %val = load x;
425   // It is unsafe to replace %val by 0 because another thread may be running:
426   //   acquire action; [2]
427   //   store x 42;
428   //   release action; [3]
429   // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
430   // being 42. A key property of this program however is that if either
431   // 1 or 4 were missing, there would be a race between the store of 42
432   // either the store of 0 or the load (making the whole program racy).
433   // The paper mentioned above shows that the same property is respected
434   // by every program that can detect any optimization of that kind: either
435   // it is racy (undefined) or there is a release followed by an acquire
436   // between the pair of accesses under consideration.
437 
438   // If the load is invariant, we "know" that it doesn't alias *any* write. We
439   // do want to respect mustalias results since defs are useful for value
440   // forwarding, but any mayalias write can be assumed to be noalias.
441   // Arguably, this logic should be pushed inside AliasAnalysis itself.
442   if (isLoad && QueryInst) {
443     LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
444     if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr)
445       isInvariantLoad = true;
446   }
447 
448   const DataLayout &DL = BB->getModule()->getDataLayout();
449 
450   // Create a numbered basic block to lazily compute and cache instruction
451   // positions inside a BB. This is used to provide fast queries for relative
452   // position between two instructions in a BB and can be used by
453   // AliasAnalysis::callCapturesBefore.
454   OrderedBasicBlock OBB(BB);
455 
456   // Return "true" if and only if the instruction I is either a non-simple
457   // load or a non-simple store.
458   auto isNonSimpleLoadOrStore = [](Instruction *I) -> bool {
459     if (auto *LI = dyn_cast<LoadInst>(I))
460       return !LI->isSimple();
461     if (auto *SI = dyn_cast<StoreInst>(I))
462       return !SI->isSimple();
463     return false;
464   };
465 
466   // Return "true" if I is not a load and not a store, but it does access
467   // memory.
468   auto isOtherMemAccess = [](Instruction *I) -> bool {
469     return !isa<LoadInst>(I) && !isa<StoreInst>(I) && I->mayReadOrWriteMemory();
470   };
471 
472   // Walk backwards through the basic block, looking for dependencies.
473   while (ScanIt != BB->begin()) {
474     Instruction *Inst = &*--ScanIt;
475 
476     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
477       // Debug intrinsics don't (and can't) cause dependencies.
478       if (isa<DbgInfoIntrinsic>(II))
479         continue;
480 
481     // Limit the amount of scanning we do so we don't end up with quadratic
482     // running time on extreme testcases.
483     --*Limit;
484     if (!*Limit)
485       return MemDepResult::getUnknown();
486 
487     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
488       // If we reach a lifetime begin or end marker, then the query ends here
489       // because the value is undefined.
490       if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
491         // FIXME: This only considers queries directly on the invariant-tagged
492         // pointer, not on query pointers that are indexed off of them.  It'd
493         // be nice to handle that at some point (the right approach is to use
494         // GetPointerBaseWithConstantOffset).
495         if (AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), MemLoc))
496           return MemDepResult::getDef(II);
497         continue;
498       }
499     }
500 
501     // Values depend on loads if the pointers are must aliased.  This means
502     // that a load depends on another must aliased load from the same value.
503     // One exception is atomic loads: a value can depend on an atomic load that
504     // it does not alias with when this atomic load indicates that another
505     // thread may be accessing the location.
506     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
507 
508       // While volatile access cannot be eliminated, they do not have to clobber
509       // non-aliasing locations, as normal accesses, for example, can be safely
510       // reordered with volatile accesses.
511       if (LI->isVolatile()) {
512         if (!QueryInst)
513           // Original QueryInst *may* be volatile
514           return MemDepResult::getClobber(LI);
515         if (isVolatile(QueryInst))
516           // Ordering required if QueryInst is itself volatile
517           return MemDepResult::getClobber(LI);
518         // Otherwise, volatile doesn't imply any special ordering
519       }
520 
521       // Atomic loads have complications involved.
522       // A Monotonic (or higher) load is OK if the query inst is itself not
523       // atomic.
524       // FIXME: This is overly conservative.
525       if (LI->isAtomic() && isStrongerThanUnordered(LI->getOrdering())) {
526         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
527             isOtherMemAccess(QueryInst))
528           return MemDepResult::getClobber(LI);
529         if (LI->getOrdering() != AtomicOrdering::Monotonic)
530           return MemDepResult::getClobber(LI);
531       }
532 
533       MemoryLocation LoadLoc = MemoryLocation::get(LI);
534 
535       // If we found a pointer, check if it could be the same as our pointer.
536       AliasResult R = AA.alias(LoadLoc, MemLoc);
537 
538       if (isLoad) {
539         if (R == NoAlias)
540           continue;
541 
542         // Must aliased loads are defs of each other.
543         if (R == MustAlias)
544           return MemDepResult::getDef(Inst);
545 
546 #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
547       // in terms of clobbering loads, but since it does this by looking
548       // at the clobbering load directly, it doesn't know about any
549       // phi translation that may have happened along the way.
550 
551         // If we have a partial alias, then return this as a clobber for the
552         // client to handle.
553         if (R == PartialAlias)
554           return MemDepResult::getClobber(Inst);
555 #endif
556 
557         // Random may-alias loads don't depend on each other without a
558         // dependence.
559         continue;
560       }
561 
562       // Stores don't depend on other no-aliased accesses.
563       if (R == NoAlias)
564         continue;
565 
566       // Stores don't alias loads from read-only memory.
567       if (AA.pointsToConstantMemory(LoadLoc))
568         continue;
569 
570       // Stores depend on may/must aliased loads.
571       return MemDepResult::getDef(Inst);
572     }
573 
574     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
575       // Atomic stores have complications involved.
576       // A Monotonic store is OK if the query inst is itself not atomic.
577       // FIXME: This is overly conservative.
578       if (!SI->isUnordered() && SI->isAtomic()) {
579         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
580             isOtherMemAccess(QueryInst))
581           return MemDepResult::getClobber(SI);
582         if (SI->getOrdering() != AtomicOrdering::Monotonic)
583           return MemDepResult::getClobber(SI);
584       }
585 
586       // FIXME: this is overly conservative.
587       // While volatile access cannot be eliminated, they do not have to clobber
588       // non-aliasing locations, as normal accesses can for example be reordered
589       // with volatile accesses.
590       if (SI->isVolatile())
591         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
592             isOtherMemAccess(QueryInst))
593           return MemDepResult::getClobber(SI);
594 
595       // If alias analysis can tell that this store is guaranteed to not modify
596       // the query pointer, ignore it.  Use getModRefInfo to handle cases where
597       // the query pointer points to constant memory etc.
598       if (AA.getModRefInfo(SI, MemLoc) == MRI_NoModRef)
599         continue;
600 
601       // Ok, this store might clobber the query pointer.  Check to see if it is
602       // a must alias: in this case, we want to return this as a def.
603       MemoryLocation StoreLoc = MemoryLocation::get(SI);
604 
605       // If we found a pointer, check if it could be the same as our pointer.
606       AliasResult R = AA.alias(StoreLoc, MemLoc);
607 
608       if (R == NoAlias)
609         continue;
610       if (R == MustAlias)
611         return MemDepResult::getDef(Inst);
612       if (isInvariantLoad)
613         continue;
614       return MemDepResult::getClobber(Inst);
615     }
616 
617     // If this is an allocation, and if we know that the accessed pointer is to
618     // the allocation, return Def.  This means that there is no dependence and
619     // the access can be optimized based on that.  For example, a load could
620     // turn into undef.  Note that we can bypass the allocation itself when
621     // looking for a clobber in many cases; that's an alias property and is
622     // handled by BasicAA.
623     if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, &TLI)) {
624       const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL);
625       if (AccessPtr == Inst || AA.isMustAlias(Inst, AccessPtr))
626         return MemDepResult::getDef(Inst);
627     }
628 
629     if (isInvariantLoad)
630       continue;
631 
632     // A release fence requires that all stores complete before it, but does
633     // not prevent the reordering of following loads or stores 'before' the
634     // fence.  As a result, we look past it when finding a dependency for
635     // loads.  DSE uses this to find preceeding stores to delete and thus we
636     // can't bypass the fence if the query instruction is a store.
637     if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
638       if (isLoad && FI->getOrdering() == AtomicOrdering::Release)
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 (auto *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     LLVM_FALLTHROUGH;
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; (void)GotWorklistLimit;
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 AnalysisKey MemoryDependenceAnalysis::Key;
1656 
1657 MemoryDependenceResults
1658 MemoryDependenceAnalysis::run(Function &F, FunctionAnalysisManager &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 
1681 MemoryDependenceWrapperPass::~MemoryDependenceWrapperPass() {}
1682 
1683 void MemoryDependenceWrapperPass::releaseMemory() {
1684   MemDep.reset();
1685 }
1686 
1687 void MemoryDependenceWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1688   AU.setPreservesAll();
1689   AU.addRequired<AssumptionCacheTracker>();
1690   AU.addRequired<DominatorTreeWrapperPass>();
1691   AU.addRequiredTransitive<AAResultsWrapperPass>();
1692   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
1693 }
1694 
1695 bool MemoryDependenceResults::invalidate(Function &F, const PreservedAnalyses &PA,
1696                                FunctionAnalysisManager::Invalidator &Inv) {
1697   // Check whether our analysis is preserved.
1698   auto PAC = PA.getChecker<MemoryDependenceAnalysis>();
1699   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
1700     // If not, give up now.
1701     return true;
1702 
1703   // Check whether the analyses we depend on became invalid for any reason.
1704   if (Inv.invalidate<AAManager>(F, PA) ||
1705       Inv.invalidate<AssumptionAnalysis>(F, PA) ||
1706       Inv.invalidate<DominatorTreeAnalysis>(F, PA))
1707     return true;
1708 
1709   // Otherwise this analysis result remains valid.
1710   return false;
1711 }
1712 
1713 unsigned MemoryDependenceResults::getDefaultBlockScanLimit() const {
1714   return BlockScanLimit;
1715 }
1716 
1717 bool MemoryDependenceWrapperPass::runOnFunction(Function &F) {
1718   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1719   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1720   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1721   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1722   MemDep.emplace(AA, AC, TLI, DT);
1723   return false;
1724 }
1725