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