blob: bbf35513416904f91241847c2bd8048beadf1933 [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
Max Kazantsevd72c1a02019-02-17 15:22:48 +000093/// Find innermost loop that contains at least one block from \p BBs and
94/// contains the header of loop \p L.
95static Loop *getInnermostLoopFor(SmallPtrSetImpl<BasicBlock *> &BBs,
96 Loop &L, LoopInfo &LI) {
Max Kazantsev45614752019-02-17 18:21:51 +000097 Loop *Innermost = nullptr;
Max Kazantsev0f943262019-02-17 15:04:09 +000098 for (BasicBlock *BB : BBs) {
99 Loop *BBL = LI.getLoopFor(BB);
Max Kazantsev45614752019-02-17 18:21:51 +0000100 while (BBL && !BBL->contains(L.getHeader()))
101 BBL = BBL->getParentLoop();
102 if (BBL == &L)
103 BBL = BBL->getParentLoop();
104 if (!BBL)
105 continue;
106 if (!Innermost || BBL->getLoopDepth() > Innermost->getLoopDepth())
107 Innermost = BBL;
Max Kazantsev0f943262019-02-17 15:04:09 +0000108 }
Max Kazantsev45614752019-02-17 18:21:51 +0000109 return Innermost;
Max Kazantsev0f943262019-02-17 15:04:09 +0000110}
111
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000112namespace {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000113/// Helper class that can turn branches and switches with constant conditions
114/// into unconditional branches.
115class ConstantTerminatorFoldingImpl {
116private:
117 Loop &L;
118 LoopInfo &LI;
119 DominatorTree &DT;
Max Kazantsev201534d2018-12-29 04:26:22 +0000120 ScalarEvolution &SE;
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000121 MemorySSAUpdater *MSSAU;
Max Kazantsev136f09b2019-02-15 11:39:35 +0000122 LoopBlocksDFS DFS;
Simon Pilgrim623c38d2019-02-15 12:13:16 +0000123 DomTreeUpdater DTU;
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000124 SmallVector<DominatorTree::UpdateType, 16> DTUpdates;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000125
Max Kazantseva523a212018-12-07 05:44:45 +0000126 // Whether or not the current loop has irreducible CFG.
127 bool HasIrreducibleCFG = false;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000128 // Whether or not the current loop will still exist after terminator constant
129 // folding will be done. In theory, there are two ways how it can happen:
130 // 1. Loop's latch(es) become unreachable from loop header;
131 // 2. Loop's header becomes unreachable from method entry.
132 // In practice, the second situation is impossible because we only modify the
133 // current loop and its preheader and do not affect preheader's reachibility
134 // from any other block. So this variable set to true means that loop's latch
135 // has become unreachable from loop header.
136 bool DeleteCurrentLoop = false;
137
138 // The blocks of the original loop that will still be reachable from entry
139 // after the constant folding.
140 SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
141 // The blocks of the original loop that will become unreachable from entry
142 // after the constant folding.
Max Kazantsev80e4b402018-12-28 06:08:51 +0000143 SmallVector<BasicBlock *, 8> DeadLoopBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000144 // The exits of the original loop that will still be reachable from entry
145 // after the constant folding.
146 SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
147 // The exits of the original loop that will become unreachable from entry
148 // after the constant folding.
Max Kazantsev56a24432018-11-22 12:33:41 +0000149 SmallVector<BasicBlock *, 8> DeadExitBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000150 // The blocks that will still be a part of the current loop after folding.
151 SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
152 // The blocks that have terminators with constant condition that can be
153 // folded. Note: fold candidates should be in L but not in any of its
154 // subloops to avoid complex LI updates.
155 SmallVector<BasicBlock *, 8> FoldCandidates;
156
157 void dump() const {
158 dbgs() << "Constant terminator folding for loop " << L << "\n";
159 dbgs() << "After terminator constant-folding, the loop will";
160 if (!DeleteCurrentLoop)
161 dbgs() << " not";
162 dbgs() << " be destroyed\n";
Max Kazantsev56a24432018-11-22 12:33:41 +0000163 auto PrintOutVector = [&](const char *Message,
164 const SmallVectorImpl<BasicBlock *> &S) {
165 dbgs() << Message << "\n";
166 for (const BasicBlock *BB : S)
167 dbgs() << "\t" << BB->getName() << "\n";
168 };
Max Kazantsevc04b5302018-11-20 05:43:32 +0000169 auto PrintOutSet = [&](const char *Message,
170 const SmallPtrSetImpl<BasicBlock *> &S) {
171 dbgs() << Message << "\n";
172 for (const BasicBlock *BB : S)
173 dbgs() << "\t" << BB->getName() << "\n";
174 };
Max Kazantsev56a24432018-11-22 12:33:41 +0000175 PrintOutVector("Blocks in which we can constant-fold terminator:",
176 FoldCandidates);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000177 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
Max Kazantsev80e4b402018-12-28 06:08:51 +0000178 PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000179 PrintOutSet("Live exit blocks:", LiveExitBlocks);
Max Kazantsev56a24432018-11-22 12:33:41 +0000180 PrintOutVector("Dead exit blocks:", DeadExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000181 if (!DeleteCurrentLoop)
182 PrintOutSet("The following blocks will still be part of the loop:",
183 BlocksInLoopAfterFolding);
184 }
185
Max Kazantseva523a212018-12-07 05:44:45 +0000186 /// Whether or not the current loop has irreducible CFG.
187 bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
188 assert(DFS.isComplete() && "DFS is expected to be finished");
189 // Index of a basic block in RPO traversal.
190 DenseMap<const BasicBlock *, unsigned> RPO;
191 unsigned Current = 0;
192 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
193 RPO[*I] = Current++;
194
195 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
196 BasicBlock *BB = *I;
197 for (auto *Succ : successors(BB))
198 if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
199 // If an edge goes from a block with greater order number into a block
200 // with lesses number, and it is not a loop backedge, then it can only
201 // be a part of irreducible non-loop cycle.
202 return true;
203 }
204 return false;
205 }
206
Max Kazantsevc04b5302018-11-20 05:43:32 +0000207 /// Fill all information about status of blocks and exits of the current loop
208 /// if constant folding of all branches will be done.
209 void analyze() {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000210 DFS.perform(&LI);
211 assert(DFS.isComplete() && "DFS is expected to be finished");
212
Max Kazantseva523a212018-12-07 05:44:45 +0000213 // TODO: The algorithm below relies on both RPO and Postorder traversals.
214 // When the loop has only reducible CFG inside, then the invariant "all
215 // predecessors of X are processed before X in RPO" is preserved. However
216 // an irreducible loop can break this invariant (e.g. latch does not have to
217 // be the last block in the traversal in this case, and the algorithm relies
218 // on this). We can later decide to support such cases by altering the
219 // algorithms, but so far we just give up analyzing them.
220 if (hasIrreducibleCFG(DFS)) {
221 HasIrreducibleCFG = true;
222 return;
223 }
224
Max Kazantsevc04b5302018-11-20 05:43:32 +0000225 // Collect live and dead loop blocks and exits.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000226 LiveLoopBlocks.insert(L.getHeader());
227 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
228 BasicBlock *BB = *I;
229
230 // If a loop block wasn't marked as live so far, then it's dead.
231 if (!LiveLoopBlocks.count(BB)) {
Max Kazantsev80e4b402018-12-28 06:08:51 +0000232 DeadLoopBlocks.push_back(BB);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000233 continue;
234 }
235
236 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
237
238 // If a block has only one live successor, it's a candidate on constant
239 // folding. Only handle blocks from current loop: branches in child loops
240 // are skipped because if they can be folded, they should be folded during
241 // the processing of child loops.
Max Kazantsev56515a22019-01-24 05:20:29 +0000242 bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
243 if (TakeFoldCandidate)
Max Kazantsevc04b5302018-11-20 05:43:32 +0000244 FoldCandidates.push_back(BB);
245
246 // Handle successors.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000247 for (BasicBlock *Succ : successors(BB))
Max Kazantsev56515a22019-01-24 05:20:29 +0000248 if (!TakeFoldCandidate || TheOnlySucc == Succ) {
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000249 if (L.contains(Succ))
250 LiveLoopBlocks.insert(Succ);
251 else
252 LiveExitBlocks.insert(Succ);
253 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000254 }
255
256 // Sanity check: amount of dead and live loop blocks should match the total
257 // number of blocks in loop.
258 assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
259 "Malformed block sets?");
260
261 // Now, all exit blocks that are not marked as live are dead.
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000262 SmallVector<BasicBlock *, 8> ExitBlocks;
263 L.getExitBlocks(ExitBlocks);
Max Kazantseva4ccfc12019-02-06 07:49:17 +0000264 SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000265 for (auto *ExitBlock : ExitBlocks)
Max Kazantseva4ccfc12019-02-06 07:49:17 +0000266 if (!LiveExitBlocks.count(ExitBlock) &&
267 UniqueDeadExits.insert(ExitBlock).second)
Max Kazantsev56a24432018-11-22 12:33:41 +0000268 DeadExitBlocks.push_back(ExitBlock);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000269
270 // Whether or not the edge From->To will still be present in graph after the
271 // folding.
272 auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
273 if (!LiveLoopBlocks.count(From))
274 return false;
275 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
Max Kazantsev38cd9ac2019-01-25 05:05:02 +0000276 return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000277 };
278
279 // The loop will not be destroyed if its latch is live.
280 DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
281
282 // If we are going to delete the current loop completely, no extra analysis
283 // is needed.
284 if (DeleteCurrentLoop)
285 return;
286
287 // Otherwise, we should check which blocks will still be a part of the
288 // current loop after the transform.
289 BlocksInLoopAfterFolding.insert(L.getLoopLatch());
290 // If the loop is live, then we should compute what blocks are still in
291 // loop after all branch folding has been done. A block is in loop if
292 // it has a live edge to another block that is in the loop; by definition,
293 // latch is in the loop.
294 auto BlockIsInLoop = [&](BasicBlock *BB) {
295 return any_of(successors(BB), [&](BasicBlock *Succ) {
296 return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
297 });
298 };
299 for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
300 BasicBlock *BB = *I;
301 if (BlockIsInLoop(BB))
302 BlocksInLoopAfterFolding.insert(BB);
303 }
304
305 // Sanity check: header must be in loop.
306 assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
307 "Header not in loop?");
Max Kazantsevb565e602018-11-22 12:43:27 +0000308 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
309 "All blocks that stay in loop should be live!");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000310 }
311
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000312 /// We need to preserve static reachibility of all loop exit blocks (this is)
313 /// required by loop pass manager. In order to do it, we make the following
314 /// trick:
315 ///
316 /// preheader:
317 /// <preheader code>
318 /// br label %loop_header
319 ///
320 /// loop_header:
321 /// ...
322 /// br i1 false, label %dead_exit, label %loop_block
323 /// ...
324 ///
325 /// We cannot simply remove edge from the loop to dead exit because in this
326 /// case dead_exit (and its successors) may become unreachable. To avoid that,
327 /// we insert the following fictive preheader:
328 ///
329 /// preheader:
330 /// <preheader code>
331 /// switch i32 0, label %preheader-split,
332 /// [i32 1, label %dead_exit_1],
333 /// [i32 2, label %dead_exit_2],
334 /// ...
335 /// [i32 N, label %dead_exit_N],
336 ///
337 /// preheader-split:
338 /// br label %loop_header
339 ///
340 /// loop_header:
341 /// ...
342 /// br i1 false, label %dead_exit_N, label %loop_block
343 /// ...
344 ///
345 /// Doing so, we preserve static reachibility of all dead exits and can later
346 /// remove edges from the loop to these blocks.
347 void handleDeadExits() {
348 // If no dead exits, nothing to do.
349 if (DeadExitBlocks.empty())
350 return;
351
352 // Construct split preheader and the dummy switch to thread edges from it to
353 // dead exits.
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000354 BasicBlock *Preheader = L.getLoopPreheader();
355 BasicBlock *NewPreheader = Preheader->splitBasicBlock(
356 Preheader->getTerminator(),
357 Twine(Preheader->getName()).concat("-split"));
Max Kazantsev10489d72019-02-21 05:51:29 +0000358 if (MSSAU)
359 MSSAU->removeEdge(Preheader, L.getHeader());
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000360 DTUpdates.push_back({DominatorTree::Delete, Preheader, L.getHeader()});
361 DTUpdates.push_back({DominatorTree::Insert, NewPreheader, L.getHeader()});
362 DTUpdates.push_back({DominatorTree::Insert, Preheader, NewPreheader});
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000363 IRBuilder<> Builder(Preheader->getTerminator());
364 SwitchInst *DummySwitch =
365 Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
366 Preheader->getTerminator()->eraseFromParent();
367
368 unsigned DummyIdx = 1;
369 for (BasicBlock *BB : DeadExitBlocks) {
370 SmallVector<Instruction *, 4> DeadPhis;
371 for (auto &PN : BB->phis())
372 DeadPhis.push_back(&PN);
373
374 // Eliminate all Phis from dead exits.
375 for (Instruction *PN : DeadPhis) {
376 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
377 PN->eraseFromParent();
378 }
379 assert(DummyIdx != 0 && "Too many dead exits!");
380 DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000381 DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000382 ++NumLoopExitsDeleted;
383 }
384
385 assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
386 if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
387 OuterLoop->addBasicBlockToLoop(NewPreheader, LI);
388
389 // When we break dead edges, the outer loop may become unreachable from
390 // the current loop. We need to fix loop info accordingly. For this, we
391 // find the most nested loop that still contains L and remove L from all
392 // loops that are inside of it.
Max Kazantsevd72c1a02019-02-17 15:22:48 +0000393 Loop *StillReachable = getInnermostLoopFor(LiveExitBlocks, L, LI);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000394
395 // Okay, our loop is no longer in the outer loop (and maybe not in some of
396 // its parents as well). Make the fixup.
397 if (StillReachable != OuterLoop) {
398 LI.changeLoopFor(NewPreheader, StillReachable);
Max Kazantsevc065b022019-02-15 12:18:10 +0000399 removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);
400 for (auto *BB : L.blocks())
401 removeBlockFromLoops(BB, OuterLoop, StillReachable);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000402 OuterLoop->removeChildLoop(&L);
403 if (StillReachable)
404 StillReachable->addChildLoop(&L);
405 else
406 LI.addTopLevelLoop(&L);
Max Kazantsev61a8d3f2019-01-17 12:51:10 +0000407
408 // Some values from loops in [OuterLoop, StillReachable) could be used
409 // in the current loop. Now it is not their child anymore, so such uses
410 // require LCSSA Phis.
411 Loop *FixLCSSALoop = OuterLoop;
412 while (FixLCSSALoop->getParentLoop() != StillReachable)
413 FixLCSSALoop = FixLCSSALoop->getParentLoop();
414 assert(FixLCSSALoop && "Should be a loop!");
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000415 // We need all DT updates to be done before forming LCSSA.
416 DTU.applyUpdates(DTUpdates);
417 DTUpdates.clear();
Max Kazantsev61a8d3f2019-01-17 12:51:10 +0000418 formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000419 }
420 }
421 }
422
Max Kazantsev347c5832018-12-24 06:06:17 +0000423 /// Delete loop blocks that have become unreachable after folding. Make all
424 /// relevant updates to DT and LI.
425 void deleteDeadLoopBlocks() {
Max Kazantsev80e4b402018-12-28 06:08:51 +0000426 if (MSSAU) {
427 SmallPtrSet<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
428 DeadLoopBlocks.end());
429 MSSAU->removeBlocks(DeadLoopBlocksSet);
430 }
Max Kazantsevbf6af8f2019-02-12 09:37:00 +0000431
432 // The function LI.erase has some invariants that need to be preserved when
433 // it tries to remove a loop which is not the top-level loop. In particular,
434 // it requires loop's preheader to be strictly in loop's parent. We cannot
435 // just remove blocks one by one, because after removal of preheader we may
436 // break this invariant for the dead loop. So we detatch and erase all dead
437 // loops beforehand.
438 for (auto *BB : DeadLoopBlocks)
439 if (LI.isLoopHeader(BB)) {
440 assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
441 Loop *DL = LI.getLoopFor(BB);
442 if (DL->getParentLoop()) {
443 for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
444 for (auto *BB : DL->getBlocks())
445 PL->removeBlockFromLoop(BB);
446 DL->getParentLoop()->removeChildLoop(DL);
447 LI.addTopLevelLoop(DL);
448 }
449 LI.erase(DL);
450 }
451
Max Kazantsev347c5832018-12-24 06:06:17 +0000452 for (auto *BB : DeadLoopBlocks) {
453 assert(BB != L.getHeader() &&
454 "Header of the current loop cannot be dead!");
455 LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
456 << "\n");
Max Kazantsev347c5832018-12-24 06:06:17 +0000457 LI.removeBlock(BB);
Max Kazantsev347c5832018-12-24 06:06:17 +0000458 }
Max Kazantsev8b134162019-01-17 12:25:40 +0000459
Max Kazantsev6bf86152019-02-12 07:48:07 +0000460 DetatchDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000461 DTU.applyUpdates(DTUpdates);
462 DTUpdates.clear();
463 for (auto *BB : DeadLoopBlocks)
Max Kazantsev9aae9da2019-02-12 08:10:29 +0000464 DTU.deleteBB(BB);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000465
Max Kazantsev8b134162019-01-17 12:25:40 +0000466 NumLoopBlocksDeleted += DeadLoopBlocks.size();
Max Kazantsev347c5832018-12-24 06:06:17 +0000467 }
468
Max Kazantsevc04b5302018-11-20 05:43:32 +0000469 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
470 /// unconditional branches.
471 void foldTerminators() {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000472 for (BasicBlock *BB : FoldCandidates) {
473 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
474 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
475 assert(TheOnlySucc && "Should have one live successor!");
476
477 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
478 << " with an unconditional branch to the block "
479 << TheOnlySucc->getName() << "\n");
480
481 SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
482 // Remove all BB's successors except for the live one.
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000483 unsigned TheOnlySuccDuplicates = 0;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000484 for (auto *Succ : successors(BB))
485 if (Succ != TheOnlySucc) {
486 DeadSuccessors.insert(Succ);
Max Kazantsevcb8e2402018-11-23 07:56:47 +0000487 // If our successor lies in a different loop, we don't want to remove
488 // the one-input Phi because it is a LCSSA Phi.
489 bool PreserveLCSSAPhi = !L.contains(Succ);
490 Succ->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000491 if (MSSAU)
492 MSSAU->removeEdge(BB, Succ);
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000493 } else
494 ++TheOnlySuccDuplicates;
495
496 assert(TheOnlySuccDuplicates > 0 && "Should be!");
497 // If TheOnlySucc was BB's successor more than once, after transform it
498 // will be its successor only once. Remove redundant inputs from
499 // TheOnlySucc's Phis.
500 bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
501 for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
502 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000503 if (MSSAU && TheOnlySuccDuplicates > 1)
504 MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000505
506 IRBuilder<> Builder(BB->getContext());
507 Instruction *Term = BB->getTerminator();
508 Builder.SetInsertPoint(Term);
509 Builder.CreateBr(TheOnlySucc);
510 Term->eraseFromParent();
511
512 for (auto *DeadSucc : DeadSuccessors)
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000513 DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
Max Kazantsevc04b5302018-11-20 05:43:32 +0000514
515 ++NumTerminatorsFolded;
516 }
517 }
518
519public:
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000520 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
Max Kazantsev201534d2018-12-29 04:26:22 +0000521 ScalarEvolution &SE,
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000522 MemorySSAUpdater *MSSAU)
Max Kazantsev136f09b2019-02-15 11:39:35 +0000523 : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000524 DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}
Max Kazantsevc04b5302018-11-20 05:43:32 +0000525 bool run() {
526 assert(L.getLoopLatch() && "Should be single latch!");
527
528 // Collect all available information about status of blocks after constant
529 // folding.
530 analyze();
Max Kazantsev30095d92019-02-19 11:13:58 +0000531 BasicBlock *Header = L.getHeader();
532 (void)Header;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000533
Max Kazantsev30095d92019-02-19 11:13:58 +0000534 LLVM_DEBUG(dbgs() << "In function " << Header->getParent()->getName()
Max Kazantsevc04b5302018-11-20 05:43:32 +0000535 << ": ");
536
Max Kazantseva523a212018-12-07 05:44:45 +0000537 if (HasIrreducibleCFG) {
538 LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
539 return false;
540 }
541
Max Kazantsevc04b5302018-11-20 05:43:32 +0000542 // Nothing to constant-fold.
543 if (FoldCandidates.empty()) {
544 LLVM_DEBUG(
545 dbgs() << "No constant terminator folding candidates found in loop "
Max Kazantsev30095d92019-02-19 11:13:58 +0000546 << Header->getName() << "\n");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000547 return false;
548 }
549
550 // TODO: Support deletion of the current loop.
551 if (DeleteCurrentLoop) {
552 LLVM_DEBUG(
553 dbgs()
Max Kazantsev30095d92019-02-19 11:13:58 +0000554 << "Give up constant terminator folding in loop " << Header->getName()
Max Kazantsevc04b5302018-11-20 05:43:32 +0000555 << ": we don't currently support deletion of the current loop.\n");
556 return false;
557 }
558
Max Kazantsevc04b5302018-11-20 05:43:32 +0000559 // TODO: Support blocks that are not dead, but also not in loop after the
560 // folding.
Max Kazantsev347c5832018-12-24 06:06:17 +0000561 if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
562 L.getNumBlocks()) {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000563 LLVM_DEBUG(
564 dbgs() << "Give up constant terminator folding in loop "
Max Kazantsev30095d92019-02-19 11:13:58 +0000565 << Header->getName() << ": we don't currently"
Max Kazantsevc04b5302018-11-20 05:43:32 +0000566 " support blocks that are not dead, but will stop "
567 "being a part of the loop after constant-folding.\n");
568 return false;
569 }
570
Max Kazantsev201534d2018-12-29 04:26:22 +0000571 SE.forgetTopmostLoop(&L);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000572 // Dump analysis results.
573 LLVM_DEBUG(dump());
574
575 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
Max Kazantsev30095d92019-02-19 11:13:58 +0000576 << " terminators in loop " << Header->getName() << "\n");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000577
578 // Make the actual transforms.
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000579 handleDeadExits();
Max Kazantsevc04b5302018-11-20 05:43:32 +0000580 foldTerminators();
581
Max Kazantsev347c5832018-12-24 06:06:17 +0000582 if (!DeadLoopBlocks.empty()) {
583 LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
Max Kazantsev30095d92019-02-19 11:13:58 +0000584 << " dead blocks in loop " << Header->getName() << "\n");
Max Kazantsev347c5832018-12-24 06:06:17 +0000585 deleteDeadLoopBlocks();
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000586 } else {
587 // If we didn't do updates inside deleteDeadLoopBlocks, do them here.
588 DTU.applyUpdates(DTUpdates);
589 DTUpdates.clear();
Max Kazantsev347c5832018-12-24 06:06:17 +0000590 }
591
Max Kazantsevc04b5302018-11-20 05:43:32 +0000592#ifndef NDEBUG
593 // Make sure that we have preserved all data structures after the transform.
Max Kazantsev365021c2019-01-30 12:32:19 +0000594 assert(DT.verify() && "DT broken after transform!");
Max Kazantsev30095d92019-02-19 11:13:58 +0000595 assert(DT.isReachableFromEntry(Header));
Max Kazantsevc04b5302018-11-20 05:43:32 +0000596 LI.verify(DT);
597#endif
598
599 return true;
600 }
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000601
602 bool foldingBreaksCurrentLoop() const {
603 return DeleteCurrentLoop;
604 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000605};
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000606} // namespace
Max Kazantsevc04b5302018-11-20 05:43:32 +0000607
608/// Turn branches and switches with known constant conditions into unconditional
609/// branches.
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000610static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
Max Kazantsev201534d2018-12-29 04:26:22 +0000611 ScalarEvolution &SE,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000612 MemorySSAUpdater *MSSAU,
613 bool &IsLoopDeleted) {
Max Kazantseve1c2dc22018-11-23 09:14:53 +0000614 if (!EnableTermFolding)
615 return false;
616
Max Kazantsevc04b5302018-11-20 05:43:32 +0000617 // To keep things simple, only process loops with single latch. We
618 // canonicalize most loops to this form. We can support multi-latch if needed.
619 if (!L.getLoopLatch())
620 return false;
621
Max Kazantsev201534d2018-12-29 04:26:22 +0000622 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000623 bool Changed = BranchFolder.run();
624 IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();
625 return Changed;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000626}
627
Max Kazantsev46955b52018-11-01 09:42:50 +0000628static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
629 LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Fiona Glaserb417d462016-01-29 22:35:36 +0000630 bool Changed = false;
Chijun Sima21a8b602018-08-03 05:08:17 +0000631 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Fiona Glaserb417d462016-01-29 22:35:36 +0000632 // Copy blocks into a temporary array to avoid iterator invalidation issues
633 // as we remove them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000634 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
Fiona Glaserb417d462016-01-29 22:35:36 +0000635
636 for (auto &Block : Blocks) {
637 // Attempt to merge blocks in the trivial case. Don't modify blocks which
638 // belong to other loops.
Fiona Glaser36e82302016-01-29 23:12:52 +0000639 BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
Fiona Glaserb417d462016-01-29 22:35:36 +0000640 if (!Succ)
641 continue;
642
643 BasicBlock *Pred = Succ->getSinglePredecessor();
Justin Bognerab6a5132016-05-03 21:47:32 +0000644 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
Fiona Glaserb417d462016-01-29 22:35:36 +0000645 continue;
646
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000647 // Merge Succ into Pred and delete it.
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000648 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
David Greene6a9c242018-06-19 09:43:36 +0000649
Fiona Glaserb417d462016-01-29 22:35:36 +0000650 Changed = true;
651 }
652
653 return Changed;
654}
655
Max Kazantsev46955b52018-11-01 09:42:50 +0000656static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000657 ScalarEvolution &SE, MemorySSAUpdater *MSSAU,
658 bool &isLoopDeleted) {
Max Kazantsev46955b52018-11-01 09:42:50 +0000659 bool Changed = false;
660
Max Kazantsevc04b5302018-11-20 05:43:32 +0000661 // Constant-fold terminators with known constant conditions.
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000662 Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU, isLoopDeleted);
663
664 if (isLoopDeleted)
665 return true;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000666
Max Kazantsev46955b52018-11-01 09:42:50 +0000667 // Eliminate unconditional branches by merging blocks into their predecessors.
668 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
669
670 if (Changed)
671 SE.forgetTopmostLoop(&L);
672
673 return Changed;
674}
675
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000676PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
677 LoopStandardAnalysisResults &AR,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000678 LPMUpdater &LPMU) {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000679 Optional<MemorySSAUpdater> MSSAU;
680 if (EnableMSSALoopDependency && AR.MSSA)
681 MSSAU = MemorySSAUpdater(AR.MSSA);
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000682 bool DeleteCurrentLoop = false;
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000683 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000684 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
685 DeleteCurrentLoop))
Justin Bognerab6a5132016-05-03 21:47:32 +0000686 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000687
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000688 if (DeleteCurrentLoop)
689 LPMU.markLoopAsDeleted(L, "loop-simplifycfg");
690
Justin Bognerab6a5132016-05-03 21:47:32 +0000691 return getLoopPassPreservedAnalyses();
692}
693
694namespace {
695class LoopSimplifyCFGLegacyPass : public LoopPass {
696public:
697 static char ID; // Pass ID, replacement for typeid
698 LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
699 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
700 }
701
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000702 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Justin Bognerab6a5132016-05-03 21:47:32 +0000703 if (skipLoop(L))
704 return false;
705
706 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
707 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
David Greene6a9c242018-06-19 09:43:36 +0000708 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000709 Optional<MemorySSAUpdater> MSSAU;
710 if (EnableMSSALoopDependency) {
711 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
712 MSSAU = MemorySSAUpdater(MSSA);
713 if (VerifyMemorySSA)
714 MSSA->verifyMemorySSA();
715 }
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000716 bool DeleteCurrentLoop = false;
717 bool Changed = simplifyLoopCFG(
718 *L, DT, LI, SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
719 DeleteCurrentLoop);
720 if (DeleteCurrentLoop)
721 LPM.markLoopAsDeleted(*L);
722 return Changed;
Justin Bognerab6a5132016-05-03 21:47:32 +0000723 }
724
725 void getAnalysisUsage(AnalysisUsage &AU) const override {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000726 if (EnableMSSALoopDependency) {
727 AU.addRequired<MemorySSAWrapperPass>();
728 AU.addPreserved<MemorySSAWrapperPass>();
729 }
Chandler Carruth49c22192016-05-12 22:19:39 +0000730 AU.addPreserved<DependenceAnalysisWrapperPass>();
Justin Bognerab6a5132016-05-03 21:47:32 +0000731 getLoopAnalysisUsage(AU);
732 }
733};
734}
735
736char LoopSimplifyCFGLegacyPass::ID = 0;
737INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
738 "Simplify loop CFG", false, false)
739INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000740INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Justin Bognerab6a5132016-05-03 21:47:32 +0000741INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
742 "Simplify loop CFG", false, false)
743
744Pass *llvm::createLoopSimplifyCFGPass() {
745 return new LoopSimplifyCFGLegacyPass();
Fiona Glaserb417d462016-01-29 22:35:36 +0000746}