blob: dccc3e6ffb35c6dcac1dd3513bdf19b44953db1e [file] [log] [blame]
Chris Lattner7a7bef42003-06-22 20:10:28 +00001//===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner7a7bef42003-06-22 20:10:28 +00009//
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.
15//
16// This pass could be enhanced in the future to use profile information to be
17// more aggressive.
18//
19//===----------------------------------------------------------------------===//
20
Chris Lattner75144372006-09-27 04:58:23 +000021#define DEBUG_TYPE "tailduplicate"
Chris Lattner7a7bef42003-06-22 20:10:28 +000022#include "llvm/Transforms/Scalar.h"
Chris Lattner3186d272003-08-31 21:17:44 +000023#include "llvm/Constant.h"
Chris Lattner7a7bef42003-06-22 20:10:28 +000024#include "llvm/Function.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000025#include "llvm/Instructions.h"
Chris Lattnerb9df9b42004-11-22 17:23:57 +000026#include "llvm/IntrinsicInst.h"
Chris Lattner7a7bef42003-06-22 20:10:28 +000027#include "llvm/Pass.h"
28#include "llvm/Type.h"
29#include "llvm/Support/CFG.h"
Chris Lattner15678532008-11-27 22:56:14 +000030#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner7a7bef42003-06-22 20:10:28 +000031#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/CommandLine.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000033#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000036#include "llvm/ADT/Statistic.h"
Dale Johannesen72997fe2008-05-13 20:06:43 +000037#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanc9235d22008-03-21 23:51:57 +000038#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000039using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000040
Chris Lattner0e5f4992006-12-19 21:40:18 +000041STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
42
Dan Gohman844731a2008-05-13 00:00:25 +000043static cl::opt<unsigned>
Evan Cheng66ae1042008-05-16 07:55:50 +000044TailDupThreshold("taildup-threshold",
45 cl::desc("Max block size to tail duplicate"),
46 cl::init(1), cl::Hidden);
Dan Gohman844731a2008-05-13 00:00:25 +000047
Chris Lattner7a7bef42003-06-22 20:10:28 +000048namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000049 class VISIBILITY_HIDDEN TailDup : public FunctionPass {
Chris Lattner7a7bef42003-06-22 20:10:28 +000050 bool runOnFunction(Function &F);
Devang Patel794fd752007-05-01 21:15:47 +000051 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000052 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000053 TailDup() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000054
Chris Lattner7a7bef42003-06-22 20:10:28 +000055 private:
Evan Cheng66ae1042008-05-16 07:55:50 +000056 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *, unsigned);
Chris Lattner7a7bef42003-06-22 20:10:28 +000057 inline void eliminateUnconditionalBranch(BranchInst *BI);
Dale Johannesen72997fe2008-05-13 20:06:43 +000058 SmallPtrSet<BasicBlock*, 4> CycleDetector;
Chris Lattner7a7bef42003-06-22 20:10:28 +000059 };
Chris Lattner7a7bef42003-06-22 20:10:28 +000060}
61
Dan Gohman844731a2008-05-13 00:00:25 +000062char TailDup::ID = 0;
63static RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
64
Brian Gaeked0fde302003-11-11 22:41:34 +000065// Public interface to the Tail Duplication pass
Chris Lattner4b501562004-09-20 04:43:15 +000066FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
Chris Lattner7a7bef42003-06-22 20:10:28 +000067
68/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
Dale Johannesen72997fe2008-05-13 20:06:43 +000069/// 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.
Chris Lattner7a7bef42003-06-22 20:10:28 +000072bool TailDup::runOnFunction(Function &F) {
73 bool Changed = false;
Dale Johannesen72997fe2008-05-13 20:06:43 +000074 CycleDetector.clear();
75 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Evan Cheng66ae1042008-05-16 07:55:50 +000076 if (shouldEliminateUnconditionalBranch(I->getTerminator(),
77 TailDupThreshold)) {
Chris Lattner7a7bef42003-06-22 20:10:28 +000078 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
79 Changed = true;
80 } else {
81 ++I;
Dale Johannesen72997fe2008-05-13 20:06:43 +000082 CycleDetector.clear();
Chris Lattner7a7bef42003-06-22 20:10:28 +000083 }
Dale Johannesen72997fe2008-05-13 20:06:43 +000084 }
Chris Lattner7a7bef42003-06-22 20:10:28 +000085 return Changed;
86}
87
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.
93///
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.
96///
Evan Cheng66ae1042008-05-16 07:55:50 +000097bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI,
98 unsigned Threshold) {
Chris Lattner7a7bef42003-06-22 20:10:28 +000099 BranchInst *BI = dyn_cast<BranchInst>(TI);
100 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
101
102 BasicBlock *Dest = BI->getSuccessor(0);
103 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
104
Chris Lattner00f185f2003-07-23 03:32:41 +0000105 // Do not inline a block if we will just get another branch to the same block!
Chris Lattner4bebf082004-03-16 19:45:22 +0000106 TerminatorInst *DTI = Dest->getTerminator();
107 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
Chris Lattner00f185f2003-07-23 03:32:41 +0000108 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
109 return false; // Do not loop infinitely!
110
Chris Lattner24ad00d2004-03-16 23:29:09 +0000111 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
112 // because doing so would require breaking critical edges. This should be
113 // fixed eventually.
114 if (!DTI->use_empty())
115 return false;
116
Devang Patel8dbd9ad2008-05-15 18:04:29 +0000117 // Do not bother with blocks with only a single predecessor: simplify
Chris Lattner7a7bef42003-06-22 20:10:28 +0000118 // CFG will fold these two blocks together!
Devang Patel8dbd9ad2008-05-15 18:04:29 +0000119 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
Chris Lattner7a7bef42003-06-22 20:10:28 +0000120 ++PI;
121 if (PI == PE) return false; // Exactly one predecessor!
122
Dan Gohman02dea8b2008-05-23 21:05:58 +0000123 BasicBlock::iterator I = Dest->getFirstNonPHI();
Chris Lattner7a7bef42003-06-22 20:10:28 +0000124
Chris Lattnerb9df9b42004-11-22 17:23:57 +0000125 for (unsigned Size = 0; I != Dest->end(); ++I) {
126 if (Size == Threshold) return false; // The block is too large.
Chris Lattner0647ebf2007-11-04 06:37:55 +0000127
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;
Evan Cheng66ae1042008-05-16 07:55:50 +0000131
132 // Allso alloca and malloc.
133 if (isa<AllocationInst>(I)) return false;
134
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;
Chris Lattner0647ebf2007-11-04 06:37:55 +0000138
Chris Lattnerb9df9b42004-11-22 17:23:57 +0000139 // Only count instructions that are not debugger intrinsics.
140 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
141 }
Chris Lattner4bebf082004-03-16 19:45:22 +0000142
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.
Chris Lattner7e54a012004-11-01 07:05:07 +0000147 unsigned NumSuccs = DTI->getNumSuccessors();
148 if (NumSuccs > 8) {
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;
154 }
Chris Lattnere99c6232006-09-07 21:30:15 +0000155
Dale Johannesen72997fe2008-05-13 20:06:43 +0000156 // If this unconditional branch is a fall-through, be careful about
Chris Lattnere99c6232006-09-07 21:30:15 +0000157 // 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:
167 // if (a)
168 // foo();
169 // if (b)
170 // foo();
171 // Cloning the 'if b' block into the end of the first foo block is messy.
Chris Lattnerdfa1af02006-09-10 18:17:58 +0000172
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.
175 DestI = Dest;
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);
180 SI != SE; ++SI)
181 if (*SI == DestSucc)
182 return false;
183 }
Chris Lattnere99c6232006-09-07 21:30:15 +0000184 }
Chris Lattner4bebf082004-03-16 19:45:22 +0000185
Dale Johannesen72997fe2008-05-13 20:06:43 +0000186 // 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))
189 return false;
190
Misha Brukmanfd939082005-04-21 23:48:37 +0000191 return true;
Chris Lattner7a7bef42003-06-22 20:10:28 +0000192}
193
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000194/// 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.
198static 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;
203
204 BasicBlock *SrcPred = *pred_begin(SrcBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000205
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000206 // 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;
212 DstOtherPred = *PI;
213 if (++PI != PE) return 0;
214 } else {
215 DstOtherPred = *PI;
216 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
217 }
218
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)
222 return SrcPred;
223
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.
230 }
231
232 // Otherwise, this is something we can't handle.
233 return 0;
234}
235
Chris Lattner7a7bef42003-06-22 20:10:28 +0000236
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.
241///
242void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
243 BasicBlock *SourceBlock = Branch->getParent();
244 BasicBlock *DestBlock = Branch->getSuccessor(0);
245 assert(SourceBlock != DestBlock && "Our predicate is broken!");
246
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000247 DEBUG(errs() << "TailDuplication[" << SourceBlock->getParent()->getName()
248 << "]: Eliminating branch: " << *Branch);
Chris Lattner7a7bef42003-06-22 20:10:28 +0000249
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000250 // See if we can avoid duplicating code by moving it up to a dominator of both
251 // blocks.
252 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000253 DEBUG(errs() << "Found shared dominator: " << DomBlock->getName() << "\n");
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000254
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.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000258 BasicBlock::iterator BBI = DestBlock->getFirstNonPHI();
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000259 while (!isa<TerminatorInst>(BBI)) {
260 Instruction *I = BBI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000261
Eli Friedman0b79a772009-07-17 04:28:42 +0000262 bool CanHoist = I->isSafeToSpeculativelyExecute() &&
263 !I->mayReadFromMemory();
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000264 if (CanHoist) {
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)) {
269 CanHoist = false;
270 break;
271 }
272 if (CanHoist) {
273 // Remove from DestBlock, move right before the term in DomBlock.
274 DestBlock->getInstList().remove(I);
275 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
Bill Wendlingb7427032006-11-26 09:46:52 +0000276 DOUT << "Hoisted: " << *I;
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000277 }
278 }
279 }
280 }
281
Chris Lattner24ad00d2004-03-16 23:29:09 +0000282 // 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
285 // stack.
286 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
Chris Lattner0cfe85b2008-04-20 22:18:22 +0000287 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.
Owen Anderson50dead02009-07-15 23:53:25 +0000290 DemoteRegToStack(*I);
Chris Lattner24ad00d2004-03-16 23:29:09 +0000291 }
292
Chris Lattner7a7bef42003-06-22 20:10:28 +0000293 // 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.
Chris Lattnerea635cd2003-06-22 20:25:27 +0000297 //
Chris Lattner7a7bef42003-06-22 20:10:28 +0000298 std::map<Value*, Value*> ValueMapping;
299
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);
304
305 // Clone the non-phi instructions of the dest block into the source block,
306 // keeping track of the mapping...
307 //
308 for (; BI != DestBlock->end(); ++BI) {
Owen Andersone922c022009-07-22 00:24:57 +0000309 Instruction *New = BI->clone(BI->getContext());
Owen Anderson6bc41e82008-04-14 17:38:21 +0000310 New->setName(BI->getName());
Chris Lattner7a7bef42003-06-22 20:10:28 +0000311 SourceBlock->getInstList().push_back(New);
312 ValueMapping[BI] = New;
313 }
314
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
318 // instructions.
319 //
320 BI = Branch; ++BI; // Get an iterator to the first new instruction
321 for (; BI != SourceBlock->end(); ++BI)
Dan Gohmanf530c922009-07-02 00:17:47 +0000322 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);
327 }
Chris Lattner7a7bef42003-06-22 20:10:28 +0000328
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);
332 SI != SE; ++SI) {
333 BasicBlock *Succ = *SI;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000334 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
335 PHINode *PN = cast<PHINode>(PNI);
Chris Lattner7a7bef42003-06-22 20:10:28 +0000336 // Ok, we have a PHI node. Figure out what the incoming value was for the
337 // DestBlock.
338 Value *IV = PN->getIncomingValueForBlock(DestBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000339
Chris Lattner7a7bef42003-06-22 20:10:28 +0000340 // Remap the value if necessary...
Dan Gohmanf530c922009-07-02 00:17:47 +0000341 std::map<Value*, Value*>::const_iterator I = ValueMapping.find(IV);
342 if (I != ValueMapping.end())
343 IV = I->second;
Chris Lattner7a7bef42003-06-22 20:10:28 +0000344 PN->addIncoming(IV, SourceBlock);
345 }
346 }
Chris Lattner24ad00d2004-03-16 23:29:09 +0000347
348 // Next, remove the old branch instruction, and any PHI node entries that we
349 // had.
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...
Chris Lattner7a7bef42003-06-22 20:10:28 +0000353
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.
357 //
Chris Lattner15678532008-11-27 22:56:14 +0000358 if (HadPHINodes) {
359 while (BI != SourceBlock->end()) {
360 Instruction *Inst = BI++;
361 if (isInstructionTriviallyDead(Inst))
362 Inst->eraseFromParent();
Owen Andersone922c022009-07-22 00:24:57 +0000363 else if (Constant *C = ConstantFoldInstruction(Inst, BI->getContext())) {
Chris Lattner15678532008-11-27 22:56:14 +0000364 Inst->replaceAllUsesWith(C);
365 Inst->eraseFromParent();
366 }
367 }
368 }
Chris Lattner7a7bef42003-06-22 20:10:28 +0000369
Chris Lattner7a7bef42003-06-22 20:10:28 +0000370 ++NumEliminated; // We just killed a branch!
371}