xref: /freebsd/contrib/llvm-project/llvm/lib/IR/BasicBlock.cpp (revision ebacd8013fe5f7fdf9f6a5b286f6680dd2891036)
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/ADT/Statistic.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 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "ir"
27 STATISTIC(NumInstrRenumberings, "Number of renumberings across all blocks");
28 
29 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
30   if (Function *F = getParent())
31     return F->getValueSymbolTable();
32   return nullptr;
33 }
34 
35 LLVMContext &BasicBlock::getContext() const {
36   return getType()->getContext();
37 }
38 
39 template <> void llvm::invalidateParentIListOrdering(BasicBlock *BB) {
40   BB->invalidateOrders();
41 }
42 
43 // Explicit instantiation of SymbolTableListTraits since some of the methods
44 // are not in the public header file...
45 template class llvm::SymbolTableListTraits<Instruction>;
46 
47 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
48                        BasicBlock *InsertBefore)
49   : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
50 
51   if (NewParent)
52     insertInto(NewParent, InsertBefore);
53   else
54     assert(!InsertBefore &&
55            "Cannot insert block before another block with no function!");
56 
57   setName(Name);
58 }
59 
60 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
61   assert(NewParent && "Expected a parent");
62   assert(!Parent && "Already has a parent");
63 
64   if (InsertBefore)
65     NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
66   else
67     NewParent->getBasicBlockList().push_back(this);
68 }
69 
70 BasicBlock::~BasicBlock() {
71   validateInstrOrdering();
72 
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,
86                                                        BA->getType()));
87       BA->destroyConstant();
88     }
89   }
90 
91   assert(getParent() == nullptr && "BasicBlock still linked into the program!");
92   dropAllReferences();
93   InstList.clear();
94 }
95 
96 void BasicBlock::setParent(Function *parent) {
97   // Set Parent=parent, updating instruction symtab entries as appropriate.
98   InstList.setSymTabObject(&Parent, parent);
99 }
100 
101 iterator_range<filter_iterator<BasicBlock::const_iterator,
102                                std::function<bool(const Instruction &)>>>
103 BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) const {
104   std::function<bool(const Instruction &)> Fn = [=](const Instruction &I) {
105     return !isa<DbgInfoIntrinsic>(I) &&
106            !(SkipPseudoOp && isa<PseudoProbeInst>(I));
107   };
108   return make_filter_range(*this, Fn);
109 }
110 
111 iterator_range<
112     filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>>
113 BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) {
114   std::function<bool(Instruction &)> Fn = [=](Instruction &I) {
115     return !isa<DbgInfoIntrinsic>(I) &&
116            !(SkipPseudoOp && isa<PseudoProbeInst>(I));
117   };
118   return make_filter_range(*this, Fn);
119 }
120 
121 filter_iterator<BasicBlock::const_iterator,
122                 std::function<bool(const Instruction &)>>::difference_type
123 BasicBlock::sizeWithoutDebug() const {
124   return std::distance(instructionsWithoutDebug().begin(),
125                        instructionsWithoutDebug().end());
126 }
127 
128 void BasicBlock::removeFromParent() {
129   getParent()->getBasicBlockList().remove(getIterator());
130 }
131 
132 iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
133   return getParent()->getBasicBlockList().erase(getIterator());
134 }
135 
136 void BasicBlock::moveBefore(BasicBlock *MovePos) {
137   MovePos->getParent()->getBasicBlockList().splice(
138       MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
139 }
140 
141 void BasicBlock::moveAfter(BasicBlock *MovePos) {
142   MovePos->getParent()->getBasicBlockList().splice(
143       ++MovePos->getIterator(), getParent()->getBasicBlockList(),
144       getIterator());
145 }
146 
147 const Module *BasicBlock::getModule() const {
148   return getParent()->getParent();
149 }
150 
151 const CallInst *BasicBlock::getTerminatingMustTailCall() const {
152   if (InstList.empty())
153     return nullptr;
154   const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
155   if (!RI || RI == &InstList.front())
156     return nullptr;
157 
158   const Instruction *Prev = RI->getPrevNode();
159   if (!Prev)
160     return nullptr;
161 
162   if (Value *RV = RI->getReturnValue()) {
163     if (RV != Prev)
164       return nullptr;
165 
166     // Look through the optional bitcast.
167     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
168       RV = BI->getOperand(0);
169       Prev = BI->getPrevNode();
170       if (!Prev || RV != Prev)
171         return nullptr;
172     }
173   }
174 
175   if (auto *CI = dyn_cast<CallInst>(Prev)) {
176     if (CI->isMustTailCall())
177       return CI;
178   }
179   return nullptr;
180 }
181 
182 const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
183   if (InstList.empty())
184     return nullptr;
185   auto *RI = dyn_cast<ReturnInst>(&InstList.back());
186   if (!RI || RI == &InstList.front())
187     return nullptr;
188 
189   if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
190     if (Function *F = CI->getCalledFunction())
191       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
192         return CI;
193 
194   return nullptr;
195 }
196 
197 const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const {
198   const BasicBlock* BB = this;
199   SmallPtrSet<const BasicBlock *, 8> Visited;
200   Visited.insert(BB);
201   while (auto *Succ = BB->getUniqueSuccessor()) {
202     if (!Visited.insert(Succ).second)
203       return nullptr;
204     BB = Succ;
205   }
206   return BB->getTerminatingDeoptimizeCall();
207 }
208 
209 const Instruction* BasicBlock::getFirstNonPHI() const {
210   for (const Instruction &I : *this)
211     if (!isa<PHINode>(I))
212       return &I;
213   return nullptr;
214 }
215 
216 const Instruction *BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const {
217   for (const Instruction &I : *this) {
218     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
219       continue;
220 
221     if (SkipPseudoOp && isa<PseudoProbeInst>(I))
222       continue;
223 
224     return &I;
225   }
226   return nullptr;
227 }
228 
229 const Instruction *
230 BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const {
231   for (const Instruction &I : *this) {
232     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
233       continue;
234 
235     if (I.isLifetimeStartOrEnd())
236       continue;
237 
238     if (SkipPseudoOp && isa<PseudoProbeInst>(I))
239       continue;
240 
241     return &I;
242   }
243   return nullptr;
244 }
245 
246 BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
247   const Instruction *FirstNonPHI = getFirstNonPHI();
248   if (!FirstNonPHI)
249     return end();
250 
251   const_iterator InsertPt = FirstNonPHI->getIterator();
252   if (InsertPt->isEHPad()) ++InsertPt;
253   return InsertPt;
254 }
255 
256 void BasicBlock::dropAllReferences() {
257   for (Instruction &I : *this)
258     I.dropAllReferences();
259 }
260 
261 const BasicBlock *BasicBlock::getSinglePredecessor() const {
262   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
263   if (PI == E) return nullptr;         // No preds.
264   const BasicBlock *ThePred = *PI;
265   ++PI;
266   return (PI == E) ? ThePred : nullptr /*multiple preds*/;
267 }
268 
269 const BasicBlock *BasicBlock::getUniquePredecessor() const {
270   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
271   if (PI == E) return nullptr; // No preds.
272   const BasicBlock *PredBB = *PI;
273   ++PI;
274   for (;PI != E; ++PI) {
275     if (*PI != PredBB)
276       return nullptr;
277     // The same predecessor appears multiple times in the predecessor list.
278     // This is OK.
279   }
280   return PredBB;
281 }
282 
283 bool BasicBlock::hasNPredecessors(unsigned N) const {
284   return hasNItems(pred_begin(this), pred_end(this), N);
285 }
286 
287 bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
288   return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
289 }
290 
291 const BasicBlock *BasicBlock::getSingleSuccessor() const {
292   const_succ_iterator SI = succ_begin(this), E = succ_end(this);
293   if (SI == E) return nullptr; // no successors
294   const BasicBlock *TheSucc = *SI;
295   ++SI;
296   return (SI == E) ? TheSucc : nullptr /* multiple successors */;
297 }
298 
299 const BasicBlock *BasicBlock::getUniqueSuccessor() const {
300   const_succ_iterator SI = succ_begin(this), E = succ_end(this);
301   if (SI == E) return nullptr; // No successors
302   const BasicBlock *SuccBB = *SI;
303   ++SI;
304   for (;SI != E; ++SI) {
305     if (*SI != SuccBB)
306       return nullptr;
307     // The same successor appears multiple times in the successor list.
308     // This is OK.
309   }
310   return SuccBB;
311 }
312 
313 iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
314   PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
315   return make_range<phi_iterator>(P, nullptr);
316 }
317 
318 void BasicBlock::removePredecessor(BasicBlock *Pred,
319                                    bool KeepOneInputPHIs) {
320   // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs.
321   assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) &&
322          "Pred is not a predecessor!");
323 
324   // Return early if there are no PHI nodes to update.
325   if (empty() || !isa<PHINode>(begin()))
326     return;
327 
328   unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();
329   for (PHINode &Phi : make_early_inc_range(phis())) {
330     Phi.removeIncomingValue(Pred, !KeepOneInputPHIs);
331     if (KeepOneInputPHIs)
332       continue;
333 
334     // If we have a single predecessor, removeIncomingValue may have erased the
335     // PHI node itself.
336     if (NumPreds == 1)
337       continue;
338 
339     // Try to replace the PHI node with a constant value.
340     if (Value *PhiConstant = Phi.hasConstantValue()) {
341       Phi.replaceAllUsesWith(PhiConstant);
342       Phi.eraseFromParent();
343     }
344   }
345 }
346 
347 bool BasicBlock::canSplitPredecessors() const {
348   const Instruction *FirstNonPHI = getFirstNonPHI();
349   if (isa<LandingPadInst>(FirstNonPHI))
350     return true;
351   // This is perhaps a little conservative because constructs like
352   // CleanupBlockInst are pretty easy to split.  However, SplitBlockPredecessors
353   // cannot handle such things just yet.
354   if (FirstNonPHI->isEHPad())
355     return false;
356   return true;
357 }
358 
359 bool BasicBlock::isLegalToHoistInto() const {
360   auto *Term = getTerminator();
361   // No terminator means the block is under construction.
362   if (!Term)
363     return true;
364 
365   // If the block has no successors, there can be no instructions to hoist.
366   assert(Term->getNumSuccessors() > 0);
367 
368   // Instructions should not be hoisted across exception handling boundaries.
369   return !Term->isExceptionalTerminator();
370 }
371 
372 bool BasicBlock::isEntryBlock() const {
373   const Function *F = getParent();
374   assert(F && "Block must have a parent function to use this API");
375   return this == &F->getEntryBlock();
376 }
377 
378 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName,
379                                         bool Before) {
380   if (Before)
381     return splitBasicBlockBefore(I, BBName);
382 
383   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
384   assert(I != InstList.end() &&
385          "Trying to get me to create degenerate basic block!");
386 
387   BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
388                                        this->getNextNode());
389 
390   // Save DebugLoc of split point before invalidating iterator.
391   DebugLoc Loc = I->getDebugLoc();
392   // Move all of the specified instructions from the original basic block into
393   // the new basic block.
394   New->getInstList().splice(New->end(), this->getInstList(), I, end());
395 
396   // Add a branch instruction to the newly formed basic block.
397   BranchInst *BI = BranchInst::Create(New, this);
398   BI->setDebugLoc(Loc);
399 
400   // Now we must loop through all of the successors of the New block (which
401   // _were_ the successors of the 'this' block), and update any PHI nodes in
402   // successors.  If there were PHI nodes in the successors, then they need to
403   // know that incoming branches will be from New, not from Old (this).
404   //
405   New->replaceSuccessorsPhiUsesWith(this, New);
406   return New;
407 }
408 
409 BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) {
410   assert(getTerminator() &&
411          "Can't use splitBasicBlockBefore on degenerate BB!");
412   assert(I != InstList.end() &&
413          "Trying to get me to create degenerate basic block!");
414 
415   assert((!isa<PHINode>(*I) || getSinglePredecessor()) &&
416          "cannot split on multi incoming phis");
417 
418   BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this);
419   // Save DebugLoc of split point before invalidating iterator.
420   DebugLoc Loc = I->getDebugLoc();
421   // Move all of the specified instructions from the original basic block into
422   // the new basic block.
423   New->getInstList().splice(New->end(), this->getInstList(), begin(), I);
424 
425   // Loop through all of the predecessors of the 'this' block (which will be the
426   // predecessors of the New block), replace the specified successor 'this'
427   // block to point at the New block and update any PHI nodes in 'this' block.
428   // If there were PHI nodes in 'this' block, the PHI nodes are updated
429   // to reflect that the incoming branches will be from the New block and not
430   // from predecessors of the 'this' block.
431   for (BasicBlock *Pred : predecessors(this)) {
432     Instruction *TI = Pred->getTerminator();
433     TI->replaceSuccessorWith(this, New);
434     this->replacePhiUsesWith(Pred, New);
435   }
436   // Add a branch instruction from  "New" to "this" Block.
437   BranchInst *BI = BranchInst::Create(this, New);
438   BI->setDebugLoc(Loc);
439 
440   return New;
441 }
442 
443 void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {
444   // N.B. This might not be a complete BasicBlock, so don't assume
445   // that it ends with a non-phi instruction.
446   for (Instruction &I : *this) {
447     PHINode *PN = dyn_cast<PHINode>(&I);
448     if (!PN)
449       break;
450     PN->replaceIncomingBlockWith(Old, New);
451   }
452 }
453 
454 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,
455                                               BasicBlock *New) {
456   Instruction *TI = getTerminator();
457   if (!TI)
458     // Cope with being called on a BasicBlock that doesn't have a terminator
459     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
460     return;
461   for (BasicBlock *Succ : successors(TI))
462     Succ->replacePhiUsesWith(Old, New);
463 }
464 
465 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
466   this->replaceSuccessorsPhiUsesWith(this, New);
467 }
468 
469 bool BasicBlock::isLandingPad() const {
470   return isa<LandingPadInst>(getFirstNonPHI());
471 }
472 
473 const LandingPadInst *BasicBlock::getLandingPadInst() const {
474   return dyn_cast<LandingPadInst>(getFirstNonPHI());
475 }
476 
477 Optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
478   const Instruction *TI = getTerminator();
479   if (MDNode *MDIrrLoopHeader =
480       TI->getMetadata(LLVMContext::MD_irr_loop)) {
481     MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
482     if (MDName->getString().equals("loop_header_weight")) {
483       auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
484       return Optional<uint64_t>(CI->getValue().getZExtValue());
485     }
486   }
487   return Optional<uint64_t>();
488 }
489 
490 BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
491   while (isa<DbgInfoIntrinsic>(It))
492     ++It;
493   return It;
494 }
495 
496 void BasicBlock::renumberInstructions() {
497   unsigned Order = 0;
498   for (Instruction &I : *this)
499     I.Order = Order++;
500 
501   // Set the bit to indicate that the instruction order valid and cached.
502   BasicBlockBits Bits = getBasicBlockBits();
503   Bits.InstrOrderValid = true;
504   setBasicBlockBits(Bits);
505 
506   NumInstrRenumberings++;
507 }
508 
509 #ifndef NDEBUG
510 /// In asserts builds, this checks the numbering. In non-asserts builds, it
511 /// is defined as a no-op inline function in BasicBlock.h.
512 void BasicBlock::validateInstrOrdering() const {
513   if (!isInstrOrderValid())
514     return;
515   const Instruction *Prev = nullptr;
516   for (const Instruction &I : *this) {
517     assert((!Prev || Prev->comesBefore(&I)) &&
518            "cached instruction ordering is incorrect");
519     Prev = &I;
520   }
521 }
522 #endif
523