1 //===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
16 // This pass could be enhanced in the future to use profile information to be
19 //===----------------------------------------------------------------------===//
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/Analysis/ConstantFolding.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/SmallPtrSet.h"
41 STATISTIC(NumEliminated
, "Number of unconditional branches eliminated");
43 static cl::opt
<unsigned>
44 TailDupThreshold("taildup-threshold",
45 cl::desc("Max block size to tail duplicate"),
46 cl::init(1), cl::Hidden
);
49 class VISIBILITY_HIDDEN TailDup
: public FunctionPass
{
50 bool runOnFunction(Function
&F
);
52 static char ID
; // Pass identification, replacement for typeid
53 TailDup() : FunctionPass(&ID
) {}
56 inline bool shouldEliminateUnconditionalBranch(TerminatorInst
*, unsigned);
57 inline void eliminateUnconditionalBranch(BranchInst
*BI
);
58 SmallPtrSet
<BasicBlock
*, 4> CycleDetector
;
63 static RegisterPass
<TailDup
> X("tailduplicate", "Tail Duplication");
65 // Public interface to the Tail Duplication pass
66 FunctionPass
*llvm::createTailDuplicationPass() { return new TailDup(); }
68 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
69 /// the function, eliminating it if it looks attractive enough. CycleDetector
70 /// prevents infinite loops by checking that we aren't redirecting a branch to
71 /// a place it already pointed to earlier; see PR 2323.
72 bool TailDup::runOnFunction(Function
&F
) {
74 CycleDetector
.clear();
75 for (Function::iterator I
= F
.begin(), E
= F
.end(); I
!= E
; ) {
76 if (shouldEliminateUnconditionalBranch(I
->getTerminator(),
78 eliminateUnconditionalBranch(cast
<BranchInst
>(I
->getTerminator()));
82 CycleDetector
.clear();
88 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
89 /// attractive to eliminate. We eliminate the branch if the destination basic
90 /// block has <= 5 instructions in it, not counting PHI nodes. In practice,
91 /// since one of these is a terminator instruction, this means that we will add
92 /// up to 4 instructions to the new block.
94 /// We don't count PHI nodes in the count since they will be removed when the
95 /// contents of the block are copied over.
97 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst
*TI
,
99 BranchInst
*BI
= dyn_cast
<BranchInst
>(TI
);
100 if (!BI
|| !BI
->isUnconditional()) return false; // Not an uncond branch!
102 BasicBlock
*Dest
= BI
->getSuccessor(0);
103 if (Dest
== BI
->getParent()) return false; // Do not loop infinitely!
105 // Do not inline a block if we will just get another branch to the same block!
106 TerminatorInst
*DTI
= Dest
->getTerminator();
107 if (BranchInst
*DBI
= dyn_cast
<BranchInst
>(DTI
))
108 if (DBI
->isUnconditional() && DBI
->getSuccessor(0) == Dest
)
109 return false; // Do not loop infinitely!
111 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
112 // because doing so would require breaking critical edges. This should be
114 if (!DTI
->use_empty())
117 // Do not bother with blocks with only a single predecessor: simplify
118 // CFG will fold these two blocks together!
119 pred_iterator PI
= pred_begin(Dest
), PE
= pred_end(Dest
);
121 if (PI
== PE
) return false; // Exactly one predecessor!
123 BasicBlock::iterator I
= Dest
->getFirstNonPHI();
125 for (unsigned Size
= 0; I
!= Dest
->end(); ++I
) {
126 if (Size
== Threshold
) return false; // The block is too large.
128 // Don't tail duplicate call instructions. They are very large compared to
129 // other instructions.
130 if (isa
<CallInst
>(I
) || isa
<InvokeInst
>(I
)) return false;
132 // Allso alloca and malloc.
133 if (isa
<AllocationInst
>(I
)) return false;
135 // Some vector instructions can expand into a number of instructions.
136 if (isa
<ShuffleVectorInst
>(I
) || isa
<ExtractElementInst
>(I
) ||
137 isa
<InsertElementInst
>(I
)) return false;
139 // Only count instructions that are not debugger intrinsics.
140 if (!isa
<DbgInfoIntrinsic
>(I
)) ++Size
;
143 // Do not tail duplicate a block that has thousands of successors into a block
144 // with a single successor if the block has many other predecessors. This can
145 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
146 // cases that have a large number of indirect gotos.
147 unsigned NumSuccs
= DTI
->getNumSuccessors();
149 unsigned TooMany
= 128;
150 if (NumSuccs
>= TooMany
) return false;
151 TooMany
= TooMany
/NumSuccs
;
152 for (; PI
!= PE
; ++PI
)
153 if (TooMany
-- == 0) return false;
156 // If this unconditional branch is a fall-through, be careful about
157 // tail duplicating it. In particular, we don't want to taildup it if the
158 // original block will still be there after taildup is completed: doing so
159 // would eliminate the fall-through, requiring unconditional branches.
160 Function::iterator DestI
= Dest
;
161 if (&*--DestI
== BI
->getParent()) {
162 // The uncond branch is a fall-through. Tail duplication of the block is
163 // will eliminate the fall-through-ness and end up cloning the terminator
164 // at the end of the Dest block. Since the original Dest block will
165 // continue to exist, this means that one or the other will not be able to
166 // fall through. One typical example that this helps with is code like:
171 // Cloning the 'if b' block into the end of the first foo block is messy.
173 // The messy case is when the fall-through block falls through to other
174 // blocks. This is what we would be preventing if we cloned the block.
176 if (++DestI
!= Dest
->getParent()->end()) {
177 BasicBlock
*DestSucc
= DestI
;
178 // If any of Dest's successors are fall-throughs, don't do this xform.
179 for (succ_iterator SI
= succ_begin(Dest
), SE
= succ_end(Dest
);
186 // Finally, check that we haven't redirected to this target block earlier;
187 // there are cases where we loop forever if we don't check this (PR 2323).
188 if (!CycleDetector
.insert(Dest
))
194 /// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
195 /// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
196 /// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
197 /// DstBlock, return it.
198 static BasicBlock
*FindObviousSharedDomOf(BasicBlock
*SrcBlock
,
199 BasicBlock
*DstBlock
) {
200 // SrcBlock must have a single predecessor.
201 pred_iterator PI
= pred_begin(SrcBlock
), PE
= pred_end(SrcBlock
);
202 if (PI
== PE
|| ++PI
!= PE
) return 0;
204 BasicBlock
*SrcPred
= *pred_begin(SrcBlock
);
206 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
207 // there is only one other pred, get it, otherwise we can't handle it.
208 PI
= pred_begin(DstBlock
); PE
= pred_end(DstBlock
);
209 BasicBlock
*DstOtherPred
= 0;
210 if (*PI
== SrcBlock
) {
211 if (++PI
== PE
) return 0;
213 if (++PI
!= PE
) return 0;
216 if (++PI
== PE
|| *PI
!= SrcBlock
|| ++PI
!= PE
) return 0;
219 // We can handle two situations here: "if then" and "if then else" blocks. An
220 // 'if then' situation is just where DstOtherPred == SrcPred.
221 if (DstOtherPred
== SrcPred
)
224 // Check to see if we have an "if then else" situation, which means that
225 // DstOtherPred will have a single predecessor and it will be SrcPred.
226 PI
= pred_begin(DstOtherPred
); PE
= pred_end(DstOtherPred
);
227 if (PI
!= PE
&& *PI
== SrcPred
) {
228 if (++PI
!= PE
) return 0; // Not a single pred.
229 return SrcPred
; // Otherwise, it's an "if then" situation. Return the if.
232 // Otherwise, this is something we can't handle.
237 /// eliminateUnconditionalBranch - Clone the instructions from the destination
238 /// block into the source block, eliminating the specified unconditional branch.
239 /// If the destination block defines values used by successors of the dest
240 /// block, we may need to insert PHI nodes.
242 void TailDup::eliminateUnconditionalBranch(BranchInst
*Branch
) {
243 BasicBlock
*SourceBlock
= Branch
->getParent();
244 BasicBlock
*DestBlock
= Branch
->getSuccessor(0);
245 assert(SourceBlock
!= DestBlock
&& "Our predicate is broken!");
247 DEBUG(errs() << "TailDuplication[" << SourceBlock
->getParent()->getName()
248 << "]: Eliminating branch: " << *Branch
);
250 // See if we can avoid duplicating code by moving it up to a dominator of both
252 if (BasicBlock
*DomBlock
= FindObviousSharedDomOf(SourceBlock
, DestBlock
)) {
253 DEBUG(errs() << "Found shared dominator: " << DomBlock
->getName() << "\n");
255 // If there are non-phi instructions in DestBlock that have no operands
256 // defined in DestBlock, and if the instruction has no side effects, we can
257 // move the instruction to DomBlock instead of duplicating it.
258 BasicBlock::iterator BBI
= DestBlock
->getFirstNonPHI();
259 while (!isa
<TerminatorInst
>(BBI
)) {
260 Instruction
*I
= BBI
++;
262 bool CanHoist
= I
->isSafeToSpeculativelyExecute() &&
263 !I
->mayReadFromMemory();
265 for (unsigned op
= 0, e
= I
->getNumOperands(); op
!= e
; ++op
)
266 if (Instruction
*OpI
= dyn_cast
<Instruction
>(I
->getOperand(op
)))
267 if (OpI
->getParent() == DestBlock
||
268 (isa
<InvokeInst
>(OpI
) && OpI
->getParent() == DomBlock
)) {
273 // Remove from DestBlock, move right before the term in DomBlock.
274 DestBlock
->getInstList().remove(I
);
275 DomBlock
->getInstList().insert(DomBlock
->getTerminator(), I
);
276 DOUT
<< "Hoisted: " << *I
;
282 // Tail duplication can not update SSA properties correctly if the values
283 // defined in the duplicated tail are used outside of the tail itself. For
284 // this reason, we spill all values that are used outside of the tail to the
286 for (BasicBlock::iterator I
= DestBlock
->begin(); I
!= DestBlock
->end(); ++I
)
287 if (I
->isUsedOutsideOfBlock(DestBlock
)) {
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
);
293 // We are going to have to map operands from the original block B to the new
294 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
295 // nodes also define part of this mapping. Loop over these PHI nodes, adding
296 // them to our mapping.
298 std::map
<Value
*, Value
*> ValueMapping
;
300 BasicBlock::iterator BI
= DestBlock
->begin();
301 bool HadPHINodes
= isa
<PHINode
>(BI
);
302 for (; PHINode
*PN
= dyn_cast
<PHINode
>(BI
); ++BI
)
303 ValueMapping
[PN
] = PN
->getIncomingValueForBlock(SourceBlock
);
305 // Clone the non-phi instructions of the dest block into the source block,
306 // keeping track of the mapping...
308 for (; BI
!= DestBlock
->end(); ++BI
) {
309 Instruction
*New
= BI
->clone(BI
->getContext());
310 New
->setName(BI
->getName());
311 SourceBlock
->getInstList().push_back(New
);
312 ValueMapping
[BI
] = New
;
315 // Now that we have built the mapping information and cloned all of the
316 // instructions (giving us a new terminator, among other things), walk the new
317 // instructions, rewriting references of old instructions to use new
320 BI
= Branch
; ++BI
; // Get an iterator to the first new instruction
321 for (; BI
!= SourceBlock
->end(); ++BI
)
322 for (unsigned i
= 0, e
= BI
->getNumOperands(); i
!= e
; ++i
) {
323 std::map
<Value
*, Value
*>::const_iterator I
=
324 ValueMapping
.find(BI
->getOperand(i
));
325 if (I
!= ValueMapping
.end())
326 BI
->setOperand(i
, I
->second
);
329 // Next we check to see if any of the successors of DestBlock had PHI nodes.
330 // If so, we need to add entries to the PHI nodes for SourceBlock now.
331 for (succ_iterator SI
= succ_begin(DestBlock
), SE
= succ_end(DestBlock
);
333 BasicBlock
*Succ
= *SI
;
334 for (BasicBlock::iterator PNI
= Succ
->begin(); isa
<PHINode
>(PNI
); ++PNI
) {
335 PHINode
*PN
= cast
<PHINode
>(PNI
);
336 // Ok, we have a PHI node. Figure out what the incoming value was for the
338 Value
*IV
= PN
->getIncomingValueForBlock(DestBlock
);
340 // Remap the value if necessary...
341 std::map
<Value
*, Value
*>::const_iterator I
= ValueMapping
.find(IV
);
342 if (I
!= ValueMapping
.end())
344 PN
->addIncoming(IV
, SourceBlock
);
348 // Next, remove the old branch instruction, and any PHI node entries that we
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...
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.
359 while (BI
!= SourceBlock
->end()) {
360 Instruction
*Inst
= BI
++;
361 if (isInstructionTriviallyDead(Inst
))
362 Inst
->eraseFromParent();
363 else if (Constant
*C
= ConstantFoldInstruction(Inst
,
364 Inst
->getContext())) {
365 Inst
->replaceAllUsesWith(C
);
366 Inst
->eraseFromParent();
371 ++NumEliminated
; // We just killed a branch!