1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===// 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 pass performs loop invariant code motion, attempting to remove as much 11 // code from the body of a loop as possible. It does this by either hoisting 12 // code into the preheader block, or by sinking code to the exit blocks if it is 13 // safe. This pass also promotes must-aliased memory locations in the loop to 14 // live in registers, thus hoisting and sinking "invariant" loads and stores. 15 // 16 // This pass uses alias analysis for two purposes: 17 // 18 // 1. Moving loop invariant loads and calls out of loops. If we can determine 19 // that a load or call inside of a loop never aliases anything stored to, 20 // we can hoist it or sink it like any other instruction. 21 // 2. Scalar Promotion of Memory - If there is a store instruction inside of 22 // the loop, we try to move the store to happen AFTER the loop instead of 23 // inside of the loop. This can only happen if a few conditions are true: 24 // A. The pointer stored through is loop invariant 25 // B. There are no stores or loads in the loop which _may_ alias the 26 // pointer. There are no calls in the loop which mod/ref the pointer. 27 // If these conditions are true, we can promote the loads and stores in the 28 // loop of the pointer to use a temporary alloca'd variable. We then use 29 // the SSAUpdater to construct the appropriate SSA form for the value. 30 // 31 //===----------------------------------------------------------------------===// 32 33 #include "llvm/Transforms/Scalar/LICM.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/Analysis/AliasAnalysis.h" 36 #include "llvm/Analysis/AliasSetTracker.h" 37 #include "llvm/Analysis/BasicAliasAnalysis.h" 38 #include "llvm/Analysis/CaptureTracking.h" 39 #include "llvm/Analysis/ConstantFolding.h" 40 #include "llvm/Analysis/GlobalsModRef.h" 41 #include "llvm/Analysis/Loads.h" 42 #include "llvm/Analysis/LoopInfo.h" 43 #include "llvm/Analysis/LoopPass.h" 44 #include "llvm/Analysis/MemoryBuiltins.h" 45 #include "llvm/Analysis/MemorySSA.h" 46 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 47 #include "llvm/Analysis/ScalarEvolution.h" 48 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 49 #include "llvm/Analysis/TargetLibraryInfo.h" 50 #include "llvm/Transforms/Utils/Local.h" 51 #include "llvm/Analysis/ValueTracking.h" 52 #include "llvm/IR/CFG.h" 53 #include "llvm/IR/Constants.h" 54 #include "llvm/IR/DataLayout.h" 55 #include "llvm/IR/DerivedTypes.h" 56 #include "llvm/IR/Dominators.h" 57 #include "llvm/IR/Instructions.h" 58 #include "llvm/IR/IntrinsicInst.h" 59 #include "llvm/IR/LLVMContext.h" 60 #include "llvm/IR/Metadata.h" 61 #include "llvm/IR/PredIteratorCache.h" 62 #include "llvm/Support/CommandLine.h" 63 #include "llvm/Support/Debug.h" 64 #include "llvm/Support/raw_ostream.h" 65 #include "llvm/Transforms/Scalar.h" 66 #include "llvm/Transforms/Scalar/LoopPassManager.h" 67 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 68 #include "llvm/Transforms/Utils/LoopUtils.h" 69 #include "llvm/Transforms/Utils/SSAUpdater.h" 70 #include <algorithm> 71 #include <utility> 72 using namespace llvm; 73 74 #define DEBUG_TYPE "licm" 75 76 STATISTIC(NumSunk, "Number of instructions sunk out of loop"); 77 STATISTIC(NumHoisted, "Number of instructions hoisted out of loop"); 78 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk"); 79 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk"); 80 STATISTIC(NumPromoted, "Number of memory locations promoted to registers"); 81 82 /// Memory promotion is enabled by default. 83 static cl::opt<bool> 84 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false), 85 cl::desc("Disable memory promotion in LICM pass")); 86 87 static cl::opt<uint32_t> MaxNumUsesTraversed( 88 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8), 89 cl::desc("Max num uses visited for identifying load " 90 "invariance in loop using invariant start (default = 8)")); 91 92 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI); 93 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, 94 const LoopSafetyInfo *SafetyInfo, 95 TargetTransformInfo *TTI, bool &FreeInLoop); 96 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 97 const LoopSafetyInfo *SafetyInfo, 98 OptimizationRemarkEmitter *ORE); 99 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, 100 const Loop *CurLoop, LoopSafetyInfo *SafetyInfo, 101 OptimizationRemarkEmitter *ORE, bool FreeInLoop); 102 static bool isSafeToExecuteUnconditionally(Instruction &Inst, 103 const DominatorTree *DT, 104 const Loop *CurLoop, 105 const LoopSafetyInfo *SafetyInfo, 106 OptimizationRemarkEmitter *ORE, 107 const Instruction *CtxI = nullptr); 108 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, 109 const AAMDNodes &AAInfo, 110 AliasSetTracker *CurAST); 111 static Instruction * 112 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, 113 const LoopInfo *LI, 114 const LoopSafetyInfo *SafetyInfo); 115 116 namespace { 117 struct LoopInvariantCodeMotion { 118 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT, 119 TargetLibraryInfo *TLI, TargetTransformInfo *TTI, 120 ScalarEvolution *SE, MemorySSA *MSSA, 121 OptimizationRemarkEmitter *ORE, bool DeleteAST); 122 123 DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() { 124 return LoopToAliasSetMap; 125 } 126 127 private: 128 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap; 129 130 AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI, 131 AliasAnalysis *AA); 132 }; 133 134 struct LegacyLICMPass : public LoopPass { 135 static char ID; // Pass identification, replacement for typeid 136 LegacyLICMPass() : LoopPass(ID) { 137 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry()); 138 } 139 140 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 141 if (skipLoop(L)) { 142 // If we have run LICM on a previous loop but now we are skipping 143 // (because we've hit the opt-bisect limit), we need to clear the 144 // loop alias information. 145 for (auto <AS : LICM.getLoopToAliasSetMap()) 146 delete LTAS.second; 147 LICM.getLoopToAliasSetMap().clear(); 148 return false; 149 } 150 151 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 152 MemorySSA *MSSA = EnableMSSALoopDependency 153 ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA()) 154 : nullptr; 155 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 156 // pass. Function analyses need to be preserved across loop transformations 157 // but ORE cannot be preserved (see comment before the pass definition). 158 OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); 159 return LICM.runOnLoop(L, 160 &getAnalysis<AAResultsWrapperPass>().getAAResults(), 161 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), 162 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 163 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 164 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 165 *L->getHeader()->getParent()), 166 SE ? &SE->getSE() : nullptr, MSSA, &ORE, false); 167 } 168 169 /// This transformation requires natural loop information & requires that 170 /// loop preheaders be inserted into the CFG... 171 /// 172 void getAnalysisUsage(AnalysisUsage &AU) const override { 173 AU.addPreserved<DominatorTreeWrapperPass>(); 174 AU.addPreserved<LoopInfoWrapperPass>(); 175 AU.addRequired<TargetLibraryInfoWrapperPass>(); 176 if (EnableMSSALoopDependency) 177 AU.addRequired<MemorySSAWrapperPass>(); 178 AU.addRequired<TargetTransformInfoWrapperPass>(); 179 getLoopAnalysisUsage(AU); 180 } 181 182 using llvm::Pass::doFinalization; 183 184 bool doFinalization() override { 185 assert(LICM.getLoopToAliasSetMap().empty() && 186 "Didn't free loop alias sets"); 187 return false; 188 } 189 190 private: 191 LoopInvariantCodeMotion LICM; 192 193 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info. 194 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, 195 Loop *L) override; 196 197 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias 198 /// set. 199 void deleteAnalysisValue(Value *V, Loop *L) override; 200 201 /// Simple Analysis hook. Delete loop L from alias set map. 202 void deleteAnalysisLoop(Loop *L) override; 203 }; 204 } // namespace 205 206 PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM, 207 LoopStandardAnalysisResults &AR, LPMUpdater &) { 208 const auto &FAM = 209 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); 210 Function *F = L.getHeader()->getParent(); 211 212 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F); 213 // FIXME: This should probably be optional rather than required. 214 if (!ORE) 215 report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not " 216 "cached at a higher level"); 217 218 LoopInvariantCodeMotion LICM; 219 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE, 220 AR.MSSA, ORE, true)) 221 return PreservedAnalyses::all(); 222 223 auto PA = getLoopPassPreservedAnalyses(); 224 225 PA.preserve<DominatorTreeAnalysis>(); 226 PA.preserve<LoopAnalysis>(); 227 228 return PA; 229 } 230 231 char LegacyLICMPass::ID = 0; 232 INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion", 233 false, false) 234 INITIALIZE_PASS_DEPENDENCY(LoopPass) 235 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 236 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 237 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 238 INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false, 239 false) 240 241 Pass *llvm::createLICMPass() { return new LegacyLICMPass(); } 242 243 /// Hoist expressions out of the specified loop. Note, alias info for inner 244 /// loop is not preserved so it is not a good idea to run LICM multiple 245 /// times on one loop. 246 /// We should delete AST for inner loops in the new pass manager to avoid 247 /// memory leak. 248 /// 249 bool LoopInvariantCodeMotion::runOnLoop( 250 Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT, 251 TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE, 252 MemorySSA *MSSA, OptimizationRemarkEmitter *ORE, bool DeleteAST) { 253 bool Changed = false; 254 255 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form."); 256 257 AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA); 258 259 // Get the preheader block to move instructions into... 260 BasicBlock *Preheader = L->getLoopPreheader(); 261 262 // Compute loop safety information. 263 LoopSafetyInfo SafetyInfo; 264 computeLoopSafetyInfo(&SafetyInfo, L); 265 266 // We want to visit all of the instructions in this loop... that are not parts 267 // of our subloops (they have already had their invariants hoisted out of 268 // their loop, into this loop, so there is no need to process the BODIES of 269 // the subloops). 270 // 271 // Traverse the body of the loop in depth first order on the dominator tree so 272 // that we are guaranteed to see definitions before we see uses. This allows 273 // us to sink instructions in one pass, without iteration. After sinking 274 // instructions, we perform another pass to hoist them out of the loop. 275 // 276 if (L->hasDedicatedExits()) 277 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L, 278 CurAST, &SafetyInfo, ORE); 279 if (Preheader) 280 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L, 281 CurAST, &SafetyInfo, ORE); 282 283 // Now that all loop invariants have been removed from the loop, promote any 284 // memory references to scalars that we can. 285 // Don't sink stores from loops without dedicated block exits. Exits 286 // containing indirect branches are not transformed by loop simplify, 287 // make sure we catch that. An additional load may be generated in the 288 // preheader for SSA updater, so also avoid sinking when no preheader 289 // is available. 290 if (!DisablePromotion && Preheader && L->hasDedicatedExits()) { 291 // Figure out the loop exits and their insertion points 292 SmallVector<BasicBlock *, 8> ExitBlocks; 293 L->getUniqueExitBlocks(ExitBlocks); 294 295 // We can't insert into a catchswitch. 296 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) { 297 return isa<CatchSwitchInst>(Exit->getTerminator()); 298 }); 299 300 if (!HasCatchSwitch) { 301 SmallVector<Instruction *, 8> InsertPts; 302 InsertPts.reserve(ExitBlocks.size()); 303 for (BasicBlock *ExitBlock : ExitBlocks) 304 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt()); 305 306 PredIteratorCache PIC; 307 308 bool Promoted = false; 309 310 // Loop over all of the alias sets in the tracker object. 311 for (AliasSet &AS : *CurAST) { 312 // We can promote this alias set if it has a store, if it is a "Must" 313 // alias set, if the pointer is loop invariant, and if we are not 314 // eliminating any volatile loads or stores. 315 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() || 316 AS.isVolatile() || !L->isLoopInvariant(AS.begin()->getValue())) 317 continue; 318 319 assert( 320 !AS.empty() && 321 "Must alias set should have at least one pointer element in it!"); 322 323 SmallSetVector<Value *, 8> PointerMustAliases; 324 for (const auto &ASI : AS) 325 PointerMustAliases.insert(ASI.getValue()); 326 327 Promoted |= promoteLoopAccessesToScalars(PointerMustAliases, ExitBlocks, 328 InsertPts, PIC, LI, DT, TLI, L, 329 CurAST, &SafetyInfo, ORE); 330 } 331 332 // Once we have promoted values across the loop body we have to 333 // recursively reform LCSSA as any nested loop may now have values defined 334 // within the loop used in the outer loop. 335 // FIXME: This is really heavy handed. It would be a bit better to use an 336 // SSAUpdater strategy during promotion that was LCSSA aware and reformed 337 // it as it went. 338 if (Promoted) 339 formLCSSARecursively(*L, *DT, LI, SE); 340 341 Changed |= Promoted; 342 } 343 } 344 345 // Check that neither this loop nor its parent have had LCSSA broken. LICM is 346 // specifically moving instructions across the loop boundary and so it is 347 // especially in need of sanity checking here. 348 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!"); 349 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) && 350 "Parent loop not left in LCSSA form after LICM!"); 351 352 // If this loop is nested inside of another one, save the alias information 353 // for when we process the outer loop. 354 if (L->getParentLoop() && !DeleteAST) 355 LoopToAliasSetMap[L] = CurAST; 356 else 357 delete CurAST; 358 359 if (Changed && SE) 360 SE->forgetLoopDispositions(L); 361 return Changed; 362 } 363 364 /// Walk the specified region of the CFG (defined by all blocks dominated by 365 /// the specified block, and that are in the current loop) in reverse depth 366 /// first order w.r.t the DominatorTree. This allows us to visit uses before 367 /// definitions, allowing us to sink a loop body in one pass without iteration. 368 /// 369 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 370 DominatorTree *DT, TargetLibraryInfo *TLI, 371 TargetTransformInfo *TTI, Loop *CurLoop, 372 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo, 373 OptimizationRemarkEmitter *ORE) { 374 375 // Verify inputs. 376 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && 377 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr && 378 "Unexpected input to sinkRegion"); 379 380 // We want to visit children before parents. We will enque all the parents 381 // before their children in the worklist and process the worklist in reverse 382 // order. 383 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop); 384 385 bool Changed = false; 386 for (DomTreeNode *DTN : reverse(Worklist)) { 387 BasicBlock *BB = DTN->getBlock(); 388 // Only need to process the contents of this block if it is not part of a 389 // subloop (which would already have been processed). 390 if (inSubLoop(BB, CurLoop, LI)) 391 continue; 392 393 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) { 394 Instruction &I = *--II; 395 396 // If the instruction is dead, we would try to sink it because it isn't 397 // used in the loop, instead, just delete it. 398 if (isInstructionTriviallyDead(&I, TLI)) { 399 LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n'); 400 salvageDebugInfo(I); 401 ++II; 402 CurAST->deleteValue(&I); 403 I.eraseFromParent(); 404 Changed = true; 405 continue; 406 } 407 408 // Check to see if we can sink this instruction to the exit blocks 409 // of the loop. We can do this if the all users of the instruction are 410 // outside of the loop. In this case, it doesn't even matter if the 411 // operands of the instruction are loop invariant. 412 // 413 bool FreeInLoop = false; 414 if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) && 415 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE)) { 416 if (sink(I, LI, DT, CurLoop, SafetyInfo, ORE, FreeInLoop)) { 417 if (!FreeInLoop) { 418 ++II; 419 CurAST->deleteValue(&I); 420 I.eraseFromParent(); 421 } 422 Changed = true; 423 } 424 } 425 } 426 } 427 return Changed; 428 } 429 430 /// Walk the specified region of the CFG (defined by all blocks dominated by 431 /// the specified block, and that are in the current loop) in depth first 432 /// order w.r.t the DominatorTree. This allows us to visit definitions before 433 /// uses, allowing us to hoist a loop body in one pass without iteration. 434 /// 435 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 436 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, 437 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo, 438 OptimizationRemarkEmitter *ORE) { 439 // Verify inputs. 440 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && 441 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr && 442 "Unexpected input to hoistRegion"); 443 444 // We want to visit parents before children. We will enque all the parents 445 // before their children in the worklist and process the worklist in order. 446 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop); 447 448 bool Changed = false; 449 for (DomTreeNode *DTN : Worklist) { 450 BasicBlock *BB = DTN->getBlock(); 451 // Only need to process the contents of this block if it is not part of a 452 // subloop (which would already have been processed). 453 if (inSubLoop(BB, CurLoop, LI)) 454 continue; 455 456 // Keep track of whether the prefix of instructions visited so far are such 457 // that the next instruction visited is guaranteed to execute if the loop 458 // is entered. 459 bool IsMustExecute = CurLoop->getHeader() == BB; 460 461 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) { 462 Instruction &I = *II++; 463 // Try constant folding this instruction. If all the operands are 464 // constants, it is technically hoistable, but it would be better to 465 // just fold it. 466 if (Constant *C = ConstantFoldInstruction( 467 &I, I.getModule()->getDataLayout(), TLI)) { 468 LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C 469 << '\n'); 470 CurAST->copyValue(&I, C); 471 I.replaceAllUsesWith(C); 472 if (isInstructionTriviallyDead(&I, TLI)) { 473 CurAST->deleteValue(&I); 474 I.eraseFromParent(); 475 } 476 Changed = true; 477 continue; 478 } 479 480 // Try hoisting the instruction out to the preheader. We can only do 481 // this if all of the operands of the instruction are loop invariant and 482 // if it is safe to hoist the instruction. 483 // 484 if (CurLoop->hasLoopInvariantOperands(&I) && 485 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE) && 486 (IsMustExecute || 487 isSafeToExecuteUnconditionally( 488 I, DT, CurLoop, SafetyInfo, ORE, 489 CurLoop->getLoopPreheader()->getTerminator()))) { 490 Changed |= hoist(I, DT, CurLoop, SafetyInfo, ORE); 491 continue; 492 } 493 494 // Attempt to remove floating point division out of the loop by 495 // converting it to a reciprocal multiplication. 496 if (I.getOpcode() == Instruction::FDiv && 497 CurLoop->isLoopInvariant(I.getOperand(1)) && 498 I.hasAllowReciprocal()) { 499 auto Divisor = I.getOperand(1); 500 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0); 501 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor); 502 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags()); 503 ReciprocalDivisor->insertBefore(&I); 504 505 auto Product = 506 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor); 507 Product->setFastMathFlags(I.getFastMathFlags()); 508 Product->insertAfter(&I); 509 I.replaceAllUsesWith(Product); 510 I.eraseFromParent(); 511 512 hoist(*ReciprocalDivisor, DT, CurLoop, SafetyInfo, ORE); 513 Changed = true; 514 continue; 515 } 516 517 if (IsMustExecute) 518 IsMustExecute = isGuaranteedToTransferExecutionToSuccessor(&I); 519 } 520 } 521 522 return Changed; 523 } 524 525 // Return true if LI is invariant within scope of the loop. LI is invariant if 526 // CurLoop is dominated by an invariant.start representing the same memory 527 // location and size as the memory location LI loads from, and also the 528 // invariant.start has no uses. 529 static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, 530 Loop *CurLoop) { 531 Value *Addr = LI->getOperand(0); 532 const DataLayout &DL = LI->getModule()->getDataLayout(); 533 const uint32_t LocSizeInBits = DL.getTypeSizeInBits( 534 cast<PointerType>(Addr->getType())->getElementType()); 535 536 // if the type is i8 addrspace(x)*, we know this is the type of 537 // llvm.invariant.start operand 538 auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()), 539 LI->getPointerAddressSpace()); 540 unsigned BitcastsVisited = 0; 541 // Look through bitcasts until we reach the i8* type (this is invariant.start 542 // operand type). 543 while (Addr->getType() != PtrInt8Ty) { 544 auto *BC = dyn_cast<BitCastInst>(Addr); 545 // Avoid traversing high number of bitcast uses. 546 if (++BitcastsVisited > MaxNumUsesTraversed || !BC) 547 return false; 548 Addr = BC->getOperand(0); 549 } 550 551 unsigned UsesVisited = 0; 552 // Traverse all uses of the load operand value, to see if invariant.start is 553 // one of the uses, and whether it dominates the load instruction. 554 for (auto *U : Addr->users()) { 555 // Avoid traversing for Load operand with high number of users. 556 if (++UsesVisited > MaxNumUsesTraversed) 557 return false; 558 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); 559 // If there are escaping uses of invariant.start instruction, the load maybe 560 // non-invariant. 561 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start || 562 !II->use_empty()) 563 continue; 564 unsigned InvariantSizeInBits = 565 cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8; 566 // Confirm the invariant.start location size contains the load operand size 567 // in bits. Also, the invariant.start should dominate the load, and we 568 // should not hoist the load out of a loop that contains this dominating 569 // invariant.start. 570 if (LocSizeInBits <= InvariantSizeInBits && 571 DT->properlyDominates(II->getParent(), CurLoop->getHeader())) 572 return true; 573 } 574 575 return false; 576 } 577 578 bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, 579 Loop *CurLoop, AliasSetTracker *CurAST, 580 LoopSafetyInfo *SafetyInfo, 581 OptimizationRemarkEmitter *ORE) { 582 // SafetyInfo is nullptr if we are checking for sinking from preheader to 583 // loop body. 584 const bool SinkingToLoopBody = !SafetyInfo; 585 // Loads have extra constraints we have to verify before we can hoist them. 586 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 587 if (!LI->isUnordered()) 588 return false; // Don't sink/hoist volatile or ordered atomic loads! 589 590 // Loads from constant memory are always safe to move, even if they end up 591 // in the same alias set as something that ends up being modified. 592 if (AA->pointsToConstantMemory(LI->getOperand(0))) 593 return true; 594 if (LI->getMetadata(LLVMContext::MD_invariant_load)) 595 return true; 596 597 if (LI->isAtomic() && SinkingToLoopBody) 598 return false; // Don't sink unordered atomic loads to loop body. 599 600 // This checks for an invariant.start dominating the load. 601 if (isLoadInvariantInLoop(LI, DT, CurLoop)) 602 return true; 603 604 // Don't hoist loads which have may-aliased stores in loop. 605 uint64_t Size = 0; 606 if (LI->getType()->isSized()) 607 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType()); 608 609 AAMDNodes AAInfo; 610 LI->getAAMetadata(AAInfo); 611 612 bool Invalidated = 613 pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST); 614 // Check loop-invariant address because this may also be a sinkable load 615 // whose address is not necessarily loop-invariant. 616 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand())) 617 ORE->emit([&]() { 618 return OptimizationRemarkMissed( 619 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI) 620 << "failed to move load with loop-invariant address " 621 "because the loop may invalidate its value"; 622 }); 623 624 return !Invalidated; 625 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) { 626 // Don't sink or hoist dbg info; it's legal, but not useful. 627 if (isa<DbgInfoIntrinsic>(I)) 628 return false; 629 630 // Don't sink calls which can throw. 631 if (CI->mayThrow()) 632 return false; 633 634 // Handle simple cases by querying alias analysis. 635 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI); 636 if (Behavior == FMRB_DoesNotAccessMemory) 637 return true; 638 if (AliasAnalysis::onlyReadsMemory(Behavior)) { 639 // A readonly argmemonly function only reads from memory pointed to by 640 // it's arguments with arbitrary offsets. If we can prove there are no 641 // writes to this memory in the loop, we can hoist or sink. 642 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) { 643 for (Value *Op : CI->arg_operands()) 644 if (Op->getType()->isPointerTy() && 645 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize, 646 AAMDNodes(), CurAST)) 647 return false; 648 return true; 649 } 650 // If this call only reads from memory and there are no writes to memory 651 // in the loop, we can hoist or sink the call as appropriate. 652 bool FoundMod = false; 653 for (AliasSet &AS : *CurAST) { 654 if (!AS.isForwardingAliasSet() && AS.isMod()) { 655 FoundMod = true; 656 break; 657 } 658 } 659 if (!FoundMod) 660 return true; 661 } 662 663 // FIXME: This should use mod/ref information to see if we can hoist or 664 // sink the call. 665 666 return false; 667 } 668 669 // Only these instructions are hoistable/sinkable. 670 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) && 671 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) && 672 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) && 673 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) && 674 !isa<InsertValueInst>(I)) 675 return false; 676 677 // If we are checking for sinking from preheader to loop body it will be 678 // always safe as there is no speculative execution. 679 if (SinkingToLoopBody) 680 return true; 681 682 // TODO: Plumb the context instruction through to make hoisting and sinking 683 // more powerful. Hoisting of loads already works due to the special casing 684 // above. 685 return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr); 686 } 687 688 /// Returns true if a PHINode is a trivially replaceable with an 689 /// Instruction. 690 /// This is true when all incoming values are that instruction. 691 /// This pattern occurs most often with LCSSA PHI nodes. 692 /// 693 static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) { 694 for (const Value *IncValue : PN.incoming_values()) 695 if (IncValue != &I) 696 return false; 697 698 return true; 699 } 700 701 /// Return true if the instruction is free in the loop. 702 static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop, 703 const TargetTransformInfo *TTI) { 704 705 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) { 706 if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free) 707 return false; 708 // For a GEP, we cannot simply use getUserCost because currently it 709 // optimistically assume that a GEP will fold into addressing mode 710 // regardless of its users. 711 const BasicBlock *BB = GEP->getParent(); 712 for (const User *U : GEP->users()) { 713 const Instruction *UI = cast<Instruction>(U); 714 if (CurLoop->contains(UI) && 715 (BB != UI->getParent() || 716 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI)))) 717 return false; 718 } 719 return true; 720 } else 721 return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free; 722 } 723 724 /// Return true if the only users of this instruction are outside of 725 /// the loop. If this is true, we can sink the instruction to the exit 726 /// blocks of the loop. 727 /// 728 /// We also return true if the instruction could be folded away in lowering. 729 /// (e.g., a GEP can be folded into a load as an addressing mode in the loop). 730 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, 731 const LoopSafetyInfo *SafetyInfo, 732 TargetTransformInfo *TTI, bool &FreeInLoop) { 733 const auto &BlockColors = SafetyInfo->BlockColors; 734 bool IsFree = isFreeInLoop(I, CurLoop, TTI); 735 for (const User *U : I.users()) { 736 const Instruction *UI = cast<Instruction>(U); 737 if (const PHINode *PN = dyn_cast<PHINode>(UI)) { 738 const BasicBlock *BB = PN->getParent(); 739 // We cannot sink uses in catchswitches. 740 if (isa<CatchSwitchInst>(BB->getTerminator())) 741 return false; 742 743 // We need to sink a callsite to a unique funclet. Avoid sinking if the 744 // phi use is too muddled. 745 if (isa<CallInst>(I)) 746 if (!BlockColors.empty() && 747 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1) 748 return false; 749 } 750 751 if (CurLoop->contains(UI)) { 752 if (IsFree) { 753 FreeInLoop = true; 754 continue; 755 } 756 return false; 757 } 758 } 759 return true; 760 } 761 762 static Instruction * 763 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, 764 const LoopInfo *LI, 765 const LoopSafetyInfo *SafetyInfo) { 766 Instruction *New; 767 if (auto *CI = dyn_cast<CallInst>(&I)) { 768 const auto &BlockColors = SafetyInfo->BlockColors; 769 770 // Sinking call-sites need to be handled differently from other 771 // instructions. The cloned call-site needs a funclet bundle operand 772 // appropriate for it's location in the CFG. 773 SmallVector<OperandBundleDef, 1> OpBundles; 774 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles(); 775 BundleIdx != BundleEnd; ++BundleIdx) { 776 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx); 777 if (Bundle.getTagID() == LLVMContext::OB_funclet) 778 continue; 779 780 OpBundles.emplace_back(Bundle); 781 } 782 783 if (!BlockColors.empty()) { 784 const ColorVector &CV = BlockColors.find(&ExitBlock)->second; 785 assert(CV.size() == 1 && "non-unique color for exit block!"); 786 BasicBlock *BBColor = CV.front(); 787 Instruction *EHPad = BBColor->getFirstNonPHI(); 788 if (EHPad->isEHPad()) 789 OpBundles.emplace_back("funclet", EHPad); 790 } 791 792 New = CallInst::Create(CI, OpBundles); 793 } else { 794 New = I.clone(); 795 } 796 797 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New); 798 if (!I.getName().empty()) 799 New->setName(I.getName() + ".le"); 800 801 // Build LCSSA PHI nodes for any in-loop operands. Note that this is 802 // particularly cheap because we can rip off the PHI node that we're 803 // replacing for the number and blocks of the predecessors. 804 // OPT: If this shows up in a profile, we can instead finish sinking all 805 // invariant instructions, and then walk their operands to re-establish 806 // LCSSA. That will eliminate creating PHI nodes just to nuke them when 807 // sinking bottom-up. 808 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE; 809 ++OI) 810 if (Instruction *OInst = dyn_cast<Instruction>(*OI)) 811 if (Loop *OLoop = LI->getLoopFor(OInst->getParent())) 812 if (!OLoop->contains(&PN)) { 813 PHINode *OpPN = 814 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(), 815 OInst->getName() + ".lcssa", &ExitBlock.front()); 816 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) 817 OpPN->addIncoming(OInst, PN.getIncomingBlock(i)); 818 *OI = OpPN; 819 } 820 return New; 821 } 822 823 static Instruction *sinkThroughTriviallyReplaceablePHI( 824 PHINode *TPN, Instruction *I, LoopInfo *LI, 825 SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies, 826 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop) { 827 assert(isTriviallyReplaceablePHI(*TPN, *I) && 828 "Expect only trivially replaceable PHI"); 829 BasicBlock *ExitBlock = TPN->getParent(); 830 Instruction *New; 831 auto It = SunkCopies.find(ExitBlock); 832 if (It != SunkCopies.end()) 833 New = It->second; 834 else 835 New = SunkCopies[ExitBlock] = 836 CloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI, SafetyInfo); 837 return New; 838 } 839 840 static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) { 841 BasicBlock *BB = PN->getParent(); 842 if (!BB->canSplitPredecessors()) 843 return false; 844 // It's not impossible to split EHPad blocks, but if BlockColors already exist 845 // it require updating BlockColors for all offspring blocks accordingly. By 846 // skipping such corner case, we can make updating BlockColors after splitting 847 // predecessor fairly simple. 848 if (!SafetyInfo->BlockColors.empty() && BB->getFirstNonPHI()->isEHPad()) 849 return false; 850 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 851 BasicBlock *BBPred = *PI; 852 if (isa<IndirectBrInst>(BBPred->getTerminator())) 853 return false; 854 } 855 return true; 856 } 857 858 static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, 859 LoopInfo *LI, const Loop *CurLoop, 860 LoopSafetyInfo *SafetyInfo) { 861 #ifndef NDEBUG 862 SmallVector<BasicBlock *, 32> ExitBlocks; 863 CurLoop->getUniqueExitBlocks(ExitBlocks); 864 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), 865 ExitBlocks.end()); 866 #endif 867 BasicBlock *ExitBB = PN->getParent(); 868 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block."); 869 870 // Split predecessors of the loop exit to make instructions in the loop are 871 // exposed to exit blocks through trivially replaceable PHIs while keeping the 872 // loop in the canonical form where each predecessor of each exit block should 873 // be contained within the loop. For example, this will convert the loop below 874 // from 875 // 876 // LB1: 877 // %v1 = 878 // br %LE, %LB2 879 // LB2: 880 // %v2 = 881 // br %LE, %LB1 882 // LE: 883 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable 884 // 885 // to 886 // 887 // LB1: 888 // %v1 = 889 // br %LE.split, %LB2 890 // LB2: 891 // %v2 = 892 // br %LE.split2, %LB1 893 // LE.split: 894 // %p1 = phi [%v1, %LB1] <-- trivially replaceable 895 // br %LE 896 // LE.split2: 897 // %p2 = phi [%v2, %LB2] <-- trivially replaceable 898 // br %LE 899 // LE: 900 // %p = phi [%p1, %LE.split], [%p2, %LE.split2] 901 // 902 auto &BlockColors = SafetyInfo->BlockColors; 903 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB)); 904 while (!PredBBs.empty()) { 905 BasicBlock *PredBB = *PredBBs.begin(); 906 assert(CurLoop->contains(PredBB) && 907 "Expect all predecessors are in the loop"); 908 if (PN->getBasicBlockIndex(PredBB) >= 0) { 909 BasicBlock *NewPred = SplitBlockPredecessors( 910 ExitBB, PredBB, ".split.loop.exit", DT, LI, true); 911 // Since we do not allow splitting EH-block with BlockColors in 912 // canSplitPredecessors(), we can simply assign predecessor's color to 913 // the new block. 914 if (!BlockColors.empty()) { 915 // Grab a reference to the ColorVector to be inserted before getting the 916 // reference to the vector we are copying because inserting the new 917 // element in BlockColors might cause the map to be reallocated. 918 ColorVector &ColorsForNewBlock = BlockColors[NewPred]; 919 ColorVector &ColorsForOldBlock = BlockColors[PredBB]; 920 ColorsForNewBlock = ColorsForOldBlock; 921 } 922 } 923 PredBBs.remove(PredBB); 924 } 925 } 926 927 /// When an instruction is found to only be used outside of the loop, this 928 /// function moves it to the exit blocks and patches up SSA form as needed. 929 /// This method is guaranteed to remove the original instruction from its 930 /// position, and may either delete it or move it to outside of the loop. 931 /// 932 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, 933 const Loop *CurLoop, LoopSafetyInfo *SafetyInfo, 934 OptimizationRemarkEmitter *ORE, bool FreeInLoop) { 935 LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n"); 936 ORE->emit([&]() { 937 return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I) 938 << "sinking " << ore::NV("Inst", &I); 939 }); 940 bool Changed = false; 941 if (isa<LoadInst>(I)) 942 ++NumMovedLoads; 943 else if (isa<CallInst>(I)) 944 ++NumMovedCalls; 945 ++NumSunk; 946 947 // Iterate over users to be ready for actual sinking. Replace users via 948 // unrechable blocks with undef and make all user PHIs trivially replcable. 949 SmallPtrSet<Instruction *, 8> VisitedUsers; 950 for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) { 951 auto *User = cast<Instruction>(*UI); 952 Use &U = UI.getUse(); 953 ++UI; 954 955 if (VisitedUsers.count(User) || CurLoop->contains(User)) 956 continue; 957 958 if (!DT->isReachableFromEntry(User->getParent())) { 959 U = UndefValue::get(I.getType()); 960 Changed = true; 961 continue; 962 } 963 964 // The user must be a PHI node. 965 PHINode *PN = cast<PHINode>(User); 966 967 // Surprisingly, instructions can be used outside of loops without any 968 // exits. This can only happen in PHI nodes if the incoming block is 969 // unreachable. 970 BasicBlock *BB = PN->getIncomingBlock(U); 971 if (!DT->isReachableFromEntry(BB)) { 972 U = UndefValue::get(I.getType()); 973 Changed = true; 974 continue; 975 } 976 977 VisitedUsers.insert(PN); 978 if (isTriviallyReplaceablePHI(*PN, I)) 979 continue; 980 981 if (!canSplitPredecessors(PN, SafetyInfo)) 982 return Changed; 983 984 // Split predecessors of the PHI so that we can make users trivially 985 // replaceable. 986 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo); 987 988 // Should rebuild the iterators, as they may be invalidated by 989 // splitPredecessorsOfLoopExit(). 990 UI = I.user_begin(); 991 UE = I.user_end(); 992 } 993 994 if (VisitedUsers.empty()) 995 return Changed; 996 997 #ifndef NDEBUG 998 SmallVector<BasicBlock *, 32> ExitBlocks; 999 CurLoop->getUniqueExitBlocks(ExitBlocks); 1000 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), 1001 ExitBlocks.end()); 1002 #endif 1003 1004 // Clones of this instruction. Don't create more than one per exit block! 1005 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies; 1006 1007 // If this instruction is only used outside of the loop, then all users are 1008 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of 1009 // the instruction. 1010 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end()); 1011 for (auto *UI : Users) { 1012 auto *User = cast<Instruction>(UI); 1013 1014 if (CurLoop->contains(User)) 1015 continue; 1016 1017 PHINode *PN = cast<PHINode>(User); 1018 assert(ExitBlockSet.count(PN->getParent()) && 1019 "The LCSSA PHI is not in an exit block!"); 1020 // The PHI must be trivially replaceable. 1021 Instruction *New = sinkThroughTriviallyReplaceablePHI(PN, &I, LI, SunkCopies, 1022 SafetyInfo, CurLoop); 1023 PN->replaceAllUsesWith(New); 1024 PN->eraseFromParent(); 1025 Changed = true; 1026 } 1027 return Changed; 1028 } 1029 1030 /// When an instruction is found to only use loop invariant operands that 1031 /// is safe to hoist, this instruction is called to do the dirty work. 1032 /// 1033 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 1034 const LoopSafetyInfo *SafetyInfo, 1035 OptimizationRemarkEmitter *ORE) { 1036 auto *Preheader = CurLoop->getLoopPreheader(); 1037 LLVM_DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I 1038 << "\n"); 1039 ORE->emit([&]() { 1040 return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting " 1041 << ore::NV("Inst", &I); 1042 }); 1043 1044 // Metadata can be dependent on conditions we are hoisting above. 1045 // Conservatively strip all metadata on the instruction unless we were 1046 // guaranteed to execute I if we entered the loop, in which case the metadata 1047 // is valid in the loop preheader. 1048 if (I.hasMetadataOtherThanDebugLoc() && 1049 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning 1050 // time in isGuaranteedToExecute if we don't actually have anything to 1051 // drop. It is a compile time optimization, not required for correctness. 1052 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo)) 1053 I.dropUnknownNonDebugMetadata(); 1054 1055 // Move the new node to the Preheader, before its terminator. 1056 I.moveBefore(Preheader->getTerminator()); 1057 1058 // Do not retain debug locations when we are moving instructions to different 1059 // basic blocks, because we want to avoid jumpy line tables. Calls, however, 1060 // need to retain their debug locs because they may be inlined. 1061 // FIXME: How do we retain source locations without causing poor debugging 1062 // behavior? 1063 if (!isa<CallInst>(I)) 1064 I.setDebugLoc(DebugLoc()); 1065 1066 if (isa<LoadInst>(I)) 1067 ++NumMovedLoads; 1068 else if (isa<CallInst>(I)) 1069 ++NumMovedCalls; 1070 ++NumHoisted; 1071 return true; 1072 } 1073 1074 /// Only sink or hoist an instruction if it is not a trapping instruction, 1075 /// or if the instruction is known not to trap when moved to the preheader. 1076 /// or if it is a trapping instruction and is guaranteed to execute. 1077 static bool isSafeToExecuteUnconditionally(Instruction &Inst, 1078 const DominatorTree *DT, 1079 const Loop *CurLoop, 1080 const LoopSafetyInfo *SafetyInfo, 1081 OptimizationRemarkEmitter *ORE, 1082 const Instruction *CtxI) { 1083 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT)) 1084 return true; 1085 1086 bool GuaranteedToExecute = 1087 isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo); 1088 1089 if (!GuaranteedToExecute) { 1090 auto *LI = dyn_cast<LoadInst>(&Inst); 1091 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand())) 1092 ORE->emit([&]() { 1093 return OptimizationRemarkMissed( 1094 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI) 1095 << "failed to hoist load with loop-invariant address " 1096 "because load is conditionally executed"; 1097 }); 1098 } 1099 1100 return GuaranteedToExecute; 1101 } 1102 1103 namespace { 1104 class LoopPromoter : public LoadAndStorePromoter { 1105 Value *SomePtr; // Designated pointer to store to. 1106 const SmallSetVector<Value *, 8> &PointerMustAliases; 1107 SmallVectorImpl<BasicBlock *> &LoopExitBlocks; 1108 SmallVectorImpl<Instruction *> &LoopInsertPts; 1109 PredIteratorCache &PredCache; 1110 AliasSetTracker &AST; 1111 LoopInfo &LI; 1112 DebugLoc DL; 1113 int Alignment; 1114 bool UnorderedAtomic; 1115 AAMDNodes AATags; 1116 1117 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const { 1118 if (Instruction *I = dyn_cast<Instruction>(V)) 1119 if (Loop *L = LI.getLoopFor(I->getParent())) 1120 if (!L->contains(BB)) { 1121 // We need to create an LCSSA PHI node for the incoming value and 1122 // store that. 1123 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB), 1124 I->getName() + ".lcssa", &BB->front()); 1125 for (BasicBlock *Pred : PredCache.get(BB)) 1126 PN->addIncoming(I, Pred); 1127 return PN; 1128 } 1129 return V; 1130 } 1131 1132 public: 1133 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S, 1134 const SmallSetVector<Value *, 8> &PMA, 1135 SmallVectorImpl<BasicBlock *> &LEB, 1136 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC, 1137 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment, 1138 bool UnorderedAtomic, const AAMDNodes &AATags) 1139 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA), 1140 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast), 1141 LI(li), DL(std::move(dl)), Alignment(alignment), 1142 UnorderedAtomic(UnorderedAtomic), AATags(AATags) {} 1143 1144 bool isInstInList(Instruction *I, 1145 const SmallVectorImpl<Instruction *> &) const override { 1146 Value *Ptr; 1147 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 1148 Ptr = LI->getOperand(0); 1149 else 1150 Ptr = cast<StoreInst>(I)->getPointerOperand(); 1151 return PointerMustAliases.count(Ptr); 1152 } 1153 1154 void doExtraRewritesBeforeFinalDeletion() const override { 1155 // Insert stores after in the loop exit blocks. Each exit block gets a 1156 // store of the live-out values that feed them. Since we've already told 1157 // the SSA updater about the defs in the loop and the preheader 1158 // definition, it is all set and we can start using it. 1159 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) { 1160 BasicBlock *ExitBlock = LoopExitBlocks[i]; 1161 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock); 1162 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock); 1163 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock); 1164 Instruction *InsertPos = LoopInsertPts[i]; 1165 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos); 1166 if (UnorderedAtomic) 1167 NewSI->setOrdering(AtomicOrdering::Unordered); 1168 NewSI->setAlignment(Alignment); 1169 NewSI->setDebugLoc(DL); 1170 if (AATags) 1171 NewSI->setAAMetadata(AATags); 1172 } 1173 } 1174 1175 void replaceLoadWithValue(LoadInst *LI, Value *V) const override { 1176 // Update alias analysis. 1177 AST.copyValue(LI, V); 1178 } 1179 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); } 1180 }; 1181 1182 1183 /// Return true iff we can prove that a caller of this function can not inspect 1184 /// the contents of the provided object in a well defined program. 1185 bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) { 1186 if (isa<AllocaInst>(Object)) 1187 // Since the alloca goes out of scope, we know the caller can't retain a 1188 // reference to it and be well defined. Thus, we don't need to check for 1189 // capture. 1190 return true; 1191 1192 // For all other objects we need to know that the caller can't possibly 1193 // have gotten a reference to the object. There are two components of 1194 // that: 1195 // 1) Object can't be escaped by this function. This is what 1196 // PointerMayBeCaptured checks. 1197 // 2) Object can't have been captured at definition site. For this, we 1198 // need to know the return value is noalias. At the moment, we use a 1199 // weaker condition and handle only AllocLikeFunctions (which are 1200 // known to be noalias). TODO 1201 return isAllocLikeFn(Object, TLI) && 1202 !PointerMayBeCaptured(Object, true, true); 1203 } 1204 1205 } // namespace 1206 1207 /// Try to promote memory values to scalars by sinking stores out of the 1208 /// loop and moving loads to before the loop. We do this by looping over 1209 /// the stores in the loop, looking for stores to Must pointers which are 1210 /// loop invariant. 1211 /// 1212 bool llvm::promoteLoopAccessesToScalars( 1213 const SmallSetVector<Value *, 8> &PointerMustAliases, 1214 SmallVectorImpl<BasicBlock *> &ExitBlocks, 1215 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC, 1216 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, 1217 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo, 1218 OptimizationRemarkEmitter *ORE) { 1219 // Verify inputs. 1220 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr && 1221 CurAST != nullptr && SafetyInfo != nullptr && 1222 "Unexpected Input to promoteLoopAccessesToScalars"); 1223 1224 Value *SomePtr = *PointerMustAliases.begin(); 1225 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 1226 1227 // It is not safe to promote a load/store from the loop if the load/store is 1228 // conditional. For example, turning: 1229 // 1230 // for () { if (c) *P += 1; } 1231 // 1232 // into: 1233 // 1234 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp; 1235 // 1236 // is not safe, because *P may only be valid to access if 'c' is true. 1237 // 1238 // The safety property divides into two parts: 1239 // p1) The memory may not be dereferenceable on entry to the loop. In this 1240 // case, we can't insert the required load in the preheader. 1241 // p2) The memory model does not allow us to insert a store along any dynamic 1242 // path which did not originally have one. 1243 // 1244 // If at least one store is guaranteed to execute, both properties are 1245 // satisfied, and promotion is legal. 1246 // 1247 // This, however, is not a necessary condition. Even if no store/load is 1248 // guaranteed to execute, we can still establish these properties. 1249 // We can establish (p1) by proving that hoisting the load into the preheader 1250 // is safe (i.e. proving dereferenceability on all paths through the loop). We 1251 // can use any access within the alias set to prove dereferenceability, 1252 // since they're all must alias. 1253 // 1254 // There are two ways establish (p2): 1255 // a) Prove the location is thread-local. In this case the memory model 1256 // requirement does not apply, and stores are safe to insert. 1257 // b) Prove a store dominates every exit block. In this case, if an exit 1258 // blocks is reached, the original dynamic path would have taken us through 1259 // the store, so inserting a store into the exit block is safe. Note that this 1260 // is different from the store being guaranteed to execute. For instance, 1261 // if an exception is thrown on the first iteration of the loop, the original 1262 // store is never executed, but the exit blocks are not executed either. 1263 1264 bool DereferenceableInPH = false; 1265 bool SafeToInsertStore = false; 1266 1267 SmallVector<Instruction *, 64> LoopUses; 1268 1269 // We start with an alignment of one and try to find instructions that allow 1270 // us to prove better alignment. 1271 unsigned Alignment = 1; 1272 // Keep track of which types of access we see 1273 bool SawUnorderedAtomic = false; 1274 bool SawNotAtomic = false; 1275 AAMDNodes AATags; 1276 1277 const DataLayout &MDL = Preheader->getModule()->getDataLayout(); 1278 1279 bool IsKnownThreadLocalObject = false; 1280 if (SafetyInfo->MayThrow) { 1281 // If a loop can throw, we have to insert a store along each unwind edge. 1282 // That said, we can't actually make the unwind edge explicit. Therefore, 1283 // we have to prove that the store is dead along the unwind edge. We do 1284 // this by proving that the caller can't have a reference to the object 1285 // after return and thus can't possibly load from the object. 1286 Value *Object = GetUnderlyingObject(SomePtr, MDL); 1287 if (!isKnownNonEscaping(Object, TLI)) 1288 return false; 1289 // Subtlety: Alloca's aren't visible to callers, but *are* potentially 1290 // visible to other threads if captured and used during their lifetimes. 1291 IsKnownThreadLocalObject = !isa<AllocaInst>(Object); 1292 } 1293 1294 // Check that all of the pointers in the alias set have the same type. We 1295 // cannot (yet) promote a memory location that is loaded and stored in 1296 // different sizes. While we are at it, collect alignment and AA info. 1297 for (Value *ASIV : PointerMustAliases) { 1298 // Check that all of the pointers in the alias set have the same type. We 1299 // cannot (yet) promote a memory location that is loaded and stored in 1300 // different sizes. 1301 if (SomePtr->getType() != ASIV->getType()) 1302 return false; 1303 1304 for (User *U : ASIV->users()) { 1305 // Ignore instructions that are outside the loop. 1306 Instruction *UI = dyn_cast<Instruction>(U); 1307 if (!UI || !CurLoop->contains(UI)) 1308 continue; 1309 1310 // If there is an non-load/store instruction in the loop, we can't promote 1311 // it. 1312 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) { 1313 assert(!Load->isVolatile() && "AST broken"); 1314 if (!Load->isUnordered()) 1315 return false; 1316 1317 SawUnorderedAtomic |= Load->isAtomic(); 1318 SawNotAtomic |= !Load->isAtomic(); 1319 1320 if (!DereferenceableInPH) 1321 DereferenceableInPH = isSafeToExecuteUnconditionally( 1322 *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator()); 1323 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) { 1324 // Stores *of* the pointer are not interesting, only stores *to* the 1325 // pointer. 1326 if (UI->getOperand(1) != ASIV) 1327 continue; 1328 assert(!Store->isVolatile() && "AST broken"); 1329 if (!Store->isUnordered()) 1330 return false; 1331 1332 SawUnorderedAtomic |= Store->isAtomic(); 1333 SawNotAtomic |= !Store->isAtomic(); 1334 1335 // If the store is guaranteed to execute, both properties are satisfied. 1336 // We may want to check if a store is guaranteed to execute even if we 1337 // already know that promotion is safe, since it may have higher 1338 // alignment than any other guaranteed stores, in which case we can 1339 // raise the alignment on the promoted store. 1340 unsigned InstAlignment = Store->getAlignment(); 1341 if (!InstAlignment) 1342 InstAlignment = 1343 MDL.getABITypeAlignment(Store->getValueOperand()->getType()); 1344 1345 if (!DereferenceableInPH || !SafeToInsertStore || 1346 (InstAlignment > Alignment)) { 1347 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) { 1348 DereferenceableInPH = true; 1349 SafeToInsertStore = true; 1350 Alignment = std::max(Alignment, InstAlignment); 1351 } 1352 } 1353 1354 // If a store dominates all exit blocks, it is safe to sink. 1355 // As explained above, if an exit block was executed, a dominating 1356 // store must have been executed at least once, so we are not 1357 // introducing stores on paths that did not have them. 1358 // Note that this only looks at explicit exit blocks. If we ever 1359 // start sinking stores into unwind edges (see above), this will break. 1360 if (!SafeToInsertStore) 1361 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) { 1362 return DT->dominates(Store->getParent(), Exit); 1363 }); 1364 1365 // If the store is not guaranteed to execute, we may still get 1366 // deref info through it. 1367 if (!DereferenceableInPH) { 1368 DereferenceableInPH = isDereferenceableAndAlignedPointer( 1369 Store->getPointerOperand(), Store->getAlignment(), MDL, 1370 Preheader->getTerminator(), DT); 1371 } 1372 } else 1373 return false; // Not a load or store. 1374 1375 // Merge the AA tags. 1376 if (LoopUses.empty()) { 1377 // On the first load/store, just take its AA tags. 1378 UI->getAAMetadata(AATags); 1379 } else if (AATags) { 1380 UI->getAAMetadata(AATags, /* Merge = */ true); 1381 } 1382 1383 LoopUses.push_back(UI); 1384 } 1385 } 1386 1387 // If we found both an unordered atomic instruction and a non-atomic memory 1388 // access, bail. We can't blindly promote non-atomic to atomic since we 1389 // might not be able to lower the result. We can't downgrade since that 1390 // would violate memory model. Also, align 0 is an error for atomics. 1391 if (SawUnorderedAtomic && SawNotAtomic) 1392 return false; 1393 1394 // If we couldn't prove we can hoist the load, bail. 1395 if (!DereferenceableInPH) 1396 return false; 1397 1398 // We know we can hoist the load, but don't have a guaranteed store. 1399 // Check whether the location is thread-local. If it is, then we can insert 1400 // stores along paths which originally didn't have them without violating the 1401 // memory model. 1402 if (!SafeToInsertStore) { 1403 if (IsKnownThreadLocalObject) 1404 SafeToInsertStore = true; 1405 else { 1406 Value *Object = GetUnderlyingObject(SomePtr, MDL); 1407 SafeToInsertStore = 1408 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) && 1409 !PointerMayBeCaptured(Object, true, true); 1410 } 1411 } 1412 1413 // If we've still failed to prove we can sink the store, give up. 1414 if (!SafeToInsertStore) 1415 return false; 1416 1417 // Otherwise, this is safe to promote, lets do it! 1418 LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr 1419 << '\n'); 1420 ORE->emit([&]() { 1421 return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar", 1422 LoopUses[0]) 1423 << "Moving accesses to memory location out of the loop"; 1424 }); 1425 ++NumPromoted; 1426 1427 // Grab a debug location for the inserted loads/stores; given that the 1428 // inserted loads/stores have little relation to the original loads/stores, 1429 // this code just arbitrarily picks a location from one, since any debug 1430 // location is better than none. 1431 DebugLoc DL = LoopUses[0]->getDebugLoc(); 1432 1433 // We use the SSAUpdater interface to insert phi nodes as required. 1434 SmallVector<PHINode *, 16> NewPHIs; 1435 SSAUpdater SSA(&NewPHIs); 1436 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks, 1437 InsertPts, PIC, *CurAST, *LI, DL, Alignment, 1438 SawUnorderedAtomic, AATags); 1439 1440 // Set up the preheader to have a definition of the value. It is the live-out 1441 // value from the preheader that uses in the loop will use. 1442 LoadInst *PreheaderLoad = new LoadInst( 1443 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator()); 1444 if (SawUnorderedAtomic) 1445 PreheaderLoad->setOrdering(AtomicOrdering::Unordered); 1446 PreheaderLoad->setAlignment(Alignment); 1447 PreheaderLoad->setDebugLoc(DL); 1448 if (AATags) 1449 PreheaderLoad->setAAMetadata(AATags); 1450 SSA.AddAvailableValue(Preheader, PreheaderLoad); 1451 1452 // Rewrite all the loads in the loop and remember all the definitions from 1453 // stores in the loop. 1454 Promoter.run(LoopUses); 1455 1456 // If the SSAUpdater didn't use the load in the preheader, just zap it now. 1457 if (PreheaderLoad->use_empty()) 1458 PreheaderLoad->eraseFromParent(); 1459 1460 return true; 1461 } 1462 1463 /// Returns an owning pointer to an alias set which incorporates aliasing info 1464 /// from L and all subloops of L. 1465 /// FIXME: In new pass manager, there is no helper function to handle loop 1466 /// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed 1467 /// from scratch for every loop. Hook up with the helper functions when 1468 /// available in the new pass manager to avoid redundant computation. 1469 AliasSetTracker * 1470 LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI, 1471 AliasAnalysis *AA) { 1472 AliasSetTracker *CurAST = nullptr; 1473 SmallVector<Loop *, 4> RecomputeLoops; 1474 for (Loop *InnerL : L->getSubLoops()) { 1475 auto MapI = LoopToAliasSetMap.find(InnerL); 1476 // If the AST for this inner loop is missing it may have been merged into 1477 // some other loop's AST and then that loop unrolled, and so we need to 1478 // recompute it. 1479 if (MapI == LoopToAliasSetMap.end()) { 1480 RecomputeLoops.push_back(InnerL); 1481 continue; 1482 } 1483 AliasSetTracker *InnerAST = MapI->second; 1484 1485 if (CurAST != nullptr) { 1486 // What if InnerLoop was modified by other passes ? 1487 CurAST->add(*InnerAST); 1488 1489 // Once we've incorporated the inner loop's AST into ours, we don't need 1490 // the subloop's anymore. 1491 delete InnerAST; 1492 } else { 1493 CurAST = InnerAST; 1494 } 1495 LoopToAliasSetMap.erase(MapI); 1496 } 1497 if (CurAST == nullptr) 1498 CurAST = new AliasSetTracker(*AA); 1499 1500 auto mergeLoop = [&](Loop *L) { 1501 // Loop over the body of this loop, looking for calls, invokes, and stores. 1502 for (BasicBlock *BB : L->blocks()) 1503 CurAST->add(*BB); // Incorporate the specified basic block 1504 }; 1505 1506 // Add everything from the sub loops that are no longer directly available. 1507 for (Loop *InnerL : RecomputeLoops) 1508 mergeLoop(InnerL); 1509 1510 // And merge in this loop. 1511 mergeLoop(L); 1512 1513 return CurAST; 1514 } 1515 1516 /// Simple analysis hook. Clone alias set info. 1517 /// 1518 void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, 1519 Loop *L) { 1520 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L); 1521 if (!AST) 1522 return; 1523 1524 AST->copyValue(From, To); 1525 } 1526 1527 /// Simple Analysis hook. Delete value V from alias set 1528 /// 1529 void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) { 1530 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L); 1531 if (!AST) 1532 return; 1533 1534 AST->deleteValue(V); 1535 } 1536 1537 /// Simple Analysis hook. Delete value L from alias set map. 1538 /// 1539 void LegacyLICMPass::deleteAnalysisLoop(Loop *L) { 1540 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L); 1541 if (!AST) 1542 return; 1543 1544 delete AST; 1545 LICM.getLoopToAliasSetMap().erase(L); 1546 } 1547 1548 /// Return true if the body of this loop may store into the memory 1549 /// location pointed to by V. 1550 /// 1551 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, 1552 const AAMDNodes &AAInfo, 1553 AliasSetTracker *CurAST) { 1554 // Check to see if any of the basic blocks in CurLoop invalidate *V. 1555 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod(); 1556 } 1557 1558 /// Little predicate that returns true if the specified basic block is in 1559 /// a subloop of the current one, not the current one itself. 1560 /// 1561 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) { 1562 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop"); 1563 return LI->getLoopFor(BB) != CurLoop; 1564 } 1565