blob: 6cfabff21e8305fd888f6656ef7f34ec10c60e20 [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
15#include "llvm/Constant.h"
Chris Lattner3f5823f2003-08-24 18:36:16 +000016#include "llvm/Intrinsics.h"
Chris Lattner466a0492002-05-21 20:50:24 +000017#include "llvm/iPHINode.h"
Chris Lattner3f5823f2003-08-24 18:36:16 +000018#include "llvm/iTerminators.h"
19#include "llvm/iOther.h"
Chris Lattner466a0492002-05-21 20:50:24 +000020#include "llvm/Support/CFG.h"
21#include <algorithm>
22#include <functional>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000023using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000024
Misha Brukman632df282002-10-29 23:06:16 +000025// PropagatePredecessors - This gets "Succ" ready to have the predecessors from
Chris Lattner466a0492002-05-21 20:50:24 +000026// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
27// have extra slots added to them to hold the merge edges from BB's
Chris Lattner31116ba2003-03-05 21:01:52 +000028// predecessors, and BB itself might have had PHI nodes in it. This function
29// returns true (failure) if the Succ BB already has a predecessor that is a
Misha Brukman8b2bd4e2003-10-10 17:57:28 +000030// predecessor of BB and incoming PHI arguments would not be discernible.
Chris Lattner466a0492002-05-21 20:50:24 +000031//
32// Assumption: Succ is the single successor for BB.
33//
Misha Brukman632df282002-10-29 23:06:16 +000034static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner466a0492002-05-21 20:50:24 +000035 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner5325c5f2002-09-24 00:09:26 +000036
37 if (!isa<PHINode>(Succ->front()))
38 return false; // We can make the transformation, no problem.
Chris Lattner466a0492002-05-21 20:50:24 +000039
40 // If there is more than one predecessor, and there are PHI nodes in
41 // the successor, then we need to add incoming edges for the PHI nodes
42 //
43 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
44
45 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattner31116ba2003-03-05 21:01:52 +000046 // Succ. If so, we cannot do the transformation if there are any PHI nodes
47 // with incompatible values coming in from the two edges!
Chris Lattner466a0492002-05-21 20:50:24 +000048 //
Chris Lattner31116ba2003-03-05 21:01:52 +000049 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
50 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
51 // Loop over all of the PHI nodes checking to see if there are
52 // incompatible values coming in.
Chris Lattnere54d2142003-03-05 21:36:33 +000053 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000054 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattner31116ba2003-03-05 21:01:52 +000055 // Loop up the entries in the PHI node for BB and for *PI if the values
56 // coming in are non-equal, we cannot merge these two blocks (instead we
57 // should insert a conditional move or something, then merge the
58 // blocks).
59 int Idx1 = PN->getBasicBlockIndex(BB);
60 int Idx2 = PN->getBasicBlockIndex(*PI);
61 assert(Idx1 != -1 && Idx2 != -1 &&
62 "Didn't have entries for my predecessors??");
63 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
64 return true; // Values are not equal...
65 }
66 }
Chris Lattner466a0492002-05-21 20:50:24 +000067
68 // Loop over all of the PHI nodes in the successor BB
69 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000070 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnera704ac82002-10-08 21:36:33 +000071 Value *OldVal = PN->removeIncomingValue(BB, false);
Chris Lattner466a0492002-05-21 20:50:24 +000072 assert(OldVal && "No entry in PHI for Pred BB!");
73
Chris Lattnere54d2142003-03-05 21:36:33 +000074 // If this incoming value is one of the PHI nodes in BB...
75 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
76 PHINode *OldValPN = cast<PHINode>(OldVal);
77 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
78 End = BBPreds.end(); PredI != End; ++PredI) {
79 PN->addIncoming(OldValPN->getIncomingValueForBlock(*PredI), *PredI);
80 }
81 } else {
82 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
83 End = BBPreds.end(); PredI != End; ++PredI) {
84 // Add an incoming value for each of the new incoming values...
85 PN->addIncoming(OldVal, *PredI);
86 }
Chris Lattner466a0492002-05-21 20:50:24 +000087 }
88 }
89 return false;
90}
91
92
93// SimplifyCFG - This function is used to do simplification of a CFG. For
94// example, it adjusts branches to branches to eliminate the extra hop, it
95// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattner31116ba2003-03-05 21:01:52 +000096// of the CFG. It returns true if a modification was made.
Chris Lattner466a0492002-05-21 20:50:24 +000097//
98// WARNING: The entry node of a function may not be simplified.
99//
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000100bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +0000101 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +0000102 Function *M = BB->getParent();
103
104 assert(BB && BB->getParent() && "Block not embedded in function!");
105 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattnerfda72b12002-06-25 16:12:52 +0000106 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner466a0492002-05-21 20:50:24 +0000107
Chris Lattner838b8452004-02-11 01:17:07 +0000108 // Check to see if the first instruction in this block is just an unwind. If
109 // so, replace any invoke instructions which use this as an exception
110 // destination with call instructions.
Chris Lattner3f5823f2003-08-24 18:36:16 +0000111 //
Chris Lattner04ecefe2003-09-08 19:44:26 +0000112 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator()))
113 if (BB->begin() == BasicBlock::iterator(UI)) { // Empty block?
114 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
115 while (!Preds.empty()) {
116 BasicBlock *Pred = Preds.back();
117 if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000118 if (II->getUnwindDest() == BB) {
Chris Lattner04ecefe2003-09-08 19:44:26 +0000119 // Insert a new branch instruction before the invoke, because this
120 // is now a fall through...
121 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
122 Pred->getInstList().remove(II); // Take out of symbol table
123
124 // Insert the call now...
125 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
126 CallInst *CI = new CallInst(II->getCalledValue(), Args,
127 II->getName(), BI);
128 // If the invoke produced a value, the Call now does instead
129 II->replaceAllUsesWith(CI);
130 delete II;
131 Changed = true;
132 }
133
134 Preds.pop_back();
Chris Lattner3f5823f2003-08-24 18:36:16 +0000135 }
Chris Lattner04ecefe2003-09-08 19:44:26 +0000136 }
Chris Lattner3f5823f2003-08-24 18:36:16 +0000137
Chris Lattner466a0492002-05-21 20:50:24 +0000138 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattner838b8452004-02-11 01:17:07 +0000139 if (pred_begin(BB) == pred_end(BB)) {
Chris Lattner466a0492002-05-21 20:50:24 +0000140 //cerr << "Removing BB: \n" << BB;
141
142 // Loop through all of our successors and make sure they know that one
143 // of their predecessors is going away.
144 for_each(succ_begin(BB), succ_end(BB),
145 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
146
147 while (!BB->empty()) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000148 Instruction &I = BB->back();
Chris Lattner466a0492002-05-21 20:50:24 +0000149 // If this instruction is used, replace uses with an arbitrary
150 // constant value. Because control flow can't get here, we don't care
151 // what we replace the value with. Note that since this block is
152 // unreachable, and all values contained within it must dominate their
153 // uses, that all uses will eventually be removed.
Chris Lattnerfda72b12002-06-25 16:12:52 +0000154 if (!I.use_empty())
Chris Lattner466a0492002-05-21 20:50:24 +0000155 // Make all users of this instruction reference the constant instead
Chris Lattnerfda72b12002-06-25 16:12:52 +0000156 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
Chris Lattner466a0492002-05-21 20:50:24 +0000157
158 // Remove the instruction from the basic block
Chris Lattnerfda72b12002-06-25 16:12:52 +0000159 BB->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +0000160 }
Chris Lattnerfda72b12002-06-25 16:12:52 +0000161 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000162 return true;
163 }
164
Chris Lattner031340a2003-08-17 19:41:53 +0000165 // Check to see if we can constant propagate this terminator instruction
166 // away...
Chris Lattner3f5823f2003-08-24 18:36:16 +0000167 Changed |= ConstantFoldTerminator(BB);
Chris Lattner031340a2003-08-17 19:41:53 +0000168
Chris Lattnere54d2142003-03-05 21:36:33 +0000169 // Check to see if this block has no non-phi instructions and only a single
170 // successor. If so, replace references to this basic block with references
171 // to the successor.
Chris Lattner466a0492002-05-21 20:50:24 +0000172 succ_iterator SI(succ_begin(BB));
173 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattnere54d2142003-03-05 21:36:33 +0000174
175 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
176 while (isa<PHINode>(*BBI)) ++BBI;
177
178 if (BBI->isTerminator()) { // Terminator is the only non-phi instruction!
Chris Lattner466a0492002-05-21 20:50:24 +0000179 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
180
181 if (Succ != BB) { // Arg, don't hurt infinite loops!
182 // If our successor has PHI nodes, then we need to update them to
183 // include entries for BB's predecessors, not for BB itself.
184 // Be careful though, if this transformation fails (returns true) then
185 // we cannot do this transformation!
186 //
Misha Brukman632df282002-10-29 23:06:16 +0000187 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
Chris Lattner466a0492002-05-21 20:50:24 +0000188 //cerr << "Killing Trivial BB: \n" << BB;
Chris Lattnerfda72b12002-06-25 16:12:52 +0000189 std::string OldName = BB->getName();
190
Chris Lattner569a57f2003-03-07 18:13:41 +0000191 std::vector<BasicBlock*>
192 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
193
Chris Lattnere54d2142003-03-05 21:36:33 +0000194 // Move all PHI nodes in BB to Succ if they are alive, otherwise
195 // delete them.
196 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
197 if (PN->use_empty())
198 BB->getInstList().erase(BB->begin()); // Nuke instruction...
199 else {
200 // The instruction is alive, so this means that Succ must have
201 // *ONLY* had BB as a predecessor, and the PHI node is still valid
Chris Lattner569a57f2003-03-07 18:13:41 +0000202 // now. Simply move it into Succ, because we know that BB
203 // strictly dominated Succ.
Chris Lattnere54d2142003-03-05 21:36:33 +0000204 BB->getInstList().remove(BB->begin());
205 Succ->getInstList().push_front(PN);
Chris Lattner569a57f2003-03-07 18:13:41 +0000206
207 // We need to add new entries for the PHI node to account for
208 // predecessors of Succ that the PHI node does not take into
209 // account. At this point, since we know that BB dominated succ,
210 // this means that we should any newly added incoming edges should
211 // use the PHI node as the value for these edges, because they are
212 // loop back edges.
213
214 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
215 if (OldSuccPreds[i] != BB)
216 PN->addIncoming(PN, OldSuccPreds[i]);
Chris Lattnere54d2142003-03-05 21:36:33 +0000217 }
218
Chris Lattner569a57f2003-03-07 18:13:41 +0000219 // Everything that jumped to BB now goes to Succ...
220 BB->replaceAllUsesWith(Succ);
221
Chris Lattnerfda72b12002-06-25 16:12:52 +0000222 // Delete the old basic block...
223 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000224
Chris Lattnerfda72b12002-06-25 16:12:52 +0000225 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
226 Succ->setName(OldName);
Chris Lattner466a0492002-05-21 20:50:24 +0000227
228 //cerr << "Function after removal: \n" << M;
229 return true;
230 }
231 }
232 }
233 }
234
235 // Merge basic blocks into their predecessor if there is only one distinct
236 // pred, and if there is only one distinct successor of the predecessor, and
237 // if there are no PHI nodes.
238 //
Chris Lattner838b8452004-02-11 01:17:07 +0000239 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
240 BasicBlock *OnlyPred = *PI++;
241 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
242 if (*PI != OnlyPred) {
243 OnlyPred = 0; // There are multiple different predecessors...
244 break;
245 }
246
247 BasicBlock *OnlySucc = 0;
248 if (OnlyPred && OnlyPred != BB && // Don't break self loops
249 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
250 // Check to see if there is only one distinct successor...
251 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
252 OnlySucc = BB;
253 for (; SI != SE; ++SI)
254 if (*SI != OnlySucc) {
255 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner466a0492002-05-21 20:50:24 +0000256 break;
257 }
Chris Lattner838b8452004-02-11 01:17:07 +0000258 }
259
260 if (OnlySucc) {
261 //cerr << "Merging: " << BB << "into: " << OnlyPred;
262 TerminatorInst *Term = OnlyPred->getTerminator();
263
264 // Resolve any PHI nodes at the start of the block. They are all
265 // guaranteed to have exactly one entry if they exist, unless there are
266 // multiple duplicate (but guaranteed to be equal) entries for the
267 // incoming edges. This occurs when there are multiple edges from
268 // OnlyPred to OnlySucc.
269 //
270 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
271 PN->replaceAllUsesWith(PN->getIncomingValue(0));
272 BB->getInstList().pop_front(); // Delete the phi node...
Chris Lattner466a0492002-05-21 20:50:24 +0000273 }
274
Chris Lattner838b8452004-02-11 01:17:07 +0000275 // Delete the unconditional branch from the predecessor...
276 OnlyPred->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +0000277
Chris Lattner838b8452004-02-11 01:17:07 +0000278 // Move all definitions in the successor to the predecessor...
279 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Chris Lattnerfda72b12002-06-25 16:12:52 +0000280
Chris Lattner838b8452004-02-11 01:17:07 +0000281 // Make all PHI nodes that referred to BB now refer to Pred as their
282 // source...
283 BB->replaceAllUsesWith(OnlyPred);
Chris Lattnerfda72b12002-06-25 16:12:52 +0000284
Chris Lattner838b8452004-02-11 01:17:07 +0000285 std::string OldName = BB->getName();
Chris Lattnerfda72b12002-06-25 16:12:52 +0000286
Chris Lattner838b8452004-02-11 01:17:07 +0000287 // Erase basic block from the function...
288 M->getBasicBlockList().erase(BB);
Chris Lattnerfda72b12002-06-25 16:12:52 +0000289
Chris Lattner838b8452004-02-11 01:17:07 +0000290 // Inherit predecessors name if it exists...
291 if (!OldName.empty() && !OnlyPred->hasName())
292 OnlyPred->setName(OldName);
Chris Lattner466a0492002-05-21 20:50:24 +0000293
Chris Lattner838b8452004-02-11 01:17:07 +0000294 return true;
Chris Lattner466a0492002-05-21 20:50:24 +0000295 }
296
Chris Lattner031340a2003-08-17 19:41:53 +0000297 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +0000298}