MemoryDependenceAnalysis.cpp revision 7d4ff60b55772c731688cd27f9252e31ae964f84
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/ADT/STLExtras.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/Dominators.h"
23#include "llvm/Analysis/InstructionSimplify.h"
24#include "llvm/Analysis/MemoryBuiltins.h"
25#include "llvm/Analysis/PHITransAddr.h"
26#include "llvm/Analysis/ValueTracking.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/PredIteratorCache.h"
34using namespace llvm;
35
36STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
37STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
38STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
39
40STATISTIC(NumCacheNonLocalPtr,
41          "Number of fully cached non-local ptr responses");
42STATISTIC(NumCacheDirtyNonLocalPtr,
43          "Number of cached, but dirty, non-local ptr responses");
44STATISTIC(NumUncacheNonLocalPtr,
45          "Number of uncached non-local ptr responses");
46STATISTIC(NumCacheCompleteNonLocalPtr,
47          "Number of block queries that were completely cached");
48
49// Limit for the number of instructions to scan in a block.
50// FIXME: Figure out what a sane value is for this.
51//        (500 is relatively insane.)
52static const int BlockScanLimit = 500;
53
54char MemoryDependenceAnalysis::ID = 0;
55
56// Register this pass...
57INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep",
58                "Memory Dependence Analysis", false, true)
59INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
60INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep",
61                      "Memory Dependence Analysis", false, true)
62
63MemoryDependenceAnalysis::MemoryDependenceAnalysis()
64: FunctionPass(ID), PredCache(0) {
65  initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry());
66}
67MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
68}
69
70/// Clean up memory in between runs
71void MemoryDependenceAnalysis::releaseMemory() {
72  LocalDeps.clear();
73  NonLocalDeps.clear();
74  NonLocalPointerDeps.clear();
75  ReverseLocalDeps.clear();
76  ReverseNonLocalDeps.clear();
77  ReverseNonLocalPtrDeps.clear();
78  PredCache->clear();
79}
80
81
82
83/// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
84///
85void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
86  AU.setPreservesAll();
87  AU.addRequiredTransitive<AliasAnalysis>();
88}
89
90bool MemoryDependenceAnalysis::runOnFunction(Function &) {
91  AA = &getAnalysis<AliasAnalysis>();
92  TD = getAnalysisIfAvailable<DataLayout>();
93  DT = getAnalysisIfAvailable<DominatorTree>();
94  if (PredCache == 0)
95    PredCache.reset(new PredIteratorCache());
96  return false;
97}
98
99/// RemoveFromReverseMap - This is a helper function that removes Val from
100/// 'Inst's set in ReverseMap.  If the set becomes empty, remove Inst's entry.
101template <typename KeyTy>
102static void RemoveFromReverseMap(DenseMap<Instruction*,
103                                 SmallPtrSet<KeyTy, 4> > &ReverseMap,
104                                 Instruction *Inst, KeyTy Val) {
105  typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator
106  InstIt = ReverseMap.find(Inst);
107  assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
108  bool Found = InstIt->second.erase(Val);
109  assert(Found && "Invalid reverse map!"); (void)Found;
110  if (InstIt->second.empty())
111    ReverseMap.erase(InstIt);
112}
113
114/// GetLocation - If the given instruction references a specific memory
115/// location, fill in Loc with the details, otherwise set Loc.Ptr to null.
116/// Return a ModRefInfo value describing the general behavior of the
117/// instruction.
118static
119AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst,
120                                        AliasAnalysis::Location &Loc,
121                                        AliasAnalysis *AA) {
122  if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
123    if (LI->isUnordered()) {
124      Loc = AA->getLocation(LI);
125      return AliasAnalysis::Ref;
126    }
127    if (LI->getOrdering() == Monotonic) {
128      Loc = AA->getLocation(LI);
129      return AliasAnalysis::ModRef;
130    }
131    Loc = AliasAnalysis::Location();
132    return AliasAnalysis::ModRef;
133  }
134
135  if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
136    if (SI->isUnordered()) {
137      Loc = AA->getLocation(SI);
138      return AliasAnalysis::Mod;
139    }
140    if (SI->getOrdering() == Monotonic) {
141      Loc = AA->getLocation(SI);
142      return AliasAnalysis::ModRef;
143    }
144    Loc = AliasAnalysis::Location();
145    return AliasAnalysis::ModRef;
146  }
147
148  if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
149    Loc = AA->getLocation(V);
150    return AliasAnalysis::ModRef;
151  }
152
153  if (const CallInst *CI = isFreeCall(Inst, AA->getTargetLibraryInfo())) {
154    // calls to free() deallocate the entire structure
155    Loc = AliasAnalysis::Location(CI->getArgOperand(0));
156    return AliasAnalysis::Mod;
157  }
158
159  if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
160    switch (II->getIntrinsicID()) {
161    case Intrinsic::lifetime_start:
162    case Intrinsic::lifetime_end:
163    case Intrinsic::invariant_start:
164      Loc = AliasAnalysis::Location(II->getArgOperand(1),
165                                    cast<ConstantInt>(II->getArgOperand(0))
166                                      ->getZExtValue(),
167                                    II->getMetadata(LLVMContext::MD_tbaa));
168      // These intrinsics don't really modify the memory, but returning Mod
169      // will allow them to be handled conservatively.
170      return AliasAnalysis::Mod;
171    case Intrinsic::invariant_end:
172      Loc = AliasAnalysis::Location(II->getArgOperand(2),
173                                    cast<ConstantInt>(II->getArgOperand(1))
174                                      ->getZExtValue(),
175                                    II->getMetadata(LLVMContext::MD_tbaa));
176      // These intrinsics don't really modify the memory, but returning Mod
177      // will allow them to be handled conservatively.
178      return AliasAnalysis::Mod;
179    default:
180      break;
181    }
182
183  // Otherwise, just do the coarse-grained thing that always works.
184  if (Inst->mayWriteToMemory())
185    return AliasAnalysis::ModRef;
186  if (Inst->mayReadFromMemory())
187    return AliasAnalysis::Ref;
188  return AliasAnalysis::NoModRef;
189}
190
191/// getCallSiteDependencyFrom - Private helper for finding the local
192/// dependencies of a call site.
193MemDepResult MemoryDependenceAnalysis::
194getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
195                          BasicBlock::iterator ScanIt, BasicBlock *BB) {
196  unsigned Limit = BlockScanLimit;
197
198  // Walk backwards through the block, looking for dependencies
199  while (ScanIt != BB->begin()) {
200    // Limit the amount of scanning we do so we don't end up with quadratic
201    // running time on extreme testcases.
202    --Limit;
203    if (!Limit)
204      return MemDepResult::getUnknown();
205
206    Instruction *Inst = --ScanIt;
207
208    // If this inst is a memory op, get the pointer it accessed
209    AliasAnalysis::Location Loc;
210    AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA);
211    if (Loc.Ptr) {
212      // A simple instruction.
213      if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef)
214        return MemDepResult::getClobber(Inst);
215      continue;
216    }
217
218    if (CallSite InstCS = cast<Value>(Inst)) {
219      // Debug intrinsics don't cause dependences.
220      if (isa<DbgInfoIntrinsic>(Inst)) continue;
221      // If these two calls do not interfere, look past it.
222      switch (AA->getModRefInfo(CS, InstCS)) {
223      case AliasAnalysis::NoModRef:
224        // If the two calls are the same, return InstCS as a Def, so that
225        // CS can be found redundant and eliminated.
226        if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) &&
227            CS.getInstruction()->isIdenticalToWhenDefined(Inst))
228          return MemDepResult::getDef(Inst);
229
230        // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
231        // keep scanning.
232        continue;
233      default:
234        return MemDepResult::getClobber(Inst);
235      }
236    }
237
238    // If we could not obtain a pointer for the instruction and the instruction
239    // touches memory then assume that this is a dependency.
240    if (MR != AliasAnalysis::NoModRef)
241      return MemDepResult::getClobber(Inst);
242  }
243
244  // No dependence found.  If this is the entry block of the function, it is
245  // unknown, otherwise it is non-local.
246  if (BB != &BB->getParent()->getEntryBlock())
247    return MemDepResult::getNonLocal();
248  return MemDepResult::getNonFuncLocal();
249}
250
251/// isLoadLoadClobberIfExtendedToFullWidth - Return true if LI is a load that
252/// would fully overlap MemLoc if done as a wider legal integer load.
253///
254/// MemLocBase, MemLocOffset are lazily computed here the first time the
255/// base/offs of memloc is needed.
256static bool
257isLoadLoadClobberIfExtendedToFullWidth(const AliasAnalysis::Location &MemLoc,
258                                       const Value *&MemLocBase,
259                                       int64_t &MemLocOffs,
260                                       const LoadInst *LI,
261                                       const DataLayout *TD) {
262  // If we have no target data, we can't do this.
263  if (TD == 0) return false;
264
265  // If we haven't already computed the base/offset of MemLoc, do so now.
266  if (MemLocBase == 0)
267    MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, TD);
268
269  unsigned Size = MemoryDependenceAnalysis::
270    getLoadLoadClobberFullWidthSize(MemLocBase, MemLocOffs, MemLoc.Size,
271                                    LI, *TD);
272  return Size != 0;
273}
274
275/// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
276/// looks at a memory location for a load (specified by MemLocBase, Offs,
277/// and Size) and compares it against a load.  If the specified load could
278/// be safely widened to a larger integer load that is 1) still efficient,
279/// 2) safe for the target, and 3) would provide the specified memory
280/// location value, then this function returns the size in bytes of the
281/// load width to use.  If not, this returns zero.
282unsigned MemoryDependenceAnalysis::
283getLoadLoadClobberFullWidthSize(const Value *MemLocBase, int64_t MemLocOffs,
284                                unsigned MemLocSize, const LoadInst *LI,
285                                const DataLayout &TD) {
286  // We can only extend simple integer loads.
287  if (!isa<IntegerType>(LI->getType()) || !LI->isSimple()) return 0;
288
289  // Load widening is hostile to ThreadSanitizer: it may cause false positives
290  // or make the reports more cryptic (access sizes are wrong).
291  if (LI->getParent()->getParent()->getAttributes().
292      hasAttribute(AttributeSet::FunctionIndex, Attribute::SanitizeThread))
293    return 0;
294
295  // Get the base of this load.
296  int64_t LIOffs = 0;
297  const Value *LIBase =
298    GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, &TD);
299
300  // If the two pointers are not based on the same pointer, we can't tell that
301  // they are related.
302  if (LIBase != MemLocBase) return 0;
303
304  // Okay, the two values are based on the same pointer, but returned as
305  // no-alias.  This happens when we have things like two byte loads at "P+1"
306  // and "P+3".  Check to see if increasing the size of the "LI" load up to its
307  // alignment (or the largest native integer type) will allow us to load all
308  // the bits required by MemLoc.
309
310  // If MemLoc is before LI, then no widening of LI will help us out.
311  if (MemLocOffs < LIOffs) return 0;
312
313  // Get the alignment of the load in bytes.  We assume that it is safe to load
314  // any legal integer up to this size without a problem.  For example, if we're
315  // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
316  // widen it up to an i32 load.  If it is known 2-byte aligned, we can widen it
317  // to i16.
318  unsigned LoadAlign = LI->getAlignment();
319
320  int64_t MemLocEnd = MemLocOffs+MemLocSize;
321
322  // If no amount of rounding up will let MemLoc fit into LI, then bail out.
323  if (LIOffs+LoadAlign < MemLocEnd) return 0;
324
325  // This is the size of the load to try.  Start with the next larger power of
326  // two.
327  unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits()/8U;
328  NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
329
330  while (1) {
331    // If this load size is bigger than our known alignment or would not fit
332    // into a native integer register, then we fail.
333    if (NewLoadByteSize > LoadAlign ||
334        !TD.fitsInLegalInteger(NewLoadByteSize*8))
335      return 0;
336
337    if (LIOffs+NewLoadByteSize > MemLocEnd &&
338        LI->getParent()->getParent()->getAttributes().
339          hasAttribute(AttributeSet::FunctionIndex, Attribute::SanitizeAddress))
340      // We will be reading past the location accessed by the original program.
341      // While this is safe in a regular build, Address Safety analysis tools
342      // may start reporting false warnings. So, don't do widening.
343      return 0;
344
345    // If a load of this width would include all of MemLoc, then we succeed.
346    if (LIOffs+NewLoadByteSize >= MemLocEnd)
347      return NewLoadByteSize;
348
349    NewLoadByteSize <<= 1;
350  }
351}
352
353/// getPointerDependencyFrom - Return the instruction on which a memory
354/// location depends.  If isLoad is true, this routine ignores may-aliases with
355/// read-only operations.  If isLoad is false, this routine ignores may-aliases
356/// with reads from read-only locations.  If possible, pass the query
357/// instruction as well; this function may take advantage of the metadata
358/// annotated to the query instruction to refine the result.
359MemDepResult MemoryDependenceAnalysis::
360getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad,
361                         BasicBlock::iterator ScanIt, BasicBlock *BB,
362                         Instruction *QueryInst) {
363
364  const Value *MemLocBase = 0;
365  int64_t MemLocOffset = 0;
366  unsigned Limit = BlockScanLimit;
367  bool isInvariantLoad = false;
368  if (isLoad && QueryInst) {
369    LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
370    if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != 0)
371      isInvariantLoad = true;
372  }
373
374  // Walk backwards through the basic block, looking for dependencies.
375  while (ScanIt != BB->begin()) {
376    // Limit the amount of scanning we do so we don't end up with quadratic
377    // running time on extreme testcases.
378    --Limit;
379    if (!Limit)
380      return MemDepResult::getUnknown();
381
382    Instruction *Inst = --ScanIt;
383
384    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
385      // Debug intrinsics don't (and can't) cause dependences.
386      if (isa<DbgInfoIntrinsic>(II)) continue;
387
388      // If we reach a lifetime begin or end marker, then the query ends here
389      // because the value is undefined.
390      if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
391        // FIXME: This only considers queries directly on the invariant-tagged
392        // pointer, not on query pointers that are indexed off of them.  It'd
393        // be nice to handle that at some point (the right approach is to use
394        // GetPointerBaseWithConstantOffset).
395        if (AA->isMustAlias(AliasAnalysis::Location(II->getArgOperand(1)),
396                            MemLoc))
397          return MemDepResult::getDef(II);
398        continue;
399      }
400    }
401
402    // Values depend on loads if the pointers are must aliased.  This means that
403    // a load depends on another must aliased load from the same value.
404    if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
405      // Atomic loads have complications involved.
406      // FIXME: This is overly conservative.
407      if (!LI->isUnordered())
408        return MemDepResult::getClobber(LI);
409
410      AliasAnalysis::Location LoadLoc = AA->getLocation(LI);
411
412      // If we found a pointer, check if it could be the same as our pointer.
413      AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc);
414
415      if (isLoad) {
416        if (R == AliasAnalysis::NoAlias) {
417          // If this is an over-aligned integer load (for example,
418          // "load i8* %P, align 4") see if it would obviously overlap with the
419          // queried location if widened to a larger load (e.g. if the queried
420          // location is 1 byte at P+1).  If so, return it as a load/load
421          // clobber result, allowing the client to decide to widen the load if
422          // it wants to.
423          if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType()))
424            if (LI->getAlignment()*8 > ITy->getPrimitiveSizeInBits() &&
425                isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase,
426                                                       MemLocOffset, LI, TD))
427              return MemDepResult::getClobber(Inst);
428
429          continue;
430        }
431
432        // Must aliased loads are defs of each other.
433        if (R == AliasAnalysis::MustAlias)
434          return MemDepResult::getDef(Inst);
435
436#if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
437      // in terms of clobbering loads, but since it does this by looking
438      // at the clobbering load directly, it doesn't know about any
439      // phi translation that may have happened along the way.
440
441        // If we have a partial alias, then return this as a clobber for the
442        // client to handle.
443        if (R == AliasAnalysis::PartialAlias)
444          return MemDepResult::getClobber(Inst);
445#endif
446
447        // Random may-alias loads don't depend on each other without a
448        // dependence.
449        continue;
450      }
451
452      // Stores don't depend on other no-aliased accesses.
453      if (R == AliasAnalysis::NoAlias)
454        continue;
455
456      // Stores don't alias loads from read-only memory.
457      if (AA->pointsToConstantMemory(LoadLoc))
458        continue;
459
460      // Stores depend on may/must aliased loads.
461      return MemDepResult::getDef(Inst);
462    }
463
464    if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
465      // Atomic stores have complications involved.
466      // FIXME: This is overly conservative.
467      if (!SI->isUnordered())
468        return MemDepResult::getClobber(SI);
469
470      // If alias analysis can tell that this store is guaranteed to not modify
471      // the query pointer, ignore it.  Use getModRefInfo to handle cases where
472      // the query pointer points to constant memory etc.
473      if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
474        continue;
475
476      // Ok, this store might clobber the query pointer.  Check to see if it is
477      // a must alias: in this case, we want to return this as a def.
478      AliasAnalysis::Location StoreLoc = AA->getLocation(SI);
479
480      // If we found a pointer, check if it could be the same as our pointer.
481      AliasAnalysis::AliasResult R = AA->alias(StoreLoc, MemLoc);
482
483      if (R == AliasAnalysis::NoAlias)
484        continue;
485      if (R == AliasAnalysis::MustAlias)
486        return MemDepResult::getDef(Inst);
487      if (isInvariantLoad)
488       continue;
489      return MemDepResult::getClobber(Inst);
490    }
491
492    // If this is an allocation, and if we know that the accessed pointer is to
493    // the allocation, return Def.  This means that there is no dependence and
494    // the access can be optimized based on that.  For example, a load could
495    // turn into undef.
496    // Note: Only determine this to be a malloc if Inst is the malloc call, not
497    // a subsequent bitcast of the malloc call result.  There can be stores to
498    // the malloced memory between the malloc call and its bitcast uses, and we
499    // need to continue scanning until the malloc call.
500    const TargetLibraryInfo *TLI = AA->getTargetLibraryInfo();
501    if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, TLI)) {
502      const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, TD);
503
504      if (AccessPtr == Inst || AA->isMustAlias(Inst, AccessPtr))
505        return MemDepResult::getDef(Inst);
506      // Be conservative if the accessed pointer may alias the allocation.
507      if (AA->alias(Inst, AccessPtr) != AliasAnalysis::NoAlias)
508        return MemDepResult::getClobber(Inst);
509      // If the allocation is not aliased and does not read memory (like
510      // strdup), it is safe to ignore.
511      if (isa<AllocaInst>(Inst) ||
512          isMallocLikeFn(Inst, TLI) || isCallocLikeFn(Inst, TLI))
513        continue;
514    }
515
516    // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
517    AliasAnalysis::ModRefResult MR = AA->getModRefInfo(Inst, MemLoc);
518    // If necessary, perform additional analysis.
519    if (MR == AliasAnalysis::ModRef)
520      MR = AA->callCapturesBefore(Inst, MemLoc, DT);
521    switch (MR) {
522    case AliasAnalysis::NoModRef:
523      // If the call has no effect on the queried pointer, just ignore it.
524      continue;
525    case AliasAnalysis::Mod:
526      return MemDepResult::getClobber(Inst);
527    case AliasAnalysis::Ref:
528      // If the call is known to never store to the pointer, and if this is a
529      // load query, we can safely ignore it (scan past it).
530      if (isLoad)
531        continue;
532    default:
533      // Otherwise, there is a potential dependence.  Return a clobber.
534      return MemDepResult::getClobber(Inst);
535    }
536  }
537
538  // No dependence found.  If this is the entry block of the function, it is
539  // unknown, otherwise it is non-local.
540  if (BB != &BB->getParent()->getEntryBlock())
541    return MemDepResult::getNonLocal();
542  return MemDepResult::getNonFuncLocal();
543}
544
545/// getDependency - Return the instruction on which a memory operation
546/// depends.
547MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
548  Instruction *ScanPos = QueryInst;
549
550  // Check for a cached result
551  MemDepResult &LocalCache = LocalDeps[QueryInst];
552
553  // If the cached entry is non-dirty, just return it.  Note that this depends
554  // on MemDepResult's default constructing to 'dirty'.
555  if (!LocalCache.isDirty())
556    return LocalCache;
557
558  // Otherwise, if we have a dirty entry, we know we can start the scan at that
559  // instruction, which may save us some work.
560  if (Instruction *Inst = LocalCache.getInst()) {
561    ScanPos = Inst;
562
563    RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
564  }
565
566  BasicBlock *QueryParent = QueryInst->getParent();
567
568  // Do the scan.
569  if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
570    // No dependence found.  If this is the entry block of the function, it is
571    // unknown, otherwise it is non-local.
572    if (QueryParent != &QueryParent->getParent()->getEntryBlock())
573      LocalCache = MemDepResult::getNonLocal();
574    else
575      LocalCache = MemDepResult::getNonFuncLocal();
576  } else {
577    AliasAnalysis::Location MemLoc;
578    AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
579    if (MemLoc.Ptr) {
580      // If we can do a pointer scan, make it happen.
581      bool isLoad = !(MR & AliasAnalysis::Mod);
582      if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
583        isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
584
585      LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
586                                            QueryParent, QueryInst);
587    } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
588      CallSite QueryCS(QueryInst);
589      bool isReadOnly = AA->onlyReadsMemory(QueryCS);
590      LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
591                                             QueryParent);
592    } else
593      // Non-memory instruction.
594      LocalCache = MemDepResult::getUnknown();
595  }
596
597  // Remember the result!
598  if (Instruction *I = LocalCache.getInst())
599    ReverseLocalDeps[I].insert(QueryInst);
600
601  return LocalCache;
602}
603
604#ifndef NDEBUG
605/// AssertSorted - This method is used when -debug is specified to verify that
606/// cache arrays are properly kept sorted.
607static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
608                         int Count = -1) {
609  if (Count == -1) Count = Cache.size();
610  if (Count == 0) return;
611
612  for (unsigned i = 1; i != unsigned(Count); ++i)
613    assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
614}
615#endif
616
617/// getNonLocalCallDependency - Perform a full dependency query for the
618/// specified call, returning the set of blocks that the value is
619/// potentially live across.  The returned set of results will include a
620/// "NonLocal" result for all blocks where the value is live across.
621///
622/// This method assumes the instruction returns a "NonLocal" dependency
623/// within its own block.
624///
625/// This returns a reference to an internal data structure that may be
626/// invalidated on the next non-local query or when an instruction is
627/// removed.  Clients must copy this data if they want it around longer than
628/// that.
629const MemoryDependenceAnalysis::NonLocalDepInfo &
630MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
631  assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
632 "getNonLocalCallDependency should only be used on calls with non-local deps!");
633  PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
634  NonLocalDepInfo &Cache = CacheP.first;
635
636  /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
637  /// the cached case, this can happen due to instructions being deleted etc. In
638  /// the uncached case, this starts out as the set of predecessors we care
639  /// about.
640  SmallVector<BasicBlock*, 32> DirtyBlocks;
641
642  if (!Cache.empty()) {
643    // Okay, we have a cache entry.  If we know it is not dirty, just return it
644    // with no computation.
645    if (!CacheP.second) {
646      ++NumCacheNonLocal;
647      return Cache;
648    }
649
650    // If we already have a partially computed set of results, scan them to
651    // determine what is dirty, seeding our initial DirtyBlocks worklist.
652    for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
653       I != E; ++I)
654      if (I->getResult().isDirty())
655        DirtyBlocks.push_back(I->getBB());
656
657    // Sort the cache so that we can do fast binary search lookups below.
658    std::sort(Cache.begin(), Cache.end());
659
660    ++NumCacheDirtyNonLocal;
661    //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
662    //     << Cache.size() << " cached: " << *QueryInst;
663  } else {
664    // Seed DirtyBlocks with each of the preds of QueryInst's block.
665    BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
666    for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
667      DirtyBlocks.push_back(*PI);
668    ++NumUncacheNonLocal;
669  }
670
671  // isReadonlyCall - If this is a read-only call, we can be more aggressive.
672  bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
673
674  SmallPtrSet<BasicBlock*, 64> Visited;
675
676  unsigned NumSortedEntries = Cache.size();
677  DEBUG(AssertSorted(Cache));
678
679  // Iterate while we still have blocks to update.
680  while (!DirtyBlocks.empty()) {
681    BasicBlock *DirtyBB = DirtyBlocks.back();
682    DirtyBlocks.pop_back();
683
684    // Already processed this block?
685    if (!Visited.insert(DirtyBB))
686      continue;
687
688    // Do a binary search to see if we already have an entry for this block in
689    // the cache set.  If so, find it.
690    DEBUG(AssertSorted(Cache, NumSortedEntries));
691    NonLocalDepInfo::iterator Entry =
692      std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
693                       NonLocalDepEntry(DirtyBB));
694    if (Entry != Cache.begin() && prior(Entry)->getBB() == DirtyBB)
695      --Entry;
696
697    NonLocalDepEntry *ExistingResult = 0;
698    if (Entry != Cache.begin()+NumSortedEntries &&
699        Entry->getBB() == DirtyBB) {
700      // If we already have an entry, and if it isn't already dirty, the block
701      // is done.
702      if (!Entry->getResult().isDirty())
703        continue;
704
705      // Otherwise, remember this slot so we can update the value.
706      ExistingResult = &*Entry;
707    }
708
709    // If the dirty entry has a pointer, start scanning from it so we don't have
710    // to rescan the entire block.
711    BasicBlock::iterator ScanPos = DirtyBB->end();
712    if (ExistingResult) {
713      if (Instruction *Inst = ExistingResult->getResult().getInst()) {
714        ScanPos = Inst;
715        // We're removing QueryInst's use of Inst.
716        RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
717                             QueryCS.getInstruction());
718      }
719    }
720
721    // Find out if this block has a local dependency for QueryInst.
722    MemDepResult Dep;
723
724    if (ScanPos != DirtyBB->begin()) {
725      Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
726    } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
727      // No dependence found.  If this is the entry block of the function, it is
728      // a clobber, otherwise it is unknown.
729      Dep = MemDepResult::getNonLocal();
730    } else {
731      Dep = MemDepResult::getNonFuncLocal();
732    }
733
734    // If we had a dirty entry for the block, update it.  Otherwise, just add
735    // a new entry.
736    if (ExistingResult)
737      ExistingResult->setResult(Dep);
738    else
739      Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
740
741    // If the block has a dependency (i.e. it isn't completely transparent to
742    // the value), remember the association!
743    if (!Dep.isNonLocal()) {
744      // Keep the ReverseNonLocalDeps map up to date so we can efficiently
745      // update this when we remove instructions.
746      if (Instruction *Inst = Dep.getInst())
747        ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
748    } else {
749
750      // If the block *is* completely transparent to the load, we need to check
751      // the predecessors of this block.  Add them to our worklist.
752      for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
753        DirtyBlocks.push_back(*PI);
754    }
755  }
756
757  return Cache;
758}
759
760/// getNonLocalPointerDependency - Perform a full dependency query for an
761/// access to the specified (non-volatile) memory location, returning the
762/// set of instructions that either define or clobber the value.
763///
764/// This method assumes the pointer has a "NonLocal" dependency within its
765/// own block.
766///
767void MemoryDependenceAnalysis::
768getNonLocalPointerDependency(const AliasAnalysis::Location &Loc, bool isLoad,
769                             BasicBlock *FromBB,
770                             SmallVectorImpl<NonLocalDepResult> &Result) {
771  assert(Loc.Ptr->getType()->isPointerTy() &&
772         "Can't get pointer deps of a non-pointer!");
773  Result.clear();
774
775  PHITransAddr Address(const_cast<Value *>(Loc.Ptr), TD);
776
777  // This is the set of blocks we've inspected, and the pointer we consider in
778  // each block.  Because of critical edges, we currently bail out if querying
779  // a block with multiple different pointers.  This can happen during PHI
780  // translation.
781  DenseMap<BasicBlock*, Value*> Visited;
782  if (!getNonLocalPointerDepFromBB(Address, Loc, isLoad, FromBB,
783                                   Result, Visited, true))
784    return;
785  Result.clear();
786  Result.push_back(NonLocalDepResult(FromBB,
787                                     MemDepResult::getUnknown(),
788                                     const_cast<Value *>(Loc.Ptr)));
789}
790
791/// GetNonLocalInfoForBlock - Compute the memdep value for BB with
792/// Pointer/PointeeSize using either cached information in Cache or by doing a
793/// lookup (which may use dirty cache info if available).  If we do a lookup,
794/// add the result to the cache.
795MemDepResult MemoryDependenceAnalysis::
796GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
797                        bool isLoad, BasicBlock *BB,
798                        NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
799
800  // Do a binary search to see if we already have an entry for this block in
801  // the cache set.  If so, find it.
802  NonLocalDepInfo::iterator Entry =
803    std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
804                     NonLocalDepEntry(BB));
805  if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
806    --Entry;
807
808  NonLocalDepEntry *ExistingResult = 0;
809  if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
810    ExistingResult = &*Entry;
811
812  // If we have a cached entry, and it is non-dirty, use it as the value for
813  // this dependency.
814  if (ExistingResult && !ExistingResult->getResult().isDirty()) {
815    ++NumCacheNonLocalPtr;
816    return ExistingResult->getResult();
817  }
818
819  // Otherwise, we have to scan for the value.  If we have a dirty cache
820  // entry, start scanning from its position, otherwise we scan from the end
821  // of the block.
822  BasicBlock::iterator ScanPos = BB->end();
823  if (ExistingResult && ExistingResult->getResult().getInst()) {
824    assert(ExistingResult->getResult().getInst()->getParent() == BB &&
825           "Instruction invalidated?");
826    ++NumCacheDirtyNonLocalPtr;
827    ScanPos = ExistingResult->getResult().getInst();
828
829    // Eliminating the dirty entry from 'Cache', so update the reverse info.
830    ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
831    RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
832  } else {
833    ++NumUncacheNonLocalPtr;
834  }
835
836  // Scan the block for the dependency.
837  MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB);
838
839  // If we had a dirty entry for the block, update it.  Otherwise, just add
840  // a new entry.
841  if (ExistingResult)
842    ExistingResult->setResult(Dep);
843  else
844    Cache->push_back(NonLocalDepEntry(BB, Dep));
845
846  // If the block has a dependency (i.e. it isn't completely transparent to
847  // the value), remember the reverse association because we just added it
848  // to Cache!
849  if (!Dep.isDef() && !Dep.isClobber())
850    return Dep;
851
852  // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
853  // update MemDep when we remove instructions.
854  Instruction *Inst = Dep.getInst();
855  assert(Inst && "Didn't depend on anything?");
856  ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
857  ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
858  return Dep;
859}
860
861/// SortNonLocalDepInfoCache - Sort the a NonLocalDepInfo cache, given a certain
862/// number of elements in the array that are already properly ordered.  This is
863/// optimized for the case when only a few entries are added.
864static void
865SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
866                         unsigned NumSortedEntries) {
867  switch (Cache.size() - NumSortedEntries) {
868  case 0:
869    // done, no new entries.
870    break;
871  case 2: {
872    // Two new entries, insert the last one into place.
873    NonLocalDepEntry Val = Cache.back();
874    Cache.pop_back();
875    MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
876      std::upper_bound(Cache.begin(), Cache.end()-1, Val);
877    Cache.insert(Entry, Val);
878    // FALL THROUGH.
879  }
880  case 1:
881    // One new entry, Just insert the new value at the appropriate position.
882    if (Cache.size() != 1) {
883      NonLocalDepEntry Val = Cache.back();
884      Cache.pop_back();
885      MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
886        std::upper_bound(Cache.begin(), Cache.end(), Val);
887      Cache.insert(Entry, Val);
888    }
889    break;
890  default:
891    // Added many values, do a full scale sort.
892    std::sort(Cache.begin(), Cache.end());
893    break;
894  }
895}
896
897/// getNonLocalPointerDepFromBB - Perform a dependency query based on
898/// pointer/pointeesize starting at the end of StartBB.  Add any clobber/def
899/// results to the results vector and keep track of which blocks are visited in
900/// 'Visited'.
901///
902/// This has special behavior for the first block queries (when SkipFirstBlock
903/// is true).  In this special case, it ignores the contents of the specified
904/// block and starts returning dependence info for its predecessors.
905///
906/// This function returns false on success, or true to indicate that it could
907/// not compute dependence information for some reason.  This should be treated
908/// as a clobber dependence on the first instruction in the predecessor block.
909bool MemoryDependenceAnalysis::
910getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
911                            const AliasAnalysis::Location &Loc,
912                            bool isLoad, BasicBlock *StartBB,
913                            SmallVectorImpl<NonLocalDepResult> &Result,
914                            DenseMap<BasicBlock*, Value*> &Visited,
915                            bool SkipFirstBlock) {
916
917  // Look up the cached info for Pointer.
918  ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
919
920  // Set up a temporary NLPI value. If the map doesn't yet have an entry for
921  // CacheKey, this value will be inserted as the associated value. Otherwise,
922  // it'll be ignored, and we'll have to check to see if the cached size and
923  // tbaa tag are consistent with the current query.
924  NonLocalPointerInfo InitialNLPI;
925  InitialNLPI.Size = Loc.Size;
926  InitialNLPI.TBAATag = Loc.TBAATag;
927
928  // Get the NLPI for CacheKey, inserting one into the map if it doesn't
929  // already have one.
930  std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
931    NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
932  NonLocalPointerInfo *CacheInfo = &Pair.first->second;
933
934  // If we already have a cache entry for this CacheKey, we may need to do some
935  // work to reconcile the cache entry and the current query.
936  if (!Pair.second) {
937    if (CacheInfo->Size < Loc.Size) {
938      // The query's Size is greater than the cached one. Throw out the
939      // cached data and proceed with the query at the greater size.
940      CacheInfo->Pair = BBSkipFirstBlockPair();
941      CacheInfo->Size = Loc.Size;
942      for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
943           DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
944        if (Instruction *Inst = DI->getResult().getInst())
945          RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
946      CacheInfo->NonLocalDeps.clear();
947    } else if (CacheInfo->Size > Loc.Size) {
948      // This query's Size is less than the cached one. Conservatively restart
949      // the query using the greater size.
950      return getNonLocalPointerDepFromBB(Pointer,
951                                         Loc.getWithNewSize(CacheInfo->Size),
952                                         isLoad, StartBB, Result, Visited,
953                                         SkipFirstBlock);
954    }
955
956    // If the query's TBAATag is inconsistent with the cached one,
957    // conservatively throw out the cached data and restart the query with
958    // no tag if needed.
959    if (CacheInfo->TBAATag != Loc.TBAATag) {
960      if (CacheInfo->TBAATag) {
961        CacheInfo->Pair = BBSkipFirstBlockPair();
962        CacheInfo->TBAATag = 0;
963        for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
964             DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
965          if (Instruction *Inst = DI->getResult().getInst())
966            RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
967        CacheInfo->NonLocalDeps.clear();
968      }
969      if (Loc.TBAATag)
970        return getNonLocalPointerDepFromBB(Pointer, Loc.getWithoutTBAATag(),
971                                           isLoad, StartBB, Result, Visited,
972                                           SkipFirstBlock);
973    }
974  }
975
976  NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
977
978  // If we have valid cached information for exactly the block we are
979  // investigating, just return it with no recomputation.
980  if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
981    // We have a fully cached result for this query then we can just return the
982    // cached results and populate the visited set.  However, we have to verify
983    // that we don't already have conflicting results for these blocks.  Check
984    // to ensure that if a block in the results set is in the visited set that
985    // it was for the same pointer query.
986    if (!Visited.empty()) {
987      for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
988           I != E; ++I) {
989        DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
990        if (VI == Visited.end() || VI->second == Pointer.getAddr())
991          continue;
992
993        // We have a pointer mismatch in a block.  Just return clobber, saying
994        // that something was clobbered in this result.  We could also do a
995        // non-fully cached query, but there is little point in doing this.
996        return true;
997      }
998    }
999
1000    Value *Addr = Pointer.getAddr();
1001    for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
1002         I != E; ++I) {
1003      Visited.insert(std::make_pair(I->getBB(), Addr));
1004      if (!I->getResult().isNonLocal() && DT->isReachableFromEntry(I->getBB()))
1005        Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
1006    }
1007    ++NumCacheCompleteNonLocalPtr;
1008    return false;
1009  }
1010
1011  // Otherwise, either this is a new block, a block with an invalid cache
1012  // pointer or one that we're about to invalidate by putting more info into it
1013  // than its valid cache info.  If empty, the result will be valid cache info,
1014  // otherwise it isn't.
1015  if (Cache->empty())
1016    CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
1017  else
1018    CacheInfo->Pair = BBSkipFirstBlockPair();
1019
1020  SmallVector<BasicBlock*, 32> Worklist;
1021  Worklist.push_back(StartBB);
1022
1023  // PredList used inside loop.
1024  SmallVector<std::pair<BasicBlock*, PHITransAddr>, 16> PredList;
1025
1026  // Keep track of the entries that we know are sorted.  Previously cached
1027  // entries will all be sorted.  The entries we add we only sort on demand (we
1028  // don't insert every element into its sorted position).  We know that we
1029  // won't get any reuse from currently inserted values, because we don't
1030  // revisit blocks after we insert info for them.
1031  unsigned NumSortedEntries = Cache->size();
1032  DEBUG(AssertSorted(*Cache));
1033
1034  while (!Worklist.empty()) {
1035    BasicBlock *BB = Worklist.pop_back_val();
1036
1037    // Skip the first block if we have it.
1038    if (!SkipFirstBlock) {
1039      // Analyze the dependency of *Pointer in FromBB.  See if we already have
1040      // been here.
1041      assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
1042
1043      // Get the dependency info for Pointer in BB.  If we have cached
1044      // information, we will use it, otherwise we compute it.
1045      DEBUG(AssertSorted(*Cache, NumSortedEntries));
1046      MemDepResult Dep = GetNonLocalInfoForBlock(Loc, isLoad, BB, Cache,
1047                                                 NumSortedEntries);
1048
1049      // If we got a Def or Clobber, add this to the list of results.
1050      if (!Dep.isNonLocal() && DT->isReachableFromEntry(BB)) {
1051        Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
1052        continue;
1053      }
1054    }
1055
1056    // If 'Pointer' is an instruction defined in this block, then we need to do
1057    // phi translation to change it into a value live in the predecessor block.
1058    // If not, we just add the predecessors to the worklist and scan them with
1059    // the same Pointer.
1060    if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
1061      SkipFirstBlock = false;
1062      SmallVector<BasicBlock*, 16> NewBlocks;
1063      for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
1064        // Verify that we haven't looked at this block yet.
1065        std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
1066          InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
1067        if (InsertRes.second) {
1068          // First time we've looked at *PI.
1069          NewBlocks.push_back(*PI);
1070          continue;
1071        }
1072
1073        // If we have seen this block before, but it was with a different
1074        // pointer then we have a phi translation failure and we have to treat
1075        // this as a clobber.
1076        if (InsertRes.first->second != Pointer.getAddr()) {
1077          // Make sure to clean up the Visited map before continuing on to
1078          // PredTranslationFailure.
1079          for (unsigned i = 0; i < NewBlocks.size(); i++)
1080            Visited.erase(NewBlocks[i]);
1081          goto PredTranslationFailure;
1082        }
1083      }
1084      Worklist.append(NewBlocks.begin(), NewBlocks.end());
1085      continue;
1086    }
1087
1088    // We do need to do phi translation, if we know ahead of time we can't phi
1089    // translate this value, don't even try.
1090    if (!Pointer.IsPotentiallyPHITranslatable())
1091      goto PredTranslationFailure;
1092
1093    // We may have added values to the cache list before this PHI translation.
1094    // If so, we haven't done anything to ensure that the cache remains sorted.
1095    // Sort it now (if needed) so that recursive invocations of
1096    // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1097    // value will only see properly sorted cache arrays.
1098    if (Cache && NumSortedEntries != Cache->size()) {
1099      SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1100      NumSortedEntries = Cache->size();
1101    }
1102    Cache = 0;
1103
1104    PredList.clear();
1105    for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
1106      BasicBlock *Pred = *PI;
1107      PredList.push_back(std::make_pair(Pred, Pointer));
1108
1109      // Get the PHI translated pointer in this predecessor.  This can fail if
1110      // not translatable, in which case the getAddr() returns null.
1111      PHITransAddr &PredPointer = PredList.back().second;
1112      PredPointer.PHITranslateValue(BB, Pred, 0);
1113
1114      Value *PredPtrVal = PredPointer.getAddr();
1115
1116      // Check to see if we have already visited this pred block with another
1117      // pointer.  If so, we can't do this lookup.  This failure can occur
1118      // with PHI translation when a critical edge exists and the PHI node in
1119      // the successor translates to a pointer value different than the
1120      // pointer the block was first analyzed with.
1121      std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
1122        InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
1123
1124      if (!InsertRes.second) {
1125        // We found the pred; take it off the list of preds to visit.
1126        PredList.pop_back();
1127
1128        // If the predecessor was visited with PredPtr, then we already did
1129        // the analysis and can ignore it.
1130        if (InsertRes.first->second == PredPtrVal)
1131          continue;
1132
1133        // Otherwise, the block was previously analyzed with a different
1134        // pointer.  We can't represent the result of this case, so we just
1135        // treat this as a phi translation failure.
1136
1137        // Make sure to clean up the Visited map before continuing on to
1138        // PredTranslationFailure.
1139        for (unsigned i = 0, n = PredList.size(); i < n; ++i)
1140          Visited.erase(PredList[i].first);
1141
1142        goto PredTranslationFailure;
1143      }
1144    }
1145
1146    // Actually process results here; this need to be a separate loop to avoid
1147    // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1148    // any results for.  (getNonLocalPointerDepFromBB will modify our
1149    // datastructures in ways the code after the PredTranslationFailure label
1150    // doesn't expect.)
1151    for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
1152      BasicBlock *Pred = PredList[i].first;
1153      PHITransAddr &PredPointer = PredList[i].second;
1154      Value *PredPtrVal = PredPointer.getAddr();
1155
1156      bool CanTranslate = true;
1157      // If PHI translation was unable to find an available pointer in this
1158      // predecessor, then we have to assume that the pointer is clobbered in
1159      // that predecessor.  We can still do PRE of the load, which would insert
1160      // a computation of the pointer in this predecessor.
1161      if (PredPtrVal == 0)
1162        CanTranslate = false;
1163
1164      // FIXME: it is entirely possible that PHI translating will end up with
1165      // the same value.  Consider PHI translating something like:
1166      // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
1167      // to recurse here, pedantically speaking.
1168
1169      // If getNonLocalPointerDepFromBB fails here, that means the cached
1170      // result conflicted with the Visited list; we have to conservatively
1171      // assume it is unknown, but this also does not block PRE of the load.
1172      if (!CanTranslate ||
1173          getNonLocalPointerDepFromBB(PredPointer,
1174                                      Loc.getWithNewPtr(PredPtrVal),
1175                                      isLoad, Pred,
1176                                      Result, Visited)) {
1177        // Add the entry to the Result list.
1178        NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
1179        Result.push_back(Entry);
1180
1181        // Since we had a phi translation failure, the cache for CacheKey won't
1182        // include all of the entries that we need to immediately satisfy future
1183        // queries.  Mark this in NonLocalPointerDeps by setting the
1184        // BBSkipFirstBlockPair pointer to null.  This requires reuse of the
1185        // cached value to do more work but not miss the phi trans failure.
1186        NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1187        NLPI.Pair = BBSkipFirstBlockPair();
1188        continue;
1189      }
1190    }
1191
1192    // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1193    CacheInfo = &NonLocalPointerDeps[CacheKey];
1194    Cache = &CacheInfo->NonLocalDeps;
1195    NumSortedEntries = Cache->size();
1196
1197    // Since we did phi translation, the "Cache" set won't contain all of the
1198    // results for the query.  This is ok (we can still use it to accelerate
1199    // specific block queries) but we can't do the fastpath "return all
1200    // results from the set"  Clear out the indicator for this.
1201    CacheInfo->Pair = BBSkipFirstBlockPair();
1202    SkipFirstBlock = false;
1203    continue;
1204
1205  PredTranslationFailure:
1206    // The following code is "failure"; we can't produce a sane translation
1207    // for the given block.  It assumes that we haven't modified any of
1208    // our datastructures while processing the current block.
1209
1210    if (Cache == 0) {
1211      // Refresh the CacheInfo/Cache pointer if it got invalidated.
1212      CacheInfo = &NonLocalPointerDeps[CacheKey];
1213      Cache = &CacheInfo->NonLocalDeps;
1214      NumSortedEntries = Cache->size();
1215    }
1216
1217    // Since we failed phi translation, the "Cache" set won't contain all of the
1218    // results for the query.  This is ok (we can still use it to accelerate
1219    // specific block queries) but we can't do the fastpath "return all
1220    // results from the set".  Clear out the indicator for this.
1221    CacheInfo->Pair = BBSkipFirstBlockPair();
1222
1223    // If *nothing* works, mark the pointer as unknown.
1224    //
1225    // If this is the magic first block, return this as a clobber of the whole
1226    // incoming value.  Since we can't phi translate to one of the predecessors,
1227    // we have to bail out.
1228    if (SkipFirstBlock)
1229      return true;
1230
1231    for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
1232      assert(I != Cache->rend() && "Didn't find current block??");
1233      if (I->getBB() != BB)
1234        continue;
1235
1236      assert(I->getResult().isNonLocal() &&
1237             "Should only be here with transparent block");
1238      I->setResult(MemDepResult::getUnknown());
1239      Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
1240                                         Pointer.getAddr()));
1241      break;
1242    }
1243  }
1244
1245  // Okay, we're done now.  If we added new values to the cache, re-sort it.
1246  SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1247  DEBUG(AssertSorted(*Cache));
1248  return false;
1249}
1250
1251/// RemoveCachedNonLocalPointerDependencies - If P exists in
1252/// CachedNonLocalPointerInfo, remove it.
1253void MemoryDependenceAnalysis::
1254RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
1255  CachedNonLocalPointerInfo::iterator It =
1256    NonLocalPointerDeps.find(P);
1257  if (It == NonLocalPointerDeps.end()) return;
1258
1259  // Remove all of the entries in the BB->val map.  This involves removing
1260  // instructions from the reverse map.
1261  NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1262
1263  for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1264    Instruction *Target = PInfo[i].getResult().getInst();
1265    if (Target == 0) continue;  // Ignore non-local dep results.
1266    assert(Target->getParent() == PInfo[i].getBB());
1267
1268    // Eliminating the dirty entry from 'Cache', so update the reverse info.
1269    RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1270  }
1271
1272  // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1273  NonLocalPointerDeps.erase(It);
1274}
1275
1276
1277/// invalidateCachedPointerInfo - This method is used to invalidate cached
1278/// information about the specified pointer, because it may be too
1279/// conservative in memdep.  This is an optional call that can be used when
1280/// the client detects an equivalence between the pointer and some other
1281/// value and replaces the other value with ptr. This can make Ptr available
1282/// in more places that cached info does not necessarily keep.
1283void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
1284  // If Ptr isn't really a pointer, just ignore it.
1285  if (!Ptr->getType()->isPointerTy()) return;
1286  // Flush store info for the pointer.
1287  RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1288  // Flush load info for the pointer.
1289  RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1290}
1291
1292/// invalidateCachedPredecessors - Clear the PredIteratorCache info.
1293/// This needs to be done when the CFG changes, e.g., due to splitting
1294/// critical edges.
1295void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
1296  PredCache->clear();
1297}
1298
1299/// removeInstruction - Remove an instruction from the dependence analysis,
1300/// updating the dependence of instructions that previously depended on it.
1301/// This method attempts to keep the cache coherent using the reverse map.
1302void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
1303  // Walk through the Non-local dependencies, removing this one as the value
1304  // for any cached queries.
1305  NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1306  if (NLDI != NonLocalDeps.end()) {
1307    NonLocalDepInfo &BlockMap = NLDI->second.first;
1308    for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
1309         DI != DE; ++DI)
1310      if (Instruction *Inst = DI->getResult().getInst())
1311        RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1312    NonLocalDeps.erase(NLDI);
1313  }
1314
1315  // If we have a cached local dependence query for this instruction, remove it.
1316  //
1317  LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1318  if (LocalDepEntry != LocalDeps.end()) {
1319    // Remove us from DepInst's reverse set now that the local dep info is gone.
1320    if (Instruction *Inst = LocalDepEntry->second.getInst())
1321      RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1322
1323    // Remove this local dependency info.
1324    LocalDeps.erase(LocalDepEntry);
1325  }
1326
1327  // If we have any cached pointer dependencies on this instruction, remove
1328  // them.  If the instruction has non-pointer type, then it can't be a pointer
1329  // base.
1330
1331  // Remove it from both the load info and the store info.  The instruction
1332  // can't be in either of these maps if it is non-pointer.
1333  if (RemInst->getType()->isPointerTy()) {
1334    RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1335    RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1336  }
1337
1338  // Loop over all of the things that depend on the instruction we're removing.
1339  //
1340  SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
1341
1342  // If we find RemInst as a clobber or Def in any of the maps for other values,
1343  // we need to replace its entry with a dirty version of the instruction after
1344  // it.  If RemInst is a terminator, we use a null dirty value.
1345  //
1346  // Using a dirty version of the instruction after RemInst saves having to scan
1347  // the entire block to get to this point.
1348  MemDepResult NewDirtyVal;
1349  if (!RemInst->isTerminator())
1350    NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
1351
1352  ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1353  if (ReverseDepIt != ReverseLocalDeps.end()) {
1354    SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
1355    // RemInst can't be the terminator if it has local stuff depending on it.
1356    assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
1357           "Nothing can locally depend on a terminator");
1358
1359    for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
1360         E = ReverseDeps.end(); I != E; ++I) {
1361      Instruction *InstDependingOnRemInst = *I;
1362      assert(InstDependingOnRemInst != RemInst &&
1363             "Already removed our local dep info");
1364
1365      LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1366
1367      // Make sure to remember that new things depend on NewDepInst.
1368      assert(NewDirtyVal.getInst() && "There is no way something else can have "
1369             "a local dep on this if it is a terminator!");
1370      ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
1371                                                InstDependingOnRemInst));
1372    }
1373
1374    ReverseLocalDeps.erase(ReverseDepIt);
1375
1376    // Add new reverse deps after scanning the set, to avoid invalidating the
1377    // 'ReverseDeps' reference.
1378    while (!ReverseDepsToAdd.empty()) {
1379      ReverseLocalDeps[ReverseDepsToAdd.back().first]
1380        .insert(ReverseDepsToAdd.back().second);
1381      ReverseDepsToAdd.pop_back();
1382    }
1383  }
1384
1385  ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1386  if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1387    SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
1388    for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
1389         I != E; ++I) {
1390      assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
1391
1392      PerInstNLInfo &INLD = NonLocalDeps[*I];
1393      // The information is now dirty!
1394      INLD.second = true;
1395
1396      for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
1397           DE = INLD.first.end(); DI != DE; ++DI) {
1398        if (DI->getResult().getInst() != RemInst) continue;
1399
1400        // Convert to a dirty entry for the subsequent instruction.
1401        DI->setResult(NewDirtyVal);
1402
1403        if (Instruction *NextI = NewDirtyVal.getInst())
1404          ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
1405      }
1406    }
1407
1408    ReverseNonLocalDeps.erase(ReverseDepIt);
1409
1410    // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1411    while (!ReverseDepsToAdd.empty()) {
1412      ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
1413        .insert(ReverseDepsToAdd.back().second);
1414      ReverseDepsToAdd.pop_back();
1415    }
1416  }
1417
1418  // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1419  // value in the NonLocalPointerDeps info.
1420  ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1421    ReverseNonLocalPtrDeps.find(RemInst);
1422  if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1423    SmallPtrSet<ValueIsLoadPair, 4> &Set = ReversePtrDepIt->second;
1424    SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
1425
1426    for (SmallPtrSet<ValueIsLoadPair, 4>::iterator I = Set.begin(),
1427         E = Set.end(); I != E; ++I) {
1428      ValueIsLoadPair P = *I;
1429      assert(P.getPointer() != RemInst &&
1430             "Already removed NonLocalPointerDeps info for RemInst");
1431
1432      NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1433
1434      // The cache is not valid for any specific block anymore.
1435      NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1436
1437      // Update any entries for RemInst to use the instruction after it.
1438      for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
1439           DI != DE; ++DI) {
1440        if (DI->getResult().getInst() != RemInst) continue;
1441
1442        // Convert to a dirty entry for the subsequent instruction.
1443        DI->setResult(NewDirtyVal);
1444
1445        if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1446          ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1447      }
1448
1449      // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
1450      // subsequent value may invalidate the sortedness.
1451      std::sort(NLPDI.begin(), NLPDI.end());
1452    }
1453
1454    ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1455
1456    while (!ReversePtrDepsToAdd.empty()) {
1457      ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
1458        .insert(ReversePtrDepsToAdd.back().second);
1459      ReversePtrDepsToAdd.pop_back();
1460    }
1461  }
1462
1463
1464  assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1465  AA->deleteValue(RemInst);
1466  DEBUG(verifyRemoved(RemInst));
1467}
1468/// verifyRemoved - Verify that the specified instruction does not occur
1469/// in our internal data structures.
1470void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
1471  for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
1472       E = LocalDeps.end(); I != E; ++I) {
1473    assert(I->first != D && "Inst occurs in data structures");
1474    assert(I->second.getInst() != D &&
1475           "Inst occurs in data structures");
1476  }
1477
1478  for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
1479       E = NonLocalPointerDeps.end(); I != E; ++I) {
1480    assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
1481    const NonLocalDepInfo &Val = I->second.NonLocalDeps;
1482    for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
1483         II != E; ++II)
1484      assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
1485  }
1486
1487  for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
1488       E = NonLocalDeps.end(); I != E; ++I) {
1489    assert(I->first != D && "Inst occurs in data structures");
1490    const PerInstNLInfo &INLD = I->second;
1491    for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
1492         EE = INLD.first.end(); II  != EE; ++II)
1493      assert(II->getResult().getInst() != D && "Inst occurs in data structures");
1494  }
1495
1496  for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
1497       E = ReverseLocalDeps.end(); I != E; ++I) {
1498    assert(I->first != D && "Inst occurs in data structures");
1499    for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1500         EE = I->second.end(); II != EE; ++II)
1501      assert(*II != D && "Inst occurs in data structures");
1502  }
1503
1504  for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
1505       E = ReverseNonLocalDeps.end();
1506       I != E; ++I) {
1507    assert(I->first != D && "Inst occurs in data structures");
1508    for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1509         EE = I->second.end(); II != EE; ++II)
1510      assert(*II != D && "Inst occurs in data structures");
1511  }
1512
1513  for (ReverseNonLocalPtrDepTy::const_iterator
1514       I = ReverseNonLocalPtrDeps.begin(),
1515       E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
1516    assert(I->first != D && "Inst occurs in rev NLPD map");
1517
1518    for (SmallPtrSet<ValueIsLoadPair, 4>::const_iterator II = I->second.begin(),
1519         E = I->second.end(); II != E; ++II)
1520      assert(*II != ValueIsLoadPair(D, false) &&
1521             *II != ValueIsLoadPair(D, true) &&
1522             "Inst occurs in ReverseNonLocalPtrDeps map");
1523  }
1524
1525}
1526