1249259Sdim//===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
2249259Sdim//
3249259Sdim//                     The LLVM Compiler Infrastructure
4249259Sdim//
5249259Sdim// This file is distributed under the University of Illinois Open Source
6249259Sdim// License. See LICENSE.TXT for details.
7249259Sdim//
8249259Sdim//===----------------------------------------------------------------------===//
9249259Sdim//
10249259Sdim// This file implements the BasicBlock class for the IR library.
11249259Sdim//
12249259Sdim//===----------------------------------------------------------------------===//
13249259Sdim
14249259Sdim#include "llvm/IR/BasicBlock.h"
15249259Sdim#include "SymbolTableListTraitsImpl.h"
16249259Sdim#include "llvm/ADT/STLExtras.h"
17249259Sdim#include "llvm/IR/Constants.h"
18249259Sdim#include "llvm/IR/Instructions.h"
19249259Sdim#include "llvm/IR/IntrinsicInst.h"
20249259Sdim#include "llvm/IR/LLVMContext.h"
21249259Sdim#include "llvm/IR/Type.h"
22249259Sdim#include "llvm/Support/CFG.h"
23249259Sdim#include "llvm/Support/LeakDetector.h"
24249259Sdim#include <algorithm>
25249259Sdimusing namespace llvm;
26249259Sdim
27249259SdimValueSymbolTable *BasicBlock::getValueSymbolTable() {
28249259Sdim  if (Function *F = getParent())
29249259Sdim    return &F->getValueSymbolTable();
30249259Sdim  return 0;
31249259Sdim}
32249259Sdim
33249259SdimLLVMContext &BasicBlock::getContext() const {
34249259Sdim  return getType()->getContext();
35249259Sdim}
36249259Sdim
37249259Sdim// Explicit instantiation of SymbolTableListTraits since some of the methods
38249259Sdim// are not in the public header file...
39249259Sdimtemplate class llvm::SymbolTableListTraits<Instruction, BasicBlock>;
40249259Sdim
41249259Sdim
42249259SdimBasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
43249259Sdim                       BasicBlock *InsertBefore)
44249259Sdim  : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(0) {
45249259Sdim
46249259Sdim  // Make sure that we get added to a function
47249259Sdim  LeakDetector::addGarbageObject(this);
48249259Sdim
49249259Sdim  if (InsertBefore) {
50249259Sdim    assert(NewParent &&
51249259Sdim           "Cannot insert block before another block with no function!");
52249259Sdim    NewParent->getBasicBlockList().insert(InsertBefore, this);
53249259Sdim  } else if (NewParent) {
54249259Sdim    NewParent->getBasicBlockList().push_back(this);
55249259Sdim  }
56249259Sdim
57249259Sdim  setName(Name);
58249259Sdim}
59249259Sdim
60249259Sdim
61249259SdimBasicBlock::~BasicBlock() {
62249259Sdim  // If the address of the block is taken and it is being deleted (e.g. because
63249259Sdim  // it is dead), this means that there is either a dangling constant expr
64249259Sdim  // hanging off the block, or an undefined use of the block (source code
65249259Sdim  // expecting the address of a label to keep the block alive even though there
66249259Sdim  // is no indirect branch).  Handle these cases by zapping the BlockAddress
67249259Sdim  // nodes.  There are no other possible uses at this point.
68249259Sdim  if (hasAddressTaken()) {
69249259Sdim    assert(!use_empty() && "There should be at least one blockaddress!");
70249259Sdim    Constant *Replacement =
71249259Sdim      ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
72249259Sdim    while (!use_empty()) {
73249259Sdim      BlockAddress *BA = cast<BlockAddress>(use_back());
74249259Sdim      BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
75249259Sdim                                                       BA->getType()));
76249259Sdim      BA->destroyConstant();
77249259Sdim    }
78249259Sdim  }
79249259Sdim
80249259Sdim  assert(getParent() == 0 && "BasicBlock still linked into the program!");
81249259Sdim  dropAllReferences();
82249259Sdim  InstList.clear();
83249259Sdim}
84249259Sdim
85249259Sdimvoid BasicBlock::setParent(Function *parent) {
86249259Sdim  if (getParent())
87249259Sdim    LeakDetector::addGarbageObject(this);
88249259Sdim
89249259Sdim  // Set Parent=parent, updating instruction symtab entries as appropriate.
90249259Sdim  InstList.setSymTabObject(&Parent, parent);
91249259Sdim
92249259Sdim  if (getParent())
93249259Sdim    LeakDetector::removeGarbageObject(this);
94249259Sdim}
95249259Sdim
96249259Sdimvoid BasicBlock::removeFromParent() {
97249259Sdim  getParent()->getBasicBlockList().remove(this);
98249259Sdim}
99249259Sdim
100249259Sdimvoid BasicBlock::eraseFromParent() {
101249259Sdim  getParent()->getBasicBlockList().erase(this);
102249259Sdim}
103249259Sdim
104249259Sdim/// moveBefore - Unlink this basic block from its current function and
105249259Sdim/// insert it into the function that MovePos lives in, right before MovePos.
106249259Sdimvoid BasicBlock::moveBefore(BasicBlock *MovePos) {
107249259Sdim  MovePos->getParent()->getBasicBlockList().splice(MovePos,
108249259Sdim                       getParent()->getBasicBlockList(), this);
109249259Sdim}
110249259Sdim
111249259Sdim/// moveAfter - Unlink this basic block from its current function and
112249259Sdim/// insert it into the function that MovePos lives in, right after MovePos.
113249259Sdimvoid BasicBlock::moveAfter(BasicBlock *MovePos) {
114249259Sdim  Function::iterator I = MovePos;
115249259Sdim  MovePos->getParent()->getBasicBlockList().splice(++I,
116249259Sdim                                       getParent()->getBasicBlockList(), this);
117249259Sdim}
118249259Sdim
119249259Sdim
120249259SdimTerminatorInst *BasicBlock::getTerminator() {
121249259Sdim  if (InstList.empty()) return 0;
122249259Sdim  return dyn_cast<TerminatorInst>(&InstList.back());
123249259Sdim}
124249259Sdim
125249259Sdimconst TerminatorInst *BasicBlock::getTerminator() const {
126249259Sdim  if (InstList.empty()) return 0;
127249259Sdim  return dyn_cast<TerminatorInst>(&InstList.back());
128249259Sdim}
129249259Sdim
130249259SdimInstruction* BasicBlock::getFirstNonPHI() {
131249259Sdim  BasicBlock::iterator i = begin();
132249259Sdim  // All valid basic blocks should have a terminator,
133249259Sdim  // which is not a PHINode. If we have an invalid basic
134249259Sdim  // block we'll get an assertion failure when dereferencing
135249259Sdim  // a past-the-end iterator.
136249259Sdim  while (isa<PHINode>(i)) ++i;
137249259Sdim  return &*i;
138249259Sdim}
139249259Sdim
140249259SdimInstruction* BasicBlock::getFirstNonPHIOrDbg() {
141249259Sdim  BasicBlock::iterator i = begin();
142249259Sdim  // All valid basic blocks should have a terminator,
143249259Sdim  // which is not a PHINode. If we have an invalid basic
144249259Sdim  // block we'll get an assertion failure when dereferencing
145249259Sdim  // a past-the-end iterator.
146249259Sdim  while (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) ++i;
147249259Sdim  return &*i;
148249259Sdim}
149249259Sdim
150249259SdimInstruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
151249259Sdim  // All valid basic blocks should have a terminator,
152249259Sdim  // which is not a PHINode. If we have an invalid basic
153249259Sdim  // block we'll get an assertion failure when dereferencing
154249259Sdim  // a past-the-end iterator.
155249259Sdim  BasicBlock::iterator i = begin();
156249259Sdim  for (;; ++i) {
157249259Sdim    if (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i))
158249259Sdim      continue;
159249259Sdim
160249259Sdim    const IntrinsicInst *II = dyn_cast<IntrinsicInst>(i);
161249259Sdim    if (!II)
162249259Sdim      break;
163249259Sdim    if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
164249259Sdim        II->getIntrinsicID() != Intrinsic::lifetime_end)
165249259Sdim      break;
166249259Sdim  }
167249259Sdim  return &*i;
168249259Sdim}
169249259Sdim
170249259SdimBasicBlock::iterator BasicBlock::getFirstInsertionPt() {
171249259Sdim  iterator InsertPt = getFirstNonPHI();
172249259Sdim  if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
173249259Sdim  return InsertPt;
174249259Sdim}
175249259Sdim
176249259Sdimvoid BasicBlock::dropAllReferences() {
177249259Sdim  for(iterator I = begin(), E = end(); I != E; ++I)
178249259Sdim    I->dropAllReferences();
179249259Sdim}
180249259Sdim
181249259Sdim/// getSinglePredecessor - If this basic block has a single predecessor block,
182249259Sdim/// return the block, otherwise return a null pointer.
183249259SdimBasicBlock *BasicBlock::getSinglePredecessor() {
184249259Sdim  pred_iterator PI = pred_begin(this), E = pred_end(this);
185249259Sdim  if (PI == E) return 0;         // No preds.
186249259Sdim  BasicBlock *ThePred = *PI;
187249259Sdim  ++PI;
188249259Sdim  return (PI == E) ? ThePred : 0 /*multiple preds*/;
189249259Sdim}
190249259Sdim
191249259Sdim/// getUniquePredecessor - If this basic block has a unique predecessor block,
192249259Sdim/// return the block, otherwise return a null pointer.
193249259Sdim/// Note that unique predecessor doesn't mean single edge, there can be
194249259Sdim/// multiple edges from the unique predecessor to this block (for example
195249259Sdim/// a switch statement with multiple cases having the same destination).
196249259SdimBasicBlock *BasicBlock::getUniquePredecessor() {
197249259Sdim  pred_iterator PI = pred_begin(this), E = pred_end(this);
198249259Sdim  if (PI == E) return 0; // No preds.
199249259Sdim  BasicBlock *PredBB = *PI;
200249259Sdim  ++PI;
201249259Sdim  for (;PI != E; ++PI) {
202249259Sdim    if (*PI != PredBB)
203249259Sdim      return 0;
204249259Sdim    // The same predecessor appears multiple times in the predecessor list.
205249259Sdim    // This is OK.
206249259Sdim  }
207249259Sdim  return PredBB;
208249259Sdim}
209249259Sdim
210249259Sdim/// removePredecessor - This method is used to notify a BasicBlock that the
211249259Sdim/// specified Predecessor of the block is no longer able to reach it.  This is
212249259Sdim/// actually not used to update the Predecessor list, but is actually used to
213249259Sdim/// update the PHI nodes that reside in the block.  Note that this should be
214249259Sdim/// called while the predecessor still refers to this block.
215249259Sdim///
216249259Sdimvoid BasicBlock::removePredecessor(BasicBlock *Pred,
217249259Sdim                                   bool DontDeleteUselessPHIs) {
218249259Sdim  assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
219249259Sdim          find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
220249259Sdim         "removePredecessor: BB is not a predecessor!");
221249259Sdim
222249259Sdim  if (InstList.empty()) return;
223249259Sdim  PHINode *APN = dyn_cast<PHINode>(&front());
224249259Sdim  if (!APN) return;   // Quick exit.
225249259Sdim
226249259Sdim  // If there are exactly two predecessors, then we want to nuke the PHI nodes
227249259Sdim  // altogether.  However, we cannot do this, if this in this case:
228249259Sdim  //
229249259Sdim  //  Loop:
230249259Sdim  //    %x = phi [X, Loop]
231249259Sdim  //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
232249259Sdim  //    br Loop                 ;; %x2 does not dominate all uses
233249259Sdim  //
234249259Sdim  // This is because the PHI node input is actually taken from the predecessor
235249259Sdim  // basic block.  The only case this can happen is with a self loop, so we
236249259Sdim  // check for this case explicitly now.
237249259Sdim  //
238249259Sdim  unsigned max_idx = APN->getNumIncomingValues();
239249259Sdim  assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
240249259Sdim  if (max_idx == 2) {
241249259Sdim    BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
242249259Sdim
243249259Sdim    // Disable PHI elimination!
244249259Sdim    if (this == Other) max_idx = 3;
245249259Sdim  }
246249259Sdim
247249259Sdim  // <= Two predecessors BEFORE I remove one?
248249259Sdim  if (max_idx <= 2 && !DontDeleteUselessPHIs) {
249249259Sdim    // Yup, loop through and nuke the PHI nodes
250249259Sdim    while (PHINode *PN = dyn_cast<PHINode>(&front())) {
251249259Sdim      // Remove the predecessor first.
252249259Sdim      PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
253249259Sdim
254249259Sdim      // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
255249259Sdim      if (max_idx == 2) {
256249259Sdim        if (PN->getIncomingValue(0) != PN)
257249259Sdim          PN->replaceAllUsesWith(PN->getIncomingValue(0));
258249259Sdim        else
259249259Sdim          // We are left with an infinite loop with no entries: kill the PHI.
260249259Sdim          PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
261249259Sdim        getInstList().pop_front();    // Remove the PHI node
262249259Sdim      }
263249259Sdim
264249259Sdim      // If the PHI node already only had one entry, it got deleted by
265249259Sdim      // removeIncomingValue.
266249259Sdim    }
267249259Sdim  } else {
268249259Sdim    // Okay, now we know that we need to remove predecessor #pred_idx from all
269249259Sdim    // PHI nodes.  Iterate over each PHI node fixing them up
270249259Sdim    PHINode *PN;
271249259Sdim    for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
272249259Sdim      ++II;
273249259Sdim      PN->removeIncomingValue(Pred, false);
274249259Sdim      // If all incoming values to the Phi are the same, we can replace the Phi
275249259Sdim      // with that value.
276249259Sdim      Value* PNV = 0;
277249259Sdim      if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
278249259Sdim        if (PNV != PN) {
279249259Sdim          PN->replaceAllUsesWith(PNV);
280249259Sdim          PN->eraseFromParent();
281249259Sdim        }
282249259Sdim    }
283249259Sdim  }
284249259Sdim}
285249259Sdim
286249259Sdim
287249259Sdim/// splitBasicBlock - This splits a basic block into two at the specified
288249259Sdim/// instruction.  Note that all instructions BEFORE the specified iterator stay
289249259Sdim/// as part of the original basic block, an unconditional branch is added to
290249259Sdim/// the new BB, and the rest of the instructions in the BB are moved to the new
291249259Sdim/// BB, including the old terminator.  This invalidates the iterator.
292249259Sdim///
293249259Sdim/// Note that this only works on well formed basic blocks (must have a
294249259Sdim/// terminator), and 'I' must not be the end of instruction list (which would
295249259Sdim/// cause a degenerate basic block to be formed, having a terminator inside of
296249259Sdim/// the basic block).
297249259Sdim///
298249259SdimBasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
299249259Sdim  assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
300249259Sdim  assert(I != InstList.end() &&
301249259Sdim         "Trying to get me to create degenerate basic block!");
302249259Sdim
303249259Sdim  BasicBlock *InsertBefore = llvm::next(Function::iterator(this))
304249259Sdim                               .getNodePtrUnchecked();
305249259Sdim  BasicBlock *New = BasicBlock::Create(getContext(), BBName,
306249259Sdim                                       getParent(), InsertBefore);
307249259Sdim
308249259Sdim  // Move all of the specified instructions from the original basic block into
309249259Sdim  // the new basic block.
310249259Sdim  New->getInstList().splice(New->end(), this->getInstList(), I, end());
311249259Sdim
312249259Sdim  // Add a branch instruction to the newly formed basic block.
313249259Sdim  BranchInst::Create(New, this);
314249259Sdim
315249259Sdim  // Now we must loop through all of the successors of the New block (which
316249259Sdim  // _were_ the successors of the 'this' block), and update any PHI nodes in
317249259Sdim  // successors.  If there were PHI nodes in the successors, then they need to
318249259Sdim  // know that incoming branches will be from New, not from Old.
319249259Sdim  //
320249259Sdim  for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
321249259Sdim    // Loop over any phi nodes in the basic block, updating the BB field of
322249259Sdim    // incoming values...
323249259Sdim    BasicBlock *Successor = *I;
324249259Sdim    PHINode *PN;
325249259Sdim    for (BasicBlock::iterator II = Successor->begin();
326249259Sdim         (PN = dyn_cast<PHINode>(II)); ++II) {
327249259Sdim      int IDX = PN->getBasicBlockIndex(this);
328249259Sdim      while (IDX != -1) {
329249259Sdim        PN->setIncomingBlock((unsigned)IDX, New);
330249259Sdim        IDX = PN->getBasicBlockIndex(this);
331249259Sdim      }
332249259Sdim    }
333249259Sdim  }
334249259Sdim  return New;
335249259Sdim}
336249259Sdim
337249259Sdimvoid BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
338249259Sdim  TerminatorInst *TI = getTerminator();
339249259Sdim  if (!TI)
340249259Sdim    // Cope with being called on a BasicBlock that doesn't have a terminator
341249259Sdim    // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
342249259Sdim    return;
343249259Sdim  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
344249259Sdim    BasicBlock *Succ = TI->getSuccessor(i);
345249259Sdim    // N.B. Succ might not be a complete BasicBlock, so don't assume
346249259Sdim    // that it ends with a non-phi instruction.
347249259Sdim    for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
348249259Sdim      PHINode *PN = dyn_cast<PHINode>(II);
349249259Sdim      if (!PN)
350249259Sdim        break;
351249259Sdim      int i;
352249259Sdim      while ((i = PN->getBasicBlockIndex(this)) >= 0)
353249259Sdim        PN->setIncomingBlock(i, New);
354249259Sdim    }
355249259Sdim  }
356249259Sdim}
357249259Sdim
358249259Sdim/// isLandingPad - Return true if this basic block is a landing pad. I.e., it's
359249259Sdim/// the destination of the 'unwind' edge of an invoke instruction.
360249259Sdimbool BasicBlock::isLandingPad() const {
361249259Sdim  return isa<LandingPadInst>(getFirstNonPHI());
362249259Sdim}
363249259Sdim
364249259Sdim/// getLandingPadInst() - Return the landingpad instruction associated with
365249259Sdim/// the landing pad.
366249259SdimLandingPadInst *BasicBlock::getLandingPadInst() {
367249259Sdim  return dyn_cast<LandingPadInst>(getFirstNonPHI());
368249259Sdim}
369249259Sdimconst LandingPadInst *BasicBlock::getLandingPadInst() const {
370249259Sdim  return dyn_cast<LandingPadInst>(getFirstNonPHI());
371249259Sdim}
372