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/iPHINode.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Type.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Support/ValueHolder.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "Support/Debug.h"
32 #include "Support/Statistic.h"
36 Statistic<> NumEliminated("tailduplicate",
37 "Number of unconditional branches eliminated");
38 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
40 class TailDup : public FunctionPass {
41 bool runOnFunction(Function &F);
43 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
44 inline void eliminateUnconditionalBranch(BranchInst *BI);
46 RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
49 // Public interface to the Tail Duplication pass
50 Pass *llvm::createTailDuplicationPass() { return new TailDup(); }
52 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
53 /// the function, eliminating it if it looks attractive enough.
55 bool TailDup::runOnFunction(Function &F) {
57 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
58 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
59 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
67 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
68 /// attractive to eliminate. We eliminate the branch if the destination basic
69 /// block has <= 5 instructions in it, not counting PHI nodes. In practice,
70 /// since one of these is a terminator instruction, this means that we will add
71 /// up to 4 instructions to the new block.
73 /// We don't count PHI nodes in the count since they will be removed when the
74 /// contents of the block are copied over.
76 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
77 BranchInst *BI = dyn_cast<BranchInst>(TI);
78 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
80 BasicBlock *Dest = BI->getSuccessor(0);
81 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
83 // Do not inline a block if we will just get another branch to the same block!
84 TerminatorInst *DTI = Dest->getTerminator();
85 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
86 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
87 return false; // Do not loop infinitely!
89 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
90 // because doing so would require breaking critical edges. This should be
92 if (!DTI->use_empty())
95 // Do not bother working on dead blocks...
96 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
97 if (PI == PE && Dest != Dest->getParent()->begin())
98 return false; // It's just a dead block, ignore it...
100 // Also, do not bother with blocks with only a single predecessor: simplify
101 // CFG will fold these two blocks together!
103 if (PI == PE) return false; // Exactly one predecessor!
105 BasicBlock::iterator I = Dest->begin();
106 while (isa<PHINode>(*I)) ++I;
108 for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
109 if (Size == 6) return false; // The block is too large...
111 // Do not tail duplicate a block that has thousands of successors into a block
112 // with a single successor if the block has many other predecessors. This can
113 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
114 // cases that have a large number of indirect gotos.
115 if (DTI->getNumSuccessors() > 8)
116 if (std::distance(PI, PE) * DTI->getNumSuccessors() > 128)
123 /// eliminateUnconditionalBranch - Clone the instructions from the destination
124 /// block into the source block, eliminating the specified unconditional branch.
125 /// If the destination block defines values used by successors of the dest
126 /// block, we may need to insert PHI nodes.
128 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
129 BasicBlock *SourceBlock = Branch->getParent();
130 BasicBlock *DestBlock = Branch->getSuccessor(0);
131 assert(SourceBlock != DestBlock && "Our predicate is broken!");
133 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
134 << "]: Eliminating branch: " << *Branch);
136 // Tail duplication can not update SSA properties correctly if the values
137 // defined in the duplicated tail are used outside of the tail itself. For
138 // this reason, we spill all values that are used outside of the tail to the
140 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
141 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
143 bool ShouldDemote = false;
144 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
145 // We must allow our successors to use tail values in their PHI nodes
146 // (if the incoming value corresponds to the tail block).
147 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
148 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
149 if (PN->getIncomingValue(i) == I &&
150 PN->getIncomingBlock(i) != DestBlock) {
158 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
159 // If the user of this instruction is a PHI node in the current block,
160 // which has an entry from another block using the value, spill it.
161 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
162 if (PN->getIncomingValue(i) == I &&
163 PN->getIncomingBlock(i) != DestBlock) {
170 // We found a use outside of the tail. Create a new stack slot to
171 // break this inter-block usage pattern.
172 DemoteRegToStack(*I);
177 // We are going to have to map operands from the original block B to the new
178 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
179 // nodes also define part of this mapping. Loop over these PHI nodes, adding
180 // them to our mapping.
182 std::map<Value*, Value*> ValueMapping;
184 BasicBlock::iterator BI = DestBlock->begin();
185 bool HadPHINodes = isa<PHINode>(BI);
186 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
187 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
189 // Clone the non-phi instructions of the dest block into the source block,
190 // keeping track of the mapping...
192 for (; BI != DestBlock->end(); ++BI) {
193 Instruction *New = BI->clone();
194 New->setName(BI->getName());
195 SourceBlock->getInstList().push_back(New);
196 ValueMapping[BI] = New;
199 // Now that we have built the mapping information and cloned all of the
200 // instructions (giving us a new terminator, among other things), walk the new
201 // instructions, rewriting references of old instructions to use new
204 BI = Branch; ++BI; // Get an iterator to the first new instruction
205 for (; BI != SourceBlock->end(); ++BI)
206 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
207 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
208 BI->setOperand(i, Remapped);
210 // Next we check to see if any of the successors of DestBlock had PHI nodes.
211 // If so, we need to add entries to the PHI nodes for SourceBlock now.
212 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
214 BasicBlock *Succ = *SI;
215 for (BasicBlock::iterator PNI = Succ->begin();
216 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
217 // Ok, we have a PHI node. Figure out what the incoming value was for the
219 Value *IV = PN->getIncomingValueForBlock(DestBlock);
221 // Remap the value if necessary...
222 if (Value *MappedIV = ValueMapping[IV])
224 PN->addIncoming(IV, SourceBlock);
228 // Next, remove the old branch instruction, and any PHI node entries that we
230 BI = Branch; ++BI; // Get an iterator to the first new instruction
231 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
232 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
234 // Final step: now that we have finished everything up, walk the cloned
235 // instructions one last time, constant propagating and DCE'ing them, because
236 // they may not be needed anymore.
239 while (BI != SourceBlock->end())
240 if (!dceInstruction(BI) && !doConstantPropagation(BI))
243 ++NumEliminated; // We just killed a branch!