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