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.
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 #define DEBUG_TYPE "simplifycfg"
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Constants.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ParameterAttributes.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Pass.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/Statistic.h"
36 STATISTIC(NumSimpl, "Number of blocks simplified");
39 struct VISIBILITY_HIDDEN CFGSimplifyPass : public FunctionPass {
40 static char ID; // Pass identification, replacement for typeid
41 CFGSimplifyPass() : FunctionPass((intptr_t)&ID) {}
43 virtual bool runOnFunction(Function &F);
45 char CFGSimplifyPass::ID = 0;
46 RegisterPass<CFGSimplifyPass> X("simplifycfg", "Simplify the CFG");
49 // Public interface to the CFGSimplification pass
50 FunctionPass *llvm::createCFGSimplificationPass() {
51 return new CFGSimplifyPass();
54 /// ChangeToUnreachable - Insert an unreachable instruction before the specified
55 /// instruction, making it and the rest of the code in the block dead.
56 static void ChangeToUnreachable(Instruction *I) {
57 BasicBlock *BB = I->getParent();
58 // Loop over all of the successors, removing BB's entry from any PHI
60 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
61 (*SI)->removePredecessor(BB);
63 new UnreachableInst(I);
65 // All instructions after this are dead.
66 BasicBlock::iterator BBI = I, BBE = BB->end();
68 if (!BBI->use_empty())
69 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
70 BB->getInstList().erase(BBI++);
74 /// ChangeToCall - Convert the specified invoke into a normal call.
75 static void ChangeToCall(InvokeInst *II) {
76 BasicBlock *BB = II->getParent();
77 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
78 CallInst *NewCall = new CallInst(II->getCalledValue(), Args.begin(),
80 NewCall->takeName(II);
81 NewCall->setCallingConv(II->getCallingConv());
82 NewCall->setParamAttrs(II->getParamAttrs());
83 II->replaceAllUsesWith(NewCall);
85 // Follow the call by a branch to the normal destination.
86 new BranchInst(II->getNormalDest(), II);
88 // Update PHI nodes in the unwind destination
89 II->getUnwindDest()->removePredecessor(BB);
90 BB->getInstList().erase(II);
93 /// IsNoReturn - Return true if the specified call is to a no-return function.
94 static bool IsNoReturn(const CallInst *CI) {
95 if (const ParamAttrsList *Attrs = CI->getParamAttrs())
96 if (Attrs->paramHasAttr(0, ParamAttr::NoReturn))
99 if (const Function *Callee = CI->getCalledFunction()) {
100 if (const ParamAttrsList *Attrs = Callee->getParamAttrs())
101 if (Attrs->paramHasAttr(0, ParamAttr::NoReturn))
104 const FunctionType *FT = Callee->getFunctionType();
105 if (const ParamAttrsList *Attrs = FT->getParamAttrs())
106 if (Attrs->paramHasAttr(0, ParamAttr::NoReturn))
112 /// IsNoUnwind - Return true if the specified invoke is to a no-unwind function.
113 static bool IsNoUnwind(const InvokeInst *II) {
114 if (const ParamAttrsList *Attrs = II->getParamAttrs())
115 if (Attrs->paramHasAttr(0, ParamAttr::NoUnwind))
118 if (const Function *Callee = II->getCalledFunction()) {
119 if (const ParamAttrsList *Attrs = Callee->getParamAttrs())
120 if (Attrs->paramHasAttr(0, ParamAttr::NoUnwind))
123 const FunctionType *FT = Callee->getFunctionType();
124 if (const ParamAttrsList *Attrs = FT->getParamAttrs())
125 if (Attrs->paramHasAttr(0, ParamAttr::NoUnwind))
132 static bool MarkAliveBlocks(BasicBlock *BB,
133 SmallPtrSet<BasicBlock*, 128> &Reachable) {
135 SmallVector<BasicBlock*, 128> Worklist;
136 Worklist.push_back(BB);
137 bool Changed = false;
138 while (!Worklist.empty()) {
139 BB = Worklist.back();
142 if (!Reachable.insert(BB))
145 // Do a quick scan of the basic block, turning any obviously unreachable
146 // instructions into LLVM unreachable insts. The instruction combining pass
147 // canonicalizes unreachable insts into stores to null or undef.
148 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
149 if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
150 if (IsNoReturn(CI)) {
151 // If we found a call to a no-return function, insert an unreachable
152 // instruction after it. Make sure there isn't *already* one there
155 if (!isa<UnreachableInst>(BBI)) {
156 ChangeToUnreachable(BBI);
163 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
164 if (isa<ConstantPointerNull>(SI->getOperand(1)) ||
165 isa<UndefValue>(SI->getOperand(1))) {
166 ChangeToUnreachable(SI);
172 // Turn invokes that call 'nounwind' functions into ordinary calls.
173 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
174 if (IsNoUnwind(II)) {
179 Changed |= ConstantFoldTerminator(BB);
180 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
181 Worklist.push_back(*SI);
186 /// RemoveUnreachableBlocks - Remove blocks that are not reachable, even if they
187 /// are in a dead cycle. Return true if a change was made, false otherwise.
188 static bool RemoveUnreachableBlocks(Function &F) {
189 SmallPtrSet<BasicBlock*, 128> Reachable;
190 bool Changed = MarkAliveBlocks(F.begin(), Reachable);
192 // If there are unreachable blocks in the CFG...
193 if (Reachable.size() == F.size())
196 assert(Reachable.size() < F.size());
197 NumSimpl += F.size()-Reachable.size();
199 // Loop over all of the basic blocks that are not reachable, dropping all of
200 // their internal references...
201 for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB)
202 if (!Reachable.count(BB)) {
203 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI!=SE; ++SI)
204 if (Reachable.count(*SI))
205 (*SI)->removePredecessor(BB);
206 BB->dropAllReferences();
209 for (Function::iterator I = ++F.begin(); I != F.end();)
210 if (!Reachable.count(I))
211 I = F.getBasicBlockList().erase(I);
218 /// IterativeSimplifyCFG - Call SimplifyCFG on all the blocks in the function,
219 /// iterating until no more changes are made.
220 static bool IterativeSimplifyCFG(Function &F) {
221 bool Changed = false;
222 bool LocalChange = true;
223 while (LocalChange) {
226 // Loop over all of the basic blocks (except the first one) and remove them
227 // if they are unneeded...
229 for (Function::iterator BBIt = ++F.begin(); BBIt != F.end(); ) {
230 if (SimplifyCFG(BBIt++)) {
235 Changed |= LocalChange;
240 // It is possible that we may require multiple passes over the code to fully
243 bool CFGSimplifyPass::runOnFunction(Function &F) {
244 bool EverChanged = RemoveUnreachableBlocks(F);
245 EverChanged |= IterativeSimplifyCFG(F);
247 // If neither pass changed anything, we're done.
248 if (!EverChanged) return false;
250 // IterativeSimplifyCFG can (rarely) make some loops dead. If this happens,
251 // RemoveUnreachableBlocks is needed to nuke them, which means we should
252 // iterate between the two optimizations. We structure the code like this to
253 // avoid reruning IterativeSimplifyCFG if the second pass of
254 // RemoveUnreachableBlocks doesn't do anything.
255 if (!RemoveUnreachableBlocks(F))
259 EverChanged = IterativeSimplifyCFG(F);
260 EverChanged |= RemoveUnreachableBlocks(F);
261 } while (EverChanged);