1f22ef01cSRoman Divacky //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation --*- C++ -*-===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This file implements an analysis that determines, for a given memory 11f22ef01cSRoman Divacky // operation, what preceding memory operations it depends on. It builds on 12f22ef01cSRoman Divacky // alias analysis information, and tries to provide a lazy, caching interface to 13f22ef01cSRoman Divacky // a common kind of alias information query. 14f22ef01cSRoman Divacky // 15f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 16f22ef01cSRoman Divacky 17f22ef01cSRoman Divacky #define DEBUG_TYPE "memdep" 18f22ef01cSRoman Divacky #include "llvm/Analysis/MemoryDependenceAnalysis.h" 19139f7f9bSDimitry Andric #include "llvm/ADT/STLExtras.h" 20139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h" 21f22ef01cSRoman Divacky #include "llvm/Analysis/AliasAnalysis.h" 22f22ef01cSRoman Divacky #include "llvm/Analysis/Dominators.h" 23f22ef01cSRoman Divacky #include "llvm/Analysis/InstructionSimplify.h" 24f22ef01cSRoman Divacky #include "llvm/Analysis/MemoryBuiltins.h" 25f22ef01cSRoman Divacky #include "llvm/Analysis/PHITransAddr.h" 262754fe60SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 27139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 28139f7f9bSDimitry Andric #include "llvm/IR/Function.h" 29139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h" 30139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h" 31139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h" 32f22ef01cSRoman Divacky #include "llvm/Support/Debug.h" 33139f7f9bSDimitry Andric #include "llvm/Support/PredIteratorCache.h" 34f22ef01cSRoman Divacky using namespace llvm; 35f22ef01cSRoman Divacky 36f22ef01cSRoman Divacky STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses"); 37f22ef01cSRoman Divacky STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses"); 38f22ef01cSRoman Divacky STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses"); 39f22ef01cSRoman Divacky 40f22ef01cSRoman Divacky STATISTIC(NumCacheNonLocalPtr, 41f22ef01cSRoman Divacky "Number of fully cached non-local ptr responses"); 42f22ef01cSRoman Divacky STATISTIC(NumCacheDirtyNonLocalPtr, 43f22ef01cSRoman Divacky "Number of cached, but dirty, non-local ptr responses"); 44f22ef01cSRoman Divacky STATISTIC(NumUncacheNonLocalPtr, 45f22ef01cSRoman Divacky "Number of uncached non-local ptr responses"); 46f22ef01cSRoman Divacky STATISTIC(NumCacheCompleteNonLocalPtr, 47f22ef01cSRoman Divacky "Number of block queries that were completely cached"); 48f22ef01cSRoman Divacky 4917a519f9SDimitry Andric // Limit for the number of instructions to scan in a block. 5017a519f9SDimitry Andric // FIXME: Figure out what a sane value is for this. 5117a519f9SDimitry Andric // (500 is relatively insane.) 5217a519f9SDimitry Andric static const int BlockScanLimit = 500; 5317a519f9SDimitry Andric 54f22ef01cSRoman Divacky char MemoryDependenceAnalysis::ID = 0; 55f22ef01cSRoman Divacky 56f22ef01cSRoman Divacky // Register this pass... 572754fe60SDimitry Andric INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep", 582754fe60SDimitry Andric "Memory Dependence Analysis", false, true) 592754fe60SDimitry Andric INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 602754fe60SDimitry Andric INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep", 612754fe60SDimitry Andric "Memory Dependence Analysis", false, true) 62f22ef01cSRoman Divacky 63f22ef01cSRoman Divacky MemoryDependenceAnalysis::MemoryDependenceAnalysis() 64e580952dSDimitry Andric : FunctionPass(ID), PredCache(0) { 652754fe60SDimitry Andric initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry()); 66f22ef01cSRoman Divacky } 67f22ef01cSRoman Divacky MemoryDependenceAnalysis::~MemoryDependenceAnalysis() { 68f22ef01cSRoman Divacky } 69f22ef01cSRoman Divacky 70f22ef01cSRoman Divacky /// Clean up memory in between runs 71f22ef01cSRoman Divacky void MemoryDependenceAnalysis::releaseMemory() { 72f22ef01cSRoman Divacky LocalDeps.clear(); 73f22ef01cSRoman Divacky NonLocalDeps.clear(); 74f22ef01cSRoman Divacky NonLocalPointerDeps.clear(); 75f22ef01cSRoman Divacky ReverseLocalDeps.clear(); 76f22ef01cSRoman Divacky ReverseNonLocalDeps.clear(); 77f22ef01cSRoman Divacky ReverseNonLocalPtrDeps.clear(); 78f22ef01cSRoman Divacky PredCache->clear(); 79f22ef01cSRoman Divacky } 80f22ef01cSRoman Divacky 81f22ef01cSRoman Divacky 82f22ef01cSRoman Divacky 83f22ef01cSRoman Divacky /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis. 84f22ef01cSRoman Divacky /// 85f22ef01cSRoman Divacky void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { 86f22ef01cSRoman Divacky AU.setPreservesAll(); 87f22ef01cSRoman Divacky AU.addRequiredTransitive<AliasAnalysis>(); 88f22ef01cSRoman Divacky } 89f22ef01cSRoman Divacky 90f22ef01cSRoman Divacky bool MemoryDependenceAnalysis::runOnFunction(Function &) { 91f22ef01cSRoman Divacky AA = &getAnalysis<AliasAnalysis>(); 923861d79fSDimitry Andric TD = getAnalysisIfAvailable<DataLayout>(); 93dff0c46cSDimitry Andric DT = getAnalysisIfAvailable<DominatorTree>(); 94f22ef01cSRoman Divacky if (PredCache == 0) 95f22ef01cSRoman Divacky PredCache.reset(new PredIteratorCache()); 96f22ef01cSRoman Divacky return false; 97f22ef01cSRoman Divacky } 98f22ef01cSRoman Divacky 99f22ef01cSRoman Divacky /// RemoveFromReverseMap - This is a helper function that removes Val from 100f22ef01cSRoman Divacky /// 'Inst's set in ReverseMap. If the set becomes empty, remove Inst's entry. 101f22ef01cSRoman Divacky template <typename KeyTy> 102f22ef01cSRoman Divacky static void RemoveFromReverseMap(DenseMap<Instruction*, 103f22ef01cSRoman Divacky SmallPtrSet<KeyTy, 4> > &ReverseMap, 104f22ef01cSRoman Divacky Instruction *Inst, KeyTy Val) { 105f22ef01cSRoman Divacky typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator 106f22ef01cSRoman Divacky InstIt = ReverseMap.find(Inst); 107f22ef01cSRoman Divacky assert(InstIt != ReverseMap.end() && "Reverse map out of sync?"); 108f22ef01cSRoman Divacky bool Found = InstIt->second.erase(Val); 1092754fe60SDimitry Andric assert(Found && "Invalid reverse map!"); (void)Found; 110f22ef01cSRoman Divacky if (InstIt->second.empty()) 111f22ef01cSRoman Divacky ReverseMap.erase(InstIt); 112f22ef01cSRoman Divacky } 113f22ef01cSRoman Divacky 1142754fe60SDimitry Andric /// GetLocation - If the given instruction references a specific memory 1152754fe60SDimitry Andric /// location, fill in Loc with the details, otherwise set Loc.Ptr to null. 1162754fe60SDimitry Andric /// Return a ModRefInfo value describing the general behavior of the 1172754fe60SDimitry Andric /// instruction. 1182754fe60SDimitry Andric static 1192754fe60SDimitry Andric AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst, 1202754fe60SDimitry Andric AliasAnalysis::Location &Loc, 1212754fe60SDimitry Andric AliasAnalysis *AA) { 1222754fe60SDimitry Andric if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 1236122f3e6SDimitry Andric if (LI->isUnordered()) { 1242754fe60SDimitry Andric Loc = AA->getLocation(LI); 1252754fe60SDimitry Andric return AliasAnalysis::Ref; 126139f7f9bSDimitry Andric } 127139f7f9bSDimitry Andric if (LI->getOrdering() == Monotonic) { 1286122f3e6SDimitry Andric Loc = AA->getLocation(LI); 1296122f3e6SDimitry Andric return AliasAnalysis::ModRef; 1306122f3e6SDimitry Andric } 1316122f3e6SDimitry Andric Loc = AliasAnalysis::Location(); 1326122f3e6SDimitry Andric return AliasAnalysis::ModRef; 1332754fe60SDimitry Andric } 1342754fe60SDimitry Andric 1352754fe60SDimitry Andric if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 1366122f3e6SDimitry Andric if (SI->isUnordered()) { 1372754fe60SDimitry Andric Loc = AA->getLocation(SI); 1382754fe60SDimitry Andric return AliasAnalysis::Mod; 139139f7f9bSDimitry Andric } 140139f7f9bSDimitry Andric if (SI->getOrdering() == Monotonic) { 1416122f3e6SDimitry Andric Loc = AA->getLocation(SI); 1426122f3e6SDimitry Andric return AliasAnalysis::ModRef; 1436122f3e6SDimitry Andric } 1446122f3e6SDimitry Andric Loc = AliasAnalysis::Location(); 1456122f3e6SDimitry Andric return AliasAnalysis::ModRef; 1462754fe60SDimitry Andric } 1472754fe60SDimitry Andric 1482754fe60SDimitry Andric if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) { 1492754fe60SDimitry Andric Loc = AA->getLocation(V); 1502754fe60SDimitry Andric return AliasAnalysis::ModRef; 1512754fe60SDimitry Andric } 1522754fe60SDimitry Andric 1533861d79fSDimitry Andric if (const CallInst *CI = isFreeCall(Inst, AA->getTargetLibraryInfo())) { 1542754fe60SDimitry Andric // calls to free() deallocate the entire structure 1552754fe60SDimitry Andric Loc = AliasAnalysis::Location(CI->getArgOperand(0)); 1562754fe60SDimitry Andric return AliasAnalysis::Mod; 1572754fe60SDimitry Andric } 1582754fe60SDimitry Andric 1592754fe60SDimitry Andric if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) 1602754fe60SDimitry Andric switch (II->getIntrinsicID()) { 1612754fe60SDimitry Andric case Intrinsic::lifetime_start: 1622754fe60SDimitry Andric case Intrinsic::lifetime_end: 1632754fe60SDimitry Andric case Intrinsic::invariant_start: 1642754fe60SDimitry Andric Loc = AliasAnalysis::Location(II->getArgOperand(1), 1652754fe60SDimitry Andric cast<ConstantInt>(II->getArgOperand(0)) 1662754fe60SDimitry Andric ->getZExtValue(), 1672754fe60SDimitry Andric II->getMetadata(LLVMContext::MD_tbaa)); 1682754fe60SDimitry Andric // These intrinsics don't really modify the memory, but returning Mod 1692754fe60SDimitry Andric // will allow them to be handled conservatively. 1702754fe60SDimitry Andric return AliasAnalysis::Mod; 1712754fe60SDimitry Andric case Intrinsic::invariant_end: 1722754fe60SDimitry Andric Loc = AliasAnalysis::Location(II->getArgOperand(2), 1732754fe60SDimitry Andric cast<ConstantInt>(II->getArgOperand(1)) 1742754fe60SDimitry Andric ->getZExtValue(), 1752754fe60SDimitry Andric II->getMetadata(LLVMContext::MD_tbaa)); 1762754fe60SDimitry Andric // These intrinsics don't really modify the memory, but returning Mod 1772754fe60SDimitry Andric // will allow them to be handled conservatively. 1782754fe60SDimitry Andric return AliasAnalysis::Mod; 1792754fe60SDimitry Andric default: 1802754fe60SDimitry Andric break; 1812754fe60SDimitry Andric } 1822754fe60SDimitry Andric 1832754fe60SDimitry Andric // Otherwise, just do the coarse-grained thing that always works. 1842754fe60SDimitry Andric if (Inst->mayWriteToMemory()) 1852754fe60SDimitry Andric return AliasAnalysis::ModRef; 1862754fe60SDimitry Andric if (Inst->mayReadFromMemory()) 1872754fe60SDimitry Andric return AliasAnalysis::Ref; 1882754fe60SDimitry Andric return AliasAnalysis::NoModRef; 1892754fe60SDimitry Andric } 190f22ef01cSRoman Divacky 191f22ef01cSRoman Divacky /// getCallSiteDependencyFrom - Private helper for finding the local 192f22ef01cSRoman Divacky /// dependencies of a call site. 193f22ef01cSRoman Divacky MemDepResult MemoryDependenceAnalysis:: 194f22ef01cSRoman Divacky getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall, 195f22ef01cSRoman Divacky BasicBlock::iterator ScanIt, BasicBlock *BB) { 19617a519f9SDimitry Andric unsigned Limit = BlockScanLimit; 19717a519f9SDimitry Andric 198f22ef01cSRoman Divacky // Walk backwards through the block, looking for dependencies 199f22ef01cSRoman Divacky while (ScanIt != BB->begin()) { 20017a519f9SDimitry Andric // Limit the amount of scanning we do so we don't end up with quadratic 20117a519f9SDimitry Andric // running time on extreme testcases. 20217a519f9SDimitry Andric --Limit; 20317a519f9SDimitry Andric if (!Limit) 20417a519f9SDimitry Andric return MemDepResult::getUnknown(); 20517a519f9SDimitry Andric 206f22ef01cSRoman Divacky Instruction *Inst = --ScanIt; 207f22ef01cSRoman Divacky 208f22ef01cSRoman Divacky // If this inst is a memory op, get the pointer it accessed 2092754fe60SDimitry Andric AliasAnalysis::Location Loc; 2102754fe60SDimitry Andric AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA); 2112754fe60SDimitry Andric if (Loc.Ptr) { 2122754fe60SDimitry Andric // A simple instruction. 2132754fe60SDimitry Andric if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef) 2142754fe60SDimitry Andric return MemDepResult::getClobber(Inst); 2152754fe60SDimitry Andric continue; 2162754fe60SDimitry Andric } 2172754fe60SDimitry Andric 2182754fe60SDimitry Andric if (CallSite InstCS = cast<Value>(Inst)) { 219f22ef01cSRoman Divacky // Debug intrinsics don't cause dependences. 220f22ef01cSRoman Divacky if (isa<DbgInfoIntrinsic>(Inst)) continue; 221f22ef01cSRoman Divacky // If these two calls do not interfere, look past it. 222f22ef01cSRoman Divacky switch (AA->getModRefInfo(CS, InstCS)) { 223f22ef01cSRoman Divacky case AliasAnalysis::NoModRef: 224e580952dSDimitry Andric // If the two calls are the same, return InstCS as a Def, so that 225e580952dSDimitry Andric // CS can be found redundant and eliminated. 2262754fe60SDimitry Andric if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) && 227e580952dSDimitry Andric CS.getInstruction()->isIdenticalToWhenDefined(Inst)) 228f22ef01cSRoman Divacky return MemDepResult::getDef(Inst); 229e580952dSDimitry Andric 230e580952dSDimitry Andric // Otherwise if the two calls don't interact (e.g. InstCS is readnone) 231e580952dSDimitry Andric // keep scanning. 2327ae0e2c9SDimitry Andric continue; 233f22ef01cSRoman Divacky default: 234f22ef01cSRoman Divacky return MemDepResult::getClobber(Inst); 235f22ef01cSRoman Divacky } 236f22ef01cSRoman Divacky } 2377ae0e2c9SDimitry Andric 2387ae0e2c9SDimitry Andric // If we could not obtain a pointer for the instruction and the instruction 2397ae0e2c9SDimitry Andric // touches memory then assume that this is a dependency. 2407ae0e2c9SDimitry Andric if (MR != AliasAnalysis::NoModRef) 2417ae0e2c9SDimitry Andric return MemDepResult::getClobber(Inst); 242f22ef01cSRoman Divacky } 243f22ef01cSRoman Divacky 24417a519f9SDimitry Andric // No dependence found. If this is the entry block of the function, it is 24517a519f9SDimitry Andric // unknown, otherwise it is non-local. 246f22ef01cSRoman Divacky if (BB != &BB->getParent()->getEntryBlock()) 247f22ef01cSRoman Divacky return MemDepResult::getNonLocal(); 2486122f3e6SDimitry Andric return MemDepResult::getNonFuncLocal(); 249f22ef01cSRoman Divacky } 250f22ef01cSRoman Divacky 2513b0f4066SDimitry Andric /// isLoadLoadClobberIfExtendedToFullWidth - Return true if LI is a load that 2523b0f4066SDimitry Andric /// would fully overlap MemLoc if done as a wider legal integer load. 2533b0f4066SDimitry Andric /// 2543b0f4066SDimitry Andric /// MemLocBase, MemLocOffset are lazily computed here the first time the 2553b0f4066SDimitry Andric /// base/offs of memloc is needed. 2563b0f4066SDimitry Andric static bool 2573b0f4066SDimitry Andric isLoadLoadClobberIfExtendedToFullWidth(const AliasAnalysis::Location &MemLoc, 2583b0f4066SDimitry Andric const Value *&MemLocBase, 2593b0f4066SDimitry Andric int64_t &MemLocOffs, 2603b0f4066SDimitry Andric const LoadInst *LI, 2613861d79fSDimitry Andric const DataLayout *TD) { 2623b0f4066SDimitry Andric // If we have no target data, we can't do this. 2633b0f4066SDimitry Andric if (TD == 0) return false; 2643b0f4066SDimitry Andric 2653b0f4066SDimitry Andric // If we haven't already computed the base/offset of MemLoc, do so now. 2663b0f4066SDimitry Andric if (MemLocBase == 0) 267139f7f9bSDimitry Andric MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, TD); 2683b0f4066SDimitry Andric 2693b0f4066SDimitry Andric unsigned Size = MemoryDependenceAnalysis:: 2703b0f4066SDimitry Andric getLoadLoadClobberFullWidthSize(MemLocBase, MemLocOffs, MemLoc.Size, 2713b0f4066SDimitry Andric LI, *TD); 2723b0f4066SDimitry Andric return Size != 0; 2733b0f4066SDimitry Andric } 2743b0f4066SDimitry Andric 2753b0f4066SDimitry Andric /// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that 2763b0f4066SDimitry Andric /// looks at a memory location for a load (specified by MemLocBase, Offs, 2773b0f4066SDimitry Andric /// and Size) and compares it against a load. If the specified load could 2783b0f4066SDimitry Andric /// be safely widened to a larger integer load that is 1) still efficient, 2793b0f4066SDimitry Andric /// 2) safe for the target, and 3) would provide the specified memory 2803b0f4066SDimitry Andric /// location value, then this function returns the size in bytes of the 2813b0f4066SDimitry Andric /// load width to use. If not, this returns zero. 2823b0f4066SDimitry Andric unsigned MemoryDependenceAnalysis:: 2833b0f4066SDimitry Andric getLoadLoadClobberFullWidthSize(const Value *MemLocBase, int64_t MemLocOffs, 2843b0f4066SDimitry Andric unsigned MemLocSize, const LoadInst *LI, 2853861d79fSDimitry Andric const DataLayout &TD) { 2866122f3e6SDimitry Andric // We can only extend simple integer loads. 2876122f3e6SDimitry Andric if (!isa<IntegerType>(LI->getType()) || !LI->isSimple()) return 0; 2883b0f4066SDimitry Andric 289139f7f9bSDimitry Andric // Load widening is hostile to ThreadSanitizer: it may cause false positives 290139f7f9bSDimitry Andric // or make the reports more cryptic (access sizes are wrong). 291139f7f9bSDimitry Andric if (LI->getParent()->getParent()->getAttributes(). 292139f7f9bSDimitry Andric hasAttribute(AttributeSet::FunctionIndex, Attribute::SanitizeThread)) 293139f7f9bSDimitry Andric return 0; 294139f7f9bSDimitry Andric 2953b0f4066SDimitry Andric // Get the base of this load. 2963b0f4066SDimitry Andric int64_t LIOffs = 0; 2973b0f4066SDimitry Andric const Value *LIBase = 298139f7f9bSDimitry Andric GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, &TD); 2993b0f4066SDimitry Andric 3003b0f4066SDimitry Andric // If the two pointers are not based on the same pointer, we can't tell that 3013b0f4066SDimitry Andric // they are related. 3023b0f4066SDimitry Andric if (LIBase != MemLocBase) return 0; 3033b0f4066SDimitry Andric 3043b0f4066SDimitry Andric // Okay, the two values are based on the same pointer, but returned as 3053b0f4066SDimitry Andric // no-alias. This happens when we have things like two byte loads at "P+1" 3063b0f4066SDimitry Andric // and "P+3". Check to see if increasing the size of the "LI" load up to its 3073b0f4066SDimitry Andric // alignment (or the largest native integer type) will allow us to load all 3083b0f4066SDimitry Andric // the bits required by MemLoc. 3093b0f4066SDimitry Andric 3103b0f4066SDimitry Andric // If MemLoc is before LI, then no widening of LI will help us out. 3113b0f4066SDimitry Andric if (MemLocOffs < LIOffs) return 0; 3123b0f4066SDimitry Andric 3133b0f4066SDimitry Andric // Get the alignment of the load in bytes. We assume that it is safe to load 3143b0f4066SDimitry Andric // any legal integer up to this size without a problem. For example, if we're 3153b0f4066SDimitry Andric // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can 3163b0f4066SDimitry Andric // widen it up to an i32 load. If it is known 2-byte aligned, we can widen it 3173b0f4066SDimitry Andric // to i16. 3183b0f4066SDimitry Andric unsigned LoadAlign = LI->getAlignment(); 3193b0f4066SDimitry Andric 3203b0f4066SDimitry Andric int64_t MemLocEnd = MemLocOffs+MemLocSize; 3213b0f4066SDimitry Andric 3223b0f4066SDimitry Andric // If no amount of rounding up will let MemLoc fit into LI, then bail out. 3233b0f4066SDimitry Andric if (LIOffs+LoadAlign < MemLocEnd) return 0; 3243b0f4066SDimitry Andric 3253b0f4066SDimitry Andric // This is the size of the load to try. Start with the next larger power of 3263b0f4066SDimitry Andric // two. 3273b0f4066SDimitry Andric unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits()/8U; 3283b0f4066SDimitry Andric NewLoadByteSize = NextPowerOf2(NewLoadByteSize); 3293b0f4066SDimitry Andric 3303b0f4066SDimitry Andric while (1) { 3313b0f4066SDimitry Andric // If this load size is bigger than our known alignment or would not fit 3323b0f4066SDimitry Andric // into a native integer register, then we fail. 3333b0f4066SDimitry Andric if (NewLoadByteSize > LoadAlign || 3343b0f4066SDimitry Andric !TD.fitsInLegalInteger(NewLoadByteSize*8)) 3353b0f4066SDimitry Andric return 0; 3363b0f4066SDimitry Andric 337dff0c46cSDimitry Andric if (LIOffs+NewLoadByteSize > MemLocEnd && 338139f7f9bSDimitry Andric LI->getParent()->getParent()->getAttributes(). 339139f7f9bSDimitry Andric hasAttribute(AttributeSet::FunctionIndex, Attribute::SanitizeAddress)) 340dff0c46cSDimitry Andric // We will be reading past the location accessed by the original program. 341dff0c46cSDimitry Andric // While this is safe in a regular build, Address Safety analysis tools 342dff0c46cSDimitry Andric // may start reporting false warnings. So, don't do widening. 343dff0c46cSDimitry Andric return 0; 344dff0c46cSDimitry Andric 3453b0f4066SDimitry Andric // If a load of this width would include all of MemLoc, then we succeed. 3463b0f4066SDimitry Andric if (LIOffs+NewLoadByteSize >= MemLocEnd) 3473b0f4066SDimitry Andric return NewLoadByteSize; 3483b0f4066SDimitry Andric 3493b0f4066SDimitry Andric NewLoadByteSize <<= 1; 3503b0f4066SDimitry Andric } 351dff0c46cSDimitry Andric } 3523b0f4066SDimitry Andric 353f22ef01cSRoman Divacky /// getPointerDependencyFrom - Return the instruction on which a memory 3542754fe60SDimitry Andric /// location depends. If isLoad is true, this routine ignores may-aliases with 3552754fe60SDimitry Andric /// read-only operations. If isLoad is false, this routine ignores may-aliases 356139f7f9bSDimitry Andric /// with reads from read-only locations. If possible, pass the query 357139f7f9bSDimitry Andric /// instruction as well; this function may take advantage of the metadata 358139f7f9bSDimitry Andric /// annotated to the query instruction to refine the result. 359f22ef01cSRoman Divacky MemDepResult MemoryDependenceAnalysis:: 3602754fe60SDimitry Andric getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad, 361139f7f9bSDimitry Andric BasicBlock::iterator ScanIt, BasicBlock *BB, 362139f7f9bSDimitry Andric Instruction *QueryInst) { 363f22ef01cSRoman Divacky 3643b0f4066SDimitry Andric const Value *MemLocBase = 0; 3653b0f4066SDimitry Andric int64_t MemLocOffset = 0; 36617a519f9SDimitry Andric unsigned Limit = BlockScanLimit; 367139f7f9bSDimitry Andric bool isInvariantLoad = false; 368139f7f9bSDimitry Andric if (isLoad && QueryInst) { 369139f7f9bSDimitry Andric LoadInst *LI = dyn_cast<LoadInst>(QueryInst); 370139f7f9bSDimitry Andric if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != 0) 371139f7f9bSDimitry Andric isInvariantLoad = true; 372139f7f9bSDimitry Andric } 37317a519f9SDimitry Andric 374f22ef01cSRoman Divacky // Walk backwards through the basic block, looking for dependencies. 375f22ef01cSRoman Divacky while (ScanIt != BB->begin()) { 37617a519f9SDimitry Andric // Limit the amount of scanning we do so we don't end up with quadratic 37717a519f9SDimitry Andric // running time on extreme testcases. 37817a519f9SDimitry Andric --Limit; 37917a519f9SDimitry Andric if (!Limit) 38017a519f9SDimitry Andric return MemDepResult::getUnknown(); 38117a519f9SDimitry Andric 382f22ef01cSRoman Divacky Instruction *Inst = --ScanIt; 383f22ef01cSRoman Divacky 384f22ef01cSRoman Divacky if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 3852754fe60SDimitry Andric // Debug intrinsics don't (and can't) cause dependences. 3862754fe60SDimitry Andric if (isa<DbgInfoIntrinsic>(II)) continue; 387f22ef01cSRoman Divacky 388f22ef01cSRoman Divacky // If we reach a lifetime begin or end marker, then the query ends here 389f22ef01cSRoman Divacky // because the value is undefined. 3902754fe60SDimitry Andric if (II->getIntrinsicID() == Intrinsic::lifetime_start) { 391f22ef01cSRoman Divacky // FIXME: This only considers queries directly on the invariant-tagged 392f22ef01cSRoman Divacky // pointer, not on query pointers that are indexed off of them. It'd 3933b0f4066SDimitry Andric // be nice to handle that at some point (the right approach is to use 3943b0f4066SDimitry Andric // GetPointerBaseWithConstantOffset). 3953b0f4066SDimitry Andric if (AA->isMustAlias(AliasAnalysis::Location(II->getArgOperand(1)), 3963b0f4066SDimitry Andric MemLoc)) 397f22ef01cSRoman Divacky return MemDepResult::getDef(II); 3982754fe60SDimitry Andric continue; 399f22ef01cSRoman Divacky } 400f22ef01cSRoman Divacky } 401f22ef01cSRoman Divacky 402f22ef01cSRoman Divacky // Values depend on loads if the pointers are must aliased. This means that 403f22ef01cSRoman Divacky // a load depends on another must aliased load from the same value. 404f22ef01cSRoman Divacky if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 4056122f3e6SDimitry Andric // Atomic loads have complications involved. 4066122f3e6SDimitry Andric // FIXME: This is overly conservative. 4076122f3e6SDimitry Andric if (!LI->isUnordered()) 4086122f3e6SDimitry Andric return MemDepResult::getClobber(LI); 4096122f3e6SDimitry Andric 4102754fe60SDimitry Andric AliasAnalysis::Location LoadLoc = AA->getLocation(LI); 411f22ef01cSRoman Divacky 412f22ef01cSRoman Divacky // If we found a pointer, check if it could be the same as our pointer. 4132754fe60SDimitry Andric AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc); 4143b0f4066SDimitry Andric 4153b0f4066SDimitry Andric if (isLoad) { 4163b0f4066SDimitry Andric if (R == AliasAnalysis::NoAlias) { 4173b0f4066SDimitry Andric // If this is an over-aligned integer load (for example, 4183b0f4066SDimitry Andric // "load i8* %P, align 4") see if it would obviously overlap with the 4193b0f4066SDimitry Andric // queried location if widened to a larger load (e.g. if the queried 4203b0f4066SDimitry Andric // location is 1 byte at P+1). If so, return it as a load/load 4213b0f4066SDimitry Andric // clobber result, allowing the client to decide to widen the load if 4223b0f4066SDimitry Andric // it wants to. 4236122f3e6SDimitry Andric if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) 4243b0f4066SDimitry Andric if (LI->getAlignment()*8 > ITy->getPrimitiveSizeInBits() && 4253b0f4066SDimitry Andric isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase, 4263b0f4066SDimitry Andric MemLocOffset, LI, TD)) 4273b0f4066SDimitry Andric return MemDepResult::getClobber(Inst); 4283b0f4066SDimitry Andric 4293b0f4066SDimitry Andric continue; 4303b0f4066SDimitry Andric } 4313b0f4066SDimitry Andric 4323b0f4066SDimitry Andric // Must aliased loads are defs of each other. 4333b0f4066SDimitry Andric if (R == AliasAnalysis::MustAlias) 4343b0f4066SDimitry Andric return MemDepResult::getDef(Inst); 4353b0f4066SDimitry Andric 436bd5abe19SDimitry Andric #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads 437bd5abe19SDimitry Andric // in terms of clobbering loads, but since it does this by looking 438bd5abe19SDimitry Andric // at the clobbering load directly, it doesn't know about any 439bd5abe19SDimitry Andric // phi translation that may have happened along the way. 440bd5abe19SDimitry Andric 4413b0f4066SDimitry Andric // If we have a partial alias, then return this as a clobber for the 4423b0f4066SDimitry Andric // client to handle. 4433b0f4066SDimitry Andric if (R == AliasAnalysis::PartialAlias) 4443b0f4066SDimitry Andric return MemDepResult::getClobber(Inst); 445bd5abe19SDimitry Andric #endif 4463b0f4066SDimitry Andric 4473b0f4066SDimitry Andric // Random may-alias loads don't depend on each other without a 4483b0f4066SDimitry Andric // dependence. 4493b0f4066SDimitry Andric continue; 4503b0f4066SDimitry Andric } 4513b0f4066SDimitry Andric 4523b0f4066SDimitry Andric // Stores don't depend on other no-aliased accesses. 453f22ef01cSRoman Divacky if (R == AliasAnalysis::NoAlias) 454f22ef01cSRoman Divacky continue; 455f22ef01cSRoman Divacky 4562754fe60SDimitry Andric // Stores don't alias loads from read-only memory. 4573b0f4066SDimitry Andric if (AA->pointsToConstantMemory(LoadLoc)) 4582754fe60SDimitry Andric continue; 4592754fe60SDimitry Andric 4603b0f4066SDimitry Andric // Stores depend on may/must aliased loads. 461f22ef01cSRoman Divacky return MemDepResult::getDef(Inst); 462f22ef01cSRoman Divacky } 463f22ef01cSRoman Divacky 464f22ef01cSRoman Divacky if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 4656122f3e6SDimitry Andric // Atomic stores have complications involved. 4666122f3e6SDimitry Andric // FIXME: This is overly conservative. 4676122f3e6SDimitry Andric if (!SI->isUnordered()) 4686122f3e6SDimitry Andric return MemDepResult::getClobber(SI); 4696122f3e6SDimitry Andric 470f22ef01cSRoman Divacky // If alias analysis can tell that this store is guaranteed to not modify 471f22ef01cSRoman Divacky // the query pointer, ignore it. Use getModRefInfo to handle cases where 472f22ef01cSRoman Divacky // the query pointer points to constant memory etc. 4732754fe60SDimitry Andric if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef) 474f22ef01cSRoman Divacky continue; 475f22ef01cSRoman Divacky 476f22ef01cSRoman Divacky // Ok, this store might clobber the query pointer. Check to see if it is 477f22ef01cSRoman Divacky // a must alias: in this case, we want to return this as a def. 4782754fe60SDimitry Andric AliasAnalysis::Location StoreLoc = AA->getLocation(SI); 479f22ef01cSRoman Divacky 480f22ef01cSRoman Divacky // If we found a pointer, check if it could be the same as our pointer. 4812754fe60SDimitry Andric AliasAnalysis::AliasResult R = AA->alias(StoreLoc, MemLoc); 482f22ef01cSRoman Divacky 483f22ef01cSRoman Divacky if (R == AliasAnalysis::NoAlias) 484f22ef01cSRoman Divacky continue; 4852754fe60SDimitry Andric if (R == AliasAnalysis::MustAlias) 486f22ef01cSRoman Divacky return MemDepResult::getDef(Inst); 487139f7f9bSDimitry Andric if (isInvariantLoad) 488139f7f9bSDimitry Andric continue; 4892754fe60SDimitry Andric return MemDepResult::getClobber(Inst); 490f22ef01cSRoman Divacky } 491f22ef01cSRoman Divacky 492f22ef01cSRoman Divacky // If this is an allocation, and if we know that the accessed pointer is to 493f22ef01cSRoman Divacky // the allocation, return Def. This means that there is no dependence and 494f22ef01cSRoman Divacky // the access can be optimized based on that. For example, a load could 495f22ef01cSRoman Divacky // turn into undef. 496f22ef01cSRoman Divacky // Note: Only determine this to be a malloc if Inst is the malloc call, not 497f22ef01cSRoman Divacky // a subsequent bitcast of the malloc call result. There can be stores to 498f22ef01cSRoman Divacky // the malloced memory between the malloc call and its bitcast uses, and we 499f22ef01cSRoman Divacky // need to continue scanning until the malloc call. 5003861d79fSDimitry Andric const TargetLibraryInfo *TLI = AA->getTargetLibraryInfo(); 5013861d79fSDimitry Andric if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, TLI)) { 5022754fe60SDimitry Andric const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, TD); 503f22ef01cSRoman Divacky 5043b0f4066SDimitry Andric if (AccessPtr == Inst || AA->isMustAlias(Inst, AccessPtr)) 505f22ef01cSRoman Divacky return MemDepResult::getDef(Inst); 5063861d79fSDimitry Andric // Be conservative if the accessed pointer may alias the allocation. 5073861d79fSDimitry Andric if (AA->alias(Inst, AccessPtr) != AliasAnalysis::NoAlias) 5083861d79fSDimitry Andric return MemDepResult::getClobber(Inst); 5093861d79fSDimitry Andric // If the allocation is not aliased and does not read memory (like 5103861d79fSDimitry Andric // strdup), it is safe to ignore. 5113861d79fSDimitry Andric if (isa<AllocaInst>(Inst) || 5123861d79fSDimitry Andric isMallocLikeFn(Inst, TLI) || isCallocLikeFn(Inst, TLI)) 513f22ef01cSRoman Divacky continue; 514f22ef01cSRoman Divacky } 515f22ef01cSRoman Divacky 516f22ef01cSRoman Divacky // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer. 5177ae0e2c9SDimitry Andric AliasAnalysis::ModRefResult MR = AA->getModRefInfo(Inst, MemLoc); 5187ae0e2c9SDimitry Andric // If necessary, perform additional analysis. 5197ae0e2c9SDimitry Andric if (MR == AliasAnalysis::ModRef) 5207ae0e2c9SDimitry Andric MR = AA->callCapturesBefore(Inst, MemLoc, DT); 5217ae0e2c9SDimitry Andric switch (MR) { 522f22ef01cSRoman Divacky case AliasAnalysis::NoModRef: 523f22ef01cSRoman Divacky // If the call has no effect on the queried pointer, just ignore it. 524f22ef01cSRoman Divacky continue; 525f22ef01cSRoman Divacky case AliasAnalysis::Mod: 526f22ef01cSRoman Divacky return MemDepResult::getClobber(Inst); 527f22ef01cSRoman Divacky case AliasAnalysis::Ref: 528f22ef01cSRoman Divacky // If the call is known to never store to the pointer, and if this is a 529f22ef01cSRoman Divacky // load query, we can safely ignore it (scan past it). 530f22ef01cSRoman Divacky if (isLoad) 531f22ef01cSRoman Divacky continue; 532f22ef01cSRoman Divacky default: 533f22ef01cSRoman Divacky // Otherwise, there is a potential dependence. Return a clobber. 534f22ef01cSRoman Divacky return MemDepResult::getClobber(Inst); 535f22ef01cSRoman Divacky } 536f22ef01cSRoman Divacky } 537f22ef01cSRoman Divacky 53817a519f9SDimitry Andric // No dependence found. If this is the entry block of the function, it is 53917a519f9SDimitry Andric // unknown, otherwise it is non-local. 540f22ef01cSRoman Divacky if (BB != &BB->getParent()->getEntryBlock()) 541f22ef01cSRoman Divacky return MemDepResult::getNonLocal(); 5426122f3e6SDimitry Andric return MemDepResult::getNonFuncLocal(); 543f22ef01cSRoman Divacky } 544f22ef01cSRoman Divacky 545f22ef01cSRoman Divacky /// getDependency - Return the instruction on which a memory operation 546f22ef01cSRoman Divacky /// depends. 547f22ef01cSRoman Divacky MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) { 548f22ef01cSRoman Divacky Instruction *ScanPos = QueryInst; 549f22ef01cSRoman Divacky 550f22ef01cSRoman Divacky // Check for a cached result 551f22ef01cSRoman Divacky MemDepResult &LocalCache = LocalDeps[QueryInst]; 552f22ef01cSRoman Divacky 553f22ef01cSRoman Divacky // If the cached entry is non-dirty, just return it. Note that this depends 554f22ef01cSRoman Divacky // on MemDepResult's default constructing to 'dirty'. 555f22ef01cSRoman Divacky if (!LocalCache.isDirty()) 556f22ef01cSRoman Divacky return LocalCache; 557f22ef01cSRoman Divacky 558f22ef01cSRoman Divacky // Otherwise, if we have a dirty entry, we know we can start the scan at that 559f22ef01cSRoman Divacky // instruction, which may save us some work. 560f22ef01cSRoman Divacky if (Instruction *Inst = LocalCache.getInst()) { 561f22ef01cSRoman Divacky ScanPos = Inst; 562f22ef01cSRoman Divacky 563f22ef01cSRoman Divacky RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst); 564f22ef01cSRoman Divacky } 565f22ef01cSRoman Divacky 566f22ef01cSRoman Divacky BasicBlock *QueryParent = QueryInst->getParent(); 567f22ef01cSRoman Divacky 568f22ef01cSRoman Divacky // Do the scan. 569f22ef01cSRoman Divacky if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) { 57017a519f9SDimitry Andric // No dependence found. If this is the entry block of the function, it is 57117a519f9SDimitry Andric // unknown, otherwise it is non-local. 572f22ef01cSRoman Divacky if (QueryParent != &QueryParent->getParent()->getEntryBlock()) 573f22ef01cSRoman Divacky LocalCache = MemDepResult::getNonLocal(); 574f22ef01cSRoman Divacky else 5756122f3e6SDimitry Andric LocalCache = MemDepResult::getNonFuncLocal(); 5762754fe60SDimitry Andric } else { 5772754fe60SDimitry Andric AliasAnalysis::Location MemLoc; 5782754fe60SDimitry Andric AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA); 5792754fe60SDimitry Andric if (MemLoc.Ptr) { 5802754fe60SDimitry Andric // If we can do a pointer scan, make it happen. 5812754fe60SDimitry Andric bool isLoad = !(MR & AliasAnalysis::Mod); 5822754fe60SDimitry Andric if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst)) 583bd5abe19SDimitry Andric isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start; 584f22ef01cSRoman Divacky 5852754fe60SDimitry Andric LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos, 586139f7f9bSDimitry Andric QueryParent, QueryInst); 5872754fe60SDimitry Andric } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) { 588e580952dSDimitry Andric CallSite QueryCS(QueryInst); 589f22ef01cSRoman Divacky bool isReadOnly = AA->onlyReadsMemory(QueryCS); 590f22ef01cSRoman Divacky LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos, 591f22ef01cSRoman Divacky QueryParent); 5922754fe60SDimitry Andric } else 593f22ef01cSRoman Divacky // Non-memory instruction. 59417a519f9SDimitry Andric LocalCache = MemDepResult::getUnknown(); 595f22ef01cSRoman Divacky } 596f22ef01cSRoman Divacky 597f22ef01cSRoman Divacky // Remember the result! 598f22ef01cSRoman Divacky if (Instruction *I = LocalCache.getInst()) 599f22ef01cSRoman Divacky ReverseLocalDeps[I].insert(QueryInst); 600f22ef01cSRoman Divacky 601f22ef01cSRoman Divacky return LocalCache; 602f22ef01cSRoman Divacky } 603f22ef01cSRoman Divacky 604f22ef01cSRoman Divacky #ifndef NDEBUG 605f22ef01cSRoman Divacky /// AssertSorted - This method is used when -debug is specified to verify that 606f22ef01cSRoman Divacky /// cache arrays are properly kept sorted. 607f22ef01cSRoman Divacky static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache, 608f22ef01cSRoman Divacky int Count = -1) { 609f22ef01cSRoman Divacky if (Count == -1) Count = Cache.size(); 610f22ef01cSRoman Divacky if (Count == 0) return; 611f22ef01cSRoman Divacky 612f22ef01cSRoman Divacky for (unsigned i = 1; i != unsigned(Count); ++i) 613f22ef01cSRoman Divacky assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!"); 614f22ef01cSRoman Divacky } 615f22ef01cSRoman Divacky #endif 616f22ef01cSRoman Divacky 617f22ef01cSRoman Divacky /// getNonLocalCallDependency - Perform a full dependency query for the 618f22ef01cSRoman Divacky /// specified call, returning the set of blocks that the value is 619f22ef01cSRoman Divacky /// potentially live across. The returned set of results will include a 620f22ef01cSRoman Divacky /// "NonLocal" result for all blocks where the value is live across. 621f22ef01cSRoman Divacky /// 622f22ef01cSRoman Divacky /// This method assumes the instruction returns a "NonLocal" dependency 623f22ef01cSRoman Divacky /// within its own block. 624f22ef01cSRoman Divacky /// 625f22ef01cSRoman Divacky /// This returns a reference to an internal data structure that may be 626f22ef01cSRoman Divacky /// invalidated on the next non-local query or when an instruction is 627f22ef01cSRoman Divacky /// removed. Clients must copy this data if they want it around longer than 628f22ef01cSRoman Divacky /// that. 629f22ef01cSRoman Divacky const MemoryDependenceAnalysis::NonLocalDepInfo & 630f22ef01cSRoman Divacky MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) { 631f22ef01cSRoman Divacky assert(getDependency(QueryCS.getInstruction()).isNonLocal() && 632f22ef01cSRoman Divacky "getNonLocalCallDependency should only be used on calls with non-local deps!"); 633f22ef01cSRoman Divacky PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()]; 634f22ef01cSRoman Divacky NonLocalDepInfo &Cache = CacheP.first; 635f22ef01cSRoman Divacky 636f22ef01cSRoman Divacky /// DirtyBlocks - This is the set of blocks that need to be recomputed. In 637f22ef01cSRoman Divacky /// the cached case, this can happen due to instructions being deleted etc. In 638f22ef01cSRoman Divacky /// the uncached case, this starts out as the set of predecessors we care 639f22ef01cSRoman Divacky /// about. 640f22ef01cSRoman Divacky SmallVector<BasicBlock*, 32> DirtyBlocks; 641f22ef01cSRoman Divacky 642f22ef01cSRoman Divacky if (!Cache.empty()) { 643f22ef01cSRoman Divacky // Okay, we have a cache entry. If we know it is not dirty, just return it 644f22ef01cSRoman Divacky // with no computation. 645f22ef01cSRoman Divacky if (!CacheP.second) { 646ffd1746dSEd Schouten ++NumCacheNonLocal; 647f22ef01cSRoman Divacky return Cache; 648f22ef01cSRoman Divacky } 649f22ef01cSRoman Divacky 650f22ef01cSRoman Divacky // If we already have a partially computed set of results, scan them to 651f22ef01cSRoman Divacky // determine what is dirty, seeding our initial DirtyBlocks worklist. 652f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end(); 653f22ef01cSRoman Divacky I != E; ++I) 654f22ef01cSRoman Divacky if (I->getResult().isDirty()) 655f22ef01cSRoman Divacky DirtyBlocks.push_back(I->getBB()); 656f22ef01cSRoman Divacky 657f22ef01cSRoman Divacky // Sort the cache so that we can do fast binary search lookups below. 658f22ef01cSRoman Divacky std::sort(Cache.begin(), Cache.end()); 659f22ef01cSRoman Divacky 660f22ef01cSRoman Divacky ++NumCacheDirtyNonLocal; 661f22ef01cSRoman Divacky //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: " 662f22ef01cSRoman Divacky // << Cache.size() << " cached: " << *QueryInst; 663f22ef01cSRoman Divacky } else { 664f22ef01cSRoman Divacky // Seed DirtyBlocks with each of the preds of QueryInst's block. 665f22ef01cSRoman Divacky BasicBlock *QueryBB = QueryCS.getInstruction()->getParent(); 666f22ef01cSRoman Divacky for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI) 667f22ef01cSRoman Divacky DirtyBlocks.push_back(*PI); 668ffd1746dSEd Schouten ++NumUncacheNonLocal; 669f22ef01cSRoman Divacky } 670f22ef01cSRoman Divacky 671f22ef01cSRoman Divacky // isReadonlyCall - If this is a read-only call, we can be more aggressive. 672f22ef01cSRoman Divacky bool isReadonlyCall = AA->onlyReadsMemory(QueryCS); 673f22ef01cSRoman Divacky 674f22ef01cSRoman Divacky SmallPtrSet<BasicBlock*, 64> Visited; 675f22ef01cSRoman Divacky 676f22ef01cSRoman Divacky unsigned NumSortedEntries = Cache.size(); 677f22ef01cSRoman Divacky DEBUG(AssertSorted(Cache)); 678f22ef01cSRoman Divacky 679f22ef01cSRoman Divacky // Iterate while we still have blocks to update. 680f22ef01cSRoman Divacky while (!DirtyBlocks.empty()) { 681f22ef01cSRoman Divacky BasicBlock *DirtyBB = DirtyBlocks.back(); 682f22ef01cSRoman Divacky DirtyBlocks.pop_back(); 683f22ef01cSRoman Divacky 684f22ef01cSRoman Divacky // Already processed this block? 685f22ef01cSRoman Divacky if (!Visited.insert(DirtyBB)) 686f22ef01cSRoman Divacky continue; 687f22ef01cSRoman Divacky 688f22ef01cSRoman Divacky // Do a binary search to see if we already have an entry for this block in 689f22ef01cSRoman Divacky // the cache set. If so, find it. 690f22ef01cSRoman Divacky DEBUG(AssertSorted(Cache, NumSortedEntries)); 691f22ef01cSRoman Divacky NonLocalDepInfo::iterator Entry = 692f22ef01cSRoman Divacky std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries, 693f22ef01cSRoman Divacky NonLocalDepEntry(DirtyBB)); 694f22ef01cSRoman Divacky if (Entry != Cache.begin() && prior(Entry)->getBB() == DirtyBB) 695f22ef01cSRoman Divacky --Entry; 696f22ef01cSRoman Divacky 697f22ef01cSRoman Divacky NonLocalDepEntry *ExistingResult = 0; 698f22ef01cSRoman Divacky if (Entry != Cache.begin()+NumSortedEntries && 699f22ef01cSRoman Divacky Entry->getBB() == DirtyBB) { 700f22ef01cSRoman Divacky // If we already have an entry, and if it isn't already dirty, the block 701f22ef01cSRoman Divacky // is done. 702f22ef01cSRoman Divacky if (!Entry->getResult().isDirty()) 703f22ef01cSRoman Divacky continue; 704f22ef01cSRoman Divacky 705f22ef01cSRoman Divacky // Otherwise, remember this slot so we can update the value. 706f22ef01cSRoman Divacky ExistingResult = &*Entry; 707f22ef01cSRoman Divacky } 708f22ef01cSRoman Divacky 709f22ef01cSRoman Divacky // If the dirty entry has a pointer, start scanning from it so we don't have 710f22ef01cSRoman Divacky // to rescan the entire block. 711f22ef01cSRoman Divacky BasicBlock::iterator ScanPos = DirtyBB->end(); 712f22ef01cSRoman Divacky if (ExistingResult) { 713f22ef01cSRoman Divacky if (Instruction *Inst = ExistingResult->getResult().getInst()) { 714f22ef01cSRoman Divacky ScanPos = Inst; 715f22ef01cSRoman Divacky // We're removing QueryInst's use of Inst. 716f22ef01cSRoman Divacky RemoveFromReverseMap(ReverseNonLocalDeps, Inst, 717f22ef01cSRoman Divacky QueryCS.getInstruction()); 718f22ef01cSRoman Divacky } 719f22ef01cSRoman Divacky } 720f22ef01cSRoman Divacky 721f22ef01cSRoman Divacky // Find out if this block has a local dependency for QueryInst. 722f22ef01cSRoman Divacky MemDepResult Dep; 723f22ef01cSRoman Divacky 724f22ef01cSRoman Divacky if (ScanPos != DirtyBB->begin()) { 725f22ef01cSRoman Divacky Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB); 726f22ef01cSRoman Divacky } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) { 727f22ef01cSRoman Divacky // No dependence found. If this is the entry block of the function, it is 72817a519f9SDimitry Andric // a clobber, otherwise it is unknown. 729f22ef01cSRoman Divacky Dep = MemDepResult::getNonLocal(); 730f22ef01cSRoman Divacky } else { 7316122f3e6SDimitry Andric Dep = MemDepResult::getNonFuncLocal(); 732f22ef01cSRoman Divacky } 733f22ef01cSRoman Divacky 734f22ef01cSRoman Divacky // If we had a dirty entry for the block, update it. Otherwise, just add 735f22ef01cSRoman Divacky // a new entry. 736f22ef01cSRoman Divacky if (ExistingResult) 737f22ef01cSRoman Divacky ExistingResult->setResult(Dep); 738f22ef01cSRoman Divacky else 739f22ef01cSRoman Divacky Cache.push_back(NonLocalDepEntry(DirtyBB, Dep)); 740f22ef01cSRoman Divacky 741f22ef01cSRoman Divacky // If the block has a dependency (i.e. it isn't completely transparent to 742f22ef01cSRoman Divacky // the value), remember the association! 743f22ef01cSRoman Divacky if (!Dep.isNonLocal()) { 744f22ef01cSRoman Divacky // Keep the ReverseNonLocalDeps map up to date so we can efficiently 745f22ef01cSRoman Divacky // update this when we remove instructions. 746f22ef01cSRoman Divacky if (Instruction *Inst = Dep.getInst()) 747f22ef01cSRoman Divacky ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction()); 748f22ef01cSRoman Divacky } else { 749f22ef01cSRoman Divacky 750f22ef01cSRoman Divacky // If the block *is* completely transparent to the load, we need to check 751f22ef01cSRoman Divacky // the predecessors of this block. Add them to our worklist. 752f22ef01cSRoman Divacky for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI) 753f22ef01cSRoman Divacky DirtyBlocks.push_back(*PI); 754f22ef01cSRoman Divacky } 755f22ef01cSRoman Divacky } 756f22ef01cSRoman Divacky 757f22ef01cSRoman Divacky return Cache; 758f22ef01cSRoman Divacky } 759f22ef01cSRoman Divacky 760f22ef01cSRoman Divacky /// getNonLocalPointerDependency - Perform a full dependency query for an 761f22ef01cSRoman Divacky /// access to the specified (non-volatile) memory location, returning the 762f22ef01cSRoman Divacky /// set of instructions that either define or clobber the value. 763f22ef01cSRoman Divacky /// 764f22ef01cSRoman Divacky /// This method assumes the pointer has a "NonLocal" dependency within its 765f22ef01cSRoman Divacky /// own block. 766f22ef01cSRoman Divacky /// 767f22ef01cSRoman Divacky void MemoryDependenceAnalysis:: 7682754fe60SDimitry Andric getNonLocalPointerDependency(const AliasAnalysis::Location &Loc, bool isLoad, 7692754fe60SDimitry Andric BasicBlock *FromBB, 770f22ef01cSRoman Divacky SmallVectorImpl<NonLocalDepResult> &Result) { 7712754fe60SDimitry Andric assert(Loc.Ptr->getType()->isPointerTy() && 772f22ef01cSRoman Divacky "Can't get pointer deps of a non-pointer!"); 773f22ef01cSRoman Divacky Result.clear(); 774f22ef01cSRoman Divacky 7752754fe60SDimitry Andric PHITransAddr Address(const_cast<Value *>(Loc.Ptr), TD); 776f22ef01cSRoman Divacky 777f22ef01cSRoman Divacky // This is the set of blocks we've inspected, and the pointer we consider in 778f22ef01cSRoman Divacky // each block. Because of critical edges, we currently bail out if querying 779f22ef01cSRoman Divacky // a block with multiple different pointers. This can happen during PHI 780f22ef01cSRoman Divacky // translation. 781f22ef01cSRoman Divacky DenseMap<BasicBlock*, Value*> Visited; 7822754fe60SDimitry Andric if (!getNonLocalPointerDepFromBB(Address, Loc, isLoad, FromBB, 783f22ef01cSRoman Divacky Result, Visited, true)) 784f22ef01cSRoman Divacky return; 785f22ef01cSRoman Divacky Result.clear(); 786f22ef01cSRoman Divacky Result.push_back(NonLocalDepResult(FromBB, 78717a519f9SDimitry Andric MemDepResult::getUnknown(), 7882754fe60SDimitry Andric const_cast<Value *>(Loc.Ptr))); 789f22ef01cSRoman Divacky } 790f22ef01cSRoman Divacky 791f22ef01cSRoman Divacky /// GetNonLocalInfoForBlock - Compute the memdep value for BB with 792f22ef01cSRoman Divacky /// Pointer/PointeeSize using either cached information in Cache or by doing a 793f22ef01cSRoman Divacky /// lookup (which may use dirty cache info if available). If we do a lookup, 794f22ef01cSRoman Divacky /// add the result to the cache. 795f22ef01cSRoman Divacky MemDepResult MemoryDependenceAnalysis:: 7962754fe60SDimitry Andric GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc, 797f22ef01cSRoman Divacky bool isLoad, BasicBlock *BB, 798f22ef01cSRoman Divacky NonLocalDepInfo *Cache, unsigned NumSortedEntries) { 799f22ef01cSRoman Divacky 800f22ef01cSRoman Divacky // Do a binary search to see if we already have an entry for this block in 801f22ef01cSRoman Divacky // the cache set. If so, find it. 802f22ef01cSRoman Divacky NonLocalDepInfo::iterator Entry = 803f22ef01cSRoman Divacky std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries, 804f22ef01cSRoman Divacky NonLocalDepEntry(BB)); 805f22ef01cSRoman Divacky if (Entry != Cache->begin() && (Entry-1)->getBB() == BB) 806f22ef01cSRoman Divacky --Entry; 807f22ef01cSRoman Divacky 808f22ef01cSRoman Divacky NonLocalDepEntry *ExistingResult = 0; 809f22ef01cSRoman Divacky if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB) 810f22ef01cSRoman Divacky ExistingResult = &*Entry; 811f22ef01cSRoman Divacky 812f22ef01cSRoman Divacky // If we have a cached entry, and it is non-dirty, use it as the value for 813f22ef01cSRoman Divacky // this dependency. 814f22ef01cSRoman Divacky if (ExistingResult && !ExistingResult->getResult().isDirty()) { 815f22ef01cSRoman Divacky ++NumCacheNonLocalPtr; 816f22ef01cSRoman Divacky return ExistingResult->getResult(); 817f22ef01cSRoman Divacky } 818f22ef01cSRoman Divacky 819f22ef01cSRoman Divacky // Otherwise, we have to scan for the value. If we have a dirty cache 820f22ef01cSRoman Divacky // entry, start scanning from its position, otherwise we scan from the end 821f22ef01cSRoman Divacky // of the block. 822f22ef01cSRoman Divacky BasicBlock::iterator ScanPos = BB->end(); 823f22ef01cSRoman Divacky if (ExistingResult && ExistingResult->getResult().getInst()) { 824f22ef01cSRoman Divacky assert(ExistingResult->getResult().getInst()->getParent() == BB && 825f22ef01cSRoman Divacky "Instruction invalidated?"); 826f22ef01cSRoman Divacky ++NumCacheDirtyNonLocalPtr; 827f22ef01cSRoman Divacky ScanPos = ExistingResult->getResult().getInst(); 828f22ef01cSRoman Divacky 829f22ef01cSRoman Divacky // Eliminating the dirty entry from 'Cache', so update the reverse info. 8302754fe60SDimitry Andric ValueIsLoadPair CacheKey(Loc.Ptr, isLoad); 831f22ef01cSRoman Divacky RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey); 832f22ef01cSRoman Divacky } else { 833f22ef01cSRoman Divacky ++NumUncacheNonLocalPtr; 834f22ef01cSRoman Divacky } 835f22ef01cSRoman Divacky 836f22ef01cSRoman Divacky // Scan the block for the dependency. 8372754fe60SDimitry Andric MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB); 838f22ef01cSRoman Divacky 839f22ef01cSRoman Divacky // If we had a dirty entry for the block, update it. Otherwise, just add 840f22ef01cSRoman Divacky // a new entry. 841f22ef01cSRoman Divacky if (ExistingResult) 842f22ef01cSRoman Divacky ExistingResult->setResult(Dep); 843f22ef01cSRoman Divacky else 844f22ef01cSRoman Divacky Cache->push_back(NonLocalDepEntry(BB, Dep)); 845f22ef01cSRoman Divacky 846f22ef01cSRoman Divacky // If the block has a dependency (i.e. it isn't completely transparent to 847f22ef01cSRoman Divacky // the value), remember the reverse association because we just added it 848f22ef01cSRoman Divacky // to Cache! 8496122f3e6SDimitry Andric if (!Dep.isDef() && !Dep.isClobber()) 850f22ef01cSRoman Divacky return Dep; 851f22ef01cSRoman Divacky 852f22ef01cSRoman Divacky // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently 853f22ef01cSRoman Divacky // update MemDep when we remove instructions. 854f22ef01cSRoman Divacky Instruction *Inst = Dep.getInst(); 855f22ef01cSRoman Divacky assert(Inst && "Didn't depend on anything?"); 8562754fe60SDimitry Andric ValueIsLoadPair CacheKey(Loc.Ptr, isLoad); 857f22ef01cSRoman Divacky ReverseNonLocalPtrDeps[Inst].insert(CacheKey); 858f22ef01cSRoman Divacky return Dep; 859f22ef01cSRoman Divacky } 860f22ef01cSRoman Divacky 861f22ef01cSRoman Divacky /// SortNonLocalDepInfoCache - Sort the a NonLocalDepInfo cache, given a certain 862f22ef01cSRoman Divacky /// number of elements in the array that are already properly ordered. This is 863f22ef01cSRoman Divacky /// optimized for the case when only a few entries are added. 864f22ef01cSRoman Divacky static void 865f22ef01cSRoman Divacky SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache, 866f22ef01cSRoman Divacky unsigned NumSortedEntries) { 867f22ef01cSRoman Divacky switch (Cache.size() - NumSortedEntries) { 868f22ef01cSRoman Divacky case 0: 869f22ef01cSRoman Divacky // done, no new entries. 870f22ef01cSRoman Divacky break; 871f22ef01cSRoman Divacky case 2: { 872f22ef01cSRoman Divacky // Two new entries, insert the last one into place. 873f22ef01cSRoman Divacky NonLocalDepEntry Val = Cache.back(); 874f22ef01cSRoman Divacky Cache.pop_back(); 875f22ef01cSRoman Divacky MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry = 876f22ef01cSRoman Divacky std::upper_bound(Cache.begin(), Cache.end()-1, Val); 877f22ef01cSRoman Divacky Cache.insert(Entry, Val); 878f22ef01cSRoman Divacky // FALL THROUGH. 879f22ef01cSRoman Divacky } 880f22ef01cSRoman Divacky case 1: 881f22ef01cSRoman Divacky // One new entry, Just insert the new value at the appropriate position. 882f22ef01cSRoman Divacky if (Cache.size() != 1) { 883f22ef01cSRoman Divacky NonLocalDepEntry Val = Cache.back(); 884f22ef01cSRoman Divacky Cache.pop_back(); 885f22ef01cSRoman Divacky MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry = 886f22ef01cSRoman Divacky std::upper_bound(Cache.begin(), Cache.end(), Val); 887f22ef01cSRoman Divacky Cache.insert(Entry, Val); 888f22ef01cSRoman Divacky } 889f22ef01cSRoman Divacky break; 890f22ef01cSRoman Divacky default: 891f22ef01cSRoman Divacky // Added many values, do a full scale sort. 892f22ef01cSRoman Divacky std::sort(Cache.begin(), Cache.end()); 893f22ef01cSRoman Divacky break; 894f22ef01cSRoman Divacky } 895f22ef01cSRoman Divacky } 896f22ef01cSRoman Divacky 897f22ef01cSRoman Divacky /// getNonLocalPointerDepFromBB - Perform a dependency query based on 898f22ef01cSRoman Divacky /// pointer/pointeesize starting at the end of StartBB. Add any clobber/def 899f22ef01cSRoman Divacky /// results to the results vector and keep track of which blocks are visited in 900f22ef01cSRoman Divacky /// 'Visited'. 901f22ef01cSRoman Divacky /// 902f22ef01cSRoman Divacky /// This has special behavior for the first block queries (when SkipFirstBlock 903f22ef01cSRoman Divacky /// is true). In this special case, it ignores the contents of the specified 904f22ef01cSRoman Divacky /// block and starts returning dependence info for its predecessors. 905f22ef01cSRoman Divacky /// 906f22ef01cSRoman Divacky /// This function returns false on success, or true to indicate that it could 907f22ef01cSRoman Divacky /// not compute dependence information for some reason. This should be treated 908f22ef01cSRoman Divacky /// as a clobber dependence on the first instruction in the predecessor block. 909f22ef01cSRoman Divacky bool MemoryDependenceAnalysis:: 9102754fe60SDimitry Andric getNonLocalPointerDepFromBB(const PHITransAddr &Pointer, 9112754fe60SDimitry Andric const AliasAnalysis::Location &Loc, 912f22ef01cSRoman Divacky bool isLoad, BasicBlock *StartBB, 913f22ef01cSRoman Divacky SmallVectorImpl<NonLocalDepResult> &Result, 914f22ef01cSRoman Divacky DenseMap<BasicBlock*, Value*> &Visited, 915f22ef01cSRoman Divacky bool SkipFirstBlock) { 916f22ef01cSRoman Divacky 917f22ef01cSRoman Divacky // Look up the cached info for Pointer. 918f22ef01cSRoman Divacky ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad); 919f22ef01cSRoman Divacky 9202754fe60SDimitry Andric // Set up a temporary NLPI value. If the map doesn't yet have an entry for 9212754fe60SDimitry Andric // CacheKey, this value will be inserted as the associated value. Otherwise, 9222754fe60SDimitry Andric // it'll be ignored, and we'll have to check to see if the cached size and 9232754fe60SDimitry Andric // tbaa tag are consistent with the current query. 9242754fe60SDimitry Andric NonLocalPointerInfo InitialNLPI; 9252754fe60SDimitry Andric InitialNLPI.Size = Loc.Size; 9262754fe60SDimitry Andric InitialNLPI.TBAATag = Loc.TBAATag; 9272754fe60SDimitry Andric 9282754fe60SDimitry Andric // Get the NLPI for CacheKey, inserting one into the map if it doesn't 9292754fe60SDimitry Andric // already have one. 9302754fe60SDimitry Andric std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair = 9312754fe60SDimitry Andric NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI)); 9322754fe60SDimitry Andric NonLocalPointerInfo *CacheInfo = &Pair.first->second; 9332754fe60SDimitry Andric 9342754fe60SDimitry Andric // If we already have a cache entry for this CacheKey, we may need to do some 9352754fe60SDimitry Andric // work to reconcile the cache entry and the current query. 9362754fe60SDimitry Andric if (!Pair.second) { 9372754fe60SDimitry Andric if (CacheInfo->Size < Loc.Size) { 9382754fe60SDimitry Andric // The query's Size is greater than the cached one. Throw out the 9397ae0e2c9SDimitry Andric // cached data and proceed with the query at the greater size. 9402754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(); 9412754fe60SDimitry Andric CacheInfo->Size = Loc.Size; 9422754fe60SDimitry Andric for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(), 9432754fe60SDimitry Andric DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI) 9442754fe60SDimitry Andric if (Instruction *Inst = DI->getResult().getInst()) 9452754fe60SDimitry Andric RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey); 9462754fe60SDimitry Andric CacheInfo->NonLocalDeps.clear(); 9472754fe60SDimitry Andric } else if (CacheInfo->Size > Loc.Size) { 9482754fe60SDimitry Andric // This query's Size is less than the cached one. Conservatively restart 9492754fe60SDimitry Andric // the query using the greater size. 9502754fe60SDimitry Andric return getNonLocalPointerDepFromBB(Pointer, 9512754fe60SDimitry Andric Loc.getWithNewSize(CacheInfo->Size), 9522754fe60SDimitry Andric isLoad, StartBB, Result, Visited, 9532754fe60SDimitry Andric SkipFirstBlock); 9542754fe60SDimitry Andric } 9552754fe60SDimitry Andric 9562754fe60SDimitry Andric // If the query's TBAATag is inconsistent with the cached one, 9572754fe60SDimitry Andric // conservatively throw out the cached data and restart the query with 9582754fe60SDimitry Andric // no tag if needed. 9592754fe60SDimitry Andric if (CacheInfo->TBAATag != Loc.TBAATag) { 9602754fe60SDimitry Andric if (CacheInfo->TBAATag) { 9612754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(); 9622754fe60SDimitry Andric CacheInfo->TBAATag = 0; 9632754fe60SDimitry Andric for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(), 9642754fe60SDimitry Andric DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI) 9652754fe60SDimitry Andric if (Instruction *Inst = DI->getResult().getInst()) 9662754fe60SDimitry Andric RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey); 9672754fe60SDimitry Andric CacheInfo->NonLocalDeps.clear(); 9682754fe60SDimitry Andric } 9692754fe60SDimitry Andric if (Loc.TBAATag) 9702754fe60SDimitry Andric return getNonLocalPointerDepFromBB(Pointer, Loc.getWithoutTBAATag(), 9712754fe60SDimitry Andric isLoad, StartBB, Result, Visited, 9722754fe60SDimitry Andric SkipFirstBlock); 9732754fe60SDimitry Andric } 9742754fe60SDimitry Andric } 9752754fe60SDimitry Andric 9762754fe60SDimitry Andric NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps; 977f22ef01cSRoman Divacky 978f22ef01cSRoman Divacky // If we have valid cached information for exactly the block we are 979f22ef01cSRoman Divacky // investigating, just return it with no recomputation. 9802754fe60SDimitry Andric if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) { 981f22ef01cSRoman Divacky // We have a fully cached result for this query then we can just return the 982f22ef01cSRoman Divacky // cached results and populate the visited set. However, we have to verify 983f22ef01cSRoman Divacky // that we don't already have conflicting results for these blocks. Check 984f22ef01cSRoman Divacky // to ensure that if a block in the results set is in the visited set that 985f22ef01cSRoman Divacky // it was for the same pointer query. 986f22ef01cSRoman Divacky if (!Visited.empty()) { 987f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end(); 988f22ef01cSRoman Divacky I != E; ++I) { 989f22ef01cSRoman Divacky DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB()); 990f22ef01cSRoman Divacky if (VI == Visited.end() || VI->second == Pointer.getAddr()) 991f22ef01cSRoman Divacky continue; 992f22ef01cSRoman Divacky 993f22ef01cSRoman Divacky // We have a pointer mismatch in a block. Just return clobber, saying 994f22ef01cSRoman Divacky // that something was clobbered in this result. We could also do a 995f22ef01cSRoman Divacky // non-fully cached query, but there is little point in doing this. 996f22ef01cSRoman Divacky return true; 997f22ef01cSRoman Divacky } 998f22ef01cSRoman Divacky } 999f22ef01cSRoman Divacky 1000f22ef01cSRoman Divacky Value *Addr = Pointer.getAddr(); 1001f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end(); 1002f22ef01cSRoman Divacky I != E; ++I) { 1003f22ef01cSRoman Divacky Visited.insert(std::make_pair(I->getBB(), Addr)); 10043861d79fSDimitry Andric if (!I->getResult().isNonLocal() && DT->isReachableFromEntry(I->getBB())) 1005f22ef01cSRoman Divacky Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr)); 1006f22ef01cSRoman Divacky } 1007f22ef01cSRoman Divacky ++NumCacheCompleteNonLocalPtr; 1008f22ef01cSRoman Divacky return false; 1009f22ef01cSRoman Divacky } 1010f22ef01cSRoman Divacky 1011f22ef01cSRoman Divacky // Otherwise, either this is a new block, a block with an invalid cache 1012f22ef01cSRoman Divacky // pointer or one that we're about to invalidate by putting more info into it 1013f22ef01cSRoman Divacky // than its valid cache info. If empty, the result will be valid cache info, 1014f22ef01cSRoman Divacky // otherwise it isn't. 1015f22ef01cSRoman Divacky if (Cache->empty()) 10162754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock); 1017f22ef01cSRoman Divacky else 10182754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(); 1019f22ef01cSRoman Divacky 1020f22ef01cSRoman Divacky SmallVector<BasicBlock*, 32> Worklist; 1021f22ef01cSRoman Divacky Worklist.push_back(StartBB); 1022f22ef01cSRoman Divacky 1023bd5abe19SDimitry Andric // PredList used inside loop. 1024bd5abe19SDimitry Andric SmallVector<std::pair<BasicBlock*, PHITransAddr>, 16> PredList; 1025bd5abe19SDimitry Andric 1026f22ef01cSRoman Divacky // Keep track of the entries that we know are sorted. Previously cached 1027f22ef01cSRoman Divacky // entries will all be sorted. The entries we add we only sort on demand (we 1028f22ef01cSRoman Divacky // don't insert every element into its sorted position). We know that we 1029f22ef01cSRoman Divacky // won't get any reuse from currently inserted values, because we don't 1030f22ef01cSRoman Divacky // revisit blocks after we insert info for them. 1031f22ef01cSRoman Divacky unsigned NumSortedEntries = Cache->size(); 1032f22ef01cSRoman Divacky DEBUG(AssertSorted(*Cache)); 1033f22ef01cSRoman Divacky 1034f22ef01cSRoman Divacky while (!Worklist.empty()) { 1035f22ef01cSRoman Divacky BasicBlock *BB = Worklist.pop_back_val(); 1036f22ef01cSRoman Divacky 1037f22ef01cSRoman Divacky // Skip the first block if we have it. 1038f22ef01cSRoman Divacky if (!SkipFirstBlock) { 1039f22ef01cSRoman Divacky // Analyze the dependency of *Pointer in FromBB. See if we already have 1040f22ef01cSRoman Divacky // been here. 1041f22ef01cSRoman Divacky assert(Visited.count(BB) && "Should check 'visited' before adding to WL"); 1042f22ef01cSRoman Divacky 1043f22ef01cSRoman Divacky // Get the dependency info for Pointer in BB. If we have cached 1044f22ef01cSRoman Divacky // information, we will use it, otherwise we compute it. 1045f22ef01cSRoman Divacky DEBUG(AssertSorted(*Cache, NumSortedEntries)); 10462754fe60SDimitry Andric MemDepResult Dep = GetNonLocalInfoForBlock(Loc, isLoad, BB, Cache, 1047f22ef01cSRoman Divacky NumSortedEntries); 1048f22ef01cSRoman Divacky 1049f22ef01cSRoman Divacky // If we got a Def or Clobber, add this to the list of results. 10503861d79fSDimitry Andric if (!Dep.isNonLocal() && DT->isReachableFromEntry(BB)) { 1051f22ef01cSRoman Divacky Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr())); 1052f22ef01cSRoman Divacky continue; 1053f22ef01cSRoman Divacky } 1054f22ef01cSRoman Divacky } 1055f22ef01cSRoman Divacky 1056f22ef01cSRoman Divacky // If 'Pointer' is an instruction defined in this block, then we need to do 1057f22ef01cSRoman Divacky // phi translation to change it into a value live in the predecessor block. 1058f22ef01cSRoman Divacky // If not, we just add the predecessors to the worklist and scan them with 1059f22ef01cSRoman Divacky // the same Pointer. 1060f22ef01cSRoman Divacky if (!Pointer.NeedsPHITranslationFromBlock(BB)) { 1061f22ef01cSRoman Divacky SkipFirstBlock = false; 1062bd5abe19SDimitry Andric SmallVector<BasicBlock*, 16> NewBlocks; 1063f22ef01cSRoman Divacky for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) { 1064f22ef01cSRoman Divacky // Verify that we haven't looked at this block yet. 1065f22ef01cSRoman Divacky std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool> 1066f22ef01cSRoman Divacky InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr())); 1067f22ef01cSRoman Divacky if (InsertRes.second) { 1068f22ef01cSRoman Divacky // First time we've looked at *PI. 1069bd5abe19SDimitry Andric NewBlocks.push_back(*PI); 1070f22ef01cSRoman Divacky continue; 1071f22ef01cSRoman Divacky } 1072f22ef01cSRoman Divacky 1073f22ef01cSRoman Divacky // If we have seen this block before, but it was with a different 1074f22ef01cSRoman Divacky // pointer then we have a phi translation failure and we have to treat 1075f22ef01cSRoman Divacky // this as a clobber. 1076bd5abe19SDimitry Andric if (InsertRes.first->second != Pointer.getAddr()) { 1077bd5abe19SDimitry Andric // Make sure to clean up the Visited map before continuing on to 1078bd5abe19SDimitry Andric // PredTranslationFailure. 1079bd5abe19SDimitry Andric for (unsigned i = 0; i < NewBlocks.size(); i++) 1080bd5abe19SDimitry Andric Visited.erase(NewBlocks[i]); 1081f22ef01cSRoman Divacky goto PredTranslationFailure; 1082f22ef01cSRoman Divacky } 1083bd5abe19SDimitry Andric } 1084bd5abe19SDimitry Andric Worklist.append(NewBlocks.begin(), NewBlocks.end()); 1085f22ef01cSRoman Divacky continue; 1086f22ef01cSRoman Divacky } 1087f22ef01cSRoman Divacky 1088f22ef01cSRoman Divacky // We do need to do phi translation, if we know ahead of time we can't phi 1089f22ef01cSRoman Divacky // translate this value, don't even try. 1090f22ef01cSRoman Divacky if (!Pointer.IsPotentiallyPHITranslatable()) 1091f22ef01cSRoman Divacky goto PredTranslationFailure; 1092f22ef01cSRoman Divacky 1093f22ef01cSRoman Divacky // We may have added values to the cache list before this PHI translation. 1094f22ef01cSRoman Divacky // If so, we haven't done anything to ensure that the cache remains sorted. 1095f22ef01cSRoman Divacky // Sort it now (if needed) so that recursive invocations of 1096f22ef01cSRoman Divacky // getNonLocalPointerDepFromBB and other routines that could reuse the cache 1097f22ef01cSRoman Divacky // value will only see properly sorted cache arrays. 1098f22ef01cSRoman Divacky if (Cache && NumSortedEntries != Cache->size()) { 1099f22ef01cSRoman Divacky SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 1100f22ef01cSRoman Divacky NumSortedEntries = Cache->size(); 1101f22ef01cSRoman Divacky } 1102f22ef01cSRoman Divacky Cache = 0; 1103f22ef01cSRoman Divacky 1104bd5abe19SDimitry Andric PredList.clear(); 1105f22ef01cSRoman Divacky for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) { 1106f22ef01cSRoman Divacky BasicBlock *Pred = *PI; 1107bd5abe19SDimitry Andric PredList.push_back(std::make_pair(Pred, Pointer)); 1108f22ef01cSRoman Divacky 1109f22ef01cSRoman Divacky // Get the PHI translated pointer in this predecessor. This can fail if 1110f22ef01cSRoman Divacky // not translatable, in which case the getAddr() returns null. 1111bd5abe19SDimitry Andric PHITransAddr &PredPointer = PredList.back().second; 1112f22ef01cSRoman Divacky PredPointer.PHITranslateValue(BB, Pred, 0); 1113f22ef01cSRoman Divacky 1114f22ef01cSRoman Divacky Value *PredPtrVal = PredPointer.getAddr(); 1115f22ef01cSRoman Divacky 1116f22ef01cSRoman Divacky // Check to see if we have already visited this pred block with another 1117f22ef01cSRoman Divacky // pointer. If so, we can't do this lookup. This failure can occur 1118f22ef01cSRoman Divacky // with PHI translation when a critical edge exists and the PHI node in 1119f22ef01cSRoman Divacky // the successor translates to a pointer value different than the 1120f22ef01cSRoman Divacky // pointer the block was first analyzed with. 1121f22ef01cSRoman Divacky std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool> 1122f22ef01cSRoman Divacky InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal)); 1123f22ef01cSRoman Divacky 1124f22ef01cSRoman Divacky if (!InsertRes.second) { 1125bd5abe19SDimitry Andric // We found the pred; take it off the list of preds to visit. 1126bd5abe19SDimitry Andric PredList.pop_back(); 1127bd5abe19SDimitry Andric 1128f22ef01cSRoman Divacky // If the predecessor was visited with PredPtr, then we already did 1129f22ef01cSRoman Divacky // the analysis and can ignore it. 1130f22ef01cSRoman Divacky if (InsertRes.first->second == PredPtrVal) 1131f22ef01cSRoman Divacky continue; 1132f22ef01cSRoman Divacky 1133f22ef01cSRoman Divacky // Otherwise, the block was previously analyzed with a different 1134f22ef01cSRoman Divacky // pointer. We can't represent the result of this case, so we just 1135f22ef01cSRoman Divacky // treat this as a phi translation failure. 1136bd5abe19SDimitry Andric 1137bd5abe19SDimitry Andric // Make sure to clean up the Visited map before continuing on to 1138bd5abe19SDimitry Andric // PredTranslationFailure. 1139139f7f9bSDimitry Andric for (unsigned i = 0, n = PredList.size(); i < n; ++i) 1140bd5abe19SDimitry Andric Visited.erase(PredList[i].first); 1141bd5abe19SDimitry Andric 1142f22ef01cSRoman Divacky goto PredTranslationFailure; 1143f22ef01cSRoman Divacky } 1144bd5abe19SDimitry Andric } 1145f22ef01cSRoman Divacky 1146bd5abe19SDimitry Andric // Actually process results here; this need to be a separate loop to avoid 1147bd5abe19SDimitry Andric // calling getNonLocalPointerDepFromBB for blocks we don't want to return 1148bd5abe19SDimitry Andric // any results for. (getNonLocalPointerDepFromBB will modify our 1149bd5abe19SDimitry Andric // datastructures in ways the code after the PredTranslationFailure label 1150bd5abe19SDimitry Andric // doesn't expect.) 1151139f7f9bSDimitry Andric for (unsigned i = 0, n = PredList.size(); i < n; ++i) { 1152bd5abe19SDimitry Andric BasicBlock *Pred = PredList[i].first; 1153bd5abe19SDimitry Andric PHITransAddr &PredPointer = PredList[i].second; 1154bd5abe19SDimitry Andric Value *PredPtrVal = PredPointer.getAddr(); 1155bd5abe19SDimitry Andric 1156bd5abe19SDimitry Andric bool CanTranslate = true; 1157f22ef01cSRoman Divacky // If PHI translation was unable to find an available pointer in this 1158f22ef01cSRoman Divacky // predecessor, then we have to assume that the pointer is clobbered in 1159f22ef01cSRoman Divacky // that predecessor. We can still do PRE of the load, which would insert 1160f22ef01cSRoman Divacky // a computation of the pointer in this predecessor. 1161bd5abe19SDimitry Andric if (PredPtrVal == 0) 1162bd5abe19SDimitry Andric CanTranslate = false; 1163bd5abe19SDimitry Andric 1164bd5abe19SDimitry Andric // FIXME: it is entirely possible that PHI translating will end up with 1165bd5abe19SDimitry Andric // the same value. Consider PHI translating something like: 1166bd5abe19SDimitry Andric // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need* 1167bd5abe19SDimitry Andric // to recurse here, pedantically speaking. 1168bd5abe19SDimitry Andric 1169bd5abe19SDimitry Andric // If getNonLocalPointerDepFromBB fails here, that means the cached 1170bd5abe19SDimitry Andric // result conflicted with the Visited list; we have to conservatively 117117a519f9SDimitry Andric // assume it is unknown, but this also does not block PRE of the load. 1172bd5abe19SDimitry Andric if (!CanTranslate || 1173bd5abe19SDimitry Andric getNonLocalPointerDepFromBB(PredPointer, 1174bd5abe19SDimitry Andric Loc.getWithNewPtr(PredPtrVal), 1175bd5abe19SDimitry Andric isLoad, Pred, 1176bd5abe19SDimitry Andric Result, Visited)) { 1177f22ef01cSRoman Divacky // Add the entry to the Result list. 117817a519f9SDimitry Andric NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal); 1179f22ef01cSRoman Divacky Result.push_back(Entry); 1180f22ef01cSRoman Divacky 1181f22ef01cSRoman Divacky // Since we had a phi translation failure, the cache for CacheKey won't 1182f22ef01cSRoman Divacky // include all of the entries that we need to immediately satisfy future 1183f22ef01cSRoman Divacky // queries. Mark this in NonLocalPointerDeps by setting the 1184f22ef01cSRoman Divacky // BBSkipFirstBlockPair pointer to null. This requires reuse of the 1185f22ef01cSRoman Divacky // cached value to do more work but not miss the phi trans failure. 11862754fe60SDimitry Andric NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey]; 11872754fe60SDimitry Andric NLPI.Pair = BBSkipFirstBlockPair(); 1188f22ef01cSRoman Divacky continue; 1189f22ef01cSRoman Divacky } 1190f22ef01cSRoman Divacky } 1191f22ef01cSRoman Divacky 1192f22ef01cSRoman Divacky // Refresh the CacheInfo/Cache pointer so that it isn't invalidated. 1193f22ef01cSRoman Divacky CacheInfo = &NonLocalPointerDeps[CacheKey]; 11942754fe60SDimitry Andric Cache = &CacheInfo->NonLocalDeps; 1195f22ef01cSRoman Divacky NumSortedEntries = Cache->size(); 1196f22ef01cSRoman Divacky 1197f22ef01cSRoman Divacky // Since we did phi translation, the "Cache" set won't contain all of the 1198f22ef01cSRoman Divacky // results for the query. This is ok (we can still use it to accelerate 1199f22ef01cSRoman Divacky // specific block queries) but we can't do the fastpath "return all 1200f22ef01cSRoman Divacky // results from the set" Clear out the indicator for this. 12012754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(); 1202f22ef01cSRoman Divacky SkipFirstBlock = false; 1203f22ef01cSRoman Divacky continue; 1204f22ef01cSRoman Divacky 1205f22ef01cSRoman Divacky PredTranslationFailure: 1206bd5abe19SDimitry Andric // The following code is "failure"; we can't produce a sane translation 1207bd5abe19SDimitry Andric // for the given block. It assumes that we haven't modified any of 1208bd5abe19SDimitry Andric // our datastructures while processing the current block. 1209f22ef01cSRoman Divacky 1210f22ef01cSRoman Divacky if (Cache == 0) { 1211f22ef01cSRoman Divacky // Refresh the CacheInfo/Cache pointer if it got invalidated. 1212f22ef01cSRoman Divacky CacheInfo = &NonLocalPointerDeps[CacheKey]; 12132754fe60SDimitry Andric Cache = &CacheInfo->NonLocalDeps; 1214f22ef01cSRoman Divacky NumSortedEntries = Cache->size(); 1215f22ef01cSRoman Divacky } 1216f22ef01cSRoman Divacky 1217f22ef01cSRoman Divacky // Since we failed phi translation, the "Cache" set won't contain all of the 1218f22ef01cSRoman Divacky // results for the query. This is ok (we can still use it to accelerate 1219f22ef01cSRoman Divacky // specific block queries) but we can't do the fastpath "return all 1220f22ef01cSRoman Divacky // results from the set". Clear out the indicator for this. 12212754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(); 1222f22ef01cSRoman Divacky 122317a519f9SDimitry Andric // If *nothing* works, mark the pointer as unknown. 1224f22ef01cSRoman Divacky // 1225f22ef01cSRoman Divacky // If this is the magic first block, return this as a clobber of the whole 1226f22ef01cSRoman Divacky // incoming value. Since we can't phi translate to one of the predecessors, 1227f22ef01cSRoman Divacky // we have to bail out. 1228f22ef01cSRoman Divacky if (SkipFirstBlock) 1229f22ef01cSRoman Divacky return true; 1230f22ef01cSRoman Divacky 1231f22ef01cSRoman Divacky for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) { 1232f22ef01cSRoman Divacky assert(I != Cache->rend() && "Didn't find current block??"); 1233f22ef01cSRoman Divacky if (I->getBB() != BB) 1234f22ef01cSRoman Divacky continue; 1235f22ef01cSRoman Divacky 1236f22ef01cSRoman Divacky assert(I->getResult().isNonLocal() && 1237f22ef01cSRoman Divacky "Should only be here with transparent block"); 123817a519f9SDimitry Andric I->setResult(MemDepResult::getUnknown()); 1239f22ef01cSRoman Divacky Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), 1240f22ef01cSRoman Divacky Pointer.getAddr())); 1241f22ef01cSRoman Divacky break; 1242f22ef01cSRoman Divacky } 1243f22ef01cSRoman Divacky } 1244f22ef01cSRoman Divacky 1245f22ef01cSRoman Divacky // Okay, we're done now. If we added new values to the cache, re-sort it. 1246f22ef01cSRoman Divacky SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 1247f22ef01cSRoman Divacky DEBUG(AssertSorted(*Cache)); 1248f22ef01cSRoman Divacky return false; 1249f22ef01cSRoman Divacky } 1250f22ef01cSRoman Divacky 1251f22ef01cSRoman Divacky /// RemoveCachedNonLocalPointerDependencies - If P exists in 1252f22ef01cSRoman Divacky /// CachedNonLocalPointerInfo, remove it. 1253f22ef01cSRoman Divacky void MemoryDependenceAnalysis:: 1254f22ef01cSRoman Divacky RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) { 1255f22ef01cSRoman Divacky CachedNonLocalPointerInfo::iterator It = 1256f22ef01cSRoman Divacky NonLocalPointerDeps.find(P); 1257f22ef01cSRoman Divacky if (It == NonLocalPointerDeps.end()) return; 1258f22ef01cSRoman Divacky 1259f22ef01cSRoman Divacky // Remove all of the entries in the BB->val map. This involves removing 1260f22ef01cSRoman Divacky // instructions from the reverse map. 12612754fe60SDimitry Andric NonLocalDepInfo &PInfo = It->second.NonLocalDeps; 1262f22ef01cSRoman Divacky 1263f22ef01cSRoman Divacky for (unsigned i = 0, e = PInfo.size(); i != e; ++i) { 1264f22ef01cSRoman Divacky Instruction *Target = PInfo[i].getResult().getInst(); 1265f22ef01cSRoman Divacky if (Target == 0) continue; // Ignore non-local dep results. 1266f22ef01cSRoman Divacky assert(Target->getParent() == PInfo[i].getBB()); 1267f22ef01cSRoman Divacky 1268f22ef01cSRoman Divacky // Eliminating the dirty entry from 'Cache', so update the reverse info. 1269f22ef01cSRoman Divacky RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P); 1270f22ef01cSRoman Divacky } 1271f22ef01cSRoman Divacky 1272f22ef01cSRoman Divacky // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo). 1273f22ef01cSRoman Divacky NonLocalPointerDeps.erase(It); 1274f22ef01cSRoman Divacky } 1275f22ef01cSRoman Divacky 1276f22ef01cSRoman Divacky 1277f22ef01cSRoman Divacky /// invalidateCachedPointerInfo - This method is used to invalidate cached 1278f22ef01cSRoman Divacky /// information about the specified pointer, because it may be too 1279f22ef01cSRoman Divacky /// conservative in memdep. This is an optional call that can be used when 1280f22ef01cSRoman Divacky /// the client detects an equivalence between the pointer and some other 1281f22ef01cSRoman Divacky /// value and replaces the other value with ptr. This can make Ptr available 1282f22ef01cSRoman Divacky /// in more places that cached info does not necessarily keep. 1283f22ef01cSRoman Divacky void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) { 1284f22ef01cSRoman Divacky // If Ptr isn't really a pointer, just ignore it. 1285f22ef01cSRoman Divacky if (!Ptr->getType()->isPointerTy()) return; 1286f22ef01cSRoman Divacky // Flush store info for the pointer. 1287f22ef01cSRoman Divacky RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false)); 1288f22ef01cSRoman Divacky // Flush load info for the pointer. 1289f22ef01cSRoman Divacky RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true)); 1290f22ef01cSRoman Divacky } 1291f22ef01cSRoman Divacky 1292f22ef01cSRoman Divacky /// invalidateCachedPredecessors - Clear the PredIteratorCache info. 1293f22ef01cSRoman Divacky /// This needs to be done when the CFG changes, e.g., due to splitting 1294f22ef01cSRoman Divacky /// critical edges. 1295f22ef01cSRoman Divacky void MemoryDependenceAnalysis::invalidateCachedPredecessors() { 1296f22ef01cSRoman Divacky PredCache->clear(); 1297f22ef01cSRoman Divacky } 1298f22ef01cSRoman Divacky 1299f22ef01cSRoman Divacky /// removeInstruction - Remove an instruction from the dependence analysis, 1300f22ef01cSRoman Divacky /// updating the dependence of instructions that previously depended on it. 1301f22ef01cSRoman Divacky /// This method attempts to keep the cache coherent using the reverse map. 1302f22ef01cSRoman Divacky void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) { 1303f22ef01cSRoman Divacky // Walk through the Non-local dependencies, removing this one as the value 1304f22ef01cSRoman Divacky // for any cached queries. 1305f22ef01cSRoman Divacky NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst); 1306f22ef01cSRoman Divacky if (NLDI != NonLocalDeps.end()) { 1307f22ef01cSRoman Divacky NonLocalDepInfo &BlockMap = NLDI->second.first; 1308f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end(); 1309f22ef01cSRoman Divacky DI != DE; ++DI) 1310f22ef01cSRoman Divacky if (Instruction *Inst = DI->getResult().getInst()) 1311f22ef01cSRoman Divacky RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst); 1312f22ef01cSRoman Divacky NonLocalDeps.erase(NLDI); 1313f22ef01cSRoman Divacky } 1314f22ef01cSRoman Divacky 1315f22ef01cSRoman Divacky // If we have a cached local dependence query for this instruction, remove it. 1316f22ef01cSRoman Divacky // 1317f22ef01cSRoman Divacky LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst); 1318f22ef01cSRoman Divacky if (LocalDepEntry != LocalDeps.end()) { 1319f22ef01cSRoman Divacky // Remove us from DepInst's reverse set now that the local dep info is gone. 1320f22ef01cSRoman Divacky if (Instruction *Inst = LocalDepEntry->second.getInst()) 1321f22ef01cSRoman Divacky RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst); 1322f22ef01cSRoman Divacky 1323f22ef01cSRoman Divacky // Remove this local dependency info. 1324f22ef01cSRoman Divacky LocalDeps.erase(LocalDepEntry); 1325f22ef01cSRoman Divacky } 1326f22ef01cSRoman Divacky 1327f22ef01cSRoman Divacky // If we have any cached pointer dependencies on this instruction, remove 1328f22ef01cSRoman Divacky // them. If the instruction has non-pointer type, then it can't be a pointer 1329f22ef01cSRoman Divacky // base. 1330f22ef01cSRoman Divacky 1331f22ef01cSRoman Divacky // Remove it from both the load info and the store info. The instruction 1332f22ef01cSRoman Divacky // can't be in either of these maps if it is non-pointer. 1333f22ef01cSRoman Divacky if (RemInst->getType()->isPointerTy()) { 1334f22ef01cSRoman Divacky RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false)); 1335f22ef01cSRoman Divacky RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true)); 1336f22ef01cSRoman Divacky } 1337f22ef01cSRoman Divacky 1338f22ef01cSRoman Divacky // Loop over all of the things that depend on the instruction we're removing. 1339f22ef01cSRoman Divacky // 1340f22ef01cSRoman Divacky SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd; 1341f22ef01cSRoman Divacky 1342f22ef01cSRoman Divacky // If we find RemInst as a clobber or Def in any of the maps for other values, 1343f22ef01cSRoman Divacky // we need to replace its entry with a dirty version of the instruction after 1344f22ef01cSRoman Divacky // it. If RemInst is a terminator, we use a null dirty value. 1345f22ef01cSRoman Divacky // 1346f22ef01cSRoman Divacky // Using a dirty version of the instruction after RemInst saves having to scan 1347f22ef01cSRoman Divacky // the entire block to get to this point. 1348f22ef01cSRoman Divacky MemDepResult NewDirtyVal; 1349f22ef01cSRoman Divacky if (!RemInst->isTerminator()) 1350f22ef01cSRoman Divacky NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst)); 1351f22ef01cSRoman Divacky 1352f22ef01cSRoman Divacky ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst); 1353f22ef01cSRoman Divacky if (ReverseDepIt != ReverseLocalDeps.end()) { 1354f22ef01cSRoman Divacky SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second; 1355f22ef01cSRoman Divacky // RemInst can't be the terminator if it has local stuff depending on it. 1356f22ef01cSRoman Divacky assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) && 1357f22ef01cSRoman Divacky "Nothing can locally depend on a terminator"); 1358f22ef01cSRoman Divacky 1359f22ef01cSRoman Divacky for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(), 1360f22ef01cSRoman Divacky E = ReverseDeps.end(); I != E; ++I) { 1361f22ef01cSRoman Divacky Instruction *InstDependingOnRemInst = *I; 1362f22ef01cSRoman Divacky assert(InstDependingOnRemInst != RemInst && 1363f22ef01cSRoman Divacky "Already removed our local dep info"); 1364f22ef01cSRoman Divacky 1365f22ef01cSRoman Divacky LocalDeps[InstDependingOnRemInst] = NewDirtyVal; 1366f22ef01cSRoman Divacky 1367f22ef01cSRoman Divacky // Make sure to remember that new things depend on NewDepInst. 1368f22ef01cSRoman Divacky assert(NewDirtyVal.getInst() && "There is no way something else can have " 1369f22ef01cSRoman Divacky "a local dep on this if it is a terminator!"); 1370f22ef01cSRoman Divacky ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(), 1371f22ef01cSRoman Divacky InstDependingOnRemInst)); 1372f22ef01cSRoman Divacky } 1373f22ef01cSRoman Divacky 1374f22ef01cSRoman Divacky ReverseLocalDeps.erase(ReverseDepIt); 1375f22ef01cSRoman Divacky 1376f22ef01cSRoman Divacky // Add new reverse deps after scanning the set, to avoid invalidating the 1377f22ef01cSRoman Divacky // 'ReverseDeps' reference. 1378f22ef01cSRoman Divacky while (!ReverseDepsToAdd.empty()) { 1379f22ef01cSRoman Divacky ReverseLocalDeps[ReverseDepsToAdd.back().first] 1380f22ef01cSRoman Divacky .insert(ReverseDepsToAdd.back().second); 1381f22ef01cSRoman Divacky ReverseDepsToAdd.pop_back(); 1382f22ef01cSRoman Divacky } 1383f22ef01cSRoman Divacky } 1384f22ef01cSRoman Divacky 1385f22ef01cSRoman Divacky ReverseDepIt = ReverseNonLocalDeps.find(RemInst); 1386f22ef01cSRoman Divacky if (ReverseDepIt != ReverseNonLocalDeps.end()) { 1387f22ef01cSRoman Divacky SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second; 1388f22ef01cSRoman Divacky for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end(); 1389f22ef01cSRoman Divacky I != E; ++I) { 1390f22ef01cSRoman Divacky assert(*I != RemInst && "Already removed NonLocalDep info for RemInst"); 1391f22ef01cSRoman Divacky 1392f22ef01cSRoman Divacky PerInstNLInfo &INLD = NonLocalDeps[*I]; 1393f22ef01cSRoman Divacky // The information is now dirty! 1394f22ef01cSRoman Divacky INLD.second = true; 1395f22ef01cSRoman Divacky 1396f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator DI = INLD.first.begin(), 1397f22ef01cSRoman Divacky DE = INLD.first.end(); DI != DE; ++DI) { 1398f22ef01cSRoman Divacky if (DI->getResult().getInst() != RemInst) continue; 1399f22ef01cSRoman Divacky 1400f22ef01cSRoman Divacky // Convert to a dirty entry for the subsequent instruction. 1401f22ef01cSRoman Divacky DI->setResult(NewDirtyVal); 1402f22ef01cSRoman Divacky 1403f22ef01cSRoman Divacky if (Instruction *NextI = NewDirtyVal.getInst()) 1404f22ef01cSRoman Divacky ReverseDepsToAdd.push_back(std::make_pair(NextI, *I)); 1405f22ef01cSRoman Divacky } 1406f22ef01cSRoman Divacky } 1407f22ef01cSRoman Divacky 1408f22ef01cSRoman Divacky ReverseNonLocalDeps.erase(ReverseDepIt); 1409f22ef01cSRoman Divacky 1410f22ef01cSRoman Divacky // Add new reverse deps after scanning the set, to avoid invalidating 'Set' 1411f22ef01cSRoman Divacky while (!ReverseDepsToAdd.empty()) { 1412f22ef01cSRoman Divacky ReverseNonLocalDeps[ReverseDepsToAdd.back().first] 1413f22ef01cSRoman Divacky .insert(ReverseDepsToAdd.back().second); 1414f22ef01cSRoman Divacky ReverseDepsToAdd.pop_back(); 1415f22ef01cSRoman Divacky } 1416f22ef01cSRoman Divacky } 1417f22ef01cSRoman Divacky 1418f22ef01cSRoman Divacky // If the instruction is in ReverseNonLocalPtrDeps then it appears as a 1419f22ef01cSRoman Divacky // value in the NonLocalPointerDeps info. 1420f22ef01cSRoman Divacky ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt = 1421f22ef01cSRoman Divacky ReverseNonLocalPtrDeps.find(RemInst); 1422f22ef01cSRoman Divacky if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) { 1423f22ef01cSRoman Divacky SmallPtrSet<ValueIsLoadPair, 4> &Set = ReversePtrDepIt->second; 1424f22ef01cSRoman Divacky SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd; 1425f22ef01cSRoman Divacky 1426f22ef01cSRoman Divacky for (SmallPtrSet<ValueIsLoadPair, 4>::iterator I = Set.begin(), 1427f22ef01cSRoman Divacky E = Set.end(); I != E; ++I) { 1428f22ef01cSRoman Divacky ValueIsLoadPair P = *I; 1429f22ef01cSRoman Divacky assert(P.getPointer() != RemInst && 1430f22ef01cSRoman Divacky "Already removed NonLocalPointerDeps info for RemInst"); 1431f22ef01cSRoman Divacky 14322754fe60SDimitry Andric NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps; 1433f22ef01cSRoman Divacky 1434f22ef01cSRoman Divacky // The cache is not valid for any specific block anymore. 14352754fe60SDimitry Andric NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair(); 1436f22ef01cSRoman Divacky 1437f22ef01cSRoman Divacky // Update any entries for RemInst to use the instruction after it. 1438f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end(); 1439f22ef01cSRoman Divacky DI != DE; ++DI) { 1440f22ef01cSRoman Divacky if (DI->getResult().getInst() != RemInst) continue; 1441f22ef01cSRoman Divacky 1442f22ef01cSRoman Divacky // Convert to a dirty entry for the subsequent instruction. 1443f22ef01cSRoman Divacky DI->setResult(NewDirtyVal); 1444f22ef01cSRoman Divacky 1445f22ef01cSRoman Divacky if (Instruction *NewDirtyInst = NewDirtyVal.getInst()) 1446f22ef01cSRoman Divacky ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P)); 1447f22ef01cSRoman Divacky } 1448f22ef01cSRoman Divacky 1449f22ef01cSRoman Divacky // Re-sort the NonLocalDepInfo. Changing the dirty entry to its 1450f22ef01cSRoman Divacky // subsequent value may invalidate the sortedness. 1451f22ef01cSRoman Divacky std::sort(NLPDI.begin(), NLPDI.end()); 1452f22ef01cSRoman Divacky } 1453f22ef01cSRoman Divacky 1454f22ef01cSRoman Divacky ReverseNonLocalPtrDeps.erase(ReversePtrDepIt); 1455f22ef01cSRoman Divacky 1456f22ef01cSRoman Divacky while (!ReversePtrDepsToAdd.empty()) { 1457f22ef01cSRoman Divacky ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first] 1458f22ef01cSRoman Divacky .insert(ReversePtrDepsToAdd.back().second); 1459f22ef01cSRoman Divacky ReversePtrDepsToAdd.pop_back(); 1460f22ef01cSRoman Divacky } 1461f22ef01cSRoman Divacky } 1462f22ef01cSRoman Divacky 1463f22ef01cSRoman Divacky 1464f22ef01cSRoman Divacky assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?"); 1465f22ef01cSRoman Divacky AA->deleteValue(RemInst); 1466f22ef01cSRoman Divacky DEBUG(verifyRemoved(RemInst)); 1467f22ef01cSRoman Divacky } 1468f22ef01cSRoman Divacky /// verifyRemoved - Verify that the specified instruction does not occur 1469f22ef01cSRoman Divacky /// in our internal data structures. 1470f22ef01cSRoman Divacky void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const { 1471f22ef01cSRoman Divacky for (LocalDepMapType::const_iterator I = LocalDeps.begin(), 1472f22ef01cSRoman Divacky E = LocalDeps.end(); I != E; ++I) { 1473f22ef01cSRoman Divacky assert(I->first != D && "Inst occurs in data structures"); 1474f22ef01cSRoman Divacky assert(I->second.getInst() != D && 1475f22ef01cSRoman Divacky "Inst occurs in data structures"); 1476f22ef01cSRoman Divacky } 1477f22ef01cSRoman Divacky 1478f22ef01cSRoman Divacky for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(), 1479f22ef01cSRoman Divacky E = NonLocalPointerDeps.end(); I != E; ++I) { 1480f22ef01cSRoman Divacky assert(I->first.getPointer() != D && "Inst occurs in NLPD map key"); 14812754fe60SDimitry Andric const NonLocalDepInfo &Val = I->second.NonLocalDeps; 1482f22ef01cSRoman Divacky for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end(); 1483f22ef01cSRoman Divacky II != E; ++II) 1484f22ef01cSRoman Divacky assert(II->getResult().getInst() != D && "Inst occurs as NLPD value"); 1485f22ef01cSRoman Divacky } 1486f22ef01cSRoman Divacky 1487f22ef01cSRoman Divacky for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(), 1488f22ef01cSRoman Divacky E = NonLocalDeps.end(); I != E; ++I) { 1489f22ef01cSRoman Divacky assert(I->first != D && "Inst occurs in data structures"); 1490f22ef01cSRoman Divacky const PerInstNLInfo &INLD = I->second; 1491f22ef01cSRoman Divacky for (NonLocalDepInfo::const_iterator II = INLD.first.begin(), 1492f22ef01cSRoman Divacky EE = INLD.first.end(); II != EE; ++II) 1493f22ef01cSRoman Divacky assert(II->getResult().getInst() != D && "Inst occurs in data structures"); 1494f22ef01cSRoman Divacky } 1495f22ef01cSRoman Divacky 1496f22ef01cSRoman Divacky for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(), 1497f22ef01cSRoman Divacky E = ReverseLocalDeps.end(); I != E; ++I) { 1498f22ef01cSRoman Divacky assert(I->first != D && "Inst occurs in data structures"); 1499f22ef01cSRoman Divacky for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(), 1500f22ef01cSRoman Divacky EE = I->second.end(); II != EE; ++II) 1501f22ef01cSRoman Divacky assert(*II != D && "Inst occurs in data structures"); 1502f22ef01cSRoman Divacky } 1503f22ef01cSRoman Divacky 1504f22ef01cSRoman Divacky for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(), 1505f22ef01cSRoman Divacky E = ReverseNonLocalDeps.end(); 1506f22ef01cSRoman Divacky I != E; ++I) { 1507f22ef01cSRoman Divacky assert(I->first != D && "Inst occurs in data structures"); 1508f22ef01cSRoman Divacky for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(), 1509f22ef01cSRoman Divacky EE = I->second.end(); II != EE; ++II) 1510f22ef01cSRoman Divacky assert(*II != D && "Inst occurs in data structures"); 1511f22ef01cSRoman Divacky } 1512f22ef01cSRoman Divacky 1513f22ef01cSRoman Divacky for (ReverseNonLocalPtrDepTy::const_iterator 1514f22ef01cSRoman Divacky I = ReverseNonLocalPtrDeps.begin(), 1515f22ef01cSRoman Divacky E = ReverseNonLocalPtrDeps.end(); I != E; ++I) { 1516f22ef01cSRoman Divacky assert(I->first != D && "Inst occurs in rev NLPD map"); 1517f22ef01cSRoman Divacky 1518f22ef01cSRoman Divacky for (SmallPtrSet<ValueIsLoadPair, 4>::const_iterator II = I->second.begin(), 1519f22ef01cSRoman Divacky E = I->second.end(); II != E; ++II) 1520f22ef01cSRoman Divacky assert(*II != ValueIsLoadPair(D, false) && 1521f22ef01cSRoman Divacky *II != ValueIsLoadPair(D, true) && 1522f22ef01cSRoman Divacky "Inst occurs in ReverseNonLocalPtrDeps map"); 1523f22ef01cSRoman Divacky } 1524f22ef01cSRoman Divacky 1525f22ef01cSRoman Divacky } 1526