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