Implement InstCombine/add.ll:test20
[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 void eliminateUnconditionalBranch(BranchInst *BI);
45   };
46   RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
47 }
48
49 // Public interface to the Tail Duplication pass
50 Pass *llvm::createTailDuplicationPass() { return new TailDup(); }
51
52 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
53 /// the function, eliminating it if it looks attractive enough.
54 ///
55 bool TailDup::runOnFunction(Function &F) {
56   bool Changed = false;
57   for (Function::iterator I = F.begin(), E = F.end(); I != E; )
58     if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
59       eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
60       Changed = true;
61     } else {
62       ++I;
63     }
64   return Changed;
65 }
66
67 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
68 /// attractive to eliminate.  We eliminate the branch if the destination basic
69 /// block has <= 5 instructions in it, not counting PHI nodes.  In practice,
70 /// since one of these is a terminator instruction, this means that we will add
71 /// up to 4 instructions to the new block.
72 ///
73 /// We don't count PHI nodes in the count since they will be removed when the
74 /// contents of the block are copied over.
75 ///
76 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
77   BranchInst *BI = dyn_cast<BranchInst>(TI);
78   if (!BI || !BI->isUnconditional()) return false;  // Not an uncond branch!
79
80   BasicBlock *Dest = BI->getSuccessor(0);
81   if (Dest == BI->getParent()) return false;        // Do not loop infinitely!
82
83   // Do not inline a block if we will just get another branch to the same block!
84   TerminatorInst *DTI = Dest->getTerminator();
85   if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
86     if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
87       return false;                                 // Do not loop infinitely!
88
89   // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
90   // because doing so would require breaking critical edges.  This should be
91   // fixed eventually.
92   if (!DTI->use_empty())
93     return false;
94
95   // Do not bother working on dead blocks...
96   pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
97   if (PI == PE && Dest != Dest->getParent()->begin())
98     return false;   // It's just a dead block, ignore it...
99
100   // Also, do not bother with blocks with only a single predecessor: simplify
101   // CFG will fold these two blocks together!
102   ++PI;
103   if (PI == PE) return false;  // Exactly one predecessor!
104
105   BasicBlock::iterator I = Dest->begin();
106   while (isa<PHINode>(*I)) ++I;
107
108   for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
109     if (Size == 6) return false;  // The block is too large...
110
111   // Do not tail duplicate a block that has thousands of successors into a block
112   // with a single successor if the block has many other predecessors.  This can
113   // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
114   // cases that have a large number of indirect gotos.
115   if (DTI->getNumSuccessors() > 8)
116     if (std::distance(PI, PE) * DTI->getNumSuccessors() > 128)
117       return false;
118
119   return true;  
120 }
121
122
123 /// eliminateUnconditionalBranch - Clone the instructions from the destination
124 /// block into the source block, eliminating the specified unconditional branch.
125 /// If the destination block defines values used by successors of the dest
126 /// block, we may need to insert PHI nodes.
127 ///
128 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
129   BasicBlock *SourceBlock = Branch->getParent();
130   BasicBlock *DestBlock = Branch->getSuccessor(0);
131   assert(SourceBlock != DestBlock && "Our predicate is broken!");
132
133   DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
134                   << "]: Eliminating branch: " << *Branch);
135
136   // Tail duplication can not update SSA properties correctly if the values
137   // defined in the duplicated tail are used outside of the tail itself.  For
138   // this reason, we spill all values that are used outside of the tail to the
139   // stack.
140   for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
141     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
142          ++UI) {
143       bool ShouldDemote = false;
144       if (cast<Instruction>(*UI)->getParent() != DestBlock) {
145         // We must allow our successors to use tail values in their PHI nodes
146         // (if the incoming value corresponds to the tail block).
147         if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
148           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
149             if (PN->getIncomingValue(i) == I &&
150                 PN->getIncomingBlock(i) != DestBlock) {
151               ShouldDemote = true;
152               break;
153             }
154
155         } else {
156           ShouldDemote = true;
157         }
158       } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
159         // If the user of this instruction is a PHI node in the current block,
160         // which has an entry from another block using the value, spill it.
161         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
162           if (PN->getIncomingValue(i) == I &&
163               PN->getIncomingBlock(i) != DestBlock) {
164             ShouldDemote = true;
165             break;
166           }
167       }
168
169       if (ShouldDemote) {
170         // We found a use outside of the tail.  Create a new stack slot to
171         // break this inter-block usage pattern.
172         DemoteRegToStack(*I);
173         break;
174       }
175     }
176
177   // We are going to have to map operands from the original block B to the new
178   // copy of the block B'.  If there are PHI nodes in the DestBlock, these PHI
179   // nodes also define part of this mapping.  Loop over these PHI nodes, adding
180   // them to our mapping.
181   //
182   std::map<Value*, Value*> ValueMapping;
183
184   BasicBlock::iterator BI = DestBlock->begin();
185   bool HadPHINodes = isa<PHINode>(BI);
186   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
187     ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
188
189   // Clone the non-phi instructions of the dest block into the source block,
190   // keeping track of the mapping...
191   //
192   for (; BI != DestBlock->end(); ++BI) {
193     Instruction *New = BI->clone();
194     New->setName(BI->getName());
195     SourceBlock->getInstList().push_back(New);
196     ValueMapping[BI] = New;
197   }
198
199   // Now that we have built the mapping information and cloned all of the
200   // instructions (giving us a new terminator, among other things), walk the new
201   // instructions, rewriting references of old instructions to use new
202   // instructions.
203   //
204   BI = Branch; ++BI;  // Get an iterator to the first new instruction
205   for (; BI != SourceBlock->end(); ++BI)
206     for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
207       if (Value *Remapped = ValueMapping[BI->getOperand(i)])
208         BI->setOperand(i, Remapped);
209
210   // Next we check to see if any of the successors of DestBlock had PHI nodes.
211   // If so, we need to add entries to the PHI nodes for SourceBlock now.
212   for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
213        SI != SE; ++SI) {
214     BasicBlock *Succ = *SI;
215     for (BasicBlock::iterator PNI = Succ->begin();
216          PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
217       // Ok, we have a PHI node.  Figure out what the incoming value was for the
218       // DestBlock.
219       Value *IV = PN->getIncomingValueForBlock(DestBlock);
220       
221       // Remap the value if necessary...
222       if (Value *MappedIV = ValueMapping[IV])
223         IV = MappedIV;
224       PN->addIncoming(IV, SourceBlock);
225     }
226   }
227
228   // Next, remove the old branch instruction, and any PHI node entries that we
229   // had.
230   BI = Branch; ++BI;  // Get an iterator to the first new instruction
231   DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
232   SourceBlock->getInstList().erase(Branch);  // Destroy the uncond branch...
233
234   // Final step: now that we have finished everything up, walk the cloned
235   // instructions one last time, constant propagating and DCE'ing them, because
236   // they may not be needed anymore.
237   //
238   if (HadPHINodes)
239     while (BI != SourceBlock->end())
240       if (!dceInstruction(BI) && !doConstantPropagation(BI))
241         ++BI;
242
243   ++NumEliminated;  // We just killed a branch!
244 }