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