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/Constant.h"
16 #include "llvm/Function.h"
17 #include "llvm/iPHINode.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Type.h"
21 #include "llvm/Support/CFG.h"
22 #include "llvm/Support/ValueHolder.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "Support/Debug.h"
25 #include "Support/Statistic.h"
28 Statistic<> NumEliminated("tailduplicate",
29 "Number of unconditional branches eliminated");
30 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
32 class TailDup : public FunctionPass {
33 bool runOnFunction(Function &F);
35 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
36 inline void eliminateUnconditionalBranch(BranchInst *BI);
37 inline void InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
38 BasicBlock *NewBlock);
39 inline Value *GetValueInBlock(BasicBlock *BB, Value *OrigVal,
40 std::map<BasicBlock*, ValueHolder> &ValueMap,
41 std::map<BasicBlock*, ValueHolder> &OutValueMap);
42 inline Value *GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
43 std::map<BasicBlock*, ValueHolder> &ValueMap,
44 std::map<BasicBlock*, ValueHolder> &OutValueMap);
46 RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
49 Pass *createTailDuplicationPass() { return new TailDup(); }
51 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
52 /// the function, eliminating it if it looks attractive enough.
54 bool TailDup::runOnFunction(Function &F) {
56 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
57 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
58 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
66 /// shouldEliminateUnconditionalBranch - Return true if this branch looks
67 /// attractive to eliminate. We eliminate the branch if the destination basic
68 /// block has <= 5 instructions in it, not counting PHI nodes. In practice,
69 /// since one of these is a terminator instruction, this means that we will add
70 /// up to 4 instructions to the new block.
72 /// We don't count PHI nodes in the count since they will be removed when the
73 /// contents of the block are copied over.
75 bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
76 BranchInst *BI = dyn_cast<BranchInst>(TI);
77 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
79 BasicBlock *Dest = BI->getSuccessor(0);
80 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
82 // Do not inline a block if we will just get another branch to the same block!
83 if (BranchInst *DBI = dyn_cast<BranchInst>(Dest->getTerminator()))
84 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
85 return false; // Do not loop infinitely!
87 // Do not bother working on dead blocks...
88 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
89 if (PI == PE && Dest != Dest->getParent()->begin())
90 return false; // It's just a dead block, ignore it...
92 // Also, do not bother with blocks with only a single predecessor: simplify
93 // CFG will fold these two blocks together!
95 if (PI == PE) return false; // Exactly one predecessor!
97 BasicBlock::iterator I = Dest->begin();
98 while (isa<PHINode>(*I)) ++I;
100 for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
101 if (Size == 6) return false; // The block is too large...
106 /// eliminateUnconditionalBranch - Clone the instructions from the destination
107 /// block into the source block, eliminating the specified unconditional branch.
108 /// If the destination block defines values used by successors of the dest
109 /// block, we may need to insert PHI nodes.
111 void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
112 BasicBlock *SourceBlock = Branch->getParent();
113 BasicBlock *DestBlock = Branch->getSuccessor(0);
114 assert(SourceBlock != DestBlock && "Our predicate is broken!");
116 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
117 << "]: Eliminating branch: " << *Branch);
119 // We are going to have to map operands from the original block B to the new
120 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
121 // nodes also define part of this mapping. Loop over these PHI nodes, adding
122 // them to our mapping.
124 std::map<Value*, Value*> ValueMapping;
126 BasicBlock::iterator BI = DestBlock->begin();
127 bool HadPHINodes = isa<PHINode>(BI);
128 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
129 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
131 // Clone the non-phi instructions of the dest block into the source block,
132 // keeping track of the mapping...
134 for (; BI != DestBlock->end(); ++BI) {
135 Instruction *New = BI->clone();
136 New->setName(BI->getName());
137 SourceBlock->getInstList().push_back(New);
138 ValueMapping[BI] = New;
141 // Now that we have built the mapping information and cloned all of the
142 // instructions (giving us a new terminator, among other things), walk the new
143 // instructions, rewriting references of old instructions to use new
146 BI = Branch; ++BI; // Get an iterator to the first new instruction
147 for (; BI != SourceBlock->end(); ++BI)
148 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
149 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
150 BI->setOperand(i, Remapped);
152 // Next we check to see if any of the successors of DestBlock had PHI nodes.
153 // If so, we need to add entries to the PHI nodes for SourceBlock now.
154 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
156 BasicBlock *Succ = *SI;
157 for (BasicBlock::iterator PNI = Succ->begin();
158 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
159 // Ok, we have a PHI node. Figure out what the incoming value was for the
161 Value *IV = PN->getIncomingValueForBlock(DestBlock);
163 // Remap the value if necessary...
164 if (Value *MappedIV = ValueMapping[IV])
166 PN->addIncoming(IV, SourceBlock);
170 // Now that all of the instructions are correctly copied into the SourceBlock,
171 // we have one more minor problem: the successors of the original DestBB may
172 // use the values computed in DestBB either directly (if DestBB dominated the
173 // block), or through a PHI node. In either case, we need to insert PHI nodes
174 // into any successors of DestBB (which are now our successors) for each value
175 // that is computed in DestBB, but is used outside of it. All of these uses
176 // we have to rewrite with the new PHI node.
178 if (succ_begin(SourceBlock) != succ_end(SourceBlock)) // Avoid wasting time...
179 for (BI = DestBlock->begin(); BI != DestBlock->end(); ++BI)
180 if (BI->getType() != Type::VoidTy)
181 InsertPHINodesIfNecessary(BI, ValueMapping[BI], SourceBlock);
183 // Final step: now that we have finished everything up, walk the cloned
184 // instructions one last time, constant propagating and DCE'ing them, because
185 // they may not be needed anymore.
187 BI = Branch; ++BI; // Get an iterator to the first new instruction
189 while (BI != SourceBlock->end())
190 if (!dceInstruction(BI) && !doConstantPropagation(BI))
193 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
194 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
196 ++NumEliminated; // We just killed a branch!
199 /// InsertPHINodesIfNecessary - So at this point, we cloned the OrigInst
200 /// instruction into the NewBlock with the value of NewInst. If OrigInst was
201 /// used outside of its defining basic block, we need to insert a PHI nodes into
204 void TailDup::InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
205 BasicBlock *NewBlock) {
206 // Loop over all of the uses of OrigInst, rewriting them to be newly inserted
207 // PHI nodes, unless they are in the same basic block as OrigInst.
208 BasicBlock *OrigBlock = OrigInst->getParent();
209 std::vector<Instruction*> Users;
210 Users.reserve(OrigInst->use_size());
211 for (Value::use_iterator I = OrigInst->use_begin(), E = OrigInst->use_end();
213 Instruction *In = cast<Instruction>(*I);
214 if (In->getParent() != OrigBlock || // Don't modify uses in the orig block!
219 // The common case is that the instruction is only used within the block that
220 // defines it. If we have this case, quick exit.
222 if (Users.empty()) return;
224 // Otherwise, we have a more complex case, handle it now. This requires the
225 // construction of a mapping between a basic block and the value to use when
226 // in the scope of that basic block. This map will map to the original and
227 // new values when in the original or new block, but will map to inserted PHI
228 // nodes when in other blocks.
230 std::map<BasicBlock*, ValueHolder> ValueMap;
231 std::map<BasicBlock*, ValueHolder> OutValueMap; // The outgoing value map
232 OutValueMap[OrigBlock] = OrigInst;
233 OutValueMap[NewBlock ] = NewInst; // Seed the initial values...
235 DEBUG(std::cerr << " ** Inserting PHI nodes for " << OrigInst);
236 while (!Users.empty()) {
237 Instruction *User = Users.back(); Users.pop_back();
239 if (PHINode *PN = dyn_cast<PHINode>(User)) {
240 // PHI nodes must be handled specially here, because their operands are
241 // actually defined in predecessor basic blocks, NOT in the block that the
242 // PHI node lives in. Note that we have already added entries to PHI nods
243 // which are in blocks that are immediate successors of OrigBlock, so
244 // don't modify them again.
245 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
246 if (PN->getIncomingValue(i) == OrigInst &&
247 PN->getIncomingBlock(i) != OrigBlock) {
248 Value *V = GetValueOutBlock(PN->getIncomingBlock(i), OrigInst,
249 ValueMap, OutValueMap);
250 PN->setIncomingValue(i, V);
254 // Any other user of the instruction can just replace any uses with the
255 // new value defined in the block it resides in.
256 Value *V = GetValueInBlock(User->getParent(), OrigInst, ValueMap,
258 User->replaceUsesOfWith(OrigInst, V);
263 /// GetValueInBlock - This is a recursive method which inserts PHI nodes into
264 /// the function until there is a value available in basic block BB.
266 Value *TailDup::GetValueInBlock(BasicBlock *BB, Value *OrigVal,
267 std::map<BasicBlock*, ValueHolder> &ValueMap,
268 std::map<BasicBlock*,ValueHolder> &OutValueMap){
269 ValueHolder &BBVal = ValueMap[BB];
270 if (BBVal) return BBVal; // Value already computed for this block?
272 // If this block has no predecessors, then it must be unreachable, thus, it
273 // doesn't matter which value we use.
274 if (pred_begin(BB) == pred_end(BB))
275 return BBVal = Constant::getNullValue(OrigVal->getType());
277 // If there is no value already available in this basic block, we need to
278 // either reuse a value from an incoming, dominating, basic block, or we need
279 // to create a new PHI node to merge in different incoming values. Because we
280 // don't know if we're part of a loop at this point or not, we create a PHI
281 // node, even if we will ultimately eliminate it.
282 PHINode *PN = new PHINode(OrigVal->getType(), OrigVal->getName()+".pn",
284 BBVal = PN; // Insert this into the BBVal slot in case of cycles...
286 ValueHolder &BBOutVal = OutValueMap[BB];
287 if (BBOutVal == 0) BBOutVal = PN;
289 // Now that we have created the PHI node, loop over all of the predecessors of
290 // this block, computing an incoming value for the predecessor.
291 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
292 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
293 PN->addIncoming(GetValueOutBlock(Preds[i], OrigVal, ValueMap, OutValueMap),
296 // The PHI node is complete. In many cases, however the PHI node was
297 // ultimately unnecessary: we could have just reused a dominating incoming
298 // value. If this is the case, nuke the PHI node and replace the map entry
299 // with the dominating value.
301 assert(PN->getNumIncomingValues() > 0 && "No predecessors?");
303 // Check to see if all of the elements in the PHI node are either the PHI node
304 // itself or ONE particular value.
306 Value *ReplVal = PN->getIncomingValue(i);
307 for (; ReplVal == PN && i != PN->getNumIncomingValues(); ++i)
308 ReplVal = PN->getIncomingValue(i); // Skip values equal to the PN
310 for (; i != PN->getNumIncomingValues(); ++i)
311 if (PN->getIncomingValue(i) != PN && PN->getIncomingValue(i) != ReplVal) {
316 // Found a value to replace the PHI node with?
317 if (ReplVal && ReplVal != PN) {
318 PN->replaceAllUsesWith(ReplVal);
319 BB->getInstList().erase(PN); // Erase the PHI node...
327 Value *TailDup::GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
328 std::map<BasicBlock*, ValueHolder> &ValueMap,
329 std::map<BasicBlock*, ValueHolder> &OutValueMap) {
330 ValueHolder &BBVal = OutValueMap[BB];
331 if (BBVal) return BBVal; // Value already computed for this block?
333 return GetValueInBlock(BB, OrigVal, ValueMap, OutValueMap);