blob: 383a3e64d3e86f2f18f255f46e5452ef07adabcf [file] [log] [blame]
Fiona Glaserb417d462016-01-29 22:35:36 +00001//===--------- 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 Bognerab6a5132016-05-03 21:47:32 +000017#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000021#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000022#include "llvm/Analysis/BasicAliasAnalysis.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000023#include "llvm/Analysis/DependenceAnalysis.h"
24#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"
Chijun Sima21a8b602018-08-03 05:08:17 +000032#include "llvm/IR/DomTreeUpdater.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000033#include "llvm/IR/Dominators.h"
Justin Bognerab6a5132016-05-03 21:47:32 +000034#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000035#include "llvm/Transforms/Scalar/LoopPassManager.h"
David Blaikiea373d182018-03-28 17:44:36 +000036#include "llvm/Transforms/Utils.h"
Alina Sbirleadfd14ad2018-06-20 22:01:04 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
38#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000039#include "llvm/Transforms/Utils/LoopUtils.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000040using namespace llvm;
41
42#define DEBUG_TYPE "loop-simplifycfg"
43
Max Kazantseve1c2dc22018-11-23 09:14:53 +000044static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
Max Kazantsev9cf417d2018-11-30 10:06:23 +000045 cl::init(true));
Max Kazantseve1c2dc22018-11-23 09:14:53 +000046
Max Kazantsevc04b5302018-11-20 05:43:32 +000047STATISTIC(NumTerminatorsFolded,
48 "Number of terminators folded to unconditional branches");
Max Kazantsev347c5832018-12-24 06:06:17 +000049STATISTIC(NumLoopBlocksDeleted,
50 "Number of loop blocks deleted");
Max Kazantsevc04b5302018-11-20 05:43:32 +000051
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.
55static 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.
83class ConstantTerminatorFoldingImpl {
84private:
85 Loop &L;
86 LoopInfo &LI;
87 DominatorTree &DT;
Max Kazantsev9cf417d2018-11-30 10:06:23 +000088 MemorySSAUpdater *MSSAU;
Max Kazantsevc04b5302018-11-20 05:43:32 +000089
Max Kazantseva523a212018-12-07 05:44:45 +000090 // Whether or not the current loop has irreducible CFG.
91 bool HasIrreducibleCFG = false;
Max Kazantsevc04b5302018-11-20 05:43:32 +000092 // 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 Kazantsev56a24432018-11-22 12:33:41 +0000113 SmallVector<BasicBlock *, 8> DeadExitBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000114 // 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 Kazantsev56a24432018-11-22 12:33:41 +0000127 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 Kazantsevc04b5302018-11-20 05:43:32 +0000133 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 Kazantsev56a24432018-11-22 12:33:41 +0000139 PrintOutVector("Blocks in which we can constant-fold terminator:",
140 FoldCandidates);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000141 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
142 PrintOutSet("Dead blocks from the original loop:", DeadLoopBlocks);
143 PrintOutSet("Live exit blocks:", LiveExitBlocks);
Max Kazantsev56a24432018-11-22 12:33:41 +0000144 PrintOutVector("Dead exit blocks:", DeadExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000145 if (!DeleteCurrentLoop)
146 PrintOutSet("The following blocks will still be part of the loop:",
147 BlocksInLoopAfterFolding);
148 }
149
Max Kazantseva523a212018-12-07 05:44:45 +0000150 /// 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 Kazantsevc04b5302018-11-20 05:43:32 +0000171 /// 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 Kazantseva523a212018-12-07 05:44:45 +0000178 // 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 Kazantsevc04b5302018-11-20 05:43:32 +0000190 // Collect live and dead loop blocks and exits.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000191 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 Kazantsevc04b5302018-11-20 05:43:32 +0000211 for (BasicBlock *Succ : successors(BB))
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000212 if (!TheOnlySucc || TheOnlySucc == Succ) {
213 if (L.contains(Succ))
214 LiveLoopBlocks.insert(Succ);
215 else
216 LiveExitBlocks.insert(Succ);
217 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000218 }
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 Kazantsevd9f59f82018-11-22 10:48:30 +0000226 SmallVector<BasicBlock *, 8> ExitBlocks;
227 L.getExitBlocks(ExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000228 for (auto *ExitBlock : ExitBlocks)
229 if (!LiveExitBlocks.count(ExitBlock))
Max Kazantsev56a24432018-11-22 12:33:41 +0000230 DeadExitBlocks.push_back(ExitBlock);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000231
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 Kazantsevb565e602018-11-22 12:43:27 +0000270 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
271 "All blocks that stay in loop should be live!");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000272 }
273
Max Kazantsev347c5832018-12-24 06:06:17 +0000274 /// 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 Kazantsevc04b5302018-11-20 05:43:32 +0000295 /// 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 Kazantsevc4e4d642018-11-27 06:17:21 +0000311 unsigned TheOnlySuccDuplicates = 0;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000312 for (auto *Succ : successors(BB))
313 if (Succ != TheOnlySucc) {
314 DeadSuccessors.insert(Succ);
Max Kazantsevcb8e2402018-11-23 07:56:47 +0000315 // 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 Kazantsev9cf417d2018-11-30 10:06:23 +0000319 if (MSSAU)
320 MSSAU->removeEdge(BB, Succ);
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000321 } 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 Kazantsev9cf417d2018-11-30 10:06:23 +0000331 if (MSSAU && TheOnlySuccDuplicates > 1)
332 MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000333
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
347public:
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000348 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
349 MemorySSAUpdater *MSSAU)
350 : L(L), LI(LI), DT(DT), MSSAU(MSSAU) {}
Max Kazantsevc04b5302018-11-20 05:43:32 +0000351 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 Kazantseva523a212018-12-07 05:44:45 +0000361 if (HasIrreducibleCFG) {
362 LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
363 return false;
364 }
365
Max Kazantsevc04b5302018-11-20 05:43:32 +0000366 // 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 Kazantsevc04b5302018-11-20 05:43:32 +0000384 // 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 Kazantsev347c5832018-12-24 06:06:17 +0000394 if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
395 L.getNumBlocks()) {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000396 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 Kazantsev347c5832018-12-24 06:06:17 +0000415 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 Kazantsevc04b5302018-11-20 05:43:32 +0000422#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 Kazantsev9cf417d2018-11-30 10:06:23 +0000435static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
436 MemorySSAUpdater *MSSAU) {
Max Kazantseve1c2dc22018-11-23 09:14:53 +0000437 if (!EnableTermFolding)
438 return false;
439
Max Kazantsevc04b5302018-11-20 05:43:32 +0000440 // 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 Kazantsev9cf417d2018-11-30 10:06:23 +0000445 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, MSSAU);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000446 return BranchFolder.run();
447}
448
Max Kazantsev46955b52018-11-01 09:42:50 +0000449static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
450 LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Fiona Glaserb417d462016-01-29 22:35:36 +0000451 bool Changed = false;
Chijun Sima21a8b602018-08-03 05:08:17 +0000452 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Fiona Glaserb417d462016-01-29 22:35:36 +0000453 // Copy blocks into a temporary array to avoid iterator invalidation issues
454 // as we remove them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000455 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
Fiona Glaserb417d462016-01-29 22:35:36 +0000456
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 Glaser36e82302016-01-29 23:12:52 +0000460 BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
Fiona Glaserb417d462016-01-29 22:35:36 +0000461 if (!Succ)
462 continue;
463
464 BasicBlock *Pred = Succ->getSinglePredecessor();
Justin Bognerab6a5132016-05-03 21:47:32 +0000465 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
Fiona Glaserb417d462016-01-29 22:35:36 +0000466 continue;
467
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000468 // Merge Succ into Pred and delete it.
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000469 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
David Greene6a9c242018-06-19 09:43:36 +0000470
Fiona Glaserb417d462016-01-29 22:35:36 +0000471 Changed = true;
472 }
473
474 return Changed;
475}
476
Max Kazantsev46955b52018-11-01 09:42:50 +0000477static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
478 ScalarEvolution &SE, MemorySSAUpdater *MSSAU) {
479 bool Changed = false;
480
Max Kazantsevc04b5302018-11-20 05:43:32 +0000481 // Constant-fold terminators with known constant conditions.
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000482 Changed |= constantFoldTerminators(L, DT, LI, MSSAU);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000483
Max Kazantsev46955b52018-11-01 09:42:50 +0000484 // 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 Carruth410eaeb2017-01-11 06:23:21 +0000493PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
494 LoopStandardAnalysisResults &AR,
495 LPMUpdater &) {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000496 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 Bognerab6a5132016-05-03 21:47:32 +0000501 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000502
Justin Bognerab6a5132016-05-03 21:47:32 +0000503 return getLoopPassPreservedAnalyses();
504}
505
506namespace {
507class LoopSimplifyCFGLegacyPass : public LoopPass {
508public:
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 Greene6a9c242018-06-19 09:43:36 +0000520 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000521 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 Bognerab6a5132016-05-03 21:47:32 +0000530 }
531
532 void getAnalysisUsage(AnalysisUsage &AU) const override {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000533 if (EnableMSSALoopDependency) {
534 AU.addRequired<MemorySSAWrapperPass>();
535 AU.addPreserved<MemorySSAWrapperPass>();
536 }
Chandler Carruth49c22192016-05-12 22:19:39 +0000537 AU.addPreserved<DependenceAnalysisWrapperPass>();
Justin Bognerab6a5132016-05-03 21:47:32 +0000538 getLoopAnalysisUsage(AU);
539 }
540};
541}
542
543char LoopSimplifyCFGLegacyPass::ID = 0;
544INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
545 "Simplify loop CFG", false, false)
546INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000547INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Justin Bognerab6a5132016-05-03 21:47:32 +0000548INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
549 "Simplify loop CFG", false, false)
550
551Pass *llvm::createLoopSimplifyCFGPass() {
552 return new LoopSimplifyCFGLegacyPass();
Fiona Glaserb417d462016-01-29 22:35:36 +0000553}