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