LLVM API Documentation

MemoryDependenceAnalysis.cpp
Go to the documentation of this file.
00001 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements an analysis that determines, for a given memory
00011 // operation, what preceding memory operations it depends on.  It builds on
00012 // alias analysis information, and tries to provide a lazy, caching interface to
00013 // a common kind of alias information query.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/Analysis/InstructionSimplify.h"
00022 #include "llvm/Analysis/MemoryBuiltins.h"
00023 #include "llvm/Analysis/PHITransAddr.h"
00024 #include "llvm/Analysis/ValueTracking.h"
00025 #include "llvm/IR/DataLayout.h"
00026 #include "llvm/IR/Dominators.h"
00027 #include "llvm/IR/Function.h"
00028 #include "llvm/IR/Instructions.h"
00029 #include "llvm/IR/IntrinsicInst.h"
00030 #include "llvm/IR/LLVMContext.h"
00031 #include "llvm/IR/PredIteratorCache.h"
00032 #include "llvm/Support/Debug.h"
00033 using namespace llvm;
00034 
00035 #define DEBUG_TYPE "memdep"
00036 
00037 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
00038 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
00039 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
00040 
00041 STATISTIC(NumCacheNonLocalPtr,
00042           "Number of fully cached non-local ptr responses");
00043 STATISTIC(NumCacheDirtyNonLocalPtr,
00044           "Number of cached, but dirty, non-local ptr responses");
00045 STATISTIC(NumUncacheNonLocalPtr,
00046           "Number of uncached non-local ptr responses");
00047 STATISTIC(NumCacheCompleteNonLocalPtr,
00048           "Number of block queries that were completely cached");
00049 
00050 // Limit for the number of instructions to scan in a block.
00051 static const int BlockScanLimit = 100;
00052 
00053 char MemoryDependenceAnalysis::ID = 0;
00054 
00055 // Register this pass...
00056 INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep",
00057                 "Memory Dependence Analysis", false, true)
00058 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00059 INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep",
00060                       "Memory Dependence Analysis", false, true)
00061 
00062 MemoryDependenceAnalysis::MemoryDependenceAnalysis()
00063     : FunctionPass(ID), PredCache() {
00064   initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry());
00065 }
00066 MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
00067 }
00068 
00069 /// Clean up memory in between runs
00070 void MemoryDependenceAnalysis::releaseMemory() {
00071   LocalDeps.clear();
00072   NonLocalDeps.clear();
00073   NonLocalPointerDeps.clear();
00074   ReverseLocalDeps.clear();
00075   ReverseNonLocalDeps.clear();
00076   ReverseNonLocalPtrDeps.clear();
00077   PredCache->clear();
00078 }
00079 
00080 
00081 
00082 /// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
00083 ///
00084 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
00085   AU.setPreservesAll();
00086   AU.addRequiredTransitive<AliasAnalysis>();
00087 }
00088 
00089 bool MemoryDependenceAnalysis::runOnFunction(Function &) {
00090   AA = &getAnalysis<AliasAnalysis>();
00091   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00092   DL = DLP ? &DLP->getDataLayout() : nullptr;
00093   DominatorTreeWrapperPass *DTWP =
00094       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00095   DT = DTWP ? &DTWP->getDomTree() : nullptr;
00096   if (!PredCache)
00097     PredCache.reset(new PredIteratorCache());
00098   return false;
00099 }
00100 
00101 /// RemoveFromReverseMap - This is a helper function that removes Val from
00102 /// 'Inst's set in ReverseMap.  If the set becomes empty, remove Inst's entry.
00103 template <typename KeyTy>
00104 static void RemoveFromReverseMap(DenseMap<Instruction*,
00105                                  SmallPtrSet<KeyTy, 4> > &ReverseMap,
00106                                  Instruction *Inst, KeyTy Val) {
00107   typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator
00108   InstIt = ReverseMap.find(Inst);
00109   assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
00110   bool Found = InstIt->second.erase(Val);
00111   assert(Found && "Invalid reverse map!"); (void)Found;
00112   if (InstIt->second.empty())
00113     ReverseMap.erase(InstIt);
00114 }
00115 
00116 /// GetLocation - If the given instruction references a specific memory
00117 /// location, fill in Loc with the details, otherwise set Loc.Ptr to null.
00118 /// Return a ModRefInfo value describing the general behavior of the
00119 /// instruction.
00120 static
00121 AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst,
00122                                         AliasAnalysis::Location &Loc,
00123                                         AliasAnalysis *AA) {
00124   if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
00125     if (LI->isUnordered()) {
00126       Loc = AA->getLocation(LI);
00127       return AliasAnalysis::Ref;
00128     }
00129     if (LI->getOrdering() == Monotonic) {
00130       Loc = AA->getLocation(LI);
00131       return AliasAnalysis::ModRef;
00132     }
00133     Loc = AliasAnalysis::Location();
00134     return AliasAnalysis::ModRef;
00135   }
00136 
00137   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00138     if (SI->isUnordered()) {
00139       Loc = AA->getLocation(SI);
00140       return AliasAnalysis::Mod;
00141     }
00142     if (SI->getOrdering() == Monotonic) {
00143       Loc = AA->getLocation(SI);
00144       return AliasAnalysis::ModRef;
00145     }
00146     Loc = AliasAnalysis::Location();
00147     return AliasAnalysis::ModRef;
00148   }
00149 
00150   if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
00151     Loc = AA->getLocation(V);
00152     return AliasAnalysis::ModRef;
00153   }
00154 
00155   if (const CallInst *CI = isFreeCall(Inst, AA->getTargetLibraryInfo())) {
00156     // calls to free() deallocate the entire structure
00157     Loc = AliasAnalysis::Location(CI->getArgOperand(0));
00158     return AliasAnalysis::Mod;
00159   }
00160 
00161   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
00162     AAMDNodes AAInfo;
00163 
00164     switch (II->getIntrinsicID()) {
00165     case Intrinsic::lifetime_start:
00166     case Intrinsic::lifetime_end:
00167     case Intrinsic::invariant_start:
00168       II->getAAMetadata(AAInfo);
00169       Loc = AliasAnalysis::Location(II->getArgOperand(1),
00170                                     cast<ConstantInt>(II->getArgOperand(0))
00171                                       ->getZExtValue(), AAInfo);
00172       // These intrinsics don't really modify the memory, but returning Mod
00173       // will allow them to be handled conservatively.
00174       return AliasAnalysis::Mod;
00175     case Intrinsic::invariant_end:
00176       II->getAAMetadata(AAInfo);
00177       Loc = AliasAnalysis::Location(II->getArgOperand(2),
00178                                     cast<ConstantInt>(II->getArgOperand(1))
00179                                       ->getZExtValue(), AAInfo);
00180       // These intrinsics don't really modify the memory, but returning Mod
00181       // will allow them to be handled conservatively.
00182       return AliasAnalysis::Mod;
00183     default:
00184       break;
00185     }
00186   }
00187 
00188   // Otherwise, just do the coarse-grained thing that always works.
00189   if (Inst->mayWriteToMemory())
00190     return AliasAnalysis::ModRef;
00191   if (Inst->mayReadFromMemory())
00192     return AliasAnalysis::Ref;
00193   return AliasAnalysis::NoModRef;
00194 }
00195 
00196 /// getCallSiteDependencyFrom - Private helper for finding the local
00197 /// dependencies of a call site.
00198 MemDepResult MemoryDependenceAnalysis::
00199 getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
00200                           BasicBlock::iterator ScanIt, BasicBlock *BB) {
00201   unsigned Limit = BlockScanLimit;
00202 
00203   // Walk backwards through the block, looking for dependencies
00204   while (ScanIt != BB->begin()) {
00205     // Limit the amount of scanning we do so we don't end up with quadratic
00206     // running time on extreme testcases.
00207     --Limit;
00208     if (!Limit)
00209       return MemDepResult::getUnknown();
00210 
00211     Instruction *Inst = --ScanIt;
00212 
00213     // If this inst is a memory op, get the pointer it accessed
00214     AliasAnalysis::Location Loc;
00215     AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA);
00216     if (Loc.Ptr) {
00217       // A simple instruction.
00218       if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef)
00219         return MemDepResult::getClobber(Inst);
00220       continue;
00221     }
00222 
00223     if (CallSite InstCS = cast<Value>(Inst)) {
00224       // Debug intrinsics don't cause dependences.
00225       if (isa<DbgInfoIntrinsic>(Inst)) continue;
00226       // If these two calls do not interfere, look past it.
00227       switch (AA->getModRefInfo(CS, InstCS)) {
00228       case AliasAnalysis::NoModRef:
00229         // If the two calls are the same, return InstCS as a Def, so that
00230         // CS can be found redundant and eliminated.
00231         if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) &&
00232             CS.getInstruction()->isIdenticalToWhenDefined(Inst))
00233           return MemDepResult::getDef(Inst);
00234 
00235         // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
00236         // keep scanning.
00237         continue;
00238       default:
00239         return MemDepResult::getClobber(Inst);
00240       }
00241     }
00242 
00243     // If we could not obtain a pointer for the instruction and the instruction
00244     // touches memory then assume that this is a dependency.
00245     if (MR != AliasAnalysis::NoModRef)
00246       return MemDepResult::getClobber(Inst);
00247   }
00248 
00249   // No dependence found.  If this is the entry block of the function, it is
00250   // unknown, otherwise it is non-local.
00251   if (BB != &BB->getParent()->getEntryBlock())
00252     return MemDepResult::getNonLocal();
00253   return MemDepResult::getNonFuncLocal();
00254 }
00255 
00256 /// isLoadLoadClobberIfExtendedToFullWidth - Return true if LI is a load that
00257 /// would fully overlap MemLoc if done as a wider legal integer load.
00258 ///
00259 /// MemLocBase, MemLocOffset are lazily computed here the first time the
00260 /// base/offs of memloc is needed.
00261 static bool
00262 isLoadLoadClobberIfExtendedToFullWidth(const AliasAnalysis::Location &MemLoc,
00263                                        const Value *&MemLocBase,
00264                                        int64_t &MemLocOffs,
00265                                        const LoadInst *LI,
00266                                        const DataLayout *DL) {
00267   // If we have no target data, we can't do this.
00268   if (!DL) return false;
00269 
00270   // If we haven't already computed the base/offset of MemLoc, do so now.
00271   if (!MemLocBase)
00272     MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, DL);
00273 
00274   unsigned Size = MemoryDependenceAnalysis::
00275     getLoadLoadClobberFullWidthSize(MemLocBase, MemLocOffs, MemLoc.Size,
00276                                     LI, *DL);
00277   return Size != 0;
00278 }
00279 
00280 /// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
00281 /// looks at a memory location for a load (specified by MemLocBase, Offs,
00282 /// and Size) and compares it against a load.  If the specified load could
00283 /// be safely widened to a larger integer load that is 1) still efficient,
00284 /// 2) safe for the target, and 3) would provide the specified memory
00285 /// location value, then this function returns the size in bytes of the
00286 /// load width to use.  If not, this returns zero.
00287 unsigned MemoryDependenceAnalysis::
00288 getLoadLoadClobberFullWidthSize(const Value *MemLocBase, int64_t MemLocOffs,
00289                                 unsigned MemLocSize, const LoadInst *LI,
00290                                 const DataLayout &DL) {
00291   // We can only extend simple integer loads.
00292   if (!isa<IntegerType>(LI->getType()) || !LI->isSimple()) return 0;
00293 
00294   // Load widening is hostile to ThreadSanitizer: it may cause false positives
00295   // or make the reports more cryptic (access sizes are wrong).
00296   if (LI->getParent()->getParent()->getAttributes().
00297       hasAttribute(AttributeSet::FunctionIndex, Attribute::SanitizeThread))
00298     return 0;
00299 
00300   // Get the base of this load.
00301   int64_t LIOffs = 0;
00302   const Value *LIBase =
00303     GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, &DL);
00304 
00305   // If the two pointers are not based on the same pointer, we can't tell that
00306   // they are related.
00307   if (LIBase != MemLocBase) return 0;
00308 
00309   // Okay, the two values are based on the same pointer, but returned as
00310   // no-alias.  This happens when we have things like two byte loads at "P+1"
00311   // and "P+3".  Check to see if increasing the size of the "LI" load up to its
00312   // alignment (or the largest native integer type) will allow us to load all
00313   // the bits required by MemLoc.
00314 
00315   // If MemLoc is before LI, then no widening of LI will help us out.
00316   if (MemLocOffs < LIOffs) return 0;
00317 
00318   // Get the alignment of the load in bytes.  We assume that it is safe to load
00319   // any legal integer up to this size without a problem.  For example, if we're
00320   // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
00321   // widen it up to an i32 load.  If it is known 2-byte aligned, we can widen it
00322   // to i16.
00323   unsigned LoadAlign = LI->getAlignment();
00324 
00325   int64_t MemLocEnd = MemLocOffs+MemLocSize;
00326 
00327   // If no amount of rounding up will let MemLoc fit into LI, then bail out.
00328   if (LIOffs+LoadAlign < MemLocEnd) return 0;
00329 
00330   // This is the size of the load to try.  Start with the next larger power of
00331   // two.
00332   unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits()/8U;
00333   NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
00334 
00335   while (1) {
00336     // If this load size is bigger than our known alignment or would not fit
00337     // into a native integer register, then we fail.
00338     if (NewLoadByteSize > LoadAlign ||
00339         !DL.fitsInLegalInteger(NewLoadByteSize*8))
00340       return 0;
00341 
00342     if (LIOffs+NewLoadByteSize > MemLocEnd &&
00343         LI->getParent()->getParent()->getAttributes().
00344           hasAttribute(AttributeSet::FunctionIndex, Attribute::SanitizeAddress))
00345       // We will be reading past the location accessed by the original program.
00346       // While this is safe in a regular build, Address Safety analysis tools
00347       // may start reporting false warnings. So, don't do widening.
00348       return 0;
00349 
00350     // If a load of this width would include all of MemLoc, then we succeed.
00351     if (LIOffs+NewLoadByteSize >= MemLocEnd)
00352       return NewLoadByteSize;
00353 
00354     NewLoadByteSize <<= 1;
00355   }
00356 }
00357 
00358 /// getPointerDependencyFrom - Return the instruction on which a memory
00359 /// location depends.  If isLoad is true, this routine ignores may-aliases with
00360 /// read-only operations.  If isLoad is false, this routine ignores may-aliases
00361 /// with reads from read-only locations.  If possible, pass the query
00362 /// instruction as well; this function may take advantage of the metadata
00363 /// annotated to the query instruction to refine the result.
00364 MemDepResult MemoryDependenceAnalysis::
00365 getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad,
00366                          BasicBlock::iterator ScanIt, BasicBlock *BB,
00367                          Instruction *QueryInst) {
00368 
00369   const Value *MemLocBase = nullptr;
00370   int64_t MemLocOffset = 0;
00371   unsigned Limit = BlockScanLimit;
00372   bool isInvariantLoad = false;
00373 
00374   // We must be careful with atomic accesses, as they may allow another thread
00375   //   to touch this location, cloberring it. We are conservative: if the
00376   //   QueryInst is not a simple (non-atomic) memory access, we automatically
00377   //   return getClobber.
00378   // If it is simple, we know based on the results of
00379   // "Compiler testing via a theory of sound optimisations in the C11/C++11
00380   //   memory model" in PLDI 2013, that a non-atomic location can only be
00381   //   clobbered between a pair of a release and an acquire action, with no
00382   //   access to the location in between.
00383   // Here is an example for giving the general intuition behind this rule.
00384   // In the following code:
00385   //   store x 0;
00386   //   release action; [1]
00387   //   acquire action; [4]
00388   //   %val = load x;
00389   // It is unsafe to replace %val by 0 because another thread may be running:
00390   //   acquire action; [2]
00391   //   store x 42;
00392   //   release action; [3]
00393   // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
00394   // being 42. A key property of this program however is that if either
00395   // 1 or 4 were missing, there would be a race between the store of 42
00396   // either the store of 0 or the load (making the whole progam racy).
00397   // The paper mentionned above shows that the same property is respected
00398   // by every program that can detect any optimisation of that kind: either
00399   // it is racy (undefined) or there is a release followed by an acquire
00400   // between the pair of accesses under consideration.
00401   bool HasSeenAcquire = false;
00402 
00403   if (isLoad && QueryInst) {
00404     LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
00405     if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr)
00406       isInvariantLoad = true;
00407   }
00408 
00409   // Walk backwards through the basic block, looking for dependencies.
00410   while (ScanIt != BB->begin()) {
00411     Instruction *Inst = --ScanIt;
00412 
00413     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
00414       // Debug intrinsics don't (and can't) cause dependencies.
00415       if (isa<DbgInfoIntrinsic>(II)) continue;
00416 
00417     // Limit the amount of scanning we do so we don't end up with quadratic
00418     // running time on extreme testcases.
00419     --Limit;
00420     if (!Limit)
00421       return MemDepResult::getUnknown();
00422 
00423     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
00424       // If we reach a lifetime begin or end marker, then the query ends here
00425       // because the value is undefined.
00426       if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
00427         // FIXME: This only considers queries directly on the invariant-tagged
00428         // pointer, not on query pointers that are indexed off of them.  It'd
00429         // be nice to handle that at some point (the right approach is to use
00430         // GetPointerBaseWithConstantOffset).
00431         if (AA->isMustAlias(AliasAnalysis::Location(II->getArgOperand(1)),
00432                             MemLoc))
00433           return MemDepResult::getDef(II);
00434         continue;
00435       }
00436     }
00437 
00438     // Values depend on loads if the pointers are must aliased.  This means that
00439     // a load depends on another must aliased load from the same value.
00440     // One exception is atomic loads: a value can depend on an atomic load that it
00441     // does not alias with when this atomic load indicates that another thread may
00442     // be accessing the location.
00443     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
00444       // Atomic loads have complications involved.
00445       // A Monotonic (or higher) load is OK if the query inst is itself not atomic.
00446       // An Acquire (or higher) load sets the HasSeenAcquire flag, so that any
00447       //   release store will know to return getClobber.
00448       // FIXME: This is overly conservative.
00449       if (!LI->isUnordered()) {
00450         if (!QueryInst)
00451           return MemDepResult::getClobber(LI);
00452         if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst))
00453           if (!QueryLI->isSimple())
00454             return MemDepResult::getClobber(LI);
00455         if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst))
00456           if (!QuerySI->isSimple())
00457             return MemDepResult::getClobber(LI);
00458         if (isAtLeastAcquire(LI->getOrdering()))
00459           HasSeenAcquire = true;
00460       }
00461 
00462       // FIXME: this is overly conservative.
00463       // While volatile access cannot be eliminated, they do not have to clobber
00464       // non-aliasing locations, as normal accesses can for example be reordered
00465       // with volatile accesses.
00466       if (LI->isVolatile())
00467         return MemDepResult::getClobber(LI);
00468 
00469       AliasAnalysis::Location LoadLoc = AA->getLocation(LI);
00470 
00471       // If we found a pointer, check if it could be the same as our pointer.
00472       AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc);
00473 
00474       if (isLoad) {
00475         if (R == AliasAnalysis::NoAlias) {
00476           // If this is an over-aligned integer load (for example,
00477           // "load i8* %P, align 4") see if it would obviously overlap with the
00478           // queried location if widened to a larger load (e.g. if the queried
00479           // location is 1 byte at P+1).  If so, return it as a load/load
00480           // clobber result, allowing the client to decide to widen the load if
00481           // it wants to.
00482           if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType()))
00483             if (LI->getAlignment()*8 > ITy->getPrimitiveSizeInBits() &&
00484                 isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase,
00485                                                        MemLocOffset, LI, DL))
00486               return MemDepResult::getClobber(Inst);
00487 
00488           continue;
00489         }
00490 
00491         // Must aliased loads are defs of each other.
00492         if (R == AliasAnalysis::MustAlias)
00493           return MemDepResult::getDef(Inst);
00494 
00495 #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
00496       // in terms of clobbering loads, but since it does this by looking
00497       // at the clobbering load directly, it doesn't know about any
00498       // phi translation that may have happened along the way.
00499 
00500         // If we have a partial alias, then return this as a clobber for the
00501         // client to handle.
00502         if (R == AliasAnalysis::PartialAlias)
00503           return MemDepResult::getClobber(Inst);
00504 #endif
00505 
00506         // Random may-alias loads don't depend on each other without a
00507         // dependence.
00508         continue;
00509       }
00510 
00511       // Stores don't depend on other no-aliased accesses.
00512       if (R == AliasAnalysis::NoAlias)
00513         continue;
00514 
00515       // Stores don't alias loads from read-only memory.
00516       if (AA->pointsToConstantMemory(LoadLoc))
00517         continue;
00518 
00519       // Stores depend on may/must aliased loads.
00520       return MemDepResult::getDef(Inst);
00521     }
00522 
00523     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00524       // Atomic stores have complications involved.
00525       // A Monotonic store is OK if the query inst is itself not atomic.
00526       // A Release (or higher) store further requires that no acquire load
00527       //   has been seen.
00528       // FIXME: This is overly conservative.
00529       if (!SI->isUnordered()) {
00530         if (!QueryInst)
00531           return MemDepResult::getClobber(SI);
00532         if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst))
00533           if (!QueryLI->isSimple())
00534             return MemDepResult::getClobber(SI);
00535         if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst))
00536           if (!QuerySI->isSimple())
00537             return MemDepResult::getClobber(SI);
00538         if (HasSeenAcquire && isAtLeastRelease(SI->getOrdering()))
00539           return MemDepResult::getClobber(SI);
00540       }
00541 
00542       // FIXME: this is overly conservative.
00543       // While volatile access cannot be eliminated, they do not have to clobber
00544       // non-aliasing locations, as normal accesses can for example be reordered
00545       // with volatile accesses.
00546       if (SI->isVolatile())
00547         return MemDepResult::getClobber(SI);
00548 
00549       // If alias analysis can tell that this store is guaranteed to not modify
00550       // the query pointer, ignore it.  Use getModRefInfo to handle cases where
00551       // the query pointer points to constant memory etc.
00552       if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
00553         continue;
00554 
00555       // Ok, this store might clobber the query pointer.  Check to see if it is
00556       // a must alias: in this case, we want to return this as a def.
00557       AliasAnalysis::Location StoreLoc = AA->getLocation(SI);
00558 
00559       // If we found a pointer, check if it could be the same as our pointer.
00560       AliasAnalysis::AliasResult R = AA->alias(StoreLoc, MemLoc);
00561 
00562       if (R == AliasAnalysis::NoAlias)
00563         continue;
00564       if (R == AliasAnalysis::MustAlias)
00565         return MemDepResult::getDef(Inst);
00566       if (isInvariantLoad)
00567        continue;
00568       return MemDepResult::getClobber(Inst);
00569     }
00570 
00571     // If this is an allocation, and if we know that the accessed pointer is to
00572     // the allocation, return Def.  This means that there is no dependence and
00573     // the access can be optimized based on that.  For example, a load could
00574     // turn into undef.
00575     // Note: Only determine this to be a malloc if Inst is the malloc call, not
00576     // a subsequent bitcast of the malloc call result.  There can be stores to
00577     // the malloced memory between the malloc call and its bitcast uses, and we
00578     // need to continue scanning until the malloc call.
00579     const TargetLibraryInfo *TLI = AA->getTargetLibraryInfo();
00580     if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, TLI)) {
00581       const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL);
00582 
00583       if (AccessPtr == Inst || AA->isMustAlias(Inst, AccessPtr))
00584         return MemDepResult::getDef(Inst);
00585       // Be conservative if the accessed pointer may alias the allocation.
00586       if (AA->alias(Inst, AccessPtr) != AliasAnalysis::NoAlias)
00587         return MemDepResult::getClobber(Inst);
00588       // If the allocation is not aliased and does not read memory (like
00589       // strdup), it is safe to ignore.
00590       if (isa<AllocaInst>(Inst) ||
00591           isMallocLikeFn(Inst, TLI) || isCallocLikeFn(Inst, TLI))
00592         continue;
00593     }
00594 
00595     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
00596     AliasAnalysis::ModRefResult MR = AA->getModRefInfo(Inst, MemLoc);
00597     // If necessary, perform additional analysis.
00598     if (MR == AliasAnalysis::ModRef)
00599       MR = AA->callCapturesBefore(Inst, MemLoc, DT);
00600     switch (MR) {
00601     case AliasAnalysis::NoModRef:
00602       // If the call has no effect on the queried pointer, just ignore it.
00603       continue;
00604     case AliasAnalysis::Mod:
00605       return MemDepResult::getClobber(Inst);
00606     case AliasAnalysis::Ref:
00607       // If the call is known to never store to the pointer, and if this is a
00608       // load query, we can safely ignore it (scan past it).
00609       if (isLoad)
00610         continue;
00611     default:
00612       // Otherwise, there is a potential dependence.  Return a clobber.
00613       return MemDepResult::getClobber(Inst);
00614     }
00615   }
00616 
00617   // No dependence found.  If this is the entry block of the function, it is
00618   // unknown, otherwise it is non-local.
00619   if (BB != &BB->getParent()->getEntryBlock())
00620     return MemDepResult::getNonLocal();
00621   return MemDepResult::getNonFuncLocal();
00622 }
00623 
00624 /// getDependency - Return the instruction on which a memory operation
00625 /// depends.
00626 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
00627   Instruction *ScanPos = QueryInst;
00628 
00629   // Check for a cached result
00630   MemDepResult &LocalCache = LocalDeps[QueryInst];
00631 
00632   // If the cached entry is non-dirty, just return it.  Note that this depends
00633   // on MemDepResult's default constructing to 'dirty'.
00634   if (!LocalCache.isDirty())
00635     return LocalCache;
00636 
00637   // Otherwise, if we have a dirty entry, we know we can start the scan at that
00638   // instruction, which may save us some work.
00639   if (Instruction *Inst = LocalCache.getInst()) {
00640     ScanPos = Inst;
00641 
00642     RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
00643   }
00644 
00645   BasicBlock *QueryParent = QueryInst->getParent();
00646 
00647   // Do the scan.
00648   if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
00649     // No dependence found.  If this is the entry block of the function, it is
00650     // unknown, otherwise it is non-local.
00651     if (QueryParent != &QueryParent->getParent()->getEntryBlock())
00652       LocalCache = MemDepResult::getNonLocal();
00653     else
00654       LocalCache = MemDepResult::getNonFuncLocal();
00655   } else {
00656     AliasAnalysis::Location MemLoc;
00657     AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
00658     if (MemLoc.Ptr) {
00659       // If we can do a pointer scan, make it happen.
00660       bool isLoad = !(MR & AliasAnalysis::Mod);
00661       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
00662         isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
00663 
00664       LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
00665                                             QueryParent, QueryInst);
00666     } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
00667       CallSite QueryCS(QueryInst);
00668       bool isReadOnly = AA->onlyReadsMemory(QueryCS);
00669       LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
00670                                              QueryParent);
00671     } else
00672       // Non-memory instruction.
00673       LocalCache = MemDepResult::getUnknown();
00674   }
00675 
00676   // Remember the result!
00677   if (Instruction *I = LocalCache.getInst())
00678     ReverseLocalDeps[I].insert(QueryInst);
00679 
00680   return LocalCache;
00681 }
00682 
00683 #ifndef NDEBUG
00684 /// AssertSorted - This method is used when -debug is specified to verify that
00685 /// cache arrays are properly kept sorted.
00686 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
00687                          int Count = -1) {
00688   if (Count == -1) Count = Cache.size();
00689   if (Count == 0) return;
00690 
00691   for (unsigned i = 1; i != unsigned(Count); ++i)
00692     assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
00693 }
00694 #endif
00695 
00696 /// getNonLocalCallDependency - Perform a full dependency query for the
00697 /// specified call, returning the set of blocks that the value is
00698 /// potentially live across.  The returned set of results will include a
00699 /// "NonLocal" result for all blocks where the value is live across.
00700 ///
00701 /// This method assumes the instruction returns a "NonLocal" dependency
00702 /// within its own block.
00703 ///
00704 /// This returns a reference to an internal data structure that may be
00705 /// invalidated on the next non-local query or when an instruction is
00706 /// removed.  Clients must copy this data if they want it around longer than
00707 /// that.
00708 const MemoryDependenceAnalysis::NonLocalDepInfo &
00709 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
00710   assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
00711  "getNonLocalCallDependency should only be used on calls with non-local deps!");
00712   PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
00713   NonLocalDepInfo &Cache = CacheP.first;
00714 
00715   /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
00716   /// the cached case, this can happen due to instructions being deleted etc. In
00717   /// the uncached case, this starts out as the set of predecessors we care
00718   /// about.
00719   SmallVector<BasicBlock*, 32> DirtyBlocks;
00720 
00721   if (!Cache.empty()) {
00722     // Okay, we have a cache entry.  If we know it is not dirty, just return it
00723     // with no computation.
00724     if (!CacheP.second) {
00725       ++NumCacheNonLocal;
00726       return Cache;
00727     }
00728 
00729     // If we already have a partially computed set of results, scan them to
00730     // determine what is dirty, seeding our initial DirtyBlocks worklist.
00731     for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
00732        I != E; ++I)
00733       if (I->getResult().isDirty())
00734         DirtyBlocks.push_back(I->getBB());
00735 
00736     // Sort the cache so that we can do fast binary search lookups below.
00737     std::sort(Cache.begin(), Cache.end());
00738 
00739     ++NumCacheDirtyNonLocal;
00740     //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
00741     //     << Cache.size() << " cached: " << *QueryInst;
00742   } else {
00743     // Seed DirtyBlocks with each of the preds of QueryInst's block.
00744     BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
00745     for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
00746       DirtyBlocks.push_back(*PI);
00747     ++NumUncacheNonLocal;
00748   }
00749 
00750   // isReadonlyCall - If this is a read-only call, we can be more aggressive.
00751   bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
00752 
00753   SmallPtrSet<BasicBlock*, 64> Visited;
00754 
00755   unsigned NumSortedEntries = Cache.size();
00756   DEBUG(AssertSorted(Cache));
00757 
00758   // Iterate while we still have blocks to update.
00759   while (!DirtyBlocks.empty()) {
00760     BasicBlock *DirtyBB = DirtyBlocks.back();
00761     DirtyBlocks.pop_back();
00762 
00763     // Already processed this block?
00764     if (!Visited.insert(DirtyBB))
00765       continue;
00766 
00767     // Do a binary search to see if we already have an entry for this block in
00768     // the cache set.  If so, find it.
00769     DEBUG(AssertSorted(Cache, NumSortedEntries));
00770     NonLocalDepInfo::iterator Entry =
00771       std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
00772                        NonLocalDepEntry(DirtyBB));
00773     if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
00774       --Entry;
00775 
00776     NonLocalDepEntry *ExistingResult = nullptr;
00777     if (Entry != Cache.begin()+NumSortedEntries &&
00778         Entry->getBB() == DirtyBB) {
00779       // If we already have an entry, and if it isn't already dirty, the block
00780       // is done.
00781       if (!Entry->getResult().isDirty())
00782         continue;
00783 
00784       // Otherwise, remember this slot so we can update the value.
00785       ExistingResult = &*Entry;
00786     }
00787 
00788     // If the dirty entry has a pointer, start scanning from it so we don't have
00789     // to rescan the entire block.
00790     BasicBlock::iterator ScanPos = DirtyBB->end();
00791     if (ExistingResult) {
00792       if (Instruction *Inst = ExistingResult->getResult().getInst()) {
00793         ScanPos = Inst;
00794         // We're removing QueryInst's use of Inst.
00795         RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
00796                              QueryCS.getInstruction());
00797       }
00798     }
00799 
00800     // Find out if this block has a local dependency for QueryInst.
00801     MemDepResult Dep;
00802 
00803     if (ScanPos != DirtyBB->begin()) {
00804       Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
00805     } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
00806       // No dependence found.  If this is the entry block of the function, it is
00807       // a clobber, otherwise it is unknown.
00808       Dep = MemDepResult::getNonLocal();
00809     } else {
00810       Dep = MemDepResult::getNonFuncLocal();
00811     }
00812 
00813     // If we had a dirty entry for the block, update it.  Otherwise, just add
00814     // a new entry.
00815     if (ExistingResult)
00816       ExistingResult->setResult(Dep);
00817     else
00818       Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
00819 
00820     // If the block has a dependency (i.e. it isn't completely transparent to
00821     // the value), remember the association!
00822     if (!Dep.isNonLocal()) {
00823       // Keep the ReverseNonLocalDeps map up to date so we can efficiently
00824       // update this when we remove instructions.
00825       if (Instruction *Inst = Dep.getInst())
00826         ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
00827     } else {
00828 
00829       // If the block *is* completely transparent to the load, we need to check
00830       // the predecessors of this block.  Add them to our worklist.
00831       for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
00832         DirtyBlocks.push_back(*PI);
00833     }
00834   }
00835 
00836   return Cache;
00837 }
00838 
00839 /// getNonLocalPointerDependency - Perform a full dependency query for an
00840 /// access to the specified (non-volatile) memory location, returning the
00841 /// set of instructions that either define or clobber the value.
00842 ///
00843 /// This method assumes the pointer has a "NonLocal" dependency within its
00844 /// own block.
00845 ///
00846 void MemoryDependenceAnalysis::
00847 getNonLocalPointerDependency(const AliasAnalysis::Location &Loc, bool isLoad,
00848                              BasicBlock *FromBB,
00849                              SmallVectorImpl<NonLocalDepResult> &Result) {
00850   assert(Loc.Ptr->getType()->isPointerTy() &&
00851          "Can't get pointer deps of a non-pointer!");
00852   Result.clear();
00853 
00854   PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL);
00855 
00856   // This is the set of blocks we've inspected, and the pointer we consider in
00857   // each block.  Because of critical edges, we currently bail out if querying
00858   // a block with multiple different pointers.  This can happen during PHI
00859   // translation.
00860   DenseMap<BasicBlock*, Value*> Visited;
00861   if (!getNonLocalPointerDepFromBB(Address, Loc, isLoad, FromBB,
00862                                    Result, Visited, true))
00863     return;
00864   Result.clear();
00865   Result.push_back(NonLocalDepResult(FromBB,
00866                                      MemDepResult::getUnknown(),
00867                                      const_cast<Value *>(Loc.Ptr)));
00868 }
00869 
00870 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
00871 /// Pointer/PointeeSize using either cached information in Cache or by doing a
00872 /// lookup (which may use dirty cache info if available).  If we do a lookup,
00873 /// add the result to the cache.
00874 MemDepResult MemoryDependenceAnalysis::
00875 GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
00876                         bool isLoad, BasicBlock *BB,
00877                         NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
00878 
00879   // Do a binary search to see if we already have an entry for this block in
00880   // the cache set.  If so, find it.
00881   NonLocalDepInfo::iterator Entry =
00882     std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
00883                      NonLocalDepEntry(BB));
00884   if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
00885     --Entry;
00886 
00887   NonLocalDepEntry *ExistingResult = nullptr;
00888   if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
00889     ExistingResult = &*Entry;
00890 
00891   // If we have a cached entry, and it is non-dirty, use it as the value for
00892   // this dependency.
00893   if (ExistingResult && !ExistingResult->getResult().isDirty()) {
00894     ++NumCacheNonLocalPtr;
00895     return ExistingResult->getResult();
00896   }
00897 
00898   // Otherwise, we have to scan for the value.  If we have a dirty cache
00899   // entry, start scanning from its position, otherwise we scan from the end
00900   // of the block.
00901   BasicBlock::iterator ScanPos = BB->end();
00902   if (ExistingResult && ExistingResult->getResult().getInst()) {
00903     assert(ExistingResult->getResult().getInst()->getParent() == BB &&
00904            "Instruction invalidated?");
00905     ++NumCacheDirtyNonLocalPtr;
00906     ScanPos = ExistingResult->getResult().getInst();
00907 
00908     // Eliminating the dirty entry from 'Cache', so update the reverse info.
00909     ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
00910     RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
00911   } else {
00912     ++NumUncacheNonLocalPtr;
00913   }
00914 
00915   // Scan the block for the dependency.
00916   MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB);
00917 
00918   // If we had a dirty entry for the block, update it.  Otherwise, just add
00919   // a new entry.
00920   if (ExistingResult)
00921     ExistingResult->setResult(Dep);
00922   else
00923     Cache->push_back(NonLocalDepEntry(BB, Dep));
00924 
00925   // If the block has a dependency (i.e. it isn't completely transparent to
00926   // the value), remember the reverse association because we just added it
00927   // to Cache!
00928   if (!Dep.isDef() && !Dep.isClobber())
00929     return Dep;
00930 
00931   // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
00932   // update MemDep when we remove instructions.
00933   Instruction *Inst = Dep.getInst();
00934   assert(Inst && "Didn't depend on anything?");
00935   ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
00936   ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
00937   return Dep;
00938 }
00939 
00940 /// SortNonLocalDepInfoCache - Sort the NonLocalDepInfo cache, given a certain
00941 /// number of elements in the array that are already properly ordered.  This is
00942 /// optimized for the case when only a few entries are added.
00943 static void
00944 SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
00945                          unsigned NumSortedEntries) {
00946   switch (Cache.size() - NumSortedEntries) {
00947   case 0:
00948     // done, no new entries.
00949     break;
00950   case 2: {
00951     // Two new entries, insert the last one into place.
00952     NonLocalDepEntry Val = Cache.back();
00953     Cache.pop_back();
00954     MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
00955       std::upper_bound(Cache.begin(), Cache.end()-1, Val);
00956     Cache.insert(Entry, Val);
00957     // FALL THROUGH.
00958   }
00959   case 1:
00960     // One new entry, Just insert the new value at the appropriate position.
00961     if (Cache.size() != 1) {
00962       NonLocalDepEntry Val = Cache.back();
00963       Cache.pop_back();
00964       MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
00965         std::upper_bound(Cache.begin(), Cache.end(), Val);
00966       Cache.insert(Entry, Val);
00967     }
00968     break;
00969   default:
00970     // Added many values, do a full scale sort.
00971     std::sort(Cache.begin(), Cache.end());
00972     break;
00973   }
00974 }
00975 
00976 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
00977 /// pointer/pointeesize starting at the end of StartBB.  Add any clobber/def
00978 /// results to the results vector and keep track of which blocks are visited in
00979 /// 'Visited'.
00980 ///
00981 /// This has special behavior for the first block queries (when SkipFirstBlock
00982 /// is true).  In this special case, it ignores the contents of the specified
00983 /// block and starts returning dependence info for its predecessors.
00984 ///
00985 /// This function returns false on success, or true to indicate that it could
00986 /// not compute dependence information for some reason.  This should be treated
00987 /// as a clobber dependence on the first instruction in the predecessor block.
00988 bool MemoryDependenceAnalysis::
00989 getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
00990                             const AliasAnalysis::Location &Loc,
00991                             bool isLoad, BasicBlock *StartBB,
00992                             SmallVectorImpl<NonLocalDepResult> &Result,
00993                             DenseMap<BasicBlock*, Value*> &Visited,
00994                             bool SkipFirstBlock) {
00995   // Look up the cached info for Pointer.
00996   ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
00997 
00998   // Set up a temporary NLPI value. If the map doesn't yet have an entry for
00999   // CacheKey, this value will be inserted as the associated value. Otherwise,
01000   // it'll be ignored, and we'll have to check to see if the cached size and
01001   // aa tags are consistent with the current query.
01002   NonLocalPointerInfo InitialNLPI;
01003   InitialNLPI.Size = Loc.Size;
01004   InitialNLPI.AATags = Loc.AATags;
01005 
01006   // Get the NLPI for CacheKey, inserting one into the map if it doesn't
01007   // already have one.
01008   std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
01009     NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
01010   NonLocalPointerInfo *CacheInfo = &Pair.first->second;
01011 
01012   // If we already have a cache entry for this CacheKey, we may need to do some
01013   // work to reconcile the cache entry and the current query.
01014   if (!Pair.second) {
01015     if (CacheInfo->Size < Loc.Size) {
01016       // The query's Size is greater than the cached one. Throw out the
01017       // cached data and proceed with the query at the greater size.
01018       CacheInfo->Pair = BBSkipFirstBlockPair();
01019       CacheInfo->Size = Loc.Size;
01020       for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
01021            DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
01022         if (Instruction *Inst = DI->getResult().getInst())
01023           RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
01024       CacheInfo->NonLocalDeps.clear();
01025     } else if (CacheInfo->Size > Loc.Size) {
01026       // This query's Size is less than the cached one. Conservatively restart
01027       // the query using the greater size.
01028       return getNonLocalPointerDepFromBB(Pointer,
01029                                          Loc.getWithNewSize(CacheInfo->Size),
01030                                          isLoad, StartBB, Result, Visited,
01031                                          SkipFirstBlock);
01032     }
01033 
01034     // If the query's AATags are inconsistent with the cached one,
01035     // conservatively throw out the cached data and restart the query with
01036     // no tag if needed.
01037     if (CacheInfo->AATags != Loc.AATags) {
01038       if (CacheInfo->AATags) {
01039         CacheInfo->Pair = BBSkipFirstBlockPair();
01040         CacheInfo->AATags = AAMDNodes();
01041         for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
01042              DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
01043           if (Instruction *Inst = DI->getResult().getInst())
01044             RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
01045         CacheInfo->NonLocalDeps.clear();
01046       }
01047       if (Loc.AATags)
01048         return getNonLocalPointerDepFromBB(Pointer, Loc.getWithoutAATags(),
01049                                            isLoad, StartBB, Result, Visited,
01050                                            SkipFirstBlock);
01051     }
01052   }
01053 
01054   NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
01055 
01056   // If we have valid cached information for exactly the block we are
01057   // investigating, just return it with no recomputation.
01058   if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
01059     // We have a fully cached result for this query then we can just return the
01060     // cached results and populate the visited set.  However, we have to verify
01061     // that we don't already have conflicting results for these blocks.  Check
01062     // to ensure that if a block in the results set is in the visited set that
01063     // it was for the same pointer query.
01064     if (!Visited.empty()) {
01065       for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
01066            I != E; ++I) {
01067         DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
01068         if (VI == Visited.end() || VI->second == Pointer.getAddr())
01069           continue;
01070 
01071         // We have a pointer mismatch in a block.  Just return clobber, saying
01072         // that something was clobbered in this result.  We could also do a
01073         // non-fully cached query, but there is little point in doing this.
01074         return true;
01075       }
01076     }
01077 
01078     Value *Addr = Pointer.getAddr();
01079     for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
01080          I != E; ++I) {
01081       Visited.insert(std::make_pair(I->getBB(), Addr));
01082       if (I->getResult().isNonLocal()) {
01083         continue;
01084       }
01085 
01086       if (!DT) {
01087         Result.push_back(NonLocalDepResult(I->getBB(),
01088                                            MemDepResult::getUnknown(),
01089                                            Addr));
01090       } else if (DT->isReachableFromEntry(I->getBB())) {
01091         Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
01092       }
01093     }
01094     ++NumCacheCompleteNonLocalPtr;
01095     return false;
01096   }
01097 
01098   // Otherwise, either this is a new block, a block with an invalid cache
01099   // pointer or one that we're about to invalidate by putting more info into it
01100   // than its valid cache info.  If empty, the result will be valid cache info,
01101   // otherwise it isn't.
01102   if (Cache->empty())
01103     CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
01104   else
01105     CacheInfo->Pair = BBSkipFirstBlockPair();
01106 
01107   SmallVector<BasicBlock*, 32> Worklist;
01108   Worklist.push_back(StartBB);
01109 
01110   // PredList used inside loop.
01111   SmallVector<std::pair<BasicBlock*, PHITransAddr>, 16> PredList;
01112 
01113   // Keep track of the entries that we know are sorted.  Previously cached
01114   // entries will all be sorted.  The entries we add we only sort on demand (we
01115   // don't insert every element into its sorted position).  We know that we
01116   // won't get any reuse from currently inserted values, because we don't
01117   // revisit blocks after we insert info for them.
01118   unsigned NumSortedEntries = Cache->size();
01119   DEBUG(AssertSorted(*Cache));
01120 
01121   while (!Worklist.empty()) {
01122     BasicBlock *BB = Worklist.pop_back_val();
01123 
01124     // Skip the first block if we have it.
01125     if (!SkipFirstBlock) {
01126       // Analyze the dependency of *Pointer in FromBB.  See if we already have
01127       // been here.
01128       assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
01129 
01130       // Get the dependency info for Pointer in BB.  If we have cached
01131       // information, we will use it, otherwise we compute it.
01132       DEBUG(AssertSorted(*Cache, NumSortedEntries));
01133       MemDepResult Dep = GetNonLocalInfoForBlock(Loc, isLoad, BB, Cache,
01134                                                  NumSortedEntries);
01135 
01136       // If we got a Def or Clobber, add this to the list of results.
01137       if (!Dep.isNonLocal()) {
01138         if (!DT) {
01139           Result.push_back(NonLocalDepResult(BB,
01140                                              MemDepResult::getUnknown(),
01141                                              Pointer.getAddr()));
01142           continue;
01143         } else if (DT->isReachableFromEntry(BB)) {
01144           Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
01145           continue;
01146         }
01147       }
01148     }
01149 
01150     // If 'Pointer' is an instruction defined in this block, then we need to do
01151     // phi translation to change it into a value live in the predecessor block.
01152     // If not, we just add the predecessors to the worklist and scan them with
01153     // the same Pointer.
01154     if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
01155       SkipFirstBlock = false;
01156       SmallVector<BasicBlock*, 16> NewBlocks;
01157       for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
01158         // Verify that we haven't looked at this block yet.
01159         std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
01160           InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
01161         if (InsertRes.second) {
01162           // First time we've looked at *PI.
01163           NewBlocks.push_back(*PI);
01164           continue;
01165         }
01166 
01167         // If we have seen this block before, but it was with a different
01168         // pointer then we have a phi translation failure and we have to treat
01169         // this as a clobber.
01170         if (InsertRes.first->second != Pointer.getAddr()) {
01171           // Make sure to clean up the Visited map before continuing on to
01172           // PredTranslationFailure.
01173           for (unsigned i = 0; i < NewBlocks.size(); i++)
01174             Visited.erase(NewBlocks[i]);
01175           goto PredTranslationFailure;
01176         }
01177       }
01178       Worklist.append(NewBlocks.begin(), NewBlocks.end());
01179       continue;
01180     }
01181 
01182     // We do need to do phi translation, if we know ahead of time we can't phi
01183     // translate this value, don't even try.
01184     if (!Pointer.IsPotentiallyPHITranslatable())
01185       goto PredTranslationFailure;
01186 
01187     // We may have added values to the cache list before this PHI translation.
01188     // If so, we haven't done anything to ensure that the cache remains sorted.
01189     // Sort it now (if needed) so that recursive invocations of
01190     // getNonLocalPointerDepFromBB and other routines that could reuse the cache
01191     // value will only see properly sorted cache arrays.
01192     if (Cache && NumSortedEntries != Cache->size()) {
01193       SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
01194       NumSortedEntries = Cache->size();
01195     }
01196     Cache = nullptr;
01197 
01198     PredList.clear();
01199     for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
01200       BasicBlock *Pred = *PI;
01201       PredList.push_back(std::make_pair(Pred, Pointer));
01202 
01203       // Get the PHI translated pointer in this predecessor.  This can fail if
01204       // not translatable, in which case the getAddr() returns null.
01205       PHITransAddr &PredPointer = PredList.back().second;
01206       PredPointer.PHITranslateValue(BB, Pred, nullptr);
01207 
01208       Value *PredPtrVal = PredPointer.getAddr();
01209 
01210       // Check to see if we have already visited this pred block with another
01211       // pointer.  If so, we can't do this lookup.  This failure can occur
01212       // with PHI translation when a critical edge exists and the PHI node in
01213       // the successor translates to a pointer value different than the
01214       // pointer the block was first analyzed with.
01215       std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
01216         InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
01217 
01218       if (!InsertRes.second) {
01219         // We found the pred; take it off the list of preds to visit.
01220         PredList.pop_back();
01221 
01222         // If the predecessor was visited with PredPtr, then we already did
01223         // the analysis and can ignore it.
01224         if (InsertRes.first->second == PredPtrVal)
01225           continue;
01226 
01227         // Otherwise, the block was previously analyzed with a different
01228         // pointer.  We can't represent the result of this case, so we just
01229         // treat this as a phi translation failure.
01230 
01231         // Make sure to clean up the Visited map before continuing on to
01232         // PredTranslationFailure.
01233         for (unsigned i = 0, n = PredList.size(); i < n; ++i)
01234           Visited.erase(PredList[i].first);
01235 
01236         goto PredTranslationFailure;
01237       }
01238     }
01239 
01240     // Actually process results here; this need to be a separate loop to avoid
01241     // calling getNonLocalPointerDepFromBB for blocks we don't want to return
01242     // any results for.  (getNonLocalPointerDepFromBB will modify our
01243     // datastructures in ways the code after the PredTranslationFailure label
01244     // doesn't expect.)
01245     for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
01246       BasicBlock *Pred = PredList[i].first;
01247       PHITransAddr &PredPointer = PredList[i].second;
01248       Value *PredPtrVal = PredPointer.getAddr();
01249 
01250       bool CanTranslate = true;
01251       // If PHI translation was unable to find an available pointer in this
01252       // predecessor, then we have to assume that the pointer is clobbered in
01253       // that predecessor.  We can still do PRE of the load, which would insert
01254       // a computation of the pointer in this predecessor.
01255       if (!PredPtrVal)
01256         CanTranslate = false;
01257 
01258       // FIXME: it is entirely possible that PHI translating will end up with
01259       // the same value.  Consider PHI translating something like:
01260       // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
01261       // to recurse here, pedantically speaking.
01262 
01263       // If getNonLocalPointerDepFromBB fails here, that means the cached
01264       // result conflicted with the Visited list; we have to conservatively
01265       // assume it is unknown, but this also does not block PRE of the load.
01266       if (!CanTranslate ||
01267           getNonLocalPointerDepFromBB(PredPointer,
01268                                       Loc.getWithNewPtr(PredPtrVal),
01269                                       isLoad, Pred,
01270                                       Result, Visited)) {
01271         // Add the entry to the Result list.
01272         NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
01273         Result.push_back(Entry);
01274 
01275         // Since we had a phi translation failure, the cache for CacheKey won't
01276         // include all of the entries that we need to immediately satisfy future
01277         // queries.  Mark this in NonLocalPointerDeps by setting the
01278         // BBSkipFirstBlockPair pointer to null.  This requires reuse of the
01279         // cached value to do more work but not miss the phi trans failure.
01280         NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
01281         NLPI.Pair = BBSkipFirstBlockPair();
01282         continue;
01283       }
01284     }
01285 
01286     // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
01287     CacheInfo = &NonLocalPointerDeps[CacheKey];
01288     Cache = &CacheInfo->NonLocalDeps;
01289     NumSortedEntries = Cache->size();
01290 
01291     // Since we did phi translation, the "Cache" set won't contain all of the
01292     // results for the query.  This is ok (we can still use it to accelerate
01293     // specific block queries) but we can't do the fastpath "return all
01294     // results from the set"  Clear out the indicator for this.
01295     CacheInfo->Pair = BBSkipFirstBlockPair();
01296     SkipFirstBlock = false;
01297     continue;
01298 
01299   PredTranslationFailure:
01300     // The following code is "failure"; we can't produce a sane translation
01301     // for the given block.  It assumes that we haven't modified any of
01302     // our datastructures while processing the current block.
01303 
01304     if (!Cache) {
01305       // Refresh the CacheInfo/Cache pointer if it got invalidated.
01306       CacheInfo = &NonLocalPointerDeps[CacheKey];
01307       Cache = &CacheInfo->NonLocalDeps;
01308       NumSortedEntries = Cache->size();
01309     }
01310 
01311     // Since we failed phi translation, the "Cache" set won't contain all of the
01312     // results for the query.  This is ok (we can still use it to accelerate
01313     // specific block queries) but we can't do the fastpath "return all
01314     // results from the set".  Clear out the indicator for this.
01315     CacheInfo->Pair = BBSkipFirstBlockPair();
01316 
01317     // If *nothing* works, mark the pointer as unknown.
01318     //
01319     // If this is the magic first block, return this as a clobber of the whole
01320     // incoming value.  Since we can't phi translate to one of the predecessors,
01321     // we have to bail out.
01322     if (SkipFirstBlock)
01323       return true;
01324 
01325     for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
01326       assert(I != Cache->rend() && "Didn't find current block??");
01327       if (I->getBB() != BB)
01328         continue;
01329 
01330       assert(I->getResult().isNonLocal() &&
01331              "Should only be here with transparent block");
01332       I->setResult(MemDepResult::getUnknown());
01333       Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
01334                                          Pointer.getAddr()));
01335       break;
01336     }
01337   }
01338 
01339   // Okay, we're done now.  If we added new values to the cache, re-sort it.
01340   SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
01341   DEBUG(AssertSorted(*Cache));
01342   return false;
01343 }
01344 
01345 /// RemoveCachedNonLocalPointerDependencies - If P exists in
01346 /// CachedNonLocalPointerInfo, remove it.
01347 void MemoryDependenceAnalysis::
01348 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
01349   CachedNonLocalPointerInfo::iterator It =
01350     NonLocalPointerDeps.find(P);
01351   if (It == NonLocalPointerDeps.end()) return;
01352 
01353   // Remove all of the entries in the BB->val map.  This involves removing
01354   // instructions from the reverse map.
01355   NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
01356 
01357   for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
01358     Instruction *Target = PInfo[i].getResult().getInst();
01359     if (!Target) continue;  // Ignore non-local dep results.
01360     assert(Target->getParent() == PInfo[i].getBB());
01361 
01362     // Eliminating the dirty entry from 'Cache', so update the reverse info.
01363     RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
01364   }
01365 
01366   // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
01367   NonLocalPointerDeps.erase(It);
01368 }
01369 
01370 
01371 /// invalidateCachedPointerInfo - This method is used to invalidate cached
01372 /// information about the specified pointer, because it may be too
01373 /// conservative in memdep.  This is an optional call that can be used when
01374 /// the client detects an equivalence between the pointer and some other
01375 /// value and replaces the other value with ptr. This can make Ptr available
01376 /// in more places that cached info does not necessarily keep.
01377 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
01378   // If Ptr isn't really a pointer, just ignore it.
01379   if (!Ptr->getType()->isPointerTy()) return;
01380   // Flush store info for the pointer.
01381   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
01382   // Flush load info for the pointer.
01383   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
01384 }
01385 
01386 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
01387 /// This needs to be done when the CFG changes, e.g., due to splitting
01388 /// critical edges.
01389 void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
01390   PredCache->clear();
01391 }
01392 
01393 /// removeInstruction - Remove an instruction from the dependence analysis,
01394 /// updating the dependence of instructions that previously depended on it.
01395 /// This method attempts to keep the cache coherent using the reverse map.
01396 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
01397   // Walk through the Non-local dependencies, removing this one as the value
01398   // for any cached queries.
01399   NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
01400   if (NLDI != NonLocalDeps.end()) {
01401     NonLocalDepInfo &BlockMap = NLDI->second.first;
01402     for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
01403          DI != DE; ++DI)
01404       if (Instruction *Inst = DI->getResult().getInst())
01405         RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
01406     NonLocalDeps.erase(NLDI);
01407   }
01408 
01409   // If we have a cached local dependence query for this instruction, remove it.
01410   //
01411   LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
01412   if (LocalDepEntry != LocalDeps.end()) {
01413     // Remove us from DepInst's reverse set now that the local dep info is gone.
01414     if (Instruction *Inst = LocalDepEntry->second.getInst())
01415       RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
01416 
01417     // Remove this local dependency info.
01418     LocalDeps.erase(LocalDepEntry);
01419   }
01420 
01421   // If we have any cached pointer dependencies on this instruction, remove
01422   // them.  If the instruction has non-pointer type, then it can't be a pointer
01423   // base.
01424 
01425   // Remove it from both the load info and the store info.  The instruction
01426   // can't be in either of these maps if it is non-pointer.
01427   if (RemInst->getType()->isPointerTy()) {
01428     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
01429     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
01430   }
01431 
01432   // Loop over all of the things that depend on the instruction we're removing.
01433   //
01434   SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
01435 
01436   // If we find RemInst as a clobber or Def in any of the maps for other values,
01437   // we need to replace its entry with a dirty version of the instruction after
01438   // it.  If RemInst is a terminator, we use a null dirty value.
01439   //
01440   // Using a dirty version of the instruction after RemInst saves having to scan
01441   // the entire block to get to this point.
01442   MemDepResult NewDirtyVal;
01443   if (!RemInst->isTerminator())
01444     NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
01445 
01446   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
01447   if (ReverseDepIt != ReverseLocalDeps.end()) {
01448     // RemInst can't be the terminator if it has local stuff depending on it.
01449     assert(!ReverseDepIt->second.empty() && !isa<TerminatorInst>(RemInst) &&
01450            "Nothing can locally depend on a terminator");
01451 
01452     for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
01453       assert(InstDependingOnRemInst != RemInst &&
01454              "Already removed our local dep info");
01455 
01456       LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
01457 
01458       // Make sure to remember that new things depend on NewDepInst.
01459       assert(NewDirtyVal.getInst() && "There is no way something else can have "
01460              "a local dep on this if it is a terminator!");
01461       ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
01462                                                 InstDependingOnRemInst));
01463     }
01464 
01465     ReverseLocalDeps.erase(ReverseDepIt);
01466 
01467     // Add new reverse deps after scanning the set, to avoid invalidating the
01468     // 'ReverseDeps' reference.
01469     while (!ReverseDepsToAdd.empty()) {
01470       ReverseLocalDeps[ReverseDepsToAdd.back().first]
01471         .insert(ReverseDepsToAdd.back().second);
01472       ReverseDepsToAdd.pop_back();
01473     }
01474   }
01475 
01476   ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
01477   if (ReverseDepIt != ReverseNonLocalDeps.end()) {
01478     for (Instruction *I : ReverseDepIt->second) {
01479       assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
01480 
01481       PerInstNLInfo &INLD = NonLocalDeps[I];
01482       // The information is now dirty!
01483       INLD.second = true;
01484 
01485       for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
01486            DE = INLD.first.end(); DI != DE; ++DI) {
01487         if (DI->getResult().getInst() != RemInst) continue;
01488 
01489         // Convert to a dirty entry for the subsequent instruction.
01490         DI->setResult(NewDirtyVal);
01491 
01492         if (Instruction *NextI = NewDirtyVal.getInst())
01493           ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
01494       }
01495     }
01496 
01497     ReverseNonLocalDeps.erase(ReverseDepIt);
01498 
01499     // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
01500     while (!ReverseDepsToAdd.empty()) {
01501       ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
01502         .insert(ReverseDepsToAdd.back().second);
01503       ReverseDepsToAdd.pop_back();
01504     }
01505   }
01506 
01507   // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
01508   // value in the NonLocalPointerDeps info.
01509   ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
01510     ReverseNonLocalPtrDeps.find(RemInst);
01511   if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
01512     SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
01513 
01514     for (ValueIsLoadPair P : ReversePtrDepIt->second) {
01515       assert(P.getPointer() != RemInst &&
01516              "Already removed NonLocalPointerDeps info for RemInst");
01517 
01518       NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
01519 
01520       // The cache is not valid for any specific block anymore.
01521       NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
01522 
01523       // Update any entries for RemInst to use the instruction after it.
01524       for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
01525            DI != DE; ++DI) {
01526         if (DI->getResult().getInst() != RemInst) continue;
01527 
01528         // Convert to a dirty entry for the subsequent instruction.
01529         DI->setResult(NewDirtyVal);
01530 
01531         if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
01532           ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
01533       }
01534 
01535       // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
01536       // subsequent value may invalidate the sortedness.
01537       std::sort(NLPDI.begin(), NLPDI.end());
01538     }
01539 
01540     ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
01541 
01542     while (!ReversePtrDepsToAdd.empty()) {
01543       ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
01544         .insert(ReversePtrDepsToAdd.back().second);
01545       ReversePtrDepsToAdd.pop_back();
01546     }
01547   }
01548 
01549 
01550   assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
01551   AA->deleteValue(RemInst);
01552   DEBUG(verifyRemoved(RemInst));
01553 }
01554 /// verifyRemoved - Verify that the specified instruction does not occur
01555 /// in our internal data structures. This function verifies by asserting in
01556 /// debug builds.
01557 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
01558 #ifndef NDEBUG
01559   for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
01560        E = LocalDeps.end(); I != E; ++I) {
01561     assert(I->first != D && "Inst occurs in data structures");
01562     assert(I->second.getInst() != D &&
01563            "Inst occurs in data structures");
01564   }
01565 
01566   for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
01567        E = NonLocalPointerDeps.end(); I != E; ++I) {
01568     assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
01569     const NonLocalDepInfo &Val = I->second.NonLocalDeps;
01570     for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
01571          II != E; ++II)
01572       assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
01573   }
01574 
01575   for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
01576        E = NonLocalDeps.end(); I != E; ++I) {
01577     assert(I->first != D && "Inst occurs in data structures");
01578     const PerInstNLInfo &INLD = I->second;
01579     for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
01580          EE = INLD.first.end(); II  != EE; ++II)
01581       assert(II->getResult().getInst() != D && "Inst occurs in data structures");
01582   }
01583 
01584   for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
01585        E = ReverseLocalDeps.end(); I != E; ++I) {
01586     assert(I->first != D && "Inst occurs in data structures");
01587     for (Instruction *Inst : I->second)
01588       assert(Inst != D && "Inst occurs in data structures");
01589   }
01590 
01591   for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
01592        E = ReverseNonLocalDeps.end();
01593        I != E; ++I) {
01594     assert(I->first != D && "Inst occurs in data structures");
01595     for (Instruction *Inst : I->second)
01596       assert(Inst != D && "Inst occurs in data structures");
01597   }
01598 
01599   for (ReverseNonLocalPtrDepTy::const_iterator
01600        I = ReverseNonLocalPtrDeps.begin(),
01601        E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
01602     assert(I->first != D && "Inst occurs in rev NLPD map");
01603 
01604     for (ValueIsLoadPair P : I->second)
01605       assert(P != ValueIsLoadPair(D, false) &&
01606              P != ValueIsLoadPair(D, true) &&
01607              "Inst occurs in ReverseNonLocalPtrDeps map");
01608   }
01609 #endif
01610 }