Add a speculative execution pass
[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 TerminatorInst *BasicBlock::getTerminator() {
121   if (InstList.empty()) return nullptr;
122   return dyn_cast<TerminatorInst>(&InstList.back());
123 }
124
125 const TerminatorInst *BasicBlock::getTerminator() const {
126   if (InstList.empty()) return nullptr;
127   return dyn_cast<TerminatorInst>(&InstList.back());
128 }
129
130 CallInst *BasicBlock::getTerminatingMustTailCall() {
131   if (InstList.empty())
132     return nullptr;
133   ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
134   if (!RI || RI == &InstList.front())
135     return nullptr;
136
137   Instruction *Prev = RI->getPrevNode();
138   if (!Prev)
139     return nullptr;
140
141   if (Value *RV = RI->getReturnValue()) {
142     if (RV != Prev)
143       return nullptr;
144
145     // Look through the optional bitcast.
146     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
147       RV = BI->getOperand(0);
148       Prev = BI->getPrevNode();
149       if (!Prev || RV != Prev)
150         return nullptr;
151     }
152   }
153
154   if (auto *CI = dyn_cast<CallInst>(Prev)) {
155     if (CI->isMustTailCall())
156       return CI;
157   }
158   return nullptr;
159 }
160
161 Instruction* BasicBlock::getFirstNonPHI() {
162   BasicBlock::iterator i = begin();
163   // All valid basic blocks should have a terminator,
164   // which is not a PHINode. If we have an invalid basic
165   // block we'll get an assertion failure when dereferencing
166   // a past-the-end iterator.
167   while (isa<PHINode>(i)) ++i;
168   return &*i;
169 }
170
171 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
172   BasicBlock::iterator i = begin();
173   // All valid basic blocks should have a terminator,
174   // which is not a PHINode. If we have an invalid basic
175   // block we'll get an assertion failure when dereferencing
176   // a past-the-end iterator.
177   while (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) ++i;
178   return &*i;
179 }
180
181 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
182   // All valid basic blocks should have a terminator,
183   // which is not a PHINode. If we have an invalid basic
184   // block we'll get an assertion failure when dereferencing
185   // a past-the-end iterator.
186   BasicBlock::iterator i = begin();
187   for (;; ++i) {
188     if (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i))
189       continue;
190
191     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(i);
192     if (!II)
193       break;
194     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
195         II->getIntrinsicID() != Intrinsic::lifetime_end)
196       break;
197   }
198   return &*i;
199 }
200
201 BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
202   iterator InsertPt = getFirstNonPHI();
203   if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
204   return InsertPt;
205 }
206
207 void BasicBlock::dropAllReferences() {
208   for(iterator I = begin(), E = end(); I != E; ++I)
209     I->dropAllReferences();
210 }
211
212 /// If this basic block has a single predecessor block,
213 /// return the block, otherwise return a null pointer.
214 BasicBlock *BasicBlock::getSinglePredecessor() {
215   pred_iterator PI = pred_begin(this), E = pred_end(this);
216   if (PI == E) return nullptr;         // No preds.
217   BasicBlock *ThePred = *PI;
218   ++PI;
219   return (PI == E) ? ThePred : nullptr /*multiple preds*/;
220 }
221
222 /// If this basic block has a unique predecessor block,
223 /// return the block, otherwise return a null pointer.
224 /// Note that unique predecessor doesn't mean single edge, there can be
225 /// multiple edges from the unique predecessor to this block (for example
226 /// a switch statement with multiple cases having the same destination).
227 BasicBlock *BasicBlock::getUniquePredecessor() {
228   pred_iterator PI = pred_begin(this), E = pred_end(this);
229   if (PI == E) return nullptr; // No preds.
230   BasicBlock *PredBB = *PI;
231   ++PI;
232   for (;PI != E; ++PI) {
233     if (*PI != PredBB)
234       return nullptr;
235     // The same predecessor appears multiple times in the predecessor list.
236     // This is OK.
237   }
238   return PredBB;
239 }
240
241 BasicBlock *BasicBlock::getSingleSuccessor() {
242   succ_iterator SI = succ_begin(this), E = succ_end(this);
243   if (SI == E) return nullptr; // no successors
244   BasicBlock *TheSucc = *SI;
245   ++SI;
246   return (SI == E) ? TheSucc : nullptr /* multiple successors */;
247 }
248
249 BasicBlock *BasicBlock::getUniqueSuccessor() {
250   succ_iterator SI = succ_begin(this), E = succ_end(this);
251   if (SI == E) return NULL; // No successors
252   BasicBlock *SuccBB = *SI;
253   ++SI;
254   for (;SI != E; ++SI) {
255     if (*SI != SuccBB)
256       return NULL;
257     // The same successor appears multiple times in the successor list.
258     // This is OK.
259   }
260   return SuccBB;
261 }
262
263 /// This method is used to notify a BasicBlock that the
264 /// specified Predecessor of the block is no longer able to reach it.  This is
265 /// actually not used to update the Predecessor list, but is actually used to
266 /// update the PHI nodes that reside in the block.  Note that this should be
267 /// called while the predecessor still refers to this block.
268 ///
269 void BasicBlock::removePredecessor(BasicBlock *Pred,
270                                    bool DontDeleteUselessPHIs) {
271   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
272           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
273          "removePredecessor: BB is not a predecessor!");
274
275   if (InstList.empty()) return;
276   PHINode *APN = dyn_cast<PHINode>(&front());
277   if (!APN) return;   // Quick exit.
278
279   // If there are exactly two predecessors, then we want to nuke the PHI nodes
280   // altogether.  However, we cannot do this, if this in this case:
281   //
282   //  Loop:
283   //    %x = phi [X, Loop]
284   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
285   //    br Loop                 ;; %x2 does not dominate all uses
286   //
287   // This is because the PHI node input is actually taken from the predecessor
288   // basic block.  The only case this can happen is with a self loop, so we
289   // check for this case explicitly now.
290   //
291   unsigned max_idx = APN->getNumIncomingValues();
292   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
293   if (max_idx == 2) {
294     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
295
296     // Disable PHI elimination!
297     if (this == Other) max_idx = 3;
298   }
299
300   // <= Two predecessors BEFORE I remove one?
301   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
302     // Yup, loop through and nuke the PHI nodes
303     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
304       // Remove the predecessor first.
305       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
306
307       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
308       if (max_idx == 2) {
309         if (PN->getIncomingValue(0) != PN)
310           PN->replaceAllUsesWith(PN->getIncomingValue(0));
311         else
312           // We are left with an infinite loop with no entries: kill the PHI.
313           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
314         getInstList().pop_front();    // Remove the PHI node
315       }
316
317       // If the PHI node already only had one entry, it got deleted by
318       // removeIncomingValue.
319     }
320   } else {
321     // Okay, now we know that we need to remove predecessor #pred_idx from all
322     // PHI nodes.  Iterate over each PHI node fixing them up
323     PHINode *PN;
324     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
325       ++II;
326       PN->removeIncomingValue(Pred, false);
327       // If all incoming values to the Phi are the same, we can replace the Phi
328       // with that value.
329       Value* PNV = nullptr;
330       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
331         if (PNV != PN) {
332           PN->replaceAllUsesWith(PNV);
333           PN->eraseFromParent();
334         }
335     }
336   }
337 }
338
339
340 /// This splits a basic block into two at the specified
341 /// instruction.  Note that all instructions BEFORE the specified iterator stay
342 /// as part of the original basic block, an unconditional branch is added to
343 /// the new BB, and the rest of the instructions in the BB are moved to the new
344 /// BB, including the old terminator.  This invalidates the iterator.
345 ///
346 /// Note that this only works on well formed basic blocks (must have a
347 /// terminator), and 'I' must not be the end of instruction list (which would
348 /// cause a degenerate basic block to be formed, having a terminator inside of
349 /// the basic block).
350 ///
351 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
352   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
353   assert(I != InstList.end() &&
354          "Trying to get me to create degenerate basic block!");
355
356   BasicBlock *InsertBefore = std::next(Function::iterator(this))
357                                .getNodePtrUnchecked();
358   BasicBlock *New = BasicBlock::Create(getContext(), BBName,
359                                        getParent(), InsertBefore);
360
361   // Move all of the specified instructions from the original basic block into
362   // the new basic block.
363   New->getInstList().splice(New->end(), this->getInstList(), I, end());
364
365   // Add a branch instruction to the newly formed basic block.
366   BranchInst::Create(New, this);
367
368   // Now we must loop through all of the successors of the New block (which
369   // _were_ the successors of the 'this' block), and update any PHI nodes in
370   // successors.  If there were PHI nodes in the successors, then they need to
371   // know that incoming branches will be from New, not from Old.
372   //
373   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
374     // Loop over any phi nodes in the basic block, updating the BB field of
375     // incoming values...
376     BasicBlock *Successor = *I;
377     PHINode *PN;
378     for (BasicBlock::iterator II = Successor->begin();
379          (PN = dyn_cast<PHINode>(II)); ++II) {
380       int IDX = PN->getBasicBlockIndex(this);
381       while (IDX != -1) {
382         PN->setIncomingBlock((unsigned)IDX, New);
383         IDX = PN->getBasicBlockIndex(this);
384       }
385     }
386   }
387   return New;
388 }
389
390 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
391   TerminatorInst *TI = getTerminator();
392   if (!TI)
393     // Cope with being called on a BasicBlock that doesn't have a terminator
394     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
395     return;
396   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
397     BasicBlock *Succ = TI->getSuccessor(i);
398     // N.B. Succ might not be a complete BasicBlock, so don't assume
399     // that it ends with a non-phi instruction.
400     for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
401       PHINode *PN = dyn_cast<PHINode>(II);
402       if (!PN)
403         break;
404       int i;
405       while ((i = PN->getBasicBlockIndex(this)) >= 0)
406         PN->setIncomingBlock(i, New);
407     }
408   }
409 }
410
411 /// Return true if this basic block is a landing pad. I.e., it's
412 /// the destination of the 'unwind' edge of an invoke instruction.
413 bool BasicBlock::isLandingPad() const {
414   return isa<LandingPadInst>(getFirstNonPHI());
415 }
416
417 /// Return the landingpad instruction associated with the landing pad.
418 LandingPadInst *BasicBlock::getLandingPadInst() {
419   return dyn_cast<LandingPadInst>(getFirstNonPHI());
420 }
421 const LandingPadInst *BasicBlock::getLandingPadInst() const {
422   return dyn_cast<LandingPadInst>(getFirstNonPHI());
423 }