1 //===- SimplifyCFG.cpp - CFG Simplification Pass --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements dead code elimination and basic block merging.
12 // Specifically, this:
13 // * removes basic blocks with no predecessors
14 // * merges a basic block into its predecessor if there is only one and the
15 // predecessor only has one successor.
16 // * Eliminates PHI nodes for basic blocks with a single predecessor
17 // * Eliminates a basic block that only contains an unconditional branch
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Transforms/Utils/Local.h"
23 #include "llvm/Module.h"
24 #include "llvm/Support/CFG.h"
25 #include "llvm/Pass.h"
26 #include "Support/Statistic.h"
31 Statistic<> NumSimpl("cfgsimplify", "Number of blocks simplified");
33 struct CFGSimplifyPass : public FunctionPass {
34 virtual bool runOnFunction(Function &F);
36 RegisterOpt<CFGSimplifyPass> X("simplifycfg", "Simplify the CFG");
39 // Public interface to the CFGSimplification pass
40 FunctionPass *llvm::createCFGSimplificationPass() {
41 return new CFGSimplifyPass();
44 static bool MarkAliveBlocks(BasicBlock *BB, std::set<BasicBlock*> &Reachable) {
45 if (Reachable.count(BB)) return false;
48 bool Changed = ConstantFoldTerminator(BB);
49 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
50 MarkAliveBlocks(*SI, Reachable);
56 // It is possible that we may require multiple passes over the code to fully
59 bool CFGSimplifyPass::runOnFunction(Function &F) {
60 std::set<BasicBlock*> Reachable;
61 bool Changed = MarkAliveBlocks(F.begin(), Reachable);
63 // If there are unreachable blocks in the CFG...
64 if (Reachable.size() != F.size()) {
65 assert(Reachable.size() < F.size());
66 NumSimpl += F.size()-Reachable.size();
68 // Loop over all of the basic blocks that are not reachable, dropping all of
69 // their internal references...
70 for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB)
71 if (!Reachable.count(BB)) {
72 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI!=SE; ++SI)
73 if (Reachable.count(*SI))
74 (*SI)->removePredecessor(BB);
75 BB->dropAllReferences();
78 for (Function::iterator I = ++F.begin(); I != F.end();)
79 if (!Reachable.count(I))
80 I = F.getBasicBlockList().erase(I);
87 bool LocalChange = true;
91 // Loop over all of the basic blocks (except the first one) and remove them
92 // if they are unneeded...
94 for (Function::iterator BBIt = ++F.begin(); BBIt != F.end(); ) {
95 if (SimplifyCFG(BBIt++)) {
100 Changed |= LocalChange;