1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===// 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 pass performs loop invariant code motion, attempting to remove as much 10 // code from the body of a loop as possible. It does this by either hoisting 11 // code into the preheader block, or by sinking code to the exit blocks if it is 12 // safe. This pass also promotes must-aliased memory locations in the loop to 13 // live in registers, thus hoisting and sinking "invariant" loads and stores. 14 // 15 // This pass uses alias analysis for two purposes: 16 // 17 // 1. Moving loop invariant loads and calls out of loops. If we can determine 18 // that a load or call inside of a loop never aliases anything stored to, 19 // we can hoist it or sink it like any other instruction. 20 // 2. Scalar Promotion of Memory - If there is a store instruction inside of 21 // the loop, we try to move the store to happen AFTER the loop instead of 22 // inside of the loop. This can only happen if a few conditions are true: 23 // A. The pointer stored through is loop invariant 24 // B. There are no stores or loads in the loop which _may_ alias the 25 // pointer. There are no calls in the loop which mod/ref the pointer. 26 // If these conditions are true, we can promote the loads and stores in the 27 // loop of the pointer to use a temporary alloca'd variable. We then use 28 // the SSAUpdater to construct the appropriate SSA form for the value. 29 // 30 //===----------------------------------------------------------------------===// 31 32 #include "llvm/Transforms/Scalar/LICM.h" 33 #include "llvm/ADT/SetOperations.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/GuardUtils.h" 42 #include "llvm/Analysis/Loads.h" 43 #include "llvm/Analysis/LoopInfo.h" 44 #include "llvm/Analysis/LoopIterator.h" 45 #include "llvm/Analysis/LoopPass.h" 46 #include "llvm/Analysis/MemoryBuiltins.h" 47 #include "llvm/Analysis/MemorySSA.h" 48 #include "llvm/Analysis/MemorySSAUpdater.h" 49 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 50 #include "llvm/Analysis/ScalarEvolution.h" 51 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 52 #include "llvm/Analysis/TargetLibraryInfo.h" 53 #include "llvm/Analysis/ValueTracking.h" 54 #include "llvm/IR/CFG.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/DebugInfoMetadata.h" 58 #include "llvm/IR/DerivedTypes.h" 59 #include "llvm/IR/Dominators.h" 60 #include "llvm/IR/Instructions.h" 61 #include "llvm/IR/IntrinsicInst.h" 62 #include "llvm/IR/LLVMContext.h" 63 #include "llvm/IR/Metadata.h" 64 #include "llvm/IR/PatternMatch.h" 65 #include "llvm/IR/PredIteratorCache.h" 66 #include "llvm/InitializePasses.h" 67 #include "llvm/Support/CommandLine.h" 68 #include "llvm/Support/Debug.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include "llvm/Transforms/Scalar.h" 71 #include "llvm/Transforms/Scalar/LoopPassManager.h" 72 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 73 #include "llvm/Transforms/Utils/Local.h" 74 #include "llvm/Transforms/Utils/LoopUtils.h" 75 #include "llvm/Transforms/Utils/SSAUpdater.h" 76 #include <algorithm> 77 #include <utility> 78 using namespace llvm; 79 80 #define DEBUG_TYPE "licm" 81 82 STATISTIC(NumCreatedBlocks, "Number of blocks created"); 83 STATISTIC(NumClonedBranches, "Number of branches cloned"); 84 STATISTIC(NumSunk, "Number of instructions sunk out of loop"); 85 STATISTIC(NumHoisted, "Number of instructions hoisted out of loop"); 86 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk"); 87 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk"); 88 STATISTIC(NumPromoted, "Number of memory locations promoted to registers"); 89 90 /// Memory promotion is enabled by default. 91 static cl::opt<bool> 92 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false), 93 cl::desc("Disable memory promotion in LICM pass")); 94 95 static cl::opt<bool> ControlFlowHoisting( 96 "licm-control-flow-hoisting", cl::Hidden, cl::init(false), 97 cl::desc("Enable control flow (and PHI) hoisting in LICM")); 98 99 static cl::opt<uint32_t> MaxNumUsesTraversed( 100 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8), 101 cl::desc("Max num uses visited for identifying load " 102 "invariance in loop using invariant start (default = 8)")); 103 104 // Default value of zero implies we use the regular alias set tracker mechanism 105 // instead of the cross product using AA to identify aliasing of the memory 106 // location we are interested in. 107 static cl::opt<int> 108 LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0), 109 cl::desc("How many instruction to cross product using AA")); 110 111 // Experimental option to allow imprecision in LICM in pathological cases, in 112 // exchange for faster compile. This is to be removed if MemorySSA starts to 113 // address the same issue. This flag applies only when LICM uses MemorySSA 114 // instead on AliasSetTracker. LICM calls MemorySSAWalker's 115 // getClobberingMemoryAccess, up to the value of the Cap, getting perfect 116 // accuracy. Afterwards, LICM will call into MemorySSA's getDefiningAccess, 117 // which may not be precise, since optimizeUses is capped. The result is 118 // correct, but we may not get as "far up" as possible to get which access is 119 // clobbering the one queried. 120 cl::opt<unsigned> llvm::SetLicmMssaOptCap( 121 "licm-mssa-optimization-cap", cl::init(100), cl::Hidden, 122 cl::desc("Enable imprecision in LICM in pathological cases, in exchange " 123 "for faster compile. Caps the MemorySSA clobbering calls.")); 124 125 // Experimentally, memory promotion carries less importance than sinking and 126 // hoisting. Limit when we do promotion when using MemorySSA, in order to save 127 // compile time. 128 cl::opt<unsigned> llvm::SetLicmMssaNoAccForPromotionCap( 129 "licm-mssa-max-acc-promotion", cl::init(250), cl::Hidden, 130 cl::desc("[LICM & MemorySSA] When MSSA in LICM is disabled, this has no " 131 "effect. When MSSA in LICM is enabled, then this is the maximum " 132 "number of accesses allowed to be present in a loop in order to " 133 "enable memory promotion.")); 134 135 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI); 136 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, 137 const LoopSafetyInfo *SafetyInfo, 138 TargetTransformInfo *TTI, bool &FreeInLoop); 139 static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 140 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo, 141 MemorySSAUpdater *MSSAU, ScalarEvolution *SE, 142 OptimizationRemarkEmitter *ORE); 143 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, 144 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo, 145 MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE); 146 static bool isSafeToExecuteUnconditionally(Instruction &Inst, 147 const DominatorTree *DT, 148 const Loop *CurLoop, 149 const LoopSafetyInfo *SafetyInfo, 150 OptimizationRemarkEmitter *ORE, 151 const Instruction *CtxI = nullptr); 152 static bool pointerInvalidatedByLoop(MemoryLocation MemLoc, 153 AliasSetTracker *CurAST, Loop *CurLoop, 154 AliasAnalysis *AA); 155 static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU, 156 Loop *CurLoop, 157 SinkAndHoistLICMFlags &Flags); 158 static Instruction *cloneInstructionInExitBlock( 159 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, 160 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU); 161 162 static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, 163 AliasSetTracker *AST, MemorySSAUpdater *MSSAU); 164 165 static void moveInstructionBefore(Instruction &I, Instruction &Dest, 166 ICFLoopSafetyInfo &SafetyInfo, 167 MemorySSAUpdater *MSSAU, ScalarEvolution *SE); 168 169 namespace { 170 struct LoopInvariantCodeMotion { 171 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT, 172 TargetLibraryInfo *TLI, TargetTransformInfo *TTI, 173 ScalarEvolution *SE, MemorySSA *MSSA, 174 OptimizationRemarkEmitter *ORE); 175 176 LoopInvariantCodeMotion(unsigned LicmMssaOptCap, 177 unsigned LicmMssaNoAccForPromotionCap) 178 : LicmMssaOptCap(LicmMssaOptCap), 179 LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap) {} 180 181 private: 182 unsigned LicmMssaOptCap; 183 unsigned LicmMssaNoAccForPromotionCap; 184 185 std::unique_ptr<AliasSetTracker> 186 collectAliasInfoForLoop(Loop *L, LoopInfo *LI, AliasAnalysis *AA); 187 std::unique_ptr<AliasSetTracker> 188 collectAliasInfoForLoopWithMSSA(Loop *L, AliasAnalysis *AA, 189 MemorySSAUpdater *MSSAU); 190 }; 191 192 struct LegacyLICMPass : public LoopPass { 193 static char ID; // Pass identification, replacement for typeid 194 LegacyLICMPass( 195 unsigned LicmMssaOptCap = SetLicmMssaOptCap, 196 unsigned LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap) 197 : LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap) { 198 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry()); 199 } 200 201 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 202 if (skipLoop(L)) 203 return false; 204 205 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 206 MemorySSA *MSSA = EnableMSSALoopDependency 207 ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA()) 208 : nullptr; 209 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 210 // pass. Function analyses need to be preserved across loop transformations 211 // but ORE cannot be preserved (see comment before the pass definition). 212 OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); 213 return LICM.runOnLoop(L, 214 &getAnalysis<AAResultsWrapperPass>().getAAResults(), 215 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), 216 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 217 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI( 218 *L->getHeader()->getParent()), 219 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 220 *L->getHeader()->getParent()), 221 SE ? &SE->getSE() : nullptr, MSSA, &ORE); 222 } 223 224 /// This transformation requires natural loop information & requires that 225 /// loop preheaders be inserted into the CFG... 226 /// 227 void getAnalysisUsage(AnalysisUsage &AU) const override { 228 AU.addPreserved<DominatorTreeWrapperPass>(); 229 AU.addPreserved<LoopInfoWrapperPass>(); 230 AU.addRequired<TargetLibraryInfoWrapperPass>(); 231 if (EnableMSSALoopDependency) { 232 AU.addRequired<MemorySSAWrapperPass>(); 233 AU.addPreserved<MemorySSAWrapperPass>(); 234 } 235 AU.addRequired<TargetTransformInfoWrapperPass>(); 236 getLoopAnalysisUsage(AU); 237 } 238 239 private: 240 LoopInvariantCodeMotion LICM; 241 }; 242 } // namespace 243 244 PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM, 245 LoopStandardAnalysisResults &AR, LPMUpdater &) { 246 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis 247 // pass. Function analyses need to be preserved across loop transformations 248 // but ORE cannot be preserved (see comment before the pass definition). 249 OptimizationRemarkEmitter ORE(L.getHeader()->getParent()); 250 251 LoopInvariantCodeMotion LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap); 252 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE, 253 AR.MSSA, &ORE)) 254 return PreservedAnalyses::all(); 255 256 auto PA = getLoopPassPreservedAnalyses(); 257 258 PA.preserve<DominatorTreeAnalysis>(); 259 PA.preserve<LoopAnalysis>(); 260 if (AR.MSSA) 261 PA.preserve<MemorySSAAnalysis>(); 262 263 return PA; 264 } 265 266 char LegacyLICMPass::ID = 0; 267 INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion", 268 false, false) 269 INITIALIZE_PASS_DEPENDENCY(LoopPass) 270 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 271 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 272 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 273 INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false, 274 false) 275 276 Pass *llvm::createLICMPass() { return new LegacyLICMPass(); } 277 Pass *llvm::createLICMPass(unsigned LicmMssaOptCap, 278 unsigned LicmMssaNoAccForPromotionCap) { 279 return new LegacyLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap); 280 } 281 282 /// Hoist expressions out of the specified loop. Note, alias info for inner 283 /// loop is not preserved so it is not a good idea to run LICM multiple 284 /// times on one loop. 285 bool LoopInvariantCodeMotion::runOnLoop( 286 Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT, 287 TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE, 288 MemorySSA *MSSA, OptimizationRemarkEmitter *ORE) { 289 bool Changed = false; 290 291 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form."); 292 293 // If this loop has metadata indicating that LICM is not to be performed then 294 // just exit. 295 if (hasDisableLICMTransformsHint(L)) { 296 return false; 297 } 298 299 std::unique_ptr<AliasSetTracker> CurAST; 300 std::unique_ptr<MemorySSAUpdater> MSSAU; 301 bool NoOfMemAccTooLarge = false; 302 unsigned LicmMssaOptCounter = 0; 303 304 if (!MSSA) { 305 LLVM_DEBUG(dbgs() << "LICM: Using Alias Set Tracker.\n"); 306 CurAST = collectAliasInfoForLoop(L, LI, AA); 307 } else { 308 LLVM_DEBUG(dbgs() << "LICM: Using MemorySSA.\n"); 309 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 310 311 unsigned AccessCapCount = 0; 312 for (auto *BB : L->getBlocks()) { 313 if (auto *Accesses = MSSA->getBlockAccesses(BB)) { 314 for (const auto &MA : *Accesses) { 315 (void)MA; 316 AccessCapCount++; 317 if (AccessCapCount > LicmMssaNoAccForPromotionCap) { 318 NoOfMemAccTooLarge = true; 319 break; 320 } 321 } 322 } 323 if (NoOfMemAccTooLarge) 324 break; 325 } 326 } 327 328 // Get the preheader block to move instructions into... 329 BasicBlock *Preheader = L->getLoopPreheader(); 330 331 // Compute loop safety information. 332 ICFLoopSafetyInfo SafetyInfo(DT); 333 SafetyInfo.computeLoopSafetyInfo(L); 334 335 // We want to visit all of the instructions in this loop... that are not parts 336 // of our subloops (they have already had their invariants hoisted out of 337 // their loop, into this loop, so there is no need to process the BODIES of 338 // the subloops). 339 // 340 // Traverse the body of the loop in depth first order on the dominator tree so 341 // that we are guaranteed to see definitions before we see uses. This allows 342 // us to sink instructions in one pass, without iteration. After sinking 343 // instructions, we perform another pass to hoist them out of the loop. 344 SinkAndHoistLICMFlags Flags = {NoOfMemAccTooLarge, LicmMssaOptCounter, 345 LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 346 /*IsSink=*/true}; 347 if (L->hasDedicatedExits()) 348 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L, 349 CurAST.get(), MSSAU.get(), &SafetyInfo, Flags, ORE); 350 Flags.IsSink = false; 351 if (Preheader) 352 Changed |= 353 hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L, 354 CurAST.get(), MSSAU.get(), SE, &SafetyInfo, Flags, ORE); 355 356 // Now that all loop invariants have been removed from the loop, promote any 357 // memory references to scalars that we can. 358 // Don't sink stores from loops without dedicated block exits. Exits 359 // containing indirect branches are not transformed by loop simplify, 360 // make sure we catch that. An additional load may be generated in the 361 // preheader for SSA updater, so also avoid sinking when no preheader 362 // is available. 363 if (!DisablePromotion && Preheader && L->hasDedicatedExits() && 364 !NoOfMemAccTooLarge) { 365 // Figure out the loop exits and their insertion points 366 SmallVector<BasicBlock *, 8> ExitBlocks; 367 L->getUniqueExitBlocks(ExitBlocks); 368 369 // We can't insert into a catchswitch. 370 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) { 371 return isa<CatchSwitchInst>(Exit->getTerminator()); 372 }); 373 374 if (!HasCatchSwitch) { 375 SmallVector<Instruction *, 8> InsertPts; 376 SmallVector<MemoryAccess *, 8> MSSAInsertPts; 377 InsertPts.reserve(ExitBlocks.size()); 378 if (MSSAU) 379 MSSAInsertPts.reserve(ExitBlocks.size()); 380 for (BasicBlock *ExitBlock : ExitBlocks) { 381 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt()); 382 if (MSSAU) 383 MSSAInsertPts.push_back(nullptr); 384 } 385 386 PredIteratorCache PIC; 387 388 bool Promoted = false; 389 390 // Build an AST using MSSA. 391 if (!CurAST.get()) 392 CurAST = collectAliasInfoForLoopWithMSSA(L, AA, MSSAU.get()); 393 394 // Loop over all of the alias sets in the tracker object. 395 for (AliasSet &AS : *CurAST) { 396 // We can promote this alias set if it has a store, if it is a "Must" 397 // alias set, if the pointer is loop invariant, and if we are not 398 // eliminating any volatile loads or stores. 399 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() || 400 !L->isLoopInvariant(AS.begin()->getValue())) 401 continue; 402 403 assert( 404 !AS.empty() && 405 "Must alias set should have at least one pointer element in it!"); 406 407 SmallSetVector<Value *, 8> PointerMustAliases; 408 for (const auto &ASI : AS) 409 PointerMustAliases.insert(ASI.getValue()); 410 411 Promoted |= promoteLoopAccessesToScalars( 412 PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI, 413 DT, TLI, L, CurAST.get(), MSSAU.get(), &SafetyInfo, ORE); 414 } 415 416 // Once we have promoted values across the loop body we have to 417 // recursively reform LCSSA as any nested loop may now have values defined 418 // within the loop used in the outer loop. 419 // FIXME: This is really heavy handed. It would be a bit better to use an 420 // SSAUpdater strategy during promotion that was LCSSA aware and reformed 421 // it as it went. 422 if (Promoted) 423 formLCSSARecursively(*L, *DT, LI, SE); 424 425 Changed |= Promoted; 426 } 427 } 428 429 // Check that neither this loop nor its parent have had LCSSA broken. LICM is 430 // specifically moving instructions across the loop boundary and so it is 431 // especially in need of sanity checking here. 432 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!"); 433 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) && 434 "Parent loop not left in LCSSA form after LICM!"); 435 436 if (MSSAU.get() && VerifyMemorySSA) 437 MSSAU->getMemorySSA()->verifyMemorySSA(); 438 439 if (Changed && SE) 440 SE->forgetLoopDispositions(L); 441 return Changed; 442 } 443 444 /// Walk the specified region of the CFG (defined by all blocks dominated by 445 /// the specified block, and that are in the current loop) in reverse depth 446 /// first order w.r.t the DominatorTree. This allows us to visit uses before 447 /// definitions, allowing us to sink a loop body in one pass without iteration. 448 /// 449 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 450 DominatorTree *DT, TargetLibraryInfo *TLI, 451 TargetTransformInfo *TTI, Loop *CurLoop, 452 AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, 453 ICFLoopSafetyInfo *SafetyInfo, 454 SinkAndHoistLICMFlags &Flags, 455 OptimizationRemarkEmitter *ORE) { 456 457 // Verify inputs. 458 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && 459 CurLoop != nullptr && SafetyInfo != nullptr && 460 "Unexpected input to sinkRegion."); 461 assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) && 462 "Either AliasSetTracker or MemorySSA should be initialized."); 463 464 // We want to visit children before parents. We will enque all the parents 465 // before their children in the worklist and process the worklist in reverse 466 // order. 467 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop); 468 469 bool Changed = false; 470 for (DomTreeNode *DTN : reverse(Worklist)) { 471 BasicBlock *BB = DTN->getBlock(); 472 // Only need to process the contents of this block if it is not part of a 473 // subloop (which would already have been processed). 474 if (inSubLoop(BB, CurLoop, LI)) 475 continue; 476 477 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) { 478 Instruction &I = *--II; 479 480 // If the instruction is dead, we would try to sink it because it isn't 481 // used in the loop, instead, just delete it. 482 if (isInstructionTriviallyDead(&I, TLI)) { 483 LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n'); 484 salvageDebugInfo(I); 485 ++II; 486 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); 487 Changed = true; 488 continue; 489 } 490 491 // Check to see if we can sink this instruction to the exit blocks 492 // of the loop. We can do this if the all users of the instruction are 493 // outside of the loop. In this case, it doesn't even matter if the 494 // operands of the instruction are loop invariant. 495 // 496 bool FreeInLoop = false; 497 if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) && 498 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags, 499 ORE) && 500 !I.mayHaveSideEffects()) { 501 if (sink(I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE)) { 502 if (!FreeInLoop) { 503 ++II; 504 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); 505 } 506 Changed = true; 507 } 508 } 509 } 510 } 511 if (MSSAU && VerifyMemorySSA) 512 MSSAU->getMemorySSA()->verifyMemorySSA(); 513 return Changed; 514 } 515 516 namespace { 517 // This is a helper class for hoistRegion to make it able to hoist control flow 518 // in order to be able to hoist phis. The way this works is that we initially 519 // start hoisting to the loop preheader, and when we see a loop invariant branch 520 // we make note of this. When we then come to hoist an instruction that's 521 // conditional on such a branch we duplicate the branch and the relevant control 522 // flow, then hoist the instruction into the block corresponding to its original 523 // block in the duplicated control flow. 524 class ControlFlowHoister { 525 private: 526 // Information about the loop we are hoisting from 527 LoopInfo *LI; 528 DominatorTree *DT; 529 Loop *CurLoop; 530 MemorySSAUpdater *MSSAU; 531 532 // A map of blocks in the loop to the block their instructions will be hoisted 533 // to. 534 DenseMap<BasicBlock *, BasicBlock *> HoistDestinationMap; 535 536 // The branches that we can hoist, mapped to the block that marks a 537 // convergence point of their control flow. 538 DenseMap<BranchInst *, BasicBlock *> HoistableBranches; 539 540 public: 541 ControlFlowHoister(LoopInfo *LI, DominatorTree *DT, Loop *CurLoop, 542 MemorySSAUpdater *MSSAU) 543 : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {} 544 545 void registerPossiblyHoistableBranch(BranchInst *BI) { 546 // We can only hoist conditional branches with loop invariant operands. 547 if (!ControlFlowHoisting || !BI->isConditional() || 548 !CurLoop->hasLoopInvariantOperands(BI)) 549 return; 550 551 // The branch destinations need to be in the loop, and we don't gain 552 // anything by duplicating conditional branches with duplicate successors, 553 // as it's essentially the same as an unconditional branch. 554 BasicBlock *TrueDest = BI->getSuccessor(0); 555 BasicBlock *FalseDest = BI->getSuccessor(1); 556 if (!CurLoop->contains(TrueDest) || !CurLoop->contains(FalseDest) || 557 TrueDest == FalseDest) 558 return; 559 560 // We can hoist BI if one branch destination is the successor of the other, 561 // or both have common successor which we check by seeing if the 562 // intersection of their successors is non-empty. 563 // TODO: This could be expanded to allowing branches where both ends 564 // eventually converge to a single block. 565 SmallPtrSet<BasicBlock *, 4> TrueDestSucc, FalseDestSucc; 566 TrueDestSucc.insert(succ_begin(TrueDest), succ_end(TrueDest)); 567 FalseDestSucc.insert(succ_begin(FalseDest), succ_end(FalseDest)); 568 BasicBlock *CommonSucc = nullptr; 569 if (TrueDestSucc.count(FalseDest)) { 570 CommonSucc = FalseDest; 571 } else if (FalseDestSucc.count(TrueDest)) { 572 CommonSucc = TrueDest; 573 } else { 574 set_intersect(TrueDestSucc, FalseDestSucc); 575 // If there's one common successor use that. 576 if (TrueDestSucc.size() == 1) 577 CommonSucc = *TrueDestSucc.begin(); 578 // If there's more than one pick whichever appears first in the block list 579 // (we can't use the value returned by TrueDestSucc.begin() as it's 580 // unpredicatable which element gets returned). 581 else if (!TrueDestSucc.empty()) { 582 Function *F = TrueDest->getParent(); 583 auto IsSucc = [&](BasicBlock &BB) { return TrueDestSucc.count(&BB); }; 584 auto It = std::find_if(F->begin(), F->end(), IsSucc); 585 assert(It != F->end() && "Could not find successor in function"); 586 CommonSucc = &*It; 587 } 588 } 589 // The common successor has to be dominated by the branch, as otherwise 590 // there will be some other path to the successor that will not be 591 // controlled by this branch so any phi we hoist would be controlled by the 592 // wrong condition. This also takes care of avoiding hoisting of loop back 593 // edges. 594 // TODO: In some cases this could be relaxed if the successor is dominated 595 // by another block that's been hoisted and we can guarantee that the 596 // control flow has been replicated exactly. 597 if (CommonSucc && DT->dominates(BI, CommonSucc)) 598 HoistableBranches[BI] = CommonSucc; 599 } 600 601 bool canHoistPHI(PHINode *PN) { 602 // The phi must have loop invariant operands. 603 if (!ControlFlowHoisting || !CurLoop->hasLoopInvariantOperands(PN)) 604 return false; 605 // We can hoist phis if the block they are in is the target of hoistable 606 // branches which cover all of the predecessors of the block. 607 SmallPtrSet<BasicBlock *, 8> PredecessorBlocks; 608 BasicBlock *BB = PN->getParent(); 609 for (BasicBlock *PredBB : predecessors(BB)) 610 PredecessorBlocks.insert(PredBB); 611 // If we have less predecessor blocks than predecessors then the phi will 612 // have more than one incoming value for the same block which we can't 613 // handle. 614 // TODO: This could be handled be erasing some of the duplicate incoming 615 // values. 616 if (PredecessorBlocks.size() != pred_size(BB)) 617 return false; 618 for (auto &Pair : HoistableBranches) { 619 if (Pair.second == BB) { 620 // Which blocks are predecessors via this branch depends on if the 621 // branch is triangle-like or diamond-like. 622 if (Pair.first->getSuccessor(0) == BB) { 623 PredecessorBlocks.erase(Pair.first->getParent()); 624 PredecessorBlocks.erase(Pair.first->getSuccessor(1)); 625 } else if (Pair.first->getSuccessor(1) == BB) { 626 PredecessorBlocks.erase(Pair.first->getParent()); 627 PredecessorBlocks.erase(Pair.first->getSuccessor(0)); 628 } else { 629 PredecessorBlocks.erase(Pair.first->getSuccessor(0)); 630 PredecessorBlocks.erase(Pair.first->getSuccessor(1)); 631 } 632 } 633 } 634 // PredecessorBlocks will now be empty if for every predecessor of BB we 635 // found a hoistable branch source. 636 return PredecessorBlocks.empty(); 637 } 638 639 BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) { 640 if (!ControlFlowHoisting) 641 return CurLoop->getLoopPreheader(); 642 // If BB has already been hoisted, return that 643 if (HoistDestinationMap.count(BB)) 644 return HoistDestinationMap[BB]; 645 646 // Check if this block is conditional based on a pending branch 647 auto HasBBAsSuccessor = 648 [&](DenseMap<BranchInst *, BasicBlock *>::value_type &Pair) { 649 return BB != Pair.second && (Pair.first->getSuccessor(0) == BB || 650 Pair.first->getSuccessor(1) == BB); 651 }; 652 auto It = std::find_if(HoistableBranches.begin(), HoistableBranches.end(), 653 HasBBAsSuccessor); 654 655 // If not involved in a pending branch, hoist to preheader 656 BasicBlock *InitialPreheader = CurLoop->getLoopPreheader(); 657 if (It == HoistableBranches.end()) { 658 LLVM_DEBUG(dbgs() << "LICM using " << InitialPreheader->getName() 659 << " as hoist destination for " << BB->getName() 660 << "\n"); 661 HoistDestinationMap[BB] = InitialPreheader; 662 return InitialPreheader; 663 } 664 BranchInst *BI = It->first; 665 assert(std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) == 666 HoistableBranches.end() && 667 "BB is expected to be the target of at most one branch"); 668 669 LLVMContext &C = BB->getContext(); 670 BasicBlock *TrueDest = BI->getSuccessor(0); 671 BasicBlock *FalseDest = BI->getSuccessor(1); 672 BasicBlock *CommonSucc = HoistableBranches[BI]; 673 BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent()); 674 675 // Create hoisted versions of blocks that currently don't have them 676 auto CreateHoistedBlock = [&](BasicBlock *Orig) { 677 if (HoistDestinationMap.count(Orig)) 678 return HoistDestinationMap[Orig]; 679 BasicBlock *New = 680 BasicBlock::Create(C, Orig->getName() + ".licm", Orig->getParent()); 681 HoistDestinationMap[Orig] = New; 682 DT->addNewBlock(New, HoistTarget); 683 if (CurLoop->getParentLoop()) 684 CurLoop->getParentLoop()->addBasicBlockToLoop(New, *LI); 685 ++NumCreatedBlocks; 686 LLVM_DEBUG(dbgs() << "LICM created " << New->getName() 687 << " as hoist destination for " << Orig->getName() 688 << "\n"); 689 return New; 690 }; 691 BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest); 692 BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest); 693 BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc); 694 695 // Link up these blocks with branches. 696 if (!HoistCommonSucc->getTerminator()) { 697 // The new common successor we've generated will branch to whatever that 698 // hoist target branched to. 699 BasicBlock *TargetSucc = HoistTarget->getSingleSuccessor(); 700 assert(TargetSucc && "Expected hoist target to have a single successor"); 701 HoistCommonSucc->moveBefore(TargetSucc); 702 BranchInst::Create(TargetSucc, HoistCommonSucc); 703 } 704 if (!HoistTrueDest->getTerminator()) { 705 HoistTrueDest->moveBefore(HoistCommonSucc); 706 BranchInst::Create(HoistCommonSucc, HoistTrueDest); 707 } 708 if (!HoistFalseDest->getTerminator()) { 709 HoistFalseDest->moveBefore(HoistCommonSucc); 710 BranchInst::Create(HoistCommonSucc, HoistFalseDest); 711 } 712 713 // If BI is being cloned to what was originally the preheader then 714 // HoistCommonSucc will now be the new preheader. 715 if (HoistTarget == InitialPreheader) { 716 // Phis in the loop header now need to use the new preheader. 717 InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc); 718 if (MSSAU) 719 MSSAU->wireOldPredecessorsToNewImmediatePredecessor( 720 HoistTarget->getSingleSuccessor(), HoistCommonSucc, {HoistTarget}); 721 // The new preheader dominates the loop header. 722 DomTreeNode *PreheaderNode = DT->getNode(HoistCommonSucc); 723 DomTreeNode *HeaderNode = DT->getNode(CurLoop->getHeader()); 724 DT->changeImmediateDominator(HeaderNode, PreheaderNode); 725 // The preheader hoist destination is now the new preheader, with the 726 // exception of the hoist destination of this branch. 727 for (auto &Pair : HoistDestinationMap) 728 if (Pair.second == InitialPreheader && Pair.first != BI->getParent()) 729 Pair.second = HoistCommonSucc; 730 } 731 732 // Now finally clone BI. 733 ReplaceInstWithInst( 734 HoistTarget->getTerminator(), 735 BranchInst::Create(HoistTrueDest, HoistFalseDest, BI->getCondition())); 736 ++NumClonedBranches; 737 738 assert(CurLoop->getLoopPreheader() && 739 "Hoisting blocks should not have destroyed preheader"); 740 return HoistDestinationMap[BB]; 741 } 742 }; 743 } // namespace 744 745 746 /// Return true if we know how to rewrite all uses of the given alloca after 747 /// hoisting it out of the loop. The main concerns are a) potential captures 748 /// and b) invariant.start markers which don't capture, but are no longer 749 /// valid w/o a corresponding invariant.end. 750 static bool canRewriteUsesOfAlloca(AllocaInst &AI) { 751 // TODO: This looks a lot like capture tracking, but we need to remove any 752 // invariant starts if we extend the lifetime of the alloca by hoisting it. 753 // We should probably refactor capture tracking into a form which allows us 754 // to reuse the relevant bits and remove the duplicated logic here. 755 756 SmallVector<Use *, 16> Worklist; 757 for (Use &U : AI.uses()) 758 Worklist.push_back(&U); 759 760 unsigned NumUsesExplored = 0; 761 while (!Worklist.empty()) { 762 Use *U = Worklist.pop_back_val(); 763 Instruction *I = cast<Instruction>(U->getUser()); 764 NumUsesExplored++; 765 if (NumUsesExplored > DefaultMaxUsesToExplore) 766 return false; 767 // Non capturing, terminating uses 768 if (isa<LoadInst>(I) || 769 (isa<StoreInst>(I) && U->getOperandNo() == 1)) 770 continue; 771 // Non capturing, non-terminating 772 if (!isa<BitCastInst>(I) && !isa<GetElementPtrInst>(I)) 773 return false; 774 for (Use &U : I->uses()) 775 Worklist.push_back(&U); 776 } 777 return true; 778 } 779 780 /// Walk the specified region of the CFG (defined by all blocks dominated by 781 /// the specified block, and that are in the current loop) in depth first 782 /// order w.r.t the DominatorTree. This allows us to visit definitions before 783 /// uses, allowing us to hoist a loop body in one pass without iteration. 784 /// 785 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 786 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, 787 AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, 788 ScalarEvolution *SE, ICFLoopSafetyInfo *SafetyInfo, 789 SinkAndHoistLICMFlags &Flags, 790 OptimizationRemarkEmitter *ORE) { 791 // Verify inputs. 792 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && 793 CurLoop != nullptr && SafetyInfo != nullptr && 794 "Unexpected input to hoistRegion."); 795 assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) && 796 "Either AliasSetTracker or MemorySSA should be initialized."); 797 798 ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU); 799 800 // Keep track of instructions that have been hoisted, as they may need to be 801 // re-hoisted if they end up not dominating all of their uses. 802 SmallVector<Instruction *, 16> HoistedInstructions; 803 804 // For PHI hoisting to work we need to hoist blocks before their successors. 805 // We can do this by iterating through the blocks in the loop in reverse 806 // post-order. 807 LoopBlocksRPO Worklist(CurLoop); 808 Worklist.perform(LI); 809 bool Changed = false; 810 for (BasicBlock *BB : Worklist) { 811 // Only need to process the contents of this block if it is not part of a 812 // subloop (which would already have been processed). 813 if (inSubLoop(BB, CurLoop, LI)) 814 continue; 815 816 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) { 817 Instruction &I = *II++; 818 // Try constant folding this instruction. If all the operands are 819 // constants, it is technically hoistable, but it would be better to 820 // just fold it. 821 if (Constant *C = ConstantFoldInstruction( 822 &I, I.getModule()->getDataLayout(), TLI)) { 823 LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C 824 << '\n'); 825 if (CurAST) 826 CurAST->copyValue(&I, C); 827 // FIXME MSSA: Such replacements may make accesses unoptimized (D51960). 828 I.replaceAllUsesWith(C); 829 if (isInstructionTriviallyDead(&I, TLI)) 830 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); 831 Changed = true; 832 continue; 833 } 834 835 // Try hoisting the instruction out to the preheader. We can only do 836 // this if all of the operands of the instruction are loop invariant and 837 // if it is safe to hoist the instruction. 838 // TODO: It may be safe to hoist if we are hoisting to a conditional block 839 // and we have accurately duplicated the control flow from the loop header 840 // to that block. 841 if (CurLoop->hasLoopInvariantOperands(&I) && 842 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags, 843 ORE) && 844 isSafeToExecuteUnconditionally( 845 I, DT, CurLoop, SafetyInfo, ORE, 846 CurLoop->getLoopPreheader()->getTerminator())) { 847 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, 848 MSSAU, SE, ORE); 849 HoistedInstructions.push_back(&I); 850 Changed = true; 851 continue; 852 } 853 854 // Attempt to remove floating point division out of the loop by 855 // converting it to a reciprocal multiplication. 856 if (I.getOpcode() == Instruction::FDiv && 857 CurLoop->isLoopInvariant(I.getOperand(1)) && 858 I.hasAllowReciprocal()) { 859 auto Divisor = I.getOperand(1); 860 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0); 861 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor); 862 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags()); 863 SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent()); 864 ReciprocalDivisor->insertBefore(&I); 865 866 auto Product = 867 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor); 868 Product->setFastMathFlags(I.getFastMathFlags()); 869 SafetyInfo->insertInstructionTo(Product, I.getParent()); 870 Product->insertAfter(&I); 871 I.replaceAllUsesWith(Product); 872 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); 873 874 hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), 875 SafetyInfo, MSSAU, SE, ORE); 876 HoistedInstructions.push_back(ReciprocalDivisor); 877 Changed = true; 878 continue; 879 } 880 881 auto IsInvariantStart = [&](Instruction &I) { 882 using namespace PatternMatch; 883 return I.use_empty() && 884 match(&I, m_Intrinsic<Intrinsic::invariant_start>()); 885 }; 886 auto MustExecuteWithoutWritesBefore = [&](Instruction &I) { 887 return SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) && 888 SafetyInfo->doesNotWriteMemoryBefore(I, CurLoop); 889 }; 890 if ((IsInvariantStart(I) || isGuard(&I)) && 891 CurLoop->hasLoopInvariantOperands(&I) && 892 MustExecuteWithoutWritesBefore(I)) { 893 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, 894 MSSAU, SE, ORE); 895 HoistedInstructions.push_back(&I); 896 Changed = true; 897 continue; 898 } 899 900 if (isa<AllocaInst>(&I) && 901 SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) && 902 canRewriteUsesOfAlloca(cast<AllocaInst>(I))) { 903 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, 904 MSSAU, SE, ORE); 905 HoistedInstructions.push_back(&I); 906 Changed = true; 907 continue; 908 } 909 910 if (PHINode *PN = dyn_cast<PHINode>(&I)) { 911 if (CFH.canHoistPHI(PN)) { 912 // Redirect incoming blocks first to ensure that we create hoisted 913 // versions of those blocks before we hoist the phi. 914 for (unsigned int i = 0; i < PN->getNumIncomingValues(); ++i) 915 PN->setIncomingBlock( 916 i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i))); 917 hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, 918 MSSAU, SE, ORE); 919 assert(DT->dominates(PN, BB) && "Conditional PHIs not expected"); 920 Changed = true; 921 continue; 922 } 923 } 924 925 // Remember possibly hoistable branches so we can actually hoist them 926 // later if needed. 927 if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 928 CFH.registerPossiblyHoistableBranch(BI); 929 } 930 } 931 932 // If we hoisted instructions to a conditional block they may not dominate 933 // their uses that weren't hoisted (such as phis where some operands are not 934 // loop invariant). If so make them unconditional by moving them to their 935 // immediate dominator. We iterate through the instructions in reverse order 936 // which ensures that when we rehoist an instruction we rehoist its operands, 937 // and also keep track of where in the block we are rehoisting to to make sure 938 // that we rehoist instructions before the instructions that use them. 939 Instruction *HoistPoint = nullptr; 940 if (ControlFlowHoisting) { 941 for (Instruction *I : reverse(HoistedInstructions)) { 942 if (!llvm::all_of(I->uses(), 943 [&](Use &U) { return DT->dominates(I, U); })) { 944 BasicBlock *Dominator = 945 DT->getNode(I->getParent())->getIDom()->getBlock(); 946 if (!HoistPoint || !DT->dominates(HoistPoint->getParent(), Dominator)) { 947 if (HoistPoint) 948 assert(DT->dominates(Dominator, HoistPoint->getParent()) && 949 "New hoist point expected to dominate old hoist point"); 950 HoistPoint = Dominator->getTerminator(); 951 } 952 LLVM_DEBUG(dbgs() << "LICM rehoisting to " 953 << HoistPoint->getParent()->getName() 954 << ": " << *I << "\n"); 955 moveInstructionBefore(*I, *HoistPoint, *SafetyInfo, MSSAU, SE); 956 HoistPoint = I; 957 Changed = true; 958 } 959 } 960 } 961 if (MSSAU && VerifyMemorySSA) 962 MSSAU->getMemorySSA()->verifyMemorySSA(); 963 964 // Now that we've finished hoisting make sure that LI and DT are still 965 // valid. 966 #ifdef EXPENSIVE_CHECKS 967 if (Changed) { 968 assert(DT->verify(DominatorTree::VerificationLevel::Fast) && 969 "Dominator tree verification failed"); 970 LI->verify(*DT); 971 } 972 #endif 973 974 return Changed; 975 } 976 977 // Return true if LI is invariant within scope of the loop. LI is invariant if 978 // CurLoop is dominated by an invariant.start representing the same memory 979 // location and size as the memory location LI loads from, and also the 980 // invariant.start has no uses. 981 static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, 982 Loop *CurLoop) { 983 Value *Addr = LI->getOperand(0); 984 const DataLayout &DL = LI->getModule()->getDataLayout(); 985 const uint32_t LocSizeInBits = DL.getTypeSizeInBits(LI->getType()); 986 987 // if the type is i8 addrspace(x)*, we know this is the type of 988 // llvm.invariant.start operand 989 auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()), 990 LI->getPointerAddressSpace()); 991 unsigned BitcastsVisited = 0; 992 // Look through bitcasts until we reach the i8* type (this is invariant.start 993 // operand type). 994 while (Addr->getType() != PtrInt8Ty) { 995 auto *BC = dyn_cast<BitCastInst>(Addr); 996 // Avoid traversing high number of bitcast uses. 997 if (++BitcastsVisited > MaxNumUsesTraversed || !BC) 998 return false; 999 Addr = BC->getOperand(0); 1000 } 1001 1002 unsigned UsesVisited = 0; 1003 // Traverse all uses of the load operand value, to see if invariant.start is 1004 // one of the uses, and whether it dominates the load instruction. 1005 for (auto *U : Addr->users()) { 1006 // Avoid traversing for Load operand with high number of users. 1007 if (++UsesVisited > MaxNumUsesTraversed) 1008 return false; 1009 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); 1010 // If there are escaping uses of invariant.start instruction, the load maybe 1011 // non-invariant. 1012 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start || 1013 !II->use_empty()) 1014 continue; 1015 unsigned InvariantSizeInBits = 1016 cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8; 1017 // Confirm the invariant.start location size contains the load operand size 1018 // in bits. Also, the invariant.start should dominate the load, and we 1019 // should not hoist the load out of a loop that contains this dominating 1020 // invariant.start. 1021 if (LocSizeInBits <= InvariantSizeInBits && 1022 DT->properlyDominates(II->getParent(), CurLoop->getHeader())) 1023 return true; 1024 } 1025 1026 return false; 1027 } 1028 1029 namespace { 1030 /// Return true if-and-only-if we know how to (mechanically) both hoist and 1031 /// sink a given instruction out of a loop. Does not address legality 1032 /// concerns such as aliasing or speculation safety. 1033 bool isHoistableAndSinkableInst(Instruction &I) { 1034 // Only these instructions are hoistable/sinkable. 1035 return (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) || 1036 isa<FenceInst>(I) || isa<CastInst>(I) || 1037 isa<UnaryOperator>(I) || isa<BinaryOperator>(I) || 1038 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) || 1039 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) || 1040 isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) || 1041 isa<InsertValueInst>(I)); 1042 } 1043 /// Return true if all of the alias sets within this AST are known not to 1044 /// contain a Mod, or if MSSA knows thare are no MemoryDefs in the loop. 1045 bool isReadOnly(AliasSetTracker *CurAST, const MemorySSAUpdater *MSSAU, 1046 const Loop *L) { 1047 if (CurAST) { 1048 for (AliasSet &AS : *CurAST) { 1049 if (!AS.isForwardingAliasSet() && AS.isMod()) { 1050 return false; 1051 } 1052 } 1053 return true; 1054 } else { /*MSSAU*/ 1055 for (auto *BB : L->getBlocks()) 1056 if (MSSAU->getMemorySSA()->getBlockDefs(BB)) 1057 return false; 1058 return true; 1059 } 1060 } 1061 1062 /// Return true if I is the only Instruction with a MemoryAccess in L. 1063 bool isOnlyMemoryAccess(const Instruction *I, const Loop *L, 1064 const MemorySSAUpdater *MSSAU) { 1065 for (auto *BB : L->getBlocks()) 1066 if (auto *Accs = MSSAU->getMemorySSA()->getBlockAccesses(BB)) { 1067 int NotAPhi = 0; 1068 for (const auto &Acc : *Accs) { 1069 if (isa<MemoryPhi>(&Acc)) 1070 continue; 1071 const auto *MUD = cast<MemoryUseOrDef>(&Acc); 1072 if (MUD->getMemoryInst() != I || NotAPhi++ == 1) 1073 return false; 1074 } 1075 } 1076 return true; 1077 } 1078 } 1079 1080 bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, 1081 Loop *CurLoop, AliasSetTracker *CurAST, 1082 MemorySSAUpdater *MSSAU, 1083 bool TargetExecutesOncePerLoop, 1084 SinkAndHoistLICMFlags *Flags, 1085 OptimizationRemarkEmitter *ORE) { 1086 // If we don't understand the instruction, bail early. 1087 if (!isHoistableAndSinkableInst(I)) 1088 return false; 1089 1090 MemorySSA *MSSA = MSSAU ? MSSAU->getMemorySSA() : nullptr; 1091 if (MSSA) 1092 assert(Flags != nullptr && "Flags cannot be null."); 1093 1094 // Loads have extra constraints we have to verify before we can hoist them. 1095 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 1096 if (!LI->isUnordered()) 1097 return false; // Don't sink/hoist volatile or ordered atomic loads! 1098 1099 // Loads from constant memory are always safe to move, even if they end up 1100 // in the same alias set as something that ends up being modified. 1101 if (AA->pointsToConstantMemory(LI->getOperand(0))) 1102 return true; 1103 if (LI->hasMetadata(LLVMContext::MD_invariant_load)) 1104 return true; 1105 1106 if (LI->isAtomic() && !TargetExecutesOncePerLoop) 1107 return false; // Don't risk duplicating unordered loads 1108 1109 // This checks for an invariant.start dominating the load. 1110 if (isLoadInvariantInLoop(LI, DT, CurLoop)) 1111 return true; 1112 1113 bool Invalidated; 1114 if (CurAST) 1115 Invalidated = pointerInvalidatedByLoop(MemoryLocation::get(LI), CurAST, 1116 CurLoop, AA); 1117 else 1118 Invalidated = pointerInvalidatedByLoopWithMSSA( 1119 MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(LI)), CurLoop, *Flags); 1120 // Check loop-invariant address because this may also be a sinkable load 1121 // whose address is not necessarily loop-invariant. 1122 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand())) 1123 ORE->emit([&]() { 1124 return OptimizationRemarkMissed( 1125 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI) 1126 << "failed to move load with loop-invariant address " 1127 "because the loop may invalidate its value"; 1128 }); 1129 1130 return !Invalidated; 1131 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) { 1132 // Don't sink or hoist dbg info; it's legal, but not useful. 1133 if (isa<DbgInfoIntrinsic>(I)) 1134 return false; 1135 1136 // Don't sink calls which can throw. 1137 if (CI->mayThrow()) 1138 return false; 1139 1140 using namespace PatternMatch; 1141 if (match(CI, m_Intrinsic<Intrinsic::assume>())) 1142 // Assumes don't actually alias anything or throw 1143 return true; 1144 1145 if (match(CI, m_Intrinsic<Intrinsic::experimental_widenable_condition>())) 1146 // Widenable conditions don't actually alias anything or throw 1147 return true; 1148 1149 // Handle simple cases by querying alias analysis. 1150 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI); 1151 if (Behavior == FMRB_DoesNotAccessMemory) 1152 return true; 1153 if (AliasAnalysis::onlyReadsMemory(Behavior)) { 1154 // A readonly argmemonly function only reads from memory pointed to by 1155 // it's arguments with arbitrary offsets. If we can prove there are no 1156 // writes to this memory in the loop, we can hoist or sink. 1157 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) { 1158 // TODO: expand to writeable arguments 1159 for (Value *Op : CI->arg_operands()) 1160 if (Op->getType()->isPointerTy()) { 1161 bool Invalidated; 1162 if (CurAST) 1163 Invalidated = pointerInvalidatedByLoop( 1164 MemoryLocation(Op, LocationSize::unknown(), AAMDNodes()), 1165 CurAST, CurLoop, AA); 1166 else 1167 Invalidated = pointerInvalidatedByLoopWithMSSA( 1168 MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(CI)), CurLoop, 1169 *Flags); 1170 if (Invalidated) 1171 return false; 1172 } 1173 return true; 1174 } 1175 1176 // If this call only reads from memory and there are no writes to memory 1177 // in the loop, we can hoist or sink the call as appropriate. 1178 if (isReadOnly(CurAST, MSSAU, CurLoop)) 1179 return true; 1180 } 1181 1182 // FIXME: This should use mod/ref information to see if we can hoist or 1183 // sink the call. 1184 1185 return false; 1186 } else if (auto *FI = dyn_cast<FenceInst>(&I)) { 1187 // Fences alias (most) everything to provide ordering. For the moment, 1188 // just give up if there are any other memory operations in the loop. 1189 if (CurAST) { 1190 auto Begin = CurAST->begin(); 1191 assert(Begin != CurAST->end() && "must contain FI"); 1192 if (std::next(Begin) != CurAST->end()) 1193 // constant memory for instance, TODO: handle better 1194 return false; 1195 auto *UniqueI = Begin->getUniqueInstruction(); 1196 if (!UniqueI) 1197 // other memory op, give up 1198 return false; 1199 (void)FI; // suppress unused variable warning 1200 assert(UniqueI == FI && "AS must contain FI"); 1201 return true; 1202 } else // MSSAU 1203 return isOnlyMemoryAccess(FI, CurLoop, MSSAU); 1204 } else if (auto *SI = dyn_cast<StoreInst>(&I)) { 1205 if (!SI->isUnordered()) 1206 return false; // Don't sink/hoist volatile or ordered atomic store! 1207 1208 // We can only hoist a store that we can prove writes a value which is not 1209 // read or overwritten within the loop. For those cases, we fallback to 1210 // load store promotion instead. TODO: We can extend this to cases where 1211 // there is exactly one write to the location and that write dominates an 1212 // arbitrary number of reads in the loop. 1213 if (CurAST) { 1214 auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI)); 1215 1216 if (AS.isRef() || !AS.isMustAlias()) 1217 // Quick exit test, handled by the full path below as well. 1218 return false; 1219 auto *UniqueI = AS.getUniqueInstruction(); 1220 if (!UniqueI) 1221 // other memory op, give up 1222 return false; 1223 assert(UniqueI == SI && "AS must contain SI"); 1224 return true; 1225 } else { // MSSAU 1226 if (isOnlyMemoryAccess(SI, CurLoop, MSSAU)) 1227 return true; 1228 // If there are more accesses than the Promotion cap, give up, we're not 1229 // walking a list that long. 1230 if (Flags->NoOfMemAccTooLarge) 1231 return false; 1232 // Check store only if there's still "quota" to check clobber. 1233 if (Flags->LicmMssaOptCounter >= Flags->LicmMssaOptCap) 1234 return false; 1235 // If there are interfering Uses (i.e. their defining access is in the 1236 // loop), or ordered loads (stored as Defs!), don't move this store. 1237 // Could do better here, but this is conservatively correct. 1238 // TODO: Cache set of Uses on the first walk in runOnLoop, update when 1239 // moving accesses. Can also extend to dominating uses. 1240 auto *SIMD = MSSA->getMemoryAccess(SI); 1241 for (auto *BB : CurLoop->getBlocks()) 1242 if (auto *Accesses = MSSA->getBlockAccesses(BB)) { 1243 for (const auto &MA : *Accesses) 1244 if (const auto *MU = dyn_cast<MemoryUse>(&MA)) { 1245 auto *MD = MU->getDefiningAccess(); 1246 if (!MSSA->isLiveOnEntryDef(MD) && 1247 CurLoop->contains(MD->getBlock())) 1248 return false; 1249 // Disable hoisting past potentially interfering loads. Optimized 1250 // Uses may point to an access outside the loop, as getClobbering 1251 // checks the previous iteration when walking the backedge. 1252 // FIXME: More precise: no Uses that alias SI. 1253 if (!Flags->IsSink && !MSSA->dominates(SIMD, MU)) 1254 return false; 1255 } else if (const auto *MD = dyn_cast<MemoryDef>(&MA)) { 1256 if (auto *LI = dyn_cast<LoadInst>(MD->getMemoryInst())) { 1257 (void)LI; // Silence warning. 1258 assert(!LI->isUnordered() && "Expected unordered load"); 1259 return false; 1260 } 1261 // Any call, while it may not be clobbering SI, it may be a use. 1262 if (auto *CI = dyn_cast<CallInst>(MD->getMemoryInst())) { 1263 // Check if the call may read from the memory locattion written 1264 // to by SI. Check CI's attributes and arguments; the number of 1265 // such checks performed is limited above by NoOfMemAccTooLarge. 1266 ModRefInfo MRI = AA->getModRefInfo(CI, MemoryLocation::get(SI)); 1267 if (isModOrRefSet(MRI)) 1268 return false; 1269 } 1270 } 1271 } 1272 1273 auto *Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(SI); 1274 Flags->LicmMssaOptCounter++; 1275 // If there are no clobbering Defs in the loop, store is safe to hoist. 1276 return MSSA->isLiveOnEntryDef(Source) || 1277 !CurLoop->contains(Source->getBlock()); 1278 } 1279 } 1280 1281 assert(!I.mayReadOrWriteMemory() && "unhandled aliasing"); 1282 1283 // We've established mechanical ability and aliasing, it's up to the caller 1284 // to check fault safety 1285 return true; 1286 } 1287 1288 /// Returns true if a PHINode is a trivially replaceable with an 1289 /// Instruction. 1290 /// This is true when all incoming values are that instruction. 1291 /// This pattern occurs most often with LCSSA PHI nodes. 1292 /// 1293 static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) { 1294 for (const Value *IncValue : PN.incoming_values()) 1295 if (IncValue != &I) 1296 return false; 1297 1298 return true; 1299 } 1300 1301 /// Return true if the instruction is free in the loop. 1302 static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop, 1303 const TargetTransformInfo *TTI) { 1304 1305 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) { 1306 if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free) 1307 return false; 1308 // For a GEP, we cannot simply use getUserCost because currently it 1309 // optimistically assume that a GEP will fold into addressing mode 1310 // regardless of its users. 1311 const BasicBlock *BB = GEP->getParent(); 1312 for (const User *U : GEP->users()) { 1313 const Instruction *UI = cast<Instruction>(U); 1314 if (CurLoop->contains(UI) && 1315 (BB != UI->getParent() || 1316 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI)))) 1317 return false; 1318 } 1319 return true; 1320 } else 1321 return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free; 1322 } 1323 1324 /// Return true if the only users of this instruction are outside of 1325 /// the loop. If this is true, we can sink the instruction to the exit 1326 /// blocks of the loop. 1327 /// 1328 /// We also return true if the instruction could be folded away in lowering. 1329 /// (e.g., a GEP can be folded into a load as an addressing mode in the loop). 1330 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, 1331 const LoopSafetyInfo *SafetyInfo, 1332 TargetTransformInfo *TTI, bool &FreeInLoop) { 1333 const auto &BlockColors = SafetyInfo->getBlockColors(); 1334 bool IsFree = isFreeInLoop(I, CurLoop, TTI); 1335 for (const User *U : I.users()) { 1336 const Instruction *UI = cast<Instruction>(U); 1337 if (const PHINode *PN = dyn_cast<PHINode>(UI)) { 1338 const BasicBlock *BB = PN->getParent(); 1339 // We cannot sink uses in catchswitches. 1340 if (isa<CatchSwitchInst>(BB->getTerminator())) 1341 return false; 1342 1343 // We need to sink a callsite to a unique funclet. Avoid sinking if the 1344 // phi use is too muddled. 1345 if (isa<CallInst>(I)) 1346 if (!BlockColors.empty() && 1347 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1) 1348 return false; 1349 } 1350 1351 if (CurLoop->contains(UI)) { 1352 if (IsFree) { 1353 FreeInLoop = true; 1354 continue; 1355 } 1356 return false; 1357 } 1358 } 1359 return true; 1360 } 1361 1362 static Instruction *cloneInstructionInExitBlock( 1363 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, 1364 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU) { 1365 Instruction *New; 1366 if (auto *CI = dyn_cast<CallInst>(&I)) { 1367 const auto &BlockColors = SafetyInfo->getBlockColors(); 1368 1369 // Sinking call-sites need to be handled differently from other 1370 // instructions. The cloned call-site needs a funclet bundle operand 1371 // appropriate for its location in the CFG. 1372 SmallVector<OperandBundleDef, 1> OpBundles; 1373 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles(); 1374 BundleIdx != BundleEnd; ++BundleIdx) { 1375 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx); 1376 if (Bundle.getTagID() == LLVMContext::OB_funclet) 1377 continue; 1378 1379 OpBundles.emplace_back(Bundle); 1380 } 1381 1382 if (!BlockColors.empty()) { 1383 const ColorVector &CV = BlockColors.find(&ExitBlock)->second; 1384 assert(CV.size() == 1 && "non-unique color for exit block!"); 1385 BasicBlock *BBColor = CV.front(); 1386 Instruction *EHPad = BBColor->getFirstNonPHI(); 1387 if (EHPad->isEHPad()) 1388 OpBundles.emplace_back("funclet", EHPad); 1389 } 1390 1391 New = CallInst::Create(CI, OpBundles); 1392 } else { 1393 New = I.clone(); 1394 } 1395 1396 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New); 1397 if (!I.getName().empty()) 1398 New->setName(I.getName() + ".le"); 1399 1400 if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(&I)) { 1401 // Create a new MemoryAccess and let MemorySSA set its defining access. 1402 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( 1403 New, nullptr, New->getParent(), MemorySSA::Beginning); 1404 if (NewMemAcc) { 1405 if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc)) 1406 MSSAU->insertDef(MemDef, /*RenameUses=*/true); 1407 else { 1408 auto *MemUse = cast<MemoryUse>(NewMemAcc); 1409 MSSAU->insertUse(MemUse, /*RenameUses=*/true); 1410 } 1411 } 1412 } 1413 1414 // Build LCSSA PHI nodes for any in-loop operands. Note that this is 1415 // particularly cheap because we can rip off the PHI node that we're 1416 // replacing for the number and blocks of the predecessors. 1417 // OPT: If this shows up in a profile, we can instead finish sinking all 1418 // invariant instructions, and then walk their operands to re-establish 1419 // LCSSA. That will eliminate creating PHI nodes just to nuke them when 1420 // sinking bottom-up. 1421 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE; 1422 ++OI) 1423 if (Instruction *OInst = dyn_cast<Instruction>(*OI)) 1424 if (Loop *OLoop = LI->getLoopFor(OInst->getParent())) 1425 if (!OLoop->contains(&PN)) { 1426 PHINode *OpPN = 1427 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(), 1428 OInst->getName() + ".lcssa", &ExitBlock.front()); 1429 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) 1430 OpPN->addIncoming(OInst, PN.getIncomingBlock(i)); 1431 *OI = OpPN; 1432 } 1433 return New; 1434 } 1435 1436 static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, 1437 AliasSetTracker *AST, MemorySSAUpdater *MSSAU) { 1438 if (AST) 1439 AST->deleteValue(&I); 1440 if (MSSAU) 1441 MSSAU->removeMemoryAccess(&I); 1442 SafetyInfo.removeInstruction(&I); 1443 I.eraseFromParent(); 1444 } 1445 1446 static void moveInstructionBefore(Instruction &I, Instruction &Dest, 1447 ICFLoopSafetyInfo &SafetyInfo, 1448 MemorySSAUpdater *MSSAU, 1449 ScalarEvolution *SE) { 1450 SafetyInfo.removeInstruction(&I); 1451 SafetyInfo.insertInstructionTo(&I, Dest.getParent()); 1452 I.moveBefore(&Dest); 1453 if (MSSAU) 1454 if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>( 1455 MSSAU->getMemorySSA()->getMemoryAccess(&I))) 1456 MSSAU->moveToPlace(OldMemAcc, Dest.getParent(), 1457 MemorySSA::BeforeTerminator); 1458 if (SE) 1459 SE->forgetValue(&I); 1460 } 1461 1462 static Instruction *sinkThroughTriviallyReplaceablePHI( 1463 PHINode *TPN, Instruction *I, LoopInfo *LI, 1464 SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies, 1465 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop, 1466 MemorySSAUpdater *MSSAU) { 1467 assert(isTriviallyReplaceablePHI(*TPN, *I) && 1468 "Expect only trivially replaceable PHI"); 1469 BasicBlock *ExitBlock = TPN->getParent(); 1470 Instruction *New; 1471 auto It = SunkCopies.find(ExitBlock); 1472 if (It != SunkCopies.end()) 1473 New = It->second; 1474 else 1475 New = SunkCopies[ExitBlock] = cloneInstructionInExitBlock( 1476 *I, *ExitBlock, *TPN, LI, SafetyInfo, MSSAU); 1477 return New; 1478 } 1479 1480 static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) { 1481 BasicBlock *BB = PN->getParent(); 1482 if (!BB->canSplitPredecessors()) 1483 return false; 1484 // It's not impossible to split EHPad blocks, but if BlockColors already exist 1485 // it require updating BlockColors for all offspring blocks accordingly. By 1486 // skipping such corner case, we can make updating BlockColors after splitting 1487 // predecessor fairly simple. 1488 if (!SafetyInfo->getBlockColors().empty() && BB->getFirstNonPHI()->isEHPad()) 1489 return false; 1490 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 1491 BasicBlock *BBPred = *PI; 1492 if (isa<IndirectBrInst>(BBPred->getTerminator())) 1493 return false; 1494 } 1495 return true; 1496 } 1497 1498 static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, 1499 LoopInfo *LI, const Loop *CurLoop, 1500 LoopSafetyInfo *SafetyInfo, 1501 MemorySSAUpdater *MSSAU) { 1502 #ifndef NDEBUG 1503 SmallVector<BasicBlock *, 32> ExitBlocks; 1504 CurLoop->getUniqueExitBlocks(ExitBlocks); 1505 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), 1506 ExitBlocks.end()); 1507 #endif 1508 BasicBlock *ExitBB = PN->getParent(); 1509 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block."); 1510 1511 // Split predecessors of the loop exit to make instructions in the loop are 1512 // exposed to exit blocks through trivially replaceable PHIs while keeping the 1513 // loop in the canonical form where each predecessor of each exit block should 1514 // be contained within the loop. For example, this will convert the loop below 1515 // from 1516 // 1517 // LB1: 1518 // %v1 = 1519 // br %LE, %LB2 1520 // LB2: 1521 // %v2 = 1522 // br %LE, %LB1 1523 // LE: 1524 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable 1525 // 1526 // to 1527 // 1528 // LB1: 1529 // %v1 = 1530 // br %LE.split, %LB2 1531 // LB2: 1532 // %v2 = 1533 // br %LE.split2, %LB1 1534 // LE.split: 1535 // %p1 = phi [%v1, %LB1] <-- trivially replaceable 1536 // br %LE 1537 // LE.split2: 1538 // %p2 = phi [%v2, %LB2] <-- trivially replaceable 1539 // br %LE 1540 // LE: 1541 // %p = phi [%p1, %LE.split], [%p2, %LE.split2] 1542 // 1543 const auto &BlockColors = SafetyInfo->getBlockColors(); 1544 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB)); 1545 while (!PredBBs.empty()) { 1546 BasicBlock *PredBB = *PredBBs.begin(); 1547 assert(CurLoop->contains(PredBB) && 1548 "Expect all predecessors are in the loop"); 1549 if (PN->getBasicBlockIndex(PredBB) >= 0) { 1550 BasicBlock *NewPred = SplitBlockPredecessors( 1551 ExitBB, PredBB, ".split.loop.exit", DT, LI, MSSAU, true); 1552 // Since we do not allow splitting EH-block with BlockColors in 1553 // canSplitPredecessors(), we can simply assign predecessor's color to 1554 // the new block. 1555 if (!BlockColors.empty()) 1556 // Grab a reference to the ColorVector to be inserted before getting the 1557 // reference to the vector we are copying because inserting the new 1558 // element in BlockColors might cause the map to be reallocated. 1559 SafetyInfo->copyColors(NewPred, PredBB); 1560 } 1561 PredBBs.remove(PredBB); 1562 } 1563 } 1564 1565 /// When an instruction is found to only be used outside of the loop, this 1566 /// function moves it to the exit blocks and patches up SSA form as needed. 1567 /// This method is guaranteed to remove the original instruction from its 1568 /// position, and may either delete it or move it to outside of the loop. 1569 /// 1570 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, 1571 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo, 1572 MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE) { 1573 LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n"); 1574 ORE->emit([&]() { 1575 return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I) 1576 << "sinking " << ore::NV("Inst", &I); 1577 }); 1578 bool Changed = false; 1579 if (isa<LoadInst>(I)) 1580 ++NumMovedLoads; 1581 else if (isa<CallInst>(I)) 1582 ++NumMovedCalls; 1583 ++NumSunk; 1584 1585 // Iterate over users to be ready for actual sinking. Replace users via 1586 // unreachable blocks with undef and make all user PHIs trivially replaceable. 1587 SmallPtrSet<Instruction *, 8> VisitedUsers; 1588 for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) { 1589 auto *User = cast<Instruction>(*UI); 1590 Use &U = UI.getUse(); 1591 ++UI; 1592 1593 if (VisitedUsers.count(User) || CurLoop->contains(User)) 1594 continue; 1595 1596 if (!DT->isReachableFromEntry(User->getParent())) { 1597 U = UndefValue::get(I.getType()); 1598 Changed = true; 1599 continue; 1600 } 1601 1602 // The user must be a PHI node. 1603 PHINode *PN = cast<PHINode>(User); 1604 1605 // Surprisingly, instructions can be used outside of loops without any 1606 // exits. This can only happen in PHI nodes if the incoming block is 1607 // unreachable. 1608 BasicBlock *BB = PN->getIncomingBlock(U); 1609 if (!DT->isReachableFromEntry(BB)) { 1610 U = UndefValue::get(I.getType()); 1611 Changed = true; 1612 continue; 1613 } 1614 1615 VisitedUsers.insert(PN); 1616 if (isTriviallyReplaceablePHI(*PN, I)) 1617 continue; 1618 1619 if (!canSplitPredecessors(PN, SafetyInfo)) 1620 return Changed; 1621 1622 // Split predecessors of the PHI so that we can make users trivially 1623 // replaceable. 1624 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, MSSAU); 1625 1626 // Should rebuild the iterators, as they may be invalidated by 1627 // splitPredecessorsOfLoopExit(). 1628 UI = I.user_begin(); 1629 UE = I.user_end(); 1630 } 1631 1632 if (VisitedUsers.empty()) 1633 return Changed; 1634 1635 #ifndef NDEBUG 1636 SmallVector<BasicBlock *, 32> ExitBlocks; 1637 CurLoop->getUniqueExitBlocks(ExitBlocks); 1638 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), 1639 ExitBlocks.end()); 1640 #endif 1641 1642 // Clones of this instruction. Don't create more than one per exit block! 1643 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies; 1644 1645 // If this instruction is only used outside of the loop, then all users are 1646 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of 1647 // the instruction. 1648 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end()); 1649 for (auto *UI : Users) { 1650 auto *User = cast<Instruction>(UI); 1651 1652 if (CurLoop->contains(User)) 1653 continue; 1654 1655 PHINode *PN = cast<PHINode>(User); 1656 assert(ExitBlockSet.count(PN->getParent()) && 1657 "The LCSSA PHI is not in an exit block!"); 1658 // The PHI must be trivially replaceable. 1659 Instruction *New = sinkThroughTriviallyReplaceablePHI( 1660 PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU); 1661 PN->replaceAllUsesWith(New); 1662 eraseInstruction(*PN, *SafetyInfo, nullptr, nullptr); 1663 Changed = true; 1664 } 1665 return Changed; 1666 } 1667 1668 /// When an instruction is found to only use loop invariant operands that 1669 /// is safe to hoist, this instruction is called to do the dirty work. 1670 /// 1671 static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 1672 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo, 1673 MemorySSAUpdater *MSSAU, ScalarEvolution *SE, 1674 OptimizationRemarkEmitter *ORE) { 1675 LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getName() << ": " << I 1676 << "\n"); 1677 ORE->emit([&]() { 1678 return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting " 1679 << ore::NV("Inst", &I); 1680 }); 1681 1682 // Metadata can be dependent on conditions we are hoisting above. 1683 // Conservatively strip all metadata on the instruction unless we were 1684 // guaranteed to execute I if we entered the loop, in which case the metadata 1685 // is valid in the loop preheader. 1686 if (I.hasMetadataOtherThanDebugLoc() && 1687 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning 1688 // time in isGuaranteedToExecute if we don't actually have anything to 1689 // drop. It is a compile time optimization, not required for correctness. 1690 !SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop)) 1691 I.dropUnknownNonDebugMetadata(); 1692 1693 if (isa<PHINode>(I)) 1694 // Move the new node to the end of the phi list in the destination block. 1695 moveInstructionBefore(I, *Dest->getFirstNonPHI(), *SafetyInfo, MSSAU, SE); 1696 else 1697 // Move the new node to the destination block, before its terminator. 1698 moveInstructionBefore(I, *Dest->getTerminator(), *SafetyInfo, MSSAU, SE); 1699 1700 // Apply line 0 debug locations when we are moving instructions to different 1701 // basic blocks because we want to avoid jumpy line tables. 1702 if (const DebugLoc &DL = I.getDebugLoc()) 1703 I.setDebugLoc(DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt())); 1704 1705 if (isa<LoadInst>(I)) 1706 ++NumMovedLoads; 1707 else if (isa<CallInst>(I)) 1708 ++NumMovedCalls; 1709 ++NumHoisted; 1710 } 1711 1712 /// Only sink or hoist an instruction if it is not a trapping instruction, 1713 /// or if the instruction is known not to trap when moved to the preheader. 1714 /// or if it is a trapping instruction and is guaranteed to execute. 1715 static bool isSafeToExecuteUnconditionally(Instruction &Inst, 1716 const DominatorTree *DT, 1717 const Loop *CurLoop, 1718 const LoopSafetyInfo *SafetyInfo, 1719 OptimizationRemarkEmitter *ORE, 1720 const Instruction *CtxI) { 1721 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT)) 1722 return true; 1723 1724 bool GuaranteedToExecute = 1725 SafetyInfo->isGuaranteedToExecute(Inst, DT, CurLoop); 1726 1727 if (!GuaranteedToExecute) { 1728 auto *LI = dyn_cast<LoadInst>(&Inst); 1729 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand())) 1730 ORE->emit([&]() { 1731 return OptimizationRemarkMissed( 1732 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI) 1733 << "failed to hoist load with loop-invariant address " 1734 "because load is conditionally executed"; 1735 }); 1736 } 1737 1738 return GuaranteedToExecute; 1739 } 1740 1741 namespace { 1742 class LoopPromoter : public LoadAndStorePromoter { 1743 Value *SomePtr; // Designated pointer to store to. 1744 const SmallSetVector<Value *, 8> &PointerMustAliases; 1745 SmallVectorImpl<BasicBlock *> &LoopExitBlocks; 1746 SmallVectorImpl<Instruction *> &LoopInsertPts; 1747 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts; 1748 PredIteratorCache &PredCache; 1749 AliasSetTracker &AST; 1750 MemorySSAUpdater *MSSAU; 1751 LoopInfo &LI; 1752 DebugLoc DL; 1753 int Alignment; 1754 bool UnorderedAtomic; 1755 AAMDNodes AATags; 1756 ICFLoopSafetyInfo &SafetyInfo; 1757 1758 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const { 1759 if (Instruction *I = dyn_cast<Instruction>(V)) 1760 if (Loop *L = LI.getLoopFor(I->getParent())) 1761 if (!L->contains(BB)) { 1762 // We need to create an LCSSA PHI node for the incoming value and 1763 // store that. 1764 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB), 1765 I->getName() + ".lcssa", &BB->front()); 1766 for (BasicBlock *Pred : PredCache.get(BB)) 1767 PN->addIncoming(I, Pred); 1768 return PN; 1769 } 1770 return V; 1771 } 1772 1773 public: 1774 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S, 1775 const SmallSetVector<Value *, 8> &PMA, 1776 SmallVectorImpl<BasicBlock *> &LEB, 1777 SmallVectorImpl<Instruction *> &LIP, 1778 SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC, 1779 AliasSetTracker &ast, MemorySSAUpdater *MSSAU, LoopInfo &li, 1780 DebugLoc dl, int alignment, bool UnorderedAtomic, 1781 const AAMDNodes &AATags, ICFLoopSafetyInfo &SafetyInfo) 1782 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA), 1783 LoopExitBlocks(LEB), LoopInsertPts(LIP), MSSAInsertPts(MSSAIP), 1784 PredCache(PIC), AST(ast), MSSAU(MSSAU), LI(li), DL(std::move(dl)), 1785 Alignment(alignment), UnorderedAtomic(UnorderedAtomic), AATags(AATags), 1786 SafetyInfo(SafetyInfo) {} 1787 1788 bool isInstInList(Instruction *I, 1789 const SmallVectorImpl<Instruction *> &) const override { 1790 Value *Ptr; 1791 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 1792 Ptr = LI->getOperand(0); 1793 else 1794 Ptr = cast<StoreInst>(I)->getPointerOperand(); 1795 return PointerMustAliases.count(Ptr); 1796 } 1797 1798 void doExtraRewritesBeforeFinalDeletion() override { 1799 // Insert stores after in the loop exit blocks. Each exit block gets a 1800 // store of the live-out values that feed them. Since we've already told 1801 // the SSA updater about the defs in the loop and the preheader 1802 // definition, it is all set and we can start using it. 1803 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) { 1804 BasicBlock *ExitBlock = LoopExitBlocks[i]; 1805 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock); 1806 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock); 1807 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock); 1808 Instruction *InsertPos = LoopInsertPts[i]; 1809 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos); 1810 if (UnorderedAtomic) 1811 NewSI->setOrdering(AtomicOrdering::Unordered); 1812 NewSI->setAlignment(MaybeAlign(Alignment)); 1813 NewSI->setDebugLoc(DL); 1814 if (AATags) 1815 NewSI->setAAMetadata(AATags); 1816 1817 if (MSSAU) { 1818 MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i]; 1819 MemoryAccess *NewMemAcc; 1820 if (!MSSAInsertPoint) { 1821 NewMemAcc = MSSAU->createMemoryAccessInBB( 1822 NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning); 1823 } else { 1824 NewMemAcc = 1825 MSSAU->createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint); 1826 } 1827 MSSAInsertPts[i] = NewMemAcc; 1828 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true); 1829 // FIXME: true for safety, false may still be correct. 1830 } 1831 } 1832 } 1833 1834 void replaceLoadWithValue(LoadInst *LI, Value *V) const override { 1835 // Update alias analysis. 1836 AST.copyValue(LI, V); 1837 } 1838 void instructionDeleted(Instruction *I) const override { 1839 SafetyInfo.removeInstruction(I); 1840 AST.deleteValue(I); 1841 if (MSSAU) 1842 MSSAU->removeMemoryAccess(I); 1843 } 1844 }; 1845 1846 1847 /// Return true iff we can prove that a caller of this function can not inspect 1848 /// the contents of the provided object in a well defined program. 1849 bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) { 1850 if (isa<AllocaInst>(Object)) 1851 // Since the alloca goes out of scope, we know the caller can't retain a 1852 // reference to it and be well defined. Thus, we don't need to check for 1853 // capture. 1854 return true; 1855 1856 // For all other objects we need to know that the caller can't possibly 1857 // have gotten a reference to the object. There are two components of 1858 // that: 1859 // 1) Object can't be escaped by this function. This is what 1860 // PointerMayBeCaptured checks. 1861 // 2) Object can't have been captured at definition site. For this, we 1862 // need to know the return value is noalias. At the moment, we use a 1863 // weaker condition and handle only AllocLikeFunctions (which are 1864 // known to be noalias). TODO 1865 return isAllocLikeFn(Object, TLI) && 1866 !PointerMayBeCaptured(Object, true, true); 1867 } 1868 1869 } // namespace 1870 1871 /// Try to promote memory values to scalars by sinking stores out of the 1872 /// loop and moving loads to before the loop. We do this by looping over 1873 /// the stores in the loop, looking for stores to Must pointers which are 1874 /// loop invariant. 1875 /// 1876 bool llvm::promoteLoopAccessesToScalars( 1877 const SmallSetVector<Value *, 8> &PointerMustAliases, 1878 SmallVectorImpl<BasicBlock *> &ExitBlocks, 1879 SmallVectorImpl<Instruction *> &InsertPts, 1880 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts, PredIteratorCache &PIC, 1881 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, 1882 Loop *CurLoop, AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, 1883 ICFLoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE) { 1884 // Verify inputs. 1885 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr && 1886 CurAST != nullptr && SafetyInfo != nullptr && 1887 "Unexpected Input to promoteLoopAccessesToScalars"); 1888 1889 Value *SomePtr = *PointerMustAliases.begin(); 1890 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 1891 1892 // It is not safe to promote a load/store from the loop if the load/store is 1893 // conditional. For example, turning: 1894 // 1895 // for () { if (c) *P += 1; } 1896 // 1897 // into: 1898 // 1899 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp; 1900 // 1901 // is not safe, because *P may only be valid to access if 'c' is true. 1902 // 1903 // The safety property divides into two parts: 1904 // p1) The memory may not be dereferenceable on entry to the loop. In this 1905 // case, we can't insert the required load in the preheader. 1906 // p2) The memory model does not allow us to insert a store along any dynamic 1907 // path which did not originally have one. 1908 // 1909 // If at least one store is guaranteed to execute, both properties are 1910 // satisfied, and promotion is legal. 1911 // 1912 // This, however, is not a necessary condition. Even if no store/load is 1913 // guaranteed to execute, we can still establish these properties. 1914 // We can establish (p1) by proving that hoisting the load into the preheader 1915 // is safe (i.e. proving dereferenceability on all paths through the loop). We 1916 // can use any access within the alias set to prove dereferenceability, 1917 // since they're all must alias. 1918 // 1919 // There are two ways establish (p2): 1920 // a) Prove the location is thread-local. In this case the memory model 1921 // requirement does not apply, and stores are safe to insert. 1922 // b) Prove a store dominates every exit block. In this case, if an exit 1923 // blocks is reached, the original dynamic path would have taken us through 1924 // the store, so inserting a store into the exit block is safe. Note that this 1925 // is different from the store being guaranteed to execute. For instance, 1926 // if an exception is thrown on the first iteration of the loop, the original 1927 // store is never executed, but the exit blocks are not executed either. 1928 1929 bool DereferenceableInPH = false; 1930 bool SafeToInsertStore = false; 1931 1932 SmallVector<Instruction *, 64> LoopUses; 1933 1934 // We start with an alignment of one and try to find instructions that allow 1935 // us to prove better alignment. 1936 unsigned Alignment = 1; 1937 // Keep track of which types of access we see 1938 bool SawUnorderedAtomic = false; 1939 bool SawNotAtomic = false; 1940 AAMDNodes AATags; 1941 1942 const DataLayout &MDL = Preheader->getModule()->getDataLayout(); 1943 1944 bool IsKnownThreadLocalObject = false; 1945 if (SafetyInfo->anyBlockMayThrow()) { 1946 // If a loop can throw, we have to insert a store along each unwind edge. 1947 // That said, we can't actually make the unwind edge explicit. Therefore, 1948 // we have to prove that the store is dead along the unwind edge. We do 1949 // this by proving that the caller can't have a reference to the object 1950 // after return and thus can't possibly load from the object. 1951 Value *Object = GetUnderlyingObject(SomePtr, MDL); 1952 if (!isKnownNonEscaping(Object, TLI)) 1953 return false; 1954 // Subtlety: Alloca's aren't visible to callers, but *are* potentially 1955 // visible to other threads if captured and used during their lifetimes. 1956 IsKnownThreadLocalObject = !isa<AllocaInst>(Object); 1957 } 1958 1959 // Check that all of the pointers in the alias set have the same type. We 1960 // cannot (yet) promote a memory location that is loaded and stored in 1961 // different sizes. While we are at it, collect alignment and AA info. 1962 for (Value *ASIV : PointerMustAliases) { 1963 // Check that all of the pointers in the alias set have the same type. We 1964 // cannot (yet) promote a memory location that is loaded and stored in 1965 // different sizes. 1966 if (SomePtr->getType() != ASIV->getType()) 1967 return false; 1968 1969 for (User *U : ASIV->users()) { 1970 // Ignore instructions that are outside the loop. 1971 Instruction *UI = dyn_cast<Instruction>(U); 1972 if (!UI || !CurLoop->contains(UI)) 1973 continue; 1974 1975 // If there is an non-load/store instruction in the loop, we can't promote 1976 // it. 1977 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) { 1978 if (!Load->isUnordered()) 1979 return false; 1980 1981 SawUnorderedAtomic |= Load->isAtomic(); 1982 SawNotAtomic |= !Load->isAtomic(); 1983 1984 unsigned InstAlignment = Load->getAlignment(); 1985 if (!InstAlignment) 1986 InstAlignment = 1987 MDL.getABITypeAlignment(Load->getType()); 1988 1989 // Note that proving a load safe to speculate requires proving 1990 // sufficient alignment at the target location. Proving it guaranteed 1991 // to execute does as well. Thus we can increase our guaranteed 1992 // alignment as well. 1993 if (!DereferenceableInPH || (InstAlignment > Alignment)) 1994 if (isSafeToExecuteUnconditionally(*Load, DT, CurLoop, SafetyInfo, 1995 ORE, Preheader->getTerminator())) { 1996 DereferenceableInPH = true; 1997 Alignment = std::max(Alignment, InstAlignment); 1998 } 1999 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) { 2000 // Stores *of* the pointer are not interesting, only stores *to* the 2001 // pointer. 2002 if (UI->getOperand(1) != ASIV) 2003 continue; 2004 if (!Store->isUnordered()) 2005 return false; 2006 2007 SawUnorderedAtomic |= Store->isAtomic(); 2008 SawNotAtomic |= !Store->isAtomic(); 2009 2010 // If the store is guaranteed to execute, both properties are satisfied. 2011 // We may want to check if a store is guaranteed to execute even if we 2012 // already know that promotion is safe, since it may have higher 2013 // alignment than any other guaranteed stores, in which case we can 2014 // raise the alignment on the promoted store. 2015 unsigned InstAlignment = Store->getAlignment(); 2016 if (!InstAlignment) 2017 InstAlignment = 2018 MDL.getABITypeAlignment(Store->getValueOperand()->getType()); 2019 2020 if (!DereferenceableInPH || !SafeToInsertStore || 2021 (InstAlignment > Alignment)) { 2022 if (SafetyInfo->isGuaranteedToExecute(*UI, DT, CurLoop)) { 2023 DereferenceableInPH = true; 2024 SafeToInsertStore = true; 2025 Alignment = std::max(Alignment, InstAlignment); 2026 } 2027 } 2028 2029 // If a store dominates all exit blocks, it is safe to sink. 2030 // As explained above, if an exit block was executed, a dominating 2031 // store must have been executed at least once, so we are not 2032 // introducing stores on paths that did not have them. 2033 // Note that this only looks at explicit exit blocks. If we ever 2034 // start sinking stores into unwind edges (see above), this will break. 2035 if (!SafeToInsertStore) 2036 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) { 2037 return DT->dominates(Store->getParent(), Exit); 2038 }); 2039 2040 // If the store is not guaranteed to execute, we may still get 2041 // deref info through it. 2042 if (!DereferenceableInPH) { 2043 DereferenceableInPH = isDereferenceableAndAlignedPointer( 2044 Store->getPointerOperand(), Store->getValueOperand()->getType(), 2045 MaybeAlign(Store->getAlignment()), MDL, 2046 Preheader->getTerminator(), DT); 2047 } 2048 } else 2049 return false; // Not a load or store. 2050 2051 // Merge the AA tags. 2052 if (LoopUses.empty()) { 2053 // On the first load/store, just take its AA tags. 2054 UI->getAAMetadata(AATags); 2055 } else if (AATags) { 2056 UI->getAAMetadata(AATags, /* Merge = */ true); 2057 } 2058 2059 LoopUses.push_back(UI); 2060 } 2061 } 2062 2063 // If we found both an unordered atomic instruction and a non-atomic memory 2064 // access, bail. We can't blindly promote non-atomic to atomic since we 2065 // might not be able to lower the result. We can't downgrade since that 2066 // would violate memory model. Also, align 0 is an error for atomics. 2067 if (SawUnorderedAtomic && SawNotAtomic) 2068 return false; 2069 2070 // If we're inserting an atomic load in the preheader, we must be able to 2071 // lower it. We're only guaranteed to be able to lower naturally aligned 2072 // atomics. 2073 auto *SomePtrElemType = SomePtr->getType()->getPointerElementType(); 2074 if (SawUnorderedAtomic && 2075 Alignment < MDL.getTypeStoreSize(SomePtrElemType)) 2076 return false; 2077 2078 // If we couldn't prove we can hoist the load, bail. 2079 if (!DereferenceableInPH) 2080 return false; 2081 2082 // We know we can hoist the load, but don't have a guaranteed store. 2083 // Check whether the location is thread-local. If it is, then we can insert 2084 // stores along paths which originally didn't have them without violating the 2085 // memory model. 2086 if (!SafeToInsertStore) { 2087 if (IsKnownThreadLocalObject) 2088 SafeToInsertStore = true; 2089 else { 2090 Value *Object = GetUnderlyingObject(SomePtr, MDL); 2091 SafeToInsertStore = 2092 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) && 2093 !PointerMayBeCaptured(Object, true, true); 2094 } 2095 } 2096 2097 // If we've still failed to prove we can sink the store, give up. 2098 if (!SafeToInsertStore) 2099 return false; 2100 2101 // Otherwise, this is safe to promote, lets do it! 2102 LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr 2103 << '\n'); 2104 ORE->emit([&]() { 2105 return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar", 2106 LoopUses[0]) 2107 << "Moving accesses to memory location out of the loop"; 2108 }); 2109 ++NumPromoted; 2110 2111 // Grab a debug location for the inserted loads/stores; given that the 2112 // inserted loads/stores have little relation to the original loads/stores, 2113 // this code just arbitrarily picks a location from one, since any debug 2114 // location is better than none. 2115 DebugLoc DL = LoopUses[0]->getDebugLoc(); 2116 2117 // We use the SSAUpdater interface to insert phi nodes as required. 2118 SmallVector<PHINode *, 16> NewPHIs; 2119 SSAUpdater SSA(&NewPHIs); 2120 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks, 2121 InsertPts, MSSAInsertPts, PIC, *CurAST, MSSAU, *LI, DL, 2122 Alignment, SawUnorderedAtomic, AATags, *SafetyInfo); 2123 2124 // Set up the preheader to have a definition of the value. It is the live-out 2125 // value from the preheader that uses in the loop will use. 2126 LoadInst *PreheaderLoad = new LoadInst( 2127 SomePtr->getType()->getPointerElementType(), SomePtr, 2128 SomePtr->getName() + ".promoted", Preheader->getTerminator()); 2129 if (SawUnorderedAtomic) 2130 PreheaderLoad->setOrdering(AtomicOrdering::Unordered); 2131 PreheaderLoad->setAlignment(MaybeAlign(Alignment)); 2132 PreheaderLoad->setDebugLoc(DL); 2133 if (AATags) 2134 PreheaderLoad->setAAMetadata(AATags); 2135 SSA.AddAvailableValue(Preheader, PreheaderLoad); 2136 2137 if (MSSAU) { 2138 MemoryAccess *PreheaderLoadMemoryAccess = MSSAU->createMemoryAccessInBB( 2139 PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End); 2140 MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess); 2141 MSSAU->insertUse(NewMemUse, /*RenameUses=*/true); 2142 } 2143 2144 if (MSSAU && VerifyMemorySSA) 2145 MSSAU->getMemorySSA()->verifyMemorySSA(); 2146 // Rewrite all the loads in the loop and remember all the definitions from 2147 // stores in the loop. 2148 Promoter.run(LoopUses); 2149 2150 if (MSSAU && VerifyMemorySSA) 2151 MSSAU->getMemorySSA()->verifyMemorySSA(); 2152 // If the SSAUpdater didn't use the load in the preheader, just zap it now. 2153 if (PreheaderLoad->use_empty()) 2154 eraseInstruction(*PreheaderLoad, *SafetyInfo, CurAST, MSSAU); 2155 2156 return true; 2157 } 2158 2159 /// Returns an owning pointer to an alias set which incorporates aliasing info 2160 /// from L and all subloops of L. 2161 std::unique_ptr<AliasSetTracker> 2162 LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI, 2163 AliasAnalysis *AA) { 2164 auto CurAST = std::make_unique<AliasSetTracker>(*AA); 2165 2166 // Add everything from all the sub loops. 2167 for (Loop *InnerL : L->getSubLoops()) 2168 for (BasicBlock *BB : InnerL->blocks()) 2169 CurAST->add(*BB); 2170 2171 // And merge in this loop (without anything from inner loops). 2172 for (BasicBlock *BB : L->blocks()) 2173 if (LI->getLoopFor(BB) == L) 2174 CurAST->add(*BB); 2175 2176 return CurAST; 2177 } 2178 2179 std::unique_ptr<AliasSetTracker> 2180 LoopInvariantCodeMotion::collectAliasInfoForLoopWithMSSA( 2181 Loop *L, AliasAnalysis *AA, MemorySSAUpdater *MSSAU) { 2182 auto *MSSA = MSSAU->getMemorySSA(); 2183 auto CurAST = std::make_unique<AliasSetTracker>(*AA, MSSA, L); 2184 CurAST->addAllInstructionsInLoopUsingMSSA(); 2185 return CurAST; 2186 } 2187 2188 static bool pointerInvalidatedByLoop(MemoryLocation MemLoc, 2189 AliasSetTracker *CurAST, Loop *CurLoop, 2190 AliasAnalysis *AA) { 2191 // First check to see if any of the basic blocks in CurLoop invalidate *V. 2192 bool isInvalidatedAccordingToAST = CurAST->getAliasSetFor(MemLoc).isMod(); 2193 2194 if (!isInvalidatedAccordingToAST || !LICMN2Theshold) 2195 return isInvalidatedAccordingToAST; 2196 2197 // Check with a diagnostic analysis if we can refine the information above. 2198 // This is to identify the limitations of using the AST. 2199 // The alias set mechanism used by LICM has a major weakness in that it 2200 // combines all things which may alias into a single set *before* asking 2201 // modref questions. As a result, a single readonly call within a loop will 2202 // collapse all loads and stores into a single alias set and report 2203 // invalidation if the loop contains any store. For example, readonly calls 2204 // with deopt states have this form and create a general alias set with all 2205 // loads and stores. In order to get any LICM in loops containing possible 2206 // deopt states we need a more precise invalidation of checking the mod ref 2207 // info of each instruction within the loop and LI. This has a complexity of 2208 // O(N^2), so currently, it is used only as a diagnostic tool since the 2209 // default value of LICMN2Threshold is zero. 2210 2211 // Don't look at nested loops. 2212 if (CurLoop->begin() != CurLoop->end()) 2213 return true; 2214 2215 int N = 0; 2216 for (BasicBlock *BB : CurLoop->getBlocks()) 2217 for (Instruction &I : *BB) { 2218 if (N >= LICMN2Theshold) { 2219 LLVM_DEBUG(dbgs() << "Alasing N2 threshold exhausted for " 2220 << *(MemLoc.Ptr) << "\n"); 2221 return true; 2222 } 2223 N++; 2224 auto Res = AA->getModRefInfo(&I, MemLoc); 2225 if (isModSet(Res)) { 2226 LLVM_DEBUG(dbgs() << "Aliasing failed on " << I << " for " 2227 << *(MemLoc.Ptr) << "\n"); 2228 return true; 2229 } 2230 } 2231 LLVM_DEBUG(dbgs() << "Aliasing okay for " << *(MemLoc.Ptr) << "\n"); 2232 return false; 2233 } 2234 2235 static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU, 2236 Loop *CurLoop, 2237 SinkAndHoistLICMFlags &Flags) { 2238 // For hoisting, use the walker to determine safety 2239 if (!Flags.IsSink) { 2240 MemoryAccess *Source; 2241 // See declaration of SetLicmMssaOptCap for usage details. 2242 if (Flags.LicmMssaOptCounter >= Flags.LicmMssaOptCap) 2243 Source = MU->getDefiningAccess(); 2244 else { 2245 Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(MU); 2246 Flags.LicmMssaOptCounter++; 2247 } 2248 return !MSSA->isLiveOnEntryDef(Source) && 2249 CurLoop->contains(Source->getBlock()); 2250 } 2251 2252 // For sinking, we'd need to check all Defs below this use. The getClobbering 2253 // call will look on the backedge of the loop, but will check aliasing with 2254 // the instructions on the previous iteration. 2255 // For example: 2256 // for (i ... ) 2257 // load a[i] ( Use (LoE) 2258 // store a[i] ( 1 = Def (2), with 2 = Phi for the loop. 2259 // i++; 2260 // The load sees no clobbering inside the loop, as the backedge alias check 2261 // does phi translation, and will check aliasing against store a[i-1]. 2262 // However sinking the load outside the loop, below the store is incorrect. 2263 2264 // For now, only sink if there are no Defs in the loop, and the existing ones 2265 // precede the use and are in the same block. 2266 // FIXME: Increase precision: Safe to sink if Use post dominates the Def; 2267 // needs PostDominatorTreeAnalysis. 2268 // FIXME: More precise: no Defs that alias this Use. 2269 if (Flags.NoOfMemAccTooLarge) 2270 return true; 2271 for (auto *BB : CurLoop->getBlocks()) 2272 if (auto *Accesses = MSSA->getBlockDefs(BB)) 2273 for (const auto &MA : *Accesses) 2274 if (const auto *MD = dyn_cast<MemoryDef>(&MA)) 2275 if (MU->getBlock() != MD->getBlock() || 2276 !MSSA->locallyDominates(MD, MU)) 2277 return true; 2278 return false; 2279 } 2280 2281 /// Little predicate that returns true if the specified basic block is in 2282 /// a subloop of the current one, not the current one itself. 2283 /// 2284 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) { 2285 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop"); 2286 return LI->getLoopFor(BB) != CurLoop; 2287 } 2288