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