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