LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
BasicBlock.cpp
Go to the documentation of this file.
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 IR library.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/BasicBlock.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Type.h"
22 #include "llvm/Support/CFG.h"
24 #include <algorithm>
25 using namespace llvm;
26 
28  if (Function *F = getParent())
29  return &F->getValueSymbolTable();
30  return 0;
31 }
32 
34  return getType()->getContext();
35 }
36 
37 // Explicit instantiation of SymbolTableListTraits since some of the methods
38 // are not in the public header file...
40 
41 
42 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
43  BasicBlock *InsertBefore)
44  : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(0) {
45 
46  // Make sure that we get added to a function
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 
62  // If the address of the block is taken and it is being deleted (e.g. because
63  // it is dead), this means that there is either a dangling constant expr
64  // hanging off the block, or an undefined use of the block (source code
65  // expecting the address of a label to keep the block alive even though there
66  // is no indirect branch). Handle these cases by zapping the BlockAddress
67  // nodes. There are no other possible uses at this point.
68  if (hasAddressTaken()) {
69  assert(!use_empty() && "There should be at least one blockaddress!");
70  Constant *Replacement =
72  while (!use_empty()) {
73  BlockAddress *BA = cast<BlockAddress>(use_back());
75  BA->getType()));
76  BA->destroyConstant();
77  }
78  }
79 
80  assert(getParent() == 0 && "BasicBlock still linked into the program!");
82  InstList.clear();
83 }
84 
85 void BasicBlock::setParent(Function *parent) {
86  if (getParent())
88 
89  // Set Parent=parent, updating instruction symtab entries as appropriate.
90  InstList.setSymTabObject(&Parent, parent);
91 
92  if (getParent())
94 }
95 
98 }
99 
101  getParent()->getBasicBlockList().erase(this);
102 }
103 
104 /// moveBefore - Unlink this basic block from its current function and
105 /// insert it into the function that MovePos lives in, right before MovePos.
107  MovePos->getParent()->getBasicBlockList().splice(MovePos,
108  getParent()->getBasicBlockList(), this);
109 }
110 
111 /// moveAfter - Unlink this basic block from its current function and
112 /// insert it into the function that MovePos lives in, right after MovePos.
114  Function::iterator I = MovePos;
115  MovePos->getParent()->getBasicBlockList().splice(++I,
116  getParent()->getBasicBlockList(), this);
117 }
118 
119 
121  if (InstList.empty()) return 0;
122  return dyn_cast<TerminatorInst>(&InstList.back());
123 }
124 
126  if (InstList.empty()) return 0;
127  return dyn_cast<TerminatorInst>(&InstList.back());
128 }
129 
132  // All valid basic blocks should have a terminator,
133  // which is not a PHINode. If we have an invalid basic
134  // block we'll get an assertion failure when dereferencing
135  // a past-the-end iterator.
136  while (isa<PHINode>(i)) ++i;
137  return &*i;
138 }
139 
142  // All valid basic blocks should have a terminator,
143  // which is not a PHINode. If we have an invalid basic
144  // block we'll get an assertion failure when dereferencing
145  // a past-the-end iterator.
146  while (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) ++i;
147  return &*i;
148 }
149 
151  // All valid basic blocks should have a terminator,
152  // which is not a PHINode. If we have an invalid basic
153  // block we'll get an assertion failure when dereferencing
154  // a past-the-end iterator.
156  for (;; ++i) {
157  if (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i))
158  continue;
159 
160  const IntrinsicInst *II = dyn_cast<IntrinsicInst>(i);
161  if (!II)
162  break;
165  break;
166  }
167  return &*i;
168 }
169 
171  iterator InsertPt = getFirstNonPHI();
172  if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
173  return InsertPt;
174 }
175 
177  for(iterator I = begin(), E = end(); I != E; ++I)
178  I->dropAllReferences();
179 }
180 
181 /// getSinglePredecessor - If this basic block has a single predecessor block,
182 /// return the block, otherwise return a null pointer.
184  pred_iterator PI = pred_begin(this), E = pred_end(this);
185  if (PI == E) return 0; // No preds.
186  BasicBlock *ThePred = *PI;
187  ++PI;
188  return (PI == E) ? ThePred : 0 /*multiple preds*/;
189 }
190 
191 /// getUniquePredecessor - If this basic block has a unique predecessor block,
192 /// return the block, otherwise return a null pointer.
193 /// Note that unique predecessor doesn't mean single edge, there can be
194 /// multiple edges from the unique predecessor to this block (for example
195 /// a switch statement with multiple cases having the same destination).
197  pred_iterator PI = pred_begin(this), E = pred_end(this);
198  if (PI == E) return 0; // No preds.
199  BasicBlock *PredBB = *PI;
200  ++PI;
201  for (;PI != E; ++PI) {
202  if (*PI != PredBB)
203  return 0;
204  // The same predecessor appears multiple times in the predecessor list.
205  // This is OK.
206  }
207  return PredBB;
208 }
209 
210 /// removePredecessor - This method is used to notify a BasicBlock that the
211 /// specified Predecessor of the block is no longer able to reach it. This is
212 /// actually not used to update the Predecessor list, but is actually used to
213 /// update the PHI nodes that reside in the block. Note that this should be
214 /// called while the predecessor still refers to this block.
215 ///
217  bool DontDeleteUselessPHIs) {
218  assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
219  find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
220  "removePredecessor: BB is not a predecessor!");
221 
222  if (InstList.empty()) return;
223  PHINode *APN = dyn_cast<PHINode>(&front());
224  if (!APN) return; // Quick exit.
225 
226  // If there are exactly two predecessors, then we want to nuke the PHI nodes
227  // altogether. However, we cannot do this, if this in this case:
228  //
229  // Loop:
230  // %x = phi [X, Loop]
231  // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
232  // br Loop ;; %x2 does not dominate all uses
233  //
234  // This is because the PHI node input is actually taken from the predecessor
235  // basic block. The only case this can happen is with a self loop, so we
236  // check for this case explicitly now.
237  //
238  unsigned max_idx = APN->getNumIncomingValues();
239  assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
240  if (max_idx == 2) {
241  BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
242 
243  // Disable PHI elimination!
244  if (this == Other) max_idx = 3;
245  }
246 
247  // <= Two predecessors BEFORE I remove one?
248  if (max_idx <= 2 && !DontDeleteUselessPHIs) {
249  // Yup, loop through and nuke the PHI nodes
250  while (PHINode *PN = dyn_cast<PHINode>(&front())) {
251  // Remove the predecessor first.
252  PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
253 
254  // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
255  if (max_idx == 2) {
256  if (PN->getIncomingValue(0) != PN)
257  PN->replaceAllUsesWith(PN->getIncomingValue(0));
258  else
259  // We are left with an infinite loop with no entries: kill the PHI.
260  PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
261  getInstList().pop_front(); // Remove the PHI node
262  }
263 
264  // If the PHI node already only had one entry, it got deleted by
265  // removeIncomingValue.
266  }
267  } else {
268  // Okay, now we know that we need to remove predecessor #pred_idx from all
269  // PHI nodes. Iterate over each PHI node fixing them up
270  PHINode *PN;
271  for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
272  ++II;
273  PN->removeIncomingValue(Pred, false);
274  // If all incoming values to the Phi are the same, we can replace the Phi
275  // with that value.
276  Value* PNV = 0;
277  if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
278  if (PNV != PN) {
279  PN->replaceAllUsesWith(PNV);
280  PN->eraseFromParent();
281  }
282  }
283  }
284 }
285 
286 
287 /// splitBasicBlock - This splits a basic block into two at the specified
288 /// instruction. Note that all instructions BEFORE the specified iterator stay
289 /// as part of the original basic block, an unconditional branch is added to
290 /// the new BB, and the rest of the instructions in the BB are moved to the new
291 /// BB, including the old terminator. This invalidates the iterator.
292 ///
293 /// Note that this only works on well formed basic blocks (must have a
294 /// terminator), and 'I' must not be the end of instruction list (which would
295 /// cause a degenerate basic block to be formed, having a terminator inside of
296 /// the basic block).
297 ///
299  assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
300  assert(I != InstList.end() &&
301  "Trying to get me to create degenerate basic block!");
302 
303  BasicBlock *InsertBefore = llvm::next(Function::iterator(this))
304  .getNodePtrUnchecked();
305  BasicBlock *New = BasicBlock::Create(getContext(), BBName,
306  getParent(), InsertBefore);
307 
308  // Move all of the specified instructions from the original basic block into
309  // the new basic block.
310  New->getInstList().splice(New->end(), this->getInstList(), I, end());
311 
312  // Add a branch instruction to the newly formed basic block.
313  BranchInst::Create(New, this);
314 
315  // Now we must loop through all of the successors of the New block (which
316  // _were_ the successors of the 'this' block), and update any PHI nodes in
317  // successors. If there were PHI nodes in the successors, then they need to
318  // know that incoming branches will be from New, not from Old.
319  //
320  for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
321  // Loop over any phi nodes in the basic block, updating the BB field of
322  // incoming values...
323  BasicBlock *Successor = *I;
324  PHINode *PN;
325  for (BasicBlock::iterator II = Successor->begin();
326  (PN = dyn_cast<PHINode>(II)); ++II) {
327  int IDX = PN->getBasicBlockIndex(this);
328  while (IDX != -1) {
329  PN->setIncomingBlock((unsigned)IDX, New);
330  IDX = PN->getBasicBlockIndex(this);
331  }
332  }
333  }
334  return New;
335 }
336 
339  if (!TI)
340  // Cope with being called on a BasicBlock that doesn't have a terminator
341  // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
342  return;
343  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
344  BasicBlock *Succ = TI->getSuccessor(i);
345  // N.B. Succ might not be a complete BasicBlock, so don't assume
346  // that it ends with a non-phi instruction.
347  for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
348  PHINode *PN = dyn_cast<PHINode>(II);
349  if (!PN)
350  break;
351  int i;
352  while ((i = PN->getBasicBlockIndex(this)) >= 0)
353  PN->setIncomingBlock(i, New);
354  }
355  }
356 }
357 
358 /// isLandingPad - Return true if this basic block is a landing pad. I.e., it's
359 /// the destination of the 'unwind' edge of an invoke instruction.
361  return isa<LandingPadInst>(getFirstNonPHI());
362 }
363 
364 /// getLandingPadInst() - Return the landingpad instruction associated with
365 /// the landing pad.
368 }
371 }
BasicBlock * getUniquePredecessor()
Return this block if it has a unique predecessor block. Otherwise return a null pointer.
Definition: BasicBlock.cpp:196
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
Definition: BasicBlock.cpp:216
Intrinsic::ID getIntrinsicID() const
Definition: IntrinsicInst.h:43
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:266
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:116
const Instruction & front() const
Definition: BasicBlock.h:205
F(f)
iterator begin()
Definition: BasicBlock.h:193
Instruction * getFirstNonPHIOrDbg()
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
Definition: BasicBlock.cpp:140
static void removeGarbageObject(void *Object)
Definition: LeakDetector.h:47
void push_back(NodeTy *val)
Definition: ilist.h:554
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Instruction * getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:130
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=0)
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc. to it.
Definition: BasicBlock.h:268
void setName(const Twine &Name)
Definition: Value.cpp:175
void clear()
Definition: ilist.h:550
Interval::succ_iterator succ_begin(Interval *I)
Definition: Interval.h:107
LLVMContext & getContext() const
getContext - Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
void replaceAllUsesWith(Value *V)
Definition: Value.cpp:303
static Constant * getIntToPtr(Constant *C, Type *Ty)
Definition: Constants.cpp:1649
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:110
unsigned getNumIncomingValues() const
unsigned getNumSuccessors() const
Definition: InstrTypes.h:59
void replaceSuccessorsPhiUsesWith(BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of to it...
Definition: BasicBlock.cpp:337
LLVM Basic Block Representation.
Definition: BasicBlock.h:72
Value * hasConstantValue() const
BasicBlock * getSuccessor(unsigned idx) const
Definition: InstrTypes.h:65
LLVM Constant Representation.
Definition: Constant.h:41
LandingPadInst * getLandingPadInst()
Return the landingpad instruction associated with the landing pad.
Definition: BasicBlock.cpp:366
Interval::pred_iterator pred_begin(Interval *I)
Definition: Interval.h:117
BasicBlock * getIncomingBlock(unsigned i) const
ItTy next(ItTy it, Dist n)
Definition: STLExtras.h:154
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:214
iterator insert(iterator where, NodeTy *New)
Definition: ilist.h:412
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:120
static UndefValue * get(Type *T)
Definition: Constants.cpp:1334
Instruction * getFirstNonPHIOrDbgOrLifetime()
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic...
Definition: BasicBlock.cpp:150
iterator erase(iterator where)
Definition: ilist.h:465
void removeFromParent()
Unlink 'this' from the containing function, but do not delete it.
Definition: BasicBlock.cpp:96
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
Definition: BasicBlock.cpp:113
const BasicBlockListType & getBasicBlockList() const
Definition: Function.h:374
void setIncomingBlock(unsigned i, BasicBlock *BB)
iterator end()
Definition: BasicBlock.h:195
Type * getType() const
Definition: Value.h:111
void eraseFromParent()
Unlink 'this' from the containing function and delete it.
Definition: BasicBlock.cpp:100
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: ilist.h:385
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
Definition: Constants.cpp:492
void splice(iterator where, iplist &L2)
Definition: ilist.h:570
static void addGarbageObject(void *Object)
Definition: LeakDetector.h:37
BasicBlock * getSinglePredecessor()
Return this block if it has a single predecessor block. Otherwise return a null pointer.
Definition: BasicBlock.cpp:183
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:241
User * use_back()
Definition: Value.h:154
ValueSymbolTable * getValueSymbolTable()
Returns a pointer to the symbol table if one exists.
Definition: BasicBlock.cpp:27
#define I(x, y, z)
Definition: MD5.cpp:54
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
bool isLandingPad() const
Return true if this basic block is a landing pad.
Definition: BasicBlock.cpp:360
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=0, BasicBlock *InsertBefore=0)
Creates a new BasicBlock.
Definition: BasicBlock.h:109
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:298
virtual void destroyConstant()
Definition: Constants.cpp:1379
reference back()
Definition: ilist.h:398
bool hasNUsesOrMore(unsigned N) const
Definition: Value.cpp:103
bool use_empty() const
Definition: Value.h:149
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:33
iterator end()
Definition: ilist.h:367
LLVM Value Representation.
Definition: Value.h:66
void pop_front()
Definition: ilist.h:555
iterator getFirstInsertionPt()
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:170
NodeTy * remove(iterator &IT)
Definition: ilist.h:435
int getBasicBlockIndex(const BasicBlock *BB) const
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition: BasicBlock.cpp:106
void dropAllReferences()
Cause all subinstructions to "let go" of all the references that said subinstructions are maintaining...
Definition: BasicBlock.cpp:176