1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Peephole optimize the CFG.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/Constant.h"
16 #include "llvm/Intrinsics.h"
17 #include "llvm/iPHINode.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iOther.h"
20 #include "llvm/Support/CFG.h"
24 // PropagatePredecessors - This gets "Succ" ready to have the predecessors from
25 // "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
27 // 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
29 // predecessor of BB and incoming PHI arguments would not be discernible.
31 // Assumption: Succ is the single successor for BB.
33 static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
34 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
36 if (!isa<PHINode>(Succ->front()))
37 return false; // We can make the transformation, no problem.
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
42 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
44 // Check to see if one of the predecessors of BB is already a predecessor of
45 // Succ. If so, we cannot do the transformation if there are any PHI nodes
46 // with incompatible values coming in from the two edges!
48 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.
52 for (BasicBlock::iterator I = Succ->begin();
53 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
54 // 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
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...
67 // Loop over all of the PHI nodes in the successor BB
68 for (BasicBlock::iterator I = Succ->begin();
69 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
70 Value *OldVal = PN->removeIncomingValue(BB, false);
71 assert(OldVal && "No entry in PHI for Pred BB!");
73 // 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);
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);
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
95 // of the CFG. It returns true if a modification was made.
97 // WARNING: The entry node of a function may not be simplified.
99 bool SimplifyCFG(BasicBlock *BB) {
100 bool Changed = false;
101 Function *M = BB->getParent();
103 assert(BB && BB->getParent() && "Block not embedded in function!");
104 assert(BB->getTerminator() && "Degenerate basic block encountered!");
105 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
107 // 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.
111 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
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,
127 // If the invoke produced a value, the Call now does instead
128 II->replaceAllUsesWith(CI);
137 // 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;
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));
147 while (!BB->empty()) {
148 Instruction &I = BB->back();
149 // 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.
155 // Make all users of this instruction reference the constant instead
156 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
158 // Remove the instruction from the basic block
159 BB->getInstList().pop_back();
161 M->getBasicBlockList().erase(BB);
165 // Check to see if we can constant propagate this terminator instruction
167 Changed |= ConstantFoldTerminator(BB);
169 // 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
172 succ_iterator SI(succ_begin(BB));
173 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
175 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
176 while (isa<PHINode>(*BBI)) ++BBI;
178 if (BBI->isTerminator()) { // Terminator is the only non-phi instruction!
179 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
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!
187 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
188 //cerr << "Killing Trivial BB: \n" << BB;
189 std::string OldName = BB->getName();
191 std::vector<BasicBlock*>
192 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
194 // Move all PHI nodes in BB to Succ if they are alive, otherwise
196 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
198 BB->getInstList().erase(BB->begin()); // Nuke instruction...
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
202 // now. Simply move it into Succ, because we know that BB
203 // strictly dominated Succ.
204 BB->getInstList().remove(BB->begin());
205 Succ->getInstList().push_front(PN);
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
214 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
215 if (OldSuccPreds[i] != BB)
216 PN->addIncoming(PN, OldSuccPreds[i]);
219 // Everything that jumped to BB now goes to Succ...
220 BB->replaceAllUsesWith(Succ);
222 // Delete the old basic block...
223 M->getBasicBlockList().erase(BB);
225 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
226 Succ->setName(OldName);
228 //cerr << "Function after removal: \n" << M;
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.
239 if (!BB->hasConstantReferences()) {
240 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...
248 BasicBlock *OnlySucc = 0;
249 if (OnlyPred && OnlyPred != BB && // Don't break self loops
250 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
251 // Check to see if there is only one distinct successor...
252 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
254 for (; SI != SE; ++SI)
255 if (*SI != OnlySucc) {
256 OnlySucc = 0; // There are multiple distinct successors!
262 //cerr << "Merging: " << BB << "into: " << OnlyPred;
263 TerminatorInst *Term = OnlyPred->getTerminator();
265 // Resolve any PHI nodes at the start of the block. They are all
266 // 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.
271 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
272 PN->replaceAllUsesWith(PN->getIncomingValue(0));
273 BB->getInstList().pop_front(); // Delete the phi node...
276 // Delete the unconditional branch from the predecessor...
277 OnlyPred->getInstList().pop_back();
279 // Move all definitions in the successor to the predecessor...
280 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
282 // Make all PHI nodes that referred to BB now refer to Pred as their
284 BB->replaceAllUsesWith(OnlyPred);
286 std::string OldName = BB->getName();
288 // Erase basic block from the function...
289 M->getBasicBlockList().erase(BB);
291 // Inherit predecessors name if it exists...
292 if (!OldName.empty() && !OnlyPred->hasName())
293 OnlyPred->setName(OldName);