1 //===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification 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 file implements the Loop SimplifyCFG Pass. This pass is responsible for 11 // basic loop CFG cleanup, primarily to assist other loop passes. If you 12 // encounter a noncanonical CFG construct that causes another loop pass to 13 // perform suboptimally, this is the place to fix it up. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/AssumptionCache.h" 22 #include "llvm/Analysis/BasicAliasAnalysis.h" 23 #include "llvm/Analysis/DependenceAnalysis.h" 24 #include "llvm/Analysis/GlobalsModRef.h" 25 #include "llvm/Analysis/LoopInfo.h" 26 #include "llvm/Analysis/LoopPass.h" 27 #include "llvm/Analysis/MemorySSA.h" 28 #include "llvm/Analysis/MemorySSAUpdater.h" 29 #include "llvm/Analysis/ScalarEvolution.h" 30 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 31 #include "llvm/Analysis/TargetTransformInfo.h" 32 #include "llvm/IR/DomTreeUpdater.h" 33 #include "llvm/IR/Dominators.h" 34 #include "llvm/Transforms/Scalar.h" 35 #include "llvm/Transforms/Scalar/LoopPassManager.h" 36 #include "llvm/Transforms/Utils.h" 37 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38 #include "llvm/Transforms/Utils/Local.h" 39 #include "llvm/Transforms/Utils/LoopUtils.h" 40 using namespace llvm; 41 42 #define DEBUG_TYPE "loop-simplifycfg" 43 44 static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding", 45 cl::init(true)); 46 47 STATISTIC(NumTerminatorsFolded, 48 "Number of terminators folded to unconditional branches"); 49 50 /// If \p BB is a switch or a conditional branch, but only one of its successors 51 /// can be reached from this block in runtime, return this successor. Otherwise, 52 /// return nullptr. 53 static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) { 54 Instruction *TI = BB->getTerminator(); 55 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 56 if (BI->isUnconditional()) 57 return nullptr; 58 if (BI->getSuccessor(0) == BI->getSuccessor(1)) 59 return BI->getSuccessor(0); 60 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition()); 61 if (!Cond) 62 return nullptr; 63 return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0); 64 } 65 66 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 67 auto *CI = dyn_cast<ConstantInt>(SI->getCondition()); 68 if (!CI) 69 return nullptr; 70 for (auto Case : SI->cases()) 71 if (Case.getCaseValue() == CI) 72 return Case.getCaseSuccessor(); 73 return SI->getDefaultDest(); 74 } 75 76 return nullptr; 77 } 78 79 /// Helper class that can turn branches and switches with constant conditions 80 /// into unconditional branches. 81 class ConstantTerminatorFoldingImpl { 82 private: 83 Loop &L; 84 LoopInfo &LI; 85 DominatorTree &DT; 86 MemorySSAUpdater *MSSAU; 87 88 // Whether or not the current loop will still exist after terminator constant 89 // folding will be done. In theory, there are two ways how it can happen: 90 // 1. Loop's latch(es) become unreachable from loop header; 91 // 2. Loop's header becomes unreachable from method entry. 92 // In practice, the second situation is impossible because we only modify the 93 // current loop and its preheader and do not affect preheader's reachibility 94 // from any other block. So this variable set to true means that loop's latch 95 // has become unreachable from loop header. 96 bool DeleteCurrentLoop = false; 97 98 // The blocks of the original loop that will still be reachable from entry 99 // after the constant folding. 100 SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks; 101 // The blocks of the original loop that will become unreachable from entry 102 // after the constant folding. 103 SmallPtrSet<BasicBlock *, 8> DeadLoopBlocks; 104 // The exits of the original loop that will still be reachable from entry 105 // after the constant folding. 106 SmallPtrSet<BasicBlock *, 8> LiveExitBlocks; 107 // The exits of the original loop that will become unreachable from entry 108 // after the constant folding. 109 SmallVector<BasicBlock *, 8> DeadExitBlocks; 110 // The blocks that will still be a part of the current loop after folding. 111 SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding; 112 // The blocks that have terminators with constant condition that can be 113 // folded. Note: fold candidates should be in L but not in any of its 114 // subloops to avoid complex LI updates. 115 SmallVector<BasicBlock *, 8> FoldCandidates; 116 117 void dump() const { 118 dbgs() << "Constant terminator folding for loop " << L << "\n"; 119 dbgs() << "After terminator constant-folding, the loop will"; 120 if (!DeleteCurrentLoop) 121 dbgs() << " not"; 122 dbgs() << " be destroyed\n"; 123 auto PrintOutVector = [&](const char *Message, 124 const SmallVectorImpl<BasicBlock *> &S) { 125 dbgs() << Message << "\n"; 126 for (const BasicBlock *BB : S) 127 dbgs() << "\t" << BB->getName() << "\n"; 128 }; 129 auto PrintOutSet = [&](const char *Message, 130 const SmallPtrSetImpl<BasicBlock *> &S) { 131 dbgs() << Message << "\n"; 132 for (const BasicBlock *BB : S) 133 dbgs() << "\t" << BB->getName() << "\n"; 134 }; 135 PrintOutVector("Blocks in which we can constant-fold terminator:", 136 FoldCandidates); 137 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks); 138 PrintOutSet("Dead blocks from the original loop:", DeadLoopBlocks); 139 PrintOutSet("Live exit blocks:", LiveExitBlocks); 140 PrintOutVector("Dead exit blocks:", DeadExitBlocks); 141 if (!DeleteCurrentLoop) 142 PrintOutSet("The following blocks will still be part of the loop:", 143 BlocksInLoopAfterFolding); 144 } 145 146 /// Fill all information about status of blocks and exits of the current loop 147 /// if constant folding of all branches will be done. 148 void analyze() { 149 LoopBlocksDFS DFS(&L); 150 DFS.perform(&LI); 151 assert(DFS.isComplete() && "DFS is expected to be finished"); 152 153 // Collect live and dead loop blocks and exits. 154 LiveLoopBlocks.insert(L.getHeader()); 155 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) { 156 BasicBlock *BB = *I; 157 158 // If a loop block wasn't marked as live so far, then it's dead. 159 if (!LiveLoopBlocks.count(BB)) { 160 DeadLoopBlocks.insert(BB); 161 continue; 162 } 163 164 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB); 165 166 // If a block has only one live successor, it's a candidate on constant 167 // folding. Only handle blocks from current loop: branches in child loops 168 // are skipped because if they can be folded, they should be folded during 169 // the processing of child loops. 170 if (TheOnlySucc && LI.getLoopFor(BB) == &L) 171 FoldCandidates.push_back(BB); 172 173 // Handle successors. 174 for (BasicBlock *Succ : successors(BB)) 175 if (!TheOnlySucc || TheOnlySucc == Succ) { 176 if (L.contains(Succ)) 177 LiveLoopBlocks.insert(Succ); 178 else 179 LiveExitBlocks.insert(Succ); 180 } 181 } 182 183 // Sanity check: amount of dead and live loop blocks should match the total 184 // number of blocks in loop. 185 assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() && 186 "Malformed block sets?"); 187 188 // Now, all exit blocks that are not marked as live are dead. 189 SmallVector<BasicBlock *, 8> ExitBlocks; 190 L.getExitBlocks(ExitBlocks); 191 for (auto *ExitBlock : ExitBlocks) 192 if (!LiveExitBlocks.count(ExitBlock)) 193 DeadExitBlocks.push_back(ExitBlock); 194 195 // Whether or not the edge From->To will still be present in graph after the 196 // folding. 197 auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) { 198 if (!LiveLoopBlocks.count(From)) 199 return false; 200 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From); 201 return !TheOnlySucc || TheOnlySucc == To; 202 }; 203 204 // The loop will not be destroyed if its latch is live. 205 DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader()); 206 207 // If we are going to delete the current loop completely, no extra analysis 208 // is needed. 209 if (DeleteCurrentLoop) 210 return; 211 212 // Otherwise, we should check which blocks will still be a part of the 213 // current loop after the transform. 214 BlocksInLoopAfterFolding.insert(L.getLoopLatch()); 215 // If the loop is live, then we should compute what blocks are still in 216 // loop after all branch folding has been done. A block is in loop if 217 // it has a live edge to another block that is in the loop; by definition, 218 // latch is in the loop. 219 auto BlockIsInLoop = [&](BasicBlock *BB) { 220 return any_of(successors(BB), [&](BasicBlock *Succ) { 221 return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ); 222 }); 223 }; 224 for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) { 225 BasicBlock *BB = *I; 226 if (BlockIsInLoop(BB)) 227 BlocksInLoopAfterFolding.insert(BB); 228 } 229 230 // Sanity check: header must be in loop. 231 assert(BlocksInLoopAfterFolding.count(L.getHeader()) && 232 "Header not in loop?"); 233 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() && 234 "All blocks that stay in loop should be live!"); 235 } 236 237 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the 238 /// unconditional branches. 239 void foldTerminators() { 240 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 241 242 for (BasicBlock *BB : FoldCandidates) { 243 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!"); 244 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB); 245 assert(TheOnlySucc && "Should have one live successor!"); 246 247 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName() 248 << " with an unconditional branch to the block " 249 << TheOnlySucc->getName() << "\n"); 250 251 SmallPtrSet<BasicBlock *, 2> DeadSuccessors; 252 // Remove all BB's successors except for the live one. 253 unsigned TheOnlySuccDuplicates = 0; 254 for (auto *Succ : successors(BB)) 255 if (Succ != TheOnlySucc) { 256 DeadSuccessors.insert(Succ); 257 // If our successor lies in a different loop, we don't want to remove 258 // the one-input Phi because it is a LCSSA Phi. 259 bool PreserveLCSSAPhi = !L.contains(Succ); 260 Succ->removePredecessor(BB, PreserveLCSSAPhi); 261 if (MSSAU) 262 MSSAU->removeEdge(BB, Succ); 263 } else 264 ++TheOnlySuccDuplicates; 265 266 assert(TheOnlySuccDuplicates > 0 && "Should be!"); 267 // If TheOnlySucc was BB's successor more than once, after transform it 268 // will be its successor only once. Remove redundant inputs from 269 // TheOnlySucc's Phis. 270 bool PreserveLCSSAPhi = !L.contains(TheOnlySucc); 271 for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup) 272 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi); 273 if (MSSAU && TheOnlySuccDuplicates > 1) 274 MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc); 275 276 IRBuilder<> Builder(BB->getContext()); 277 Instruction *Term = BB->getTerminator(); 278 Builder.SetInsertPoint(Term); 279 Builder.CreateBr(TheOnlySucc); 280 Term->eraseFromParent(); 281 282 for (auto *DeadSucc : DeadSuccessors) 283 DTU.deleteEdge(BB, DeadSucc); 284 285 ++NumTerminatorsFolded; 286 } 287 } 288 289 public: 290 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT, 291 MemorySSAUpdater *MSSAU) 292 : L(L), LI(LI), DT(DT), MSSAU(MSSAU) {} 293 bool run() { 294 assert(L.getLoopLatch() && "Should be single latch!"); 295 296 // Collect all available information about status of blocks after constant 297 // folding. 298 analyze(); 299 300 LLVM_DEBUG(dbgs() << "In function " << L.getHeader()->getParent()->getName() 301 << ": "); 302 303 // Nothing to constant-fold. 304 if (FoldCandidates.empty()) { 305 LLVM_DEBUG( 306 dbgs() << "No constant terminator folding candidates found in loop " 307 << L.getHeader()->getName() << "\n"); 308 return false; 309 } 310 311 // TODO: Support deletion of the current loop. 312 if (DeleteCurrentLoop) { 313 LLVM_DEBUG( 314 dbgs() 315 << "Give up constant terminator folding in loop " 316 << L.getHeader()->getName() 317 << ": we don't currently support deletion of the current loop.\n"); 318 return false; 319 } 320 321 // TODO: Support deletion of dead loop blocks. 322 if (!DeadLoopBlocks.empty()) { 323 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop " 324 << L.getHeader()->getName() 325 << ": we don't currently" 326 " support deletion of dead in-loop blocks.\n"); 327 return false; 328 } 329 330 // TODO: Support dead loop exits. 331 if (!DeadExitBlocks.empty()) { 332 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop " 333 << L.getHeader()->getName() 334 << ": we don't currently support dead loop exits.\n"); 335 return false; 336 } 337 338 // TODO: Support blocks that are not dead, but also not in loop after the 339 // folding. 340 if (BlocksInLoopAfterFolding.size() != L.getNumBlocks()) { 341 LLVM_DEBUG( 342 dbgs() << "Give up constant terminator folding in loop " 343 << L.getHeader()->getName() 344 << ": we don't currently" 345 " support blocks that are not dead, but will stop " 346 "being a part of the loop after constant-folding.\n"); 347 return false; 348 } 349 350 // Dump analysis results. 351 LLVM_DEBUG(dump()); 352 353 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size() 354 << " terminators in loop " << L.getHeader()->getName() 355 << "\n"); 356 357 // Make the actual transforms. 358 foldTerminators(); 359 360 #ifndef NDEBUG 361 // Make sure that we have preserved all data structures after the transform. 362 DT.verify(); 363 assert(DT.isReachableFromEntry(L.getHeader())); 364 LI.verify(DT); 365 #endif 366 367 return true; 368 } 369 }; 370 371 /// Turn branches and switches with known constant conditions into unconditional 372 /// branches. 373 static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI, 374 MemorySSAUpdater *MSSAU) { 375 if (!EnableTermFolding) 376 return false; 377 378 // To keep things simple, only process loops with single latch. We 379 // canonicalize most loops to this form. We can support multi-latch if needed. 380 if (!L.getLoopLatch()) 381 return false; 382 383 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, MSSAU); 384 return BranchFolder.run(); 385 } 386 387 static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT, 388 LoopInfo &LI, MemorySSAUpdater *MSSAU) { 389 bool Changed = false; 390 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 391 // Copy blocks into a temporary array to avoid iterator invalidation issues 392 // as we remove them. 393 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks()); 394 395 for (auto &Block : Blocks) { 396 // Attempt to merge blocks in the trivial case. Don't modify blocks which 397 // belong to other loops. 398 BasicBlock *Succ = cast_or_null<BasicBlock>(Block); 399 if (!Succ) 400 continue; 401 402 BasicBlock *Pred = Succ->getSinglePredecessor(); 403 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L) 404 continue; 405 406 // Merge Succ into Pred and delete it. 407 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU); 408 409 Changed = true; 410 } 411 412 return Changed; 413 } 414 415 static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI, 416 ScalarEvolution &SE, MemorySSAUpdater *MSSAU) { 417 bool Changed = false; 418 419 // Constant-fold terminators with known constant conditions. 420 Changed |= constantFoldTerminators(L, DT, LI, MSSAU); 421 422 // Eliminate unconditional branches by merging blocks into their predecessors. 423 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU); 424 425 if (Changed) 426 SE.forgetTopmostLoop(&L); 427 428 return Changed; 429 } 430 431 PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM, 432 LoopStandardAnalysisResults &AR, 433 LPMUpdater &) { 434 Optional<MemorySSAUpdater> MSSAU; 435 if (EnableMSSALoopDependency && AR.MSSA) 436 MSSAU = MemorySSAUpdater(AR.MSSA); 437 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE, 438 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr)) 439 return PreservedAnalyses::all(); 440 441 return getLoopPassPreservedAnalyses(); 442 } 443 444 namespace { 445 class LoopSimplifyCFGLegacyPass : public LoopPass { 446 public: 447 static char ID; // Pass ID, replacement for typeid 448 LoopSimplifyCFGLegacyPass() : LoopPass(ID) { 449 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry()); 450 } 451 452 bool runOnLoop(Loop *L, LPPassManager &) override { 453 if (skipLoop(L)) 454 return false; 455 456 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 457 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 458 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 459 Optional<MemorySSAUpdater> MSSAU; 460 if (EnableMSSALoopDependency) { 461 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA(); 462 MSSAU = MemorySSAUpdater(MSSA); 463 if (VerifyMemorySSA) 464 MSSA->verifyMemorySSA(); 465 } 466 return simplifyLoopCFG(*L, DT, LI, SE, 467 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr); 468 } 469 470 void getAnalysisUsage(AnalysisUsage &AU) const override { 471 if (EnableMSSALoopDependency) { 472 AU.addRequired<MemorySSAWrapperPass>(); 473 AU.addPreserved<MemorySSAWrapperPass>(); 474 } 475 AU.addPreserved<DependenceAnalysisWrapperPass>(); 476 getLoopAnalysisUsage(AU); 477 } 478 }; 479 } 480 481 char LoopSimplifyCFGLegacyPass::ID = 0; 482 INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg", 483 "Simplify loop CFG", false, false) 484 INITIALIZE_PASS_DEPENDENCY(LoopPass) 485 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 486 INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg", 487 "Simplify loop CFG", false, false) 488 489 Pass *llvm::createLoopSimplifyCFGPass() { 490 return new LoopSimplifyCFGLegacyPass(); 491 } 492