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