Sets insertion point of fake cond branch to the last phi node in the block
[oota-llvm.git] / lib / IR / BasicBlock.cpp
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 IR library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/BasicBlock.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/IR/CFG.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Type.h"
23 #include <algorithm>
24
25 using namespace llvm;
26
27 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
28   if (Function *F = getParent())
29     return &F->getValueSymbolTable();
30   return nullptr;
31 }
32
33 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>;
40
41 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
42                        BasicBlock *InsertBefore)
43   : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr),
44     canEliminateBlock(true) {
45
46   if (NewParent)
47     insertInto(NewParent, InsertBefore);
48   else
49     assert(!InsertBefore &&
50            "Cannot insert block before another block with no function!");
51
52   setName(Name);
53 }
54
55 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
56   assert(NewParent && "Expected a parent");
57   assert(!Parent && "Already has a parent");
58
59   if (InsertBefore)
60     NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
61   else
62     NewParent->getBasicBlockList().push_back(this);
63 }
64
65 BasicBlock::~BasicBlock() {
66   // If the address of the block is taken and it is being deleted (e.g. because
67   // it is dead), this means that there is either a dangling constant expr
68   // hanging off the block, or an undefined use of the block (source code
69   // expecting the address of a label to keep the block alive even though there
70   // is no indirect branch).  Handle these cases by zapping the BlockAddress
71   // nodes.  There are no other possible uses at this point.
72   if (hasAddressTaken()) {
73     assert(!use_empty() && "There should be at least one blockaddress!");
74     Constant *Replacement =
75       ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
76     while (!use_empty()) {
77       BlockAddress *BA = cast<BlockAddress>(user_back());
78       BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
79                                                        BA->getType()));
80       BA->destroyConstant();
81     }
82   }
83
84   assert(getParent() == nullptr && "BasicBlock still linked into the program!");
85   dropAllReferences();
86   InstList.clear();
87 }
88
89 void BasicBlock::setParent(Function *parent) {
90   // Set Parent=parent, updating instruction symtab entries as appropriate.
91   InstList.setSymTabObject(&Parent, parent);
92 }
93
94 void BasicBlock::removeFromParent() {
95   getParent()->getBasicBlockList().remove(getIterator());
96 }
97
98 iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
99   return getParent()->getBasicBlockList().erase(getIterator());
100 }
101
102 /// Unlink this basic block from its current function and
103 /// insert it into the function that MovePos lives in, right before MovePos.
104 void BasicBlock::moveBefore(BasicBlock *MovePos) {
105   MovePos->getParent()->getBasicBlockList().splice(
106       MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
107 }
108
109 /// Unlink this basic block from its current function and
110 /// insert it into the function that MovePos lives in, right after MovePos.
111 void BasicBlock::moveAfter(BasicBlock *MovePos) {
112   MovePos->getParent()->getBasicBlockList().splice(
113       ++MovePos->getIterator(), getParent()->getBasicBlockList(),
114       getIterator());
115 }
116
117 const Module *BasicBlock::getModule() const {
118   return getParent()->getParent();
119 }
120
121 Module *BasicBlock::getModule() {
122   return getParent()->getParent();
123 }
124
125 TerminatorInst *BasicBlock::getTerminator() {
126   if (InstList.empty()) return nullptr;
127   return dyn_cast<TerminatorInst>(&InstList.back());
128 }
129
130 const TerminatorInst *BasicBlock::getTerminator() const {
131   if (InstList.empty()) return nullptr;
132   return dyn_cast<TerminatorInst>(&InstList.back());
133 }
134
135 CallInst *BasicBlock::getTerminatingMustTailCall() {
136   if (InstList.empty())
137     return nullptr;
138   ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
139   if (!RI || RI == &InstList.front())
140     return nullptr;
141
142   Instruction *Prev = RI->getPrevNode();
143   if (!Prev)
144     return nullptr;
145
146   if (Value *RV = RI->getReturnValue()) {
147     if (RV != Prev)
148       return nullptr;
149
150     // Look through the optional bitcast.
151     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
152       RV = BI->getOperand(0);
153       Prev = BI->getPrevNode();
154       if (!Prev || RV != Prev)
155         return nullptr;
156     }
157   }
158
159   if (auto *CI = dyn_cast<CallInst>(Prev)) {
160     if (CI->isMustTailCall())
161       return CI;
162   }
163   return nullptr;
164 }
165
166 Instruction* BasicBlock::getFirstNonPHI() {
167   for (Instruction &I : *this)
168     if (!isa<PHINode>(I))
169       return &I;
170   return nullptr;
171 }
172
173 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
174   for (Instruction &I : *this)
175     if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
176       return &I;
177   return nullptr;
178 }
179
180 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
181   for (Instruction &I : *this) {
182     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
183       continue;
184
185     if (auto *II = dyn_cast<IntrinsicInst>(&I))
186       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
187           II->getIntrinsicID() == Intrinsic::lifetime_end)
188         continue;
189
190     return &I;
191   }
192   return nullptr;
193 }
194
195 BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
196   Instruction *FirstNonPHI = getFirstNonPHI();
197   if (!FirstNonPHI)
198     return end();
199
200   iterator InsertPt = FirstNonPHI->getIterator();
201   if (InsertPt->isEHPad()) ++InsertPt;
202   return InsertPt;
203 }
204
205 void BasicBlock::dropAllReferences() {
206   for(iterator I = begin(), E = end(); I != E; ++I)
207     I->dropAllReferences();
208 }
209
210 /// If this basic block has a single predecessor block,
211 /// return the block, otherwise return a null pointer.
212 BasicBlock *BasicBlock::getSinglePredecessor() {
213   pred_iterator PI = pred_begin(this), E = pred_end(this);
214   if (PI == E) return nullptr;         // No preds.
215   BasicBlock *ThePred = *PI;
216   ++PI;
217   return (PI == E) ? ThePred : nullptr /*multiple preds*/;
218 }
219
220 /// If this basic block has a unique predecessor block,
221 /// return the block, otherwise return a null pointer.
222 /// Note that unique predecessor doesn't mean single edge, there can be
223 /// multiple edges from the unique predecessor to this block (for example
224 /// a switch statement with multiple cases having the same destination).
225 BasicBlock *BasicBlock::getUniquePredecessor() {
226   pred_iterator PI = pred_begin(this), E = pred_end(this);
227   if (PI == E) return nullptr; // No preds.
228   BasicBlock *PredBB = *PI;
229   ++PI;
230   for (;PI != E; ++PI) {
231     if (*PI != PredBB)
232       return nullptr;
233     // The same predecessor appears multiple times in the predecessor list.
234     // This is OK.
235   }
236   return PredBB;
237 }
238
239 BasicBlock *BasicBlock::getSingleSuccessor() {
240   succ_iterator SI = succ_begin(this), E = succ_end(this);
241   if (SI == E) return nullptr; // no successors
242   BasicBlock *TheSucc = *SI;
243   ++SI;
244   return (SI == E) ? TheSucc : nullptr /* multiple successors */;
245 }
246
247 BasicBlock *BasicBlock::getUniqueSuccessor() {
248   succ_iterator SI = succ_begin(this), E = succ_end(this);
249   if (SI == E) return nullptr; // No successors
250   BasicBlock *SuccBB = *SI;
251   ++SI;
252   for (;SI != E; ++SI) {
253     if (*SI != SuccBB)
254       return nullptr;
255     // The same successor appears multiple times in the successor list.
256     // This is OK.
257   }
258   return SuccBB;
259 }
260
261 /// This method is used to notify a BasicBlock that the
262 /// specified Predecessor of the block is no longer able to reach it.  This is
263 /// actually not used to update the Predecessor list, but is actually used to
264 /// update the PHI nodes that reside in the block.  Note that this should be
265 /// called while the predecessor still refers to this block.
266 ///
267 void BasicBlock::removePredecessor(BasicBlock *Pred,
268                                    bool DontDeleteUselessPHIs) {
269   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
270           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
271          "removePredecessor: BB is not a predecessor!");
272
273   if (InstList.empty()) return;
274   PHINode *APN = dyn_cast<PHINode>(&front());
275   if (!APN) return;   // Quick exit.
276
277   // If there are exactly two predecessors, then we want to nuke the PHI nodes
278   // altogether.  However, we cannot do this, if this in this case:
279   //
280   //  Loop:
281   //    %x = phi [X, Loop]
282   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
283   //    br Loop                 ;; %x2 does not dominate all uses
284   //
285   // This is because the PHI node input is actually taken from the predecessor
286   // basic block.  The only case this can happen is with a self loop, so we
287   // check for this case explicitly now.
288   //
289   unsigned max_idx = APN->getNumIncomingValues();
290   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
291   if (max_idx == 2) {
292     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
293
294     // Disable PHI elimination!
295     if (this == Other) max_idx = 3;
296   }
297
298   // <= Two predecessors BEFORE I remove one?
299   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
300     // Yup, loop through and nuke the PHI nodes
301     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
302       // Remove the predecessor first.
303       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
304
305       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
306       if (max_idx == 2) {
307         if (PN->getIncomingValue(0) != PN)
308           PN->replaceAllUsesWith(PN->getIncomingValue(0));
309         else
310           // We are left with an infinite loop with no entries: kill the PHI.
311           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
312         getInstList().pop_front();    // Remove the PHI node
313       }
314
315       // If the PHI node already only had one entry, it got deleted by
316       // removeIncomingValue.
317     }
318   } else {
319     // Okay, now we know that we need to remove predecessor #pred_idx from all
320     // PHI nodes.  Iterate over each PHI node fixing them up
321     PHINode *PN;
322     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
323       ++II;
324       PN->removeIncomingValue(Pred, false);
325       // If all incoming values to the Phi are the same, we can replace the Phi
326       // with that value.
327       Value* PNV = nullptr;
328       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
329         if (PNV != PN) {
330           PN->replaceAllUsesWith(PNV);
331           PN->eraseFromParent();
332         }
333     }
334   }
335 }
336
337 bool BasicBlock::canSplitPredecessors() const {
338   const Instruction *FirstNonPHI = getFirstNonPHI();
339   if (isa<LandingPadInst>(FirstNonPHI))
340     return true;
341   // This is perhaps a little conservative because constructs like
342   // CleanupBlockInst are pretty easy to split.  However, SplitBlockPredecessors
343   // cannot handle such things just yet.
344   if (FirstNonPHI->isEHPad())
345     return false;
346   return true;
347 }
348
349 /// This splits a basic block into two at the specified
350 /// instruction.  Note that all instructions BEFORE the specified iterator stay
351 /// as part of the original basic block, an unconditional branch is added to
352 /// the new BB, and the rest of the instructions in the BB are moved to the new
353 /// BB, including the old terminator.  This invalidates the iterator.
354 ///
355 /// Note that this only works on well formed basic blocks (must have a
356 /// terminator), and 'I' must not be the end of instruction list (which would
357 /// cause a degenerate basic block to be formed, having a terminator inside of
358 /// the basic block).
359 ///
360 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
361   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
362   assert(I != InstList.end() &&
363          "Trying to get me to create degenerate basic block!");
364
365   BasicBlock *InsertBefore = std::next(Function::iterator(this))
366                                .getNodePtrUnchecked();
367   BasicBlock *New = BasicBlock::Create(getContext(), BBName,
368                                        getParent(), InsertBefore);
369
370   // Save DebugLoc of split point before invalidating iterator.
371   DebugLoc Loc = I->getDebugLoc();
372   // Move all of the specified instructions from the original basic block into
373   // the new basic block.
374   New->getInstList().splice(New->end(), this->getInstList(), I, end());
375
376   // Add a branch instruction to the newly formed basic block.
377   BranchInst *BI = BranchInst::Create(New, this);
378   BI->setDebugLoc(Loc);
379
380   // Now we must loop through all of the successors of the New block (which
381   // _were_ the successors of the 'this' block), and update any PHI nodes in
382   // successors.  If there were PHI nodes in the successors, then they need to
383   // know that incoming branches will be from New, not from Old.
384   //
385   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
386     // Loop over any phi nodes in the basic block, updating the BB field of
387     // incoming values...
388     BasicBlock *Successor = *I;
389     PHINode *PN;
390     for (BasicBlock::iterator II = Successor->begin();
391          (PN = dyn_cast<PHINode>(II)); ++II) {
392       int IDX = PN->getBasicBlockIndex(this);
393       while (IDX != -1) {
394         PN->setIncomingBlock((unsigned)IDX, New);
395         IDX = PN->getBasicBlockIndex(this);
396       }
397     }
398   }
399   return New;
400 }
401
402 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
403   TerminatorInst *TI = getTerminator();
404   if (!TI)
405     // Cope with being called on a BasicBlock that doesn't have a terminator
406     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
407     return;
408   for (BasicBlock *Succ : TI->successors()) {
409     // N.B. Succ might not be a complete BasicBlock, so don't assume
410     // that it ends with a non-phi instruction.
411     for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
412       PHINode *PN = dyn_cast<PHINode>(II);
413       if (!PN)
414         break;
415       int i;
416       while ((i = PN->getBasicBlockIndex(this)) >= 0)
417         PN->setIncomingBlock(i, New);
418     }
419   }
420 }
421
422 /// Return true if this basic block is a landing pad. I.e., it's
423 /// the destination of the 'unwind' edge of an invoke instruction.
424 bool BasicBlock::isLandingPad() const {
425   return isa<LandingPadInst>(getFirstNonPHI());
426 }
427
428 /// Return the landingpad instruction associated with the landing pad.
429 LandingPadInst *BasicBlock::getLandingPadInst() {
430   return dyn_cast<LandingPadInst>(getFirstNonPHI());
431 }
432 const LandingPadInst *BasicBlock::getLandingPadInst() const {
433   return dyn_cast<LandingPadInst>(getFirstNonPHI());
434 }