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