blob: 64ea2c7f603c8c933b5f28357a3d580abe7c7f9c [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?");
229 }
230
231 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
232 /// unconditional branches.
233 void foldTerminators() {
234 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
235
236 for (BasicBlock *BB : FoldCandidates) {
237 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
238 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
239 assert(TheOnlySucc && "Should have one live successor!");
240
241 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
242 << " with an unconditional branch to the block "
243 << TheOnlySucc->getName() << "\n");
244
245 SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
246 // Remove all BB's successors except for the live one.
247 for (auto *Succ : successors(BB))
248 if (Succ != TheOnlySucc) {
249 DeadSuccessors.insert(Succ);
250 Succ->removePredecessor(BB);
251 }
252
253 IRBuilder<> Builder(BB->getContext());
254 Instruction *Term = BB->getTerminator();
255 Builder.SetInsertPoint(Term);
256 Builder.CreateBr(TheOnlySucc);
257 Term->eraseFromParent();
258
259 for (auto *DeadSucc : DeadSuccessors)
260 DTU.deleteEdge(BB, DeadSucc);
261
262 ++NumTerminatorsFolded;
263 }
264 }
265
266public:
267 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT)
268 : L(L), LI(LI), DT(DT) {}
269 bool run() {
270 assert(L.getLoopLatch() && "Should be single latch!");
271
272 // Collect all available information about status of blocks after constant
273 // folding.
274 analyze();
275
276 LLVM_DEBUG(dbgs() << "In function " << L.getHeader()->getParent()->getName()
277 << ": ");
278
279 // Nothing to constant-fold.
280 if (FoldCandidates.empty()) {
281 LLVM_DEBUG(
282 dbgs() << "No constant terminator folding candidates found in loop "
283 << L.getHeader()->getName() << "\n");
284 return false;
285 }
286
287 // TODO: Support deletion of the current loop.
288 if (DeleteCurrentLoop) {
289 LLVM_DEBUG(
290 dbgs()
291 << "Give up constant terminator folding in loop "
292 << L.getHeader()->getName()
293 << ": we don't currently support deletion of the current loop.\n");
294 return false;
295 }
296
297 // TODO: Support deletion of dead loop blocks.
298 if (!DeadLoopBlocks.empty()) {
299 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop "
300 << L.getHeader()->getName()
301 << ": we don't currently"
302 " support deletion of dead in-loop blocks.\n");
303 return false;
304 }
305
306 // TODO: Support dead loop exits.
307 if (!DeadExitBlocks.empty()) {
308 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop "
309 << L.getHeader()->getName()
310 << ": we don't currently support dead loop exits.\n");
311 return false;
312 }
313
314 // TODO: Support blocks that are not dead, but also not in loop after the
315 // folding.
316 if (BlocksInLoopAfterFolding.size() != L.getNumBlocks()) {
317 LLVM_DEBUG(
318 dbgs() << "Give up constant terminator folding in loop "
319 << L.getHeader()->getName()
320 << ": we don't currently"
321 " support blocks that are not dead, but will stop "
322 "being a part of the loop after constant-folding.\n");
323 return false;
324 }
325
326 // Dump analysis results.
327 LLVM_DEBUG(dump());
328
329 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
330 << " terminators in loop " << L.getHeader()->getName()
331 << "\n");
332
333 // Make the actual transforms.
334 foldTerminators();
335
336#ifndef NDEBUG
337 // Make sure that we have preserved all data structures after the transform.
338 DT.verify();
339 assert(DT.isReachableFromEntry(L.getHeader()));
340 LI.verify(DT);
341#endif
342
343 return true;
344 }
345};
346
347/// Turn branches and switches with known constant conditions into unconditional
348/// branches.
349static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI) {
350 // To keep things simple, only process loops with single latch. We
351 // canonicalize most loops to this form. We can support multi-latch if needed.
352 if (!L.getLoopLatch())
353 return false;
354
355 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT);
356 return BranchFolder.run();
357}
358
Max Kazantsev46955b52018-11-01 09:42:50 +0000359static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
360 LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Fiona Glaserb417d462016-01-29 22:35:36 +0000361 bool Changed = false;
Chijun Sima21a8b602018-08-03 05:08:17 +0000362 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Fiona Glaserb417d462016-01-29 22:35:36 +0000363 // Copy blocks into a temporary array to avoid iterator invalidation issues
364 // as we remove them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000365 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
Fiona Glaserb417d462016-01-29 22:35:36 +0000366
367 for (auto &Block : Blocks) {
368 // Attempt to merge blocks in the trivial case. Don't modify blocks which
369 // belong to other loops.
Fiona Glaser36e82302016-01-29 23:12:52 +0000370 BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
Fiona Glaserb417d462016-01-29 22:35:36 +0000371 if (!Succ)
372 continue;
373
374 BasicBlock *Pred = Succ->getSinglePredecessor();
Justin Bognerab6a5132016-05-03 21:47:32 +0000375 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
Fiona Glaserb417d462016-01-29 22:35:36 +0000376 continue;
377
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000378 // Merge Succ into Pred and delete it.
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000379 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
David Greene6a9c242018-06-19 09:43:36 +0000380
Fiona Glaserb417d462016-01-29 22:35:36 +0000381 Changed = true;
382 }
383
384 return Changed;
385}
386
Max Kazantsev46955b52018-11-01 09:42:50 +0000387static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
388 ScalarEvolution &SE, MemorySSAUpdater *MSSAU) {
389 bool Changed = false;
390
Max Kazantsevc04b5302018-11-20 05:43:32 +0000391 // Constant-fold terminators with known constant conditions.
392 Changed |= constantFoldTerminators(L, DT, LI);
393
Max Kazantsev46955b52018-11-01 09:42:50 +0000394 // Eliminate unconditional branches by merging blocks into their predecessors.
395 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
396
397 if (Changed)
398 SE.forgetTopmostLoop(&L);
399
400 return Changed;
401}
402
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000403PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
404 LoopStandardAnalysisResults &AR,
405 LPMUpdater &) {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000406 Optional<MemorySSAUpdater> MSSAU;
407 if (EnableMSSALoopDependency && AR.MSSA)
408 MSSAU = MemorySSAUpdater(AR.MSSA);
409 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
410 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
Justin Bognerab6a5132016-05-03 21:47:32 +0000411 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000412
Justin Bognerab6a5132016-05-03 21:47:32 +0000413 return getLoopPassPreservedAnalyses();
414}
415
416namespace {
417class LoopSimplifyCFGLegacyPass : public LoopPass {
418public:
419 static char ID; // Pass ID, replacement for typeid
420 LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
421 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
422 }
423
424 bool runOnLoop(Loop *L, LPPassManager &) override {
425 if (skipLoop(L))
426 return false;
427
428 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
429 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
David Greene6a9c242018-06-19 09:43:36 +0000430 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000431 Optional<MemorySSAUpdater> MSSAU;
432 if (EnableMSSALoopDependency) {
433 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
434 MSSAU = MemorySSAUpdater(MSSA);
435 if (VerifyMemorySSA)
436 MSSA->verifyMemorySSA();
437 }
438 return simplifyLoopCFG(*L, DT, LI, SE,
439 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
Justin Bognerab6a5132016-05-03 21:47:32 +0000440 }
441
442 void getAnalysisUsage(AnalysisUsage &AU) const override {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000443 if (EnableMSSALoopDependency) {
444 AU.addRequired<MemorySSAWrapperPass>();
445 AU.addPreserved<MemorySSAWrapperPass>();
446 }
Chandler Carruth49c22192016-05-12 22:19:39 +0000447 AU.addPreserved<DependenceAnalysisWrapperPass>();
Justin Bognerab6a5132016-05-03 21:47:32 +0000448 getLoopAnalysisUsage(AU);
449 }
450};
451}
452
453char LoopSimplifyCFGLegacyPass::ID = 0;
454INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
455 "Simplify loop CFG", false, false)
456INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000457INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Justin Bognerab6a5132016-05-03 21:47:32 +0000458INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
459 "Simplify loop CFG", false, false)
460
461Pass *llvm::createLoopSimplifyCFGPass() {
462 return new LoopSimplifyCFGLegacyPass();
Fiona Glaserb417d462016-01-29 22:35:36 +0000463}