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"
35 Statistic<> NumEliminated("tailduplicate",
36 "Number of unconditional branches eliminated");
37 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
39 class TailDup : public FunctionPass {
40 bool runOnFunction(Function &F);
42 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
43 inline void eliminateUnconditionalBranch(BranchInst *BI);
44 inline void InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
45 BasicBlock *NewBlock);
46 inline Value *GetValueInBlock(BasicBlock *BB, Value *OrigVal,
47 std::map<BasicBlock*, ValueHolder> &ValueMap,
48 std::map<BasicBlock*, ValueHolder> &OutValueMap);
49 inline Value *GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
50 std::map<BasicBlock*, ValueHolder> &ValueMap,
51 std::map<BasicBlock*, ValueHolder> &OutValueMap);
53 RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
56 Pass *createTailDuplicationPass() { return new TailDup(); }
58 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
59 /// the function, eliminating it if it looks attractive enough.
61 bool TailDup::runOnFunction(Function &F) {
63 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
64 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
65 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
73 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
74 /// attractive to eliminate. We eliminate the branch if the destination basic
75 /// block has <= 5 instructions in it, not counting PHI nodes. In practice,
76 /// since one of these is a terminator instruction, this means that we will add
77 /// up to 4 instructions to the new block.
79 /// We don't count PHI nodes in the count since they will be removed when the
80 /// contents of the block are copied over.
82 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
83 BranchInst *BI = dyn_cast<BranchInst>(TI);
84 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
86 BasicBlock *Dest = BI->getSuccessor(0);
87 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
89 // Do not inline a block if we will just get another branch to the same block!
90 if (BranchInst *DBI = dyn_cast<BranchInst>(Dest->getTerminator()))
91 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
92 return false; // Do not loop infinitely!
94 // Do not bother working on dead blocks...
95 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
96 if (PI == PE && Dest != Dest->getParent()->begin())
97 return false; // It's just a dead block, ignore it...
99 // Also, do not bother with blocks with only a single predecessor: simplify
100 // CFG will fold these two blocks together!
102 if (PI == PE) return false; // Exactly one predecessor!
104 BasicBlock::iterator I = Dest->begin();
105 while (isa<PHINode>(*I)) ++I;
107 for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
108 if (Size == 6) return false; // The block is too large...
113 /// eliminateUnconditionalBranch - Clone the instructions from the destination
114 /// block into the source block, eliminating the specified unconditional branch.
115 /// If the destination block defines values used by successors of the dest
116 /// block, we may need to insert PHI nodes.
118 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
119 BasicBlock *SourceBlock = Branch->getParent();
120 BasicBlock *DestBlock = Branch->getSuccessor(0);
121 assert(SourceBlock != DestBlock && "Our predicate is broken!");
123 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
124 << "]: Eliminating branch: " << *Branch);
126 // We are going to have to map operands from the original block B to the new
127 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
128 // nodes also define part of this mapping. Loop over these PHI nodes, adding
129 // them to our mapping.
131 std::map<Value*, Value*> ValueMapping;
133 BasicBlock::iterator BI = DestBlock->begin();
134 bool HadPHINodes = isa<PHINode>(BI);
135 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
136 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
138 // Clone the non-phi instructions of the dest block into the source block,
139 // keeping track of the mapping...
141 for (; BI != DestBlock->end(); ++BI) {
142 Instruction *New = BI->clone();
143 New->setName(BI->getName());
144 SourceBlock->getInstList().push_back(New);
145 ValueMapping[BI] = New;
148 // Now that we have built the mapping information and cloned all of the
149 // instructions (giving us a new terminator, among other things), walk the new
150 // instructions, rewriting references of old instructions to use new
153 BI = Branch; ++BI; // Get an iterator to the first new instruction
154 for (; BI != SourceBlock->end(); ++BI)
155 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
156 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
157 BI->setOperand(i, Remapped);
159 // Next we check to see if any of the successors of DestBlock had PHI nodes.
160 // If so, we need to add entries to the PHI nodes for SourceBlock now.
161 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
163 BasicBlock *Succ = *SI;
164 for (BasicBlock::iterator PNI = Succ->begin();
165 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
166 // Ok, we have a PHI node. Figure out what the incoming value was for the
168 Value *IV = PN->getIncomingValueForBlock(DestBlock);
170 // Remap the value if necessary...
171 if (Value *MappedIV = ValueMapping[IV])
173 PN->addIncoming(IV, SourceBlock);
177 // Now that all of the instructions are correctly copied into the SourceBlock,
178 // we have one more minor problem: the successors of the original DestBB may
179 // use the values computed in DestBB either directly (if DestBB dominated the
180 // block), or through a PHI node. In either case, we need to insert PHI nodes
181 // into any successors of DestBB (which are now our successors) for each value
182 // that is computed in DestBB, but is used outside of it. All of these uses
183 // we have to rewrite with the new PHI node.
185 if (succ_begin(SourceBlock) != succ_end(SourceBlock)) // Avoid wasting time...
186 for (BI = DestBlock->begin(); BI != DestBlock->end(); ++BI)
187 if (BI->getType() != Type::VoidTy)
188 InsertPHINodesIfNecessary(BI, ValueMapping[BI], SourceBlock);
190 // Final step: now that we have finished everything up, walk the cloned
191 // instructions one last time, constant propagating and DCE'ing them, because
192 // they may not be needed anymore.
194 BI = Branch; ++BI; // Get an iterator to the first new instruction
196 while (BI != SourceBlock->end())
197 if (!dceInstruction(BI) && !doConstantPropagation(BI))
200 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
201 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
203 ++NumEliminated; // We just killed a branch!
206 /// InsertPHINodesIfNecessary - So at this point, we cloned the OrigInst
207 /// instruction into the NewBlock with the value of NewInst. If OrigInst was
208 /// used outside of its defining basic block, we need to insert a PHI nodes into
211 void TailDup::InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
212 BasicBlock *NewBlock) {
213 // Loop over all of the uses of OrigInst, rewriting them to be newly inserted
214 // PHI nodes, unless they are in the same basic block as OrigInst.
215 BasicBlock *OrigBlock = OrigInst->getParent();
216 std::vector<Instruction*> Users;
217 Users.reserve(OrigInst->use_size());
218 for (Value::use_iterator I = OrigInst->use_begin(), E = OrigInst->use_end();
220 Instruction *In = cast<Instruction>(*I);
221 if (In->getParent() != OrigBlock || // Don't modify uses in the orig block!
226 // The common case is that the instruction is only used within the block that
227 // defines it. If we have this case, quick exit.
229 if (Users.empty()) return;
231 // Otherwise, we have a more complex case, handle it now. This requires the
232 // construction of a mapping between a basic block and the value to use when
233 // in the scope of that basic block. This map will map to the original and
234 // new values when in the original or new block, but will map to inserted PHI
235 // nodes when in other blocks.
237 std::map<BasicBlock*, ValueHolder> ValueMap;
238 std::map<BasicBlock*, ValueHolder> OutValueMap; // The outgoing value map
239 OutValueMap[OrigBlock] = OrigInst;
240 OutValueMap[NewBlock ] = NewInst; // Seed the initial values...
242 DEBUG(std::cerr << " ** Inserting PHI nodes for " << OrigInst);
243 while (!Users.empty()) {
244 Instruction *User = Users.back(); Users.pop_back();
246 if (PHINode *PN = dyn_cast<PHINode>(User)) {
247 // PHI nodes must be handled specially here, because their operands are
248 // actually defined in predecessor basic blocks, NOT in the block that the
249 // PHI node lives in. Note that we have already added entries to PHI nods
250 // which are in blocks that are immediate successors of OrigBlock, so
251 // don't modify them again.
252 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
253 if (PN->getIncomingValue(i) == OrigInst &&
254 PN->getIncomingBlock(i) != OrigBlock) {
255 Value *V = GetValueOutBlock(PN->getIncomingBlock(i), OrigInst,
256 ValueMap, OutValueMap);
257 PN->setIncomingValue(i, V);
261 // Any other user of the instruction can just replace any uses with the
262 // new value defined in the block it resides in.
263 Value *V = GetValueInBlock(User->getParent(), OrigInst, ValueMap,
265 User->replaceUsesOfWith(OrigInst, V);
270 /// GetValueInBlock - This is a recursive method which inserts PHI nodes into
271 /// the function until there is a value available in basic block BB.
273 Value *TailDup::GetValueInBlock(BasicBlock *BB, Value *OrigVal,
274 std::map<BasicBlock*, ValueHolder> &ValueMap,
275 std::map<BasicBlock*,ValueHolder> &OutValueMap){
276 ValueHolder &BBVal = ValueMap[BB];
277 if (BBVal) return BBVal; // Value already computed for this block?
279 // If this block has no predecessors, then it must be unreachable, thus, it
280 // doesn't matter which value we use.
281 if (pred_begin(BB) == pred_end(BB))
282 return BBVal = Constant::getNullValue(OrigVal->getType());
284 // If there is no value already available in this basic block, we need to
285 // either reuse a value from an incoming, dominating, basic block, or we need
286 // to create a new PHI node to merge in different incoming values. Because we
287 // don't know if we're part of a loop at this point or not, we create a PHI
288 // node, even if we will ultimately eliminate it.
289 PHINode *PN = new PHINode(OrigVal->getType(), OrigVal->getName()+".pn",
291 BBVal = PN; // Insert this into the BBVal slot in case of cycles...
293 ValueHolder &BBOutVal = OutValueMap[BB];
294 if (BBOutVal == 0) BBOutVal = PN;
296 // Now that we have created the PHI node, loop over all of the predecessors of
297 // this block, computing an incoming value for the predecessor.
298 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
299 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
300 PN->addIncoming(GetValueOutBlock(Preds[i], OrigVal, ValueMap, OutValueMap),
303 // The PHI node is complete. In many cases, however the PHI node was
304 // ultimately unnecessary: we could have just reused a dominating incoming
305 // value. If this is the case, nuke the PHI node and replace the map entry
306 // with the dominating value.
308 assert(PN->getNumIncomingValues() > 0 && "No predecessors?");
310 // Check to see if all of the elements in the PHI node are either the PHI node
311 // itself or ONE particular value.
313 Value *ReplVal = PN->getIncomingValue(i);
314 for (; ReplVal == PN && i != PN->getNumIncomingValues(); ++i)
315 ReplVal = PN->getIncomingValue(i); // Skip values equal to the PN
317 for (; i != PN->getNumIncomingValues(); ++i)
318 if (PN->getIncomingValue(i) != PN && PN->getIncomingValue(i) != ReplVal) {
323 // Found a value to replace the PHI node with?
324 if (ReplVal && ReplVal != PN) {
325 PN->replaceAllUsesWith(ReplVal);
326 BB->getInstList().erase(PN); // Erase the PHI node...
334 Value *TailDup::GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
335 std::map<BasicBlock*, ValueHolder> &ValueMap,
336 std::map<BasicBlock*, ValueHolder> &OutValueMap) {
337 ValueHolder &BBVal = OutValueMap[BB];
338 if (BBVal) return BBVal; // Value already computed for this block?
340 return GetValueInBlock(BB, OrigVal, ValueMap, OutValueMap);