1 //===- SimplifyCFG.cpp - CFG Simplification Pass --------------------------===//
3 // This file implements dead code elimination and basic block merging.
6 // * removes basic blocks with no predecessors
7 // * merges a basic block into its predecessor if there is only one and the
8 // predecessor only has one successor.
9 // * Eliminates PHI nodes for basic blocks with a single predecessor
10 // * Eliminates a basic block that only contains an unconditional branch
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Module.h"
17 #include "llvm/Support/CFG.h"
18 #include "llvm/Pass.h"
19 #include "Support/Statistic.h"
23 Statistic<> NumSimpl("cfgsimplify", "Number of blocks simplified");
25 struct CFGSimplifyPass : public FunctionPass {
26 virtual bool runOnFunction(Function &F);
28 RegisterOpt<CFGSimplifyPass> X("simplifycfg", "Simplify the CFG");
31 FunctionPass *createCFGSimplificationPass() {
32 return new CFGSimplifyPass();
35 static bool MarkAliveBlocks(BasicBlock *BB, std::set<BasicBlock*> &Reachable) {
36 if (Reachable.count(BB)) return false;
39 bool Changed = ConstantFoldTerminator(BB);
40 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
41 MarkAliveBlocks(*SI, Reachable);
47 // It is possible that we may require multiple passes over the code to fully
50 bool CFGSimplifyPass::runOnFunction(Function &F) {
51 std::set<BasicBlock*> Reachable;
52 bool Changed = MarkAliveBlocks(F.begin(), Reachable);
54 // If there are unreachable blocks in the CFG...
55 if (Reachable.size() != F.size()) {
56 assert(Reachable.size() < F.size());
57 NumSimpl += F.size()-Reachable.size();
59 // Loop over all of the basic blocks that are not reachable, dropping all of
60 // their internal references...
61 for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB)
62 if (!Reachable.count(BB)) {
63 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI!=SE; ++SI)
64 if (Reachable.count(*SI))
65 (*SI)->removePredecessor(BB);
66 BB->dropAllReferences();
69 for (Function::iterator I = ++F.begin(); I != F.end();)
70 if (!Reachable.count(I))
71 I = F.getBasicBlockList().erase(I);
78 bool LocalChange = true;
82 // Loop over all of the basic blocks (except the first one) and remove them
83 // if they are unneeded...
85 for (Function::iterator BBIt = ++F.begin(); BBIt != F.end(); ) {
86 if (SimplifyCFG(BBIt++)) {
91 Changed |= LocalChange;