1 //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===// 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 transforms loops by placing phi nodes at the end of the loops for 10 // all values that are live across the loop boundary. For example, it turns 11 // the left into the right code: 12 // 13 // for (...) for (...) 14 // if (c) if (c) 15 // X1 = ... X1 = ... 16 // else else 17 // X2 = ... X2 = ... 18 // X3 = phi(X1, X2) X3 = phi(X1, X2) 19 // ... = X3 + 4 X4 = phi(X3) 20 // ... = X4 + 4 21 // 22 // This is still valid LLVM; the extra phi nodes are purely redundant, and will 23 // be trivially eliminated by InstCombine. The major benefit of this 24 // transformation is that it makes many other loop optimizations, such as 25 // LoopUnswitching, simpler. 26 // 27 //===----------------------------------------------------------------------===// 28 29 #include "llvm/Transforms/Utils/LCSSA.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/Statistic.h" 32 #include "llvm/Analysis/AliasAnalysis.h" 33 #include "llvm/Analysis/BasicAliasAnalysis.h" 34 #include "llvm/Analysis/BranchProbabilityInfo.h" 35 #include "llvm/Analysis/GlobalsModRef.h" 36 #include "llvm/Analysis/LoopPass.h" 37 #include "llvm/Analysis/MemorySSA.h" 38 #include "llvm/Analysis/ScalarEvolution.h" 39 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 40 #include "llvm/IR/Constants.h" 41 #include "llvm/IR/Dominators.h" 42 #include "llvm/IR/Function.h" 43 #include "llvm/IR/Instructions.h" 44 #include "llvm/IR/IntrinsicInst.h" 45 #include "llvm/IR/PredIteratorCache.h" 46 #include "llvm/Pass.h" 47 #include "llvm/Transforms/Utils.h" 48 #include "llvm/Transforms/Utils/Local.h" 49 #include "llvm/Transforms/Utils/LoopUtils.h" 50 #include "llvm/Transforms/Utils/SSAUpdater.h" 51 using namespace llvm; 52 53 #define DEBUG_TYPE "lcssa" 54 55 STATISTIC(NumLCSSA, "Number of live out of a loop variables"); 56 57 #ifdef EXPENSIVE_CHECKS 58 static bool VerifyLoopLCSSA = true; 59 #else 60 static bool VerifyLoopLCSSA = false; 61 #endif 62 static cl::opt<bool, true> 63 VerifyLoopLCSSAFlag("verify-loop-lcssa", cl::location(VerifyLoopLCSSA), 64 cl::Hidden, 65 cl::desc("Verify loop lcssa form (time consuming)")); 66 67 /// Return true if the specified block is in the list. 68 static bool isExitBlock(BasicBlock *BB, 69 const SmallVectorImpl<BasicBlock *> &ExitBlocks) { 70 return is_contained(ExitBlocks, BB); 71 } 72 73 /// For every instruction from the worklist, check to see if it has any uses 74 /// that are outside the current loop. If so, insert LCSSA PHI nodes and 75 /// rewrite the uses. 76 bool llvm::formLCSSAForInstructions(SmallVectorImpl<Instruction *> &Worklist, 77 DominatorTree &DT, LoopInfo &LI, 78 ScalarEvolution *SE) { 79 SmallVector<Use *, 16> UsesToRewrite; 80 SmallSetVector<PHINode *, 16> PHIsToRemove; 81 PredIteratorCache PredCache; 82 bool Changed = false; 83 84 // Cache the Loop ExitBlocks across this loop. We expect to get a lot of 85 // instructions within the same loops, computing the exit blocks is 86 // expensive, and we're not mutating the loop structure. 87 SmallDenseMap<Loop*, SmallVector<BasicBlock *,1>> LoopExitBlocks; 88 89 while (!Worklist.empty()) { 90 UsesToRewrite.clear(); 91 92 Instruction *I = Worklist.pop_back_val(); 93 assert(!I->getType()->isTokenTy() && "Tokens shouldn't be in the worklist"); 94 BasicBlock *InstBB = I->getParent(); 95 Loop *L = LI.getLoopFor(InstBB); 96 assert(L && "Instruction belongs to a BB that's not part of a loop"); 97 if (!LoopExitBlocks.count(L)) 98 L->getExitBlocks(LoopExitBlocks[L]); 99 assert(LoopExitBlocks.count(L)); 100 const SmallVectorImpl<BasicBlock *> &ExitBlocks = LoopExitBlocks[L]; 101 102 if (ExitBlocks.empty()) 103 continue; 104 105 for (Use &U : I->uses()) { 106 Instruction *User = cast<Instruction>(U.getUser()); 107 BasicBlock *UserBB = User->getParent(); 108 if (auto *PN = dyn_cast<PHINode>(User)) 109 UserBB = PN->getIncomingBlock(U); 110 111 if (InstBB != UserBB && !L->contains(UserBB)) 112 UsesToRewrite.push_back(&U); 113 } 114 115 // If there are no uses outside the loop, exit with no change. 116 if (UsesToRewrite.empty()) 117 continue; 118 119 ++NumLCSSA; // We are applying the transformation 120 121 // Invoke instructions are special in that their result value is not 122 // available along their unwind edge. The code below tests to see whether 123 // DomBB dominates the value, so adjust DomBB to the normal destination 124 // block, which is effectively where the value is first usable. 125 BasicBlock *DomBB = InstBB; 126 if (auto *Inv = dyn_cast<InvokeInst>(I)) 127 DomBB = Inv->getNormalDest(); 128 129 DomTreeNode *DomNode = DT.getNode(DomBB); 130 131 SmallVector<PHINode *, 16> AddedPHIs; 132 SmallVector<PHINode *, 8> PostProcessPHIs; 133 134 SmallVector<PHINode *, 4> InsertedPHIs; 135 SSAUpdater SSAUpdate(&InsertedPHIs); 136 SSAUpdate.Initialize(I->getType(), I->getName()); 137 138 // Force re-computation of I, as some users now need to use the new PHI 139 // node. 140 if (SE) 141 SE->forgetValue(I); 142 143 // Insert the LCSSA phi's into all of the exit blocks dominated by the 144 // value, and add them to the Phi's map. 145 for (BasicBlock *ExitBB : ExitBlocks) { 146 if (!DT.dominates(DomNode, DT.getNode(ExitBB))) 147 continue; 148 149 // If we already inserted something for this BB, don't reprocess it. 150 if (SSAUpdate.HasValueForBlock(ExitBB)) 151 continue; 152 153 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(ExitBB), 154 I->getName() + ".lcssa", &ExitBB->front()); 155 // Get the debug location from the original instruction. 156 PN->setDebugLoc(I->getDebugLoc()); 157 // Add inputs from inside the loop for this PHI. 158 for (BasicBlock *Pred : PredCache.get(ExitBB)) { 159 PN->addIncoming(I, Pred); 160 161 // If the exit block has a predecessor not within the loop, arrange for 162 // the incoming value use corresponding to that predecessor to be 163 // rewritten in terms of a different LCSSA PHI. 164 if (!L->contains(Pred)) 165 UsesToRewrite.push_back( 166 &PN->getOperandUse(PN->getOperandNumForIncomingValue( 167 PN->getNumIncomingValues() - 1))); 168 } 169 170 AddedPHIs.push_back(PN); 171 172 // Remember that this phi makes the value alive in this block. 173 SSAUpdate.AddAvailableValue(ExitBB, PN); 174 175 // LoopSimplify might fail to simplify some loops (e.g. when indirect 176 // branches are involved). In such situations, it might happen that an 177 // exit for Loop L1 is the header of a disjoint Loop L2. Thus, when we 178 // create PHIs in such an exit block, we are also inserting PHIs into L2's 179 // header. This could break LCSSA form for L2 because these inserted PHIs 180 // can also have uses outside of L2. Remember all PHIs in such situation 181 // as to revisit than later on. FIXME: Remove this if indirectbr support 182 // into LoopSimplify gets improved. 183 if (auto *OtherLoop = LI.getLoopFor(ExitBB)) 184 if (!L->contains(OtherLoop)) 185 PostProcessPHIs.push_back(PN); 186 } 187 188 // Rewrite all uses outside the loop in terms of the new PHIs we just 189 // inserted. 190 for (Use *UseToRewrite : UsesToRewrite) { 191 // If this use is in an exit block, rewrite to use the newly inserted PHI. 192 // This is required for correctness because SSAUpdate doesn't handle uses 193 // in the same block. It assumes the PHI we inserted is at the end of the 194 // block. 195 Instruction *User = cast<Instruction>(UseToRewrite->getUser()); 196 BasicBlock *UserBB = User->getParent(); 197 if (auto *PN = dyn_cast<PHINode>(User)) 198 UserBB = PN->getIncomingBlock(*UseToRewrite); 199 200 if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) { 201 // Tell the VHs that the uses changed. This updates SCEV's caches. 202 if (UseToRewrite->get()->hasValueHandle()) 203 ValueHandleBase::ValueIsRAUWd(*UseToRewrite, &UserBB->front()); 204 UseToRewrite->set(&UserBB->front()); 205 continue; 206 } 207 208 // If we added a single PHI, it must dominate all uses and we can directly 209 // rename it. 210 if (AddedPHIs.size() == 1) { 211 // Tell the VHs that the uses changed. This updates SCEV's caches. 212 // We might call ValueIsRAUWd multiple times for the same value. 213 if (UseToRewrite->get()->hasValueHandle()) 214 ValueHandleBase::ValueIsRAUWd(*UseToRewrite, AddedPHIs[0]); 215 UseToRewrite->set(AddedPHIs[0]); 216 continue; 217 } 218 219 // Otherwise, do full PHI insertion. 220 SSAUpdate.RewriteUse(*UseToRewrite); 221 } 222 223 SmallVector<DbgValueInst *, 4> DbgValues; 224 llvm::findDbgValues(DbgValues, I); 225 226 // Update pre-existing debug value uses that reside outside the loop. 227 auto &Ctx = I->getContext(); 228 for (auto DVI : DbgValues) { 229 BasicBlock *UserBB = DVI->getParent(); 230 if (InstBB == UserBB || L->contains(UserBB)) 231 continue; 232 // We currently only handle debug values residing in blocks that were 233 // traversed while rewriting the uses. If we inserted just a single PHI, 234 // we will handle all relevant debug values. 235 Value *V = AddedPHIs.size() == 1 ? AddedPHIs[0] 236 : SSAUpdate.FindValueForBlock(UserBB); 237 if (V) 238 DVI->setOperand(0, MetadataAsValue::get(Ctx, ValueAsMetadata::get(V))); 239 } 240 241 // SSAUpdater might have inserted phi-nodes inside other loops. We'll need 242 // to post-process them to keep LCSSA form. 243 for (PHINode *InsertedPN : InsertedPHIs) { 244 if (auto *OtherLoop = LI.getLoopFor(InsertedPN->getParent())) 245 if (!L->contains(OtherLoop)) 246 PostProcessPHIs.push_back(InsertedPN); 247 } 248 249 // Post process PHI instructions that were inserted into another disjoint 250 // loop and update their exits properly. 251 for (auto *PostProcessPN : PostProcessPHIs) 252 if (!PostProcessPN->use_empty()) 253 Worklist.push_back(PostProcessPN); 254 255 // Keep track of PHI nodes that we want to remove because they did not have 256 // any uses rewritten. If the new PHI is used, store it so that we can 257 // try to propagate dbg.value intrinsics to it. 258 SmallVector<PHINode *, 2> NeedDbgValues; 259 for (PHINode *PN : AddedPHIs) 260 if (PN->use_empty()) 261 PHIsToRemove.insert(PN); 262 else 263 NeedDbgValues.push_back(PN); 264 insertDebugValuesForPHIs(InstBB, NeedDbgValues); 265 Changed = true; 266 } 267 // Remove PHI nodes that did not have any uses rewritten. We need to redo the 268 // use_empty() check here, because even if the PHI node wasn't used when added 269 // to PHIsToRemove, later added PHI nodes can be using it. This cleanup is 270 // not guaranteed to handle trees/cycles of PHI nodes that only are used by 271 // each other. Such situations has only been noticed when the input IR 272 // contains unreachable code, and leaving some extra redundant PHI nodes in 273 // such situations is considered a minor problem. 274 for (PHINode *PN : PHIsToRemove) 275 if (PN->use_empty()) 276 PN->eraseFromParent(); 277 return Changed; 278 } 279 280 // Compute the set of BasicBlocks in the loop `L` dominating at least one exit. 281 static void computeBlocksDominatingExits( 282 Loop &L, DominatorTree &DT, SmallVector<BasicBlock *, 8> &ExitBlocks, 283 SmallSetVector<BasicBlock *, 8> &BlocksDominatingExits) { 284 SmallVector<BasicBlock *, 8> BBWorklist; 285 286 // We start from the exit blocks, as every block trivially dominates itself 287 // (not strictly). 288 for (BasicBlock *BB : ExitBlocks) 289 BBWorklist.push_back(BB); 290 291 while (!BBWorklist.empty()) { 292 BasicBlock *BB = BBWorklist.pop_back_val(); 293 294 // Check if this is a loop header. If this is the case, we're done. 295 if (L.getHeader() == BB) 296 continue; 297 298 // Otherwise, add its immediate predecessor in the dominator tree to the 299 // worklist, unless we visited it already. 300 BasicBlock *IDomBB = DT.getNode(BB)->getIDom()->getBlock(); 301 302 // Exit blocks can have an immediate dominator not beloinging to the 303 // loop. For an exit block to be immediately dominated by another block 304 // outside the loop, it implies not all paths from that dominator, to the 305 // exit block, go through the loop. 306 // Example: 307 // 308 // |---- A 309 // | | 310 // | B<-- 311 // | | | 312 // |---> C -- 313 // | 314 // D 315 // 316 // C is the exit block of the loop and it's immediately dominated by A, 317 // which doesn't belong to the loop. 318 if (!L.contains(IDomBB)) 319 continue; 320 321 if (BlocksDominatingExits.insert(IDomBB)) 322 BBWorklist.push_back(IDomBB); 323 } 324 } 325 326 bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI, 327 ScalarEvolution *SE) { 328 bool Changed = false; 329 330 #ifdef EXPENSIVE_CHECKS 331 // Verify all sub-loops are in LCSSA form already. 332 for (Loop *SubLoop: L) 333 assert(SubLoop->isRecursivelyLCSSAForm(DT, *LI) && "Subloop not in LCSSA!"); 334 #endif 335 336 SmallVector<BasicBlock *, 8> ExitBlocks; 337 L.getExitBlocks(ExitBlocks); 338 if (ExitBlocks.empty()) 339 return false; 340 341 SmallSetVector<BasicBlock *, 8> BlocksDominatingExits; 342 343 // We want to avoid use-scanning leveraging dominance informations. 344 // If a block doesn't dominate any of the loop exits, the none of the values 345 // defined in the loop can be used outside. 346 // We compute the set of blocks fullfilling the conditions in advance 347 // walking the dominator tree upwards until we hit a loop header. 348 computeBlocksDominatingExits(L, DT, ExitBlocks, BlocksDominatingExits); 349 350 SmallVector<Instruction *, 8> Worklist; 351 352 // Look at all the instructions in the loop, checking to see if they have uses 353 // outside the loop. If so, put them into the worklist to rewrite those uses. 354 for (BasicBlock *BB : BlocksDominatingExits) { 355 // Skip blocks that are part of any sub-loops, they must be in LCSSA 356 // already. 357 if (LI->getLoopFor(BB) != &L) 358 continue; 359 for (Instruction &I : *BB) { 360 // Reject two common cases fast: instructions with no uses (like stores) 361 // and instructions with one use that is in the same block as this. 362 if (I.use_empty() || 363 (I.hasOneUse() && I.user_back()->getParent() == BB && 364 !isa<PHINode>(I.user_back()))) 365 continue; 366 367 // Tokens cannot be used in PHI nodes, so we skip over them. 368 // We can run into tokens which are live out of a loop with catchswitch 369 // instructions in Windows EH if the catchswitch has one catchpad which 370 // is inside the loop and another which is not. 371 if (I.getType()->isTokenTy()) 372 continue; 373 374 Worklist.push_back(&I); 375 } 376 } 377 Changed = formLCSSAForInstructions(Worklist, DT, *LI, SE); 378 379 // If we modified the code, remove any caches about the loop from SCEV to 380 // avoid dangling entries. 381 // FIXME: This is a big hammer, can we clear the cache more selectively? 382 if (SE && Changed) 383 SE->forgetLoop(&L); 384 385 assert(L.isLCSSAForm(DT)); 386 387 return Changed; 388 } 389 390 /// Process a loop nest depth first. 391 bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, 392 ScalarEvolution *SE) { 393 bool Changed = false; 394 395 // Recurse depth-first through inner loops. 396 for (Loop *SubLoop : L.getSubLoops()) 397 Changed |= formLCSSARecursively(*SubLoop, DT, LI, SE); 398 399 Changed |= formLCSSA(L, DT, LI, SE); 400 return Changed; 401 } 402 403 /// Process all loops in the function, inner-most out. 404 static bool formLCSSAOnAllLoops(LoopInfo *LI, DominatorTree &DT, 405 ScalarEvolution *SE) { 406 bool Changed = false; 407 for (auto &L : *LI) 408 Changed |= formLCSSARecursively(*L, DT, LI, SE); 409 return Changed; 410 } 411 412 namespace { 413 struct LCSSAWrapperPass : public FunctionPass { 414 static char ID; // Pass identification, replacement for typeid 415 LCSSAWrapperPass() : FunctionPass(ID) { 416 initializeLCSSAWrapperPassPass(*PassRegistry::getPassRegistry()); 417 } 418 419 // Cached analysis information for the current function. 420 DominatorTree *DT; 421 LoopInfo *LI; 422 ScalarEvolution *SE; 423 424 bool runOnFunction(Function &F) override; 425 void verifyAnalysis() const override { 426 // This check is very expensive. On the loop intensive compiles it may cause 427 // up to 10x slowdown. Currently it's disabled by default. LPPassManager 428 // always does limited form of the LCSSA verification. Similar reasoning 429 // was used for the LoopInfo verifier. 430 if (VerifyLoopLCSSA) { 431 assert(all_of(*LI, 432 [&](Loop *L) { 433 return L->isRecursivelyLCSSAForm(*DT, *LI); 434 }) && 435 "LCSSA form is broken!"); 436 } 437 }; 438 439 /// This transformation requires natural loop information & requires that 440 /// loop preheaders be inserted into the CFG. It maintains both of these, 441 /// as well as the CFG. It also requires dominator information. 442 void getAnalysisUsage(AnalysisUsage &AU) const override { 443 AU.setPreservesCFG(); 444 445 AU.addRequired<DominatorTreeWrapperPass>(); 446 AU.addRequired<LoopInfoWrapperPass>(); 447 AU.addPreservedID(LoopSimplifyID); 448 AU.addPreserved<AAResultsWrapperPass>(); 449 AU.addPreserved<BasicAAWrapperPass>(); 450 AU.addPreserved<GlobalsAAWrapperPass>(); 451 AU.addPreserved<ScalarEvolutionWrapperPass>(); 452 AU.addPreserved<SCEVAAWrapperPass>(); 453 AU.addPreserved<BranchProbabilityInfoWrapperPass>(); 454 AU.addPreserved<MemorySSAWrapperPass>(); 455 456 // This is needed to perform LCSSA verification inside LPPassManager 457 AU.addRequired<LCSSAVerificationPass>(); 458 AU.addPreserved<LCSSAVerificationPass>(); 459 } 460 }; 461 } 462 463 char LCSSAWrapperPass::ID = 0; 464 INITIALIZE_PASS_BEGIN(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass", 465 false, false) 466 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 467 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 468 INITIALIZE_PASS_DEPENDENCY(LCSSAVerificationPass) 469 INITIALIZE_PASS_END(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass", 470 false, false) 471 472 Pass *llvm::createLCSSAPass() { return new LCSSAWrapperPass(); } 473 char &llvm::LCSSAID = LCSSAWrapperPass::ID; 474 475 /// Transform \p F into loop-closed SSA form. 476 bool LCSSAWrapperPass::runOnFunction(Function &F) { 477 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 478 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 479 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 480 SE = SEWP ? &SEWP->getSE() : nullptr; 481 482 return formLCSSAOnAllLoops(LI, *DT, SE); 483 } 484 485 PreservedAnalyses LCSSAPass::run(Function &F, FunctionAnalysisManager &AM) { 486 auto &LI = AM.getResult<LoopAnalysis>(F); 487 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 488 auto *SE = AM.getCachedResult<ScalarEvolutionAnalysis>(F); 489 if (!formLCSSAOnAllLoops(&LI, DT, SE)) 490 return PreservedAnalyses::all(); 491 492 PreservedAnalyses PA; 493 PA.preserveSet<CFGAnalyses>(); 494 PA.preserve<BasicAA>(); 495 PA.preserve<GlobalsAA>(); 496 PA.preserve<SCEVAA>(); 497 PA.preserve<ScalarEvolutionAnalysis>(); 498 // BPI maps terminators to probabilities, since we don't modify the CFG, no 499 // updates are needed to preserve it. 500 PA.preserve<BranchProbabilityAnalysis>(); 501 PA.preserve<MemorySSAAnalysis>(); 502 return PA; 503 } 504