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