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