MemoryDependenceAnalysis.cpp revision 533c2ad360eaaab2a0a25dab5a99255256b84814
1//===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation --*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements an analysis that determines, for a given memory 11// operation, what preceding memory operations it depends on. It builds on 12// alias analysis information, and tries to provide a lazy, caching interface to 13// a common kind of alias information query. 14// 15//===----------------------------------------------------------------------===// 16 17#define DEBUG_TYPE "memdep" 18#include "llvm/Analysis/MemoryDependenceAnalysis.h" 19#include "llvm/Instructions.h" 20#include "llvm/IntrinsicInst.h" 21#include "llvm/Function.h" 22#include "llvm/LLVMContext.h" 23#include "llvm/Analysis/AliasAnalysis.h" 24#include "llvm/Analysis/Dominators.h" 25#include "llvm/Analysis/InstructionSimplify.h" 26#include "llvm/Analysis/MemoryBuiltins.h" 27#include "llvm/Analysis/PHITransAddr.h" 28#include "llvm/ADT/Statistic.h" 29#include "llvm/ADT/STLExtras.h" 30#include "llvm/Support/PredIteratorCache.h" 31#include "llvm/Support/Debug.h" 32using namespace llvm; 33 34STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses"); 35STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses"); 36STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses"); 37 38STATISTIC(NumCacheNonLocalPtr, 39 "Number of fully cached non-local ptr responses"); 40STATISTIC(NumCacheDirtyNonLocalPtr, 41 "Number of cached, but dirty, non-local ptr responses"); 42STATISTIC(NumUncacheNonLocalPtr, 43 "Number of uncached non-local ptr responses"); 44STATISTIC(NumCacheCompleteNonLocalPtr, 45 "Number of block queries that were completely cached"); 46 47char MemoryDependenceAnalysis::ID = 0; 48 49// Register this pass... 50INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep", 51 "Memory Dependence Analysis", false, true) 52INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 53INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep", 54 "Memory Dependence Analysis", false, true) 55 56MemoryDependenceAnalysis::MemoryDependenceAnalysis() 57: FunctionPass(ID), PredCache(0) { 58 initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry()); 59} 60MemoryDependenceAnalysis::~MemoryDependenceAnalysis() { 61} 62 63/// Clean up memory in between runs 64void MemoryDependenceAnalysis::releaseMemory() { 65 LocalDeps.clear(); 66 NonLocalDeps.clear(); 67 NonLocalPointerDeps.clear(); 68 ReverseLocalDeps.clear(); 69 ReverseNonLocalDeps.clear(); 70 ReverseNonLocalPtrDeps.clear(); 71 PredCache->clear(); 72} 73 74 75 76/// getAnalysisUsage - Does not modify anything. It uses Alias Analysis. 77/// 78void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { 79 AU.setPreservesAll(); 80 AU.addRequiredTransitive<AliasAnalysis>(); 81} 82 83bool MemoryDependenceAnalysis::runOnFunction(Function &) { 84 AA = &getAnalysis<AliasAnalysis>(); 85 if (PredCache == 0) 86 PredCache.reset(new PredIteratorCache()); 87 return false; 88} 89 90/// RemoveFromReverseMap - This is a helper function that removes Val from 91/// 'Inst's set in ReverseMap. If the set becomes empty, remove Inst's entry. 92template <typename KeyTy> 93static void RemoveFromReverseMap(DenseMap<Instruction*, 94 SmallPtrSet<KeyTy, 4> > &ReverseMap, 95 Instruction *Inst, KeyTy Val) { 96 typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator 97 InstIt = ReverseMap.find(Inst); 98 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?"); 99 bool Found = InstIt->second.erase(Val); 100 assert(Found && "Invalid reverse map!"); Found=Found; 101 if (InstIt->second.empty()) 102 ReverseMap.erase(InstIt); 103} 104 105/// GetLocation - If the given instruction references a specific memory 106/// location, fill in Loc with the details, otherwise set Loc.Ptr to null. 107/// Return a ModRefInfo value describing the general behavior of the 108/// instruction. 109static 110AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst, 111 AliasAnalysis::Location &Loc, 112 AliasAnalysis *AA) { 113 if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 114 if (LI->isVolatile()) { 115 Loc = AliasAnalysis::Location(); 116 return AliasAnalysis::ModRef; 117 } 118 Loc = AliasAnalysis::Location(LI->getPointerOperand(), 119 AA->getTypeStoreSize(LI->getType()), 120 LI->getMetadata(LLVMContext::MD_tbaa)); 121 return AliasAnalysis::Ref; 122 } 123 124 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 125 if (SI->isVolatile()) { 126 Loc = AliasAnalysis::Location(); 127 return AliasAnalysis::ModRef; 128 } 129 Loc = AliasAnalysis::Location(SI->getPointerOperand(), 130 AA->getTypeStoreSize(SI->getValueOperand() 131 ->getType()), 132 SI->getMetadata(LLVMContext::MD_tbaa)); 133 return AliasAnalysis::Mod; 134 } 135 136 if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) { 137 Loc = AliasAnalysis::Location(V->getPointerOperand(), 138 AA->getTypeStoreSize(V->getType()), 139 V->getMetadata(LLVMContext::MD_tbaa)); 140 return AliasAnalysis::ModRef; 141 } 142 143 if (const CallInst *CI = isFreeCall(Inst)) { 144 // calls to free() deallocate the entire structure 145 Loc = AliasAnalysis::Location(CI->getArgOperand(0)); 146 return AliasAnalysis::Mod; 147 } 148 149 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) 150 switch (II->getIntrinsicID()) { 151 case Intrinsic::lifetime_start: 152 case Intrinsic::lifetime_end: 153 case Intrinsic::invariant_start: 154 Loc = AliasAnalysis::Location(II->getArgOperand(1), 155 cast<ConstantInt>(II->getArgOperand(0)) 156 ->getZExtValue(), 157 II->getMetadata(LLVMContext::MD_tbaa)); 158 // These intrinsics don't really modify the memory, but returning Mod 159 // will allow them to be handled conservatively. 160 return AliasAnalysis::Mod; 161 case Intrinsic::invariant_end: 162 Loc = AliasAnalysis::Location(II->getArgOperand(2), 163 cast<ConstantInt>(II->getArgOperand(1)) 164 ->getZExtValue(), 165 II->getMetadata(LLVMContext::MD_tbaa)); 166 // These intrinsics don't really modify the memory, but returning Mod 167 // will allow them to be handled conservatively. 168 return AliasAnalysis::Mod; 169 default: 170 break; 171 } 172 173 // Otherwise, just do the coarse-grained thing that always works. 174 if (Inst->mayWriteToMemory()) 175 return AliasAnalysis::ModRef; 176 if (Inst->mayReadFromMemory()) 177 return AliasAnalysis::Ref; 178 return AliasAnalysis::NoModRef; 179} 180 181/// getCallSiteDependencyFrom - Private helper for finding the local 182/// dependencies of a call site. 183MemDepResult MemoryDependenceAnalysis:: 184getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall, 185 BasicBlock::iterator ScanIt, BasicBlock *BB) { 186 // Walk backwards through the block, looking for dependencies 187 while (ScanIt != BB->begin()) { 188 Instruction *Inst = --ScanIt; 189 190 // If this inst is a memory op, get the pointer it accessed 191 AliasAnalysis::Location Loc; 192 AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA); 193 if (Loc.Ptr) { 194 // A simple instruction. 195 if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef) 196 return MemDepResult::getClobber(Inst); 197 continue; 198 } 199 200 if (CallSite InstCS = cast<Value>(Inst)) { 201 // Debug intrinsics don't cause dependences. 202 if (isa<DbgInfoIntrinsic>(Inst)) continue; 203 // If these two calls do not interfere, look past it. 204 switch (AA->getModRefInfo(CS, InstCS)) { 205 case AliasAnalysis::NoModRef: 206 // If the two calls are the same, return InstCS as a Def, so that 207 // CS can be found redundant and eliminated. 208 if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) && 209 CS.getInstruction()->isIdenticalToWhenDefined(Inst)) 210 return MemDepResult::getDef(Inst); 211 212 // Otherwise if the two calls don't interact (e.g. InstCS is readnone) 213 // keep scanning. 214 break; 215 default: 216 return MemDepResult::getClobber(Inst); 217 } 218 } 219 } 220 221 // No dependence found. If this is the entry block of the function, it is a 222 // clobber, otherwise it is non-local. 223 if (BB != &BB->getParent()->getEntryBlock()) 224 return MemDepResult::getNonLocal(); 225 return MemDepResult::getClobber(ScanIt); 226} 227 228/// getPointerDependencyFrom - Return the instruction on which a memory 229/// location depends. If isLoad is true, this routine ignores may-aliases with 230/// read-only operations. If isLoad is false, this routine ignores may-aliases 231/// with reads from read-only locations. 232MemDepResult MemoryDependenceAnalysis:: 233getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad, 234 BasicBlock::iterator ScanIt, BasicBlock *BB) { 235 236 Value *InvariantTag = 0; 237 238 // Walk backwards through the basic block, looking for dependencies. 239 while (ScanIt != BB->begin()) { 240 Instruction *Inst = --ScanIt; 241 242 // If we're in an invariant region, no dependencies can be found before 243 // we pass an invariant-begin marker. 244 if (InvariantTag == Inst) { 245 InvariantTag = 0; 246 continue; 247 } 248 249 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 250 // Debug intrinsics don't (and can't) cause dependences. 251 if (isa<DbgInfoIntrinsic>(II)) continue; 252 253 // If we pass an invariant-end marker, then we've just entered an 254 // invariant region and can start ignoring dependencies. 255 if (II->getIntrinsicID() == Intrinsic::invariant_end) { 256 // FIXME: This only considers queries directly on the invariant-tagged 257 // pointer, not on query pointers that are indexed off of them. It'd 258 // be nice to handle that at some point. 259 AliasAnalysis::AliasResult R = 260 AA->alias(AliasAnalysis::Location(II->getArgOperand(2)), MemLoc); 261 if (R == AliasAnalysis::MustAlias) 262 InvariantTag = II->getArgOperand(0); 263 264 continue; 265 } 266 267 // If we reach a lifetime begin or end marker, then the query ends here 268 // because the value is undefined. 269 if (II->getIntrinsicID() == Intrinsic::lifetime_start) { 270 // FIXME: This only considers queries directly on the invariant-tagged 271 // pointer, not on query pointers that are indexed off of them. It'd 272 // be nice to handle that at some point. 273 AliasAnalysis::AliasResult R = 274 AA->alias(AliasAnalysis::Location(II->getArgOperand(1)), MemLoc); 275 if (R == AliasAnalysis::MustAlias) 276 return MemDepResult::getDef(II); 277 continue; 278 } 279 } 280 281 // If we're querying on a load and we're in an invariant region, we're done 282 // at this point. Nothing a load depends on can live in an invariant region. 283 // 284 // FIXME: this will prevent us from returning load/load must-aliases, so GVN 285 // won't remove redundant loads. 286 if (isLoad && InvariantTag) continue; 287 288 // Values depend on loads if the pointers are must aliased. This means that 289 // a load depends on another must aliased load from the same value. 290 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 291 Value *Pointer = LI->getPointerOperand(); 292 uint64_t PointerSize = AA->getTypeStoreSize(LI->getType()); 293 MDNode *TBAATag = LI->getMetadata(LLVMContext::MD_tbaa); 294 AliasAnalysis::Location LoadLoc(Pointer, PointerSize, TBAATag); 295 296 // If we found a pointer, check if it could be the same as our pointer. 297 AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc); 298 if (R == AliasAnalysis::NoAlias) 299 continue; 300 301 // May-alias loads don't depend on each other without a dependence. 302 if (isLoad && R == AliasAnalysis::MayAlias) 303 continue; 304 305 // Stores don't alias loads from read-only memory. 306 if (!isLoad && AA->pointsToConstantMemory(LoadLoc)) 307 continue; 308 309 // Stores depend on may and must aliased loads, loads depend on must-alias 310 // loads. 311 return MemDepResult::getDef(Inst); 312 } 313 314 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 315 // There can't be stores to the value we care about inside an 316 // invariant region. 317 if (InvariantTag) continue; 318 319 // If alias analysis can tell that this store is guaranteed to not modify 320 // the query pointer, ignore it. Use getModRefInfo to handle cases where 321 // the query pointer points to constant memory etc. 322 if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef) 323 continue; 324 325 // Ok, this store might clobber the query pointer. Check to see if it is 326 // a must alias: in this case, we want to return this as a def. 327 Value *Pointer = SI->getPointerOperand(); 328 uint64_t PointerSize = AA->getTypeStoreSize(SI->getOperand(0)->getType()); 329 MDNode *TBAATag = SI->getMetadata(LLVMContext::MD_tbaa); 330 331 // If we found a pointer, check if it could be the same as our pointer. 332 AliasAnalysis::AliasResult R = 333 AA->alias(AliasAnalysis::Location(Pointer, PointerSize, TBAATag), 334 MemLoc); 335 336 if (R == AliasAnalysis::NoAlias) 337 continue; 338 if (R == AliasAnalysis::MayAlias) 339 return MemDepResult::getClobber(Inst); 340 return MemDepResult::getDef(Inst); 341 } 342 343 // If this is an allocation, and if we know that the accessed pointer is to 344 // the allocation, return Def. This means that there is no dependence and 345 // the access can be optimized based on that. For example, a load could 346 // turn into undef. 347 // Note: Only determine this to be a malloc if Inst is the malloc call, not 348 // a subsequent bitcast of the malloc call result. There can be stores to 349 // the malloced memory between the malloc call and its bitcast uses, and we 350 // need to continue scanning until the malloc call. 351 if (isa<AllocaInst>(Inst) || 352 (isa<CallInst>(Inst) && extractMallocCall(Inst))) { 353 const Value *AccessPtr = MemLoc.Ptr->getUnderlyingObject(); 354 355 if (AccessPtr == Inst || 356 AA->alias(Inst, 1, AccessPtr, 1) == AliasAnalysis::MustAlias) 357 return MemDepResult::getDef(Inst); 358 continue; 359 } 360 361 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer. 362 switch (AA->getModRefInfo(Inst, MemLoc)) { 363 case AliasAnalysis::NoModRef: 364 // If the call has no effect on the queried pointer, just ignore it. 365 continue; 366 case AliasAnalysis::Mod: 367 // If we're in an invariant region, we can ignore calls that ONLY 368 // modify the pointer. 369 if (InvariantTag) continue; 370 return MemDepResult::getClobber(Inst); 371 case AliasAnalysis::Ref: 372 // If the call is known to never store to the pointer, and if this is a 373 // load query, we can safely ignore it (scan past it). 374 if (isLoad) 375 continue; 376 default: 377 // Otherwise, there is a potential dependence. Return a clobber. 378 return MemDepResult::getClobber(Inst); 379 } 380 } 381 382 // No dependence found. If this is the entry block of the function, it is a 383 // clobber, otherwise it is non-local. 384 if (BB != &BB->getParent()->getEntryBlock()) 385 return MemDepResult::getNonLocal(); 386 return MemDepResult::getClobber(ScanIt); 387} 388 389/// getDependency - Return the instruction on which a memory operation 390/// depends. 391MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) { 392 Instruction *ScanPos = QueryInst; 393 394 // Check for a cached result 395 MemDepResult &LocalCache = LocalDeps[QueryInst]; 396 397 // If the cached entry is non-dirty, just return it. Note that this depends 398 // on MemDepResult's default constructing to 'dirty'. 399 if (!LocalCache.isDirty()) 400 return LocalCache; 401 402 // Otherwise, if we have a dirty entry, we know we can start the scan at that 403 // instruction, which may save us some work. 404 if (Instruction *Inst = LocalCache.getInst()) { 405 ScanPos = Inst; 406 407 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst); 408 } 409 410 BasicBlock *QueryParent = QueryInst->getParent(); 411 412 // Do the scan. 413 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) { 414 // No dependence found. If this is the entry block of the function, it is a 415 // clobber, otherwise it is non-local. 416 if (QueryParent != &QueryParent->getParent()->getEntryBlock()) 417 LocalCache = MemDepResult::getNonLocal(); 418 else 419 LocalCache = MemDepResult::getClobber(QueryInst); 420 } else { 421 AliasAnalysis::Location MemLoc; 422 AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA); 423 if (MemLoc.Ptr) { 424 // If we can do a pointer scan, make it happen. 425 bool isLoad = !(MR & AliasAnalysis::Mod); 426 if (IntrinsicInst *II = dyn_cast<MemoryUseIntrinsic>(QueryInst)) { 427 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_end; 428 } 429 LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos, 430 QueryParent); 431 } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) { 432 CallSite QueryCS(QueryInst); 433 bool isReadOnly = AA->onlyReadsMemory(QueryCS); 434 LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos, 435 QueryParent); 436 } else 437 // Non-memory instruction. 438 LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos)); 439 } 440 441 // Remember the result! 442 if (Instruction *I = LocalCache.getInst()) 443 ReverseLocalDeps[I].insert(QueryInst); 444 445 return LocalCache; 446} 447 448#ifndef NDEBUG 449/// AssertSorted - This method is used when -debug is specified to verify that 450/// cache arrays are properly kept sorted. 451static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache, 452 int Count = -1) { 453 if (Count == -1) Count = Cache.size(); 454 if (Count == 0) return; 455 456 for (unsigned i = 1; i != unsigned(Count); ++i) 457 assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!"); 458} 459#endif 460 461/// getNonLocalCallDependency - Perform a full dependency query for the 462/// specified call, returning the set of blocks that the value is 463/// potentially live across. The returned set of results will include a 464/// "NonLocal" result for all blocks where the value is live across. 465/// 466/// This method assumes the instruction returns a "NonLocal" dependency 467/// within its own block. 468/// 469/// This returns a reference to an internal data structure that may be 470/// invalidated on the next non-local query or when an instruction is 471/// removed. Clients must copy this data if they want it around longer than 472/// that. 473const MemoryDependenceAnalysis::NonLocalDepInfo & 474MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) { 475 assert(getDependency(QueryCS.getInstruction()).isNonLocal() && 476 "getNonLocalCallDependency should only be used on calls with non-local deps!"); 477 PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()]; 478 NonLocalDepInfo &Cache = CacheP.first; 479 480 /// DirtyBlocks - This is the set of blocks that need to be recomputed. In 481 /// the cached case, this can happen due to instructions being deleted etc. In 482 /// the uncached case, this starts out as the set of predecessors we care 483 /// about. 484 SmallVector<BasicBlock*, 32> DirtyBlocks; 485 486 if (!Cache.empty()) { 487 // Okay, we have a cache entry. If we know it is not dirty, just return it 488 // with no computation. 489 if (!CacheP.second) { 490 ++NumCacheNonLocal; 491 return Cache; 492 } 493 494 // If we already have a partially computed set of results, scan them to 495 // determine what is dirty, seeding our initial DirtyBlocks worklist. 496 for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end(); 497 I != E; ++I) 498 if (I->getResult().isDirty()) 499 DirtyBlocks.push_back(I->getBB()); 500 501 // Sort the cache so that we can do fast binary search lookups below. 502 std::sort(Cache.begin(), Cache.end()); 503 504 ++NumCacheDirtyNonLocal; 505 //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: " 506 // << Cache.size() << " cached: " << *QueryInst; 507 } else { 508 // Seed DirtyBlocks with each of the preds of QueryInst's block. 509 BasicBlock *QueryBB = QueryCS.getInstruction()->getParent(); 510 for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI) 511 DirtyBlocks.push_back(*PI); 512 ++NumUncacheNonLocal; 513 } 514 515 // isReadonlyCall - If this is a read-only call, we can be more aggressive. 516 bool isReadonlyCall = AA->onlyReadsMemory(QueryCS); 517 518 SmallPtrSet<BasicBlock*, 64> Visited; 519 520 unsigned NumSortedEntries = Cache.size(); 521 DEBUG(AssertSorted(Cache)); 522 523 // Iterate while we still have blocks to update. 524 while (!DirtyBlocks.empty()) { 525 BasicBlock *DirtyBB = DirtyBlocks.back(); 526 DirtyBlocks.pop_back(); 527 528 // Already processed this block? 529 if (!Visited.insert(DirtyBB)) 530 continue; 531 532 // Do a binary search to see if we already have an entry for this block in 533 // the cache set. If so, find it. 534 DEBUG(AssertSorted(Cache, NumSortedEntries)); 535 NonLocalDepInfo::iterator Entry = 536 std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries, 537 NonLocalDepEntry(DirtyBB)); 538 if (Entry != Cache.begin() && prior(Entry)->getBB() == DirtyBB) 539 --Entry; 540 541 NonLocalDepEntry *ExistingResult = 0; 542 if (Entry != Cache.begin()+NumSortedEntries && 543 Entry->getBB() == DirtyBB) { 544 // If we already have an entry, and if it isn't already dirty, the block 545 // is done. 546 if (!Entry->getResult().isDirty()) 547 continue; 548 549 // Otherwise, remember this slot so we can update the value. 550 ExistingResult = &*Entry; 551 } 552 553 // If the dirty entry has a pointer, start scanning from it so we don't have 554 // to rescan the entire block. 555 BasicBlock::iterator ScanPos = DirtyBB->end(); 556 if (ExistingResult) { 557 if (Instruction *Inst = ExistingResult->getResult().getInst()) { 558 ScanPos = Inst; 559 // We're removing QueryInst's use of Inst. 560 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, 561 QueryCS.getInstruction()); 562 } 563 } 564 565 // Find out if this block has a local dependency for QueryInst. 566 MemDepResult Dep; 567 568 if (ScanPos != DirtyBB->begin()) { 569 Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB); 570 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) { 571 // No dependence found. If this is the entry block of the function, it is 572 // a clobber, otherwise it is non-local. 573 Dep = MemDepResult::getNonLocal(); 574 } else { 575 Dep = MemDepResult::getClobber(ScanPos); 576 } 577 578 // If we had a dirty entry for the block, update it. Otherwise, just add 579 // a new entry. 580 if (ExistingResult) 581 ExistingResult->setResult(Dep); 582 else 583 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep)); 584 585 // If the block has a dependency (i.e. it isn't completely transparent to 586 // the value), remember the association! 587 if (!Dep.isNonLocal()) { 588 // Keep the ReverseNonLocalDeps map up to date so we can efficiently 589 // update this when we remove instructions. 590 if (Instruction *Inst = Dep.getInst()) 591 ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction()); 592 } else { 593 594 // If the block *is* completely transparent to the load, we need to check 595 // the predecessors of this block. Add them to our worklist. 596 for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI) 597 DirtyBlocks.push_back(*PI); 598 } 599 } 600 601 return Cache; 602} 603 604/// getNonLocalPointerDependency - Perform a full dependency query for an 605/// access to the specified (non-volatile) memory location, returning the 606/// set of instructions that either define or clobber the value. 607/// 608/// This method assumes the pointer has a "NonLocal" dependency within its 609/// own block. 610/// 611void MemoryDependenceAnalysis:: 612getNonLocalPointerDependency(const AliasAnalysis::Location &Loc, bool isLoad, 613 BasicBlock *FromBB, 614 SmallVectorImpl<NonLocalDepResult> &Result) { 615 assert(Loc.Ptr->getType()->isPointerTy() && 616 "Can't get pointer deps of a non-pointer!"); 617 Result.clear(); 618 619 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), TD); 620 621 // This is the set of blocks we've inspected, and the pointer we consider in 622 // each block. Because of critical edges, we currently bail out if querying 623 // a block with multiple different pointers. This can happen during PHI 624 // translation. 625 DenseMap<BasicBlock*, Value*> Visited; 626 if (!getNonLocalPointerDepFromBB(Address, Loc, isLoad, FromBB, 627 Result, Visited, true)) 628 return; 629 Result.clear(); 630 Result.push_back(NonLocalDepResult(FromBB, 631 MemDepResult::getClobber(FromBB->begin()), 632 const_cast<Value *>(Loc.Ptr))); 633} 634 635/// GetNonLocalInfoForBlock - Compute the memdep value for BB with 636/// Pointer/PointeeSize using either cached information in Cache or by doing a 637/// lookup (which may use dirty cache info if available). If we do a lookup, 638/// add the result to the cache. 639MemDepResult MemoryDependenceAnalysis:: 640GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc, 641 bool isLoad, BasicBlock *BB, 642 NonLocalDepInfo *Cache, unsigned NumSortedEntries) { 643 644 // Do a binary search to see if we already have an entry for this block in 645 // the cache set. If so, find it. 646 NonLocalDepInfo::iterator Entry = 647 std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries, 648 NonLocalDepEntry(BB)); 649 if (Entry != Cache->begin() && (Entry-1)->getBB() == BB) 650 --Entry; 651 652 NonLocalDepEntry *ExistingResult = 0; 653 if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB) 654 ExistingResult = &*Entry; 655 656 // If we have a cached entry, and it is non-dirty, use it as the value for 657 // this dependency. 658 if (ExistingResult && !ExistingResult->getResult().isDirty()) { 659 ++NumCacheNonLocalPtr; 660 return ExistingResult->getResult(); 661 } 662 663 // Otherwise, we have to scan for the value. If we have a dirty cache 664 // entry, start scanning from its position, otherwise we scan from the end 665 // of the block. 666 BasicBlock::iterator ScanPos = BB->end(); 667 if (ExistingResult && ExistingResult->getResult().getInst()) { 668 assert(ExistingResult->getResult().getInst()->getParent() == BB && 669 "Instruction invalidated?"); 670 ++NumCacheDirtyNonLocalPtr; 671 ScanPos = ExistingResult->getResult().getInst(); 672 673 // Eliminating the dirty entry from 'Cache', so update the reverse info. 674 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad); 675 RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey); 676 } else { 677 ++NumUncacheNonLocalPtr; 678 } 679 680 // Scan the block for the dependency. 681 MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB); 682 683 // If we had a dirty entry for the block, update it. Otherwise, just add 684 // a new entry. 685 if (ExistingResult) 686 ExistingResult->setResult(Dep); 687 else 688 Cache->push_back(NonLocalDepEntry(BB, Dep)); 689 690 // If the block has a dependency (i.e. it isn't completely transparent to 691 // the value), remember the reverse association because we just added it 692 // to Cache! 693 if (Dep.isNonLocal()) 694 return Dep; 695 696 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently 697 // update MemDep when we remove instructions. 698 Instruction *Inst = Dep.getInst(); 699 assert(Inst && "Didn't depend on anything?"); 700 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad); 701 ReverseNonLocalPtrDeps[Inst].insert(CacheKey); 702 return Dep; 703} 704 705/// SortNonLocalDepInfoCache - Sort the a NonLocalDepInfo cache, given a certain 706/// number of elements in the array that are already properly ordered. This is 707/// optimized for the case when only a few entries are added. 708static void 709SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache, 710 unsigned NumSortedEntries) { 711 switch (Cache.size() - NumSortedEntries) { 712 case 0: 713 // done, no new entries. 714 break; 715 case 2: { 716 // Two new entries, insert the last one into place. 717 NonLocalDepEntry Val = Cache.back(); 718 Cache.pop_back(); 719 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry = 720 std::upper_bound(Cache.begin(), Cache.end()-1, Val); 721 Cache.insert(Entry, Val); 722 // FALL THROUGH. 723 } 724 case 1: 725 // One new entry, Just insert the new value at the appropriate position. 726 if (Cache.size() != 1) { 727 NonLocalDepEntry Val = Cache.back(); 728 Cache.pop_back(); 729 MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry = 730 std::upper_bound(Cache.begin(), Cache.end(), Val); 731 Cache.insert(Entry, Val); 732 } 733 break; 734 default: 735 // Added many values, do a full scale sort. 736 std::sort(Cache.begin(), Cache.end()); 737 break; 738 } 739} 740 741/// getNonLocalPointerDepFromBB - Perform a dependency query based on 742/// pointer/pointeesize starting at the end of StartBB. Add any clobber/def 743/// results to the results vector and keep track of which blocks are visited in 744/// 'Visited'. 745/// 746/// This has special behavior for the first block queries (when SkipFirstBlock 747/// is true). In this special case, it ignores the contents of the specified 748/// block and starts returning dependence info for its predecessors. 749/// 750/// This function returns false on success, or true to indicate that it could 751/// not compute dependence information for some reason. This should be treated 752/// as a clobber dependence on the first instruction in the predecessor block. 753bool MemoryDependenceAnalysis:: 754getNonLocalPointerDepFromBB(const PHITransAddr &Pointer, 755 const AliasAnalysis::Location &Loc, 756 bool isLoad, BasicBlock *StartBB, 757 SmallVectorImpl<NonLocalDepResult> &Result, 758 DenseMap<BasicBlock*, Value*> &Visited, 759 bool SkipFirstBlock) { 760 761 // Look up the cached info for Pointer. 762 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad); 763 764 // Set up a temporary NLPI value. If the map doesn't yet have an entry for 765 // CacheKey, this value will be inserted as the associated value. Otherwise, 766 // it'll be ignored, and we'll have to check to see if the cached size and 767 // tbaa tag are consistent with the current query. 768 NonLocalPointerInfo InitialNLPI; 769 InitialNLPI.Size = Loc.Size; 770 InitialNLPI.TBAATag = Loc.TBAATag; 771 772 // Get the NLPI for CacheKey, inserting one into the map if it doesn't 773 // already have one. 774 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair = 775 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI)); 776 NonLocalPointerInfo *CacheInfo = &Pair.first->second; 777 778 // If we already have a cache entry for this CacheKey, we may need to do some 779 // work to reconcile the cache entry and the current query. 780 if (!Pair.second) { 781 if (CacheInfo->Size < Loc.Size) { 782 // The query's Size is greater than the cached one. Throw out the 783 // cached data and procede with the query at the greater size. 784 CacheInfo->Pair = BBSkipFirstBlockPair(); 785 CacheInfo->Size = Loc.Size; 786 CacheInfo->NonLocalDeps.clear(); 787 } else if (CacheInfo->Size > Loc.Size) { 788 // This query's Size is less than the cached one. Conservatively restart 789 // the query using the greater size. 790 return getNonLocalPointerDepFromBB(Pointer, 791 Loc.getWithNewSize(CacheInfo->Size), 792 isLoad, StartBB, Result, Visited, 793 SkipFirstBlock); 794 } 795 796 // If the query's TBAATag is inconsistent with the cached one, 797 // conservatively throw out the cached data and restart the query with 798 // no tag if needed. 799 if (CacheInfo->TBAATag != Loc.TBAATag) { 800 if (CacheInfo->TBAATag) { 801 CacheInfo->Pair = BBSkipFirstBlockPair(); 802 CacheInfo->TBAATag = 0; 803 CacheInfo->NonLocalDeps.clear(); 804 } 805 if (Loc.TBAATag) 806 return getNonLocalPointerDepFromBB(Pointer, Loc.getWithoutTBAATag(), 807 isLoad, StartBB, Result, Visited, 808 SkipFirstBlock); 809 } 810 } 811 812 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps; 813 814 // If we have valid cached information for exactly the block we are 815 // investigating, just return it with no recomputation. 816 if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) { 817 // We have a fully cached result for this query then we can just return the 818 // cached results and populate the visited set. However, we have to verify 819 // that we don't already have conflicting results for these blocks. Check 820 // to ensure that if a block in the results set is in the visited set that 821 // it was for the same pointer query. 822 if (!Visited.empty()) { 823 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end(); 824 I != E; ++I) { 825 DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB()); 826 if (VI == Visited.end() || VI->second == Pointer.getAddr()) 827 continue; 828 829 // We have a pointer mismatch in a block. Just return clobber, saying 830 // that something was clobbered in this result. We could also do a 831 // non-fully cached query, but there is little point in doing this. 832 return true; 833 } 834 } 835 836 Value *Addr = Pointer.getAddr(); 837 for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end(); 838 I != E; ++I) { 839 Visited.insert(std::make_pair(I->getBB(), Addr)); 840 if (!I->getResult().isNonLocal()) 841 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr)); 842 } 843 ++NumCacheCompleteNonLocalPtr; 844 return false; 845 } 846 847 // Otherwise, either this is a new block, a block with an invalid cache 848 // pointer or one that we're about to invalidate by putting more info into it 849 // than its valid cache info. If empty, the result will be valid cache info, 850 // otherwise it isn't. 851 if (Cache->empty()) 852 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock); 853 else { 854 CacheInfo->Pair = BBSkipFirstBlockPair(); 855 CacheInfo->Size = 0; 856 CacheInfo->TBAATag = 0; 857 } 858 859 SmallVector<BasicBlock*, 32> Worklist; 860 Worklist.push_back(StartBB); 861 862 // Keep track of the entries that we know are sorted. Previously cached 863 // entries will all be sorted. The entries we add we only sort on demand (we 864 // don't insert every element into its sorted position). We know that we 865 // won't get any reuse from currently inserted values, because we don't 866 // revisit blocks after we insert info for them. 867 unsigned NumSortedEntries = Cache->size(); 868 DEBUG(AssertSorted(*Cache)); 869 870 while (!Worklist.empty()) { 871 BasicBlock *BB = Worklist.pop_back_val(); 872 873 // Skip the first block if we have it. 874 if (!SkipFirstBlock) { 875 // Analyze the dependency of *Pointer in FromBB. See if we already have 876 // been here. 877 assert(Visited.count(BB) && "Should check 'visited' before adding to WL"); 878 879 // Get the dependency info for Pointer in BB. If we have cached 880 // information, we will use it, otherwise we compute it. 881 DEBUG(AssertSorted(*Cache, NumSortedEntries)); 882 MemDepResult Dep = GetNonLocalInfoForBlock(Loc, isLoad, BB, Cache, 883 NumSortedEntries); 884 885 // If we got a Def or Clobber, add this to the list of results. 886 if (!Dep.isNonLocal()) { 887 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr())); 888 continue; 889 } 890 } 891 892 // If 'Pointer' is an instruction defined in this block, then we need to do 893 // phi translation to change it into a value live in the predecessor block. 894 // If not, we just add the predecessors to the worklist and scan them with 895 // the same Pointer. 896 if (!Pointer.NeedsPHITranslationFromBlock(BB)) { 897 SkipFirstBlock = false; 898 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) { 899 // Verify that we haven't looked at this block yet. 900 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool> 901 InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr())); 902 if (InsertRes.second) { 903 // First time we've looked at *PI. 904 Worklist.push_back(*PI); 905 continue; 906 } 907 908 // If we have seen this block before, but it was with a different 909 // pointer then we have a phi translation failure and we have to treat 910 // this as a clobber. 911 if (InsertRes.first->second != Pointer.getAddr()) 912 goto PredTranslationFailure; 913 } 914 continue; 915 } 916 917 // We do need to do phi translation, if we know ahead of time we can't phi 918 // translate this value, don't even try. 919 if (!Pointer.IsPotentiallyPHITranslatable()) 920 goto PredTranslationFailure; 921 922 // We may have added values to the cache list before this PHI translation. 923 // If so, we haven't done anything to ensure that the cache remains sorted. 924 // Sort it now (if needed) so that recursive invocations of 925 // getNonLocalPointerDepFromBB and other routines that could reuse the cache 926 // value will only see properly sorted cache arrays. 927 if (Cache && NumSortedEntries != Cache->size()) { 928 SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 929 NumSortedEntries = Cache->size(); 930 } 931 Cache = 0; 932 933 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) { 934 BasicBlock *Pred = *PI; 935 936 // Get the PHI translated pointer in this predecessor. This can fail if 937 // not translatable, in which case the getAddr() returns null. 938 PHITransAddr PredPointer(Pointer); 939 PredPointer.PHITranslateValue(BB, Pred, 0); 940 941 Value *PredPtrVal = PredPointer.getAddr(); 942 943 // Check to see if we have already visited this pred block with another 944 // pointer. If so, we can't do this lookup. This failure can occur 945 // with PHI translation when a critical edge exists and the PHI node in 946 // the successor translates to a pointer value different than the 947 // pointer the block was first analyzed with. 948 std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool> 949 InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal)); 950 951 if (!InsertRes.second) { 952 // If the predecessor was visited with PredPtr, then we already did 953 // the analysis and can ignore it. 954 if (InsertRes.first->second == PredPtrVal) 955 continue; 956 957 // Otherwise, the block was previously analyzed with a different 958 // pointer. We can't represent the result of this case, so we just 959 // treat this as a phi translation failure. 960 goto PredTranslationFailure; 961 } 962 963 // If PHI translation was unable to find an available pointer in this 964 // predecessor, then we have to assume that the pointer is clobbered in 965 // that predecessor. We can still do PRE of the load, which would insert 966 // a computation of the pointer in this predecessor. 967 if (PredPtrVal == 0) { 968 // Add the entry to the Result list. 969 NonLocalDepResult Entry(Pred, 970 MemDepResult::getClobber(Pred->getTerminator()), 971 PredPtrVal); 972 Result.push_back(Entry); 973 974 // Since we had a phi translation failure, the cache for CacheKey won't 975 // include all of the entries that we need to immediately satisfy future 976 // queries. Mark this in NonLocalPointerDeps by setting the 977 // BBSkipFirstBlockPair pointer to null. This requires reuse of the 978 // cached value to do more work but not miss the phi trans failure. 979 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey]; 980 NLPI.Pair = BBSkipFirstBlockPair(); 981 NLPI.Size = 0; 982 NLPI.TBAATag = 0; 983 continue; 984 } 985 986 // FIXME: it is entirely possible that PHI translating will end up with 987 // the same value. Consider PHI translating something like: 988 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need* 989 // to recurse here, pedantically speaking. 990 991 // If we have a problem phi translating, fall through to the code below 992 // to handle the failure condition. 993 if (getNonLocalPointerDepFromBB(PredPointer, 994 Loc.getWithNewPtr(PredPointer.getAddr()), 995 isLoad, Pred, 996 Result, Visited)) 997 goto PredTranslationFailure; 998 } 999 1000 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated. 1001 CacheInfo = &NonLocalPointerDeps[CacheKey]; 1002 Cache = &CacheInfo->NonLocalDeps; 1003 NumSortedEntries = Cache->size(); 1004 1005 // Since we did phi translation, the "Cache" set won't contain all of the 1006 // results for the query. This is ok (we can still use it to accelerate 1007 // specific block queries) but we can't do the fastpath "return all 1008 // results from the set" Clear out the indicator for this. 1009 CacheInfo->Pair = BBSkipFirstBlockPair(); 1010 CacheInfo->Size = 0; 1011 CacheInfo->TBAATag = 0; 1012 SkipFirstBlock = false; 1013 continue; 1014 1015 PredTranslationFailure: 1016 1017 if (Cache == 0) { 1018 // Refresh the CacheInfo/Cache pointer if it got invalidated. 1019 CacheInfo = &NonLocalPointerDeps[CacheKey]; 1020 Cache = &CacheInfo->NonLocalDeps; 1021 NumSortedEntries = Cache->size(); 1022 } 1023 1024 // Since we failed phi translation, the "Cache" set won't contain all of the 1025 // results for the query. This is ok (we can still use it to accelerate 1026 // specific block queries) but we can't do the fastpath "return all 1027 // results from the set". Clear out the indicator for this. 1028 CacheInfo->Pair = BBSkipFirstBlockPair(); 1029 CacheInfo->Size = 0; 1030 CacheInfo->TBAATag = 0; 1031 1032 // If *nothing* works, mark the pointer as being clobbered by the first 1033 // instruction in this block. 1034 // 1035 // If this is the magic first block, return this as a clobber of the whole 1036 // incoming value. Since we can't phi translate to one of the predecessors, 1037 // we have to bail out. 1038 if (SkipFirstBlock) 1039 return true; 1040 1041 for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) { 1042 assert(I != Cache->rend() && "Didn't find current block??"); 1043 if (I->getBB() != BB) 1044 continue; 1045 1046 assert(I->getResult().isNonLocal() && 1047 "Should only be here with transparent block"); 1048 I->setResult(MemDepResult::getClobber(BB->begin())); 1049 ReverseNonLocalPtrDeps[BB->begin()].insert(CacheKey); 1050 Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), 1051 Pointer.getAddr())); 1052 break; 1053 } 1054 } 1055 1056 // Okay, we're done now. If we added new values to the cache, re-sort it. 1057 SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 1058 DEBUG(AssertSorted(*Cache)); 1059 return false; 1060} 1061 1062/// RemoveCachedNonLocalPointerDependencies - If P exists in 1063/// CachedNonLocalPointerInfo, remove it. 1064void MemoryDependenceAnalysis:: 1065RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) { 1066 CachedNonLocalPointerInfo::iterator It = 1067 NonLocalPointerDeps.find(P); 1068 if (It == NonLocalPointerDeps.end()) return; 1069 1070 // Remove all of the entries in the BB->val map. This involves removing 1071 // instructions from the reverse map. 1072 NonLocalDepInfo &PInfo = It->second.NonLocalDeps; 1073 1074 for (unsigned i = 0, e = PInfo.size(); i != e; ++i) { 1075 Instruction *Target = PInfo[i].getResult().getInst(); 1076 if (Target == 0) continue; // Ignore non-local dep results. 1077 assert(Target->getParent() == PInfo[i].getBB()); 1078 1079 // Eliminating the dirty entry from 'Cache', so update the reverse info. 1080 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P); 1081 } 1082 1083 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo). 1084 NonLocalPointerDeps.erase(It); 1085} 1086 1087 1088/// invalidateCachedPointerInfo - This method is used to invalidate cached 1089/// information about the specified pointer, because it may be too 1090/// conservative in memdep. This is an optional call that can be used when 1091/// the client detects an equivalence between the pointer and some other 1092/// value and replaces the other value with ptr. This can make Ptr available 1093/// in more places that cached info does not necessarily keep. 1094void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) { 1095 // If Ptr isn't really a pointer, just ignore it. 1096 if (!Ptr->getType()->isPointerTy()) return; 1097 // Flush store info for the pointer. 1098 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false)); 1099 // Flush load info for the pointer. 1100 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true)); 1101} 1102 1103/// invalidateCachedPredecessors - Clear the PredIteratorCache info. 1104/// This needs to be done when the CFG changes, e.g., due to splitting 1105/// critical edges. 1106void MemoryDependenceAnalysis::invalidateCachedPredecessors() { 1107 PredCache->clear(); 1108} 1109 1110/// removeInstruction - Remove an instruction from the dependence analysis, 1111/// updating the dependence of instructions that previously depended on it. 1112/// This method attempts to keep the cache coherent using the reverse map. 1113void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) { 1114 // Walk through the Non-local dependencies, removing this one as the value 1115 // for any cached queries. 1116 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst); 1117 if (NLDI != NonLocalDeps.end()) { 1118 NonLocalDepInfo &BlockMap = NLDI->second.first; 1119 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end(); 1120 DI != DE; ++DI) 1121 if (Instruction *Inst = DI->getResult().getInst()) 1122 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst); 1123 NonLocalDeps.erase(NLDI); 1124 } 1125 1126 // If we have a cached local dependence query for this instruction, remove it. 1127 // 1128 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst); 1129 if (LocalDepEntry != LocalDeps.end()) { 1130 // Remove us from DepInst's reverse set now that the local dep info is gone. 1131 if (Instruction *Inst = LocalDepEntry->second.getInst()) 1132 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst); 1133 1134 // Remove this local dependency info. 1135 LocalDeps.erase(LocalDepEntry); 1136 } 1137 1138 // If we have any cached pointer dependencies on this instruction, remove 1139 // them. If the instruction has non-pointer type, then it can't be a pointer 1140 // base. 1141 1142 // Remove it from both the load info and the store info. The instruction 1143 // can't be in either of these maps if it is non-pointer. 1144 if (RemInst->getType()->isPointerTy()) { 1145 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false)); 1146 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true)); 1147 } 1148 1149 // Loop over all of the things that depend on the instruction we're removing. 1150 // 1151 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd; 1152 1153 // If we find RemInst as a clobber or Def in any of the maps for other values, 1154 // we need to replace its entry with a dirty version of the instruction after 1155 // it. If RemInst is a terminator, we use a null dirty value. 1156 // 1157 // Using a dirty version of the instruction after RemInst saves having to scan 1158 // the entire block to get to this point. 1159 MemDepResult NewDirtyVal; 1160 if (!RemInst->isTerminator()) 1161 NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst)); 1162 1163 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst); 1164 if (ReverseDepIt != ReverseLocalDeps.end()) { 1165 SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second; 1166 // RemInst can't be the terminator if it has local stuff depending on it. 1167 assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) && 1168 "Nothing can locally depend on a terminator"); 1169 1170 for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(), 1171 E = ReverseDeps.end(); I != E; ++I) { 1172 Instruction *InstDependingOnRemInst = *I; 1173 assert(InstDependingOnRemInst != RemInst && 1174 "Already removed our local dep info"); 1175 1176 LocalDeps[InstDependingOnRemInst] = NewDirtyVal; 1177 1178 // Make sure to remember that new things depend on NewDepInst. 1179 assert(NewDirtyVal.getInst() && "There is no way something else can have " 1180 "a local dep on this if it is a terminator!"); 1181 ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(), 1182 InstDependingOnRemInst)); 1183 } 1184 1185 ReverseLocalDeps.erase(ReverseDepIt); 1186 1187 // Add new reverse deps after scanning the set, to avoid invalidating the 1188 // 'ReverseDeps' reference. 1189 while (!ReverseDepsToAdd.empty()) { 1190 ReverseLocalDeps[ReverseDepsToAdd.back().first] 1191 .insert(ReverseDepsToAdd.back().second); 1192 ReverseDepsToAdd.pop_back(); 1193 } 1194 } 1195 1196 ReverseDepIt = ReverseNonLocalDeps.find(RemInst); 1197 if (ReverseDepIt != ReverseNonLocalDeps.end()) { 1198 SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second; 1199 for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end(); 1200 I != E; ++I) { 1201 assert(*I != RemInst && "Already removed NonLocalDep info for RemInst"); 1202 1203 PerInstNLInfo &INLD = NonLocalDeps[*I]; 1204 // The information is now dirty! 1205 INLD.second = true; 1206 1207 for (NonLocalDepInfo::iterator DI = INLD.first.begin(), 1208 DE = INLD.first.end(); DI != DE; ++DI) { 1209 if (DI->getResult().getInst() != RemInst) continue; 1210 1211 // Convert to a dirty entry for the subsequent instruction. 1212 DI->setResult(NewDirtyVal); 1213 1214 if (Instruction *NextI = NewDirtyVal.getInst()) 1215 ReverseDepsToAdd.push_back(std::make_pair(NextI, *I)); 1216 } 1217 } 1218 1219 ReverseNonLocalDeps.erase(ReverseDepIt); 1220 1221 // Add new reverse deps after scanning the set, to avoid invalidating 'Set' 1222 while (!ReverseDepsToAdd.empty()) { 1223 ReverseNonLocalDeps[ReverseDepsToAdd.back().first] 1224 .insert(ReverseDepsToAdd.back().second); 1225 ReverseDepsToAdd.pop_back(); 1226 } 1227 } 1228 1229 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a 1230 // value in the NonLocalPointerDeps info. 1231 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt = 1232 ReverseNonLocalPtrDeps.find(RemInst); 1233 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) { 1234 SmallPtrSet<ValueIsLoadPair, 4> &Set = ReversePtrDepIt->second; 1235 SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd; 1236 1237 for (SmallPtrSet<ValueIsLoadPair, 4>::iterator I = Set.begin(), 1238 E = Set.end(); I != E; ++I) { 1239 ValueIsLoadPair P = *I; 1240 assert(P.getPointer() != RemInst && 1241 "Already removed NonLocalPointerDeps info for RemInst"); 1242 1243 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps; 1244 1245 // The cache is not valid for any specific block anymore. 1246 NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair(); 1247 NonLocalPointerDeps[P].Size = 0; 1248 NonLocalPointerDeps[P].TBAATag = 0; 1249 1250 // Update any entries for RemInst to use the instruction after it. 1251 for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end(); 1252 DI != DE; ++DI) { 1253 if (DI->getResult().getInst() != RemInst) continue; 1254 1255 // Convert to a dirty entry for the subsequent instruction. 1256 DI->setResult(NewDirtyVal); 1257 1258 if (Instruction *NewDirtyInst = NewDirtyVal.getInst()) 1259 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P)); 1260 } 1261 1262 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its 1263 // subsequent value may invalidate the sortedness. 1264 std::sort(NLPDI.begin(), NLPDI.end()); 1265 } 1266 1267 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt); 1268 1269 while (!ReversePtrDepsToAdd.empty()) { 1270 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first] 1271 .insert(ReversePtrDepsToAdd.back().second); 1272 ReversePtrDepsToAdd.pop_back(); 1273 } 1274 } 1275 1276 1277 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?"); 1278 AA->deleteValue(RemInst); 1279 DEBUG(verifyRemoved(RemInst)); 1280} 1281/// verifyRemoved - Verify that the specified instruction does not occur 1282/// in our internal data structures. 1283void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const { 1284 for (LocalDepMapType::const_iterator I = LocalDeps.begin(), 1285 E = LocalDeps.end(); I != E; ++I) { 1286 assert(I->first != D && "Inst occurs in data structures"); 1287 assert(I->second.getInst() != D && 1288 "Inst occurs in data structures"); 1289 } 1290 1291 for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(), 1292 E = NonLocalPointerDeps.end(); I != E; ++I) { 1293 assert(I->first.getPointer() != D && "Inst occurs in NLPD map key"); 1294 const NonLocalDepInfo &Val = I->second.NonLocalDeps; 1295 for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end(); 1296 II != E; ++II) 1297 assert(II->getResult().getInst() != D && "Inst occurs as NLPD value"); 1298 } 1299 1300 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(), 1301 E = NonLocalDeps.end(); I != E; ++I) { 1302 assert(I->first != D && "Inst occurs in data structures"); 1303 const PerInstNLInfo &INLD = I->second; 1304 for (NonLocalDepInfo::const_iterator II = INLD.first.begin(), 1305 EE = INLD.first.end(); II != EE; ++II) 1306 assert(II->getResult().getInst() != D && "Inst occurs in data structures"); 1307 } 1308 1309 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(), 1310 E = ReverseLocalDeps.end(); I != E; ++I) { 1311 assert(I->first != D && "Inst occurs in data structures"); 1312 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(), 1313 EE = I->second.end(); II != EE; ++II) 1314 assert(*II != D && "Inst occurs in data structures"); 1315 } 1316 1317 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(), 1318 E = ReverseNonLocalDeps.end(); 1319 I != E; ++I) { 1320 assert(I->first != D && "Inst occurs in data structures"); 1321 for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(), 1322 EE = I->second.end(); II != EE; ++II) 1323 assert(*II != D && "Inst occurs in data structures"); 1324 } 1325 1326 for (ReverseNonLocalPtrDepTy::const_iterator 1327 I = ReverseNonLocalPtrDeps.begin(), 1328 E = ReverseNonLocalPtrDeps.end(); I != E; ++I) { 1329 assert(I->first != D && "Inst occurs in rev NLPD map"); 1330 1331 for (SmallPtrSet<ValueIsLoadPair, 4>::const_iterator II = I->second.begin(), 1332 E = I->second.end(); II != E; ++II) 1333 assert(*II != ValueIsLoadPair(D, false) && 1334 *II != ValueIsLoadPair(D, true) && 1335 "Inst occurs in ReverseNonLocalPtrDeps map"); 1336 } 1337 1338} 1339