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/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Function.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/PHITransAddr.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Support/PredIteratorCache.h"
31 #include "llvm/Support/Debug.h"
34 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
35 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
36 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
38 STATISTIC(NumCacheNonLocalPtr,
39 "Number of fully cached non-local ptr responses");
40 STATISTIC(NumCacheDirtyNonLocalPtr,
41 "Number of cached, but dirty, non-local ptr responses");
42 STATISTIC(NumUncacheNonLocalPtr,
43 "Number of uncached non-local ptr responses");
44 STATISTIC(NumCacheCompleteNonLocalPtr,
45 "Number of block queries that were completely cached");
47 char MemoryDependenceAnalysis::ID = 0;
49 // Register this pass...
50 INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep",
51 "Memory Dependence Analysis", false, true)
52 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
53 INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep",
54 "Memory Dependence Analysis", false, true)
56 MemoryDependenceAnalysis::MemoryDependenceAnalysis()
57 : FunctionPass(ID), PredCache(0) {
58 initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry());
60 MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
63 /// Clean up memory in between runs
64 void MemoryDependenceAnalysis::releaseMemory() {
67 NonLocalPointerDeps.clear();
68 ReverseLocalDeps.clear();
69 ReverseNonLocalDeps.clear();
70 ReverseNonLocalPtrDeps.clear();
76 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
78 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
80 AU.addRequiredTransitive<AliasAnalysis>();
83 bool MemoryDependenceAnalysis::runOnFunction(Function &) {
84 AA = &getAnalysis<AliasAnalysis>();
86 PredCache.reset(new PredIteratorCache());
90 /// RemoveFromReverseMap - This is a helper function that removes Val from
91 /// 'Inst's set in ReverseMap. If the set becomes empty, remove Inst's entry.
92 template <typename KeyTy>
93 static void RemoveFromReverseMap(DenseMap<Instruction*,
94 SmallPtrSet<KeyTy, 4> > &ReverseMap,
95 Instruction *Inst, KeyTy Val) {
96 typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator
97 InstIt = ReverseMap.find(Inst);
98 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
99 bool Found = InstIt->second.erase(Val);
100 assert(Found && "Invalid reverse map!"); Found=Found;
101 if (InstIt->second.empty())
102 ReverseMap.erase(InstIt);
105 /// GetLocation - If the given instruction references a specific memory
106 /// location, fill in Loc with the details, otherwise set Loc.Ptr to null.
107 /// Return a ModRefInfo value describing the general behavior of the
110 AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst,
111 AliasAnalysis::Location &Loc,
113 if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
114 if (LI->isVolatile()) {
115 Loc = AliasAnalysis::Location();
116 return AliasAnalysis::ModRef;
118 Loc = AliasAnalysis::Location(LI->getPointerOperand(),
119 AA->getTypeStoreSize(LI->getType()),
120 LI->getMetadata(LLVMContext::MD_tbaa));
121 return AliasAnalysis::Ref;
124 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
125 if (SI->isVolatile()) {
126 Loc = AliasAnalysis::Location();
127 return AliasAnalysis::ModRef;
129 Loc = AliasAnalysis::Location(SI->getPointerOperand(),
130 AA->getTypeStoreSize(SI->getValueOperand()
132 SI->getMetadata(LLVMContext::MD_tbaa));
133 return AliasAnalysis::Mod;
136 if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
137 Loc = AliasAnalysis::Location(V->getPointerOperand(),
138 AA->getTypeStoreSize(V->getType()),
139 V->getMetadata(LLVMContext::MD_tbaa));
140 return AliasAnalysis::ModRef;
143 if (const CallInst *CI = isFreeCall(Inst)) {
144 // calls to free() deallocate the entire structure
145 Loc = AliasAnalysis::Location(CI->getArgOperand(0));
146 return AliasAnalysis::Mod;
149 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
150 switch (II->getIntrinsicID()) {
151 case Intrinsic::lifetime_start:
152 case Intrinsic::lifetime_end:
153 case Intrinsic::invariant_start:
154 Loc = AliasAnalysis::Location(II->getArgOperand(1),
155 cast<ConstantInt>(II->getArgOperand(0))
157 II->getMetadata(LLVMContext::MD_tbaa));
158 // These intrinsics don't really modify the memory, but returning Mod
159 // will allow them to be handled conservatively.
160 return AliasAnalysis::Mod;
161 case Intrinsic::invariant_end:
162 Loc = AliasAnalysis::Location(II->getArgOperand(2),
163 cast<ConstantInt>(II->getArgOperand(1))
165 II->getMetadata(LLVMContext::MD_tbaa));
166 // These intrinsics don't really modify the memory, but returning Mod
167 // will allow them to be handled conservatively.
168 return AliasAnalysis::Mod;
173 // Otherwise, just do the coarse-grained thing that always works.
174 if (Inst->mayWriteToMemory())
175 return AliasAnalysis::ModRef;
176 if (Inst->mayReadFromMemory())
177 return AliasAnalysis::Ref;
178 return AliasAnalysis::NoModRef;
181 /// getCallSiteDependencyFrom - Private helper for finding the local
182 /// dependencies of a call site.
183 MemDepResult MemoryDependenceAnalysis::
184 getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
185 BasicBlock::iterator ScanIt, BasicBlock *BB) {
186 // Walk backwards through the block, looking for dependencies
187 while (ScanIt != BB->begin()) {
188 Instruction *Inst = --ScanIt;
190 // If this inst is a memory op, get the pointer it accessed
191 AliasAnalysis::Location Loc;
192 AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA);
194 // A simple instruction.
195 if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef)
196 return MemDepResult::getClobber(Inst);
200 if (CallSite InstCS = cast<Value>(Inst)) {
201 // Debug intrinsics don't cause dependences.
202 if (isa<DbgInfoIntrinsic>(Inst)) continue;
203 // If these two calls do not interfere, look past it.
204 switch (AA->getModRefInfo(CS, InstCS)) {
205 case AliasAnalysis::NoModRef:
206 // If the two calls are the same, return InstCS as a Def, so that
207 // CS can be found redundant and eliminated.
208 if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) &&
209 CS.getInstruction()->isIdenticalToWhenDefined(Inst))
210 return MemDepResult::getDef(Inst);
212 // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
216 return MemDepResult::getClobber(Inst);
221 // No dependence found. If this is the entry block of the function, it is a
222 // clobber, otherwise it is non-local.
223 if (BB != &BB->getParent()->getEntryBlock())
224 return MemDepResult::getNonLocal();
225 return MemDepResult::getClobber(ScanIt);
228 /// getPointerDependencyFrom - Return the instruction on which a memory
229 /// location depends. If isLoad is true, this routine ignores may-aliases with
230 /// read-only operations. If isLoad is false, this routine ignores may-aliases
231 /// with reads from read-only locations.
232 MemDepResult MemoryDependenceAnalysis::
233 getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad,
234 BasicBlock::iterator ScanIt, BasicBlock *BB) {
236 Value *InvariantTag = 0;
238 // Walk backwards through the basic block, looking for dependencies.
239 while (ScanIt != BB->begin()) {
240 Instruction *Inst = --ScanIt;
242 // If we're in an invariant region, no dependencies can be found before
243 // we pass an invariant-begin marker.
244 if (InvariantTag == Inst) {
249 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
250 // Debug intrinsics don't (and can't) cause dependences.
251 if (isa<DbgInfoIntrinsic>(II)) continue;
253 // If we pass an invariant-end marker, then we've just entered an
254 // invariant region and can start ignoring dependencies.
255 if (II->getIntrinsicID() == Intrinsic::invariant_end) {
256 // FIXME: This only considers queries directly on the invariant-tagged
257 // pointer, not on query pointers that are indexed off of them. It'd
258 // be nice to handle that at some point.
259 AliasAnalysis::AliasResult R =
260 AA->alias(AliasAnalysis::Location(II->getArgOperand(2)), MemLoc);
261 if (R == AliasAnalysis::MustAlias)
262 InvariantTag = II->getArgOperand(0);
267 // If we reach a lifetime begin or end marker, then the query ends here
268 // because the value is undefined.
269 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
270 // FIXME: This only considers queries directly on the invariant-tagged
271 // pointer, not on query pointers that are indexed off of them. It'd
272 // be nice to handle that at some point.
273 AliasAnalysis::AliasResult R =
274 AA->alias(AliasAnalysis::Location(II->getArgOperand(1)), MemLoc);
275 if (R == AliasAnalysis::MustAlias)
276 return MemDepResult::getDef(II);
281 // If we're querying on a load and we're in an invariant region, we're done
282 // at this point. Nothing a load depends on can live in an invariant region.
284 // FIXME: this will prevent us from returning load/load must-aliases, so GVN
285 // won't remove redundant loads.
286 if (isLoad && InvariantTag) continue;
288 // Values depend on loads if the pointers are must aliased. This means that
289 // a load depends on another must aliased load from the same value.
290 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
291 Value *Pointer = LI->getPointerOperand();
292 uint64_t PointerSize = AA->getTypeStoreSize(LI->getType());
293 MDNode *TBAATag = LI->getMetadata(LLVMContext::MD_tbaa);
294 AliasAnalysis::Location LoadLoc(Pointer, PointerSize, TBAATag);
296 // If we found a pointer, check if it could be the same as our pointer.
297 AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc);
298 if (R == AliasAnalysis::NoAlias)
301 // May-alias loads don't depend on each other without a dependence.
302 if (isLoad && R == AliasAnalysis::MayAlias)
305 // Stores don't alias loads from read-only memory.
306 if (!isLoad && AA->pointsToConstantMemory(LoadLoc))
309 // Stores depend on may and must aliased loads, loads depend on must-alias
311 return MemDepResult::getDef(Inst);
314 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
315 // There can't be stores to the value we care about inside an
317 if (InvariantTag) continue;
319 // If alias analysis can tell that this store is guaranteed to not modify
320 // the query pointer, ignore it. Use getModRefInfo to handle cases where
321 // the query pointer points to constant memory etc.
322 if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
325 // Ok, this store might clobber the query pointer. Check to see if it is
326 // a must alias: in this case, we want to return this as a def.
327 Value *Pointer = SI->getPointerOperand();
328 uint64_t PointerSize = AA->getTypeStoreSize(SI->getOperand(0)->getType());
329 MDNode *TBAATag = SI->getMetadata(LLVMContext::MD_tbaa);
331 // If we found a pointer, check if it could be the same as our pointer.
332 AliasAnalysis::AliasResult R =
333 AA->alias(AliasAnalysis::Location(Pointer, PointerSize, TBAATag),
336 if (R == AliasAnalysis::NoAlias)
338 if (R == AliasAnalysis::MayAlias)
339 return MemDepResult::getClobber(Inst);
340 return MemDepResult::getDef(Inst);
343 // If this is an allocation, and if we know that the accessed pointer is to
344 // the allocation, return Def. This means that there is no dependence and
345 // the access can be optimized based on that. For example, a load could
347 // Note: Only determine this to be a malloc if Inst is the malloc call, not
348 // a subsequent bitcast of the malloc call result. There can be stores to
349 // the malloced memory between the malloc call and its bitcast uses, and we
350 // need to continue scanning until the malloc call.
351 if (isa<AllocaInst>(Inst) ||
352 (isa<CallInst>(Inst) && extractMallocCall(Inst))) {
353 const Value *AccessPtr = MemLoc.Ptr->getUnderlyingObject();
355 if (AccessPtr == Inst ||
356 AA->alias(Inst, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
357 return MemDepResult::getDef(Inst);
361 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
362 switch (AA->getModRefInfo(Inst, MemLoc)) {
363 case AliasAnalysis::NoModRef:
364 // If the call has no effect on the queried pointer, just ignore it.
366 case AliasAnalysis::Mod:
367 // If we're in an invariant region, we can ignore calls that ONLY
368 // modify the pointer.
369 if (InvariantTag) continue;
370 return MemDepResult::getClobber(Inst);
371 case AliasAnalysis::Ref:
372 // If the call is known to never store to the pointer, and if this is a
373 // load query, we can safely ignore it (scan past it).
377 // Otherwise, there is a potential dependence. Return a clobber.
378 return MemDepResult::getClobber(Inst);
382 // No dependence found. If this is the entry block of the function, it is a
383 // clobber, otherwise it is non-local.
384 if (BB != &BB->getParent()->getEntryBlock())
385 return MemDepResult::getNonLocal();
386 return MemDepResult::getClobber(ScanIt);
389 /// getDependency - Return the instruction on which a memory operation
391 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
392 Instruction *ScanPos = QueryInst;
394 // Check for a cached result
395 MemDepResult &LocalCache = LocalDeps[QueryInst];
397 // If the cached entry is non-dirty, just return it. Note that this depends
398 // on MemDepResult's default constructing to 'dirty'.
399 if (!LocalCache.isDirty())
402 // Otherwise, if we have a dirty entry, we know we can start the scan at that
403 // instruction, which may save us some work.
404 if (Instruction *Inst = LocalCache.getInst()) {
407 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
410 BasicBlock *QueryParent = QueryInst->getParent();
413 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
414 // No dependence found. If this is the entry block of the function, it is a
415 // clobber, otherwise it is non-local.
416 if (QueryParent != &QueryParent->getParent()->getEntryBlock())
417 LocalCache = MemDepResult::getNonLocal();
419 LocalCache = MemDepResult::getClobber(QueryInst);
421 AliasAnalysis::Location MemLoc;
422 AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
424 // If we can do a pointer scan, make it happen.
425 bool isLoad = !(MR & AliasAnalysis::Mod);
426 if (IntrinsicInst *II = dyn_cast<MemoryUseIntrinsic>(QueryInst)) {
427 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_end;
429 LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
431 } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
432 CallSite QueryCS(QueryInst);
433 bool isReadOnly = AA->onlyReadsMemory(QueryCS);
434 LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
437 // Non-memory instruction.
438 LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
441 // Remember the result!
442 if (Instruction *I = LocalCache.getInst())
443 ReverseLocalDeps[I].insert(QueryInst);
449 /// AssertSorted - This method is used when -debug is specified to verify that
450 /// cache arrays are properly kept sorted.
451 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
453 if (Count == -1) Count = Cache.size();
454 if (Count == 0) return;
456 for (unsigned i = 1; i != unsigned(Count); ++i)
457 assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
461 /// getNonLocalCallDependency - Perform a full dependency query for the
462 /// specified call, returning the set of blocks that the value is
463 /// potentially live across. The returned set of results will include a
464 /// "NonLocal" result for all blocks where the value is live across.
466 /// This method assumes the instruction returns a "NonLocal" dependency
467 /// within its own block.
469 /// This returns a reference to an internal data structure that may be
470 /// invalidated on the next non-local query or when an instruction is
471 /// removed. Clients must copy this data if they want it around longer than
473 const MemoryDependenceAnalysis::NonLocalDepInfo &
474 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
475 assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
476 "getNonLocalCallDependency should only be used on calls with non-local deps!");
477 PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
478 NonLocalDepInfo &Cache = CacheP.first;
480 /// DirtyBlocks - This is the set of blocks that need to be recomputed. In
481 /// the cached case, this can happen due to instructions being deleted etc. In
482 /// the uncached case, this starts out as the set of predecessors we care
484 SmallVector<BasicBlock*, 32> DirtyBlocks;
486 if (!Cache.empty()) {
487 // Okay, we have a cache entry. If we know it is not dirty, just return it
488 // with no computation.
489 if (!CacheP.second) {
494 // If we already have a partially computed set of results, scan them to
495 // determine what is dirty, seeding our initial DirtyBlocks worklist.
496 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
498 if (I->getResult().isDirty())
499 DirtyBlocks.push_back(I->getBB());
501 // Sort the cache so that we can do fast binary search lookups below.
502 std::sort(Cache.begin(), Cache.end());
504 ++NumCacheDirtyNonLocal;
505 //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
506 // << Cache.size() << " cached: " << *QueryInst;
508 // Seed DirtyBlocks with each of the preds of QueryInst's block.
509 BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
510 for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
511 DirtyBlocks.push_back(*PI);
512 ++NumUncacheNonLocal;
515 // isReadonlyCall - If this is a read-only call, we can be more aggressive.
516 bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
518 SmallPtrSet<BasicBlock*, 64> Visited;
520 unsigned NumSortedEntries = Cache.size();
521 DEBUG(AssertSorted(Cache));
523 // Iterate while we still have blocks to update.
524 while (!DirtyBlocks.empty()) {
525 BasicBlock *DirtyBB = DirtyBlocks.back();
526 DirtyBlocks.pop_back();
528 // Already processed this block?
529 if (!Visited.insert(DirtyBB))
532 // Do a binary search to see if we already have an entry for this block in
533 // the cache set. If so, find it.
534 DEBUG(AssertSorted(Cache, NumSortedEntries));
535 NonLocalDepInfo::iterator Entry =
536 std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
537 NonLocalDepEntry(DirtyBB));
538 if (Entry != Cache.begin() && prior(Entry)->getBB() == DirtyBB)
541 NonLocalDepEntry *ExistingResult = 0;
542 if (Entry != Cache.begin()+NumSortedEntries &&
543 Entry->getBB() == DirtyBB) {
544 // If we already have an entry, and if it isn't already dirty, the block
546 if (!Entry->getResult().isDirty())
549 // Otherwise, remember this slot so we can update the value.
550 ExistingResult = &*Entry;
553 // If the dirty entry has a pointer, start scanning from it so we don't have
554 // to rescan the entire block.
555 BasicBlock::iterator ScanPos = DirtyBB->end();
556 if (ExistingResult) {
557 if (Instruction *Inst = ExistingResult->getResult().getInst()) {
559 // We're removing QueryInst's use of Inst.
560 RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
561 QueryCS.getInstruction());
565 // Find out if this block has a local dependency for QueryInst.
568 if (ScanPos != DirtyBB->begin()) {
569 Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
570 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
571 // No dependence found. If this is the entry block of the function, it is
572 // a clobber, otherwise it is non-local.
573 Dep = MemDepResult::getNonLocal();
575 Dep = MemDepResult::getClobber(ScanPos);
578 // If we had a dirty entry for the block, update it. Otherwise, just add
581 ExistingResult->setResult(Dep);
583 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
585 // If the block has a dependency (i.e. it isn't completely transparent to
586 // the value), remember the association!
587 if (!Dep.isNonLocal()) {
588 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
589 // update this when we remove instructions.
590 if (Instruction *Inst = Dep.getInst())
591 ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
594 // If the block *is* completely transparent to the load, we need to check
595 // the predecessors of this block. Add them to our worklist.
596 for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
597 DirtyBlocks.push_back(*PI);
604 /// getNonLocalPointerDependency - Perform a full dependency query for an
605 /// access to the specified (non-volatile) memory location, returning the
606 /// set of instructions that either define or clobber the value.
608 /// This method assumes the pointer has a "NonLocal" dependency within its
611 void MemoryDependenceAnalysis::
612 getNonLocalPointerDependency(const AliasAnalysis::Location &Loc, bool isLoad,
614 SmallVectorImpl<NonLocalDepResult> &Result) {
615 assert(Loc.Ptr->getType()->isPointerTy() &&
616 "Can't get pointer deps of a non-pointer!");
619 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), TD);
621 // This is the set of blocks we've inspected, and the pointer we consider in
622 // each block. Because of critical edges, we currently bail out if querying
623 // a block with multiple different pointers. This can happen during PHI
625 DenseMap<BasicBlock*, Value*> Visited;
626 if (!getNonLocalPointerDepFromBB(Address, Loc, isLoad, FromBB,
627 Result, Visited, true))
630 Result.push_back(NonLocalDepResult(FromBB,
631 MemDepResult::getClobber(FromBB->begin()),
632 const_cast<Value *>(Loc.Ptr)));
635 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
636 /// Pointer/PointeeSize using either cached information in Cache or by doing a
637 /// lookup (which may use dirty cache info if available). If we do a lookup,
638 /// add the result to the cache.
639 MemDepResult MemoryDependenceAnalysis::
640 GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
641 bool isLoad, BasicBlock *BB,
642 NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
644 // Do a binary search to see if we already have an entry for this block in
645 // the cache set. If so, find it.
646 NonLocalDepInfo::iterator Entry =
647 std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
648 NonLocalDepEntry(BB));
649 if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
652 NonLocalDepEntry *ExistingResult = 0;
653 if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
654 ExistingResult = &*Entry;
656 // If we have a cached entry, and it is non-dirty, use it as the value for
658 if (ExistingResult && !ExistingResult->getResult().isDirty()) {
659 ++NumCacheNonLocalPtr;
660 return ExistingResult->getResult();
663 // Otherwise, we have to scan for the value. If we have a dirty cache
664 // entry, start scanning from its position, otherwise we scan from the end
666 BasicBlock::iterator ScanPos = BB->end();
667 if (ExistingResult && ExistingResult->getResult().getInst()) {
668 assert(ExistingResult->getResult().getInst()->getParent() == BB &&
669 "Instruction invalidated?");
670 ++NumCacheDirtyNonLocalPtr;
671 ScanPos = ExistingResult->getResult().getInst();
673 // Eliminating the dirty entry from 'Cache', so update the reverse info.
674 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
675 RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
677 ++NumUncacheNonLocalPtr;
680 // Scan the block for the dependency.
681 MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB);
683 // If we had a dirty entry for the block, update it. Otherwise, just add
686 ExistingResult->setResult(Dep);
688 Cache->push_back(NonLocalDepEntry(BB, Dep));
690 // If the block has a dependency (i.e. it isn't completely transparent to
691 // the value), remember the reverse association because we just added it
693 if (Dep.isNonLocal())
696 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
697 // update MemDep when we remove instructions.
698 Instruction *Inst = Dep.getInst();
699 assert(Inst && "Didn't depend on anything?");
700 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
701 ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
705 /// SortNonLocalDepInfoCache - Sort the a NonLocalDepInfo cache, given a certain
706 /// number of elements in the array that are already properly ordered. This is
707 /// optimized for the case when only a few entries are added.
709 SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
710 unsigned NumSortedEntries) {
711 switch (Cache.size() - NumSortedEntries) {
713 // done, no new entries.
716 // Two new entries, insert the last one into place.
717 NonLocalDepEntry Val = Cache.back();
719 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
720 std::upper_bound(Cache.begin(), Cache.end()-1, Val);
721 Cache.insert(Entry, Val);
725 // One new entry, Just insert the new value at the appropriate position.
726 if (Cache.size() != 1) {
727 NonLocalDepEntry Val = Cache.back();
729 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
730 std::upper_bound(Cache.begin(), Cache.end(), Val);
731 Cache.insert(Entry, Val);
735 // Added many values, do a full scale sort.
736 std::sort(Cache.begin(), Cache.end());
741 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
742 /// pointer/pointeesize starting at the end of StartBB. Add any clobber/def
743 /// results to the results vector and keep track of which blocks are visited in
746 /// This has special behavior for the first block queries (when SkipFirstBlock
747 /// is true). In this special case, it ignores the contents of the specified
748 /// block and starts returning dependence info for its predecessors.
750 /// This function returns false on success, or true to indicate that it could
751 /// not compute dependence information for some reason. This should be treated
752 /// as a clobber dependence on the first instruction in the predecessor block.
753 bool MemoryDependenceAnalysis::
754 getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
755 const AliasAnalysis::Location &Loc,
756 bool isLoad, BasicBlock *StartBB,
757 SmallVectorImpl<NonLocalDepResult> &Result,
758 DenseMap<BasicBlock*, Value*> &Visited,
759 bool SkipFirstBlock) {
761 // Look up the cached info for Pointer.
762 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
764 // Set up a temporary NLPI value. If the map doesn't yet have an entry for
765 // CacheKey, this value will be inserted as the associated value. Otherwise,
766 // it'll be ignored, and we'll have to check to see if the cached size and
767 // tbaa tag are consistent with the current query.
768 NonLocalPointerInfo InitialNLPI;
769 InitialNLPI.Size = Loc.Size;
770 InitialNLPI.TBAATag = Loc.TBAATag;
772 // Get the NLPI for CacheKey, inserting one into the map if it doesn't
774 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
775 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
776 NonLocalPointerInfo *CacheInfo = &Pair.first->second;
778 // If we already have a cache entry for this CacheKey, we may need to do some
779 // work to reconcile the cache entry and the current query.
781 if (CacheInfo->Size < Loc.Size) {
782 // The query's Size is greater than the cached one. Throw out the
783 // cached data and procede with the query at the greater size.
784 CacheInfo->Pair = BBSkipFirstBlockPair();
785 CacheInfo->Size = Loc.Size;
786 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
787 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
788 if (Instruction *Inst = DI->getResult().getInst())
789 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
790 CacheInfo->NonLocalDeps.clear();
791 } else if (CacheInfo->Size > Loc.Size) {
792 // This query's Size is less than the cached one. Conservatively restart
793 // the query using the greater size.
794 return getNonLocalPointerDepFromBB(Pointer,
795 Loc.getWithNewSize(CacheInfo->Size),
796 isLoad, StartBB, Result, Visited,
800 // If the query's TBAATag is inconsistent with the cached one,
801 // conservatively throw out the cached data and restart the query with
803 if (CacheInfo->TBAATag != Loc.TBAATag) {
804 if (CacheInfo->TBAATag) {
805 CacheInfo->Pair = BBSkipFirstBlockPair();
806 CacheInfo->TBAATag = 0;
807 for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
808 DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
809 if (Instruction *Inst = DI->getResult().getInst())
810 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
811 CacheInfo->NonLocalDeps.clear();
814 return getNonLocalPointerDepFromBB(Pointer, Loc.getWithoutTBAATag(),
815 isLoad, StartBB, Result, Visited,
820 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
822 // If we have valid cached information for exactly the block we are
823 // investigating, just return it with no recomputation.
824 if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
825 // We have a fully cached result for this query then we can just return the
826 // cached results and populate the visited set. However, we have to verify
827 // that we don't already have conflicting results for these blocks. Check
828 // to ensure that if a block in the results set is in the visited set that
829 // it was for the same pointer query.
830 if (!Visited.empty()) {
831 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
833 DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
834 if (VI == Visited.end() || VI->second == Pointer.getAddr())
837 // We have a pointer mismatch in a block. Just return clobber, saying
838 // that something was clobbered in this result. We could also do a
839 // non-fully cached query, but there is little point in doing this.
844 Value *Addr = Pointer.getAddr();
845 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
847 Visited.insert(std::make_pair(I->getBB(), Addr));
848 if (!I->getResult().isNonLocal())
849 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
851 ++NumCacheCompleteNonLocalPtr;
855 // Otherwise, either this is a new block, a block with an invalid cache
856 // pointer or one that we're about to invalidate by putting more info into it
857 // than its valid cache info. If empty, the result will be valid cache info,
858 // otherwise it isn't.
860 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
862 CacheInfo->Pair = BBSkipFirstBlockPair();
863 CacheInfo->Size = AliasAnalysis::UnknownSize;
864 CacheInfo->TBAATag = 0;
867 SmallVector<BasicBlock*, 32> Worklist;
868 Worklist.push_back(StartBB);
870 // Keep track of the entries that we know are sorted. Previously cached
871 // entries will all be sorted. The entries we add we only sort on demand (we
872 // don't insert every element into its sorted position). We know that we
873 // won't get any reuse from currently inserted values, because we don't
874 // revisit blocks after we insert info for them.
875 unsigned NumSortedEntries = Cache->size();
876 DEBUG(AssertSorted(*Cache));
878 while (!Worklist.empty()) {
879 BasicBlock *BB = Worklist.pop_back_val();
881 // Skip the first block if we have it.
882 if (!SkipFirstBlock) {
883 // Analyze the dependency of *Pointer in FromBB. See if we already have
885 assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
887 // Get the dependency info for Pointer in BB. If we have cached
888 // information, we will use it, otherwise we compute it.
889 DEBUG(AssertSorted(*Cache, NumSortedEntries));
890 MemDepResult Dep = GetNonLocalInfoForBlock(Loc, isLoad, BB, Cache,
893 // If we got a Def or Clobber, add this to the list of results.
894 if (!Dep.isNonLocal()) {
895 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
900 // If 'Pointer' is an instruction defined in this block, then we need to do
901 // phi translation to change it into a value live in the predecessor block.
902 // If not, we just add the predecessors to the worklist and scan them with
904 if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
905 SkipFirstBlock = false;
906 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
907 // Verify that we haven't looked at this block yet.
908 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
909 InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
910 if (InsertRes.second) {
911 // First time we've looked at *PI.
912 Worklist.push_back(*PI);
916 // If we have seen this block before, but it was with a different
917 // pointer then we have a phi translation failure and we have to treat
918 // this as a clobber.
919 if (InsertRes.first->second != Pointer.getAddr())
920 goto PredTranslationFailure;
925 // We do need to do phi translation, if we know ahead of time we can't phi
926 // translate this value, don't even try.
927 if (!Pointer.IsPotentiallyPHITranslatable())
928 goto PredTranslationFailure;
930 // We may have added values to the cache list before this PHI translation.
931 // If so, we haven't done anything to ensure that the cache remains sorted.
932 // Sort it now (if needed) so that recursive invocations of
933 // getNonLocalPointerDepFromBB and other routines that could reuse the cache
934 // value will only see properly sorted cache arrays.
935 if (Cache && NumSortedEntries != Cache->size()) {
936 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
937 NumSortedEntries = Cache->size();
941 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
942 BasicBlock *Pred = *PI;
944 // Get the PHI translated pointer in this predecessor. This can fail if
945 // not translatable, in which case the getAddr() returns null.
946 PHITransAddr PredPointer(Pointer);
947 PredPointer.PHITranslateValue(BB, Pred, 0);
949 Value *PredPtrVal = PredPointer.getAddr();
951 // Check to see if we have already visited this pred block with another
952 // pointer. If so, we can't do this lookup. This failure can occur
953 // with PHI translation when a critical edge exists and the PHI node in
954 // the successor translates to a pointer value different than the
955 // pointer the block was first analyzed with.
956 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
957 InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
959 if (!InsertRes.second) {
960 // If the predecessor was visited with PredPtr, then we already did
961 // the analysis and can ignore it.
962 if (InsertRes.first->second == PredPtrVal)
965 // Otherwise, the block was previously analyzed with a different
966 // pointer. We can't represent the result of this case, so we just
967 // treat this as a phi translation failure.
968 goto PredTranslationFailure;
971 // If PHI translation was unable to find an available pointer in this
972 // predecessor, then we have to assume that the pointer is clobbered in
973 // that predecessor. We can still do PRE of the load, which would insert
974 // a computation of the pointer in this predecessor.
975 if (PredPtrVal == 0) {
976 // Add the entry to the Result list.
977 NonLocalDepResult Entry(Pred,
978 MemDepResult::getClobber(Pred->getTerminator()),
980 Result.push_back(Entry);
982 // Since we had a phi translation failure, the cache for CacheKey won't
983 // include all of the entries that we need to immediately satisfy future
984 // queries. Mark this in NonLocalPointerDeps by setting the
985 // BBSkipFirstBlockPair pointer to null. This requires reuse of the
986 // cached value to do more work but not miss the phi trans failure.
987 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
988 NLPI.Pair = BBSkipFirstBlockPair();
989 NLPI.Size = AliasAnalysis::UnknownSize;
994 // FIXME: it is entirely possible that PHI translating will end up with
995 // the same value. Consider PHI translating something like:
996 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need*
997 // to recurse here, pedantically speaking.
999 // If we have a problem phi translating, fall through to the code below
1000 // to handle the failure condition.
1001 if (getNonLocalPointerDepFromBB(PredPointer,
1002 Loc.getWithNewPtr(PredPointer.getAddr()),
1005 goto PredTranslationFailure;
1008 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1009 CacheInfo = &NonLocalPointerDeps[CacheKey];
1010 Cache = &CacheInfo->NonLocalDeps;
1011 NumSortedEntries = Cache->size();
1013 // Since we did phi translation, the "Cache" set won't contain all of the
1014 // results for the query. This is ok (we can still use it to accelerate
1015 // specific block queries) but we can't do the fastpath "return all
1016 // results from the set" Clear out the indicator for this.
1017 CacheInfo->Pair = BBSkipFirstBlockPair();
1018 CacheInfo->Size = AliasAnalysis::UnknownSize;
1019 CacheInfo->TBAATag = 0;
1020 SkipFirstBlock = false;
1023 PredTranslationFailure:
1026 // Refresh the CacheInfo/Cache pointer if it got invalidated.
1027 CacheInfo = &NonLocalPointerDeps[CacheKey];
1028 Cache = &CacheInfo->NonLocalDeps;
1029 NumSortedEntries = Cache->size();
1032 // Since we failed phi translation, the "Cache" set won't contain all of the
1033 // results for the query. This is ok (we can still use it to accelerate
1034 // specific block queries) but we can't do the fastpath "return all
1035 // results from the set". Clear out the indicator for this.
1036 CacheInfo->Pair = BBSkipFirstBlockPair();
1037 CacheInfo->Size = AliasAnalysis::UnknownSize;
1038 CacheInfo->TBAATag = 0;
1040 // If *nothing* works, mark the pointer as being clobbered by the first
1041 // instruction in this block.
1043 // If this is the magic first block, return this as a clobber of the whole
1044 // incoming value. Since we can't phi translate to one of the predecessors,
1045 // we have to bail out.
1049 for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
1050 assert(I != Cache->rend() && "Didn't find current block??");
1051 if (I->getBB() != BB)
1054 assert(I->getResult().isNonLocal() &&
1055 "Should only be here with transparent block");
1056 I->setResult(MemDepResult::getClobber(BB->begin()));
1057 ReverseNonLocalPtrDeps[BB->begin()].insert(CacheKey);
1058 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
1059 Pointer.getAddr()));
1064 // Okay, we're done now. If we added new values to the cache, re-sort it.
1065 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1066 DEBUG(AssertSorted(*Cache));
1070 /// RemoveCachedNonLocalPointerDependencies - If P exists in
1071 /// CachedNonLocalPointerInfo, remove it.
1072 void MemoryDependenceAnalysis::
1073 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
1074 CachedNonLocalPointerInfo::iterator It =
1075 NonLocalPointerDeps.find(P);
1076 if (It == NonLocalPointerDeps.end()) return;
1078 // Remove all of the entries in the BB->val map. This involves removing
1079 // instructions from the reverse map.
1080 NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1082 for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1083 Instruction *Target = PInfo[i].getResult().getInst();
1084 if (Target == 0) continue; // Ignore non-local dep results.
1085 assert(Target->getParent() == PInfo[i].getBB());
1087 // Eliminating the dirty entry from 'Cache', so update the reverse info.
1088 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1091 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1092 NonLocalPointerDeps.erase(It);
1096 /// invalidateCachedPointerInfo - This method is used to invalidate cached
1097 /// information about the specified pointer, because it may be too
1098 /// conservative in memdep. This is an optional call that can be used when
1099 /// the client detects an equivalence between the pointer and some other
1100 /// value and replaces the other value with ptr. This can make Ptr available
1101 /// in more places that cached info does not necessarily keep.
1102 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
1103 // If Ptr isn't really a pointer, just ignore it.
1104 if (!Ptr->getType()->isPointerTy()) return;
1105 // Flush store info for the pointer.
1106 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1107 // Flush load info for the pointer.
1108 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1111 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
1112 /// This needs to be done when the CFG changes, e.g., due to splitting
1114 void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
1118 /// removeInstruction - Remove an instruction from the dependence analysis,
1119 /// updating the dependence of instructions that previously depended on it.
1120 /// This method attempts to keep the cache coherent using the reverse map.
1121 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
1122 // Walk through the Non-local dependencies, removing this one as the value
1123 // for any cached queries.
1124 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1125 if (NLDI != NonLocalDeps.end()) {
1126 NonLocalDepInfo &BlockMap = NLDI->second.first;
1127 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
1129 if (Instruction *Inst = DI->getResult().getInst())
1130 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1131 NonLocalDeps.erase(NLDI);
1134 // If we have a cached local dependence query for this instruction, remove it.
1136 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1137 if (LocalDepEntry != LocalDeps.end()) {
1138 // Remove us from DepInst's reverse set now that the local dep info is gone.
1139 if (Instruction *Inst = LocalDepEntry->second.getInst())
1140 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1142 // Remove this local dependency info.
1143 LocalDeps.erase(LocalDepEntry);
1146 // If we have any cached pointer dependencies on this instruction, remove
1147 // them. If the instruction has non-pointer type, then it can't be a pointer
1150 // Remove it from both the load info and the store info. The instruction
1151 // can't be in either of these maps if it is non-pointer.
1152 if (RemInst->getType()->isPointerTy()) {
1153 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1154 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1157 // Loop over all of the things that depend on the instruction we're removing.
1159 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
1161 // If we find RemInst as a clobber or Def in any of the maps for other values,
1162 // we need to replace its entry with a dirty version of the instruction after
1163 // it. If RemInst is a terminator, we use a null dirty value.
1165 // Using a dirty version of the instruction after RemInst saves having to scan
1166 // the entire block to get to this point.
1167 MemDepResult NewDirtyVal;
1168 if (!RemInst->isTerminator())
1169 NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
1171 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1172 if (ReverseDepIt != ReverseLocalDeps.end()) {
1173 SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
1174 // RemInst can't be the terminator if it has local stuff depending on it.
1175 assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
1176 "Nothing can locally depend on a terminator");
1178 for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
1179 E = ReverseDeps.end(); I != E; ++I) {
1180 Instruction *InstDependingOnRemInst = *I;
1181 assert(InstDependingOnRemInst != RemInst &&
1182 "Already removed our local dep info");
1184 LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1186 // Make sure to remember that new things depend on NewDepInst.
1187 assert(NewDirtyVal.getInst() && "There is no way something else can have "
1188 "a local dep on this if it is a terminator!");
1189 ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
1190 InstDependingOnRemInst));
1193 ReverseLocalDeps.erase(ReverseDepIt);
1195 // Add new reverse deps after scanning the set, to avoid invalidating the
1196 // 'ReverseDeps' reference.
1197 while (!ReverseDepsToAdd.empty()) {
1198 ReverseLocalDeps[ReverseDepsToAdd.back().first]
1199 .insert(ReverseDepsToAdd.back().second);
1200 ReverseDepsToAdd.pop_back();
1204 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1205 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1206 SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
1207 for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
1209 assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
1211 PerInstNLInfo &INLD = NonLocalDeps[*I];
1212 // The information is now dirty!
1215 for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
1216 DE = INLD.first.end(); DI != DE; ++DI) {
1217 if (DI->getResult().getInst() != RemInst) continue;
1219 // Convert to a dirty entry for the subsequent instruction.
1220 DI->setResult(NewDirtyVal);
1222 if (Instruction *NextI = NewDirtyVal.getInst())
1223 ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
1227 ReverseNonLocalDeps.erase(ReverseDepIt);
1229 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1230 while (!ReverseDepsToAdd.empty()) {
1231 ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
1232 .insert(ReverseDepsToAdd.back().second);
1233 ReverseDepsToAdd.pop_back();
1237 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1238 // value in the NonLocalPointerDeps info.
1239 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1240 ReverseNonLocalPtrDeps.find(RemInst);
1241 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1242 SmallPtrSet<ValueIsLoadPair, 4> &Set = ReversePtrDepIt->second;
1243 SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
1245 for (SmallPtrSet<ValueIsLoadPair, 4>::iterator I = Set.begin(),
1246 E = Set.end(); I != E; ++I) {
1247 ValueIsLoadPair P = *I;
1248 assert(P.getPointer() != RemInst &&
1249 "Already removed NonLocalPointerDeps info for RemInst");
1251 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1253 // The cache is not valid for any specific block anymore.
1254 NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1255 NonLocalPointerDeps[P].Size = AliasAnalysis::UnknownSize;
1256 NonLocalPointerDeps[P].TBAATag = 0;
1258 // Update any entries for RemInst to use the instruction after it.
1259 for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
1261 if (DI->getResult().getInst() != RemInst) continue;
1263 // Convert to a dirty entry for the subsequent instruction.
1264 DI->setResult(NewDirtyVal);
1266 if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1267 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1270 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its
1271 // subsequent value may invalidate the sortedness.
1272 std::sort(NLPDI.begin(), NLPDI.end());
1275 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1277 while (!ReversePtrDepsToAdd.empty()) {
1278 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
1279 .insert(ReversePtrDepsToAdd.back().second);
1280 ReversePtrDepsToAdd.pop_back();
1285 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1286 AA->deleteValue(RemInst);
1287 DEBUG(verifyRemoved(RemInst));
1289 /// verifyRemoved - Verify that the specified instruction does not occur
1290 /// in our internal data structures.
1291 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
1292 for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
1293 E = LocalDeps.end(); I != E; ++I) {
1294 assert(I->first != D && "Inst occurs in data structures");
1295 assert(I->second.getInst() != D &&
1296 "Inst occurs in data structures");
1299 for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
1300 E = NonLocalPointerDeps.end(); I != E; ++I) {
1301 assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
1302 const NonLocalDepInfo &Val = I->second.NonLocalDeps;
1303 for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
1305 assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
1308 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
1309 E = NonLocalDeps.end(); I != E; ++I) {
1310 assert(I->first != D && "Inst occurs in data structures");
1311 const PerInstNLInfo &INLD = I->second;
1312 for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
1313 EE = INLD.first.end(); II != EE; ++II)
1314 assert(II->getResult().getInst() != D && "Inst occurs in data structures");
1317 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
1318 E = ReverseLocalDeps.end(); I != E; ++I) {
1319 assert(I->first != D && "Inst occurs in data structures");
1320 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1321 EE = I->second.end(); II != EE; ++II)
1322 assert(*II != D && "Inst occurs in data structures");
1325 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
1326 E = ReverseNonLocalDeps.end();
1328 assert(I->first != D && "Inst occurs in data structures");
1329 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1330 EE = I->second.end(); II != EE; ++II)
1331 assert(*II != D && "Inst occurs in data structures");
1334 for (ReverseNonLocalPtrDepTy::const_iterator
1335 I = ReverseNonLocalPtrDeps.begin(),
1336 E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
1337 assert(I->first != D && "Inst occurs in rev NLPD map");
1339 for (SmallPtrSet<ValueIsLoadPair, 4>::const_iterator II = I->second.begin(),
1340 E = I->second.end(); II != E; ++II)
1341 assert(*II != ValueIsLoadPair(D, false) &&
1342 *II != ValueIsLoadPair(D, true) &&
1343 "Inst occurs in ReverseNonLocalPtrDeps map");