1 //===- SimplifyCFG.cpp ----------------------------------------------------===//
2 //
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the control flow graph (CFG) simplifications
11 // presented as part of the 'Getting Started With LLVM: Basics' tutorial at the
12 // US LLVM Developers Meeting 2019. It also contains additional material.
13 //
14 // The current file contains three different CFG simplifications. There are
15 // multiple versions of each implementation (e.g. _v1 and _v2), which implement
16 // additional functionality (e.g. preserving analysis like the DominatorTree) or
17 // use additional utilities to simplify the code (e.g. LLVM's PatternMatch.h).
18 // The available simplifications are:
19 //  1. Trivially Dead block Removal (removeDeadBlocks_v[1,2]).
20 //     This simplifications removes all blocks without predecessors in the CFG
21 //     from a function.
22 //  2. Conditional Branch Elimination (eliminateCondBranches_v[1,2,3])
23 //     This simplification replaces conditional branches with constant integer
24 //     conditions with unconditional branches.
25 //  3. Single Predecessor Block Merging (mergeIntoSinglePredecessor_v[1,2])
26 //     This simplification merges blocks with a single predecessor into the
27 //     predecessor, if that block has a single successor.
28 //
29 // TODOs
30 //  * Hook up pass to the new pass manager.
31 //  * Preserve LoopInfo.
32 //  * Add fixed point iteration to delete all dead blocks
33 //  * Add implementation using reachability to discover dead blocks.
34 //===----------------------------------------------------------------------===//
35 
36 #include "SimplifyCFG.h"
37 #include "InitializePasses.h"
38 #include "llvm/Analysis/DomTreeUpdater.h"
39 #include "llvm/IR/Dominators.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/PassManager.h"
42 #include "llvm/IR/PatternMatch.h"
43 #include "llvm/Support/CommandLine.h"
44 
45 using namespace llvm;
46 using namespace PatternMatch;
47 
48 enum TutorialVersion { V1, V2, V3 };
49 static cl::opt<TutorialVersion>
50     Version("tut-simplifycfg-version", cl::desc("Select tutorial version"),
51             cl::Hidden, cl::ValueOptional, cl::init(V1),
52             cl::values(clEnumValN(V1, "v1", "version 1"),
53                        clEnumValN(V2, "v2", "version 2"),
54                        clEnumValN(V3, "v3", "version 3"),
55                        // Sentinel value for unspecified option.
56                        clEnumValN(V3, "", "")));
57 
58 #define DEBUG_TYPE "tut-simplifycfg"
59 
60 // Remove trivially dead blocks. First version, not preserving the
61 // DominatorTree.
62 static bool removeDeadBlocks_v1(Function &F) {
63   bool Changed = false;
64 
65   // Remove trivially dead blocks.
66   for (BasicBlock &BB : make_early_inc_range(F)) {
67     // Skip blocks we know to not be trivially dead. We know a block is
68     // guaranteed to be dead, iff it is neither the entry block nor
69     // has any predecessors.
70     if (&F.getEntryBlock() == &BB || !pred_empty(&BB))
71       continue;
72 
73     // Notify successors of BB that BB is going to be removed. This removes
74     // incoming values from BB from PHIs in the successors. Note that this will
75     // not actually remove BB from the predecessor lists of its successors.
76     for (BasicBlock *Succ : successors(&BB))
77       Succ->removePredecessor(&BB);
78     // TODO: Find a better place to put such small variations.
79     // Alternatively, we can update the PHI nodes manually:
80     // for (PHINode &PN : make_early_inc_range(Succ->phis()))
81     //  PN.removeIncomingValue(&BB);
82 
83     // Replace all instructions in BB with an undef constant. The block is
84     // unreachable, so the results of the instructions should never get used.
85     while (!BB.empty()) {
86       Instruction &I = BB.back();
87       I.replaceAllUsesWith(UndefValue::get(I.getType()));
88       I.eraseFromParent();
89     }
90 
91     // Finally remove the basic block.
92     BB.eraseFromParent();
93     Changed = true;
94   }
95 
96   return Changed;
97 }
98 
99 // Remove trivially dead blocks. This is the second version and preserves the
100 // dominator tree.
101 static bool removeDeadBlocks_v2(Function &F, DominatorTree &DT) {
102   bool Changed = false;
103   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
104   SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
105 
106   // Remove trivially dead blocks.
107   for (BasicBlock &BB : make_early_inc_range(F)) {
108     // Skip blocks we know to not be trivially dead. We know a block is
109     // guaranteed to be dead, iff it is neither the entry block nor
110     // has any predecessors.
111     if (&F.getEntryBlock() == &BB || !pred_empty(&BB))
112       continue;
113 
114     // Notify successors of BB that BB is going to be removed. This removes
115     // incoming values from BB from PHIs in the successors. Note that this will
116     // not actually remove BB from the predecessor lists of its successors.
117     for (BasicBlock *Succ : successors(&BB)) {
118       Succ->removePredecessor(&BB);
119 
120       // Collect updates that need to be applied to the dominator tree.
121       DTUpdates.push_back({DominatorTree::Delete, &BB, Succ});
122     }
123 
124     // Remove BB via the DomTreeUpdater. DomTreeUpdater::deleteBB conveniently
125     // removes the instructions in BB as well.
126     DTU.deleteBB(&BB);
127     Changed = true;
128   }
129 
130   // Apply updates permissively, to remove duplicates.
131   DTU.applyUpdatesPermissive(DTUpdates);
132 
133   return Changed;
134 }
135 
136 // Eliminate branches with constant conditionals. This is the first version,
137 // which *does not* preserve the dominator tree.
138 static bool eliminateCondBranches_v1(Function &F) {
139   bool Changed = false;
140 
141   // Eliminate branches with constant conditionals.
142   for (BasicBlock &BB : F) {
143     // Skip blocks without conditional branches as terminators.
144     BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator());
145     if (!BI || !BI->isConditional())
146       continue;
147 
148     // Skip blocks with conditional branches without ConstantInt conditions.
149     ConstantInt *CI = dyn_cast<ConstantInt>(BI->getCondition());
150     if (!CI)
151       continue;
152 
153     // We use the branch condition (CI), to select the successor we remove:
154     // if CI == 1 (true), we remove the second successor, otherwise the first.
155     BasicBlock *RemovedSucc = BI->getSuccessor(CI->isOne());
156     // Tell RemovedSucc we will remove BB from its predecessors.
157     RemovedSucc->removePredecessor(&BB);
158 
159     // Replace the conditional branch with an unconditional one, by creating
160     // a new unconditional branch to the selected successor and removing the
161     // conditional one.
162     BranchInst::Create(BI->getSuccessor(CI->isZero()), BI);
163     BI->eraseFromParent();
164     Changed = true;
165   }
166 
167   return Changed;
168 }
169 
170 // Eliminate branches with constant conditionals. This is the second
171 // version, which *does* preserve the dominator tree.
172 static bool eliminateCondBranches_v2(Function &F, DominatorTree &DT) {
173   bool Changed = false;
174 
175   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
176   SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
177   // Eliminate branches with constant conditionals.
178   for (BasicBlock &BB : F) {
179     // Skip blocks without conditional branches as terminators.
180     BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator());
181     if (!BI || !BI->isConditional())
182       continue;
183 
184     // Skip blocks with conditional branches without ConstantInt conditions.
185     ConstantInt *CI = dyn_cast<ConstantInt>(BI->getCondition());
186     if (!CI)
187       continue;
188 
189     // We use the branch condition (CI), to select the successor we remove:
190     // if CI == 1 (true), we remove the second successor, otherwise the first.
191     BasicBlock *RemovedSucc = BI->getSuccessor(CI->isOne());
192     // Tell RemovedSucc we will remove BB from its predecessors.
193     RemovedSucc->removePredecessor(&BB);
194 
195     // Replace the conditional branch with an unconditional one, by creating
196     // a new unconditional branch to the selected successor and removing the
197     // conditional one.
198     BranchInst *NewBranch =
199         BranchInst::Create(BI->getSuccessor(CI->isZero()), BI);
200     BI->eraseFromParent();
201 
202     // Delete the edge between BB and RemovedSucc in the DominatorTree, iff
203     // the conditional branch did not use RemovedSucc as both the true and false
204     // branches.
205     if (NewBranch->getSuccessor(0) != RemovedSucc)
206       DTUpdates.push_back({DominatorTree::Delete, &BB, RemovedSucc});
207     Changed = true;
208   }
209 
210   // Apply updates permissively, to remove duplicates.
211   DTU.applyUpdatesPermissive(DTUpdates);
212 
213   return Changed;
214 }
215 
216 // Eliminate branches with constant conditionals. This is the third
217 // version, which uses PatternMatch.h.
218 static bool eliminateCondBranches_v3(Function &F, DominatorTree &DT) {
219   bool Changed = false;
220   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
221   SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
222 
223   // Eliminate branches with constant conditionals.
224   for (BasicBlock &BB : F) {
225     ConstantInt *CI = nullptr;
226     BasicBlock *TakenSucc, *RemovedSucc;
227     // Check if the terminator is a conditional branch, with constant integer
228     // condition and also capture the successor blocks as TakenSucc and
229     // RemovedSucc.
230     if (!match(BB.getTerminator(),
231                m_Br(m_ConstantInt(CI), m_BasicBlock(TakenSucc),
232                     m_BasicBlock(RemovedSucc))))
233       continue;
234 
235     // If the condition is false, swap TakenSucc and RemovedSucc.
236     if (CI->isZero())
237       std::swap(TakenSucc, RemovedSucc);
238 
239     // Tell RemovedSucc we will remove BB from its predecessors.
240     RemovedSucc->removePredecessor(&BB);
241 
242     // Replace the conditional branch with an unconditional one, by creating
243     // a new unconditional branch to the selected successor and removing the
244     // conditional one.
245 
246     BranchInst *NewBranch = BranchInst::Create(TakenSucc, BB.getTerminator());
247     BB.getTerminator()->eraseFromParent();
248 
249     // Delete the edge between BB and RemovedSucc in the DominatorTree, iff
250     // the conditional branch did not use RemovedSucc as both the true and false
251     // branches.
252     if (NewBranch->getSuccessor(0) != RemovedSucc)
253       DTUpdates.push_back({DominatorTree::Delete, &BB, RemovedSucc});
254     Changed = true;
255   }
256 
257   // Apply updates permissively, to remove duplicates.
258   DTU.applyUpdatesPermissive(DTUpdates);
259   return Changed;
260 }
261 
262 // Merge basic blocks into their single predecessor, if their predecessor has a
263 // single successor. This is the first version and does not preserve the
264 // DominatorTree.
265 static bool mergeIntoSinglePredecessor_v1(Function &F) {
266   bool Changed = false;
267 
268   // Merge blocks with single predecessors.
269   for (BasicBlock &BB : make_early_inc_range(F)) {
270     BasicBlock *Pred = BB.getSinglePredecessor();
271     // Make sure  BB has a single predecessor Pred and BB is the single
272     // successor of Pred.
273     if (!Pred || Pred->getSingleSuccessor() != &BB)
274       continue;
275 
276     // Do not try to merge self loops. That can happen in dead blocks.
277     if (Pred == &BB)
278       continue;
279 
280     // Need to replace it before nuking the branch.
281     BB.replaceAllUsesWith(Pred);
282     // PHI nodes in BB can only have a single incoming value. Remove them.
283     for (PHINode &PN : make_early_inc_range(BB.phis())) {
284       PN.replaceAllUsesWith(PN.getIncomingValue(0));
285       PN.eraseFromParent();
286     }
287     // Move all instructions from BB to Pred.
288     for (Instruction &I : make_early_inc_range(BB))
289       I.moveBefore(Pred->getTerminator());
290 
291     // Remove the Pred's terminator (which jumped to BB). BB's terminator
292     // will become Pred's terminator.
293     Pred->getTerminator()->eraseFromParent();
294     BB.eraseFromParent();
295 
296     Changed = true;
297   }
298 
299   return Changed;
300 }
301 
302 // Merge basic blocks into their single predecessor, if their predecessor has a
303 // single successor. This is the second version and does preserve the
304 // DominatorTree.
305 static bool mergeIntoSinglePredecessor_v2(Function &F, DominatorTree &DT) {
306   bool Changed = false;
307   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
308   SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
309 
310   // Merge blocks with single predecessors.
311   for (BasicBlock &BB : make_early_inc_range(F)) {
312     BasicBlock *Pred = BB.getSinglePredecessor();
313     // Make sure  BB has a single predecessor Pred and BB is the single
314     // successor of Pred.
315     if (!Pred || Pred->getSingleSuccessor() != &BB)
316       continue;
317 
318     // Do not try to merge self loops. That can happen in dead blocks.
319     if (Pred == &BB)
320       continue;
321 
322     // Tell DTU about the changes to the CFG: All edges from BB to its
323     // successors get removed and we add edges between Pred and BB's successors.
324     for (BasicBlock *Succ : successors(&BB)) {
325       DTUpdates.push_back({DominatorTree::Delete, &BB, Succ});
326       DTUpdates.push_back({DominatorTree::Insert, Pred, Succ});
327     }
328     // Also remove the edge between Pred and BB.
329     DTUpdates.push_back({DominatorTree::Delete, Pred, &BB});
330 
331     // Need to replace it before nuking the branch.
332     BB.replaceAllUsesWith(Pred);
333     // PHI nodes in BB can only have a single incoming value. Remove them.
334     for (PHINode &PN : make_early_inc_range(BB.phis())) {
335       PN.replaceAllUsesWith(PN.getIncomingValue(0));
336       PN.eraseFromParent();
337     }
338     // Move all instructions from BB to Pred.
339     for (Instruction &I : make_early_inc_range(BB))
340       I.moveBefore(Pred->getTerminator());
341 
342     // Remove the Pred's terminator (which jumped to BB). BB's terminator
343     // will become Pred's terminator.
344     Pred->getTerminator()->eraseFromParent();
345     DTU.deleteBB(&BB);
346 
347     Changed = true;
348   }
349 
350   // Apply updates permissively, to remove duplicates.
351   DTU.applyUpdatesPermissive(DTUpdates);
352   return Changed;
353 }
354 
355 static bool doSimplify_v1(Function &F) {
356   return eliminateCondBranches_v1(F) & mergeIntoSinglePredecessor_v1(F) &
357          removeDeadBlocks_v1(F);
358 }
359 
360 static bool doSimplify_v2(Function &F, DominatorTree &DT) {
361   return eliminateCondBranches_v2(F, DT) &
362          mergeIntoSinglePredecessor_v2(F, DT) & removeDeadBlocks_v2(F, DT);
363 }
364 
365 static bool doSimplify_v3(Function &F, DominatorTree &DT) {
366   return eliminateCondBranches_v3(F, DT) &
367          mergeIntoSinglePredecessor_v2(F, DT) & removeDeadBlocks_v2(F, DT);
368 }
369 
370 namespace {
371 struct SimplifyCFGLegacyPass : public FunctionPass {
372   static char ID;
373   SimplifyCFGLegacyPass() : FunctionPass(ID) {
374     initializeSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
375   }
376 
377   void getAnalysisUsage(AnalysisUsage &AU) const override {
378     AU.addRequired<DominatorTreeWrapperPass>();
379     // Version 1 of the implementation does not preserve the dominator tree.
380     if (Version != V1)
381       AU.addPreserved<DominatorTreeWrapperPass>();
382 
383     FunctionPass::getAnalysisUsage(AU);
384   }
385 
386   bool runOnFunction(Function &F) override {
387     if (skipFunction(F))
388       return false;
389 
390     switch (Version) {
391     case V1:
392       return doSimplify_v1(F);
393     case V2: {
394       auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
395       return doSimplify_v2(F, DT);
396     }
397     case V3: {
398       auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
399       return doSimplify_v3(F, DT);
400     }
401     }
402 
403     llvm_unreachable("Unsupported version");
404   }
405 };
406 } // namespace
407 
408 char SimplifyCFGLegacyPass::ID = 0;
409 INITIALIZE_PASS_BEGIN(SimplifyCFGLegacyPass, DEBUG_TYPE,
410                       "Tutorial CFG simplification", false, false)
411 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
412 INITIALIZE_PASS_END(SimplifyCFGLegacyPass, DEBUG_TYPE,
413                     "Tutorial CFG simplifications", false, false)
414