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