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/LeakDetector.h"
23 #include "llvm/IR/Type.h"
27 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
28 if (Function *F = getParent())
29 return &F->getValueSymbolTable();
33 const DataLayout *BasicBlock::getDataLayout() const {
34 return getParent()->getDataLayout();
37 LLVMContext &BasicBlock::getContext() const {
38 return getType()->getContext();
41 // Explicit instantiation of SymbolTableListTraits since some of the methods
42 // are not in the public header file...
43 template class llvm::SymbolTableListTraits<Instruction, BasicBlock>;
46 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
47 BasicBlock *InsertBefore)
48 : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
50 // Make sure that we get added to a function
51 LeakDetector::addGarbageObject(this);
54 insertInto(NewParent, InsertBefore);
56 assert(!InsertBefore &&
57 "Cannot insert block before another block with no function!");
62 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
63 assert(NewParent && "Expected a parent");
64 assert(!Parent && "Already has a parent");
67 NewParent->getBasicBlockList().insert(InsertBefore, this);
69 NewParent->getBasicBlockList().push_back(this);
72 BasicBlock::~BasicBlock() {
73 // If the address of the block is taken and it is being deleted (e.g. because
74 // it is dead), this means that there is either a dangling constant expr
75 // hanging off the block, or an undefined use of the block (source code
76 // expecting the address of a label to keep the block alive even though there
77 // is no indirect branch). Handle these cases by zapping the BlockAddress
78 // nodes. There are no other possible uses at this point.
79 if (hasAddressTaken()) {
80 assert(!use_empty() && "There should be at least one blockaddress!");
81 Constant *Replacement =
82 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
83 while (!use_empty()) {
84 BlockAddress *BA = cast<BlockAddress>(user_back());
85 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
87 BA->destroyConstant();
91 assert(getParent() == nullptr && "BasicBlock still linked into the program!");
96 void BasicBlock::setParent(Function *parent) {
98 LeakDetector::addGarbageObject(this);
100 // Set Parent=parent, updating instruction symtab entries as appropriate.
101 InstList.setSymTabObject(&Parent, parent);
104 LeakDetector::removeGarbageObject(this);
107 void BasicBlock::removeFromParent() {
108 getParent()->getBasicBlockList().remove(this);
111 void BasicBlock::eraseFromParent() {
112 getParent()->getBasicBlockList().erase(this);
115 /// moveBefore - Unlink this basic block from its current function and
116 /// insert it into the function that MovePos lives in, right before MovePos.
117 void BasicBlock::moveBefore(BasicBlock *MovePos) {
118 MovePos->getParent()->getBasicBlockList().splice(MovePos,
119 getParent()->getBasicBlockList(), this);
122 /// moveAfter - Unlink this basic block from its current function and
123 /// insert it into the function that MovePos lives in, right after MovePos.
124 void BasicBlock::moveAfter(BasicBlock *MovePos) {
125 Function::iterator I = MovePos;
126 MovePos->getParent()->getBasicBlockList().splice(++I,
127 getParent()->getBasicBlockList(), this);
131 TerminatorInst *BasicBlock::getTerminator() {
132 if (InstList.empty()) return nullptr;
133 return dyn_cast<TerminatorInst>(&InstList.back());
136 const TerminatorInst *BasicBlock::getTerminator() const {
137 if (InstList.empty()) return nullptr;
138 return dyn_cast<TerminatorInst>(&InstList.back());
141 Instruction* BasicBlock::getFirstNonPHI() {
142 BasicBlock::iterator i = begin();
143 // All valid basic blocks should have a terminator,
144 // which is not a PHINode. If we have an invalid basic
145 // block we'll get an assertion failure when dereferencing
146 // a past-the-end iterator.
147 while (isa<PHINode>(i)) ++i;
151 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
152 BasicBlock::iterator i = begin();
153 // All valid basic blocks should have a terminator,
154 // which is not a PHINode. If we have an invalid basic
155 // block we'll get an assertion failure when dereferencing
156 // a past-the-end iterator.
157 while (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) ++i;
161 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
162 // All valid basic blocks should have a terminator,
163 // which is not a PHINode. If we have an invalid basic
164 // block we'll get an assertion failure when dereferencing
165 // a past-the-end iterator.
166 BasicBlock::iterator i = begin();
168 if (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i))
171 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(i);
174 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
175 II->getIntrinsicID() != Intrinsic::lifetime_end)
181 BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
182 iterator InsertPt = getFirstNonPHI();
183 if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
187 void BasicBlock::dropAllReferences() {
188 for(iterator I = begin(), E = end(); I != E; ++I)
189 I->dropAllReferences();
192 /// getSinglePredecessor - If this basic block has a single predecessor block,
193 /// return the block, otherwise return a null pointer.
194 BasicBlock *BasicBlock::getSinglePredecessor() {
195 pred_iterator PI = pred_begin(this), E = pred_end(this);
196 if (PI == E) return nullptr; // No preds.
197 BasicBlock *ThePred = *PI;
199 return (PI == E) ? ThePred : nullptr /*multiple preds*/;
202 /// getUniquePredecessor - If this basic block has a unique predecessor block,
203 /// return the block, otherwise return a null pointer.
204 /// Note that unique predecessor doesn't mean single edge, there can be
205 /// multiple edges from the unique predecessor to this block (for example
206 /// a switch statement with multiple cases having the same destination).
207 BasicBlock *BasicBlock::getUniquePredecessor() {
208 pred_iterator PI = pred_begin(this), E = pred_end(this);
209 if (PI == E) return nullptr; // No preds.
210 BasicBlock *PredBB = *PI;
212 for (;PI != E; ++PI) {
215 // The same predecessor appears multiple times in the predecessor list.
221 /// removePredecessor - This method is used to notify a BasicBlock that the
222 /// specified Predecessor of the block is no longer able to reach it. This is
223 /// actually not used to update the Predecessor list, but is actually used to
224 /// update the PHI nodes that reside in the block. Note that this should be
225 /// called while the predecessor still refers to this block.
227 void BasicBlock::removePredecessor(BasicBlock *Pred,
228 bool DontDeleteUselessPHIs) {
229 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
230 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
231 "removePredecessor: BB is not a predecessor!");
233 if (InstList.empty()) return;
234 PHINode *APN = dyn_cast<PHINode>(&front());
235 if (!APN) return; // Quick exit.
237 // If there are exactly two predecessors, then we want to nuke the PHI nodes
238 // altogether. However, we cannot do this, if this in this case:
241 // %x = phi [X, Loop]
242 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
243 // br Loop ;; %x2 does not dominate all uses
245 // This is because the PHI node input is actually taken from the predecessor
246 // basic block. The only case this can happen is with a self loop, so we
247 // check for this case explicitly now.
249 unsigned max_idx = APN->getNumIncomingValues();
250 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
252 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
254 // Disable PHI elimination!
255 if (this == Other) max_idx = 3;
258 // <= Two predecessors BEFORE I remove one?
259 if (max_idx <= 2 && !DontDeleteUselessPHIs) {
260 // Yup, loop through and nuke the PHI nodes
261 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
262 // Remove the predecessor first.
263 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
265 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
267 if (PN->getIncomingValue(0) != PN)
268 PN->replaceAllUsesWith(PN->getIncomingValue(0));
270 // We are left with an infinite loop with no entries: kill the PHI.
271 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
272 getInstList().pop_front(); // Remove the PHI node
275 // If the PHI node already only had one entry, it got deleted by
276 // removeIncomingValue.
279 // Okay, now we know that we need to remove predecessor #pred_idx from all
280 // PHI nodes. Iterate over each PHI node fixing them up
282 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
284 PN->removeIncomingValue(Pred, false);
285 // If all incoming values to the Phi are the same, we can replace the Phi
287 Value* PNV = nullptr;
288 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
290 PN->replaceAllUsesWith(PNV);
291 PN->eraseFromParent();
298 /// splitBasicBlock - This splits a basic block into two at the specified
299 /// instruction. Note that all instructions BEFORE the specified iterator stay
300 /// as part of the original basic block, an unconditional branch is added to
301 /// the new BB, and the rest of the instructions in the BB are moved to the new
302 /// BB, including the old terminator. This invalidates the iterator.
304 /// Note that this only works on well formed basic blocks (must have a
305 /// terminator), and 'I' must not be the end of instruction list (which would
306 /// cause a degenerate basic block to be formed, having a terminator inside of
307 /// the basic block).
309 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
310 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
311 assert(I != InstList.end() &&
312 "Trying to get me to create degenerate basic block!");
314 BasicBlock *InsertBefore = std::next(Function::iterator(this))
315 .getNodePtrUnchecked();
316 BasicBlock *New = BasicBlock::Create(getContext(), BBName,
317 getParent(), InsertBefore);
319 // Move all of the specified instructions from the original basic block into
320 // the new basic block.
321 New->getInstList().splice(New->end(), this->getInstList(), I, end());
323 // Add a branch instruction to the newly formed basic block.
324 BranchInst::Create(New, this);
326 // Now we must loop through all of the successors of the New block (which
327 // _were_ the successors of the 'this' block), and update any PHI nodes in
328 // successors. If there were PHI nodes in the successors, then they need to
329 // know that incoming branches will be from New, not from Old.
331 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
332 // Loop over any phi nodes in the basic block, updating the BB field of
333 // incoming values...
334 BasicBlock *Successor = *I;
336 for (BasicBlock::iterator II = Successor->begin();
337 (PN = dyn_cast<PHINode>(II)); ++II) {
338 int IDX = PN->getBasicBlockIndex(this);
340 PN->setIncomingBlock((unsigned)IDX, New);
341 IDX = PN->getBasicBlockIndex(this);
348 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
349 TerminatorInst *TI = getTerminator();
351 // Cope with being called on a BasicBlock that doesn't have a terminator
352 // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
354 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
355 BasicBlock *Succ = TI->getSuccessor(i);
356 // N.B. Succ might not be a complete BasicBlock, so don't assume
357 // that it ends with a non-phi instruction.
358 for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
359 PHINode *PN = dyn_cast<PHINode>(II);
363 while ((i = PN->getBasicBlockIndex(this)) >= 0)
364 PN->setIncomingBlock(i, New);
369 /// isLandingPad - Return true if this basic block is a landing pad. I.e., it's
370 /// the destination of the 'unwind' edge of an invoke instruction.
371 bool BasicBlock::isLandingPad() const {
372 return isa<LandingPadInst>(getFirstNonPHI());
375 /// getLandingPadInst() - Return the landingpad instruction associated with
377 LandingPadInst *BasicBlock::getLandingPadInst() {
378 return dyn_cast<LandingPadInst>(getFirstNonPHI());
380 const LandingPadInst *BasicBlock::getLandingPadInst() const {
381 return dyn_cast<LandingPadInst>(getFirstNonPHI());