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