1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/iTerminators.h"
16 #include "llvm/Type.h"
17 #include "llvm/Support/CFG.h"
18 #include "llvm/Constant.h"
19 #include "llvm/iPHINode.h"
20 #include "llvm/SymbolTable.h"
21 #include "Support/LeakDetector.h"
22 #include "SymbolTableListTraitsImpl.h"
27 /// DummyInst - An instance of this class is used to mark the end of the
28 /// instruction list. This is not a real instruction.
29 struct DummyInst : public Instruction {
30 DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd) {
31 // This should not be garbage monitored.
32 LeakDetector::removeGarbageObject(this);
35 virtual Instruction *clone() const {
36 assert(0 && "Cannot clone EOL");abort();
39 virtual const char *getOpcodeName() const { return "*end-of-list-inst*"; }
41 // Methods for support type inquiry through isa, cast, and dyn_cast...
42 static inline bool classof(const DummyInst *) { return true; }
43 static inline bool classof(const Instruction *I) {
44 return I->getOpcode() == OtherOpsEnd;
46 static inline bool classof(const Value *V) {
47 return isa<Instruction>(V) && classof(cast<Instruction>(V));
52 Instruction *ilist_traits<Instruction>::createNode() {
53 return new DummyInst();
55 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
56 return BB->getInstList();
59 // Explicit instantiation of SymbolTableListTraits since some of the methods
60 // are not in the public header file...
61 template class SymbolTableListTraits<Instruction, BasicBlock, Function>;
64 BasicBlock::BasicBlock(const std::string &Name, Function *Parent,
65 BasicBlock *InsertBefore)
66 : Value(Type::LabelTy, Value::BasicBlockVal, Name) {
67 // Initialize the instlist...
68 InstList.setItemParent(this);
70 // Make sure that we get added to a function
71 LeakDetector::addGarbageObject(this);
75 "Cannot insert block before another block with no function!");
76 Parent->getBasicBlockList().insert(InsertBefore, this);
78 Parent->getBasicBlockList().push_back(this);
83 BasicBlock::~BasicBlock() {
84 assert(getParent() == 0 && "BasicBlock still linked into the program!");
89 void BasicBlock::setParent(Function *parent) {
91 LeakDetector::addGarbageObject(this);
93 InstList.setParent(parent);
96 LeakDetector::removeGarbageObject(this);
99 // Specialize setName to take care of symbol table majik
100 void BasicBlock::setName(const std::string &name, SymbolTable *ST) {
102 assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) &&
103 "Invalid symtab argument!");
104 if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this);
105 Value::setName(name);
106 if (P && hasName()) P->getSymbolTable().insert(this);
109 TerminatorInst *BasicBlock::getTerminator() {
110 if (InstList.empty()) return 0;
111 return dyn_cast<TerminatorInst>(&InstList.back());
114 const TerminatorInst *const BasicBlock::getTerminator() const {
115 if (InstList.empty()) return 0;
116 return dyn_cast<TerminatorInst>(&InstList.back());
119 void BasicBlock::dropAllReferences() {
120 for(iterator I = begin(), E = end(); I != E; ++I)
121 I->dropAllReferences();
124 // removePredecessor - This method is used to notify a BasicBlock that the
125 // specified Predecessor of the block is no longer able to reach it. This is
126 // actually not used to update the Predecessor list, but is actually used to
127 // update the PHI nodes that reside in the block. Note that this should be
128 // called while the predecessor still refers to this block.
130 void BasicBlock::removePredecessor(BasicBlock *Pred) {
131 assert(find(pred_begin(this), pred_end(this), Pred) != pred_end(this) &&
132 "removePredecessor: BB is not a predecessor!");
133 if (!isa<PHINode>(front())) return; // Quick exit.
135 pred_iterator PI(pred_begin(this)), EI(pred_end(this));
138 // Loop over the rest of the predecessors until we run out, or until we find
139 // out that there are more than 2 predecessors.
140 for (max_idx = 0; PI != EI && max_idx < 3; ++PI, ++max_idx) /*empty*/;
142 // If there are exactly two predecessors, then we want to nuke the PHI nodes
143 // altogether. We cannot do this, however if this in this case however:
146 // %x = phi [X, Loop]
147 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
148 // br Loop ;; %x2 does not dominate all uses
150 // This is because the PHI node input is actually taken from the predecessor
151 // basic block. The only case this can happen is with a self loop, so we
152 // check for this case explicitly now.
154 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
156 PI = pred_begin(this);
157 BasicBlock *Other = *PI == Pred ? *++PI : *PI;
159 // Disable PHI elimination!
160 if (this == Other) max_idx = 3;
163 if (max_idx <= 2) { // <= Two predecessors BEFORE I remove one?
164 // Yup, loop through and nuke the PHI nodes
165 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
166 PN->removeIncomingValue(Pred); // Remove the predecessor first...
168 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
170 if (PN->getOperand(0) != PN)
171 PN->replaceAllUsesWith(PN->getOperand(0));
173 // We are left with an infinite loop with no entries: kill the PHI.
174 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
175 getInstList().pop_front(); // Remove the PHI node
178 // If the PHI node already only had one entry, it got deleted by
179 // removeIncomingValue.
182 // Okay, now we know that we need to remove predecessor #pred_idx from all
183 // PHI nodes. Iterate over each PHI node fixing them up
184 for (iterator II = begin(); PHINode *PN = dyn_cast<PHINode>(II); ++II)
185 PN->removeIncomingValue(Pred);
190 // splitBasicBlock - This splits a basic block into two at the specified
191 // instruction. Note that all instructions BEFORE the specified iterator stay
192 // as part of the original basic block, an unconditional branch is added to
193 // the new BB, and the rest of the instructions in the BB are moved to the new
194 // BB, including the old terminator. This invalidates the iterator.
196 // Note that this only works on well formed basic blocks (must have a
197 // terminator), and 'I' must not be the end of instruction list (which would
198 // cause a degenerate basic block to be formed, having a terminator inside of
201 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
202 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
203 assert(I != InstList.end() &&
204 "Trying to get me to create degenerate basic block!");
206 BasicBlock *New = new BasicBlock(BBName, getParent(), getNext());
208 // Move all of the specified instructions from the original basic block into
209 // the new basic block.
210 New->getInstList().splice(New->end(), this->getInstList(), I, end());
212 // Add a branch instruction to the newly formed basic block.
213 new BranchInst(New, this);
215 // Now we must loop through all of the successors of the New block (which
216 // _were_ the successors of the 'this' block), and update any PHI nodes in
217 // successors. If there were PHI nodes in the successors, then they need to
218 // know that incoming branches will be from New, not from Old.
220 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
221 // Loop over any phi nodes in the basic block, updating the BB field of
222 // incoming values...
223 BasicBlock *Successor = *I;
224 for (BasicBlock::iterator II = Successor->begin();
225 PHINode *PN = dyn_cast<PHINode>(II); ++II) {
226 int IDX = PN->getBasicBlockIndex(this);
228 PN->setIncomingBlock((unsigned)IDX, New);
229 IDX = PN->getBasicBlockIndex(this);