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