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/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 // allocate space for exactly zero operands
39 void *operator new(size_t s) {
40 return User::operator new(s, 0);
42 DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
43 // This should not be garbage monitored.
44 LeakDetector::removeGarbageObject(this);
47 Instruction *clone() const {
48 assert(0 && "Cannot clone EOL");abort();
51 const char *getOpcodeName() const { return "*end-of-list-inst*"; }
53 // Methods for support type inquiry through isa, cast, and dyn_cast...
54 static inline bool classof(const DummyInst *) { return true; }
55 static inline bool classof(const Instruction *I) {
56 return I->getOpcode() == OtherOpsEnd;
58 static inline bool classof(const Value *V) {
59 return isa<Instruction>(V) && classof(cast<Instruction>(V));
64 Instruction *ilist_traits<Instruction>::createSentinel() {
65 return new DummyInst();
67 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
68 return BB->getInstList();
71 // Explicit instantiation of SymbolTableListTraits since some of the methods
72 // are not in the public header file...
73 template class SymbolTableListTraits<Instruction, BasicBlock>;
76 BasicBlock::BasicBlock(const std::string &Name, Function *NewParent,
77 BasicBlock *InsertBefore)
78 : Value(Type::LabelTy, Value::BasicBlockVal), Parent(0) {
80 // Make sure that we get added to a function
81 LeakDetector::addGarbageObject(this);
85 "Cannot insert block before another block with no function!");
86 NewParent->getBasicBlockList().insert(InsertBefore, this);
87 } else if (NewParent) {
88 NewParent->getBasicBlockList().push_back(this);
95 BasicBlock::~BasicBlock() {
96 assert(getParent() == 0 && "BasicBlock still linked into the program!");
101 void BasicBlock::setParent(Function *parent) {
103 LeakDetector::addGarbageObject(this);
105 // Set Parent=parent, updating instruction symtab entries as appropriate.
106 InstList.setSymTabObject(&Parent, parent);
109 LeakDetector::removeGarbageObject(this);
112 void BasicBlock::removeFromParent() {
113 getParent()->getBasicBlockList().remove(this);
116 void BasicBlock::eraseFromParent() {
117 getParent()->getBasicBlockList().erase(this);
120 /// moveBefore - Unlink this basic block from its current function and
121 /// insert it into the function that MovePos lives in, right before MovePos.
122 void BasicBlock::moveBefore(BasicBlock *MovePos) {
123 MovePos->getParent()->getBasicBlockList().splice(MovePos,
124 getParent()->getBasicBlockList(), this);
127 /// moveAfter - Unlink this basic block from its current function and
128 /// insert it into the function that MovePos lives in, right after MovePos.
129 void BasicBlock::moveAfter(BasicBlock *MovePos) {
130 Function::iterator I = MovePos;
131 MovePos->getParent()->getBasicBlockList().splice(++I,
132 getParent()->getBasicBlockList(), this);
136 TerminatorInst *BasicBlock::getTerminator() {
137 if (InstList.empty()) return 0;
138 return dyn_cast<TerminatorInst>(&InstList.back());
141 const TerminatorInst *BasicBlock::getTerminator() const {
142 if (InstList.empty()) return 0;
143 return dyn_cast<TerminatorInst>(&InstList.back());
146 Instruction* BasicBlock::getFirstNonPHI()
148 BasicBlock::iterator i = begin();
149 // All valid basic blocks should have a terminator,
150 // which is not a PHINode. If we have invalid basic
151 // block we'll get assert when dereferencing past-the-end
153 while (isa<PHINode>(i)) ++i;
157 void BasicBlock::dropAllReferences() {
158 for(iterator I = begin(), E = end(); I != E; ++I)
159 I->dropAllReferences();
162 /// getSinglePredecessor - If this basic block has a single predecessor block,
163 /// return the block, otherwise return a null pointer.
164 BasicBlock *BasicBlock::getSinglePredecessor() {
165 pred_iterator PI = pred_begin(this), E = pred_end(this);
166 if (PI == E) return 0; // No preds.
167 BasicBlock *ThePred = *PI;
169 return (PI == E) ? ThePred : 0 /*multiple preds*/;
172 /// removePredecessor - This method is used to notify a BasicBlock that the
173 /// specified Predecessor of the block is no longer able to reach it. This is
174 /// actually not used to update the Predecessor list, but is actually used to
175 /// update the PHI nodes that reside in the block. Note that this should be
176 /// called while the predecessor still refers to this block.
178 void BasicBlock::removePredecessor(BasicBlock *Pred,
179 bool DontDeleteUselessPHIs) {
180 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
181 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
182 "removePredecessor: BB is not a predecessor!");
184 if (InstList.empty()) return;
185 PHINode *APN = dyn_cast<PHINode>(&front());
186 if (!APN) return; // Quick exit.
188 // If there are exactly two predecessors, then we want to nuke the PHI nodes
189 // altogether. However, we cannot do this, if this in this case:
192 // %x = phi [X, Loop]
193 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
194 // br Loop ;; %x2 does not dominate all uses
196 // This is because the PHI node input is actually taken from the predecessor
197 // basic block. The only case this can happen is with a self loop, so we
198 // check for this case explicitly now.
200 unsigned max_idx = APN->getNumIncomingValues();
201 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
203 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
205 // Disable PHI elimination!
206 if (this == Other) max_idx = 3;
209 // <= Two predecessors BEFORE I remove one?
210 if (max_idx <= 2 && !DontDeleteUselessPHIs) {
211 // Yup, loop through and nuke the PHI nodes
212 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
213 // Remove the predecessor first.
214 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
216 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
218 if (PN->getOperand(0) != PN)
219 PN->replaceAllUsesWith(PN->getOperand(0));
221 // We are left with an infinite loop with no entries: kill the PHI.
222 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
223 getInstList().pop_front(); // Remove the PHI node
226 // If the PHI node already only had one entry, it got deleted by
227 // removeIncomingValue.
230 // Okay, now we know that we need to remove predecessor #pred_idx from all
231 // PHI nodes. Iterate over each PHI node fixing them up
233 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
235 PN->removeIncomingValue(Pred, false);
236 // If all incoming values to the Phi are the same, we can replace the Phi
239 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
240 PN->replaceAllUsesWith(PNV);
241 PN->eraseFromParent();
248 /// splitBasicBlock - This splits a basic block into two at the specified
249 /// instruction. Note that all instructions BEFORE the specified iterator stay
250 /// as part of the original basic block, an unconditional branch is added to
251 /// the new BB, and the rest of the instructions in the BB are moved to the new
252 /// BB, including the old terminator. This invalidates the iterator.
254 /// Note that this only works on well formed basic blocks (must have a
255 /// terminator), and 'I' must not be the end of instruction list (which would
256 /// cause a degenerate basic block to be formed, having a terminator inside of
257 /// the basic block).
259 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
260 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
261 assert(I != InstList.end() &&
262 "Trying to get me to create degenerate basic block!");
264 BasicBlock *New = BasicBlock::Create(BBName, getParent(), getNext());
266 // Move all of the specified instructions from the original basic block into
267 // the new basic block.
268 New->getInstList().splice(New->end(), this->getInstList(), I, end());
270 // Add a branch instruction to the newly formed basic block.
271 BranchInst::Create(New, this);
273 // Now we must loop through all of the successors of the New block (which
274 // _were_ the successors of the 'this' block), and update any PHI nodes in
275 // successors. If there were PHI nodes in the successors, then they need to
276 // know that incoming branches will be from New, not from Old.
278 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
279 // Loop over any phi nodes in the basic block, updating the BB field of
280 // incoming values...
281 BasicBlock *Successor = *I;
283 for (BasicBlock::iterator II = Successor->begin();
284 (PN = dyn_cast<PHINode>(II)); ++II) {
285 int IDX = PN->getBasicBlockIndex(this);
287 PN->setIncomingBlock((unsigned)IDX, New);
288 IDX = PN->getBasicBlockIndex(this);