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 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Constant.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Type.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "Support/CommandLine.h"
30 #include "Support/Debug.h"
31 #include "Support/Statistic.h"
36 Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
37 cl::init(6), cl::Hidden);
38 Statistic<> NumEliminated("tailduplicate",
39 "Number of unconditional branches eliminated");
40 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
42 class TailDup : public FunctionPass {
43 bool runOnFunction(Function &F);
45 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
46 inline void eliminateUnconditionalBranch(BranchInst *BI);
48 RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
51 // Public interface to the Tail Duplication pass
52 Pass *llvm::createTailDuplicationPass() { return new TailDup(); }
54 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
55 /// the function, eliminating it if it looks attractive enough.
57 bool TailDup::runOnFunction(Function &F) {
59 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
60 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
61 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
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.
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.
78 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
79 BranchInst *BI = dyn_cast<BranchInst>(TI);
80 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
82 BasicBlock *Dest = BI->getSuccessor(0);
83 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
85 // Do not inline a block if we will just get another branch to the same block!
86 TerminatorInst *DTI = Dest->getTerminator();
87 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
88 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
89 return false; // Do not loop infinitely!
91 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
92 // because doing so would require breaking critical edges. This should be
94 if (!DTI->use_empty())
97 // 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...
102 // Also, do not bother with blocks with only a single predecessor: simplify
103 // CFG will fold these two blocks together!
105 if (PI == PE) return false; // Exactly one predecessor!
107 BasicBlock::iterator I = Dest->begin();
108 while (isa<PHINode>(*I)) ++I;
110 for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
111 if (Size == Threshold) return false; // The block is too large...
113 // Do not tail duplicate a block that has thousands of successors into a block
114 // with a single successor if the block has many other predecessors. This can
115 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
116 // cases that have a large number of indirect gotos.
117 if (DTI->getNumSuccessors() > 8)
118 if (std::distance(PI, PE) * DTI->getNumSuccessors() > 128)
125 /// eliminateUnconditionalBranch - Clone the instructions from the destination
126 /// block into the source block, eliminating the specified unconditional branch.
127 /// If the destination block defines values used by successors of the dest
128 /// block, we may need to insert PHI nodes.
130 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
131 BasicBlock *SourceBlock = Branch->getParent();
132 BasicBlock *DestBlock = Branch->getSuccessor(0);
133 assert(SourceBlock != DestBlock && "Our predicate is broken!");
135 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
136 << "]: Eliminating branch: " << *Branch);
138 // Tail duplication can not update SSA properties correctly if the values
139 // defined in the duplicated tail are used outside of the tail itself. For
140 // this reason, we spill all values that are used outside of the tail to the
142 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
143 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
145 bool ShouldDemote = false;
146 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
147 // We must allow our successors to use tail values in their PHI nodes
148 // (if the incoming value corresponds to the tail block).
149 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
150 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
151 if (PN->getIncomingValue(i) == I &&
152 PN->getIncomingBlock(i) != DestBlock) {
160 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
161 // If the user of this instruction is a PHI node in the current block,
162 // which has an entry from another block using the value, spill it.
163 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
164 if (PN->getIncomingValue(i) == I &&
165 PN->getIncomingBlock(i) != DestBlock) {
172 // We found a use outside of the tail. Create a new stack slot to
173 // break this inter-block usage pattern.
174 DemoteRegToStack(*I);
179 // We are going to have to map operands from the original block B to the new
180 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
181 // nodes also define part of this mapping. Loop over these PHI nodes, adding
182 // them to our mapping.
184 std::map<Value*, Value*> ValueMapping;
186 BasicBlock::iterator BI = DestBlock->begin();
187 bool HadPHINodes = isa<PHINode>(BI);
188 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
189 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
191 // Clone the non-phi instructions of the dest block into the source block,
192 // keeping track of the mapping...
194 for (; BI != DestBlock->end(); ++BI) {
195 Instruction *New = BI->clone();
196 New->setName(BI->getName());
197 SourceBlock->getInstList().push_back(New);
198 ValueMapping[BI] = New;
201 // Now that we have built the mapping information and cloned all of the
202 // instructions (giving us a new terminator, among other things), walk the new
203 // instructions, rewriting references of old instructions to use new
206 BI = Branch; ++BI; // Get an iterator to the first new instruction
207 for (; BI != SourceBlock->end(); ++BI)
208 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
209 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
210 BI->setOperand(i, Remapped);
212 // Next we check to see if any of the successors of DestBlock had PHI nodes.
213 // If so, we need to add entries to the PHI nodes for SourceBlock now.
214 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
216 BasicBlock *Succ = *SI;
217 for (BasicBlock::iterator PNI = Succ->begin();
218 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
219 // Ok, we have a PHI node. Figure out what the incoming value was for the
221 Value *IV = PN->getIncomingValueForBlock(DestBlock);
223 // Remap the value if necessary...
224 if (Value *MappedIV = ValueMapping[IV])
226 PN->addIncoming(IV, SourceBlock);
230 // Next, remove the old branch instruction, and any PHI node entries that we
232 BI = Branch; ++BI; // Get an iterator to the first new instruction
233 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
234 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
236 // Final step: now that we have finished everything up, walk the cloned
237 // instructions one last time, constant propagating and DCE'ing them, because
238 // they may not be needed anymore.
241 while (BI != SourceBlock->end())
242 if (!dceInstruction(BI) && !doConstantPropagation(BI))
245 ++NumEliminated; // We just killed a branch!