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