blob: 00a02dc61a6b3986a672738886bdbba8ac23c606 [file] [log] [blame]
Chris Lattner01d1ee32002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2//
3// SimplifyCFG - This function is used to do simplification of a CFG. For
4// example, it adjusts branches to branches to eliminate the extra hop, it
5// eliminates unreachable basic blocks, and does other "peephole" optimization
6// of the CFG. It returns true if a modification was made, and returns an
7// iterator that designates the first element remaining after the block that
8// was deleted.
9//
10// WARNING: The entry node of a function may not be simplified.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
15#include "llvm/Constant.h"
16#include "llvm/iPHINode.h"
17#include "llvm/Support/CFG.h"
18#include <algorithm>
19#include <functional>
20
21// PropogatePredecessors - This gets "Succ" ready to have the predecessors from
22// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
23// have extra slots added to them to hold the merge edges from BB's
24// predecessors. This function returns true (failure) if the Succ BB already
25// has a predecessor that is a predecessor of BB.
26//
27// Assumption: Succ is the single successor for BB.
28//
29static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
30 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
31 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
32
33 // If there is more than one predecessor, and there are PHI nodes in
34 // the successor, then we need to add incoming edges for the PHI nodes
35 //
36 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
37
38 // Check to see if one of the predecessors of BB is already a predecessor of
39 // Succ. If so, we cannot do the transformation!
40 //
41 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
42 PI != PE; ++PI) {
43 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end())
44 return true;
45 }
46
47 // Loop over all of the PHI nodes in the successor BB
48 for (BasicBlock::iterator I = Succ->begin();
49 PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
50 Value *OldVal = PN->removeIncomingValue(BB);
51 assert(OldVal && "No entry in PHI for Pred BB!");
52
53 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
54 End = BBPreds.end(); PredI != End; ++PredI) {
55 // Add an incoming value for each of the new incoming values...
56 PN->addIncoming(OldVal, *PredI);
57 }
58 }
59 return false;
60}
61
62
63// SimplifyCFG - This function is used to do simplification of a CFG. For
64// example, it adjusts branches to branches to eliminate the extra hop, it
65// eliminates unreachable basic blocks, and does other "peephole" optimization
66// of the CFG. It returns true if a modification was made, and returns an
67// iterator that designates the first element remaining after the block that
68// was deleted.
69//
70// WARNING: The entry node of a function may not be simplified.
71//
72bool SimplifyCFG(Function::iterator &BBIt) {
73 BasicBlock *BB = *BBIt;
74 Function *M = BB->getParent();
75
76 assert(BB && BB->getParent() && "Block not embedded in function!");
77 assert(BB->getTerminator() && "Degenerate basic block encountered!");
78 assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
79
80
81 // Remove basic blocks that have no predecessors... which are unreachable.
82 if (pred_begin(BB) == pred_end(BB) &&
83 !BB->hasConstantReferences()) {
84 //cerr << "Removing BB: \n" << BB;
85
86 // Loop through all of our successors and make sure they know that one
87 // of their predecessors is going away.
88 for_each(succ_begin(BB), succ_end(BB),
89 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
90
91 while (!BB->empty()) {
92 Instruction *I = BB->back();
93 // If this instruction is used, replace uses with an arbitrary
94 // constant value. Because control flow can't get here, we don't care
95 // what we replace the value with. Note that since this block is
96 // unreachable, and all values contained within it must dominate their
97 // uses, that all uses will eventually be removed.
98 if (!I->use_empty())
99 // Make all users of this instruction reference the constant instead
100 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
101
102 // Remove the instruction from the basic block
103 delete BB->getInstList().pop_back();
104 }
105 delete M->getBasicBlocks().remove(BBIt);
106 return true;
107 }
108
109 // Check to see if this block has no instructions and only a single
110 // successor. If so, replace block references with successor.
111 succ_iterator SI(succ_begin(BB));
112 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
113 if (BB->front()->isTerminator()) { // Terminator is the only instruction!
114 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
115
116 if (Succ != BB) { // Arg, don't hurt infinite loops!
117 // If our successor has PHI nodes, then we need to update them to
118 // include entries for BB's predecessors, not for BB itself.
119 // Be careful though, if this transformation fails (returns true) then
120 // we cannot do this transformation!
121 //
122 if (!isa<PHINode>(Succ->front()) ||
123 !PropogatePredecessorsForPHIs(BB, Succ)) {
124
125 //cerr << "Killing Trivial BB: \n" << BB;
126
127 BB->replaceAllUsesWith(Succ);
128 BB = M->getBasicBlocks().remove(BBIt);
129
130 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can
131 Succ->setName(BB->getName());
132 delete BB; // Delete basic block
133
134 //cerr << "Function after removal: \n" << M;
135 return true;
136 }
137 }
138 }
139 }
140
141 // Merge basic blocks into their predecessor if there is only one distinct
142 // pred, and if there is only one distinct successor of the predecessor, and
143 // if there are no PHI nodes.
144 //
145 if (!isa<PHINode>(BB->front()) && !BB->hasConstantReferences()) {
146 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
147 BasicBlock *OnlyPred = *PI++;
148 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
149 if (*PI != OnlyPred) {
150 OnlyPred = 0; // There are multiple different predecessors...
151 break;
152 }
153
154 BasicBlock *OnlySucc = 0;
155 if (OnlyPred && OnlyPred != BB) { // Don't break self loops
156 // Check to see if there is only one distinct successor...
157 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
158 OnlySucc = BB;
159 for (; SI != SE; ++SI)
160 if (*SI != OnlySucc) {
161 OnlySucc = 0; // There are multiple distinct successors!
162 break;
163 }
164 }
165
166 if (OnlySucc) {
167 //cerr << "Merging: " << BB << "into: " << OnlyPred;
168 TerminatorInst *Term = OnlyPred->getTerminator();
169
170 // Delete the unconditional branch from the predecessor...
171 BasicBlock::iterator DI = OnlyPred->end();
172 delete OnlyPred->getInstList().remove(--DI); // Destroy branch
173
174 // Move all definitions in the succecessor to the predecessor...
175 std::vector<Instruction*> Insts(BB->begin(), BB->end());
176 BB->getInstList().remove(BB->begin(), BB->end());
177 OnlyPred->getInstList().insert(OnlyPred->end(),
178 Insts.begin(), Insts.end());
179
180 // Remove basic block from the function... and advance iterator to the
181 // next valid block...
182 M->getBasicBlocks().remove(BBIt);
183
184 // Make all PHI nodes that refered to BB now refer to Pred as their
185 // source...
186 BB->replaceAllUsesWith(OnlyPred);
187
188 // Inherit predecessors name if it exists...
189 if (BB->hasName() && !OnlyPred->hasName())
190 OnlyPred->setName(BB->getName());
191
192 delete BB; // You ARE the weakest link... goodbye
193 return true;
194 }
195 }
196
197 return false;
198}