Added LLVM project notice to the top of every C++ source file.
[oota-llvm.git] / lib / Transforms / Scalar / TailDuplication.cpp
1 //===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs a limited form of tail duplication, intended to simplify
11 // CFGs by removing some unconditional branches.  This pass is necessary to
12 // straighten out loops created by the C front-end, but also is capable of
13 // making other code nicer.  After this pass is run, the CFG simplify pass
14 // should be run to clean up the mess.
15 //
16 // This pass could be enhanced in the future to use profile information to be
17 // more aggressive.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Constant.h"
23 #include "llvm/Function.h"
24 #include "llvm/iPHINode.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Type.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Support/ValueHolder.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "Support/Debug.h"
32 #include "Support/Statistic.h"
33
34 namespace {
35   Statistic<> NumEliminated("tailduplicate",
36                             "Number of unconditional branches eliminated");
37   Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
38
39   class TailDup : public FunctionPass {
40     bool runOnFunction(Function &F);
41   private:
42     inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
43     inline void eliminateUnconditionalBranch(BranchInst *BI);
44     inline void InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
45                                           BasicBlock *NewBlock);
46     inline Value *GetValueInBlock(BasicBlock *BB, Value *OrigVal,
47                                   std::map<BasicBlock*, ValueHolder> &ValueMap,
48                               std::map<BasicBlock*, ValueHolder> &OutValueMap);
49     inline Value *GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
50                                    std::map<BasicBlock*, ValueHolder> &ValueMap,
51                                std::map<BasicBlock*, ValueHolder> &OutValueMap);
52   };
53   RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
54 }
55
56 Pass *createTailDuplicationPass() { return new TailDup(); }
57
58 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
59 /// the function, eliminating it if it looks attractive enough.
60 ///
61 bool TailDup::runOnFunction(Function &F) {
62   bool Changed = false;
63   for (Function::iterator I = F.begin(), E = F.end(); I != E; )
64     if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
65       eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
66       Changed = true;
67     } else {
68       ++I;
69     }
70   return Changed;
71 }
72
73 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
74 /// attractive to eliminate.  We eliminate the branch if the destination basic
75 /// block has <= 5 instructions in it, not counting PHI nodes.  In practice,
76 /// since one of these is a terminator instruction, this means that we will add
77 /// up to 4 instructions to the new block.
78 ///
79 /// We don't count PHI nodes in the count since they will be removed when the
80 /// contents of the block are copied over.
81 ///
82 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
83   BranchInst *BI = dyn_cast<BranchInst>(TI);
84   if (!BI || !BI->isUnconditional()) return false;  // Not an uncond branch!
85
86   BasicBlock *Dest = BI->getSuccessor(0);
87   if (Dest == BI->getParent()) return false;        // Do not loop infinitely!
88
89   // Do not inline a block if we will just get another branch to the same block!
90   if (BranchInst *DBI = dyn_cast<BranchInst>(Dest->getTerminator()))
91     if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
92       return false;                                 // Do not loop infinitely!
93
94   // Do not bother working on dead blocks...
95   pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
96   if (PI == PE && Dest != Dest->getParent()->begin())
97     return false;   // It's just a dead block, ignore it...
98
99   // Also, do not bother with blocks with only a single predecessor: simplify
100   // CFG will fold these two blocks together!
101   ++PI;
102   if (PI == PE) return false;  // Exactly one predecessor!
103
104   BasicBlock::iterator I = Dest->begin();
105   while (isa<PHINode>(*I)) ++I;
106
107   for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
108     if (Size == 6) return false;  // The block is too large...
109   return true;  
110 }
111
112
113 /// eliminateUnconditionalBranch - Clone the instructions from the destination
114 /// block into the source block, eliminating the specified unconditional branch.
115 /// If the destination block defines values used by successors of the dest
116 /// block, we may need to insert PHI nodes.
117 ///
118 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
119   BasicBlock *SourceBlock = Branch->getParent();
120   BasicBlock *DestBlock = Branch->getSuccessor(0);
121   assert(SourceBlock != DestBlock && "Our predicate is broken!");
122
123   DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
124                   << "]: Eliminating branch: " << *Branch);
125
126   // We are going to have to map operands from the original block B to the new
127   // copy of the block B'.  If there are PHI nodes in the DestBlock, these PHI
128   // nodes also define part of this mapping.  Loop over these PHI nodes, adding
129   // them to our mapping.
130   //
131   std::map<Value*, Value*> ValueMapping;
132
133   BasicBlock::iterator BI = DestBlock->begin();
134   bool HadPHINodes = isa<PHINode>(BI);
135   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
136     ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
137
138   // Clone the non-phi instructions of the dest block into the source block,
139   // keeping track of the mapping...
140   //
141   for (; BI != DestBlock->end(); ++BI) {
142     Instruction *New = BI->clone();
143     New->setName(BI->getName());
144     SourceBlock->getInstList().push_back(New);
145     ValueMapping[BI] = New;
146   }
147
148   // Now that we have built the mapping information and cloned all of the
149   // instructions (giving us a new terminator, among other things), walk the new
150   // instructions, rewriting references of old instructions to use new
151   // instructions.
152   //
153   BI = Branch; ++BI;  // Get an iterator to the first new instruction
154   for (; BI != SourceBlock->end(); ++BI)
155     for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
156       if (Value *Remapped = ValueMapping[BI->getOperand(i)])
157         BI->setOperand(i, Remapped);
158
159   // Next we check to see if any of the successors of DestBlock had PHI nodes.
160   // If so, we need to add entries to the PHI nodes for SourceBlock now.
161   for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
162        SI != SE; ++SI) {
163     BasicBlock *Succ = *SI;
164     for (BasicBlock::iterator PNI = Succ->begin();
165          PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
166       // Ok, we have a PHI node.  Figure out what the incoming value was for the
167       // DestBlock.
168       Value *IV = PN->getIncomingValueForBlock(DestBlock);
169       
170       // Remap the value if necessary...
171       if (Value *MappedIV = ValueMapping[IV])
172         IV = MappedIV;
173       PN->addIncoming(IV, SourceBlock);
174     }
175   }
176   
177   // Now that all of the instructions are correctly copied into the SourceBlock,
178   // we have one more minor problem: the successors of the original DestBB may
179   // use the values computed in DestBB either directly (if DestBB dominated the
180   // block), or through a PHI node.  In either case, we need to insert PHI nodes
181   // into any successors of DestBB (which are now our successors) for each value
182   // that is computed in DestBB, but is used outside of it.  All of these uses
183   // we have to rewrite with the new PHI node.
184   //
185   if (succ_begin(SourceBlock) != succ_end(SourceBlock)) // Avoid wasting time...
186     for (BI = DestBlock->begin(); BI != DestBlock->end(); ++BI)
187       if (BI->getType() != Type::VoidTy)
188         InsertPHINodesIfNecessary(BI, ValueMapping[BI], SourceBlock);
189
190   // Final step: now that we have finished everything up, walk the cloned
191   // instructions one last time, constant propagating and DCE'ing them, because
192   // they may not be needed anymore.
193   //
194   BI = Branch; ++BI;  // Get an iterator to the first new instruction
195   if (HadPHINodes)
196     while (BI != SourceBlock->end())
197       if (!dceInstruction(BI) && !doConstantPropagation(BI))
198         ++BI;
199
200   DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
201   SourceBlock->getInstList().erase(Branch);  // Destroy the uncond branch...
202   
203   ++NumEliminated;  // We just killed a branch!
204 }
205
206 /// InsertPHINodesIfNecessary - So at this point, we cloned the OrigInst
207 /// instruction into the NewBlock with the value of NewInst.  If OrigInst was
208 /// used outside of its defining basic block, we need to insert a PHI nodes into
209 /// the successors.
210 ///
211 void TailDup::InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
212                                         BasicBlock *NewBlock) {
213   // Loop over all of the uses of OrigInst, rewriting them to be newly inserted
214   // PHI nodes, unless they are in the same basic block as OrigInst.
215   BasicBlock *OrigBlock = OrigInst->getParent();
216   std::vector<Instruction*> Users;
217   Users.reserve(OrigInst->use_size());
218   for (Value::use_iterator I = OrigInst->use_begin(), E = OrigInst->use_end();
219        I != E; ++I) {
220     Instruction *In = cast<Instruction>(*I);
221     if (In->getParent() != OrigBlock ||  // Don't modify uses in the orig block!
222         isa<PHINode>(In))
223       Users.push_back(In);
224   }
225
226   // The common case is that the instruction is only used within the block that
227   // defines it.  If we have this case, quick exit.
228   //
229   if (Users.empty()) return; 
230
231   // Otherwise, we have a more complex case, handle it now.  This requires the
232   // construction of a mapping between a basic block and the value to use when
233   // in the scope of that basic block.  This map will map to the original and
234   // new values when in the original or new block, but will map to inserted PHI
235   // nodes when in other blocks.
236   //
237   std::map<BasicBlock*, ValueHolder> ValueMap;
238   std::map<BasicBlock*, ValueHolder> OutValueMap;   // The outgoing value map
239   OutValueMap[OrigBlock] = OrigInst;
240   OutValueMap[NewBlock ] = NewInst;    // Seed the initial values...
241
242   DEBUG(std::cerr << "  ** Inserting PHI nodes for " << OrigInst);
243   while (!Users.empty()) {
244     Instruction *User = Users.back(); Users.pop_back();
245
246     if (PHINode *PN = dyn_cast<PHINode>(User)) {
247       // PHI nodes must be handled specially here, because their operands are
248       // actually defined in predecessor basic blocks, NOT in the block that the
249       // PHI node lives in.  Note that we have already added entries to PHI nods
250       // which are in blocks that are immediate successors of OrigBlock, so
251       // don't modify them again.
252       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
253         if (PN->getIncomingValue(i) == OrigInst &&
254             PN->getIncomingBlock(i) != OrigBlock) {
255           Value *V = GetValueOutBlock(PN->getIncomingBlock(i), OrigInst,
256                                       ValueMap, OutValueMap);
257           PN->setIncomingValue(i, V);
258         }
259       
260     } else {
261       // Any other user of the instruction can just replace any uses with the
262       // new value defined in the block it resides in.
263       Value *V = GetValueInBlock(User->getParent(), OrigInst, ValueMap,
264                                  OutValueMap);
265       User->replaceUsesOfWith(OrigInst, V);
266     }
267   }
268 }
269
270 /// GetValueInBlock - This is a recursive method which inserts PHI nodes into
271 /// the function until there is a value available in basic block BB.
272 ///
273 Value *TailDup::GetValueInBlock(BasicBlock *BB, Value *OrigVal,
274                                 std::map<BasicBlock*, ValueHolder> &ValueMap,
275                                 std::map<BasicBlock*,ValueHolder> &OutValueMap){
276   ValueHolder &BBVal = ValueMap[BB];
277   if (BBVal) return BBVal;       // Value already computed for this block?
278
279   // If this block has no predecessors, then it must be unreachable, thus, it
280   // doesn't matter which value we use.
281   if (pred_begin(BB) == pred_end(BB))
282     return BBVal = Constant::getNullValue(OrigVal->getType());
283
284   // If there is no value already available in this basic block, we need to
285   // either reuse a value from an incoming, dominating, basic block, or we need
286   // to create a new PHI node to merge in different incoming values.  Because we
287   // don't know if we're part of a loop at this point or not, we create a PHI
288   // node, even if we will ultimately eliminate it.
289   PHINode *PN = new PHINode(OrigVal->getType(), OrigVal->getName()+".pn",
290                             BB->begin());
291   BBVal = PN;   // Insert this into the BBVal slot in case of cycles...
292
293   ValueHolder &BBOutVal = OutValueMap[BB];
294   if (BBOutVal == 0) BBOutVal = PN;
295
296   // Now that we have created the PHI node, loop over all of the predecessors of
297   // this block, computing an incoming value for the predecessor.
298   std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
299   for (unsigned i = 0, e = Preds.size(); i != e; ++i)
300     PN->addIncoming(GetValueOutBlock(Preds[i], OrigVal, ValueMap, OutValueMap),
301                     Preds[i]);
302
303   // The PHI node is complete.  In many cases, however the PHI node was
304   // ultimately unnecessary: we could have just reused a dominating incoming
305   // value.  If this is the case, nuke the PHI node and replace the map entry
306   // with the dominating value.
307   //
308   assert(PN->getNumIncomingValues() > 0 && "No predecessors?");
309
310   // Check to see if all of the elements in the PHI node are either the PHI node
311   // itself or ONE particular value.
312   unsigned i = 0;
313   Value *ReplVal = PN->getIncomingValue(i);
314   for (; ReplVal == PN && i != PN->getNumIncomingValues(); ++i)
315     ReplVal = PN->getIncomingValue(i);  // Skip values equal to the PN
316
317   for (; i != PN->getNumIncomingValues(); ++i)
318     if (PN->getIncomingValue(i) != PN && PN->getIncomingValue(i) != ReplVal) {
319       ReplVal = 0;
320       break;
321     }
322
323   // Found a value to replace the PHI node with?
324   if (ReplVal && ReplVal != PN) {
325     PN->replaceAllUsesWith(ReplVal);
326     BB->getInstList().erase(PN);   // Erase the PHI node...
327   } else {
328     ++NumPHINodes;
329   }
330
331   return BBVal;
332 }
333
334 Value *TailDup::GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
335                                  std::map<BasicBlock*, ValueHolder> &ValueMap,
336                               std::map<BasicBlock*, ValueHolder> &OutValueMap) {
337   ValueHolder &BBVal = OutValueMap[BB];
338   if (BBVal) return BBVal;       // Value already computed for this block?
339
340   return GetValueInBlock(BB, OrigVal, ValueMap, OutValueMap);
341 }