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