• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
11 //
12 //===----------------------------------------------------------------------===//
13 
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;
26 
getValueSymbolTable()27 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
28   if (Function *F = getParent())
29     return &F->getValueSymbolTable();
30   return 0;
31 }
32 
getContext() const33 LLVMContext &BasicBlock::getContext() const {
34   return getType()->getContext();
35 }
36 
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>;
40 
41 
BasicBlock(LLVMContext & C,const Twine & Name,Function * NewParent,BasicBlock * InsertBefore)42 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
43                        BasicBlock *InsertBefore)
44   : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(0) {
45 
46   // Make sure that we get added to a function
47   LeakDetector::addGarbageObject(this);
48 
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);
55   }
56 
57   setName(Name);
58 }
59 
60 
~BasicBlock()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();
77     }
78   }
79 
80   assert(getParent() == 0 && "BasicBlock still linked into the program!");
81   dropAllReferences();
82   InstList.clear();
83 }
84 
setParent(Function * parent)85 void BasicBlock::setParent(Function *parent) {
86   if (getParent())
87     LeakDetector::addGarbageObject(this);
88 
89   // Set Parent=parent, updating instruction symtab entries as appropriate.
90   InstList.setSymTabObject(&Parent, parent);
91 
92   if (getParent())
93     LeakDetector::removeGarbageObject(this);
94 }
95 
removeFromParent()96 void BasicBlock::removeFromParent() {
97   getParent()->getBasicBlockList().remove(this);
98 }
99 
eraseFromParent()100 void BasicBlock::eraseFromParent() {
101   getParent()->getBasicBlockList().erase(this);
102 }
103 
104 /// moveBefore - Unlink this basic block from its current function and
105 /// insert it into the function that MovePos lives in, right before MovePos.
moveBefore(BasicBlock * MovePos)106 void BasicBlock::moveBefore(BasicBlock *MovePos) {
107   MovePos->getParent()->getBasicBlockList().splice(MovePos,
108                        getParent()->getBasicBlockList(), this);
109 }
110 
111 /// moveAfter - Unlink this basic block from its current function and
112 /// insert it into the function that MovePos lives in, right after MovePos.
moveAfter(BasicBlock * MovePos)113 void BasicBlock::moveAfter(BasicBlock *MovePos) {
114   Function::iterator I = MovePos;
115   MovePos->getParent()->getBasicBlockList().splice(++I,
116                                        getParent()->getBasicBlockList(), this);
117 }
118 
119 
getTerminator()120 TerminatorInst *BasicBlock::getTerminator() {
121   if (InstList.empty()) return 0;
122   return dyn_cast<TerminatorInst>(&InstList.back());
123 }
124 
getTerminator() const125 const TerminatorInst *BasicBlock::getTerminator() const {
126   if (InstList.empty()) return 0;
127   return dyn_cast<TerminatorInst>(&InstList.back());
128 }
129 
getFirstNonPHI()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;
138 }
139 
getFirstNonPHIOrDbg()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;
148 }
149 
getFirstNonPHIOrDbgOrLifetime()150 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
151   // All valid basic blocks should have a terminator,
152   // which is not a PHINode. If we have an invalid basic
153   // block we'll get an assertion failure when dereferencing
154   // a past-the-end iterator.
155   BasicBlock::iterator i = begin();
156   for (;; ++i) {
157     if (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i))
158       continue;
159 
160     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(i);
161     if (!II)
162       break;
163     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
164         II->getIntrinsicID() != Intrinsic::lifetime_end)
165       break;
166   }
167   return &*i;
168 }
169 
dropAllReferences()170 void BasicBlock::dropAllReferences() {
171   for(iterator I = begin(), E = end(); I != E; ++I)
172     I->dropAllReferences();
173 }
174 
175 /// getSinglePredecessor - If this basic block has a single predecessor block,
176 /// return the block, otherwise return a null pointer.
getSinglePredecessor()177 BasicBlock *BasicBlock::getSinglePredecessor() {
178   pred_iterator PI = pred_begin(this), E = pred_end(this);
179   if (PI == E) return 0;         // No preds.
180   BasicBlock *ThePred = *PI;
181   ++PI;
182   return (PI == E) ? ThePred : 0 /*multiple preds*/;
183 }
184 
185 /// getUniquePredecessor - If this basic block has a unique predecessor block,
186 /// return the block, otherwise return a null pointer.
187 /// Note that unique predecessor doesn't mean single edge, there can be
188 /// multiple edges from the unique predecessor to this block (for example
189 /// a switch statement with multiple cases having the same destination).
getUniquePredecessor()190 BasicBlock *BasicBlock::getUniquePredecessor() {
191   pred_iterator PI = pred_begin(this), E = pred_end(this);
192   if (PI == E) return 0; // No preds.
193   BasicBlock *PredBB = *PI;
194   ++PI;
195   for (;PI != E; ++PI) {
196     if (*PI != PredBB)
197       return 0;
198     // The same predecessor appears multiple times in the predecessor list.
199     // This is OK.
200   }
201   return PredBB;
202 }
203 
204 /// removePredecessor - This method is used to notify a BasicBlock that the
205 /// specified Predecessor of the block is no longer able to reach it.  This is
206 /// actually not used to update the Predecessor list, but is actually used to
207 /// update the PHI nodes that reside in the block.  Note that this should be
208 /// called while the predecessor still refers to this block.
209 ///
removePredecessor(BasicBlock * Pred,bool DontDeleteUselessPHIs)210 void BasicBlock::removePredecessor(BasicBlock *Pred,
211                                    bool DontDeleteUselessPHIs) {
212   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
213           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
214          "removePredecessor: BB is not a predecessor!");
215 
216   if (InstList.empty()) return;
217   PHINode *APN = dyn_cast<PHINode>(&front());
218   if (!APN) return;   // Quick exit.
219 
220   // If there are exactly two predecessors, then we want to nuke the PHI nodes
221   // altogether.  However, we cannot do this, if this in this case:
222   //
223   //  Loop:
224   //    %x = phi [X, Loop]
225   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
226   //    br Loop                 ;; %x2 does not dominate all uses
227   //
228   // This is because the PHI node input is actually taken from the predecessor
229   // basic block.  The only case this can happen is with a self loop, so we
230   // check for this case explicitly now.
231   //
232   unsigned max_idx = APN->getNumIncomingValues();
233   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
234   if (max_idx == 2) {
235     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
236 
237     // Disable PHI elimination!
238     if (this == Other) max_idx = 3;
239   }
240 
241   // <= Two predecessors BEFORE I remove one?
242   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
243     // Yup, loop through and nuke the PHI nodes
244     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
245       // Remove the predecessor first.
246       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
247 
248       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
249       if (max_idx == 2) {
250         if (PN->getIncomingValue(0) != PN)
251           PN->replaceAllUsesWith(PN->getIncomingValue(0));
252         else
253           // We are left with an infinite loop with no entries: kill the PHI.
254           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
255         getInstList().pop_front();    // Remove the PHI node
256       }
257 
258       // If the PHI node already only had one entry, it got deleted by
259       // removeIncomingValue.
260     }
261   } else {
262     // Okay, now we know that we need to remove predecessor #pred_idx from all
263     // PHI nodes.  Iterate over each PHI node fixing them up
264     PHINode *PN;
265     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
266       ++II;
267       PN->removeIncomingValue(Pred, false);
268       // If all incoming values to the Phi are the same, we can replace the Phi
269       // with that value.
270       Value* PNV = 0;
271       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
272         if (PNV != PN) {
273           PN->replaceAllUsesWith(PNV);
274           PN->eraseFromParent();
275         }
276     }
277   }
278 }
279 
280 
281 /// splitBasicBlock - This splits a basic block into two at the specified
282 /// instruction.  Note that all instructions BEFORE the specified iterator stay
283 /// as part of the original basic block, an unconditional branch is added to
284 /// the new BB, and the rest of the instructions in the BB are moved to the new
285 /// BB, including the old terminator.  This invalidates the iterator.
286 ///
287 /// Note that this only works on well formed basic blocks (must have a
288 /// terminator), and 'I' must not be the end of instruction list (which would
289 /// cause a degenerate basic block to be formed, having a terminator inside of
290 /// the basic block).
291 ///
splitBasicBlock(iterator I,const Twine & BBName)292 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
293   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
294   assert(I != InstList.end() &&
295          "Trying to get me to create degenerate basic block!");
296 
297   BasicBlock *InsertBefore = llvm::next(Function::iterator(this))
298                                .getNodePtrUnchecked();
299   BasicBlock *New = BasicBlock::Create(getContext(), BBName,
300                                        getParent(), InsertBefore);
301 
302   // Move all of the specified instructions from the original basic block into
303   // the new basic block.
304   New->getInstList().splice(New->end(), this->getInstList(), I, end());
305 
306   // Add a branch instruction to the newly formed basic block.
307   BranchInst::Create(New, this);
308 
309   // Now we must loop through all of the successors of the New block (which
310   // _were_ the successors of the 'this' block), and update any PHI nodes in
311   // successors.  If there were PHI nodes in the successors, then they need to
312   // know that incoming branches will be from New, not from Old.
313   //
314   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
315     // Loop over any phi nodes in the basic block, updating the BB field of
316     // incoming values...
317     BasicBlock *Successor = *I;
318     PHINode *PN;
319     for (BasicBlock::iterator II = Successor->begin();
320          (PN = dyn_cast<PHINode>(II)); ++II) {
321       int IDX = PN->getBasicBlockIndex(this);
322       while (IDX != -1) {
323         PN->setIncomingBlock((unsigned)IDX, New);
324         IDX = PN->getBasicBlockIndex(this);
325       }
326     }
327   }
328   return New;
329 }
330 
replaceSuccessorsPhiUsesWith(BasicBlock * New)331 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
332   TerminatorInst *TI = getTerminator();
333   if (!TI)
334     // Cope with being called on a BasicBlock that doesn't have a terminator
335     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
336     return;
337   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
338     BasicBlock *Succ = TI->getSuccessor(i);
339     for (iterator II = Succ->begin(); PHINode *PN = dyn_cast<PHINode>(II);
340          ++II) {
341       int i;
342       while ((i = PN->getBasicBlockIndex(this)) >= 0)
343         PN->setIncomingBlock(i, New);
344     }
345   }
346 }
347