blob: ed51746b3ce32a5e034dd589d1ba8ebf128ff895 [file] [log] [blame]
Chris Lattnerfa7dad82002-05-21 20:49:37 +00001//===- SimplifyCFG.cpp - CFG Simplification Pass --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerfa7dad82002-05-21 20:49:37 +00009//
10// This file implements dead code elimination and basic block merging.
Gordon Henriksend5687672007-11-04 16:15:04 +000011// Specifically:
Chris Lattnerfa7dad82002-05-21 20:49:37 +000012//
Gordon Henriksend5687672007-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 Lattnerfa7dad82002-05-21 20:49:37 +000015// predecessor only has one successor.
Gordon Henriksend5687672007-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 Lattnerfa7dad82002-05-21 20:49:37 +000018//
19//===----------------------------------------------------------------------===//
20
Chris Lattner79a42ac2006-12-19 21:40:18 +000021#define DEBUG_TYPE "simplifycfg"
Chris Lattnerfa7dad82002-05-21 20:49:37 +000022#include "llvm/Transforms/Scalar.h"
23#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera67dd322004-10-18 03:00:50 +000024#include "llvm/Constants.h"
25#include "llvm/Instructions.h"
Chris Lattnerfa7dad82002-05-21 20:49:37 +000026#include "llvm/Module.h"
Chris Lattnera77e74e2007-11-14 06:19:25 +000027#include "llvm/ParameterAttributes.h"
Chris Lattnerfa7dad82002-05-21 20:49:37 +000028#include "llvm/Support/CFG.h"
Reid Spencer557ab152007-02-05 23:32:05 +000029#include "llvm/Support/Compiler.h"
Chris Lattnerfa7dad82002-05-21 20:49:37 +000030#include "llvm/Pass.h"
Chris Lattner61ce4df2007-11-13 07:32:38 +000031#include "llvm/ADT/SmallVector.h"
Chris Lattnera5403a52007-03-04 04:20:48 +000032#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000033#include "llvm/ADT/Statistic.h"
Chris Lattner49525f82004-01-09 06:02:20 +000034using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000035
Chris Lattner79a42ac2006-12-19 21:40:18 +000036STATISTIC(NumSimpl, "Number of blocks simplified");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000037
Chris Lattner79a42ac2006-12-19 21:40:18 +000038namespace {
Reid Spencer557ab152007-02-05 23:32:05 +000039 struct VISIBILITY_HIDDEN CFGSimplifyPass : public FunctionPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000040 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +000041 CFGSimplifyPass() : FunctionPass((intptr_t)&ID) {}
42
Chris Lattner113f4f42002-06-25 16:13:24 +000043 virtual bool runOnFunction(Function &F);
Chris Lattnerfa7dad82002-05-21 20:49:37 +000044 };
Devang Patel8c78a0b2007-05-03 01:11:54 +000045 char CFGSimplifyPass::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +000046 RegisterPass<CFGSimplifyPass> X("simplifycfg", "Simplify the CFG");
Chris Lattnerfa7dad82002-05-21 20:49:37 +000047}
48
Brian Gaeke960707c2003-11-11 22:41:34 +000049// Public interface to the CFGSimplification pass
Chris Lattner49525f82004-01-09 06:02:20 +000050FunctionPass *llvm::createCFGSimplificationPass() {
Chris Lattnerfa7dad82002-05-21 20:49:37 +000051 return new CFGSimplifyPass();
52}
53
Chris Lattnera77e74e2007-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 Sandsa915b532007-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 Sandsa915b532007-11-22 22:24:59 +000091}
92
Chris Lattnera5403a52007-03-04 04:20:48 +000093static bool MarkAliveBlocks(BasicBlock *BB,
Chris Lattner61ce4df2007-11-13 07:32:38 +000094 SmallPtrSet<BasicBlock*, 128> &Reachable) {
Chris Lattner108083e2007-04-05 01:27:02 +000095
Chris Lattner61ce4df2007-11-13 07:32:38 +000096 SmallVector<BasicBlock*, 128> Worklist;
Chris Lattner108083e2007-04-05 01:27:02 +000097 Worklist.push_back(BB);
98 bool Changed = false;
99 while (!Worklist.empty()) {
100 BB = Worklist.back();
101 Worklist.pop_back();
102
103 if (!Reachable.insert(BB))
104 continue;
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000105
Chris Lattner108083e2007-04-05 01:27:02 +0000106 // Do a quick scan of the basic block, turning any obviously unreachable
107 // instructions into LLVM unreachable insts. The instruction combining pass
Duncan Sandsa915b532007-11-22 22:24:59 +0000108 // canonicalizes unreachable insts into stores to null or undef.
Chris Lattnera77e74e2007-11-14 06:19:25 +0000109 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
110 if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
Duncan Sands5208d1a2007-11-28 17:07:01 +0000111 if (CI->paramHasAttr(0, ParamAttr::NoReturn)) {
Chris Lattnera77e74e2007-11-14 06:19:25 +0000112 // If we found a call to a no-return function, insert an unreachable
113 // instruction after it. Make sure there isn't *already* one there
114 // though.
115 ++BBI;
116 if (!isa<UnreachableInst>(BBI)) {
117 ChangeToUnreachable(BBI);
118 Changed = true;
Chris Lattner108083e2007-04-05 01:27:02 +0000119 }
120 break;
Chris Lattnera67dd322004-10-18 03:00:50 +0000121 }
Chris Lattnera77e74e2007-11-14 06:19:25 +0000122 }
123
124 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
125 if (isa<ConstantPointerNull>(SI->getOperand(1)) ||
126 isa<UndefValue>(SI->getOperand(1))) {
127 ChangeToUnreachable(SI);
128 Changed = true;
129 break;
130 }
131 }
Chris Lattnera67dd322004-10-18 03:00:50 +0000132
Duncan Sandsa915b532007-11-22 22:24:59 +0000133 // Turn invokes that call 'nounwind' functions into ordinary calls.
134 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
Duncan Sands5208d1a2007-11-28 17:07:01 +0000135 if (II->paramHasAttr(0, ParamAttr::NoUnwind)) {
Duncan Sandsa915b532007-11-22 22:24:59 +0000136 ChangeToCall(II);
137 Changed = true;
138 }
139
Chris Lattner108083e2007-04-05 01:27:02 +0000140 Changed |= ConstantFoldTerminator(BB);
141 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
142 Worklist.push_back(*SI);
143 }
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000144 return Changed;
145}
146
Chris Lattner61ce4df2007-11-13 07:32:38 +0000147/// RemoveUnreachableBlocks - Remove blocks that are not reachable, even if they
148/// are in a dead cycle. Return true if a change was made, false otherwise.
149static bool RemoveUnreachableBlocks(Function &F) {
150 SmallPtrSet<BasicBlock*, 128> Reachable;
Chris Lattner113f4f42002-06-25 16:13:24 +0000151 bool Changed = MarkAliveBlocks(F.begin(), Reachable);
Chris Lattner61ce4df2007-11-13 07:32:38 +0000152
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000153 // If there are unreachable blocks in the CFG...
Chris Lattner61ce4df2007-11-13 07:32:38 +0000154 if (Reachable.size() == F.size())
155 return Changed;
156
157 assert(Reachable.size() < F.size());
158 NumSimpl += F.size()-Reachable.size();
159
160 // Loop over all of the basic blocks that are not reachable, dropping all of
161 // their internal references...
162 for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB)
163 if (!Reachable.count(BB)) {
164 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI!=SE; ++SI)
165 if (Reachable.count(*SI))
166 (*SI)->removePredecessor(BB);
167 BB->dropAllReferences();
168 }
169
170 for (Function::iterator I = ++F.begin(); I != F.end();)
171 if (!Reachable.count(I))
172 I = F.getBasicBlockList().erase(I);
173 else
174 ++I;
175
176 return true;
177}
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000178
Chris Lattner61ce4df2007-11-13 07:32:38 +0000179/// IterativeSimplifyCFG - Call SimplifyCFG on all the blocks in the function,
180/// iterating until no more changes are made.
181static bool IterativeSimplifyCFG(Function &F) {
182 bool Changed = false;
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000183 bool LocalChange = true;
184 while (LocalChange) {
185 LocalChange = false;
Chris Lattner61ce4df2007-11-13 07:32:38 +0000186
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000187 // Loop over all of the basic blocks (except the first one) and remove them
188 // if they are unneeded...
189 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000190 for (Function::iterator BBIt = ++F.begin(); BBIt != F.end(); ) {
191 if (SimplifyCFG(BBIt++)) {
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000192 LocalChange = true;
193 ++NumSimpl;
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000194 }
195 }
196 Changed |= LocalChange;
197 }
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000198 return Changed;
199}
Chris Lattner61ce4df2007-11-13 07:32:38 +0000200
201// It is possible that we may require multiple passes over the code to fully
202// simplify the CFG.
203//
204bool CFGSimplifyPass::runOnFunction(Function &F) {
205 bool EverChanged = RemoveUnreachableBlocks(F);
206 EverChanged |= IterativeSimplifyCFG(F);
207
208 // If neither pass changed anything, we're done.
209 if (!EverChanged) return false;
210
211 // IterativeSimplifyCFG can (rarely) make some loops dead. If this happens,
212 // RemoveUnreachableBlocks is needed to nuke them, which means we should
213 // iterate between the two optimizations. We structure the code like this to
214 // avoid reruning IterativeSimplifyCFG if the second pass of
215 // RemoveUnreachableBlocks doesn't do anything.
216 if (!RemoveUnreachableBlocks(F))
217 return true;
218
219 do {
220 EverChanged = IterativeSimplifyCFG(F);
221 EverChanged |= RemoveUnreachableBlocks(F);
222 } while (EverChanged);
223
224 return true;
225}