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