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/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"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/Analysis/LoopInfo.h"
40 STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
42 static cl::opt<unsigned>
43 TailDupThreshold("taildup-threshold",
44 cl::desc("Max block size to tail duplicate"),
45 cl::init(1), cl::Hidden);
48 class VISIBILITY_HIDDEN TailDup : public FunctionPass {
49 bool runOnFunction(Function &F);
51 static char ID; // Pass identification, replacement for typeid
52 TailDup() : FunctionPass((intptr_t)&ID) {}
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
56 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *, unsigned);
57 inline void eliminateUnconditionalBranch(BranchInst *BI);
58 SmallPtrSet<BasicBlock*, 4> CycleDetector;
59 LoopInfo *LI; // The current loop information
64 static RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
66 // Public interface to the Tail Duplication pass
67 FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
69 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
70 /// the function, eliminating it if it looks attractive enough. CycleDetector
71 /// prevents infinite loops by checking that we aren't redirecting a branch to
72 /// a place it already pointed to earlier; see PR 2323.
73 bool TailDup::runOnFunction(Function &F) {
76 LI = &getAnalysis<LoopInfo>();
78 CycleDetector.clear();
79 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
80 if (shouldEliminateUnconditionalBranch(I->getTerminator(),
82 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
86 CycleDetector.clear();
92 void TailDup::getAnalysisUsage(AnalysisUsage &AU) const {
93 AU.addRequired<LoopInfo>();
96 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
97 /// attractive to eliminate. We eliminate the branch if the destination basic
98 /// block has <= 5 instructions in it, not counting PHI nodes. In practice,
99 /// since one of these is a terminator instruction, this means that we will add
100 /// up to 4 instructions to the new block.
102 /// We don't count PHI nodes in the count since they will be removed when the
103 /// contents of the block are copied over.
105 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI,
106 unsigned Threshold) {
107 BranchInst *BI = dyn_cast<BranchInst>(TI);
108 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
110 BasicBlock *Dest = BI->getSuccessor(0);
111 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
113 // Do not inline a block if we will just get another branch to the same block!
114 TerminatorInst *DTI = Dest->getTerminator();
115 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
116 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
117 return false; // Do not loop infinitely!
119 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
120 // because doing so would require breaking critical edges. This should be
122 if (!DTI->use_empty())
125 // Do not bother with blocks with only a single predecessor: simplify
126 // CFG will fold these two blocks together!
127 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
129 if (PI == PE) return false; // Exactly one predecessor!
131 BasicBlock::iterator I = Dest->getFirstNonPHI();
133 for (unsigned Size = 0; I != Dest->end(); ++I) {
134 if (Size == Threshold) return false; // The block is too large.
136 // Don't tail duplicate call instructions. They are very large compared to
137 // other instructions.
138 if (isa<CallInst>(I) || isa<InvokeInst>(I)) return false;
140 // Allso alloca and malloc.
141 if (isa<AllocationInst>(I)) return false;
143 // Some vector instructions can expand into a number of instructions.
144 if (isa<ShuffleVectorInst>(I) || isa<ExtractElementInst>(I) ||
145 isa<InsertElementInst>(I)) return false;
147 // Only count instructions that are not debugger intrinsics.
148 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
151 // Do not tail duplicate a block that has thousands of successors into a block
152 // with a single successor if the block has many other predecessors. This can
153 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
154 // cases that have a large number of indirect gotos.
155 unsigned NumSuccs = DTI->getNumSuccessors();
157 unsigned TooMany = 128;
158 if (NumSuccs >= TooMany) return false;
159 TooMany = TooMany/NumSuccs;
160 for (; PI != PE; ++PI)
161 if (TooMany-- == 0) return false;
164 // If this unconditional branch is a fall-through, be careful about
165 // tail duplicating it. In particular, we don't want to taildup it if the
166 // original block will still be there after taildup is completed: doing so
167 // would eliminate the fall-through, requiring unconditional branches.
168 Function::iterator DestI = Dest;
169 if (&*--DestI == BI->getParent()) {
170 // The uncond branch is a fall-through. Tail duplication of the block is
171 // will eliminate the fall-through-ness and end up cloning the terminator
172 // at the end of the Dest block. Since the original Dest block will
173 // continue to exist, this means that one or the other will not be able to
174 // fall through. One typical example that this helps with is code like:
179 // Cloning the 'if b' block into the end of the first foo block is messy.
181 // The messy case is when the fall-through block falls through to other
182 // blocks. This is what we would be preventing if we cloned the block.
184 if (++DestI != Dest->getParent()->end()) {
185 BasicBlock *DestSucc = DestI;
186 // If any of Dest's successors are fall-throughs, don't do this xform.
187 for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
194 // Finally, check that we haven't redirected to this target block earlier;
195 // there are cases where we loop forever if we don't check this (PR 2323).
196 if (!CycleDetector.insert(Dest))
199 // Avoid non-natural loops:
200 // If a loop header is duplicated, the former natural loop will contain two
201 // paths into the loop --> the loop it not natural anymore. We want to avoid
202 // this, because other optimizaions may fail to improve the loop because of
204 if (LI->isLoopHeader(Dest))
210 /// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
211 /// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
212 /// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
213 /// DstBlock, return it.
214 static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
215 BasicBlock *DstBlock) {
216 // SrcBlock must have a single predecessor.
217 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
218 if (PI == PE || ++PI != PE) return 0;
220 BasicBlock *SrcPred = *pred_begin(SrcBlock);
222 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
223 // there is only one other pred, get it, otherwise we can't handle it.
224 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
225 BasicBlock *DstOtherPred = 0;
226 if (*PI == SrcBlock) {
227 if (++PI == PE) return 0;
229 if (++PI != PE) return 0;
232 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
235 // We can handle two situations here: "if then" and "if then else" blocks. An
236 // 'if then' situation is just where DstOtherPred == SrcPred.
237 if (DstOtherPred == SrcPred)
240 // Check to see if we have an "if then else" situation, which means that
241 // DstOtherPred will have a single predecessor and it will be SrcPred.
242 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
243 if (PI != PE && *PI == SrcPred) {
244 if (++PI != PE) return 0; // Not a single pred.
245 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
248 // Otherwise, this is something we can't handle.
253 /// eliminateUnconditionalBranch - Clone the instructions from the destination
254 /// block into the source block, eliminating the specified unconditional branch.
255 /// If the destination block defines values used by successors of the dest
256 /// block, we may need to insert PHI nodes.
258 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
259 BasicBlock *SourceBlock = Branch->getParent();
260 BasicBlock *DestBlock = Branch->getSuccessor(0);
261 assert(SourceBlock != DestBlock && "Our predicate is broken!");
263 DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
264 << "]: Eliminating branch: " << *Branch;
266 // See if we can avoid duplicating code by moving it up to a dominator of both
268 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
269 DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
271 // If there are non-phi instructions in DestBlock that have no operands
272 // defined in DestBlock, and if the instruction has no side effects, we can
273 // move the instruction to DomBlock instead of duplicating it.
274 BasicBlock::iterator BBI = DestBlock->getFirstNonPHI();
275 while (!isa<TerminatorInst>(BBI)) {
276 Instruction *I = BBI++;
278 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
280 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
281 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
282 if (OpI->getParent() == DestBlock ||
283 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
288 // Remove from DestBlock, move right before the term in DomBlock.
289 DestBlock->getInstList().remove(I);
290 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
291 DOUT << "Hoisted: " << *I;
297 // Tail duplication can not update SSA properties correctly if the values
298 // defined in the duplicated tail are used outside of the tail itself. For
299 // this reason, we spill all values that are used outside of the tail to the
301 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
302 if (I->isUsedOutsideOfBlock(DestBlock)) {
303 // We found a use outside of the tail. Create a new stack slot to
304 // break this inter-block usage pattern.
305 DemoteRegToStack(*I);
308 // We are going to have to map operands from the original block B to the new
309 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
310 // nodes also define part of this mapping. Loop over these PHI nodes, adding
311 // them to our mapping.
313 std::map<Value*, Value*> ValueMapping;
315 BasicBlock::iterator BI = DestBlock->begin();
316 bool HadPHINodes = isa<PHINode>(BI);
317 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
318 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
320 // Clone the non-phi instructions of the dest block into the source block,
321 // keeping track of the mapping...
323 for (; BI != DestBlock->end(); ++BI) {
324 Instruction *New = BI->clone();
325 New->setName(BI->getName());
326 SourceBlock->getInstList().push_back(New);
327 ValueMapping[BI] = New;
330 // Now that we have built the mapping information and cloned all of the
331 // instructions (giving us a new terminator, among other things), walk the new
332 // instructions, rewriting references of old instructions to use new
335 BI = Branch; ++BI; // Get an iterator to the first new instruction
336 for (; BI != SourceBlock->end(); ++BI)
337 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
338 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
339 BI->setOperand(i, Remapped);
341 // Next we check to see if any of the successors of DestBlock had PHI nodes.
342 // If so, we need to add entries to the PHI nodes for SourceBlock now.
343 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
345 BasicBlock *Succ = *SI;
346 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
347 PHINode *PN = cast<PHINode>(PNI);
348 // Ok, we have a PHI node. Figure out what the incoming value was for the
350 Value *IV = PN->getIncomingValueForBlock(DestBlock);
352 // Remap the value if necessary...
353 if (Value *MappedIV = ValueMapping[IV])
355 PN->addIncoming(IV, SourceBlock);
359 // Next, remove the old branch instruction, and any PHI node entries that we
361 BI = Branch; ++BI; // Get an iterator to the first new instruction
362 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
363 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
365 // Final step: now that we have finished everything up, walk the cloned
366 // instructions one last time, constant propagating and DCE'ing them, because
367 // they may not be needed anymore.
370 while (BI != SourceBlock->end())
371 if (!dceInstruction(BI) && !doConstantPropagation(BI))
374 ++NumEliminated; // We just killed a branch!