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