blob: d38099f4eb14db0ffede8ea234daf687cf025048 [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 Lattneree6e10b2008-11-27 08:18:12 +000023#include "llvm/Target/TargetData.h"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000024#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Owen Andersonb31b06d2008-07-17 00:01:40 +000027/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
28/// if possible. The return value indicates success or failure.
29bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
Owen Anderson11f2ec82008-07-17 19:42:29 +000030 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Owen Andersonb31b06d2008-07-17 00:01:40 +000031 // Can't merge the entry block.
32 if (pred_begin(BB) == pred_end(BB)) return false;
Owen Andersonb31b06d2008-07-17 00:01:40 +000033
Owen Anderson11f2ec82008-07-17 19:42:29 +000034 BasicBlock *PredBB = *PI++;
35 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
36 if (*PI != PredBB) {
37 PredBB = 0; // There are multiple different predecessors...
38 break;
39 }
Owen Andersonb31b06d2008-07-17 00:01:40 +000040
Owen Anderson11f2ec82008-07-17 19:42:29 +000041 // Can't merge if there are multiple predecessors.
42 if (!PredBB) return false;
Owen Anderson3ecaf1b2008-07-18 17:46:41 +000043 // Don't break self-loops.
44 if (PredBB == BB) return false;
45 // Don't break invokes.
46 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +000047
48 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
49 BasicBlock* OnlySucc = BB;
50 for (; SI != SE; ++SI)
51 if (*SI != OnlySucc) {
52 OnlySucc = 0; // There are multiple distinct successors!
53 break;
54 }
55
56 // Can't merge if there are multiple successors.
57 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +000058
59 // Can't merge if there is PHI loop.
60 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
61 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
62 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
63 if (PN->getIncomingValue(i) == PN)
64 return false;
65 } else
66 break;
67 }
68
Owen Andersonb31b06d2008-07-17 00:01:40 +000069 // Begin by getting rid of unneeded PHIs.
70 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
71 PN->replaceAllUsesWith(PN->getIncomingValue(0));
72 BB->getInstList().pop_front(); // Delete the phi node...
73 }
74
75 // Delete the unconditional branch from the predecessor...
76 PredBB->getInstList().pop_back();
77
78 // Move all definitions in the successor to the predecessor...
79 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
80
81 // Make all PHI nodes that referred to BB now refer to Pred as their
82 // source...
83 BB->replaceAllUsesWith(PredBB);
84
Owen Anderson11f2ec82008-07-17 19:42:29 +000085 // Inherit predecessors name if it exists.
86 if (!PredBB->hasName())
87 PredBB->takeName(BB);
88
Owen Andersonb31b06d2008-07-17 00:01:40 +000089 // Finally, erase the old block and update dominator info.
90 if (P) {
91 if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
92 DomTreeNode* DTN = DT->getNode(BB);
93 DomTreeNode* PredDTN = DT->getNode(PredBB);
94
95 if (DTN) {
96 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
97 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
98 DE = Children.end(); DI != DE; ++DI)
99 DT->changeImmediateDominator(*DI, PredDTN);
100
101 DT->eraseNode(BB);
102 }
103 }
104 }
105
106 BB->eraseFromParent();
107
108
109 return true;
110}
111
Chris Lattner0f67dd62005-04-21 16:04:49 +0000112/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
113/// with a value, then remove and delete the original instruction.
114///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000115void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
116 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000117 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000118 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000119 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000120
Chris Lattner86cc4232007-02-11 01:37:51 +0000121 // Make sure to propagate a name if there is one already.
122 if (I.hasName() && !V->hasName())
123 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000124
Misha Brukman5560c9d2003-08-18 14:43:39 +0000125 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000126 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000127}
128
129
Chris Lattner0f67dd62005-04-21 16:04:49 +0000130/// ReplaceInstWithInst - Replace the instruction specified by BI with the
131/// instruction specified by I. The original instruction is deleted and BI is
132/// updated to point to the new instruction.
133///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000134void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
135 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000136 assert(I->getParent() == 0 &&
137 "ReplaceInstWithInst: Instruction already inserted into basic block!");
138
139 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000140 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000141
142 // Replace all uses of the old instruction, and delete it.
143 ReplaceInstWithValue(BIL, BI, I);
144
145 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000146 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000147}
148
Chris Lattner0f67dd62005-04-21 16:04:49 +0000149/// ReplaceInstWithInst - Replace the instruction specified by From with the
150/// instruction specified by To.
151///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000152void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000153 BasicBlock::iterator BI(From);
154 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000155}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000156
Chris Lattner0f67dd62005-04-21 16:04:49 +0000157/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000158/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000159/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000160/// may have to be changed. In the case where the last successor of the block
161/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000162/// surprising change in program behavior if it is not expected.
163///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000164void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000165 assert(SuccNum < TI->getNumSuccessors() &&
166 "Trying to remove a nonexistant successor!");
167
168 // If our old successor block contains any PHI nodes, remove the entry in the
169 // PHI nodes that comes from this branch...
170 //
171 BasicBlock *BB = TI->getParent();
172 TI->getSuccessor(SuccNum)->removePredecessor(BB);
173
174 TerminatorInst *NewTI = 0;
175 switch (TI->getOpcode()) {
176 case Instruction::Br:
177 // If this is a conditional branch... convert to unconditional branch.
178 if (TI->getNumSuccessors() == 2) {
179 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
180 } else { // Otherwise convert to a return instruction...
181 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000182
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000183 // Create a value to return... if the function doesn't return null...
184 if (BB->getParent()->getReturnType() != Type::VoidTy)
185 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
186
187 // Create the return...
Gabor Greif051a9502008-04-06 20:25:17 +0000188 NewTI = ReturnInst::Create(RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000189 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000190 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000191
192 case Instruction::Invoke: // Should convert to call
193 case Instruction::Switch: // Should remove entry
194 default:
195 case Instruction::Ret: // Cannot happen, has no successors!
196 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
197 abort();
198 }
199
200 if (NewTI) // If it's a different instruction, replace.
201 ReplaceInstWithInst(TI, NewTI);
202}
Brian Gaeked0fde302003-11-11 22:41:34 +0000203
Devang Patel80198932007-07-06 21:39:20 +0000204/// SplitEdge - Split the edge connecting specified block. Pass P must
205/// not be NULL.
206BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
207 TerminatorInst *LatchTerm = BB->getTerminator();
208 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000209#ifndef NDEBUG
210 unsigned e = LatchTerm->getNumSuccessors();
211#endif
212 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000213 assert(i != e && "Didn't find edge?");
214 if (LatchTerm->getSuccessor(i) == Succ) {
215 SuccNum = i;
216 break;
217 }
218 }
219
220 // If this is a critical edge, let SplitCriticalEdge do it.
221 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
222 return LatchTerm->getSuccessor(SuccNum);
223
224 // If the edge isn't critical, then BB has a single successor or Succ has a
225 // single pred. Split the block.
226 BasicBlock::iterator SplitPoint;
227 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
228 // If the successor only has a single pred, split the top of the successor
229 // block.
230 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000231 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000232 return SplitBlock(Succ, Succ->begin(), P);
233 } else {
234 // Otherwise, if BB has a single successor, split it at the bottom of the
235 // block.
236 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
237 "Should have a single succ!");
238 return SplitBlock(BB, BB->getTerminator(), P);
239 }
240}
241
242/// SplitBlock - Split the specified block at the specified instruction - every
243/// thing before SplitPt stays in Old and everything starting with SplitPt moves
244/// to a new block. The two blocks are joined by an unconditional branch and
245/// the loop info is updated.
246///
247BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000248 BasicBlock::iterator SplitIt = SplitPt;
249 while (isa<PHINode>(SplitIt))
250 ++SplitIt;
251 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
252
253 // The new block lives in whichever loop the old one did.
Owen Andersona90793b2008-10-03 06:55:35 +0000254 if (LoopInfo* LI = P->getAnalysisToUpdate<LoopInfo>())
255 if (Loop *L = LI->getLoopFor(Old))
256 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000257
Devang Patela8a8a362007-07-19 02:29:24 +0000258 if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>())
259 {
260 // Old dominates New. New node domiantes all other nodes dominated by Old.
261 DomTreeNode *OldNode = DT->getNode(Old);
262 std::vector<DomTreeNode *> Children;
263 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
264 I != E; ++I)
265 Children.push_back(*I);
266
267 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
268
269 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
270 E = Children.end(); I != E; ++I)
271 DT->changeImmediateDominator(*I, NewNode);
272 }
Devang Patel80198932007-07-06 21:39:20 +0000273
274 if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
275 DF->splitBlock(Old);
276
277 return New;
278}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000279
280
281/// SplitBlockPredecessors - This method transforms BB by introducing a new
282/// basic block into the function, and moving some of the predecessors of BB to
283/// be predecessors of the new block. The new predecessors are indicated by the
284/// Preds array, which has NumPreds elements in it. The new block is given a
285/// suffix of 'Suffix'.
286///
287/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
288/// DominanceFrontier, but no other analyses.
289BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
290 BasicBlock *const *Preds,
291 unsigned NumPreds, const char *Suffix,
292 Pass *P) {
293 // Create new basic block, insert right before the original block.
294 BasicBlock *NewBB =
295 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
296
297 // The new block unconditionally branches to the old block.
298 BranchInst *BI = BranchInst::Create(BB, NewBB);
299
300 // Move the edges from Preds to point to NewBB instead of BB.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000301 for (unsigned i = 0; i != NumPreds; ++i)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000302 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000303
304 // Update dominator tree and dominator frontier if available.
305 DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
306 if (DT)
307 DT->splitBlock(NewBB);
308 if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
309 DF->splitBlock(NewBB);
310 AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
311
312
313 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
314 // node becomes an incoming value for BB's phi node. However, if the Preds
315 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
316 // account for the newly created predecessor.
317 if (NumPreds == 0) {
318 // Insert dummy values as the incoming value.
319 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
320 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
321 return NewBB;
322 }
323
324 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
325 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
326 PHINode *PN = cast<PHINode>(I++);
327
328 // Check to see if all of the values coming in are the same. If so, we
329 // don't need to create a new PHI node.
330 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
331 for (unsigned i = 1; i != NumPreds; ++i)
332 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
333 InVal = 0;
334 break;
335 }
336
337 if (InVal) {
338 // If all incoming values for the new PHI would be the same, just don't
339 // make a new PHI. Instead, just remove the incoming values from the old
340 // PHI.
341 for (unsigned i = 0; i != NumPreds; ++i)
342 PN->removeIncomingValue(Preds[i], false);
343 } else {
344 // If the values coming into the block are not the same, we need a PHI.
345 // Create the new PHI node, insert it into NewBB at the end of the block
346 PHINode *NewPHI =
347 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
348 if (AA) AA->copyValue(PN, NewPHI);
349
350 // Move all of the PHI values for 'Preds' to the new PHI.
351 for (unsigned i = 0; i != NumPreds; ++i) {
352 Value *V = PN->removeIncomingValue(Preds[i], false);
353 NewPHI->addIncoming(V, Preds[i]);
354 }
355 InVal = NewPHI;
356 }
357
358 // Add an incoming value to the PHI node in the loop for the preheader
359 // edge.
360 PN->addIncoming(InVal, NewBB);
361
362 // Check to see if we can eliminate this phi node.
363 if (Value *V = PN->hasConstantValue(DT != 0)) {
364 Instruction *I = dyn_cast<Instruction>(V);
365 if (!I || DT == 0 || DT->dominates(I, PN)) {
366 PN->replaceAllUsesWith(V);
367 if (AA) AA->deleteValue(PN);
368 PN->eraseFromParent();
369 }
370 }
371 }
372
373 return NewBB;
374}
Chris Lattner52c95852008-11-27 08:10:05 +0000375
376/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
377/// instruction before ScanFrom) checking to see if we have the value at the
378/// memory address *Ptr locally available within a small number of instructions.
379/// If the value is available, return it.
380///
381/// If not, return the iterator for the last validated instruction that the
382/// value would be live through. If we scanned the entire block and didn't find
383/// something that invalidates *Ptr or provides it, ScanFrom would be left at
384/// begin() and this returns null. ScanFrom could also be left
385///
386/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
387/// it is set to 0, it will scan the whole block. You can also optionally
388/// specify an alias analysis implementation, which makes this more precise.
389Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
390 BasicBlock::iterator &ScanFrom,
391 unsigned MaxInstsToScan,
392 AliasAnalysis *AA) {
393 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000394
395 // If we're using alias analysis to disambiguate get the size of *Ptr.
396 unsigned AccessSize = 0;
397 if (AA) {
398 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
399 AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
400 }
Chris Lattner52c95852008-11-27 08:10:05 +0000401
402 while (ScanFrom != ScanBB->begin()) {
403 // Don't scan huge blocks.
404 if (MaxInstsToScan-- == 0) return 0;
405
406 Instruction *Inst = --ScanFrom;
407
408 // If this is a load of Ptr, the loaded value is available.
409 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
410 if (LI->getOperand(0) == Ptr)
411 return LI;
412
413 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
414 // If this is a store through Ptr, the value is available!
415 if (SI->getOperand(1) == Ptr)
416 return SI->getOperand(0);
417
418 // If Ptr is an alloca and this is a store to a different alloca, ignore
419 // the store. This is a trivial form of alias analysis that is important
420 // for reg2mem'd code.
421 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
422 (isa<AllocaInst>(SI->getOperand(1)) ||
423 isa<GlobalVariable>(SI->getOperand(1))))
424 continue;
425
Chris Lattneree6e10b2008-11-27 08:18:12 +0000426 // If we have alias analysis and it says the store won't modify the loaded
427 // value, ignore the store.
428 if (AA &&
429 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
430 continue;
431
Chris Lattner52c95852008-11-27 08:10:05 +0000432 // Otherwise the store that may or may not alias the pointer, bail out.
433 ++ScanFrom;
434 return 0;
435 }
436
Chris Lattner52c95852008-11-27 08:10:05 +0000437 // If this is some other instruction that may clobber Ptr, bail out.
438 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000439 // If alias analysis claims that it really won't modify the load,
440 // ignore it.
441 if (AA &&
442 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
443 continue;
444
Chris Lattner52c95852008-11-27 08:10:05 +0000445 // May modify the pointer, bail out.
446 ++ScanFrom;
447 return 0;
448 }
449 }
450
451 // Got to the start of the block, we didn't find it, but are done for this
452 // block.
453 return 0;
454}