1009b1c42SEd Schouten //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
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 //
9009b1c42SEd Schouten // Collect the sequence of machine instructions for a basic block.
10009b1c42SEd Schouten //
11009b1c42SEd Schouten //===----------------------------------------------------------------------===//
12009b1c42SEd Schouten
13009b1c42SEd Schouten #include "llvm/CodeGen/MachineBasicBlock.h"
14e3b55780SDimitry Andric #include "llvm/ADT/STLExtras.h"
157fa27ce4SDimitry Andric #include "llvm/ADT/StringExtras.h"
16044eb2f6SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
17145449b1SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
1866e41e3cSRoman Divacky #include "llvm/CodeGen/LiveVariables.h"
1966e41e3cSRoman Divacky #include "llvm/CodeGen/MachineDominators.h"
20009b1c42SEd Schouten #include "llvm/CodeGen/MachineFunction.h"
21f8af5cf6SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
227fa27ce4SDimitry Andric #include "llvm/CodeGen/MachineJumpTableInfo.h"
2366e41e3cSRoman Divacky #include "llvm/CodeGen/MachineLoopInfo.h"
244a16efa3SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
25cf099d11SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
26044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
27344a3780SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
28044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
29044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
30eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
314a16efa3SDimitry Andric #include "llvm/IR/BasicBlock.h"
3271d5a254SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
331a82d4c0SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
346fe5c7aaSRoman Divacky #include "llvm/MC/MCAsmInfo.h"
356fe5c7aaSRoman Divacky #include "llvm/MC/MCContext.h"
36829000e0SRoman Divacky #include "llvm/Support/Debug.h"
3759850d08SRoman Divacky #include "llvm/Support/raw_ostream.h"
384a16efa3SDimitry Andric #include "llvm/Target/TargetMachine.h"
39009b1c42SEd Schouten #include <algorithm>
40e3b55780SDimitry Andric #include <cmath>
41009b1c42SEd Schouten using namespace llvm;
42009b1c42SEd Schouten
435ca98fd9SDimitry Andric #define DEBUG_TYPE "codegen"
445ca98fd9SDimitry Andric
451d5ae102SDimitry Andric static cl::opt<bool> PrintSlotIndexes(
461d5ae102SDimitry Andric "print-slotindexes",
471d5ae102SDimitry Andric cl::desc("When printing machine IR, annotate instructions and blocks with "
481d5ae102SDimitry Andric "SlotIndexes when available"),
491d5ae102SDimitry Andric cl::init(true), cl::Hidden);
501d5ae102SDimitry Andric
MachineBasicBlock(MachineFunction & MF,const BasicBlock * B)51dd58ef01SDimitry Andric MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
52dd58ef01SDimitry Andric : BB(B), Number(-1), xParent(&MF) {
53009b1c42SEd Schouten Insts.Parent = this;
54044eb2f6SDimitry Andric if (B)
55044eb2f6SDimitry Andric IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight();
56009b1c42SEd Schouten }
57009b1c42SEd Schouten
58145449b1SDimitry Andric MachineBasicBlock::~MachineBasicBlock() = default;
59009b1c42SEd Schouten
60dd58ef01SDimitry Andric /// Return the MCSymbol for this basic block.
getSymbol() const61c6910277SRoman Divacky MCSymbol *MachineBasicBlock::getSymbol() const {
6259d6cff9SDimitry Andric if (!CachedMCSymbol) {
636fe5c7aaSRoman Divacky const MachineFunction *MF = getParent();
64c6910277SRoman Divacky MCContext &Ctx = MF->getContext();
65cfca06d7SDimitry Andric
66b60736ecSDimitry Andric // We emit a non-temporary symbol -- with a descriptive name -- if it begins
67b60736ecSDimitry Andric // a section (with basic block sections). Otherwise we fall back to use temp
68b60736ecSDimitry Andric // label.
69b60736ecSDimitry Andric if (MF->hasBBSections() && isBeginSection()) {
70cfca06d7SDimitry Andric SmallString<5> Suffix;
71cfca06d7SDimitry Andric if (SectionID == MBBSectionID::ColdSectionID) {
72cfca06d7SDimitry Andric Suffix += ".cold";
73cfca06d7SDimitry Andric } else if (SectionID == MBBSectionID::ExceptionSectionID) {
74cfca06d7SDimitry Andric Suffix += ".eh";
75cfca06d7SDimitry Andric } else {
76b60736ecSDimitry Andric // For symbols that represent basic block sections, we add ".__part." to
77b60736ecSDimitry Andric // allow tools like symbolizers to know that this represents a part of
78b60736ecSDimitry Andric // the original function.
79b60736ecSDimitry Andric Suffix = (Suffix + Twine(".__part.") + Twine(SectionID.Number)).str();
80cfca06d7SDimitry Andric }
81cfca06d7SDimitry Andric CachedMCSymbol = Ctx.getOrCreateSymbol(MF->getName() + Suffix);
82cfca06d7SDimitry Andric } else {
83ac9a064cSDimitry Andric // If the block occurs as label in inline assembly, parsing the assembly
84ac9a064cSDimitry Andric // needs an actual label name => set AlwaysEmit in these cases.
85ac9a064cSDimitry Andric CachedMCSymbol = Ctx.createBlockSymbol(
86ac9a064cSDimitry Andric "BB" + Twine(MF->getFunctionNumber()) + "_" + Twine(getNumber()),
87ac9a064cSDimitry Andric /*AlwaysEmit=*/hasLabelMustBeEmitted());
8859d6cff9SDimitry Andric }
89cfca06d7SDimitry Andric }
9059d6cff9SDimitry Andric return CachedMCSymbol;
916fe5c7aaSRoman Divacky }
926fe5c7aaSRoman Divacky
getEHCatchretSymbol() const93344a3780SDimitry Andric MCSymbol *MachineBasicBlock::getEHCatchretSymbol() const {
94344a3780SDimitry Andric if (!CachedEHCatchretMCSymbol) {
95344a3780SDimitry Andric const MachineFunction *MF = getParent();
96344a3780SDimitry Andric SmallString<128> SymbolName;
97344a3780SDimitry Andric raw_svector_ostream(SymbolName)
98344a3780SDimitry Andric << "$ehgcr_" << MF->getFunctionNumber() << '_' << getNumber();
99344a3780SDimitry Andric CachedEHCatchretMCSymbol = MF->getContext().getOrCreateSymbol(SymbolName);
100344a3780SDimitry Andric }
101344a3780SDimitry Andric return CachedEHCatchretMCSymbol;
102344a3780SDimitry Andric }
103344a3780SDimitry Andric
getEndSymbol() const104b60736ecSDimitry Andric MCSymbol *MachineBasicBlock::getEndSymbol() const {
105b60736ecSDimitry Andric if (!CachedEndMCSymbol) {
106b60736ecSDimitry Andric const MachineFunction *MF = getParent();
107b60736ecSDimitry Andric MCContext &Ctx = MF->getContext();
108ac9a064cSDimitry Andric CachedEndMCSymbol = Ctx.createBlockSymbol(
109ac9a064cSDimitry Andric "BB_END" + Twine(MF->getFunctionNumber()) + "_" + Twine(getNumber()),
110ac9a064cSDimitry Andric /*AlwaysEmit=*/false);
111b60736ecSDimitry Andric }
112b60736ecSDimitry Andric return CachedEndMCSymbol;
113b60736ecSDimitry Andric }
1146fe5c7aaSRoman Divacky
operator <<(raw_ostream & OS,const MachineBasicBlock & MBB)11559850d08SRoman Divacky raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
116009b1c42SEd Schouten MBB.print(OS);
117009b1c42SEd Schouten return OS;
118009b1c42SEd Schouten }
119009b1c42SEd Schouten
printMBBReference(const MachineBasicBlock & MBB)120044eb2f6SDimitry Andric Printable llvm::printMBBReference(const MachineBasicBlock &MBB) {
121044eb2f6SDimitry Andric return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
122044eb2f6SDimitry Andric }
123044eb2f6SDimitry Andric
124dd58ef01SDimitry Andric /// When an MBB is added to an MF, we need to update the parent pointer of the
125dd58ef01SDimitry Andric /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
126dd58ef01SDimitry Andric /// operand list for registers.
127009b1c42SEd Schouten ///
128009b1c42SEd Schouten /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
129009b1c42SEd Schouten /// gets the next available unique MBB number. If it is removed from a
130009b1c42SEd Schouten /// MachineFunction, it goes back to being #-1.
addNodeToList(MachineBasicBlock * N)131b915e9e0SDimitry Andric void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
132b915e9e0SDimitry Andric MachineBasicBlock *N) {
133009b1c42SEd Schouten MachineFunction &MF = *N->getParent();
134009b1c42SEd Schouten N->Number = MF.addToMBBNumbering(N);
135009b1c42SEd Schouten
136009b1c42SEd Schouten // Make sure the instructions have their operands in the reginfo lists.
137009b1c42SEd Schouten MachineRegisterInfo &RegInfo = MF.getRegInfo();
138c0981da4SDimitry Andric for (MachineInstr &MI : N->instrs())
139145449b1SDimitry Andric MI.addRegOperandsToUseLists(RegInfo);
140009b1c42SEd Schouten }
141009b1c42SEd Schouten
removeNodeFromList(MachineBasicBlock * N)142b915e9e0SDimitry Andric void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
143b915e9e0SDimitry Andric MachineBasicBlock *N) {
144009b1c42SEd Schouten N->getParent()->removeFromMBBNumbering(N->Number);
145009b1c42SEd Schouten N->Number = -1;
146009b1c42SEd Schouten }
147009b1c42SEd Schouten
148dd58ef01SDimitry Andric /// When we add an instruction to a basic block list, we update its parent
149dd58ef01SDimitry Andric /// pointer and add its operands from reg use/def lists if appropriate.
addNodeToList(MachineInstr * N)150009b1c42SEd Schouten void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
1515ca98fd9SDimitry Andric assert(!N->getParent() && "machine instruction already in a basic block");
152009b1c42SEd Schouten N->setParent(Parent);
153009b1c42SEd Schouten
154009b1c42SEd Schouten // Add the instruction's register operands to their corresponding
155009b1c42SEd Schouten // use/def lists.
156009b1c42SEd Schouten MachineFunction *MF = Parent->getParent();
157145449b1SDimitry Andric N->addRegOperandsToUseLists(MF->getRegInfo());
158d8e91e46SDimitry Andric MF->handleInsertion(*N);
159009b1c42SEd Schouten }
160009b1c42SEd Schouten
161dd58ef01SDimitry Andric /// When we remove an instruction from a basic block list, we update its parent
162dd58ef01SDimitry Andric /// pointer and remove its operands from reg use/def lists if appropriate.
removeNodeFromList(MachineInstr * N)163009b1c42SEd Schouten void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
1645ca98fd9SDimitry Andric assert(N->getParent() && "machine instruction not in a basic block");
165009b1c42SEd Schouten
166009b1c42SEd Schouten // Remove from the use/def lists.
167d8e91e46SDimitry Andric if (MachineFunction *MF = N->getMF()) {
168d8e91e46SDimitry Andric MF->handleRemoval(*N);
169145449b1SDimitry Andric N->removeRegOperandsFromUseLists(MF->getRegInfo());
170d8e91e46SDimitry Andric }
171009b1c42SEd Schouten
1725ca98fd9SDimitry Andric N->setParent(nullptr);
173009b1c42SEd Schouten }
174009b1c42SEd Schouten
175dd58ef01SDimitry Andric /// When moving a range of instructions from one MBB list to another, we need to
176dd58ef01SDimitry Andric /// update the parent pointers and the use/def lists.
transferNodesFromList(ilist_traits & FromList,instr_iterator First,instr_iterator Last)177b915e9e0SDimitry Andric void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
178b915e9e0SDimitry Andric instr_iterator First,
179b915e9e0SDimitry Andric instr_iterator Last) {
180dd58ef01SDimitry Andric assert(Parent->getParent() == FromList.Parent->getParent() &&
181e6d15924SDimitry Andric "cannot transfer MachineInstrs between MachineFunctions");
182e6d15924SDimitry Andric
183e6d15924SDimitry Andric // If it's within the same BB, there's nothing to do.
184e6d15924SDimitry Andric if (this == &FromList)
185e6d15924SDimitry Andric return;
186e6d15924SDimitry Andric
187b915e9e0SDimitry Andric assert(Parent != FromList.Parent && "Two lists have the same parent?");
188009b1c42SEd Schouten
189009b1c42SEd Schouten // If splicing between two blocks within the same function, just update the
190009b1c42SEd Schouten // parent pointers.
191dd58ef01SDimitry Andric for (; First != Last; ++First)
192dd58ef01SDimitry Andric First->setParent(Parent);
193009b1c42SEd Schouten }
194009b1c42SEd Schouten
deleteNode(MachineInstr * MI)195009b1c42SEd Schouten void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
196009b1c42SEd Schouten assert(!MI->getParent() && "MI is still in a block!");
19777fc4c14SDimitry Andric Parent->getParent()->deleteMachineInstr(MI);
198009b1c42SEd Schouten }
199009b1c42SEd Schouten
getFirstNonPHI()20066e41e3cSRoman Divacky MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
20163faed5bSDimitry Andric instr_iterator I = instr_begin(), E = instr_end();
20263faed5bSDimitry Andric while (I != E && I->isPHI())
20366e41e3cSRoman Divacky ++I;
204522600a2SDimitry Andric assert((I == E || !I->isInsideBundle()) &&
205522600a2SDimitry Andric "First non-phi MI cannot be inside a bundle!");
20666e41e3cSRoman Divacky return I;
20766e41e3cSRoman Divacky }
20866e41e3cSRoman Divacky
209cf099d11SDimitry Andric MachineBasicBlock::iterator
SkipPHIsAndLabels(MachineBasicBlock::iterator I)210cf099d11SDimitry Andric MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
21171d5a254SDimitry Andric const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
21271d5a254SDimitry Andric
21363faed5bSDimitry Andric iterator E = end();
21471d5a254SDimitry Andric while (I != E && (I->isPHI() || I->isPosition() ||
21571d5a254SDimitry Andric TII->isBasicBlockPrologue(*I)))
216b915e9e0SDimitry Andric ++I;
217b915e9e0SDimitry Andric // FIXME: This needs to change if we wish to bundle labels
218b915e9e0SDimitry Andric // inside the bundle.
219b915e9e0SDimitry Andric assert((I == E || !I->isInsideBundle()) &&
220b915e9e0SDimitry Andric "First non-phi / non-label instruction is inside a bundle!");
221b915e9e0SDimitry Andric return I;
222b915e9e0SDimitry Andric }
223b915e9e0SDimitry Andric
224b915e9e0SDimitry Andric MachineBasicBlock::iterator
SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I,Register Reg,bool SkipPseudoOp)225344a3780SDimitry Andric MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I,
226b1c73532SDimitry Andric Register Reg, bool SkipPseudoOp) {
22771d5a254SDimitry Andric const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
22871d5a254SDimitry Andric
229b915e9e0SDimitry Andric iterator E = end();
230eb11fae6SDimitry Andric while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() ||
231344a3780SDimitry Andric (SkipPseudoOp && I->isPseudoProbe()) ||
232b1c73532SDimitry Andric TII->isBasicBlockPrologue(*I, Reg)))
233cf099d11SDimitry Andric ++I;
23463faed5bSDimitry Andric // FIXME: This needs to change if we wish to bundle labels / dbg_values
23563faed5bSDimitry Andric // inside the bundle.
236522600a2SDimitry Andric assert((I == E || !I->isInsideBundle()) &&
237b915e9e0SDimitry Andric "First non-phi / non-label / non-debug "
238b915e9e0SDimitry Andric "instruction is inside a bundle!");
239cf099d11SDimitry Andric return I;
240cf099d11SDimitry Andric }
241cf099d11SDimitry Andric
getFirstTerminator()242009b1c42SEd Schouten MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
24363faed5bSDimitry Andric iterator B = begin(), E = end(), I = E;
244eb11fae6SDimitry Andric while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
245009b1c42SEd Schouten ; /*noop */
24663faed5bSDimitry Andric while (I != E && !I->isTerminator())
24763faed5bSDimitry Andric ++I;
24863faed5bSDimitry Andric return I;
24963faed5bSDimitry Andric }
25063faed5bSDimitry Andric
getFirstInstrTerminator()25163faed5bSDimitry Andric MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
25263faed5bSDimitry Andric instr_iterator B = instr_begin(), E = instr_end(), I = E;
253eb11fae6SDimitry Andric while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
25463faed5bSDimitry Andric ; /*noop */
25563faed5bSDimitry Andric while (I != E && !I->isTerminator())
256cf099d11SDimitry Andric ++I;
257009b1c42SEd Schouten return I;
258009b1c42SEd Schouten }
259009b1c42SEd Schouten
getFirstTerminatorForward()260e3b55780SDimitry Andric MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminatorForward() {
261e3b55780SDimitry Andric return find_if(instrs(), [](auto &II) { return II.isTerminator(); });
262e3b55780SDimitry Andric }
263e3b55780SDimitry Andric
264344a3780SDimitry Andric MachineBasicBlock::iterator
getFirstNonDebugInstr(bool SkipPseudoOp)265344a3780SDimitry Andric MachineBasicBlock::getFirstNonDebugInstr(bool SkipPseudoOp) {
2661a82d4c0SDimitry Andric // Skip over begin-of-block dbg_value instructions.
267344a3780SDimitry Andric return skipDebugInstructionsForward(begin(), end(), SkipPseudoOp);
2681a82d4c0SDimitry Andric }
2691a82d4c0SDimitry Andric
270344a3780SDimitry Andric MachineBasicBlock::iterator
getLastNonDebugInstr(bool SkipPseudoOp)271344a3780SDimitry Andric MachineBasicBlock::getLastNonDebugInstr(bool SkipPseudoOp) {
27263faed5bSDimitry Andric // Skip over end-of-block dbg_value instructions.
27363faed5bSDimitry Andric instr_iterator B = instr_begin(), I = instr_end();
274cf099d11SDimitry Andric while (I != B) {
275cf099d11SDimitry Andric --I;
27663faed5bSDimitry Andric // Return instruction that starts a bundle.
277eb11fae6SDimitry Andric if (I->isDebugInstr() || I->isInsideBundle())
27863faed5bSDimitry Andric continue;
279344a3780SDimitry Andric if (SkipPseudoOp && I->isPseudoProbe())
280344a3780SDimitry Andric continue;
28163faed5bSDimitry Andric return I;
28263faed5bSDimitry Andric }
28363faed5bSDimitry Andric // The block is all debug values.
28463faed5bSDimitry Andric return end();
28563faed5bSDimitry Andric }
28663faed5bSDimitry Andric
hasEHPadSuccessor() const287dd58ef01SDimitry Andric bool MachineBasicBlock::hasEHPadSuccessor() const {
288c0981da4SDimitry Andric for (const MachineBasicBlock *Succ : successors())
289c0981da4SDimitry Andric if (Succ->isEHPad())
290dd58ef01SDimitry Andric return true;
291dd58ef01SDimitry Andric return false;
292dd58ef01SDimitry Andric }
293dd58ef01SDimitry Andric
isEntryBlock() const294b60736ecSDimitry Andric bool MachineBasicBlock::isEntryBlock() const {
295b60736ecSDimitry Andric return getParent()->begin() == getIterator();
296b60736ecSDimitry Andric }
297b60736ecSDimitry Andric
298522600a2SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const29901095a5dSDimitry Andric LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
300829000e0SRoman Divacky print(dbgs());
301009b1c42SEd Schouten }
302522600a2SDimitry Andric #endif
303009b1c42SEd Schouten
mayHaveInlineAsmBr() const304cfca06d7SDimitry Andric bool MachineBasicBlock::mayHaveInlineAsmBr() const {
305cfca06d7SDimitry Andric for (const MachineBasicBlock *Succ : successors()) {
306cfca06d7SDimitry Andric if (Succ->isInlineAsmBrIndirectTarget())
307cfca06d7SDimitry Andric return true;
308cfca06d7SDimitry Andric }
309cfca06d7SDimitry Andric return false;
310cfca06d7SDimitry Andric }
311cfca06d7SDimitry Andric
isLegalToHoistInto() const31208bbd35aSDimitry Andric bool MachineBasicBlock::isLegalToHoistInto() const {
313cfca06d7SDimitry Andric if (isReturnBlock() || hasEHPadSuccessor() || mayHaveInlineAsmBr())
31408bbd35aSDimitry Andric return false;
31508bbd35aSDimitry Andric return true;
31608bbd35aSDimitry Andric }
31708bbd35aSDimitry Andric
hasName() const318ac9a064cSDimitry Andric bool MachineBasicBlock::hasName() const {
319ac9a064cSDimitry Andric if (const BasicBlock *LBB = getBasicBlock())
320ac9a064cSDimitry Andric return LBB->hasName();
321ac9a064cSDimitry Andric return false;
322ac9a064cSDimitry Andric }
323ac9a064cSDimitry Andric
getName() const32406f9d401SRoman Divacky StringRef MachineBasicBlock::getName() const {
32506f9d401SRoman Divacky if (const BasicBlock *LBB = getBasicBlock())
32606f9d401SRoman Divacky return LBB->getName();
32706f9d401SRoman Divacky else
32871d5a254SDimitry Andric return StringRef("", 0);
32906f9d401SRoman Divacky }
33006f9d401SRoman Divacky
33163faed5bSDimitry Andric /// Return a hopefully unique identifier for this block.
getFullName() const33263faed5bSDimitry Andric std::string MachineBasicBlock::getFullName() const {
33363faed5bSDimitry Andric std::string Name;
33463faed5bSDimitry Andric if (getParent())
335522600a2SDimitry Andric Name = (getParent()->getName() + ":").str();
33663faed5bSDimitry Andric if (getBasicBlock())
33763faed5bSDimitry Andric Name += getBasicBlock()->getName();
33863faed5bSDimitry Andric else
3395a5ac124SDimitry Andric Name += ("BB" + Twine(getNumber())).str();
34063faed5bSDimitry Andric return Name;
34163faed5bSDimitry Andric }
34263faed5bSDimitry Andric
print(raw_ostream & OS,const SlotIndexes * Indexes,bool IsStandalone) const343eb11fae6SDimitry Andric void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes,
344eb11fae6SDimitry Andric bool IsStandalone) const {
345009b1c42SEd Schouten const MachineFunction *MF = getParent();
346009b1c42SEd Schouten if (!MF) {
347009b1c42SEd Schouten OS << "Can't print out MachineBasicBlock because parent MachineFunction"
348009b1c42SEd Schouten << " is null\n";
349009b1c42SEd Schouten return;
350009b1c42SEd Schouten }
351044eb2f6SDimitry Andric const Function &F = MF->getFunction();
352044eb2f6SDimitry Andric const Module *M = F.getParent();
3531a82d4c0SDimitry Andric ModuleSlotTracker MST(M);
354eb11fae6SDimitry Andric MST.incorporateFunction(F);
355eb11fae6SDimitry Andric print(OS, MST, Indexes, IsStandalone);
3561a82d4c0SDimitry Andric }
3571a82d4c0SDimitry Andric
print(raw_ostream & OS,ModuleSlotTracker & MST,const SlotIndexes * Indexes,bool IsStandalone) const3581a82d4c0SDimitry Andric void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
359eb11fae6SDimitry Andric const SlotIndexes *Indexes,
360eb11fae6SDimitry Andric bool IsStandalone) const {
3611a82d4c0SDimitry Andric const MachineFunction *MF = getParent();
3621a82d4c0SDimitry Andric if (!MF) {
3631a82d4c0SDimitry Andric OS << "Can't print out MachineBasicBlock because parent MachineFunction"
3641a82d4c0SDimitry Andric << " is null\n";
3651a82d4c0SDimitry Andric return;
3661a82d4c0SDimitry Andric }
367009b1c42SEd Schouten
3681d5ae102SDimitry Andric if (Indexes && PrintSlotIndexes)
369cf099d11SDimitry Andric OS << Indexes->getMBBStartIdx(this) << '\t';
370cf099d11SDimitry Andric
371b60736ecSDimitry Andric printName(OS, PrintNameIr | PrintNameAttributes, &MST);
372eb11fae6SDimitry Andric OS << ":\n";
373009b1c42SEd Schouten
37467c32a98SDimitry Andric const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
375eb11fae6SDimitry Andric const MachineRegisterInfo &MRI = MF->getRegInfo();
376eb11fae6SDimitry Andric const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
377eb11fae6SDimitry Andric bool HasLineAttributes = false;
378eb11fae6SDimitry Andric
379009b1c42SEd Schouten // Print the preds of this block according to the CFG.
380eb11fae6SDimitry Andric if (!pred_empty() && IsStandalone) {
381cf099d11SDimitry Andric if (Indexes) OS << '\t';
382eb11fae6SDimitry Andric // Don't indent(2), align with previous line attributes.
383eb11fae6SDimitry Andric OS << "; predecessors: ";
384b60736ecSDimitry Andric ListSeparator LS;
385b60736ecSDimitry Andric for (auto *Pred : predecessors())
386b60736ecSDimitry Andric OS << LS << printMBBReference(*Pred);
38759850d08SRoman Divacky OS << '\n';
388eb11fae6SDimitry Andric HasLineAttributes = true;
389009b1c42SEd Schouten }
390009b1c42SEd Schouten
391009b1c42SEd Schouten if (!succ_empty()) {
392cf099d11SDimitry Andric if (Indexes) OS << '\t';
393eb11fae6SDimitry Andric // Print the successors
394eb11fae6SDimitry Andric OS.indent(2) << "successors: ";
395b60736ecSDimitry Andric ListSeparator LS;
396eb11fae6SDimitry Andric for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
397b60736ecSDimitry Andric OS << LS << printMBBReference(**I);
398dd58ef01SDimitry Andric if (!Probs.empty())
399eb11fae6SDimitry Andric OS << '('
400eb11fae6SDimitry Andric << format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
401eb11fae6SDimitry Andric << ')';
40258b69754SDimitry Andric }
403eb11fae6SDimitry Andric if (!Probs.empty() && IsStandalone) {
404eb11fae6SDimitry Andric // Print human readable probabilities as comments.
405eb11fae6SDimitry Andric OS << "; ";
406b60736ecSDimitry Andric ListSeparator LS;
407eb11fae6SDimitry Andric for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
408d8e91e46SDimitry Andric const BranchProbability &BP = getSuccProbability(I);
409b60736ecSDimitry Andric OS << LS << printMBBReference(**I) << '('
410eb11fae6SDimitry Andric << format("%.2f%%",
411eb11fae6SDimitry Andric rint(((double)BP.getNumerator() / BP.getDenominator()) *
412eb11fae6SDimitry Andric 100.0 * 100.0) /
413eb11fae6SDimitry Andric 100.0)
414eb11fae6SDimitry Andric << ')';
415eb11fae6SDimitry Andric }
416eb11fae6SDimitry Andric }
417eb11fae6SDimitry Andric
41859850d08SRoman Divacky OS << '\n';
419eb11fae6SDimitry Andric HasLineAttributes = true;
420009b1c42SEd Schouten }
421eb11fae6SDimitry Andric
422eb11fae6SDimitry Andric if (!livein_empty() && MRI.tracksLiveness()) {
423044eb2f6SDimitry Andric if (Indexes) OS << '\t';
424eb11fae6SDimitry Andric OS.indent(2) << "liveins: ";
425eb11fae6SDimitry Andric
426b60736ecSDimitry Andric ListSeparator LS;
427eb11fae6SDimitry Andric for (const auto &LI : liveins()) {
428b60736ecSDimitry Andric OS << LS << printReg(LI.PhysReg, TRI);
429eb11fae6SDimitry Andric if (!LI.LaneMask.all())
430eb11fae6SDimitry Andric OS << ":0x" << PrintLaneMask(LI.LaneMask);
431eb11fae6SDimitry Andric }
432eb11fae6SDimitry Andric HasLineAttributes = true;
433eb11fae6SDimitry Andric }
434eb11fae6SDimitry Andric
435eb11fae6SDimitry Andric if (HasLineAttributes)
436044eb2f6SDimitry Andric OS << '\n';
437eb11fae6SDimitry Andric
438eb11fae6SDimitry Andric bool IsInBundle = false;
439eb11fae6SDimitry Andric for (const MachineInstr &MI : instrs()) {
4401d5ae102SDimitry Andric if (Indexes && PrintSlotIndexes) {
441eb11fae6SDimitry Andric if (Indexes->hasIndex(MI))
442eb11fae6SDimitry Andric OS << Indexes->getInstructionIndex(MI);
443eb11fae6SDimitry Andric OS << '\t';
444eb11fae6SDimitry Andric }
445eb11fae6SDimitry Andric
446eb11fae6SDimitry Andric if (IsInBundle && !MI.isInsideBundle()) {
447eb11fae6SDimitry Andric OS.indent(2) << "}\n";
448eb11fae6SDimitry Andric IsInBundle = false;
449eb11fae6SDimitry Andric }
450eb11fae6SDimitry Andric
451eb11fae6SDimitry Andric OS.indent(IsInBundle ? 4 : 2);
452eb11fae6SDimitry Andric MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
453eb11fae6SDimitry Andric /*AddNewLine=*/false, &TII);
454eb11fae6SDimitry Andric
455eb11fae6SDimitry Andric if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
456eb11fae6SDimitry Andric OS << " {";
457eb11fae6SDimitry Andric IsInBundle = true;
458eb11fae6SDimitry Andric }
459eb11fae6SDimitry Andric OS << '\n';
460eb11fae6SDimitry Andric }
461eb11fae6SDimitry Andric
462eb11fae6SDimitry Andric if (IsInBundle)
463eb11fae6SDimitry Andric OS.indent(2) << "}\n";
464eb11fae6SDimitry Andric
465eb11fae6SDimitry Andric if (IrrLoopHeaderWeight && IsStandalone) {
466eb11fae6SDimitry Andric if (Indexes) OS << '\t';
467e3b55780SDimitry Andric OS.indent(2) << "; Irreducible loop header weight: " << *IrrLoopHeaderWeight
468e3b55780SDimitry Andric << '\n';
469044eb2f6SDimitry Andric }
470009b1c42SEd Schouten }
471009b1c42SEd Schouten
472b60736ecSDimitry Andric /// Print the basic block's name as:
473b60736ecSDimitry Andric ///
474b60736ecSDimitry Andric /// bb.{number}[.{ir-name}] [(attributes...)]
475b60736ecSDimitry Andric ///
476b60736ecSDimitry Andric /// The {ir-name} is only printed when the \ref PrintNameIr flag is passed
477b60736ecSDimitry Andric /// (which is the default). If the IR block has no name, it is identified
478b60736ecSDimitry Andric /// numerically using the attribute syntax as "(%ir-block.{ir-slot})".
479b60736ecSDimitry Andric ///
480b60736ecSDimitry Andric /// When the \ref PrintNameAttributes flag is passed, additional attributes
481b60736ecSDimitry Andric /// of the block are printed when set.
482b60736ecSDimitry Andric ///
483b60736ecSDimitry Andric /// \param printNameFlags Combination of \ref PrintNameFlag flags indicating
484b60736ecSDimitry Andric /// the parts to print.
485b60736ecSDimitry Andric /// \param moduleSlotTracker Optional ModuleSlotTracker. This method will
486b60736ecSDimitry Andric /// incorporate its own tracker when necessary to
487b60736ecSDimitry Andric /// determine the block's IR name.
printName(raw_ostream & os,unsigned printNameFlags,ModuleSlotTracker * moduleSlotTracker) const488b60736ecSDimitry Andric void MachineBasicBlock::printName(raw_ostream &os, unsigned printNameFlags,
489b60736ecSDimitry Andric ModuleSlotTracker *moduleSlotTracker) const {
490b60736ecSDimitry Andric os << "bb." << getNumber();
491b60736ecSDimitry Andric bool hasAttributes = false;
492b60736ecSDimitry Andric
493e3b55780SDimitry Andric auto PrintBBRef = [&](const BasicBlock *bb) {
494e3b55780SDimitry Andric os << "%ir-block.";
495b60736ecSDimitry Andric if (bb->hasName()) {
496e3b55780SDimitry Andric os << bb->getName();
497b60736ecSDimitry Andric } else {
498b60736ecSDimitry Andric int slot = -1;
499b60736ecSDimitry Andric
500b60736ecSDimitry Andric if (moduleSlotTracker) {
501b60736ecSDimitry Andric slot = moduleSlotTracker->getLocalSlot(bb);
502b60736ecSDimitry Andric } else if (bb->getParent()) {
503b60736ecSDimitry Andric ModuleSlotTracker tmpTracker(bb->getModule(), false);
504b60736ecSDimitry Andric tmpTracker.incorporateFunction(*bb->getParent());
505b60736ecSDimitry Andric slot = tmpTracker.getLocalSlot(bb);
506b60736ecSDimitry Andric }
507b60736ecSDimitry Andric
508b60736ecSDimitry Andric if (slot == -1)
509b60736ecSDimitry Andric os << "<ir-block badref>";
510b60736ecSDimitry Andric else
511e3b55780SDimitry Andric os << slot;
512e3b55780SDimitry Andric }
513e3b55780SDimitry Andric };
514e3b55780SDimitry Andric
515e3b55780SDimitry Andric if (printNameFlags & PrintNameIr) {
516e3b55780SDimitry Andric if (const auto *bb = getBasicBlock()) {
517e3b55780SDimitry Andric if (bb->hasName()) {
518e3b55780SDimitry Andric os << '.' << bb->getName();
519e3b55780SDimitry Andric } else {
520e3b55780SDimitry Andric hasAttributes = true;
521e3b55780SDimitry Andric os << " (";
522e3b55780SDimitry Andric PrintBBRef(bb);
523b60736ecSDimitry Andric }
524b60736ecSDimitry Andric }
525b60736ecSDimitry Andric }
526b60736ecSDimitry Andric
527b60736ecSDimitry Andric if (printNameFlags & PrintNameAttributes) {
528e3b55780SDimitry Andric if (isMachineBlockAddressTaken()) {
529b60736ecSDimitry Andric os << (hasAttributes ? ", " : " (");
530e3b55780SDimitry Andric os << "machine-block-address-taken";
531e3b55780SDimitry Andric hasAttributes = true;
532e3b55780SDimitry Andric }
533e3b55780SDimitry Andric if (isIRBlockAddressTaken()) {
534e3b55780SDimitry Andric os << (hasAttributes ? ", " : " (");
535e3b55780SDimitry Andric os << "ir-block-address-taken ";
536e3b55780SDimitry Andric PrintBBRef(getAddressTakenIRBlock());
537b60736ecSDimitry Andric hasAttributes = true;
538b60736ecSDimitry Andric }
539b60736ecSDimitry Andric if (isEHPad()) {
540b60736ecSDimitry Andric os << (hasAttributes ? ", " : " (");
541b60736ecSDimitry Andric os << "landing-pad";
542b60736ecSDimitry Andric hasAttributes = true;
543b60736ecSDimitry Andric }
544c0981da4SDimitry Andric if (isInlineAsmBrIndirectTarget()) {
545c0981da4SDimitry Andric os << (hasAttributes ? ", " : " (");
546c0981da4SDimitry Andric os << "inlineasm-br-indirect-target";
547c0981da4SDimitry Andric hasAttributes = true;
548c0981da4SDimitry Andric }
549b60736ecSDimitry Andric if (isEHFuncletEntry()) {
550b60736ecSDimitry Andric os << (hasAttributes ? ", " : " (");
551b60736ecSDimitry Andric os << "ehfunclet-entry";
552b60736ecSDimitry Andric hasAttributes = true;
553b60736ecSDimitry Andric }
554b60736ecSDimitry Andric if (getAlignment() != Align(1)) {
555b60736ecSDimitry Andric os << (hasAttributes ? ", " : " (");
556b60736ecSDimitry Andric os << "align " << getAlignment().value();
557b60736ecSDimitry Andric hasAttributes = true;
558b60736ecSDimitry Andric }
559b60736ecSDimitry Andric if (getSectionID() != MBBSectionID(0)) {
560b60736ecSDimitry Andric os << (hasAttributes ? ", " : " (");
561b60736ecSDimitry Andric os << "bbsections ";
562b60736ecSDimitry Andric switch (getSectionID().Type) {
563b60736ecSDimitry Andric case MBBSectionID::SectionType::Exception:
564b60736ecSDimitry Andric os << "Exception";
565b60736ecSDimitry Andric break;
566b60736ecSDimitry Andric case MBBSectionID::SectionType::Cold:
567b60736ecSDimitry Andric os << "Cold";
568b60736ecSDimitry Andric break;
569b60736ecSDimitry Andric default:
570b60736ecSDimitry Andric os << getSectionID().Number;
571b60736ecSDimitry Andric }
572b60736ecSDimitry Andric hasAttributes = true;
573b60736ecSDimitry Andric }
574e3b55780SDimitry Andric if (getBBID().has_value()) {
575e3b55780SDimitry Andric os << (hasAttributes ? ", " : " (");
576b1c73532SDimitry Andric os << "bb_id " << getBBID()->BaseID;
577b1c73532SDimitry Andric if (getBBID()->CloneID != 0)
578b1c73532SDimitry Andric os << " " << getBBID()->CloneID;
579b1c73532SDimitry Andric hasAttributes = true;
580b1c73532SDimitry Andric }
581b1c73532SDimitry Andric if (CallFrameSize != 0) {
582b1c73532SDimitry Andric os << (hasAttributes ? ", " : " (");
583b1c73532SDimitry Andric os << "call-frame-size " << CallFrameSize;
584e3b55780SDimitry Andric hasAttributes = true;
585e3b55780SDimitry Andric }
586b60736ecSDimitry Andric }
587b60736ecSDimitry Andric
588b60736ecSDimitry Andric if (hasAttributes)
589b60736ecSDimitry Andric os << ')';
590b60736ecSDimitry Andric }
591b60736ecSDimitry Andric
printAsOperand(raw_ostream & OS,bool) const592dd58ef01SDimitry Andric void MachineBasicBlock::printAsOperand(raw_ostream &OS,
593dd58ef01SDimitry Andric bool /*PrintType*/) const {
594b60736ecSDimitry Andric OS << '%';
595b60736ecSDimitry Andric printName(OS, 0);
5965ca98fd9SDimitry Andric }
5975ca98fd9SDimitry Andric
removeLiveIn(MCPhysReg Reg,LaneBitmask LaneMask)598dd58ef01SDimitry Andric void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
599b915e9e0SDimitry Andric LiveInVector::iterator I = find_if(
600b915e9e0SDimitry Andric LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
601dd58ef01SDimitry Andric if (I == LiveIns.end())
602dd58ef01SDimitry Andric return;
603dd58ef01SDimitry Andric
604dd58ef01SDimitry Andric I->LaneMask &= ~LaneMask;
605b915e9e0SDimitry Andric if (I->LaneMask.none())
606009b1c42SEd Schouten LiveIns.erase(I);
607009b1c42SEd Schouten }
608009b1c42SEd Schouten
609f382538dSDimitry Andric MachineBasicBlock::livein_iterator
removeLiveIn(MachineBasicBlock::livein_iterator I)610f382538dSDimitry Andric MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
611f382538dSDimitry Andric // Get non-const version of iterator.
612f382538dSDimitry Andric LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
613f382538dSDimitry Andric return LiveIns.erase(LI);
614f382538dSDimitry Andric }
615f382538dSDimitry Andric
isLiveIn(MCPhysReg Reg,LaneBitmask LaneMask) const616dd58ef01SDimitry Andric bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
617b915e9e0SDimitry Andric livein_iterator I = find_if(
618b915e9e0SDimitry Andric LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
619b915e9e0SDimitry Andric return I != livein_end() && (I->LaneMask & LaneMask).any();
620dd58ef01SDimitry Andric }
621dd58ef01SDimitry Andric
sortUniqueLiveIns()622dd58ef01SDimitry Andric void MachineBasicBlock::sortUniqueLiveIns() {
623d8e91e46SDimitry Andric llvm::sort(LiveIns,
624dd58ef01SDimitry Andric [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
625dd58ef01SDimitry Andric return LI0.PhysReg < LI1.PhysReg;
626dd58ef01SDimitry Andric });
627dd58ef01SDimitry Andric // Liveins are sorted by physreg now we can merge their lanemasks.
628dd58ef01SDimitry Andric LiveInVector::const_iterator I = LiveIns.begin();
629dd58ef01SDimitry Andric LiveInVector::const_iterator J;
630dd58ef01SDimitry Andric LiveInVector::iterator Out = LiveIns.begin();
631dd58ef01SDimitry Andric for (; I != LiveIns.end(); ++Out, I = J) {
632cfca06d7SDimitry Andric MCRegister PhysReg = I->PhysReg;
633dd58ef01SDimitry Andric LaneBitmask LaneMask = I->LaneMask;
634dd58ef01SDimitry Andric for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
635dd58ef01SDimitry Andric LaneMask |= J->LaneMask;
636dd58ef01SDimitry Andric Out->PhysReg = PhysReg;
637dd58ef01SDimitry Andric Out->LaneMask = LaneMask;
638dd58ef01SDimitry Andric }
639dd58ef01SDimitry Andric LiveIns.erase(Out, LiveIns.end());
640009b1c42SEd Schouten }
641009b1c42SEd Schouten
642cfca06d7SDimitry Andric Register
addLiveIn(MCRegister PhysReg,const TargetRegisterClass * RC)6431d5ae102SDimitry Andric MachineBasicBlock::addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC) {
644f8af5cf6SDimitry Andric assert(getParent() && "MBB must be inserted in function");
645b60736ecSDimitry Andric assert(Register::isPhysicalRegister(PhysReg) && "Expected physreg");
646f8af5cf6SDimitry Andric assert(RC && "Register class is required");
647dd58ef01SDimitry Andric assert((isEHPad() || this == &getParent()->front()) &&
648f8af5cf6SDimitry Andric "Only the entry block and landing pads can have physreg live ins");
649f8af5cf6SDimitry Andric
650f8af5cf6SDimitry Andric bool LiveIn = isLiveIn(PhysReg);
651f8af5cf6SDimitry Andric iterator I = SkipPHIsAndLabels(begin()), E = end();
652f8af5cf6SDimitry Andric MachineRegisterInfo &MRI = getParent()->getRegInfo();
65367c32a98SDimitry Andric const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
654f8af5cf6SDimitry Andric
655f8af5cf6SDimitry Andric // Look for an existing copy.
656f8af5cf6SDimitry Andric if (LiveIn)
657f8af5cf6SDimitry Andric for (;I != E && I->isCopy(); ++I)
658f8af5cf6SDimitry Andric if (I->getOperand(1).getReg() == PhysReg) {
6591d5ae102SDimitry Andric Register VirtReg = I->getOperand(0).getReg();
660f8af5cf6SDimitry Andric if (!MRI.constrainRegClass(VirtReg, RC))
661f8af5cf6SDimitry Andric llvm_unreachable("Incompatible live-in register class.");
662f8af5cf6SDimitry Andric return VirtReg;
663f8af5cf6SDimitry Andric }
664f8af5cf6SDimitry Andric
665f8af5cf6SDimitry Andric // No luck, create a virtual register.
6661d5ae102SDimitry Andric Register VirtReg = MRI.createVirtualRegister(RC);
667f8af5cf6SDimitry Andric BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
668f8af5cf6SDimitry Andric .addReg(PhysReg, RegState::Kill);
669f8af5cf6SDimitry Andric if (!LiveIn)
670f8af5cf6SDimitry Andric addLiveIn(PhysReg);
671f8af5cf6SDimitry Andric return VirtReg;
672f8af5cf6SDimitry Andric }
673f8af5cf6SDimitry Andric
moveBefore(MachineBasicBlock * NewAfter)674009b1c42SEd Schouten void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
675dd58ef01SDimitry Andric getParent()->splice(NewAfter->getIterator(), getIterator());
676009b1c42SEd Schouten }
677009b1c42SEd Schouten
moveAfter(MachineBasicBlock * NewBefore)678009b1c42SEd Schouten void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
679dd58ef01SDimitry Andric getParent()->splice(++NewBefore->getIterator(), getIterator());
680009b1c42SEd Schouten }
681009b1c42SEd Schouten
findJumpTableIndex(const MachineBasicBlock & MBB)6827fa27ce4SDimitry Andric static int findJumpTableIndex(const MachineBasicBlock &MBB) {
6837fa27ce4SDimitry Andric MachineBasicBlock::const_iterator TerminatorI = MBB.getFirstTerminator();
6847fa27ce4SDimitry Andric if (TerminatorI == MBB.end())
6857fa27ce4SDimitry Andric return -1;
6867fa27ce4SDimitry Andric const MachineInstr &Terminator = *TerminatorI;
6877fa27ce4SDimitry Andric const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
6887fa27ce4SDimitry Andric return TII->getJumpTableIndex(Terminator);
6897fa27ce4SDimitry Andric }
6907fa27ce4SDimitry Andric
updateTerminator(MachineBasicBlock * PreviousLayoutSuccessor)691cfca06d7SDimitry Andric void MachineBasicBlock::updateTerminator(
692cfca06d7SDimitry Andric MachineBasicBlock *PreviousLayoutSuccessor) {
693cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
694cfca06d7SDimitry Andric << "\n");
695cfca06d7SDimitry Andric
69667c32a98SDimitry Andric const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
697907da171SRoman Divacky // A block with no successors has no concerns with fall-through edges.
69801095a5dSDimitry Andric if (this->succ_empty())
69901095a5dSDimitry Andric return;
700907da171SRoman Divacky
7015ca98fd9SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
702907da171SRoman Divacky SmallVector<MachineOperand, 4> Cond;
70371d5a254SDimitry Andric DebugLoc DL = findBranchDebugLoc();
70401095a5dSDimitry Andric bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
705907da171SRoman Divacky (void) B;
706907da171SRoman Divacky assert(!B && "UpdateTerminators requires analyzable predecessors!");
707907da171SRoman Divacky if (Cond.empty()) {
708907da171SRoman Divacky if (TBB) {
70901095a5dSDimitry Andric // The block has an unconditional branch. If its successor is now its
71001095a5dSDimitry Andric // layout successor, delete the branch.
711907da171SRoman Divacky if (isLayoutSuccessor(TBB))
712b915e9e0SDimitry Andric TII->removeBranch(*this);
713907da171SRoman Divacky } else {
714cfca06d7SDimitry Andric // The block has an unconditional fallthrough, or the end of the block is
715cfca06d7SDimitry Andric // unreachable.
71663faed5bSDimitry Andric
717cfca06d7SDimitry Andric // Unfortunately, whether the end of the block is unreachable is not
718cfca06d7SDimitry Andric // immediately obvious; we must fall back to checking the successor list,
719cfca06d7SDimitry Andric // and assuming that if the passed in block is in the succesor list and
720cfca06d7SDimitry Andric // not an EHPad, it must be the intended target.
721cfca06d7SDimitry Andric if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) ||
722cfca06d7SDimitry Andric PreviousLayoutSuccessor->isEHPad())
72363faed5bSDimitry Andric return;
72463faed5bSDimitry Andric
725cfca06d7SDimitry Andric // If the unconditional successor block is not the current layout
726cfca06d7SDimitry Andric // successor, insert a branch to jump to it.
727cfca06d7SDimitry Andric if (!isLayoutSuccessor(PreviousLayoutSuccessor))
728cfca06d7SDimitry Andric TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
729907da171SRoman Divacky }
73001095a5dSDimitry Andric return;
73101095a5dSDimitry Andric }
73201095a5dSDimitry Andric
733907da171SRoman Divacky if (FBB) {
734907da171SRoman Divacky // The block has a non-fallthrough conditional branch. If one of its
735907da171SRoman Divacky // successors is its layout successor, rewrite it to a fallthrough
736907da171SRoman Divacky // conditional branch.
737907da171SRoman Divacky if (isLayoutSuccessor(TBB)) {
738b915e9e0SDimitry Andric if (TII->reverseBranchCondition(Cond))
73906f9d401SRoman Divacky return;
740b915e9e0SDimitry Andric TII->removeBranch(*this);
741b915e9e0SDimitry Andric TII->insertBranch(*this, FBB, nullptr, Cond, DL);
742907da171SRoman Divacky } else if (isLayoutSuccessor(FBB)) {
743b915e9e0SDimitry Andric TII->removeBranch(*this);
744b915e9e0SDimitry Andric TII->insertBranch(*this, TBB, nullptr, Cond, DL);
745907da171SRoman Divacky }
74601095a5dSDimitry Andric return;
74701095a5dSDimitry Andric }
74801095a5dSDimitry Andric
749cfca06d7SDimitry Andric // We now know we're going to fallthrough to PreviousLayoutSuccessor.
750cfca06d7SDimitry Andric assert(PreviousLayoutSuccessor);
751cfca06d7SDimitry Andric assert(!PreviousLayoutSuccessor->isEHPad());
752cfca06d7SDimitry Andric assert(isSuccessor(PreviousLayoutSuccessor));
75301095a5dSDimitry Andric
754cfca06d7SDimitry Andric if (PreviousLayoutSuccessor == TBB) {
755cfca06d7SDimitry Andric // We had a fallthrough to the same basic block as the conditional jump
756cfca06d7SDimitry Andric // targets. Remove the conditional jump, leaving an unconditional
757cfca06d7SDimitry Andric // fallthrough or an unconditional jump.
758b915e9e0SDimitry Andric TII->removeBranch(*this);
759cfca06d7SDimitry Andric if (!isLayoutSuccessor(TBB)) {
76001095a5dSDimitry Andric Cond.clear();
761b915e9e0SDimitry Andric TII->insertBranch(*this, TBB, nullptr, Cond, DL);
762cfca06d7SDimitry Andric }
76301095a5dSDimitry Andric return;
76401095a5dSDimitry Andric }
76501095a5dSDimitry Andric
766907da171SRoman Divacky // The block has a fallthrough conditional branch.
767907da171SRoman Divacky if (isLayoutSuccessor(TBB)) {
768b915e9e0SDimitry Andric if (TII->reverseBranchCondition(Cond)) {
76906f9d401SRoman Divacky // We can't reverse the condition, add an unconditional branch.
77006f9d401SRoman Divacky Cond.clear();
771cfca06d7SDimitry Andric TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
77206f9d401SRoman Divacky return;
77306f9d401SRoman Divacky }
774b915e9e0SDimitry Andric TII->removeBranch(*this);
775cfca06d7SDimitry Andric TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
776cfca06d7SDimitry Andric } else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) {
777b915e9e0SDimitry Andric TII->removeBranch(*this);
778cfca06d7SDimitry Andric TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL);
779907da171SRoman Divacky }
780907da171SRoman Divacky }
781009b1c42SEd Schouten
validateSuccProbs() const782dd58ef01SDimitry Andric void MachineBasicBlock::validateSuccProbs() const {
783dd58ef01SDimitry Andric #ifndef NDEBUG
784dd58ef01SDimitry Andric int64_t Sum = 0;
785dd58ef01SDimitry Andric for (auto Prob : Probs)
786dd58ef01SDimitry Andric Sum += Prob.getNumerator();
787dd58ef01SDimitry Andric // Due to precision issue, we assume that the sum of probabilities is one if
788dd58ef01SDimitry Andric // the difference between the sum of their numerators and the denominator is
789dd58ef01SDimitry Andric // no greater than the number of successors.
790dd58ef01SDimitry Andric assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
791dd58ef01SDimitry Andric Probs.size() &&
792dd58ef01SDimitry Andric "The sum of successors's probabilities exceeds one.");
793dd58ef01SDimitry Andric #endif // NDEBUG
794009b1c42SEd Schouten }
795009b1c42SEd Schouten
addSuccessor(MachineBasicBlock * Succ,BranchProbability Prob)796dd58ef01SDimitry Andric void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
797dd58ef01SDimitry Andric BranchProbability Prob) {
798dd58ef01SDimitry Andric // Probability list is either empty (if successor list isn't empty, this means
799dd58ef01SDimitry Andric // disabled optimization) or has the same size as successor list.
800dd58ef01SDimitry Andric if (!(Probs.empty() && !Successors.empty()))
801dd58ef01SDimitry Andric Probs.push_back(Prob);
802dd58ef01SDimitry Andric Successors.push_back(Succ);
803dd58ef01SDimitry Andric Succ->addPredecessor(this);
804411bd29eSDimitry Andric }
805411bd29eSDimitry Andric
addSuccessorWithoutProb(MachineBasicBlock * Succ)806dd58ef01SDimitry Andric void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
807dd58ef01SDimitry Andric // We need to make sure probability list is either empty or has the same size
808dd58ef01SDimitry Andric // of successor list. When this function is called, we can safely delete all
809dd58ef01SDimitry Andric // probability in the list.
810dd58ef01SDimitry Andric Probs.clear();
811dd58ef01SDimitry Andric Successors.push_back(Succ);
812dd58ef01SDimitry Andric Succ->addPredecessor(this);
813dd58ef01SDimitry Andric }
814dd58ef01SDimitry Andric
splitSuccessor(MachineBasicBlock * Old,MachineBasicBlock * New,bool NormalizeSuccProbs)815eb11fae6SDimitry Andric void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
816eb11fae6SDimitry Andric MachineBasicBlock *New,
817eb11fae6SDimitry Andric bool NormalizeSuccProbs) {
818eb11fae6SDimitry Andric succ_iterator OldI = llvm::find(successors(), Old);
819eb11fae6SDimitry Andric assert(OldI != succ_end() && "Old is not a successor of this block!");
820b60736ecSDimitry Andric assert(!llvm::is_contained(successors(), New) &&
821eb11fae6SDimitry Andric "New is already a successor of this block!");
822eb11fae6SDimitry Andric
823eb11fae6SDimitry Andric // Add a new successor with equal probability as the original one. Note
824eb11fae6SDimitry Andric // that we directly copy the probability using the iterator rather than
825eb11fae6SDimitry Andric // getting a potentially synthetic probability computed when unknown. This
826eb11fae6SDimitry Andric // preserves the probabilities as-is and then we can renormalize them and
827eb11fae6SDimitry Andric // query them effectively afterward.
828eb11fae6SDimitry Andric addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
829eb11fae6SDimitry Andric : *getProbabilityIterator(OldI));
830eb11fae6SDimitry Andric if (NormalizeSuccProbs)
831eb11fae6SDimitry Andric normalizeSuccProbs();
832eb11fae6SDimitry Andric }
833eb11fae6SDimitry Andric
removeSuccessor(MachineBasicBlock * Succ,bool NormalizeSuccProbs)834dd58ef01SDimitry Andric void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
835dd58ef01SDimitry Andric bool NormalizeSuccProbs) {
836b915e9e0SDimitry Andric succ_iterator I = find(Successors, Succ);
837dd58ef01SDimitry Andric removeSuccessor(I, NormalizeSuccProbs);
838009b1c42SEd Schouten }
839009b1c42SEd Schouten
840009b1c42SEd Schouten MachineBasicBlock::succ_iterator
removeSuccessor(succ_iterator I,bool NormalizeSuccProbs)841dd58ef01SDimitry Andric MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
842009b1c42SEd Schouten assert(I != Successors.end() && "Not a current successor!");
843411bd29eSDimitry Andric
844dd58ef01SDimitry Andric // If probability list is empty it means we don't use it (disabled
845dd58ef01SDimitry Andric // optimization).
846dd58ef01SDimitry Andric if (!Probs.empty()) {
847dd58ef01SDimitry Andric probability_iterator WI = getProbabilityIterator(I);
848dd58ef01SDimitry Andric Probs.erase(WI);
849dd58ef01SDimitry Andric if (NormalizeSuccProbs)
850dd58ef01SDimitry Andric normalizeSuccProbs();
851411bd29eSDimitry Andric }
852411bd29eSDimitry Andric
853009b1c42SEd Schouten (*I)->removePredecessor(this);
854009b1c42SEd Schouten return Successors.erase(I);
855009b1c42SEd Schouten }
856009b1c42SEd Schouten
replaceSuccessor(MachineBasicBlock * Old,MachineBasicBlock * New)857411bd29eSDimitry Andric void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
858411bd29eSDimitry Andric MachineBasicBlock *New) {
85958b69754SDimitry Andric if (Old == New)
86058b69754SDimitry Andric return;
861411bd29eSDimitry Andric
86258b69754SDimitry Andric succ_iterator E = succ_end();
86358b69754SDimitry Andric succ_iterator NewI = E;
86458b69754SDimitry Andric succ_iterator OldI = E;
86558b69754SDimitry Andric for (succ_iterator I = succ_begin(); I != E; ++I) {
86658b69754SDimitry Andric if (*I == Old) {
86758b69754SDimitry Andric OldI = I;
86858b69754SDimitry Andric if (NewI != E)
86958b69754SDimitry Andric break;
87058b69754SDimitry Andric }
87158b69754SDimitry Andric if (*I == New) {
87258b69754SDimitry Andric NewI = I;
87358b69754SDimitry Andric if (OldI != E)
87458b69754SDimitry Andric break;
87558b69754SDimitry Andric }
87658b69754SDimitry Andric }
87758b69754SDimitry Andric assert(OldI != E && "Old is not a successor of this block");
87858b69754SDimitry Andric
87958b69754SDimitry Andric // If New isn't already a successor, let it take Old's place.
88058b69754SDimitry Andric if (NewI == E) {
881dd58ef01SDimitry Andric Old->removePredecessor(this);
88258b69754SDimitry Andric New->addPredecessor(this);
88358b69754SDimitry Andric *OldI = New;
88458b69754SDimitry Andric return;
885411bd29eSDimitry Andric }
886411bd29eSDimitry Andric
88758b69754SDimitry Andric // New is already a successor.
888dd58ef01SDimitry Andric // Update its probability instead of adding a duplicate edge.
889dd58ef01SDimitry Andric if (!Probs.empty()) {
890dd58ef01SDimitry Andric auto ProbIter = getProbabilityIterator(NewI);
891dd58ef01SDimitry Andric if (!ProbIter->isUnknown())
892dd58ef01SDimitry Andric *ProbIter += *getProbabilityIterator(OldI);
89358b69754SDimitry Andric }
894dd58ef01SDimitry Andric removeSuccessor(OldI);
895411bd29eSDimitry Andric }
896411bd29eSDimitry Andric
copySuccessor(const MachineBasicBlock * Orig,succ_iterator I)897b1c73532SDimitry Andric void MachineBasicBlock::copySuccessor(const MachineBasicBlock *Orig,
898eb11fae6SDimitry Andric succ_iterator I) {
899b60736ecSDimitry Andric if (!Orig->Probs.empty())
900eb11fae6SDimitry Andric addSuccessor(*I, Orig->getSuccProbability(I));
901eb11fae6SDimitry Andric else
902eb11fae6SDimitry Andric addSuccessorWithoutProb(*I);
903eb11fae6SDimitry Andric }
904eb11fae6SDimitry Andric
addPredecessor(MachineBasicBlock * Pred)905dd58ef01SDimitry Andric void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
906dd58ef01SDimitry Andric Predecessors.push_back(Pred);
907009b1c42SEd Schouten }
908009b1c42SEd Schouten
removePredecessor(MachineBasicBlock * Pred)909dd58ef01SDimitry Andric void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
910b915e9e0SDimitry Andric pred_iterator I = find(Predecessors, Pred);
911009b1c42SEd Schouten assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
912009b1c42SEd Schouten Predecessors.erase(I);
913009b1c42SEd Schouten }
914009b1c42SEd Schouten
transferSuccessors(MachineBasicBlock * FromMBB)915dd58ef01SDimitry Andric void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
916dd58ef01SDimitry Andric if (this == FromMBB)
917009b1c42SEd Schouten return;
918009b1c42SEd Schouten
919dd58ef01SDimitry Andric while (!FromMBB->succ_empty()) {
920dd58ef01SDimitry Andric MachineBasicBlock *Succ = *FromMBB->succ_begin();
921411bd29eSDimitry Andric
9221d5ae102SDimitry Andric // If probability list is empty it means we don't use it (disabled
9231d5ae102SDimitry Andric // optimization).
924dd58ef01SDimitry Andric if (!FromMBB->Probs.empty()) {
925dd58ef01SDimitry Andric auto Prob = *FromMBB->Probs.begin();
926dd58ef01SDimitry Andric addSuccessor(Succ, Prob);
927dd58ef01SDimitry Andric } else
928dd58ef01SDimitry Andric addSuccessorWithoutProb(Succ);
929411bd29eSDimitry Andric
930dd58ef01SDimitry Andric FromMBB->removeSuccessor(Succ);
93166e41e3cSRoman Divacky }
93266e41e3cSRoman Divacky }
93359850d08SRoman Divacky
93466e41e3cSRoman Divacky void
transferSuccessorsAndUpdatePHIs(MachineBasicBlock * FromMBB)935dd58ef01SDimitry Andric MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
936dd58ef01SDimitry Andric if (this == FromMBB)
93766e41e3cSRoman Divacky return;
93866e41e3cSRoman Divacky
939dd58ef01SDimitry Andric while (!FromMBB->succ_empty()) {
940dd58ef01SDimitry Andric MachineBasicBlock *Succ = *FromMBB->succ_begin();
941dd58ef01SDimitry Andric if (!FromMBB->Probs.empty()) {
942dd58ef01SDimitry Andric auto Prob = *FromMBB->Probs.begin();
943dd58ef01SDimitry Andric addSuccessor(Succ, Prob);
944dd58ef01SDimitry Andric } else
945dd58ef01SDimitry Andric addSuccessorWithoutProb(Succ);
946dd58ef01SDimitry Andric FromMBB->removeSuccessor(Succ);
94766e41e3cSRoman Divacky
94866e41e3cSRoman Divacky // Fix up any PHI nodes in the successor.
9491d5ae102SDimitry Andric Succ->replacePhiUsesWith(FromMBB, this);
95066e41e3cSRoman Divacky }
951dd58ef01SDimitry Andric normalizeSuccProbs();
952009b1c42SEd Schouten }
953009b1c42SEd Schouten
isPredecessor(const MachineBasicBlock * MBB) const95458b69754SDimitry Andric bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
955b915e9e0SDimitry Andric return is_contained(predecessors(), MBB);
95658b69754SDimitry Andric }
95758b69754SDimitry Andric
isSuccessor(const MachineBasicBlock * MBB) const958009b1c42SEd Schouten bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
959b915e9e0SDimitry Andric return is_contained(successors(), MBB);
960009b1c42SEd Schouten }
961009b1c42SEd Schouten
isLayoutSuccessor(const MachineBasicBlock * MBB) const962009b1c42SEd Schouten bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
963009b1c42SEd Schouten MachineFunction::const_iterator I(this);
9645ca98fd9SDimitry Andric return std::next(I) == MachineFunction::const_iterator(MBB);
965009b1c42SEd Schouten }
966009b1c42SEd Schouten
getSingleSuccessor() const967145449b1SDimitry Andric const MachineBasicBlock *MachineBasicBlock::getSingleSuccessor() const {
968145449b1SDimitry Andric return Successors.size() == 1 ? Successors[0] : nullptr;
969145449b1SDimitry Andric }
970145449b1SDimitry Andric
getSinglePredecessor() const971b1c73532SDimitry Andric const MachineBasicBlock *MachineBasicBlock::getSinglePredecessor() const {
972b1c73532SDimitry Andric return Predecessors.size() == 1 ? Predecessors[0] : nullptr;
973b1c73532SDimitry Andric }
974b1c73532SDimitry Andric
getFallThrough(bool JumpToFallThrough)975e3b55780SDimitry Andric MachineBasicBlock *MachineBasicBlock::getFallThrough(bool JumpToFallThrough) {
976dd58ef01SDimitry Andric MachineFunction::iterator Fallthrough = getIterator();
97706f9d401SRoman Divacky ++Fallthrough;
97806f9d401SRoman Divacky // If FallthroughBlock is off the end of the function, it can't fall through.
97906f9d401SRoman Divacky if (Fallthrough == getParent()->end())
98071d5a254SDimitry Andric return nullptr;
98106f9d401SRoman Divacky
98206f9d401SRoman Divacky // If FallthroughBlock isn't a successor, no fallthrough is possible.
983dd58ef01SDimitry Andric if (!isSuccessor(&*Fallthrough))
98471d5a254SDimitry Andric return nullptr;
98506f9d401SRoman Divacky
986571945e6SRoman Divacky // Analyze the branches, if any, at the end of the block.
9875ca98fd9SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
988571945e6SRoman Divacky SmallVector<MachineOperand, 4> Cond;
98967c32a98SDimitry Andric const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
99001095a5dSDimitry Andric if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
99106f9d401SRoman Divacky // If we couldn't analyze the branch, examine the last instruction.
99206f9d401SRoman Divacky // If the block doesn't end in a known control barrier, assume fallthrough
99363faed5bSDimitry Andric // is possible. The isPredicated check is needed because this code can be
99406f9d401SRoman Divacky // called during IfConversion, where an instruction which is normally a
99563faed5bSDimitry Andric // Barrier is predicated and thus no longer an actual control barrier.
99671d5a254SDimitry Andric return (empty() || !back().isBarrier() || TII->isPredicated(back()))
99771d5a254SDimitry Andric ? &*Fallthrough
99871d5a254SDimitry Andric : nullptr;
999571945e6SRoman Divacky }
100006f9d401SRoman Divacky
100106f9d401SRoman Divacky // If there is no branch, control always falls through.
100271d5a254SDimitry Andric if (!TBB) return &*Fallthrough;
100306f9d401SRoman Divacky
100406f9d401SRoman Divacky // If there is some explicit branch to the fallthrough block, it can obviously
100506f9d401SRoman Divacky // reach, even though the branch should get folded to fall through implicitly.
10067fa27ce4SDimitry Andric if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough ||
1007e3b55780SDimitry Andric MachineFunction::iterator(FBB) == Fallthrough))
100871d5a254SDimitry Andric return &*Fallthrough;
100906f9d401SRoman Divacky
101006f9d401SRoman Divacky // If it's an unconditional branch to some block not the fall through, it
101106f9d401SRoman Divacky // doesn't fall through.
101271d5a254SDimitry Andric if (Cond.empty()) return nullptr;
101306f9d401SRoman Divacky
101406f9d401SRoman Divacky // Otherwise, if it is conditional and has no explicit false block, it falls
101506f9d401SRoman Divacky // through.
101671d5a254SDimitry Andric return (FBB == nullptr) ? &*Fallthrough : nullptr;
101771d5a254SDimitry Andric }
101871d5a254SDimitry Andric
canFallThrough()101971d5a254SDimitry Andric bool MachineBasicBlock::canFallThrough() {
102071d5a254SDimitry Andric return getFallThrough() != nullptr;
102106f9d401SRoman Divacky }
102206f9d401SRoman Divacky
splitAt(MachineInstr & MI,bool UpdateLiveIns,LiveIntervals * LIS)1023b60736ecSDimitry Andric MachineBasicBlock *MachineBasicBlock::splitAt(MachineInstr &MI,
1024b60736ecSDimitry Andric bool UpdateLiveIns,
1025b60736ecSDimitry Andric LiveIntervals *LIS) {
1026b60736ecSDimitry Andric MachineBasicBlock::iterator SplitPoint(&MI);
1027b60736ecSDimitry Andric ++SplitPoint;
1028b60736ecSDimitry Andric
1029b60736ecSDimitry Andric if (SplitPoint == end()) {
1030b60736ecSDimitry Andric // Don't bother with a new block.
1031b60736ecSDimitry Andric return this;
1032b60736ecSDimitry Andric }
1033b60736ecSDimitry Andric
1034b60736ecSDimitry Andric MachineFunction *MF = getParent();
1035b60736ecSDimitry Andric
1036b60736ecSDimitry Andric LivePhysRegs LiveRegs;
1037b60736ecSDimitry Andric if (UpdateLiveIns) {
1038b60736ecSDimitry Andric // Make sure we add any physregs we define in the block as liveins to the
1039b60736ecSDimitry Andric // new block.
1040b60736ecSDimitry Andric MachineBasicBlock::iterator Prev(&MI);
1041b60736ecSDimitry Andric LiveRegs.init(*MF->getSubtarget().getRegisterInfo());
1042b60736ecSDimitry Andric LiveRegs.addLiveOuts(*this);
1043b60736ecSDimitry Andric for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
1044b60736ecSDimitry Andric LiveRegs.stepBackward(*I);
1045b60736ecSDimitry Andric }
1046b60736ecSDimitry Andric
1047b60736ecSDimitry Andric MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(getBasicBlock());
1048b60736ecSDimitry Andric
1049b60736ecSDimitry Andric MF->insert(++MachineFunction::iterator(this), SplitBB);
1050b60736ecSDimitry Andric SplitBB->splice(SplitBB->begin(), this, SplitPoint, end());
1051b60736ecSDimitry Andric
1052b60736ecSDimitry Andric SplitBB->transferSuccessorsAndUpdatePHIs(this);
1053b60736ecSDimitry Andric addSuccessor(SplitBB);
1054b60736ecSDimitry Andric
1055b60736ecSDimitry Andric if (UpdateLiveIns)
1056b60736ecSDimitry Andric addLiveIns(*SplitBB, LiveRegs);
1057b60736ecSDimitry Andric
1058b60736ecSDimitry Andric if (LIS)
1059b60736ecSDimitry Andric LIS->insertMBBInMaps(SplitBB);
1060b60736ecSDimitry Andric
1061b60736ecSDimitry Andric return SplitBB;
1062b60736ecSDimitry Andric }
1063b60736ecSDimitry Andric
10647fa27ce4SDimitry Andric // Returns `true` if there are possibly other users of the jump table at
10657fa27ce4SDimitry Andric // `JumpTableIndex` except for the ones in `IgnoreMBB`.
jumpTableHasOtherUses(const MachineFunction & MF,const MachineBasicBlock & IgnoreMBB,int JumpTableIndex)10667fa27ce4SDimitry Andric static bool jumpTableHasOtherUses(const MachineFunction &MF,
10677fa27ce4SDimitry Andric const MachineBasicBlock &IgnoreMBB,
10687fa27ce4SDimitry Andric int JumpTableIndex) {
10697fa27ce4SDimitry Andric assert(JumpTableIndex >= 0 && "need valid index");
10707fa27ce4SDimitry Andric const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo();
10717fa27ce4SDimitry Andric const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex];
10727fa27ce4SDimitry Andric // Take any basic block from the table; every user of the jump table must
10737fa27ce4SDimitry Andric // show up in the predecessor list.
10747fa27ce4SDimitry Andric const MachineBasicBlock *MBB = nullptr;
10757fa27ce4SDimitry Andric for (MachineBasicBlock *B : MJTE.MBBs) {
10767fa27ce4SDimitry Andric if (B != nullptr) {
10777fa27ce4SDimitry Andric MBB = B;
10787fa27ce4SDimitry Andric break;
10797fa27ce4SDimitry Andric }
10807fa27ce4SDimitry Andric }
10817fa27ce4SDimitry Andric if (MBB == nullptr)
10827fa27ce4SDimitry Andric return true; // can't rule out other users if there isn't any block.
10837fa27ce4SDimitry Andric const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
10847fa27ce4SDimitry Andric SmallVector<MachineOperand, 4> Cond;
10857fa27ce4SDimitry Andric for (MachineBasicBlock *Pred : MBB->predecessors()) {
10867fa27ce4SDimitry Andric if (Pred == &IgnoreMBB)
10877fa27ce4SDimitry Andric continue;
10887fa27ce4SDimitry Andric MachineBasicBlock *DummyT = nullptr;
10897fa27ce4SDimitry Andric MachineBasicBlock *DummyF = nullptr;
10907fa27ce4SDimitry Andric Cond.clear();
10917fa27ce4SDimitry Andric if (!TII.analyzeBranch(*Pred, DummyT, DummyF, Cond,
10927fa27ce4SDimitry Andric /*AllowModify=*/false)) {
10937fa27ce4SDimitry Andric // analyzable direct jump
10947fa27ce4SDimitry Andric continue;
10957fa27ce4SDimitry Andric }
10967fa27ce4SDimitry Andric int PredJTI = findJumpTableIndex(*Pred);
10977fa27ce4SDimitry Andric if (PredJTI >= 0) {
10987fa27ce4SDimitry Andric if (PredJTI == JumpTableIndex)
10997fa27ce4SDimitry Andric return true;
11007fa27ce4SDimitry Andric continue;
11017fa27ce4SDimitry Andric }
11027fa27ce4SDimitry Andric // Be conservative for unanalyzable jumps.
11037fa27ce4SDimitry Andric return true;
11047fa27ce4SDimitry Andric }
11057fa27ce4SDimitry Andric return false;
11067fa27ce4SDimitry Andric }
11077fa27ce4SDimitry Andric
1108b1c73532SDimitry Andric class SlotIndexUpdateDelegate : public MachineFunction::Delegate {
1109b1c73532SDimitry Andric private:
1110b1c73532SDimitry Andric MachineFunction &MF;
1111b1c73532SDimitry Andric SlotIndexes *Indexes;
1112b1c73532SDimitry Andric SmallSetVector<MachineInstr *, 2> Insertions;
1113b1c73532SDimitry Andric
1114b1c73532SDimitry Andric public:
SlotIndexUpdateDelegate(MachineFunction & MF,SlotIndexes * Indexes)1115b1c73532SDimitry Andric SlotIndexUpdateDelegate(MachineFunction &MF, SlotIndexes *Indexes)
1116b1c73532SDimitry Andric : MF(MF), Indexes(Indexes) {
1117b1c73532SDimitry Andric MF.setDelegate(this);
1118b1c73532SDimitry Andric }
1119b1c73532SDimitry Andric
~SlotIndexUpdateDelegate()1120b1c73532SDimitry Andric ~SlotIndexUpdateDelegate() {
1121b1c73532SDimitry Andric MF.resetDelegate(this);
1122b1c73532SDimitry Andric for (auto MI : Insertions)
1123b1c73532SDimitry Andric Indexes->insertMachineInstrInMaps(*MI);
1124b1c73532SDimitry Andric }
1125b1c73532SDimitry Andric
MF_HandleInsertion(MachineInstr & MI)1126b1c73532SDimitry Andric void MF_HandleInsertion(MachineInstr &MI) override {
1127b1c73532SDimitry Andric // This is called before MI is inserted into block so defer index update.
1128b1c73532SDimitry Andric if (Indexes)
1129b1c73532SDimitry Andric Insertions.insert(&MI);
1130b1c73532SDimitry Andric }
1131b1c73532SDimitry Andric
MF_HandleRemoval(MachineInstr & MI)1132b1c73532SDimitry Andric void MF_HandleRemoval(MachineInstr &MI) override {
1133b1c73532SDimitry Andric if (Indexes && !Insertions.remove(&MI))
1134b1c73532SDimitry Andric Indexes->removeMachineInstrFromMaps(MI);
1135b1c73532SDimitry Andric }
1136b1c73532SDimitry Andric };
1137b1c73532SDimitry Andric
1138ac9a064cSDimitry Andric #define GET_RESULT(RESULT, GETTER, INFIX) \
1139ac9a064cSDimitry Andric [MF, P, MFAM]() { \
1140ac9a064cSDimitry Andric if (P) { \
1141ac9a064cSDimitry Andric auto *Wrapper = P->getAnalysisIfAvailable<RESULT##INFIX##WrapperPass>(); \
1142ac9a064cSDimitry Andric return Wrapper ? &Wrapper->GETTER() : nullptr; \
1143ac9a064cSDimitry Andric } \
1144ac9a064cSDimitry Andric return MFAM->getCachedResult<RESULT##Analysis>(*MF); \
1145ac9a064cSDimitry Andric }()
1146ac9a064cSDimitry Andric
SplitCriticalEdge(MachineBasicBlock * Succ,Pass * P,MachineFunctionAnalysisManager * MFAM,std::vector<SparseBitVector<>> * LiveInSets)1147cfca06d7SDimitry Andric MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
1148ac9a064cSDimitry Andric MachineBasicBlock *Succ, Pass *P, MachineFunctionAnalysisManager *MFAM,
1149cfca06d7SDimitry Andric std::vector<SparseBitVector<>> *LiveInSets) {
1150ac9a064cSDimitry Andric assert((P || MFAM) && "Need a way to get analysis results!");
115101095a5dSDimitry Andric if (!canSplitCriticalEdge(Succ))
11525ca98fd9SDimitry Andric return nullptr;
115358b69754SDimitry Andric
115466e41e3cSRoman Divacky MachineFunction *MF = getParent();
1155cfca06d7SDimitry Andric MachineBasicBlock *PrevFallthrough = getNextNode();
115666e41e3cSRoman Divacky
115766e41e3cSRoman Divacky MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
1158b1c73532SDimitry Andric NMBB->setCallFrameSize(Succ->getCallFrameSize());
11597fa27ce4SDimitry Andric
11607fa27ce4SDimitry Andric // Is there an indirect jump with jump table?
11617fa27ce4SDimitry Andric bool ChangedIndirectJump = false;
11627fa27ce4SDimitry Andric int JTI = findJumpTableIndex(*this);
11637fa27ce4SDimitry Andric if (JTI >= 0) {
11647fa27ce4SDimitry Andric MachineJumpTableInfo &MJTI = *MF->getJumpTableInfo();
11657fa27ce4SDimitry Andric MJTI.ReplaceMBBInJumpTable(JTI, Succ, NMBB);
11667fa27ce4SDimitry Andric ChangedIndirectJump = true;
11677fa27ce4SDimitry Andric }
11687fa27ce4SDimitry Andric
11695ca98fd9SDimitry Andric MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
1170eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
1171044eb2f6SDimitry Andric << " -- " << printMBBReference(*NMBB) << " -- "
1172044eb2f6SDimitry Andric << printMBBReference(*Succ) << '\n');
117366e41e3cSRoman Divacky
1174ac9a064cSDimitry Andric LiveIntervals *LIS = GET_RESULT(LiveIntervals, getLIS, );
1175ac9a064cSDimitry Andric SlotIndexes *Indexes = GET_RESULT(SlotIndexes, getSI, );
11764a16efa3SDimitry Andric if (LIS)
11774a16efa3SDimitry Andric LIS->insertMBBInMaps(NMBB);
11784a16efa3SDimitry Andric else if (Indexes)
11794a16efa3SDimitry Andric Indexes->insertMBBInMaps(NMBB);
11804a16efa3SDimitry Andric
118156fe8f14SDimitry Andric // On some targets like Mips, branches may kill virtual registers. Make sure
118256fe8f14SDimitry Andric // that LiveVariables is properly updated after updateTerminator replaces the
118356fe8f14SDimitry Andric // terminators.
1184ac9a064cSDimitry Andric LiveVariables *LV = GET_RESULT(LiveVariables, getLV, );
118556fe8f14SDimitry Andric
118656fe8f14SDimitry Andric // Collect a list of virtual registers killed by the terminators.
1187cfca06d7SDimitry Andric SmallVector<Register, 4> KilledRegs;
118856fe8f14SDimitry Andric if (LV)
118977fc4c14SDimitry Andric for (MachineInstr &MI :
119077fc4c14SDimitry Andric llvm::make_range(getFirstInstrTerminator(), instr_end())) {
11917fa27ce4SDimitry Andric for (MachineOperand &MO : MI.all_uses()) {
11927fa27ce4SDimitry Andric if (MO.getReg() == 0 || !MO.isKill() || MO.isUndef())
119356fe8f14SDimitry Andric continue;
1194c0981da4SDimitry Andric Register Reg = MO.getReg();
1195e3b55780SDimitry Andric if (Reg.isPhysical() || LV->getVarInfo(Reg).removeKill(MI)) {
119656fe8f14SDimitry Andric KilledRegs.push_back(Reg);
1197c0981da4SDimitry Andric LLVM_DEBUG(dbgs() << "Removing terminator kill: " << MI);
1198c0981da4SDimitry Andric MO.setIsKill(false);
119956fe8f14SDimitry Andric }
120056fe8f14SDimitry Andric }
120156fe8f14SDimitry Andric }
120256fe8f14SDimitry Andric
1203cfca06d7SDimitry Andric SmallVector<Register, 4> UsedRegs;
12044a16efa3SDimitry Andric if (LIS) {
120577fc4c14SDimitry Andric for (MachineInstr &MI :
120677fc4c14SDimitry Andric llvm::make_range(getFirstInstrTerminator(), instr_end())) {
120777fc4c14SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
1208c0981da4SDimitry Andric if (!MO.isReg() || MO.getReg() == 0)
12094a16efa3SDimitry Andric continue;
12104a16efa3SDimitry Andric
1211c0981da4SDimitry Andric Register Reg = MO.getReg();
1212b915e9e0SDimitry Andric if (!is_contained(UsedRegs, Reg))
12134a16efa3SDimitry Andric UsedRegs.push_back(Reg);
12144a16efa3SDimitry Andric }
12154a16efa3SDimitry Andric }
12164a16efa3SDimitry Andric }
12174a16efa3SDimitry Andric
121866e41e3cSRoman Divacky ReplaceUsesOfBlockWith(Succ, NMBB);
12194a16efa3SDimitry Andric
1220cfca06d7SDimitry Andric // Since we replaced all uses of Succ with NMBB, that should also be treated
1221cfca06d7SDimitry Andric // as the fallthrough successor
1222cfca06d7SDimitry Andric if (Succ == PrevFallthrough)
1223cfca06d7SDimitry Andric PrevFallthrough = NMBB;
12247fa27ce4SDimitry Andric
1225b1c73532SDimitry Andric if (!ChangedIndirectJump) {
1226b1c73532SDimitry Andric SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1227cfca06d7SDimitry Andric updateTerminator(PrevFallthrough);
12284a16efa3SDimitry Andric }
12294a16efa3SDimitry Andric
123066e41e3cSRoman Divacky // Insert unconditional "jump Succ" instruction in NMBB if necessary.
123166e41e3cSRoman Divacky NMBB->addSuccessor(Succ);
123266e41e3cSRoman Divacky if (!NMBB->isLayoutSuccessor(Succ)) {
1233b1c73532SDimitry Andric SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
123401095a5dSDimitry Andric SmallVector<MachineOperand, 4> Cond;
123501095a5dSDimitry Andric const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
1236ac9a064cSDimitry Andric
1237ac9a064cSDimitry Andric // In original 'this' BB, there must be a branch instruction targeting at
1238ac9a064cSDimitry Andric // Succ. We can not find it out since currently getBranchDestBlock was not
1239ac9a064cSDimitry Andric // implemented for all targets. However, if the merged DL has column or line
1240ac9a064cSDimitry Andric // number, the scope and non-zero column and line number is same with that
1241ac9a064cSDimitry Andric // branch instruction so we can safely use it.
1242ac9a064cSDimitry Andric DebugLoc DL, MergedDL = findBranchDebugLoc();
1243ac9a064cSDimitry Andric if (MergedDL && (MergedDL.getLine() || MergedDL.getCol()))
1244ac9a064cSDimitry Andric DL = MergedDL;
1245b915e9e0SDimitry Andric TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
124666e41e3cSRoman Divacky }
124766e41e3cSRoman Divacky
12481d5ae102SDimitry Andric // Fix PHI nodes in Succ so they refer to NMBB instead of this.
12491d5ae102SDimitry Andric Succ->replacePhiUsesWith(this, NMBB);
125066e41e3cSRoman Divacky
125130815c53SDimitry Andric // Inherit live-ins from the successor
1252dd58ef01SDimitry Andric for (const auto &LI : Succ->liveins())
1253dd58ef01SDimitry Andric NMBB->addLiveIn(LI);
125430815c53SDimitry Andric
125556fe8f14SDimitry Andric // Update LiveVariables.
125667c32a98SDimitry Andric const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
125756fe8f14SDimitry Andric if (LV) {
125856fe8f14SDimitry Andric // Restore kills of virtual registers that were killed by the terminators.
125956fe8f14SDimitry Andric while (!KilledRegs.empty()) {
1260cfca06d7SDimitry Andric Register Reg = KilledRegs.pop_back_val();
126163faed5bSDimitry Andric for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
1262e6d15924SDimitry Andric if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false))
126356fe8f14SDimitry Andric continue;
1264e3b55780SDimitry Andric if (Reg.isVirtual())
1265dd58ef01SDimitry Andric LV->getVarInfo(Reg).Kills.push_back(&*I);
1266eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
126756fe8f14SDimitry Andric break;
126856fe8f14SDimitry Andric }
126956fe8f14SDimitry Andric }
127056fe8f14SDimitry Andric // Update relevant live-through information.
1271cfca06d7SDimitry Andric if (LiveInSets != nullptr)
1272cfca06d7SDimitry Andric LV->addNewBlock(NMBB, this, Succ, *LiveInSets);
1273cfca06d7SDimitry Andric else
127466e41e3cSRoman Divacky LV->addNewBlock(NMBB, this, Succ);
127556fe8f14SDimitry Andric }
127666e41e3cSRoman Divacky
12774a16efa3SDimitry Andric if (LIS) {
12784a16efa3SDimitry Andric // After splitting the edge and updating SlotIndexes, live intervals may be
12794a16efa3SDimitry Andric // in one of two situations, depending on whether this block was the last in
1280dd58ef01SDimitry Andric // the function. If the original block was the last in the function, all
1281dd58ef01SDimitry Andric // live intervals will end prior to the beginning of the new split block. If
1282dd58ef01SDimitry Andric // the original block was not at the end of the function, all live intervals
1283dd58ef01SDimitry Andric // will extend to the end of the new split block.
12844a16efa3SDimitry Andric
12854a16efa3SDimitry Andric bool isLastMBB =
12865ca98fd9SDimitry Andric std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
12874a16efa3SDimitry Andric
12884a16efa3SDimitry Andric SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
12894a16efa3SDimitry Andric SlotIndex PrevIndex = StartIndex.getPrevSlot();
12904a16efa3SDimitry Andric SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
12914a16efa3SDimitry Andric
12924a16efa3SDimitry Andric // Find the registers used from NMBB in PHIs in Succ.
1293cfca06d7SDimitry Andric SmallSet<Register, 8> PHISrcRegs;
12944a16efa3SDimitry Andric for (MachineBasicBlock::instr_iterator
12954a16efa3SDimitry Andric I = Succ->instr_begin(), E = Succ->instr_end();
12964a16efa3SDimitry Andric I != E && I->isPHI(); ++I) {
12974a16efa3SDimitry Andric for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
12984a16efa3SDimitry Andric if (I->getOperand(ni+1).getMBB() == NMBB) {
12994a16efa3SDimitry Andric MachineOperand &MO = I->getOperand(ni);
13001d5ae102SDimitry Andric Register Reg = MO.getReg();
13014a16efa3SDimitry Andric PHISrcRegs.insert(Reg);
13024a16efa3SDimitry Andric if (MO.isUndef())
13034a16efa3SDimitry Andric continue;
13044a16efa3SDimitry Andric
13054a16efa3SDimitry Andric LiveInterval &LI = LIS->getInterval(Reg);
13064a16efa3SDimitry Andric VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1307dd58ef01SDimitry Andric assert(VNI &&
1308dd58ef01SDimitry Andric "PHI sources should be live out of their predecessors.");
1309f8af5cf6SDimitry Andric LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1310b1c73532SDimitry Andric for (auto &SR : LI.subranges())
1311b1c73532SDimitry Andric SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
13124a16efa3SDimitry Andric }
13134a16efa3SDimitry Andric }
13144a16efa3SDimitry Andric }
13154a16efa3SDimitry Andric
13164a16efa3SDimitry Andric MachineRegisterInfo *MRI = &getParent()->getRegInfo();
13174a16efa3SDimitry Andric for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1318cfca06d7SDimitry Andric Register Reg = Register::index2VirtReg(i);
13194a16efa3SDimitry Andric if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
13204a16efa3SDimitry Andric continue;
13214a16efa3SDimitry Andric
13224a16efa3SDimitry Andric LiveInterval &LI = LIS->getInterval(Reg);
13234a16efa3SDimitry Andric if (!LI.liveAt(PrevIndex))
13244a16efa3SDimitry Andric continue;
13254a16efa3SDimitry Andric
13264a16efa3SDimitry Andric bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
13274a16efa3SDimitry Andric if (isLiveOut && isLastMBB) {
13284a16efa3SDimitry Andric VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
13294a16efa3SDimitry Andric assert(VNI && "LiveInterval should have VNInfo where it is live.");
1330f8af5cf6SDimitry Andric LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1331b1c73532SDimitry Andric // Update subranges with live values
1332b1c73532SDimitry Andric for (auto &SR : LI.subranges()) {
1333b1c73532SDimitry Andric VNInfo *VNI = SR.getVNInfoAt(PrevIndex);
1334b1c73532SDimitry Andric if (VNI)
1335b1c73532SDimitry Andric SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1336b1c73532SDimitry Andric }
13374a16efa3SDimitry Andric } else if (!isLiveOut && !isLastMBB) {
1338f8af5cf6SDimitry Andric LI.removeSegment(StartIndex, EndIndex);
1339b1c73532SDimitry Andric for (auto &SR : LI.subranges())
1340b1c73532SDimitry Andric SR.removeSegment(StartIndex, EndIndex);
13414a16efa3SDimitry Andric }
13424a16efa3SDimitry Andric }
13434a16efa3SDimitry Andric
13444a16efa3SDimitry Andric // Update all intervals for registers whose uses may have been modified by
13454a16efa3SDimitry Andric // updateTerminator().
13464a16efa3SDimitry Andric LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
13474a16efa3SDimitry Andric }
13484a16efa3SDimitry Andric
1349ac9a064cSDimitry Andric if (auto *MDT = GET_RESULT(MachineDominatorTree, getDomTree, ))
135067c32a98SDimitry Andric MDT->recordSplitCriticalEdge(this, Succ, NMBB);
1351d39c594dSDimitry Andric
1352ac9a064cSDimitry Andric if (MachineLoopInfo *MLI = GET_RESULT(MachineLoop, getLI, Info))
135366e41e3cSRoman Divacky if (MachineLoop *TIL = MLI->getLoopFor(this)) {
135466e41e3cSRoman Divacky // If one or the other blocks were not in a loop, the new block is not
135566e41e3cSRoman Divacky // either, and thus LI doesn't need to be updated.
135666e41e3cSRoman Divacky if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
135766e41e3cSRoman Divacky if (TIL == DestLoop) {
135866e41e3cSRoman Divacky // Both in the same loop, the NMBB joins loop.
1359ac9a064cSDimitry Andric DestLoop->addBasicBlockToLoop(NMBB, *MLI);
136066e41e3cSRoman Divacky } else if (TIL->contains(DestLoop)) {
136166e41e3cSRoman Divacky // Edge from an outer loop to an inner loop. Add to the outer loop.
1362ac9a064cSDimitry Andric TIL->addBasicBlockToLoop(NMBB, *MLI);
136366e41e3cSRoman Divacky } else if (DestLoop->contains(TIL)) {
136466e41e3cSRoman Divacky // Edge from an inner loop to an outer loop. Add to the outer loop.
1365ac9a064cSDimitry Andric DestLoop->addBasicBlockToLoop(NMBB, *MLI);
136666e41e3cSRoman Divacky } else {
136766e41e3cSRoman Divacky // Edge from two loops with no containment relation. Because these
136866e41e3cSRoman Divacky // are natural loops, we know that the destination block must be the
136966e41e3cSRoman Divacky // header of its loop (adding a branch into a loop elsewhere would
137066e41e3cSRoman Divacky // create an irreducible loop).
137166e41e3cSRoman Divacky assert(DestLoop->getHeader() == Succ &&
137266e41e3cSRoman Divacky "Should not create irreducible loops!");
137366e41e3cSRoman Divacky if (MachineLoop *P = DestLoop->getParentLoop())
1374ac9a064cSDimitry Andric P->addBasicBlockToLoop(NMBB, *MLI);
137566e41e3cSRoman Divacky }
137666e41e3cSRoman Divacky }
137766e41e3cSRoman Divacky }
137866e41e3cSRoman Divacky
137966e41e3cSRoman Divacky return NMBB;
138066e41e3cSRoman Divacky }
138166e41e3cSRoman Divacky
canSplitCriticalEdge(const MachineBasicBlock * Succ) const138201095a5dSDimitry Andric bool MachineBasicBlock::canSplitCriticalEdge(
138301095a5dSDimitry Andric const MachineBasicBlock *Succ) const {
138401095a5dSDimitry Andric // Splitting the critical edge to a landing pad block is non-trivial. Don't do
138501095a5dSDimitry Andric // it in this generic function.
138601095a5dSDimitry Andric if (Succ->isEHPad())
138701095a5dSDimitry Andric return false;
138801095a5dSDimitry Andric
1389cfca06d7SDimitry Andric // Splitting the critical edge to a callbr's indirect block isn't advised.
1390cfca06d7SDimitry Andric // Don't do it in this generic function.
1391cfca06d7SDimitry Andric if (Succ->isInlineAsmBrIndirectTarget())
1392cfca06d7SDimitry Andric return false;
139301095a5dSDimitry Andric
1394cfca06d7SDimitry Andric const MachineFunction *MF = getParent();
139501095a5dSDimitry Andric // Performance might be harmed on HW that implements branching using exec mask
139601095a5dSDimitry Andric // where both sides of the branches are always executed.
139701095a5dSDimitry Andric if (MF->getTarget().requiresStructuredCFG())
139801095a5dSDimitry Andric return false;
139901095a5dSDimitry Andric
14007fa27ce4SDimitry Andric // Do we have an Indirect jump with a jumptable that we can rewrite?
14017fa27ce4SDimitry Andric int JTI = findJumpTableIndex(*this);
14027fa27ce4SDimitry Andric if (JTI >= 0 && !jumpTableHasOtherUses(*MF, *this, JTI))
14037fa27ce4SDimitry Andric return true;
14047fa27ce4SDimitry Andric
140501095a5dSDimitry Andric // We may need to update this's terminator, but we can't do that if
14067fa27ce4SDimitry Andric // analyzeBranch fails.
140701095a5dSDimitry Andric const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
140801095a5dSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
140901095a5dSDimitry Andric SmallVector<MachineOperand, 4> Cond;
141001095a5dSDimitry Andric // AnalyzeBanch should modify this, since we did not allow modification.
141101095a5dSDimitry Andric if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
141201095a5dSDimitry Andric /*AllowModify*/ false))
141301095a5dSDimitry Andric return false;
141401095a5dSDimitry Andric
141501095a5dSDimitry Andric // Avoid bugpoint weirdness: A block may end with a conditional branch but
141601095a5dSDimitry Andric // jumps to the same MBB is either case. We have duplicate CFG edges in that
141701095a5dSDimitry Andric // case that we can't handle. Since this never happens in properly optimized
141801095a5dSDimitry Andric // code, just skip those edges.
141901095a5dSDimitry Andric if (TBB && TBB == FBB) {
1420eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1421044eb2f6SDimitry Andric << printMBBReference(*this) << '\n');
142201095a5dSDimitry Andric return false;
142301095a5dSDimitry Andric }
142401095a5dSDimitry Andric return true;
142501095a5dSDimitry Andric }
142601095a5dSDimitry Andric
14274a16efa3SDimitry Andric /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
14284a16efa3SDimitry Andric /// neighboring instructions so the bundle won't be broken by removing MI.
unbundleSingleMI(MachineInstr * MI)14294a16efa3SDimitry Andric static void unbundleSingleMI(MachineInstr *MI) {
14304a16efa3SDimitry Andric // Removing the first instruction in a bundle.
14314a16efa3SDimitry Andric if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
14324a16efa3SDimitry Andric MI->unbundleFromSucc();
14334a16efa3SDimitry Andric // Removing the last instruction in a bundle.
14344a16efa3SDimitry Andric if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
14354a16efa3SDimitry Andric MI->unbundleFromPred();
14364a16efa3SDimitry Andric // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
14374a16efa3SDimitry Andric // are already fine.
143863faed5bSDimitry Andric }
143963faed5bSDimitry Andric
14404a16efa3SDimitry Andric MachineBasicBlock::instr_iterator
erase(MachineBasicBlock::instr_iterator I)14414a16efa3SDimitry Andric MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
1442dd58ef01SDimitry Andric unbundleSingleMI(&*I);
14434a16efa3SDimitry Andric return Insts.erase(I);
144463faed5bSDimitry Andric }
144563faed5bSDimitry Andric
remove_instr(MachineInstr * MI)14464a16efa3SDimitry Andric MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
14474a16efa3SDimitry Andric unbundleSingleMI(MI);
14484a16efa3SDimitry Andric MI->clearFlag(MachineInstr::BundledPred);
14494a16efa3SDimitry Andric MI->clearFlag(MachineInstr::BundledSucc);
14504a16efa3SDimitry Andric return Insts.remove(MI);
145163faed5bSDimitry Andric }
145263faed5bSDimitry Andric
14534a16efa3SDimitry Andric MachineBasicBlock::instr_iterator
insert(instr_iterator I,MachineInstr * MI)14544a16efa3SDimitry Andric MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
14554a16efa3SDimitry Andric assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
14564a16efa3SDimitry Andric "Cannot insert instruction with bundle flags");
14574a16efa3SDimitry Andric // Set the bundle flags when inserting inside a bundle.
14584a16efa3SDimitry Andric if (I != instr_end() && I->isBundledWithPred()) {
14594a16efa3SDimitry Andric MI->setFlag(MachineInstr::BundledPred);
14604a16efa3SDimitry Andric MI->setFlag(MachineInstr::BundledSucc);
146163faed5bSDimitry Andric }
14624a16efa3SDimitry Andric return Insts.insert(I, MI);
146363faed5bSDimitry Andric }
146463faed5bSDimitry Andric
1465dd58ef01SDimitry Andric /// This method unlinks 'this' from the containing function, and returns it, but
1466dd58ef01SDimitry Andric /// does not delete it.
removeFromParent()1467009b1c42SEd Schouten MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1468009b1c42SEd Schouten assert(getParent() && "Not embedded in a function!");
1469009b1c42SEd Schouten getParent()->remove(this);
1470009b1c42SEd Schouten return this;
1471009b1c42SEd Schouten }
1472009b1c42SEd Schouten
1473dd58ef01SDimitry Andric /// This method unlinks 'this' from the containing function, and deletes it.
eraseFromParent()1474009b1c42SEd Schouten void MachineBasicBlock::eraseFromParent() {
1475009b1c42SEd Schouten assert(getParent() && "Not embedded in a function!");
1476009b1c42SEd Schouten getParent()->erase(this);
1477009b1c42SEd Schouten }
1478009b1c42SEd Schouten
1479dd58ef01SDimitry Andric /// Given a machine basic block that branched to 'Old', change the code and CFG
1480dd58ef01SDimitry Andric /// so that it branches to 'New' instead.
ReplaceUsesOfBlockWith(MachineBasicBlock * Old,MachineBasicBlock * New)1481009b1c42SEd Schouten void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1482009b1c42SEd Schouten MachineBasicBlock *New) {
1483009b1c42SEd Schouten assert(Old != New && "Cannot replace self with self!");
1484009b1c42SEd Schouten
148563faed5bSDimitry Andric MachineBasicBlock::instr_iterator I = instr_end();
148663faed5bSDimitry Andric while (I != instr_begin()) {
1487009b1c42SEd Schouten --I;
148863faed5bSDimitry Andric if (!I->isTerminator()) break;
1489009b1c42SEd Schouten
1490009b1c42SEd Schouten // Scan the operands of this machine instruction, replacing any uses of Old
1491009b1c42SEd Schouten // with New.
1492ac9a064cSDimitry Andric for (MachineOperand &MO : I->operands())
1493ac9a064cSDimitry Andric if (MO.isMBB() && MO.getMBB() == Old)
1494ac9a064cSDimitry Andric MO.setMBB(New);
1495009b1c42SEd Schouten }
1496009b1c42SEd Schouten
1497009b1c42SEd Schouten // Update the successor information.
1498411bd29eSDimitry Andric replaceSuccessor(Old, New);
1499009b1c42SEd Schouten }
1500009b1c42SEd Schouten
replacePhiUsesWith(MachineBasicBlock * Old,MachineBasicBlock * New)15011d5ae102SDimitry Andric void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old,
15021d5ae102SDimitry Andric MachineBasicBlock *New) {
15031d5ae102SDimitry Andric for (MachineInstr &MI : phis())
15041d5ae102SDimitry Andric for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
15051d5ae102SDimitry Andric MachineOperand &MO = MI.getOperand(i);
15061d5ae102SDimitry Andric if (MO.getMBB() == Old)
15071d5ae102SDimitry Andric MO.setMBB(New);
15081d5ae102SDimitry Andric }
15091d5ae102SDimitry Andric }
15101d5ae102SDimitry Andric
15117fa27ce4SDimitry Andric /// Find the next valid DebugLoc starting at MBBI, skipping any debug
1512dd58ef01SDimitry Andric /// instructions. Return UnknownLoc if there is none.
1513989df958SRoman Divacky DebugLoc
findDebugLoc(instr_iterator MBBI)151463faed5bSDimitry Andric MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1515989df958SRoman Divacky // Skip debug declarations, we don't want a DebugLoc from them.
1516b915e9e0SDimitry Andric MBBI = skipDebugInstructionsForward(MBBI, instr_end());
1517b915e9e0SDimitry Andric if (MBBI != instr_end())
1518b915e9e0SDimitry Andric return MBBI->getDebugLoc();
1519b915e9e0SDimitry Andric return {};
1520989df958SRoman Divacky }
1521989df958SRoman Divacky
rfindDebugLoc(reverse_instr_iterator MBBI)1522344a3780SDimitry Andric DebugLoc MachineBasicBlock::rfindDebugLoc(reverse_instr_iterator MBBI) {
15237fa27ce4SDimitry Andric if (MBBI == instr_rend())
15247fa27ce4SDimitry Andric return findDebugLoc(instr_begin());
1525344a3780SDimitry Andric // Skip debug declarations, we don't want a DebugLoc from them.
1526344a3780SDimitry Andric MBBI = skipDebugInstructionsBackward(MBBI, instr_rbegin());
1527344a3780SDimitry Andric if (!MBBI->isDebugInstr())
1528344a3780SDimitry Andric return MBBI->getDebugLoc();
1529344a3780SDimitry Andric return {};
1530344a3780SDimitry Andric }
1531344a3780SDimitry Andric
15327fa27ce4SDimitry Andric /// Find the previous valid DebugLoc preceding MBBI, skipping any debug
1533eb11fae6SDimitry Andric /// instructions. Return UnknownLoc if there is none.
findPrevDebugLoc(instr_iterator MBBI)1534eb11fae6SDimitry Andric DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) {
15357fa27ce4SDimitry Andric if (MBBI == instr_begin())
15367fa27ce4SDimitry Andric return {};
1537cfca06d7SDimitry Andric // Skip debug instructions, we don't want a DebugLoc from them.
1538cfca06d7SDimitry Andric MBBI = prev_nodbg(MBBI, instr_begin());
15397fa27ce4SDimitry Andric if (!MBBI->isDebugInstr())
15407fa27ce4SDimitry Andric return MBBI->getDebugLoc();
1541eb11fae6SDimitry Andric return {};
1542eb11fae6SDimitry Andric }
1543eb11fae6SDimitry Andric
rfindPrevDebugLoc(reverse_instr_iterator MBBI)1544344a3780SDimitry Andric DebugLoc MachineBasicBlock::rfindPrevDebugLoc(reverse_instr_iterator MBBI) {
1545344a3780SDimitry Andric if (MBBI == instr_rend())
1546344a3780SDimitry Andric return {};
1547344a3780SDimitry Andric // Skip debug declarations, we don't want a DebugLoc from them.
1548344a3780SDimitry Andric MBBI = next_nodbg(MBBI, instr_rend());
1549344a3780SDimitry Andric if (MBBI != instr_rend())
1550344a3780SDimitry Andric return MBBI->getDebugLoc();
1551344a3780SDimitry Andric return {};
1552344a3780SDimitry Andric }
1553344a3780SDimitry Andric
155471d5a254SDimitry Andric /// Find and return the merged DebugLoc of the branch instructions of the block.
155571d5a254SDimitry Andric /// Return UnknownLoc if there is none.
155671d5a254SDimitry Andric DebugLoc
findBranchDebugLoc()155771d5a254SDimitry Andric MachineBasicBlock::findBranchDebugLoc() {
155871d5a254SDimitry Andric DebugLoc DL;
155971d5a254SDimitry Andric auto TI = getFirstTerminator();
156071d5a254SDimitry Andric while (TI != end() && !TI->isBranch())
156171d5a254SDimitry Andric ++TI;
156271d5a254SDimitry Andric
156371d5a254SDimitry Andric if (TI != end()) {
156471d5a254SDimitry Andric DL = TI->getDebugLoc();
156571d5a254SDimitry Andric for (++TI ; TI != end() ; ++TI)
156671d5a254SDimitry Andric if (TI->isBranch())
156771d5a254SDimitry Andric DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
156871d5a254SDimitry Andric }
156971d5a254SDimitry Andric return DL;
157071d5a254SDimitry Andric }
157171d5a254SDimitry Andric
1572dd58ef01SDimitry Andric /// Return probability of the edge from this block to MBB.
1573dd58ef01SDimitry Andric BranchProbability
getSuccProbability(const_succ_iterator Succ) const1574dd58ef01SDimitry Andric MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
1575dd58ef01SDimitry Andric if (Probs.empty())
1576dd58ef01SDimitry Andric return BranchProbability(1, succ_size());
1577411bd29eSDimitry Andric
1578dd58ef01SDimitry Andric const auto &Prob = *getProbabilityIterator(Succ);
1579dd58ef01SDimitry Andric if (Prob.isUnknown()) {
1580dd58ef01SDimitry Andric // For unknown probabilities, collect the sum of all known ones, and evenly
1581dd58ef01SDimitry Andric // ditribute the complemental of the sum to each unknown probability.
1582dd58ef01SDimitry Andric unsigned KnownProbNum = 0;
1583dd58ef01SDimitry Andric auto Sum = BranchProbability::getZero();
15844b4fe385SDimitry Andric for (const auto &P : Probs) {
1585dd58ef01SDimitry Andric if (!P.isUnknown()) {
1586dd58ef01SDimitry Andric Sum += P;
1587dd58ef01SDimitry Andric KnownProbNum++;
1588dd58ef01SDimitry Andric }
1589dd58ef01SDimitry Andric }
1590dd58ef01SDimitry Andric return Sum.getCompl() / (Probs.size() - KnownProbNum);
1591dd58ef01SDimitry Andric } else
1592dd58ef01SDimitry Andric return Prob;
1593411bd29eSDimitry Andric }
1594411bd29eSDimitry Andric
1595dd58ef01SDimitry Andric /// Set successor probability of a given iterator.
setSuccProbability(succ_iterator I,BranchProbability Prob)1596dd58ef01SDimitry Andric void MachineBasicBlock::setSuccProbability(succ_iterator I,
1597dd58ef01SDimitry Andric BranchProbability Prob) {
1598dd58ef01SDimitry Andric assert(!Prob.isUnknown());
1599dd58ef01SDimitry Andric if (Probs.empty())
16005ca98fd9SDimitry Andric return;
1601dd58ef01SDimitry Andric *getProbabilityIterator(I) = Prob;
16025ca98fd9SDimitry Andric }
16035ca98fd9SDimitry Andric
1604dd58ef01SDimitry Andric /// Return probability iterator corresonding to the I successor iterator
1605dd58ef01SDimitry Andric MachineBasicBlock::const_probability_iterator
getProbabilityIterator(MachineBasicBlock::const_succ_iterator I) const1606dd58ef01SDimitry Andric MachineBasicBlock::getProbabilityIterator(
1607dd58ef01SDimitry Andric MachineBasicBlock::const_succ_iterator I) const {
1608dd58ef01SDimitry Andric assert(Probs.size() == Successors.size() && "Async probability list!");
160963faed5bSDimitry Andric const size_t index = std::distance(Successors.begin(), I);
1610dd58ef01SDimitry Andric assert(index < Probs.size() && "Not a current successor!");
1611dd58ef01SDimitry Andric return Probs.begin() + index;
1612dd58ef01SDimitry Andric }
1613dd58ef01SDimitry Andric
1614dd58ef01SDimitry Andric /// Return probability iterator corresonding to the I successor iterator.
1615dd58ef01SDimitry Andric MachineBasicBlock::probability_iterator
getProbabilityIterator(MachineBasicBlock::succ_iterator I)1616dd58ef01SDimitry Andric MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1617dd58ef01SDimitry Andric assert(Probs.size() == Successors.size() && "Async probability list!");
1618dd58ef01SDimitry Andric const size_t index = std::distance(Successors.begin(), I);
1619dd58ef01SDimitry Andric assert(index < Probs.size() && "Not a current successor!");
1620dd58ef01SDimitry Andric return Probs.begin() + index;
162163faed5bSDimitry Andric }
162263faed5bSDimitry Andric
1623522600a2SDimitry Andric /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1624522600a2SDimitry Andric /// as of just before "MI".
1625522600a2SDimitry Andric ///
1626522600a2SDimitry Andric /// Search is localised to a neighborhood of
1627522600a2SDimitry Andric /// Neighborhood instructions before (searching for defs or kills) and N
1628522600a2SDimitry Andric /// instructions after (searching just for defs) MI.
1629522600a2SDimitry Andric MachineBasicBlock::LivenessQueryResult
computeRegisterLiveness(const TargetRegisterInfo * TRI,MCRegister Reg,const_iterator Before,unsigned Neighborhood) const1630522600a2SDimitry Andric MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1631cfca06d7SDimitry Andric MCRegister Reg, const_iterator Before,
16325a5ac124SDimitry Andric unsigned Neighborhood) const {
1633522600a2SDimitry Andric unsigned N = Neighborhood;
1634522600a2SDimitry Andric
1635d8e91e46SDimitry Andric // Try searching forwards from Before, looking for reads or defs.
16365a5ac124SDimitry Andric const_iterator I(Before);
1637d8e91e46SDimitry Andric for (; I != end() && N > 0; ++I) {
1638344a3780SDimitry Andric if (I->isDebugOrPseudoInstr())
1639d8e91e46SDimitry Andric continue;
1640d8e91e46SDimitry Andric
1641d8e91e46SDimitry Andric --N;
1642d8e91e46SDimitry Andric
1643706b4fc4SDimitry Andric PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1644d8e91e46SDimitry Andric
1645d8e91e46SDimitry Andric // Register is live when we read it here.
1646d8e91e46SDimitry Andric if (Info.Read)
1647d8e91e46SDimitry Andric return LQR_Live;
1648d8e91e46SDimitry Andric // Register is dead if we can fully overwrite or clobber it here.
1649d8e91e46SDimitry Andric if (Info.FullyDefined || Info.Clobbered)
1650d8e91e46SDimitry Andric return LQR_Dead;
1651d8e91e46SDimitry Andric }
1652d8e91e46SDimitry Andric
1653d8e91e46SDimitry Andric // If we reached the end, it is safe to clobber Reg at the end of a block of
1654d8e91e46SDimitry Andric // no successor has it live in.
1655d8e91e46SDimitry Andric if (I == end()) {
1656d8e91e46SDimitry Andric for (MachineBasicBlock *S : successors()) {
1657d8e91e46SDimitry Andric for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
1658d8e91e46SDimitry Andric if (TRI->regsOverlap(LI.PhysReg, Reg))
1659d8e91e46SDimitry Andric return LQR_Live;
1660d8e91e46SDimitry Andric }
1661d8e91e46SDimitry Andric }
1662d8e91e46SDimitry Andric
1663d8e91e46SDimitry Andric return LQR_Dead;
1664d8e91e46SDimitry Andric }
1665d8e91e46SDimitry Andric
1666d8e91e46SDimitry Andric
1667d8e91e46SDimitry Andric N = Neighborhood;
1668d8e91e46SDimitry Andric
1669d8e91e46SDimitry Andric // Start by searching backwards from Before, looking for kills, reads or defs.
1670d8e91e46SDimitry Andric I = const_iterator(Before);
1671522600a2SDimitry Andric // If this is the first insn in the block, don't search backwards.
16725a5ac124SDimitry Andric if (I != begin()) {
1673522600a2SDimitry Andric do {
1674522600a2SDimitry Andric --I;
1675522600a2SDimitry Andric
1676344a3780SDimitry Andric if (I->isDebugOrPseudoInstr())
1677d8e91e46SDimitry Andric continue;
1678d8e91e46SDimitry Andric
1679d8e91e46SDimitry Andric --N;
1680d8e91e46SDimitry Andric
1681706b4fc4SDimitry Andric PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1682522600a2SDimitry Andric
1683dd58ef01SDimitry Andric // Defs happen after uses so they take precedence if both are present.
16844a16efa3SDimitry Andric
1685dd58ef01SDimitry Andric // Register is dead after a dead def of the full register.
1686dd58ef01SDimitry Andric if (Info.DeadDef)
1687522600a2SDimitry Andric return LQR_Dead;
1688dd58ef01SDimitry Andric // Register is (at least partially) live after a def.
168901095a5dSDimitry Andric if (Info.Defined) {
169001095a5dSDimitry Andric if (!Info.PartialDeadDef)
1691dd58ef01SDimitry Andric return LQR_Live;
169201095a5dSDimitry Andric // As soon as we saw a partial definition (dead or not),
169301095a5dSDimitry Andric // we cannot tell if the value is partial live without
169401095a5dSDimitry Andric // tracking the lanemasks. We are not going to do this,
169501095a5dSDimitry Andric // so fall back on the remaining of the analysis.
169601095a5dSDimitry Andric break;
169701095a5dSDimitry Andric }
1698dd58ef01SDimitry Andric // Register is dead after a full kill or clobber and no def.
1699dd58ef01SDimitry Andric if (Info.Killed || Info.Clobbered)
1700dd58ef01SDimitry Andric return LQR_Dead;
1701dd58ef01SDimitry Andric // Register must be live if we read it.
1702dd58ef01SDimitry Andric if (Info.Read)
1703dd58ef01SDimitry Andric return LQR_Live;
1704d8e91e46SDimitry Andric
1705d8e91e46SDimitry Andric } while (I != begin() && N > 0);
1706522600a2SDimitry Andric }
1707522600a2SDimitry Andric
1708706b4fc4SDimitry Andric // If all the instructions before this in the block are debug instructions,
1709706b4fc4SDimitry Andric // skip over them.
1710344a3780SDimitry Andric while (I != begin() && std::prev(I)->isDebugOrPseudoInstr())
1711706b4fc4SDimitry Andric --I;
1712706b4fc4SDimitry Andric
1713522600a2SDimitry Andric // Did we get to the start of the block?
17145a5ac124SDimitry Andric if (I == begin()) {
1715522600a2SDimitry Andric // If so, the register's state is definitely defined by the live-in state.
1716d8e91e46SDimitry Andric for (const MachineBasicBlock::RegisterMaskPair &LI : liveins())
1717d8e91e46SDimitry Andric if (TRI->regsOverlap(LI.PhysReg, Reg))
1718dd58ef01SDimitry Andric return LQR_Live;
1719522600a2SDimitry Andric
1720522600a2SDimitry Andric return LQR_Dead;
1721522600a2SDimitry Andric }
1722522600a2SDimitry Andric
1723522600a2SDimitry Andric // At this point we have no idea of the liveness of the register.
1724522600a2SDimitry Andric return LQR_Unknown;
1725522600a2SDimitry Andric }
1726dd58ef01SDimitry Andric
1727dd58ef01SDimitry Andric const uint32_t *
getBeginClobberMask(const TargetRegisterInfo * TRI) const1728dd58ef01SDimitry Andric MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
1729dd58ef01SDimitry Andric // EH funclet entry does not preserve any registers.
1730dd58ef01SDimitry Andric return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1731dd58ef01SDimitry Andric }
1732dd58ef01SDimitry Andric
1733dd58ef01SDimitry Andric const uint32_t *
getEndClobberMask(const TargetRegisterInfo * TRI) const1734dd58ef01SDimitry Andric MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
1735dd58ef01SDimitry Andric // If we see a return block with successors, this must be a funclet return,
1736dd58ef01SDimitry Andric // which does not preserve any registers. If there are no successors, we don't
1737dd58ef01SDimitry Andric // care what kind of return it is, putting a mask after it is a no-op.
1738dd58ef01SDimitry Andric return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1739dd58ef01SDimitry Andric }
1740b915e9e0SDimitry Andric
clearLiveIns()1741b915e9e0SDimitry Andric void MachineBasicBlock::clearLiveIns() {
1742b915e9e0SDimitry Andric LiveIns.clear();
1743b915e9e0SDimitry Andric }
17447e7b6700SDimitry Andric
clearLiveIns(std::vector<RegisterMaskPair> & OldLiveIns)1745ac9a064cSDimitry Andric void MachineBasicBlock::clearLiveIns(
1746ac9a064cSDimitry Andric std::vector<RegisterMaskPair> &OldLiveIns) {
1747ac9a064cSDimitry Andric assert(OldLiveIns.empty() && "Vector must be empty");
1748ac9a064cSDimitry Andric std::swap(LiveIns, OldLiveIns);
1749ac9a064cSDimitry Andric }
1750ac9a064cSDimitry Andric
livein_begin() const17517e7b6700SDimitry Andric MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
17527e7b6700SDimitry Andric assert(getParent()->getProperties().hasProperty(
17537e7b6700SDimitry Andric MachineFunctionProperties::Property::TracksLiveness) &&
17547e7b6700SDimitry Andric "Liveness information is accurate");
17557e7b6700SDimitry Andric return LiveIns.begin();
17567e7b6700SDimitry Andric }
1757cfca06d7SDimitry Andric
liveout_begin() const1758344a3780SDimitry Andric MachineBasicBlock::liveout_iterator MachineBasicBlock::liveout_begin() const {
1759344a3780SDimitry Andric const MachineFunction &MF = *getParent();
1760344a3780SDimitry Andric assert(MF.getProperties().hasProperty(
1761344a3780SDimitry Andric MachineFunctionProperties::Property::TracksLiveness) &&
1762344a3780SDimitry Andric "Liveness information is accurate");
1763344a3780SDimitry Andric
1764344a3780SDimitry Andric const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1765344a3780SDimitry Andric MCPhysReg ExceptionPointer = 0, ExceptionSelector = 0;
1766344a3780SDimitry Andric if (MF.getFunction().hasPersonalityFn()) {
1767344a3780SDimitry Andric auto PersonalityFn = MF.getFunction().getPersonalityFn();
1768344a3780SDimitry Andric ExceptionPointer = TLI.getExceptionPointerRegister(PersonalityFn);
1769344a3780SDimitry Andric ExceptionSelector = TLI.getExceptionSelectorRegister(PersonalityFn);
1770344a3780SDimitry Andric }
1771344a3780SDimitry Andric
1772344a3780SDimitry Andric return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false);
1773344a3780SDimitry Andric }
1774344a3780SDimitry Andric
sizeWithoutDebugLargerThan(unsigned Limit) const1775145449b1SDimitry Andric bool MachineBasicBlock::sizeWithoutDebugLargerThan(unsigned Limit) const {
1776145449b1SDimitry Andric unsigned Cntr = 0;
1777145449b1SDimitry Andric auto R = instructionsWithoutDebug(begin(), end());
1778145449b1SDimitry Andric for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1779145449b1SDimitry Andric if (++Cntr > Limit)
1780145449b1SDimitry Andric return true;
1781145449b1SDimitry Andric }
1782145449b1SDimitry Andric return false;
1783145449b1SDimitry Andric }
1784145449b1SDimitry Andric
1785cfca06d7SDimitry Andric const MBBSectionID MBBSectionID::ColdSectionID(MBBSectionID::SectionType::Cold);
1786cfca06d7SDimitry Andric const MBBSectionID
1787cfca06d7SDimitry Andric MBBSectionID::ExceptionSectionID(MBBSectionID::SectionType::Exception);
1788