Do not count debugger intrinsics in size estimation.
[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/Instructions.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Type.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/ADT/Statistic.h"
33 using namespace llvm;
34
35 namespace {
36   cl::opt<unsigned>
37   Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
38             cl::init(6), cl::Hidden);
39   Statistic<> NumEliminated("tailduplicate",
40                             "Number of unconditional branches eliminated");
41   Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
42
43   class TailDup : public FunctionPass {
44     bool runOnFunction(Function &F);
45   private:
46     inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
47     inline void eliminateUnconditionalBranch(BranchInst *BI);
48   };
49   RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
50 }
51
52 // Public interface to the Tail Duplication pass
53 FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
54
55 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
56 /// the function, eliminating it if it looks attractive enough.
57 ///
58 bool TailDup::runOnFunction(Function &F) {
59   bool Changed = false;
60   for (Function::iterator I = F.begin(), E = F.end(); I != E; )
61     if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
62       eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
63       Changed = true;
64     } else {
65       ++I;
66     }
67   return Changed;
68 }
69
70 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
71 /// attractive to eliminate.  We eliminate the branch if the destination basic
72 /// block has <= 5 instructions in it, not counting PHI nodes.  In practice,
73 /// since one of these is a terminator instruction, this means that we will add
74 /// up to 4 instructions to the new block.
75 ///
76 /// We don't count PHI nodes in the count since they will be removed when the
77 /// contents of the block are copied over.
78 ///
79 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
80   BranchInst *BI = dyn_cast<BranchInst>(TI);
81   if (!BI || !BI->isUnconditional()) return false;  // Not an uncond branch!
82
83   BasicBlock *Dest = BI->getSuccessor(0);
84   if (Dest == BI->getParent()) return false;        // Do not loop infinitely!
85
86   // Do not inline a block if we will just get another branch to the same block!
87   TerminatorInst *DTI = Dest->getTerminator();
88   if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
89     if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
90       return false;                                 // Do not loop infinitely!
91
92   // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
93   // because doing so would require breaking critical edges.  This should be
94   // fixed eventually.
95   if (!DTI->use_empty())
96     return false;
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(); ++I) {
112     if (Size == Threshold) return false;  // The block is too large.
113     // Only count instructions that are not debugger intrinsics.
114     if (!isa<DbgInfoIntrinsic>(I)) ++Size;
115   }
116
117   // Do not tail duplicate a block that has thousands of successors into a block
118   // with a single successor if the block has many other predecessors.  This can
119   // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
120   // cases that have a large number of indirect gotos.
121   unsigned NumSuccs = DTI->getNumSuccessors();
122   if (NumSuccs > 8) {
123     unsigned TooMany = 128;
124     if (NumSuccs >= TooMany) return false;
125     TooMany = TooMany/NumSuccs;
126     for (; PI != PE; ++PI)
127       if (TooMany-- == 0) return false;
128   }
129
130   return true;  
131 }
132
133 /// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
134 /// DestBlock, and that SrcBlock is not the only predecessor of DstBlock.  If we
135 /// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
136 /// DstBlock, return it.
137 static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
138                                           BasicBlock *DstBlock) {
139   // SrcBlock must have a single predecessor.
140   pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
141   if (PI == PE || ++PI != PE) return 0;
142
143   BasicBlock *SrcPred = *pred_begin(SrcBlock);
144   
145   // Look at the predecessors of DstBlock.  One of them will be SrcBlock.  If
146   // there is only one other pred, get it, otherwise we can't handle it.
147   PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
148   BasicBlock *DstOtherPred = 0;
149   if (*PI == SrcBlock) {
150     if (++PI == PE) return 0;
151     DstOtherPred = *PI;
152     if (++PI != PE) return 0;
153   } else {
154     DstOtherPred = *PI;
155     if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
156   }
157
158   // We can handle two situations here: "if then" and "if then else" blocks.  An
159   // 'if then' situation is just where DstOtherPred == SrcPred.
160   if (DstOtherPred == SrcPred)
161     return SrcPred;
162
163   // Check to see if we have an "if then else" situation, which means that
164   // DstOtherPred will have a single predecessor and it will be SrcPred.
165   PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
166   if (PI != PE && *PI == SrcPred) {
167     if (++PI != PE) return 0;  // Not a single pred.
168     return SrcPred;  // Otherwise, it's an "if then" situation.  Return the if.
169   }
170
171   // Otherwise, this is something we can't handle.
172   return 0;
173 }
174
175
176 /// eliminateUnconditionalBranch - Clone the instructions from the destination
177 /// block into the source block, eliminating the specified unconditional branch.
178 /// If the destination block defines values used by successors of the dest
179 /// block, we may need to insert PHI nodes.
180 ///
181 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
182   BasicBlock *SourceBlock = Branch->getParent();
183   BasicBlock *DestBlock = Branch->getSuccessor(0);
184   assert(SourceBlock != DestBlock && "Our predicate is broken!");
185
186   DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
187                   << "]: Eliminating branch: " << *Branch);
188
189   // See if we can avoid duplicating code by moving it up to a dominator of both
190   // blocks.
191   if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
192     DEBUG(std::cerr << "Found shared dominator: " << DomBlock->getName()
193                     << "\n");
194
195     // If there are non-phi instructions in DestBlock that have no operands
196     // defined in DestBlock, and if the instruction has no side effects, we can
197     // move the instruction to DomBlock instead of duplicating it.
198     BasicBlock::iterator BBI = DestBlock->begin();
199     while (isa<PHINode>(BBI)) ++BBI;
200     while (!isa<TerminatorInst>(BBI)) {
201       Instruction *I = BBI++;
202       
203       bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
204       if (CanHoist) {
205         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
206           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
207             if (OpI->getParent() == DestBlock ||
208                 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
209               CanHoist = false;
210               break;
211             }
212         if (CanHoist) {
213           // Remove from DestBlock, move right before the term in DomBlock.
214           DestBlock->getInstList().remove(I);
215           DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
216           DEBUG(std::cerr << "Hoisted: " << *I);
217         }
218       }
219     }
220   }
221
222   // Tail duplication can not update SSA properties correctly if the values
223   // defined in the duplicated tail are used outside of the tail itself.  For
224   // this reason, we spill all values that are used outside of the tail to the
225   // stack.
226   for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
227     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
228          ++UI) {
229       bool ShouldDemote = false;
230       if (cast<Instruction>(*UI)->getParent() != DestBlock) {
231         // We must allow our successors to use tail values in their PHI nodes
232         // (if the incoming value corresponds to the tail block).
233         if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
234           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
235             if (PN->getIncomingValue(i) == I &&
236                 PN->getIncomingBlock(i) != DestBlock) {
237               ShouldDemote = true;
238               break;
239             }
240
241         } else {
242           ShouldDemote = true;
243         }
244       } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
245         // If the user of this instruction is a PHI node in the current block,
246         // which has an entry from another block using the value, spill it.
247         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
248           if (PN->getIncomingValue(i) == I &&
249               PN->getIncomingBlock(i) != DestBlock) {
250             ShouldDemote = true;
251             break;
252           }
253       }
254
255       if (ShouldDemote) {
256         // We found a use outside of the tail.  Create a new stack slot to
257         // break this inter-block usage pattern.
258         DemoteRegToStack(*I);
259         break;
260       }
261     }
262
263   // We are going to have to map operands from the original block B to the new
264   // copy of the block B'.  If there are PHI nodes in the DestBlock, these PHI
265   // nodes also define part of this mapping.  Loop over these PHI nodes, adding
266   // them to our mapping.
267   //
268   std::map<Value*, Value*> ValueMapping;
269
270   BasicBlock::iterator BI = DestBlock->begin();
271   bool HadPHINodes = isa<PHINode>(BI);
272   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
273     ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
274
275   // Clone the non-phi instructions of the dest block into the source block,
276   // keeping track of the mapping...
277   //
278   for (; BI != DestBlock->end(); ++BI) {
279     Instruction *New = BI->clone();
280     New->setName(BI->getName());
281     SourceBlock->getInstList().push_back(New);
282     ValueMapping[BI] = New;
283   }
284
285   // Now that we have built the mapping information and cloned all of the
286   // instructions (giving us a new terminator, among other things), walk the new
287   // instructions, rewriting references of old instructions to use new
288   // instructions.
289   //
290   BI = Branch; ++BI;  // Get an iterator to the first new instruction
291   for (; BI != SourceBlock->end(); ++BI)
292     for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
293       if (Value *Remapped = ValueMapping[BI->getOperand(i)])
294         BI->setOperand(i, Remapped);
295
296   // Next we check to see if any of the successors of DestBlock had PHI nodes.
297   // If so, we need to add entries to the PHI nodes for SourceBlock now.
298   for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
299        SI != SE; ++SI) {
300     BasicBlock *Succ = *SI;
301     for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
302       PHINode *PN = cast<PHINode>(PNI);
303       // Ok, we have a PHI node.  Figure out what the incoming value was for the
304       // DestBlock.
305       Value *IV = PN->getIncomingValueForBlock(DestBlock);
306       
307       // Remap the value if necessary...
308       if (Value *MappedIV = ValueMapping[IV])
309         IV = MappedIV;
310       PN->addIncoming(IV, SourceBlock);
311     }
312   }
313
314   // Next, remove the old branch instruction, and any PHI node entries that we
315   // had.
316   BI = Branch; ++BI;  // Get an iterator to the first new instruction
317   DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
318   SourceBlock->getInstList().erase(Branch);  // Destroy the uncond branch...
319
320   // Final step: now that we have finished everything up, walk the cloned
321   // instructions one last time, constant propagating and DCE'ing them, because
322   // they may not be needed anymore.
323   //
324   if (HadPHINodes)
325     while (BI != SourceBlock->end())
326       if (!dceInstruction(BI) && !doConstantPropagation(BI))
327         ++BI;
328
329   ++NumEliminated;  // We just killed a branch!
330 }