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