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/Constants.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Type.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/Support/LeakDetector.h"
20 #include "llvm/Support/Compiler.h"
21 #include "SymbolTableListTraitsImpl.h"
25 inline ValueSymbolTable *
26 ilist_traits<Instruction>::getSymTab(BasicBlock *BB) {
28 if (Function *F = BB->getParent())
29 return &F->getValueSymbolTable();
35 /// DummyInst - An instance of this class is used to mark the end of the
36 /// instruction list. This is not a real instruction.
37 struct VISIBILITY_HIDDEN DummyInst : public Instruction {
38 DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
39 // This should not be garbage monitored.
40 LeakDetector::removeGarbageObject(this);
43 Instruction *clone() const {
44 assert(0 && "Cannot clone EOL");abort();
47 const char *getOpcodeName() const { return "*end-of-list-inst*"; }
49 // Methods for support type inquiry through isa, cast, and dyn_cast...
50 static inline bool classof(const DummyInst *) { return true; }
51 static inline bool classof(const Instruction *I) {
52 return I->getOpcode() == OtherOpsEnd;
54 static inline bool classof(const Value *V) {
55 return isa<Instruction>(V) && classof(cast<Instruction>(V));
60 Instruction *ilist_traits<Instruction>::createSentinel() {
61 return new DummyInst();
63 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
64 return BB->getInstList();
67 // Explicit instantiation of SymbolTableListTraits since some of the methods
68 // are not in the public header file...
69 template class SymbolTableListTraits<Instruction, BasicBlock>;
72 BasicBlock::BasicBlock(const std::string &Name, Function *NewParent,
73 BasicBlock *InsertBefore)
74 : Value(Type::LabelTy, Value::BasicBlockVal), Parent(0) {
76 // Make sure that we get added to a function
77 LeakDetector::addGarbageObject(this);
81 "Cannot insert block before another block with no function!");
82 NewParent->getBasicBlockList().insert(InsertBefore, this);
83 } else if (NewParent) {
84 NewParent->getBasicBlockList().push_back(this);
91 BasicBlock::~BasicBlock() {
92 assert(getParent() == 0 && "BasicBlock still linked into the program!");
97 void BasicBlock::setParent(Function *parent) {
99 LeakDetector::addGarbageObject(this);
101 // Set Parent=parent, updating instruction symtab entries as appropriate.
102 InstList.setSymTabObject(&Parent, parent);
105 LeakDetector::removeGarbageObject(this);
108 void BasicBlock::removeFromParent() {
109 getParent()->getBasicBlockList().remove(this);
112 void BasicBlock::eraseFromParent() {
113 getParent()->getBasicBlockList().erase(this);
116 /// moveBefore - Unlink this basic block from its current function and
117 /// insert it into the function that MovePos lives in, right before MovePos.
118 void BasicBlock::moveBefore(BasicBlock *MovePos) {
119 MovePos->getParent()->getBasicBlockList().splice(MovePos,
120 getParent()->getBasicBlockList(), this);
123 /// moveAfter - Unlink this basic block from its current function and
124 /// insert it into the function that MovePos lives in, right after MovePos.
125 void BasicBlock::moveAfter(BasicBlock *MovePos) {
126 Function::iterator I = MovePos;
127 MovePos->getParent()->getBasicBlockList().splice(++I,
128 getParent()->getBasicBlockList(), this);
132 TerminatorInst *BasicBlock::getTerminator() {
133 if (InstList.empty()) return 0;
134 return dyn_cast<TerminatorInst>(&InstList.back());
137 const TerminatorInst *const BasicBlock::getTerminator() const {
138 if (InstList.empty()) return 0;
139 return dyn_cast<TerminatorInst>(&InstList.back());
142 Instruction* BasicBlock::getFirstNonPHI()
144 BasicBlock::iterator i = begin();
145 // All valid basic blocks should have a terminator,
146 // which is not a PHINode. If we have invalid basic
147 // block we'll get assert when dereferencing past-the-end
149 while (isa<PHINode>(i)) ++i;
153 void BasicBlock::dropAllReferences() {
154 for(iterator I = begin(), E = end(); I != E; ++I)
155 I->dropAllReferences();
158 /// getSinglePredecessor - If this basic block has a single predecessor block,
159 /// return the block, otherwise return a null pointer.
160 BasicBlock *BasicBlock::getSinglePredecessor() {
161 pred_iterator PI = pred_begin(this), E = pred_end(this);
162 if (PI == E) return 0; // No preds.
163 BasicBlock *ThePred = *PI;
165 return (PI == E) ? ThePred : 0 /*multiple preds*/;
168 /// removePredecessor - This method is used to notify a BasicBlock that the
169 /// specified Predecessor of the block is no longer able to reach it. This is
170 /// actually not used to update the Predecessor list, but is actually used to
171 /// update the PHI nodes that reside in the block. Note that this should be
172 /// called while the predecessor still refers to this block.
174 void BasicBlock::removePredecessor(BasicBlock *Pred,
175 bool DontDeleteUselessPHIs) {
176 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
177 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
178 "removePredecessor: BB is not a predecessor!");
180 if (InstList.empty()) return;
181 PHINode *APN = dyn_cast<PHINode>(&front());
182 if (!APN) return; // Quick exit.
184 // If there are exactly two predecessors, then we want to nuke the PHI nodes
185 // altogether. However, we cannot do this, if this in this case:
188 // %x = phi [X, Loop]
189 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
190 // br Loop ;; %x2 does not dominate all uses
192 // This is because the PHI node input is actually taken from the predecessor
193 // basic block. The only case this can happen is with a self loop, so we
194 // check for this case explicitly now.
196 unsigned max_idx = APN->getNumIncomingValues();
197 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
199 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
201 // Disable PHI elimination!
202 if (this == Other) max_idx = 3;
205 // <= Two predecessors BEFORE I remove one?
206 if (max_idx <= 2 && !DontDeleteUselessPHIs) {
207 // Yup, loop through and nuke the PHI nodes
208 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
209 // Remove the predecessor first.
210 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
212 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
214 if (PN->getOperand(0) != PN)
215 PN->replaceAllUsesWith(PN->getOperand(0));
217 // We are left with an infinite loop with no entries: kill the PHI.
218 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
219 getInstList().pop_front(); // Remove the PHI node
222 // If the PHI node already only had one entry, it got deleted by
223 // removeIncomingValue.
226 // Okay, now we know that we need to remove predecessor #pred_idx from all
227 // PHI nodes. Iterate over each PHI node fixing them up
229 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
231 PN->removeIncomingValue(Pred, false);
232 // If all incoming values to the Phi are the same, we can replace the Phi
235 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
236 PN->replaceAllUsesWith(PNV);
237 PN->eraseFromParent();
244 /// splitBasicBlock - This splits a basic block into two at the specified
245 /// instruction. Note that all instructions BEFORE the specified iterator stay
246 /// as part of the original basic block, an unconditional branch is added to
247 /// the new BB, and the rest of the instructions in the BB are moved to the new
248 /// BB, including the old terminator. This invalidates the iterator.
250 /// Note that this only works on well formed basic blocks (must have a
251 /// terminator), and 'I' must not be the end of instruction list (which would
252 /// cause a degenerate basic block to be formed, having a terminator inside of
253 /// the basic block).
255 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
256 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
257 assert(I != InstList.end() &&
258 "Trying to get me to create degenerate basic block!");
260 BasicBlock *New = new BasicBlock(BBName, getParent(), getNext());
262 // Move all of the specified instructions from the original basic block into
263 // the new basic block.
264 New->getInstList().splice(New->end(), this->getInstList(), I, end());
266 // Add a branch instruction to the newly formed basic block.
267 new BranchInst(New, this);
269 // Now we must loop through all of the successors of the New block (which
270 // _were_ the successors of the 'this' block), and update any PHI nodes in
271 // successors. If there were PHI nodes in the successors, then they need to
272 // know that incoming branches will be from New, not from Old.
274 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
275 // Loop over any phi nodes in the basic block, updating the BB field of
276 // incoming values...
277 BasicBlock *Successor = *I;
279 for (BasicBlock::iterator II = Successor->begin();
280 (PN = dyn_cast<PHINode>(II)); ++II) {
281 int IDX = PN->getBasicBlockIndex(this);
283 PN->setIncomingBlock((unsigned)IDX, New);
284 IDX = PN->getBasicBlockIndex(this);