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