1 //===-- BasicBlock.cpp - Implement BasicBlock related functions --*- C++ -*--=//
3 // This file implements the BasicBlock class for the VMCore library.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/BasicBlock.h"
8 #include "llvm/iTerminators.h"
10 #include "llvm/Support/CFG.h"
11 #include "llvm/Constant.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/SymbolTable.h"
14 #include "SymbolTableListTraitsImpl.h"
17 // DummyInst - An instance of this class is used to mark the end of the
18 // instruction list. This is not a real instruction.
20 struct DummyInst : public Instruction {
21 DummyInst() : Instruction(Type::VoidTy, NumOtherOps) {}
23 virtual Instruction *clone() const {
24 assert(0 && "Cannot clone EOL");abort();
27 virtual const char *getOpcodeName() const { return "*end-of-list-inst*"; }
29 // Methods for support type inquiry through isa, cast, and dyn_cast...
30 static inline bool classof(const DummyInst *) { return true; }
31 static inline bool classof(const Instruction *I) {
32 return I->getOpcode() == NumOtherOps;
34 static inline bool classof(const Value *V) {
35 return isa<Instruction>(V) && classof(cast<Instruction>(V));
39 Instruction *ilist_traits<Instruction>::createNode() {
40 return new DummyInst();
42 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
43 return BB->getInstList();
46 // Explicit instantiation of SymbolTableListTraits since some of the methods
47 // are not in the public header file...
48 template SymbolTableListTraits<Instruction, BasicBlock, Function>;
51 // BasicBlock ctor - If the function parameter is specified, the basic block is
52 // automatically inserted at the end of the function.
54 BasicBlock::BasicBlock(const std::string &name, Function *Parent)
55 : Value(Type::LabelTy, Value::BasicBlockVal, name) {
56 // Initialize the instlist...
57 InstList.setItemParent(this);
60 Parent->getBasicBlockList().push_back(this);
63 BasicBlock::~BasicBlock() {
68 void BasicBlock::setParent(Function *parent) {
69 InstList.setParent(parent);
72 // Specialize setName to take care of symbol table majik
73 void BasicBlock::setName(const std::string &name, SymbolTable *ST) {
75 assert((ST == 0 || (!getParent() || ST == getParent()->getSymbolTable())) &&
76 "Invalid symtab argument!");
77 if ((P = getParent()) && hasName()) P->getSymbolTable()->remove(this);
79 if (P && hasName()) P->getSymbolTable()->insert(this);
82 TerminatorInst *BasicBlock::getTerminator() {
83 if (InstList.empty()) return 0;
84 return dyn_cast<TerminatorInst>(&InstList.back());
87 const TerminatorInst *const BasicBlock::getTerminator() const {
88 if (InstList.empty()) return 0;
89 return dyn_cast<TerminatorInst>(&InstList.back());
92 void BasicBlock::dropAllReferences() {
93 for(iterator I = begin(), E = end(); I != E; ++I)
94 I->dropAllReferences();
97 // hasConstantReferences() - This predicate is true if there is a
98 // reference to this basic block in the constant pool for this method. For
99 // example, if a block is reached through a switch table, that table resides
100 // in the constant pool, and the basic block is reference from it.
102 bool BasicBlock::hasConstantReferences() const {
103 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I)
104 if (::isa<Constant>((Value*)*I))
110 // removePredecessor - This method is used to notify a BasicBlock that the
111 // specified Predecessor of the block is no longer able to reach it. This is
112 // actually not used to update the Predecessor list, but is actually used to
113 // update the PHI nodes that reside in the block. Note that this should be
114 // called while the predecessor still refers to this block.
116 void BasicBlock::removePredecessor(BasicBlock *Pred) {
117 assert(find(pred_begin(this), pred_end(this), Pred) != pred_end(this) &&
118 "removePredecessor: BB is not a predecessor!");
119 if (!isa<PHINode>(front())) return; // Quick exit.
121 pred_iterator PI(pred_begin(this)), EI(pred_end(this));
124 // Loop over the rest of the predecessors until we run out, or until we find
125 // out that there are more than 2 predecessors.
126 for (max_idx = 0; PI != EI && max_idx < 3; ++PI, ++max_idx) /*empty*/;
128 // If there are exactly two predecessors, then we want to nuke the PHI nodes
129 // altogether. We cannot do this, however if this in this case however:
132 // %x = phi [X, Loop]
133 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
134 // br Loop ;; %x2 does not dominate all uses
136 // This is because the PHI node input is actually taken from the predecessor
137 // basic block. The only case this can happen is with a self loop, so we
138 // check for this case explicitly now.
140 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
142 PI = pred_begin(this);
143 BasicBlock *Other = *PI == Pred ? *++PI : *PI;
145 // Disable PHI elimination!
146 if (this == Other) max_idx = 3;
149 if (max_idx <= 2) { // <= Two predecessors BEFORE I remove one?
150 // Yup, loop through and nuke the PHI nodes
151 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
152 PN->removeIncomingValue(Pred); // Remove the predecessor first...
154 assert(PN->getNumIncomingValues() == max_idx-1 &&
155 "PHI node shouldn't have this many values!!!");
157 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
159 PN->replaceAllUsesWith(PN->getOperand(0));
160 else // Otherwise there are no incoming values/edges, replace with dummy
161 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
162 getInstList().pop_front(); // Remove the PHI node
165 // Okay, now we know that we need to remove predecessor #pred_idx from all
166 // PHI nodes. Iterate over each PHI node fixing them up
167 for (iterator II = begin(); PHINode *PN = dyn_cast<PHINode>(&*II); ++II)
168 PN->removeIncomingValue(Pred);
173 // splitBasicBlock - This splits a basic block into two at the specified
174 // instruction. Note that all instructions BEFORE the specified iterator stay
175 // as part of the original basic block, an unconditional branch is added to
176 // the new BB, and the rest of the instructions in the BB are moved to the new
177 // BB, including the old terminator. This invalidates the iterator.
179 // Note that this only works on well formed basic blocks (must have a
180 // terminator), and 'I' must not be the end of instruction list (which would
181 // cause a degenerate basic block to be formed, having a terminator inside of
184 BasicBlock *BasicBlock::splitBasicBlock(iterator I) {
185 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
186 assert(I != InstList.end() &&
187 "Trying to get me to create degenerate basic block!");
189 BasicBlock *New = new BasicBlock("", getParent());
191 // Go from the end of the basic block through to the iterator pointer, moving
192 // to the new basic block...
193 Instruction *Inst = 0;
195 iterator EndIt = end();
196 Inst = InstList.remove(--EndIt); // Remove from end
197 New->InstList.push_front(Inst); // Add to front
198 } while (Inst != &*I); // Loop until we move the specified instruction.
200 // Add a branch instruction to the newly formed basic block.
201 InstList.push_back(new BranchInst(New));
203 // Now we must loop through all of the successors of the New block (which
204 // _were_ the successors of the 'this' block), and update any PHI nodes in
205 // successors. If there were PHI nodes in the successors, then they need to
206 // know that incoming branches will be from New, not from Old.
208 for (BasicBlock::succ_iterator I = succ_begin(New), E = succ_end(New);
210 // Loop over any phi nodes in the basic block, updating the BB field of
211 // incoming values...
212 BasicBlock *Successor = *I;
213 for (BasicBlock::iterator II = Successor->begin();
214 PHINode *PN = dyn_cast<PHINode>(&*II); ++II) {
215 int IDX = PN->getBasicBlockIndex(this);
217 PN->setIncomingBlock((unsigned)IDX, New);
218 IDX = PN->getBasicBlockIndex(this);