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