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