1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the BasicBlock class for the IR library.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/BasicBlock.h"
14 #include "SymbolTableListTraitsImpl.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/IR/CFG.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Type.h"
22 #include <algorithm>
23 
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 template <> void llvm::invalidateParentIListOrdering(BasicBlock *BB) {
37   BB->invalidateOrders();
38 }
39 
40 // Explicit instantiation of SymbolTableListTraits since some of the methods
41 // are not in the public header file...
42 template class llvm::SymbolTableListTraits<Instruction>;
43 
44 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
45                        BasicBlock *InsertBefore)
46   : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
47 
48   if (NewParent)
49     insertInto(NewParent, InsertBefore);
50   else
51     assert(!InsertBefore &&
52            "Cannot insert block before another block with no function!");
53 
54   setName(Name);
55 }
56 
57 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
58   assert(NewParent && "Expected a parent");
59   assert(!Parent && "Already has a parent");
60 
61   if (InsertBefore)
62     NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
63   else
64     NewParent->getBasicBlockList().push_back(this);
65 }
66 
67 BasicBlock::~BasicBlock() {
68   validateInstrOrdering();
69 
70   // If the address of the block is taken and it is being deleted (e.g. because
71   // it is dead), this means that there is either a dangling constant expr
72   // hanging off the block, or an undefined use of the block (source code
73   // expecting the address of a label to keep the block alive even though there
74   // is no indirect branch).  Handle these cases by zapping the BlockAddress
75   // nodes.  There are no other possible uses at this point.
76   if (hasAddressTaken()) {
77     assert(!use_empty() && "There should be at least one blockaddress!");
78     Constant *Replacement =
79       ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
80     while (!use_empty()) {
81       BlockAddress *BA = cast<BlockAddress>(user_back());
82       BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
83                                                        BA->getType()));
84       BA->destroyConstant();
85     }
86   }
87 
88   assert(getParent() == nullptr && "BasicBlock still linked into the program!");
89   dropAllReferences();
90   InstList.clear();
91 }
92 
93 void BasicBlock::setParent(Function *parent) {
94   // Set Parent=parent, updating instruction symtab entries as appropriate.
95   InstList.setSymTabObject(&Parent, parent);
96 }
97 
98 iterator_range<filter_iterator<BasicBlock::const_iterator,
99                                std::function<bool(const Instruction &)>>>
100 BasicBlock::instructionsWithoutDebug() const {
101   std::function<bool(const Instruction &)> Fn = [](const Instruction &I) {
102     return !isa<DbgInfoIntrinsic>(I);
103   };
104   return make_filter_range(*this, Fn);
105 }
106 
107 iterator_range<filter_iterator<BasicBlock::iterator,
108                                std::function<bool(Instruction &)>>>
109 BasicBlock::instructionsWithoutDebug() {
110   std::function<bool(Instruction &)> Fn = [](Instruction &I) {
111     return !isa<DbgInfoIntrinsic>(I);
112   };
113   return make_filter_range(*this, Fn);
114 }
115 
116 filter_iterator<BasicBlock::const_iterator,
117                 std::function<bool(const Instruction &)>>::difference_type
118 BasicBlock::sizeWithoutDebug() const {
119   return std::distance(instructionsWithoutDebug().begin(),
120                        instructionsWithoutDebug().end());
121 }
122 
123 void BasicBlock::removeFromParent() {
124   getParent()->getBasicBlockList().remove(getIterator());
125 }
126 
127 iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
128   return getParent()->getBasicBlockList().erase(getIterator());
129 }
130 
131 /// Unlink this basic block from its current function and
132 /// insert it into the function that MovePos lives in, right before MovePos.
133 void BasicBlock::moveBefore(BasicBlock *MovePos) {
134   MovePos->getParent()->getBasicBlockList().splice(
135       MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
136 }
137 
138 /// Unlink this basic block from its current function and
139 /// insert it into the function that MovePos lives in, right after MovePos.
140 void BasicBlock::moveAfter(BasicBlock *MovePos) {
141   MovePos->getParent()->getBasicBlockList().splice(
142       ++MovePos->getIterator(), getParent()->getBasicBlockList(),
143       getIterator());
144 }
145 
146 const Module *BasicBlock::getModule() const {
147   return getParent()->getParent();
148 }
149 
150 const Instruction *BasicBlock::getTerminator() const {
151   if (InstList.empty() || !InstList.back().isTerminator())
152     return nullptr;
153   return &InstList.back();
154 }
155 
156 const CallInst *BasicBlock::getTerminatingMustTailCall() const {
157   if (InstList.empty())
158     return nullptr;
159   const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
160   if (!RI || RI == &InstList.front())
161     return nullptr;
162 
163   const Instruction *Prev = RI->getPrevNode();
164   if (!Prev)
165     return nullptr;
166 
167   if (Value *RV = RI->getReturnValue()) {
168     if (RV != Prev)
169       return nullptr;
170 
171     // Look through the optional bitcast.
172     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
173       RV = BI->getOperand(0);
174       Prev = BI->getPrevNode();
175       if (!Prev || RV != Prev)
176         return nullptr;
177     }
178   }
179 
180   if (auto *CI = dyn_cast<CallInst>(Prev)) {
181     if (CI->isMustTailCall())
182       return CI;
183   }
184   return nullptr;
185 }
186 
187 const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
188   if (InstList.empty())
189     return nullptr;
190   auto *RI = dyn_cast<ReturnInst>(&InstList.back());
191   if (!RI || RI == &InstList.front())
192     return nullptr;
193 
194   if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
195     if (Function *F = CI->getCalledFunction())
196       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
197         return CI;
198 
199   return nullptr;
200 }
201 
202 const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const {
203   const BasicBlock* BB = this;
204   SmallPtrSet<const BasicBlock *, 8> Visited;
205   Visited.insert(BB);
206   while (auto *Succ = BB->getUniqueSuccessor()) {
207     if (!Visited.insert(Succ).second)
208       return nullptr;
209     BB = Succ;
210   }
211   return BB->getTerminatingDeoptimizeCall();
212 }
213 
214 const Instruction* BasicBlock::getFirstNonPHI() const {
215   for (const Instruction &I : *this)
216     if (!isa<PHINode>(I))
217       return &I;
218   return nullptr;
219 }
220 
221 const Instruction* BasicBlock::getFirstNonPHIOrDbg() const {
222   for (const Instruction &I : *this)
223     if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
224       return &I;
225   return nullptr;
226 }
227 
228 const Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() const {
229   for (const Instruction &I : *this) {
230     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
231       continue;
232 
233     if (I.isLifetimeStartOrEnd())
234       continue;
235 
236     return &I;
237   }
238   return nullptr;
239 }
240 
241 BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
242   const Instruction *FirstNonPHI = getFirstNonPHI();
243   if (!FirstNonPHI)
244     return end();
245 
246   const_iterator InsertPt = FirstNonPHI->getIterator();
247   if (InsertPt->isEHPad()) ++InsertPt;
248   return InsertPt;
249 }
250 
251 void BasicBlock::dropAllReferences() {
252   for (Instruction &I : *this)
253     I.dropAllReferences();
254 }
255 
256 /// If this basic block has a single predecessor block,
257 /// return the block, otherwise return a null pointer.
258 const BasicBlock *BasicBlock::getSinglePredecessor() const {
259   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
260   if (PI == E) return nullptr;         // No preds.
261   const BasicBlock *ThePred = *PI;
262   ++PI;
263   return (PI == E) ? ThePred : nullptr /*multiple preds*/;
264 }
265 
266 /// If this basic block has a unique predecessor block,
267 /// return the block, otherwise return a null pointer.
268 /// Note that unique predecessor doesn't mean single edge, there can be
269 /// multiple edges from the unique predecessor to this block (for example
270 /// a switch statement with multiple cases having the same destination).
271 const BasicBlock *BasicBlock::getUniquePredecessor() const {
272   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
273   if (PI == E) return nullptr; // No preds.
274   const BasicBlock *PredBB = *PI;
275   ++PI;
276   for (;PI != E; ++PI) {
277     if (*PI != PredBB)
278       return nullptr;
279     // The same predecessor appears multiple times in the predecessor list.
280     // This is OK.
281   }
282   return PredBB;
283 }
284 
285 bool BasicBlock::hasNPredecessors(unsigned N) const {
286   return hasNItems(pred_begin(this), pred_end(this), N);
287 }
288 
289 bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
290   return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
291 }
292 
293 const BasicBlock *BasicBlock::getSingleSuccessor() const {
294   const_succ_iterator SI = succ_begin(this), E = succ_end(this);
295   if (SI == E) return nullptr; // no successors
296   const BasicBlock *TheSucc = *SI;
297   ++SI;
298   return (SI == E) ? TheSucc : nullptr /* multiple successors */;
299 }
300 
301 const BasicBlock *BasicBlock::getUniqueSuccessor() const {
302   const_succ_iterator SI = succ_begin(this), E = succ_end(this);
303   if (SI == E) return nullptr; // No successors
304   const BasicBlock *SuccBB = *SI;
305   ++SI;
306   for (;SI != E; ++SI) {
307     if (*SI != SuccBB)
308       return nullptr;
309     // The same successor appears multiple times in the successor list.
310     // This is OK.
311   }
312   return SuccBB;
313 }
314 
315 iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
316   PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
317   return make_range<phi_iterator>(P, nullptr);
318 }
319 
320 /// Update PHI nodes in this BasicBlock before removal of predecessor \p Pred.
321 /// Note that this function does not actually remove the predecessor.
322 ///
323 /// If \p KeepOneInputPHIs is true then don't remove PHIs that are left with
324 /// zero or one incoming values, and don't simplify PHIs with all incoming
325 /// values the same.
326 void BasicBlock::removePredecessor(BasicBlock *Pred,
327                                    bool KeepOneInputPHIs) {
328   // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs.
329   assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) &&
330          "Pred is not a predecessor!");
331 
332   // Return early if there are no PHI nodes to update.
333   if (!isa<PHINode>(begin()))
334     return;
335   unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();
336 
337   // Update all PHI nodes.
338   for (iterator II = begin(); isa<PHINode>(II);) {
339     PHINode *PN = cast<PHINode>(II++);
340     PN->removeIncomingValue(Pred, !KeepOneInputPHIs);
341     if (!KeepOneInputPHIs) {
342       // If we have a single predecessor, removeIncomingValue erased the PHI
343       // node itself.
344       if (NumPreds > 1) {
345         if (Value *PNV = PN->hasConstantValue()) {
346           // Replace the PHI node with its constant value.
347           PN->replaceAllUsesWith(PNV);
348           PN->eraseFromParent();
349         }
350       }
351     }
352   }
353 }
354 
355 bool BasicBlock::canSplitPredecessors() const {
356   const Instruction *FirstNonPHI = getFirstNonPHI();
357   if (isa<LandingPadInst>(FirstNonPHI))
358     return true;
359   // This is perhaps a little conservative because constructs like
360   // CleanupBlockInst are pretty easy to split.  However, SplitBlockPredecessors
361   // cannot handle such things just yet.
362   if (FirstNonPHI->isEHPad())
363     return false;
364   return true;
365 }
366 
367 bool BasicBlock::isLegalToHoistInto() const {
368   auto *Term = getTerminator();
369   // No terminator means the block is under construction.
370   if (!Term)
371     return true;
372 
373   // If the block has no successors, there can be no instructions to hoist.
374   assert(Term->getNumSuccessors() > 0);
375 
376   // Instructions should not be hoisted across exception handling boundaries.
377   return !Term->isExceptionalTerminator();
378 }
379 
380 /// This splits a basic block into two at the specified
381 /// instruction.  Note that all instructions BEFORE the specified iterator stay
382 /// as part of the original basic block, an unconditional branch is added to
383 /// the new BB, and the rest of the instructions in the BB are moved to the new
384 /// BB, including the old terminator.  This invalidates the iterator.
385 ///
386 /// Note that this only works on well formed basic blocks (must have a
387 /// terminator), and 'I' must not be the end of instruction list (which would
388 /// cause a degenerate basic block to be formed, having a terminator inside of
389 /// the basic block).
390 ///
391 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
392   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
393   assert(I != InstList.end() &&
394          "Trying to get me to create degenerate basic block!");
395 
396   BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
397                                        this->getNextNode());
398 
399   // Save DebugLoc of split point before invalidating iterator.
400   DebugLoc Loc = I->getDebugLoc();
401   // Move all of the specified instructions from the original basic block into
402   // the new basic block.
403   New->getInstList().splice(New->end(), this->getInstList(), I, end());
404 
405   // Add a branch instruction to the newly formed basic block.
406   BranchInst *BI = BranchInst::Create(New, this);
407   BI->setDebugLoc(Loc);
408 
409   // Now we must loop through all of the successors of the New block (which
410   // _were_ the successors of the 'this' block), and update any PHI nodes in
411   // successors.  If there were PHI nodes in the successors, then they need to
412   // know that incoming branches will be from New, not from Old (this).
413   //
414   New->replaceSuccessorsPhiUsesWith(this, New);
415   return New;
416 }
417 
418 void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {
419   // N.B. This might not be a complete BasicBlock, so don't assume
420   // that it ends with a non-phi instruction.
421   for (iterator II = begin(), IE = end(); II != IE; ++II) {
422     PHINode *PN = dyn_cast<PHINode>(II);
423     if (!PN)
424       break;
425     PN->replaceIncomingBlockWith(Old, New);
426   }
427 }
428 
429 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,
430                                               BasicBlock *New) {
431   Instruction *TI = getTerminator();
432   if (!TI)
433     // Cope with being called on a BasicBlock that doesn't have a terminator
434     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
435     return;
436   llvm::for_each(successors(TI), [Old, New](BasicBlock *Succ) {
437     Succ->replacePhiUsesWith(Old, New);
438   });
439 }
440 
441 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
442   this->replaceSuccessorsPhiUsesWith(this, New);
443 }
444 
445 /// Return true if this basic block is a landing pad. I.e., it's
446 /// the destination of the 'unwind' edge of an invoke instruction.
447 bool BasicBlock::isLandingPad() const {
448   return isa<LandingPadInst>(getFirstNonPHI());
449 }
450 
451 /// Return the landingpad instruction associated with the landing pad.
452 const LandingPadInst *BasicBlock::getLandingPadInst() const {
453   return dyn_cast<LandingPadInst>(getFirstNonPHI());
454 }
455 
456 Optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
457   const Instruction *TI = getTerminator();
458   if (MDNode *MDIrrLoopHeader =
459       TI->getMetadata(LLVMContext::MD_irr_loop)) {
460     MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
461     if (MDName->getString().equals("loop_header_weight")) {
462       auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
463       return Optional<uint64_t>(CI->getValue().getZExtValue());
464     }
465   }
466   return Optional<uint64_t>();
467 }
468 
469 BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
470   while (isa<DbgInfoIntrinsic>(It))
471     ++It;
472   return It;
473 }
474 
475 void BasicBlock::renumberInstructions() {
476   unsigned Order = 0;
477   for (Instruction &I : *this)
478     I.Order = Order++;
479 
480   // Set the bit to indicate that the instruction order valid and cached.
481   BasicBlockBits Bits = getBasicBlockBits();
482   Bits.InstrOrderValid = true;
483   setBasicBlockBits(Bits);
484 }
485 
486 #ifndef NDEBUG
487 /// In asserts builds, this checks the numbering. In non-asserts builds, it
488 /// is defined as a no-op inline function in BasicBlock.h.
489 void BasicBlock::validateInstrOrdering() const {
490   if (!isInstrOrderValid())
491     return;
492   const Instruction *Prev = nullptr;
493   for (const Instruction &I : *this) {
494     assert((!Prev || Prev->comesBefore(&I)) &&
495            "cached instruction ordering is incorrect");
496     Prev = &I;
497   }
498 }
499 #endif
500