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