Eliminate duplicate or unneccesary #include's
[oota-llvm.git] / lib / VMCore / BasicBlock.cpp
1 //===-- BasicBlock.cpp - Implement BasicBlock related functions --*- C++ -*--=//
2 //
3 // This file implements the BasicBlock class for the VMCore library.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "ValueHolderImpl.h"
8 #include "llvm/iTerminators.h"
9 #include "llvm/Type.h"
10 #include "llvm/Support/CFG.h"
11 #include "llvm/iPHINode.h"
12 #include "llvm/CodeGen/MachineInstr.h"
13
14 // Instantiate Templates - This ugliness is the price we have to pay
15 // for having a ValueHolderImpl.h file seperate from ValueHolder.h!  :(
16 //
17 template class ValueHolder<Instruction, BasicBlock, Function>;
18
19 BasicBlock::BasicBlock(const std::string &name, Function *Parent)
20   : Value(Type::LabelTy, Value::BasicBlockVal, name), InstList(this, 0),
21     machineInstrVec(new MachineCodeForBasicBlock) {
22   if (Parent)
23     Parent->getBasicBlocks().push_back(this);
24 }
25
26 BasicBlock::~BasicBlock() {
27   dropAllReferences();
28   InstList.delete_all();
29   delete machineInstrVec;
30 }
31
32 // Specialize setName to take care of symbol table majik
33 void BasicBlock::setName(const std::string &name, SymbolTable *ST) {
34   Function *P;
35   assert((ST == 0 || (!getParent() || ST == getParent()->getSymbolTable())) &&
36          "Invalid symtab argument!");
37   if ((P = getParent()) && hasName()) P->getSymbolTable()->remove(this);
38   Value::setName(name);
39   if (P && hasName()) P->getSymbolTable()->insert(this);
40 }
41
42 void BasicBlock::setParent(Function *parent) { 
43   if (getParent() && hasName())
44     getParent()->getSymbolTable()->remove(this);
45
46   InstList.setParent(parent);
47
48   if (getParent() && hasName())
49     getParent()->getSymbolTableSure()->insert(this);
50 }
51
52 TerminatorInst *BasicBlock::getTerminator() {
53   if (InstList.empty()) return 0;
54   Instruction *T = InstList.back();
55   if (isa<TerminatorInst>(T)) return cast<TerminatorInst>(T);
56   return 0;
57 }
58
59 const TerminatorInst *const BasicBlock::getTerminator() const {
60   if (InstList.empty()) return 0;
61   if (const TerminatorInst *TI = dyn_cast<TerminatorInst>(InstList.back()))
62     return TI;
63   return 0;
64 }
65
66 void BasicBlock::dropAllReferences() {
67   for_each(InstList.begin(), InstList.end(), 
68            std::mem_fun(&Instruction::dropAllReferences));
69 }
70
71 // hasConstantReferences() - This predicate is true if there is a 
72 // reference to this basic block in the constant pool for this method.  For
73 // example, if a block is reached through a switch table, that table resides
74 // in the constant pool, and the basic block is reference from it.
75 //
76 bool BasicBlock::hasConstantReferences() const {
77   for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I)
78     if (::isa<Constant>((Value*)*I))
79       return true;
80
81   return false;
82 }
83
84 // removePredecessor - This method is used to notify a BasicBlock that the
85 // specified Predecessor of the block is no longer able to reach it.  This is
86 // actually not used to update the Predecessor list, but is actually used to 
87 // update the PHI nodes that reside in the block.  Note that this should be
88 // called while the predecessor still refers to this block.
89 //
90 void BasicBlock::removePredecessor(BasicBlock *Pred) {
91   assert(find(pred_begin(this), pred_end(this), Pred) != pred_end(this) &&
92          "removePredecessor: BB is not a predecessor!");
93   if (!isa<PHINode>(front())) return;   // Quick exit.
94
95   pred_iterator PI(pred_begin(this)), EI(pred_end(this));
96   unsigned max_idx;
97
98   // Loop over the rest of the predecessors until we run out, or until we find
99   // out that there are more than 2 predecessors.
100   for (max_idx = 0; PI != EI && max_idx < 3; ++PI, ++max_idx) /*empty*/;
101
102   // If there are exactly two predecessors, then we want to nuke the PHI nodes
103   // altogether.
104   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
105   if (max_idx <= 2) {                // <= Two predecessors BEFORE I remove one?
106     // Yup, loop through and nuke the PHI nodes
107     while (PHINode *PN = dyn_cast<PHINode>(front())) {
108       PN->removeIncomingValue(Pred); // Remove the predecessor first...
109       
110       assert(PN->getNumIncomingValues() == max_idx-1 && 
111              "PHI node shouldn't have this many values!!!");
112
113       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
114       if (max_idx == 2)
115         PN->replaceAllUsesWith(PN->getOperand(0));
116       delete getInstList().remove(begin());  // Remove the PHI node
117     }
118   } else {
119     // Okay, now we know that we need to remove predecessor #pred_idx from all
120     // PHI nodes.  Iterate over each PHI node fixing them up
121     iterator II(begin());
122     for (; isa<PHINode>(*II); ++II)
123       cast<PHINode>(*II)->removeIncomingValue(Pred);
124   }
125 }
126
127
128 // splitBasicBlock - This splits a basic block into two at the specified
129 // instruction.  Note that all instructions BEFORE the specified iterator stay
130 // as part of the original basic block, an unconditional branch is added to 
131 // the new BB, and the rest of the instructions in the BB are moved to the new
132 // BB, including the old terminator.  This invalidates the iterator.
133 //
134 // Note that this only works on well formed basic blocks (must have a 
135 // terminator), and 'I' must not be the end of instruction list (which would
136 // cause a degenerate basic block to be formed, having a terminator inside of
137 // the basic block). 
138 //
139 BasicBlock *BasicBlock::splitBasicBlock(iterator I) {
140   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
141   assert(I != InstList.end() && 
142          "Trying to get me to create degenerate basic block!");
143
144   BasicBlock *New = new BasicBlock("", getParent());
145
146   // Go from the end of the basic block through to the iterator pointer, moving
147   // to the new basic block...
148   Instruction *Inst = 0;
149   do {
150     iterator EndIt = end();
151     Inst = InstList.remove(--EndIt);                  // Remove from end
152     New->InstList.push_front(Inst);                   // Add to front
153   } while (Inst != *I);   // Loop until we move the specified instruction.
154
155   // Add a branch instruction to the newly formed basic block.
156   InstList.push_back(new BranchInst(New));
157
158   // Now we must loop through all of the successors of the New block (which
159   // _were_ the successors of the 'this' block), and update any PHI nodes in
160   // successors.  If there were PHI nodes in the successors, then they need to
161   // know that incoming branches will be from New, not from Old.
162   //
163   for (BasicBlock::succ_iterator I = succ_begin(New), E = succ_end(New);
164        I != E; ++I) {
165     // Loop over any phi nodes in the basic block, updating the BB field of
166     // incoming values...
167     BasicBlock *Successor = *I;
168     for (BasicBlock::iterator II = Successor->begin();
169          PHINode *PN = dyn_cast<PHINode>(*II); ++II) {
170       int IDX = PN->getBasicBlockIndex(this);
171       while (IDX != -1) {
172         PN->setIncomingBlock((unsigned)IDX, New);
173         IDX = PN->getBasicBlockIndex(this);
174       }
175     }
176   }
177   return New;
178 }