1 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AssumptionCache.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/MemoryBuiltins.h"
24 #include "llvm/Analysis/PHITransAddr.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/PredIteratorCache.h"
33 #include "llvm/Support/Debug.h"
36 #define DEBUG_TYPE "memdep"
38 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
39 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
40 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
42 STATISTIC(NumCacheNonLocalPtr,
43 "Number of fully cached non-local ptr responses");
44 STATISTIC(NumCacheDirtyNonLocalPtr,
45 "Number of cached, but dirty, non-local ptr responses");
46 STATISTIC(NumUncacheNonLocalPtr,
47 "Number of uncached non-local ptr responses");
48 STATISTIC(NumCacheCompleteNonLocalPtr,
49 "Number of block queries that were completely cached");
51 // Limit for the number of instructions to scan in a block.
52 static const unsigned int BlockScanLimit = 100;
54 // Limit on the number of memdep results to process.
55 static const unsigned int NumResultsLimit = 100;
57 char MemoryDependenceAnalysis::ID = 0;
59 // Register this pass...
60 INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep",
61 "Memory Dependence Analysis", false, true)
62 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
63 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
64 INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep",
65 "Memory Dependence Analysis", false, true)
67 MemoryDependenceAnalysis::MemoryDependenceAnalysis()
68 : FunctionPass(ID), PredCache() {
69 initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry());
71 MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
74 /// Clean up memory in between runs
75 void MemoryDependenceAnalysis::releaseMemory() {
78 NonLocalPointerDeps.clear();
79 ReverseLocalDeps.clear();
80 ReverseNonLocalDeps.clear();
81 ReverseNonLocalPtrDeps.clear();
85 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
87 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
89 AU.addRequired<AssumptionCacheTracker>();
90 AU.addRequiredTransitive<AliasAnalysis>();
93 bool MemoryDependenceAnalysis::runOnFunction(Function &F) {
94 AA = &getAnalysis<AliasAnalysis>();
95 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
96 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
97 DL = DLP ? &DLP->getDataLayout() : nullptr;
98 DominatorTreeWrapperPass *DTWP =
99 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
100 DT = DTWP ? &DTWP->getDomTree() : nullptr;
102 PredCache.reset(new PredIteratorCache());
106 /// RemoveFromReverseMap - This is a helper function that removes Val from
107 /// 'Inst's set in ReverseMap. If the set becomes empty, remove Inst's entry.
108 template <typename KeyTy>
109 static void RemoveFromReverseMap(DenseMap<Instruction*,
110 SmallPtrSet<KeyTy, 4> > &ReverseMap,
111 Instruction *Inst, KeyTy Val) {
112 typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator
113 InstIt = ReverseMap.find(Inst);
114 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
115 bool Found = InstIt->second.erase(Val);
116 assert(Found && "Invalid reverse map!"); (void)Found;
117 if (InstIt->second.empty())
118 ReverseMap.erase(InstIt);
121 /// GetLocation - If the given instruction references a specific memory
122 /// location, fill in Loc with the details, otherwise set Loc.Ptr to null.
123 /// Return a ModRefInfo value describing the general behavior of the
126 AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst,
127 AliasAnalysis::Location &Loc,
129 if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
130 if (LI->isUnordered()) {
131 Loc = AA->getLocation(LI);
132 return AliasAnalysis::Ref;
134 if (LI->getOrdering() == Monotonic) {
135 Loc = AA->getLocation(LI);
136 return AliasAnalysis::ModRef;
138 Loc = AliasAnalysis::Location();
139 return AliasAnalysis::ModRef;
142 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
143 if (SI->isUnordered()) {
144 Loc = AA->getLocation(SI);
145 return AliasAnalysis::Mod;
147 if (SI->getOrdering() == Monotonic) {
148 Loc = AA->getLocation(SI);
149 return AliasAnalysis::ModRef;
151 Loc = AliasAnalysis::Location();
152 return AliasAnalysis::ModRef;
155 if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
156 Loc = AA->getLocation(V);
157 return AliasAnalysis::ModRef;
160 if (const CallInst *CI = isFreeCall(Inst, AA->getTargetLibraryInfo())) {
161 // calls to free() deallocate the entire structure
162 Loc = AliasAnalysis::Location(CI->getArgOperand(0));
163 return AliasAnalysis::Mod;
166 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
169 switch (II->getIntrinsicID()) {
170 case Intrinsic::lifetime_start:
171 case Intrinsic::lifetime_end:
172 case Intrinsic::invariant_start:
173 II->getAAMetadata(AAInfo);
174 Loc = AliasAnalysis::Location(II->getArgOperand(1),
175 cast<ConstantInt>(II->getArgOperand(0))
176 ->getZExtValue(), AAInfo);
177 // These intrinsics don't really modify the memory, but returning Mod
178 // will allow them to be handled conservatively.
179 return AliasAnalysis::Mod;
180 case Intrinsic::invariant_end:
181 II->getAAMetadata(AAInfo);
182 Loc = AliasAnalysis::Location(II->getArgOperand(2),
183 cast<ConstantInt>(II->getArgOperand(1))
184 ->getZExtValue(), AAInfo);
185 // These intrinsics don't really modify the memory, but returning Mod
186 // will allow them to be handled conservatively.
187 return AliasAnalysis::Mod;
193 // Otherwise, just do the coarse-grained thing that always works.
194 if (Inst->mayWriteToMemory())
195 return AliasAnalysis::ModRef;
196 if (Inst->mayReadFromMemory())
197 return AliasAnalysis::Ref;
198 return AliasAnalysis::NoModRef;
201 /// getCallSiteDependencyFrom - Private helper for finding the local
202 /// dependencies of a call site.
203 MemDepResult MemoryDependenceAnalysis::
204 getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
205 BasicBlock::iterator ScanIt, BasicBlock *BB) {
206 unsigned Limit = BlockScanLimit;
208 // Walk backwards through the block, looking for dependencies
209 while (ScanIt != BB->begin()) {
210 // Limit the amount of scanning we do so we don't end up with quadratic
211 // running time on extreme testcases.
214 return MemDepResult::getUnknown();
216 Instruction *Inst = --ScanIt;
218 // If this inst is a memory op, get the pointer it accessed
219 AliasAnalysis::Location Loc;
220 AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA);
222 // A simple instruction.
223 if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef)
224 return MemDepResult::getClobber(Inst);
228 if (CallSite InstCS = cast<Value>(Inst)) {
229 // Debug intrinsics don't cause dependences.
230 if (isa<DbgInfoIntrinsic>(Inst)) continue;
231 // If these two calls do not interfere, look past it.
232 switch (AA->getModRefInfo(CS, InstCS)) {
233 case AliasAnalysis::NoModRef:
234 // If the two calls are the same, return InstCS as a Def, so that
235 // CS can be found redundant and eliminated.
236 if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) &&
237 CS.getInstruction()->isIdenticalToWhenDefined(Inst))
238 return MemDepResult::getDef(Inst);
240 // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
244 return MemDepResult::getClobber(Inst);
248 // If we could not obtain a pointer for the instruction and the instruction
249 // touches memory then assume that this is a dependency.
250 if (MR != AliasAnalysis::NoModRef)
251 return MemDepResult::getClobber(Inst);
254 // No dependence found. If this is the entry block of the function, it is
255 // unknown, otherwise it is non-local.
256 if (BB != &BB->getParent()->getEntryBlock())
257 return MemDepResult::getNonLocal();
258 return MemDepResult::getNonFuncLocal();
261 /// isLoadLoadClobberIfExtendedToFullWidth - Return true if LI is a load that
262 /// would fully overlap MemLoc if done as a wider legal integer load.
264 /// MemLocBase, MemLocOffset are lazily computed here the first time the
265 /// base/offs of memloc is needed.
267 isLoadLoadClobberIfExtendedToFullWidth(const AliasAnalysis::Location &MemLoc,
268 const Value *&MemLocBase,
271 const DataLayout *DL) {
272 // If we have no target data, we can't do this.
273 if (!DL) return false;
275 // If we haven't already computed the base/offset of MemLoc, do so now.
277 MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, DL);
279 unsigned Size = MemoryDependenceAnalysis::
280 getLoadLoadClobberFullWidthSize(MemLocBase, MemLocOffs, MemLoc.Size,
285 /// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
286 /// looks at a memory location for a load (specified by MemLocBase, Offs,
287 /// and Size) and compares it against a load. If the specified load could
288 /// be safely widened to a larger integer load that is 1) still efficient,
289 /// 2) safe for the target, and 3) would provide the specified memory
290 /// location value, then this function returns the size in bytes of the
291 /// load width to use. If not, this returns zero.
292 unsigned MemoryDependenceAnalysis::
293 getLoadLoadClobberFullWidthSize(const Value *MemLocBase, int64_t MemLocOffs,
294 unsigned MemLocSize, const LoadInst *LI,
295 const DataLayout &DL) {
296 // We can only extend simple integer loads.
297 if (!isa<IntegerType>(LI->getType()) || !LI->isSimple()) return 0;
299 // Load widening is hostile to ThreadSanitizer: it may cause false positives
300 // or make the reports more cryptic (access sizes are wrong).
301 if (LI->getParent()->getParent()->getAttributes().
302 hasAttribute(AttributeSet::FunctionIndex, Attribute::SanitizeThread))
305 // Get the base of this load.
307 const Value *LIBase =
308 GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, &DL);
310 // If the two pointers are not based on the same pointer, we can't tell that
312 if (LIBase != MemLocBase) return 0;
314 // Okay, the two values are based on the same pointer, but returned as
315 // no-alias. This happens when we have things like two byte loads at "P+1"
316 // and "P+3". Check to see if increasing the size of the "LI" load up to its
317 // alignment (or the largest native integer type) will allow us to load all
318 // the bits required by MemLoc.
320 // If MemLoc is before LI, then no widening of LI will help us out.
321 if (MemLocOffs < LIOffs) return 0;
323 // Get the alignment of the load in bytes. We assume that it is safe to load
324 // any legal integer up to this size without a problem. For example, if we're
325 // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
326 // widen it up to an i32 load. If it is known 2-byte aligned, we can widen it
328 unsigned LoadAlign = LI->getAlignment();
330 int64_t MemLocEnd = MemLocOffs+MemLocSize;
332 // If no amount of rounding up will let MemLoc fit into LI, then bail out.
333 if (LIOffs+LoadAlign < MemLocEnd) return 0;
335 // This is the size of the load to try. Start with the next larger power of
337 unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits()/8U;
338 NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
341 // If this load size is bigger than our known alignment or would not fit
342 // into a native integer register, then we fail.
343 if (NewLoadByteSize > LoadAlign ||
344 !DL.fitsInLegalInteger(NewLoadByteSize*8))
347 if (LIOffs+NewLoadByteSize > MemLocEnd &&
348 LI->getParent()->getParent()->getAttributes().
349 hasAttribute(AttributeSet::FunctionIndex, Attribute::SanitizeAddress))
350 // We will be reading past the location accessed by the original program.
351 // While this is safe in a regular build, Address Safety analysis tools
352 // may start reporting false warnings. So, don't do widening.
355 // If a load of this width would include all of MemLoc, then we succeed.
356 if (LIOffs+NewLoadByteSize >= MemLocEnd)
357 return NewLoadByteSize;
359 NewLoadByteSize <<= 1;
363 static bool isVolatile(Instruction *Inst) {
364 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
365 return LI->isVolatile();
366 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
367 return SI->isVolatile();
368 else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst))
369 return AI->isVolatile();
374 /// getPointerDependencyFrom - Return the instruction on which a memory
375 /// location depends. If isLoad is true, this routine ignores may-aliases with
376 /// read-only operations. If isLoad is false, this routine ignores may-aliases
377 /// with reads from read-only locations. If possible, pass the query
378 /// instruction as well; this function may take advantage of the metadata
379 /// annotated to the query instruction to refine the result.
380 MemDepResult MemoryDependenceAnalysis::
381 getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad,
382 BasicBlock::iterator ScanIt, BasicBlock *BB,
383 Instruction *QueryInst) {
385 const Value *MemLocBase = nullptr;
386 int64_t MemLocOffset = 0;
387 unsigned Limit = BlockScanLimit;
388 bool isInvariantLoad = false;
390 // We must be careful with atomic accesses, as they may allow another thread
391 // to touch this location, cloberring it. We are conservative: if the
392 // QueryInst is not a simple (non-atomic) memory access, we automatically
393 // return getClobber.
394 // If it is simple, we know based on the results of
395 // "Compiler testing via a theory of sound optimisations in the C11/C++11
396 // memory model" in PLDI 2013, that a non-atomic location can only be
397 // clobbered between a pair of a release and an acquire action, with no
398 // access to the location in between.
399 // Here is an example for giving the general intuition behind this rule.
400 // In the following code:
402 // release action; [1]
403 // acquire action; [4]
405 // It is unsafe to replace %val by 0 because another thread may be running:
406 // acquire action; [2]
408 // release action; [3]
409 // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
410 // being 42. A key property of this program however is that if either
411 // 1 or 4 were missing, there would be a race between the store of 42
412 // either the store of 0 or the load (making the whole progam racy).
413 // The paper mentionned above shows that the same property is respected
414 // by every program that can detect any optimisation of that kind: either
415 // it is racy (undefined) or there is a release followed by an acquire
416 // between the pair of accesses under consideration.
417 bool HasSeenAcquire = false;
419 if (isLoad && QueryInst) {
420 LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
421 if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr)
422 isInvariantLoad = true;
425 // Walk backwards through the basic block, looking for dependencies.
426 while (ScanIt != BB->begin()) {
427 Instruction *Inst = --ScanIt;
429 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
430 // Debug intrinsics don't (and can't) cause dependencies.
431 if (isa<DbgInfoIntrinsic>(II)) continue;
433 // Limit the amount of scanning we do so we don't end up with quadratic
434 // running time on extreme testcases.
437 return MemDepResult::getUnknown();
439 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
440 // If we reach a lifetime begin or end marker, then the query ends here
441 // because the value is undefined.
442 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
443 // FIXME: This only considers queries directly on the invariant-tagged
444 // pointer, not on query pointers that are indexed off of them. It'd
445 // be nice to handle that at some point (the right approach is to use
446 // GetPointerBaseWithConstantOffset).
447 if (AA->isMustAlias(AliasAnalysis::Location(II->getArgOperand(1)),
449 return MemDepResult::getDef(II);
454 // Values depend on loads if the pointers are must aliased. This means that
455 // a load depends on another must aliased load from the same value.
456 // One exception is atomic loads: a value can depend on an atomic load that it
457 // does not alias with when this atomic load indicates that another thread may
458 // be accessing the location.
459 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
461 // While volatile access cannot be eliminated, they do not have to clobber
462 // non-aliasing locations, as normal accesses, for example, can be safely
463 // reordered with volatile accesses.
464 if (LI->isVolatile()) {
466 // Original QueryInst *may* be volatile
467 return MemDepResult::getClobber(LI);
468 if (isVolatile(QueryInst))
469 // Ordering required if QueryInst is itself volatile
470 return MemDepResult::getClobber(LI);
471 // Otherwise, volatile doesn't imply any special ordering
474 // Atomic loads have complications involved.
475 // A Monotonic (or higher) load is OK if the query inst is itself not atomic.
476 // An Acquire (or higher) load sets the HasSeenAcquire flag, so that any
477 // release store will know to return getClobber.
478 // FIXME: This is overly conservative.
479 if (LI->isAtomic() && LI->getOrdering() > Unordered) {
481 return MemDepResult::getClobber(LI);
482 if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst)) {
483 if (!QueryLI->isSimple())
484 return MemDepResult::getClobber(LI);
485 } else if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst)) {
486 if (!QuerySI->isSimple())
487 return MemDepResult::getClobber(LI);
488 } else if (QueryInst->mayReadOrWriteMemory()) {
489 return MemDepResult::getClobber(LI);
492 if (isAtLeastAcquire(LI->getOrdering()))
493 HasSeenAcquire = true;
496 AliasAnalysis::Location LoadLoc = AA->getLocation(LI);
498 // If we found a pointer, check if it could be the same as our pointer.
499 AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc);
502 if (R == AliasAnalysis::NoAlias) {
503 // If this is an over-aligned integer load (for example,
504 // "load i8* %P, align 4") see if it would obviously overlap with the
505 // queried location if widened to a larger load (e.g. if the queried
506 // location is 1 byte at P+1). If so, return it as a load/load
507 // clobber result, allowing the client to decide to widen the load if
509 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType()))
510 if (LI->getAlignment()*8 > ITy->getPrimitiveSizeInBits() &&
511 isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase,
512 MemLocOffset, LI, DL))
513 return MemDepResult::getClobber(Inst);
518 // Must aliased loads are defs of each other.
519 if (R == AliasAnalysis::MustAlias)
520 return MemDepResult::getDef(Inst);
522 #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
523 // in terms of clobbering loads, but since it does this by looking
524 // at the clobbering load directly, it doesn't know about any
525 // phi translation that may have happened along the way.
527 // If we have a partial alias, then return this as a clobber for the
529 if (R == AliasAnalysis::PartialAlias)
530 return MemDepResult::getClobber(Inst);
533 // Random may-alias loads don't depend on each other without a
538 // Stores don't depend on other no-aliased accesses.
539 if (R == AliasAnalysis::NoAlias)
542 // Stores don't alias loads from read-only memory.
543 if (AA->pointsToConstantMemory(LoadLoc))
546 // Stores depend on may/must aliased loads.
547 return MemDepResult::getDef(Inst);
550 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
551 // Atomic stores have complications involved.
552 // A Monotonic store is OK if the query inst is itself not atomic.
553 // A Release (or higher) store further requires that no acquire load
555 // FIXME: This is overly conservative.
556 if (!SI->isUnordered()) {
558 return MemDepResult::getClobber(SI);
559 if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst)) {
560 if (!QueryLI->isSimple())
561 return MemDepResult::getClobber(SI);
562 } else if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst)) {
563 if (!QuerySI->isSimple())
564 return MemDepResult::getClobber(SI);
565 } else if (QueryInst->mayReadOrWriteMemory()) {
566 return MemDepResult::getClobber(SI);
569 if (HasSeenAcquire && isAtLeastRelease(SI->getOrdering()))
570 return MemDepResult::getClobber(SI);
573 // FIXME: this is overly conservative.
574 // While volatile access cannot be eliminated, they do not have to clobber
575 // non-aliasing locations, as normal accesses can for example be reordered
576 // with volatile accesses.
577 if (SI->isVolatile())
578 return MemDepResult::getClobber(SI);
580 // If alias analysis can tell that this store is guaranteed to not modify
581 // the query pointer, ignore it. Use getModRefInfo to handle cases where
582 // the query pointer points to constant memory etc.
583 if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
586 // Ok, this store might clobber the query pointer. Check to see if it is
587 // a must alias: in this case, we want to return this as a def.
588 AliasAnalysis::Location StoreLoc = AA->getLocation(SI);
590 // If we found a pointer, check if it could be the same as our pointer.
591 AliasAnalysis::AliasResult R = AA->alias(StoreLoc, MemLoc);
593 if (R == AliasAnalysis::NoAlias)
595 if (R == AliasAnalysis::MustAlias)
596 return MemDepResult::getDef(Inst);
599 return MemDepResult::getClobber(Inst);
602 // If this is an allocation, and if we know that the accessed pointer is to
603 // the allocation, return Def. This means that there is no dependence and
604 // the access can be optimized based on that. For example, a load could
606 // Note: Only determine this to be a malloc if Inst is the malloc call, not
607 // a subsequent bitcast of the malloc call result. There can be stores to
608 // the malloced memory between the malloc call and its bitcast uses, and we
609 // need to continue scanning until the malloc call.
610 const TargetLibraryInfo *TLI = AA->getTargetLibraryInfo();
611 if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, TLI)) {
612 const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL);
614 if (AccessPtr == Inst || AA->isMustAlias(Inst, AccessPtr))
615 return MemDepResult::getDef(Inst);
616 // Be conservative if the accessed pointer may alias the allocation.
617 if (AA->alias(Inst, AccessPtr) != AliasAnalysis::NoAlias)
618 return MemDepResult::getClobber(Inst);
619 // If the allocation is not aliased and does not read memory (like
620 // strdup), it is safe to ignore.
621 if (isa<AllocaInst>(Inst) ||
622 isMallocLikeFn(Inst, TLI) || isCallocLikeFn(Inst, TLI))
626 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
627 AliasAnalysis::ModRefResult MR = AA->getModRefInfo(Inst, MemLoc);
628 // If necessary, perform additional analysis.
629 if (MR == AliasAnalysis::ModRef)
630 MR = AA->callCapturesBefore(Inst, MemLoc, DT);
632 case AliasAnalysis::NoModRef:
633 // If the call has no effect on the queried pointer, just ignore it.
635 case AliasAnalysis::Mod:
636 return MemDepResult::getClobber(Inst);
637 case AliasAnalysis::Ref:
638 // If the call is known to never store to the pointer, and if this is a
639 // load query, we can safely ignore it (scan past it).
643 // Otherwise, there is a potential dependence. Return a clobber.
644 return MemDepResult::getClobber(Inst);
648 // No dependence found. If this is the entry block of the function, it is
649 // unknown, otherwise it is non-local.
650 if (BB != &BB->getParent()->getEntryBlock())
651 return MemDepResult::getNonLocal();
652 return MemDepResult::getNonFuncLocal();
655 /// getDependency - Return the instruction on which a memory operation
657 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
658 Instruction *ScanPos = QueryInst;
660 // Check for a cached result
661 MemDepResult &LocalCache = LocalDeps[QueryInst];
663 // If the cached entry is non-dirty, just return it. Note that this depends
664 // on MemDepResult's default constructing to 'dirty'.
665 if (!LocalCache.isDirty())
668 // Otherwise, if we have a dirty entry, we know we can start the scan at that
669 // instruction, which may save us some work.
670 if (Instruction *Inst = LocalCache.getInst()) {
673 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
676 BasicBlock *QueryParent = QueryInst->getParent();
679 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
680 // No dependence found. If this is the entry block of the function, it is
681 // unknown, otherwise it is non-local.
682 if (QueryParent != &QueryParent->getParent()->getEntryBlock())
683 LocalCache = MemDepResult::getNonLocal();
685 LocalCache = MemDepResult::getNonFuncLocal();
687 AliasAnalysis::Location MemLoc;
688 AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
690 // If we can do a pointer scan, make it happen.
691 bool isLoad = !(MR & AliasAnalysis::Mod);
692 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
693 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
695 LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
696 QueryParent, QueryInst);
697 } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
698 CallSite QueryCS(QueryInst);
699 bool isReadOnly = AA->onlyReadsMemory(QueryCS);
700 LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
703 // Non-memory instruction.
704 LocalCache = MemDepResult::getUnknown();
707 // Remember the result!
708 if (Instruction *I = LocalCache.getInst())
709 ReverseLocalDeps[I].insert(QueryInst);
715 /// AssertSorted - This method is used when -debug is specified to verify that
716 /// cache arrays are properly kept sorted.
717 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
719 if (Count == -1) Count = Cache.size();
720 if (Count == 0) return;
722 for (unsigned i = 1; i != unsigned(Count); ++i)
723 assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
727 /// getNonLocalCallDependency - Perform a full dependency query for the
728 /// specified call, returning the set of blocks that the value is
729 /// potentially live across. The returned set of results will include a
730 /// "NonLocal" result for all blocks where the value is live across.
732 /// This method assumes the instruction returns a "NonLocal" dependency
733 /// within its own block.
735 /// This returns a reference to an internal data structure that may be
736 /// invalidated on the next non-local query or when an instruction is
737 /// removed. Clients must copy this data if they want it around longer than
739 const MemoryDependenceAnalysis::NonLocalDepInfo &
740 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
741 assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
742 "getNonLocalCallDependency should only be used on calls with non-local deps!");
743 PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
744 NonLocalDepInfo &Cache = CacheP.first;
746 /// DirtyBlocks - This is the set of blocks that need to be recomputed. In
747 /// the cached case, this can happen due to instructions being deleted etc. In
748 /// the uncached case, this starts out as the set of predecessors we care
750 SmallVector<BasicBlock*, 32> DirtyBlocks;
752 if (!Cache.empty()) {
753 // Okay, we have a cache entry. If we know it is not dirty, just return it
754 // with no computation.
755 if (!CacheP.second) {
760 // If we already have a partially computed set of results, scan them to
761 // determine what is dirty, seeding our initial DirtyBlocks worklist.
762 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
764 if (I->getResult().isDirty())
765 DirtyBlocks.push_back(I->getBB());
767 // Sort the cache so that we can do fast binary search lookups below.
768 std::sort(Cache.begin(), Cache.end());
770 ++NumCacheDirtyNonLocal;
771 //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
772 // << Cache.size() << " cached: " << *QueryInst;
774 // Seed DirtyBlocks with each of the preds of QueryInst's block.
775 BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
776 for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
777 DirtyBlocks.push_back(*PI);
778 ++NumUncacheNonLocal;
781 // isReadonlyCall - If this is a read-only call, we can be more aggressive.
782 bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
784 SmallPtrSet<BasicBlock*, 64> Visited;
786 unsigned NumSortedEntries = Cache.size();
787 DEBUG(AssertSorted(Cache));
789 // Iterate while we still have blocks to update.
790 while (!DirtyBlocks.empty()) {
791 BasicBlock *DirtyBB = DirtyBlocks.back();
792 DirtyBlocks.pop_back();
794 // Already processed this block?
795 if (!Visited.insert(DirtyBB).second)
798 // Do a binary search to see if we already have an entry for this block in
799 // the cache set. If so, find it.
800 DEBUG(AssertSorted(Cache, NumSortedEntries));
801 NonLocalDepInfo::iterator Entry =
802 std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
803 NonLocalDepEntry(DirtyBB));
804 if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
807 NonLocalDepEntry *ExistingResult = nullptr;
808 if (Entry != Cache.begin()+NumSortedEntries &&
809 Entry->getBB() == DirtyBB) {
810 // If we already have an entry, and if it isn't already dirty, the block
812 if (!Entry->getResult().isDirty())
815 // Otherwise, remember this slot so we can update the value.
816 ExistingResult = &*Entry;
819 // If the dirty entry has a pointer, start scanning from it so we don't have
820 // to rescan the entire block.
821 BasicBlock::iterator ScanPos = DirtyBB->end();
822 if (ExistingResult) {
823 if (Instruction *Inst = ExistingResult->getResult().getInst()) {
825 // We're removing QueryInst's use of Inst.
826 RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
827 QueryCS.getInstruction());
831 // Find out if this block has a local dependency for QueryInst.
834 if (ScanPos != DirtyBB->begin()) {
835 Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
836 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
837 // No dependence found. If this is the entry block of the function, it is
838 // a clobber, otherwise it is unknown.
839 Dep = MemDepResult::getNonLocal();
841 Dep = MemDepResult::getNonFuncLocal();
844 // If we had a dirty entry for the block, update it. Otherwise, just add
847 ExistingResult->setResult(Dep);
849 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
851 // If the block has a dependency (i.e. it isn't completely transparent to
852 // the value), remember the association!
853 if (!Dep.isNonLocal()) {
854 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
855 // update this when we remove instructions.
856 if (Instruction *Inst = Dep.getInst())
857 ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
860 // If the block *is* completely transparent to the load, we need to check
861 // the predecessors of this block. Add them to our worklist.
862 for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
863 DirtyBlocks.push_back(*PI);
870 /// getNonLocalPointerDependency - Perform a full dependency query for an
871 /// access to the specified (non-volatile) memory location, returning the
872 /// set of instructions that either define or clobber the value.
874 /// This method assumes the pointer has a "NonLocal" dependency within its
877 void MemoryDependenceAnalysis::
878 getNonLocalPointerDependency(Instruction *QueryInst,
879 SmallVectorImpl<NonLocalDepResult> &Result) {
881 auto getLocation = [](AliasAnalysis *AA, Instruction *Inst) {
882 if (auto *I = dyn_cast<LoadInst>(Inst))
883 return AA->getLocation(I);
884 else if (auto *I = dyn_cast<StoreInst>(Inst))
885 return AA->getLocation(I);
886 else if (auto *I = dyn_cast<VAArgInst>(Inst))
887 return AA->getLocation(I);
888 else if (auto *I = dyn_cast<AtomicCmpXchgInst>(Inst))
889 return AA->getLocation(I);
890 else if (auto *I = dyn_cast<AtomicRMWInst>(Inst))
891 return AA->getLocation(I);
893 llvm_unreachable("unsupported memory instruction");
896 const AliasAnalysis::Location Loc = getLocation(AA, QueryInst);
897 bool isLoad = isa<LoadInst>(QueryInst);
898 BasicBlock *FromBB = QueryInst->getParent();
901 assert(Loc.Ptr->getType()->isPointerTy() &&
902 "Can't get pointer deps of a non-pointer!");
905 // This routine does not expect to deal with volatile instructions.
906 // Doing so would require piping through the QueryInst all the way through.
907 // TODO: volatiles can't be elided, but they can be reordered with other
908 // non-volatile accesses.
910 // We currently give up on any instruction which is ordered, but we do handle
911 // atomic instructions which are unordered.
912 // TODO: Handle ordered instructions
913 auto isOrdered = [](Instruction *Inst) {
914 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
915 return !LI->isUnordered();
916 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
917 return !SI->isUnordered();
921 if (isVolatile(QueryInst) || isOrdered(QueryInst)) {
922 Result.push_back(NonLocalDepResult(FromBB,
923 MemDepResult::getUnknown(),
924 const_cast<Value *>(Loc.Ptr)));
929 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, AC);
931 // This is the set of blocks we've inspected, and the pointer we consider in
932 // each block. Because of critical edges, we currently bail out if querying
933 // a block with multiple different pointers. This can happen during PHI
935 DenseMap<BasicBlock*, Value*> Visited;
936 if (!getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
937 Result, Visited, true))
940 Result.push_back(NonLocalDepResult(FromBB,
941 MemDepResult::getUnknown(),
942 const_cast<Value *>(Loc.Ptr)));
945 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
946 /// Pointer/PointeeSize using either cached information in Cache or by doing a
947 /// lookup (which may use dirty cache info if available). If we do a lookup,
948 /// add the result to the cache.
949 MemDepResult MemoryDependenceAnalysis::
950 GetNonLocalInfoForBlock(Instruction *QueryInst,
951 const AliasAnalysis::Location &Loc,
952 bool isLoad, BasicBlock *BB,
953 NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
955 // Do a binary search to see if we already have an entry for this block in
956 // the cache set. If so, find it.
957 NonLocalDepInfo::iterator Entry =
958 std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
959 NonLocalDepEntry(BB));
960 if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
963 NonLocalDepEntry *ExistingResult = nullptr;
964 if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
965 ExistingResult = &*Entry;
967 // If we have a cached entry, and it is non-dirty, use it as the value for
969 if (ExistingResult && !ExistingResult->getResult().isDirty()) {
970 ++NumCacheNonLocalPtr;
971 return ExistingResult->getResult();
974 // Otherwise, we have to scan for the value. If we have a dirty cache
975 // entry, start scanning from its position, otherwise we scan from the end
977 BasicBlock::iterator ScanPos = BB->end();
978 if (ExistingResult && ExistingResult->getResult().getInst()) {
979 assert(ExistingResult->getResult().getInst()->getParent() == BB &&
980 "Instruction invalidated?");
981 ++NumCacheDirtyNonLocalPtr;
982 ScanPos = ExistingResult->getResult().getInst();
984 // Eliminating the dirty entry from 'Cache', so update the reverse info.
985 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
986 RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
988 ++NumUncacheNonLocalPtr;
991 // Scan the block for the dependency.
992 MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB,
995 // If we had a dirty entry for the block, update it. Otherwise, just add
998 ExistingResult->setResult(Dep);
1000 Cache->push_back(NonLocalDepEntry(BB, Dep));
1002 // If the block has a dependency (i.e. it isn't completely transparent to
1003 // the value), remember the reverse association because we just added it
1005 if (!Dep.isDef() && !Dep.isClobber())
1008 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
1009 // update MemDep when we remove instructions.
1010 Instruction *Inst = Dep.getInst();
1011 assert(Inst && "Didn't depend on anything?");
1012 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
1013 ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
1017 /// SortNonLocalDepInfoCache - Sort the NonLocalDepInfo cache, given a certain
1018 /// number of elements in the array that are already properly ordered. This is
1019 /// optimized for the case when only a few entries are added.
1021 SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
1022 unsigned NumSortedEntries) {
1023 switch (Cache.size() - NumSortedEntries) {
1025 // done, no new entries.
1028 // Two new entries, insert the last one into place.
1029 NonLocalDepEntry Val = Cache.back();
1031 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
1032 std::upper_bound(Cache.begin(), Cache.end()-1, Val);
1033 Cache.insert(Entry, Val);
1037 // One new entry, Just insert the new value at the appropriate position.
1038 if (Cache.size() != 1) {
1039 NonLocalDepEntry Val = Cache.back();
1041 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
1042 std::upper_bound(Cache.begin(), Cache.end(), Val);
1043 Cache.insert(Entry, Val);
1047 // Added many values, do a full scale sort.
1048 std::sort(Cache.begin(), Cache.end());
1053 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
1054 /// pointer/pointeesize starting at the end of StartBB. Add any clobber/def
1055 /// results to the results vector and keep track of which blocks are visited in
1058 /// This has special behavior for the first block queries (when SkipFirstBlock
1059 /// is true). In this special case, it ignores the contents of the specified
1060 /// block and starts returning dependence info for its predecessors.
1062 /// This function returns false on success, or true to indicate that it could
1063 /// not compute dependence information for some reason. This should be treated
1064 /// as a clobber dependence on the first instruction in the predecessor block.
1065 bool MemoryDependenceAnalysis::
1066 getNonLocalPointerDepFromBB(Instruction *QueryInst,
1067 const PHITransAddr &Pointer,
1068 const AliasAnalysis::Location &Loc,
1069 bool isLoad, BasicBlock *StartBB,
1070 SmallVectorImpl<NonLocalDepResult> &Result,
1071 DenseMap<BasicBlock*, Value*> &Visited,
1072 bool SkipFirstBlock) {
1073 // Look up the cached info for Pointer.
1074 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
1076 // Set up a temporary NLPI value. If the map doesn't yet have an entry for
1077 // CacheKey, this value will be inserted as the associated value. Otherwise,
1078 // it'll be ignored, and we'll have to check to see if the cached size and
1079 // aa tags are consistent with the current query.
1080 NonLocalPointerInfo InitialNLPI;
1081 InitialNLPI.Size = Loc.Size;
1082 InitialNLPI.AATags = Loc.AATags;
1084 // Get the NLPI for CacheKey, inserting one into the map if it doesn't
1085 // already have one.
1086 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
1087 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
1088 NonLocalPointerInfo *CacheInfo = &Pair.first->second;
1090 // If we already have a cache entry for this CacheKey, we may need to do some
1091 // work to reconcile the cache entry and the current query.
1093 if (CacheInfo->Size < Loc.Size) {
1094 // The query's Size is greater than the cached one. Throw out the
1095 // cached data and proceed with the query at the greater size.
1096 CacheInfo->Pair = BBSkipFirstBlockPair();
1097 CacheInfo->Size = Loc.Size;
1098 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
1099 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
1100 if (Instruction *Inst = DI->getResult().getInst())
1101 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1102 CacheInfo->NonLocalDeps.clear();
1103 } else if (CacheInfo->Size > Loc.Size) {
1104 // This query's Size is less than the cached one. Conservatively restart
1105 // the query using the greater size.
1106 return getNonLocalPointerDepFromBB(QueryInst, Pointer,
1107 Loc.getWithNewSize(CacheInfo->Size),
1108 isLoad, StartBB, Result, Visited,
1112 // If the query's AATags are inconsistent with the cached one,
1113 // conservatively throw out the cached data and restart the query with
1114 // no tag if needed.
1115 if (CacheInfo->AATags != Loc.AATags) {
1116 if (CacheInfo->AATags) {
1117 CacheInfo->Pair = BBSkipFirstBlockPair();
1118 CacheInfo->AATags = AAMDNodes();
1119 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
1120 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
1121 if (Instruction *Inst = DI->getResult().getInst())
1122 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1123 CacheInfo->NonLocalDeps.clear();
1126 return getNonLocalPointerDepFromBB(QueryInst,
1127 Pointer, Loc.getWithoutAATags(),
1128 isLoad, StartBB, Result, Visited,
1133 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
1135 // If we have valid cached information for exactly the block we are
1136 // investigating, just return it with no recomputation.
1137 if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
1138 // We have a fully cached result for this query then we can just return the
1139 // cached results and populate the visited set. However, we have to verify
1140 // that we don't already have conflicting results for these blocks. Check
1141 // to ensure that if a block in the results set is in the visited set that
1142 // it was for the same pointer query.
1143 if (!Visited.empty()) {
1144 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
1146 DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
1147 if (VI == Visited.end() || VI->second == Pointer.getAddr())
1150 // We have a pointer mismatch in a block. Just return clobber, saying
1151 // that something was clobbered in this result. We could also do a
1152 // non-fully cached query, but there is little point in doing this.
1157 Value *Addr = Pointer.getAddr();
1158 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
1160 Visited.insert(std::make_pair(I->getBB(), Addr));
1161 if (I->getResult().isNonLocal()) {
1166 Result.push_back(NonLocalDepResult(I->getBB(),
1167 MemDepResult::getUnknown(),
1169 } else if (DT->isReachableFromEntry(I->getBB())) {
1170 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
1173 ++NumCacheCompleteNonLocalPtr;
1177 // Otherwise, either this is a new block, a block with an invalid cache
1178 // pointer or one that we're about to invalidate by putting more info into it
1179 // than its valid cache info. If empty, the result will be valid cache info,
1180 // otherwise it isn't.
1182 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
1184 CacheInfo->Pair = BBSkipFirstBlockPair();
1186 SmallVector<BasicBlock*, 32> Worklist;
1187 Worklist.push_back(StartBB);
1189 // PredList used inside loop.
1190 SmallVector<std::pair<BasicBlock*, PHITransAddr>, 16> PredList;
1192 // Keep track of the entries that we know are sorted. Previously cached
1193 // entries will all be sorted. The entries we add we only sort on demand (we
1194 // don't insert every element into its sorted position). We know that we
1195 // won't get any reuse from currently inserted values, because we don't
1196 // revisit blocks after we insert info for them.
1197 unsigned NumSortedEntries = Cache->size();
1198 DEBUG(AssertSorted(*Cache));
1200 while (!Worklist.empty()) {
1201 BasicBlock *BB = Worklist.pop_back_val();
1203 // If we do process a large number of blocks it becomes very expensive and
1204 // likely it isn't worth worrying about
1205 if (Result.size() > NumResultsLimit) {
1207 // Sort it now (if needed) so that recursive invocations of
1208 // getNonLocalPointerDepFromBB and other routines that could reuse the
1209 // cache value will only see properly sorted cache arrays.
1210 if (Cache && NumSortedEntries != Cache->size()) {
1211 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1213 // Since we bail out, the "Cache" set won't contain all of the
1214 // results for the query. This is ok (we can still use it to accelerate
1215 // specific block queries) but we can't do the fastpath "return all
1216 // results from the set". Clear out the indicator for this.
1217 CacheInfo->Pair = BBSkipFirstBlockPair();
1221 // Skip the first block if we have it.
1222 if (!SkipFirstBlock) {
1223 // Analyze the dependency of *Pointer in FromBB. See if we already have
1225 assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
1227 // Get the dependency info for Pointer in BB. If we have cached
1228 // information, we will use it, otherwise we compute it.
1229 DEBUG(AssertSorted(*Cache, NumSortedEntries));
1230 MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst,
1231 Loc, isLoad, BB, Cache,
1234 // If we got a Def or Clobber, add this to the list of results.
1235 if (!Dep.isNonLocal()) {
1237 Result.push_back(NonLocalDepResult(BB,
1238 MemDepResult::getUnknown(),
1239 Pointer.getAddr()));
1241 } else if (DT->isReachableFromEntry(BB)) {
1242 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
1248 // If 'Pointer' is an instruction defined in this block, then we need to do
1249 // phi translation to change it into a value live in the predecessor block.
1250 // If not, we just add the predecessors to the worklist and scan them with
1251 // the same Pointer.
1252 if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
1253 SkipFirstBlock = false;
1254 SmallVector<BasicBlock*, 16> NewBlocks;
1255 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
1256 // Verify that we haven't looked at this block yet.
1257 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
1258 InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
1259 if (InsertRes.second) {
1260 // First time we've looked at *PI.
1261 NewBlocks.push_back(*PI);
1265 // If we have seen this block before, but it was with a different
1266 // pointer then we have a phi translation failure and we have to treat
1267 // this as a clobber.
1268 if (InsertRes.first->second != Pointer.getAddr()) {
1269 // Make sure to clean up the Visited map before continuing on to
1270 // PredTranslationFailure.
1271 for (unsigned i = 0; i < NewBlocks.size(); i++)
1272 Visited.erase(NewBlocks[i]);
1273 goto PredTranslationFailure;
1276 Worklist.append(NewBlocks.begin(), NewBlocks.end());
1280 // We do need to do phi translation, if we know ahead of time we can't phi
1281 // translate this value, don't even try.
1282 if (!Pointer.IsPotentiallyPHITranslatable())
1283 goto PredTranslationFailure;
1285 // We may have added values to the cache list before this PHI translation.
1286 // If so, we haven't done anything to ensure that the cache remains sorted.
1287 // Sort it now (if needed) so that recursive invocations of
1288 // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1289 // value will only see properly sorted cache arrays.
1290 if (Cache && NumSortedEntries != Cache->size()) {
1291 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1292 NumSortedEntries = Cache->size();
1297 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
1298 BasicBlock *Pred = *PI;
1299 PredList.push_back(std::make_pair(Pred, Pointer));
1301 // Get the PHI translated pointer in this predecessor. This can fail if
1302 // not translatable, in which case the getAddr() returns null.
1303 PHITransAddr &PredPointer = PredList.back().second;
1304 PredPointer.PHITranslateValue(BB, Pred, nullptr);
1306 Value *PredPtrVal = PredPointer.getAddr();
1308 // Check to see if we have already visited this pred block with another
1309 // pointer. If so, we can't do this lookup. This failure can occur
1310 // with PHI translation when a critical edge exists and the PHI node in
1311 // the successor translates to a pointer value different than the
1312 // pointer the block was first analyzed with.
1313 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
1314 InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
1316 if (!InsertRes.second) {
1317 // We found the pred; take it off the list of preds to visit.
1318 PredList.pop_back();
1320 // If the predecessor was visited with PredPtr, then we already did
1321 // the analysis and can ignore it.
1322 if (InsertRes.first->second == PredPtrVal)
1325 // Otherwise, the block was previously analyzed with a different
1326 // pointer. We can't represent the result of this case, so we just
1327 // treat this as a phi translation failure.
1329 // Make sure to clean up the Visited map before continuing on to
1330 // PredTranslationFailure.
1331 for (unsigned i = 0, n = PredList.size(); i < n; ++i)
1332 Visited.erase(PredList[i].first);
1334 goto PredTranslationFailure;
1338 // Actually process results here; this need to be a separate loop to avoid
1339 // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1340 // any results for. (getNonLocalPointerDepFromBB will modify our
1341 // datastructures in ways the code after the PredTranslationFailure label
1343 for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
1344 BasicBlock *Pred = PredList[i].first;
1345 PHITransAddr &PredPointer = PredList[i].second;
1346 Value *PredPtrVal = PredPointer.getAddr();
1348 bool CanTranslate = true;
1349 // If PHI translation was unable to find an available pointer in this
1350 // predecessor, then we have to assume that the pointer is clobbered in
1351 // that predecessor. We can still do PRE of the load, which would insert
1352 // a computation of the pointer in this predecessor.
1354 CanTranslate = false;
1356 // FIXME: it is entirely possible that PHI translating will end up with
1357 // the same value. Consider PHI translating something like:
1358 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need*
1359 // to recurse here, pedantically speaking.
1361 // If getNonLocalPointerDepFromBB fails here, that means the cached
1362 // result conflicted with the Visited list; we have to conservatively
1363 // assume it is unknown, but this also does not block PRE of the load.
1364 if (!CanTranslate ||
1365 getNonLocalPointerDepFromBB(QueryInst, PredPointer,
1366 Loc.getWithNewPtr(PredPtrVal),
1369 // Add the entry to the Result list.
1370 NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
1371 Result.push_back(Entry);
1373 // Since we had a phi translation failure, the cache for CacheKey won't
1374 // include all of the entries that we need to immediately satisfy future
1375 // queries. Mark this in NonLocalPointerDeps by setting the
1376 // BBSkipFirstBlockPair pointer to null. This requires reuse of the
1377 // cached value to do more work but not miss the phi trans failure.
1378 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1379 NLPI.Pair = BBSkipFirstBlockPair();
1384 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1385 CacheInfo = &NonLocalPointerDeps[CacheKey];
1386 Cache = &CacheInfo->NonLocalDeps;
1387 NumSortedEntries = Cache->size();
1389 // Since we did phi translation, the "Cache" set won't contain all of the
1390 // results for the query. This is ok (we can still use it to accelerate
1391 // specific block queries) but we can't do the fastpath "return all
1392 // results from the set" Clear out the indicator for this.
1393 CacheInfo->Pair = BBSkipFirstBlockPair();
1394 SkipFirstBlock = false;
1397 PredTranslationFailure:
1398 // The following code is "failure"; we can't produce a sane translation
1399 // for the given block. It assumes that we haven't modified any of
1400 // our datastructures while processing the current block.
1403 // Refresh the CacheInfo/Cache pointer if it got invalidated.
1404 CacheInfo = &NonLocalPointerDeps[CacheKey];
1405 Cache = &CacheInfo->NonLocalDeps;
1406 NumSortedEntries = Cache->size();
1409 // Since we failed phi translation, the "Cache" set won't contain all of the
1410 // results for the query. This is ok (we can still use it to accelerate
1411 // specific block queries) but we can't do the fastpath "return all
1412 // results from the set". Clear out the indicator for this.
1413 CacheInfo->Pair = BBSkipFirstBlockPair();
1415 // If *nothing* works, mark the pointer as unknown.
1417 // If this is the magic first block, return this as a clobber of the whole
1418 // incoming value. Since we can't phi translate to one of the predecessors,
1419 // we have to bail out.
1423 for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
1424 assert(I != Cache->rend() && "Didn't find current block??");
1425 if (I->getBB() != BB)
1428 assert((I->getResult().isNonLocal() || !DT->isReachableFromEntry(BB)) &&
1429 "Should only be here with transparent block");
1430 I->setResult(MemDepResult::getUnknown());
1431 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
1432 Pointer.getAddr()));
1437 // Okay, we're done now. If we added new values to the cache, re-sort it.
1438 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1439 DEBUG(AssertSorted(*Cache));
1443 /// RemoveCachedNonLocalPointerDependencies - If P exists in
1444 /// CachedNonLocalPointerInfo, remove it.
1445 void MemoryDependenceAnalysis::
1446 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
1447 CachedNonLocalPointerInfo::iterator It =
1448 NonLocalPointerDeps.find(P);
1449 if (It == NonLocalPointerDeps.end()) return;
1451 // Remove all of the entries in the BB->val map. This involves removing
1452 // instructions from the reverse map.
1453 NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1455 for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1456 Instruction *Target = PInfo[i].getResult().getInst();
1457 if (!Target) continue; // Ignore non-local dep results.
1458 assert(Target->getParent() == PInfo[i].getBB());
1460 // Eliminating the dirty entry from 'Cache', so update the reverse info.
1461 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1464 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1465 NonLocalPointerDeps.erase(It);
1469 /// invalidateCachedPointerInfo - This method is used to invalidate cached
1470 /// information about the specified pointer, because it may be too
1471 /// conservative in memdep. This is an optional call that can be used when
1472 /// the client detects an equivalence between the pointer and some other
1473 /// value and replaces the other value with ptr. This can make Ptr available
1474 /// in more places that cached info does not necessarily keep.
1475 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
1476 // If Ptr isn't really a pointer, just ignore it.
1477 if (!Ptr->getType()->isPointerTy()) return;
1478 // Flush store info for the pointer.
1479 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1480 // Flush load info for the pointer.
1481 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1484 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
1485 /// This needs to be done when the CFG changes, e.g., due to splitting
1487 void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
1491 /// removeInstruction - Remove an instruction from the dependence analysis,
1492 /// updating the dependence of instructions that previously depended on it.
1493 /// This method attempts to keep the cache coherent using the reverse map.
1494 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
1495 // Walk through the Non-local dependencies, removing this one as the value
1496 // for any cached queries.
1497 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1498 if (NLDI != NonLocalDeps.end()) {
1499 NonLocalDepInfo &BlockMap = NLDI->second.first;
1500 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
1502 if (Instruction *Inst = DI->getResult().getInst())
1503 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1504 NonLocalDeps.erase(NLDI);
1507 // If we have a cached local dependence query for this instruction, remove it.
1509 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1510 if (LocalDepEntry != LocalDeps.end()) {
1511 // Remove us from DepInst's reverse set now that the local dep info is gone.
1512 if (Instruction *Inst = LocalDepEntry->second.getInst())
1513 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1515 // Remove this local dependency info.
1516 LocalDeps.erase(LocalDepEntry);
1519 // If we have any cached pointer dependencies on this instruction, remove
1520 // them. If the instruction has non-pointer type, then it can't be a pointer
1523 // Remove it from both the load info and the store info. The instruction
1524 // can't be in either of these maps if it is non-pointer.
1525 if (RemInst->getType()->isPointerTy()) {
1526 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1527 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1530 // Loop over all of the things that depend on the instruction we're removing.
1532 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
1534 // If we find RemInst as a clobber or Def in any of the maps for other values,
1535 // we need to replace its entry with a dirty version of the instruction after
1536 // it. If RemInst is a terminator, we use a null dirty value.
1538 // Using a dirty version of the instruction after RemInst saves having to scan
1539 // the entire block to get to this point.
1540 MemDepResult NewDirtyVal;
1541 if (!RemInst->isTerminator())
1542 NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
1544 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1545 if (ReverseDepIt != ReverseLocalDeps.end()) {
1546 // RemInst can't be the terminator if it has local stuff depending on it.
1547 assert(!ReverseDepIt->second.empty() && !isa<TerminatorInst>(RemInst) &&
1548 "Nothing can locally depend on a terminator");
1550 for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
1551 assert(InstDependingOnRemInst != RemInst &&
1552 "Already removed our local dep info");
1554 LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1556 // Make sure to remember that new things depend on NewDepInst.
1557 assert(NewDirtyVal.getInst() && "There is no way something else can have "
1558 "a local dep on this if it is a terminator!");
1559 ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
1560 InstDependingOnRemInst));
1563 ReverseLocalDeps.erase(ReverseDepIt);
1565 // Add new reverse deps after scanning the set, to avoid invalidating the
1566 // 'ReverseDeps' reference.
1567 while (!ReverseDepsToAdd.empty()) {
1568 ReverseLocalDeps[ReverseDepsToAdd.back().first]
1569 .insert(ReverseDepsToAdd.back().second);
1570 ReverseDepsToAdd.pop_back();
1574 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1575 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1576 for (Instruction *I : ReverseDepIt->second) {
1577 assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
1579 PerInstNLInfo &INLD = NonLocalDeps[I];
1580 // The information is now dirty!
1583 for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
1584 DE = INLD.first.end(); DI != DE; ++DI) {
1585 if (DI->getResult().getInst() != RemInst) continue;
1587 // Convert to a dirty entry for the subsequent instruction.
1588 DI->setResult(NewDirtyVal);
1590 if (Instruction *NextI = NewDirtyVal.getInst())
1591 ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
1595 ReverseNonLocalDeps.erase(ReverseDepIt);
1597 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1598 while (!ReverseDepsToAdd.empty()) {
1599 ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
1600 .insert(ReverseDepsToAdd.back().second);
1601 ReverseDepsToAdd.pop_back();
1605 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1606 // value in the NonLocalPointerDeps info.
1607 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1608 ReverseNonLocalPtrDeps.find(RemInst);
1609 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1610 SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
1612 for (ValueIsLoadPair P : ReversePtrDepIt->second) {
1613 assert(P.getPointer() != RemInst &&
1614 "Already removed NonLocalPointerDeps info for RemInst");
1616 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1618 // The cache is not valid for any specific block anymore.
1619 NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1621 // Update any entries for RemInst to use the instruction after it.
1622 for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
1624 if (DI->getResult().getInst() != RemInst) continue;
1626 // Convert to a dirty entry for the subsequent instruction.
1627 DI->setResult(NewDirtyVal);
1629 if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1630 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1633 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its
1634 // subsequent value may invalidate the sortedness.
1635 std::sort(NLPDI.begin(), NLPDI.end());
1638 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1640 while (!ReversePtrDepsToAdd.empty()) {
1641 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
1642 .insert(ReversePtrDepsToAdd.back().second);
1643 ReversePtrDepsToAdd.pop_back();
1648 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1649 AA->deleteValue(RemInst);
1650 DEBUG(verifyRemoved(RemInst));
1652 /// verifyRemoved - Verify that the specified instruction does not occur
1653 /// in our internal data structures. This function verifies by asserting in
1655 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
1657 for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
1658 E = LocalDeps.end(); I != E; ++I) {
1659 assert(I->first != D && "Inst occurs in data structures");
1660 assert(I->second.getInst() != D &&
1661 "Inst occurs in data structures");
1664 for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
1665 E = NonLocalPointerDeps.end(); I != E; ++I) {
1666 assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
1667 const NonLocalDepInfo &Val = I->second.NonLocalDeps;
1668 for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
1670 assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
1673 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
1674 E = NonLocalDeps.end(); I != E; ++I) {
1675 assert(I->first != D && "Inst occurs in data structures");
1676 const PerInstNLInfo &INLD = I->second;
1677 for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
1678 EE = INLD.first.end(); II != EE; ++II)
1679 assert(II->getResult().getInst() != D && "Inst occurs in data structures");
1682 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
1683 E = ReverseLocalDeps.end(); I != E; ++I) {
1684 assert(I->first != D && "Inst occurs in data structures");
1685 for (Instruction *Inst : I->second)
1686 assert(Inst != D && "Inst occurs in data structures");
1689 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
1690 E = ReverseNonLocalDeps.end();
1692 assert(I->first != D && "Inst occurs in data structures");
1693 for (Instruction *Inst : I->second)
1694 assert(Inst != D && "Inst occurs in data structures");
1697 for (ReverseNonLocalPtrDepTy::const_iterator
1698 I = ReverseNonLocalPtrDeps.begin(),
1699 E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
1700 assert(I->first != D && "Inst occurs in rev NLPD map");
1702 for (ValueIsLoadPair P : I->second)
1703 assert(P != ValueIsLoadPair(D, false) &&
1704 P != ValueIsLoadPair(D, true) &&
1705 "Inst occurs in ReverseNonLocalPtrDeps map");