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