1 //===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
3 // This pass performs a limited form of tail duplication, intended to simplify
4 // CFGs by removing some unconditional branches. This pass is necessary to
5 // straighten out loops created by the C front-end, but also is capable of
6 // making other code nicer. After this pass is run, the CFG simplify pass
7 // should be run to clean up the mess.
9 // This pass could be enhanced in the future to use profile information to be
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/Function.h"
16 #include "llvm/iPHINode.h"
17 #include "llvm/iTerminators.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Type.h"
20 #include "llvm/Support/CFG.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "Support/Statistic.h"
25 Statistic<> NumEliminated("tailduplicate",
26 "Number of unconditional branches eliminated");
27 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
29 class TailDup : public FunctionPass {
30 bool runOnFunction(Function &F);
32 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
33 inline void eliminateUnconditionalBranch(BranchInst *BI);
34 inline void InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
35 BasicBlock *NewBlock);
36 inline Value *GetValueInBlock(BasicBlock *BB, Value *OrigVal,
37 std::map<BasicBlock*, Value*> &ValueMap,
38 std::map<BasicBlock*, Value*> &OutValueMap);
39 inline Value *GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
40 std::map<BasicBlock*, Value*> &ValueMap,
41 std::map<BasicBlock*, Value*> &OutValueMap);
43 RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
46 Pass *createTailDuplicationPass() { return new TailDup(); }
48 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
49 /// the function, eliminating it if it looks attractive enough.
51 bool TailDup::runOnFunction(Function &F) {
53 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
54 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
55 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
63 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
64 /// attractive to eliminate. We eliminate the branch if the destination basic
65 /// block has <= 5 instructions in it, not counting PHI nodes. In practice,
66 /// since one of these is a terminator instruction, this means that we will add
67 /// up to 4 instructions to the new block.
69 /// We don't count PHI nodes in the count since they will be removed when the
70 /// contents of the block are copied over.
72 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
73 BranchInst *BI = dyn_cast<BranchInst>(TI);
74 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
76 BasicBlock *Dest = BI->getSuccessor(0);
77 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
79 // Do not inline a block if we will just get another branch to the same block!
80 if (BranchInst *DBI = dyn_cast<BranchInst>(Dest->getTerminator()))
81 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
82 return false; // Do not loop infinitely!
84 // Do not bother working on dead blocks...
85 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
86 if (PI == PE && Dest != Dest->getParent()->begin())
87 return false; // It's just a dead block, ignore it...
89 // Also, do not bother with blocks with only a single predecessor: simplify
90 // CFG will fold these two blocks together!
92 if (PI == PE) return false; // Exactly one predecessor!
94 BasicBlock::iterator I = Dest->begin();
95 while (isa<PHINode>(*I)) ++I;
97 for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
98 if (Size == 6) return false; // The block is too large...
103 /// eliminateUnconditionalBranch - Clone the instructions from the destination
104 /// block into the source block, eliminating the specified unconditional branch.
105 /// If the destination block defines values used by successors of the dest
106 /// block, we may need to insert PHI nodes.
108 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
109 BasicBlock *SourceBlock = Branch->getParent();
110 BasicBlock *DestBlock = Branch->getSuccessor(0);
111 assert(SourceBlock != DestBlock && "Our predicate is broken!");
113 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
114 << "]: Eliminating branch: " << *Branch);
116 // We are going to have to map operands from the original block B to the new
117 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
118 // nodes also define part of this mapping. Loop over these PHI nodes, adding
119 // them to our mapping.
121 std::map<Value*, Value*> ValueMapping;
123 BasicBlock::iterator BI = DestBlock->begin();
124 bool HadPHINodes = isa<PHINode>(BI);
125 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
126 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
128 // Clone the non-phi instructions of the dest block into the source block,
129 // keeping track of the mapping...
131 for (; BI != DestBlock->end(); ++BI) {
132 Instruction *New = BI->clone();
133 New->setName(BI->getName());
134 SourceBlock->getInstList().push_back(New);
135 ValueMapping[BI] = New;
138 // Now that we have built the mapping information and cloned all of the
139 // instructions (giving us a new terminator, among other things), walk the new
140 // instructions, rewriting references of old instructions to use new
143 BI = Branch; ++BI; // Get an iterator to the first new instruction
144 for (; BI != SourceBlock->end(); ++BI)
145 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
146 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
147 BI->setOperand(i, Remapped);
149 // Next we check to see if any of the successors of DestBlock had PHI nodes.
150 // If so, we need to add entries to the PHI nodes for SourceBlock now.
151 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
153 BasicBlock *Succ = *SI;
154 for (BasicBlock::iterator PNI = Succ->begin();
155 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
156 // Ok, we have a PHI node. Figure out what the incoming value was for the
158 Value *IV = PN->getIncomingValueForBlock(DestBlock);
160 // Remap the value if necessary...
161 if (Value *MappedIV = ValueMapping[IV])
163 PN->addIncoming(IV, SourceBlock);
167 // Now that all of the instructions are correctly copied into the SourceBlock,
168 // we have one more minor problem: the successors of the original DestBB may
169 // use the values computed in DestBB either directly (if DestBB dominated the
170 // block), or through a PHI node. In either case, we need to insert PHI nodes
171 // into any successors of DestBB (which are now our successors) for each value
172 // that is computed in DestBB, but is used outside of it. All of these uses
173 // we have to rewrite with the new PHI node.
175 if (succ_begin(SourceBlock) != succ_end(SourceBlock)) // Avoid wasting time...
176 for (BI = DestBlock->begin(); BI != DestBlock->end(); ++BI)
177 if (BI->getType() != Type::VoidTy)
178 InsertPHINodesIfNecessary(BI, ValueMapping[BI], SourceBlock);
180 // Final step: now that we have finished everything up, walk the cloned
181 // instructions one last time, constant propagating and DCE'ing them, because
182 // they may not be needed anymore.
184 BI = Branch; ++BI; // Get an iterator to the first new instruction
186 while (BI != SourceBlock->end())
187 if (!dceInstruction(BI) && !doConstantPropagation(BI))
190 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
191 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
193 ++NumEliminated; // We just killed a branch!
196 /// InsertPHINodesIfNecessary - So at this point, we cloned the OrigInst
197 /// instruction into the NewBlock with the value of NewInst. If OrigInst was
198 /// used outside of its defining basic block, we need to insert a PHI nodes into
201 void TailDup::InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
202 BasicBlock *NewBlock) {
203 // Loop over all of the uses of OrigInst, rewriting them to be newly inserted
204 // PHI nodes, unless they are in the same basic block as OrigInst.
205 BasicBlock *OrigBlock = OrigInst->getParent();
206 std::vector<Instruction*> Users;
207 Users.reserve(OrigInst->use_size());
208 for (Value::use_iterator I = OrigInst->use_begin(), E = OrigInst->use_end();
210 Instruction *In = cast<Instruction>(*I);
211 if (In->getParent() != OrigBlock || // Don't modify uses in the orig block!
216 // The common case is that the instruction is only used within the block that
217 // defines it. If we have this case, quick exit.
219 if (Users.empty()) return;
221 // Otherwise, we have a more complex case, handle it now. This requires the
222 // construction of a mapping between a basic block and the value to use when
223 // in the scope of that basic block. This map will map to the original and
224 // new values when in the original or new block, but will map to inserted PHI
225 // nodes when in other blocks.
227 std::map<BasicBlock*, Value*> ValueMap;
228 std::map<BasicBlock*, Value*> OutValueMap; // The outgoing value map
229 OutValueMap[OrigBlock] = OrigInst;
230 OutValueMap[NewBlock ] = NewInst; // Seed the initial values...
232 DEBUG(std::cerr << " ** Inserting PHI nodes for " << OrigInst);
233 while (!Users.empty()) {
234 Instruction *User = Users.back(); Users.pop_back();
236 if (PHINode *PN = dyn_cast<PHINode>(User)) {
237 // PHI nodes must be handled specially here, because their operands are
238 // actually defined in predecessor basic blocks, NOT in the block that the
239 // PHI node lives in. Note that we have already added entries to PHI nods
240 // which are in blocks that are immediate successors of OrigBlock, so
241 // don't modify them again.
242 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
243 if (PN->getIncomingValue(i) == OrigInst &&
244 PN->getIncomingBlock(i) != OrigBlock) {
245 Value *V = GetValueOutBlock(PN->getIncomingBlock(i), OrigInst,
246 ValueMap, OutValueMap);
247 PN->setIncomingValue(i, V);
251 // Any other user of the instruction can just replace any uses with the
252 // new value defined in the block it resides in.
253 Value *V = GetValueInBlock(User->getParent(), OrigInst, ValueMap,
255 User->replaceUsesOfWith(OrigInst, V);
260 /// GetValueInBlock - This is a recursive method which inserts PHI nodes into
261 /// the function until there is a value available in basic block BB.
263 Value *TailDup::GetValueInBlock(BasicBlock *BB, Value *OrigVal,
264 std::map<BasicBlock*, Value*> &ValueMap,
265 std::map<BasicBlock*, Value*> &OutValueMap) {
266 Value*& BBVal = ValueMap[BB];
267 if (BBVal) return BBVal; // Value already computed for this block?
269 assert(pred_begin(BB) != pred_end(BB) &&
270 "Propagating PHI nodes to unreachable blocks?");
272 // If there is no value already available in this basic block, we need to
273 // either reuse a value from an incoming, dominating, basic block, or we need
274 // to create a new PHI node to merge in different incoming values. Because we
275 // don't know if we're part of a loop at this point or not, we create a PHI
276 // node, even if we will ultimately eliminate it.
277 PHINode *PN = new PHINode(OrigVal->getType(), OrigVal->getName()+".pn",
279 BBVal = PN; // Insert this into the BBVal slot in case of cycles...
281 Value*& BBOutVal = OutValueMap[BB];
282 if (BBOutVal == 0) BBOutVal = PN;
284 // Now that we have created the PHI node, loop over all of the predecessors of
285 // this block, computing an incoming value for the predecessor.
286 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
287 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
288 PN->addIncoming(GetValueOutBlock(Preds[i], OrigVal, ValueMap, OutValueMap),
291 // The PHI node is complete. In many cases, however the PHI node was
292 // ultimately unnecessary: we could have just reused a dominating incoming
293 // value. If this is the case, nuke the PHI node and replace the map entry
294 // with the dominating value.
296 assert(PN->getNumIncomingValues() > 0 && "No predecessors?");
298 // Check to see if all of the elements in the PHI node are either the PHI node
299 // itself or ONE particular value.
301 Value *ReplVal = PN->getIncomingValue(i);
302 for (; ReplVal == PN && i != PN->getNumIncomingValues(); ++i)
303 ReplVal = PN->getIncomingValue(i); // Skip values equal to the PN
305 for (; i != PN->getNumIncomingValues(); ++i)
306 if (PN->getIncomingValue(i) != PN && PN->getIncomingValue(i) != ReplVal) {
311 // Found a value to replace the PHI node with?
312 if (ReplVal && ReplVal != PN) {
313 PN->replaceAllUsesWith(ReplVal);
315 if (BBOutVal == PN) BBOutVal = ReplVal;
316 BB->getInstList().erase(PN); // Erase the PHI node...
324 Value *TailDup::GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
325 std::map<BasicBlock*, Value*> &ValueMap,
326 std::map<BasicBlock*, Value*> &OutValueMap) {
327 Value*& BBVal = OutValueMap[BB];
328 if (BBVal) return BBVal; // Value already computed for this block?
330 return BBVal = GetValueInBlock(BB, OrigVal, ValueMap, OutValueMap);