1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the BasicBlock class for the IR library.
12 //===----------------------------------------------------------------------===//
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"
27 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
28 if (Function *F = getParent())
29 return &F->getValueSymbolTable();
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>;
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) {
47 insertInto(NewParent, InsertBefore);
49 assert(!InsertBefore &&
50 "Cannot insert block before another block with no function!");
55 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
56 assert(NewParent && "Expected a parent");
57 assert(!Parent && "Already has a parent");
60 NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
62 NewParent->getBasicBlockList().push_back(this);
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,
80 BA->destroyConstant();
84 assert(getParent() == nullptr && "BasicBlock still linked into the program!");
89 void BasicBlock::setParent(Function *parent) {
90 // Set Parent=parent, updating instruction symtab entries as appropriate.
91 InstList.setSymTabObject(&Parent, parent);
94 void BasicBlock::removeFromParent() {
95 getParent()->getBasicBlockList().remove(getIterator());
98 iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
99 return getParent()->getBasicBlockList().erase(getIterator());
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());
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(),
117 const Module *BasicBlock::getModule() const {
118 return getParent()->getParent();
121 Module *BasicBlock::getModule() {
122 return getParent()->getParent();
125 TerminatorInst *BasicBlock::getTerminator() {
126 if (InstList.empty()) return nullptr;
127 return dyn_cast<TerminatorInst>(&InstList.back());
130 const TerminatorInst *BasicBlock::getTerminator() const {
131 if (InstList.empty()) return nullptr;
132 return dyn_cast<TerminatorInst>(&InstList.back());
135 CallInst *BasicBlock::getTerminatingMustTailCall() {
136 if (InstList.empty())
138 ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
139 if (!RI || RI == &InstList.front())
142 Instruction *Prev = RI->getPrevNode();
146 if (Value *RV = RI->getReturnValue()) {
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)
159 if (auto *CI = dyn_cast<CallInst>(Prev)) {
160 if (CI->isMustTailCall())
166 Instruction* BasicBlock::getFirstNonPHI() {
167 for (Instruction &I : *this)
168 if (!isa<PHINode>(I))
173 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
174 for (Instruction &I : *this)
175 if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
180 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
181 for (Instruction &I : *this) {
182 if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
185 if (auto *II = dyn_cast<IntrinsicInst>(&I))
186 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
187 II->getIntrinsicID() == Intrinsic::lifetime_end)
195 BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
196 Instruction *FirstNonPHI = getFirstNonPHI();
200 iterator InsertPt = FirstNonPHI->getIterator();
201 if (InsertPt->isEHPad()) ++InsertPt;
205 void BasicBlock::dropAllReferences() {
206 for(iterator I = begin(), E = end(); I != E; ++I)
207 I->dropAllReferences();
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;
217 return (PI == E) ? ThePred : nullptr /*multiple preds*/;
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;
230 for (;PI != E; ++PI) {
233 // The same predecessor appears multiple times in the predecessor list.
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;
244 return (SI == E) ? TheSucc : nullptr /* multiple successors */;
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;
252 for (;SI != E; ++SI) {
255 // The same successor appears multiple times in the successor list.
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.
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!");
273 if (InstList.empty()) return;
274 PHINode *APN = dyn_cast<PHINode>(&front());
275 if (!APN) return; // Quick exit.
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:
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
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.
289 unsigned max_idx = APN->getNumIncomingValues();
290 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
292 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
294 // Disable PHI elimination!
295 if (this == Other) max_idx = 3;
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);
305 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
307 if (PN->getIncomingValue(0) != PN)
308 PN->replaceAllUsesWith(PN->getIncomingValue(0));
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
315 // If the PHI node already only had one entry, it got deleted by
316 // removeIncomingValue.
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
322 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
324 PN->removeIncomingValue(Pred, false);
325 // If all incoming values to the Phi are the same, we can replace the Phi
327 Value* PNV = nullptr;
328 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
330 PN->replaceAllUsesWith(PNV);
331 PN->eraseFromParent();
337 bool BasicBlock::canSplitPredecessors() const {
338 const Instruction *FirstNonPHI = getFirstNonPHI();
339 if (isa<LandingPadInst>(FirstNonPHI))
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())
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.
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).
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!");
365 BasicBlock *InsertBefore = std::next(Function::iterator(this))
366 .getNodePtrUnchecked();
367 BasicBlock *New = BasicBlock::Create(getContext(), BBName,
368 getParent(), InsertBefore);
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());
376 // Add a branch instruction to the newly formed basic block.
377 BranchInst *BI = BranchInst::Create(New, this);
378 BI->setDebugLoc(Loc);
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.
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;
390 for (BasicBlock::iterator II = Successor->begin();
391 (PN = dyn_cast<PHINode>(II)); ++II) {
392 int IDX = PN->getBasicBlockIndex(this);
394 PN->setIncomingBlock((unsigned)IDX, New);
395 IDX = PN->getBasicBlockIndex(this);
402 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
403 TerminatorInst *TI = getTerminator();
405 // Cope with being called on a BasicBlock that doesn't have a terminator
406 // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
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);
416 while ((i = PN->getBasicBlockIndex(this)) >= 0)
417 PN->setIncomingBlock(i, New);
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());
428 /// Return the landingpad instruction associated with the landing pad.
429 LandingPadInst *BasicBlock::getLandingPadInst() {
430 return dyn_cast<LandingPadInst>(getFirstNonPHI());
432 const LandingPadInst *BasicBlock::getLandingPadInst() const {
433 return dyn_cast<LandingPadInst>(getFirstNonPHI());