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