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/IntrinsicInst.h"
19 #include "llvm/Constant.h"
20 #include "llvm/Type.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Transforms/Utils/Local.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ValueHandle.h"
32 /// DeleteDeadBlock - Delete the specified block, which must have no
34 void llvm::DeleteDeadBlock(BasicBlock *BB) {
35 assert((pred_begin(BB) == pred_end(BB) ||
36 // Can delete self loop.
37 BB->getSinglePredecessor() == BB) && "Block is not dead!");
38 TerminatorInst *BBTerm = BB->getTerminator();
40 // Loop through all of our successors and make sure they know that one
41 // of their predecessors is going away.
42 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
43 BBTerm->getSuccessor(i)->removePredecessor(BB);
45 // Zap all the instructions in the block.
46 while (!BB->empty()) {
47 Instruction &I = BB->back();
48 // If this instruction is used, replace uses with an arbitrary value.
49 // Because control flow can't get here, we don't care what we replace the
50 // value with. Note that since this block is unreachable, and all values
51 // contained within it must dominate their uses, that all uses will
52 // eventually be removed (they are themselves dead).
54 I.replaceAllUsesWith(UndefValue::get(I.getType()));
55 BB->getInstList().pop_back();
59 BB->eraseFromParent();
62 /// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
63 /// any single-entry PHI nodes in it, fold them away. This handles the case
64 /// when all entries to the PHI nodes in a block are guaranteed equal, such as
65 /// when the block has exactly one predecessor.
66 void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
67 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
68 if (PN->getIncomingValue(0) != PN)
69 PN->replaceAllUsesWith(PN->getIncomingValue(0));
71 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
72 PN->eraseFromParent();
77 /// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
78 /// is dead. Also recursively delete any operands that become dead as
79 /// a result. This includes tracing the def-use list from the PHI to see if
80 /// it is ultimately unused or if it reaches an unused cycle.
81 bool llvm::DeleteDeadPHIs(BasicBlock *BB) {
82 // Recursively deleting a PHI may cause multiple PHIs to be deleted
83 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
84 SmallVector<WeakVH, 8> PHIs;
85 for (BasicBlock::iterator I = BB->begin();
86 PHINode *PN = dyn_cast<PHINode>(I); ++I)
90 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
91 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
92 Changed |= RecursivelyDeleteDeadPHINode(PN);
97 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
98 /// if possible. The return value indicates success or failure.
99 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
100 // Don't merge away blocks who have their address taken.
101 if (BB->hasAddressTaken()) return false;
103 // Can't merge if there are multiple predecessors, or no predecessors.
104 BasicBlock *PredBB = BB->getUniquePredecessor();
105 if (!PredBB) return false;
107 // Don't break self-loops.
108 if (PredBB == BB) return false;
109 // Don't break invokes.
110 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
112 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
113 BasicBlock* OnlySucc = BB;
114 for (; SI != SE; ++SI)
115 if (*SI != OnlySucc) {
116 OnlySucc = 0; // There are multiple distinct successors!
120 // Can't merge if there are multiple successors.
121 if (!OnlySucc) return false;
123 // Can't merge if there is PHI loop.
124 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
125 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
126 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
127 if (PN->getIncomingValue(i) == PN)
133 // Begin by getting rid of unneeded PHIs.
134 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
135 PN->replaceAllUsesWith(PN->getIncomingValue(0));
136 BB->getInstList().pop_front(); // Delete the phi node...
139 // Delete the unconditional branch from the predecessor...
140 PredBB->getInstList().pop_back();
142 // Move all definitions in the successor to the predecessor...
143 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
145 // Make all PHI nodes that referred to BB now refer to Pred as their
147 BB->replaceAllUsesWith(PredBB);
149 // Inherit predecessors name if it exists.
150 if (!PredBB->hasName())
151 PredBB->takeName(BB);
153 // Finally, erase the old block and update dominator info.
155 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
156 DomTreeNode* DTN = DT->getNode(BB);
157 DomTreeNode* PredDTN = DT->getNode(PredBB);
160 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
161 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
162 DE = Children.end(); DI != DE; ++DI)
163 DT->changeImmediateDominator(*DI, PredDTN);
170 BB->eraseFromParent();
176 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
177 /// with a value, then remove and delete the original instruction.
179 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
180 BasicBlock::iterator &BI, Value *V) {
181 Instruction &I = *BI;
182 // Replaces all of the uses of the instruction with uses of the value
183 I.replaceAllUsesWith(V);
185 // Make sure to propagate a name if there is one already.
186 if (I.hasName() && !V->hasName())
189 // Delete the unnecessary instruction now...
194 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
195 /// instruction specified by I. The original instruction is deleted and BI is
196 /// updated to point to the new instruction.
198 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
199 BasicBlock::iterator &BI, Instruction *I) {
200 assert(I->getParent() == 0 &&
201 "ReplaceInstWithInst: Instruction already inserted into basic block!");
203 // Insert the new instruction into the basic block...
204 BasicBlock::iterator New = BIL.insert(BI, I);
206 // Replace all uses of the old instruction, and delete it.
207 ReplaceInstWithValue(BIL, BI, I);
209 // Move BI back to point to the newly inserted instruction
213 /// ReplaceInstWithInst - Replace the instruction specified by From with the
214 /// instruction specified by To.
216 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
217 BasicBlock::iterator BI(From);
218 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
221 /// RemoveSuccessor - Change the specified terminator instruction such that its
222 /// successor SuccNum no longer exists. Because this reduces the outgoing
223 /// degree of the current basic block, the actual terminator instruction itself
224 /// may have to be changed. In the case where the last successor of the block
225 /// is deleted, a return instruction is inserted in its place which can cause a
226 /// surprising change in program behavior if it is not expected.
228 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
229 assert(SuccNum < TI->getNumSuccessors() &&
230 "Trying to remove a nonexistant successor!");
232 // If our old successor block contains any PHI nodes, remove the entry in the
233 // PHI nodes that comes from this branch...
235 BasicBlock *BB = TI->getParent();
236 TI->getSuccessor(SuccNum)->removePredecessor(BB);
238 TerminatorInst *NewTI = 0;
239 switch (TI->getOpcode()) {
240 case Instruction::Br:
241 // If this is a conditional branch... convert to unconditional branch.
242 if (TI->getNumSuccessors() == 2) {
243 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
244 } else { // Otherwise convert to a return instruction...
247 // Create a value to return... if the function doesn't return null...
248 if (!BB->getParent()->getReturnType()->isVoidTy())
249 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
251 // Create the return...
252 NewTI = ReturnInst::Create(TI->getContext(), RetVal);
256 case Instruction::Invoke: // Should convert to call
257 case Instruction::Switch: // Should remove entry
259 case Instruction::Ret: // Cannot happen, has no successors!
260 llvm_unreachable("Unhandled terminator inst type in RemoveSuccessor!");
263 if (NewTI) // If it's a different instruction, replace.
264 ReplaceInstWithInst(TI, NewTI);
267 /// GetSuccessorNumber - Search for the specified successor of basic block BB
268 /// and return its position in the terminator instruction's list of
269 /// successors. It is an error to call this with a block that is not a
271 unsigned llvm::GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ) {
272 TerminatorInst *Term = BB->getTerminator();
274 unsigned e = Term->getNumSuccessors();
276 for (unsigned i = 0; ; ++i) {
277 assert(i != e && "Didn't find edge?");
278 if (Term->getSuccessor(i) == Succ)
284 /// SplitEdge - Split the edge connecting specified block. Pass P must
286 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
287 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
289 // If this is a critical edge, let SplitCriticalEdge do it.
290 TerminatorInst *LatchTerm = BB->getTerminator();
291 if (SplitCriticalEdge(LatchTerm, SuccNum, P))
292 return LatchTerm->getSuccessor(SuccNum);
294 // If the edge isn't critical, then BB has a single successor or Succ has a
295 // single pred. Split the block.
296 BasicBlock::iterator SplitPoint;
297 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
298 // If the successor only has a single pred, split the top of the successor
300 assert(SP == BB && "CFG broken");
302 return SplitBlock(Succ, Succ->begin(), P);
304 // Otherwise, if BB has a single successor, split it at the bottom of the
306 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
307 "Should have a single succ!");
308 return SplitBlock(BB, BB->getTerminator(), P);
312 /// SplitBlock - Split the specified block at the specified instruction - every
313 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
314 /// to a new block. The two blocks are joined by an unconditional branch and
315 /// the loop info is updated.
317 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
318 BasicBlock::iterator SplitIt = SplitPt;
319 while (isa<PHINode>(SplitIt))
321 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
323 // The new block lives in whichever loop the old one did. This preserves
324 // LCSSA as well, because we force the split point to be after any PHI nodes.
325 if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
326 if (Loop *L = LI->getLoopFor(Old))
327 L->addBasicBlockToLoop(New, LI->getBase());
329 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) {
330 // Old dominates New. New node domiantes all other nodes dominated by Old.
331 DomTreeNode *OldNode = DT->getNode(Old);
332 std::vector<DomTreeNode *> Children;
333 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
335 Children.push_back(*I);
337 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
338 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
339 E = Children.end(); I != E; ++I)
340 DT->changeImmediateDominator(*I, NewNode);
343 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
350 /// SplitBlockPredecessors - This method transforms BB by introducing a new
351 /// basic block into the function, and moving some of the predecessors of BB to
352 /// be predecessors of the new block. The new predecessors are indicated by the
353 /// Preds array, which has NumPreds elements in it. The new block is given a
354 /// suffix of 'Suffix'.
356 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
357 /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
358 /// In particular, it does not preserve LoopSimplify (because it's
359 /// complicated to handle the case where one of the edges being split
360 /// is an exit of a loop with other exits).
362 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
363 BasicBlock *const *Preds,
364 unsigned NumPreds, const char *Suffix,
366 // Create new basic block, insert right before the original block.
367 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
368 BB->getParent(), BB);
370 // The new block unconditionally branches to the old block.
371 BranchInst *BI = BranchInst::Create(BB, NewBB);
373 LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0;
374 Loop *L = LI ? LI->getLoopFor(BB) : 0;
375 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
377 // Move the edges from Preds to point to NewBB instead of BB.
378 // While here, if we need to preserve loop analyses, collect
379 // some information about how this split will affect loops.
380 bool HasLoopExit = false;
381 bool IsLoopEntry = !!L;
382 bool SplitMakesNewLoopHeader = false;
383 for (unsigned i = 0; i != NumPreds; ++i) {
384 // This is slightly more strict than necessary; the minimum requirement
385 // is that there be no more than one indirectbr branching to BB. And
386 // all BlockAddress uses would need to be updated.
387 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
388 "Cannot split an edge from an IndirectBrInst");
390 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
393 // If we need to preserve LCSSA, determine if any of
394 // the preds is a loop exit.
396 if (Loop *PL = LI->getLoopFor(Preds[i]))
397 if (!PL->contains(BB))
399 // If we need to preserve LoopInfo, note whether any of the
400 // preds crosses an interesting loop boundary.
402 if (L->contains(Preds[i]))
405 SplitMakesNewLoopHeader = true;
410 // Update dominator tree and dominator frontier if available.
411 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
413 DT->splitBlock(NewBB);
414 if (DominanceFrontier *DF =
415 P ? P->getAnalysisIfAvailable<DominanceFrontier>() : 0)
416 DF->splitBlock(NewBB);
418 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
419 // node becomes an incoming value for BB's phi node. However, if the Preds
420 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
421 // account for the newly created predecessor.
423 // Insert dummy values as the incoming value.
424 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
425 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
429 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
433 // Add the new block to the nearest enclosing loop (and not an
434 // adjacent loop). To find this, examine each of the predecessors and
435 // determine which loops enclose them, and select the most-nested loop
436 // which contains the loop containing the block being split.
437 Loop *InnermostPredLoop = 0;
438 for (unsigned i = 0; i != NumPreds; ++i)
439 if (Loop *PredLoop = LI->getLoopFor(Preds[i])) {
440 // Seek a loop which actually contains the block being split (to
441 // avoid adjacent loops).
442 while (PredLoop && !PredLoop->contains(BB))
443 PredLoop = PredLoop->getParentLoop();
444 // Select the most-nested of these loops which contains the block.
446 PredLoop->contains(BB) &&
447 (!InnermostPredLoop ||
448 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
449 InnermostPredLoop = PredLoop;
451 if (InnermostPredLoop)
452 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
454 L->addBasicBlockToLoop(NewBB, LI->getBase());
455 if (SplitMakesNewLoopHeader)
456 L->moveToHeader(NewBB);
460 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
461 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
462 PHINode *PN = cast<PHINode>(I++);
464 // Check to see if all of the values coming in are the same. If so, we
465 // don't need to create a new PHI node, unless it's needed for LCSSA.
468 InVal = PN->getIncomingValueForBlock(Preds[0]);
469 for (unsigned i = 1; i != NumPreds; ++i)
470 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
477 // If all incoming values for the new PHI would be the same, just don't
478 // make a new PHI. Instead, just remove the incoming values from the old
480 for (unsigned i = 0; i != NumPreds; ++i)
481 PN->removeIncomingValue(Preds[i], false);
483 // If the values coming into the block are not the same, we need a PHI.
484 // Create the new PHI node, insert it into NewBB at the end of the block
486 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
487 if (AA) AA->copyValue(PN, NewPHI);
489 // Move all of the PHI values for 'Preds' to the new PHI.
490 for (unsigned i = 0; i != NumPreds; ++i) {
491 Value *V = PN->removeIncomingValue(Preds[i], false);
492 NewPHI->addIncoming(V, Preds[i]);
497 // Add an incoming value to the PHI node in the loop for the preheader
499 PN->addIncoming(InVal, NewBB);
505 /// FindFunctionBackedges - Analyze the specified function to find all of the
506 /// loop backedges in the function and return them. This is a relatively cheap
507 /// (compared to computing dominators and loop info) analysis.
509 /// The output is added to Result, as pairs of <from,to> edge info.
510 void llvm::FindFunctionBackedges(const Function &F,
511 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
512 const BasicBlock *BB = &F.getEntryBlock();
513 if (succ_begin(BB) == succ_end(BB))
516 SmallPtrSet<const BasicBlock*, 8> Visited;
517 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
518 SmallPtrSet<const BasicBlock*, 8> InStack;
521 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
524 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
525 const BasicBlock *ParentBB = Top.first;
526 succ_const_iterator &I = Top.second;
528 bool FoundNew = false;
529 while (I != succ_end(ParentBB)) {
531 if (Visited.insert(BB)) {
535 // Successor is in VisitStack, it's a back edge.
536 if (InStack.count(BB))
537 Result.push_back(std::make_pair(ParentBB, BB));
541 // Go down one level if there is a unvisited successor.
543 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
546 InStack.erase(VisitStack.pop_back_val().first);
548 } while (!VisitStack.empty());