blob: a5f54b1326c1c4d6ca7ce0469fe7eabab842db79 [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>
23
Misha Brukman632df282002-10-29 23:06:16 +000024// PropagatePredecessors - This gets "Succ" ready to have the predecessors from
Chris Lattner466a0492002-05-21 20:50:24 +000025// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
26// have extra slots added to them to hold the merge edges from BB's
Chris Lattner31116ba2003-03-05 21:01:52 +000027// predecessors, and BB itself might have had PHI nodes in it. This function
28// returns true (failure) if the Succ BB already has a predecessor that is a
Misha Brukman8b2bd4e2003-10-10 17:57:28 +000029// predecessor of BB and incoming PHI arguments would not be discernible.
Chris Lattner466a0492002-05-21 20:50:24 +000030//
31// Assumption: Succ is the single successor for BB.
32//
Misha Brukman632df282002-10-29 23:06:16 +000033static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner466a0492002-05-21 20:50:24 +000034 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner5325c5f2002-09-24 00:09:26 +000035
36 if (!isa<PHINode>(Succ->front()))
37 return false; // We can make the transformation, no problem.
Chris Lattner466a0492002-05-21 20:50:24 +000038
39 // If there is more than one predecessor, and there are PHI nodes in
40 // the successor, then we need to add incoming edges for the PHI nodes
41 //
42 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
43
44 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattner31116ba2003-03-05 21:01:52 +000045 // Succ. If so, we cannot do the transformation if there are any PHI nodes
46 // with incompatible values coming in from the two edges!
Chris Lattner466a0492002-05-21 20:50:24 +000047 //
Chris Lattner31116ba2003-03-05 21:01:52 +000048 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
49 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
50 // Loop over all of the PHI nodes checking to see if there are
51 // incompatible values coming in.
Chris Lattnere54d2142003-03-05 21:36:33 +000052 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000053 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattner31116ba2003-03-05 21:01:52 +000054 // Loop up the entries in the PHI node for BB and for *PI if the values
55 // coming in are non-equal, we cannot merge these two blocks (instead we
56 // should insert a conditional move or something, then merge the
57 // blocks).
58 int Idx1 = PN->getBasicBlockIndex(BB);
59 int Idx2 = PN->getBasicBlockIndex(*PI);
60 assert(Idx1 != -1 && Idx2 != -1 &&
61 "Didn't have entries for my predecessors??");
62 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
63 return true; // Values are not equal...
64 }
65 }
Chris Lattner466a0492002-05-21 20:50:24 +000066
67 // Loop over all of the PHI nodes in the successor BB
68 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000069 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnera704ac82002-10-08 21:36:33 +000070 Value *OldVal = PN->removeIncomingValue(BB, false);
Chris Lattner466a0492002-05-21 20:50:24 +000071 assert(OldVal && "No entry in PHI for Pred BB!");
72
Chris Lattnere54d2142003-03-05 21:36:33 +000073 // If this incoming value is one of the PHI nodes in BB...
74 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
75 PHINode *OldValPN = cast<PHINode>(OldVal);
76 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
77 End = BBPreds.end(); PredI != End; ++PredI) {
78 PN->addIncoming(OldValPN->getIncomingValueForBlock(*PredI), *PredI);
79 }
80 } else {
81 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
82 End = BBPreds.end(); PredI != End; ++PredI) {
83 // Add an incoming value for each of the new incoming values...
84 PN->addIncoming(OldVal, *PredI);
85 }
Chris Lattner466a0492002-05-21 20:50:24 +000086 }
87 }
88 return false;
89}
90
91
92// SimplifyCFG - This function is used to do simplification of a CFG. For
93// example, it adjusts branches to branches to eliminate the extra hop, it
94// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattner31116ba2003-03-05 21:01:52 +000095// of the CFG. It returns true if a modification was made.
Chris Lattner466a0492002-05-21 20:50:24 +000096//
97// WARNING: The entry node of a function may not be simplified.
98//
Chris Lattnerfda72b12002-06-25 16:12:52 +000099bool SimplifyCFG(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +0000100 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +0000101 Function *M = BB->getParent();
102
103 assert(BB && BB->getParent() && "Block not embedded in function!");
104 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattnerfda72b12002-06-25 16:12:52 +0000105 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner466a0492002-05-21 20:50:24 +0000106
Chris Lattner3f5823f2003-08-24 18:36:16 +0000107 // Check to see if the first instruction in this block is just an
108 // 'llvm.unwind'. If so, replace any invoke instructions which use this as an
109 // exception destination with call instructions.
110 //
Chris Lattner04ecefe2003-09-08 19:44:26 +0000111 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator()))
112 if (BB->begin() == BasicBlock::iterator(UI)) { // Empty block?
113 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
114 while (!Preds.empty()) {
115 BasicBlock *Pred = Preds.back();
116 if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
117 if (II->getExceptionalDest() == BB) {
118 // Insert a new branch instruction before the invoke, because this
119 // is now a fall through...
120 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
121 Pred->getInstList().remove(II); // Take out of symbol table
122
123 // Insert the call now...
124 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
125 CallInst *CI = new CallInst(II->getCalledValue(), Args,
126 II->getName(), BI);
127 // If the invoke produced a value, the Call now does instead
128 II->replaceAllUsesWith(CI);
129 delete II;
130 Changed = true;
131 }
132
133 Preds.pop_back();
Chris Lattner3f5823f2003-08-24 18:36:16 +0000134 }
Chris Lattner04ecefe2003-09-08 19:44:26 +0000135 }
Chris Lattner3f5823f2003-08-24 18:36:16 +0000136
Chris Lattner466a0492002-05-21 20:50:24 +0000137 // Remove basic blocks that have no predecessors... which are unreachable.
138 if (pred_begin(BB) == pred_end(BB) &&
139 !BB->hasConstantReferences()) {
140 //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 Lattner1cec4d92002-07-29 21:26:30 +0000239 if (!BB->hasConstantReferences()) {
Chris Lattner466a0492002-05-21 20:50:24 +0000240 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
241 BasicBlock *OnlyPred = *PI++;
242 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
243 if (*PI != OnlyPred) {
244 OnlyPred = 0; // There are multiple different predecessors...
245 break;
246 }
247
248 BasicBlock *OnlySucc = 0;
Chris Lattneredc8c542003-08-05 16:27:44 +0000249 if (OnlyPred && OnlyPred != BB && // Don't break self loops
250 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
Chris Lattner466a0492002-05-21 20:50:24 +0000251 // Check to see if there is only one distinct successor...
252 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
253 OnlySucc = BB;
254 for (; SI != SE; ++SI)
255 if (*SI != OnlySucc) {
256 OnlySucc = 0; // There are multiple distinct successors!
257 break;
258 }
259 }
260
261 if (OnlySucc) {
262 //cerr << "Merging: " << BB << "into: " << OnlyPred;
263 TerminatorInst *Term = OnlyPred->getTerminator();
264
Chris Lattner1cec4d92002-07-29 21:26:30 +0000265 // Resolve any PHI nodes at the start of the block. They are all
Chris Lattnerd6dcd8e2002-09-24 16:09:17 +0000266 // guaranteed to have exactly one entry if they exist, unless there are
267 // multiple duplicate (but guaranteed to be equal) entries for the
268 // incoming edges. This occurs when there are multiple edges from
269 // OnlyPred to OnlySucc.
Chris Lattner1cec4d92002-07-29 21:26:30 +0000270 //
271 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
Chris Lattner1cec4d92002-07-29 21:26:30 +0000272 PN->replaceAllUsesWith(PN->getIncomingValue(0));
273 BB->getInstList().pop_front(); // Delete the phi node...
274 }
275
Chris Lattner466a0492002-05-21 20:50:24 +0000276 // Delete the unconditional branch from the predecessor...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000277 OnlyPred->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +0000278
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000279 // Move all definitions in the successor to the predecessor...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000280 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
281
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000282 // Make all PHI nodes that referred to BB now refer to Pred as their
Chris Lattner466a0492002-05-21 20:50:24 +0000283 // source...
284 BB->replaceAllUsesWith(OnlyPred);
Chris Lattnerfda72b12002-06-25 16:12:52 +0000285
286 std::string OldName = BB->getName();
287
288 // Erase basic block from the function...
289 M->getBasicBlockList().erase(BB);
290
Chris Lattner466a0492002-05-21 20:50:24 +0000291 // Inherit predecessors name if it exists...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000292 if (!OldName.empty() && !OnlyPred->hasName())
293 OnlyPred->setName(OldName);
Chris Lattner466a0492002-05-21 20:50:24 +0000294
Chris Lattner466a0492002-05-21 20:50:24 +0000295 return true;
296 }
297 }
298
Chris Lattner031340a2003-08-17 19:41:53 +0000299 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +0000300}