blob: 97e8b186e525d6fe25c9afbe746df6b0060a96c9 [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"
32#include "llvm/Support/Debug.h"
33#include "llvm/ADT/Statistic.h"
Chris Lattner49525f82004-01-09 06:02:20 +000034using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000035
Chris Lattner79a42ac2006-12-19 21:40:18 +000036STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
37
Chris Lattnera5434ca2003-06-22 20:10:28 +000038namespace {
Chris Lattnerc14da962004-04-18 00:52:43 +000039 cl::opt<unsigned>
40 Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
41 cl::init(6), cl::Hidden);
Chris Lattnera5434ca2003-06-22 20:10:28 +000042 class TailDup : public FunctionPass {
43 bool runOnFunction(Function &F);
44 private:
45 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
46 inline void eliminateUnconditionalBranch(BranchInst *BI);
Chris Lattnera5434ca2003-06-22 20:10:28 +000047 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +000048 RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
Chris Lattnera5434ca2003-06-22 20:10:28 +000049}
50
Brian Gaeke960707c2003-11-11 22:41:34 +000051// Public interface to the Tail Duplication pass
Chris Lattner3e860842004-09-20 04:43:15 +000052FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
Chris Lattnera5434ca2003-06-22 20:10:28 +000053
54/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
55/// the function, eliminating it if it looks attractive enough.
56///
57bool TailDup::runOnFunction(Function &F) {
58 bool Changed = false;
59 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
Chris Lattner95057f62004-03-16 23:29:09 +000060 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
Chris Lattnera5434ca2003-06-22 20:10:28 +000061 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///
78bool 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
Chris Lattnerd78ebd02003-07-23 03:32:41 +000085 // Do not inline a block if we will just get another branch to the same block!
Chris Lattnera64923a2004-03-16 19:45:22 +000086 TerminatorInst *DTI = Dest->getTerminator();
87 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
Chris Lattnerd78ebd02003-07-23 03:32:41 +000088 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
89 return false; // Do not loop infinitely!
90
Chris Lattner95057f62004-03-16 23:29:09 +000091 // 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
Chris Lattnera5434ca2003-06-22 20:10:28 +000097 // 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
Chris Lattner540e5f92004-11-22 17:23:57 +0000110 for (unsigned Size = 0; I != Dest->end(); ++I) {
111 if (Size == Threshold) return false; // The block is too large.
112 // Only count instructions that are not debugger intrinsics.
113 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
114 }
Chris Lattnera64923a2004-03-16 19:45:22 +0000115
116 // Do not tail duplicate a block that has thousands of successors into a block
117 // with a single successor if the block has many other predecessors. This can
118 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
119 // cases that have a large number of indirect gotos.
Chris Lattner8af74242004-11-01 07:05:07 +0000120 unsigned NumSuccs = DTI->getNumSuccessors();
121 if (NumSuccs > 8) {
122 unsigned TooMany = 128;
123 if (NumSuccs >= TooMany) return false;
124 TooMany = TooMany/NumSuccs;
125 for (; PI != PE; ++PI)
126 if (TooMany-- == 0) return false;
127 }
Chris Lattnerc4650462006-09-07 21:30:15 +0000128
129 // Finally, if this unconditional branch is a fall-through, be careful about
130 // tail duplicating it. In particular, we don't want to taildup it if the
131 // original block will still be there after taildup is completed: doing so
132 // would eliminate the fall-through, requiring unconditional branches.
133 Function::iterator DestI = Dest;
134 if (&*--DestI == BI->getParent()) {
135 // The uncond branch is a fall-through. Tail duplication of the block is
136 // will eliminate the fall-through-ness and end up cloning the terminator
137 // at the end of the Dest block. Since the original Dest block will
138 // continue to exist, this means that one or the other will not be able to
139 // fall through. One typical example that this helps with is code like:
140 // if (a)
141 // foo();
142 // if (b)
143 // foo();
144 // Cloning the 'if b' block into the end of the first foo block is messy.
Chris Lattnerd1f8e072006-09-10 18:17:58 +0000145
146 // The messy case is when the fall-through block falls through to other
147 // blocks. This is what we would be preventing if we cloned the block.
148 DestI = Dest;
149 if (++DestI != Dest->getParent()->end()) {
150 BasicBlock *DestSucc = DestI;
151 // If any of Dest's successors are fall-throughs, don't do this xform.
152 for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
153 SI != SE; ++SI)
154 if (*SI == DestSucc)
155 return false;
156 }
Chris Lattnerc4650462006-09-07 21:30:15 +0000157 }
Chris Lattnera64923a2004-03-16 19:45:22 +0000158
Misha Brukmanb1c93172005-04-21 23:48:37 +0000159 return true;
Chris Lattnera5434ca2003-06-22 20:10:28 +0000160}
161
Chris Lattner2ce32df2004-10-06 03:27:37 +0000162/// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
163/// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
164/// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
165/// DstBlock, return it.
166static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
167 BasicBlock *DstBlock) {
168 // SrcBlock must have a single predecessor.
169 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
170 if (PI == PE || ++PI != PE) return 0;
171
172 BasicBlock *SrcPred = *pred_begin(SrcBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000173
Chris Lattner2ce32df2004-10-06 03:27:37 +0000174 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
175 // there is only one other pred, get it, otherwise we can't handle it.
176 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
177 BasicBlock *DstOtherPred = 0;
178 if (*PI == SrcBlock) {
179 if (++PI == PE) return 0;
180 DstOtherPred = *PI;
181 if (++PI != PE) return 0;
182 } else {
183 DstOtherPred = *PI;
184 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
185 }
186
187 // We can handle two situations here: "if then" and "if then else" blocks. An
188 // 'if then' situation is just where DstOtherPred == SrcPred.
189 if (DstOtherPred == SrcPred)
190 return SrcPred;
191
192 // Check to see if we have an "if then else" situation, which means that
193 // DstOtherPred will have a single predecessor and it will be SrcPred.
194 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
195 if (PI != PE && *PI == SrcPred) {
196 if (++PI != PE) return 0; // Not a single pred.
197 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
198 }
199
200 // Otherwise, this is something we can't handle.
201 return 0;
202}
203
Chris Lattnera5434ca2003-06-22 20:10:28 +0000204
205/// eliminateUnconditionalBranch - Clone the instructions from the destination
206/// block into the source block, eliminating the specified unconditional branch.
207/// If the destination block defines values used by successors of the dest
208/// block, we may need to insert PHI nodes.
209///
210void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
211 BasicBlock *SourceBlock = Branch->getParent();
212 BasicBlock *DestBlock = Branch->getSuccessor(0);
213 assert(SourceBlock != DestBlock && "Our predicate is broken!");
214
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000215 DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
216 << "]: Eliminating branch: " << *Branch;
Chris Lattnera5434ca2003-06-22 20:10:28 +0000217
Chris Lattner2ce32df2004-10-06 03:27:37 +0000218 // See if we can avoid duplicating code by moving it up to a dominator of both
219 // blocks.
220 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000221 DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
Chris Lattner2ce32df2004-10-06 03:27:37 +0000222
223 // If there are non-phi instructions in DestBlock that have no operands
224 // defined in DestBlock, and if the instruction has no side effects, we can
225 // move the instruction to DomBlock instead of duplicating it.
226 BasicBlock::iterator BBI = DestBlock->begin();
227 while (isa<PHINode>(BBI)) ++BBI;
228 while (!isa<TerminatorInst>(BBI)) {
229 Instruction *I = BBI++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000230
Chris Lattner2ce32df2004-10-06 03:27:37 +0000231 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
232 if (CanHoist) {
233 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
234 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
235 if (OpI->getParent() == DestBlock ||
236 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
237 CanHoist = false;
238 break;
239 }
240 if (CanHoist) {
241 // Remove from DestBlock, move right before the term in DomBlock.
242 DestBlock->getInstList().remove(I);
243 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000244 DOUT << "Hoisted: " << *I;
Chris Lattner2ce32df2004-10-06 03:27:37 +0000245 }
246 }
247 }
248 }
249
Chris Lattner95057f62004-03-16 23:29:09 +0000250 // Tail duplication can not update SSA properties correctly if the values
251 // defined in the duplicated tail are used outside of the tail itself. For
252 // this reason, we spill all values that are used outside of the tail to the
253 // stack.
254 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
255 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
256 ++UI) {
257 bool ShouldDemote = false;
258 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
259 // We must allow our successors to use tail values in their PHI nodes
260 // (if the incoming value corresponds to the tail block).
261 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
262 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
263 if (PN->getIncomingValue(i) == I &&
264 PN->getIncomingBlock(i) != DestBlock) {
265 ShouldDemote = true;
266 break;
267 }
268
269 } else {
270 ShouldDemote = true;
271 }
272 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
273 // If the user of this instruction is a PHI node in the current block,
Chris Lattnera3783a52004-03-16 23:36:49 +0000274 // which has an entry from another block using the value, spill it.
275 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
276 if (PN->getIncomingValue(i) == I &&
277 PN->getIncomingBlock(i) != DestBlock) {
278 ShouldDemote = true;
279 break;
280 }
Chris Lattner95057f62004-03-16 23:29:09 +0000281 }
282
283 if (ShouldDemote) {
284 // We found a use outside of the tail. Create a new stack slot to
285 // break this inter-block usage pattern.
286 DemoteRegToStack(*I);
287 break;
288 }
289 }
290
Chris Lattnera5434ca2003-06-22 20:10:28 +0000291 // We are going to have to map operands from the original block B to the new
292 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
293 // nodes also define part of this mapping. Loop over these PHI nodes, adding
294 // them to our mapping.
Chris Lattner268c1392003-06-22 20:25:27 +0000295 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000296 std::map<Value*, Value*> ValueMapping;
297
298 BasicBlock::iterator BI = DestBlock->begin();
299 bool HadPHINodes = isa<PHINode>(BI);
300 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
301 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
302
303 // Clone the non-phi instructions of the dest block into the source block,
304 // keeping track of the mapping...
305 //
306 for (; BI != DestBlock->end(); ++BI) {
307 Instruction *New = BI->clone();
308 New->setName(BI->getName());
309 SourceBlock->getInstList().push_back(New);
310 ValueMapping[BI] = New;
311 }
312
313 // Now that we have built the mapping information and cloned all of the
314 // instructions (giving us a new terminator, among other things), walk the new
315 // instructions, rewriting references of old instructions to use new
316 // instructions.
317 //
318 BI = Branch; ++BI; // Get an iterator to the first new instruction
319 for (; BI != SourceBlock->end(); ++BI)
320 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
321 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
322 BI->setOperand(i, Remapped);
323
324 // Next we check to see if any of the successors of DestBlock had PHI nodes.
325 // If so, we need to add entries to the PHI nodes for SourceBlock now.
326 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
327 SI != SE; ++SI) {
328 BasicBlock *Succ = *SI;
Reid Spencer66149462004-09-15 17:06:42 +0000329 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
330 PHINode *PN = cast<PHINode>(PNI);
Chris Lattnera5434ca2003-06-22 20:10:28 +0000331 // Ok, we have a PHI node. Figure out what the incoming value was for the
332 // DestBlock.
333 Value *IV = PN->getIncomingValueForBlock(DestBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000334
Chris Lattnera5434ca2003-06-22 20:10:28 +0000335 // Remap the value if necessary...
336 if (Value *MappedIV = ValueMapping[IV])
337 IV = MappedIV;
338 PN->addIncoming(IV, SourceBlock);
339 }
340 }
Chris Lattner95057f62004-03-16 23:29:09 +0000341
342 // Next, remove the old branch instruction, and any PHI node entries that we
343 // had.
344 BI = Branch; ++BI; // Get an iterator to the first new instruction
345 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
346 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
Chris Lattnera5434ca2003-06-22 20:10:28 +0000347
348 // Final step: now that we have finished everything up, walk the cloned
349 // instructions one last time, constant propagating and DCE'ing them, because
350 // they may not be needed anymore.
351 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000352 if (HadPHINodes)
353 while (BI != SourceBlock->end())
354 if (!dceInstruction(BI) && !doConstantPropagation(BI))
355 ++BI;
356
Chris Lattnera5434ca2003-06-22 20:10:28 +0000357 ++NumEliminated; // We just killed a branch!
358}