1 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform manipulations on basic blocks, and
11 // instructions contained within basic blocks.
13 //===----------------------------------------------------------------------===//
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 "llvm/Target/TargetData.h"
27 /// DeleteDeadBlock - Delete the specified block, which must have no
29 void llvm::DeleteDeadBlock(BasicBlock *BB) {
30 assert(pred_begin(BB) == pred_end(BB) && "Block is not dead!");
31 TerminatorInst *BBTerm = BB->getTerminator();
33 // Loop through all of our successors and make sure they know that one
34 // of their predecessors is going away.
35 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
36 BBTerm->getSuccessor(i)->removePredecessor(BB);
38 // Zap all the instructions in the block.
39 while (!BB->empty()) {
40 Instruction &I = BB->back();
41 // If this instruction is used, replace uses with an arbitrary value.
42 // Because control flow can't get here, we don't care what we replace the
43 // value with. Note that since this block is unreachable, and all values
44 // contained within it must dominate their uses, that all uses will
45 // eventually be removed (they are themselves dead).
47 I.replaceAllUsesWith(UndefValue::get(I.getType()));
48 BB->getInstList().pop_back();
52 BB->eraseFromParent();
55 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
56 /// if possible. The return value indicates success or failure.
57 bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
58 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
59 // Can't merge the entry block.
60 if (pred_begin(BB) == pred_end(BB)) return false;
62 BasicBlock *PredBB = *PI++;
63 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
65 PredBB = 0; // There are multiple different predecessors...
69 // Can't merge if there are multiple predecessors.
70 if (!PredBB) return false;
71 // Don't break self-loops.
72 if (PredBB == BB) return false;
73 // Don't break invokes.
74 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
76 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
77 BasicBlock* OnlySucc = BB;
78 for (; SI != SE; ++SI)
79 if (*SI != OnlySucc) {
80 OnlySucc = 0; // There are multiple distinct successors!
84 // Can't merge if there are multiple successors.
85 if (!OnlySucc) return false;
87 // Can't merge if there is PHI loop.
88 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
89 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
90 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
91 if (PN->getIncomingValue(i) == PN)
97 // Begin by getting rid of unneeded PHIs.
98 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
99 PN->replaceAllUsesWith(PN->getIncomingValue(0));
100 BB->getInstList().pop_front(); // Delete the phi node...
103 // Delete the unconditional branch from the predecessor...
104 PredBB->getInstList().pop_back();
106 // Move all definitions in the successor to the predecessor...
107 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
109 // Make all PHI nodes that referred to BB now refer to Pred as their
111 BB->replaceAllUsesWith(PredBB);
113 // Inherit predecessors name if it exists.
114 if (!PredBB->hasName())
115 PredBB->takeName(BB);
117 // Finally, erase the old block and update dominator info.
119 if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
120 DomTreeNode* DTN = DT->getNode(BB);
121 DomTreeNode* PredDTN = DT->getNode(PredBB);
124 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
125 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
126 DE = Children.end(); DI != DE; ++DI)
127 DT->changeImmediateDominator(*DI, PredDTN);
134 BB->eraseFromParent();
140 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
141 /// with a value, then remove and delete the original instruction.
143 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
144 BasicBlock::iterator &BI, Value *V) {
145 Instruction &I = *BI;
146 // Replaces all of the uses of the instruction with uses of the value
147 I.replaceAllUsesWith(V);
149 // Make sure to propagate a name if there is one already.
150 if (I.hasName() && !V->hasName())
153 // Delete the unnecessary instruction now...
158 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
159 /// instruction specified by I. The original instruction is deleted and BI is
160 /// updated to point to the new instruction.
162 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
163 BasicBlock::iterator &BI, Instruction *I) {
164 assert(I->getParent() == 0 &&
165 "ReplaceInstWithInst: Instruction already inserted into basic block!");
167 // Insert the new instruction into the basic block...
168 BasicBlock::iterator New = BIL.insert(BI, I);
170 // Replace all uses of the old instruction, and delete it.
171 ReplaceInstWithValue(BIL, BI, I);
173 // Move BI back to point to the newly inserted instruction
177 /// ReplaceInstWithInst - Replace the instruction specified by From with the
178 /// instruction specified by To.
180 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
181 BasicBlock::iterator BI(From);
182 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
185 /// RemoveSuccessor - Change the specified terminator instruction such that its
186 /// successor SuccNum no longer exists. Because this reduces the outgoing
187 /// degree of the current basic block, the actual terminator instruction itself
188 /// may have to be changed. In the case where the last successor of the block
189 /// is deleted, a return instruction is inserted in its place which can cause a
190 /// surprising change in program behavior if it is not expected.
192 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
193 assert(SuccNum < TI->getNumSuccessors() &&
194 "Trying to remove a nonexistant successor!");
196 // If our old successor block contains any PHI nodes, remove the entry in the
197 // PHI nodes that comes from this branch...
199 BasicBlock *BB = TI->getParent();
200 TI->getSuccessor(SuccNum)->removePredecessor(BB);
202 TerminatorInst *NewTI = 0;
203 switch (TI->getOpcode()) {
204 case Instruction::Br:
205 // If this is a conditional branch... convert to unconditional branch.
206 if (TI->getNumSuccessors() == 2) {
207 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
208 } else { // Otherwise convert to a return instruction...
211 // Create a value to return... if the function doesn't return null...
212 if (BB->getParent()->getReturnType() != Type::VoidTy)
213 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
215 // Create the return...
216 NewTI = ReturnInst::Create(RetVal);
220 case Instruction::Invoke: // Should convert to call
221 case Instruction::Switch: // Should remove entry
223 case Instruction::Ret: // Cannot happen, has no successors!
224 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
228 if (NewTI) // If it's a different instruction, replace.
229 ReplaceInstWithInst(TI, NewTI);
232 /// SplitEdge - Split the edge connecting specified block. Pass P must
234 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
235 TerminatorInst *LatchTerm = BB->getTerminator();
236 unsigned SuccNum = 0;
238 unsigned e = LatchTerm->getNumSuccessors();
240 for (unsigned i = 0; ; ++i) {
241 assert(i != e && "Didn't find edge?");
242 if (LatchTerm->getSuccessor(i) == Succ) {
248 // If this is a critical edge, let SplitCriticalEdge do it.
249 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
250 return LatchTerm->getSuccessor(SuccNum);
252 // If the edge isn't critical, then BB has a single successor or Succ has a
253 // single pred. Split the block.
254 BasicBlock::iterator SplitPoint;
255 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
256 // If the successor only has a single pred, split the top of the successor
258 assert(SP == BB && "CFG broken");
260 return SplitBlock(Succ, Succ->begin(), P);
262 // Otherwise, if BB has a single successor, split it at the bottom of the
264 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
265 "Should have a single succ!");
266 return SplitBlock(BB, BB->getTerminator(), P);
270 /// SplitBlock - Split the specified block at the specified instruction - every
271 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
272 /// to a new block. The two blocks are joined by an unconditional branch and
273 /// the loop info is updated.
275 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
276 BasicBlock::iterator SplitIt = SplitPt;
277 while (isa<PHINode>(SplitIt))
279 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
281 // The new block lives in whichever loop the old one did.
282 if (LoopInfo* LI = P->getAnalysisToUpdate<LoopInfo>())
283 if (Loop *L = LI->getLoopFor(Old))
284 L->addBasicBlockToLoop(New, LI->getBase());
286 if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>())
288 // Old dominates New. New node domiantes all other nodes dominated by Old.
289 DomTreeNode *OldNode = DT->getNode(Old);
290 std::vector<DomTreeNode *> Children;
291 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
293 Children.push_back(*I);
295 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
297 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
298 E = Children.end(); I != E; ++I)
299 DT->changeImmediateDominator(*I, NewNode);
302 if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
309 /// SplitBlockPredecessors - This method transforms BB by introducing a new
310 /// basic block into the function, and moving some of the predecessors of BB to
311 /// be predecessors of the new block. The new predecessors are indicated by the
312 /// Preds array, which has NumPreds elements in it. The new block is given a
313 /// suffix of 'Suffix'.
315 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
316 /// DominanceFrontier, but no other analyses.
317 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
318 BasicBlock *const *Preds,
319 unsigned NumPreds, const char *Suffix,
321 // Create new basic block, insert right before the original block.
323 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
325 // The new block unconditionally branches to the old block.
326 BranchInst *BI = BranchInst::Create(BB, NewBB);
328 // Move the edges from Preds to point to NewBB instead of BB.
329 for (unsigned i = 0; i != NumPreds; ++i)
330 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
332 // Update dominator tree and dominator frontier if available.
333 DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
335 DT->splitBlock(NewBB);
336 if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
337 DF->splitBlock(NewBB);
338 AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
341 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
342 // node becomes an incoming value for BB's phi node. However, if the Preds
343 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
344 // account for the newly created predecessor.
346 // Insert dummy values as the incoming value.
347 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
348 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
352 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
353 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
354 PHINode *PN = cast<PHINode>(I++);
356 // Check to see if all of the values coming in are the same. If so, we
357 // don't need to create a new PHI node.
358 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
359 for (unsigned i = 1; i != NumPreds; ++i)
360 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
366 // If all incoming values for the new PHI would be the same, just don't
367 // make a new PHI. Instead, just remove the incoming values from the old
369 for (unsigned i = 0; i != NumPreds; ++i)
370 PN->removeIncomingValue(Preds[i], false);
372 // If the values coming into the block are not the same, we need a PHI.
373 // Create the new PHI node, insert it into NewBB at the end of the block
375 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
376 if (AA) AA->copyValue(PN, NewPHI);
378 // Move all of the PHI values for 'Preds' to the new PHI.
379 for (unsigned i = 0; i != NumPreds; ++i) {
380 Value *V = PN->removeIncomingValue(Preds[i], false);
381 NewPHI->addIncoming(V, Preds[i]);
386 // Add an incoming value to the PHI node in the loop for the preheader
388 PN->addIncoming(InVal, NewBB);
390 // Check to see if we can eliminate this phi node.
391 if (Value *V = PN->hasConstantValue(DT != 0)) {
392 Instruction *I = dyn_cast<Instruction>(V);
393 if (!I || DT == 0 || DT->dominates(I, PN)) {
394 PN->replaceAllUsesWith(V);
395 if (AA) AA->deleteValue(PN);
396 PN->eraseFromParent();
404 /// AreEquivalentAddressValues - Test if A and B will obviously have the same
405 /// value. This includes recognizing that %t0 and %t1 will have the same
406 /// value in code like this:
407 /// %t0 = getelementptr @a, 0, 3
408 /// store i32 0, i32* %t0
409 /// %t1 = getelementptr @a, 0, 3
410 /// %t2 = load i32* %t1
412 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
413 // Test if the values are trivially equivalent.
414 if (A == B) return true;
416 // Test if the values come form identical arithmetic instructions.
417 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
418 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
419 if (const Instruction *BI = dyn_cast<Instruction>(B))
420 if (cast<Instruction>(A)->isIdenticalTo(BI))
423 // Otherwise they may not be equivalent.
427 /// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
428 /// instruction before ScanFrom) checking to see if we have the value at the
429 /// memory address *Ptr locally available within a small number of instructions.
430 /// If the value is available, return it.
432 /// If not, return the iterator for the last validated instruction that the
433 /// value would be live through. If we scanned the entire block and didn't find
434 /// something that invalidates *Ptr or provides it, ScanFrom would be left at
435 /// begin() and this returns null. ScanFrom could also be left
437 /// MaxInstsToScan specifies the maximum instructions to scan in the block. If
438 /// it is set to 0, it will scan the whole block. You can also optionally
439 /// specify an alias analysis implementation, which makes this more precise.
440 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
441 BasicBlock::iterator &ScanFrom,
442 unsigned MaxInstsToScan,
444 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
446 // If we're using alias analysis to disambiguate get the size of *Ptr.
447 unsigned AccessSize = 0;
449 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
450 AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
453 while (ScanFrom != ScanBB->begin()) {
454 // Don't scan huge blocks.
455 if (MaxInstsToScan-- == 0) return 0;
457 Instruction *Inst = --ScanFrom;
459 // If this is a load of Ptr, the loaded value is available.
460 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
461 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
464 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
465 // If this is a store through Ptr, the value is available!
466 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
467 return SI->getOperand(0);
469 // If Ptr is an alloca and this is a store to a different alloca, ignore
470 // the store. This is a trivial form of alias analysis that is important
471 // for reg2mem'd code.
472 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
473 (isa<AllocaInst>(SI->getOperand(1)) ||
474 isa<GlobalVariable>(SI->getOperand(1))))
477 // If we have alias analysis and it says the store won't modify the loaded
478 // value, ignore the store.
480 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
483 // Otherwise the store that may or may not alias the pointer, bail out.
488 // If this is some other instruction that may clobber Ptr, bail out.
489 if (Inst->mayWriteToMemory()) {
490 // If alias analysis claims that it really won't modify the load,
493 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
496 // May modify the pointer, bail out.
502 // Got to the start of the block, we didn't find it, but are done for this