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 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, replacing them with BlockAddress(F, NULL). There are no other
67 // possible uses at this point.
68 if (hasAddressTaken()) {
69 assert(!use_empty() && "There should be at least one blockaddress!");
70 while (!use_empty()) {
71 BlockAddress *BA = cast<BlockAddress>(use_back());
72 BA->replaceAllUsesWith(BlockAddress::get(BA->getFunction(), 0));
73 BA->destroyConstant();
77 assert(getParent() == 0 && "BasicBlock still linked into the program!");
82 void BasicBlock::setParent(Function *parent) {
84 LeakDetector::addGarbageObject(this);
86 // Set Parent=parent, updating instruction symtab entries as appropriate.
87 InstList.setSymTabObject(&Parent, parent);
90 LeakDetector::removeGarbageObject(this);
93 void BasicBlock::removeFromParent() {
94 getParent()->getBasicBlockList().remove(this);
97 void BasicBlock::eraseFromParent() {
98 getParent()->getBasicBlockList().erase(this);
101 /// moveBefore - Unlink this basic block from its current function and
102 /// insert it into the function that MovePos lives in, right before MovePos.
103 void BasicBlock::moveBefore(BasicBlock *MovePos) {
104 MovePos->getParent()->getBasicBlockList().splice(MovePos,
105 getParent()->getBasicBlockList(), this);
108 /// moveAfter - Unlink this basic block from its current function and
109 /// insert it into the function that MovePos lives in, right after MovePos.
110 void BasicBlock::moveAfter(BasicBlock *MovePos) {
111 Function::iterator I = MovePos;
112 MovePos->getParent()->getBasicBlockList().splice(++I,
113 getParent()->getBasicBlockList(), this);
117 TerminatorInst *BasicBlock::getTerminator() {
118 if (InstList.empty()) return 0;
119 return dyn_cast<TerminatorInst>(&InstList.back());
122 const TerminatorInst *BasicBlock::getTerminator() const {
123 if (InstList.empty()) return 0;
124 return dyn_cast<TerminatorInst>(&InstList.back());
127 Instruction* BasicBlock::getFirstNonPHI() {
128 BasicBlock::iterator i = begin();
129 // All valid basic blocks should have a terminator,
130 // which is not a PHINode. If we have an invalid basic
131 // block we'll get an assertion failure when dereferencing
132 // a past-the-end iterator.
133 while (isa<PHINode>(i)) ++i;
137 void BasicBlock::dropAllReferences() {
138 for(iterator I = begin(), E = end(); I != E; ++I)
139 I->dropAllReferences();
142 /// getSinglePredecessor - If this basic block has a single predecessor block,
143 /// return the block, otherwise return a null pointer.
144 BasicBlock *BasicBlock::getSinglePredecessor() {
145 pred_iterator PI = pred_begin(this), E = pred_end(this);
146 if (PI == E) return 0; // No preds.
147 BasicBlock *ThePred = *PI;
149 return (PI == E) ? ThePred : 0 /*multiple preds*/;
152 /// getUniquePredecessor - If this basic block has a unique predecessor block,
153 /// return the block, otherwise return a null pointer.
154 /// Note that unique predecessor doesn't mean single edge, there can be
155 /// multiple edges from the unique predecessor to this block (for example
156 /// a switch statement with multiple cases having the same destination).
157 BasicBlock *BasicBlock::getUniquePredecessor() {
158 pred_iterator PI = pred_begin(this), E = pred_end(this);
159 if (PI == E) return 0; // No preds.
160 BasicBlock *PredBB = *PI;
162 for (;PI != E; ++PI) {
165 // The same predecessor appears multiple times in the predecessor list.
171 /// removePredecessor - This method is used to notify a BasicBlock that the
172 /// specified Predecessor of the block is no longer able to reach it. This is
173 /// actually not used to update the Predecessor list, but is actually used to
174 /// update the PHI nodes that reside in the block. Note that this should be
175 /// called while the predecessor still refers to this block.
177 void BasicBlock::removePredecessor(BasicBlock *Pred,
178 bool DontDeleteUselessPHIs) {
179 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
180 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
181 "removePredecessor: BB is not a predecessor!");
183 if (InstList.empty()) return;
184 PHINode *APN = dyn_cast<PHINode>(&front());
185 if (!APN) return; // Quick exit.
187 // If there are exactly two predecessors, then we want to nuke the PHI nodes
188 // altogether. However, we cannot do this, if this in this case:
191 // %x = phi [X, Loop]
192 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
193 // br Loop ;; %x2 does not dominate all uses
195 // This is because the PHI node input is actually taken from the predecessor
196 // basic block. The only case this can happen is with a self loop, so we
197 // check for this case explicitly now.
199 unsigned max_idx = APN->getNumIncomingValues();
200 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
202 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
204 // Disable PHI elimination!
205 if (this == Other) max_idx = 3;
208 // <= Two predecessors BEFORE I remove one?
209 if (max_idx <= 2 && !DontDeleteUselessPHIs) {
210 // Yup, loop through and nuke the PHI nodes
211 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
212 // Remove the predecessor first.
213 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
215 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
217 if (PN->getOperand(0) != PN)
218 PN->replaceAllUsesWith(PN->getOperand(0));
220 // We are left with an infinite loop with no entries: kill the PHI.
221 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
222 getInstList().pop_front(); // Remove the PHI node
225 // If the PHI node already only had one entry, it got deleted by
226 // removeIncomingValue.
229 // Okay, now we know that we need to remove predecessor #pred_idx from all
230 // PHI nodes. Iterate over each PHI node fixing them up
232 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
234 PN->removeIncomingValue(Pred, false);
235 // If all incoming values to the Phi are the same, we can replace the Phi
238 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
239 PN->replaceAllUsesWith(PNV);
240 PN->eraseFromParent();
247 /// splitBasicBlock - This splits a basic block into two at the specified
248 /// instruction. Note that all instructions BEFORE the specified iterator stay
249 /// as part of the original basic block, an unconditional branch is added to
250 /// the new BB, and the rest of the instructions in the BB are moved to the new
251 /// BB, including the old terminator. This invalidates the iterator.
253 /// Note that this only works on well formed basic blocks (must have a
254 /// terminator), and 'I' must not be the end of instruction list (which would
255 /// cause a degenerate basic block to be formed, having a terminator inside of
256 /// the basic block).
258 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
259 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
260 assert(I != InstList.end() &&
261 "Trying to get me to create degenerate basic block!");
263 BasicBlock *InsertBefore = next(Function::iterator(this))
264 .getNodePtrUnchecked();
265 BasicBlock *New = BasicBlock::Create(getContext(), BBName,
266 getParent(), InsertBefore);
268 // Move all of the specified instructions from the original basic block into
269 // the new basic block.
270 New->getInstList().splice(New->end(), this->getInstList(), I, end());
272 // Add a branch instruction to the newly formed basic block.
273 BranchInst::Create(New, this);
275 // Now we must loop through all of the successors of the New block (which
276 // _were_ the successors of the 'this' block), and update any PHI nodes in
277 // successors. If there were PHI nodes in the successors, then they need to
278 // know that incoming branches will be from New, not from Old.
280 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
281 // Loop over any phi nodes in the basic block, updating the BB field of
282 // incoming values...
283 BasicBlock *Successor = *I;
285 for (BasicBlock::iterator II = Successor->begin();
286 (PN = dyn_cast<PHINode>(II)); ++II) {
287 int IDX = PN->getBasicBlockIndex(this);
289 PN->setIncomingBlock((unsigned)IDX, New);
290 IDX = PN->getBasicBlockIndex(this);