blob: d0998ab5a65d5984d7443985da79f179aa60e357 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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"
Dale Johannesen0ba11562008-05-13 20:06:43 +000035#include "llvm/ADT/SmallPtrSet.h"
Dan Gohman249ddbf2008-03-21 23:51:57 +000036#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037using namespace llvm;
38
39STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
40
Dan Gohman089efff2008-05-13 00:00:25 +000041static cl::opt<unsigned>
Evan Cheng2c88b9b2008-05-16 07:55:50 +000042TailDupThreshold("taildup-threshold",
43 cl::desc("Max block size to tail duplicate"),
44 cl::init(1), cl::Hidden);
Dan Gohman089efff2008-05-13 00:00:25 +000045
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047 class VISIBILITY_HIDDEN TailDup : public FunctionPass {
48 bool runOnFunction(Function &F);
49 public:
50 static char ID; // Pass identification, replacement for typeid
51 TailDup() : FunctionPass((intptr_t)&ID) {}
52
53 private:
Evan Cheng2c88b9b2008-05-16 07:55:50 +000054 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *, unsigned);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055 inline void eliminateUnconditionalBranch(BranchInst *BI);
Dale Johannesen0ba11562008-05-13 20:06:43 +000056 SmallPtrSet<BasicBlock*, 4> CycleDetector;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058}
59
Dan Gohman089efff2008-05-13 00:00:25 +000060char TailDup::ID = 0;
61static RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
62
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063// Public interface to the Tail Duplication pass
64FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
65
66/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
Dale Johannesen0ba11562008-05-13 20:06:43 +000067/// the function, eliminating it if it looks attractive enough. CycleDetector
68/// prevents infinite loops by checking that we aren't redirecting a branch to
69/// a place it already pointed to earlier; see PR 2323.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070bool TailDup::runOnFunction(Function &F) {
71 bool Changed = false;
Dale Johannesen0ba11562008-05-13 20:06:43 +000072 CycleDetector.clear();
73 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Evan Cheng2c88b9b2008-05-16 07:55:50 +000074 if (shouldEliminateUnconditionalBranch(I->getTerminator(),
75 TailDupThreshold)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
77 Changed = true;
78 } else {
79 ++I;
Dale Johannesen0ba11562008-05-13 20:06:43 +000080 CycleDetector.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081 }
Dale Johannesen0ba11562008-05-13 20:06:43 +000082 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083 return Changed;
84}
85
86/// shouldEliminateUnconditionalBranch - Return true if this branch looks
87/// attractive to eliminate. We eliminate the branch if the destination basic
88/// block has <= 5 instructions in it, not counting PHI nodes. In practice,
89/// since one of these is a terminator instruction, this means that we will add
90/// up to 4 instructions to the new block.
91///
92/// We don't count PHI nodes in the count since they will be removed when the
93/// contents of the block are copied over.
94///
Evan Cheng2c88b9b2008-05-16 07:55:50 +000095bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI,
96 unsigned Threshold) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097 BranchInst *BI = dyn_cast<BranchInst>(TI);
98 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
99
100 BasicBlock *Dest = BI->getSuccessor(0);
101 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
102
103 // Do not inline a block if we will just get another branch to the same block!
104 TerminatorInst *DTI = Dest->getTerminator();
105 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
106 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
107 return false; // Do not loop infinitely!
108
109 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
110 // because doing so would require breaking critical edges. This should be
111 // fixed eventually.
112 if (!DTI->use_empty())
113 return false;
114
Devang Patel4082ea22008-05-15 18:04:29 +0000115 // Do not bother with blocks with only a single predecessor: simplify
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116 // CFG will fold these two blocks together!
Devang Patel4082ea22008-05-15 18:04:29 +0000117 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118 ++PI;
119 if (PI == PE) return false; // Exactly one predecessor!
120
Dan Gohman514277c2008-05-23 21:05:58 +0000121 BasicBlock::iterator I = Dest->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122
123 for (unsigned Size = 0; I != Dest->end(); ++I) {
124 if (Size == Threshold) return false; // The block is too large.
Chris Lattner5fafff82007-11-04 06:37:55 +0000125
126 // Don't tail duplicate call instructions. They are very large compared to
127 // other instructions.
128 if (isa<CallInst>(I) || isa<InvokeInst>(I)) return false;
Evan Cheng2c88b9b2008-05-16 07:55:50 +0000129
130 // Allso alloca and malloc.
131 if (isa<AllocationInst>(I)) return false;
132
133 // Some vector instructions can expand into a number of instructions.
134 if (isa<ShuffleVectorInst>(I) || isa<ExtractElementInst>(I) ||
135 isa<InsertElementInst>(I)) return false;
Chris Lattner5fafff82007-11-04 06:37:55 +0000136
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137 // Only count instructions that are not debugger intrinsics.
138 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
139 }
140
141 // Do not tail duplicate a block that has thousands of successors into a block
142 // with a single successor if the block has many other predecessors. This can
143 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
144 // cases that have a large number of indirect gotos.
145 unsigned NumSuccs = DTI->getNumSuccessors();
146 if (NumSuccs > 8) {
147 unsigned TooMany = 128;
148 if (NumSuccs >= TooMany) return false;
149 TooMany = TooMany/NumSuccs;
150 for (; PI != PE; ++PI)
151 if (TooMany-- == 0) return false;
152 }
153
Dale Johannesen0ba11562008-05-13 20:06:43 +0000154 // If this unconditional branch is a fall-through, be careful about
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 // tail duplicating it. In particular, we don't want to taildup it if the
156 // original block will still be there after taildup is completed: doing so
157 // would eliminate the fall-through, requiring unconditional branches.
158 Function::iterator DestI = Dest;
159 if (&*--DestI == BI->getParent()) {
160 // The uncond branch is a fall-through. Tail duplication of the block is
161 // will eliminate the fall-through-ness and end up cloning the terminator
162 // at the end of the Dest block. Since the original Dest block will
163 // continue to exist, this means that one or the other will not be able to
164 // fall through. One typical example that this helps with is code like:
165 // if (a)
166 // foo();
167 // if (b)
168 // foo();
169 // Cloning the 'if b' block into the end of the first foo block is messy.
170
171 // The messy case is when the fall-through block falls through to other
172 // blocks. This is what we would be preventing if we cloned the block.
173 DestI = Dest;
174 if (++DestI != Dest->getParent()->end()) {
175 BasicBlock *DestSucc = DestI;
176 // If any of Dest's successors are fall-throughs, don't do this xform.
177 for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
178 SI != SE; ++SI)
179 if (*SI == DestSucc)
180 return false;
181 }
182 }
183
Dale Johannesen0ba11562008-05-13 20:06:43 +0000184 // Finally, check that we haven't redirected to this target block earlier;
185 // there are cases where we loop forever if we don't check this (PR 2323).
186 if (!CycleDetector.insert(Dest))
187 return false;
188
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 return true;
190}
191
192/// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
193/// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
194/// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
195/// DstBlock, return it.
196static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
197 BasicBlock *DstBlock) {
198 // SrcBlock must have a single predecessor.
199 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
200 if (PI == PE || ++PI != PE) return 0;
201
202 BasicBlock *SrcPred = *pred_begin(SrcBlock);
203
204 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
205 // there is only one other pred, get it, otherwise we can't handle it.
206 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
207 BasicBlock *DstOtherPred = 0;
208 if (*PI == SrcBlock) {
209 if (++PI == PE) return 0;
210 DstOtherPred = *PI;
211 if (++PI != PE) return 0;
212 } else {
213 DstOtherPred = *PI;
214 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
215 }
216
217 // We can handle two situations here: "if then" and "if then else" blocks. An
218 // 'if then' situation is just where DstOtherPred == SrcPred.
219 if (DstOtherPred == SrcPred)
220 return SrcPred;
221
222 // Check to see if we have an "if then else" situation, which means that
223 // DstOtherPred will have a single predecessor and it will be SrcPred.
224 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
225 if (PI != PE && *PI == SrcPred) {
226 if (++PI != PE) return 0; // Not a single pred.
227 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
228 }
229
230 // Otherwise, this is something we can't handle.
231 return 0;
232}
233
234
235/// eliminateUnconditionalBranch - Clone the instructions from the destination
236/// block into the source block, eliminating the specified unconditional branch.
237/// If the destination block defines values used by successors of the dest
238/// block, we may need to insert PHI nodes.
239///
240void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
241 BasicBlock *SourceBlock = Branch->getParent();
242 BasicBlock *DestBlock = Branch->getSuccessor(0);
243 assert(SourceBlock != DestBlock && "Our predicate is broken!");
244
245 DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
246 << "]: Eliminating branch: " << *Branch;
247
248 // See if we can avoid duplicating code by moving it up to a dominator of both
249 // blocks.
250 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
251 DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
252
253 // If there are non-phi instructions in DestBlock that have no operands
254 // defined in DestBlock, and if the instruction has no side effects, we can
255 // move the instruction to DomBlock instead of duplicating it.
Dan Gohman514277c2008-05-23 21:05:58 +0000256 BasicBlock::iterator BBI = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 while (!isa<TerminatorInst>(BBI)) {
258 Instruction *I = BBI++;
259
260 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
261 if (CanHoist) {
262 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
263 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
264 if (OpI->getParent() == DestBlock ||
265 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
266 CanHoist = false;
267 break;
268 }
269 if (CanHoist) {
270 // Remove from DestBlock, move right before the term in DomBlock.
271 DestBlock->getInstList().remove(I);
272 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
273 DOUT << "Hoisted: " << *I;
274 }
275 }
276 }
277 }
278
279 // Tail duplication can not update SSA properties correctly if the values
280 // defined in the duplicated tail are used outside of the tail itself. For
281 // this reason, we spill all values that are used outside of the tail to the
282 // stack.
283 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
Chris Lattnerfe86ab22008-04-20 22:18:22 +0000284 if (I->isUsedOutsideOfBlock(DestBlock)) {
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);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 }
289
290 // We are going to have to map operands from the original block B to the new
291 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
292 // nodes also define part of this mapping. Loop over these PHI nodes, adding
293 // them to our mapping.
294 //
295 std::map<Value*, Value*> ValueMapping;
296
297 BasicBlock::iterator BI = DestBlock->begin();
298 bool HadPHINodes = isa<PHINode>(BI);
299 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
300 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
301
302 // Clone the non-phi instructions of the dest block into the source block,
303 // keeping track of the mapping...
304 //
305 for (; BI != DestBlock->end(); ++BI) {
306 Instruction *New = BI->clone();
Owen Andersonab567f82008-04-14 17:38:21 +0000307 New->setName(BI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 SourceBlock->getInstList().push_back(New);
309 ValueMapping[BI] = New;
310 }
311
312 // Now that we have built the mapping information and cloned all of the
313 // instructions (giving us a new terminator, among other things), walk the new
314 // instructions, rewriting references of old instructions to use new
315 // instructions.
316 //
317 BI = Branch; ++BI; // Get an iterator to the first new instruction
318 for (; BI != SourceBlock->end(); ++BI)
319 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
320 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
321 BI->setOperand(i, Remapped);
322
323 // Next we check to see if any of the successors of DestBlock had PHI nodes.
324 // If so, we need to add entries to the PHI nodes for SourceBlock now.
325 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
326 SI != SE; ++SI) {
327 BasicBlock *Succ = *SI;
328 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
329 PHINode *PN = cast<PHINode>(PNI);
330 // Ok, we have a PHI node. Figure out what the incoming value was for the
331 // DestBlock.
332 Value *IV = PN->getIncomingValueForBlock(DestBlock);
333
334 // Remap the value if necessary...
335 if (Value *MappedIV = ValueMapping[IV])
336 IV = MappedIV;
337 PN->addIncoming(IV, SourceBlock);
338 }
339 }
340
341 // Next, remove the old branch instruction, and any PHI node entries that we
342 // had.
343 BI = Branch; ++BI; // Get an iterator to the first new instruction
344 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
345 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
346
347 // Final step: now that we have finished everything up, walk the cloned
348 // instructions one last time, constant propagating and DCE'ing them, because
349 // they may not be needed anymore.
350 //
351 if (HadPHINodes)
352 while (BI != SourceBlock->end())
353 if (!dceInstruction(BI) && !doConstantPropagation(BI))
354 ++BI;
355
356 ++NumEliminated; // We just killed a branch!
357}