xref: /src/contrib/llvm-project/llvm/lib/IR/BasicBlock.cpp (revision c80e69b00d976a5a3b3e84527f270fa7e72a8205)
1009b1c42SEd Schouten //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
94a16efa3SDimitry Andric // This file implements the BasicBlock class for the IR library.
10009b1c42SEd Schouten //
11009b1c42SEd Schouten //===----------------------------------------------------------------------===//
12009b1c42SEd Schouten 
134a16efa3SDimitry Andric #include "llvm/IR/BasicBlock.h"
144a16efa3SDimitry Andric #include "SymbolTableListTraitsImpl.h"
15009b1c42SEd Schouten #include "llvm/ADT/STLExtras.h"
16ecbca9f5SDimitry Andric #include "llvm/ADT/Statistic.h"
175ca98fd9SDimitry Andric #include "llvm/IR/CFG.h"
184a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
19b1c73532SDimitry Andric #include "llvm/IR/DebugProgramInstruction.h"
204a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
214a16efa3SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
224a16efa3SDimitry Andric #include "llvm/IR/LLVMContext.h"
234a16efa3SDimitry Andric #include "llvm/IR/Type.h"
24b1c73532SDimitry Andric #include "llvm/Support/CommandLine.h"
25b1c73532SDimitry Andric 
26b1c73532SDimitry Andric #include "LLVMContextImpl.h"
27dd58ef01SDimitry Andric 
28009b1c42SEd Schouten using namespace llvm;
29009b1c42SEd Schouten 
30c0981da4SDimitry Andric #define DEBUG_TYPE "ir"
31c0981da4SDimitry Andric STATISTIC(NumInstrRenumberings, "Number of renumberings across all blocks");
32c0981da4SDimitry Andric 
33ac9a064cSDimitry Andric cl::opt<bool> UseNewDbgInfoFormat(
34ac9a064cSDimitry Andric     "experimental-debuginfo-iterators",
35ac9a064cSDimitry Andric     cl::desc("Enable communicating debuginfo positions through iterators, "
36ac9a064cSDimitry Andric              "eliminating intrinsics. Has no effect if "
37ac9a064cSDimitry Andric              "--preserve-input-debuginfo-format=true."),
38ac9a064cSDimitry Andric     cl::init(true));
39ac9a064cSDimitry Andric cl::opt<cl::boolOrDefault> PreserveInputDbgFormat(
40ac9a064cSDimitry Andric     "preserve-input-debuginfo-format", cl::Hidden,
41ac9a064cSDimitry Andric     cl::desc("When set to true, IR files will be processed and printed in "
42ac9a064cSDimitry Andric              "their current debug info format, regardless of default behaviour "
43ac9a064cSDimitry Andric              "or other flags passed. Has no effect if input IR does not "
44ac9a064cSDimitry Andric              "contain debug records or intrinsics. Ignored in llvm-link, "
45ac9a064cSDimitry Andric              "llvm-lto, and llvm-lto2."));
46b1c73532SDimitry Andric 
47ac9a064cSDimitry Andric bool WriteNewDbgInfoFormatToBitcode /*set default value in cl::init() below*/;
48ac9a064cSDimitry Andric cl::opt<bool, true> WriteNewDbgInfoFormatToBitcode2(
49ac9a064cSDimitry Andric     "write-experimental-debuginfo-iterators-to-bitcode", cl::Hidden,
50ac9a064cSDimitry Andric     cl::location(WriteNewDbgInfoFormatToBitcode), cl::init(true));
51ac9a064cSDimitry Andric 
createMarker(Instruction * I)52ac9a064cSDimitry Andric DbgMarker *BasicBlock::createMarker(Instruction *I) {
53b1c73532SDimitry Andric   assert(IsNewDbgInfoFormat &&
54b1c73532SDimitry Andric          "Tried to create a marker in a non new debug-info block!");
55ac9a064cSDimitry Andric   if (I->DebugMarker)
56ac9a064cSDimitry Andric     return I->DebugMarker;
57ac9a064cSDimitry Andric   DbgMarker *Marker = new DbgMarker();
58b1c73532SDimitry Andric   Marker->MarkedInstr = I;
59ac9a064cSDimitry Andric   I->DebugMarker = Marker;
60b1c73532SDimitry Andric   return Marker;
61b1c73532SDimitry Andric }
62b1c73532SDimitry Andric 
createMarker(InstListType::iterator It)63ac9a064cSDimitry Andric DbgMarker *BasicBlock::createMarker(InstListType::iterator It) {
64b1c73532SDimitry Andric   assert(IsNewDbgInfoFormat &&
65b1c73532SDimitry Andric          "Tried to create a marker in a non new debug-info block!");
66b1c73532SDimitry Andric   if (It != end())
67b1c73532SDimitry Andric     return createMarker(&*It);
68ac9a064cSDimitry Andric   DbgMarker *DM = getTrailingDbgRecords();
69ac9a064cSDimitry Andric   if (DM)
70ac9a064cSDimitry Andric     return DM;
71ac9a064cSDimitry Andric   DM = new DbgMarker();
72ac9a064cSDimitry Andric   setTrailingDbgRecords(DM);
73ac9a064cSDimitry Andric   return DM;
74b1c73532SDimitry Andric }
75b1c73532SDimitry Andric 
convertToNewDbgValues()76b1c73532SDimitry Andric void BasicBlock::convertToNewDbgValues() {
77b1c73532SDimitry Andric   IsNewDbgInfoFormat = true;
78b1c73532SDimitry Andric 
79ac9a064cSDimitry Andric   // Iterate over all instructions in the instruction list, collecting debug
80ac9a064cSDimitry Andric   // info intrinsics and converting them to DbgRecords. Once we find a "real"
81ac9a064cSDimitry Andric   // instruction, attach all those DbgRecords to a DbgMarker in that
82ac9a064cSDimitry Andric   // instruction.
83ac9a064cSDimitry Andric   SmallVector<DbgRecord *, 4> DbgVarRecs;
84b1c73532SDimitry Andric   for (Instruction &I : make_early_inc_range(InstList)) {
85ac9a064cSDimitry Andric     assert(!I.DebugMarker && "DebugMarker already set on old-format instrs?");
86312c0ed1SDimitry Andric     if (DbgVariableIntrinsic *DVI = dyn_cast<DbgVariableIntrinsic>(&I)) {
87ac9a064cSDimitry Andric       // Convert this dbg.value to a DbgVariableRecord.
88ac9a064cSDimitry Andric       DbgVariableRecord *Value = new DbgVariableRecord(DVI);
89ac9a064cSDimitry Andric       DbgVarRecs.push_back(Value);
90b1c73532SDimitry Andric       DVI->eraseFromParent();
91b1c73532SDimitry Andric       continue;
92b1c73532SDimitry Andric     }
93b1c73532SDimitry Andric 
94ac9a064cSDimitry Andric     if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(&I)) {
95ac9a064cSDimitry Andric       DbgVarRecs.push_back(
96ac9a064cSDimitry Andric           new DbgLabelRecord(DLI->getLabel(), DLI->getDebugLoc()));
97ac9a064cSDimitry Andric       DLI->eraseFromParent();
98ac9a064cSDimitry Andric       continue;
99ac9a064cSDimitry Andric     }
100ac9a064cSDimitry Andric 
101ac9a064cSDimitry Andric     if (DbgVarRecs.empty())
102ac9a064cSDimitry Andric       continue;
103ac9a064cSDimitry Andric 
104ac9a064cSDimitry Andric     // Create a marker to store DbgRecords in.
105b1c73532SDimitry Andric     createMarker(&I);
106ac9a064cSDimitry Andric     DbgMarker *Marker = I.DebugMarker;
107b1c73532SDimitry Andric 
108ac9a064cSDimitry Andric     for (DbgRecord *DVR : DbgVarRecs)
109ac9a064cSDimitry Andric       Marker->insertDbgRecord(DVR, false);
110b1c73532SDimitry Andric 
111ac9a064cSDimitry Andric     DbgVarRecs.clear();
112b1c73532SDimitry Andric   }
113b1c73532SDimitry Andric }
114b1c73532SDimitry Andric 
convertFromNewDbgValues()115b1c73532SDimitry Andric void BasicBlock::convertFromNewDbgValues() {
116b1c73532SDimitry Andric   invalidateOrders();
117b1c73532SDimitry Andric   IsNewDbgInfoFormat = false;
118b1c73532SDimitry Andric 
119ac9a064cSDimitry Andric   // Iterate over the block, finding instructions annotated with DbgMarkers.
120ac9a064cSDimitry Andric   // Convert any attached DbgRecords to debug intrinsics and insert ahead of the
121b1c73532SDimitry Andric   // instruction.
122b1c73532SDimitry Andric   for (auto &Inst : *this) {
123ac9a064cSDimitry Andric     if (!Inst.DebugMarker)
124b1c73532SDimitry Andric       continue;
125b1c73532SDimitry Andric 
126ac9a064cSDimitry Andric     DbgMarker &Marker = *Inst.DebugMarker;
127ac9a064cSDimitry Andric     for (DbgRecord &DR : Marker.getDbgRecordRange())
128b1c73532SDimitry Andric       InstList.insert(Inst.getIterator(),
129ac9a064cSDimitry Andric                       DR.createDebugIntrinsic(getModule(), nullptr));
130b1c73532SDimitry Andric 
131b1c73532SDimitry Andric     Marker.eraseFromParent();
132ac9a064cSDimitry Andric   }
133b1c73532SDimitry Andric 
134ac9a064cSDimitry Andric   // Assume no trailing DbgRecords: we could technically create them at the end
135b1c73532SDimitry Andric   // of the block, after a terminator, but this would be non-cannonical and
136b1c73532SDimitry Andric   // indicates that something else is broken somewhere.
137ac9a064cSDimitry Andric   assert(!getTrailingDbgRecords());
138b1c73532SDimitry Andric }
139b1c73532SDimitry Andric 
140b1c73532SDimitry Andric #ifndef NDEBUG
dumpDbgValues() const141b1c73532SDimitry Andric void BasicBlock::dumpDbgValues() const {
142b1c73532SDimitry Andric   for (auto &Inst : *this) {
143ac9a064cSDimitry Andric     if (!Inst.DebugMarker)
144b1c73532SDimitry Andric       continue;
145b1c73532SDimitry Andric 
146ac9a064cSDimitry Andric     dbgs() << "@ " << Inst.DebugMarker << " ";
147ac9a064cSDimitry Andric     Inst.DebugMarker->dump();
148b1c73532SDimitry Andric   };
149b1c73532SDimitry Andric }
150b1c73532SDimitry Andric #endif
151b1c73532SDimitry Andric 
setIsNewDbgInfoFormat(bool NewFlag)152b1c73532SDimitry Andric void BasicBlock::setIsNewDbgInfoFormat(bool NewFlag) {
153b1c73532SDimitry Andric   if (NewFlag && !IsNewDbgInfoFormat)
154b1c73532SDimitry Andric     convertToNewDbgValues();
155b1c73532SDimitry Andric   else if (!NewFlag && IsNewDbgInfoFormat)
156b1c73532SDimitry Andric     convertFromNewDbgValues();
157b1c73532SDimitry Andric }
setNewDbgInfoFormatFlag(bool NewFlag)158ac9a064cSDimitry Andric void BasicBlock::setNewDbgInfoFormatFlag(bool NewFlag) {
159ac9a064cSDimitry Andric   IsNewDbgInfoFormat = NewFlag;
160ac9a064cSDimitry Andric }
161b1c73532SDimitry Andric 
getValueSymbolTable()162009b1c42SEd Schouten ValueSymbolTable *BasicBlock::getValueSymbolTable() {
163009b1c42SEd Schouten   if (Function *F = getParent())
164b915e9e0SDimitry Andric     return F->getValueSymbolTable();
1655ca98fd9SDimitry Andric   return nullptr;
1665ca98fd9SDimitry Andric }
1675ca98fd9SDimitry Andric 
getContext() const16859850d08SRoman Divacky LLVMContext &BasicBlock::getContext() const {
16959850d08SRoman Divacky   return getType()->getContext();
17059850d08SRoman Divacky }
17159850d08SRoman Divacky 
invalidateParentIListOrdering(BasicBlock * BB)172cfca06d7SDimitry Andric template <> void llvm::invalidateParentIListOrdering(BasicBlock *BB) {
173cfca06d7SDimitry Andric   BB->invalidateOrders();
174cfca06d7SDimitry Andric }
175cfca06d7SDimitry Andric 
176009b1c42SEd Schouten // Explicit instantiation of SymbolTableListTraits since some of the methods
177009b1c42SEd Schouten // are not in the public header file...
178ac9a064cSDimitry Andric template class llvm::SymbolTableListTraits<
179ac9a064cSDimitry Andric     Instruction, ilist_iterator_bits<true>, ilist_parent<BasicBlock>>;
180009b1c42SEd Schouten 
BasicBlock(LLVMContext & C,const Twine & Name,Function * NewParent,BasicBlock * InsertBefore)18159850d08SRoman Divacky BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
182009b1c42SEd Schouten                        BasicBlock *InsertBefore)
183b1c73532SDimitry Andric     : Value(Type::getLabelTy(C), Value::BasicBlockVal),
184ac9a064cSDimitry Andric       IsNewDbgInfoFormat(UseNewDbgInfoFormat), Parent(nullptr) {
185009b1c42SEd Schouten 
18667c32a98SDimitry Andric   if (NewParent)
18767c32a98SDimitry Andric     insertInto(NewParent, InsertBefore);
18867c32a98SDimitry Andric   else
18967c32a98SDimitry Andric     assert(!InsertBefore &&
190009b1c42SEd Schouten            "Cannot insert block before another block with no function!");
191009b1c42SEd Schouten 
192ac9a064cSDimitry Andric   end().getNodePtr()->setParent(this);
193009b1c42SEd Schouten   setName(Name);
194b1c73532SDimitry Andric   if (NewParent)
195b1c73532SDimitry Andric     setIsNewDbgInfoFormat(NewParent->IsNewDbgInfoFormat);
196009b1c42SEd Schouten }
197009b1c42SEd Schouten 
insertInto(Function * NewParent,BasicBlock * InsertBefore)19867c32a98SDimitry Andric void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
19967c32a98SDimitry Andric   assert(NewParent && "Expected a parent");
20067c32a98SDimitry Andric   assert(!Parent && "Already has a parent");
20167c32a98SDimitry Andric 
20267c32a98SDimitry Andric   if (InsertBefore)
203e3b55780SDimitry Andric     NewParent->insert(InsertBefore->getIterator(), this);
20467c32a98SDimitry Andric   else
205e3b55780SDimitry Andric     NewParent->insert(NewParent->end(), this);
2064df029ccSDimitry Andric 
2074df029ccSDimitry Andric   setIsNewDbgInfoFormat(NewParent->IsNewDbgInfoFormat);
20867c32a98SDimitry Andric }
209009b1c42SEd Schouten 
~BasicBlock()210009b1c42SEd Schouten BasicBlock::~BasicBlock() {
211cfca06d7SDimitry Andric   validateInstrOrdering();
212cfca06d7SDimitry Andric 
21336bf506aSRoman Divacky   // If the address of the block is taken and it is being deleted (e.g. because
21436bf506aSRoman Divacky   // it is dead), this means that there is either a dangling constant expr
21536bf506aSRoman Divacky   // hanging off the block, or an undefined use of the block (source code
21636bf506aSRoman Divacky   // expecting the address of a label to keep the block alive even though there
21736bf506aSRoman Divacky   // is no indirect branch).  Handle these cases by zapping the BlockAddress
21836bf506aSRoman Divacky   // nodes.  There are no other possible uses at this point.
21936bf506aSRoman Divacky   if (hasAddressTaken()) {
22036bf506aSRoman Divacky     assert(!use_empty() && "There should be at least one blockaddress!");
22136bf506aSRoman Divacky     Constant *Replacement =
22236bf506aSRoman Divacky       ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
22336bf506aSRoman Divacky     while (!use_empty()) {
2245ca98fd9SDimitry Andric       BlockAddress *BA = cast<BlockAddress>(user_back());
22536bf506aSRoman Divacky       BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
22636bf506aSRoman Divacky                                                        BA->getType()));
22736bf506aSRoman Divacky       BA->destroyConstant();
22836bf506aSRoman Divacky     }
22936bf506aSRoman Divacky   }
23036bf506aSRoman Divacky 
2315ca98fd9SDimitry Andric   assert(getParent() == nullptr && "BasicBlock still linked into the program!");
232009b1c42SEd Schouten   dropAllReferences();
233b1c73532SDimitry Andric   for (auto &Inst : *this) {
234ac9a064cSDimitry Andric     if (!Inst.DebugMarker)
235b1c73532SDimitry Andric       continue;
236ac9a064cSDimitry Andric     Inst.DebugMarker->eraseFromParent();
237b1c73532SDimitry Andric   }
238009b1c42SEd Schouten   InstList.clear();
239009b1c42SEd Schouten }
240009b1c42SEd Schouten 
setParent(Function * parent)241009b1c42SEd Schouten void BasicBlock::setParent(Function *parent) {
242009b1c42SEd Schouten   // Set Parent=parent, updating instruction symtab entries as appropriate.
243009b1c42SEd Schouten   InstList.setSymTabObject(&Parent, parent);
244009b1c42SEd Schouten }
245009b1c42SEd Schouten 
246eb11fae6SDimitry Andric iterator_range<filter_iterator<BasicBlock::const_iterator,
247eb11fae6SDimitry Andric                                std::function<bool(const Instruction &)>>>
instructionsWithoutDebug(bool SkipPseudoOp) const248b60736ecSDimitry Andric BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) const {
249b60736ecSDimitry Andric   std::function<bool(const Instruction &)> Fn = [=](const Instruction &I) {
250b60736ecSDimitry Andric     return !isa<DbgInfoIntrinsic>(I) &&
251b60736ecSDimitry Andric            !(SkipPseudoOp && isa<PseudoProbeInst>(I));
252eb11fae6SDimitry Andric   };
253eb11fae6SDimitry Andric   return make_filter_range(*this, Fn);
254eb11fae6SDimitry Andric }
255eb11fae6SDimitry Andric 
256b60736ecSDimitry Andric iterator_range<
257b60736ecSDimitry Andric     filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>>
instructionsWithoutDebug(bool SkipPseudoOp)258b60736ecSDimitry Andric BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) {
259b60736ecSDimitry Andric   std::function<bool(Instruction &)> Fn = [=](Instruction &I) {
260b60736ecSDimitry Andric     return !isa<DbgInfoIntrinsic>(I) &&
261b60736ecSDimitry Andric            !(SkipPseudoOp && isa<PseudoProbeInst>(I));
262eb11fae6SDimitry Andric   };
263eb11fae6SDimitry Andric   return make_filter_range(*this, Fn);
264eb11fae6SDimitry Andric }
265eb11fae6SDimitry Andric 
2661d5ae102SDimitry Andric filter_iterator<BasicBlock::const_iterator,
2671d5ae102SDimitry Andric                 std::function<bool(const Instruction &)>>::difference_type
sizeWithoutDebug() const2681d5ae102SDimitry Andric BasicBlock::sizeWithoutDebug() const {
2691d5ae102SDimitry Andric   return std::distance(instructionsWithoutDebug().begin(),
2701d5ae102SDimitry Andric                        instructionsWithoutDebug().end());
2711d5ae102SDimitry Andric }
2721d5ae102SDimitry Andric 
removeFromParent()273009b1c42SEd Schouten void BasicBlock::removeFromParent() {
274dd58ef01SDimitry Andric   getParent()->getBasicBlockList().remove(getIterator());
275009b1c42SEd Schouten }
276009b1c42SEd Schouten 
eraseFromParent()2775a5ac124SDimitry Andric iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
278dd58ef01SDimitry Andric   return getParent()->getBasicBlockList().erase(getIterator());
279009b1c42SEd Schouten }
280009b1c42SEd Schouten 
moveBefore(SymbolTableList<BasicBlock>::iterator MovePos)2817fa27ce4SDimitry Andric void BasicBlock::moveBefore(SymbolTableList<BasicBlock>::iterator MovePos) {
2827fa27ce4SDimitry Andric   getParent()->splice(MovePos, getParent(), getIterator());
283009b1c42SEd Schouten }
284009b1c42SEd Schouten 
moveAfter(BasicBlock * MovePos)285009b1c42SEd Schouten void BasicBlock::moveAfter(BasicBlock *MovePos) {
286e3b55780SDimitry Andric   MovePos->getParent()->splice(++MovePos->getIterator(), getParent(),
287dd58ef01SDimitry Andric                                getIterator());
288009b1c42SEd Schouten }
289009b1c42SEd Schouten 
getModule() const2905a5ac124SDimitry Andric const Module *BasicBlock::getModule() const {
2915a5ac124SDimitry Andric   return getParent()->getParent();
2925a5ac124SDimitry Andric }
2935a5ac124SDimitry Andric 
getDataLayout() const294ac9a064cSDimitry Andric const DataLayout &BasicBlock::getDataLayout() const {
295ac9a064cSDimitry Andric   return getModule()->getDataLayout();
296ac9a064cSDimitry Andric }
297ac9a064cSDimitry Andric 
getTerminatingMustTailCall() const29871d5a254SDimitry Andric const CallInst *BasicBlock::getTerminatingMustTailCall() const {
29967c32a98SDimitry Andric   if (InstList.empty())
30067c32a98SDimitry Andric     return nullptr;
30171d5a254SDimitry Andric   const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
30267c32a98SDimitry Andric   if (!RI || RI == &InstList.front())
30367c32a98SDimitry Andric     return nullptr;
30467c32a98SDimitry Andric 
30571d5a254SDimitry Andric   const Instruction *Prev = RI->getPrevNode();
30667c32a98SDimitry Andric   if (!Prev)
30767c32a98SDimitry Andric     return nullptr;
30867c32a98SDimitry Andric 
30967c32a98SDimitry Andric   if (Value *RV = RI->getReturnValue()) {
31067c32a98SDimitry Andric     if (RV != Prev)
31167c32a98SDimitry Andric       return nullptr;
31267c32a98SDimitry Andric 
31367c32a98SDimitry Andric     // Look through the optional bitcast.
31467c32a98SDimitry Andric     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
31567c32a98SDimitry Andric       RV = BI->getOperand(0);
31667c32a98SDimitry Andric       Prev = BI->getPrevNode();
31767c32a98SDimitry Andric       if (!Prev || RV != Prev)
31867c32a98SDimitry Andric         return nullptr;
31967c32a98SDimitry Andric     }
32067c32a98SDimitry Andric   }
32167c32a98SDimitry Andric 
32267c32a98SDimitry Andric   if (auto *CI = dyn_cast<CallInst>(Prev)) {
32367c32a98SDimitry Andric     if (CI->isMustTailCall())
32467c32a98SDimitry Andric       return CI;
32567c32a98SDimitry Andric   }
32667c32a98SDimitry Andric   return nullptr;
32767c32a98SDimitry Andric }
32867c32a98SDimitry Andric 
getTerminatingDeoptimizeCall() const32971d5a254SDimitry Andric const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
33001095a5dSDimitry Andric   if (InstList.empty())
33101095a5dSDimitry Andric     return nullptr;
33201095a5dSDimitry Andric   auto *RI = dyn_cast<ReturnInst>(&InstList.back());
33301095a5dSDimitry Andric   if (!RI || RI == &InstList.front())
33401095a5dSDimitry Andric     return nullptr;
33501095a5dSDimitry Andric 
33601095a5dSDimitry Andric   if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
33701095a5dSDimitry Andric     if (Function *F = CI->getCalledFunction())
33801095a5dSDimitry Andric       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
33901095a5dSDimitry Andric         return CI;
34001095a5dSDimitry Andric 
34101095a5dSDimitry Andric   return nullptr;
34201095a5dSDimitry Andric }
34301095a5dSDimitry Andric 
getPostdominatingDeoptimizeCall() const344cfca06d7SDimitry Andric const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const {
345cfca06d7SDimitry Andric   const BasicBlock* BB = this;
346cfca06d7SDimitry Andric   SmallPtrSet<const BasicBlock *, 8> Visited;
347cfca06d7SDimitry Andric   Visited.insert(BB);
348cfca06d7SDimitry Andric   while (auto *Succ = BB->getUniqueSuccessor()) {
349cfca06d7SDimitry Andric     if (!Visited.insert(Succ).second)
350cfca06d7SDimitry Andric       return nullptr;
351cfca06d7SDimitry Andric     BB = Succ;
352cfca06d7SDimitry Andric   }
353cfca06d7SDimitry Andric   return BB->getTerminatingDeoptimizeCall();
354cfca06d7SDimitry Andric }
355cfca06d7SDimitry Andric 
getFirstMayFaultInst() const3567fa27ce4SDimitry Andric const Instruction *BasicBlock::getFirstMayFaultInst() const {
3577fa27ce4SDimitry Andric   if (InstList.empty())
3587fa27ce4SDimitry Andric     return nullptr;
3597fa27ce4SDimitry Andric   for (const Instruction &I : *this)
3607fa27ce4SDimitry Andric     if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallBase>(I))
3617fa27ce4SDimitry Andric       return &I;
3627fa27ce4SDimitry Andric   return nullptr;
3637fa27ce4SDimitry Andric }
3647fa27ce4SDimitry Andric 
getFirstNonPHI() const36571d5a254SDimitry Andric const Instruction* BasicBlock::getFirstNonPHI() const {
36671d5a254SDimitry Andric   for (const Instruction &I : *this)
367ee8648bdSDimitry Andric     if (!isa<PHINode>(I))
368ee8648bdSDimitry Andric       return &I;
369ee8648bdSDimitry Andric   return nullptr;
370009b1c42SEd Schouten }
371009b1c42SEd Schouten 
getFirstNonPHIIt() const372b1c73532SDimitry Andric BasicBlock::const_iterator BasicBlock::getFirstNonPHIIt() const {
373b1c73532SDimitry Andric   const Instruction *I = getFirstNonPHI();
374ac9a064cSDimitry Andric   if (!I)
375ac9a064cSDimitry Andric     return end();
376b1c73532SDimitry Andric   BasicBlock::const_iterator It = I->getIterator();
377b1c73532SDimitry Andric   // Set the head-inclusive bit to indicate that this iterator includes
378b1c73532SDimitry Andric   // any debug-info at the start of the block. This is a no-op unless the
379b1c73532SDimitry Andric   // appropriate CMake flag is set.
380b1c73532SDimitry Andric   It.setHeadBit(true);
381b1c73532SDimitry Andric   return It;
382b1c73532SDimitry Andric }
383b1c73532SDimitry Andric 
getFirstNonPHIOrDbg(bool SkipPseudoOp) const384b60736ecSDimitry Andric const Instruction *BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const {
385b60736ecSDimitry Andric   for (const Instruction &I : *this) {
386b60736ecSDimitry Andric     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
387b60736ecSDimitry Andric       continue;
388b60736ecSDimitry Andric 
389b60736ecSDimitry Andric     if (SkipPseudoOp && isa<PseudoProbeInst>(I))
390b60736ecSDimitry Andric       continue;
391b60736ecSDimitry Andric 
392ee8648bdSDimitry Andric     return &I;
393b60736ecSDimitry Andric   }
394ee8648bdSDimitry Andric   return nullptr;
395b5efedafSRoman Divacky }
396b5efedafSRoman Divacky 
397b60736ecSDimitry Andric const Instruction *
getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const398b60736ecSDimitry Andric BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const {
39971d5a254SDimitry Andric   for (const Instruction &I : *this) {
400ee8648bdSDimitry Andric     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
401411bd29eSDimitry Andric       continue;
402411bd29eSDimitry Andric 
403d8e91e46SDimitry Andric     if (I.isLifetimeStartOrEnd())
404ee8648bdSDimitry Andric       continue;
405ee8648bdSDimitry Andric 
406b60736ecSDimitry Andric     if (SkipPseudoOp && isa<PseudoProbeInst>(I))
407b60736ecSDimitry Andric       continue;
408b60736ecSDimitry Andric 
409ee8648bdSDimitry Andric     return &I;
410411bd29eSDimitry Andric   }
411ee8648bdSDimitry Andric   return nullptr;
412411bd29eSDimitry Andric }
413411bd29eSDimitry Andric 
getFirstInsertionPt() const41471d5a254SDimitry Andric BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
41571d5a254SDimitry Andric   const Instruction *FirstNonPHI = getFirstNonPHI();
416ee8648bdSDimitry Andric   if (!FirstNonPHI)
417ee8648bdSDimitry Andric     return end();
418ee8648bdSDimitry Andric 
41971d5a254SDimitry Andric   const_iterator InsertPt = FirstNonPHI->getIterator();
420dd58ef01SDimitry Andric   if (InsertPt->isEHPad()) ++InsertPt;
421b1c73532SDimitry Andric   // Set the head-inclusive bit to indicate that this iterator includes
422b1c73532SDimitry Andric   // any debug-info at the start of the block. This is a no-op unless the
423b1c73532SDimitry Andric   // appropriate CMake flag is set.
424b1c73532SDimitry Andric   InsertPt.setHeadBit(true);
42530815c53SDimitry Andric   return InsertPt;
42630815c53SDimitry Andric }
42730815c53SDimitry Andric 
getFirstNonPHIOrDbgOrAlloca() const428e3b55780SDimitry Andric BasicBlock::const_iterator BasicBlock::getFirstNonPHIOrDbgOrAlloca() const {
429e3b55780SDimitry Andric   const Instruction *FirstNonPHI = getFirstNonPHI();
430e3b55780SDimitry Andric   if (!FirstNonPHI)
431e3b55780SDimitry Andric     return end();
432e3b55780SDimitry Andric 
433e3b55780SDimitry Andric   const_iterator InsertPt = FirstNonPHI->getIterator();
434e3b55780SDimitry Andric   if (InsertPt->isEHPad())
435e3b55780SDimitry Andric     ++InsertPt;
436e3b55780SDimitry Andric 
437e3b55780SDimitry Andric   if (isEntryBlock()) {
438e3b55780SDimitry Andric     const_iterator End = end();
439e3b55780SDimitry Andric     while (InsertPt != End &&
440e3b55780SDimitry Andric            (isa<AllocaInst>(*InsertPt) || isa<DbgInfoIntrinsic>(*InsertPt) ||
441e3b55780SDimitry Andric             isa<PseudoProbeInst>(*InsertPt))) {
442e3b55780SDimitry Andric       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&*InsertPt)) {
443e3b55780SDimitry Andric         if (!AI->isStaticAlloca())
444e3b55780SDimitry Andric           break;
445e3b55780SDimitry Andric       }
446e3b55780SDimitry Andric       ++InsertPt;
447e3b55780SDimitry Andric     }
448e3b55780SDimitry Andric   }
449e3b55780SDimitry Andric   return InsertPt;
450e3b55780SDimitry Andric }
451e3b55780SDimitry Andric 
dropAllReferences()452009b1c42SEd Schouten void BasicBlock::dropAllReferences() {
45301095a5dSDimitry Andric   for (Instruction &I : *this)
45401095a5dSDimitry Andric     I.dropAllReferences();
455009b1c42SEd Schouten }
456009b1c42SEd Schouten 
getSinglePredecessor() const45771d5a254SDimitry Andric const BasicBlock *BasicBlock::getSinglePredecessor() const {
45871d5a254SDimitry Andric   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
4595ca98fd9SDimitry Andric   if (PI == E) return nullptr;         // No preds.
46071d5a254SDimitry Andric   const BasicBlock *ThePred = *PI;
461009b1c42SEd Schouten   ++PI;
4625ca98fd9SDimitry Andric   return (PI == E) ? ThePred : nullptr /*multiple preds*/;
463009b1c42SEd Schouten }
464009b1c42SEd Schouten 
getUniquePredecessor() const46571d5a254SDimitry Andric const BasicBlock *BasicBlock::getUniquePredecessor() const {
46671d5a254SDimitry Andric   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
4675ca98fd9SDimitry Andric   if (PI == E) return nullptr; // No preds.
46871d5a254SDimitry Andric   const BasicBlock *PredBB = *PI;
469009b1c42SEd Schouten   ++PI;
470009b1c42SEd Schouten   for (;PI != E; ++PI) {
471009b1c42SEd Schouten     if (*PI != PredBB)
4725ca98fd9SDimitry Andric       return nullptr;
473009b1c42SEd Schouten     // The same predecessor appears multiple times in the predecessor list.
474009b1c42SEd Schouten     // This is OK.
475009b1c42SEd Schouten   }
476009b1c42SEd Schouten   return PredBB;
477009b1c42SEd Schouten }
478009b1c42SEd Schouten 
hasNPredecessors(unsigned N) const479d8e91e46SDimitry Andric bool BasicBlock::hasNPredecessors(unsigned N) const {
480d8e91e46SDimitry Andric   return hasNItems(pred_begin(this), pred_end(this), N);
481d8e91e46SDimitry Andric }
482d8e91e46SDimitry Andric 
hasNPredecessorsOrMore(unsigned N) const483d8e91e46SDimitry Andric bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
484d8e91e46SDimitry Andric   return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
485d8e91e46SDimitry Andric }
486d8e91e46SDimitry Andric 
getSingleSuccessor() const48771d5a254SDimitry Andric const BasicBlock *BasicBlock::getSingleSuccessor() const {
488cfca06d7SDimitry Andric   const_succ_iterator SI = succ_begin(this), E = succ_end(this);
4895a5ac124SDimitry Andric   if (SI == E) return nullptr; // no successors
49071d5a254SDimitry Andric   const BasicBlock *TheSucc = *SI;
4915a5ac124SDimitry Andric   ++SI;
4925a5ac124SDimitry Andric   return (SI == E) ? TheSucc : nullptr /* multiple successors */;
4935a5ac124SDimitry Andric }
4945a5ac124SDimitry Andric 
getUniqueSuccessor() const49571d5a254SDimitry Andric const BasicBlock *BasicBlock::getUniqueSuccessor() const {
496cfca06d7SDimitry Andric   const_succ_iterator SI = succ_begin(this), E = succ_end(this);
497dd58ef01SDimitry Andric   if (SI == E) return nullptr; // No successors
49871d5a254SDimitry Andric   const BasicBlock *SuccBB = *SI;
4995a5ac124SDimitry Andric   ++SI;
5005a5ac124SDimitry Andric   for (;SI != E; ++SI) {
5015a5ac124SDimitry Andric     if (*SI != SuccBB)
502dd58ef01SDimitry Andric       return nullptr;
5035a5ac124SDimitry Andric     // The same successor appears multiple times in the successor list.
5045a5ac124SDimitry Andric     // This is OK.
5055a5ac124SDimitry Andric   }
5065a5ac124SDimitry Andric   return SuccBB;
5075a5ac124SDimitry Andric }
5085a5ac124SDimitry Andric 
phis()509ab44ce3dSDimitry Andric iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
510eb11fae6SDimitry Andric   PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
511eb11fae6SDimitry Andric   return make_range<phi_iterator>(P, nullptr);
512ab44ce3dSDimitry Andric }
513ab44ce3dSDimitry Andric 
removePredecessor(BasicBlock * Pred,bool KeepOneInputPHIs)514009b1c42SEd Schouten void BasicBlock::removePredecessor(BasicBlock *Pred,
515e6d15924SDimitry Andric                                    bool KeepOneInputPHIs) {
516cfca06d7SDimitry Andric   // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs.
517b60736ecSDimitry Andric   assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) &&
518cfca06d7SDimitry Andric          "Pred is not a predecessor!");
519009b1c42SEd Schouten 
520cfca06d7SDimitry Andric   // Return early if there are no PHI nodes to update.
521b60736ecSDimitry Andric   if (empty() || !isa<PHINode>(begin()))
522cfca06d7SDimitry Andric     return;
523009b1c42SEd Schouten 
524b60736ecSDimitry Andric   unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();
525b60736ecSDimitry Andric   for (PHINode &Phi : make_early_inc_range(phis())) {
526b60736ecSDimitry Andric     Phi.removeIncomingValue(Pred, !KeepOneInputPHIs);
527b60736ecSDimitry Andric     if (KeepOneInputPHIs)
528b60736ecSDimitry Andric       continue;
529b60736ecSDimitry Andric 
530b60736ecSDimitry Andric     // If we have a single predecessor, removeIncomingValue may have erased the
531b60736ecSDimitry Andric     // PHI node itself.
532b60736ecSDimitry Andric     if (NumPreds == 1)
533b60736ecSDimitry Andric       continue;
534b60736ecSDimitry Andric 
535b60736ecSDimitry Andric     // Try to replace the PHI node with a constant value.
536b60736ecSDimitry Andric     if (Value *PhiConstant = Phi.hasConstantValue()) {
537b60736ecSDimitry Andric       Phi.replaceAllUsesWith(PhiConstant);
538b60736ecSDimitry Andric       Phi.eraseFromParent();
539009b1c42SEd Schouten     }
540009b1c42SEd Schouten   }
541cfca06d7SDimitry Andric }
542009b1c42SEd Schouten 
canSplitPredecessors() const543dd58ef01SDimitry Andric bool BasicBlock::canSplitPredecessors() const {
544dd58ef01SDimitry Andric   const Instruction *FirstNonPHI = getFirstNonPHI();
545dd58ef01SDimitry Andric   if (isa<LandingPadInst>(FirstNonPHI))
546dd58ef01SDimitry Andric     return true;
547dd58ef01SDimitry Andric   // This is perhaps a little conservative because constructs like
548dd58ef01SDimitry Andric   // CleanupBlockInst are pretty easy to split.  However, SplitBlockPredecessors
549dd58ef01SDimitry Andric   // cannot handle such things just yet.
550dd58ef01SDimitry Andric   if (FirstNonPHI->isEHPad())
551dd58ef01SDimitry Andric     return false;
552dd58ef01SDimitry Andric   return true;
553dd58ef01SDimitry Andric }
554009b1c42SEd Schouten 
isLegalToHoistInto() const55508bbd35aSDimitry Andric bool BasicBlock::isLegalToHoistInto() const {
55608bbd35aSDimitry Andric   auto *Term = getTerminator();
55708bbd35aSDimitry Andric   // No terminator means the block is under construction.
55808bbd35aSDimitry Andric   if (!Term)
55908bbd35aSDimitry Andric     return true;
56008bbd35aSDimitry Andric 
56108bbd35aSDimitry Andric   // If the block has no successors, there can be no instructions to hoist.
56208bbd35aSDimitry Andric   assert(Term->getNumSuccessors() > 0);
56308bbd35aSDimitry Andric 
564b1c73532SDimitry Andric   // Instructions should not be hoisted across special terminators, which may
565b1c73532SDimitry Andric   // have side effects or return values.
566b1c73532SDimitry Andric   return !Term->isSpecialTerminator();
56708bbd35aSDimitry Andric }
56808bbd35aSDimitry Andric 
isEntryBlock() const569344a3780SDimitry Andric bool BasicBlock::isEntryBlock() const {
570344a3780SDimitry Andric   const Function *F = getParent();
571344a3780SDimitry Andric   assert(F && "Block must have a parent function to use this API");
572344a3780SDimitry Andric   return this == &F->getEntryBlock();
573344a3780SDimitry Andric }
574344a3780SDimitry Andric 
splitBasicBlock(iterator I,const Twine & BBName,bool Before)575b60736ecSDimitry Andric BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName,
576b60736ecSDimitry Andric                                         bool Before) {
577b60736ecSDimitry Andric   if (Before)
578b60736ecSDimitry Andric     return splitBasicBlockBefore(I, BBName);
579b60736ecSDimitry Andric 
580009b1c42SEd Schouten   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
581009b1c42SEd Schouten   assert(I != InstList.end() &&
582009b1c42SEd Schouten          "Trying to get me to create degenerate basic block!");
583009b1c42SEd Schouten 
58401095a5dSDimitry Andric   BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
58501095a5dSDimitry Andric                                        this->getNextNode());
586009b1c42SEd Schouten 
5873a0822f0SDimitry Andric   // Save DebugLoc of split point before invalidating iterator.
588b1c73532SDimitry Andric   DebugLoc Loc = I->getStableDebugLoc();
589009b1c42SEd Schouten   // Move all of the specified instructions from the original basic block into
590009b1c42SEd Schouten   // the new basic block.
591e3b55780SDimitry Andric   New->splice(New->end(), this, I, end());
592009b1c42SEd Schouten 
593009b1c42SEd Schouten   // Add a branch instruction to the newly formed basic block.
5943a0822f0SDimitry Andric   BranchInst *BI = BranchInst::Create(New, this);
5953a0822f0SDimitry Andric   BI->setDebugLoc(Loc);
596009b1c42SEd Schouten 
597009b1c42SEd Schouten   // Now we must loop through all of the successors of the New block (which
598009b1c42SEd Schouten   // _were_ the successors of the 'this' block), and update any PHI nodes in
599009b1c42SEd Schouten   // successors.  If there were PHI nodes in the successors, then they need to
600e6d15924SDimitry Andric   // know that incoming branches will be from New, not from Old (this).
601009b1c42SEd Schouten   //
602e6d15924SDimitry Andric   New->replaceSuccessorsPhiUsesWith(this, New);
603009b1c42SEd Schouten   return New;
604009b1c42SEd Schouten }
60536bf506aSRoman Divacky 
splitBasicBlockBefore(iterator I,const Twine & BBName)606b60736ecSDimitry Andric BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) {
607b60736ecSDimitry Andric   assert(getTerminator() &&
608b60736ecSDimitry Andric          "Can't use splitBasicBlockBefore on degenerate BB!");
609b60736ecSDimitry Andric   assert(I != InstList.end() &&
610b60736ecSDimitry Andric          "Trying to get me to create degenerate basic block!");
611b60736ecSDimitry Andric 
612b60736ecSDimitry Andric   assert((!isa<PHINode>(*I) || getSinglePredecessor()) &&
613b60736ecSDimitry Andric          "cannot split on multi incoming phis");
614b60736ecSDimitry Andric 
615b60736ecSDimitry Andric   BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this);
616b60736ecSDimitry Andric   // Save DebugLoc of split point before invalidating iterator.
617b60736ecSDimitry Andric   DebugLoc Loc = I->getDebugLoc();
618b60736ecSDimitry Andric   // Move all of the specified instructions from the original basic block into
619b60736ecSDimitry Andric   // the new basic block.
620e3b55780SDimitry Andric   New->splice(New->end(), this, begin(), I);
621b60736ecSDimitry Andric 
622b60736ecSDimitry Andric   // Loop through all of the predecessors of the 'this' block (which will be the
623b60736ecSDimitry Andric   // predecessors of the New block), replace the specified successor 'this'
624b60736ecSDimitry Andric   // block to point at the New block and update any PHI nodes in 'this' block.
625b60736ecSDimitry Andric   // If there were PHI nodes in 'this' block, the PHI nodes are updated
626b60736ecSDimitry Andric   // to reflect that the incoming branches will be from the New block and not
627b60736ecSDimitry Andric   // from predecessors of the 'this' block.
628e3b55780SDimitry Andric   // Save predecessors to separate vector before modifying them.
629e3b55780SDimitry Andric   SmallVector<BasicBlock *, 4> Predecessors;
630e3b55780SDimitry Andric   for (BasicBlock *Pred : predecessors(this))
631e3b55780SDimitry Andric     Predecessors.push_back(Pred);
632e3b55780SDimitry Andric   for (BasicBlock *Pred : Predecessors) {
633b60736ecSDimitry Andric     Instruction *TI = Pred->getTerminator();
634b60736ecSDimitry Andric     TI->replaceSuccessorWith(this, New);
635b60736ecSDimitry Andric     this->replacePhiUsesWith(Pred, New);
636b60736ecSDimitry Andric   }
637b60736ecSDimitry Andric   // Add a branch instruction from  "New" to "this" Block.
638b60736ecSDimitry Andric   BranchInst *BI = BranchInst::Create(this, New);
639b60736ecSDimitry Andric   BI->setDebugLoc(Loc);
640b60736ecSDimitry Andric 
641b60736ecSDimitry Andric   return New;
642b60736ecSDimitry Andric }
643b60736ecSDimitry Andric 
erase(BasicBlock::iterator FromIt,BasicBlock::iterator ToIt)644e3b55780SDimitry Andric BasicBlock::iterator BasicBlock::erase(BasicBlock::iterator FromIt,
645e3b55780SDimitry Andric                                        BasicBlock::iterator ToIt) {
646ac9a064cSDimitry Andric   for (Instruction &I : make_early_inc_range(make_range(FromIt, ToIt)))
647ac9a064cSDimitry Andric     I.eraseFromParent();
648ac9a064cSDimitry Andric   return ToIt;
649e3b55780SDimitry Andric }
650e3b55780SDimitry Andric 
replacePhiUsesWith(BasicBlock * Old,BasicBlock * New)651e6d15924SDimitry Andric void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {
652e6d15924SDimitry Andric   // N.B. This might not be a complete BasicBlock, so don't assume
653e6d15924SDimitry Andric   // that it ends with a non-phi instruction.
65477fc4c14SDimitry Andric   for (Instruction &I : *this) {
65577fc4c14SDimitry Andric     PHINode *PN = dyn_cast<PHINode>(&I);
656e6d15924SDimitry Andric     if (!PN)
657e6d15924SDimitry Andric       break;
658e6d15924SDimitry Andric     PN->replaceIncomingBlockWith(Old, New);
659e6d15924SDimitry Andric   }
660e6d15924SDimitry Andric }
661e6d15924SDimitry Andric 
replaceSuccessorsPhiUsesWith(BasicBlock * Old,BasicBlock * New)662e6d15924SDimitry Andric void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,
663e6d15924SDimitry Andric                                               BasicBlock *New) {
664d8e91e46SDimitry Andric   Instruction *TI = getTerminator();
665411bd29eSDimitry Andric   if (!TI)
666411bd29eSDimitry Andric     // Cope with being called on a BasicBlock that doesn't have a terminator
667411bd29eSDimitry Andric     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
668411bd29eSDimitry Andric     return;
669344a3780SDimitry Andric   for (BasicBlock *Succ : successors(TI))
670e6d15924SDimitry Andric     Succ->replacePhiUsesWith(Old, New);
671411bd29eSDimitry Andric }
672e6d15924SDimitry Andric 
replaceSuccessorsPhiUsesWith(BasicBlock * New)673e6d15924SDimitry Andric void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
674e6d15924SDimitry Andric   this->replaceSuccessorsPhiUsesWith(this, New);
675411bd29eSDimitry Andric }
67630815c53SDimitry Andric 
isLandingPad() const67730815c53SDimitry Andric bool BasicBlock::isLandingPad() const {
67830815c53SDimitry Andric   return isa<LandingPadInst>(getFirstNonPHI());
67930815c53SDimitry Andric }
68030815c53SDimitry Andric 
getLandingPadInst() const68163faed5bSDimitry Andric const LandingPadInst *BasicBlock::getLandingPadInst() const {
68263faed5bSDimitry Andric   return dyn_cast<LandingPadInst>(getFirstNonPHI());
68363faed5bSDimitry Andric }
684044eb2f6SDimitry Andric 
getIrrLoopHeaderWeight() const685e3b55780SDimitry Andric std::optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
686d8e91e46SDimitry Andric   const Instruction *TI = getTerminator();
687044eb2f6SDimitry Andric   if (MDNode *MDIrrLoopHeader =
688044eb2f6SDimitry Andric       TI->getMetadata(LLVMContext::MD_irr_loop)) {
689044eb2f6SDimitry Andric     MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
690ac9a064cSDimitry Andric     if (MDName->getString() == "loop_header_weight") {
691044eb2f6SDimitry Andric       auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
692e3b55780SDimitry Andric       return std::optional<uint64_t>(CI->getValue().getZExtValue());
693044eb2f6SDimitry Andric     }
694044eb2f6SDimitry Andric   }
695e3b55780SDimitry Andric   return std::nullopt;
696044eb2f6SDimitry Andric }
697eb11fae6SDimitry Andric 
skipDebugIntrinsics(BasicBlock::iterator It)698eb11fae6SDimitry Andric BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
699eb11fae6SDimitry Andric   while (isa<DbgInfoIntrinsic>(It))
700eb11fae6SDimitry Andric     ++It;
701eb11fae6SDimitry Andric   return It;
702eb11fae6SDimitry Andric }
703cfca06d7SDimitry Andric 
renumberInstructions()704cfca06d7SDimitry Andric void BasicBlock::renumberInstructions() {
705cfca06d7SDimitry Andric   unsigned Order = 0;
706cfca06d7SDimitry Andric   for (Instruction &I : *this)
707cfca06d7SDimitry Andric     I.Order = Order++;
708cfca06d7SDimitry Andric 
709cfca06d7SDimitry Andric   // Set the bit to indicate that the instruction order valid and cached.
710cfca06d7SDimitry Andric   BasicBlockBits Bits = getBasicBlockBits();
711cfca06d7SDimitry Andric   Bits.InstrOrderValid = true;
712cfca06d7SDimitry Andric   setBasicBlockBits(Bits);
713c0981da4SDimitry Andric 
714c0981da4SDimitry Andric   NumInstrRenumberings++;
715cfca06d7SDimitry Andric }
716cfca06d7SDimitry Andric 
flushTerminatorDbgRecords()717ac9a064cSDimitry Andric void BasicBlock::flushTerminatorDbgRecords() {
718ac9a064cSDimitry Andric   // If we erase the terminator in a block, any DbgRecords will sink and "fall
719b1c73532SDimitry Andric   // off the end", existing after any terminator that gets inserted. With
720b1c73532SDimitry Andric   // dbg.value intrinsics we would just insert the terminator at end() and
721ac9a064cSDimitry Andric   // the dbg.values would come before the terminator. With DbgRecords, we must
722b1c73532SDimitry Andric   // do this manually.
723b1c73532SDimitry Andric   // To get out of this unfortunate form, whenever we insert a terminator,
724ac9a064cSDimitry Andric   // check whether there's anything trailing at the end and move those
725ac9a064cSDimitry Andric   // DbgRecords in front of the terminator.
726b1c73532SDimitry Andric 
727b1c73532SDimitry Andric   // Do nothing if we're not in new debug-info format.
728b1c73532SDimitry Andric   if (!IsNewDbgInfoFormat)
729b1c73532SDimitry Andric     return;
730b1c73532SDimitry Andric 
731b1c73532SDimitry Andric   // If there's no terminator, there's nothing to do.
732b1c73532SDimitry Andric   Instruction *Term = getTerminator();
733b1c73532SDimitry Andric   if (!Term)
734b1c73532SDimitry Andric     return;
735b1c73532SDimitry Andric 
736ac9a064cSDimitry Andric   // Are there any dangling DbgRecords?
737ac9a064cSDimitry Andric   DbgMarker *TrailingDbgRecords = getTrailingDbgRecords();
738ac9a064cSDimitry Andric   if (!TrailingDbgRecords)
739b1c73532SDimitry Andric     return;
740b1c73532SDimitry Andric 
741ac9a064cSDimitry Andric   // Transfer DbgRecords from the trailing position onto the terminator.
742ac9a064cSDimitry Andric   createMarker(Term);
743ac9a064cSDimitry Andric   Term->DebugMarker->absorbDebugValues(*TrailingDbgRecords, false);
744ac9a064cSDimitry Andric   TrailingDbgRecords->eraseFromParent();
745ac9a064cSDimitry Andric   deleteTrailingDbgRecords();
746b1c73532SDimitry Andric }
747b1c73532SDimitry Andric 
spliceDebugInfoEmptyBlock(BasicBlock::iterator Dest,BasicBlock * Src,BasicBlock::iterator First,BasicBlock::iterator Last)748b1c73532SDimitry Andric void BasicBlock::spliceDebugInfoEmptyBlock(BasicBlock::iterator Dest,
749b1c73532SDimitry Andric                                            BasicBlock *Src,
750b1c73532SDimitry Andric                                            BasicBlock::iterator First,
751b1c73532SDimitry Andric                                            BasicBlock::iterator Last) {
752b1c73532SDimitry Andric   // Imagine the folowing:
753b1c73532SDimitry Andric   //
754b1c73532SDimitry Andric   //   bb1:
755b1c73532SDimitry Andric   //     dbg.value(...
756b1c73532SDimitry Andric   //     ret i32 0
757b1c73532SDimitry Andric   //
758b1c73532SDimitry Andric   // If an optimisation pass attempts to splice the contents of the block from
759b1c73532SDimitry Andric   // BB1->begin() to BB1->getTerminator(), then the dbg.value will be
760b1c73532SDimitry Andric   // transferred to the destination.
761ac9a064cSDimitry Andric   // However, in the "new" DbgRecord format for debug-info, that range is empty:
762b1c73532SDimitry Andric   // begin() returns an iterator to the terminator, as there will only be a
763b1c73532SDimitry Andric   // single instruction in the block. We must piece together from the bits set
764b1c73532SDimitry Andric   // in the iterators whether there was the intention to transfer any debug
765b1c73532SDimitry Andric   // info.
766b1c73532SDimitry Andric 
767b1c73532SDimitry Andric   // If we're not in "new" debug-info format, do nothing.
768b1c73532SDimitry Andric   if (!IsNewDbgInfoFormat)
769b1c73532SDimitry Andric     return;
770b1c73532SDimitry Andric 
771b1c73532SDimitry Andric   assert(First == Last);
772b1c73532SDimitry Andric   bool InsertAtHead = Dest.getHeadBit();
773b1c73532SDimitry Andric   bool ReadFromHead = First.getHeadBit();
774b1c73532SDimitry Andric 
775b1c73532SDimitry Andric   // If the source block is completely empty, including no terminator, then
776ac9a064cSDimitry Andric   // transfer any trailing DbgRecords that are still hanging around. This can
777b1c73532SDimitry Andric   // occur when a block is optimised away and the terminator has been moved
778b1c73532SDimitry Andric   // somewhere else.
779b1c73532SDimitry Andric   if (Src->empty()) {
780ac9a064cSDimitry Andric     DbgMarker *SrcTrailingDbgRecords = Src->getTrailingDbgRecords();
781ac9a064cSDimitry Andric     if (!SrcTrailingDbgRecords)
782b1c73532SDimitry Andric       return;
783b1c73532SDimitry Andric 
784ac9a064cSDimitry Andric     Dest->adoptDbgRecords(Src, Src->end(), InsertAtHead);
785ac9a064cSDimitry Andric     // adoptDbgRecords should have released the trailing DbgRecords.
786ac9a064cSDimitry Andric     assert(!Src->getTrailingDbgRecords());
787b1c73532SDimitry Andric     return;
788b1c73532SDimitry Andric   }
789b1c73532SDimitry Andric 
790b1c73532SDimitry Andric   // There are instructions in this block; if the First iterator was
791b1c73532SDimitry Andric   // with begin() / getFirstInsertionPt() then the caller intended debug-info
7924df029ccSDimitry Andric   // at the start of the block to be transferred. Return otherwise.
7934df029ccSDimitry Andric   if (Src->empty() || First != Src->begin() || !ReadFromHead)
7944df029ccSDimitry Andric     return;
7954df029ccSDimitry Andric 
7964df029ccSDimitry Andric   // Is there actually anything to transfer?
797ac9a064cSDimitry Andric   if (!First->hasDbgRecords())
7984df029ccSDimitry Andric     return;
7994df029ccSDimitry Andric 
800ac9a064cSDimitry Andric   createMarker(Dest)->absorbDebugValues(*First->DebugMarker, InsertAtHead);
801b1c73532SDimitry Andric 
802b1c73532SDimitry Andric   return;
803b1c73532SDimitry Andric }
804b1c73532SDimitry Andric 
spliceDebugInfo(BasicBlock::iterator Dest,BasicBlock * Src,BasicBlock::iterator First,BasicBlock::iterator Last)805b1c73532SDimitry Andric void BasicBlock::spliceDebugInfo(BasicBlock::iterator Dest, BasicBlock *Src,
806b1c73532SDimitry Andric                                  BasicBlock::iterator First,
807b1c73532SDimitry Andric                                  BasicBlock::iterator Last) {
808b1c73532SDimitry Andric   /* Do a quick normalisation before calling the real splice implementation. We
809b1c73532SDimitry Andric      might be operating on a degenerate basic block that has no instructions
810b1c73532SDimitry Andric      in it, a legitimate transient state. In that case, Dest will be end() and
811ac9a064cSDimitry Andric      any DbgRecords temporarily stored in the TrailingDbgRecords map in
812ac9a064cSDimitry Andric      LLVMContext. We might illustrate it thus:
813b1c73532SDimitry Andric 
814b1c73532SDimitry Andric                          Dest
815b1c73532SDimitry Andric                            |
816b1c73532SDimitry Andric      this-block:    ~~~~~~~~
817b1c73532SDimitry Andric       Src-block:            ++++B---B---B---B:::C
818b1c73532SDimitry Andric                                 |               |
819b1c73532SDimitry Andric                                First           Last
820b1c73532SDimitry Andric 
821ac9a064cSDimitry Andric      However: does the caller expect the "~" DbgRecords to end up before or
822ac9a064cSDimitry Andric      after the spliced segment? This is communciated in the "Head" bit of Dest,
823ac9a064cSDimitry Andric      which signals whether the caller called begin() or end() on this block.
824b1c73532SDimitry Andric 
825ac9a064cSDimitry Andric      If the head bit is set, then all is well, we leave DbgRecords trailing just
826b1c73532SDimitry Andric      like how dbg.value instructions would trail after instructions spliced to
827b1c73532SDimitry Andric      the beginning of this block.
828b1c73532SDimitry Andric 
829ac9a064cSDimitry Andric      If the head bit isn't set, then try to jam the "~" DbgRecords onto the
830ac9a064cSDimitry Andric      front of the First instruction, then splice like normal, which joins the
831ac9a064cSDimitry Andric      "~" DbgRecords with the "+" DbgRecords. However if the "+" DbgRecords are
832ac9a064cSDimitry Andric      supposed to be left behind in Src, then:
833ac9a064cSDimitry Andric       * detach the "+" DbgRecords,
834ac9a064cSDimitry Andric       * move the "~" DbgRecords onto First,
835b1c73532SDimitry Andric       * splice like normal,
836ac9a064cSDimitry Andric       * replace the "+" DbgRecords onto the Last position.
837b1c73532SDimitry Andric      Complicated, but gets the job done. */
838b1c73532SDimitry Andric 
839ac9a064cSDimitry Andric   // If we're inserting at end(), and not in front of dangling DbgRecords, then
840ac9a064cSDimitry Andric   // move the DbgRecords onto "First". They'll then be moved naturally in the
841b1c73532SDimitry Andric   // splice process.
842ac9a064cSDimitry Andric   DbgMarker *MoreDanglingDbgRecords = nullptr;
843ac9a064cSDimitry Andric   DbgMarker *OurTrailingDbgRecords = getTrailingDbgRecords();
844ac9a064cSDimitry Andric   if (Dest == end() && !Dest.getHeadBit() && OurTrailingDbgRecords) {
845ac9a064cSDimitry Andric     // Are the "+" DbgRecords not supposed to move? If so, detach them
846b1c73532SDimitry Andric     // temporarily.
847ac9a064cSDimitry Andric     if (!First.getHeadBit() && First->hasDbgRecords()) {
848ac9a064cSDimitry Andric       MoreDanglingDbgRecords = Src->getMarker(First);
849ac9a064cSDimitry Andric       MoreDanglingDbgRecords->removeFromParent();
850b1c73532SDimitry Andric     }
851b1c73532SDimitry Andric 
852ac9a064cSDimitry Andric     if (First->hasDbgRecords()) {
853b1c73532SDimitry Andric       // Place them at the front, it would look like this:
854b1c73532SDimitry Andric       //            Dest
855b1c73532SDimitry Andric       //              |
856b1c73532SDimitry Andric       // this-block:
857b1c73532SDimitry Andric       // Src-block: ~~~~~~~~++++B---B---B---B:::C
858b1c73532SDimitry Andric       //                        |               |
859b1c73532SDimitry Andric       //                       First           Last
860ac9a064cSDimitry Andric       First->adoptDbgRecords(this, end(), true);
861b1c73532SDimitry Andric     } else {
862b1c73532SDimitry Andric       // No current marker, create one and absorb in. (FIXME: we can avoid an
863b1c73532SDimitry Andric       // allocation in the future).
864ac9a064cSDimitry Andric       DbgMarker *CurMarker = Src->createMarker(&*First);
865ac9a064cSDimitry Andric       CurMarker->absorbDebugValues(*OurTrailingDbgRecords, false);
866ac9a064cSDimitry Andric       OurTrailingDbgRecords->eraseFromParent();
867b1c73532SDimitry Andric     }
868ac9a064cSDimitry Andric     deleteTrailingDbgRecords();
869b1c73532SDimitry Andric     First.setHeadBit(true);
870b1c73532SDimitry Andric   }
871b1c73532SDimitry Andric 
872b1c73532SDimitry Andric   // Call the main debug-info-splicing implementation.
873b1c73532SDimitry Andric   spliceDebugInfoImpl(Dest, Src, First, Last);
874b1c73532SDimitry Andric 
875ac9a064cSDimitry Andric   // Do we have some "+" DbgRecords hanging around that weren't supposed to
876ac9a064cSDimitry Andric   // move, and we detached to make things easier?
877ac9a064cSDimitry Andric   if (!MoreDanglingDbgRecords)
878b1c73532SDimitry Andric     return;
879b1c73532SDimitry Andric 
880ac9a064cSDimitry Andric   // FIXME: we could avoid an allocation here sometimes. (adoptDbgRecords
881ac9a064cSDimitry Andric   // requires an iterator).
882ac9a064cSDimitry Andric   DbgMarker *LastMarker = Src->createMarker(Last);
883ac9a064cSDimitry Andric   LastMarker->absorbDebugValues(*MoreDanglingDbgRecords, true);
884ac9a064cSDimitry Andric   MoreDanglingDbgRecords->eraseFromParent();
885b1c73532SDimitry Andric }
886b1c73532SDimitry Andric 
spliceDebugInfoImpl(BasicBlock::iterator Dest,BasicBlock * Src,BasicBlock::iterator First,BasicBlock::iterator Last)887b1c73532SDimitry Andric void BasicBlock::spliceDebugInfoImpl(BasicBlock::iterator Dest, BasicBlock *Src,
888b1c73532SDimitry Andric                                      BasicBlock::iterator First,
889b1c73532SDimitry Andric                                      BasicBlock::iterator Last) {
890b1c73532SDimitry Andric   // Find out where to _place_ these dbg.values; if InsertAtHead is specified,
891b1c73532SDimitry Andric   // this will be at the start of Dest's debug value range, otherwise this is
892b1c73532SDimitry Andric   // just Dest's marker.
893b1c73532SDimitry Andric   bool InsertAtHead = Dest.getHeadBit();
894b1c73532SDimitry Andric   bool ReadFromHead = First.getHeadBit();
895b1c73532SDimitry Andric   // Use this flag to signal the abnormal case, where we don't want to copy the
896ac9a064cSDimitry Andric   // DbgRecords ahead of the "Last" position.
897b1c73532SDimitry Andric   bool ReadFromTail = !Last.getTailBit();
898b1c73532SDimitry Andric   bool LastIsEnd = (Last == Src->end());
899b1c73532SDimitry Andric 
900b1c73532SDimitry Andric   /*
901b1c73532SDimitry Andric     Here's an illustration of what we're about to do. We have two blocks, this
902b1c73532SDimitry Andric     and Src, and two segments of list. Each instruction is marked by a capital
903ac9a064cSDimitry Andric     while potential DbgRecord debug-info is marked out by "-" characters and a
904ac9a064cSDimitry Andric     few other special characters (+:=) where I want to highlight what's going
905ac9a064cSDimitry Andric     on.
906b1c73532SDimitry Andric 
907b1c73532SDimitry Andric                                                  Dest
908b1c73532SDimitry Andric                                                    |
909b1c73532SDimitry Andric      this-block:    A----A----A                ====A----A----A----A---A---A
910b1c73532SDimitry Andric       Src-block                ++++B---B---B---B:::C
911b1c73532SDimitry Andric                                    |               |
912b1c73532SDimitry Andric                                   First           Last
913b1c73532SDimitry Andric 
914b1c73532SDimitry Andric     The splice method is going to take all the instructions from First up to
915b1c73532SDimitry Andric     (but not including) Last and insert them in _front_ of Dest, forming one
916ac9a064cSDimitry Andric     long list. All the DbgRecords attached to instructions _between_ First and
917b1c73532SDimitry Andric     Last need no maintenence. However, we have to do special things with the
918ac9a064cSDimitry Andric     DbgRecords marked with the +:= characters. We only have three positions:
919ac9a064cSDimitry Andric     should the "+" DbgRecords be transferred, and if so to where? Do we move the
920ac9a064cSDimitry Andric     ":" DbgRecords? Would they go in front of the "=" DbgRecords, or should the
921ac9a064cSDimitry Andric     "=" DbgRecords go before "+" DbgRecords?
922b1c73532SDimitry Andric 
923b1c73532SDimitry Andric     We're told which way it should be by the bits carried in the iterators. The
924b1c73532SDimitry Andric     "Head" bit indicates whether the specified position is supposed to be at the
925ac9a064cSDimitry Andric     front of the attached DbgRecords (true) or not (false). The Tail bit is true
926ac9a064cSDimitry Andric     on the other end of a range: is the range intended to include DbgRecords up
927ac9a064cSDimitry Andric     to the end (false) or not (true).
928b1c73532SDimitry Andric 
929b1c73532SDimitry Andric     FIXME: the tail bit doesn't need to be distinct from the head bit, we could
930b1c73532SDimitry Andric     combine them.
931b1c73532SDimitry Andric 
932b1c73532SDimitry Andric     Here are some examples of different configurations:
933b1c73532SDimitry Andric 
934b1c73532SDimitry Andric       Dest.Head = true, First.Head = true, Last.Tail = false
935b1c73532SDimitry Andric 
936b1c73532SDimitry Andric       this-block:    A----A----A++++B---B---B---B:::====A----A----A----A---A---A
937b1c73532SDimitry Andric                                     |                   |
938b1c73532SDimitry Andric                                   First                Dest
939b1c73532SDimitry Andric 
940b1c73532SDimitry Andric     Wheras if we didn't want to read from the Src list,
941b1c73532SDimitry Andric 
942b1c73532SDimitry Andric       Dest.Head = true, First.Head = false, Last.Tail = false
943b1c73532SDimitry Andric 
944b1c73532SDimitry Andric       this-block:    A----A----AB---B---B---B:::====A----A----A----A---A---A
945b1c73532SDimitry Andric                                 |                   |
946b1c73532SDimitry Andric                               First                Dest
947b1c73532SDimitry Andric 
948b1c73532SDimitry Andric     Or if we didn't want to insert at the head of Dest:
949b1c73532SDimitry Andric 
950b1c73532SDimitry Andric       Dest.Head = false, First.Head = false, Last.Tail = false
951b1c73532SDimitry Andric 
952b1c73532SDimitry Andric       this-block:    A----A----A====B---B---B---B:::A----A----A----A---A---A
953b1c73532SDimitry Andric                                     |               |
954b1c73532SDimitry Andric                                   First            Dest
955b1c73532SDimitry Andric 
956b1c73532SDimitry Andric     Tests for these various configurations can be found in the unit test file
957b1c73532SDimitry Andric     BasicBlockDbgInfoTest.cpp.
958b1c73532SDimitry Andric 
959b1c73532SDimitry Andric    */
960b1c73532SDimitry Andric 
961ac9a064cSDimitry Andric   // Detach the marker at Dest -- this lets us move the "====" DbgRecords
962ac9a064cSDimitry Andric   // around.
963ac9a064cSDimitry Andric   DbgMarker *DestMarker = nullptr;
9647432c960SDimitry Andric   if ((DestMarker = getMarker(Dest))) {
9657432c960SDimitry Andric     if (Dest == end()) {
9667432c960SDimitry Andric       assert(DestMarker == getTrailingDbgRecords());
9677432c960SDimitry Andric       deleteTrailingDbgRecords();
9687432c960SDimitry Andric     } else {
969b1c73532SDimitry Andric       DestMarker->removeFromParent();
970b1c73532SDimitry Andric     }
9717432c960SDimitry Andric   }
972b1c73532SDimitry Andric 
973ac9a064cSDimitry Andric   // If we're moving the tail range of DbgRecords (":::"), absorb them into the
974ac9a064cSDimitry Andric   // front of the DbgRecords at Dest.
975b1c73532SDimitry Andric   if (ReadFromTail && Src->getMarker(Last)) {
976ac9a064cSDimitry Andric     DbgMarker *FromLast = Src->getMarker(Last);
977b1c73532SDimitry Andric     if (LastIsEnd) {
9781de139fdSDimitry Andric       if (Dest == end()) {
9791de139fdSDimitry Andric         // Abosrb the trailing markers from Src.
9801de139fdSDimitry Andric         assert(FromLast == Src->getTrailingDbgRecords());
9811de139fdSDimitry Andric         createMarker(Dest)->absorbDebugValues(*FromLast, true);
9821de139fdSDimitry Andric         FromLast->eraseFromParent();
9831de139fdSDimitry Andric         Src->deleteTrailingDbgRecords();
9841de139fdSDimitry Andric       } else {
985ac9a064cSDimitry Andric         // adoptDbgRecords will release any trailers.
9861de139fdSDimitry Andric         Dest->adoptDbgRecords(Src, Last, true);
9871de139fdSDimitry Andric       }
988ac9a064cSDimitry Andric       assert(!Src->getTrailingDbgRecords());
989ac9a064cSDimitry Andric     } else {
990ac9a064cSDimitry Andric       // FIXME: can we use adoptDbgRecords here to reduce allocations?
991ac9a064cSDimitry Andric       DbgMarker *OntoDest = createMarker(Dest);
992ac9a064cSDimitry Andric       OntoDest->absorbDebugValues(*FromLast, true);
993b1c73532SDimitry Andric     }
994b1c73532SDimitry Andric   }
995b1c73532SDimitry Andric 
996ac9a064cSDimitry Andric   // If we're _not_ reading from the head of First, i.e. the "++++" DbgRecords,
997b1c73532SDimitry Andric   // move their markers onto Last. They remain in the Src block. No action
998b1c73532SDimitry Andric   // needed.
999ac9a064cSDimitry Andric   if (!ReadFromHead && First->hasDbgRecords()) {
1000ac9a064cSDimitry Andric     if (Last != Src->end()) {
1001ac9a064cSDimitry Andric       Last->adoptDbgRecords(Src, First, true);
1002ac9a064cSDimitry Andric     } else {
1003ac9a064cSDimitry Andric       DbgMarker *OntoLast = Src->createMarker(Last);
1004ac9a064cSDimitry Andric       DbgMarker *FromFirst = Src->createMarker(First);
1005ac9a064cSDimitry Andric       // Always insert at front of Last.
1006ac9a064cSDimitry Andric       OntoLast->absorbDebugValues(*FromFirst, true);
1007ac9a064cSDimitry Andric     }
1008b1c73532SDimitry Andric   }
1009b1c73532SDimitry Andric 
1010ac9a064cSDimitry Andric   // Finally, do something with the "====" DbgRecords we detached.
1011b1c73532SDimitry Andric   if (DestMarker) {
1012b1c73532SDimitry Andric     if (InsertAtHead) {
1013ac9a064cSDimitry Andric       // Insert them at the end of the DbgRecords at Dest. The "::::" DbgRecords
1014b1c73532SDimitry Andric       // might be in front of them.
1015ac9a064cSDimitry Andric       DbgMarker *NewDestMarker = createMarker(Dest);
1016b1c73532SDimitry Andric       NewDestMarker->absorbDebugValues(*DestMarker, false);
1017b1c73532SDimitry Andric     } else {
1018b1c73532SDimitry Andric       // Insert them right at the start of the range we moved, ahead of First
1019ac9a064cSDimitry Andric       // and the "++++" DbgRecords.
10207432c960SDimitry Andric       // This also covers the rare circumstance where we insert at end(), and we
10217432c960SDimitry Andric       // did not generate the iterator with begin() / getFirstInsertionPt(),
10227432c960SDimitry Andric       // meaning any trailing debug-info at the end of the block would
10237432c960SDimitry Andric       // "normally" have been pushed in front of "First". We move it there now.
1024ac9a064cSDimitry Andric       DbgMarker *FirstMarker = createMarker(First);
1025b1c73532SDimitry Andric       FirstMarker->absorbDebugValues(*DestMarker, true);
1026b1c73532SDimitry Andric     }
1027b1c73532SDimitry Andric     DestMarker->eraseFromParent();
1028b1c73532SDimitry Andric   }
1029b1c73532SDimitry Andric }
1030b1c73532SDimitry Andric 
splice(iterator Dest,BasicBlock * Src,iterator First,iterator Last)1031b1c73532SDimitry Andric void BasicBlock::splice(iterator Dest, BasicBlock *Src, iterator First,
1032b1c73532SDimitry Andric                         iterator Last) {
1033b1c73532SDimitry Andric   assert(Src->IsNewDbgInfoFormat == IsNewDbgInfoFormat);
1034b1c73532SDimitry Andric 
1035b1c73532SDimitry Andric #ifdef EXPENSIVE_CHECKS
1036b1c73532SDimitry Andric   // Check that First is before Last.
1037b1c73532SDimitry Andric   auto FromBBEnd = Src->end();
1038b1c73532SDimitry Andric   for (auto It = First; It != Last; ++It)
1039b1c73532SDimitry Andric     assert(It != FromBBEnd && "FromBeginIt not before FromEndIt!");
1040b1c73532SDimitry Andric #endif // EXPENSIVE_CHECKS
1041b1c73532SDimitry Andric 
1042b1c73532SDimitry Andric   // Lots of horrible special casing for empty transfers: the dbg.values between
1043b1c73532SDimitry Andric   // two positions could be spliced in dbg.value mode.
1044b1c73532SDimitry Andric   if (First == Last) {
1045b1c73532SDimitry Andric     spliceDebugInfoEmptyBlock(Dest, Src, First, Last);
1046b1c73532SDimitry Andric     return;
1047b1c73532SDimitry Andric   }
1048b1c73532SDimitry Andric 
1049b1c73532SDimitry Andric   // Handle non-instr debug-info specific juggling.
1050b1c73532SDimitry Andric   if (IsNewDbgInfoFormat)
1051b1c73532SDimitry Andric     spliceDebugInfo(Dest, Src, First, Last);
1052b1c73532SDimitry Andric 
1053b1c73532SDimitry Andric   // And move the instructions.
1054b1c73532SDimitry Andric   getInstList().splice(Dest, Src->getInstList(), First, Last);
1055b1c73532SDimitry Andric 
1056ac9a064cSDimitry Andric   flushTerminatorDbgRecords();
1057b1c73532SDimitry Andric }
1058b1c73532SDimitry Andric 
insertDbgRecordAfter(DbgRecord * DR,Instruction * I)1059ac9a064cSDimitry Andric void BasicBlock::insertDbgRecordAfter(DbgRecord *DR, Instruction *I) {
1060b1c73532SDimitry Andric   assert(IsNewDbgInfoFormat);
1061b1c73532SDimitry Andric   assert(I->getParent() == this);
1062b1c73532SDimitry Andric 
1063b1c73532SDimitry Andric   iterator NextIt = std::next(I->getIterator());
1064ac9a064cSDimitry Andric   DbgMarker *NextMarker = createMarker(NextIt);
1065ac9a064cSDimitry Andric   NextMarker->insertDbgRecord(DR, true);
1066b1c73532SDimitry Andric }
1067b1c73532SDimitry Andric 
insertDbgRecordBefore(DbgRecord * DR,InstListType::iterator Where)1068ac9a064cSDimitry Andric void BasicBlock::insertDbgRecordBefore(DbgRecord *DR,
1069b1c73532SDimitry Andric                                        InstListType::iterator Where) {
1070ac9a064cSDimitry Andric   assert(Where == end() || Where->getParent() == this);
1071b1c73532SDimitry Andric   bool InsertAtHead = Where.getHeadBit();
1072ac9a064cSDimitry Andric   DbgMarker *M = createMarker(Where);
1073ac9a064cSDimitry Andric   M->insertDbgRecord(DR, InsertAtHead);
1074b1c73532SDimitry Andric }
1075b1c73532SDimitry Andric 
getNextMarker(Instruction * I)1076ac9a064cSDimitry Andric DbgMarker *BasicBlock::getNextMarker(Instruction *I) {
1077b1c73532SDimitry Andric   return getMarker(std::next(I->getIterator()));
1078b1c73532SDimitry Andric }
1079b1c73532SDimitry Andric 
getMarker(InstListType::iterator It)1080ac9a064cSDimitry Andric DbgMarker *BasicBlock::getMarker(InstListType::iterator It) {
1081b1c73532SDimitry Andric   if (It == end()) {
1082ac9a064cSDimitry Andric     DbgMarker *DM = getTrailingDbgRecords();
1083ac9a064cSDimitry Andric     return DM;
1084b1c73532SDimitry Andric   }
1085ac9a064cSDimitry Andric   return It->DebugMarker;
1086b1c73532SDimitry Andric }
1087b1c73532SDimitry Andric 
reinsertInstInDbgRecords(Instruction * I,std::optional<DbgRecord::self_iterator> Pos)1088ac9a064cSDimitry Andric void BasicBlock::reinsertInstInDbgRecords(
1089ac9a064cSDimitry Andric     Instruction *I, std::optional<DbgRecord::self_iterator> Pos) {
1090b1c73532SDimitry Andric   // "I" was originally removed from a position where it was
1091ac9a064cSDimitry Andric   // immediately in front of Pos. Any DbgRecords on that position then "fell
1092ac9a064cSDimitry Andric   // down" onto Pos. "I" has been re-inserted at the front of that wedge of
1093ac9a064cSDimitry Andric   // DbgRecords, shuffle them around to represent the original positioning. To
1094ac9a064cSDimitry Andric   // illustrate:
1095b1c73532SDimitry Andric   //
1096b1c73532SDimitry Andric   //   Instructions:  I1---I---I0
1097ac9a064cSDimitry Andric   //       DbgRecords:    DDD DDD
1098b1c73532SDimitry Andric   //
1099b1c73532SDimitry Andric   // Instruction "I" removed,
1100b1c73532SDimitry Andric   //
1101b1c73532SDimitry Andric   //   Instructions:  I1------I0
1102ac9a064cSDimitry Andric   //       DbgRecords:    DDDDDD
1103b1c73532SDimitry Andric   //                       ^Pos
1104b1c73532SDimitry Andric   //
1105b1c73532SDimitry Andric   // Instruction "I" re-inserted (now):
1106b1c73532SDimitry Andric   //
1107b1c73532SDimitry Andric   //   Instructions:  I1---I------I0
1108ac9a064cSDimitry Andric   //       DbgRecords:        DDDDDD
1109b1c73532SDimitry Andric   //                           ^Pos
1110b1c73532SDimitry Andric   //
1111b1c73532SDimitry Andric   // After this method completes:
1112b1c73532SDimitry Andric   //
1113b1c73532SDimitry Andric   //   Instructions:  I1---I---I0
1114ac9a064cSDimitry Andric   //       DbgRecords:    DDD DDD
1115b1c73532SDimitry Andric 
1116ac9a064cSDimitry Andric   // This happens if there were no DbgRecords on I0. Are there now DbgRecords
1117ac9a064cSDimitry Andric   // there?
1118b1c73532SDimitry Andric   if (!Pos) {
1119ac9a064cSDimitry Andric     DbgMarker *NextMarker = getNextMarker(I);
1120b1c73532SDimitry Andric     if (!NextMarker)
1121b1c73532SDimitry Andric       return;
1122ac9a064cSDimitry Andric     if (NextMarker->StoredDbgRecords.empty())
1123b1c73532SDimitry Andric       return;
1124ac9a064cSDimitry Andric     // There are DbgMarkers there now -- they fell down from "I".
1125ac9a064cSDimitry Andric     DbgMarker *ThisMarker = createMarker(I);
1126b1c73532SDimitry Andric     ThisMarker->absorbDebugValues(*NextMarker, false);
1127b1c73532SDimitry Andric     return;
1128b1c73532SDimitry Andric   }
1129b1c73532SDimitry Andric 
1130ac9a064cSDimitry Andric   // Is there even a range of DbgRecords to move?
1131ac9a064cSDimitry Andric   DbgMarker *DM = (*Pos)->getMarker();
1132ac9a064cSDimitry Andric   auto Range = make_range(DM->StoredDbgRecords.begin(), (*Pos));
1133b1c73532SDimitry Andric   if (Range.begin() == Range.end())
1134b1c73532SDimitry Andric     return;
1135b1c73532SDimitry Andric 
1136b1c73532SDimitry Andric   // Otherwise: splice.
1137ac9a064cSDimitry Andric   DbgMarker *ThisMarker = createMarker(I);
1138ac9a064cSDimitry Andric   assert(ThisMarker->StoredDbgRecords.empty());
1139ac9a064cSDimitry Andric   ThisMarker->absorbDebugValues(Range, *DM, true);
1140b1c73532SDimitry Andric }
1141b1c73532SDimitry Andric 
1142cfca06d7SDimitry Andric #ifndef NDEBUG
1143cfca06d7SDimitry Andric /// In asserts builds, this checks the numbering. In non-asserts builds, it
1144cfca06d7SDimitry Andric /// is defined as a no-op inline function in BasicBlock.h.
validateInstrOrdering() const1145cfca06d7SDimitry Andric void BasicBlock::validateInstrOrdering() const {
1146cfca06d7SDimitry Andric   if (!isInstrOrderValid())
1147cfca06d7SDimitry Andric     return;
1148cfca06d7SDimitry Andric   const Instruction *Prev = nullptr;
1149cfca06d7SDimitry Andric   for (const Instruction &I : *this) {
1150cfca06d7SDimitry Andric     assert((!Prev || Prev->comesBefore(&I)) &&
1151cfca06d7SDimitry Andric            "cached instruction ordering is incorrect");
1152cfca06d7SDimitry Andric     Prev = &I;
1153cfca06d7SDimitry Andric   }
1154cfca06d7SDimitry Andric }
1155cfca06d7SDimitry Andric #endif
1156b1c73532SDimitry Andric 
setTrailingDbgRecords(DbgMarker * foo)1157ac9a064cSDimitry Andric void BasicBlock::setTrailingDbgRecords(DbgMarker *foo) {
1158ac9a064cSDimitry Andric   getContext().pImpl->setTrailingDbgRecords(this, foo);
1159b1c73532SDimitry Andric }
1160b1c73532SDimitry Andric 
getTrailingDbgRecords()1161ac9a064cSDimitry Andric DbgMarker *BasicBlock::getTrailingDbgRecords() {
1162ac9a064cSDimitry Andric   return getContext().pImpl->getTrailingDbgRecords(this);
1163b1c73532SDimitry Andric }
1164b1c73532SDimitry Andric 
deleteTrailingDbgRecords()1165ac9a064cSDimitry Andric void BasicBlock::deleteTrailingDbgRecords() {
1166ac9a064cSDimitry Andric   getContext().pImpl->deleteTrailingDbgRecords(this);
1167b1c73532SDimitry Andric }
1168