blob: d889422992b3104a8d302b41210eef33ae7f6162 [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4d1e46e2002-05-07 18:07:59 +00009//
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"
Misha Brukman47b14a42004-07-29 17:30:56 +000017#include "llvm/Instructions.h"
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000018#include "llvm/Constant.h"
19#include "llvm/Type.h"
Chris Lattner54b9c3b2008-04-21 01:28:02 +000020#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel80198932007-07-06 21:39:20 +000021#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/Dominators.h"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000023#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000024using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000025
Owen Andersonb31b06d2008-07-17 00:01:40 +000026/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
27/// if possible. The return value indicates success or failure.
28bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
Owen Anderson11f2ec82008-07-17 19:42:29 +000029 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Owen Andersonb31b06d2008-07-17 00:01:40 +000030 // Can't merge the entry block.
31 if (pred_begin(BB) == pred_end(BB)) return false;
Owen Andersonb31b06d2008-07-17 00:01:40 +000032
Owen Anderson11f2ec82008-07-17 19:42:29 +000033 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 }
Owen Andersonb31b06d2008-07-17 00:01:40 +000039
Owen Anderson11f2ec82008-07-17 19:42:29 +000040 // 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;
Owen Andersonb31b06d2008-07-17 00:01:40 +000053
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
Owen Anderson11f2ec82008-07-17 19:42:29 +000070 // Inherit predecessors name if it exists.
71 if (!PredBB->hasName())
72 PredBB->takeName(BB);
73
Owen Andersonb31b06d2008-07-17 00:01:40 +000074 // 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
Chris Lattner0f67dd62005-04-21 16:04:49 +000097/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
98/// with a value, then remove and delete the original instruction.
99///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000100void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
101 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000102 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000103 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000104 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000105
Chris Lattner86cc4232007-02-11 01:37:51 +0000106 // Make sure to propagate a name if there is one already.
107 if (I.hasName() && !V->hasName())
108 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000109
Misha Brukman5560c9d2003-08-18 14:43:39 +0000110 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000111 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000112}
113
114
Chris Lattner0f67dd62005-04-21 16:04:49 +0000115/// 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///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000119void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
120 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000121 assert(I->getParent() == 0 &&
122 "ReplaceInstWithInst: Instruction already inserted into basic block!");
123
124 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000125 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000126
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
Chris Lattner18961502002-06-25 16:12:52 +0000131 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000132}
133
Chris Lattner0f67dd62005-04-21 16:04:49 +0000134/// ReplaceInstWithInst - Replace the instruction specified by From with the
135/// instruction specified by To.
136///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000137void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000138 BasicBlock::iterator BI(From);
139 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000140}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000141
Chris Lattner0f67dd62005-04-21 16:04:49 +0000142/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000143/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000144/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000145/// 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
Chris Lattner0f67dd62005-04-21 16:04:49 +0000147/// surprising change in program behavior if it is not expected.
148///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000149void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000150 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;
Misha Brukmanfd939082005-04-21 23:48:37 +0000167
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000168 // 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...
Gabor Greif051a9502008-04-06 20:25:17 +0000173 NewTI = ReturnInst::Create(RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000174 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000175 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000176
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}
Brian Gaeked0fde302003-11-11 22:41:34 +0000188
Devang Patel80198932007-07-06 21:39:20 +0000189/// SplitEdge - Split the edge connecting specified block. Pass P must
190/// not be NULL.
191BasicBlock *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///
228BasicBlock *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))
Owen Andersond735ee82007-11-27 03:43:35 +0000238 L->addBasicBlockToLoop(New, LI.getBase());
Devang Patel80198932007-07-06 21:39:20 +0000239
Devang Patela8a8a362007-07-19 02:29:24 +0000240 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 }
Devang Patel80198932007-07-06 21:39:20 +0000255
256 if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
257 DF->splitBlock(Old);
258
259 return New;
260}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000261
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.
271BasicBlock *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.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000283 for (unsigned i = 0; i != NumPreds; ++i)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000284 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000285
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}