blob: 7edba7c60c55101f275a3b528873f9388fb96e61 [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 Kazantsevc04b5302018-11-20 05:43:32 +000044STATISTIC(NumTerminatorsFolded,
45 "Number of terminators folded to unconditional branches");
46
47/// If \p BB is a switch or a conditional branch, but only one of its successors
48/// can be reached from this block in runtime, return this successor. Otherwise,
49/// return nullptr.
50static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {
51 Instruction *TI = BB->getTerminator();
52 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
53 if (BI->isUnconditional())
54 return nullptr;
55 if (BI->getSuccessor(0) == BI->getSuccessor(1))
56 return BI->getSuccessor(0);
57 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
58 if (!Cond)
59 return nullptr;
60 return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
61 }
62
63 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
64 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
65 if (!CI)
66 return nullptr;
67 for (auto Case : SI->cases())
68 if (Case.getCaseValue() == CI)
69 return Case.getCaseSuccessor();
70 return SI->getDefaultDest();
71 }
72
73 return nullptr;
74}
75
76/// Helper class that can turn branches and switches with constant conditions
77/// into unconditional branches.
78class ConstantTerminatorFoldingImpl {
79private:
80 Loop &L;
81 LoopInfo &LI;
82 DominatorTree &DT;
83
84 // Whether or not the current loop will still exist after terminator constant
85 // folding will be done. In theory, there are two ways how it can happen:
86 // 1. Loop's latch(es) become unreachable from loop header;
87 // 2. Loop's header becomes unreachable from method entry.
88 // In practice, the second situation is impossible because we only modify the
89 // current loop and its preheader and do not affect preheader's reachibility
90 // from any other block. So this variable set to true means that loop's latch
91 // has become unreachable from loop header.
92 bool DeleteCurrentLoop = false;
93
94 // The blocks of the original loop that will still be reachable from entry
95 // after the constant folding.
96 SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
97 // The blocks of the original loop that will become unreachable from entry
98 // after the constant folding.
99 SmallPtrSet<BasicBlock *, 8> DeadLoopBlocks;
100 // The exits of the original loop that will still be reachable from entry
101 // after the constant folding.
102 SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
103 // The exits of the original loop that will become unreachable from entry
104 // after the constant folding.
Max Kazantsev56a24432018-11-22 12:33:41 +0000105 SmallVector<BasicBlock *, 8> DeadExitBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000106 // The blocks that will still be a part of the current loop after folding.
107 SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
108 // The blocks that have terminators with constant condition that can be
109 // folded. Note: fold candidates should be in L but not in any of its
110 // subloops to avoid complex LI updates.
111 SmallVector<BasicBlock *, 8> FoldCandidates;
112
113 void dump() const {
114 dbgs() << "Constant terminator folding for loop " << L << "\n";
115 dbgs() << "After terminator constant-folding, the loop will";
116 if (!DeleteCurrentLoop)
117 dbgs() << " not";
118 dbgs() << " be destroyed\n";
Max Kazantsev56a24432018-11-22 12:33:41 +0000119 auto PrintOutVector = [&](const char *Message,
120 const SmallVectorImpl<BasicBlock *> &S) {
121 dbgs() << Message << "\n";
122 for (const BasicBlock *BB : S)
123 dbgs() << "\t" << BB->getName() << "\n";
124 };
Max Kazantsevc04b5302018-11-20 05:43:32 +0000125 auto PrintOutSet = [&](const char *Message,
126 const SmallPtrSetImpl<BasicBlock *> &S) {
127 dbgs() << Message << "\n";
128 for (const BasicBlock *BB : S)
129 dbgs() << "\t" << BB->getName() << "\n";
130 };
Max Kazantsev56a24432018-11-22 12:33:41 +0000131 PrintOutVector("Blocks in which we can constant-fold terminator:",
132 FoldCandidates);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000133 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
134 PrintOutSet("Dead blocks from the original loop:", DeadLoopBlocks);
135 PrintOutSet("Live exit blocks:", LiveExitBlocks);
Max Kazantsev56a24432018-11-22 12:33:41 +0000136 PrintOutVector("Dead exit blocks:", DeadExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000137 if (!DeleteCurrentLoop)
138 PrintOutSet("The following blocks will still be part of the loop:",
139 BlocksInLoopAfterFolding);
140 }
141
142 /// Fill all information about status of blocks and exits of the current loop
143 /// if constant folding of all branches will be done.
144 void analyze() {
145 LoopBlocksDFS DFS(&L);
146 DFS.perform(&LI);
147 assert(DFS.isComplete() && "DFS is expected to be finished");
148
149 // Collect live and dead loop blocks and exits.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000150 LiveLoopBlocks.insert(L.getHeader());
151 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
152 BasicBlock *BB = *I;
153
154 // If a loop block wasn't marked as live so far, then it's dead.
155 if (!LiveLoopBlocks.count(BB)) {
156 DeadLoopBlocks.insert(BB);
157 continue;
158 }
159
160 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
161
162 // If a block has only one live successor, it's a candidate on constant
163 // folding. Only handle blocks from current loop: branches in child loops
164 // are skipped because if they can be folded, they should be folded during
165 // the processing of child loops.
166 if (TheOnlySucc && LI.getLoopFor(BB) == &L)
167 FoldCandidates.push_back(BB);
168
169 // Handle successors.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000170 for (BasicBlock *Succ : successors(BB))
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000171 if (!TheOnlySucc || TheOnlySucc == Succ) {
172 if (L.contains(Succ))
173 LiveLoopBlocks.insert(Succ);
174 else
175 LiveExitBlocks.insert(Succ);
176 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000177 }
178
179 // Sanity check: amount of dead and live loop blocks should match the total
180 // number of blocks in loop.
181 assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
182 "Malformed block sets?");
183
184 // Now, all exit blocks that are not marked as live are dead.
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000185 SmallVector<BasicBlock *, 8> ExitBlocks;
186 L.getExitBlocks(ExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000187 for (auto *ExitBlock : ExitBlocks)
188 if (!LiveExitBlocks.count(ExitBlock))
Max Kazantsev56a24432018-11-22 12:33:41 +0000189 DeadExitBlocks.push_back(ExitBlock);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000190
191 // Whether or not the edge From->To will still be present in graph after the
192 // folding.
193 auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
194 if (!LiveLoopBlocks.count(From))
195 return false;
196 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
197 return !TheOnlySucc || TheOnlySucc == To;
198 };
199
200 // The loop will not be destroyed if its latch is live.
201 DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
202
203 // If we are going to delete the current loop completely, no extra analysis
204 // is needed.
205 if (DeleteCurrentLoop)
206 return;
207
208 // Otherwise, we should check which blocks will still be a part of the
209 // current loop after the transform.
210 BlocksInLoopAfterFolding.insert(L.getLoopLatch());
211 // If the loop is live, then we should compute what blocks are still in
212 // loop after all branch folding has been done. A block is in loop if
213 // it has a live edge to another block that is in the loop; by definition,
214 // latch is in the loop.
215 auto BlockIsInLoop = [&](BasicBlock *BB) {
216 return any_of(successors(BB), [&](BasicBlock *Succ) {
217 return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
218 });
219 };
220 for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
221 BasicBlock *BB = *I;
222 if (BlockIsInLoop(BB))
223 BlocksInLoopAfterFolding.insert(BB);
224 }
225
226 // Sanity check: header must be in loop.
227 assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
228 "Header not in loop?");
Max Kazantsevb565e602018-11-22 12:43:27 +0000229 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
230 "All blocks that stay in loop should be live!");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000231 }
232
233 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
234 /// unconditional branches.
235 void foldTerminators() {
236 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
237
238 for (BasicBlock *BB : FoldCandidates) {
239 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
240 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
241 assert(TheOnlySucc && "Should have one live successor!");
242
243 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
244 << " with an unconditional branch to the block "
245 << TheOnlySucc->getName() << "\n");
246
247 SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
248 // Remove all BB's successors except for the live one.
249 for (auto *Succ : successors(BB))
250 if (Succ != TheOnlySucc) {
251 DeadSuccessors.insert(Succ);
Max Kazantsevcb8e2402018-11-23 07:56:47 +0000252 // If our successor lies in a different loop, we don't want to remove
253 // the one-input Phi because it is a LCSSA Phi.
254 bool PreserveLCSSAPhi = !L.contains(Succ);
255 Succ->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000256 }
257
258 IRBuilder<> Builder(BB->getContext());
259 Instruction *Term = BB->getTerminator();
260 Builder.SetInsertPoint(Term);
261 Builder.CreateBr(TheOnlySucc);
262 Term->eraseFromParent();
263
264 for (auto *DeadSucc : DeadSuccessors)
265 DTU.deleteEdge(BB, DeadSucc);
266
267 ++NumTerminatorsFolded;
268 }
269 }
270
271public:
272 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT)
273 : L(L), LI(LI), DT(DT) {}
274 bool run() {
275 assert(L.getLoopLatch() && "Should be single latch!");
276
277 // Collect all available information about status of blocks after constant
278 // folding.
279 analyze();
280
281 LLVM_DEBUG(dbgs() << "In function " << L.getHeader()->getParent()->getName()
282 << ": ");
283
284 // Nothing to constant-fold.
285 if (FoldCandidates.empty()) {
286 LLVM_DEBUG(
287 dbgs() << "No constant terminator folding candidates found in loop "
288 << L.getHeader()->getName() << "\n");
289 return false;
290 }
291
292 // TODO: Support deletion of the current loop.
293 if (DeleteCurrentLoop) {
294 LLVM_DEBUG(
295 dbgs()
296 << "Give up constant terminator folding in loop "
297 << L.getHeader()->getName()
298 << ": we don't currently support deletion of the current loop.\n");
299 return false;
300 }
301
302 // TODO: Support deletion of dead loop blocks.
303 if (!DeadLoopBlocks.empty()) {
304 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop "
305 << L.getHeader()->getName()
306 << ": we don't currently"
307 " support deletion of dead in-loop blocks.\n");
308 return false;
309 }
310
311 // TODO: Support dead loop exits.
312 if (!DeadExitBlocks.empty()) {
313 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop "
314 << L.getHeader()->getName()
315 << ": we don't currently support dead loop exits.\n");
316 return false;
317 }
318
319 // TODO: Support blocks that are not dead, but also not in loop after the
320 // folding.
321 if (BlocksInLoopAfterFolding.size() != L.getNumBlocks()) {
322 LLVM_DEBUG(
323 dbgs() << "Give up constant terminator folding in loop "
324 << L.getHeader()->getName()
325 << ": we don't currently"
326 " support blocks that are not dead, but will stop "
327 "being a part of the loop after constant-folding.\n");
328 return false;
329 }
330
331 // Dump analysis results.
332 LLVM_DEBUG(dump());
333
334 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
335 << " terminators in loop " << L.getHeader()->getName()
336 << "\n");
337
338 // Make the actual transforms.
339 foldTerminators();
340
341#ifndef NDEBUG
342 // Make sure that we have preserved all data structures after the transform.
343 DT.verify();
344 assert(DT.isReachableFromEntry(L.getHeader()));
345 LI.verify(DT);
346#endif
347
348 return true;
349 }
350};
351
352/// Turn branches and switches with known constant conditions into unconditional
353/// branches.
354static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI) {
355 // To keep things simple, only process loops with single latch. We
356 // canonicalize most loops to this form. We can support multi-latch if needed.
357 if (!L.getLoopLatch())
358 return false;
359
360 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT);
361 return BranchFolder.run();
362}
363
Max Kazantsev46955b52018-11-01 09:42:50 +0000364static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
365 LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Fiona Glaserb417d462016-01-29 22:35:36 +0000366 bool Changed = false;
Chijun Sima21a8b602018-08-03 05:08:17 +0000367 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Fiona Glaserb417d462016-01-29 22:35:36 +0000368 // Copy blocks into a temporary array to avoid iterator invalidation issues
369 // as we remove them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000370 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
Fiona Glaserb417d462016-01-29 22:35:36 +0000371
372 for (auto &Block : Blocks) {
373 // Attempt to merge blocks in the trivial case. Don't modify blocks which
374 // belong to other loops.
Fiona Glaser36e82302016-01-29 23:12:52 +0000375 BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
Fiona Glaserb417d462016-01-29 22:35:36 +0000376 if (!Succ)
377 continue;
378
379 BasicBlock *Pred = Succ->getSinglePredecessor();
Justin Bognerab6a5132016-05-03 21:47:32 +0000380 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
Fiona Glaserb417d462016-01-29 22:35:36 +0000381 continue;
382
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000383 // Merge Succ into Pred and delete it.
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000384 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
David Greene6a9c242018-06-19 09:43:36 +0000385
Fiona Glaserb417d462016-01-29 22:35:36 +0000386 Changed = true;
387 }
388
389 return Changed;
390}
391
Max Kazantsev46955b52018-11-01 09:42:50 +0000392static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
393 ScalarEvolution &SE, MemorySSAUpdater *MSSAU) {
394 bool Changed = false;
395
Max Kazantsevc04b5302018-11-20 05:43:32 +0000396 // Constant-fold terminators with known constant conditions.
397 Changed |= constantFoldTerminators(L, DT, LI);
398
Max Kazantsev46955b52018-11-01 09:42:50 +0000399 // Eliminate unconditional branches by merging blocks into their predecessors.
400 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
401
402 if (Changed)
403 SE.forgetTopmostLoop(&L);
404
405 return Changed;
406}
407
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000408PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
409 LoopStandardAnalysisResults &AR,
410 LPMUpdater &) {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000411 Optional<MemorySSAUpdater> MSSAU;
412 if (EnableMSSALoopDependency && AR.MSSA)
413 MSSAU = MemorySSAUpdater(AR.MSSA);
414 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
415 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
Justin Bognerab6a5132016-05-03 21:47:32 +0000416 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000417
Justin Bognerab6a5132016-05-03 21:47:32 +0000418 return getLoopPassPreservedAnalyses();
419}
420
421namespace {
422class LoopSimplifyCFGLegacyPass : public LoopPass {
423public:
424 static char ID; // Pass ID, replacement for typeid
425 LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
426 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
427 }
428
429 bool runOnLoop(Loop *L, LPPassManager &) override {
430 if (skipLoop(L))
431 return false;
432
433 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
434 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
David Greene6a9c242018-06-19 09:43:36 +0000435 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000436 Optional<MemorySSAUpdater> MSSAU;
437 if (EnableMSSALoopDependency) {
438 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
439 MSSAU = MemorySSAUpdater(MSSA);
440 if (VerifyMemorySSA)
441 MSSA->verifyMemorySSA();
442 }
443 return simplifyLoopCFG(*L, DT, LI, SE,
444 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
Justin Bognerab6a5132016-05-03 21:47:32 +0000445 }
446
447 void getAnalysisUsage(AnalysisUsage &AU) const override {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000448 if (EnableMSSALoopDependency) {
449 AU.addRequired<MemorySSAWrapperPass>();
450 AU.addPreserved<MemorySSAWrapperPass>();
451 }
Chandler Carruth49c22192016-05-12 22:19:39 +0000452 AU.addPreserved<DependenceAnalysisWrapperPass>();
Justin Bognerab6a5132016-05-03 21:47:32 +0000453 getLoopAnalysisUsage(AU);
454 }
455};
456}
457
458char LoopSimplifyCFGLegacyPass::ID = 0;
459INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
460 "Simplify loop CFG", false, false)
461INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000462INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Justin Bognerab6a5132016-05-03 21:47:32 +0000463INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
464 "Simplify loop CFG", false, false)
465
466Pass *llvm::createLoopSimplifyCFGPass() {
467 return new LoopSimplifyCFGLegacyPass();
Fiona Glaserb417d462016-01-29 22:35:36 +0000468}