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