BasicBlock.cpp revision f81b57694b3c34a79b1464ffd21e6768c8d22662
1//===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
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 file implements the BasicBlock class for the VMCore library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/BasicBlock.h"
15#include "llvm/Constants.h"
16#include "llvm/Instructions.h"
17#include "llvm/LLVMContext.h"
18#include "llvm/Type.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/Support/CFG.h"
21#include "llvm/Support/LeakDetector.h"
22#include "llvm/Support/Compiler.h"
23#include "SymbolTableListTraitsImpl.h"
24#include <algorithm>
25using namespace llvm;
26
27ValueSymbolTable *BasicBlock::getValueSymbolTable() {
28  if (Function *F = getParent())
29    return &F->getValueSymbolTable();
30  return 0;
31}
32
33LLVMContext *BasicBlock::getContext() const {
34  return Parent ? Parent->getContext() : 0;
35}
36
37// Explicit instantiation of SymbolTableListTraits since some of the methods
38// are not in the public header file...
39template class SymbolTableListTraits<Instruction, BasicBlock>;
40
41
42BasicBlock::BasicBlock(const std::string &Name, Function *NewParent,
43                       BasicBlock *InsertBefore)
44  : Value(Type::LabelTy, Value::BasicBlockVal), Parent(0) {
45
46  // Make sure that we get added to a function
47  LeakDetector::addGarbageObject(this);
48
49  if (InsertBefore) {
50    assert(NewParent &&
51           "Cannot insert block before another block with no function!");
52    NewParent->getBasicBlockList().insert(InsertBefore, this);
53  } else if (NewParent) {
54    NewParent->getBasicBlockList().push_back(this);
55  }
56
57  setName(Name);
58}
59
60
61BasicBlock::~BasicBlock() {
62  assert(getParent() == 0 && "BasicBlock still linked into the program!");
63  dropAllReferences();
64  InstList.clear();
65}
66
67void BasicBlock::setParent(Function *parent) {
68  if (getParent())
69    LeakDetector::addGarbageObject(this);
70
71  // Set Parent=parent, updating instruction symtab entries as appropriate.
72  InstList.setSymTabObject(&Parent, parent);
73
74  if (getParent())
75    LeakDetector::removeGarbageObject(this);
76}
77
78void BasicBlock::removeFromParent() {
79  getParent()->getBasicBlockList().remove(this);
80}
81
82void BasicBlock::eraseFromParent() {
83  getParent()->getBasicBlockList().erase(this);
84}
85
86/// moveBefore - Unlink this basic block from its current function and
87/// insert it into the function that MovePos lives in, right before MovePos.
88void BasicBlock::moveBefore(BasicBlock *MovePos) {
89  MovePos->getParent()->getBasicBlockList().splice(MovePos,
90                       getParent()->getBasicBlockList(), this);
91}
92
93/// moveAfter - Unlink this basic block from its current function and
94/// insert it into the function that MovePos lives in, right after MovePos.
95void BasicBlock::moveAfter(BasicBlock *MovePos) {
96  Function::iterator I = MovePos;
97  MovePos->getParent()->getBasicBlockList().splice(++I,
98                                       getParent()->getBasicBlockList(), this);
99}
100
101
102TerminatorInst *BasicBlock::getTerminator() {
103  if (InstList.empty()) return 0;
104  return dyn_cast<TerminatorInst>(&InstList.back());
105}
106
107const TerminatorInst *BasicBlock::getTerminator() const {
108  if (InstList.empty()) return 0;
109  return dyn_cast<TerminatorInst>(&InstList.back());
110}
111
112Instruction* BasicBlock::getFirstNonPHI() {
113  BasicBlock::iterator i = begin();
114  // All valid basic blocks should have a terminator,
115  // which is not a PHINode. If we have an invalid basic
116  // block we'll get an assertion failure when dereferencing
117  // a past-the-end iterator.
118  while (isa<PHINode>(i)) ++i;
119  return &*i;
120}
121
122void BasicBlock::dropAllReferences() {
123  for(iterator I = begin(), E = end(); I != E; ++I)
124    I->dropAllReferences();
125}
126
127/// getSinglePredecessor - If this basic block has a single predecessor block,
128/// return the block, otherwise return a null pointer.
129BasicBlock *BasicBlock::getSinglePredecessor() {
130  pred_iterator PI = pred_begin(this), E = pred_end(this);
131  if (PI == E) return 0;         // No preds.
132  BasicBlock *ThePred = *PI;
133  ++PI;
134  return (PI == E) ? ThePred : 0 /*multiple preds*/;
135}
136
137/// getUniquePredecessor - If this basic block has a unique predecessor block,
138/// return the block, otherwise return a null pointer.
139/// Note that unique predecessor doesn't mean single edge, there can be
140/// multiple edges from the unique predecessor to this block (for example
141/// a switch statement with multiple cases having the same destination).
142BasicBlock *BasicBlock::getUniquePredecessor() {
143  pred_iterator PI = pred_begin(this), E = pred_end(this);
144  if (PI == E) return 0; // No preds.
145  BasicBlock *PredBB = *PI;
146  ++PI;
147  for (;PI != E; ++PI) {
148    if (*PI != PredBB)
149      return 0;
150    // The same predecessor appears multiple times in the predecessor list.
151    // This is OK.
152  }
153  return PredBB;
154}
155
156/// removePredecessor - This method is used to notify a BasicBlock that the
157/// specified Predecessor of the block is no longer able to reach it.  This is
158/// actually not used to update the Predecessor list, but is actually used to
159/// update the PHI nodes that reside in the block.  Note that this should be
160/// called while the predecessor still refers to this block.
161///
162void BasicBlock::removePredecessor(BasicBlock *Pred,
163                                   bool DontDeleteUselessPHIs) {
164  assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
165          find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
166         "removePredecessor: BB is not a predecessor!");
167
168  if (InstList.empty()) return;
169  PHINode *APN = dyn_cast<PHINode>(&front());
170  if (!APN) return;   // Quick exit.
171
172  // If there are exactly two predecessors, then we want to nuke the PHI nodes
173  // altogether.  However, we cannot do this, if this in this case:
174  //
175  //  Loop:
176  //    %x = phi [X, Loop]
177  //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
178  //    br Loop                 ;; %x2 does not dominate all uses
179  //
180  // This is because the PHI node input is actually taken from the predecessor
181  // basic block.  The only case this can happen is with a self loop, so we
182  // check for this case explicitly now.
183  //
184  unsigned max_idx = APN->getNumIncomingValues();
185  assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
186  if (max_idx == 2) {
187    BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
188
189    // Disable PHI elimination!
190    if (this == Other) max_idx = 3;
191  }
192
193  // <= Two predecessors BEFORE I remove one?
194  if (max_idx <= 2 && !DontDeleteUselessPHIs) {
195    // Yup, loop through and nuke the PHI nodes
196    while (PHINode *PN = dyn_cast<PHINode>(&front())) {
197      // Remove the predecessor first.
198      PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
199
200      // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
201      if (max_idx == 2) {
202        if (PN->getOperand(0) != PN)
203          PN->replaceAllUsesWith(PN->getOperand(0));
204        else
205          // We are left with an infinite loop with no entries: kill the PHI.
206          PN->replaceAllUsesWith(getContext()->getUndef(PN->getType()));
207        getInstList().pop_front();    // Remove the PHI node
208      }
209
210      // If the PHI node already only had one entry, it got deleted by
211      // removeIncomingValue.
212    }
213  } else {
214    // Okay, now we know that we need to remove predecessor #pred_idx from all
215    // PHI nodes.  Iterate over each PHI node fixing them up
216    PHINode *PN;
217    for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
218      ++II;
219      PN->removeIncomingValue(Pred, false);
220      // If all incoming values to the Phi are the same, we can replace the Phi
221      // with that value.
222      Value* PNV = 0;
223      if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
224        PN->replaceAllUsesWith(PNV);
225        PN->eraseFromParent();
226      }
227    }
228  }
229}
230
231
232/// splitBasicBlock - This splits a basic block into two at the specified
233/// instruction.  Note that all instructions BEFORE the specified iterator stay
234/// as part of the original basic block, an unconditional branch is added to
235/// the new BB, and the rest of the instructions in the BB are moved to the new
236/// BB, including the old terminator.  This invalidates the iterator.
237///
238/// Note that this only works on well formed basic blocks (must have a
239/// terminator), and 'I' must not be the end of instruction list (which would
240/// cause a degenerate basic block to be formed, having a terminator inside of
241/// the basic block).
242///
243BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
244  assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
245  assert(I != InstList.end() &&
246         "Trying to get me to create degenerate basic block!");
247
248  BasicBlock *InsertBefore = next(Function::iterator(this))
249                               .getNodePtrUnchecked();
250  BasicBlock *New = BasicBlock::Create(BBName, getParent(), InsertBefore);
251
252  // Move all of the specified instructions from the original basic block into
253  // the new basic block.
254  New->getInstList().splice(New->end(), this->getInstList(), I, end());
255
256  // Add a branch instruction to the newly formed basic block.
257  BranchInst::Create(New, this);
258
259  // Now we must loop through all of the successors of the New block (which
260  // _were_ the successors of the 'this' block), and update any PHI nodes in
261  // successors.  If there were PHI nodes in the successors, then they need to
262  // know that incoming branches will be from New, not from Old.
263  //
264  for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
265    // Loop over any phi nodes in the basic block, updating the BB field of
266    // incoming values...
267    BasicBlock *Successor = *I;
268    PHINode *PN;
269    for (BasicBlock::iterator II = Successor->begin();
270         (PN = dyn_cast<PHINode>(II)); ++II) {
271      int IDX = PN->getBasicBlockIndex(this);
272      while (IDX != -1) {
273        PN->setIncomingBlock((unsigned)IDX, New);
274        IDX = PN->getBasicBlockIndex(this);
275      }
276    }
277  }
278  return New;
279}
280