6b642360d6cf0c841e14c04d9c9ba6b226d20d78
[oota-llvm.git] / lib / Transforms / Utils / SimplifyCFG.cpp
1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2 //
3 // Peephole optimize the CFG.
4 //
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
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.
19 //
20 // Assumption: Succ is the single successor for BB.
21 //
22 static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
23   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
24
25   if (!isa<PHINode>(Succ->front()))
26     return false;  // We can make the transformation, no problem.
27
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
30   //
31   const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
32
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!
35   //
36   for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
37        PI != PE; ++PI)
38     if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end())
39       return true;
40
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!");
46
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);
51     }
52   }
53   return false;
54 }
55
56
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
62 // was deleted.
63 //
64 // WARNING:  The entry node of a function may not be simplified.
65 //
66 bool SimplifyCFG(BasicBlock *BB) {
67   Function *M = BB->getParent();
68
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!");
72
73
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;
78
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));
83
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.
91       if (!I.use_empty()) 
92         // Make all users of this instruction reference the constant instead
93         I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
94       
95       // Remove the instruction from the basic block
96       BB->getInstList().pop_back();
97     }
98     M->getBasicBlockList().erase(BB);
99     return true;
100   }
101
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
108      
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!
114         //
115         if (!PropogatePredecessorsForPHIs(BB, Succ)) {
116           //cerr << "Killing Trivial BB: \n" << BB;
117           BB->replaceAllUsesWith(Succ);
118           std::string OldName = BB->getName();
119
120           // Delete the old basic block...
121           M->getBasicBlockList().erase(BB);
122         
123           if (!OldName.empty() && !Succ->hasName())  // Transfer name if we can
124             Succ->setName(OldName);
125           
126           //cerr << "Function after removal: \n" << M;
127           return true;
128         }
129       }
130     }
131   }
132
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.
136   //
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...
143         break;
144       }
145   
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));
150       OnlySucc = BB;
151       for (; SI != SE; ++SI)
152         if (*SI != OnlySucc) {
153           OnlySucc = 0;     // There are multiple distinct successors!
154           break;
155         }
156     }
157
158     if (OnlySucc) {
159       //cerr << "Merging: " << BB << "into: " << OnlyPred;
160       TerminatorInst *Term = OnlyPred->getTerminator();
161
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.
167       //
168       while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
169         PN->replaceAllUsesWith(PN->getIncomingValue(0));
170         BB->getInstList().pop_front();  // Delete the phi node...
171       }
172
173       // Delete the unconditional branch from the predecessor...
174       OnlyPred->getInstList().pop_back();
175       
176       // Move all definitions in the succecessor to the predecessor...
177       OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
178                                      
179       // Make all PHI nodes that refered to BB now refer to Pred as their
180       // source...
181       BB->replaceAllUsesWith(OnlyPred);
182
183       std::string OldName = BB->getName();
184
185       // Erase basic block from the function... 
186       M->getBasicBlockList().erase(BB);
187
188       // Inherit predecessors name if it exists...
189       if (!OldName.empty() && !OnlyPred->hasName())
190         OnlyPred->setName(OldName);
191       
192       return true;
193     }
194   }
195   
196   return false;
197 }