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