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