blob: 22d81c881ec4193a9ff93a7d53b36047b0df11d9 [file] [log] [blame]
Chris Lattner573527b2002-05-21 20:49:37 +00001//===- SimplifyCFG.cpp - CFG Simplification Pass --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner573527b2002-05-21 20:49:37 +00009//
10// This file implements dead code elimination and basic block merging.
Gordon Henriksenc86b6772007-11-04 16:15:04 +000011// Specifically:
Chris Lattner573527b2002-05-21 20:49:37 +000012//
Gordon Henriksenc86b6772007-11-04 16:15:04 +000013// * Removes basic blocks with no predecessors.
14// * Merges a basic block into its predecessor if there is only one and the
Chris Lattner573527b2002-05-21 20:49:37 +000015// predecessor only has one successor.
Gordon Henriksenc86b6772007-11-04 16:15:04 +000016// * Eliminates PHI nodes for basic blocks with a single predecessor.
17// * Eliminates a basic block that only contains an unconditional branch.
Chris Lattner573527b2002-05-21 20:49:37 +000018//
19//===----------------------------------------------------------------------===//
20
Chris Lattner0e5f4992006-12-19 21:40:18 +000021#define DEBUG_TYPE "simplifycfg"
Chris Lattner573527b2002-05-21 20:49:37 +000022#include "llvm/Transforms/Scalar.h"
23#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerfc5c1bb02004-10-18 03:00:50 +000024#include "llvm/Constants.h"
25#include "llvm/Instructions.h"
Chris Lattner573527b2002-05-21 20:49:37 +000026#include "llvm/Module.h"
Chris Lattner1b12d882007-11-14 06:19:25 +000027#include "llvm/ParameterAttributes.h"
Chris Lattner573527b2002-05-21 20:49:37 +000028#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000029#include "llvm/Support/Compiler.h"
Chris Lattner573527b2002-05-21 20:49:37 +000030#include "llvm/Pass.h"
Chris Lattnerb42c8f72007-11-13 07:32:38 +000031#include "llvm/ADT/SmallVector.h"
Chris Lattner55091782007-03-04 04:20:48 +000032#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/Statistic.h"
Chris Lattnerd7456022004-01-09 06:02:20 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Chris Lattner0e5f4992006-12-19 21:40:18 +000036STATISTIC(NumSimpl, "Number of blocks simplified");
Chris Lattnera92f6962002-10-01 22:38:41 +000037
Chris Lattner0e5f4992006-12-19 21:40:18 +000038namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000039 struct VISIBILITY_HIDDEN CFGSimplifyPass : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000040 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000041 CFGSimplifyPass() : FunctionPass((intptr_t)&ID) {}
42
Chris Lattner7e708292002-06-25 16:13:24 +000043 virtual bool runOnFunction(Function &F);
Chris Lattner573527b2002-05-21 20:49:37 +000044 };
Devang Patel19974732007-05-03 01:11:54 +000045 char CFGSimplifyPass::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000046 RegisterPass<CFGSimplifyPass> X("simplifycfg", "Simplify the CFG");
Chris Lattner573527b2002-05-21 20:49:37 +000047}
48
Brian Gaeked0fde302003-11-11 22:41:34 +000049// Public interface to the CFGSimplification pass
Chris Lattnerd7456022004-01-09 06:02:20 +000050FunctionPass *llvm::createCFGSimplificationPass() {
Chris Lattner573527b2002-05-21 20:49:37 +000051 return new CFGSimplifyPass();
52}
53
Chris Lattner1b12d882007-11-14 06:19:25 +000054/// ChangeToUnreachable - Insert an unreachable instruction before the specified
55/// instruction, making it and the rest of the code in the block dead.
56static void ChangeToUnreachable(Instruction *I) {
57 BasicBlock *BB = I->getParent();
58 // Loop over all of the successors, removing BB's entry from any PHI
59 // nodes.
60 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
61 (*SI)->removePredecessor(BB);
62
63 new UnreachableInst(I);
64
65 // All instructions after this are dead.
66 BasicBlock::iterator BBI = I, BBE = BB->end();
67 while (BBI != BBE) {
68 if (!BBI->use_empty())
69 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
70 BB->getInstList().erase(BBI++);
71 }
72}
73
Duncan Sands73d4bb62007-11-22 22:24:59 +000074/// ChangeToCall - Convert the specified invoke into a normal call.
75static 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(),
79 Args.end(), "", II);
80 NewCall->takeName(II);
81 NewCall->setCallingConv(II->getCallingConv());
82 NewCall->setParamAttrs(II->getParamAttrs());
83 II->replaceAllUsesWith(NewCall);
84
85 // Follow the call by a branch to the normal destination.
86 new BranchInst(II->getNormalDest(), II);
87
88 // Update PHI nodes in the unwind destination
89 II->getUnwindDest()->removePredecessor(BB);
90 BB->getInstList().erase(II);
Duncan Sands73d4bb62007-11-22 22:24:59 +000091}
92
Chris Lattner1b12d882007-11-14 06:19:25 +000093/// IsNoReturn - Return true if the specified call is to a no-return function.
94static bool IsNoReturn(const CallInst *CI) {
95 if (const ParamAttrsList *Attrs = CI->getParamAttrs())
96 if (Attrs->paramHasAttr(0, ParamAttr::NoReturn))
97 return true;
98
Duncan Sandsdc024672007-11-27 13:23:08 +000099 if (const Function *Callee = CI->getCalledFunction())
Chris Lattner1b12d882007-11-14 06:19:25 +0000100 if (const ParamAttrsList *Attrs = Callee->getParamAttrs())
101 if (Attrs->paramHasAttr(0, ParamAttr::NoReturn))
102 return true;
Duncan Sandsdc024672007-11-27 13:23:08 +0000103
Chris Lattner1b12d882007-11-14 06:19:25 +0000104 return false;
105}
106
Duncan Sands73d4bb62007-11-22 22:24:59 +0000107/// IsNoUnwind - Return true if the specified invoke is to a no-unwind function.
108static bool IsNoUnwind(const InvokeInst *II) {
109 if (const ParamAttrsList *Attrs = II->getParamAttrs())
110 if (Attrs->paramHasAttr(0, ParamAttr::NoUnwind))
111 return true;
112
Duncan Sandsdc024672007-11-27 13:23:08 +0000113 if (const Function *Callee = II->getCalledFunction())
Duncan Sands73d4bb62007-11-22 22:24:59 +0000114 if (const ParamAttrsList *Attrs = Callee->getParamAttrs())
115 if (Attrs->paramHasAttr(0, ParamAttr::NoUnwind))
116 return true;
Duncan Sandsdc024672007-11-27 13:23:08 +0000117
Duncan Sands73d4bb62007-11-22 22:24:59 +0000118 return false;
119}
120
Chris Lattner1b12d882007-11-14 06:19:25 +0000121
Chris Lattner55091782007-03-04 04:20:48 +0000122static bool MarkAliveBlocks(BasicBlock *BB,
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000123 SmallPtrSet<BasicBlock*, 128> &Reachable) {
Chris Lattner1984a3282007-04-05 01:27:02 +0000124
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000125 SmallVector<BasicBlock*, 128> Worklist;
Chris Lattner1984a3282007-04-05 01:27:02 +0000126 Worklist.push_back(BB);
127 bool Changed = false;
128 while (!Worklist.empty()) {
129 BB = Worklist.back();
130 Worklist.pop_back();
131
132 if (!Reachable.insert(BB))
133 continue;
Chris Lattner573527b2002-05-21 20:49:37 +0000134
Chris Lattner1984a3282007-04-05 01:27:02 +0000135 // Do a quick scan of the basic block, turning any obviously unreachable
136 // instructions into LLVM unreachable insts. The instruction combining pass
Duncan Sands73d4bb62007-11-22 22:24:59 +0000137 // canonicalizes unreachable insts into stores to null or undef.
Chris Lattner1b12d882007-11-14 06:19:25 +0000138 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
139 if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
140 if (IsNoReturn(CI)) {
141 // If we found a call to a no-return function, insert an unreachable
142 // instruction after it. Make sure there isn't *already* one there
143 // though.
144 ++BBI;
145 if (!isa<UnreachableInst>(BBI)) {
146 ChangeToUnreachable(BBI);
147 Changed = true;
Chris Lattner1984a3282007-04-05 01:27:02 +0000148 }
149 break;
Chris Lattnerfc5c1bb02004-10-18 03:00:50 +0000150 }
Chris Lattner1b12d882007-11-14 06:19:25 +0000151 }
152
153 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
154 if (isa<ConstantPointerNull>(SI->getOperand(1)) ||
155 isa<UndefValue>(SI->getOperand(1))) {
156 ChangeToUnreachable(SI);
157 Changed = true;
158 break;
159 }
160 }
Chris Lattnerfc5c1bb02004-10-18 03:00:50 +0000161
Duncan Sands73d4bb62007-11-22 22:24:59 +0000162 // Turn invokes that call 'nounwind' functions into ordinary calls.
163 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
164 if (IsNoUnwind(II)) {
165 ChangeToCall(II);
166 Changed = true;
167 }
168
Chris Lattner1984a3282007-04-05 01:27:02 +0000169 Changed |= ConstantFoldTerminator(BB);
170 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
171 Worklist.push_back(*SI);
172 }
Chris Lattner573527b2002-05-21 20:49:37 +0000173 return Changed;
174}
175
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000176/// RemoveUnreachableBlocks - Remove blocks that are not reachable, even if they
177/// are in a dead cycle. Return true if a change was made, false otherwise.
178static bool RemoveUnreachableBlocks(Function &F) {
179 SmallPtrSet<BasicBlock*, 128> Reachable;
Chris Lattner7e708292002-06-25 16:13:24 +0000180 bool Changed = MarkAliveBlocks(F.begin(), Reachable);
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000181
Chris Lattner573527b2002-05-21 20:49:37 +0000182 // If there are unreachable blocks in the CFG...
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000183 if (Reachable.size() == F.size())
184 return Changed;
185
186 assert(Reachable.size() < F.size());
187 NumSimpl += F.size()-Reachable.size();
188
189 // Loop over all of the basic blocks that are not reachable, dropping all of
190 // their internal references...
191 for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB)
192 if (!Reachable.count(BB)) {
193 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI!=SE; ++SI)
194 if (Reachable.count(*SI))
195 (*SI)->removePredecessor(BB);
196 BB->dropAllReferences();
197 }
198
199 for (Function::iterator I = ++F.begin(); I != F.end();)
200 if (!Reachable.count(I))
201 I = F.getBasicBlockList().erase(I);
202 else
203 ++I;
204
205 return true;
206}
Chris Lattner573527b2002-05-21 20:49:37 +0000207
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000208/// IterativeSimplifyCFG - Call SimplifyCFG on all the blocks in the function,
209/// iterating until no more changes are made.
210static bool IterativeSimplifyCFG(Function &F) {
211 bool Changed = false;
Chris Lattner573527b2002-05-21 20:49:37 +0000212 bool LocalChange = true;
213 while (LocalChange) {
214 LocalChange = false;
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000215
Chris Lattner573527b2002-05-21 20:49:37 +0000216 // Loop over all of the basic blocks (except the first one) and remove them
217 // if they are unneeded...
218 //
Chris Lattner7e708292002-06-25 16:13:24 +0000219 for (Function::iterator BBIt = ++F.begin(); BBIt != F.end(); ) {
220 if (SimplifyCFG(BBIt++)) {
Chris Lattner573527b2002-05-21 20:49:37 +0000221 LocalChange = true;
222 ++NumSimpl;
Chris Lattner573527b2002-05-21 20:49:37 +0000223 }
224 }
225 Changed |= LocalChange;
226 }
Chris Lattner573527b2002-05-21 20:49:37 +0000227 return Changed;
228}
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000229
230// It is possible that we may require multiple passes over the code to fully
231// simplify the CFG.
232//
233bool CFGSimplifyPass::runOnFunction(Function &F) {
234 bool EverChanged = RemoveUnreachableBlocks(F);
235 EverChanged |= IterativeSimplifyCFG(F);
236
237 // If neither pass changed anything, we're done.
238 if (!EverChanged) return false;
239
240 // IterativeSimplifyCFG can (rarely) make some loops dead. If this happens,
241 // RemoveUnreachableBlocks is needed to nuke them, which means we should
242 // iterate between the two optimizations. We structure the code like this to
243 // avoid reruning IterativeSimplifyCFG if the second pass of
244 // RemoveUnreachableBlocks doesn't do anything.
245 if (!RemoveUnreachableBlocks(F))
246 return true;
247
248 do {
249 EverChanged = IterativeSimplifyCFG(F);
250 EverChanged |= RemoveUnreachableBlocks(F);
251 } while (EverChanged);
252
253 return true;
254}