1 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation --*- C++ -*-===//
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 #define DEBUG_TYPE "memdep"
18 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/Function.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/MemoryBuiltins.h"
28 #include "llvm/Analysis/PHITransAddr.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/PredIteratorCache.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Target/TargetData.h"
37 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
38 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
39 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
41 STATISTIC(NumCacheNonLocalPtr,
42 "Number of fully cached non-local ptr responses");
43 STATISTIC(NumCacheDirtyNonLocalPtr,
44 "Number of cached, but dirty, non-local ptr responses");
45 STATISTIC(NumUncacheNonLocalPtr,
46 "Number of uncached non-local ptr responses");
47 STATISTIC(NumCacheCompleteNonLocalPtr,
48 "Number of block queries that were completely cached");
50 char MemoryDependenceAnalysis::ID = 0;
52 // Register this pass...
53 INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep",
54 "Memory Dependence Analysis", false, true)
55 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
56 INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep",
57 "Memory Dependence Analysis", false, true)
59 MemoryDependenceAnalysis::MemoryDependenceAnalysis()
60 : FunctionPass(ID), PredCache(0) {
61 initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry());
63 MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
66 /// Clean up memory in between runs
67 void MemoryDependenceAnalysis::releaseMemory() {
70 NonLocalPointerDeps.clear();
71 ReverseLocalDeps.clear();
72 ReverseNonLocalDeps.clear();
73 ReverseNonLocalPtrDeps.clear();
79 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
81 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
83 AU.addRequiredTransitive<AliasAnalysis>();
86 bool MemoryDependenceAnalysis::runOnFunction(Function &) {
87 AA = &getAnalysis<AliasAnalysis>();
88 TD = getAnalysisIfAvailable<TargetData>();
90 PredCache.reset(new PredIteratorCache());
94 /// RemoveFromReverseMap - This is a helper function that removes Val from
95 /// 'Inst's set in ReverseMap. If the set becomes empty, remove Inst's entry.
96 template <typename KeyTy>
97 static void RemoveFromReverseMap(DenseMap<Instruction*,
98 SmallPtrSet<KeyTy, 4> > &ReverseMap,
99 Instruction *Inst, KeyTy Val) {
100 typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator
101 InstIt = ReverseMap.find(Inst);
102 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
103 bool Found = InstIt->second.erase(Val);
104 assert(Found && "Invalid reverse map!"); (void)Found;
105 if (InstIt->second.empty())
106 ReverseMap.erase(InstIt);
109 /// GetLocation - If the given instruction references a specific memory
110 /// location, fill in Loc with the details, otherwise set Loc.Ptr to null.
111 /// Return a ModRefInfo value describing the general behavior of the
114 AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst,
115 AliasAnalysis::Location &Loc,
117 if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
118 if (LI->isVolatile()) {
119 Loc = AliasAnalysis::Location();
120 return AliasAnalysis::ModRef;
122 Loc = AA->getLocation(LI);
123 return AliasAnalysis::Ref;
126 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
127 if (SI->isVolatile()) {
128 Loc = AliasAnalysis::Location();
129 return AliasAnalysis::ModRef;
131 Loc = AA->getLocation(SI);
132 return AliasAnalysis::Mod;
135 if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
136 Loc = AA->getLocation(V);
137 return AliasAnalysis::ModRef;
140 if (const CallInst *CI = isFreeCall(Inst)) {
141 // calls to free() deallocate the entire structure
142 Loc = AliasAnalysis::Location(CI->getArgOperand(0));
143 return AliasAnalysis::Mod;
146 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
147 switch (II->getIntrinsicID()) {
148 case Intrinsic::lifetime_start:
149 case Intrinsic::lifetime_end:
150 case Intrinsic::invariant_start:
151 Loc = AliasAnalysis::Location(II->getArgOperand(1),
152 cast<ConstantInt>(II->getArgOperand(0))
154 II->getMetadata(LLVMContext::MD_tbaa));
155 // These intrinsics don't really modify the memory, but returning Mod
156 // will allow them to be handled conservatively.
157 return AliasAnalysis::Mod;
158 case Intrinsic::invariant_end:
159 Loc = AliasAnalysis::Location(II->getArgOperand(2),
160 cast<ConstantInt>(II->getArgOperand(1))
162 II->getMetadata(LLVMContext::MD_tbaa));
163 // These intrinsics don't really modify the memory, but returning Mod
164 // will allow them to be handled conservatively.
165 return AliasAnalysis::Mod;
170 // Otherwise, just do the coarse-grained thing that always works.
171 if (Inst->mayWriteToMemory())
172 return AliasAnalysis::ModRef;
173 if (Inst->mayReadFromMemory())
174 return AliasAnalysis::Ref;
175 return AliasAnalysis::NoModRef;
178 /// getCallSiteDependencyFrom - Private helper for finding the local
179 /// dependencies of a call site.
180 MemDepResult MemoryDependenceAnalysis::
181 getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
182 BasicBlock::iterator ScanIt, BasicBlock *BB) {
183 // Walk backwards through the block, looking for dependencies
184 while (ScanIt != BB->begin()) {
185 Instruction *Inst = --ScanIt;
187 // If this inst is a memory op, get the pointer it accessed
188 AliasAnalysis::Location Loc;
189 AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA);
191 // A simple instruction.
192 if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef)
193 return MemDepResult::getClobber(Inst);
197 if (CallSite InstCS = cast<Value>(Inst)) {
198 // Debug intrinsics don't cause dependences.
199 if (isa<DbgInfoIntrinsic>(Inst)) continue;
200 // If these two calls do not interfere, look past it.
201 switch (AA->getModRefInfo(CS, InstCS)) {
202 case AliasAnalysis::NoModRef:
203 // If the two calls are the same, return InstCS as a Def, so that
204 // CS can be found redundant and eliminated.
205 if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) &&
206 CS.getInstruction()->isIdenticalToWhenDefined(Inst))
207 return MemDepResult::getDef(Inst);
209 // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
213 return MemDepResult::getClobber(Inst);
218 // No dependence found. If this is the entry block of the function, it is a
219 // clobber, otherwise it is non-local.
220 if (BB != &BB->getParent()->getEntryBlock())
221 return MemDepResult::getNonLocal();
222 return MemDepResult::getClobber(ScanIt);
225 /// isLoadLoadClobberIfExtendedToFullWidth - Return true if LI is a load that
226 /// would fully overlap MemLoc if done as a wider legal integer load.
228 /// MemLocBase, MemLocOffset are lazily computed here the first time the
229 /// base/offs of memloc is needed.
231 isLoadLoadClobberIfExtendedToFullWidth(const AliasAnalysis::Location &MemLoc,
232 const Value *&MemLocBase,
235 const TargetData *TD) {
236 // If we have no target data, we can't do this.
237 if (TD == 0) return false;
239 // If we haven't already computed the base/offset of MemLoc, do so now.
241 MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, *TD);
243 unsigned Size = MemoryDependenceAnalysis::
244 getLoadLoadClobberFullWidthSize(MemLocBase, MemLocOffs, MemLoc.Size,
249 /// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
250 /// looks at a memory location for a load (specified by MemLocBase, Offs,
251 /// and Size) and compares it against a load. If the specified load could
252 /// be safely widened to a larger integer load that is 1) still efficient,
253 /// 2) safe for the target, and 3) would provide the specified memory
254 /// location value, then this function returns the size in bytes of the
255 /// load width to use. If not, this returns zero.
256 unsigned MemoryDependenceAnalysis::
257 getLoadLoadClobberFullWidthSize(const Value *MemLocBase, int64_t MemLocOffs,
258 unsigned MemLocSize, const LoadInst *LI,
259 const TargetData &TD) {
260 // We can only extend non-volatile integer loads.
261 if (!isa<IntegerType>(LI->getType()) || LI->isVolatile()) return 0;
263 // Get the base of this load.
265 const Value *LIBase =
266 GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, TD);
268 // If the two pointers are not based on the same pointer, we can't tell that
270 if (LIBase != MemLocBase) return 0;
272 // Okay, the two values are based on the same pointer, but returned as
273 // no-alias. This happens when we have things like two byte loads at "P+1"
274 // and "P+3". Check to see if increasing the size of the "LI" load up to its
275 // alignment (or the largest native integer type) will allow us to load all
276 // the bits required by MemLoc.
278 // If MemLoc is before LI, then no widening of LI will help us out.
279 if (MemLocOffs < LIOffs) return 0;
281 // Get the alignment of the load in bytes. We assume that it is safe to load
282 // any legal integer up to this size without a problem. For example, if we're
283 // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
284 // widen it up to an i32 load. If it is known 2-byte aligned, we can widen it
286 unsigned LoadAlign = LI->getAlignment();
288 int64_t MemLocEnd = MemLocOffs+MemLocSize;
290 // If no amount of rounding up will let MemLoc fit into LI, then bail out.
291 if (LIOffs+LoadAlign < MemLocEnd) return 0;
293 // This is the size of the load to try. Start with the next larger power of
295 unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits()/8U;
296 NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
299 // If this load size is bigger than our known alignment or would not fit
300 // into a native integer register, then we fail.
301 if (NewLoadByteSize > LoadAlign ||
302 !TD.fitsInLegalInteger(NewLoadByteSize*8))
305 // If a load of this width would include all of MemLoc, then we succeed.
306 if (LIOffs+NewLoadByteSize >= MemLocEnd)
307 return NewLoadByteSize;
309 NewLoadByteSize <<= 1;
315 /// getPointerDependencyFrom - Return the instruction on which a memory
316 /// location depends. If isLoad is true, this routine ignores may-aliases with
317 /// read-only operations. If isLoad is false, this routine ignores may-aliases
318 /// with reads from read-only locations.
319 MemDepResult MemoryDependenceAnalysis::
320 getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad,
321 BasicBlock::iterator ScanIt, BasicBlock *BB) {
323 const Value *MemLocBase = 0;
324 int64_t MemLocOffset = 0;
326 // Walk backwards through the basic block, looking for dependencies.
327 while (ScanIt != BB->begin()) {
328 Instruction *Inst = --ScanIt;
330 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
331 // Debug intrinsics don't (and can't) cause dependences.
332 if (isa<DbgInfoIntrinsic>(II)) continue;
334 // If we reach a lifetime begin or end marker, then the query ends here
335 // because the value is undefined.
336 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
337 // FIXME: This only considers queries directly on the invariant-tagged
338 // pointer, not on query pointers that are indexed off of them. It'd
339 // be nice to handle that at some point (the right approach is to use
340 // GetPointerBaseWithConstantOffset).
341 if (AA->isMustAlias(AliasAnalysis::Location(II->getArgOperand(1)),
343 return MemDepResult::getDef(II);
348 // Values depend on loads if the pointers are must aliased. This means that
349 // a load depends on another must aliased load from the same value.
350 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
351 AliasAnalysis::Location LoadLoc = AA->getLocation(LI);
353 // If we found a pointer, check if it could be the same as our pointer.
354 AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc);
357 if (R == AliasAnalysis::NoAlias) {
358 // If this is an over-aligned integer load (for example,
359 // "load i8* %P, align 4") see if it would obviously overlap with the
360 // queried location if widened to a larger load (e.g. if the queried
361 // location is 1 byte at P+1). If so, return it as a load/load
362 // clobber result, allowing the client to decide to widen the load if
364 if (const IntegerType *ITy = dyn_cast<IntegerType>(LI->getType()))
365 if (LI->getAlignment()*8 > ITy->getPrimitiveSizeInBits() &&
366 isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase,
367 MemLocOffset, LI, TD))
368 return MemDepResult::getClobber(Inst);
373 // Must aliased loads are defs of each other.
374 if (R == AliasAnalysis::MustAlias)
375 return MemDepResult::getDef(Inst);
377 // If we have a partial alias, then return this as a clobber for the
379 if (R == AliasAnalysis::PartialAlias)
380 return MemDepResult::getClobber(Inst);
382 // Random may-alias loads don't depend on each other without a
387 // Stores don't depend on other no-aliased accesses.
388 if (R == AliasAnalysis::NoAlias)
391 // Stores don't alias loads from read-only memory.
392 if (AA->pointsToConstantMemory(LoadLoc))
395 // Stores depend on may/must aliased loads.
396 return MemDepResult::getDef(Inst);
399 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
400 // If alias analysis can tell that this store is guaranteed to not modify
401 // the query pointer, ignore it. Use getModRefInfo to handle cases where
402 // the query pointer points to constant memory etc.
403 if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
406 // Ok, this store might clobber the query pointer. Check to see if it is
407 // a must alias: in this case, we want to return this as a def.
408 AliasAnalysis::Location StoreLoc = AA->getLocation(SI);
410 // If we found a pointer, check if it could be the same as our pointer.
411 AliasAnalysis::AliasResult R = AA->alias(StoreLoc, MemLoc);
413 if (R == AliasAnalysis::NoAlias)
415 if (R == AliasAnalysis::MustAlias)
416 return MemDepResult::getDef(Inst);
417 return MemDepResult::getClobber(Inst);
420 // If this is an allocation, and if we know that the accessed pointer is to
421 // the allocation, return Def. This means that there is no dependence and
422 // the access can be optimized based on that. For example, a load could
424 // Note: Only determine this to be a malloc if Inst is the malloc call, not
425 // a subsequent bitcast of the malloc call result. There can be stores to
426 // the malloced memory between the malloc call and its bitcast uses, and we
427 // need to continue scanning until the malloc call.
428 if (isa<AllocaInst>(Inst) ||
429 (isa<CallInst>(Inst) && extractMallocCall(Inst))) {
430 const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, TD);
432 if (AccessPtr == Inst || AA->isMustAlias(Inst, AccessPtr))
433 return MemDepResult::getDef(Inst);
437 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
438 switch (AA->getModRefInfo(Inst, MemLoc)) {
439 case AliasAnalysis::NoModRef:
440 // If the call has no effect on the queried pointer, just ignore it.
442 case AliasAnalysis::Mod:
443 return MemDepResult::getClobber(Inst);
444 case AliasAnalysis::Ref:
445 // If the call is known to never store to the pointer, and if this is a
446 // load query, we can safely ignore it (scan past it).
450 // Otherwise, there is a potential dependence. Return a clobber.
451 return MemDepResult::getClobber(Inst);
455 // No dependence found. If this is the entry block of the function, it is a
456 // clobber, otherwise it is non-local.
457 if (BB != &BB->getParent()->getEntryBlock())
458 return MemDepResult::getNonLocal();
459 return MemDepResult::getClobber(ScanIt);
462 /// getDependency - Return the instruction on which a memory operation
464 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
465 Instruction *ScanPos = QueryInst;
467 // Check for a cached result
468 MemDepResult &LocalCache = LocalDeps[QueryInst];
470 // If the cached entry is non-dirty, just return it. Note that this depends
471 // on MemDepResult's default constructing to 'dirty'.
472 if (!LocalCache.isDirty())
475 // Otherwise, if we have a dirty entry, we know we can start the scan at that
476 // instruction, which may save us some work.
477 if (Instruction *Inst = LocalCache.getInst()) {
480 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
483 BasicBlock *QueryParent = QueryInst->getParent();
486 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
487 // No dependence found. If this is the entry block of the function, it is a
488 // clobber, otherwise it is non-local.
489 if (QueryParent != &QueryParent->getParent()->getEntryBlock())
490 LocalCache = MemDepResult::getNonLocal();
492 LocalCache = MemDepResult::getClobber(QueryInst);
494 AliasAnalysis::Location MemLoc;
495 AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
497 // If we can do a pointer scan, make it happen.
498 bool isLoad = !(MR & AliasAnalysis::Mod);
499 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
500 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
502 LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
504 } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
505 CallSite QueryCS(QueryInst);
506 bool isReadOnly = AA->onlyReadsMemory(QueryCS);
507 LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
510 // Non-memory instruction.
511 LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
514 // Remember the result!
515 if (Instruction *I = LocalCache.getInst())
516 ReverseLocalDeps[I].insert(QueryInst);
522 /// AssertSorted - This method is used when -debug is specified to verify that
523 /// cache arrays are properly kept sorted.
524 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
526 if (Count == -1) Count = Cache.size();
527 if (Count == 0) return;
529 for (unsigned i = 1; i != unsigned(Count); ++i)
530 assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
534 /// getNonLocalCallDependency - Perform a full dependency query for the
535 /// specified call, returning the set of blocks that the value is
536 /// potentially live across. The returned set of results will include a
537 /// "NonLocal" result for all blocks where the value is live across.
539 /// This method assumes the instruction returns a "NonLocal" dependency
540 /// within its own block.
542 /// This returns a reference to an internal data structure that may be
543 /// invalidated on the next non-local query or when an instruction is
544 /// removed. Clients must copy this data if they want it around longer than
546 const MemoryDependenceAnalysis::NonLocalDepInfo &
547 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
548 assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
549 "getNonLocalCallDependency should only be used on calls with non-local deps!");
550 PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
551 NonLocalDepInfo &Cache = CacheP.first;
553 /// DirtyBlocks - This is the set of blocks that need to be recomputed. In
554 /// the cached case, this can happen due to instructions being deleted etc. In
555 /// the uncached case, this starts out as the set of predecessors we care
557 SmallVector<BasicBlock*, 32> DirtyBlocks;
559 if (!Cache.empty()) {
560 // Okay, we have a cache entry. If we know it is not dirty, just return it
561 // with no computation.
562 if (!CacheP.second) {
567 // If we already have a partially computed set of results, scan them to
568 // determine what is dirty, seeding our initial DirtyBlocks worklist.
569 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
571 if (I->getResult().isDirty())
572 DirtyBlocks.push_back(I->getBB());
574 // Sort the cache so that we can do fast binary search lookups below.
575 std::sort(Cache.begin(), Cache.end());
577 ++NumCacheDirtyNonLocal;
578 //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
579 // << Cache.size() << " cached: " << *QueryInst;
581 // Seed DirtyBlocks with each of the preds of QueryInst's block.
582 BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
583 for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
584 DirtyBlocks.push_back(*PI);
585 ++NumUncacheNonLocal;
588 // isReadonlyCall - If this is a read-only call, we can be more aggressive.
589 bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
591 SmallPtrSet<BasicBlock*, 64> Visited;
593 unsigned NumSortedEntries = Cache.size();
594 DEBUG(AssertSorted(Cache));
596 // Iterate while we still have blocks to update.
597 while (!DirtyBlocks.empty()) {
598 BasicBlock *DirtyBB = DirtyBlocks.back();
599 DirtyBlocks.pop_back();
601 // Already processed this block?
602 if (!Visited.insert(DirtyBB))
605 // Do a binary search to see if we already have an entry for this block in
606 // the cache set. If so, find it.
607 DEBUG(AssertSorted(Cache, NumSortedEntries));
608 NonLocalDepInfo::iterator Entry =
609 std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
610 NonLocalDepEntry(DirtyBB));
611 if (Entry != Cache.begin() && prior(Entry)->getBB() == DirtyBB)
614 NonLocalDepEntry *ExistingResult = 0;
615 if (Entry != Cache.begin()+NumSortedEntries &&
616 Entry->getBB() == DirtyBB) {
617 // If we already have an entry, and if it isn't already dirty, the block
619 if (!Entry->getResult().isDirty())
622 // Otherwise, remember this slot so we can update the value.
623 ExistingResult = &*Entry;
626 // If the dirty entry has a pointer, start scanning from it so we don't have
627 // to rescan the entire block.
628 BasicBlock::iterator ScanPos = DirtyBB->end();
629 if (ExistingResult) {
630 if (Instruction *Inst = ExistingResult->getResult().getInst()) {
632 // We're removing QueryInst's use of Inst.
633 RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
634 QueryCS.getInstruction());
638 // Find out if this block has a local dependency for QueryInst.
641 if (ScanPos != DirtyBB->begin()) {
642 Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
643 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
644 // No dependence found. If this is the entry block of the function, it is
645 // a clobber, otherwise it is non-local.
646 Dep = MemDepResult::getNonLocal();
648 Dep = MemDepResult::getClobber(ScanPos);
651 // If we had a dirty entry for the block, update it. Otherwise, just add
654 ExistingResult->setResult(Dep);
656 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
658 // If the block has a dependency (i.e. it isn't completely transparent to
659 // the value), remember the association!
660 if (!Dep.isNonLocal()) {
661 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
662 // update this when we remove instructions.
663 if (Instruction *Inst = Dep.getInst())
664 ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
667 // If the block *is* completely transparent to the load, we need to check
668 // the predecessors of this block. Add them to our worklist.
669 for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
670 DirtyBlocks.push_back(*PI);
677 /// getNonLocalPointerDependency - Perform a full dependency query for an
678 /// access to the specified (non-volatile) memory location, returning the
679 /// set of instructions that either define or clobber the value.
681 /// This method assumes the pointer has a "NonLocal" dependency within its
684 void MemoryDependenceAnalysis::
685 getNonLocalPointerDependency(const AliasAnalysis::Location &Loc, bool isLoad,
687 SmallVectorImpl<NonLocalDepResult> &Result) {
688 assert(Loc.Ptr->getType()->isPointerTy() &&
689 "Can't get pointer deps of a non-pointer!");
692 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), TD);
694 // This is the set of blocks we've inspected, and the pointer we consider in
695 // each block. Because of critical edges, we currently bail out if querying
696 // a block with multiple different pointers. This can happen during PHI
698 DenseMap<BasicBlock*, Value*> Visited;
699 if (!getNonLocalPointerDepFromBB(Address, Loc, isLoad, FromBB,
700 Result, Visited, true))
703 Result.push_back(NonLocalDepResult(FromBB,
704 MemDepResult::getClobber(FromBB->begin()),
705 const_cast<Value *>(Loc.Ptr)));
708 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
709 /// Pointer/PointeeSize using either cached information in Cache or by doing a
710 /// lookup (which may use dirty cache info if available). If we do a lookup,
711 /// add the result to the cache.
712 MemDepResult MemoryDependenceAnalysis::
713 GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
714 bool isLoad, BasicBlock *BB,
715 NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
717 // Do a binary search to see if we already have an entry for this block in
718 // the cache set. If so, find it.
719 NonLocalDepInfo::iterator Entry =
720 std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
721 NonLocalDepEntry(BB));
722 if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
725 NonLocalDepEntry *ExistingResult = 0;
726 if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
727 ExistingResult = &*Entry;
729 // If we have a cached entry, and it is non-dirty, use it as the value for
731 if (ExistingResult && !ExistingResult->getResult().isDirty()) {
732 ++NumCacheNonLocalPtr;
733 return ExistingResult->getResult();
736 // Otherwise, we have to scan for the value. If we have a dirty cache
737 // entry, start scanning from its position, otherwise we scan from the end
739 BasicBlock::iterator ScanPos = BB->end();
740 if (ExistingResult && ExistingResult->getResult().getInst()) {
741 assert(ExistingResult->getResult().getInst()->getParent() == BB &&
742 "Instruction invalidated?");
743 ++NumCacheDirtyNonLocalPtr;
744 ScanPos = ExistingResult->getResult().getInst();
746 // Eliminating the dirty entry from 'Cache', so update the reverse info.
747 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
748 RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
750 ++NumUncacheNonLocalPtr;
753 // Scan the block for the dependency.
754 MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB);
756 // If we had a dirty entry for the block, update it. Otherwise, just add
759 ExistingResult->setResult(Dep);
761 Cache->push_back(NonLocalDepEntry(BB, Dep));
763 // If the block has a dependency (i.e. it isn't completely transparent to
764 // the value), remember the reverse association because we just added it
766 if (Dep.isNonLocal())
769 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
770 // update MemDep when we remove instructions.
771 Instruction *Inst = Dep.getInst();
772 assert(Inst && "Didn't depend on anything?");
773 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
774 ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
778 /// SortNonLocalDepInfoCache - Sort the a NonLocalDepInfo cache, given a certain
779 /// number of elements in the array that are already properly ordered. This is
780 /// optimized for the case when only a few entries are added.
782 SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
783 unsigned NumSortedEntries) {
784 switch (Cache.size() - NumSortedEntries) {
786 // done, no new entries.
789 // Two new entries, insert the last one into place.
790 NonLocalDepEntry Val = Cache.back();
792 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
793 std::upper_bound(Cache.begin(), Cache.end()-1, Val);
794 Cache.insert(Entry, Val);
798 // One new entry, Just insert the new value at the appropriate position.
799 if (Cache.size() != 1) {
800 NonLocalDepEntry Val = Cache.back();
802 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
803 std::upper_bound(Cache.begin(), Cache.end(), Val);
804 Cache.insert(Entry, Val);
808 // Added many values, do a full scale sort.
809 std::sort(Cache.begin(), Cache.end());
814 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
815 /// pointer/pointeesize starting at the end of StartBB. Add any clobber/def
816 /// results to the results vector and keep track of which blocks are visited in
819 /// This has special behavior for the first block queries (when SkipFirstBlock
820 /// is true). In this special case, it ignores the contents of the specified
821 /// block and starts returning dependence info for its predecessors.
823 /// This function returns false on success, or true to indicate that it could
824 /// not compute dependence information for some reason. This should be treated
825 /// as a clobber dependence on the first instruction in the predecessor block.
826 bool MemoryDependenceAnalysis::
827 getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
828 const AliasAnalysis::Location &Loc,
829 bool isLoad, BasicBlock *StartBB,
830 SmallVectorImpl<NonLocalDepResult> &Result,
831 DenseMap<BasicBlock*, Value*> &Visited,
832 bool SkipFirstBlock) {
834 // Look up the cached info for Pointer.
835 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
837 // Set up a temporary NLPI value. If the map doesn't yet have an entry for
838 // CacheKey, this value will be inserted as the associated value. Otherwise,
839 // it'll be ignored, and we'll have to check to see if the cached size and
840 // tbaa tag are consistent with the current query.
841 NonLocalPointerInfo InitialNLPI;
842 InitialNLPI.Size = Loc.Size;
843 InitialNLPI.TBAATag = Loc.TBAATag;
845 // Get the NLPI for CacheKey, inserting one into the map if it doesn't
847 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
848 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
849 NonLocalPointerInfo *CacheInfo = &Pair.first->second;
851 // If we already have a cache entry for this CacheKey, we may need to do some
852 // work to reconcile the cache entry and the current query.
854 if (CacheInfo->Size < Loc.Size) {
855 // The query's Size is greater than the cached one. Throw out the
856 // cached data and procede with the query at the greater size.
857 CacheInfo->Pair = BBSkipFirstBlockPair();
858 CacheInfo->Size = Loc.Size;
859 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
860 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
861 if (Instruction *Inst = DI->getResult().getInst())
862 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
863 CacheInfo->NonLocalDeps.clear();
864 } else if (CacheInfo->Size > Loc.Size) {
865 // This query's Size is less than the cached one. Conservatively restart
866 // the query using the greater size.
867 return getNonLocalPointerDepFromBB(Pointer,
868 Loc.getWithNewSize(CacheInfo->Size),
869 isLoad, StartBB, Result, Visited,
873 // If the query's TBAATag is inconsistent with the cached one,
874 // conservatively throw out the cached data and restart the query with
876 if (CacheInfo->TBAATag != Loc.TBAATag) {
877 if (CacheInfo->TBAATag) {
878 CacheInfo->Pair = BBSkipFirstBlockPair();
879 CacheInfo->TBAATag = 0;
880 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
881 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
882 if (Instruction *Inst = DI->getResult().getInst())
883 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
884 CacheInfo->NonLocalDeps.clear();
887 return getNonLocalPointerDepFromBB(Pointer, Loc.getWithoutTBAATag(),
888 isLoad, StartBB, Result, Visited,
893 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
895 // If we have valid cached information for exactly the block we are
896 // investigating, just return it with no recomputation.
897 if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
898 // We have a fully cached result for this query then we can just return the
899 // cached results and populate the visited set. However, we have to verify
900 // that we don't already have conflicting results for these blocks. Check
901 // to ensure that if a block in the results set is in the visited set that
902 // it was for the same pointer query.
903 if (!Visited.empty()) {
904 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
906 DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
907 if (VI == Visited.end() || VI->second == Pointer.getAddr())
910 // We have a pointer mismatch in a block. Just return clobber, saying
911 // that something was clobbered in this result. We could also do a
912 // non-fully cached query, but there is little point in doing this.
917 Value *Addr = Pointer.getAddr();
918 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
920 Visited.insert(std::make_pair(I->getBB(), Addr));
921 if (!I->getResult().isNonLocal())
922 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
924 ++NumCacheCompleteNonLocalPtr;
928 // Otherwise, either this is a new block, a block with an invalid cache
929 // pointer or one that we're about to invalidate by putting more info into it
930 // than its valid cache info. If empty, the result will be valid cache info,
931 // otherwise it isn't.
933 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
935 CacheInfo->Pair = BBSkipFirstBlockPair();
937 SmallVector<BasicBlock*, 32> Worklist;
938 Worklist.push_back(StartBB);
940 // PredList used inside loop.
941 SmallVector<std::pair<BasicBlock*, PHITransAddr>, 16> PredList;
943 // Keep track of the entries that we know are sorted. Previously cached
944 // entries will all be sorted. The entries we add we only sort on demand (we
945 // don't insert every element into its sorted position). We know that we
946 // won't get any reuse from currently inserted values, because we don't
947 // revisit blocks after we insert info for them.
948 unsigned NumSortedEntries = Cache->size();
949 DEBUG(AssertSorted(*Cache));
951 while (!Worklist.empty()) {
952 BasicBlock *BB = Worklist.pop_back_val();
954 // Skip the first block if we have it.
955 if (!SkipFirstBlock) {
956 // Analyze the dependency of *Pointer in FromBB. See if we already have
958 assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
960 // Get the dependency info for Pointer in BB. If we have cached
961 // information, we will use it, otherwise we compute it.
962 DEBUG(AssertSorted(*Cache, NumSortedEntries));
963 MemDepResult Dep = GetNonLocalInfoForBlock(Loc, isLoad, BB, Cache,
966 // If we got a Def or Clobber, add this to the list of results.
967 if (!Dep.isNonLocal()) {
968 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
973 // If 'Pointer' is an instruction defined in this block, then we need to do
974 // phi translation to change it into a value live in the predecessor block.
975 // If not, we just add the predecessors to the worklist and scan them with
977 if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
978 SkipFirstBlock = false;
979 SmallVector<BasicBlock*, 16> NewBlocks;
980 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
981 // Verify that we haven't looked at this block yet.
982 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
983 InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
984 if (InsertRes.second) {
985 // First time we've looked at *PI.
986 NewBlocks.push_back(*PI);
990 // If we have seen this block before, but it was with a different
991 // pointer then we have a phi translation failure and we have to treat
992 // this as a clobber.
993 if (InsertRes.first->second != Pointer.getAddr()) {
994 // Make sure to clean up the Visited map before continuing on to
995 // PredTranslationFailure.
996 for (unsigned i = 0; i < NewBlocks.size(); i++)
997 Visited.erase(NewBlocks[i]);
998 goto PredTranslationFailure;
1001 Worklist.append(NewBlocks.begin(), NewBlocks.end());
1005 // We do need to do phi translation, if we know ahead of time we can't phi
1006 // translate this value, don't even try.
1007 if (!Pointer.IsPotentiallyPHITranslatable())
1008 goto PredTranslationFailure;
1010 // We may have added values to the cache list before this PHI translation.
1011 // If so, we haven't done anything to ensure that the cache remains sorted.
1012 // Sort it now (if needed) so that recursive invocations of
1013 // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1014 // value will only see properly sorted cache arrays.
1015 if (Cache && NumSortedEntries != Cache->size()) {
1016 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1017 NumSortedEntries = Cache->size();
1022 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
1023 BasicBlock *Pred = *PI;
1024 PredList.push_back(std::make_pair(Pred, Pointer));
1026 // Get the PHI translated pointer in this predecessor. This can fail if
1027 // not translatable, in which case the getAddr() returns null.
1028 PHITransAddr &PredPointer = PredList.back().second;
1029 PredPointer.PHITranslateValue(BB, Pred, 0);
1031 Value *PredPtrVal = PredPointer.getAddr();
1033 // Check to see if we have already visited this pred block with another
1034 // pointer. If so, we can't do this lookup. This failure can occur
1035 // with PHI translation when a critical edge exists and the PHI node in
1036 // the successor translates to a pointer value different than the
1037 // pointer the block was first analyzed with.
1038 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
1039 InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
1041 if (!InsertRes.second) {
1042 // We found the pred; take it off the list of preds to visit.
1043 PredList.pop_back();
1045 // If the predecessor was visited with PredPtr, then we already did
1046 // the analysis and can ignore it.
1047 if (InsertRes.first->second == PredPtrVal)
1050 // Otherwise, the block was previously analyzed with a different
1051 // pointer. We can't represent the result of this case, so we just
1052 // treat this as a phi translation failure.
1054 // Make sure to clean up the Visited map before continuing on to
1055 // PredTranslationFailure.
1056 for (unsigned i = 0; i < PredList.size(); i++)
1057 Visited.erase(PredList[i].first);
1059 goto PredTranslationFailure;
1063 // Actually process results here; this need to be a separate loop to avoid
1064 // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1065 // any results for. (getNonLocalPointerDepFromBB will modify our
1066 // datastructures in ways the code after the PredTranslationFailure label
1068 for (unsigned i = 0; i < PredList.size(); i++) {
1069 BasicBlock *Pred = PredList[i].first;
1070 PHITransAddr &PredPointer = PredList[i].second;
1071 Value *PredPtrVal = PredPointer.getAddr();
1073 bool CanTranslate = true;
1074 // If PHI translation was unable to find an available pointer in this
1075 // predecessor, then we have to assume that the pointer is clobbered in
1076 // that predecessor. We can still do PRE of the load, which would insert
1077 // a computation of the pointer in this predecessor.
1078 if (PredPtrVal == 0)
1079 CanTranslate = false;
1081 // FIXME: it is entirely possible that PHI translating will end up with
1082 // the same value. Consider PHI translating something like:
1083 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need*
1084 // to recurse here, pedantically speaking.
1086 // If getNonLocalPointerDepFromBB fails here, that means the cached
1087 // result conflicted with the Visited list; we have to conservatively
1088 // assume a clobber, but this also does not block PRE of the load.
1089 if (!CanTranslate ||
1090 getNonLocalPointerDepFromBB(PredPointer,
1091 Loc.getWithNewPtr(PredPtrVal),
1094 // Add the entry to the Result list.
1095 NonLocalDepResult Entry(Pred,
1096 MemDepResult::getClobber(Pred->getTerminator()),
1098 Result.push_back(Entry);
1100 // Since we had a phi translation failure, the cache for CacheKey won't
1101 // include all of the entries that we need to immediately satisfy future
1102 // queries. Mark this in NonLocalPointerDeps by setting the
1103 // BBSkipFirstBlockPair pointer to null. This requires reuse of the
1104 // cached value to do more work but not miss the phi trans failure.
1105 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1106 NLPI.Pair = BBSkipFirstBlockPair();
1111 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1112 CacheInfo = &NonLocalPointerDeps[CacheKey];
1113 Cache = &CacheInfo->NonLocalDeps;
1114 NumSortedEntries = Cache->size();
1116 // Since we did phi translation, the "Cache" set won't contain all of the
1117 // results for the query. This is ok (we can still use it to accelerate
1118 // specific block queries) but we can't do the fastpath "return all
1119 // results from the set" Clear out the indicator for this.
1120 CacheInfo->Pair = BBSkipFirstBlockPair();
1121 SkipFirstBlock = false;
1124 PredTranslationFailure:
1125 // The following code is "failure"; we can't produce a sane translation
1126 // for the given block. It assumes that we haven't modified any of
1127 // our datastructures while processing the current block.
1130 // Refresh the CacheInfo/Cache pointer if it got invalidated.
1131 CacheInfo = &NonLocalPointerDeps[CacheKey];
1132 Cache = &CacheInfo->NonLocalDeps;
1133 NumSortedEntries = Cache->size();
1136 // Since we failed phi translation, the "Cache" set won't contain all of the
1137 // results for the query. This is ok (we can still use it to accelerate
1138 // specific block queries) but we can't do the fastpath "return all
1139 // results from the set". Clear out the indicator for this.
1140 CacheInfo->Pair = BBSkipFirstBlockPair();
1142 // If *nothing* works, mark the pointer as being clobbered by the first
1143 // instruction in this block.
1145 // If this is the magic first block, return this as a clobber of the whole
1146 // incoming value. Since we can't phi translate to one of the predecessors,
1147 // we have to bail out.
1151 for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
1152 assert(I != Cache->rend() && "Didn't find current block??");
1153 if (I->getBB() != BB)
1156 assert(I->getResult().isNonLocal() &&
1157 "Should only be here with transparent block");
1158 I->setResult(MemDepResult::getClobber(BB->getTerminator()));
1159 ReverseNonLocalPtrDeps[BB->getTerminator()].insert(CacheKey);
1160 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
1161 Pointer.getAddr()));
1166 // Okay, we're done now. If we added new values to the cache, re-sort it.
1167 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1168 DEBUG(AssertSorted(*Cache));
1172 /// RemoveCachedNonLocalPointerDependencies - If P exists in
1173 /// CachedNonLocalPointerInfo, remove it.
1174 void MemoryDependenceAnalysis::
1175 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
1176 CachedNonLocalPointerInfo::iterator It =
1177 NonLocalPointerDeps.find(P);
1178 if (It == NonLocalPointerDeps.end()) return;
1180 // Remove all of the entries in the BB->val map. This involves removing
1181 // instructions from the reverse map.
1182 NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1184 for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1185 Instruction *Target = PInfo[i].getResult().getInst();
1186 if (Target == 0) continue; // Ignore non-local dep results.
1187 assert(Target->getParent() == PInfo[i].getBB());
1189 // Eliminating the dirty entry from 'Cache', so update the reverse info.
1190 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1193 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1194 NonLocalPointerDeps.erase(It);
1198 /// invalidateCachedPointerInfo - This method is used to invalidate cached
1199 /// information about the specified pointer, because it may be too
1200 /// conservative in memdep. This is an optional call that can be used when
1201 /// the client detects an equivalence between the pointer and some other
1202 /// value and replaces the other value with ptr. This can make Ptr available
1203 /// in more places that cached info does not necessarily keep.
1204 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
1205 // If Ptr isn't really a pointer, just ignore it.
1206 if (!Ptr->getType()->isPointerTy()) return;
1207 // Flush store info for the pointer.
1208 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1209 // Flush load info for the pointer.
1210 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1213 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
1214 /// This needs to be done when the CFG changes, e.g., due to splitting
1216 void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
1220 /// removeInstruction - Remove an instruction from the dependence analysis,
1221 /// updating the dependence of instructions that previously depended on it.
1222 /// This method attempts to keep the cache coherent using the reverse map.
1223 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
1224 // Walk through the Non-local dependencies, removing this one as the value
1225 // for any cached queries.
1226 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1227 if (NLDI != NonLocalDeps.end()) {
1228 NonLocalDepInfo &BlockMap = NLDI->second.first;
1229 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
1231 if (Instruction *Inst = DI->getResult().getInst())
1232 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1233 NonLocalDeps.erase(NLDI);
1236 // If we have a cached local dependence query for this instruction, remove it.
1238 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1239 if (LocalDepEntry != LocalDeps.end()) {
1240 // Remove us from DepInst's reverse set now that the local dep info is gone.
1241 if (Instruction *Inst = LocalDepEntry->second.getInst())
1242 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1244 // Remove this local dependency info.
1245 LocalDeps.erase(LocalDepEntry);
1248 // If we have any cached pointer dependencies on this instruction, remove
1249 // them. If the instruction has non-pointer type, then it can't be a pointer
1252 // Remove it from both the load info and the store info. The instruction
1253 // can't be in either of these maps if it is non-pointer.
1254 if (RemInst->getType()->isPointerTy()) {
1255 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1256 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1259 // Loop over all of the things that depend on the instruction we're removing.
1261 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
1263 // If we find RemInst as a clobber or Def in any of the maps for other values,
1264 // we need to replace its entry with a dirty version of the instruction after
1265 // it. If RemInst is a terminator, we use a null dirty value.
1267 // Using a dirty version of the instruction after RemInst saves having to scan
1268 // the entire block to get to this point.
1269 MemDepResult NewDirtyVal;
1270 if (!RemInst->isTerminator())
1271 NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
1273 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1274 if (ReverseDepIt != ReverseLocalDeps.end()) {
1275 SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
1276 // RemInst can't be the terminator if it has local stuff depending on it.
1277 assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
1278 "Nothing can locally depend on a terminator");
1280 for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
1281 E = ReverseDeps.end(); I != E; ++I) {
1282 Instruction *InstDependingOnRemInst = *I;
1283 assert(InstDependingOnRemInst != RemInst &&
1284 "Already removed our local dep info");
1286 LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1288 // Make sure to remember that new things depend on NewDepInst.
1289 assert(NewDirtyVal.getInst() && "There is no way something else can have "
1290 "a local dep on this if it is a terminator!");
1291 ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
1292 InstDependingOnRemInst));
1295 ReverseLocalDeps.erase(ReverseDepIt);
1297 // Add new reverse deps after scanning the set, to avoid invalidating the
1298 // 'ReverseDeps' reference.
1299 while (!ReverseDepsToAdd.empty()) {
1300 ReverseLocalDeps[ReverseDepsToAdd.back().first]
1301 .insert(ReverseDepsToAdd.back().second);
1302 ReverseDepsToAdd.pop_back();
1306 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1307 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1308 SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
1309 for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
1311 assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
1313 PerInstNLInfo &INLD = NonLocalDeps[*I];
1314 // The information is now dirty!
1317 for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
1318 DE = INLD.first.end(); DI != DE; ++DI) {
1319 if (DI->getResult().getInst() != RemInst) continue;
1321 // Convert to a dirty entry for the subsequent instruction.
1322 DI->setResult(NewDirtyVal);
1324 if (Instruction *NextI = NewDirtyVal.getInst())
1325 ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
1329 ReverseNonLocalDeps.erase(ReverseDepIt);
1331 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1332 while (!ReverseDepsToAdd.empty()) {
1333 ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
1334 .insert(ReverseDepsToAdd.back().second);
1335 ReverseDepsToAdd.pop_back();
1339 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1340 // value in the NonLocalPointerDeps info.
1341 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1342 ReverseNonLocalPtrDeps.find(RemInst);
1343 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1344 SmallPtrSet<ValueIsLoadPair, 4> &Set = ReversePtrDepIt->second;
1345 SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
1347 for (SmallPtrSet<ValueIsLoadPair, 4>::iterator I = Set.begin(),
1348 E = Set.end(); I != E; ++I) {
1349 ValueIsLoadPair P = *I;
1350 assert(P.getPointer() != RemInst &&
1351 "Already removed NonLocalPointerDeps info for RemInst");
1353 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1355 // The cache is not valid for any specific block anymore.
1356 NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1358 // Update any entries for RemInst to use the instruction after it.
1359 for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
1361 if (DI->getResult().getInst() != RemInst) continue;
1363 // Convert to a dirty entry for the subsequent instruction.
1364 DI->setResult(NewDirtyVal);
1366 if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1367 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1370 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its
1371 // subsequent value may invalidate the sortedness.
1372 std::sort(NLPDI.begin(), NLPDI.end());
1375 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1377 while (!ReversePtrDepsToAdd.empty()) {
1378 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
1379 .insert(ReversePtrDepsToAdd.back().second);
1380 ReversePtrDepsToAdd.pop_back();
1385 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1386 AA->deleteValue(RemInst);
1387 DEBUG(verifyRemoved(RemInst));
1389 /// verifyRemoved - Verify that the specified instruction does not occur
1390 /// in our internal data structures.
1391 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
1392 for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
1393 E = LocalDeps.end(); I != E; ++I) {
1394 assert(I->first != D && "Inst occurs in data structures");
1395 assert(I->second.getInst() != D &&
1396 "Inst occurs in data structures");
1399 for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
1400 E = NonLocalPointerDeps.end(); I != E; ++I) {
1401 assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
1402 const NonLocalDepInfo &Val = I->second.NonLocalDeps;
1403 for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
1405 assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
1408 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
1409 E = NonLocalDeps.end(); I != E; ++I) {
1410 assert(I->first != D && "Inst occurs in data structures");
1411 const PerInstNLInfo &INLD = I->second;
1412 for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
1413 EE = INLD.first.end(); II != EE; ++II)
1414 assert(II->getResult().getInst() != D && "Inst occurs in data structures");
1417 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
1418 E = ReverseLocalDeps.end(); I != E; ++I) {
1419 assert(I->first != D && "Inst occurs in data structures");
1420 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1421 EE = I->second.end(); II != EE; ++II)
1422 assert(*II != D && "Inst occurs in data structures");
1425 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
1426 E = ReverseNonLocalDeps.end();
1428 assert(I->first != D && "Inst occurs in data structures");
1429 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1430 EE = I->second.end(); II != EE; ++II)
1431 assert(*II != D && "Inst occurs in data structures");
1434 for (ReverseNonLocalPtrDepTy::const_iterator
1435 I = ReverseNonLocalPtrDeps.begin(),
1436 E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
1437 assert(I->first != D && "Inst occurs in rev NLPD map");
1439 for (SmallPtrSet<ValueIsLoadPair, 4>::const_iterator II = I->second.begin(),
1440 E = I->second.end(); II != E; ++II)
1441 assert(*II != ValueIsLoadPair(D, false) &&
1442 *II != ValueIsLoadPair(D, true) &&
1443 "Inst occurs in ReverseNonLocalPtrDeps map");