1 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements an analysis that determines, for a given memory 10 // operation, what preceding memory operations it depends on. It builds on 11 // alias analysis information, and tries to provide a lazy, caching interface to 12 // a common kind of alias information query. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/AliasAnalysis.h" 23 #include "llvm/Analysis/AssumptionCache.h" 24 #include "llvm/Analysis/MemoryBuiltins.h" 25 #include "llvm/Analysis/MemoryLocation.h" 26 #include "llvm/Analysis/PHITransAddr.h" 27 #include "llvm/Analysis/PhiValues.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/IR/Attributes.h" 31 #include "llvm/IR/BasicBlock.h" 32 #include "llvm/IR/Constants.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/DerivedTypes.h" 35 #include "llvm/IR/Dominators.h" 36 #include "llvm/IR/Function.h" 37 #include "llvm/IR/InstrTypes.h" 38 #include "llvm/IR/Instruction.h" 39 #include "llvm/IR/Instructions.h" 40 #include "llvm/IR/IntrinsicInst.h" 41 #include "llvm/IR/LLVMContext.h" 42 #include "llvm/IR/Metadata.h" 43 #include "llvm/IR/Module.h" 44 #include "llvm/IR/PredIteratorCache.h" 45 #include "llvm/IR/Type.h" 46 #include "llvm/IR/Use.h" 47 #include "llvm/IR/User.h" 48 #include "llvm/IR/Value.h" 49 #include "llvm/InitializePasses.h" 50 #include "llvm/Pass.h" 51 #include "llvm/Support/AtomicOrdering.h" 52 #include "llvm/Support/Casting.h" 53 #include "llvm/Support/CommandLine.h" 54 #include "llvm/Support/Compiler.h" 55 #include "llvm/Support/Debug.h" 56 #include "llvm/Support/MathExtras.h" 57 #include <algorithm> 58 #include <cassert> 59 #include <cstdint> 60 #include <iterator> 61 #include <utility> 62 63 using namespace llvm; 64 65 #define DEBUG_TYPE "memdep" 66 67 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses"); 68 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses"); 69 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses"); 70 71 STATISTIC(NumCacheNonLocalPtr, 72 "Number of fully cached non-local ptr responses"); 73 STATISTIC(NumCacheDirtyNonLocalPtr, 74 "Number of cached, but dirty, non-local ptr responses"); 75 STATISTIC(NumUncacheNonLocalPtr, "Number of uncached non-local ptr responses"); 76 STATISTIC(NumCacheCompleteNonLocalPtr, 77 "Number of block queries that were completely cached"); 78 79 // Limit for the number of instructions to scan in a block. 80 81 static cl::opt<unsigned> BlockScanLimit( 82 "memdep-block-scan-limit", cl::Hidden, cl::init(100), 83 cl::desc("The number of instructions to scan in a block in memory " 84 "dependency analysis (default = 100)")); 85 86 static cl::opt<unsigned> 87 BlockNumberLimit("memdep-block-number-limit", cl::Hidden, cl::init(1000), 88 cl::desc("The number of blocks to scan during memory " 89 "dependency analysis (default = 1000)")); 90 91 // Limit on the number of memdep results to process. 92 static const unsigned int NumResultsLimit = 100; 93 94 /// This is a helper function that removes Val from 'Inst's set in ReverseMap. 95 /// 96 /// If the set becomes empty, remove Inst's entry. 97 template <typename KeyTy> 98 static void 99 RemoveFromReverseMap(DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>> &ReverseMap, 100 Instruction *Inst, KeyTy Val) { 101 typename DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>>::iterator InstIt = 102 ReverseMap.find(Inst); 103 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?"); 104 bool Found = InstIt->second.erase(Val); 105 assert(Found && "Invalid reverse map!"); 106 (void)Found; 107 if (InstIt->second.empty()) 108 ReverseMap.erase(InstIt); 109 } 110 111 /// If the given instruction references a specific memory location, fill in Loc 112 /// with the details, otherwise set Loc.Ptr to null. 113 /// 114 /// Returns a ModRefInfo value describing the general behavior of the 115 /// instruction. 116 static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc, 117 const TargetLibraryInfo &TLI) { 118 if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 119 if (LI->isUnordered()) { 120 Loc = MemoryLocation::get(LI); 121 return ModRefInfo::Ref; 122 } 123 if (LI->getOrdering() == AtomicOrdering::Monotonic) { 124 Loc = MemoryLocation::get(LI); 125 return ModRefInfo::ModRef; 126 } 127 Loc = MemoryLocation(); 128 return ModRefInfo::ModRef; 129 } 130 131 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 132 if (SI->isUnordered()) { 133 Loc = MemoryLocation::get(SI); 134 return ModRefInfo::Mod; 135 } 136 if (SI->getOrdering() == AtomicOrdering::Monotonic) { 137 Loc = MemoryLocation::get(SI); 138 return ModRefInfo::ModRef; 139 } 140 Loc = MemoryLocation(); 141 return ModRefInfo::ModRef; 142 } 143 144 if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) { 145 Loc = MemoryLocation::get(V); 146 return ModRefInfo::ModRef; 147 } 148 149 if (const CallInst *CI = isFreeCall(Inst, &TLI)) { 150 // calls to free() deallocate the entire structure 151 Loc = MemoryLocation::getAfter(CI->getArgOperand(0)); 152 return ModRefInfo::Mod; 153 } 154 155 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 156 switch (II->getIntrinsicID()) { 157 case Intrinsic::lifetime_start: 158 case Intrinsic::lifetime_end: 159 case Intrinsic::invariant_start: 160 Loc = MemoryLocation::getForArgument(II, 1, TLI); 161 // These intrinsics don't really modify the memory, but returning Mod 162 // will allow them to be handled conservatively. 163 return ModRefInfo::Mod; 164 case Intrinsic::invariant_end: 165 Loc = MemoryLocation::getForArgument(II, 2, TLI); 166 // These intrinsics don't really modify the memory, but returning Mod 167 // will allow them to be handled conservatively. 168 return ModRefInfo::Mod; 169 case Intrinsic::masked_load: 170 Loc = MemoryLocation::getForArgument(II, 0, TLI); 171 return ModRefInfo::Ref; 172 case Intrinsic::masked_store: 173 Loc = MemoryLocation::getForArgument(II, 1, TLI); 174 return ModRefInfo::Mod; 175 default: 176 break; 177 } 178 } 179 180 // Otherwise, just do the coarse-grained thing that always works. 181 if (Inst->mayWriteToMemory()) 182 return ModRefInfo::ModRef; 183 if (Inst->mayReadFromMemory()) 184 return ModRefInfo::Ref; 185 return ModRefInfo::NoModRef; 186 } 187 188 /// Private helper for finding the local dependencies of a call site. 189 MemDepResult MemoryDependenceResults::getCallDependencyFrom( 190 CallBase *Call, bool isReadOnlyCall, BasicBlock::iterator ScanIt, 191 BasicBlock *BB) { 192 unsigned Limit = getDefaultBlockScanLimit(); 193 194 // Walk backwards through the block, looking for dependencies. 195 while (ScanIt != BB->begin()) { 196 Instruction *Inst = &*--ScanIt; 197 // Debug intrinsics don't cause dependences and should not affect Limit 198 if (isa<DbgInfoIntrinsic>(Inst)) 199 continue; 200 201 // Limit the amount of scanning we do so we don't end up with quadratic 202 // running time on extreme testcases. 203 --Limit; 204 if (!Limit) 205 return MemDepResult::getUnknown(); 206 207 // If this inst is a memory op, get the pointer it accessed 208 MemoryLocation Loc; 209 ModRefInfo MR = GetLocation(Inst, Loc, TLI); 210 if (Loc.Ptr) { 211 // A simple instruction. 212 if (isModOrRefSet(AA.getModRefInfo(Call, Loc))) 213 return MemDepResult::getClobber(Inst); 214 continue; 215 } 216 217 if (auto *CallB = dyn_cast<CallBase>(Inst)) { 218 // If these two calls do not interfere, look past it. 219 if (isNoModRef(AA.getModRefInfo(Call, CallB))) { 220 // If the two calls are the same, return Inst as a Def, so that 221 // Call can be found redundant and eliminated. 222 if (isReadOnlyCall && !isModSet(MR) && 223 Call->isIdenticalToWhenDefined(CallB)) 224 return MemDepResult::getDef(Inst); 225 226 // Otherwise if the two calls don't interact (e.g. CallB is readnone) 227 // keep scanning. 228 continue; 229 } else 230 return MemDepResult::getClobber(Inst); 231 } 232 233 // If we could not obtain a pointer for the instruction and the instruction 234 // touches memory then assume that this is a dependency. 235 if (isModOrRefSet(MR)) 236 return MemDepResult::getClobber(Inst); 237 } 238 239 // No dependence found. If this is the entry block of the function, it is 240 // unknown, otherwise it is non-local. 241 if (BB != &BB->getParent()->getEntryBlock()) 242 return MemDepResult::getNonLocal(); 243 return MemDepResult::getNonFuncLocal(); 244 } 245 246 MemDepResult MemoryDependenceResults::getPointerDependencyFrom( 247 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt, 248 BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) { 249 MemDepResult InvariantGroupDependency = MemDepResult::getUnknown(); 250 if (QueryInst != nullptr) { 251 if (auto *LI = dyn_cast<LoadInst>(QueryInst)) { 252 InvariantGroupDependency = getInvariantGroupPointerDependency(LI, BB); 253 254 if (InvariantGroupDependency.isDef()) 255 return InvariantGroupDependency; 256 } 257 } 258 MemDepResult SimpleDep = getSimplePointerDependencyFrom( 259 MemLoc, isLoad, ScanIt, BB, QueryInst, Limit); 260 if (SimpleDep.isDef()) 261 return SimpleDep; 262 // Non-local invariant group dependency indicates there is non local Def 263 // (it only returns nonLocal if it finds nonLocal def), which is better than 264 // local clobber and everything else. 265 if (InvariantGroupDependency.isNonLocal()) 266 return InvariantGroupDependency; 267 268 assert(InvariantGroupDependency.isUnknown() && 269 "InvariantGroupDependency should be only unknown at this point"); 270 return SimpleDep; 271 } 272 273 MemDepResult 274 MemoryDependenceResults::getInvariantGroupPointerDependency(LoadInst *LI, 275 BasicBlock *BB) { 276 277 if (!LI->hasMetadata(LLVMContext::MD_invariant_group)) 278 return MemDepResult::getUnknown(); 279 280 // Take the ptr operand after all casts and geps 0. This way we can search 281 // cast graph down only. 282 Value *LoadOperand = LI->getPointerOperand()->stripPointerCasts(); 283 284 // It's is not safe to walk the use list of global value, because function 285 // passes aren't allowed to look outside their functions. 286 // FIXME: this could be fixed by filtering instructions from outside 287 // of current function. 288 if (isa<GlobalValue>(LoadOperand)) 289 return MemDepResult::getUnknown(); 290 291 // Queue to process all pointers that are equivalent to load operand. 292 SmallVector<const Value *, 8> LoadOperandsQueue; 293 LoadOperandsQueue.push_back(LoadOperand); 294 295 Instruction *ClosestDependency = nullptr; 296 // Order of instructions in uses list is unpredictible. In order to always 297 // get the same result, we will look for the closest dominance. 298 auto GetClosestDependency = [this](Instruction *Best, Instruction *Other) { 299 assert(Other && "Must call it with not null instruction"); 300 if (Best == nullptr || DT.dominates(Best, Other)) 301 return Other; 302 return Best; 303 }; 304 305 // FIXME: This loop is O(N^2) because dominates can be O(n) and in worst case 306 // we will see all the instructions. This should be fixed in MSSA. 307 while (!LoadOperandsQueue.empty()) { 308 const Value *Ptr = LoadOperandsQueue.pop_back_val(); 309 assert(Ptr && !isa<GlobalValue>(Ptr) && 310 "Null or GlobalValue should not be inserted"); 311 312 for (const Use &Us : Ptr->uses()) { 313 auto *U = dyn_cast<Instruction>(Us.getUser()); 314 if (!U || U == LI || !DT.dominates(U, LI)) 315 continue; 316 317 // Bitcast or gep with zeros are using Ptr. Add to queue to check it's 318 // users. U = bitcast Ptr 319 if (isa<BitCastInst>(U)) { 320 LoadOperandsQueue.push_back(U); 321 continue; 322 } 323 // Gep with zeros is equivalent to bitcast. 324 // FIXME: we are not sure if some bitcast should be canonicalized to gep 0 325 // or gep 0 to bitcast because of SROA, so there are 2 forms. When 326 // typeless pointers will be ready then both cases will be gone 327 // (and this BFS also won't be needed). 328 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) 329 if (GEP->hasAllZeroIndices()) { 330 LoadOperandsQueue.push_back(U); 331 continue; 332 } 333 334 // If we hit load/store with the same invariant.group metadata (and the 335 // same pointer operand) we can assume that value pointed by pointer 336 // operand didn't change. 337 if ((isa<LoadInst>(U) || 338 (isa<StoreInst>(U) && 339 cast<StoreInst>(U)->getPointerOperand() == Ptr)) && 340 U->hasMetadata(LLVMContext::MD_invariant_group)) 341 ClosestDependency = GetClosestDependency(ClosestDependency, U); 342 } 343 } 344 345 if (!ClosestDependency) 346 return MemDepResult::getUnknown(); 347 if (ClosestDependency->getParent() == BB) 348 return MemDepResult::getDef(ClosestDependency); 349 // Def(U) can't be returned here because it is non-local. If local 350 // dependency won't be found then return nonLocal counting that the 351 // user will call getNonLocalPointerDependency, which will return cached 352 // result. 353 NonLocalDefsCache.try_emplace( 354 LI, NonLocalDepResult(ClosestDependency->getParent(), 355 MemDepResult::getDef(ClosestDependency), nullptr)); 356 ReverseNonLocalDefsCache[ClosestDependency].insert(LI); 357 return MemDepResult::getNonLocal(); 358 } 359 360 MemDepResult MemoryDependenceResults::getSimplePointerDependencyFrom( 361 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt, 362 BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) { 363 // We can batch AA queries, because IR does not change during a MemDep query. 364 BatchAAResults BatchAA(AA); 365 bool isInvariantLoad = false; 366 367 unsigned DefaultLimit = getDefaultBlockScanLimit(); 368 if (!Limit) 369 Limit = &DefaultLimit; 370 371 // We must be careful with atomic accesses, as they may allow another thread 372 // to touch this location, clobbering it. We are conservative: if the 373 // QueryInst is not a simple (non-atomic) memory access, we automatically 374 // return getClobber. 375 // If it is simple, we know based on the results of 376 // "Compiler testing via a theory of sound optimisations in the C11/C++11 377 // memory model" in PLDI 2013, that a non-atomic location can only be 378 // clobbered between a pair of a release and an acquire action, with no 379 // access to the location in between. 380 // Here is an example for giving the general intuition behind this rule. 381 // In the following code: 382 // store x 0; 383 // release action; [1] 384 // acquire action; [4] 385 // %val = load x; 386 // It is unsafe to replace %val by 0 because another thread may be running: 387 // acquire action; [2] 388 // store x 42; 389 // release action; [3] 390 // with synchronization from 1 to 2 and from 3 to 4, resulting in %val 391 // being 42. A key property of this program however is that if either 392 // 1 or 4 were missing, there would be a race between the store of 42 393 // either the store of 0 or the load (making the whole program racy). 394 // The paper mentioned above shows that the same property is respected 395 // by every program that can detect any optimization of that kind: either 396 // it is racy (undefined) or there is a release followed by an acquire 397 // between the pair of accesses under consideration. 398 399 // If the load is invariant, we "know" that it doesn't alias *any* write. We 400 // do want to respect mustalias results since defs are useful for value 401 // forwarding, but any mayalias write can be assumed to be noalias. 402 // Arguably, this logic should be pushed inside AliasAnalysis itself. 403 if (isLoad && QueryInst) { 404 LoadInst *LI = dyn_cast<LoadInst>(QueryInst); 405 if (LI && LI->hasMetadata(LLVMContext::MD_invariant_load)) 406 isInvariantLoad = true; 407 } 408 409 // Return "true" if and only if the instruction I is either a non-simple 410 // load or a non-simple store. 411 auto isNonSimpleLoadOrStore = [](Instruction *I) -> bool { 412 if (auto *LI = dyn_cast<LoadInst>(I)) 413 return !LI->isSimple(); 414 if (auto *SI = dyn_cast<StoreInst>(I)) 415 return !SI->isSimple(); 416 return false; 417 }; 418 419 // Return "true" if I is not a load and not a store, but it does access 420 // memory. 421 auto isOtherMemAccess = [](Instruction *I) -> bool { 422 return !isa<LoadInst>(I) && !isa<StoreInst>(I) && I->mayReadOrWriteMemory(); 423 }; 424 425 // Walk backwards through the basic block, looking for dependencies. 426 while (ScanIt != BB->begin()) { 427 Instruction *Inst = &*--ScanIt; 428 429 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) 430 // Debug intrinsics don't (and can't) cause dependencies. 431 if (isa<DbgInfoIntrinsic>(II)) 432 continue; 433 434 // Limit the amount of scanning we do so we don't end up with quadratic 435 // running time on extreme testcases. 436 --*Limit; 437 if (!*Limit) 438 return MemDepResult::getUnknown(); 439 440 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 441 // If we reach a lifetime begin or end marker, then the query ends here 442 // because the value is undefined. 443 Intrinsic::ID ID = II->getIntrinsicID(); 444 switch (ID) { 445 case Intrinsic::lifetime_start: { 446 // FIXME: This only considers queries directly on the invariant-tagged 447 // pointer, not on query pointers that are indexed off of them. It'd 448 // be nice to handle that at some point (the right approach is to use 449 // GetPointerBaseWithConstantOffset). 450 MemoryLocation ArgLoc = MemoryLocation::getAfter(II->getArgOperand(1)); 451 if (BatchAA.isMustAlias(ArgLoc, MemLoc)) 452 return MemDepResult::getDef(II); 453 continue; 454 } 455 case Intrinsic::masked_load: 456 case Intrinsic::masked_store: { 457 MemoryLocation Loc; 458 /*ModRefInfo MR =*/ GetLocation(II, Loc, TLI); 459 AliasResult R = BatchAA.alias(Loc, MemLoc); 460 if (R == AliasResult::NoAlias) 461 continue; 462 if (R == AliasResult::MustAlias) 463 return MemDepResult::getDef(II); 464 if (ID == Intrinsic::masked_load) 465 continue; 466 return MemDepResult::getClobber(II); 467 } 468 } 469 } 470 471 // Values depend on loads if the pointers are must aliased. This means 472 // that a load depends on another must aliased load from the same value. 473 // One exception is atomic loads: a value can depend on an atomic load that 474 // it does not alias with when this atomic load indicates that another 475 // thread may be accessing the location. 476 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 477 // While volatile access cannot be eliminated, they do not have to clobber 478 // non-aliasing locations, as normal accesses, for example, can be safely 479 // reordered with volatile accesses. 480 if (LI->isVolatile()) { 481 if (!QueryInst) 482 // Original QueryInst *may* be volatile 483 return MemDepResult::getClobber(LI); 484 if (QueryInst->isVolatile()) 485 // Ordering required if QueryInst is itself volatile 486 return MemDepResult::getClobber(LI); 487 // Otherwise, volatile doesn't imply any special ordering 488 } 489 490 // Atomic loads have complications involved. 491 // A Monotonic (or higher) load is OK if the query inst is itself not 492 // atomic. 493 // FIXME: This is overly conservative. 494 if (LI->isAtomic() && isStrongerThanUnordered(LI->getOrdering())) { 495 if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) || 496 isOtherMemAccess(QueryInst)) 497 return MemDepResult::getClobber(LI); 498 if (LI->getOrdering() != AtomicOrdering::Monotonic) 499 return MemDepResult::getClobber(LI); 500 } 501 502 MemoryLocation LoadLoc = MemoryLocation::get(LI); 503 504 // If we found a pointer, check if it could be the same as our pointer. 505 AliasResult R = BatchAA.alias(LoadLoc, MemLoc); 506 507 if (isLoad) { 508 if (R == AliasResult::NoAlias) 509 continue; 510 511 // Must aliased loads are defs of each other. 512 if (R == AliasResult::MustAlias) 513 return MemDepResult::getDef(Inst); 514 515 // If we have a partial alias, then return this as a clobber for the 516 // client to handle. 517 if (R == AliasResult::PartialAlias && R.hasOffset()) { 518 ClobberOffsets[LI] = R.getOffset(); 519 return MemDepResult::getClobber(Inst); 520 } 521 522 // Random may-alias loads don't depend on each other without a 523 // dependence. 524 continue; 525 } 526 527 // Stores don't depend on other no-aliased accesses. 528 if (R == AliasResult::NoAlias) 529 continue; 530 531 // Stores don't alias loads from read-only memory. 532 if (BatchAA.pointsToConstantMemory(LoadLoc)) 533 continue; 534 535 // Stores depend on may/must aliased loads. 536 return MemDepResult::getDef(Inst); 537 } 538 539 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 540 // Atomic stores have complications involved. 541 // A Monotonic store is OK if the query inst is itself not atomic. 542 // FIXME: This is overly conservative. 543 if (!SI->isUnordered() && SI->isAtomic()) { 544 if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) || 545 isOtherMemAccess(QueryInst)) 546 return MemDepResult::getClobber(SI); 547 if (SI->getOrdering() != AtomicOrdering::Monotonic) 548 return MemDepResult::getClobber(SI); 549 } 550 551 // FIXME: this is overly conservative. 552 // While volatile access cannot be eliminated, they do not have to clobber 553 // non-aliasing locations, as normal accesses can for example be reordered 554 // with volatile accesses. 555 if (SI->isVolatile()) 556 if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) || 557 isOtherMemAccess(QueryInst)) 558 return MemDepResult::getClobber(SI); 559 560 // If alias analysis can tell that this store is guaranteed to not modify 561 // the query pointer, ignore it. Use getModRefInfo to handle cases where 562 // the query pointer points to constant memory etc. 563 if (!isModOrRefSet(BatchAA.getModRefInfo(SI, MemLoc))) 564 continue; 565 566 // Ok, this store might clobber the query pointer. Check to see if it is 567 // a must alias: in this case, we want to return this as a def. 568 // FIXME: Use ModRefInfo::Must bit from getModRefInfo call above. 569 MemoryLocation StoreLoc = MemoryLocation::get(SI); 570 571 // If we found a pointer, check if it could be the same as our pointer. 572 AliasResult R = BatchAA.alias(StoreLoc, MemLoc); 573 574 if (R == AliasResult::NoAlias) 575 continue; 576 if (R == AliasResult::MustAlias) 577 return MemDepResult::getDef(Inst); 578 if (isInvariantLoad) 579 continue; 580 return MemDepResult::getClobber(Inst); 581 } 582 583 // If this is an allocation, and if we know that the accessed pointer is to 584 // the allocation, return Def. This means that there is no dependence and 585 // the access can be optimized based on that. For example, a load could 586 // turn into undef. Note that we can bypass the allocation itself when 587 // looking for a clobber in many cases; that's an alias property and is 588 // handled by BasicAA. 589 if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, &TLI)) { 590 const Value *AccessPtr = getUnderlyingObject(MemLoc.Ptr); 591 if (AccessPtr == Inst || BatchAA.isMustAlias(Inst, AccessPtr)) 592 return MemDepResult::getDef(Inst); 593 } 594 595 if (isInvariantLoad) 596 continue; 597 598 // A release fence requires that all stores complete before it, but does 599 // not prevent the reordering of following loads or stores 'before' the 600 // fence. As a result, we look past it when finding a dependency for 601 // loads. DSE uses this to find preceding stores to delete and thus we 602 // can't bypass the fence if the query instruction is a store. 603 if (FenceInst *FI = dyn_cast<FenceInst>(Inst)) 604 if (isLoad && FI->getOrdering() == AtomicOrdering::Release) 605 continue; 606 607 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer. 608 ModRefInfo MR = BatchAA.getModRefInfo(Inst, MemLoc); 609 // If necessary, perform additional analysis. 610 if (isModAndRefSet(MR)) 611 // TODO: Support callCapturesBefore() on BatchAAResults. 612 MR = AA.callCapturesBefore(Inst, MemLoc, &DT); 613 switch (clearMust(MR)) { 614 case ModRefInfo::NoModRef: 615 // If the call has no effect on the queried pointer, just ignore it. 616 continue; 617 case ModRefInfo::Mod: 618 return MemDepResult::getClobber(Inst); 619 case ModRefInfo::Ref: 620 // If the call is known to never store to the pointer, and if this is a 621 // load query, we can safely ignore it (scan past it). 622 if (isLoad) 623 continue; 624 LLVM_FALLTHROUGH; 625 default: 626 // Otherwise, there is a potential dependence. Return a clobber. 627 return MemDepResult::getClobber(Inst); 628 } 629 } 630 631 // No dependence found. If this is the entry block of the function, it is 632 // unknown, otherwise it is non-local. 633 if (BB != &BB->getParent()->getEntryBlock()) 634 return MemDepResult::getNonLocal(); 635 return MemDepResult::getNonFuncLocal(); 636 } 637 638 MemDepResult MemoryDependenceResults::getDependency(Instruction *QueryInst) { 639 ClobberOffsets.clear(); 640 Instruction *ScanPos = QueryInst; 641 642 // Check for a cached result 643 MemDepResult &LocalCache = LocalDeps[QueryInst]; 644 645 // If the cached entry is non-dirty, just return it. Note that this depends 646 // on MemDepResult's default constructing to 'dirty'. 647 if (!LocalCache.isDirty()) 648 return LocalCache; 649 650 // Otherwise, if we have a dirty entry, we know we can start the scan at that 651 // instruction, which may save us some work. 652 if (Instruction *Inst = LocalCache.getInst()) { 653 ScanPos = Inst; 654 655 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst); 656 } 657 658 BasicBlock *QueryParent = QueryInst->getParent(); 659 660 // Do the scan. 661 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) { 662 // No dependence found. If this is the entry block of the function, it is 663 // unknown, otherwise it is non-local. 664 if (QueryParent != &QueryParent->getParent()->getEntryBlock()) 665 LocalCache = MemDepResult::getNonLocal(); 666 else 667 LocalCache = MemDepResult::getNonFuncLocal(); 668 } else { 669 MemoryLocation MemLoc; 670 ModRefInfo MR = GetLocation(QueryInst, MemLoc, TLI); 671 if (MemLoc.Ptr) { 672 // If we can do a pointer scan, make it happen. 673 bool isLoad = !isModSet(MR); 674 if (auto *II = dyn_cast<IntrinsicInst>(QueryInst)) 675 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start; 676 677 LocalCache = 678 getPointerDependencyFrom(MemLoc, isLoad, ScanPos->getIterator(), 679 QueryParent, QueryInst, nullptr); 680 } else if (auto *QueryCall = dyn_cast<CallBase>(QueryInst)) { 681 bool isReadOnly = AA.onlyReadsMemory(QueryCall); 682 LocalCache = getCallDependencyFrom(QueryCall, isReadOnly, 683 ScanPos->getIterator(), QueryParent); 684 } else 685 // Non-memory instruction. 686 LocalCache = MemDepResult::getUnknown(); 687 } 688 689 // Remember the result! 690 if (Instruction *I = LocalCache.getInst()) 691 ReverseLocalDeps[I].insert(QueryInst); 692 693 return LocalCache; 694 } 695 696 #ifndef NDEBUG 697 /// This method is used when -debug is specified to verify that cache arrays 698 /// are properly kept sorted. 699 static void AssertSorted(MemoryDependenceResults::NonLocalDepInfo &Cache, 700 int Count = -1) { 701 if (Count == -1) 702 Count = Cache.size(); 703 assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) && 704 "Cache isn't sorted!"); 705 } 706 #endif 707 708 const MemoryDependenceResults::NonLocalDepInfo & 709 MemoryDependenceResults::getNonLocalCallDependency(CallBase *QueryCall) { 710 assert(getDependency(QueryCall).isNonLocal() && 711 "getNonLocalCallDependency should only be used on calls with " 712 "non-local deps!"); 713 PerInstNLInfo &CacheP = NonLocalDeps[QueryCall]; 714 NonLocalDepInfo &Cache = CacheP.first; 715 716 // This is the set of blocks that need to be recomputed. In the cached case, 717 // this can happen due to instructions being deleted etc. In the uncached 718 // case, this starts out as the set of predecessors we care about. 719 SmallVector<BasicBlock *, 32> DirtyBlocks; 720 721 if (!Cache.empty()) { 722 // Okay, we have a cache entry. If we know it is not dirty, just return it 723 // with no computation. 724 if (!CacheP.second) { 725 ++NumCacheNonLocal; 726 return Cache; 727 } 728 729 // If we already have a partially computed set of results, scan them to 730 // determine what is dirty, seeding our initial DirtyBlocks worklist. 731 for (auto &Entry : Cache) 732 if (Entry.getResult().isDirty()) 733 DirtyBlocks.push_back(Entry.getBB()); 734 735 // Sort the cache so that we can do fast binary search lookups below. 736 llvm::sort(Cache); 737 738 ++NumCacheDirtyNonLocal; 739 // cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: " 740 // << Cache.size() << " cached: " << *QueryInst; 741 } else { 742 // Seed DirtyBlocks with each of the preds of QueryInst's block. 743 BasicBlock *QueryBB = QueryCall->getParent(); 744 append_range(DirtyBlocks, PredCache.get(QueryBB)); 745 ++NumUncacheNonLocal; 746 } 747 748 // isReadonlyCall - If this is a read-only call, we can be more aggressive. 749 bool isReadonlyCall = AA.onlyReadsMemory(QueryCall); 750 751 SmallPtrSet<BasicBlock *, 32> Visited; 752 753 unsigned NumSortedEntries = Cache.size(); 754 LLVM_DEBUG(AssertSorted(Cache)); 755 756 // Iterate while we still have blocks to update. 757 while (!DirtyBlocks.empty()) { 758 BasicBlock *DirtyBB = DirtyBlocks.pop_back_val(); 759 760 // Already processed this block? 761 if (!Visited.insert(DirtyBB).second) 762 continue; 763 764 // Do a binary search to see if we already have an entry for this block in 765 // the cache set. If so, find it. 766 LLVM_DEBUG(AssertSorted(Cache, NumSortedEntries)); 767 NonLocalDepInfo::iterator Entry = 768 std::upper_bound(Cache.begin(), Cache.begin() + NumSortedEntries, 769 NonLocalDepEntry(DirtyBB)); 770 if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB) 771 --Entry; 772 773 NonLocalDepEntry *ExistingResult = nullptr; 774 if (Entry != Cache.begin() + NumSortedEntries && 775 Entry->getBB() == DirtyBB) { 776 // If we already have an entry, and if it isn't already dirty, the block 777 // is done. 778 if (!Entry->getResult().isDirty()) 779 continue; 780 781 // Otherwise, remember this slot so we can update the value. 782 ExistingResult = &*Entry; 783 } 784 785 // If the dirty entry has a pointer, start scanning from it so we don't have 786 // to rescan the entire block. 787 BasicBlock::iterator ScanPos = DirtyBB->end(); 788 if (ExistingResult) { 789 if (Instruction *Inst = ExistingResult->getResult().getInst()) { 790 ScanPos = Inst->getIterator(); 791 // We're removing QueryInst's use of Inst. 792 RemoveFromReverseMap<Instruction *>(ReverseNonLocalDeps, Inst, 793 QueryCall); 794 } 795 } 796 797 // Find out if this block has a local dependency for QueryInst. 798 MemDepResult Dep; 799 800 if (ScanPos != DirtyBB->begin()) { 801 Dep = getCallDependencyFrom(QueryCall, isReadonlyCall, ScanPos, DirtyBB); 802 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) { 803 // No dependence found. If this is the entry block of the function, it is 804 // a clobber, otherwise it is unknown. 805 Dep = MemDepResult::getNonLocal(); 806 } else { 807 Dep = MemDepResult::getNonFuncLocal(); 808 } 809 810 // If we had a dirty entry for the block, update it. Otherwise, just add 811 // a new entry. 812 if (ExistingResult) 813 ExistingResult->setResult(Dep); 814 else 815 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep)); 816 817 // If the block has a dependency (i.e. it isn't completely transparent to 818 // the value), remember the association! 819 if (!Dep.isNonLocal()) { 820 // Keep the ReverseNonLocalDeps map up to date so we can efficiently 821 // update this when we remove instructions. 822 if (Instruction *Inst = Dep.getInst()) 823 ReverseNonLocalDeps[Inst].insert(QueryCall); 824 } else { 825 826 // If the block *is* completely transparent to the load, we need to check 827 // the predecessors of this block. Add them to our worklist. 828 append_range(DirtyBlocks, PredCache.get(DirtyBB)); 829 } 830 } 831 832 return Cache; 833 } 834 835 void MemoryDependenceResults::getNonLocalPointerDependency( 836 Instruction *QueryInst, SmallVectorImpl<NonLocalDepResult> &Result) { 837 const MemoryLocation Loc = MemoryLocation::get(QueryInst); 838 bool isLoad = isa<LoadInst>(QueryInst); 839 BasicBlock *FromBB = QueryInst->getParent(); 840 assert(FromBB); 841 842 assert(Loc.Ptr->getType()->isPointerTy() && 843 "Can't get pointer deps of a non-pointer!"); 844 Result.clear(); 845 { 846 // Check if there is cached Def with invariant.group. 847 auto NonLocalDefIt = NonLocalDefsCache.find(QueryInst); 848 if (NonLocalDefIt != NonLocalDefsCache.end()) { 849 Result.push_back(NonLocalDefIt->second); 850 ReverseNonLocalDefsCache[NonLocalDefIt->second.getResult().getInst()] 851 .erase(QueryInst); 852 NonLocalDefsCache.erase(NonLocalDefIt); 853 return; 854 } 855 } 856 // This routine does not expect to deal with volatile instructions. 857 // Doing so would require piping through the QueryInst all the way through. 858 // TODO: volatiles can't be elided, but they can be reordered with other 859 // non-volatile accesses. 860 861 // We currently give up on any instruction which is ordered, but we do handle 862 // atomic instructions which are unordered. 863 // TODO: Handle ordered instructions 864 auto isOrdered = [](Instruction *Inst) { 865 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 866 return !LI->isUnordered(); 867 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 868 return !SI->isUnordered(); 869 } 870 return false; 871 }; 872 if (QueryInst->isVolatile() || isOrdered(QueryInst)) { 873 Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(), 874 const_cast<Value *>(Loc.Ptr))); 875 return; 876 } 877 const DataLayout &DL = FromBB->getModule()->getDataLayout(); 878 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC); 879 880 // This is the set of blocks we've inspected, and the pointer we consider in 881 // each block. Because of critical edges, we currently bail out if querying 882 // a block with multiple different pointers. This can happen during PHI 883 // translation. 884 DenseMap<BasicBlock *, Value *> Visited; 885 if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB, 886 Result, Visited, true)) 887 return; 888 Result.clear(); 889 Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(), 890 const_cast<Value *>(Loc.Ptr))); 891 } 892 893 /// Compute the memdep value for BB with Pointer/PointeeSize using either 894 /// cached information in Cache or by doing a lookup (which may use dirty cache 895 /// info if available). 896 /// 897 /// If we do a lookup, add the result to the cache. 898 MemDepResult MemoryDependenceResults::GetNonLocalInfoForBlock( 899 Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad, 900 BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries) { 901 902 bool isInvariantLoad = false; 903 904 if (LoadInst *LI = dyn_cast_or_null<LoadInst>(QueryInst)) 905 isInvariantLoad = LI->getMetadata(LLVMContext::MD_invariant_load); 906 907 // Do a binary search to see if we already have an entry for this block in 908 // the cache set. If so, find it. 909 NonLocalDepInfo::iterator Entry = std::upper_bound( 910 Cache->begin(), Cache->begin() + NumSortedEntries, NonLocalDepEntry(BB)); 911 if (Entry != Cache->begin() && (Entry - 1)->getBB() == BB) 912 --Entry; 913 914 NonLocalDepEntry *ExistingResult = nullptr; 915 if (Entry != Cache->begin() + NumSortedEntries && Entry->getBB() == BB) 916 ExistingResult = &*Entry; 917 918 // Use cached result for invariant load only if there is no dependency for non 919 // invariant load. In this case invariant load can not have any dependency as 920 // well. 921 if (ExistingResult && isInvariantLoad && 922 !ExistingResult->getResult().isNonFuncLocal()) 923 ExistingResult = nullptr; 924 925 // If we have a cached entry, and it is non-dirty, use it as the value for 926 // this dependency. 927 if (ExistingResult && !ExistingResult->getResult().isDirty()) { 928 ++NumCacheNonLocalPtr; 929 return ExistingResult->getResult(); 930 } 931 932 // Otherwise, we have to scan for the value. If we have a dirty cache 933 // entry, start scanning from its position, otherwise we scan from the end 934 // of the block. 935 BasicBlock::iterator ScanPos = BB->end(); 936 if (ExistingResult && ExistingResult->getResult().getInst()) { 937 assert(ExistingResult->getResult().getInst()->getParent() == BB && 938 "Instruction invalidated?"); 939 ++NumCacheDirtyNonLocalPtr; 940 ScanPos = ExistingResult->getResult().getInst()->getIterator(); 941 942 // Eliminating the dirty entry from 'Cache', so update the reverse info. 943 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad); 944 RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey); 945 } else { 946 ++NumUncacheNonLocalPtr; 947 } 948 949 // Scan the block for the dependency. 950 MemDepResult Dep = 951 getPointerDependencyFrom(Loc, isLoad, ScanPos, BB, QueryInst); 952 953 // Don't cache results for invariant load. 954 if (isInvariantLoad) 955 return Dep; 956 957 // If we had a dirty entry for the block, update it. Otherwise, just add 958 // a new entry. 959 if (ExistingResult) 960 ExistingResult->setResult(Dep); 961 else 962 Cache->push_back(NonLocalDepEntry(BB, Dep)); 963 964 // If the block has a dependency (i.e. it isn't completely transparent to 965 // the value), remember the reverse association because we just added it 966 // to Cache! 967 if (!Dep.isDef() && !Dep.isClobber()) 968 return Dep; 969 970 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently 971 // update MemDep when we remove instructions. 972 Instruction *Inst = Dep.getInst(); 973 assert(Inst && "Didn't depend on anything?"); 974 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad); 975 ReverseNonLocalPtrDeps[Inst].insert(CacheKey); 976 return Dep; 977 } 978 979 /// Sort the NonLocalDepInfo cache, given a certain number of elements in the 980 /// array that are already properly ordered. 981 /// 982 /// This is optimized for the case when only a few entries are added. 983 static void 984 SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache, 985 unsigned NumSortedEntries) { 986 switch (Cache.size() - NumSortedEntries) { 987 case 0: 988 // done, no new entries. 989 break; 990 case 2: { 991 // Two new entries, insert the last one into place. 992 NonLocalDepEntry Val = Cache.back(); 993 Cache.pop_back(); 994 MemoryDependenceResults::NonLocalDepInfo::iterator Entry = 995 std::upper_bound(Cache.begin(), Cache.end() - 1, Val); 996 Cache.insert(Entry, Val); 997 LLVM_FALLTHROUGH; 998 } 999 case 1: 1000 // One new entry, Just insert the new value at the appropriate position. 1001 if (Cache.size() != 1) { 1002 NonLocalDepEntry Val = Cache.back(); 1003 Cache.pop_back(); 1004 MemoryDependenceResults::NonLocalDepInfo::iterator Entry = 1005 llvm::upper_bound(Cache, Val); 1006 Cache.insert(Entry, Val); 1007 } 1008 break; 1009 default: 1010 // Added many values, do a full scale sort. 1011 llvm::sort(Cache); 1012 break; 1013 } 1014 } 1015 1016 /// Perform a dependency query based on pointer/pointeesize starting at the end 1017 /// of StartBB. 1018 /// 1019 /// Add any clobber/def results to the results vector and keep track of which 1020 /// blocks are visited in 'Visited'. 1021 /// 1022 /// This has special behavior for the first block queries (when SkipFirstBlock 1023 /// is true). In this special case, it ignores the contents of the specified 1024 /// block and starts returning dependence info for its predecessors. 1025 /// 1026 /// This function returns true on success, or false to indicate that it could 1027 /// not compute dependence information for some reason. This should be treated 1028 /// as a clobber dependence on the first instruction in the predecessor block. 1029 bool MemoryDependenceResults::getNonLocalPointerDepFromBB( 1030 Instruction *QueryInst, const PHITransAddr &Pointer, 1031 const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB, 1032 SmallVectorImpl<NonLocalDepResult> &Result, 1033 DenseMap<BasicBlock *, Value *> &Visited, bool SkipFirstBlock, 1034 bool IsIncomplete) { 1035 // Look up the cached info for Pointer. 1036 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad); 1037 1038 // Set up a temporary NLPI value. If the map doesn't yet have an entry for 1039 // CacheKey, this value will be inserted as the associated value. Otherwise, 1040 // it'll be ignored, and we'll have to check to see if the cached size and 1041 // aa tags are consistent with the current query. 1042 NonLocalPointerInfo InitialNLPI; 1043 InitialNLPI.Size = Loc.Size; 1044 InitialNLPI.AATags = Loc.AATags; 1045 1046 bool isInvariantLoad = false; 1047 if (LoadInst *LI = dyn_cast_or_null<LoadInst>(QueryInst)) 1048 isInvariantLoad = LI->getMetadata(LLVMContext::MD_invariant_load); 1049 1050 // Get the NLPI for CacheKey, inserting one into the map if it doesn't 1051 // already have one. 1052 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair = 1053 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI)); 1054 NonLocalPointerInfo *CacheInfo = &Pair.first->second; 1055 1056 // If we already have a cache entry for this CacheKey, we may need to do some 1057 // work to reconcile the cache entry and the current query. 1058 // Invariant loads don't participate in caching. Thus no need to reconcile. 1059 if (!isInvariantLoad && !Pair.second) { 1060 if (CacheInfo->Size != Loc.Size) { 1061 bool ThrowOutEverything; 1062 if (CacheInfo->Size.hasValue() && Loc.Size.hasValue()) { 1063 // FIXME: We may be able to do better in the face of results with mixed 1064 // precision. We don't appear to get them in practice, though, so just 1065 // be conservative. 1066 ThrowOutEverything = 1067 CacheInfo->Size.isPrecise() != Loc.Size.isPrecise() || 1068 CacheInfo->Size.getValue() < Loc.Size.getValue(); 1069 } else { 1070 // For our purposes, unknown size > all others. 1071 ThrowOutEverything = !Loc.Size.hasValue(); 1072 } 1073 1074 if (ThrowOutEverything) { 1075 // The query's Size is greater than the cached one. Throw out the 1076 // cached data and proceed with the query at the greater size. 1077 CacheInfo->Pair = BBSkipFirstBlockPair(); 1078 CacheInfo->Size = Loc.Size; 1079 for (auto &Entry : CacheInfo->NonLocalDeps) 1080 if (Instruction *Inst = Entry.getResult().getInst()) 1081 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey); 1082 CacheInfo->NonLocalDeps.clear(); 1083 // The cache is cleared (in the above line) so we will have lost 1084 // information about blocks we have already visited. We therefore must 1085 // assume that the cache information is incomplete. 1086 IsIncomplete = true; 1087 } else { 1088 // This query's Size is less than the cached one. Conservatively restart 1089 // the query using the greater size. 1090 return getNonLocalPointerDepFromBB( 1091 QueryInst, Pointer, Loc.getWithNewSize(CacheInfo->Size), isLoad, 1092 StartBB, Result, Visited, SkipFirstBlock, IsIncomplete); 1093 } 1094 } 1095 1096 // If the query's AATags are inconsistent with the cached one, 1097 // conservatively throw out the cached data and restart the query with 1098 // no tag if needed. 1099 if (CacheInfo->AATags != Loc.AATags) { 1100 if (CacheInfo->AATags) { 1101 CacheInfo->Pair = BBSkipFirstBlockPair(); 1102 CacheInfo->AATags = AAMDNodes(); 1103 for (auto &Entry : CacheInfo->NonLocalDeps) 1104 if (Instruction *Inst = Entry.getResult().getInst()) 1105 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey); 1106 CacheInfo->NonLocalDeps.clear(); 1107 // The cache is cleared (in the above line) so we will have lost 1108 // information about blocks we have already visited. We therefore must 1109 // assume that the cache information is incomplete. 1110 IsIncomplete = true; 1111 } 1112 if (Loc.AATags) 1113 return getNonLocalPointerDepFromBB( 1114 QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result, 1115 Visited, SkipFirstBlock, IsIncomplete); 1116 } 1117 } 1118 1119 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps; 1120 1121 // If we have valid cached information for exactly the block we are 1122 // investigating, just return it with no recomputation. 1123 // Don't use cached information for invariant loads since it is valid for 1124 // non-invariant loads only. 1125 if (!IsIncomplete && !isInvariantLoad && 1126 CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) { 1127 // We have a fully cached result for this query then we can just return the 1128 // cached results and populate the visited set. However, we have to verify 1129 // that we don't already have conflicting results for these blocks. Check 1130 // to ensure that if a block in the results set is in the visited set that 1131 // it was for the same pointer query. 1132 if (!Visited.empty()) { 1133 for (auto &Entry : *Cache) { 1134 DenseMap<BasicBlock *, Value *>::iterator VI = 1135 Visited.find(Entry.getBB()); 1136 if (VI == Visited.end() || VI->second == Pointer.getAddr()) 1137 continue; 1138 1139 // We have a pointer mismatch in a block. Just return false, saying 1140 // that something was clobbered in this result. We could also do a 1141 // non-fully cached query, but there is little point in doing this. 1142 return false; 1143 } 1144 } 1145 1146 Value *Addr = Pointer.getAddr(); 1147 for (auto &Entry : *Cache) { 1148 Visited.insert(std::make_pair(Entry.getBB(), Addr)); 1149 if (Entry.getResult().isNonLocal()) { 1150 continue; 1151 } 1152 1153 if (DT.isReachableFromEntry(Entry.getBB())) { 1154 Result.push_back( 1155 NonLocalDepResult(Entry.getBB(), Entry.getResult(), Addr)); 1156 } 1157 } 1158 ++NumCacheCompleteNonLocalPtr; 1159 return true; 1160 } 1161 1162 // Otherwise, either this is a new block, a block with an invalid cache 1163 // pointer or one that we're about to invalidate by putting more info into 1164 // it than its valid cache info. If empty and not explicitly indicated as 1165 // incomplete, the result will be valid cache info, otherwise it isn't. 1166 // 1167 // Invariant loads don't affect cache in any way thus no need to update 1168 // CacheInfo as well. 1169 if (!isInvariantLoad) { 1170 if (!IsIncomplete && Cache->empty()) 1171 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock); 1172 else 1173 CacheInfo->Pair = BBSkipFirstBlockPair(); 1174 } 1175 1176 SmallVector<BasicBlock *, 32> Worklist; 1177 Worklist.push_back(StartBB); 1178 1179 // PredList used inside loop. 1180 SmallVector<std::pair<BasicBlock *, PHITransAddr>, 16> PredList; 1181 1182 // Keep track of the entries that we know are sorted. Previously cached 1183 // entries will all be sorted. The entries we add we only sort on demand (we 1184 // don't insert every element into its sorted position). We know that we 1185 // won't get any reuse from currently inserted values, because we don't 1186 // revisit blocks after we insert info for them. 1187 unsigned NumSortedEntries = Cache->size(); 1188 unsigned WorklistEntries = BlockNumberLimit; 1189 bool GotWorklistLimit = false; 1190 LLVM_DEBUG(AssertSorted(*Cache)); 1191 1192 while (!Worklist.empty()) { 1193 BasicBlock *BB = Worklist.pop_back_val(); 1194 1195 // If we do process a large number of blocks it becomes very expensive and 1196 // likely it isn't worth worrying about 1197 if (Result.size() > NumResultsLimit) { 1198 Worklist.clear(); 1199 // Sort it now (if needed) so that recursive invocations of 1200 // getNonLocalPointerDepFromBB and other routines that could reuse the 1201 // cache value will only see properly sorted cache arrays. 1202 if (Cache && NumSortedEntries != Cache->size()) { 1203 SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 1204 } 1205 // Since we bail out, the "Cache" set won't contain all of the 1206 // results for the query. This is ok (we can still use it to accelerate 1207 // specific block queries) but we can't do the fastpath "return all 1208 // results from the set". Clear out the indicator for this. 1209 CacheInfo->Pair = BBSkipFirstBlockPair(); 1210 return false; 1211 } 1212 1213 // Skip the first block if we have it. 1214 if (!SkipFirstBlock) { 1215 // Analyze the dependency of *Pointer in FromBB. See if we already have 1216 // been here. 1217 assert(Visited.count(BB) && "Should check 'visited' before adding to WL"); 1218 1219 // Get the dependency info for Pointer in BB. If we have cached 1220 // information, we will use it, otherwise we compute it. 1221 LLVM_DEBUG(AssertSorted(*Cache, NumSortedEntries)); 1222 MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst, Loc, isLoad, BB, 1223 Cache, NumSortedEntries); 1224 1225 // If we got a Def or Clobber, add this to the list of results. 1226 if (!Dep.isNonLocal()) { 1227 if (DT.isReachableFromEntry(BB)) { 1228 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr())); 1229 continue; 1230 } 1231 } 1232 } 1233 1234 // If 'Pointer' is an instruction defined in this block, then we need to do 1235 // phi translation to change it into a value live in the predecessor block. 1236 // If not, we just add the predecessors to the worklist and scan them with 1237 // the same Pointer. 1238 if (!Pointer.NeedsPHITranslationFromBlock(BB)) { 1239 SkipFirstBlock = false; 1240 SmallVector<BasicBlock *, 16> NewBlocks; 1241 for (BasicBlock *Pred : PredCache.get(BB)) { 1242 // Verify that we haven't looked at this block yet. 1243 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes = 1244 Visited.insert(std::make_pair(Pred, Pointer.getAddr())); 1245 if (InsertRes.second) { 1246 // First time we've looked at *PI. 1247 NewBlocks.push_back(Pred); 1248 continue; 1249 } 1250 1251 // If we have seen this block before, but it was with a different 1252 // pointer then we have a phi translation failure and we have to treat 1253 // this as a clobber. 1254 if (InsertRes.first->second != Pointer.getAddr()) { 1255 // Make sure to clean up the Visited map before continuing on to 1256 // PredTranslationFailure. 1257 for (unsigned i = 0; i < NewBlocks.size(); i++) 1258 Visited.erase(NewBlocks[i]); 1259 goto PredTranslationFailure; 1260 } 1261 } 1262 if (NewBlocks.size() > WorklistEntries) { 1263 // Make sure to clean up the Visited map before continuing on to 1264 // PredTranslationFailure. 1265 for (unsigned i = 0; i < NewBlocks.size(); i++) 1266 Visited.erase(NewBlocks[i]); 1267 GotWorklistLimit = true; 1268 goto PredTranslationFailure; 1269 } 1270 WorklistEntries -= NewBlocks.size(); 1271 Worklist.append(NewBlocks.begin(), NewBlocks.end()); 1272 continue; 1273 } 1274 1275 // We do need to do phi translation, if we know ahead of time we can't phi 1276 // translate this value, don't even try. 1277 if (!Pointer.IsPotentiallyPHITranslatable()) 1278 goto PredTranslationFailure; 1279 1280 // We may have added values to the cache list before this PHI translation. 1281 // If so, we haven't done anything to ensure that the cache remains sorted. 1282 // Sort it now (if needed) so that recursive invocations of 1283 // getNonLocalPointerDepFromBB and other routines that could reuse the cache 1284 // value will only see properly sorted cache arrays. 1285 if (Cache && NumSortedEntries != Cache->size()) { 1286 SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 1287 NumSortedEntries = Cache->size(); 1288 } 1289 Cache = nullptr; 1290 1291 PredList.clear(); 1292 for (BasicBlock *Pred : PredCache.get(BB)) { 1293 PredList.push_back(std::make_pair(Pred, Pointer)); 1294 1295 // Get the PHI translated pointer in this predecessor. This can fail if 1296 // not translatable, in which case the getAddr() returns null. 1297 PHITransAddr &PredPointer = PredList.back().second; 1298 PredPointer.PHITranslateValue(BB, Pred, &DT, /*MustDominate=*/false); 1299 Value *PredPtrVal = PredPointer.getAddr(); 1300 1301 // Check to see if we have already visited this pred block with another 1302 // pointer. If so, we can't do this lookup. This failure can occur 1303 // with PHI translation when a critical edge exists and the PHI node in 1304 // the successor translates to a pointer value different than the 1305 // pointer the block was first analyzed with. 1306 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes = 1307 Visited.insert(std::make_pair(Pred, PredPtrVal)); 1308 1309 if (!InsertRes.second) { 1310 // We found the pred; take it off the list of preds to visit. 1311 PredList.pop_back(); 1312 1313 // If the predecessor was visited with PredPtr, then we already did 1314 // the analysis and can ignore it. 1315 if (InsertRes.first->second == PredPtrVal) 1316 continue; 1317 1318 // Otherwise, the block was previously analyzed with a different 1319 // pointer. We can't represent the result of this case, so we just 1320 // treat this as a phi translation failure. 1321 1322 // Make sure to clean up the Visited map before continuing on to 1323 // PredTranslationFailure. 1324 for (unsigned i = 0, n = PredList.size(); i < n; ++i) 1325 Visited.erase(PredList[i].first); 1326 1327 goto PredTranslationFailure; 1328 } 1329 } 1330 1331 // Actually process results here; this need to be a separate loop to avoid 1332 // calling getNonLocalPointerDepFromBB for blocks we don't want to return 1333 // any results for. (getNonLocalPointerDepFromBB will modify our 1334 // datastructures in ways the code after the PredTranslationFailure label 1335 // doesn't expect.) 1336 for (unsigned i = 0, n = PredList.size(); i < n; ++i) { 1337 BasicBlock *Pred = PredList[i].first; 1338 PHITransAddr &PredPointer = PredList[i].second; 1339 Value *PredPtrVal = PredPointer.getAddr(); 1340 1341 bool CanTranslate = true; 1342 // If PHI translation was unable to find an available pointer in this 1343 // predecessor, then we have to assume that the pointer is clobbered in 1344 // that predecessor. We can still do PRE of the load, which would insert 1345 // a computation of the pointer in this predecessor. 1346 if (!PredPtrVal) 1347 CanTranslate = false; 1348 1349 // FIXME: it is entirely possible that PHI translating will end up with 1350 // the same value. Consider PHI translating something like: 1351 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need* 1352 // to recurse here, pedantically speaking. 1353 1354 // If getNonLocalPointerDepFromBB fails here, that means the cached 1355 // result conflicted with the Visited list; we have to conservatively 1356 // assume it is unknown, but this also does not block PRE of the load. 1357 if (!CanTranslate || 1358 !getNonLocalPointerDepFromBB(QueryInst, PredPointer, 1359 Loc.getWithNewPtr(PredPtrVal), isLoad, 1360 Pred, Result, Visited)) { 1361 // Add the entry to the Result list. 1362 NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal); 1363 Result.push_back(Entry); 1364 1365 // Since we had a phi translation failure, the cache for CacheKey won't 1366 // include all of the entries that we need to immediately satisfy future 1367 // queries. Mark this in NonLocalPointerDeps by setting the 1368 // BBSkipFirstBlockPair pointer to null. This requires reuse of the 1369 // cached value to do more work but not miss the phi trans failure. 1370 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey]; 1371 NLPI.Pair = BBSkipFirstBlockPair(); 1372 continue; 1373 } 1374 } 1375 1376 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated. 1377 CacheInfo = &NonLocalPointerDeps[CacheKey]; 1378 Cache = &CacheInfo->NonLocalDeps; 1379 NumSortedEntries = Cache->size(); 1380 1381 // Since we did phi translation, the "Cache" set won't contain all of the 1382 // results for the query. This is ok (we can still use it to accelerate 1383 // specific block queries) but we can't do the fastpath "return all 1384 // results from the set" Clear out the indicator for this. 1385 CacheInfo->Pair = BBSkipFirstBlockPair(); 1386 SkipFirstBlock = false; 1387 continue; 1388 1389 PredTranslationFailure: 1390 // The following code is "failure"; we can't produce a sane translation 1391 // for the given block. It assumes that we haven't modified any of 1392 // our datastructures while processing the current block. 1393 1394 if (!Cache) { 1395 // Refresh the CacheInfo/Cache pointer if it got invalidated. 1396 CacheInfo = &NonLocalPointerDeps[CacheKey]; 1397 Cache = &CacheInfo->NonLocalDeps; 1398 NumSortedEntries = Cache->size(); 1399 } 1400 1401 // Since we failed phi translation, the "Cache" set won't contain all of the 1402 // results for the query. This is ok (we can still use it to accelerate 1403 // specific block queries) but we can't do the fastpath "return all 1404 // results from the set". Clear out the indicator for this. 1405 CacheInfo->Pair = BBSkipFirstBlockPair(); 1406 1407 // If *nothing* works, mark the pointer as unknown. 1408 // 1409 // If this is the magic first block, return this as a clobber of the whole 1410 // incoming value. Since we can't phi translate to one of the predecessors, 1411 // we have to bail out. 1412 if (SkipFirstBlock) 1413 return false; 1414 1415 // Results of invariant loads are not cached thus no need to update cached 1416 // information. 1417 if (!isInvariantLoad) { 1418 for (NonLocalDepEntry &I : llvm::reverse(*Cache)) { 1419 if (I.getBB() != BB) 1420 continue; 1421 1422 assert((GotWorklistLimit || I.getResult().isNonLocal() || 1423 !DT.isReachableFromEntry(BB)) && 1424 "Should only be here with transparent block"); 1425 1426 I.setResult(MemDepResult::getUnknown()); 1427 1428 1429 break; 1430 } 1431 } 1432 (void)GotWorklistLimit; 1433 // Go ahead and report unknown dependence. 1434 Result.push_back( 1435 NonLocalDepResult(BB, MemDepResult::getUnknown(), Pointer.getAddr())); 1436 } 1437 1438 // Okay, we're done now. If we added new values to the cache, re-sort it. 1439 SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 1440 LLVM_DEBUG(AssertSorted(*Cache)); 1441 return true; 1442 } 1443 1444 /// If P exists in CachedNonLocalPointerInfo or NonLocalDefsCache, remove it. 1445 void MemoryDependenceResults::RemoveCachedNonLocalPointerDependencies( 1446 ValueIsLoadPair P) { 1447 1448 // Most of the time this cache is empty. 1449 if (!NonLocalDefsCache.empty()) { 1450 auto it = NonLocalDefsCache.find(P.getPointer()); 1451 if (it != NonLocalDefsCache.end()) { 1452 RemoveFromReverseMap(ReverseNonLocalDefsCache, 1453 it->second.getResult().getInst(), P.getPointer()); 1454 NonLocalDefsCache.erase(it); 1455 } 1456 1457 if (auto *I = dyn_cast<Instruction>(P.getPointer())) { 1458 auto toRemoveIt = ReverseNonLocalDefsCache.find(I); 1459 if (toRemoveIt != ReverseNonLocalDefsCache.end()) { 1460 for (const auto *entry : toRemoveIt->second) 1461 NonLocalDefsCache.erase(entry); 1462 ReverseNonLocalDefsCache.erase(toRemoveIt); 1463 } 1464 } 1465 } 1466 1467 CachedNonLocalPointerInfo::iterator It = NonLocalPointerDeps.find(P); 1468 if (It == NonLocalPointerDeps.end()) 1469 return; 1470 1471 // Remove all of the entries in the BB->val map. This involves removing 1472 // instructions from the reverse map. 1473 NonLocalDepInfo &PInfo = It->second.NonLocalDeps; 1474 1475 for (unsigned i = 0, e = PInfo.size(); i != e; ++i) { 1476 Instruction *Target = PInfo[i].getResult().getInst(); 1477 if (!Target) 1478 continue; // Ignore non-local dep results. 1479 assert(Target->getParent() == PInfo[i].getBB()); 1480 1481 // Eliminating the dirty entry from 'Cache', so update the reverse info. 1482 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P); 1483 } 1484 1485 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo). 1486 NonLocalPointerDeps.erase(It); 1487 } 1488 1489 void MemoryDependenceResults::invalidateCachedPointerInfo(Value *Ptr) { 1490 // If Ptr isn't really a pointer, just ignore it. 1491 if (!Ptr->getType()->isPointerTy()) 1492 return; 1493 // Flush store info for the pointer. 1494 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false)); 1495 // Flush load info for the pointer. 1496 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true)); 1497 // Invalidate phis that use the pointer. 1498 PV.invalidateValue(Ptr); 1499 } 1500 1501 void MemoryDependenceResults::invalidateCachedPredecessors() { 1502 PredCache.clear(); 1503 } 1504 1505 void MemoryDependenceResults::removeInstruction(Instruction *RemInst) { 1506 // Walk through the Non-local dependencies, removing this one as the value 1507 // for any cached queries. 1508 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst); 1509 if (NLDI != NonLocalDeps.end()) { 1510 NonLocalDepInfo &BlockMap = NLDI->second.first; 1511 for (auto &Entry : BlockMap) 1512 if (Instruction *Inst = Entry.getResult().getInst()) 1513 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst); 1514 NonLocalDeps.erase(NLDI); 1515 } 1516 1517 // If we have a cached local dependence query for this instruction, remove it. 1518 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst); 1519 if (LocalDepEntry != LocalDeps.end()) { 1520 // Remove us from DepInst's reverse set now that the local dep info is gone. 1521 if (Instruction *Inst = LocalDepEntry->second.getInst()) 1522 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst); 1523 1524 // Remove this local dependency info. 1525 LocalDeps.erase(LocalDepEntry); 1526 } 1527 1528 // If we have any cached dependencies on this instruction, remove 1529 // them. 1530 1531 // If the instruction is a pointer, remove it from both the load info and the 1532 // store info. 1533 if (RemInst->getType()->isPointerTy()) { 1534 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false)); 1535 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true)); 1536 } else { 1537 // Otherwise, if the instructions is in the map directly, it must be a load. 1538 // Remove it. 1539 auto toRemoveIt = NonLocalDefsCache.find(RemInst); 1540 if (toRemoveIt != NonLocalDefsCache.end()) { 1541 assert(isa<LoadInst>(RemInst) && 1542 "only load instructions should be added directly"); 1543 const Instruction *DepV = toRemoveIt->second.getResult().getInst(); 1544 ReverseNonLocalDefsCache.find(DepV)->second.erase(RemInst); 1545 NonLocalDefsCache.erase(toRemoveIt); 1546 } 1547 } 1548 1549 // Loop over all of the things that depend on the instruction we're removing. 1550 SmallVector<std::pair<Instruction *, Instruction *>, 8> ReverseDepsToAdd; 1551 1552 // If we find RemInst as a clobber or Def in any of the maps for other values, 1553 // we need to replace its entry with a dirty version of the instruction after 1554 // it. If RemInst is a terminator, we use a null dirty value. 1555 // 1556 // Using a dirty version of the instruction after RemInst saves having to scan 1557 // the entire block to get to this point. 1558 MemDepResult NewDirtyVal; 1559 if (!RemInst->isTerminator()) 1560 NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator()); 1561 1562 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst); 1563 if (ReverseDepIt != ReverseLocalDeps.end()) { 1564 // RemInst can't be the terminator if it has local stuff depending on it. 1565 assert(!ReverseDepIt->second.empty() && !RemInst->isTerminator() && 1566 "Nothing can locally depend on a terminator"); 1567 1568 for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) { 1569 assert(InstDependingOnRemInst != RemInst && 1570 "Already removed our local dep info"); 1571 1572 LocalDeps[InstDependingOnRemInst] = NewDirtyVal; 1573 1574 // Make sure to remember that new things depend on NewDepInst. 1575 assert(NewDirtyVal.getInst() && 1576 "There is no way something else can have " 1577 "a local dep on this if it is a terminator!"); 1578 ReverseDepsToAdd.push_back( 1579 std::make_pair(NewDirtyVal.getInst(), InstDependingOnRemInst)); 1580 } 1581 1582 ReverseLocalDeps.erase(ReverseDepIt); 1583 1584 // Add new reverse deps after scanning the set, to avoid invalidating the 1585 // 'ReverseDeps' reference. 1586 while (!ReverseDepsToAdd.empty()) { 1587 ReverseLocalDeps[ReverseDepsToAdd.back().first].insert( 1588 ReverseDepsToAdd.back().second); 1589 ReverseDepsToAdd.pop_back(); 1590 } 1591 } 1592 1593 ReverseDepIt = ReverseNonLocalDeps.find(RemInst); 1594 if (ReverseDepIt != ReverseNonLocalDeps.end()) { 1595 for (Instruction *I : ReverseDepIt->second) { 1596 assert(I != RemInst && "Already removed NonLocalDep info for RemInst"); 1597 1598 PerInstNLInfo &INLD = NonLocalDeps[I]; 1599 // The information is now dirty! 1600 INLD.second = true; 1601 1602 for (auto &Entry : INLD.first) { 1603 if (Entry.getResult().getInst() != RemInst) 1604 continue; 1605 1606 // Convert to a dirty entry for the subsequent instruction. 1607 Entry.setResult(NewDirtyVal); 1608 1609 if (Instruction *NextI = NewDirtyVal.getInst()) 1610 ReverseDepsToAdd.push_back(std::make_pair(NextI, I)); 1611 } 1612 } 1613 1614 ReverseNonLocalDeps.erase(ReverseDepIt); 1615 1616 // Add new reverse deps after scanning the set, to avoid invalidating 'Set' 1617 while (!ReverseDepsToAdd.empty()) { 1618 ReverseNonLocalDeps[ReverseDepsToAdd.back().first].insert( 1619 ReverseDepsToAdd.back().second); 1620 ReverseDepsToAdd.pop_back(); 1621 } 1622 } 1623 1624 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a 1625 // value in the NonLocalPointerDeps info. 1626 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt = 1627 ReverseNonLocalPtrDeps.find(RemInst); 1628 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) { 1629 SmallVector<std::pair<Instruction *, ValueIsLoadPair>, 8> 1630 ReversePtrDepsToAdd; 1631 1632 for (ValueIsLoadPair P : ReversePtrDepIt->second) { 1633 assert(P.getPointer() != RemInst && 1634 "Already removed NonLocalPointerDeps info for RemInst"); 1635 1636 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps; 1637 1638 // The cache is not valid for any specific block anymore. 1639 NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair(); 1640 1641 // Update any entries for RemInst to use the instruction after it. 1642 for (auto &Entry : NLPDI) { 1643 if (Entry.getResult().getInst() != RemInst) 1644 continue; 1645 1646 // Convert to a dirty entry for the subsequent instruction. 1647 Entry.setResult(NewDirtyVal); 1648 1649 if (Instruction *NewDirtyInst = NewDirtyVal.getInst()) 1650 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P)); 1651 } 1652 1653 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its 1654 // subsequent value may invalidate the sortedness. 1655 llvm::sort(NLPDI); 1656 } 1657 1658 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt); 1659 1660 while (!ReversePtrDepsToAdd.empty()) { 1661 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first].insert( 1662 ReversePtrDepsToAdd.back().second); 1663 ReversePtrDepsToAdd.pop_back(); 1664 } 1665 } 1666 1667 // Invalidate phis that use the removed instruction. 1668 PV.invalidateValue(RemInst); 1669 1670 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?"); 1671 LLVM_DEBUG(verifyRemoved(RemInst)); 1672 } 1673 1674 /// Verify that the specified instruction does not occur in our internal data 1675 /// structures. 1676 /// 1677 /// This function verifies by asserting in debug builds. 1678 void MemoryDependenceResults::verifyRemoved(Instruction *D) const { 1679 #ifndef NDEBUG 1680 for (const auto &DepKV : LocalDeps) { 1681 assert(DepKV.first != D && "Inst occurs in data structures"); 1682 assert(DepKV.second.getInst() != D && "Inst occurs in data structures"); 1683 } 1684 1685 for (const auto &DepKV : NonLocalPointerDeps) { 1686 assert(DepKV.first.getPointer() != D && "Inst occurs in NLPD map key"); 1687 for (const auto &Entry : DepKV.second.NonLocalDeps) 1688 assert(Entry.getResult().getInst() != D && "Inst occurs as NLPD value"); 1689 } 1690 1691 for (const auto &DepKV : NonLocalDeps) { 1692 assert(DepKV.first != D && "Inst occurs in data structures"); 1693 const PerInstNLInfo &INLD = DepKV.second; 1694 for (const auto &Entry : INLD.first) 1695 assert(Entry.getResult().getInst() != D && 1696 "Inst occurs in data structures"); 1697 } 1698 1699 for (const auto &DepKV : ReverseLocalDeps) { 1700 assert(DepKV.first != D && "Inst occurs in data structures"); 1701 for (Instruction *Inst : DepKV.second) 1702 assert(Inst != D && "Inst occurs in data structures"); 1703 } 1704 1705 for (const auto &DepKV : ReverseNonLocalDeps) { 1706 assert(DepKV.first != D && "Inst occurs in data structures"); 1707 for (Instruction *Inst : DepKV.second) 1708 assert(Inst != D && "Inst occurs in data structures"); 1709 } 1710 1711 for (const auto &DepKV : ReverseNonLocalPtrDeps) { 1712 assert(DepKV.first != D && "Inst occurs in rev NLPD map"); 1713 1714 for (ValueIsLoadPair P : DepKV.second) 1715 assert(P != ValueIsLoadPair(D, false) && P != ValueIsLoadPair(D, true) && 1716 "Inst occurs in ReverseNonLocalPtrDeps map"); 1717 } 1718 #endif 1719 } 1720 1721 AnalysisKey MemoryDependenceAnalysis::Key; 1722 1723 MemoryDependenceAnalysis::MemoryDependenceAnalysis() 1724 : DefaultBlockScanLimit(BlockScanLimit) {} 1725 1726 MemoryDependenceResults 1727 MemoryDependenceAnalysis::run(Function &F, FunctionAnalysisManager &AM) { 1728 auto &AA = AM.getResult<AAManager>(F); 1729 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1730 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1731 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1732 auto &PV = AM.getResult<PhiValuesAnalysis>(F); 1733 return MemoryDependenceResults(AA, AC, TLI, DT, PV, DefaultBlockScanLimit); 1734 } 1735 1736 char MemoryDependenceWrapperPass::ID = 0; 1737 1738 INITIALIZE_PASS_BEGIN(MemoryDependenceWrapperPass, "memdep", 1739 "Memory Dependence Analysis", false, true) 1740 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1741 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1742 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1743 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1744 INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass) 1745 INITIALIZE_PASS_END(MemoryDependenceWrapperPass, "memdep", 1746 "Memory Dependence Analysis", false, true) 1747 1748 MemoryDependenceWrapperPass::MemoryDependenceWrapperPass() : FunctionPass(ID) { 1749 initializeMemoryDependenceWrapperPassPass(*PassRegistry::getPassRegistry()); 1750 } 1751 1752 MemoryDependenceWrapperPass::~MemoryDependenceWrapperPass() = default; 1753 1754 void MemoryDependenceWrapperPass::releaseMemory() { 1755 MemDep.reset(); 1756 } 1757 1758 void MemoryDependenceWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1759 AU.setPreservesAll(); 1760 AU.addRequired<AssumptionCacheTracker>(); 1761 AU.addRequired<DominatorTreeWrapperPass>(); 1762 AU.addRequired<PhiValuesWrapperPass>(); 1763 AU.addRequiredTransitive<AAResultsWrapperPass>(); 1764 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 1765 } 1766 1767 bool MemoryDependenceResults::invalidate(Function &F, const PreservedAnalyses &PA, 1768 FunctionAnalysisManager::Invalidator &Inv) { 1769 // Check whether our analysis is preserved. 1770 auto PAC = PA.getChecker<MemoryDependenceAnalysis>(); 1771 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>()) 1772 // If not, give up now. 1773 return true; 1774 1775 // Check whether the analyses we depend on became invalid for any reason. 1776 if (Inv.invalidate<AAManager>(F, PA) || 1777 Inv.invalidate<AssumptionAnalysis>(F, PA) || 1778 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 1779 Inv.invalidate<PhiValuesAnalysis>(F, PA)) 1780 return true; 1781 1782 // Otherwise this analysis result remains valid. 1783 return false; 1784 } 1785 1786 unsigned MemoryDependenceResults::getDefaultBlockScanLimit() const { 1787 return DefaultBlockScanLimit; 1788 } 1789 1790 bool MemoryDependenceWrapperPass::runOnFunction(Function &F) { 1791 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 1792 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1793 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 1794 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1795 auto &PV = getAnalysis<PhiValuesWrapperPass>().getResult(); 1796 MemDep.emplace(AA, AC, TLI, DT, PV, BlockScanLimit); 1797 return false; 1798 } 1799