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"
25 // DummyInst - An instance of this class is used to mark the end of the
26 // instruction list. This is not a real instruction.
28 struct DummyInst : public Instruction {
29 DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd) {
30 // This should not be garbage monitored.
31 LeakDetector::removeGarbageObject(this);
34 virtual Instruction *clone() const {
35 assert(0 && "Cannot clone EOL");abort();
38 virtual const char *getOpcodeName() const { return "*end-of-list-inst*"; }
40 // Methods for support type inquiry through isa, cast, and dyn_cast...
41 static inline bool classof(const DummyInst *) { return true; }
42 static inline bool classof(const Instruction *I) {
43 return I->getOpcode() == OtherOpsEnd;
45 static inline bool classof(const Value *V) {
46 return isa<Instruction>(V) && classof(cast<Instruction>(V));
50 Instruction *ilist_traits<Instruction>::createNode() {
51 return new DummyInst();
53 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
54 return BB->getInstList();
57 // Explicit instantiation of SymbolTableListTraits since some of the methods
58 // are not in the public header file...
59 template class SymbolTableListTraits<Instruction, BasicBlock, Function>;
62 // BasicBlock ctor - If the function parameter is specified, the basic block is
63 // automatically inserted at the end of the function.
65 BasicBlock::BasicBlock(const std::string &name, Function *Parent)
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);
74 Parent->getBasicBlockList().push_back(this);
77 /// BasicBlock ctor - If the InsertBefore parameter is specified, the basic
78 /// block is automatically inserted right before the specified block.
80 BasicBlock::BasicBlock(const std::string &Name, BasicBlock *InsertBefore)
81 : Value(Type::LabelTy, Value::BasicBlockVal, Name) {
82 // Initialize the instlist...
83 InstList.setItemParent(this);
85 // Make sure that we get added to a function
86 LeakDetector::addGarbageObject(this);
89 assert(InsertBefore->getParent() &&
90 "Cannot insert block before another block that is not embedded into"
92 InsertBefore->getParent()->getBasicBlockList().insert(InsertBefore, this);
97 BasicBlock::~BasicBlock() {
102 void BasicBlock::setParent(Function *parent) {
104 LeakDetector::addGarbageObject(this);
106 InstList.setParent(parent);
109 LeakDetector::removeGarbageObject(this);
112 // Specialize setName to take care of symbol table majik
113 void BasicBlock::setName(const std::string &name, SymbolTable *ST) {
115 assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) &&
116 "Invalid symtab argument!");
117 if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this);
118 Value::setName(name);
119 if (P && hasName()) P->getSymbolTable().insert(this);
122 TerminatorInst *BasicBlock::getTerminator() {
123 if (InstList.empty()) return 0;
124 return dyn_cast<TerminatorInst>(&InstList.back());
127 const TerminatorInst *const BasicBlock::getTerminator() const {
128 if (InstList.empty()) return 0;
129 return dyn_cast<TerminatorInst>(&InstList.back());
132 void BasicBlock::dropAllReferences() {
133 for(iterator I = begin(), E = end(); I != E; ++I)
134 I->dropAllReferences();
137 // hasConstantReferences() - This predicate is true if there is a
138 // reference to this basic block in the constant pool for this method. For
139 // example, if a block is reached through a switch table, that table resides
140 // in the constant pool, and the basic block is reference from it.
142 bool BasicBlock::hasConstantReferences() const {
143 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I)
144 if (::isa<Constant>((Value*)*I))
150 // removePredecessor - This method is used to notify a BasicBlock that the
151 // specified Predecessor of the block is no longer able to reach it. This is
152 // actually not used to update the Predecessor list, but is actually used to
153 // update the PHI nodes that reside in the block. Note that this should be
154 // called while the predecessor still refers to this block.
156 void BasicBlock::removePredecessor(BasicBlock *Pred) {
157 assert(find(pred_begin(this), pred_end(this), Pred) != pred_end(this) &&
158 "removePredecessor: BB is not a predecessor!");
159 if (!isa<PHINode>(front())) return; // Quick exit.
161 pred_iterator PI(pred_begin(this)), EI(pred_end(this));
164 // Loop over the rest of the predecessors until we run out, or until we find
165 // out that there are more than 2 predecessors.
166 for (max_idx = 0; PI != EI && max_idx < 3; ++PI, ++max_idx) /*empty*/;
168 // If there are exactly two predecessors, then we want to nuke the PHI nodes
169 // altogether. We cannot do this, however if this in this case however:
172 // %x = phi [X, Loop]
173 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
174 // br Loop ;; %x2 does not dominate all uses
176 // This is because the PHI node input is actually taken from the predecessor
177 // basic block. The only case this can happen is with a self loop, so we
178 // check for this case explicitly now.
180 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
182 PI = pred_begin(this);
183 BasicBlock *Other = *PI == Pred ? *++PI : *PI;
185 // Disable PHI elimination!
186 if (this == Other) max_idx = 3;
189 if (max_idx <= 2) { // <= Two predecessors BEFORE I remove one?
190 // Yup, loop through and nuke the PHI nodes
191 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
192 PN->removeIncomingValue(Pred); // Remove the predecessor first...
194 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
196 if (PN->getOperand(0) != PN)
197 PN->replaceAllUsesWith(PN->getOperand(0));
199 // We are left with an infinite loop with no entries: kill the PHI.
200 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
201 getInstList().pop_front(); // Remove the PHI node
204 // If the PHI node already only had one entry, it got deleted by
205 // removeIncomingValue.
208 // Okay, now we know that we need to remove predecessor #pred_idx from all
209 // PHI nodes. Iterate over each PHI node fixing them up
210 for (iterator II = begin(); PHINode *PN = dyn_cast<PHINode>(II); ++II)
211 PN->removeIncomingValue(Pred);
216 // splitBasicBlock - This splits a basic block into two at the specified
217 // instruction. Note that all instructions BEFORE the specified iterator stay
218 // as part of the original basic block, an unconditional branch is added to
219 // the new BB, and the rest of the instructions in the BB are moved to the new
220 // BB, including the old terminator. This invalidates the iterator.
222 // Note that this only works on well formed basic blocks (must have a
223 // terminator), and 'I' must not be the end of instruction list (which would
224 // cause a degenerate basic block to be formed, having a terminator inside of
227 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
228 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
229 assert(I != InstList.end() &&
230 "Trying to get me to create degenerate basic block!");
232 BasicBlock *New = new BasicBlock(BBName, getParent());
234 // Go from the end of the basic block through to the iterator pointer, moving
235 // to the new basic block...
236 Instruction *Inst = 0;
238 iterator EndIt = end();
239 Inst = InstList.remove(--EndIt); // Remove from end
240 New->InstList.push_front(Inst); // Add to front
241 } while (Inst != &*I); // Loop until we move the specified instruction.
243 // Add a branch instruction to the newly formed basic block.
244 InstList.push_back(new BranchInst(New));
246 // Now we must loop through all of the successors of the New block (which
247 // _were_ the successors of the 'this' block), and update any PHI nodes in
248 // successors. If there were PHI nodes in the successors, then they need to
249 // know that incoming branches will be from New, not from Old.
251 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
252 // Loop over any phi nodes in the basic block, updating the BB field of
253 // incoming values...
254 BasicBlock *Successor = *I;
255 for (BasicBlock::iterator II = Successor->begin();
256 PHINode *PN = dyn_cast<PHINode>(II); ++II) {
257 int IDX = PN->getBasicBlockIndex(this);
259 PN->setIncomingBlock((unsigned)IDX, New);
260 IDX = PN->getBasicBlockIndex(this);