1 //===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
3 // The LLVM Compiler Infrastructure
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.
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/Transforms/Utils/Local.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/Statistic.h"
39 Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
40 cl::init(6), cl::Hidden);
41 Statistic<> NumEliminated("tailduplicate",
42 "Number of unconditional branches eliminated");
43 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
45 class TailDup : public FunctionPass {
46 bool runOnFunction(Function &F);
48 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
49 inline void eliminateUnconditionalBranch(BranchInst *BI);
51 RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
54 // Public interface to the Tail Duplication pass
55 FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
57 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
58 /// the function, eliminating it if it looks attractive enough.
60 bool TailDup::runOnFunction(Function &F) {
62 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
63 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
64 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
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.
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.
81 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
82 BranchInst *BI = dyn_cast<BranchInst>(TI);
83 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
85 BasicBlock *Dest = BI->getSuccessor(0);
86 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
88 // Do not inline a block if we will just get another branch to the same block!
89 TerminatorInst *DTI = Dest->getTerminator();
90 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
91 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
92 return false; // Do not loop infinitely!
94 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
95 // because doing so would require breaking critical edges. This should be
97 if (!DTI->use_empty())
100 // 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...
105 // Also, do not bother with blocks with only a single predecessor: simplify
106 // CFG will fold these two blocks together!
108 if (PI == PE) return false; // Exactly one predecessor!
110 BasicBlock::iterator I = Dest->begin();
111 while (isa<PHINode>(*I)) ++I;
113 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;
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.
123 unsigned NumSuccs = DTI->getNumSuccessors();
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;
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:
147 // Cloning the 'if b' block into the end of the first foo block is messy.
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.
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);
165 /// 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.
169 static 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;
175 BasicBlock *SrcPred = *pred_begin(SrcBlock);
177 // 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;
184 if (++PI != PE) return 0;
187 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
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)
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.
203 // Otherwise, this is something we can't handle.
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.
213 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
214 BasicBlock *SourceBlock = Branch->getParent();
215 BasicBlock *DestBlock = Branch->getSuccessor(0);
216 assert(SourceBlock != DestBlock && "Our predicate is broken!");
218 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
219 << "]: Eliminating branch: " << *Branch);
221 // See if we can avoid duplicating code by moving it up to a dominator of both
223 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
224 DEBUG(std::cerr << "Found shared dominator: " << DomBlock->getName()
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++;
235 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
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)) {
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);
254 // 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
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;
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) {
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,
278 // 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) {
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);
295 // 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.
300 std::map<Value*, Value*> ValueMapping;
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);
307 // Clone the non-phi instructions of the dest block into the source block,
308 // keeping track of the mapping...
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;
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
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);
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);
332 BasicBlock *Succ = *SI;
333 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
334 PHINode *PN = cast<PHINode>(PNI);
335 // Ok, we have a PHI node. Figure out what the incoming value was for the
337 Value *IV = PN->getIncomingValueForBlock(DestBlock);
339 // Remap the value if necessary...
340 if (Value *MappedIV = ValueMapping[IV])
342 PN->addIncoming(IV, SourceBlock);
346 // Next, remove the old branch instruction, and any PHI node entries that we
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...
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.
357 while (BI != SourceBlock->end())
358 if (!dceInstruction(BI) && !doConstantPropagation(BI))
361 ++NumEliminated; // We just killed a branch!