MemoryDependenceAnalysis.cpp revision fd3dcbea06f934572a3ba02821b1485eb7a073aa
1//===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation  --*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
14//
15//===----------------------------------------------------------------------===//
16
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/ADT/STLExtras.h"
25#include "llvm/Support/CFG.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Target/TargetData.h"
29using namespace llvm;
30
31STATISTIC(NumCacheNonLocal, "Number of cached non-local responses");
32STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
33
34char MemoryDependenceAnalysis::ID = 0;
35
36// Register this pass...
37static RegisterPass<MemoryDependenceAnalysis> X("memdep",
38                                     "Memory Dependence Analysis", false, true);
39
40/// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
41///
42void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
43  AU.setPreservesAll();
44  AU.addRequiredTransitive<AliasAnalysis>();
45  AU.addRequiredTransitive<TargetData>();
46}
47
48bool MemoryDependenceAnalysis::runOnFunction(Function &) {
49  AA = &getAnalysis<AliasAnalysis>();
50  TD = &getAnalysis<TargetData>();
51  return false;
52}
53
54/// getCallSiteDependency - Private helper for finding the local dependencies
55/// of a call site.
56MemDepResult MemoryDependenceAnalysis::
57getCallSiteDependency(CallSite C, BasicBlock::iterator ScanIt, BasicBlock *BB) {
58  // Walk backwards through the block, looking for dependencies
59  while (ScanIt != BB->begin()) {
60    Instruction *Inst = --ScanIt;
61
62    // If this inst is a memory op, get the pointer it accessed
63    Value *Pointer = 0;
64    uint64_t PointerSize = 0;
65    if (StoreInst *S = dyn_cast<StoreInst>(Inst)) {
66      Pointer = S->getPointerOperand();
67      PointerSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
68    } else if (VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
69      Pointer = V->getOperand(0);
70      PointerSize = TD->getTypeStoreSize(V->getType());
71    } else if (FreeInst *F = dyn_cast<FreeInst>(Inst)) {
72      Pointer = F->getPointerOperand();
73
74      // FreeInsts erase the entire structure
75      PointerSize = ~0UL;
76    } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
77      if (AA->getModRefBehavior(CallSite::get(Inst)) ==
78            AliasAnalysis::DoesNotAccessMemory)
79        continue;
80      return MemDepResult::get(Inst);
81    } else {
82      // Non-memory instruction.
83      continue;
84    }
85
86    if (AA->getModRefInfo(C, Pointer, PointerSize) != AliasAnalysis::NoModRef)
87      return MemDepResult::get(Inst);
88  }
89
90  // No dependence found.
91  return MemDepResult::getNonLocal();
92}
93
94/// getDependencyFrom - Return the instruction on which a memory operation
95/// depends.
96MemDepResult MemoryDependenceAnalysis::
97getDependencyFrom(Instruction *QueryInst, BasicBlock::iterator ScanIt,
98                  BasicBlock *BB) {
99  // Get the pointer value for which dependence will be determined
100  Value *MemPtr = 0;
101  uint64_t MemSize = 0;
102  bool MemVolatile = false;
103
104  if (StoreInst* S = dyn_cast<StoreInst>(QueryInst)) {
105    MemPtr = S->getPointerOperand();
106    MemSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
107    MemVolatile = S->isVolatile();
108  } else if (LoadInst* L = dyn_cast<LoadInst>(QueryInst)) {
109    MemPtr = L->getPointerOperand();
110    MemSize = TD->getTypeStoreSize(L->getType());
111    MemVolatile = L->isVolatile();
112  } else if (VAArgInst* V = dyn_cast<VAArgInst>(QueryInst)) {
113    MemPtr = V->getOperand(0);
114    MemSize = TD->getTypeStoreSize(V->getType());
115  } else if (FreeInst* F = dyn_cast<FreeInst>(QueryInst)) {
116    MemPtr = F->getPointerOperand();
117    // FreeInsts erase the entire structure, not just a field.
118    MemSize = ~0UL;
119  } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst))
120    return getCallSiteDependency(CallSite::get(QueryInst), ScanIt, BB);
121  else  // Non-memory instructions depend on nothing.
122    return MemDepResult::getNone();
123
124  // Walk backwards through the basic block, looking for dependencies
125  while (ScanIt != BB->begin()) {
126    Instruction *Inst = --ScanIt;
127
128    // If the access is volatile and this is a volatile load/store, return a
129    // dependence.
130    if (MemVolatile &&
131        ((isa<LoadInst>(Inst) && cast<LoadInst>(Inst)->isVolatile()) ||
132         (isa<StoreInst>(Inst) && cast<StoreInst>(Inst)->isVolatile())))
133      return MemDepResult::get(Inst);
134
135    // Values depend on loads if the pointers are must aliased.  This means that
136    // a load depends on another must aliased load from the same value.
137    if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
138      Value *Pointer = L->getPointerOperand();
139      uint64_t PointerSize = TD->getTypeStoreSize(L->getType());
140
141      // If we found a pointer, check if it could be the same as our pointer
142      AliasAnalysis::AliasResult R =
143        AA->alias(Pointer, PointerSize, MemPtr, MemSize);
144
145      if (R == AliasAnalysis::NoAlias)
146        continue;
147
148      // May-alias loads don't depend on each other without a dependence.
149      if (isa<LoadInst>(QueryInst) && R == AliasAnalysis::MayAlias)
150        continue;
151      return MemDepResult::get(Inst);
152    }
153
154    // If this is an allocation, and if we know that the accessed pointer is to
155    // the allocation, return None.  This means that there is no dependence and
156    // the access can be optimized based on that.  For example, a load could
157    // turn into undef.
158    if (AllocationInst *AI = dyn_cast<AllocationInst>(Inst)) {
159      Value *AccessPtr = MemPtr->getUnderlyingObject();
160
161      if (AccessPtr == AI ||
162          AA->alias(AI, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
163        return MemDepResult::getNone();
164      continue;
165    }
166
167    // See if this instruction mod/ref's the pointer.
168    AliasAnalysis::ModRefResult MRR = AA->getModRefInfo(Inst, MemPtr, MemSize);
169
170    if (MRR == AliasAnalysis::NoModRef)
171      continue;
172
173    // Loads don't depend on read-only instructions.
174    if (isa<LoadInst>(QueryInst) && MRR == AliasAnalysis::Ref)
175      continue;
176
177    // Otherwise, there is a dependence.
178    return MemDepResult::get(Inst);
179  }
180
181  // If we found nothing, return the non-local flag.
182  return MemDepResult::getNonLocal();
183}
184
185/// getDependency - Return the instruction on which a memory operation
186/// depends.
187MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
188  Instruction *ScanPos = QueryInst;
189
190  // Check for a cached result
191  MemDepResult &LocalCache = LocalDeps[QueryInst];
192
193  // If the cached entry is non-dirty, just return it.  Note that this depends
194  // on MemDepResult's default constructing to 'dirty'.
195  if (!LocalCache.isDirty())
196    return LocalCache;
197
198  // Otherwise, if we have a dirty entry, we know we can start the scan at that
199  // instruction, which may save us some work.
200  if (Instruction *Inst = LocalCache.getInst()) {
201    ScanPos = Inst;
202
203    SmallPtrSet<Instruction*, 4> &InstMap = ReverseLocalDeps[Inst];
204    InstMap.erase(QueryInst);
205    if (InstMap.empty())
206      ReverseLocalDeps.erase(Inst);
207  }
208
209  // Do the scan.
210  LocalCache = getDependencyFrom(QueryInst, ScanPos, QueryInst->getParent());
211
212  // Remember the result!
213  if (Instruction *I = LocalCache.getInst())
214    ReverseLocalDeps[I].insert(QueryInst);
215
216  return LocalCache;
217}
218
219/// getNonLocalDependency - Perform a full dependency query for the
220/// specified instruction, returning the set of blocks that the value is
221/// potentially live across.  The returned set of results will include a
222/// "NonLocal" result for all blocks where the value is live across.
223///
224/// This method assumes the instruction returns a "nonlocal" dependency
225/// within its own block.
226///
227void MemoryDependenceAnalysis::
228getNonLocalDependency(Instruction *QueryInst,
229                      SmallVectorImpl<std::pair<BasicBlock*,
230                                                      MemDepResult> > &Result) {
231  assert(getDependency(QueryInst).isNonLocal() &&
232     "getNonLocalDependency should only be used on insts with non-local deps!");
233  PerInstNLInfo &CacheP = NonLocalDeps[QueryInst];
234  if (CacheP.getPointer() == 0) CacheP.setPointer(new NonLocalDepInfo());
235
236  NonLocalDepInfo &Cache = *CacheP.getPointer();
237
238  /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
239  /// the cached case, this can happen due to instructions being deleted etc. In
240  /// the uncached case, this starts out as the set of predecessors we care
241  /// about.
242  SmallVector<BasicBlock*, 32> DirtyBlocks;
243
244  if (!Cache.empty()) {
245    // If we already have a partially computed set of results, scan them to
246    // determine what is dirty, seeding our initial DirtyBlocks worklist.  The
247    // Int bit of CacheP tells us if we have anything dirty.
248    if (CacheP.getInt())
249      for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
250         I != E; ++I)
251        if (I->second.isDirty())
252          DirtyBlocks.push_back(I->first);
253
254    NumCacheNonLocal++;
255
256    //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
257    //     << Cache.size() << " cached: " << *QueryInst;
258  } else {
259    // Seed DirtyBlocks with each of the preds of QueryInst's block.
260    BasicBlock *QueryBB = QueryInst->getParent();
261    DirtyBlocks.append(pred_begin(QueryBB), pred_end(QueryBB));
262    NumUncacheNonLocal++;
263  }
264
265  // Iterate while we still have blocks to update.
266  while (!DirtyBlocks.empty()) {
267    BasicBlock *DirtyBB = DirtyBlocks.back();
268    DirtyBlocks.pop_back();
269
270    // Get the entry for this block.  Note that this relies on MemDepResult
271    // default initializing to Dirty.
272    MemDepResult &DirtyBBEntry = Cache[DirtyBB];
273
274    // If DirtyBBEntry isn't dirty, it ended up on the worklist multiple times.
275    if (!DirtyBBEntry.isDirty()) continue;
276
277    // If the dirty entry has a pointer, start scanning from it so we don't have
278    // to rescan the entire block.
279    BasicBlock::iterator ScanPos = DirtyBB->end();
280    if (Instruction *Inst = DirtyBBEntry.getInst()) {
281      ScanPos = Inst;
282
283      // We're removing QueryInst's dependence on Inst.
284      SmallPtrSet<Instruction*, 4> &InstMap = ReverseNonLocalDeps[Inst];
285      InstMap.erase(QueryInst);
286      if (InstMap.empty()) ReverseNonLocalDeps.erase(Inst);
287    }
288
289    // Find out if this block has a local dependency for QueryInst.
290    DirtyBBEntry = getDependencyFrom(QueryInst, ScanPos, DirtyBB);
291
292    // If the block has a dependency (i.e. it isn't completely transparent to
293    // the value), remember it!
294    if (!DirtyBBEntry.isNonLocal()) {
295      // Keep the ReverseNonLocalDeps map up to date so we can efficiently
296      // update this when we remove instructions.
297      if (Instruction *Inst = DirtyBBEntry.getInst())
298        ReverseNonLocalDeps[Inst].insert(QueryInst);
299      continue;
300    }
301
302    // If the block *is* completely transparent to the load, we need to check
303    // the predecessors of this block.  Add them to our worklist.
304    DirtyBlocks.append(pred_begin(DirtyBB), pred_end(DirtyBB));
305  }
306
307
308  // Copy the result into the output set.
309  for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end(); I != E;++I)
310    Result.push_back(std::make_pair(I->first, I->second));
311}
312
313/// removeInstruction - Remove an instruction from the dependence analysis,
314/// updating the dependence of instructions that previously depended on it.
315/// This method attempts to keep the cache coherent using the reverse map.
316void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
317  // Walk through the Non-local dependencies, removing this one as the value
318  // for any cached queries.
319  NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
320  if (NLDI != NonLocalDeps.end()) {
321    NonLocalDepInfo &BlockMap = *NLDI->second.getPointer();
322    for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
323         DI != DE; ++DI)
324      if (Instruction *Inst = DI->second.getInst())
325        ReverseNonLocalDeps[Inst].erase(RemInst);
326    delete &BlockMap;
327    NonLocalDeps.erase(NLDI);
328  }
329
330  // If we have a cached local dependence query for this instruction, remove it.
331  //
332  LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
333  if (LocalDepEntry != LocalDeps.end()) {
334    // Remove us from DepInst's reverse set now that the local dep info is gone.
335    if (Instruction *Inst = LocalDepEntry->second.getInst()) {
336      SmallPtrSet<Instruction*, 4> &RLD = ReverseLocalDeps[Inst];
337      RLD.erase(RemInst);
338      if (RLD.empty())
339        ReverseLocalDeps.erase(Inst);
340    }
341
342    // Remove this local dependency info.
343    LocalDeps.erase(LocalDepEntry);
344  }
345
346  // Loop over all of the things that depend on the instruction we're removing.
347  //
348  SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
349
350  ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
351  if (ReverseDepIt != ReverseLocalDeps.end()) {
352    SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
353    // RemInst can't be the terminator if it has stuff depending on it.
354    assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
355           "Nothing can locally depend on a terminator");
356
357    // Anything that was locally dependent on RemInst is now going to be
358    // dependent on the instruction after RemInst.  It will have the dirty flag
359    // set so it will rescan.  This saves having to scan the entire block to get
360    // to this point.
361    Instruction *NewDepInst = next(BasicBlock::iterator(RemInst));
362
363    for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
364         E = ReverseDeps.end(); I != E; ++I) {
365      Instruction *InstDependingOnRemInst = *I;
366      assert(InstDependingOnRemInst != RemInst &&
367             "Already removed our local dep info");
368
369      LocalDeps[InstDependingOnRemInst] = MemDepResult::getDirty(NewDepInst);
370
371      // Make sure to remember that new things depend on NewDepInst.
372      ReverseDepsToAdd.push_back(std::make_pair(NewDepInst,
373                                                InstDependingOnRemInst));
374    }
375
376    ReverseLocalDeps.erase(ReverseDepIt);
377
378    // Add new reverse deps after scanning the set, to avoid invalidating the
379    // 'ReverseDeps' reference.
380    while (!ReverseDepsToAdd.empty()) {
381      ReverseLocalDeps[ReverseDepsToAdd.back().first]
382        .insert(ReverseDepsToAdd.back().second);
383      ReverseDepsToAdd.pop_back();
384    }
385  }
386
387  ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
388  if (ReverseDepIt != ReverseNonLocalDeps.end()) {
389    SmallPtrSet<Instruction*, 4>& set = ReverseDepIt->second;
390    for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
391         I != E; ++I) {
392      assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
393
394      PerInstNLInfo &INLD = NonLocalDeps[*I];
395      assert(INLD.getPointer() != 0 && "Reverse mapping out of date?");
396      // The information is now dirty!
397      INLD.setInt(true);
398
399      for (NonLocalDepInfo::iterator DI = INLD.getPointer()->begin(),
400           DE = INLD.getPointer()->end(); DI != DE; ++DI) {
401        if (DI->second.getInst() != RemInst) continue;
402
403        // Convert to a dirty entry for the subsequent instruction.
404        Instruction *NextI = 0;
405        if (!RemInst->isTerminator()) {
406          NextI = next(BasicBlock::iterator(RemInst));
407          ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
408        }
409        DI->second = MemDepResult::getDirty(NextI);
410      }
411    }
412
413    ReverseNonLocalDeps.erase(ReverseDepIt);
414
415    // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
416    while (!ReverseDepsToAdd.empty()) {
417      ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
418        .insert(ReverseDepsToAdd.back().second);
419      ReverseDepsToAdd.pop_back();
420    }
421  }
422
423  assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
424  AA->deleteValue(RemInst);
425  DEBUG(verifyRemoved(RemInst));
426}
427
428/// verifyRemoved - Verify that the specified instruction does not occur
429/// in our internal data structures.
430void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
431  for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
432       E = LocalDeps.end(); I != E; ++I) {
433    assert(I->first != D && "Inst occurs in data structures");
434    assert(I->second.getInst() != D &&
435           "Inst occurs in data structures");
436  }
437
438  for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
439       E = NonLocalDeps.end(); I != E; ++I) {
440    assert(I->first != D && "Inst occurs in data structures");
441    const PerInstNLInfo &INLD = I->second;
442    for (NonLocalDepInfo::iterator II = INLD.getPointer()->begin(),
443         EE = INLD.getPointer()->end(); II  != EE; ++II)
444      assert(II->second.getInst() != D && "Inst occurs in data structures");
445  }
446
447  for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
448       E = ReverseLocalDeps.end(); I != E; ++I) {
449    assert(I->first != D && "Inst occurs in data structures");
450    for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
451         EE = I->second.end(); II != EE; ++II)
452      assert(*II != D && "Inst occurs in data structures");
453  }
454
455  for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
456       E = ReverseNonLocalDeps.end();
457       I != E; ++I) {
458    assert(I->first != D && "Inst occurs in data structures");
459    for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
460         EE = I->second.end(); II != EE; ++II)
461      assert(*II != D && "Inst occurs in data structures");
462  }
463}
464