blob: 0db5d9e772d623d4fd16a522fafe179db5fee08d [file] [log] [blame]
Fiona Glaserb417d462016-01-29 22:35:36 +00001//===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification Pass ---------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Fiona Glaserb417d462016-01-29 22:35:36 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Loop SimplifyCFG Pass. This pass is responsible for
10// basic loop CFG cleanup, primarily to assist other loop passes. If you
11// encounter a noncanonical CFG construct that causes another loop pass to
12// perform suboptimally, this is the place to fix it up.
13//
14//===----------------------------------------------------------------------===//
15
Justin Bognerab6a5132016-05-03 21:47:32 +000016#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000020#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000021#include "llvm/Analysis/BasicAliasAnalysis.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000022#include "llvm/Analysis/DependenceAnalysis.h"
Richard Trieu5f436fc2019-02-06 02:52:52 +000023#include "llvm/Analysis/DomTreeUpdater.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000024#include "llvm/Analysis/GlobalsModRef.h"
25#include "llvm/Analysis/LoopInfo.h"
26#include "llvm/Analysis/LoopPass.h"
Alina Sbirlea8b83d682018-08-22 20:10:21 +000027#include "llvm/Analysis/MemorySSA.h"
28#include "llvm/Analysis/MemorySSAUpdater.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000029#include "llvm/Analysis/ScalarEvolution.h"
30#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
31#include "llvm/Analysis/TargetTransformInfo.h"
32#include "llvm/IR/Dominators.h"
Justin Bognerab6a5132016-05-03 21:47:32 +000033#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000034#include "llvm/Transforms/Scalar/LoopPassManager.h"
David Blaikiea373d182018-03-28 17:44:36 +000035#include "llvm/Transforms/Utils.h"
Alina Sbirleadfd14ad2018-06-20 22:01:04 +000036#include "llvm/Transforms/Utils/BasicBlockUtils.h"
37#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000038#include "llvm/Transforms/Utils/LoopUtils.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000039using namespace llvm;
40
41#define DEBUG_TYPE "loop-simplifycfg"
42
Max Kazantseve1c2dc22018-11-23 09:14:53 +000043static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
Max Kazantsev5cf777e2019-02-13 06:12:48 +000044 cl::init(true));
Max Kazantseve1c2dc22018-11-23 09:14:53 +000045
Max Kazantsevc04b5302018-11-20 05:43:32 +000046STATISTIC(NumTerminatorsFolded,
47 "Number of terminators folded to unconditional branches");
Max Kazantsev347c5832018-12-24 06:06:17 +000048STATISTIC(NumLoopBlocksDeleted,
49 "Number of loop blocks deleted");
Max Kazantsevedabb9a2018-12-24 07:41:33 +000050STATISTIC(NumLoopExitsDeleted,
51 "Number of loop exiting edges deleted");
Max Kazantsevc04b5302018-11-20 05:43:32 +000052
53/// If \p BB is a switch or a conditional branch, but only one of its successors
54/// can be reached from this block in runtime, return this successor. Otherwise,
55/// return nullptr.
56static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {
57 Instruction *TI = BB->getTerminator();
58 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
59 if (BI->isUnconditional())
60 return nullptr;
61 if (BI->getSuccessor(0) == BI->getSuccessor(1))
62 return BI->getSuccessor(0);
63 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
64 if (!Cond)
65 return nullptr;
66 return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
67 }
68
69 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
70 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
71 if (!CI)
72 return nullptr;
73 for (auto Case : SI->cases())
74 if (Case.getCaseValue() == CI)
75 return Case.getCaseSuccessor();
76 return SI->getDefaultDest();
77 }
78
79 return nullptr;
80}
81
Max Kazantsevc065b022019-02-15 12:18:10 +000082/// Removes \p BB from all loops from [FirstLoop, LastLoop) in parent chain.
83static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop,
84 Loop *LastLoop = nullptr) {
85 assert((!LastLoop || LastLoop->contains(FirstLoop->getHeader())) &&
86 "First loop is supposed to be inside of last loop!");
87 assert(FirstLoop->contains(BB) && "Must be a loop block!");
88 for (Loop *Current = FirstLoop; Current != LastLoop;
89 Current = Current->getParentLoop())
90 Current->removeBlockFromLoop(BB);
91}
92
Benjamin Kramerb17d2132019-01-12 18:36:22 +000093namespace {
Max Kazantsevc04b5302018-11-20 05:43:32 +000094/// Helper class that can turn branches and switches with constant conditions
95/// into unconditional branches.
96class ConstantTerminatorFoldingImpl {
97private:
98 Loop &L;
99 LoopInfo &LI;
100 DominatorTree &DT;
Max Kazantsev201534d2018-12-29 04:26:22 +0000101 ScalarEvolution &SE;
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000102 MemorySSAUpdater *MSSAU;
Max Kazantsev136f09b2019-02-15 11:39:35 +0000103 LoopBlocksDFS DFS;
Simon Pilgrim623c38d2019-02-15 12:13:16 +0000104 DomTreeUpdater DTU;
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000105 SmallVector<DominatorTree::UpdateType, 16> DTUpdates;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000106
Max Kazantseva523a212018-12-07 05:44:45 +0000107 // Whether or not the current loop has irreducible CFG.
108 bool HasIrreducibleCFG = false;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000109 // Whether or not the current loop will still exist after terminator constant
110 // folding will be done. In theory, there are two ways how it can happen:
111 // 1. Loop's latch(es) become unreachable from loop header;
112 // 2. Loop's header becomes unreachable from method entry.
113 // In practice, the second situation is impossible because we only modify the
114 // current loop and its preheader and do not affect preheader's reachibility
115 // from any other block. So this variable set to true means that loop's latch
116 // has become unreachable from loop header.
117 bool DeleteCurrentLoop = false;
118
119 // The blocks of the original loop that will still be reachable from entry
120 // after the constant folding.
121 SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
122 // The blocks of the original loop that will become unreachable from entry
123 // after the constant folding.
Max Kazantsev80e4b402018-12-28 06:08:51 +0000124 SmallVector<BasicBlock *, 8> DeadLoopBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000125 // The exits of the original loop that will still be reachable from entry
126 // after the constant folding.
127 SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
128 // The exits of the original loop that will become unreachable from entry
129 // after the constant folding.
Max Kazantsev56a24432018-11-22 12:33:41 +0000130 SmallVector<BasicBlock *, 8> DeadExitBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000131 // The blocks that will still be a part of the current loop after folding.
132 SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
133 // The blocks that have terminators with constant condition that can be
134 // folded. Note: fold candidates should be in L but not in any of its
135 // subloops to avoid complex LI updates.
136 SmallVector<BasicBlock *, 8> FoldCandidates;
137
138 void dump() const {
139 dbgs() << "Constant terminator folding for loop " << L << "\n";
140 dbgs() << "After terminator constant-folding, the loop will";
141 if (!DeleteCurrentLoop)
142 dbgs() << " not";
143 dbgs() << " be destroyed\n";
Max Kazantsev56a24432018-11-22 12:33:41 +0000144 auto PrintOutVector = [&](const char *Message,
145 const SmallVectorImpl<BasicBlock *> &S) {
146 dbgs() << Message << "\n";
147 for (const BasicBlock *BB : S)
148 dbgs() << "\t" << BB->getName() << "\n";
149 };
Max Kazantsevc04b5302018-11-20 05:43:32 +0000150 auto PrintOutSet = [&](const char *Message,
151 const SmallPtrSetImpl<BasicBlock *> &S) {
152 dbgs() << Message << "\n";
153 for (const BasicBlock *BB : S)
154 dbgs() << "\t" << BB->getName() << "\n";
155 };
Max Kazantsev56a24432018-11-22 12:33:41 +0000156 PrintOutVector("Blocks in which we can constant-fold terminator:",
157 FoldCandidates);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000158 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
Max Kazantsev80e4b402018-12-28 06:08:51 +0000159 PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000160 PrintOutSet("Live exit blocks:", LiveExitBlocks);
Max Kazantsev56a24432018-11-22 12:33:41 +0000161 PrintOutVector("Dead exit blocks:", DeadExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000162 if (!DeleteCurrentLoop)
163 PrintOutSet("The following blocks will still be part of the loop:",
164 BlocksInLoopAfterFolding);
165 }
166
Max Kazantseva523a212018-12-07 05:44:45 +0000167 /// Whether or not the current loop has irreducible CFG.
168 bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
169 assert(DFS.isComplete() && "DFS is expected to be finished");
170 // Index of a basic block in RPO traversal.
171 DenseMap<const BasicBlock *, unsigned> RPO;
172 unsigned Current = 0;
173 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
174 RPO[*I] = Current++;
175
176 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
177 BasicBlock *BB = *I;
178 for (auto *Succ : successors(BB))
179 if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
180 // If an edge goes from a block with greater order number into a block
181 // with lesses number, and it is not a loop backedge, then it can only
182 // be a part of irreducible non-loop cycle.
183 return true;
184 }
185 return false;
186 }
187
Max Kazantsevc04b5302018-11-20 05:43:32 +0000188 /// Fill all information about status of blocks and exits of the current loop
189 /// if constant folding of all branches will be done.
190 void analyze() {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000191 DFS.perform(&LI);
192 assert(DFS.isComplete() && "DFS is expected to be finished");
193
Max Kazantseva523a212018-12-07 05:44:45 +0000194 // TODO: The algorithm below relies on both RPO and Postorder traversals.
195 // When the loop has only reducible CFG inside, then the invariant "all
196 // predecessors of X are processed before X in RPO" is preserved. However
197 // an irreducible loop can break this invariant (e.g. latch does not have to
198 // be the last block in the traversal in this case, and the algorithm relies
199 // on this). We can later decide to support such cases by altering the
200 // algorithms, but so far we just give up analyzing them.
201 if (hasIrreducibleCFG(DFS)) {
202 HasIrreducibleCFG = true;
203 return;
204 }
205
Max Kazantsevc04b5302018-11-20 05:43:32 +0000206 // Collect live and dead loop blocks and exits.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000207 LiveLoopBlocks.insert(L.getHeader());
208 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
209 BasicBlock *BB = *I;
210
211 // If a loop block wasn't marked as live so far, then it's dead.
212 if (!LiveLoopBlocks.count(BB)) {
Max Kazantsev80e4b402018-12-28 06:08:51 +0000213 DeadLoopBlocks.push_back(BB);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000214 continue;
215 }
216
217 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
218
219 // If a block has only one live successor, it's a candidate on constant
220 // folding. Only handle blocks from current loop: branches in child loops
221 // are skipped because if they can be folded, they should be folded during
222 // the processing of child loops.
Max Kazantsev56515a22019-01-24 05:20:29 +0000223 bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
224 if (TakeFoldCandidate)
Max Kazantsevc04b5302018-11-20 05:43:32 +0000225 FoldCandidates.push_back(BB);
226
227 // Handle successors.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000228 for (BasicBlock *Succ : successors(BB))
Max Kazantsev56515a22019-01-24 05:20:29 +0000229 if (!TakeFoldCandidate || TheOnlySucc == Succ) {
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000230 if (L.contains(Succ))
231 LiveLoopBlocks.insert(Succ);
232 else
233 LiveExitBlocks.insert(Succ);
234 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000235 }
236
237 // Sanity check: amount of dead and live loop blocks should match the total
238 // number of blocks in loop.
239 assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
240 "Malformed block sets?");
241
242 // Now, all exit blocks that are not marked as live are dead.
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000243 SmallVector<BasicBlock *, 8> ExitBlocks;
244 L.getExitBlocks(ExitBlocks);
Max Kazantseva4ccfc12019-02-06 07:49:17 +0000245 SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000246 for (auto *ExitBlock : ExitBlocks)
Max Kazantseva4ccfc12019-02-06 07:49:17 +0000247 if (!LiveExitBlocks.count(ExitBlock) &&
248 UniqueDeadExits.insert(ExitBlock).second)
Max Kazantsev56a24432018-11-22 12:33:41 +0000249 DeadExitBlocks.push_back(ExitBlock);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000250
251 // Whether or not the edge From->To will still be present in graph after the
252 // folding.
253 auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
254 if (!LiveLoopBlocks.count(From))
255 return false;
256 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
Max Kazantsev38cd9ac2019-01-25 05:05:02 +0000257 return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000258 };
259
260 // The loop will not be destroyed if its latch is live.
261 DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
262
263 // If we are going to delete the current loop completely, no extra analysis
264 // is needed.
265 if (DeleteCurrentLoop)
266 return;
267
268 // Otherwise, we should check which blocks will still be a part of the
269 // current loop after the transform.
270 BlocksInLoopAfterFolding.insert(L.getLoopLatch());
271 // If the loop is live, then we should compute what blocks are still in
272 // loop after all branch folding has been done. A block is in loop if
273 // it has a live edge to another block that is in the loop; by definition,
274 // latch is in the loop.
275 auto BlockIsInLoop = [&](BasicBlock *BB) {
276 return any_of(successors(BB), [&](BasicBlock *Succ) {
277 return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
278 });
279 };
280 for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
281 BasicBlock *BB = *I;
282 if (BlockIsInLoop(BB))
283 BlocksInLoopAfterFolding.insert(BB);
284 }
285
286 // Sanity check: header must be in loop.
287 assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
288 "Header not in loop?");
Max Kazantsevb565e602018-11-22 12:43:27 +0000289 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
290 "All blocks that stay in loop should be live!");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000291 }
292
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000293 /// We need to preserve static reachibility of all loop exit blocks (this is)
294 /// required by loop pass manager. In order to do it, we make the following
295 /// trick:
296 ///
297 /// preheader:
298 /// <preheader code>
299 /// br label %loop_header
300 ///
301 /// loop_header:
302 /// ...
303 /// br i1 false, label %dead_exit, label %loop_block
304 /// ...
305 ///
306 /// We cannot simply remove edge from the loop to dead exit because in this
307 /// case dead_exit (and its successors) may become unreachable. To avoid that,
308 /// we insert the following fictive preheader:
309 ///
310 /// preheader:
311 /// <preheader code>
312 /// switch i32 0, label %preheader-split,
313 /// [i32 1, label %dead_exit_1],
314 /// [i32 2, label %dead_exit_2],
315 /// ...
316 /// [i32 N, label %dead_exit_N],
317 ///
318 /// preheader-split:
319 /// br label %loop_header
320 ///
321 /// loop_header:
322 /// ...
323 /// br i1 false, label %dead_exit_N, label %loop_block
324 /// ...
325 ///
326 /// Doing so, we preserve static reachibility of all dead exits and can later
327 /// remove edges from the loop to these blocks.
328 void handleDeadExits() {
329 // If no dead exits, nothing to do.
330 if (DeadExitBlocks.empty())
331 return;
332
333 // Construct split preheader and the dummy switch to thread edges from it to
334 // dead exits.
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000335 BasicBlock *Preheader = L.getLoopPreheader();
336 BasicBlock *NewPreheader = Preheader->splitBasicBlock(
337 Preheader->getTerminator(),
338 Twine(Preheader->getName()).concat("-split"));
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000339 DTUpdates.push_back({DominatorTree::Delete, Preheader, L.getHeader()});
340 DTUpdates.push_back({DominatorTree::Insert, NewPreheader, L.getHeader()});
341 DTUpdates.push_back({DominatorTree::Insert, Preheader, NewPreheader});
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000342 IRBuilder<> Builder(Preheader->getTerminator());
343 SwitchInst *DummySwitch =
344 Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
345 Preheader->getTerminator()->eraseFromParent();
346
347 unsigned DummyIdx = 1;
348 for (BasicBlock *BB : DeadExitBlocks) {
349 SmallVector<Instruction *, 4> DeadPhis;
350 for (auto &PN : BB->phis())
351 DeadPhis.push_back(&PN);
352
353 // Eliminate all Phis from dead exits.
354 for (Instruction *PN : DeadPhis) {
355 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
356 PN->eraseFromParent();
357 }
358 assert(DummyIdx != 0 && "Too many dead exits!");
359 DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000360 DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000361 ++NumLoopExitsDeleted;
362 }
363
364 assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
365 if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
366 OuterLoop->addBasicBlockToLoop(NewPreheader, LI);
367
368 // When we break dead edges, the outer loop may become unreachable from
369 // the current loop. We need to fix loop info accordingly. For this, we
370 // find the most nested loop that still contains L and remove L from all
371 // loops that are inside of it.
372 Loop *StillReachable = nullptr;
373 for (BasicBlock *BB : LiveExitBlocks) {
374 Loop *BBL = LI.getLoopFor(BB);
375 if (BBL && BBL->contains(L.getHeader()))
376 if (!StillReachable ||
377 BBL->getLoopDepth() > StillReachable->getLoopDepth())
378 StillReachable = BBL;
379 }
380
381 // Okay, our loop is no longer in the outer loop (and maybe not in some of
382 // its parents as well). Make the fixup.
383 if (StillReachable != OuterLoop) {
384 LI.changeLoopFor(NewPreheader, StillReachable);
Max Kazantsevc065b022019-02-15 12:18:10 +0000385 removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);
386 for (auto *BB : L.blocks())
387 removeBlockFromLoops(BB, OuterLoop, StillReachable);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000388 OuterLoop->removeChildLoop(&L);
389 if (StillReachable)
390 StillReachable->addChildLoop(&L);
391 else
392 LI.addTopLevelLoop(&L);
Max Kazantsev61a8d3f2019-01-17 12:51:10 +0000393
394 // Some values from loops in [OuterLoop, StillReachable) could be used
395 // in the current loop. Now it is not their child anymore, so such uses
396 // require LCSSA Phis.
397 Loop *FixLCSSALoop = OuterLoop;
398 while (FixLCSSALoop->getParentLoop() != StillReachable)
399 FixLCSSALoop = FixLCSSALoop->getParentLoop();
400 assert(FixLCSSALoop && "Should be a loop!");
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000401 // We need all DT updates to be done before forming LCSSA.
402 DTU.applyUpdates(DTUpdates);
403 DTUpdates.clear();
Max Kazantsev61a8d3f2019-01-17 12:51:10 +0000404 formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000405 }
406 }
407 }
408
Max Kazantsev347c5832018-12-24 06:06:17 +0000409 /// Delete loop blocks that have become unreachable after folding. Make all
410 /// relevant updates to DT and LI.
411 void deleteDeadLoopBlocks() {
Max Kazantsev80e4b402018-12-28 06:08:51 +0000412 if (MSSAU) {
413 SmallPtrSet<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
414 DeadLoopBlocks.end());
415 MSSAU->removeBlocks(DeadLoopBlocksSet);
416 }
Max Kazantsevbf6af8f2019-02-12 09:37:00 +0000417
418 // The function LI.erase has some invariants that need to be preserved when
419 // it tries to remove a loop which is not the top-level loop. In particular,
420 // it requires loop's preheader to be strictly in loop's parent. We cannot
421 // just remove blocks one by one, because after removal of preheader we may
422 // break this invariant for the dead loop. So we detatch and erase all dead
423 // loops beforehand.
424 for (auto *BB : DeadLoopBlocks)
425 if (LI.isLoopHeader(BB)) {
426 assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
427 Loop *DL = LI.getLoopFor(BB);
428 if (DL->getParentLoop()) {
429 for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
430 for (auto *BB : DL->getBlocks())
431 PL->removeBlockFromLoop(BB);
432 DL->getParentLoop()->removeChildLoop(DL);
433 LI.addTopLevelLoop(DL);
434 }
435 LI.erase(DL);
436 }
437
Max Kazantsev347c5832018-12-24 06:06:17 +0000438 for (auto *BB : DeadLoopBlocks) {
439 assert(BB != L.getHeader() &&
440 "Header of the current loop cannot be dead!");
441 LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
442 << "\n");
Max Kazantsev347c5832018-12-24 06:06:17 +0000443 LI.removeBlock(BB);
Max Kazantsev347c5832018-12-24 06:06:17 +0000444 }
Max Kazantsev8b134162019-01-17 12:25:40 +0000445
Max Kazantsev6bf86152019-02-12 07:48:07 +0000446 DetatchDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000447 DTU.applyUpdates(DTUpdates);
448 DTUpdates.clear();
449 for (auto *BB : DeadLoopBlocks)
Max Kazantsev9aae9da2019-02-12 08:10:29 +0000450 DTU.deleteBB(BB);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000451
Max Kazantsev8b134162019-01-17 12:25:40 +0000452 NumLoopBlocksDeleted += DeadLoopBlocks.size();
Max Kazantsev347c5832018-12-24 06:06:17 +0000453 }
454
Max Kazantsevc04b5302018-11-20 05:43:32 +0000455 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
456 /// unconditional branches.
457 void foldTerminators() {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000458 for (BasicBlock *BB : FoldCandidates) {
459 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
460 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
461 assert(TheOnlySucc && "Should have one live successor!");
462
463 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
464 << " with an unconditional branch to the block "
465 << TheOnlySucc->getName() << "\n");
466
467 SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
468 // Remove all BB's successors except for the live one.
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000469 unsigned TheOnlySuccDuplicates = 0;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000470 for (auto *Succ : successors(BB))
471 if (Succ != TheOnlySucc) {
472 DeadSuccessors.insert(Succ);
Max Kazantsevcb8e2402018-11-23 07:56:47 +0000473 // If our successor lies in a different loop, we don't want to remove
474 // the one-input Phi because it is a LCSSA Phi.
475 bool PreserveLCSSAPhi = !L.contains(Succ);
476 Succ->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000477 if (MSSAU)
478 MSSAU->removeEdge(BB, Succ);
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000479 } else
480 ++TheOnlySuccDuplicates;
481
482 assert(TheOnlySuccDuplicates > 0 && "Should be!");
483 // If TheOnlySucc was BB's successor more than once, after transform it
484 // will be its successor only once. Remove redundant inputs from
485 // TheOnlySucc's Phis.
486 bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
487 for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
488 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000489 if (MSSAU && TheOnlySuccDuplicates > 1)
490 MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000491
492 IRBuilder<> Builder(BB->getContext());
493 Instruction *Term = BB->getTerminator();
494 Builder.SetInsertPoint(Term);
495 Builder.CreateBr(TheOnlySucc);
496 Term->eraseFromParent();
497
498 for (auto *DeadSucc : DeadSuccessors)
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000499 DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
Max Kazantsevc04b5302018-11-20 05:43:32 +0000500
501 ++NumTerminatorsFolded;
502 }
503 }
504
505public:
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000506 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
Max Kazantsev201534d2018-12-29 04:26:22 +0000507 ScalarEvolution &SE,
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000508 MemorySSAUpdater *MSSAU)
Max Kazantsev136f09b2019-02-15 11:39:35 +0000509 : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000510 DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}
Max Kazantsevc04b5302018-11-20 05:43:32 +0000511 bool run() {
512 assert(L.getLoopLatch() && "Should be single latch!");
513
514 // Collect all available information about status of blocks after constant
515 // folding.
516 analyze();
517
518 LLVM_DEBUG(dbgs() << "In function " << L.getHeader()->getParent()->getName()
519 << ": ");
520
Max Kazantseva523a212018-12-07 05:44:45 +0000521 if (HasIrreducibleCFG) {
522 LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
523 return false;
524 }
525
Max Kazantsevc04b5302018-11-20 05:43:32 +0000526 // Nothing to constant-fold.
527 if (FoldCandidates.empty()) {
528 LLVM_DEBUG(
529 dbgs() << "No constant terminator folding candidates found in loop "
530 << L.getHeader()->getName() << "\n");
531 return false;
532 }
533
534 // TODO: Support deletion of the current loop.
535 if (DeleteCurrentLoop) {
536 LLVM_DEBUG(
537 dbgs()
538 << "Give up constant terminator folding in loop "
539 << L.getHeader()->getName()
540 << ": we don't currently support deletion of the current loop.\n");
541 return false;
542 }
543
Max Kazantsevc04b5302018-11-20 05:43:32 +0000544 // TODO: Support blocks that are not dead, but also not in loop after the
545 // folding.
Max Kazantsev347c5832018-12-24 06:06:17 +0000546 if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
547 L.getNumBlocks()) {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000548 LLVM_DEBUG(
549 dbgs() << "Give up constant terminator folding in loop "
550 << L.getHeader()->getName()
551 << ": we don't currently"
552 " support blocks that are not dead, but will stop "
553 "being a part of the loop after constant-folding.\n");
554 return false;
555 }
556
Max Kazantsev201534d2018-12-29 04:26:22 +0000557 SE.forgetTopmostLoop(&L);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000558 // Dump analysis results.
559 LLVM_DEBUG(dump());
560
561 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
562 << " terminators in loop " << L.getHeader()->getName()
563 << "\n");
564
565 // Make the actual transforms.
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000566 handleDeadExits();
Max Kazantsevc04b5302018-11-20 05:43:32 +0000567 foldTerminators();
568
Max Kazantsev347c5832018-12-24 06:06:17 +0000569 if (!DeadLoopBlocks.empty()) {
570 LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
571 << " dead blocks in loop " << L.getHeader()->getName()
572 << "\n");
573 deleteDeadLoopBlocks();
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000574 } else {
575 // If we didn't do updates inside deleteDeadLoopBlocks, do them here.
576 DTU.applyUpdates(DTUpdates);
577 DTUpdates.clear();
Max Kazantsev347c5832018-12-24 06:06:17 +0000578 }
579
Max Kazantsevc04b5302018-11-20 05:43:32 +0000580#ifndef NDEBUG
581 // Make sure that we have preserved all data structures after the transform.
Max Kazantsev365021c2019-01-30 12:32:19 +0000582 assert(DT.verify() && "DT broken after transform!");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000583 assert(DT.isReachableFromEntry(L.getHeader()));
584 LI.verify(DT);
585#endif
586
587 return true;
588 }
589};
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000590} // namespace
Max Kazantsevc04b5302018-11-20 05:43:32 +0000591
592/// Turn branches and switches with known constant conditions into unconditional
593/// branches.
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000594static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
Max Kazantsev201534d2018-12-29 04:26:22 +0000595 ScalarEvolution &SE,
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000596 MemorySSAUpdater *MSSAU) {
Max Kazantseve1c2dc22018-11-23 09:14:53 +0000597 if (!EnableTermFolding)
598 return false;
599
Max Kazantsevc04b5302018-11-20 05:43:32 +0000600 // To keep things simple, only process loops with single latch. We
601 // canonicalize most loops to this form. We can support multi-latch if needed.
602 if (!L.getLoopLatch())
603 return false;
604
Max Kazantsev201534d2018-12-29 04:26:22 +0000605 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000606 return BranchFolder.run();
607}
608
Max Kazantsev46955b52018-11-01 09:42:50 +0000609static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
610 LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Fiona Glaserb417d462016-01-29 22:35:36 +0000611 bool Changed = false;
Chijun Sima21a8b602018-08-03 05:08:17 +0000612 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Fiona Glaserb417d462016-01-29 22:35:36 +0000613 // Copy blocks into a temporary array to avoid iterator invalidation issues
614 // as we remove them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000615 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
Fiona Glaserb417d462016-01-29 22:35:36 +0000616
617 for (auto &Block : Blocks) {
618 // Attempt to merge blocks in the trivial case. Don't modify blocks which
619 // belong to other loops.
Fiona Glaser36e82302016-01-29 23:12:52 +0000620 BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
Fiona Glaserb417d462016-01-29 22:35:36 +0000621 if (!Succ)
622 continue;
623
624 BasicBlock *Pred = Succ->getSinglePredecessor();
Justin Bognerab6a5132016-05-03 21:47:32 +0000625 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
Fiona Glaserb417d462016-01-29 22:35:36 +0000626 continue;
627
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000628 // Merge Succ into Pred and delete it.
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000629 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
David Greene6a9c242018-06-19 09:43:36 +0000630
Fiona Glaserb417d462016-01-29 22:35:36 +0000631 Changed = true;
632 }
633
634 return Changed;
635}
636
Max Kazantsev46955b52018-11-01 09:42:50 +0000637static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
638 ScalarEvolution &SE, MemorySSAUpdater *MSSAU) {
639 bool Changed = false;
640
Max Kazantsevc04b5302018-11-20 05:43:32 +0000641 // Constant-fold terminators with known constant conditions.
Max Kazantsev201534d2018-12-29 04:26:22 +0000642 Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000643
Max Kazantsev46955b52018-11-01 09:42:50 +0000644 // Eliminate unconditional branches by merging blocks into their predecessors.
645 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
646
647 if (Changed)
648 SE.forgetTopmostLoop(&L);
649
650 return Changed;
651}
652
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000653PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
654 LoopStandardAnalysisResults &AR,
655 LPMUpdater &) {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000656 Optional<MemorySSAUpdater> MSSAU;
657 if (EnableMSSALoopDependency && AR.MSSA)
658 MSSAU = MemorySSAUpdater(AR.MSSA);
659 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
660 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
Justin Bognerab6a5132016-05-03 21:47:32 +0000661 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000662
Justin Bognerab6a5132016-05-03 21:47:32 +0000663 return getLoopPassPreservedAnalyses();
664}
665
666namespace {
667class LoopSimplifyCFGLegacyPass : public LoopPass {
668public:
669 static char ID; // Pass ID, replacement for typeid
670 LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
671 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
672 }
673
674 bool runOnLoop(Loop *L, LPPassManager &) override {
675 if (skipLoop(L))
676 return false;
677
678 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
679 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
David Greene6a9c242018-06-19 09:43:36 +0000680 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000681 Optional<MemorySSAUpdater> MSSAU;
682 if (EnableMSSALoopDependency) {
683 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
684 MSSAU = MemorySSAUpdater(MSSA);
685 if (VerifyMemorySSA)
686 MSSA->verifyMemorySSA();
687 }
688 return simplifyLoopCFG(*L, DT, LI, SE,
689 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
Justin Bognerab6a5132016-05-03 21:47:32 +0000690 }
691
692 void getAnalysisUsage(AnalysisUsage &AU) const override {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000693 if (EnableMSSALoopDependency) {
694 AU.addRequired<MemorySSAWrapperPass>();
695 AU.addPreserved<MemorySSAWrapperPass>();
696 }
Chandler Carruth49c22192016-05-12 22:19:39 +0000697 AU.addPreserved<DependenceAnalysisWrapperPass>();
Justin Bognerab6a5132016-05-03 21:47:32 +0000698 getLoopAnalysisUsage(AU);
699 }
700};
701}
702
703char LoopSimplifyCFGLegacyPass::ID = 0;
704INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
705 "Simplify loop CFG", false, false)
706INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000707INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Justin Bognerab6a5132016-05-03 21:47:32 +0000708INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
709 "Simplify loop CFG", false, false)
710
711Pass *llvm::createLoopSimplifyCFGPass() {
712 return new LoopSimplifyCFGLegacyPass();
Fiona Glaserb417d462016-01-29 22:35:36 +0000713}