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 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Function.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/ADT/Statistic.h"
27 #define DEBUG_TYPE "memdep"
32 // Control the calculation of non-local dependencies by only examining the
33 // predecessors if the basic block has less than X amount (50 by default).
35 PredLimit("nonlocaldep-threshold", cl::Hidden, cl::init(50),
36 cl::desc("Control the calculation of non-local"
37 "dependencies (default = 50)"));
40 STATISTIC(NumCacheNonlocal, "Number of cached non-local responses");
41 STATISTIC(NumUncacheNonlocal, "Number of uncached non-local responses");
43 char MemoryDependenceAnalysis::ID = 0;
45 Instruction* const MemoryDependenceAnalysis::NonLocal = (Instruction*)-3;
46 Instruction* const MemoryDependenceAnalysis::None = (Instruction*)-4;
47 Instruction* const MemoryDependenceAnalysis::Dirty = (Instruction*)-5;
49 // Register this pass...
50 static RegisterPass<MemoryDependenceAnalysis> X("memdep",
51 "Memory Dependence Analysis", false, true);
53 void MemoryDependenceAnalysis::ping(Instruction *D) {
54 for (depMapType::iterator I = depGraphLocal.begin(), E = depGraphLocal.end();
56 assert(I->first != D);
57 assert(I->second.first != D);
60 for (nonLocalDepMapType::iterator I = depGraphNonLocal.begin(), E = depGraphNonLocal.end();
62 assert(I->first != D);
65 for (reverseDepMapType::iterator I = reverseDep.begin(), E = reverseDep.end();
67 for (SmallPtrSet<Instruction*, 4>::iterator II = I->second.begin(), EE = I->second.end();
71 for (reverseDepMapType::iterator I = reverseDepNonLocal.begin(), E = reverseDepNonLocal.end();
73 for (SmallPtrSet<Instruction*, 4>::iterator II = I->second.begin(), EE = I->second.end();
78 /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis.
80 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
82 AU.addRequiredTransitive<AliasAnalysis>();
83 AU.addRequiredTransitive<TargetData>();
86 /// getCallSiteDependency - Private helper for finding the local dependencies
88 Instruction* MemoryDependenceAnalysis::getCallSiteDependency(CallSite C,
92 std::pair<Instruction*, bool>& cachedResult =
93 depGraphLocal[C.getInstruction()];
94 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
95 TargetData& TD = getAnalysis<TargetData>();
96 BasicBlock::iterator blockBegin = C.getInstruction()->getParent()->begin();
97 BasicBlock::iterator QI = C.getInstruction();
99 // If the starting point was specifiy, use it
102 blockBegin = start->getParent()->begin();
103 // If the starting point wasn't specified, but the block was, use it
104 } else if (!start && block) {
106 blockBegin = block->begin();
109 // Walk backwards through the block, looking for dependencies
110 while (QI != blockBegin) {
113 // If this inst is a memory op, get the pointer it accessed
115 uint64_t pointerSize = 0;
116 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
117 pointer = S->getPointerOperand();
118 pointerSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
119 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
121 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
122 pointerSize = C->getZExtValue() * \
123 TD.getABITypeSize(AI->getAllocatedType());
126 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
127 pointer = V->getOperand(0);
128 pointerSize = TD.getTypeStoreSize(V->getType());
129 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
130 pointer = F->getPointerOperand();
132 // FreeInsts erase the entire structure
134 } else if (isa<CallInst>(QI)) {
135 AliasAnalysis::ModRefBehavior result =
136 AA.getModRefBehavior(CallSite::get(QI));
137 if (result != AliasAnalysis::DoesNotAccessMemory) {
138 if (!start && !block) {
139 cachedResult.first = QI;
140 cachedResult.second = true;
141 reverseDep[QI].insert(C.getInstruction());
150 if (AA.getModRefInfo(C, pointer, pointerSize) != AliasAnalysis::NoModRef) {
151 if (!start && !block) {
152 cachedResult.first = QI;
153 cachedResult.second = true;
154 reverseDep[QI].insert(C.getInstruction());
160 // No dependence found
161 cachedResult.first = NonLocal;
162 cachedResult.second = true;
163 reverseDep[NonLocal].insert(C.getInstruction());
167 /// nonLocalHelper - Private helper used to calculate non-local dependencies
168 /// by doing DFS on the predecessors of a block to find its dependencies
169 void MemoryDependenceAnalysis::nonLocalHelper(Instruction* query,
171 DenseMap<BasicBlock*, Value*>& resp) {
172 // Set of blocks that we've already visited in our DFS
173 SmallPtrSet<BasicBlock*, 4> visited;
174 // If we're updating a dirtied cache entry, we don't need to reprocess
175 // already computed entries.
176 for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(),
177 E = resp.end(); I != E; ++I)
178 if (I->second != Dirty)
179 visited.insert(I->first);
181 // Current stack of the DFS
182 SmallVector<BasicBlock*, 4> stack;
183 for (pred_iterator PI = pred_begin(block), PE = pred_end(block);
185 stack.push_back(*PI);
188 while (!stack.empty()) {
189 BasicBlock* BB = stack.back();
191 // If we've already visited this block, no need to revist
192 if (visited.count(BB)) {
197 // If we find a new block with a local dependency for query,
198 // then we insert the new dependency and backtrack.
202 Instruction* localDep = getDependency(query, 0, BB);
203 if (localDep != NonLocal) {
204 resp.insert(std::make_pair(BB, localDep));
209 // If we re-encounter the starting block, we still need to search it
210 // because there might be a dependency in the starting block AFTER
211 // the position of the query. This is necessary to get loops right.
212 } else if (BB == block) {
215 Instruction* localDep = getDependency(query, 0, BB);
216 if (localDep != query)
217 resp.insert(std::make_pair(BB, localDep));
224 // If we didn't find anything, recurse on the precessors of this block
225 // Only do this for blocks with a small number of predecessors.
226 bool predOnStack = false;
227 bool inserted = false;
228 if (std::distance(pred_begin(BB), pred_end(BB)) <= PredLimit) {
229 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
231 if (!visited.count(*PI)) {
232 stack.push_back(*PI);
238 // If we inserted a new predecessor, then we'll come back to this block
241 // If we didn't insert because we have no predecessors, then this
242 // query has no dependency at all.
243 else if (!inserted && !predOnStack) {
244 resp.insert(std::make_pair(BB, None));
245 // If we didn't insert because our predecessors are already on the stack,
246 // then we might still have a dependency, but it will be discovered during
248 } else if (!inserted && predOnStack){
249 resp.insert(std::make_pair(BB, NonLocal));
256 /// getNonLocalDependency - Fills the passed-in map with the non-local
257 /// dependencies of the queries. The map will contain NonLocal for
258 /// blocks between the query and its dependencies.
259 void MemoryDependenceAnalysis::getNonLocalDependency(Instruction* query,
260 DenseMap<BasicBlock*, Value*>& resp) {
261 if (depGraphNonLocal.count(query)) {
262 DenseMap<BasicBlock*, Value*>& cached = depGraphNonLocal[query];
265 SmallVector<BasicBlock*, 4> dirtied;
266 for (DenseMap<BasicBlock*, Value*>::iterator I = cached.begin(),
267 E = cached.end(); I != E; ++I)
268 if (I->second == Dirty)
269 dirtied.push_back(I->first);
271 for (SmallVector<BasicBlock*, 4>::iterator I = dirtied.begin(),
272 E = dirtied.end(); I != E; ++I) {
273 Instruction* localDep = getDependency(query, 0, *I);
274 if (localDep != NonLocal)
275 cached[*I] = localDep;
278 nonLocalHelper(query, *I, cached);
286 NumUncacheNonlocal++;
288 // If not, go ahead and search for non-local deps.
289 nonLocalHelper(query, query->getParent(), resp);
291 // Update the non-local dependency cache
292 for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(), E = resp.end();
294 depGraphNonLocal[query].insert(*I);
295 reverseDepNonLocal[I->second].insert(query);
299 /// getDependency - Return the instruction on which a memory operation
300 /// depends. The local parameter indicates if the query should only
301 /// evaluate dependencies within the same basic block.
302 Instruction* MemoryDependenceAnalysis::getDependency(Instruction* query,
305 // Start looking for dependencies with the queried inst
306 BasicBlock::iterator QI = query;
308 // Check for a cached result
309 std::pair<Instruction*, bool>& cachedResult = depGraphLocal[query];
310 // If we have a _confirmed_ cached entry, return it
311 if (!block && !start) {
312 if (cachedResult.second)
313 return cachedResult.first;
314 else if (cachedResult.first && cachedResult.first != NonLocal)
315 // If we have an unconfirmed cached entry, we can start our search from there
316 QI = cachedResult.first;
321 else if (!start && block)
324 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
325 TargetData& TD = getAnalysis<TargetData>();
327 // Get the pointer value for which dependence will be determined
329 uint64_t dependeeSize = 0;
330 bool queryIsVolatile = false;
331 if (StoreInst* S = dyn_cast<StoreInst>(query)) {
332 dependee = S->getPointerOperand();
333 dependeeSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
334 queryIsVolatile = S->isVolatile();
335 } else if (LoadInst* L = dyn_cast<LoadInst>(query)) {
336 dependee = L->getPointerOperand();
337 dependeeSize = TD.getTypeStoreSize(L->getType());
338 queryIsVolatile = L->isVolatile();
339 } else if (VAArgInst* V = dyn_cast<VAArgInst>(query)) {
340 dependee = V->getOperand(0);
341 dependeeSize = TD.getTypeStoreSize(V->getType());
342 } else if (FreeInst* F = dyn_cast<FreeInst>(query)) {
343 dependee = F->getPointerOperand();
345 // FreeInsts erase the entire structure, not just a field
347 } else if (CallSite::get(query).getInstruction() != 0)
348 return getCallSiteDependency(CallSite::get(query), start, block);
349 else if (isa<AllocationInst>(query))
354 BasicBlock::iterator blockBegin = block ? block->begin()
355 : query->getParent()->begin();
357 // Walk backwards through the basic block, looking for dependencies
358 while (QI != blockBegin) {
361 // If this inst is a memory op, get the pointer it accessed
363 uint64_t pointerSize = 0;
364 if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
365 // All volatile loads/stores depend on each other
366 if (queryIsVolatile && S->isVolatile()) {
367 if (!start && !block) {
368 cachedResult.first = S;
369 cachedResult.second = true;
370 reverseDep[S].insert(query);
376 pointer = S->getPointerOperand();
377 pointerSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
378 } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
379 // All volatile loads/stores depend on each other
380 if (queryIsVolatile && L->isVolatile()) {
381 if (!start && !block) {
382 cachedResult.first = L;
383 cachedResult.second = true;
384 reverseDep[L].insert(query);
390 pointer = L->getPointerOperand();
391 pointerSize = TD.getTypeStoreSize(L->getType());
392 } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
394 if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
395 pointerSize = C->getZExtValue() * \
396 TD.getABITypeSize(AI->getAllocatedType());
399 } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
400 pointer = V->getOperand(0);
401 pointerSize = TD.getTypeStoreSize(V->getType());
402 } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
403 pointer = F->getPointerOperand();
405 // FreeInsts erase the entire structure
407 } else if (CallSite::get(QI).getInstruction() != 0) {
408 // Call insts need special handling. Check if they can modify our pointer
409 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(CallSite::get(QI),
410 dependee, dependeeSize);
412 if (MR != AliasAnalysis::NoModRef) {
413 // Loads don't depend on read-only calls
414 if (isa<LoadInst>(query) && MR == AliasAnalysis::Ref)
417 if (!start && !block) {
418 cachedResult.first = QI;
419 cachedResult.second = true;
420 reverseDep[QI].insert(query);
429 // If we found a pointer, check if it could be the same as our pointer
431 AliasAnalysis::AliasResult R = AA.alias(pointer, pointerSize,
432 dependee, dependeeSize);
434 if (R != AliasAnalysis::NoAlias) {
435 // May-alias loads don't depend on each other
436 if (isa<LoadInst>(query) && isa<LoadInst>(QI) &&
437 R == AliasAnalysis::MayAlias)
440 if (!start && !block) {
441 cachedResult.first = QI;
442 cachedResult.second = true;
443 reverseDep[QI].insert(query);
451 // If we found nothing, return the non-local flag
452 if (!start && !block) {
453 cachedResult.first = NonLocal;
454 cachedResult.second = true;
455 reverseDep[NonLocal].insert(query);
461 /// dropInstruction - Remove an instruction from the analysis, making
462 /// absolutely conservative assumptions when updating the cache. This is
463 /// useful, for example when an instruction is changed rather than removed.
464 void MemoryDependenceAnalysis::dropInstruction(Instruction* drop) {
465 depMapType::iterator depGraphEntry = depGraphLocal.find(drop);
466 if (depGraphEntry != depGraphLocal.end())
467 reverseDep[depGraphEntry->second.first].erase(drop);
469 // Drop dependency information for things that depended on this instr
470 SmallPtrSet<Instruction*, 4>& set = reverseDep[drop];
471 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
473 depGraphLocal.erase(*I);
475 depGraphLocal.erase(drop);
476 reverseDep.erase(drop);
478 for (DenseMap<BasicBlock*, Value*>::iterator DI =
479 depGraphNonLocal[drop].begin(), DE = depGraphNonLocal[drop].end();
481 if (DI->second != None)
482 reverseDepNonLocal[DI->second].erase(drop);
484 if (reverseDepNonLocal.count(drop)) {
485 SmallPtrSet<Instruction*, 4>& set = reverseDepNonLocal[drop];
486 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
488 for (DenseMap<BasicBlock*, Value*>::iterator DI =
489 depGraphNonLocal[*I].begin(), DE = depGraphNonLocal[*I].end();
491 if (DI->second == drop)
495 reverseDepNonLocal.erase(drop);
496 nonLocalDepMapType::iterator I = depGraphNonLocal.find(drop);
497 if (I != depGraphNonLocal.end())
498 depGraphNonLocal.erase(I);
501 /// removeInstruction - Remove an instruction from the dependence analysis,
502 /// updating the dependence of instructions that previously depended on it.
503 /// This method attempts to keep the cache coherent using the reverse map.
504 void MemoryDependenceAnalysis::removeInstruction(Instruction* rem) {
505 // Figure out the new dep for things that currently depend on rem
506 Instruction* newDep = NonLocal;
508 for (DenseMap<BasicBlock*, Value*>::iterator DI =
509 depGraphNonLocal[rem].begin(), DE = depGraphNonLocal[rem].end();
511 if (DI->second != None)
512 reverseDepNonLocal[DI->second].erase(rem);
514 depMapType::iterator depGraphEntry = depGraphLocal.find(rem);
516 if (depGraphEntry != depGraphLocal.end()) {
517 reverseDep[depGraphEntry->second.first].erase(rem);
519 if (depGraphEntry->second.first != NonLocal &&
520 depGraphEntry->second.first != None &&
521 depGraphEntry->second.second) {
522 // If we have dep info for rem, set them to it
523 BasicBlock::iterator RI = depGraphEntry->second.first;
526 } else if ( (depGraphEntry->second.first == NonLocal ||
527 depGraphEntry->second.first == None ) &&
528 depGraphEntry->second.second ) {
529 // If we have a confirmed non-local flag, use it
530 newDep = depGraphEntry->second.first;
532 // Otherwise, use the immediate successor of rem
533 // NOTE: This is because, when getDependence is called, it will first
534 // check the immediate predecessor of what is in the cache.
535 BasicBlock::iterator RI = rem;
540 // Otherwise, use the immediate successor of rem
541 // NOTE: This is because, when getDependence is called, it will first
542 // check the immediate predecessor of what is in the cache.
543 BasicBlock::iterator RI = rem;
548 SmallPtrSet<Instruction*, 4>& set = reverseDep[rem];
549 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
551 // Insert the new dependencies
552 // Mark it as unconfirmed as long as it is not the non-local flag
553 depGraphLocal[*I] = std::make_pair(newDep, (newDep == NonLocal ||
557 depGraphLocal.erase(rem);
558 reverseDep.erase(rem);
560 if (reverseDepNonLocal.count(rem)) {
561 SmallPtrSet<Instruction*, 4>& set = reverseDepNonLocal[rem];
562 for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
564 for (DenseMap<BasicBlock*, Value*>::iterator DI =
565 depGraphNonLocal[*I].begin(), DE = depGraphNonLocal[*I].end();
567 if (DI->second == rem)
572 reverseDepNonLocal.erase(rem);
573 nonLocalDepMapType::iterator I = depGraphNonLocal.find(rem);
574 if (I != depGraphNonLocal.end())
575 depGraphNonLocal.erase(I);
577 getAnalysis<AliasAnalysis>().deleteValue(rem);