1
//===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
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 file implements the BasicBlock class for the VMCore library.
12
//===----------------------------------------------------------------------===//
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 "SymbolTableListTraitsImpl.h"
26
ValueSymbolTable *BasicBlock::getValueSymbolTable() {
27
if (Function *F = getParent())
28
return &F->getValueSymbolTable();
32
LLVMContext &BasicBlock::getContext() const {
33
return getType()->getContext();
36
// Explicit instantiation of SymbolTableListTraits since some of the methods
37
// are not in the public header file...
38
template class llvm::SymbolTableListTraits<Instruction, BasicBlock>;
41
BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
42
BasicBlock *InsertBefore)
43
: Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(0) {
45
// Make sure that we get added to a function
46
LeakDetector::addGarbageObject(this);
50
"Cannot insert block before another block with no function!");
51
NewParent->getBasicBlockList().insert(InsertBefore, this);
52
} else if (NewParent) {
53
NewParent->getBasicBlockList().push_back(this);
60
BasicBlock::~BasicBlock() {
61
// If the address of the block is taken and it is being deleted (e.g. because
62
// it is dead), this means that there is either a dangling constant expr
63
// hanging off the block, or an undefined use of the block (source code
64
// expecting the address of a label to keep the block alive even though there
65
// is no indirect branch). Handle these cases by zapping the BlockAddress
66
// nodes. There are no other possible uses at this point.
67
if (hasAddressTaken()) {
68
assert(!use_empty() && "There should be at least one blockaddress!");
69
Constant *Replacement =
70
ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
71
while (!use_empty()) {
72
BlockAddress *BA = cast<BlockAddress>(use_back());
73
BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
75
BA->destroyConstant();
79
assert(getParent() == 0 && "BasicBlock still linked into the program!");
84
void BasicBlock::setParent(Function *parent) {
86
LeakDetector::addGarbageObject(this);
88
// Set Parent=parent, updating instruction symtab entries as appropriate.
89
InstList.setSymTabObject(&Parent, parent);
92
LeakDetector::removeGarbageObject(this);
95
void BasicBlock::removeFromParent() {
96
getParent()->getBasicBlockList().remove(this);
99
void BasicBlock::eraseFromParent() {
100
getParent()->getBasicBlockList().erase(this);
103
/// moveBefore - Unlink this basic block from its current function and
104
/// insert it into the function that MovePos lives in, right before MovePos.
105
void BasicBlock::moveBefore(BasicBlock *MovePos) {
106
MovePos->getParent()->getBasicBlockList().splice(MovePos,
107
getParent()->getBasicBlockList(), this);
110
/// moveAfter - Unlink this basic block from its current function and
111
/// insert it into the function that MovePos lives in, right after MovePos.
112
void BasicBlock::moveAfter(BasicBlock *MovePos) {
113
Function::iterator I = MovePos;
114
MovePos->getParent()->getBasicBlockList().splice(++I,
115
getParent()->getBasicBlockList(), this);
119
TerminatorInst *BasicBlock::getTerminator() {
120
if (InstList.empty()) return 0;
121
return dyn_cast<TerminatorInst>(&InstList.back());
124
const TerminatorInst *BasicBlock::getTerminator() const {
125
if (InstList.empty()) return 0;
126
return dyn_cast<TerminatorInst>(&InstList.back());
129
Instruction* BasicBlock::getFirstNonPHI() {
130
BasicBlock::iterator i = begin();
131
// All valid basic blocks should have a terminator,
132
// which is not a PHINode. If we have an invalid basic
133
// block we'll get an assertion failure when dereferencing
134
// a past-the-end iterator.
135
while (isa<PHINode>(i)) ++i;
139
void BasicBlock::dropAllReferences() {
140
for(iterator I = begin(), E = end(); I != E; ++I)
141
I->dropAllReferences();
144
/// getSinglePredecessor - If this basic block has a single predecessor block,
145
/// return the block, otherwise return a null pointer.
146
BasicBlock *BasicBlock::getSinglePredecessor() {
147
pred_iterator PI = pred_begin(this), E = pred_end(this);
148
if (PI == E) return 0; // No preds.
149
BasicBlock *ThePred = *PI;
151
return (PI == E) ? ThePred : 0 /*multiple preds*/;
154
/// getUniquePredecessor - If this basic block has a unique predecessor block,
155
/// return the block, otherwise return a null pointer.
156
/// Note that unique predecessor doesn't mean single edge, there can be
157
/// multiple edges from the unique predecessor to this block (for example
158
/// a switch statement with multiple cases having the same destination).
159
BasicBlock *BasicBlock::getUniquePredecessor() {
160
pred_iterator PI = pred_begin(this), E = pred_end(this);
161
if (PI == E) return 0; // No preds.
162
BasicBlock *PredBB = *PI;
164
for (;PI != E; ++PI) {
167
// The same predecessor appears multiple times in the predecessor list.
173
/// removePredecessor - This method is used to notify a BasicBlock that the
174
/// specified Predecessor of the block is no longer able to reach it. This is
175
/// actually not used to update the Predecessor list, but is actually used to
176
/// update the PHI nodes that reside in the block. Note that this should be
177
/// called while the predecessor still refers to this block.
179
void BasicBlock::removePredecessor(BasicBlock *Pred,
180
bool DontDeleteUselessPHIs) {
181
assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
182
find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
183
"removePredecessor: BB is not a predecessor!");
185
if (InstList.empty()) return;
186
PHINode *APN = dyn_cast<PHINode>(&front());
187
if (!APN) return; // Quick exit.
189
// If there are exactly two predecessors, then we want to nuke the PHI nodes
190
// altogether. However, we cannot do this, if this in this case:
193
// %x = phi [X, Loop]
194
// %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
195
// br Loop ;; %x2 does not dominate all uses
197
// This is because the PHI node input is actually taken from the predecessor
198
// basic block. The only case this can happen is with a self loop, so we
199
// check for this case explicitly now.
201
unsigned max_idx = APN->getNumIncomingValues();
202
assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
204
BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
206
// Disable PHI elimination!
207
if (this == Other) max_idx = 3;
210
// <= Two predecessors BEFORE I remove one?
211
if (max_idx <= 2 && !DontDeleteUselessPHIs) {
212
// Yup, loop through and nuke the PHI nodes
213
while (PHINode *PN = dyn_cast<PHINode>(&front())) {
214
// Remove the predecessor first.
215
PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
217
// If the PHI _HAD_ two uses, replace PHI node with its now *single* value
219
if (PN->getOperand(0) != PN)
220
PN->replaceAllUsesWith(PN->getOperand(0));
222
// We are left with an infinite loop with no entries: kill the PHI.
223
PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
224
getInstList().pop_front(); // Remove the PHI node
227
// If the PHI node already only had one entry, it got deleted by
228
// removeIncomingValue.
231
// Okay, now we know that we need to remove predecessor #pred_idx from all
232
// PHI nodes. Iterate over each PHI node fixing them up
234
for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
236
PN->removeIncomingValue(Pred, false);
237
// If all incoming values to the Phi are the same, we can replace the Phi
240
if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
241
PN->replaceAllUsesWith(PNV);
242
PN->eraseFromParent();
249
/// splitBasicBlock - This splits a basic block into two at the specified
250
/// instruction. Note that all instructions BEFORE the specified iterator stay
251
/// as part of the original basic block, an unconditional branch is added to
252
/// the new BB, and the rest of the instructions in the BB are moved to the new
253
/// BB, including the old terminator. This invalidates the iterator.
255
/// Note that this only works on well formed basic blocks (must have a
256
/// terminator), and 'I' must not be the end of instruction list (which would
257
/// cause a degenerate basic block to be formed, having a terminator inside of
258
/// the basic block).
260
BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
261
assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
262
assert(I != InstList.end() &&
263
"Trying to get me to create degenerate basic block!");
265
BasicBlock *InsertBefore = llvm::next(Function::iterator(this))
266
.getNodePtrUnchecked();
267
BasicBlock *New = BasicBlock::Create(getContext(), BBName,
268
getParent(), InsertBefore);
270
// Move all of the specified instructions from the original basic block into
271
// the new basic block.
272
New->getInstList().splice(New->end(), this->getInstList(), I, end());
274
// Add a branch instruction to the newly formed basic block.
275
BranchInst::Create(New, this);
277
// Now we must loop through all of the successors of the New block (which
278
// _were_ the successors of the 'this' block), and update any PHI nodes in
279
// successors. If there were PHI nodes in the successors, then they need to
280
// know that incoming branches will be from New, not from Old.
282
for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
283
// Loop over any phi nodes in the basic block, updating the BB field of
284
// incoming values...
285
BasicBlock *Successor = *I;
287
for (BasicBlock::iterator II = Successor->begin();
288
(PN = dyn_cast<PHINode>(II)); ++II) {
289
int IDX = PN->getBasicBlockIndex(this);
291
PN->setIncomingBlock((unsigned)IDX, New);
292
IDX = PN->getBasicBlockIndex(this);