blob: ed0d45be26b826a3d3d30fd17f7cdb28f002c134 [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2//
Chris Lattnera704ac82002-10-08 21:36:33 +00003// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +00004//
5//===----------------------------------------------------------------------===//
6
7#include "llvm/Transforms/Utils/Local.h"
8#include "llvm/Constant.h"
9#include "llvm/iPHINode.h"
10#include "llvm/Support/CFG.h"
11#include <algorithm>
12#include <functional>
13
Misha Brukman632df282002-10-29 23:06:16 +000014// PropagatePredecessors - This gets "Succ" ready to have the predecessors from
Chris Lattner466a0492002-05-21 20:50:24 +000015// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
16// have extra slots added to them to hold the merge edges from BB's
Chris Lattner31116ba2003-03-05 21:01:52 +000017// predecessors, and BB itself might have had PHI nodes in it. This function
18// returns true (failure) if the Succ BB already has a predecessor that is a
19// predecessor of BB and incoming PHI arguments would not be discernable.
Chris Lattner466a0492002-05-21 20:50:24 +000020//
21// Assumption: Succ is the single successor for BB.
22//
Misha Brukman632df282002-10-29 23:06:16 +000023static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner466a0492002-05-21 20:50:24 +000024 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner5325c5f2002-09-24 00:09:26 +000025
26 if (!isa<PHINode>(Succ->front()))
27 return false; // We can make the transformation, no problem.
Chris Lattner466a0492002-05-21 20:50:24 +000028
29 // If there is more than one predecessor, and there are PHI nodes in
30 // the successor, then we need to add incoming edges for the PHI nodes
31 //
32 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
33
34 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattner31116ba2003-03-05 21:01:52 +000035 // Succ. If so, we cannot do the transformation if there are any PHI nodes
36 // with incompatible values coming in from the two edges!
Chris Lattner466a0492002-05-21 20:50:24 +000037 //
Chris Lattner31116ba2003-03-05 21:01:52 +000038 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
39 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
40 // Loop over all of the PHI nodes checking to see if there are
41 // incompatible values coming in.
Chris Lattnere54d2142003-03-05 21:36:33 +000042 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000043 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattner31116ba2003-03-05 21:01:52 +000044 // Loop up the entries in the PHI node for BB and for *PI if the values
45 // coming in are non-equal, we cannot merge these two blocks (instead we
46 // should insert a conditional move or something, then merge the
47 // blocks).
48 int Idx1 = PN->getBasicBlockIndex(BB);
49 int Idx2 = PN->getBasicBlockIndex(*PI);
50 assert(Idx1 != -1 && Idx2 != -1 &&
51 "Didn't have entries for my predecessors??");
52 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
53 return true; // Values are not equal...
54 }
55 }
Chris Lattner466a0492002-05-21 20:50:24 +000056
57 // Loop over all of the PHI nodes in the successor BB
58 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000059 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnera704ac82002-10-08 21:36:33 +000060 Value *OldVal = PN->removeIncomingValue(BB, false);
Chris Lattner466a0492002-05-21 20:50:24 +000061 assert(OldVal && "No entry in PHI for Pred BB!");
62
Chris Lattnere54d2142003-03-05 21:36:33 +000063 // If this incoming value is one of the PHI nodes in BB...
64 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
65 PHINode *OldValPN = cast<PHINode>(OldVal);
66 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
67 End = BBPreds.end(); PredI != End; ++PredI) {
68 PN->addIncoming(OldValPN->getIncomingValueForBlock(*PredI), *PredI);
69 }
70 } else {
71 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
72 End = BBPreds.end(); PredI != End; ++PredI) {
73 // Add an incoming value for each of the new incoming values...
74 PN->addIncoming(OldVal, *PredI);
75 }
Chris Lattner466a0492002-05-21 20:50:24 +000076 }
77 }
78 return false;
79}
80
81
82// SimplifyCFG - This function is used to do simplification of a CFG. For
83// example, it adjusts branches to branches to eliminate the extra hop, it
84// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattner31116ba2003-03-05 21:01:52 +000085// of the CFG. It returns true if a modification was made.
Chris Lattner466a0492002-05-21 20:50:24 +000086//
87// WARNING: The entry node of a function may not be simplified.
88//
Chris Lattnerfda72b12002-06-25 16:12:52 +000089bool SimplifyCFG(BasicBlock *BB) {
Chris Lattner466a0492002-05-21 20:50:24 +000090 Function *M = BB->getParent();
91
92 assert(BB && BB->getParent() && "Block not embedded in function!");
93 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattnerfda72b12002-06-25 16:12:52 +000094 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner466a0492002-05-21 20:50:24 +000095
Chris Lattner466a0492002-05-21 20:50:24 +000096 // Remove basic blocks that have no predecessors... which are unreachable.
97 if (pred_begin(BB) == pred_end(BB) &&
98 !BB->hasConstantReferences()) {
99 //cerr << "Removing BB: \n" << BB;
100
101 // Loop through all of our successors and make sure they know that one
102 // of their predecessors is going away.
103 for_each(succ_begin(BB), succ_end(BB),
104 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
105
106 while (!BB->empty()) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000107 Instruction &I = BB->back();
Chris Lattner466a0492002-05-21 20:50:24 +0000108 // If this instruction is used, replace uses with an arbitrary
109 // constant value. Because control flow can't get here, we don't care
110 // what we replace the value with. Note that since this block is
111 // unreachable, and all values contained within it must dominate their
112 // uses, that all uses will eventually be removed.
Chris Lattnerfda72b12002-06-25 16:12:52 +0000113 if (!I.use_empty())
Chris Lattner466a0492002-05-21 20:50:24 +0000114 // Make all users of this instruction reference the constant instead
Chris Lattnerfda72b12002-06-25 16:12:52 +0000115 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
Chris Lattner466a0492002-05-21 20:50:24 +0000116
117 // Remove the instruction from the basic block
Chris Lattnerfda72b12002-06-25 16:12:52 +0000118 BB->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +0000119 }
Chris Lattnerfda72b12002-06-25 16:12:52 +0000120 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000121 return true;
122 }
123
Chris Lattner031340a2003-08-17 19:41:53 +0000124 // Check to see if we can constant propagate this terminator instruction
125 // away...
126 bool Changed = ConstantFoldTerminator(BB);
127
Chris Lattnere54d2142003-03-05 21:36:33 +0000128 // Check to see if this block has no non-phi instructions and only a single
129 // successor. If so, replace references to this basic block with references
130 // to the successor.
Chris Lattner466a0492002-05-21 20:50:24 +0000131 succ_iterator SI(succ_begin(BB));
132 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattnere54d2142003-03-05 21:36:33 +0000133
134 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
135 while (isa<PHINode>(*BBI)) ++BBI;
136
137 if (BBI->isTerminator()) { // Terminator is the only non-phi instruction!
Chris Lattner466a0492002-05-21 20:50:24 +0000138 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
139
140 if (Succ != BB) { // Arg, don't hurt infinite loops!
141 // If our successor has PHI nodes, then we need to update them to
142 // include entries for BB's predecessors, not for BB itself.
143 // Be careful though, if this transformation fails (returns true) then
144 // we cannot do this transformation!
145 //
Misha Brukman632df282002-10-29 23:06:16 +0000146 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
Chris Lattner466a0492002-05-21 20:50:24 +0000147 //cerr << "Killing Trivial BB: \n" << BB;
Chris Lattnerfda72b12002-06-25 16:12:52 +0000148 std::string OldName = BB->getName();
149
Chris Lattner569a57f2003-03-07 18:13:41 +0000150 std::vector<BasicBlock*>
151 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
152
Chris Lattnere54d2142003-03-05 21:36:33 +0000153 // Move all PHI nodes in BB to Succ if they are alive, otherwise
154 // delete them.
155 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
156 if (PN->use_empty())
157 BB->getInstList().erase(BB->begin()); // Nuke instruction...
158 else {
159 // The instruction is alive, so this means that Succ must have
160 // *ONLY* had BB as a predecessor, and the PHI node is still valid
Chris Lattner569a57f2003-03-07 18:13:41 +0000161 // now. Simply move it into Succ, because we know that BB
162 // strictly dominated Succ.
Chris Lattnere54d2142003-03-05 21:36:33 +0000163 BB->getInstList().remove(BB->begin());
164 Succ->getInstList().push_front(PN);
Chris Lattner569a57f2003-03-07 18:13:41 +0000165
166 // We need to add new entries for the PHI node to account for
167 // predecessors of Succ that the PHI node does not take into
168 // account. At this point, since we know that BB dominated succ,
169 // this means that we should any newly added incoming edges should
170 // use the PHI node as the value for these edges, because they are
171 // loop back edges.
172
173 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
174 if (OldSuccPreds[i] != BB)
175 PN->addIncoming(PN, OldSuccPreds[i]);
Chris Lattnere54d2142003-03-05 21:36:33 +0000176 }
177
Chris Lattner569a57f2003-03-07 18:13:41 +0000178 // Everything that jumped to BB now goes to Succ...
179 BB->replaceAllUsesWith(Succ);
180
Chris Lattnerfda72b12002-06-25 16:12:52 +0000181 // Delete the old basic block...
182 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000183
Chris Lattnerfda72b12002-06-25 16:12:52 +0000184 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
185 Succ->setName(OldName);
Chris Lattner466a0492002-05-21 20:50:24 +0000186
187 //cerr << "Function after removal: \n" << M;
188 return true;
189 }
190 }
191 }
192 }
193
194 // Merge basic blocks into their predecessor if there is only one distinct
195 // pred, and if there is only one distinct successor of the predecessor, and
196 // if there are no PHI nodes.
197 //
Chris Lattner1cec4d92002-07-29 21:26:30 +0000198 if (!BB->hasConstantReferences()) {
Chris Lattner466a0492002-05-21 20:50:24 +0000199 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
200 BasicBlock *OnlyPred = *PI++;
201 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
202 if (*PI != OnlyPred) {
203 OnlyPred = 0; // There are multiple different predecessors...
204 break;
205 }
206
207 BasicBlock *OnlySucc = 0;
Chris Lattneredc8c542003-08-05 16:27:44 +0000208 if (OnlyPred && OnlyPred != BB && // Don't break self loops
209 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
Chris Lattner466a0492002-05-21 20:50:24 +0000210 // Check to see if there is only one distinct successor...
211 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
212 OnlySucc = BB;
213 for (; SI != SE; ++SI)
214 if (*SI != OnlySucc) {
215 OnlySucc = 0; // There are multiple distinct successors!
216 break;
217 }
218 }
219
220 if (OnlySucc) {
221 //cerr << "Merging: " << BB << "into: " << OnlyPred;
222 TerminatorInst *Term = OnlyPred->getTerminator();
223
Chris Lattner1cec4d92002-07-29 21:26:30 +0000224 // Resolve any PHI nodes at the start of the block. They are all
Chris Lattnerd6dcd8e2002-09-24 16:09:17 +0000225 // guaranteed to have exactly one entry if they exist, unless there are
226 // multiple duplicate (but guaranteed to be equal) entries for the
227 // incoming edges. This occurs when there are multiple edges from
228 // OnlyPred to OnlySucc.
Chris Lattner1cec4d92002-07-29 21:26:30 +0000229 //
230 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
Chris Lattner1cec4d92002-07-29 21:26:30 +0000231 PN->replaceAllUsesWith(PN->getIncomingValue(0));
232 BB->getInstList().pop_front(); // Delete the phi node...
233 }
234
Chris Lattner466a0492002-05-21 20:50:24 +0000235 // Delete the unconditional branch from the predecessor...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000236 OnlyPred->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +0000237
238 // Move all definitions in the succecessor to the predecessor...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000239 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
240
Chris Lattner466a0492002-05-21 20:50:24 +0000241 // Make all PHI nodes that refered to BB now refer to Pred as their
242 // source...
243 BB->replaceAllUsesWith(OnlyPred);
Chris Lattnerfda72b12002-06-25 16:12:52 +0000244
245 std::string OldName = BB->getName();
246
247 // Erase basic block from the function...
248 M->getBasicBlockList().erase(BB);
249
Chris Lattner466a0492002-05-21 20:50:24 +0000250 // Inherit predecessors name if it exists...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000251 if (!OldName.empty() && !OnlyPred->hasName())
252 OnlyPred->setName(OldName);
Chris Lattner466a0492002-05-21 20:50:24 +0000253
Chris Lattner466a0492002-05-21 20:50:24 +0000254 return true;
255 }
256 }
257
Chris Lattner031340a2003-08-17 19:41:53 +0000258 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +0000259}