blob: 398da0aa9b6aa8fa640b7c989a77913b876c5cdc [file] [log] [blame]
Chris Lattnera5434ca2003-06-22 20:10:28 +00001//===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnera5434ca2003-06-22 20:10:28 +00009//
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
Chris Lattnere03ca2c2006-09-27 04:58:23 +000021#define DEBUG_TYPE "tailduplicate"
Chris Lattnera5434ca2003-06-22 20:10:28 +000022#include "llvm/Transforms/Scalar.h"
Chris Lattner1c884e12003-08-31 21:17:44 +000023#include "llvm/Constant.h"
Chris Lattnera5434ca2003-06-22 20:10:28 +000024#include "llvm/Function.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000025#include "llvm/Instructions.h"
Chris Lattner540e5f92004-11-22 17:23:57 +000026#include "llvm/IntrinsicInst.h"
Chris Lattnera5434ca2003-06-22 20:10:28 +000027#include "llvm/Pass.h"
28#include "llvm/Type.h"
29#include "llvm/Support/CFG.h"
30#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000031#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000032#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
34#include "llvm/ADT/Statistic.h"
Chris Lattner49525f82004-01-09 06:02:20 +000035using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000036
Chris Lattner79a42ac2006-12-19 21:40:18 +000037STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
38
Chris Lattnera5434ca2003-06-22 20:10:28 +000039namespace {
Chris Lattnerc14da962004-04-18 00:52:43 +000040 cl::opt<unsigned>
41 Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
42 cl::init(6), cl::Hidden);
Reid Spencer557ab152007-02-05 23:32:05 +000043 class VISIBILITY_HIDDEN TailDup : public FunctionPass {
Chris Lattnera5434ca2003-06-22 20:10:28 +000044 bool runOnFunction(Function &F);
45 private:
46 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
47 inline void eliminateUnconditionalBranch(BranchInst *BI);
Chris Lattnera5434ca2003-06-22 20:10:28 +000048 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +000049 RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
Chris Lattnera5434ca2003-06-22 20:10:28 +000050}
51
Brian Gaeke960707c2003-11-11 22:41:34 +000052// Public interface to the Tail Duplication pass
Chris Lattner3e860842004-09-20 04:43:15 +000053FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
Chris Lattnera5434ca2003-06-22 20:10:28 +000054
55/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
56/// the function, eliminating it if it looks attractive enough.
57///
58bool TailDup::runOnFunction(Function &F) {
59 bool Changed = false;
60 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
Chris Lattner95057f62004-03-16 23:29:09 +000061 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
Chris Lattnera5434ca2003-06-22 20:10:28 +000062 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///
79bool 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
Chris Lattnerd78ebd02003-07-23 03:32:41 +000086 // Do not inline a block if we will just get another branch to the same block!
Chris Lattnera64923a2004-03-16 19:45:22 +000087 TerminatorInst *DTI = Dest->getTerminator();
88 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
Chris Lattnerd78ebd02003-07-23 03:32:41 +000089 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
90 return false; // Do not loop infinitely!
91
Chris Lattner95057f62004-03-16 23:29:09 +000092 // 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
Chris Lattnera5434ca2003-06-22 20:10:28 +000098 // 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
Chris Lattner540e5f92004-11-22 17:23:57 +0000111 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 }
Chris Lattnera64923a2004-03-16 19:45:22 +0000116
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.
Chris Lattner8af74242004-11-01 07:05:07 +0000121 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 }
Chris Lattnerc4650462006-09-07 21:30:15 +0000129
130 // Finally, if this unconditional branch is a fall-through, be careful about
131 // tail duplicating it. In particular, we don't want to taildup it if the
132 // original block will still be there after taildup is completed: doing so
133 // would eliminate the fall-through, requiring unconditional branches.
134 Function::iterator DestI = Dest;
135 if (&*--DestI == BI->getParent()) {
136 // The uncond branch is a fall-through. Tail duplication of the block is
137 // will eliminate the fall-through-ness and end up cloning the terminator
138 // at the end of the Dest block. Since the original Dest block will
139 // continue to exist, this means that one or the other will not be able to
140 // fall through. One typical example that this helps with is code like:
141 // if (a)
142 // foo();
143 // if (b)
144 // foo();
145 // Cloning the 'if b' block into the end of the first foo block is messy.
Chris Lattnerd1f8e072006-09-10 18:17:58 +0000146
147 // The messy case is when the fall-through block falls through to other
148 // blocks. This is what we would be preventing if we cloned the block.
149 DestI = Dest;
150 if (++DestI != Dest->getParent()->end()) {
151 BasicBlock *DestSucc = DestI;
152 // If any of Dest's successors are fall-throughs, don't do this xform.
153 for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
154 SI != SE; ++SI)
155 if (*SI == DestSucc)
156 return false;
157 }
Chris Lattnerc4650462006-09-07 21:30:15 +0000158 }
Chris Lattnera64923a2004-03-16 19:45:22 +0000159
Misha Brukmanb1c93172005-04-21 23:48:37 +0000160 return true;
Chris Lattnera5434ca2003-06-22 20:10:28 +0000161}
162
Chris Lattner2ce32df2004-10-06 03:27:37 +0000163/// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
164/// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
165/// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
166/// DstBlock, return it.
167static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
168 BasicBlock *DstBlock) {
169 // SrcBlock must have a single predecessor.
170 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
171 if (PI == PE || ++PI != PE) return 0;
172
173 BasicBlock *SrcPred = *pred_begin(SrcBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000174
Chris Lattner2ce32df2004-10-06 03:27:37 +0000175 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
176 // there is only one other pred, get it, otherwise we can't handle it.
177 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
178 BasicBlock *DstOtherPred = 0;
179 if (*PI == SrcBlock) {
180 if (++PI == PE) return 0;
181 DstOtherPred = *PI;
182 if (++PI != PE) return 0;
183 } else {
184 DstOtherPred = *PI;
185 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
186 }
187
188 // We can handle two situations here: "if then" and "if then else" blocks. An
189 // 'if then' situation is just where DstOtherPred == SrcPred.
190 if (DstOtherPred == SrcPred)
191 return SrcPred;
192
193 // Check to see if we have an "if then else" situation, which means that
194 // DstOtherPred will have a single predecessor and it will be SrcPred.
195 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
196 if (PI != PE && *PI == SrcPred) {
197 if (++PI != PE) return 0; // Not a single pred.
198 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
199 }
200
201 // Otherwise, this is something we can't handle.
202 return 0;
203}
204
Chris Lattnera5434ca2003-06-22 20:10:28 +0000205
206/// eliminateUnconditionalBranch - Clone the instructions from the destination
207/// block into the source block, eliminating the specified unconditional branch.
208/// If the destination block defines values used by successors of the dest
209/// block, we may need to insert PHI nodes.
210///
211void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
212 BasicBlock *SourceBlock = Branch->getParent();
213 BasicBlock *DestBlock = Branch->getSuccessor(0);
214 assert(SourceBlock != DestBlock && "Our predicate is broken!");
215
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000216 DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
217 << "]: Eliminating branch: " << *Branch;
Chris Lattnera5434ca2003-06-22 20:10:28 +0000218
Chris Lattner2ce32df2004-10-06 03:27:37 +0000219 // See if we can avoid duplicating code by moving it up to a dominator of both
220 // blocks.
221 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000222 DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
Chris Lattner2ce32df2004-10-06 03:27:37 +0000223
224 // If there are non-phi instructions in DestBlock that have no operands
225 // defined in DestBlock, and if the instruction has no side effects, we can
226 // move the instruction to DomBlock instead of duplicating it.
227 BasicBlock::iterator BBI = DestBlock->begin();
228 while (isa<PHINode>(BBI)) ++BBI;
229 while (!isa<TerminatorInst>(BBI)) {
230 Instruction *I = BBI++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000231
Chris Lattner2ce32df2004-10-06 03:27:37 +0000232 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
233 if (CanHoist) {
234 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
235 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
236 if (OpI->getParent() == DestBlock ||
237 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
238 CanHoist = false;
239 break;
240 }
241 if (CanHoist) {
242 // Remove from DestBlock, move right before the term in DomBlock.
243 DestBlock->getInstList().remove(I);
244 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000245 DOUT << "Hoisted: " << *I;
Chris Lattner2ce32df2004-10-06 03:27:37 +0000246 }
247 }
248 }
249 }
250
Chris Lattner95057f62004-03-16 23:29:09 +0000251 // Tail duplication can not update SSA properties correctly if the values
252 // defined in the duplicated tail are used outside of the tail itself. For
253 // this reason, we spill all values that are used outside of the tail to the
254 // stack.
255 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
256 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
257 ++UI) {
258 bool ShouldDemote = false;
259 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
260 // We must allow our successors to use tail values in their PHI nodes
261 // (if the incoming value corresponds to the tail block).
262 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
263 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
264 if (PN->getIncomingValue(i) == I &&
265 PN->getIncomingBlock(i) != DestBlock) {
266 ShouldDemote = true;
267 break;
268 }
269
270 } else {
271 ShouldDemote = true;
272 }
273 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
274 // If the user of this instruction is a PHI node in the current block,
Chris Lattnera3783a52004-03-16 23:36:49 +0000275 // which has an entry from another block using the value, spill it.
276 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
277 if (PN->getIncomingValue(i) == I &&
278 PN->getIncomingBlock(i) != DestBlock) {
279 ShouldDemote = true;
280 break;
281 }
Chris Lattner95057f62004-03-16 23:29:09 +0000282 }
283
284 if (ShouldDemote) {
285 // We found a use outside of the tail. Create a new stack slot to
286 // break this inter-block usage pattern.
287 DemoteRegToStack(*I);
288 break;
289 }
290 }
291
Chris Lattnera5434ca2003-06-22 20:10:28 +0000292 // We are going to have to map operands from the original block B to the new
293 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
294 // nodes also define part of this mapping. Loop over these PHI nodes, adding
295 // them to our mapping.
Chris Lattner268c1392003-06-22 20:25:27 +0000296 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000297 std::map<Value*, Value*> ValueMapping;
298
299 BasicBlock::iterator BI = DestBlock->begin();
300 bool HadPHINodes = isa<PHINode>(BI);
301 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
302 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
303
304 // Clone the non-phi instructions of the dest block into the source block,
305 // keeping track of the mapping...
306 //
307 for (; BI != DestBlock->end(); ++BI) {
308 Instruction *New = BI->clone();
309 New->setName(BI->getName());
310 SourceBlock->getInstList().push_back(New);
311 ValueMapping[BI] = New;
312 }
313
314 // Now that we have built the mapping information and cloned all of the
315 // instructions (giving us a new terminator, among other things), walk the new
316 // instructions, rewriting references of old instructions to use new
317 // instructions.
318 //
319 BI = Branch; ++BI; // Get an iterator to the first new instruction
320 for (; BI != SourceBlock->end(); ++BI)
321 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
322 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
323 BI->setOperand(i, Remapped);
324
325 // Next we check to see if any of the successors of DestBlock had PHI nodes.
326 // If so, we need to add entries to the PHI nodes for SourceBlock now.
327 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
328 SI != SE; ++SI) {
329 BasicBlock *Succ = *SI;
Reid Spencer66149462004-09-15 17:06:42 +0000330 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
331 PHINode *PN = cast<PHINode>(PNI);
Chris Lattnera5434ca2003-06-22 20:10:28 +0000332 // Ok, we have a PHI node. Figure out what the incoming value was for the
333 // DestBlock.
334 Value *IV = PN->getIncomingValueForBlock(DestBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000335
Chris Lattnera5434ca2003-06-22 20:10:28 +0000336 // Remap the value if necessary...
337 if (Value *MappedIV = ValueMapping[IV])
338 IV = MappedIV;
339 PN->addIncoming(IV, SourceBlock);
340 }
341 }
Chris Lattner95057f62004-03-16 23:29:09 +0000342
343 // Next, remove the old branch instruction, and any PHI node entries that we
344 // had.
345 BI = Branch; ++BI; // Get an iterator to the first new instruction
346 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
347 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
Chris Lattnera5434ca2003-06-22 20:10:28 +0000348
349 // Final step: now that we have finished everything up, walk the cloned
350 // instructions one last time, constant propagating and DCE'ing them, because
351 // they may not be needed anymore.
352 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000353 if (HadPHINodes)
354 while (BI != SourceBlock->end())
355 if (!dceInstruction(BI) && !doConstantPropagation(BI))
356 ++BI;
357
Chris Lattnera5434ca2003-06-22 20:10:28 +0000358 ++NumEliminated; // We just killed a branch!
359}