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