zpu: wip - add pass to convert registers to stack slots
[llvm/zpu.git] / lib / VMCore / BasicBlock.cpp
blob8ad53736c993f9c3c79e2737d1186bc8f50df76f
1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/IntrinsicInst.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Type.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/CFG.h"
22 #include "llvm/Support/LeakDetector.h"
23 #include "SymbolTableListTraitsImpl.h"
24 #include <algorithm>
25 using namespace llvm;
27 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
28 if (Function *F = getParent())
29 return &F->getValueSymbolTable();
30 return 0;
33 LLVMContext &BasicBlock::getContext() const {
34 return getType()->getContext();
37 // Explicit instantiation of SymbolTableListTraits since some of the methods
38 // are not in the public header file...
39 template class llvm::SymbolTableListTraits<Instruction, BasicBlock>;
42 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
43 BasicBlock *InsertBefore)
44 : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(0) {
46 // Make sure that we get added to a function
47 LeakDetector::addGarbageObject(this);
49 if (InsertBefore) {
50 assert(NewParent &&
51 "Cannot insert block before another block with no function!");
52 NewParent->getBasicBlockList().insert(InsertBefore, this);
53 } else if (NewParent) {
54 NewParent->getBasicBlockList().push_back(this);
57 setName(Name);
61 BasicBlock::~BasicBlock() {
62 // If the address of the block is taken and it is being deleted (e.g. because
63 // it is dead), this means that there is either a dangling constant expr
64 // hanging off the block, or an undefined use of the block (source code
65 // expecting the address of a label to keep the block alive even though there
66 // is no indirect branch). Handle these cases by zapping the BlockAddress
67 // nodes. There are no other possible uses at this point.
68 if (hasAddressTaken()) {
69 assert(!use_empty() && "There should be at least one blockaddress!");
70 Constant *Replacement =
71 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
72 while (!use_empty()) {
73 BlockAddress *BA = cast<BlockAddress>(use_back());
74 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
75 BA->getType()));
76 BA->destroyConstant();
80 assert(getParent() == 0 && "BasicBlock still linked into the program!");
81 dropAllReferences();
82 InstList.clear();
85 void BasicBlock::setParent(Function *parent) {
86 if (getParent())
87 LeakDetector::addGarbageObject(this);
89 // Set Parent=parent, updating instruction symtab entries as appropriate.
90 InstList.setSymTabObject(&Parent, parent);
92 if (getParent())
93 LeakDetector::removeGarbageObject(this);
96 void BasicBlock::removeFromParent() {
97 getParent()->getBasicBlockList().remove(this);
100 void BasicBlock::eraseFromParent() {
101 getParent()->getBasicBlockList().erase(this);
104 /// moveBefore - Unlink this basic block from its current function and
105 /// insert it into the function that MovePos lives in, right before MovePos.
106 void BasicBlock::moveBefore(BasicBlock *MovePos) {
107 MovePos->getParent()->getBasicBlockList().splice(MovePos,
108 getParent()->getBasicBlockList(), this);
111 /// moveAfter - Unlink this basic block from its current function and
112 /// insert it into the function that MovePos lives in, right after MovePos.
113 void BasicBlock::moveAfter(BasicBlock *MovePos) {
114 Function::iterator I = MovePos;
115 MovePos->getParent()->getBasicBlockList().splice(++I,
116 getParent()->getBasicBlockList(), this);
120 TerminatorInst *BasicBlock::getTerminator() {
121 if (InstList.empty()) return 0;
122 return dyn_cast<TerminatorInst>(&InstList.back());
125 const TerminatorInst *BasicBlock::getTerminator() const {
126 if (InstList.empty()) return 0;
127 return dyn_cast<TerminatorInst>(&InstList.back());
130 Instruction* BasicBlock::getFirstNonPHI() {
131 BasicBlock::iterator i = begin();
132 // All valid basic blocks should have a terminator,
133 // which is not a PHINode. If we have an invalid basic
134 // block we'll get an assertion failure when dereferencing
135 // a past-the-end iterator.
136 while (isa<PHINode>(i)) ++i;
137 return &*i;
140 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
141 BasicBlock::iterator i = begin();
142 // All valid basic blocks should have a terminator,
143 // which is not a PHINode. If we have an invalid basic
144 // block we'll get an assertion failure when dereferencing
145 // a past-the-end iterator.
146 while (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) ++i;
147 return &*i;
150 void BasicBlock::dropAllReferences() {
151 for(iterator I = begin(), E = end(); I != E; ++I)
152 I->dropAllReferences();
155 /// getSinglePredecessor - If this basic block has a single predecessor block,
156 /// return the block, otherwise return a null pointer.
157 BasicBlock *BasicBlock::getSinglePredecessor() {
158 pred_iterator PI = pred_begin(this), E = pred_end(this);
159 if (PI == E) return 0; // No preds.
160 BasicBlock *ThePred = *PI;
161 ++PI;
162 return (PI == E) ? ThePred : 0 /*multiple preds*/;
165 /// getUniquePredecessor - If this basic block has a unique predecessor block,
166 /// return the block, otherwise return a null pointer.
167 /// Note that unique predecessor doesn't mean single edge, there can be
168 /// multiple edges from the unique predecessor to this block (for example
169 /// a switch statement with multiple cases having the same destination).
170 BasicBlock *BasicBlock::getUniquePredecessor() {
171 pred_iterator PI = pred_begin(this), E = pred_end(this);
172 if (PI == E) return 0; // No preds.
173 BasicBlock *PredBB = *PI;
174 ++PI;
175 for (;PI != E; ++PI) {
176 if (*PI != PredBB)
177 return 0;
178 // The same predecessor appears multiple times in the predecessor list.
179 // This is OK.
181 return PredBB;
184 /// removePredecessor - This method is used to notify a BasicBlock that the
185 /// specified Predecessor of the block is no longer able to reach it. This is
186 /// actually not used to update the Predecessor list, but is actually used to
187 /// update the PHI nodes that reside in the block. Note that this should be
188 /// called while the predecessor still refers to this block.
190 void BasicBlock::removePredecessor(BasicBlock *Pred,
191 bool DontDeleteUselessPHIs) {
192 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
193 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
194 "removePredecessor: BB is not a predecessor!");
196 if (InstList.empty()) return;
197 PHINode *APN = dyn_cast<PHINode>(&front());
198 if (!APN) return; // Quick exit.
200 // If there are exactly two predecessors, then we want to nuke the PHI nodes
201 // altogether. However, we cannot do this, if this in this case:
203 // Loop:
204 // %x = phi [X, Loop]
205 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
206 // br Loop ;; %x2 does not dominate all uses
208 // This is because the PHI node input is actually taken from the predecessor
209 // basic block. The only case this can happen is with a self loop, so we
210 // check for this case explicitly now.
212 unsigned max_idx = APN->getNumIncomingValues();
213 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
214 if (max_idx == 2) {
215 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
217 // Disable PHI elimination!
218 if (this == Other) max_idx = 3;
221 // <= Two predecessors BEFORE I remove one?
222 if (max_idx <= 2 && !DontDeleteUselessPHIs) {
223 // Yup, loop through and nuke the PHI nodes
224 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
225 // Remove the predecessor first.
226 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
228 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
229 if (max_idx == 2) {
230 if (PN->getOperand(0) != PN)
231 PN->replaceAllUsesWith(PN->getOperand(0));
232 else
233 // We are left with an infinite loop with no entries: kill the PHI.
234 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
235 getInstList().pop_front(); // Remove the PHI node
238 // If the PHI node already only had one entry, it got deleted by
239 // removeIncomingValue.
241 } else {
242 // Okay, now we know that we need to remove predecessor #pred_idx from all
243 // PHI nodes. Iterate over each PHI node fixing them up
244 PHINode *PN;
245 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
246 ++II;
247 PN->removeIncomingValue(Pred, false);
248 // If all incoming values to the Phi are the same, we can replace the Phi
249 // with that value.
250 Value* PNV = 0;
251 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
252 PN->replaceAllUsesWith(PNV);
253 PN->eraseFromParent();
260 /// splitBasicBlock - This splits a basic block into two at the specified
261 /// instruction. Note that all instructions BEFORE the specified iterator stay
262 /// as part of the original basic block, an unconditional branch is added to
263 /// the new BB, and the rest of the instructions in the BB are moved to the new
264 /// BB, including the old terminator. This invalidates the iterator.
266 /// Note that this only works on well formed basic blocks (must have a
267 /// terminator), and 'I' must not be the end of instruction list (which would
268 /// cause a degenerate basic block to be formed, having a terminator inside of
269 /// the basic block).
271 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
272 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
273 assert(I != InstList.end() &&
274 "Trying to get me to create degenerate basic block!");
276 BasicBlock *InsertBefore = llvm::next(Function::iterator(this))
277 .getNodePtrUnchecked();
278 BasicBlock *New = BasicBlock::Create(getContext(), BBName,
279 getParent(), InsertBefore);
281 // Move all of the specified instructions from the original basic block into
282 // the new basic block.
283 New->getInstList().splice(New->end(), this->getInstList(), I, end());
285 // Add a branch instruction to the newly formed basic block.
286 BranchInst::Create(New, this);
288 // Now we must loop through all of the successors of the New block (which
289 // _were_ the successors of the 'this' block), and update any PHI nodes in
290 // successors. If there were PHI nodes in the successors, then they need to
291 // know that incoming branches will be from New, not from Old.
293 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
294 // Loop over any phi nodes in the basic block, updating the BB field of
295 // incoming values...
296 BasicBlock *Successor = *I;
297 PHINode *PN;
298 for (BasicBlock::iterator II = Successor->begin();
299 (PN = dyn_cast<PHINode>(II)); ++II) {
300 int IDX = PN->getBasicBlockIndex(this);
301 while (IDX != -1) {
302 PN->setIncomingBlock((unsigned)IDX, New);
303 IDX = PN->getBasicBlockIndex(this);
307 return New;