blob: 9427fc664ad844710f6f50468417b08ebe2f384e [file] [log] [blame]
Chris Lattner7a7bef42003-06-22 20:10:28 +00001//===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
2//
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.
8//
9// This pass could be enhanced in the future to use profile information to be
10// more aggressive.
11//
12//===----------------------------------------------------------------------===//
13
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"
Chris Lattner086cb002003-08-23 20:08:30 +000021#include "llvm/Support/ValueHolder.h"
Chris Lattner7a7bef42003-06-22 20:10:28 +000022#include "llvm/Transforms/Utils/Local.h"
Chris Lattner6806f562003-08-01 22:15:03 +000023#include "Support/Debug.h"
Chris Lattner7a7bef42003-06-22 20:10:28 +000024#include "Support/Statistic.h"
25
26namespace {
27 Statistic<> NumEliminated("tailduplicate",
28 "Number of unconditional branches eliminated");
29 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
30
31 class TailDup : public FunctionPass {
32 bool runOnFunction(Function &F);
33 private:
34 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
35 inline void eliminateUnconditionalBranch(BranchInst *BI);
36 inline void InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
37 BasicBlock *NewBlock);
38 inline Value *GetValueInBlock(BasicBlock *BB, Value *OrigVal,
Chris Lattner086cb002003-08-23 20:08:30 +000039 std::map<BasicBlock*, ValueHolder> &ValueMap,
40 std::map<BasicBlock*, ValueHolder> &OutValueMap);
Chris Lattner7a7bef42003-06-22 20:10:28 +000041 inline Value *GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
Chris Lattner086cb002003-08-23 20:08:30 +000042 std::map<BasicBlock*, ValueHolder> &ValueMap,
43 std::map<BasicBlock*, ValueHolder> &OutValueMap);
Chris Lattner7a7bef42003-06-22 20:10:28 +000044 };
45 RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
46}
47
48Pass *createTailDuplicationPass() { return new TailDup(); }
49
50/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
51/// the function, eliminating it if it looks attractive enough.
52///
53bool TailDup::runOnFunction(Function &F) {
54 bool Changed = false;
55 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
56 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
57 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
58 Changed = true;
59 } else {
60 ++I;
61 }
62 return Changed;
63}
64
65/// shouldEliminateUnconditionalBranch - Return true if this branch looks
66/// attractive to eliminate. We eliminate the branch if the destination basic
67/// block has <= 5 instructions in it, not counting PHI nodes. In practice,
68/// since one of these is a terminator instruction, this means that we will add
69/// up to 4 instructions to the new block.
70///
71/// We don't count PHI nodes in the count since they will be removed when the
72/// contents of the block are copied over.
73///
74bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
75 BranchInst *BI = dyn_cast<BranchInst>(TI);
76 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
77
78 BasicBlock *Dest = BI->getSuccessor(0);
79 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
80
Chris Lattner00f185f2003-07-23 03:32:41 +000081 // Do not inline a block if we will just get another branch to the same block!
82 if (BranchInst *DBI = dyn_cast<BranchInst>(Dest->getTerminator()))
83 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
84 return false; // Do not loop infinitely!
85
Chris Lattner7a7bef42003-06-22 20:10:28 +000086 // Do not bother working on dead blocks...
87 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
88 if (PI == PE && Dest != Dest->getParent()->begin())
89 return false; // It's just a dead block, ignore it...
90
91 // Also, do not bother with blocks with only a single predecessor: simplify
92 // CFG will fold these two blocks together!
93 ++PI;
94 if (PI == PE) return false; // Exactly one predecessor!
95
96 BasicBlock::iterator I = Dest->begin();
97 while (isa<PHINode>(*I)) ++I;
98
99 for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
100 if (Size == 6) return false; // The block is too large...
101 return true;
102}
103
104
105/// eliminateUnconditionalBranch - Clone the instructions from the destination
106/// block into the source block, eliminating the specified unconditional branch.
107/// If the destination block defines values used by successors of the dest
108/// block, we may need to insert PHI nodes.
109///
110void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
111 BasicBlock *SourceBlock = Branch->getParent();
112 BasicBlock *DestBlock = Branch->getSuccessor(0);
113 assert(SourceBlock != DestBlock && "Our predicate is broken!");
114
115 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
116 << "]: Eliminating branch: " << *Branch);
117
118 // We are going to have to map operands from the original block B to the new
119 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
120 // nodes also define part of this mapping. Loop over these PHI nodes, adding
121 // them to our mapping.
Chris Lattnerea635cd2003-06-22 20:25:27 +0000122 //
Chris Lattner7a7bef42003-06-22 20:10:28 +0000123 std::map<Value*, Value*> ValueMapping;
124
125 BasicBlock::iterator BI = DestBlock->begin();
126 bool HadPHINodes = isa<PHINode>(BI);
127 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
128 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
129
130 // Clone the non-phi instructions of the dest block into the source block,
131 // keeping track of the mapping...
132 //
133 for (; BI != DestBlock->end(); ++BI) {
134 Instruction *New = BI->clone();
135 New->setName(BI->getName());
136 SourceBlock->getInstList().push_back(New);
137 ValueMapping[BI] = New;
138 }
139
140 // Now that we have built the mapping information and cloned all of the
141 // instructions (giving us a new terminator, among other things), walk the new
142 // instructions, rewriting references of old instructions to use new
143 // instructions.
144 //
145 BI = Branch; ++BI; // Get an iterator to the first new instruction
146 for (; BI != SourceBlock->end(); ++BI)
147 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
148 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
149 BI->setOperand(i, Remapped);
150
151 // Next we check to see if any of the successors of DestBlock had PHI nodes.
152 // If so, we need to add entries to the PHI nodes for SourceBlock now.
153 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
154 SI != SE; ++SI) {
155 BasicBlock *Succ = *SI;
156 for (BasicBlock::iterator PNI = Succ->begin();
157 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
158 // Ok, we have a PHI node. Figure out what the incoming value was for the
159 // DestBlock.
160 Value *IV = PN->getIncomingValueForBlock(DestBlock);
161
162 // Remap the value if necessary...
163 if (Value *MappedIV = ValueMapping[IV])
164 IV = MappedIV;
165 PN->addIncoming(IV, SourceBlock);
166 }
167 }
168
169 // Now that all of the instructions are correctly copied into the SourceBlock,
170 // we have one more minor problem: the successors of the original DestBB may
171 // use the values computed in DestBB either directly (if DestBB dominated the
172 // block), or through a PHI node. In either case, we need to insert PHI nodes
173 // into any successors of DestBB (which are now our successors) for each value
174 // that is computed in DestBB, but is used outside of it. All of these uses
175 // we have to rewrite with the new PHI node.
176 //
177 if (succ_begin(SourceBlock) != succ_end(SourceBlock)) // Avoid wasting time...
178 for (BI = DestBlock->begin(); BI != DestBlock->end(); ++BI)
179 if (BI->getType() != Type::VoidTy)
180 InsertPHINodesIfNecessary(BI, ValueMapping[BI], SourceBlock);
181
182 // Final step: now that we have finished everything up, walk the cloned
183 // instructions one last time, constant propagating and DCE'ing them, because
184 // they may not be needed anymore.
185 //
186 BI = Branch; ++BI; // Get an iterator to the first new instruction
187 if (HadPHINodes)
188 while (BI != SourceBlock->end())
189 if (!dceInstruction(BI) && !doConstantPropagation(BI))
190 ++BI;
191
192 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
193 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
194
195 ++NumEliminated; // We just killed a branch!
196}
197
198/// InsertPHINodesIfNecessary - So at this point, we cloned the OrigInst
199/// instruction into the NewBlock with the value of NewInst. If OrigInst was
200/// used outside of its defining basic block, we need to insert a PHI nodes into
201/// the successors.
202///
203void TailDup::InsertPHINodesIfNecessary(Instruction *OrigInst, Value *NewInst,
204 BasicBlock *NewBlock) {
205 // Loop over all of the uses of OrigInst, rewriting them to be newly inserted
206 // PHI nodes, unless they are in the same basic block as OrigInst.
207 BasicBlock *OrigBlock = OrigInst->getParent();
208 std::vector<Instruction*> Users;
209 Users.reserve(OrigInst->use_size());
210 for (Value::use_iterator I = OrigInst->use_begin(), E = OrigInst->use_end();
211 I != E; ++I) {
212 Instruction *In = cast<Instruction>(*I);
Chris Lattnerfcd74e22003-06-24 19:48:06 +0000213 if (In->getParent() != OrigBlock || // Don't modify uses in the orig block!
214 isa<PHINode>(In))
Chris Lattner7a7bef42003-06-22 20:10:28 +0000215 Users.push_back(In);
216 }
217
218 // The common case is that the instruction is only used within the block that
219 // defines it. If we have this case, quick exit.
220 //
221 if (Users.empty()) return;
222
223 // Otherwise, we have a more complex case, handle it now. This requires the
224 // construction of a mapping between a basic block and the value to use when
225 // in the scope of that basic block. This map will map to the original and
226 // new values when in the original or new block, but will map to inserted PHI
227 // nodes when in other blocks.
228 //
Chris Lattner086cb002003-08-23 20:08:30 +0000229 std::map<BasicBlock*, ValueHolder> ValueMap;
230 std::map<BasicBlock*, ValueHolder> OutValueMap; // The outgoing value map
Chris Lattner7a7bef42003-06-22 20:10:28 +0000231 OutValueMap[OrigBlock] = OrigInst;
232 OutValueMap[NewBlock ] = NewInst; // Seed the initial values...
233
234 DEBUG(std::cerr << " ** Inserting PHI nodes for " << OrigInst);
235 while (!Users.empty()) {
236 Instruction *User = Users.back(); Users.pop_back();
237
238 if (PHINode *PN = dyn_cast<PHINode>(User)) {
239 // PHI nodes must be handled specially here, because their operands are
240 // actually defined in predecessor basic blocks, NOT in the block that the
241 // PHI node lives in. Note that we have already added entries to PHI nods
242 // which are in blocks that are immediate successors of OrigBlock, so
243 // don't modify them again.
244 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
245 if (PN->getIncomingValue(i) == OrigInst &&
246 PN->getIncomingBlock(i) != OrigBlock) {
247 Value *V = GetValueOutBlock(PN->getIncomingBlock(i), OrigInst,
248 ValueMap, OutValueMap);
249 PN->setIncomingValue(i, V);
250 }
251
252 } else {
253 // Any other user of the instruction can just replace any uses with the
254 // new value defined in the block it resides in.
255 Value *V = GetValueInBlock(User->getParent(), OrigInst, ValueMap,
256 OutValueMap);
257 User->replaceUsesOfWith(OrigInst, V);
258 }
259 }
260}
261
262/// GetValueInBlock - This is a recursive method which inserts PHI nodes into
263/// the function until there is a value available in basic block BB.
264///
265Value *TailDup::GetValueInBlock(BasicBlock *BB, Value *OrigVal,
Chris Lattner086cb002003-08-23 20:08:30 +0000266 std::map<BasicBlock*, ValueHolder> &ValueMap,
267 std::map<BasicBlock*,ValueHolder> &OutValueMap){
268 ValueHolder &BBVal = ValueMap[BB];
Chris Lattner7a7bef42003-06-22 20:10:28 +0000269 if (BBVal) return BBVal; // Value already computed for this block?
270
271 assert(pred_begin(BB) != pred_end(BB) &&
272 "Propagating PHI nodes to unreachable blocks?");
273
274 // If there is no value already available in this basic block, we need to
275 // either reuse a value from an incoming, dominating, basic block, or we need
276 // to create a new PHI node to merge in different incoming values. Because we
277 // don't know if we're part of a loop at this point or not, we create a PHI
278 // node, even if we will ultimately eliminate it.
279 PHINode *PN = new PHINode(OrigVal->getType(), OrigVal->getName()+".pn",
280 BB->begin());
281 BBVal = PN; // Insert this into the BBVal slot in case of cycles...
282
Chris Lattner086cb002003-08-23 20:08:30 +0000283 ValueHolder &BBOutVal = OutValueMap[BB];
Chris Lattner7a7bef42003-06-22 20:10:28 +0000284 if (BBOutVal == 0) BBOutVal = PN;
285
286 // Now that we have created the PHI node, loop over all of the predecessors of
287 // this block, computing an incoming value for the predecessor.
288 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
289 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
290 PN->addIncoming(GetValueOutBlock(Preds[i], OrigVal, ValueMap, OutValueMap),
291 Preds[i]);
292
293 // The PHI node is complete. In many cases, however the PHI node was
294 // ultimately unnecessary: we could have just reused a dominating incoming
295 // value. If this is the case, nuke the PHI node and replace the map entry
296 // with the dominating value.
297 //
298 assert(PN->getNumIncomingValues() > 0 && "No predecessors?");
299
300 // Check to see if all of the elements in the PHI node are either the PHI node
301 // itself or ONE particular value.
302 unsigned i = 0;
303 Value *ReplVal = PN->getIncomingValue(i);
304 for (; ReplVal == PN && i != PN->getNumIncomingValues(); ++i)
305 ReplVal = PN->getIncomingValue(i); // Skip values equal to the PN
306
307 for (; i != PN->getNumIncomingValues(); ++i)
308 if (PN->getIncomingValue(i) != PN && PN->getIncomingValue(i) != ReplVal) {
309 ReplVal = 0;
310 break;
311 }
312
313 // Found a value to replace the PHI node with?
Chris Lattner066ab6a2003-06-22 20:46:00 +0000314 if (ReplVal && ReplVal != PN) {
Chris Lattner7a7bef42003-06-22 20:10:28 +0000315 PN->replaceAllUsesWith(ReplVal);
Chris Lattner7a7bef42003-06-22 20:10:28 +0000316 BB->getInstList().erase(PN); // Erase the PHI node...
317 } else {
318 ++NumPHINodes;
319 }
320
321 return BBVal;
322}
323
324Value *TailDup::GetValueOutBlock(BasicBlock *BB, Value *OrigVal,
Chris Lattner086cb002003-08-23 20:08:30 +0000325 std::map<BasicBlock*, ValueHolder> &ValueMap,
326 std::map<BasicBlock*, ValueHolder> &OutValueMap) {
327 ValueHolder &BBVal = OutValueMap[BB];
Chris Lattner7a7bef42003-06-22 20:10:28 +0000328 if (BBVal) return BBVal; // Value already computed for this block?
329
Chris Lattner086cb002003-08-23 20:08:30 +0000330 return GetValueInBlock(BB, OrigVal, ValueMap, OutValueMap);
Chris Lattner7a7bef42003-06-22 20:10:28 +0000331}