Make MergeBlockIntoPredecessor more aggressive when the same successor appears
[oota-llvm.git] / lib / Transforms / Utils / BasicBlockUtils.cpp
1 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This family of functions perform manipulations on basic blocks, and
11 // instructions contained within basic blocks.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Constant.h"
19 #include "llvm/Type.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include <algorithm>
24 using namespace llvm;
25
26 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
27 /// if possible.  The return value indicates success or failure.
28 bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
29   pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
30   // Can't merge the entry block.
31   if (pred_begin(BB) == pred_end(BB)) return false;
32   
33   BasicBlock *PredBB = *PI++;
34   for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
35     if (*PI != PredBB) {
36       PredBB = 0;       // There are multiple different predecessors...
37       break;
38     }
39   
40   // Can't merge if there are multiple predecessors.
41   if (!PredBB) return false;
42   
43   succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
44   BasicBlock* OnlySucc = BB;
45   for (; SI != SE; ++SI)
46     if (*SI != OnlySucc) {
47       OnlySucc = 0;     // There are multiple distinct successors!
48       break;
49     }
50   
51   // Can't merge if there are multiple successors.
52   if (!OnlySucc) return false;
53   
54   // Begin by getting rid of unneeded PHIs.
55   while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
56     PN->replaceAllUsesWith(PN->getIncomingValue(0));
57     BB->getInstList().pop_front();  // Delete the phi node...
58   }
59   
60   // Delete the unconditional branch from the predecessor...
61   PredBB->getInstList().pop_back();
62   
63   // Move all definitions in the successor to the predecessor...
64   PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
65   
66   // Make all PHI nodes that referred to BB now refer to Pred as their
67   // source...
68   BB->replaceAllUsesWith(PredBB);
69   
70   // Inherit predecessors name if it exists.
71   if (!PredBB->hasName())
72     PredBB->takeName(BB);
73   
74   // Finally, erase the old block and update dominator info.
75   if (P) {
76     if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
77       DomTreeNode* DTN = DT->getNode(BB);
78       DomTreeNode* PredDTN = DT->getNode(PredBB);
79   
80       if (DTN) {
81         SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
82         for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
83              DE = Children.end(); DI != DE; ++DI)
84           DT->changeImmediateDominator(*DI, PredDTN);
85
86         DT->eraseNode(BB);
87       }
88     }
89   }
90   
91   BB->eraseFromParent();
92   
93   
94   return true;
95 }
96
97 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
98 /// with a value, then remove and delete the original instruction.
99 ///
100 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
101                                 BasicBlock::iterator &BI, Value *V) {
102   Instruction &I = *BI;
103   // Replaces all of the uses of the instruction with uses of the value
104   I.replaceAllUsesWith(V);
105
106   // Make sure to propagate a name if there is one already.
107   if (I.hasName() && !V->hasName())
108     V->takeName(&I);
109
110   // Delete the unnecessary instruction now...
111   BI = BIL.erase(BI);
112 }
113
114
115 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
116 /// instruction specified by I.  The original instruction is deleted and BI is
117 /// updated to point to the new instruction.
118 ///
119 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
120                                BasicBlock::iterator &BI, Instruction *I) {
121   assert(I->getParent() == 0 &&
122          "ReplaceInstWithInst: Instruction already inserted into basic block!");
123
124   // Insert the new instruction into the basic block...
125   BasicBlock::iterator New = BIL.insert(BI, I);
126
127   // Replace all uses of the old instruction, and delete it.
128   ReplaceInstWithValue(BIL, BI, I);
129
130   // Move BI back to point to the newly inserted instruction
131   BI = New;
132 }
133
134 /// ReplaceInstWithInst - Replace the instruction specified by From with the
135 /// instruction specified by To.
136 ///
137 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
138   BasicBlock::iterator BI(From);
139   ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
140 }
141
142 /// RemoveSuccessor - Change the specified terminator instruction such that its
143 /// successor SuccNum no longer exists.  Because this reduces the outgoing
144 /// degree of the current basic block, the actual terminator instruction itself
145 /// may have to be changed.  In the case where the last successor of the block 
146 /// is deleted, a return instruction is inserted in its place which can cause a
147 /// surprising change in program behavior if it is not expected.
148 ///
149 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
150   assert(SuccNum < TI->getNumSuccessors() &&
151          "Trying to remove a nonexistant successor!");
152
153   // If our old successor block contains any PHI nodes, remove the entry in the
154   // PHI nodes that comes from this branch...
155   //
156   BasicBlock *BB = TI->getParent();
157   TI->getSuccessor(SuccNum)->removePredecessor(BB);
158
159   TerminatorInst *NewTI = 0;
160   switch (TI->getOpcode()) {
161   case Instruction::Br:
162     // If this is a conditional branch... convert to unconditional branch.
163     if (TI->getNumSuccessors() == 2) {
164       cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
165     } else {                    // Otherwise convert to a return instruction...
166       Value *RetVal = 0;
167
168       // Create a value to return... if the function doesn't return null...
169       if (BB->getParent()->getReturnType() != Type::VoidTy)
170         RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
171
172       // Create the return...
173       NewTI = ReturnInst::Create(RetVal);
174     }
175     break;
176
177   case Instruction::Invoke:    // Should convert to call
178   case Instruction::Switch:    // Should remove entry
179   default:
180   case Instruction::Ret:       // Cannot happen, has no successors!
181     assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
182     abort();
183   }
184
185   if (NewTI)   // If it's a different instruction, replace.
186     ReplaceInstWithInst(TI, NewTI);
187 }
188
189 /// SplitEdge -  Split the edge connecting specified block. Pass P must 
190 /// not be NULL. 
191 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
192   TerminatorInst *LatchTerm = BB->getTerminator();
193   unsigned SuccNum = 0;
194   for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
195     assert(i != e && "Didn't find edge?");
196     if (LatchTerm->getSuccessor(i) == Succ) {
197       SuccNum = i;
198       break;
199     }
200   }
201   
202   // If this is a critical edge, let SplitCriticalEdge do it.
203   if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
204     return LatchTerm->getSuccessor(SuccNum);
205
206   // If the edge isn't critical, then BB has a single successor or Succ has a
207   // single pred.  Split the block.
208   BasicBlock::iterator SplitPoint;
209   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
210     // If the successor only has a single pred, split the top of the successor
211     // block.
212     assert(SP == BB && "CFG broken");
213     return SplitBlock(Succ, Succ->begin(), P);
214   } else {
215     // Otherwise, if BB has a single successor, split it at the bottom of the
216     // block.
217     assert(BB->getTerminator()->getNumSuccessors() == 1 &&
218            "Should have a single succ!"); 
219     return SplitBlock(BB, BB->getTerminator(), P);
220   }
221 }
222
223 /// SplitBlock - Split the specified block at the specified instruction - every
224 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
225 /// to a new block.  The two blocks are joined by an unconditional branch and
226 /// the loop info is updated.
227 ///
228 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
229
230   LoopInfo &LI = P->getAnalysis<LoopInfo>();
231   BasicBlock::iterator SplitIt = SplitPt;
232   while (isa<PHINode>(SplitIt))
233     ++SplitIt;
234   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
235
236   // The new block lives in whichever loop the old one did.
237   if (Loop *L = LI.getLoopFor(Old))
238     L->addBasicBlockToLoop(New, LI.getBase());
239
240   if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>()) 
241     {
242       // Old dominates New. New node domiantes all other nodes dominated by Old.
243       DomTreeNode *OldNode = DT->getNode(Old);
244       std::vector<DomTreeNode *> Children;
245       for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
246            I != E; ++I) 
247         Children.push_back(*I);
248
249       DomTreeNode *NewNode =   DT->addNewBlock(New,Old);
250
251       for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
252              E = Children.end(); I != E; ++I) 
253         DT->changeImmediateDominator(*I, NewNode);
254     }
255
256   if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
257     DF->splitBlock(Old);
258     
259   return New;
260 }
261
262
263 /// SplitBlockPredecessors - This method transforms BB by introducing a new
264 /// basic block into the function, and moving some of the predecessors of BB to
265 /// be predecessors of the new block.  The new predecessors are indicated by the
266 /// Preds array, which has NumPreds elements in it.  The new block is given a
267 /// suffix of 'Suffix'.
268 ///
269 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
270 /// DominanceFrontier, but no other analyses.
271 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 
272                                          BasicBlock *const *Preds,
273                                          unsigned NumPreds, const char *Suffix,
274                                          Pass *P) {
275   // Create new basic block, insert right before the original block.
276   BasicBlock *NewBB =
277     BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
278   
279   // The new block unconditionally branches to the old block.
280   BranchInst *BI = BranchInst::Create(BB, NewBB);
281   
282   // Move the edges from Preds to point to NewBB instead of BB.
283   for (unsigned i = 0; i != NumPreds; ++i)
284     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
285   
286   // Update dominator tree and dominator frontier if available.
287   DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
288   if (DT)
289     DT->splitBlock(NewBB);
290   if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
291     DF->splitBlock(NewBB);
292   AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
293   
294   
295   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
296   // node becomes an incoming value for BB's phi node.  However, if the Preds
297   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
298   // account for the newly created predecessor.
299   if (NumPreds == 0) {
300     // Insert dummy values as the incoming value.
301     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
302       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
303     return NewBB;
304   }
305   
306   // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
307   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
308     PHINode *PN = cast<PHINode>(I++);
309     
310     // Check to see if all of the values coming in are the same.  If so, we
311     // don't need to create a new PHI node.
312     Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
313     for (unsigned i = 1; i != NumPreds; ++i)
314       if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
315         InVal = 0;
316         break;
317       }
318     
319     if (InVal) {
320       // If all incoming values for the new PHI would be the same, just don't
321       // make a new PHI.  Instead, just remove the incoming values from the old
322       // PHI.
323       for (unsigned i = 0; i != NumPreds; ++i)
324         PN->removeIncomingValue(Preds[i], false);
325     } else {
326       // If the values coming into the block are not the same, we need a PHI.
327       // Create the new PHI node, insert it into NewBB at the end of the block
328       PHINode *NewPHI =
329         PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
330       if (AA) AA->copyValue(PN, NewPHI);
331       
332       // Move all of the PHI values for 'Preds' to the new PHI.
333       for (unsigned i = 0; i != NumPreds; ++i) {
334         Value *V = PN->removeIncomingValue(Preds[i], false);
335         NewPHI->addIncoming(V, Preds[i]);
336       }
337       InVal = NewPHI;
338     }
339     
340     // Add an incoming value to the PHI node in the loop for the preheader
341     // edge.
342     PN->addIncoming(InVal, NewBB);
343     
344     // Check to see if we can eliminate this phi node.
345     if (Value *V = PN->hasConstantValue(DT != 0)) {
346       Instruction *I = dyn_cast<Instruction>(V);
347       if (!I || DT == 0 || DT->dominates(I, PN)) {
348         PN->replaceAllUsesWith(V);
349         if (AA) AA->deleteValue(PN);
350         PN->eraseFromParent();
351       }
352     }
353   }
354   
355   return NewBB;
356 }