BasicBlockUtils.cpp revision 0f8b53f19d29013ab18f3d444cea1e6305405611
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/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 <algorithm>
26using namespace llvm;
27
28/// DeleteDeadBlock - Delete the specified block, which must have no
29/// predecessors.
30void llvm::DeleteDeadBlock(BasicBlock *BB) {
31  assert((pred_begin(BB) == pred_end(BB) ||
32         // Can delete self loop.
33         BB->getSinglePredecessor() == BB) && "Block is not dead!");
34  TerminatorInst *BBTerm = BB->getTerminator();
35
36  // Loop through all of our successors and make sure they know that one
37  // of their predecessors is going away.
38  for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
39    BBTerm->getSuccessor(i)->removePredecessor(BB);
40
41  // Zap all the instructions in the block.
42  while (!BB->empty()) {
43    Instruction &I = BB->back();
44    // If this instruction is used, replace uses with an arbitrary value.
45    // Because control flow can't get here, we don't care what we replace the
46    // value with.  Note that since this block is unreachable, and all values
47    // contained within it must dominate their uses, that all uses will
48    // eventually be removed (they are themselves dead).
49    if (!I.use_empty())
50      I.replaceAllUsesWith(UndefValue::get(I.getType()));
51    BB->getInstList().pop_back();
52  }
53
54  // Zap the block!
55  BB->eraseFromParent();
56}
57
58/// FoldSingleEntryPHINodes - We know that BB has one predecessor.  If there are
59/// any single-entry PHI nodes in it, fold them away.  This handles the case
60/// when all entries to the PHI nodes in a block are guaranteed equal, such as
61/// when the block has exactly one predecessor.
62void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
63  if (!isa<PHINode>(BB->begin()))
64    return;
65
66  while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
67    if (PN->getIncomingValue(0) != PN)
68      PN->replaceAllUsesWith(PN->getIncomingValue(0));
69    else
70      PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
71    PN->eraseFromParent();
72  }
73}
74
75
76/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
77/// if possible.  The return value indicates success or failure.
78bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
79  pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
80  // Can't merge the entry block.
81  if (pred_begin(BB) == pred_end(BB)) return false;
82
83  BasicBlock *PredBB = *PI++;
84  for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
85    if (*PI != PredBB) {
86      PredBB = 0;       // There are multiple different predecessors...
87      break;
88    }
89
90  // Can't merge if there are multiple predecessors.
91  if (!PredBB) return false;
92  // Don't break self-loops.
93  if (PredBB == BB) return false;
94  // Don't break invokes.
95  if (isa<InvokeInst>(PredBB->getTerminator())) return false;
96
97  succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
98  BasicBlock* OnlySucc = BB;
99  for (; SI != SE; ++SI)
100    if (*SI != OnlySucc) {
101      OnlySucc = 0;     // There are multiple distinct successors!
102      break;
103    }
104
105  // Can't merge if there are multiple successors.
106  if (!OnlySucc) return false;
107
108  // Can't merge if there is PHI loop.
109  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
110    if (PHINode *PN = dyn_cast<PHINode>(BI)) {
111      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
112        if (PN->getIncomingValue(i) == PN)
113          return false;
114    } else
115      break;
116  }
117
118  // Begin by getting rid of unneeded PHIs.
119  while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
120    PN->replaceAllUsesWith(PN->getIncomingValue(0));
121    BB->getInstList().pop_front();  // Delete the phi node...
122  }
123
124  // Delete the unconditional branch from the predecessor...
125  PredBB->getInstList().pop_back();
126
127  // Move all definitions in the successor to the predecessor...
128  PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
129
130  // Make all PHI nodes that referred to BB now refer to Pred as their
131  // source...
132  BB->replaceAllUsesWith(PredBB);
133
134  // Inherit predecessors name if it exists.
135  if (!PredBB->hasName())
136    PredBB->takeName(BB);
137
138  // Finally, erase the old block and update dominator info.
139  if (P) {
140    if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
141      DomTreeNode* DTN = DT->getNode(BB);
142      DomTreeNode* PredDTN = DT->getNode(PredBB);
143
144      if (DTN) {
145        SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
146        for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
147             DE = Children.end(); DI != DE; ++DI)
148          DT->changeImmediateDominator(*DI, PredDTN);
149
150        DT->eraseNode(BB);
151      }
152    }
153  }
154
155  BB->eraseFromParent();
156
157
158  return true;
159}
160
161/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
162/// with a value, then remove and delete the original instruction.
163///
164void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
165                                BasicBlock::iterator &BI, Value *V) {
166  Instruction &I = *BI;
167  // Replaces all of the uses of the instruction with uses of the value
168  I.replaceAllUsesWith(V);
169
170  // Make sure to propagate a name if there is one already.
171  if (I.hasName() && !V->hasName())
172    V->takeName(&I);
173
174  // Delete the unnecessary instruction now...
175  BI = BIL.erase(BI);
176}
177
178
179/// ReplaceInstWithInst - Replace the instruction specified by BI with the
180/// instruction specified by I.  The original instruction is deleted and BI is
181/// updated to point to the new instruction.
182///
183void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
184                               BasicBlock::iterator &BI, Instruction *I) {
185  assert(I->getParent() == 0 &&
186         "ReplaceInstWithInst: Instruction already inserted into basic block!");
187
188  // Insert the new instruction into the basic block...
189  BasicBlock::iterator New = BIL.insert(BI, I);
190
191  // Replace all uses of the old instruction, and delete it.
192  ReplaceInstWithValue(BIL, BI, I);
193
194  // Move BI back to point to the newly inserted instruction
195  BI = New;
196}
197
198/// ReplaceInstWithInst - Replace the instruction specified by From with the
199/// instruction specified by To.
200///
201void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
202  BasicBlock::iterator BI(From);
203  ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
204}
205
206/// RemoveSuccessor - Change the specified terminator instruction such that its
207/// successor SuccNum no longer exists.  Because this reduces the outgoing
208/// degree of the current basic block, the actual terminator instruction itself
209/// may have to be changed.  In the case where the last successor of the block
210/// is deleted, a return instruction is inserted in its place which can cause a
211/// surprising change in program behavior if it is not expected.
212///
213void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
214  assert(SuccNum < TI->getNumSuccessors() &&
215         "Trying to remove a nonexistant successor!");
216
217  // If our old successor block contains any PHI nodes, remove the entry in the
218  // PHI nodes that comes from this branch...
219  //
220  BasicBlock *BB = TI->getParent();
221  TI->getSuccessor(SuccNum)->removePredecessor(BB);
222
223  TerminatorInst *NewTI = 0;
224  switch (TI->getOpcode()) {
225  case Instruction::Br:
226    // If this is a conditional branch... convert to unconditional branch.
227    if (TI->getNumSuccessors() == 2) {
228      cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
229    } else {                    // Otherwise convert to a return instruction...
230      Value *RetVal = 0;
231
232      // Create a value to return... if the function doesn't return null...
233      if (BB->getParent()->getReturnType() != Type::VoidTy)
234        RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
235
236      // Create the return...
237      NewTI = ReturnInst::Create(RetVal);
238    }
239    break;
240
241  case Instruction::Invoke:    // Should convert to call
242  case Instruction::Switch:    // Should remove entry
243  default:
244  case Instruction::Ret:       // Cannot happen, has no successors!
245    assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
246    abort();
247  }
248
249  if (NewTI)   // If it's a different instruction, replace.
250    ReplaceInstWithInst(TI, NewTI);
251}
252
253/// SplitEdge -  Split the edge connecting specified block. Pass P must
254/// not be NULL.
255BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
256  TerminatorInst *LatchTerm = BB->getTerminator();
257  unsigned SuccNum = 0;
258#ifndef NDEBUG
259  unsigned e = LatchTerm->getNumSuccessors();
260#endif
261  for (unsigned i = 0; ; ++i) {
262    assert(i != e && "Didn't find edge?");
263    if (LatchTerm->getSuccessor(i) == Succ) {
264      SuccNum = i;
265      break;
266    }
267  }
268
269  // If this is a critical edge, let SplitCriticalEdge do it.
270  if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
271    return LatchTerm->getSuccessor(SuccNum);
272
273  // If the edge isn't critical, then BB has a single successor or Succ has a
274  // single pred.  Split the block.
275  BasicBlock::iterator SplitPoint;
276  if (BasicBlock *SP = Succ->getSinglePredecessor()) {
277    // If the successor only has a single pred, split the top of the successor
278    // block.
279    assert(SP == BB && "CFG broken");
280    SP = NULL;
281    return SplitBlock(Succ, Succ->begin(), P);
282  } else {
283    // Otherwise, if BB has a single successor, split it at the bottom of the
284    // block.
285    assert(BB->getTerminator()->getNumSuccessors() == 1 &&
286           "Should have a single succ!");
287    return SplitBlock(BB, BB->getTerminator(), P);
288  }
289}
290
291/// SplitBlock - Split the specified block at the specified instruction - every
292/// thing before SplitPt stays in Old and everything starting with SplitPt moves
293/// to a new block.  The two blocks are joined by an unconditional branch and
294/// the loop info is updated.
295///
296BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
297  BasicBlock::iterator SplitIt = SplitPt;
298  while (isa<PHINode>(SplitIt))
299    ++SplitIt;
300  BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
301
302  // The new block lives in whichever loop the old one did.
303  if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
304    if (Loop *L = LI->getLoopFor(Old))
305      L->addBasicBlockToLoop(New, LI->getBase());
306
307  if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
308    {
309      // Old dominates New. New node domiantes all other nodes dominated by Old.
310      DomTreeNode *OldNode = DT->getNode(Old);
311      std::vector<DomTreeNode *> Children;
312      for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
313           I != E; ++I)
314        Children.push_back(*I);
315
316      DomTreeNode *NewNode =   DT->addNewBlock(New,Old);
317
318      for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
319             E = Children.end(); I != E; ++I)
320        DT->changeImmediateDominator(*I, NewNode);
321    }
322
323  if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
324    DF->splitBlock(Old);
325
326  return New;
327}
328
329
330/// SplitBlockPredecessors - This method transforms BB by introducing a new
331/// basic block into the function, and moving some of the predecessors of BB to
332/// be predecessors of the new block.  The new predecessors are indicated by the
333/// Preds array, which has NumPreds elements in it.  The new block is given a
334/// suffix of 'Suffix'.
335///
336/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
337/// DominanceFrontier, but no other analyses.
338BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
339                                         BasicBlock *const *Preds,
340                                         unsigned NumPreds, const char *Suffix,
341                                         Pass *P) {
342  // Create new basic block, insert right before the original block.
343  BasicBlock *NewBB =
344    BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
345
346  // The new block unconditionally branches to the old block.
347  BranchInst *BI = BranchInst::Create(BB, NewBB);
348
349  // Move the edges from Preds to point to NewBB instead of BB.
350  for (unsigned i = 0; i != NumPreds; ++i)
351    Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
352
353  // Update dominator tree and dominator frontier if available.
354  DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
355  if (DT)
356    DT->splitBlock(NewBB);
357  if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
358    DF->splitBlock(NewBB);
359  AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
360
361
362  // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
363  // node becomes an incoming value for BB's phi node.  However, if the Preds
364  // list is empty, we need to insert dummy entries into the PHI nodes in BB to
365  // account for the newly created predecessor.
366  if (NumPreds == 0) {
367    // Insert dummy values as the incoming value.
368    for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
369      cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
370    return NewBB;
371  }
372
373  // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
374  for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
375    PHINode *PN = cast<PHINode>(I++);
376
377    // Check to see if all of the values coming in are the same.  If so, we
378    // don't need to create a new PHI node.
379    Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
380    for (unsigned i = 1; i != NumPreds; ++i)
381      if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
382        InVal = 0;
383        break;
384      }
385
386    if (InVal) {
387      // If all incoming values for the new PHI would be the same, just don't
388      // make a new PHI.  Instead, just remove the incoming values from the old
389      // PHI.
390      for (unsigned i = 0; i != NumPreds; ++i)
391        PN->removeIncomingValue(Preds[i], false);
392    } else {
393      // If the values coming into the block are not the same, we need a PHI.
394      // Create the new PHI node, insert it into NewBB at the end of the block
395      PHINode *NewPHI =
396        PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
397      if (AA) AA->copyValue(PN, NewPHI);
398
399      // Move all of the PHI values for 'Preds' to the new PHI.
400      for (unsigned i = 0; i != NumPreds; ++i) {
401        Value *V = PN->removeIncomingValue(Preds[i], false);
402        NewPHI->addIncoming(V, Preds[i]);
403      }
404      InVal = NewPHI;
405    }
406
407    // Add an incoming value to the PHI node in the loop for the preheader
408    // edge.
409    PN->addIncoming(InVal, NewBB);
410
411    // Check to see if we can eliminate this phi node.
412    if (Value *V = PN->hasConstantValue(DT != 0)) {
413      Instruction *I = dyn_cast<Instruction>(V);
414      if (!I || DT == 0 || DT->dominates(I, PN)) {
415        PN->replaceAllUsesWith(V);
416        if (AA) AA->deleteValue(PN);
417        PN->eraseFromParent();
418      }
419    }
420  }
421
422  return NewBB;
423}
424
425/// AreEquivalentAddressValues - Test if A and B will obviously have the same
426/// value. This includes recognizing that %t0 and %t1 will have the same
427/// value in code like this:
428///   %t0 = getelementptr \@a, 0, 3
429///   store i32 0, i32* %t0
430///   %t1 = getelementptr \@a, 0, 3
431///   %t2 = load i32* %t1
432///
433static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
434  // Test if the values are trivially equivalent.
435  if (A == B) return true;
436
437  // Test if the values come form identical arithmetic instructions.
438  if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
439      isa<PHINode>(A) || isa<GetElementPtrInst>(A))
440    if (const Instruction *BI = dyn_cast<Instruction>(B))
441      if (cast<Instruction>(A)->isIdenticalTo(BI))
442        return true;
443
444  // Otherwise they may not be equivalent.
445  return false;
446}
447
448/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
449/// instruction before ScanFrom) checking to see if we have the value at the
450/// memory address *Ptr locally available within a small number of instructions.
451/// If the value is available, return it.
452///
453/// If not, return the iterator for the last validated instruction that the
454/// value would be live through.  If we scanned the entire block and didn't find
455/// something that invalidates *Ptr or provides it, ScanFrom would be left at
456/// begin() and this returns null.  ScanFrom could also be left
457///
458/// MaxInstsToScan specifies the maximum instructions to scan in the block.  If
459/// it is set to 0, it will scan the whole block. You can also optionally
460/// specify an alias analysis implementation, which makes this more precise.
461Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
462                                      BasicBlock::iterator &ScanFrom,
463                                      unsigned MaxInstsToScan,
464                                      AliasAnalysis *AA) {
465  if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
466
467  // If we're using alias analysis to disambiguate get the size of *Ptr.
468  unsigned AccessSize = 0;
469  if (AA) {
470    const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
471    AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
472  }
473
474  while (ScanFrom != ScanBB->begin()) {
475    // We must ignore debug info directives when counting (otherwise they
476    // would affect codegen).
477    Instruction *Inst = --ScanFrom;
478    if (isa<DbgInfoIntrinsic>(Inst))
479      continue;
480    // Restore ScanFrom to expected value in case next test succeeds
481    ScanFrom++;
482
483    // Don't scan huge blocks.
484    if (MaxInstsToScan-- == 0) return 0;
485
486    --ScanFrom;
487    // If this is a load of Ptr, the loaded value is available.
488    if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
489      if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
490        return LI;
491
492    if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
493      // If this is a store through Ptr, the value is available!
494      if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
495        return SI->getOperand(0);
496
497      // If Ptr is an alloca and this is a store to a different alloca, ignore
498      // the store.  This is a trivial form of alias analysis that is important
499      // for reg2mem'd code.
500      if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
501          (isa<AllocaInst>(SI->getOperand(1)) ||
502           isa<GlobalVariable>(SI->getOperand(1))))
503        continue;
504
505      // If we have alias analysis and it says the store won't modify the loaded
506      // value, ignore the store.
507      if (AA &&
508          (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
509        continue;
510
511      // Otherwise the store that may or may not alias the pointer, bail out.
512      ++ScanFrom;
513      return 0;
514    }
515
516    // If this is some other instruction that may clobber Ptr, bail out.
517    if (Inst->mayWriteToMemory()) {
518      // If alias analysis claims that it really won't modify the load,
519      // ignore it.
520      if (AA &&
521          (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
522        continue;
523
524      // May modify the pointer, bail out.
525      ++ScanFrom;
526      return 0;
527    }
528  }
529
530  // Got to the start of the block, we didn't find it, but are done for this
531  // block.
532  return 0;
533}
534
535/// CopyPrecedingStopPoint - If I is immediately preceded by a StopPoint,
536/// make a copy of the stoppoint before InsertPos (presumably before copying
537/// or moving I).
538void llvm::CopyPrecedingStopPoint(Instruction *I,
539                                  BasicBlock::iterator InsertPos) {
540  if (I != I->getParent()->begin()) {
541    BasicBlock::iterator BBI = I;  --BBI;
542    if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BBI)) {
543      DbgStopPointInst *newDSPI =
544        reinterpret_cast<DbgStopPointInst*>(DSPI->clone());
545      newDSPI->insertBefore(InsertPos);
546    }
547  }
548}
549