xref: /freebsd/contrib/llvm-project/llvm/lib/IR/BasicBlock.cpp (revision 5b56413d04e608379c9a306373554a8e4d321bc0)
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/DebugProgramInstruction.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Type.h"
24 #include "llvm/Support/CommandLine.h"
25 
26 #include "LLVMContextImpl.h"
27 
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "ir"
31 STATISTIC(NumInstrRenumberings, "Number of renumberings across all blocks");
32 
33 cl::opt<bool>
34     UseNewDbgInfoFormat("experimental-debuginfo-iterators",
35                         cl::desc("Enable communicating debuginfo positions "
36                                  "through iterators, eliminating intrinsics"),
37                         cl::init(false));
38 
39 DPMarker *BasicBlock::createMarker(Instruction *I) {
40   assert(IsNewDbgInfoFormat &&
41          "Tried to create a marker in a non new debug-info block!");
42   if (I->DbgMarker)
43     return I->DbgMarker;
44   DPMarker *Marker = new DPMarker();
45   Marker->MarkedInstr = I;
46   I->DbgMarker = Marker;
47   return Marker;
48 }
49 
50 DPMarker *BasicBlock::createMarker(InstListType::iterator It) {
51   assert(IsNewDbgInfoFormat &&
52          "Tried to create a marker in a non new debug-info block!");
53   if (It != end())
54     return createMarker(&*It);
55   DPMarker *DPM = getTrailingDPValues();
56   if (DPM)
57     return DPM;
58   DPM = new DPMarker();
59   setTrailingDPValues(DPM);
60   return DPM;
61 }
62 
63 void BasicBlock::convertToNewDbgValues() {
64   // Is the command line option set?
65   if (!UseNewDbgInfoFormat)
66     return;
67 
68   IsNewDbgInfoFormat = true;
69 
70   // Iterate over all instructions in the instruction list, collecting dbg.value
71   // instructions and converting them to DPValues. Once we find a "real"
72   // instruction, attach all those DPValues to a DPMarker in that instruction.
73   SmallVector<DPValue *, 4> DPVals;
74   for (Instruction &I : make_early_inc_range(InstList)) {
75     assert(!I.DbgMarker && "DbgMarker already set on old-format instrs?");
76     if (DbgVariableIntrinsic *DVI = dyn_cast<DbgVariableIntrinsic>(&I)) {
77       // Convert this dbg.value to a DPValue.
78       DPValue *Value = new DPValue(DVI);
79       DPVals.push_back(Value);
80       DVI->eraseFromParent();
81       continue;
82     }
83 
84     // Create a marker to store DPValues in. Technically we don't need to store
85     // one marker per instruction, but that's a future optimisation.
86     createMarker(&I);
87     DPMarker *Marker = I.DbgMarker;
88 
89     for (DPValue *DPV : DPVals)
90       Marker->insertDPValue(DPV, false);
91 
92     DPVals.clear();
93   }
94 }
95 
96 void BasicBlock::convertFromNewDbgValues() {
97   invalidateOrders();
98   IsNewDbgInfoFormat = false;
99 
100   // Iterate over the block, finding instructions annotated with DPMarkers.
101   // Convert any attached DPValues to dbg.values and insert ahead of the
102   // instruction.
103   for (auto &Inst : *this) {
104     if (!Inst.DbgMarker)
105       continue;
106 
107     DPMarker &Marker = *Inst.DbgMarker;
108     for (DPValue &DPV : Marker.getDbgValueRange())
109       InstList.insert(Inst.getIterator(),
110                       DPV.createDebugIntrinsic(getModule(), nullptr));
111 
112     Marker.eraseFromParent();
113   };
114 
115   // Assume no trailing DPValues: we could technically create them at the end
116   // of the block, after a terminator, but this would be non-cannonical and
117   // indicates that something else is broken somewhere.
118   assert(!getTrailingDPValues());
119 }
120 
121 bool BasicBlock::validateDbgValues(bool Assert, bool Msg, raw_ostream *OS) {
122   bool RetVal = false;
123   if (!OS)
124     OS = &errs();
125 
126   // Helper lambda for reporting failures: via assertion, printing, and return
127   // value.
128   auto TestFailure = [Assert, Msg, &RetVal, OS](bool Val, const char *Text) {
129     // Did the test fail?
130     if (Val)
131       return;
132 
133     // If we're asserting, then fire off an assertion.
134     if (Assert)
135       llvm_unreachable(Text);
136 
137     if (Msg)
138       *OS << Text << "\n";
139     RetVal = true;
140   };
141 
142   // We should have the same debug-format as the parent function.
143   TestFailure(getParent()->IsNewDbgInfoFormat == IsNewDbgInfoFormat,
144               "Parent function doesn't have the same debug-info format");
145 
146   // Only validate if we are using the new format.
147   if (!IsNewDbgInfoFormat)
148     return RetVal;
149 
150   // Match every DPMarker to every Instruction and vice versa, and
151   // verify that there are no invalid DPValues.
152   for (auto It = begin(); It != end(); ++It) {
153     if (!It->DbgMarker)
154       continue;
155 
156     // Validate DebugProgramMarkers.
157     DPMarker *CurrentDebugMarker = It->DbgMarker;
158 
159     // If this is a marker, it should match the instruction and vice versa.
160     TestFailure(CurrentDebugMarker->MarkedInstr == &*It,
161                 "Debug Marker points to incorrect instruction?");
162 
163     // Now validate any DPValues in the marker.
164     for (DPValue &DPV : CurrentDebugMarker->getDbgValueRange()) {
165       // Validate DebugProgramValues.
166       TestFailure(DPV.getMarker() == CurrentDebugMarker,
167                   "Not pointing at correct next marker!");
168 
169       // Verify that no DbgValues appear prior to PHIs.
170       TestFailure(
171           !isa<PHINode>(It),
172           "DebugProgramValues must not appear before PHI nodes in a block!");
173     }
174   }
175 
176   // Except transiently when removing + re-inserting the block terminator, there
177   // should be no trailing DPValues.
178   TestFailure(!getTrailingDPValues(), "Trailing DPValues in block");
179   return RetVal;
180 }
181 
182 #ifndef NDEBUG
183 void BasicBlock::dumpDbgValues() const {
184   for (auto &Inst : *this) {
185     if (!Inst.DbgMarker)
186       continue;
187 
188     dbgs() << "@ " << Inst.DbgMarker << " ";
189     Inst.DbgMarker->dump();
190   };
191 }
192 #endif
193 
194 void BasicBlock::setIsNewDbgInfoFormat(bool NewFlag) {
195   if (NewFlag && !IsNewDbgInfoFormat)
196     convertToNewDbgValues();
197   else if (!NewFlag && IsNewDbgInfoFormat)
198     convertFromNewDbgValues();
199 }
200 
201 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
202   if (Function *F = getParent())
203     return F->getValueSymbolTable();
204   return nullptr;
205 }
206 
207 LLVMContext &BasicBlock::getContext() const {
208   return getType()->getContext();
209 }
210 
211 template <> void llvm::invalidateParentIListOrdering(BasicBlock *BB) {
212   BB->invalidateOrders();
213 }
214 
215 // Explicit instantiation of SymbolTableListTraits since some of the methods
216 // are not in the public header file...
217 template class llvm::SymbolTableListTraits<Instruction,
218                                            ilist_iterator_bits<true>>;
219 
220 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
221                        BasicBlock *InsertBefore)
222     : Value(Type::getLabelTy(C), Value::BasicBlockVal),
223       IsNewDbgInfoFormat(false), Parent(nullptr) {
224 
225   if (NewParent)
226     insertInto(NewParent, InsertBefore);
227   else
228     assert(!InsertBefore &&
229            "Cannot insert block before another block with no function!");
230 
231   setName(Name);
232   if (NewParent)
233     setIsNewDbgInfoFormat(NewParent->IsNewDbgInfoFormat);
234 }
235 
236 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
237   assert(NewParent && "Expected a parent");
238   assert(!Parent && "Already has a parent");
239 
240   if (InsertBefore)
241     NewParent->insert(InsertBefore->getIterator(), this);
242   else
243     NewParent->insert(NewParent->end(), this);
244 
245   setIsNewDbgInfoFormat(NewParent->IsNewDbgInfoFormat);
246 }
247 
248 BasicBlock::~BasicBlock() {
249   validateInstrOrdering();
250 
251   // If the address of the block is taken and it is being deleted (e.g. because
252   // it is dead), this means that there is either a dangling constant expr
253   // hanging off the block, or an undefined use of the block (source code
254   // expecting the address of a label to keep the block alive even though there
255   // is no indirect branch).  Handle these cases by zapping the BlockAddress
256   // nodes.  There are no other possible uses at this point.
257   if (hasAddressTaken()) {
258     assert(!use_empty() && "There should be at least one blockaddress!");
259     Constant *Replacement =
260       ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
261     while (!use_empty()) {
262       BlockAddress *BA = cast<BlockAddress>(user_back());
263       BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
264                                                        BA->getType()));
265       BA->destroyConstant();
266     }
267   }
268 
269   assert(getParent() == nullptr && "BasicBlock still linked into the program!");
270   dropAllReferences();
271   for (auto &Inst : *this) {
272     if (!Inst.DbgMarker)
273       continue;
274     Inst.DbgMarker->eraseFromParent();
275   }
276   InstList.clear();
277 }
278 
279 void BasicBlock::setParent(Function *parent) {
280   // Set Parent=parent, updating instruction symtab entries as appropriate.
281   InstList.setSymTabObject(&Parent, parent);
282 }
283 
284 iterator_range<filter_iterator<BasicBlock::const_iterator,
285                                std::function<bool(const Instruction &)>>>
286 BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) const {
287   std::function<bool(const Instruction &)> Fn = [=](const Instruction &I) {
288     return !isa<DbgInfoIntrinsic>(I) &&
289            !(SkipPseudoOp && isa<PseudoProbeInst>(I));
290   };
291   return make_filter_range(*this, Fn);
292 }
293 
294 iterator_range<
295     filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>>
296 BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) {
297   std::function<bool(Instruction &)> Fn = [=](Instruction &I) {
298     return !isa<DbgInfoIntrinsic>(I) &&
299            !(SkipPseudoOp && isa<PseudoProbeInst>(I));
300   };
301   return make_filter_range(*this, Fn);
302 }
303 
304 filter_iterator<BasicBlock::const_iterator,
305                 std::function<bool(const Instruction &)>>::difference_type
306 BasicBlock::sizeWithoutDebug() const {
307   return std::distance(instructionsWithoutDebug().begin(),
308                        instructionsWithoutDebug().end());
309 }
310 
311 void BasicBlock::removeFromParent() {
312   getParent()->getBasicBlockList().remove(getIterator());
313 }
314 
315 iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
316   return getParent()->getBasicBlockList().erase(getIterator());
317 }
318 
319 void BasicBlock::moveBefore(SymbolTableList<BasicBlock>::iterator MovePos) {
320   getParent()->splice(MovePos, getParent(), getIterator());
321 }
322 
323 void BasicBlock::moveAfter(BasicBlock *MovePos) {
324   MovePos->getParent()->splice(++MovePos->getIterator(), getParent(),
325                                getIterator());
326 }
327 
328 const Module *BasicBlock::getModule() const {
329   return getParent()->getParent();
330 }
331 
332 const CallInst *BasicBlock::getTerminatingMustTailCall() const {
333   if (InstList.empty())
334     return nullptr;
335   const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
336   if (!RI || RI == &InstList.front())
337     return nullptr;
338 
339   const Instruction *Prev = RI->getPrevNode();
340   if (!Prev)
341     return nullptr;
342 
343   if (Value *RV = RI->getReturnValue()) {
344     if (RV != Prev)
345       return nullptr;
346 
347     // Look through the optional bitcast.
348     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
349       RV = BI->getOperand(0);
350       Prev = BI->getPrevNode();
351       if (!Prev || RV != Prev)
352         return nullptr;
353     }
354   }
355 
356   if (auto *CI = dyn_cast<CallInst>(Prev)) {
357     if (CI->isMustTailCall())
358       return CI;
359   }
360   return nullptr;
361 }
362 
363 const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
364   if (InstList.empty())
365     return nullptr;
366   auto *RI = dyn_cast<ReturnInst>(&InstList.back());
367   if (!RI || RI == &InstList.front())
368     return nullptr;
369 
370   if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
371     if (Function *F = CI->getCalledFunction())
372       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
373         return CI;
374 
375   return nullptr;
376 }
377 
378 const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const {
379   const BasicBlock* BB = this;
380   SmallPtrSet<const BasicBlock *, 8> Visited;
381   Visited.insert(BB);
382   while (auto *Succ = BB->getUniqueSuccessor()) {
383     if (!Visited.insert(Succ).second)
384       return nullptr;
385     BB = Succ;
386   }
387   return BB->getTerminatingDeoptimizeCall();
388 }
389 
390 const Instruction *BasicBlock::getFirstMayFaultInst() const {
391   if (InstList.empty())
392     return nullptr;
393   for (const Instruction &I : *this)
394     if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallBase>(I))
395       return &I;
396   return nullptr;
397 }
398 
399 const Instruction* BasicBlock::getFirstNonPHI() const {
400   for (const Instruction &I : *this)
401     if (!isa<PHINode>(I))
402       return &I;
403   return nullptr;
404 }
405 
406 BasicBlock::const_iterator BasicBlock::getFirstNonPHIIt() const {
407   const Instruction *I = getFirstNonPHI();
408   BasicBlock::const_iterator It = I->getIterator();
409   // Set the head-inclusive bit to indicate that this iterator includes
410   // any debug-info at the start of the block. This is a no-op unless the
411   // appropriate CMake flag is set.
412   It.setHeadBit(true);
413   return It;
414 }
415 
416 const Instruction *BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const {
417   for (const Instruction &I : *this) {
418     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
419       continue;
420 
421     if (SkipPseudoOp && isa<PseudoProbeInst>(I))
422       continue;
423 
424     return &I;
425   }
426   return nullptr;
427 }
428 
429 const Instruction *
430 BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const {
431   for (const Instruction &I : *this) {
432     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
433       continue;
434 
435     if (I.isLifetimeStartOrEnd())
436       continue;
437 
438     if (SkipPseudoOp && isa<PseudoProbeInst>(I))
439       continue;
440 
441     return &I;
442   }
443   return nullptr;
444 }
445 
446 BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
447   const Instruction *FirstNonPHI = getFirstNonPHI();
448   if (!FirstNonPHI)
449     return end();
450 
451   const_iterator InsertPt = FirstNonPHI->getIterator();
452   if (InsertPt->isEHPad()) ++InsertPt;
453   // Set the head-inclusive bit to indicate that this iterator includes
454   // any debug-info at the start of the block. This is a no-op unless the
455   // appropriate CMake flag is set.
456   InsertPt.setHeadBit(true);
457   return InsertPt;
458 }
459 
460 BasicBlock::const_iterator BasicBlock::getFirstNonPHIOrDbgOrAlloca() const {
461   const Instruction *FirstNonPHI = getFirstNonPHI();
462   if (!FirstNonPHI)
463     return end();
464 
465   const_iterator InsertPt = FirstNonPHI->getIterator();
466   if (InsertPt->isEHPad())
467     ++InsertPt;
468 
469   if (isEntryBlock()) {
470     const_iterator End = end();
471     while (InsertPt != End &&
472            (isa<AllocaInst>(*InsertPt) || isa<DbgInfoIntrinsic>(*InsertPt) ||
473             isa<PseudoProbeInst>(*InsertPt))) {
474       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&*InsertPt)) {
475         if (!AI->isStaticAlloca())
476           break;
477       }
478       ++InsertPt;
479     }
480   }
481   return InsertPt;
482 }
483 
484 void BasicBlock::dropAllReferences() {
485   for (Instruction &I : *this)
486     I.dropAllReferences();
487 }
488 
489 const BasicBlock *BasicBlock::getSinglePredecessor() const {
490   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
491   if (PI == E) return nullptr;         // No preds.
492   const BasicBlock *ThePred = *PI;
493   ++PI;
494   return (PI == E) ? ThePred : nullptr /*multiple preds*/;
495 }
496 
497 const BasicBlock *BasicBlock::getUniquePredecessor() const {
498   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
499   if (PI == E) return nullptr; // No preds.
500   const BasicBlock *PredBB = *PI;
501   ++PI;
502   for (;PI != E; ++PI) {
503     if (*PI != PredBB)
504       return nullptr;
505     // The same predecessor appears multiple times in the predecessor list.
506     // This is OK.
507   }
508   return PredBB;
509 }
510 
511 bool BasicBlock::hasNPredecessors(unsigned N) const {
512   return hasNItems(pred_begin(this), pred_end(this), N);
513 }
514 
515 bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
516   return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
517 }
518 
519 const BasicBlock *BasicBlock::getSingleSuccessor() const {
520   const_succ_iterator SI = succ_begin(this), E = succ_end(this);
521   if (SI == E) return nullptr; // no successors
522   const BasicBlock *TheSucc = *SI;
523   ++SI;
524   return (SI == E) ? TheSucc : nullptr /* multiple successors */;
525 }
526 
527 const BasicBlock *BasicBlock::getUniqueSuccessor() const {
528   const_succ_iterator SI = succ_begin(this), E = succ_end(this);
529   if (SI == E) return nullptr; // No successors
530   const BasicBlock *SuccBB = *SI;
531   ++SI;
532   for (;SI != E; ++SI) {
533     if (*SI != SuccBB)
534       return nullptr;
535     // The same successor appears multiple times in the successor list.
536     // This is OK.
537   }
538   return SuccBB;
539 }
540 
541 iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
542   PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
543   return make_range<phi_iterator>(P, nullptr);
544 }
545 
546 void BasicBlock::removePredecessor(BasicBlock *Pred,
547                                    bool KeepOneInputPHIs) {
548   // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs.
549   assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) &&
550          "Pred is not a predecessor!");
551 
552   // Return early if there are no PHI nodes to update.
553   if (empty() || !isa<PHINode>(begin()))
554     return;
555 
556   unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();
557   for (PHINode &Phi : make_early_inc_range(phis())) {
558     Phi.removeIncomingValue(Pred, !KeepOneInputPHIs);
559     if (KeepOneInputPHIs)
560       continue;
561 
562     // If we have a single predecessor, removeIncomingValue may have erased the
563     // PHI node itself.
564     if (NumPreds == 1)
565       continue;
566 
567     // Try to replace the PHI node with a constant value.
568     if (Value *PhiConstant = Phi.hasConstantValue()) {
569       Phi.replaceAllUsesWith(PhiConstant);
570       Phi.eraseFromParent();
571     }
572   }
573 }
574 
575 bool BasicBlock::canSplitPredecessors() const {
576   const Instruction *FirstNonPHI = getFirstNonPHI();
577   if (isa<LandingPadInst>(FirstNonPHI))
578     return true;
579   // This is perhaps a little conservative because constructs like
580   // CleanupBlockInst are pretty easy to split.  However, SplitBlockPredecessors
581   // cannot handle such things just yet.
582   if (FirstNonPHI->isEHPad())
583     return false;
584   return true;
585 }
586 
587 bool BasicBlock::isLegalToHoistInto() const {
588   auto *Term = getTerminator();
589   // No terminator means the block is under construction.
590   if (!Term)
591     return true;
592 
593   // If the block has no successors, there can be no instructions to hoist.
594   assert(Term->getNumSuccessors() > 0);
595 
596   // Instructions should not be hoisted across special terminators, which may
597   // have side effects or return values.
598   return !Term->isSpecialTerminator();
599 }
600 
601 bool BasicBlock::isEntryBlock() const {
602   const Function *F = getParent();
603   assert(F && "Block must have a parent function to use this API");
604   return this == &F->getEntryBlock();
605 }
606 
607 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName,
608                                         bool Before) {
609   if (Before)
610     return splitBasicBlockBefore(I, BBName);
611 
612   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
613   assert(I != InstList.end() &&
614          "Trying to get me to create degenerate basic block!");
615 
616   BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
617                                        this->getNextNode());
618 
619   // Save DebugLoc of split point before invalidating iterator.
620   DebugLoc Loc = I->getStableDebugLoc();
621   // Move all of the specified instructions from the original basic block into
622   // the new basic block.
623   New->splice(New->end(), this, I, end());
624 
625   // Add a branch instruction to the newly formed basic block.
626   BranchInst *BI = BranchInst::Create(New, this);
627   BI->setDebugLoc(Loc);
628 
629   // Now we must loop through all of the successors of the New block (which
630   // _were_ the successors of the 'this' block), and update any PHI nodes in
631   // successors.  If there were PHI nodes in the successors, then they need to
632   // know that incoming branches will be from New, not from Old (this).
633   //
634   New->replaceSuccessorsPhiUsesWith(this, New);
635   return New;
636 }
637 
638 BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) {
639   assert(getTerminator() &&
640          "Can't use splitBasicBlockBefore on degenerate BB!");
641   assert(I != InstList.end() &&
642          "Trying to get me to create degenerate basic block!");
643 
644   assert((!isa<PHINode>(*I) || getSinglePredecessor()) &&
645          "cannot split on multi incoming phis");
646 
647   BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this);
648   // Save DebugLoc of split point before invalidating iterator.
649   DebugLoc Loc = I->getDebugLoc();
650   // Move all of the specified instructions from the original basic block into
651   // the new basic block.
652   New->splice(New->end(), this, begin(), I);
653 
654   // Loop through all of the predecessors of the 'this' block (which will be the
655   // predecessors of the New block), replace the specified successor 'this'
656   // block to point at the New block and update any PHI nodes in 'this' block.
657   // If there were PHI nodes in 'this' block, the PHI nodes are updated
658   // to reflect that the incoming branches will be from the New block and not
659   // from predecessors of the 'this' block.
660   // Save predecessors to separate vector before modifying them.
661   SmallVector<BasicBlock *, 4> Predecessors;
662   for (BasicBlock *Pred : predecessors(this))
663     Predecessors.push_back(Pred);
664   for (BasicBlock *Pred : Predecessors) {
665     Instruction *TI = Pred->getTerminator();
666     TI->replaceSuccessorWith(this, New);
667     this->replacePhiUsesWith(Pred, New);
668   }
669   // Add a branch instruction from  "New" to "this" Block.
670   BranchInst *BI = BranchInst::Create(this, New);
671   BI->setDebugLoc(Loc);
672 
673   return New;
674 }
675 
676 BasicBlock::iterator BasicBlock::erase(BasicBlock::iterator FromIt,
677                                        BasicBlock::iterator ToIt) {
678   return InstList.erase(FromIt, ToIt);
679 }
680 
681 void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {
682   // N.B. This might not be a complete BasicBlock, so don't assume
683   // that it ends with a non-phi instruction.
684   for (Instruction &I : *this) {
685     PHINode *PN = dyn_cast<PHINode>(&I);
686     if (!PN)
687       break;
688     PN->replaceIncomingBlockWith(Old, New);
689   }
690 }
691 
692 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,
693                                               BasicBlock *New) {
694   Instruction *TI = getTerminator();
695   if (!TI)
696     // Cope with being called on a BasicBlock that doesn't have a terminator
697     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
698     return;
699   for (BasicBlock *Succ : successors(TI))
700     Succ->replacePhiUsesWith(Old, New);
701 }
702 
703 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
704   this->replaceSuccessorsPhiUsesWith(this, New);
705 }
706 
707 bool BasicBlock::isLandingPad() const {
708   return isa<LandingPadInst>(getFirstNonPHI());
709 }
710 
711 const LandingPadInst *BasicBlock::getLandingPadInst() const {
712   return dyn_cast<LandingPadInst>(getFirstNonPHI());
713 }
714 
715 std::optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
716   const Instruction *TI = getTerminator();
717   if (MDNode *MDIrrLoopHeader =
718       TI->getMetadata(LLVMContext::MD_irr_loop)) {
719     MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
720     if (MDName->getString().equals("loop_header_weight")) {
721       auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
722       return std::optional<uint64_t>(CI->getValue().getZExtValue());
723     }
724   }
725   return std::nullopt;
726 }
727 
728 BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
729   while (isa<DbgInfoIntrinsic>(It))
730     ++It;
731   return It;
732 }
733 
734 void BasicBlock::renumberInstructions() {
735   unsigned Order = 0;
736   for (Instruction &I : *this)
737     I.Order = Order++;
738 
739   // Set the bit to indicate that the instruction order valid and cached.
740   BasicBlockBits Bits = getBasicBlockBits();
741   Bits.InstrOrderValid = true;
742   setBasicBlockBits(Bits);
743 
744   NumInstrRenumberings++;
745 }
746 
747 void BasicBlock::flushTerminatorDbgValues() {
748   // If we erase the terminator in a block, any DPValues will sink and "fall
749   // off the end", existing after any terminator that gets inserted. With
750   // dbg.value intrinsics we would just insert the terminator at end() and
751   // the dbg.values would come before the terminator. With DPValues, we must
752   // do this manually.
753   // To get out of this unfortunate form, whenever we insert a terminator,
754   // check whether there's anything trailing at the end and move those DPValues
755   // in front of the terminator.
756 
757   // Do nothing if we're not in new debug-info format.
758   if (!IsNewDbgInfoFormat)
759     return;
760 
761   // If there's no terminator, there's nothing to do.
762   Instruction *Term = getTerminator();
763   if (!Term)
764     return;
765 
766   // Are there any dangling DPValues?
767   DPMarker *TrailingDPValues = getTrailingDPValues();
768   if (!TrailingDPValues)
769     return;
770 
771   // Transfer DPValues from the trailing position onto the terminator.
772   Term->DbgMarker->absorbDebugValues(*TrailingDPValues, false);
773   TrailingDPValues->eraseFromParent();
774   deleteTrailingDPValues();
775 }
776 
777 void BasicBlock::spliceDebugInfoEmptyBlock(BasicBlock::iterator Dest,
778                                            BasicBlock *Src,
779                                            BasicBlock::iterator First,
780                                            BasicBlock::iterator Last) {
781   // Imagine the folowing:
782   //
783   //   bb1:
784   //     dbg.value(...
785   //     ret i32 0
786   //
787   // If an optimisation pass attempts to splice the contents of the block from
788   // BB1->begin() to BB1->getTerminator(), then the dbg.value will be
789   // transferred to the destination.
790   // However, in the "new" DPValue format for debug-info, that range is empty:
791   // begin() returns an iterator to the terminator, as there will only be a
792   // single instruction in the block. We must piece together from the bits set
793   // in the iterators whether there was the intention to transfer any debug
794   // info.
795 
796   // If we're not in "new" debug-info format, do nothing.
797   if (!IsNewDbgInfoFormat)
798     return;
799 
800   assert(First == Last);
801   bool InsertAtHead = Dest.getHeadBit();
802   bool ReadFromHead = First.getHeadBit();
803 
804   // If the source block is completely empty, including no terminator, then
805   // transfer any trailing DPValues that are still hanging around. This can
806   // occur when a block is optimised away and the terminator has been moved
807   // somewhere else.
808   if (Src->empty()) {
809     assert(Dest != end() &&
810            "Transferring trailing DPValues to another trailing position");
811     DPMarker *SrcTrailingDPValues = Src->getTrailingDPValues();
812     if (!SrcTrailingDPValues)
813       return;
814 
815     DPMarker *M = Dest->DbgMarker;
816     M->absorbDebugValues(*SrcTrailingDPValues, InsertAtHead);
817     SrcTrailingDPValues->eraseFromParent();
818     Src->deleteTrailingDPValues();
819     return;
820   }
821 
822   // There are instructions in this block; if the First iterator was
823   // with begin() / getFirstInsertionPt() then the caller intended debug-info
824   // at the start of the block to be transferred. Return otherwise.
825   if (Src->empty() || First != Src->begin() || !ReadFromHead)
826     return;
827 
828   // Is there actually anything to transfer?
829   if (!First->hasDbgValues())
830     return;
831 
832   createMarker(Dest)->absorbDebugValues(*First->DbgMarker, InsertAtHead);
833 
834   return;
835 }
836 
837 void BasicBlock::spliceDebugInfo(BasicBlock::iterator Dest, BasicBlock *Src,
838                                  BasicBlock::iterator First,
839                                  BasicBlock::iterator Last) {
840   /* Do a quick normalisation before calling the real splice implementation. We
841      might be operating on a degenerate basic block that has no instructions
842      in it, a legitimate transient state. In that case, Dest will be end() and
843      any DPValues temporarily stored in the TrailingDPValues map in LLVMContext.
844      We might illustrate it thus:
845 
846                          Dest
847                            |
848      this-block:    ~~~~~~~~
849       Src-block:            ++++B---B---B---B:::C
850                                 |               |
851                                First           Last
852 
853      However: does the caller expect the "~" DPValues to end up before or after
854      the spliced segment? This is communciated in the "Head" bit of Dest, which
855      signals whether the caller called begin() or end() on this block.
856 
857      If the head bit is set, then all is well, we leave DPValues trailing just
858      like how dbg.value instructions would trail after instructions spliced to
859      the beginning of this block.
860 
861      If the head bit isn't set, then try to jam the "~" DPValues onto the front
862      of the First instruction, then splice like normal, which joins the "~"
863      DPValues with the "+" DPValues. However if the "+" DPValues are supposed to
864      be left behind in Src, then:
865       * detach the "+" DPValues,
866       * move the "~" DPValues onto First,
867       * splice like normal,
868       * replace the "+" DPValues onto the Last position.
869      Complicated, but gets the job done. */
870 
871   // If we're inserting at end(), and not in front of dangling DPValues, then
872   // move the DPValues onto "First". They'll then be moved naturally in the
873   // splice process.
874   DPMarker *MoreDanglingDPValues = nullptr;
875   DPMarker *OurTrailingDPValues = getTrailingDPValues();
876   if (Dest == end() && !Dest.getHeadBit() && OurTrailingDPValues) {
877     // Are the "+" DPValues not supposed to move? If so, detach them
878     // temporarily.
879     if (!First.getHeadBit() && First->hasDbgValues()) {
880       MoreDanglingDPValues = Src->getMarker(First);
881       MoreDanglingDPValues->removeFromParent();
882     }
883 
884     if (First->hasDbgValues()) {
885       DPMarker *CurMarker = Src->getMarker(First);
886       // Place them at the front, it would look like this:
887       //            Dest
888       //              |
889       // this-block:
890       // Src-block: ~~~~~~~~++++B---B---B---B:::C
891       //                        |               |
892       //                       First           Last
893       CurMarker->absorbDebugValues(*OurTrailingDPValues, true);
894       OurTrailingDPValues->eraseFromParent();
895     } else {
896       // No current marker, create one and absorb in. (FIXME: we can avoid an
897       // allocation in the future).
898       DPMarker *CurMarker = Src->createMarker(&*First);
899       CurMarker->absorbDebugValues(*OurTrailingDPValues, false);
900       OurTrailingDPValues->eraseFromParent();
901     }
902     deleteTrailingDPValues();
903     First.setHeadBit(true);
904   }
905 
906   // Call the main debug-info-splicing implementation.
907   spliceDebugInfoImpl(Dest, Src, First, Last);
908 
909   // Do we have some "+" DPValues hanging around that weren't supposed to move,
910   // and we detached to make things easier?
911   if (!MoreDanglingDPValues)
912     return;
913 
914   // FIXME: we could avoid an allocation here sometimes.
915   DPMarker *LastMarker = Src->createMarker(Last);
916   LastMarker->absorbDebugValues(*MoreDanglingDPValues, true);
917   MoreDanglingDPValues->eraseFromParent();
918 }
919 
920 void BasicBlock::spliceDebugInfoImpl(BasicBlock::iterator Dest, BasicBlock *Src,
921                                      BasicBlock::iterator First,
922                                      BasicBlock::iterator Last) {
923   // Find out where to _place_ these dbg.values; if InsertAtHead is specified,
924   // this will be at the start of Dest's debug value range, otherwise this is
925   // just Dest's marker.
926   bool InsertAtHead = Dest.getHeadBit();
927   bool ReadFromHead = First.getHeadBit();
928   // Use this flag to signal the abnormal case, where we don't want to copy the
929   // DPValues ahead of the "Last" position.
930   bool ReadFromTail = !Last.getTailBit();
931   bool LastIsEnd = (Last == Src->end());
932 
933   /*
934     Here's an illustration of what we're about to do. We have two blocks, this
935     and Src, and two segments of list. Each instruction is marked by a capital
936     while potential DPValue debug-info is marked out by "-" characters and a few
937     other special characters (+:=) where I want to highlight what's going on.
938 
939                                                  Dest
940                                                    |
941      this-block:    A----A----A                ====A----A----A----A---A---A
942       Src-block                ++++B---B---B---B:::C
943                                    |               |
944                                   First           Last
945 
946     The splice method is going to take all the instructions from First up to
947     (but not including) Last and insert them in _front_ of Dest, forming one
948     long list. All the DPValues attached to instructions _between_ First and
949     Last need no maintenence. However, we have to do special things with the
950     DPValues marked with the +:= characters. We only have three positions:
951     should the "+" DPValues be transferred, and if so to where? Do we move the
952     ":" DPValues? Would they go in front of the "=" DPValues, or should the "="
953     DPValues go before "+" DPValues?
954 
955     We're told which way it should be by the bits carried in the iterators. The
956     "Head" bit indicates whether the specified position is supposed to be at the
957     front of the attached DPValues (true) or not (false). The Tail bit is true
958     on the other end of a range: is the range intended to include DPValues up to
959     the end (false) or not (true).
960 
961     FIXME: the tail bit doesn't need to be distinct from the head bit, we could
962     combine them.
963 
964     Here are some examples of different configurations:
965 
966       Dest.Head = true, First.Head = true, Last.Tail = false
967 
968       this-block:    A----A----A++++B---B---B---B:::====A----A----A----A---A---A
969                                     |                   |
970                                   First                Dest
971 
972     Wheras if we didn't want to read from the Src list,
973 
974       Dest.Head = true, First.Head = false, Last.Tail = false
975 
976       this-block:    A----A----AB---B---B---B:::====A----A----A----A---A---A
977                                 |                   |
978                               First                Dest
979 
980     Or if we didn't want to insert at the head of Dest:
981 
982       Dest.Head = false, First.Head = false, Last.Tail = false
983 
984       this-block:    A----A----A====B---B---B---B:::A----A----A----A---A---A
985                                     |               |
986                                   First            Dest
987 
988     Tests for these various configurations can be found in the unit test file
989     BasicBlockDbgInfoTest.cpp.
990 
991    */
992 
993   // Detach the marker at Dest -- this lets us move the "====" DPValues around.
994   DPMarker *DestMarker = nullptr;
995   if (Dest != end()) {
996     DestMarker = getMarker(Dest);
997     DestMarker->removeFromParent();
998     createMarker(&*Dest);
999   }
1000 
1001   // If we're moving the tail range of DPValues (":::"), absorb them into the
1002   // front of the DPValues at Dest.
1003   if (ReadFromTail && Src->getMarker(Last)) {
1004     DPMarker *OntoDest = getMarker(Dest);
1005     DPMarker *FromLast = Src->getMarker(Last);
1006     OntoDest->absorbDebugValues(*FromLast, true);
1007     if (LastIsEnd) {
1008       FromLast->eraseFromParent();
1009       Src->deleteTrailingDPValues();
1010     }
1011   }
1012 
1013   // If we're _not_ reading from the head of First, i.e. the "++++" DPValues,
1014   // move their markers onto Last. They remain in the Src block. No action
1015   // needed.
1016   if (!ReadFromHead && First->hasDbgValues()) {
1017     DPMarker *OntoLast = Src->createMarker(Last);
1018     DPMarker *FromFirst = Src->createMarker(First);
1019     OntoLast->absorbDebugValues(*FromFirst,
1020                                 true); // Always insert at head of it.
1021   }
1022 
1023   // Finally, do something with the "====" DPValues we detached.
1024   if (DestMarker) {
1025     if (InsertAtHead) {
1026       // Insert them at the end of the DPValues at Dest. The "::::" DPValues
1027       // might be in front of them.
1028       DPMarker *NewDestMarker = getMarker(Dest);
1029       NewDestMarker->absorbDebugValues(*DestMarker, false);
1030     } else {
1031       // Insert them right at the start of the range we moved, ahead of First
1032       // and the "++++" DPValues.
1033       DPMarker *FirstMarker = getMarker(First);
1034       FirstMarker->absorbDebugValues(*DestMarker, true);
1035     }
1036     DestMarker->eraseFromParent();
1037   } else if (Dest == end() && !InsertAtHead) {
1038     // In the rare circumstance where we insert at end(), and we did not
1039     // generate the iterator with begin() / getFirstInsertionPt(), it means
1040     // any trailing debug-info at the end of the block would "normally" have
1041     // been pushed in front of "First". Move it there now.
1042     DPMarker *FirstMarker = getMarker(First);
1043     DPMarker *TrailingDPValues = getTrailingDPValues();
1044     if (TrailingDPValues) {
1045       FirstMarker->absorbDebugValues(*TrailingDPValues, true);
1046       TrailingDPValues->eraseFromParent();
1047       deleteTrailingDPValues();
1048     }
1049   }
1050 }
1051 
1052 void BasicBlock::splice(iterator Dest, BasicBlock *Src, iterator First,
1053                         iterator Last) {
1054   assert(Src->IsNewDbgInfoFormat == IsNewDbgInfoFormat);
1055 
1056 #ifdef EXPENSIVE_CHECKS
1057   // Check that First is before Last.
1058   auto FromBBEnd = Src->end();
1059   for (auto It = First; It != Last; ++It)
1060     assert(It != FromBBEnd && "FromBeginIt not before FromEndIt!");
1061 #endif // EXPENSIVE_CHECKS
1062 
1063   // Lots of horrible special casing for empty transfers: the dbg.values between
1064   // two positions could be spliced in dbg.value mode.
1065   if (First == Last) {
1066     spliceDebugInfoEmptyBlock(Dest, Src, First, Last);
1067     return;
1068   }
1069 
1070   // Handle non-instr debug-info specific juggling.
1071   if (IsNewDbgInfoFormat)
1072     spliceDebugInfo(Dest, Src, First, Last);
1073 
1074   // And move the instructions.
1075   getInstList().splice(Dest, Src->getInstList(), First, Last);
1076 
1077   flushTerminatorDbgValues();
1078 }
1079 
1080 void BasicBlock::insertDPValueAfter(DPValue *DPV, Instruction *I) {
1081   assert(IsNewDbgInfoFormat);
1082   assert(I->getParent() == this);
1083 
1084   iterator NextIt = std::next(I->getIterator());
1085   DPMarker *NextMarker = getMarker(NextIt);
1086   if (!NextMarker)
1087     NextMarker = createMarker(NextIt);
1088   NextMarker->insertDPValue(DPV, true);
1089 }
1090 
1091 void BasicBlock::insertDPValueBefore(DPValue *DPV,
1092                                      InstListType::iterator Where) {
1093   // We should never directly insert at the end of the block, new DPValues
1094   // shouldn't be generated at times when there's no terminator.
1095   assert(Where != end());
1096   assert(Where->getParent() == this);
1097   if (!Where->DbgMarker)
1098     createMarker(Where);
1099   bool InsertAtHead = Where.getHeadBit();
1100   Where->DbgMarker->insertDPValue(DPV, InsertAtHead);
1101 }
1102 
1103 DPMarker *BasicBlock::getNextMarker(Instruction *I) {
1104   return getMarker(std::next(I->getIterator()));
1105 }
1106 
1107 DPMarker *BasicBlock::getMarker(InstListType::iterator It) {
1108   if (It == end()) {
1109     DPMarker *DPM = getTrailingDPValues();
1110     return DPM;
1111   }
1112   return It->DbgMarker;
1113 }
1114 
1115 void BasicBlock::reinsertInstInDPValues(
1116     Instruction *I, std::optional<DPValue::self_iterator> Pos) {
1117   // "I" was originally removed from a position where it was
1118   // immediately in front of Pos. Any DPValues on that position then "fell down"
1119   // onto Pos. "I" has been re-inserted at the front of that wedge of DPValues,
1120   // shuffle them around to represent the original positioning. To illustrate:
1121   //
1122   //   Instructions:  I1---I---I0
1123   //       DPValues:    DDD DDD
1124   //
1125   // Instruction "I" removed,
1126   //
1127   //   Instructions:  I1------I0
1128   //       DPValues:    DDDDDD
1129   //                       ^Pos
1130   //
1131   // Instruction "I" re-inserted (now):
1132   //
1133   //   Instructions:  I1---I------I0
1134   //       DPValues:        DDDDDD
1135   //                           ^Pos
1136   //
1137   // After this method completes:
1138   //
1139   //   Instructions:  I1---I---I0
1140   //       DPValues:    DDD DDD
1141 
1142   // This happens if there were no DPValues on I0. Are there now DPValues there?
1143   if (!Pos) {
1144     DPMarker *NextMarker = getNextMarker(I);
1145     if (!NextMarker)
1146       return;
1147     if (NextMarker->StoredDPValues.empty())
1148       return;
1149     // There are DPMarkers there now -- they fell down from "I".
1150     DPMarker *ThisMarker = createMarker(I);
1151     ThisMarker->absorbDebugValues(*NextMarker, false);
1152     return;
1153   }
1154 
1155   // Is there even a range of DPValues to move?
1156   DPMarker *DPM = (*Pos)->getMarker();
1157   auto Range = make_range(DPM->StoredDPValues.begin(), (*Pos));
1158   if (Range.begin() == Range.end())
1159     return;
1160 
1161   // Otherwise: splice.
1162   DPMarker *ThisMarker = createMarker(I);
1163   assert(ThisMarker->StoredDPValues.empty());
1164   ThisMarker->absorbDebugValues(Range, *DPM, true);
1165 }
1166 
1167 #ifndef NDEBUG
1168 /// In asserts builds, this checks the numbering. In non-asserts builds, it
1169 /// is defined as a no-op inline function in BasicBlock.h.
1170 void BasicBlock::validateInstrOrdering() const {
1171   if (!isInstrOrderValid())
1172     return;
1173   const Instruction *Prev = nullptr;
1174   for (const Instruction &I : *this) {
1175     assert((!Prev || Prev->comesBefore(&I)) &&
1176            "cached instruction ordering is incorrect");
1177     Prev = &I;
1178   }
1179 }
1180 #endif
1181 
1182 void BasicBlock::setTrailingDPValues(DPMarker *foo) {
1183   getContext().pImpl->setTrailingDPValues(this, foo);
1184 }
1185 
1186 DPMarker *BasicBlock::getTrailingDPValues() {
1187   return getContext().pImpl->getTrailingDPValues(this);
1188 }
1189 
1190 void BasicBlock::deleteTrailingDPValues() {
1191   getContext().pImpl->deleteTrailingDPValues(this);
1192 }
1193 
1194