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