[sanitizer] Improve FreeBSD ASLR detection
[llvm-project.git] / llvm / examples / IRTransforms / SimplifyCFG.cpp
blob111d4538fae0fed8de37a04cbbb7a74c91ba87a9
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.
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.
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 //===----------------------------------------------------------------------===//
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/InitializePasses.h"
44 #include "llvm/Support/CommandLine.h"
46 using namespace llvm;
47 using namespace PatternMatch;
49 enum TutorialVersion { V1, V2, V3 };
50 static cl::opt<TutorialVersion>
51 Version("tut-simplifycfg-version", cl::desc("Select tutorial version"),
52 cl::Hidden, cl::ValueOptional, cl::init(V1),
53 cl::values(clEnumValN(V1, "v1", "version 1"),
54 clEnumValN(V2, "v2", "version 2"),
55 clEnumValN(V3, "v3", "version 3"),
56 // Sentinel value for unspecified option.
57 clEnumValN(V3, "", "")));
59 #define DEBUG_TYPE "tut-simplifycfg"
61 // Remove trivially dead blocks. First version, not preserving the
62 // DominatorTree.
63 static bool removeDeadBlocks_v1(Function &F) {
64 bool Changed = false;
66 // Remove trivially dead blocks.
67 for (BasicBlock &BB : make_early_inc_range(F)) {
68 // Skip blocks we know to not be trivially dead. We know a block is
69 // guaranteed to be dead, iff it is neither the entry block nor
70 // has any predecessors.
71 if (&F.getEntryBlock() == &BB || !pred_empty(&BB))
72 continue;
74 // Notify successors of BB that BB is going to be removed. This removes
75 // incoming values from BB from PHIs in the successors. Note that this will
76 // not actually remove BB from the predecessor lists of its successors.
77 for (BasicBlock *Succ : successors(&BB))
78 Succ->removePredecessor(&BB);
79 // TODO: Find a better place to put such small variations.
80 // Alternatively, we can update the PHI nodes manually:
81 // for (PHINode &PN : make_early_inc_range(Succ->phis()))
82 // PN.removeIncomingValue(&BB);
84 // Replace all instructions in BB with an undef constant. The block is
85 // unreachable, so the results of the instructions should never get used.
86 while (!BB.empty()) {
87 Instruction &I = BB.back();
88 I.replaceAllUsesWith(UndefValue::get(I.getType()));
89 I.eraseFromParent();
92 // Finally remove the basic block.
93 BB.eraseFromParent();
94 Changed = true;
97 return Changed;
100 // Remove trivially dead blocks. This is the second version and preserves the
101 // dominator tree.
102 static bool removeDeadBlocks_v2(Function &F, DominatorTree &DT) {
103 bool Changed = false;
104 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
105 SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
107 // Remove trivially dead blocks.
108 for (BasicBlock &BB : make_early_inc_range(F)) {
109 // Skip blocks we know to not be trivially dead. We know a block is
110 // guaranteed to be dead, iff it is neither the entry block nor
111 // has any predecessors.
112 if (&F.getEntryBlock() == &BB || !pred_empty(&BB))
113 continue;
115 // Notify successors of BB that BB is going to be removed. This removes
116 // incoming values from BB from PHIs in the successors. Note that this will
117 // not actually remove BB from the predecessor lists of its successors.
118 for (BasicBlock *Succ : successors(&BB)) {
119 Succ->removePredecessor(&BB);
121 // Collect updates that need to be applied to the dominator tree.
122 DTUpdates.push_back({DominatorTree::Delete, &BB, Succ});
125 // Remove BB via the DomTreeUpdater. DomTreeUpdater::deleteBB conveniently
126 // removes the instructions in BB as well.
127 DTU.deleteBB(&BB);
128 Changed = true;
131 // Apply updates permissively, to remove duplicates.
132 DTU.applyUpdatesPermissive(DTUpdates);
134 return Changed;
137 // Eliminate branches with constant conditionals. This is the first version,
138 // which *does not* preserve the dominator tree.
139 static bool eliminateCondBranches_v1(Function &F) {
140 bool Changed = false;
142 // Eliminate branches with constant conditionals.
143 for (BasicBlock &BB : F) {
144 // Skip blocks without conditional branches as terminators.
145 BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator());
146 if (!BI || !BI->isConditional())
147 continue;
149 // Skip blocks with conditional branches without ConstantInt conditions.
150 ConstantInt *CI = dyn_cast<ConstantInt>(BI->getCondition());
151 if (!CI)
152 continue;
154 // We use the branch condition (CI), to select the successor we remove:
155 // if CI == 1 (true), we remove the second successor, otherwise the first.
156 BasicBlock *RemovedSucc = BI->getSuccessor(CI->isOne());
157 // Tell RemovedSucc we will remove BB from its predecessors.
158 RemovedSucc->removePredecessor(&BB);
160 // Replace the conditional branch with an unconditional one, by creating
161 // a new unconditional branch to the selected successor and removing the
162 // conditional one.
163 BranchInst::Create(BI->getSuccessor(CI->isZero()), BI);
164 BI->eraseFromParent();
165 Changed = true;
168 return Changed;
171 // Eliminate branches with constant conditionals. This is the second
172 // version, which *does* preserve the dominator tree.
173 static bool eliminateCondBranches_v2(Function &F, DominatorTree &DT) {
174 bool Changed = false;
176 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
177 SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
178 // Eliminate branches with constant conditionals.
179 for (BasicBlock &BB : F) {
180 // Skip blocks without conditional branches as terminators.
181 BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator());
182 if (!BI || !BI->isConditional())
183 continue;
185 // Skip blocks with conditional branches without ConstantInt conditions.
186 ConstantInt *CI = dyn_cast<ConstantInt>(BI->getCondition());
187 if (!CI)
188 continue;
190 // We use the branch condition (CI), to select the successor we remove:
191 // if CI == 1 (true), we remove the second successor, otherwise the first.
192 BasicBlock *RemovedSucc = BI->getSuccessor(CI->isOne());
193 // Tell RemovedSucc we will remove BB from its predecessors.
194 RemovedSucc->removePredecessor(&BB);
196 // Replace the conditional branch with an unconditional one, by creating
197 // a new unconditional branch to the selected successor and removing the
198 // conditional one.
199 BranchInst *NewBranch =
200 BranchInst::Create(BI->getSuccessor(CI->isZero()), BI);
201 BI->eraseFromParent();
203 // Delete the edge between BB and RemovedSucc in the DominatorTree, iff
204 // the conditional branch did not use RemovedSucc as both the true and false
205 // branches.
206 if (NewBranch->getSuccessor(0) != RemovedSucc)
207 DTUpdates.push_back({DominatorTree::Delete, &BB, RemovedSucc});
208 Changed = true;
211 // Apply updates permissively, to remove duplicates.
212 DTU.applyUpdatesPermissive(DTUpdates);
214 return Changed;
217 // Eliminate branches with constant conditionals. This is the third
218 // version, which uses PatternMatch.h.
219 static bool eliminateCondBranches_v3(Function &F, DominatorTree &DT) {
220 bool Changed = false;
221 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
222 SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
224 // Eliminate branches with constant conditionals.
225 for (BasicBlock &BB : F) {
226 ConstantInt *CI = nullptr;
227 BasicBlock *TakenSucc, *RemovedSucc;
228 // Check if the terminator is a conditional branch, with constant integer
229 // condition and also capture the successor blocks as TakenSucc and
230 // RemovedSucc.
231 if (!match(BB.getTerminator(),
232 m_Br(m_ConstantInt(CI), m_BasicBlock(TakenSucc),
233 m_BasicBlock(RemovedSucc))))
234 continue;
236 // If the condition is false, swap TakenSucc and RemovedSucc.
237 if (CI->isZero())
238 std::swap(TakenSucc, RemovedSucc);
240 // Tell RemovedSucc we will remove BB from its predecessors.
241 RemovedSucc->removePredecessor(&BB);
243 // Replace the conditional branch with an unconditional one, by creating
244 // a new unconditional branch to the selected successor and removing the
245 // conditional one.
247 BranchInst *NewBranch = BranchInst::Create(TakenSucc, BB.getTerminator());
248 BB.getTerminator()->eraseFromParent();
250 // Delete the edge between BB and RemovedSucc in the DominatorTree, iff
251 // the conditional branch did not use RemovedSucc as both the true and false
252 // branches.
253 if (NewBranch->getSuccessor(0) != RemovedSucc)
254 DTUpdates.push_back({DominatorTree::Delete, &BB, RemovedSucc});
255 Changed = true;
258 // Apply updates permissively, to remove duplicates.
259 DTU.applyUpdatesPermissive(DTUpdates);
260 return Changed;
263 // Merge basic blocks into their single predecessor, if their predecessor has a
264 // single successor. This is the first version and does not preserve the
265 // DominatorTree.
266 static bool mergeIntoSinglePredecessor_v1(Function &F) {
267 bool Changed = false;
269 // Merge blocks with single predecessors.
270 for (BasicBlock &BB : make_early_inc_range(F)) {
271 BasicBlock *Pred = BB.getSinglePredecessor();
272 // Make sure BB has a single predecessor Pred and BB is the single
273 // successor of Pred.
274 if (!Pred || Pred->getSingleSuccessor() != &BB)
275 continue;
277 // Do not try to merge self loops. That can happen in dead blocks.
278 if (Pred == &BB)
279 continue;
281 // Need to replace it before nuking the branch.
282 BB.replaceAllUsesWith(Pred);
283 // PHI nodes in BB can only have a single incoming value. Remove them.
284 for (PHINode &PN : make_early_inc_range(BB.phis())) {
285 PN.replaceAllUsesWith(PN.getIncomingValue(0));
286 PN.eraseFromParent();
288 // Move all instructions from BB to Pred.
289 for (Instruction &I : make_early_inc_range(BB))
290 I.moveBefore(Pred->getTerminator());
292 // Remove the Pred's terminator (which jumped to BB). BB's terminator
293 // will become Pred's terminator.
294 Pred->getTerminator()->eraseFromParent();
295 BB.eraseFromParent();
297 Changed = true;
300 return Changed;
303 // Merge basic blocks into their single predecessor, if their predecessor has a
304 // single successor. This is the second version and does preserve the
305 // DominatorTree.
306 static bool mergeIntoSinglePredecessor_v2(Function &F, DominatorTree &DT) {
307 bool Changed = false;
308 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
309 SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
311 // Merge blocks with single predecessors.
312 for (BasicBlock &BB : make_early_inc_range(F)) {
313 BasicBlock *Pred = BB.getSinglePredecessor();
314 // Make sure BB has a single predecessor Pred and BB is the single
315 // successor of Pred.
316 if (!Pred || Pred->getSingleSuccessor() != &BB)
317 continue;
319 // Do not try to merge self loops. That can happen in dead blocks.
320 if (Pred == &BB)
321 continue;
323 // Tell DTU about the changes to the CFG: All edges from BB to its
324 // successors get removed and we add edges between Pred and BB's successors.
325 for (BasicBlock *Succ : successors(&BB)) {
326 DTUpdates.push_back({DominatorTree::Delete, &BB, Succ});
327 DTUpdates.push_back({DominatorTree::Insert, Pred, Succ});
329 // Also remove the edge between Pred and BB.
330 DTUpdates.push_back({DominatorTree::Delete, Pred, &BB});
332 // Need to replace it before nuking the branch.
333 BB.replaceAllUsesWith(Pred);
334 // PHI nodes in BB can only have a single incoming value. Remove them.
335 for (PHINode &PN : make_early_inc_range(BB.phis())) {
336 PN.replaceAllUsesWith(PN.getIncomingValue(0));
337 PN.eraseFromParent();
339 // Move all instructions from BB to Pred.
340 for (Instruction &I : make_early_inc_range(BB))
341 I.moveBefore(Pred->getTerminator());
343 // Remove the Pred's terminator (which jumped to BB). BB's terminator
344 // will become Pred's terminator.
345 Pred->getTerminator()->eraseFromParent();
346 DTU.deleteBB(&BB);
348 Changed = true;
351 // Apply updates permissively, to remove duplicates.
352 DTU.applyUpdatesPermissive(DTUpdates);
353 return Changed;
356 static bool doSimplify_v1(Function &F) {
357 return (int)eliminateCondBranches_v1(F) | mergeIntoSinglePredecessor_v1(F) |
358 removeDeadBlocks_v1(F);
361 static bool doSimplify_v2(Function &F, DominatorTree &DT) {
362 return (int)eliminateCondBranches_v2(F, DT) |
363 mergeIntoSinglePredecessor_v2(F, DT) | removeDeadBlocks_v2(F, DT);
366 static bool doSimplify_v3(Function &F, DominatorTree &DT) {
367 return (int)eliminateCondBranches_v3(F, DT) |
368 mergeIntoSinglePredecessor_v2(F, DT) | removeDeadBlocks_v2(F, DT);
371 namespace {
372 struct SimplifyCFGLegacyPass : public FunctionPass {
373 static char ID;
374 SimplifyCFGLegacyPass() : FunctionPass(ID) {
375 initializeSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
378 void getAnalysisUsage(AnalysisUsage &AU) const override {
379 AU.addRequired<DominatorTreeWrapperPass>();
380 // Version 1 of the implementation does not preserve the dominator tree.
381 if (Version != V1)
382 AU.addPreserved<DominatorTreeWrapperPass>();
384 FunctionPass::getAnalysisUsage(AU);
387 bool runOnFunction(Function &F) override {
388 if (skipFunction(F))
389 return false;
391 switch (Version) {
392 case V1:
393 return doSimplify_v1(F);
394 case V2: {
395 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
396 return doSimplify_v2(F, DT);
398 case V3: {
399 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
400 return doSimplify_v3(F, DT);
404 llvm_unreachable("Unsupported version");
407 } // namespace
409 char SimplifyCFGLegacyPass::ID = 0;
410 INITIALIZE_PASS_BEGIN(SimplifyCFGLegacyPass, DEBUG_TYPE,
411 "Tutorial CFG simplification", false, false)
412 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
413 INITIALIZE_PASS_END(SimplifyCFGLegacyPass, DEBUG_TYPE,
414 "Tutorial CFG simplifications", false, false)