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