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/Constants.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Function.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Support/PredIteratorCache.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Target/TargetData.h"
29 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
30 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
31 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
33 STATISTIC(NumCacheNonLocalPtr,
34 "Number of fully cached non-local ptr responses");
35 STATISTIC(NumCacheDirtyNonLocalPtr,
36 "Number of cached, but dirty, non-local ptr responses");
37 STATISTIC(NumUncacheNonLocalPtr,
38 "Number of uncached non-local ptr responses");
39 STATISTIC(NumCacheCompleteNonLocalPtr,
40 "Number of block queries that were completely cached");
42 char MemoryDependenceAnalysis::ID = 0;
44 // Register this pass...
45 static RegisterPass<MemoryDependenceAnalysis> X("memdep",
46 "Memory Dependence Analysis", false, true);
48 MemoryDependenceAnalysis::MemoryDependenceAnalysis()
49 : FunctionPass(&ID), PredCache(0) {
51 MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
54 /// Clean up memory in between runs
55 void MemoryDependenceAnalysis::releaseMemory() {
58 NonLocalPointerDeps.clear();
59 ReverseLocalDeps.clear();
60 ReverseNonLocalDeps.clear();
61 ReverseNonLocalPtrDeps.clear();
67 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
69 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequiredTransitive<AliasAnalysis>();
72 AU.addRequiredTransitive<TargetData>();
75 bool MemoryDependenceAnalysis::runOnFunction(Function &) {
76 AA = &getAnalysis<AliasAnalysis>();
77 TD = &getAnalysis<TargetData>();
79 PredCache.reset(new PredIteratorCache());
83 /// RemoveFromReverseMap - This is a helper function that removes Val from
84 /// 'Inst's set in ReverseMap. If the set becomes empty, remove Inst's entry.
85 template <typename KeyTy>
86 static void RemoveFromReverseMap(DenseMap<Instruction*,
87 SmallPtrSet<KeyTy*, 4> > &ReverseMap,
88 Instruction *Inst, KeyTy *Val) {
89 typename DenseMap<Instruction*, SmallPtrSet<KeyTy*, 4> >::iterator
90 InstIt = ReverseMap.find(Inst);
91 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
92 bool Found = InstIt->second.erase(Val);
93 assert(Found && "Invalid reverse map!"); Found=Found;
94 if (InstIt->second.empty())
95 ReverseMap.erase(InstIt);
99 /// getCallSiteDependencyFrom - Private helper for finding the local
100 /// dependencies of a call site.
101 MemDepResult MemoryDependenceAnalysis::
102 getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
103 BasicBlock::iterator ScanIt, BasicBlock *BB) {
104 // Walk backwards through the block, looking for dependencies
105 while (ScanIt != BB->begin()) {
106 Instruction *Inst = --ScanIt;
108 // If this inst is a memory op, get the pointer it accessed
110 uint64_t PointerSize = 0;
111 if (StoreInst *S = dyn_cast<StoreInst>(Inst)) {
112 Pointer = S->getPointerOperand();
113 PointerSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
114 } else if (VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
115 Pointer = V->getOperand(0);
116 PointerSize = TD->getTypeStoreSize(V->getType());
117 } else if (FreeInst *F = dyn_cast<FreeInst>(Inst)) {
118 Pointer = F->getPointerOperand();
120 // FreeInsts erase the entire structure
122 } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
123 CallSite InstCS = CallSite::get(Inst);
124 // If these two calls do not interfere, look past it.
125 switch (AA->getModRefInfo(CS, InstCS)) {
126 case AliasAnalysis::NoModRef:
127 // If the two calls don't interact (e.g. InstCS is readnone) keep
130 case AliasAnalysis::Ref:
131 // If the two calls read the same memory locations and CS is a readonly
132 // function, then we have two cases: 1) the calls may not interfere with
133 // each other at all. 2) the calls may produce the same value. In case
134 // #1 we want to ignore the values, in case #2, we want to return Inst
135 // as a Def dependence. This allows us to CSE in cases like:
138 // Y = strlen(P); // Y = X
139 if (isReadOnlyCall) {
140 if (CS.getCalledFunction() != 0 &&
141 CS.getCalledFunction() == InstCS.getCalledFunction())
142 return MemDepResult::getDef(Inst);
143 // Ignore unrelated read/read call dependences.
148 return MemDepResult::getClobber(Inst);
151 // Non-memory instruction.
155 if (AA->getModRefInfo(CS, Pointer, PointerSize) != AliasAnalysis::NoModRef)
156 return MemDepResult::getClobber(Inst);
159 // No dependence found. If this is the entry block of the function, it is a
160 // clobber, otherwise it is non-local.
161 if (BB != &BB->getParent()->getEntryBlock())
162 return MemDepResult::getNonLocal();
163 return MemDepResult::getClobber(ScanIt);
166 /// getPointerDependencyFrom - Return the instruction on which a memory
167 /// location depends. If isLoad is true, this routine ignore may-aliases with
168 /// read-only operations.
169 MemDepResult MemoryDependenceAnalysis::
170 getPointerDependencyFrom(Value *MemPtr, uint64_t MemSize, bool isLoad,
171 BasicBlock::iterator ScanIt, BasicBlock *BB) {
173 // Walk backwards through the basic block, looking for dependencies.
174 while (ScanIt != BB->begin()) {
175 Instruction *Inst = --ScanIt;
177 // Values depend on loads if the pointers are must aliased. This means that
178 // a load depends on another must aliased load from the same value.
179 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
180 Value *Pointer = LI->getPointerOperand();
181 uint64_t PointerSize = TD->getTypeStoreSize(LI->getType());
183 // If we found a pointer, check if it could be the same as our pointer.
184 AliasAnalysis::AliasResult R =
185 AA->alias(Pointer, PointerSize, MemPtr, MemSize);
186 if (R == AliasAnalysis::NoAlias)
189 // May-alias loads don't depend on each other without a dependence.
190 if (isLoad && R == AliasAnalysis::MayAlias)
192 // Stores depend on may and must aliased loads, loads depend on must-alias
194 return MemDepResult::getDef(Inst);
197 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
198 Value *Pointer = SI->getPointerOperand();
199 uint64_t PointerSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
201 // If we found a pointer, check if it could be the same as our pointer.
202 AliasAnalysis::AliasResult R =
203 AA->alias(Pointer, PointerSize, MemPtr, MemSize);
205 if (R == AliasAnalysis::NoAlias)
207 if (R == AliasAnalysis::MayAlias)
208 return MemDepResult::getClobber(Inst);
209 return MemDepResult::getDef(Inst);
212 // If this is an allocation, and if we know that the accessed pointer is to
213 // the allocation, return Def. This means that there is no dependence and
214 // the access can be optimized based on that. For example, a load could
216 if (AllocationInst *AI = dyn_cast<AllocationInst>(Inst)) {
217 Value *AccessPtr = MemPtr->getUnderlyingObject();
219 if (AccessPtr == AI ||
220 AA->alias(AI, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
221 return MemDepResult::getDef(AI);
225 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
226 switch (AA->getModRefInfo(Inst, MemPtr, MemSize)) {
227 case AliasAnalysis::NoModRef:
228 // If the call has no effect on the queried pointer, just ignore it.
230 case AliasAnalysis::Ref:
231 // If the call is known to never store to the pointer, and if this is a
232 // load query, we can safely ignore it (scan past it).
237 // Otherwise, there is a potential dependence. Return a clobber.
238 return MemDepResult::getClobber(Inst);
242 // No dependence found. If this is the entry block of the function, it is a
243 // clobber, otherwise it is non-local.
244 if (BB != &BB->getParent()->getEntryBlock())
245 return MemDepResult::getNonLocal();
246 return MemDepResult::getClobber(ScanIt);
249 /// getDependency - Return the instruction on which a memory operation
251 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
252 Instruction *ScanPos = QueryInst;
254 // Check for a cached result
255 MemDepResult &LocalCache = LocalDeps[QueryInst];
257 // If the cached entry is non-dirty, just return it. Note that this depends
258 // on MemDepResult's default constructing to 'dirty'.
259 if (!LocalCache.isDirty())
262 // Otherwise, if we have a dirty entry, we know we can start the scan at that
263 // instruction, which may save us some work.
264 if (Instruction *Inst = LocalCache.getInst()) {
267 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
270 BasicBlock *QueryParent = QueryInst->getParent();
273 uint64_t MemSize = 0;
276 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
277 // No dependence found. If this is the entry block of the function, it is a
278 // clobber, otherwise it is non-local.
279 if (QueryParent != &QueryParent->getParent()->getEntryBlock())
280 LocalCache = MemDepResult::getNonLocal();
282 LocalCache = MemDepResult::getClobber(QueryInst);
283 } else if (StoreInst *SI = dyn_cast<StoreInst>(QueryInst)) {
284 // If this is a volatile store, don't mess around with it. Just return the
285 // previous instruction as a clobber.
286 if (SI->isVolatile())
287 LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
289 MemPtr = SI->getPointerOperand();
290 MemSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
292 } else if (LoadInst *LI = dyn_cast<LoadInst>(QueryInst)) {
293 // If this is a volatile load, don't mess around with it. Just return the
294 // previous instruction as a clobber.
295 if (LI->isVolatile())
296 LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
298 MemPtr = LI->getPointerOperand();
299 MemSize = TD->getTypeStoreSize(LI->getType());
301 } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
302 CallSite QueryCS = CallSite::get(QueryInst);
303 bool isReadOnly = AA->onlyReadsMemory(QueryCS);
304 LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
306 } else if (FreeInst *FI = dyn_cast<FreeInst>(QueryInst)) {
307 MemPtr = FI->getPointerOperand();
308 // FreeInsts erase the entire structure, not just a field.
311 // Non-memory instruction.
312 LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
315 // If we need to do a pointer scan, make it happen.
317 LocalCache = getPointerDependencyFrom(MemPtr, MemSize,
318 isa<LoadInst>(QueryInst),
319 ScanPos, QueryParent);
321 // Remember the result!
322 if (Instruction *I = LocalCache.getInst())
323 ReverseLocalDeps[I].insert(QueryInst);
328 /// getNonLocalCallDependency - Perform a full dependency query for the
329 /// specified call, returning the set of blocks that the value is
330 /// potentially live across. The returned set of results will include a
331 /// "NonLocal" result for all blocks where the value is live across.
333 /// This method assumes the instruction returns a "NonLocal" dependency
334 /// within its own block.
336 /// This returns a reference to an internal data structure that may be
337 /// invalidated on the next non-local query or when an instruction is
338 /// removed. Clients must copy this data if they want it around longer than
340 const MemoryDependenceAnalysis::NonLocalDepInfo &
341 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
342 assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
343 "getNonLocalCallDependency should only be used on calls with non-local deps!");
344 PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
345 NonLocalDepInfo &Cache = CacheP.first;
347 /// DirtyBlocks - This is the set of blocks that need to be recomputed. In
348 /// the cached case, this can happen due to instructions being deleted etc. In
349 /// the uncached case, this starts out as the set of predecessors we care
351 SmallVector<BasicBlock*, 32> DirtyBlocks;
353 if (!Cache.empty()) {
354 // Okay, we have a cache entry. If we know it is not dirty, just return it
355 // with no computation.
356 if (!CacheP.second) {
361 // If we already have a partially computed set of results, scan them to
362 // determine what is dirty, seeding our initial DirtyBlocks worklist.
363 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
365 if (I->second.isDirty())
366 DirtyBlocks.push_back(I->first);
368 // Sort the cache so that we can do fast binary search lookups below.
369 std::sort(Cache.begin(), Cache.end());
371 ++NumCacheDirtyNonLocal;
372 //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
373 // << Cache.size() << " cached: " << *QueryInst;
375 // Seed DirtyBlocks with each of the preds of QueryInst's block.
376 BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
377 for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
378 DirtyBlocks.push_back(*PI);
379 NumUncacheNonLocal++;
382 // isReadonlyCall - If this is a read-only call, we can be more aggressive.
383 bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
385 // Visited checked first, vector in sorted order.
386 SmallPtrSet<BasicBlock*, 64> Visited;
388 unsigned NumSortedEntries = Cache.size();
390 // Iterate while we still have blocks to update.
391 while (!DirtyBlocks.empty()) {
392 BasicBlock *DirtyBB = DirtyBlocks.back();
393 DirtyBlocks.pop_back();
395 // Already processed this block?
396 if (!Visited.insert(DirtyBB))
399 // Do a binary search to see if we already have an entry for this block in
400 // the cache set. If so, find it.
401 NonLocalDepInfo::iterator Entry =
402 std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
403 std::make_pair(DirtyBB, MemDepResult()));
404 if (Entry != Cache.begin() && (&*Entry)[-1].first == DirtyBB)
407 MemDepResult *ExistingResult = 0;
408 if (Entry != Cache.begin()+NumSortedEntries &&
409 Entry->first == DirtyBB) {
410 // If we already have an entry, and if it isn't already dirty, the block
412 if (!Entry->second.isDirty())
415 // Otherwise, remember this slot so we can update the value.
416 ExistingResult = &Entry->second;
419 // If the dirty entry has a pointer, start scanning from it so we don't have
420 // to rescan the entire block.
421 BasicBlock::iterator ScanPos = DirtyBB->end();
422 if (ExistingResult) {
423 if (Instruction *Inst = ExistingResult->getInst()) {
425 // We're removing QueryInst's use of Inst.
426 RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
427 QueryCS.getInstruction());
431 // Find out if this block has a local dependency for QueryInst.
434 if (ScanPos != DirtyBB->begin()) {
435 Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
436 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
437 // No dependence found. If this is the entry block of the function, it is
438 // a clobber, otherwise it is non-local.
439 Dep = MemDepResult::getNonLocal();
441 Dep = MemDepResult::getClobber(ScanPos);
444 // If we had a dirty entry for the block, update it. Otherwise, just add
447 *ExistingResult = Dep;
449 Cache.push_back(std::make_pair(DirtyBB, Dep));
451 // If the block has a dependency (i.e. it isn't completely transparent to
452 // the value), remember the association!
453 if (!Dep.isNonLocal()) {
454 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
455 // update this when we remove instructions.
456 if (Instruction *Inst = Dep.getInst())
457 ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
460 // If the block *is* completely transparent to the load, we need to check
461 // the predecessors of this block. Add them to our worklist.
462 for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
463 DirtyBlocks.push_back(*PI);
470 /// getNonLocalPointerDependency - Perform a full dependency query for an
471 /// access to the specified (non-volatile) memory location, returning the
472 /// set of instructions that either define or clobber the value.
474 /// This method assumes the pointer has a "NonLocal" dependency within its
477 void MemoryDependenceAnalysis::
478 getNonLocalPointerDependency(Value *Pointer, bool isLoad, BasicBlock *FromBB,
479 SmallVectorImpl<NonLocalDepEntry> &Result) {
480 assert(isa<PointerType>(Pointer->getType()) &&
481 "Can't get pointer deps of a non-pointer!");
484 // We know that the pointer value is live into FromBB find the def/clobbers
485 // from presecessors.
486 const Type *EltTy = cast<PointerType>(Pointer->getType())->getElementType();
487 uint64_t PointeeSize = TD->getTypeStoreSize(EltTy);
489 // While we have blocks to analyze, get their values.
490 SmallPtrSet<BasicBlock*, 64> Visited;
491 getNonLocalPointerDepFromBB(Pointer, PointeeSize, isLoad, FromBB,
495 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
496 /// Pointer/PointeeSize using either cached information in Cache or by doing a
497 /// lookup (which may use dirty cache info if available). If we do a lookup,
498 /// add the result to the cache.
499 MemDepResult MemoryDependenceAnalysis::
500 GetNonLocalInfoForBlock(Value *Pointer, uint64_t PointeeSize,
501 bool isLoad, BasicBlock *BB,
502 NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
504 // Do a binary search to see if we already have an entry for this block in
505 // the cache set. If so, find it.
506 NonLocalDepInfo::iterator Entry =
507 std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
508 std::make_pair(BB, MemDepResult()));
509 if (Entry != Cache->begin() && (&*Entry)[-1].first == BB)
512 MemDepResult *ExistingResult = 0;
513 if (Entry != Cache->begin()+NumSortedEntries && Entry->first == BB)
514 ExistingResult = &Entry->second;
516 // If we have a cached entry, and it is non-dirty, use it as the value for
518 if (ExistingResult && !ExistingResult->isDirty()) {
519 ++NumCacheNonLocalPtr;
520 return *ExistingResult;
523 // Otherwise, we have to scan for the value. If we have a dirty cache
524 // entry, start scanning from its position, otherwise we scan from the end
526 BasicBlock::iterator ScanPos = BB->end();
527 if (ExistingResult && ExistingResult->getInst()) {
528 assert(ExistingResult->getInst()->getParent() == BB &&
529 "Instruction invalidated?");
530 ++NumCacheDirtyNonLocalPtr;
531 ScanPos = ExistingResult->getInst();
533 // Eliminating the dirty entry from 'Cache', so update the reverse info.
534 ValueIsLoadPair CacheKey(Pointer, isLoad);
535 RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos,
536 CacheKey.getOpaqueValue());
538 ++NumUncacheNonLocalPtr;
541 // Scan the block for the dependency.
542 MemDepResult Dep = getPointerDependencyFrom(Pointer, PointeeSize, isLoad,
545 // If we had a dirty entry for the block, update it. Otherwise, just add
548 *ExistingResult = Dep;
550 Cache->push_back(std::make_pair(BB, Dep));
552 // If the block has a dependency (i.e. it isn't completely transparent to
553 // the value), remember the reverse association because we just added it
555 if (Dep.isNonLocal())
558 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
559 // update MemDep when we remove instructions.
560 Instruction *Inst = Dep.getInst();
561 assert(Inst && "Didn't depend on anything?");
562 ValueIsLoadPair CacheKey(Pointer, isLoad);
563 ReverseNonLocalPtrDeps[Inst].insert(CacheKey.getOpaqueValue());
568 /// getNonLocalPointerDepFromBB -
569 void MemoryDependenceAnalysis::
570 getNonLocalPointerDepFromBB(Value *Pointer, uint64_t PointeeSize,
571 bool isLoad, BasicBlock *StartBB,
572 SmallVectorImpl<NonLocalDepEntry> &Result,
573 SmallPtrSet<BasicBlock*, 64> &Visited) {
574 // Look up the cached info for Pointer.
575 ValueIsLoadPair CacheKey(Pointer, isLoad);
577 std::pair<BasicBlock*, NonLocalDepInfo> &CacheInfo =
578 NonLocalPointerDeps[CacheKey];
579 NonLocalDepInfo *Cache = &CacheInfo.second;
581 // If we have valid cached information for exactly the block we are
582 // investigating, just return it with no recomputation.
583 if (CacheInfo.first == StartBB) {
584 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
586 if (!I->second.isNonLocal())
587 Result.push_back(*I);
588 ++NumCacheCompleteNonLocalPtr;
592 // Otherwise, either this is a new block, a block with an invalid cache
593 // pointer or one that we're about to invalidate by putting more info into it
594 // than its valid cache info. If empty, the result will be valid cache info,
595 // otherwise it isn't.
596 CacheInfo.first = Cache->empty() ? StartBB : 0;
598 SmallVector<BasicBlock*, 32> Worklist;
599 Worklist.push_back(StartBB);
601 // Keep track of the entries that we know are sorted. Previously cached
602 // entries will all be sorted. The entries we add we only sort on demand (we
603 // don't insert every element into its sorted position). We know that we
604 // won't get any reuse from currently inserted values, because we don't
605 // revisit blocks after we insert info for them.
606 unsigned NumSortedEntries = Cache->size();
608 // SkipFirstBlock - If this is the very first block that we're processing, we
609 // don't want to scan or think about its body, because the client was supposed
610 // to do a local dependence query. Instead, just start processing it by
611 // adding its predecessors to the worklist and iterating.
612 bool SkipFirstBlock = Visited.empty();
614 while (!Worklist.empty()) {
615 BasicBlock *BB = Worklist.pop_back_val();
617 // Skip the first block if we have it.
618 if (SkipFirstBlock) {
619 SkipFirstBlock = false;
621 // Analyze the dependency of *Pointer in FromBB. See if we already have
623 if (!Visited.insert(BB))
626 // Get the dependency info for Pointer in BB. If we have cached
627 // information, we will use it, otherwise we compute it.
628 MemDepResult Dep = GetNonLocalInfoForBlock(Pointer, PointeeSize, isLoad,
629 BB, Cache, NumSortedEntries);
631 // If we got a Def or Clobber, add this to the list of results.
632 if (!Dep.isNonLocal()) {
633 Result.push_back(NonLocalDepEntry(BB, Dep));
638 // Otherwise, we have to process all the predecessors of this block to scan
640 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
641 // TODO: PHI TRANSLATE.
642 Worklist.push_back(*PI);
646 // Okay, we're done now. If we added new values to the cache, re-sort it.
647 switch (Cache->size()-NumSortedEntries) {
649 // done, no new entries.
652 // Two new entries, insert the last one into place.
653 NonLocalDepEntry Val = Cache->back();
655 NonLocalDepInfo::iterator Entry =
656 std::upper_bound(Cache->begin(), Cache->end()-1, Val);
657 Cache->insert(Entry, Val);
661 // One new entry, Just insert the new value at the appropriate position.
662 NonLocalDepEntry Val = Cache->back();
664 NonLocalDepInfo::iterator Entry =
665 std::upper_bound(Cache->begin(), Cache->end(), Val);
666 Cache->insert(Entry, Val);
670 // Added many values, do a full scale sort.
671 std::sort(Cache->begin(), Cache->end());
675 /// RemoveCachedNonLocalPointerDependencies - If P exists in
676 /// CachedNonLocalPointerInfo, remove it.
677 void MemoryDependenceAnalysis::
678 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
679 CachedNonLocalPointerInfo::iterator It =
680 NonLocalPointerDeps.find(P);
681 if (It == NonLocalPointerDeps.end()) return;
683 // Remove all of the entries in the BB->val map. This involves removing
684 // instructions from the reverse map.
685 NonLocalDepInfo &PInfo = It->second.second;
687 for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
688 Instruction *Target = PInfo[i].second.getInst();
689 if (Target == 0) continue; // Ignore non-local dep results.
690 assert(Target->getParent() == PInfo[i].first && Target != P.getPointer());
692 // Eliminating the dirty entry from 'Cache', so update the reverse info.
693 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P.getOpaqueValue());
696 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
697 NonLocalPointerDeps.erase(It);
701 /// invalidateCachedPointerInfo - This method is used to invalidate cached
702 /// information about the specified pointer, because it may be too
703 /// conservative in memdep. This is an optional call that can be used when
704 /// the client detects an equivalence between the pointer and some other
705 /// value and replaces the other value with ptr. This can make Ptr available
706 /// in more places that cached info does not necessarily keep.
707 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
708 // If Ptr isn't really a pointer, just ignore it.
709 if (!isa<PointerType>(Ptr->getType())) return;
710 // Flush store info for the pointer.
711 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
712 // Flush load info for the pointer.
713 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
716 /// removeInstruction - Remove an instruction from the dependence analysis,
717 /// updating the dependence of instructions that previously depended on it.
718 /// This method attempts to keep the cache coherent using the reverse map.
719 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
720 // Walk through the Non-local dependencies, removing this one as the value
721 // for any cached queries.
722 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
723 if (NLDI != NonLocalDeps.end()) {
724 NonLocalDepInfo &BlockMap = NLDI->second.first;
725 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
727 if (Instruction *Inst = DI->second.getInst())
728 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
729 NonLocalDeps.erase(NLDI);
732 // If we have a cached local dependence query for this instruction, remove it.
734 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
735 if (LocalDepEntry != LocalDeps.end()) {
736 // Remove us from DepInst's reverse set now that the local dep info is gone.
737 if (Instruction *Inst = LocalDepEntry->second.getInst())
738 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
740 // Remove this local dependency info.
741 LocalDeps.erase(LocalDepEntry);
744 // If we have any cached pointer dependencies on this instruction, remove
745 // them. If the instruction has non-pointer type, then it can't be a pointer
748 // Remove it from both the load info and the store info. The instruction
749 // can't be in either of these maps if it is non-pointer.
750 if (isa<PointerType>(RemInst->getType())) {
751 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
752 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
755 // Loop over all of the things that depend on the instruction we're removing.
757 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
759 // If we find RemInst as a clobber or Def in any of the maps for other values,
760 // we need to replace its entry with a dirty version of the instruction after
761 // it. If RemInst is a terminator, we use a null dirty value.
763 // Using a dirty version of the instruction after RemInst saves having to scan
764 // the entire block to get to this point.
765 MemDepResult NewDirtyVal;
766 if (!RemInst->isTerminator())
767 NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
769 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
770 if (ReverseDepIt != ReverseLocalDeps.end()) {
771 SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
772 // RemInst can't be the terminator if it has local stuff depending on it.
773 assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
774 "Nothing can locally depend on a terminator");
776 for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
777 E = ReverseDeps.end(); I != E; ++I) {
778 Instruction *InstDependingOnRemInst = *I;
779 assert(InstDependingOnRemInst != RemInst &&
780 "Already removed our local dep info");
782 LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
784 // Make sure to remember that new things depend on NewDepInst.
785 assert(NewDirtyVal.getInst() && "There is no way something else can have "
786 "a local dep on this if it is a terminator!");
787 ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
788 InstDependingOnRemInst));
791 ReverseLocalDeps.erase(ReverseDepIt);
793 // Add new reverse deps after scanning the set, to avoid invalidating the
794 // 'ReverseDeps' reference.
795 while (!ReverseDepsToAdd.empty()) {
796 ReverseLocalDeps[ReverseDepsToAdd.back().first]
797 .insert(ReverseDepsToAdd.back().second);
798 ReverseDepsToAdd.pop_back();
802 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
803 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
804 SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
805 for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
807 assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
809 PerInstNLInfo &INLD = NonLocalDeps[*I];
810 // The information is now dirty!
813 for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
814 DE = INLD.first.end(); DI != DE; ++DI) {
815 if (DI->second.getInst() != RemInst) continue;
817 // Convert to a dirty entry for the subsequent instruction.
818 DI->second = NewDirtyVal;
820 if (Instruction *NextI = NewDirtyVal.getInst())
821 ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
825 ReverseNonLocalDeps.erase(ReverseDepIt);
827 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
828 while (!ReverseDepsToAdd.empty()) {
829 ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
830 .insert(ReverseDepsToAdd.back().second);
831 ReverseDepsToAdd.pop_back();
835 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
836 // value in the NonLocalPointerDeps info.
837 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
838 ReverseNonLocalPtrDeps.find(RemInst);
839 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
840 SmallPtrSet<void*, 4> &Set = ReversePtrDepIt->second;
841 SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
843 for (SmallPtrSet<void*, 4>::iterator I = Set.begin(), E = Set.end();
846 P.setFromOpaqueValue(*I);
847 assert(P.getPointer() != RemInst &&
848 "Already removed NonLocalPointerDeps info for RemInst");
850 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].second;
852 // The cache is not valid for any specific block anymore.
853 NonLocalPointerDeps[P].first = 0;
855 // Update any entries for RemInst to use the instruction after it.
856 for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
858 if (DI->second.getInst() != RemInst) continue;
860 // Convert to a dirty entry for the subsequent instruction.
861 DI->second = NewDirtyVal;
863 if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
864 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
868 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
870 while (!ReversePtrDepsToAdd.empty()) {
871 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
872 .insert(ReversePtrDepsToAdd.back().second.getOpaqueValue());
873 ReversePtrDepsToAdd.pop_back();
878 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
879 AA->deleteValue(RemInst);
880 DEBUG(verifyRemoved(RemInst));
882 /// verifyRemoved - Verify that the specified instruction does not occur
883 /// in our internal data structures.
884 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
885 for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
886 E = LocalDeps.end(); I != E; ++I) {
887 assert(I->first != D && "Inst occurs in data structures");
888 assert(I->second.getInst() != D &&
889 "Inst occurs in data structures");
892 for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
893 E = NonLocalPointerDeps.end(); I != E; ++I) {
894 assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
895 const NonLocalDepInfo &Val = I->second.second;
896 for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
898 assert(II->second.getInst() != D && "Inst occurs as NLPD value");
901 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
902 E = NonLocalDeps.end(); I != E; ++I) {
903 assert(I->first != D && "Inst occurs in data structures");
904 const PerInstNLInfo &INLD = I->second;
905 for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
906 EE = INLD.first.end(); II != EE; ++II)
907 assert(II->second.getInst() != D && "Inst occurs in data structures");
910 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
911 E = ReverseLocalDeps.end(); I != E; ++I) {
912 assert(I->first != D && "Inst occurs in data structures");
913 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
914 EE = I->second.end(); II != EE; ++II)
915 assert(*II != D && "Inst occurs in data structures");
918 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
919 E = ReverseNonLocalDeps.end();
921 assert(I->first != D && "Inst occurs in data structures");
922 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
923 EE = I->second.end(); II != EE; ++II)
924 assert(*II != D && "Inst occurs in data structures");
927 for (ReverseNonLocalPtrDepTy::const_iterator
928 I = ReverseNonLocalPtrDeps.begin(),
929 E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
930 assert(I->first != D && "Inst occurs in rev NLPD map");
932 for (SmallPtrSet<void*, 4>::const_iterator II = I->second.begin(),
933 E = I->second.end(); II != E; ++II)
934 assert(*II != ValueIsLoadPair(D, false).getOpaqueValue() &&
935 *II != ValueIsLoadPair(D, true).getOpaqueValue() &&
936 "Inst occurs in ReverseNonLocalPtrDeps map");