1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
3 // Peephole optimize the CFG.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Transforms/Utils/Local.h"
8 #include "llvm/Constant.h"
9 #include "llvm/iPHINode.h"
10 #include "llvm/Support/CFG.h"
14 // PropogatePredecessors - This gets "Succ" ready to have the predecessors from
15 // "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
17 // predecessors. This function returns true (failure) if the Succ BB already
18 // has a predecessor that is a predecessor of BB.
20 // Assumption: Succ is the single successor for BB.
22 static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
23 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
25 if (!isa<PHINode>(Succ->front()))
26 return false; // We can make the transformation, no problem.
28 // If there is more than one predecessor, and there are PHI nodes in
29 // the successor, then we need to add incoming edges for the PHI nodes
31 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
33 // Check to see if one of the predecessors of BB is already a predecessor of
34 // Succ. If so, we cannot do the transformation!
36 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
38 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end())
41 // Loop over all of the PHI nodes in the successor BB
42 for (BasicBlock::iterator I = Succ->begin();
43 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
44 Value *OldVal = PN->removeIncomingValue(BB, false);
45 assert(OldVal && "No entry in PHI for Pred BB!");
47 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
48 End = BBPreds.end(); PredI != End; ++PredI) {
49 // Add an incoming value for each of the new incoming values...
50 PN->addIncoming(OldVal, *PredI);
57 // SimplifyCFG - This function is used to do simplification of a CFG. For
58 // example, it adjusts branches to branches to eliminate the extra hop, it
59 // eliminates unreachable basic blocks, and does other "peephole" optimization
60 // of the CFG. It returns true if a modification was made, and returns an
61 // iterator that designates the first element remaining after the block that
64 // WARNING: The entry node of a function may not be simplified.
66 bool SimplifyCFG(BasicBlock *BB) {
67 Function *M = BB->getParent();
69 assert(BB && BB->getParent() && "Block not embedded in function!");
70 assert(BB->getTerminator() && "Degenerate basic block encountered!");
71 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
74 // Remove basic blocks that have no predecessors... which are unreachable.
75 if (pred_begin(BB) == pred_end(BB) &&
76 !BB->hasConstantReferences()) {
77 //cerr << "Removing BB: \n" << BB;
79 // Loop through all of our successors and make sure they know that one
80 // of their predecessors is going away.
81 for_each(succ_begin(BB), succ_end(BB),
82 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
84 while (!BB->empty()) {
85 Instruction &I = BB->back();
86 // If this instruction is used, replace uses with an arbitrary
87 // constant value. Because control flow can't get here, we don't care
88 // what we replace the value with. Note that since this block is
89 // unreachable, and all values contained within it must dominate their
90 // uses, that all uses will eventually be removed.
92 // Make all users of this instruction reference the constant instead
93 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
95 // Remove the instruction from the basic block
96 BB->getInstList().pop_back();
98 M->getBasicBlockList().erase(BB);
102 // Check to see if this block has no instructions and only a single
103 // successor. If so, replace block references with successor.
104 succ_iterator SI(succ_begin(BB));
105 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
106 if (BB->front().isTerminator()) { // Terminator is the only instruction!
107 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
109 if (Succ != BB) { // Arg, don't hurt infinite loops!
110 // If our successor has PHI nodes, then we need to update them to
111 // include entries for BB's predecessors, not for BB itself.
112 // Be careful though, if this transformation fails (returns true) then
113 // we cannot do this transformation!
115 if (!PropogatePredecessorsForPHIs(BB, Succ)) {
116 //cerr << "Killing Trivial BB: \n" << BB;
117 BB->replaceAllUsesWith(Succ);
118 std::string OldName = BB->getName();
120 // Delete the old basic block...
121 M->getBasicBlockList().erase(BB);
123 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
124 Succ->setName(OldName);
126 //cerr << "Function after removal: \n" << M;
133 // Merge basic blocks into their predecessor if there is only one distinct
134 // pred, and if there is only one distinct successor of the predecessor, and
135 // if there are no PHI nodes.
137 if (!BB->hasConstantReferences()) {
138 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
139 BasicBlock *OnlyPred = *PI++;
140 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
141 if (*PI != OnlyPred) {
142 OnlyPred = 0; // There are multiple different predecessors...
146 BasicBlock *OnlySucc = 0;
147 if (OnlyPred && OnlyPred != BB) { // Don't break self loops
148 // Check to see if there is only one distinct successor...
149 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
151 for (; SI != SE; ++SI)
152 if (*SI != OnlySucc) {
153 OnlySucc = 0; // There are multiple distinct successors!
159 //cerr << "Merging: " << BB << "into: " << OnlyPred;
160 TerminatorInst *Term = OnlyPred->getTerminator();
162 // Resolve any PHI nodes at the start of the block. They are all
163 // guaranteed to have exactly one entry if they exist, unless there are
164 // multiple duplicate (but guaranteed to be equal) entries for the
165 // incoming edges. This occurs when there are multiple edges from
166 // OnlyPred to OnlySucc.
168 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
169 PN->replaceAllUsesWith(PN->getIncomingValue(0));
170 BB->getInstList().pop_front(); // Delete the phi node...
173 // Delete the unconditional branch from the predecessor...
174 OnlyPred->getInstList().pop_back();
176 // Move all definitions in the succecessor to the predecessor...
177 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
179 // Make all PHI nodes that refered to BB now refer to Pred as their
181 BB->replaceAllUsesWith(OnlyPred);
183 std::string OldName = BB->getName();
185 // Erase basic block from the function...
186 M->getBasicBlockList().erase(BB);
188 // Inherit predecessors name if it exists...
189 if (!OldName.empty() && !OnlyPred->hasName())
190 OnlyPred->setName(OldName);