10b57cec5SDimitry Andric //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Collect the sequence of machine instructions for a basic block.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
14bdd1243dSDimitry Andric #include "llvm/ADT/STLExtras.h"
15*fe013be4SDimitry Andric #include "llvm/ADT/StringExtras.h"
160b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
1781ad6265SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/LiveVariables.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
22*fe013be4SDimitry Andric #include "llvm/CodeGen/MachineJumpTableInfo.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
27fe6060f1SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
300b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
310b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
320b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
330b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
340b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
350b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
360b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
370b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
380b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
390b57cec5SDimitry Andric #include <algorithm>
40bdd1243dSDimitry Andric #include <cmath>
410b57cec5SDimitry Andric using namespace llvm;
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric #define DEBUG_TYPE "codegen"
440b57cec5SDimitry Andric 
458bcb0991SDimitry Andric static cl::opt<bool> PrintSlotIndexes(
468bcb0991SDimitry Andric     "print-slotindexes",
478bcb0991SDimitry Andric     cl::desc("When printing machine IR, annotate instructions and blocks with "
488bcb0991SDimitry Andric              "SlotIndexes when available"),
498bcb0991SDimitry Andric     cl::init(true), cl::Hidden);
508bcb0991SDimitry Andric 
510b57cec5SDimitry Andric MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
520b57cec5SDimitry Andric     : BB(B), Number(-1), xParent(&MF) {
530b57cec5SDimitry Andric   Insts.Parent = this;
540b57cec5SDimitry Andric   if (B)
550b57cec5SDimitry Andric     IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight();
560b57cec5SDimitry Andric }
570b57cec5SDimitry Andric 
5881ad6265SDimitry Andric MachineBasicBlock::~MachineBasicBlock() = default;
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric /// Return the MCSymbol for this basic block.
610b57cec5SDimitry Andric MCSymbol *MachineBasicBlock::getSymbol() const {
620b57cec5SDimitry Andric   if (!CachedMCSymbol) {
630b57cec5SDimitry Andric     const MachineFunction *MF = getParent();
640b57cec5SDimitry Andric     MCContext &Ctx = MF->getContext();
655ffd83dbSDimitry Andric 
66e8d8bef9SDimitry Andric     // We emit a non-temporary symbol -- with a descriptive name -- if it begins
67e8d8bef9SDimitry Andric     // a section (with basic block sections). Otherwise we fall back to use temp
68e8d8bef9SDimitry Andric     // label.
69e8d8bef9SDimitry Andric     if (MF->hasBBSections() && isBeginSection()) {
705ffd83dbSDimitry Andric       SmallString<5> Suffix;
715ffd83dbSDimitry Andric       if (SectionID == MBBSectionID::ColdSectionID) {
725ffd83dbSDimitry Andric         Suffix += ".cold";
735ffd83dbSDimitry Andric       } else if (SectionID == MBBSectionID::ExceptionSectionID) {
745ffd83dbSDimitry Andric         Suffix += ".eh";
755ffd83dbSDimitry Andric       } else {
76e8d8bef9SDimitry Andric         // For symbols that represent basic block sections, we add ".__part." to
77e8d8bef9SDimitry Andric         // allow tools like symbolizers to know that this represents a part of
78e8d8bef9SDimitry Andric         // the original function.
79e8d8bef9SDimitry Andric         Suffix = (Suffix + Twine(".__part.") + Twine(SectionID.Number)).str();
805ffd83dbSDimitry Andric       }
815ffd83dbSDimitry Andric       CachedMCSymbol = Ctx.getOrCreateSymbol(MF->getName() + Suffix);
825ffd83dbSDimitry Andric     } else {
83e8d8bef9SDimitry Andric       const StringRef Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
840b57cec5SDimitry Andric       CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
850b57cec5SDimitry Andric                                              Twine(MF->getFunctionNumber()) +
860b57cec5SDimitry Andric                                              "_" + Twine(getNumber()));
870b57cec5SDimitry Andric     }
885ffd83dbSDimitry Andric   }
890b57cec5SDimitry Andric   return CachedMCSymbol;
900b57cec5SDimitry Andric }
910b57cec5SDimitry Andric 
92fe6060f1SDimitry Andric MCSymbol *MachineBasicBlock::getEHCatchretSymbol() const {
93fe6060f1SDimitry Andric   if (!CachedEHCatchretMCSymbol) {
94fe6060f1SDimitry Andric     const MachineFunction *MF = getParent();
95fe6060f1SDimitry Andric     SmallString<128> SymbolName;
96fe6060f1SDimitry Andric     raw_svector_ostream(SymbolName)
97fe6060f1SDimitry Andric         << "$ehgcr_" << MF->getFunctionNumber() << '_' << getNumber();
98fe6060f1SDimitry Andric     CachedEHCatchretMCSymbol = MF->getContext().getOrCreateSymbol(SymbolName);
99fe6060f1SDimitry Andric   }
100fe6060f1SDimitry Andric   return CachedEHCatchretMCSymbol;
101fe6060f1SDimitry Andric }
102fe6060f1SDimitry Andric 
103e8d8bef9SDimitry Andric MCSymbol *MachineBasicBlock::getEndSymbol() const {
104e8d8bef9SDimitry Andric   if (!CachedEndMCSymbol) {
105e8d8bef9SDimitry Andric     const MachineFunction *MF = getParent();
106e8d8bef9SDimitry Andric     MCContext &Ctx = MF->getContext();
107e8d8bef9SDimitry Andric     auto Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
108e8d8bef9SDimitry Andric     CachedEndMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB_END" +
109e8d8bef9SDimitry Andric                                               Twine(MF->getFunctionNumber()) +
110e8d8bef9SDimitry Andric                                               "_" + Twine(getNumber()));
111e8d8bef9SDimitry Andric   }
112e8d8bef9SDimitry Andric   return CachedEndMCSymbol;
113e8d8bef9SDimitry Andric }
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
1160b57cec5SDimitry Andric   MBB.print(OS);
1170b57cec5SDimitry Andric   return OS;
1180b57cec5SDimitry Andric }
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric Printable llvm::printMBBReference(const MachineBasicBlock &MBB) {
1210b57cec5SDimitry Andric   return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
1220b57cec5SDimitry Andric }
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric /// When an MBB is added to an MF, we need to update the parent pointer of the
1250b57cec5SDimitry Andric /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
1260b57cec5SDimitry Andric /// operand list for registers.
1270b57cec5SDimitry Andric ///
1280b57cec5SDimitry Andric /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
1290b57cec5SDimitry Andric /// gets the next available unique MBB number. If it is removed from a
1300b57cec5SDimitry Andric /// MachineFunction, it goes back to being #-1.
1310b57cec5SDimitry Andric void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
1320b57cec5SDimitry Andric     MachineBasicBlock *N) {
1330b57cec5SDimitry Andric   MachineFunction &MF = *N->getParent();
1340b57cec5SDimitry Andric   N->Number = MF.addToMBBNumbering(N);
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric   // Make sure the instructions have their operands in the reginfo lists.
1370b57cec5SDimitry Andric   MachineRegisterInfo &RegInfo = MF.getRegInfo();
138349cc55cSDimitry Andric   for (MachineInstr &MI : N->instrs())
13981ad6265SDimitry Andric     MI.addRegOperandsToUseLists(RegInfo);
1400b57cec5SDimitry Andric }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
1430b57cec5SDimitry Andric     MachineBasicBlock *N) {
1440b57cec5SDimitry Andric   N->getParent()->removeFromMBBNumbering(N->Number);
1450b57cec5SDimitry Andric   N->Number = -1;
1460b57cec5SDimitry Andric }
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric /// When we add an instruction to a basic block list, we update its parent
1490b57cec5SDimitry Andric /// pointer and add its operands from reg use/def lists if appropriate.
1500b57cec5SDimitry Andric void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
1510b57cec5SDimitry Andric   assert(!N->getParent() && "machine instruction already in a basic block");
1520b57cec5SDimitry Andric   N->setParent(Parent);
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   // Add the instruction's register operands to their corresponding
1550b57cec5SDimitry Andric   // use/def lists.
1560b57cec5SDimitry Andric   MachineFunction *MF = Parent->getParent();
15781ad6265SDimitry Andric   N->addRegOperandsToUseLists(MF->getRegInfo());
1580b57cec5SDimitry Andric   MF->handleInsertion(*N);
1590b57cec5SDimitry Andric }
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric /// When we remove an instruction from a basic block list, we update its parent
1620b57cec5SDimitry Andric /// pointer and remove its operands from reg use/def lists if appropriate.
1630b57cec5SDimitry Andric void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
1640b57cec5SDimitry Andric   assert(N->getParent() && "machine instruction not in a basic block");
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   // Remove from the use/def lists.
1670b57cec5SDimitry Andric   if (MachineFunction *MF = N->getMF()) {
1680b57cec5SDimitry Andric     MF->handleRemoval(*N);
16981ad6265SDimitry Andric     N->removeRegOperandsFromUseLists(MF->getRegInfo());
1700b57cec5SDimitry Andric   }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   N->setParent(nullptr);
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric /// When moving a range of instructions from one MBB list to another, we need to
1760b57cec5SDimitry Andric /// update the parent pointers and the use/def lists.
1770b57cec5SDimitry Andric void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
1780b57cec5SDimitry Andric                                                        instr_iterator First,
1790b57cec5SDimitry Andric                                                        instr_iterator Last) {
1800b57cec5SDimitry Andric   assert(Parent->getParent() == FromList.Parent->getParent() &&
1810b57cec5SDimitry Andric          "cannot transfer MachineInstrs between MachineFunctions");
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric   // If it's within the same BB, there's nothing to do.
1840b57cec5SDimitry Andric   if (this == &FromList)
1850b57cec5SDimitry Andric     return;
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   assert(Parent != FromList.Parent && "Two lists have the same parent?");
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   // If splicing between two blocks within the same function, just update the
1900b57cec5SDimitry Andric   // parent pointers.
1910b57cec5SDimitry Andric   for (; First != Last; ++First)
1920b57cec5SDimitry Andric     First->setParent(Parent);
1930b57cec5SDimitry Andric }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
1960b57cec5SDimitry Andric   assert(!MI->getParent() && "MI is still in a block!");
1970eae32dcSDimitry Andric   Parent->getParent()->deleteMachineInstr(MI);
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
2010b57cec5SDimitry Andric   instr_iterator I = instr_begin(), E = instr_end();
2020b57cec5SDimitry Andric   while (I != E && I->isPHI())
2030b57cec5SDimitry Andric     ++I;
2040b57cec5SDimitry Andric   assert((I == E || !I->isInsideBundle()) &&
2050b57cec5SDimitry Andric          "First non-phi MI cannot be inside a bundle!");
2060b57cec5SDimitry Andric   return I;
2070b57cec5SDimitry Andric }
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric MachineBasicBlock::iterator
2100b57cec5SDimitry Andric MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
2110b57cec5SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric   iterator E = end();
2140b57cec5SDimitry Andric   while (I != E && (I->isPHI() || I->isPosition() ||
2150b57cec5SDimitry Andric                     TII->isBasicBlockPrologue(*I)))
2160b57cec5SDimitry Andric     ++I;
2170b57cec5SDimitry Andric   // FIXME: This needs to change if we wish to bundle labels
2180b57cec5SDimitry Andric   // inside the bundle.
2190b57cec5SDimitry Andric   assert((I == E || !I->isInsideBundle()) &&
2200b57cec5SDimitry Andric          "First non-phi / non-label instruction is inside a bundle!");
2210b57cec5SDimitry Andric   return I;
2220b57cec5SDimitry Andric }
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric MachineBasicBlock::iterator
225fe6060f1SDimitry Andric MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I,
226fe6060f1SDimitry Andric                                           bool SkipPseudoOp) {
2270b57cec5SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   iterator E = end();
2300b57cec5SDimitry Andric   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() ||
231fe6060f1SDimitry Andric                     (SkipPseudoOp && I->isPseudoProbe()) ||
2320b57cec5SDimitry Andric                     TII->isBasicBlockPrologue(*I)))
2330b57cec5SDimitry Andric     ++I;
2340b57cec5SDimitry Andric   // FIXME: This needs to change if we wish to bundle labels / dbg_values
2350b57cec5SDimitry Andric   // inside the bundle.
2360b57cec5SDimitry Andric   assert((I == E || !I->isInsideBundle()) &&
2370b57cec5SDimitry Andric          "First non-phi / non-label / non-debug "
2380b57cec5SDimitry Andric          "instruction is inside a bundle!");
2390b57cec5SDimitry Andric   return I;
2400b57cec5SDimitry Andric }
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
2430b57cec5SDimitry Andric   iterator B = begin(), E = end(), I = E;
2440b57cec5SDimitry Andric   while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
2450b57cec5SDimitry Andric     ; /*noop */
2460b57cec5SDimitry Andric   while (I != E && !I->isTerminator())
2470b57cec5SDimitry Andric     ++I;
2480b57cec5SDimitry Andric   return I;
2490b57cec5SDimitry Andric }
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
2520b57cec5SDimitry Andric   instr_iterator B = instr_begin(), E = instr_end(), I = E;
2530b57cec5SDimitry Andric   while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
2540b57cec5SDimitry Andric     ; /*noop */
2550b57cec5SDimitry Andric   while (I != E && !I->isTerminator())
2560b57cec5SDimitry Andric     ++I;
2570b57cec5SDimitry Andric   return I;
2580b57cec5SDimitry Andric }
2590b57cec5SDimitry Andric 
260bdd1243dSDimitry Andric MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminatorForward() {
261bdd1243dSDimitry Andric   return find_if(instrs(), [](auto &II) { return II.isTerminator(); });
262bdd1243dSDimitry Andric }
263bdd1243dSDimitry Andric 
264fe6060f1SDimitry Andric MachineBasicBlock::iterator
265fe6060f1SDimitry Andric MachineBasicBlock::getFirstNonDebugInstr(bool SkipPseudoOp) {
2660b57cec5SDimitry Andric   // Skip over begin-of-block dbg_value instructions.
267fe6060f1SDimitry Andric   return skipDebugInstructionsForward(begin(), end(), SkipPseudoOp);
2680b57cec5SDimitry Andric }
2690b57cec5SDimitry Andric 
270fe6060f1SDimitry Andric MachineBasicBlock::iterator
271fe6060f1SDimitry Andric MachineBasicBlock::getLastNonDebugInstr(bool SkipPseudoOp) {
2720b57cec5SDimitry Andric   // Skip over end-of-block dbg_value instructions.
2730b57cec5SDimitry Andric   instr_iterator B = instr_begin(), I = instr_end();
2740b57cec5SDimitry Andric   while (I != B) {
2750b57cec5SDimitry Andric     --I;
2760b57cec5SDimitry Andric     // Return instruction that starts a bundle.
2770b57cec5SDimitry Andric     if (I->isDebugInstr() || I->isInsideBundle())
2780b57cec5SDimitry Andric       continue;
279fe6060f1SDimitry Andric     if (SkipPseudoOp && I->isPseudoProbe())
280fe6060f1SDimitry Andric       continue;
2810b57cec5SDimitry Andric     return I;
2820b57cec5SDimitry Andric   }
2830b57cec5SDimitry Andric   // The block is all debug values.
2840b57cec5SDimitry Andric   return end();
2850b57cec5SDimitry Andric }
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric bool MachineBasicBlock::hasEHPadSuccessor() const {
288349cc55cSDimitry Andric   for (const MachineBasicBlock *Succ : successors())
289349cc55cSDimitry Andric     if (Succ->isEHPad())
2900b57cec5SDimitry Andric       return true;
2910b57cec5SDimitry Andric   return false;
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric 
294e8d8bef9SDimitry Andric bool MachineBasicBlock::isEntryBlock() const {
295e8d8bef9SDimitry Andric   return getParent()->begin() == getIterator();
296e8d8bef9SDimitry Andric }
297e8d8bef9SDimitry Andric 
2980b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2990b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
3000b57cec5SDimitry Andric   print(dbgs());
3010b57cec5SDimitry Andric }
3020b57cec5SDimitry Andric #endif
3030b57cec5SDimitry Andric 
3045ffd83dbSDimitry Andric bool MachineBasicBlock::mayHaveInlineAsmBr() const {
3055ffd83dbSDimitry Andric   for (const MachineBasicBlock *Succ : successors()) {
3065ffd83dbSDimitry Andric     if (Succ->isInlineAsmBrIndirectTarget())
3075ffd83dbSDimitry Andric       return true;
3085ffd83dbSDimitry Andric   }
3095ffd83dbSDimitry Andric   return false;
3105ffd83dbSDimitry Andric }
3115ffd83dbSDimitry Andric 
3120b57cec5SDimitry Andric bool MachineBasicBlock::isLegalToHoistInto() const {
3135ffd83dbSDimitry Andric   if (isReturnBlock() || hasEHPadSuccessor() || mayHaveInlineAsmBr())
3140b57cec5SDimitry Andric     return false;
3150b57cec5SDimitry Andric   return true;
3160b57cec5SDimitry Andric }
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric StringRef MachineBasicBlock::getName() const {
3190b57cec5SDimitry Andric   if (const BasicBlock *LBB = getBasicBlock())
3200b57cec5SDimitry Andric     return LBB->getName();
3210b57cec5SDimitry Andric   else
3220b57cec5SDimitry Andric     return StringRef("", 0);
3230b57cec5SDimitry Andric }
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric /// Return a hopefully unique identifier for this block.
3260b57cec5SDimitry Andric std::string MachineBasicBlock::getFullName() const {
3270b57cec5SDimitry Andric   std::string Name;
3280b57cec5SDimitry Andric   if (getParent())
3290b57cec5SDimitry Andric     Name = (getParent()->getName() + ":").str();
3300b57cec5SDimitry Andric   if (getBasicBlock())
3310b57cec5SDimitry Andric     Name += getBasicBlock()->getName();
3320b57cec5SDimitry Andric   else
3330b57cec5SDimitry Andric     Name += ("BB" + Twine(getNumber())).str();
3340b57cec5SDimitry Andric   return Name;
3350b57cec5SDimitry Andric }
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes,
3380b57cec5SDimitry Andric                               bool IsStandalone) const {
3390b57cec5SDimitry Andric   const MachineFunction *MF = getParent();
3400b57cec5SDimitry Andric   if (!MF) {
3410b57cec5SDimitry Andric     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
3420b57cec5SDimitry Andric        << " is null\n";
3430b57cec5SDimitry Andric     return;
3440b57cec5SDimitry Andric   }
3450b57cec5SDimitry Andric   const Function &F = MF->getFunction();
3460b57cec5SDimitry Andric   const Module *M = F.getParent();
3470b57cec5SDimitry Andric   ModuleSlotTracker MST(M);
3480b57cec5SDimitry Andric   MST.incorporateFunction(F);
3490b57cec5SDimitry Andric   print(OS, MST, Indexes, IsStandalone);
3500b57cec5SDimitry Andric }
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
3530b57cec5SDimitry Andric                               const SlotIndexes *Indexes,
3540b57cec5SDimitry Andric                               bool IsStandalone) const {
3550b57cec5SDimitry Andric   const MachineFunction *MF = getParent();
3560b57cec5SDimitry Andric   if (!MF) {
3570b57cec5SDimitry Andric     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
3580b57cec5SDimitry Andric        << " is null\n";
3590b57cec5SDimitry Andric     return;
3600b57cec5SDimitry Andric   }
3610b57cec5SDimitry Andric 
3628bcb0991SDimitry Andric   if (Indexes && PrintSlotIndexes)
3630b57cec5SDimitry Andric     OS << Indexes->getMBBStartIdx(this) << '\t';
3640b57cec5SDimitry Andric 
365e8d8bef9SDimitry Andric   printName(OS, PrintNameIr | PrintNameAttributes, &MST);
3660b57cec5SDimitry Andric   OS << ":\n";
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
3690b57cec5SDimitry Andric   const MachineRegisterInfo &MRI = MF->getRegInfo();
3700b57cec5SDimitry Andric   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
3710b57cec5SDimitry Andric   bool HasLineAttributes = false;
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric   // Print the preds of this block according to the CFG.
3740b57cec5SDimitry Andric   if (!pred_empty() && IsStandalone) {
3750b57cec5SDimitry Andric     if (Indexes) OS << '\t';
3760b57cec5SDimitry Andric     // Don't indent(2), align with previous line attributes.
3770b57cec5SDimitry Andric     OS << "; predecessors: ";
378e8d8bef9SDimitry Andric     ListSeparator LS;
379e8d8bef9SDimitry Andric     for (auto *Pred : predecessors())
380e8d8bef9SDimitry Andric       OS << LS << printMBBReference(*Pred);
3810b57cec5SDimitry Andric     OS << '\n';
3820b57cec5SDimitry Andric     HasLineAttributes = true;
3830b57cec5SDimitry Andric   }
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   if (!succ_empty()) {
3860b57cec5SDimitry Andric     if (Indexes) OS << '\t';
3870b57cec5SDimitry Andric     // Print the successors
3880b57cec5SDimitry Andric     OS.indent(2) << "successors: ";
389e8d8bef9SDimitry Andric     ListSeparator LS;
3900b57cec5SDimitry Andric     for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
391e8d8bef9SDimitry Andric       OS << LS << printMBBReference(**I);
3920b57cec5SDimitry Andric       if (!Probs.empty())
3930b57cec5SDimitry Andric         OS << '('
3940b57cec5SDimitry Andric            << format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
3950b57cec5SDimitry Andric            << ')';
3960b57cec5SDimitry Andric     }
3970b57cec5SDimitry Andric     if (!Probs.empty() && IsStandalone) {
3980b57cec5SDimitry Andric       // Print human readable probabilities as comments.
3990b57cec5SDimitry Andric       OS << "; ";
400e8d8bef9SDimitry Andric       ListSeparator LS;
4010b57cec5SDimitry Andric       for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
4020b57cec5SDimitry Andric         const BranchProbability &BP = getSuccProbability(I);
403e8d8bef9SDimitry Andric         OS << LS << printMBBReference(**I) << '('
4040b57cec5SDimitry Andric            << format("%.2f%%",
4050b57cec5SDimitry Andric                      rint(((double)BP.getNumerator() / BP.getDenominator()) *
4060b57cec5SDimitry Andric                           100.0 * 100.0) /
4070b57cec5SDimitry Andric                          100.0)
4080b57cec5SDimitry Andric            << ')';
4090b57cec5SDimitry Andric       }
4100b57cec5SDimitry Andric     }
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric     OS << '\n';
4130b57cec5SDimitry Andric     HasLineAttributes = true;
4140b57cec5SDimitry Andric   }
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric   if (!livein_empty() && MRI.tracksLiveness()) {
4170b57cec5SDimitry Andric     if (Indexes) OS << '\t';
4180b57cec5SDimitry Andric     OS.indent(2) << "liveins: ";
4190b57cec5SDimitry Andric 
420e8d8bef9SDimitry Andric     ListSeparator LS;
4210b57cec5SDimitry Andric     for (const auto &LI : liveins()) {
422e8d8bef9SDimitry Andric       OS << LS << printReg(LI.PhysReg, TRI);
4230b57cec5SDimitry Andric       if (!LI.LaneMask.all())
4240b57cec5SDimitry Andric         OS << ":0x" << PrintLaneMask(LI.LaneMask);
4250b57cec5SDimitry Andric     }
4260b57cec5SDimitry Andric     HasLineAttributes = true;
4270b57cec5SDimitry Andric   }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   if (HasLineAttributes)
4300b57cec5SDimitry Andric     OS << '\n';
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric   bool IsInBundle = false;
4330b57cec5SDimitry Andric   for (const MachineInstr &MI : instrs()) {
4348bcb0991SDimitry Andric     if (Indexes && PrintSlotIndexes) {
4350b57cec5SDimitry Andric       if (Indexes->hasIndex(MI))
4360b57cec5SDimitry Andric         OS << Indexes->getInstructionIndex(MI);
4370b57cec5SDimitry Andric       OS << '\t';
4380b57cec5SDimitry Andric     }
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric     if (IsInBundle && !MI.isInsideBundle()) {
4410b57cec5SDimitry Andric       OS.indent(2) << "}\n";
4420b57cec5SDimitry Andric       IsInBundle = false;
4430b57cec5SDimitry Andric     }
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric     OS.indent(IsInBundle ? 4 : 2);
4460b57cec5SDimitry Andric     MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
4470b57cec5SDimitry Andric              /*AddNewLine=*/false, &TII);
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
4500b57cec5SDimitry Andric       OS << " {";
4510b57cec5SDimitry Andric       IsInBundle = true;
4520b57cec5SDimitry Andric     }
4530b57cec5SDimitry Andric     OS << '\n';
4540b57cec5SDimitry Andric   }
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric   if (IsInBundle)
4570b57cec5SDimitry Andric     OS.indent(2) << "}\n";
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   if (IrrLoopHeaderWeight && IsStandalone) {
4600b57cec5SDimitry Andric     if (Indexes) OS << '\t';
461bdd1243dSDimitry Andric     OS.indent(2) << "; Irreducible loop header weight: " << *IrrLoopHeaderWeight
462bdd1243dSDimitry Andric                  << '\n';
4630b57cec5SDimitry Andric   }
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric 
466e8d8bef9SDimitry Andric /// Print the basic block's name as:
467e8d8bef9SDimitry Andric ///
468e8d8bef9SDimitry Andric ///    bb.{number}[.{ir-name}] [(attributes...)]
469e8d8bef9SDimitry Andric ///
470e8d8bef9SDimitry Andric /// The {ir-name} is only printed when the \ref PrintNameIr flag is passed
471e8d8bef9SDimitry Andric /// (which is the default). If the IR block has no name, it is identified
472e8d8bef9SDimitry Andric /// numerically using the attribute syntax as "(%ir-block.{ir-slot})".
473e8d8bef9SDimitry Andric ///
474e8d8bef9SDimitry Andric /// When the \ref PrintNameAttributes flag is passed, additional attributes
475e8d8bef9SDimitry Andric /// of the block are printed when set.
476e8d8bef9SDimitry Andric ///
477e8d8bef9SDimitry Andric /// \param printNameFlags Combination of \ref PrintNameFlag flags indicating
478e8d8bef9SDimitry Andric ///                       the parts to print.
479e8d8bef9SDimitry Andric /// \param moduleSlotTracker Optional ModuleSlotTracker. This method will
480e8d8bef9SDimitry Andric ///                          incorporate its own tracker when necessary to
481e8d8bef9SDimitry Andric ///                          determine the block's IR name.
482e8d8bef9SDimitry Andric void MachineBasicBlock::printName(raw_ostream &os, unsigned printNameFlags,
483e8d8bef9SDimitry Andric                                   ModuleSlotTracker *moduleSlotTracker) const {
484e8d8bef9SDimitry Andric   os << "bb." << getNumber();
485e8d8bef9SDimitry Andric   bool hasAttributes = false;
486e8d8bef9SDimitry Andric 
487bdd1243dSDimitry Andric   auto PrintBBRef = [&](const BasicBlock *bb) {
488bdd1243dSDimitry Andric     os << "%ir-block.";
489e8d8bef9SDimitry Andric     if (bb->hasName()) {
490bdd1243dSDimitry Andric       os << bb->getName();
491e8d8bef9SDimitry Andric     } else {
492e8d8bef9SDimitry Andric       int slot = -1;
493e8d8bef9SDimitry Andric 
494e8d8bef9SDimitry Andric       if (moduleSlotTracker) {
495e8d8bef9SDimitry Andric         slot = moduleSlotTracker->getLocalSlot(bb);
496e8d8bef9SDimitry Andric       } else if (bb->getParent()) {
497e8d8bef9SDimitry Andric         ModuleSlotTracker tmpTracker(bb->getModule(), false);
498e8d8bef9SDimitry Andric         tmpTracker.incorporateFunction(*bb->getParent());
499e8d8bef9SDimitry Andric         slot = tmpTracker.getLocalSlot(bb);
500e8d8bef9SDimitry Andric       }
501e8d8bef9SDimitry Andric 
502e8d8bef9SDimitry Andric       if (slot == -1)
503e8d8bef9SDimitry Andric         os << "<ir-block badref>";
504e8d8bef9SDimitry Andric       else
505bdd1243dSDimitry Andric         os << slot;
506bdd1243dSDimitry Andric     }
507bdd1243dSDimitry Andric   };
508bdd1243dSDimitry Andric 
509bdd1243dSDimitry Andric   if (printNameFlags & PrintNameIr) {
510bdd1243dSDimitry Andric     if (const auto *bb = getBasicBlock()) {
511bdd1243dSDimitry Andric       if (bb->hasName()) {
512bdd1243dSDimitry Andric         os << '.' << bb->getName();
513bdd1243dSDimitry Andric       } else {
514bdd1243dSDimitry Andric         hasAttributes = true;
515bdd1243dSDimitry Andric         os << " (";
516bdd1243dSDimitry Andric         PrintBBRef(bb);
517e8d8bef9SDimitry Andric       }
518e8d8bef9SDimitry Andric     }
519e8d8bef9SDimitry Andric   }
520e8d8bef9SDimitry Andric 
521e8d8bef9SDimitry Andric   if (printNameFlags & PrintNameAttributes) {
522bdd1243dSDimitry Andric     if (isMachineBlockAddressTaken()) {
523e8d8bef9SDimitry Andric       os << (hasAttributes ? ", " : " (");
524bdd1243dSDimitry Andric       os << "machine-block-address-taken";
525bdd1243dSDimitry Andric       hasAttributes = true;
526bdd1243dSDimitry Andric     }
527bdd1243dSDimitry Andric     if (isIRBlockAddressTaken()) {
528bdd1243dSDimitry Andric       os << (hasAttributes ? ", " : " (");
529bdd1243dSDimitry Andric       os << "ir-block-address-taken ";
530bdd1243dSDimitry Andric       PrintBBRef(getAddressTakenIRBlock());
531e8d8bef9SDimitry Andric       hasAttributes = true;
532e8d8bef9SDimitry Andric     }
533e8d8bef9SDimitry Andric     if (isEHPad()) {
534e8d8bef9SDimitry Andric       os << (hasAttributes ? ", " : " (");
535e8d8bef9SDimitry Andric       os << "landing-pad";
536e8d8bef9SDimitry Andric       hasAttributes = true;
537e8d8bef9SDimitry Andric     }
538349cc55cSDimitry Andric     if (isInlineAsmBrIndirectTarget()) {
539349cc55cSDimitry Andric       os << (hasAttributes ? ", " : " (");
540349cc55cSDimitry Andric       os << "inlineasm-br-indirect-target";
541349cc55cSDimitry Andric       hasAttributes = true;
542349cc55cSDimitry Andric     }
543e8d8bef9SDimitry Andric     if (isEHFuncletEntry()) {
544e8d8bef9SDimitry Andric       os << (hasAttributes ? ", " : " (");
545e8d8bef9SDimitry Andric       os << "ehfunclet-entry";
546e8d8bef9SDimitry Andric       hasAttributes = true;
547e8d8bef9SDimitry Andric     }
548e8d8bef9SDimitry Andric     if (getAlignment() != Align(1)) {
549e8d8bef9SDimitry Andric       os << (hasAttributes ? ", " : " (");
550e8d8bef9SDimitry Andric       os << "align " << getAlignment().value();
551e8d8bef9SDimitry Andric       hasAttributes = true;
552e8d8bef9SDimitry Andric     }
553e8d8bef9SDimitry Andric     if (getSectionID() != MBBSectionID(0)) {
554e8d8bef9SDimitry Andric       os << (hasAttributes ? ", " : " (");
555e8d8bef9SDimitry Andric       os << "bbsections ";
556e8d8bef9SDimitry Andric       switch (getSectionID().Type) {
557e8d8bef9SDimitry Andric       case MBBSectionID::SectionType::Exception:
558e8d8bef9SDimitry Andric         os << "Exception";
559e8d8bef9SDimitry Andric         break;
560e8d8bef9SDimitry Andric       case MBBSectionID::SectionType::Cold:
561e8d8bef9SDimitry Andric         os << "Cold";
562e8d8bef9SDimitry Andric         break;
563e8d8bef9SDimitry Andric       default:
564e8d8bef9SDimitry Andric         os << getSectionID().Number;
565e8d8bef9SDimitry Andric       }
566e8d8bef9SDimitry Andric       hasAttributes = true;
567e8d8bef9SDimitry Andric     }
568bdd1243dSDimitry Andric     if (getBBID().has_value()) {
569bdd1243dSDimitry Andric       os << (hasAttributes ? ", " : " (");
570bdd1243dSDimitry Andric       os << "bb_id " << *getBBID();
571bdd1243dSDimitry Andric       hasAttributes = true;
572bdd1243dSDimitry Andric     }
573e8d8bef9SDimitry Andric   }
574e8d8bef9SDimitry Andric 
575e8d8bef9SDimitry Andric   if (hasAttributes)
576e8d8bef9SDimitry Andric     os << ')';
577e8d8bef9SDimitry Andric }
578e8d8bef9SDimitry Andric 
5790b57cec5SDimitry Andric void MachineBasicBlock::printAsOperand(raw_ostream &OS,
5800b57cec5SDimitry Andric                                        bool /*PrintType*/) const {
581e8d8bef9SDimitry Andric   OS << '%';
582e8d8bef9SDimitry Andric   printName(OS, 0);
5830b57cec5SDimitry Andric }
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
5860b57cec5SDimitry Andric   LiveInVector::iterator I = find_if(
5870b57cec5SDimitry Andric       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
5880b57cec5SDimitry Andric   if (I == LiveIns.end())
5890b57cec5SDimitry Andric     return;
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric   I->LaneMask &= ~LaneMask;
5920b57cec5SDimitry Andric   if (I->LaneMask.none())
5930b57cec5SDimitry Andric     LiveIns.erase(I);
5940b57cec5SDimitry Andric }
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric MachineBasicBlock::livein_iterator
5970b57cec5SDimitry Andric MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
5980b57cec5SDimitry Andric   // Get non-const version of iterator.
5990b57cec5SDimitry Andric   LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
6000b57cec5SDimitry Andric   return LiveIns.erase(LI);
6010b57cec5SDimitry Andric }
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
6040b57cec5SDimitry Andric   livein_iterator I = find_if(
6050b57cec5SDimitry Andric       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
6060b57cec5SDimitry Andric   return I != livein_end() && (I->LaneMask & LaneMask).any();
6070b57cec5SDimitry Andric }
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric void MachineBasicBlock::sortUniqueLiveIns() {
6100b57cec5SDimitry Andric   llvm::sort(LiveIns,
6110b57cec5SDimitry Andric              [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
6120b57cec5SDimitry Andric                return LI0.PhysReg < LI1.PhysReg;
6130b57cec5SDimitry Andric              });
6140b57cec5SDimitry Andric   // Liveins are sorted by physreg now we can merge their lanemasks.
6150b57cec5SDimitry Andric   LiveInVector::const_iterator I = LiveIns.begin();
6160b57cec5SDimitry Andric   LiveInVector::const_iterator J;
6170b57cec5SDimitry Andric   LiveInVector::iterator Out = LiveIns.begin();
6180b57cec5SDimitry Andric   for (; I != LiveIns.end(); ++Out, I = J) {
6195ffd83dbSDimitry Andric     MCRegister PhysReg = I->PhysReg;
6200b57cec5SDimitry Andric     LaneBitmask LaneMask = I->LaneMask;
6210b57cec5SDimitry Andric     for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
6220b57cec5SDimitry Andric       LaneMask |= J->LaneMask;
6230b57cec5SDimitry Andric     Out->PhysReg = PhysReg;
6240b57cec5SDimitry Andric     Out->LaneMask = LaneMask;
6250b57cec5SDimitry Andric   }
6260b57cec5SDimitry Andric   LiveIns.erase(Out, LiveIns.end());
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric 
6295ffd83dbSDimitry Andric Register
6308bcb0991SDimitry Andric MachineBasicBlock::addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC) {
6310b57cec5SDimitry Andric   assert(getParent() && "MBB must be inserted in function");
632e8d8bef9SDimitry Andric   assert(Register::isPhysicalRegister(PhysReg) && "Expected physreg");
6330b57cec5SDimitry Andric   assert(RC && "Register class is required");
6340b57cec5SDimitry Andric   assert((isEHPad() || this == &getParent()->front()) &&
6350b57cec5SDimitry Andric          "Only the entry block and landing pads can have physreg live ins");
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   bool LiveIn = isLiveIn(PhysReg);
6380b57cec5SDimitry Andric   iterator I = SkipPHIsAndLabels(begin()), E = end();
6390b57cec5SDimitry Andric   MachineRegisterInfo &MRI = getParent()->getRegInfo();
6400b57cec5SDimitry Andric   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   // Look for an existing copy.
6430b57cec5SDimitry Andric   if (LiveIn)
6440b57cec5SDimitry Andric     for (;I != E && I->isCopy(); ++I)
6450b57cec5SDimitry Andric       if (I->getOperand(1).getReg() == PhysReg) {
6468bcb0991SDimitry Andric         Register VirtReg = I->getOperand(0).getReg();
6470b57cec5SDimitry Andric         if (!MRI.constrainRegClass(VirtReg, RC))
6480b57cec5SDimitry Andric           llvm_unreachable("Incompatible live-in register class.");
6490b57cec5SDimitry Andric         return VirtReg;
6500b57cec5SDimitry Andric       }
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric   // No luck, create a virtual register.
6538bcb0991SDimitry Andric   Register VirtReg = MRI.createVirtualRegister(RC);
6540b57cec5SDimitry Andric   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
6550b57cec5SDimitry Andric     .addReg(PhysReg, RegState::Kill);
6560b57cec5SDimitry Andric   if (!LiveIn)
6570b57cec5SDimitry Andric     addLiveIn(PhysReg);
6580b57cec5SDimitry Andric   return VirtReg;
6590b57cec5SDimitry Andric }
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
6620b57cec5SDimitry Andric   getParent()->splice(NewAfter->getIterator(), getIterator());
6630b57cec5SDimitry Andric }
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
6660b57cec5SDimitry Andric   getParent()->splice(++NewBefore->getIterator(), getIterator());
6670b57cec5SDimitry Andric }
6680b57cec5SDimitry Andric 
669*fe013be4SDimitry Andric static int findJumpTableIndex(const MachineBasicBlock &MBB) {
670*fe013be4SDimitry Andric   MachineBasicBlock::const_iterator TerminatorI = MBB.getFirstTerminator();
671*fe013be4SDimitry Andric   if (TerminatorI == MBB.end())
672*fe013be4SDimitry Andric     return -1;
673*fe013be4SDimitry Andric   const MachineInstr &Terminator = *TerminatorI;
674*fe013be4SDimitry Andric   const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
675*fe013be4SDimitry Andric   return TII->getJumpTableIndex(Terminator);
676*fe013be4SDimitry Andric }
677*fe013be4SDimitry Andric 
6785ffd83dbSDimitry Andric void MachineBasicBlock::updateTerminator(
6795ffd83dbSDimitry Andric     MachineBasicBlock *PreviousLayoutSuccessor) {
6805ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
6815ffd83dbSDimitry Andric                     << "\n");
6825ffd83dbSDimitry Andric 
6830b57cec5SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
6840b57cec5SDimitry Andric   // A block with no successors has no concerns with fall-through edges.
6850b57cec5SDimitry Andric   if (this->succ_empty())
6860b57cec5SDimitry Andric     return;
6870b57cec5SDimitry Andric 
6880b57cec5SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
6890b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
6900b57cec5SDimitry Andric   DebugLoc DL = findBranchDebugLoc();
6910b57cec5SDimitry Andric   bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
6920b57cec5SDimitry Andric   (void) B;
6930b57cec5SDimitry Andric   assert(!B && "UpdateTerminators requires analyzable predecessors!");
6940b57cec5SDimitry Andric   if (Cond.empty()) {
6950b57cec5SDimitry Andric     if (TBB) {
6960b57cec5SDimitry Andric       // The block has an unconditional branch. If its successor is now its
6970b57cec5SDimitry Andric       // layout successor, delete the branch.
6980b57cec5SDimitry Andric       if (isLayoutSuccessor(TBB))
6990b57cec5SDimitry Andric         TII->removeBranch(*this);
7000b57cec5SDimitry Andric     } else {
7015ffd83dbSDimitry Andric       // The block has an unconditional fallthrough, or the end of the block is
7025ffd83dbSDimitry Andric       // unreachable.
7030b57cec5SDimitry Andric 
7045ffd83dbSDimitry Andric       // Unfortunately, whether the end of the block is unreachable is not
7055ffd83dbSDimitry Andric       // immediately obvious; we must fall back to checking the successor list,
7065ffd83dbSDimitry Andric       // and assuming that if the passed in block is in the succesor list and
7075ffd83dbSDimitry Andric       // not an EHPad, it must be the intended target.
7085ffd83dbSDimitry Andric       if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) ||
7095ffd83dbSDimitry Andric           PreviousLayoutSuccessor->isEHPad())
7100b57cec5SDimitry Andric         return;
7110b57cec5SDimitry Andric 
7125ffd83dbSDimitry Andric       // If the unconditional successor block is not the current layout
7135ffd83dbSDimitry Andric       // successor, insert a branch to jump to it.
7145ffd83dbSDimitry Andric       if (!isLayoutSuccessor(PreviousLayoutSuccessor))
7155ffd83dbSDimitry Andric         TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
7160b57cec5SDimitry Andric     }
7170b57cec5SDimitry Andric     return;
7180b57cec5SDimitry Andric   }
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric   if (FBB) {
7210b57cec5SDimitry Andric     // The block has a non-fallthrough conditional branch. If one of its
7220b57cec5SDimitry Andric     // successors is its layout successor, rewrite it to a fallthrough
7230b57cec5SDimitry Andric     // conditional branch.
7240b57cec5SDimitry Andric     if (isLayoutSuccessor(TBB)) {
7250b57cec5SDimitry Andric       if (TII->reverseBranchCondition(Cond))
7260b57cec5SDimitry Andric         return;
7270b57cec5SDimitry Andric       TII->removeBranch(*this);
7280b57cec5SDimitry Andric       TII->insertBranch(*this, FBB, nullptr, Cond, DL);
7290b57cec5SDimitry Andric     } else if (isLayoutSuccessor(FBB)) {
7300b57cec5SDimitry Andric       TII->removeBranch(*this);
7310b57cec5SDimitry Andric       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
7320b57cec5SDimitry Andric     }
7330b57cec5SDimitry Andric     return;
7340b57cec5SDimitry Andric   }
7350b57cec5SDimitry Andric 
7365ffd83dbSDimitry Andric   // We now know we're going to fallthrough to PreviousLayoutSuccessor.
7375ffd83dbSDimitry Andric   assert(PreviousLayoutSuccessor);
7385ffd83dbSDimitry Andric   assert(!PreviousLayoutSuccessor->isEHPad());
7395ffd83dbSDimitry Andric   assert(isSuccessor(PreviousLayoutSuccessor));
7400b57cec5SDimitry Andric 
7415ffd83dbSDimitry Andric   if (PreviousLayoutSuccessor == TBB) {
7425ffd83dbSDimitry Andric     // We had a fallthrough to the same basic block as the conditional jump
7435ffd83dbSDimitry Andric     // targets.  Remove the conditional jump, leaving an unconditional
7445ffd83dbSDimitry Andric     // fallthrough or an unconditional jump.
7450b57cec5SDimitry Andric     TII->removeBranch(*this);
7465ffd83dbSDimitry Andric     if (!isLayoutSuccessor(TBB)) {
7470b57cec5SDimitry Andric       Cond.clear();
7480b57cec5SDimitry Andric       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
7495ffd83dbSDimitry Andric     }
7500b57cec5SDimitry Andric     return;
7510b57cec5SDimitry Andric   }
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   // The block has a fallthrough conditional branch.
7540b57cec5SDimitry Andric   if (isLayoutSuccessor(TBB)) {
7550b57cec5SDimitry Andric     if (TII->reverseBranchCondition(Cond)) {
7560b57cec5SDimitry Andric       // We can't reverse the condition, add an unconditional branch.
7570b57cec5SDimitry Andric       Cond.clear();
7585ffd83dbSDimitry Andric       TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
7590b57cec5SDimitry Andric       return;
7600b57cec5SDimitry Andric     }
7610b57cec5SDimitry Andric     TII->removeBranch(*this);
7625ffd83dbSDimitry Andric     TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
7635ffd83dbSDimitry Andric   } else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) {
7640b57cec5SDimitry Andric     TII->removeBranch(*this);
7655ffd83dbSDimitry Andric     TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL);
7660b57cec5SDimitry Andric   }
7670b57cec5SDimitry Andric }
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric void MachineBasicBlock::validateSuccProbs() const {
7700b57cec5SDimitry Andric #ifndef NDEBUG
7710b57cec5SDimitry Andric   int64_t Sum = 0;
7720b57cec5SDimitry Andric   for (auto Prob : Probs)
7730b57cec5SDimitry Andric     Sum += Prob.getNumerator();
7740b57cec5SDimitry Andric   // Due to precision issue, we assume that the sum of probabilities is one if
7750b57cec5SDimitry Andric   // the difference between the sum of their numerators and the denominator is
7760b57cec5SDimitry Andric   // no greater than the number of successors.
7770b57cec5SDimitry Andric   assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
7780b57cec5SDimitry Andric              Probs.size() &&
7790b57cec5SDimitry Andric          "The sum of successors's probabilities exceeds one.");
7800b57cec5SDimitry Andric #endif // NDEBUG
7810b57cec5SDimitry Andric }
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
7840b57cec5SDimitry Andric                                      BranchProbability Prob) {
7850b57cec5SDimitry Andric   // Probability list is either empty (if successor list isn't empty, this means
7860b57cec5SDimitry Andric   // disabled optimization) or has the same size as successor list.
7870b57cec5SDimitry Andric   if (!(Probs.empty() && !Successors.empty()))
7880b57cec5SDimitry Andric     Probs.push_back(Prob);
7890b57cec5SDimitry Andric   Successors.push_back(Succ);
7900b57cec5SDimitry Andric   Succ->addPredecessor(this);
7910b57cec5SDimitry Andric }
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
7940b57cec5SDimitry Andric   // We need to make sure probability list is either empty or has the same size
7950b57cec5SDimitry Andric   // of successor list. When this function is called, we can safely delete all
7960b57cec5SDimitry Andric   // probability in the list.
7970b57cec5SDimitry Andric   Probs.clear();
7980b57cec5SDimitry Andric   Successors.push_back(Succ);
7990b57cec5SDimitry Andric   Succ->addPredecessor(this);
8000b57cec5SDimitry Andric }
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
8030b57cec5SDimitry Andric                                        MachineBasicBlock *New,
8040b57cec5SDimitry Andric                                        bool NormalizeSuccProbs) {
8050b57cec5SDimitry Andric   succ_iterator OldI = llvm::find(successors(), Old);
8060b57cec5SDimitry Andric   assert(OldI != succ_end() && "Old is not a successor of this block!");
807e8d8bef9SDimitry Andric   assert(!llvm::is_contained(successors(), New) &&
8080b57cec5SDimitry Andric          "New is already a successor of this block!");
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   // Add a new successor with equal probability as the original one. Note
8110b57cec5SDimitry Andric   // that we directly copy the probability using the iterator rather than
8120b57cec5SDimitry Andric   // getting a potentially synthetic probability computed when unknown. This
8130b57cec5SDimitry Andric   // preserves the probabilities as-is and then we can renormalize them and
8140b57cec5SDimitry Andric   // query them effectively afterward.
8150b57cec5SDimitry Andric   addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
8160b57cec5SDimitry Andric                                   : *getProbabilityIterator(OldI));
8170b57cec5SDimitry Andric   if (NormalizeSuccProbs)
8180b57cec5SDimitry Andric     normalizeSuccProbs();
8190b57cec5SDimitry Andric }
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
8220b57cec5SDimitry Andric                                         bool NormalizeSuccProbs) {
8230b57cec5SDimitry Andric   succ_iterator I = find(Successors, Succ);
8240b57cec5SDimitry Andric   removeSuccessor(I, NormalizeSuccProbs);
8250b57cec5SDimitry Andric }
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric MachineBasicBlock::succ_iterator
8280b57cec5SDimitry Andric MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
8290b57cec5SDimitry Andric   assert(I != Successors.end() && "Not a current successor!");
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   // If probability list is empty it means we don't use it (disabled
8320b57cec5SDimitry Andric   // optimization).
8330b57cec5SDimitry Andric   if (!Probs.empty()) {
8340b57cec5SDimitry Andric     probability_iterator WI = getProbabilityIterator(I);
8350b57cec5SDimitry Andric     Probs.erase(WI);
8360b57cec5SDimitry Andric     if (NormalizeSuccProbs)
8370b57cec5SDimitry Andric       normalizeSuccProbs();
8380b57cec5SDimitry Andric   }
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric   (*I)->removePredecessor(this);
8410b57cec5SDimitry Andric   return Successors.erase(I);
8420b57cec5SDimitry Andric }
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
8450b57cec5SDimitry Andric                                          MachineBasicBlock *New) {
8460b57cec5SDimitry Andric   if (Old == New)
8470b57cec5SDimitry Andric     return;
8480b57cec5SDimitry Andric 
8490b57cec5SDimitry Andric   succ_iterator E = succ_end();
8500b57cec5SDimitry Andric   succ_iterator NewI = E;
8510b57cec5SDimitry Andric   succ_iterator OldI = E;
8520b57cec5SDimitry Andric   for (succ_iterator I = succ_begin(); I != E; ++I) {
8530b57cec5SDimitry Andric     if (*I == Old) {
8540b57cec5SDimitry Andric       OldI = I;
8550b57cec5SDimitry Andric       if (NewI != E)
8560b57cec5SDimitry Andric         break;
8570b57cec5SDimitry Andric     }
8580b57cec5SDimitry Andric     if (*I == New) {
8590b57cec5SDimitry Andric       NewI = I;
8600b57cec5SDimitry Andric       if (OldI != E)
8610b57cec5SDimitry Andric         break;
8620b57cec5SDimitry Andric     }
8630b57cec5SDimitry Andric   }
8640b57cec5SDimitry Andric   assert(OldI != E && "Old is not a successor of this block");
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric   // If New isn't already a successor, let it take Old's place.
8670b57cec5SDimitry Andric   if (NewI == E) {
8680b57cec5SDimitry Andric     Old->removePredecessor(this);
8690b57cec5SDimitry Andric     New->addPredecessor(this);
8700b57cec5SDimitry Andric     *OldI = New;
8710b57cec5SDimitry Andric     return;
8720b57cec5SDimitry Andric   }
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric   // New is already a successor.
8750b57cec5SDimitry Andric   // Update its probability instead of adding a duplicate edge.
8760b57cec5SDimitry Andric   if (!Probs.empty()) {
8770b57cec5SDimitry Andric     auto ProbIter = getProbabilityIterator(NewI);
8780b57cec5SDimitry Andric     if (!ProbIter->isUnknown())
8790b57cec5SDimitry Andric       *ProbIter += *getProbabilityIterator(OldI);
8800b57cec5SDimitry Andric   }
8810b57cec5SDimitry Andric   removeSuccessor(OldI);
8820b57cec5SDimitry Andric }
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric void MachineBasicBlock::copySuccessor(MachineBasicBlock *Orig,
8850b57cec5SDimitry Andric                                       succ_iterator I) {
886e8d8bef9SDimitry Andric   if (!Orig->Probs.empty())
8870b57cec5SDimitry Andric     addSuccessor(*I, Orig->getSuccProbability(I));
8880b57cec5SDimitry Andric   else
8890b57cec5SDimitry Andric     addSuccessorWithoutProb(*I);
8900b57cec5SDimitry Andric }
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
8930b57cec5SDimitry Andric   Predecessors.push_back(Pred);
8940b57cec5SDimitry Andric }
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
8970b57cec5SDimitry Andric   pred_iterator I = find(Predecessors, Pred);
8980b57cec5SDimitry Andric   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
8990b57cec5SDimitry Andric   Predecessors.erase(I);
9000b57cec5SDimitry Andric }
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
9030b57cec5SDimitry Andric   if (this == FromMBB)
9040b57cec5SDimitry Andric     return;
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric   while (!FromMBB->succ_empty()) {
9070b57cec5SDimitry Andric     MachineBasicBlock *Succ = *FromMBB->succ_begin();
9080b57cec5SDimitry Andric 
9098bcb0991SDimitry Andric     // If probability list is empty it means we don't use it (disabled
9108bcb0991SDimitry Andric     // optimization).
9110b57cec5SDimitry Andric     if (!FromMBB->Probs.empty()) {
9120b57cec5SDimitry Andric       auto Prob = *FromMBB->Probs.begin();
9130b57cec5SDimitry Andric       addSuccessor(Succ, Prob);
9140b57cec5SDimitry Andric     } else
9150b57cec5SDimitry Andric       addSuccessorWithoutProb(Succ);
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric     FromMBB->removeSuccessor(Succ);
9180b57cec5SDimitry Andric   }
9190b57cec5SDimitry Andric }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric void
9220b57cec5SDimitry Andric MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
9230b57cec5SDimitry Andric   if (this == FromMBB)
9240b57cec5SDimitry Andric     return;
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   while (!FromMBB->succ_empty()) {
9270b57cec5SDimitry Andric     MachineBasicBlock *Succ = *FromMBB->succ_begin();
9280b57cec5SDimitry Andric     if (!FromMBB->Probs.empty()) {
9290b57cec5SDimitry Andric       auto Prob = *FromMBB->Probs.begin();
9300b57cec5SDimitry Andric       addSuccessor(Succ, Prob);
9310b57cec5SDimitry Andric     } else
9320b57cec5SDimitry Andric       addSuccessorWithoutProb(Succ);
9330b57cec5SDimitry Andric     FromMBB->removeSuccessor(Succ);
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric     // Fix up any PHI nodes in the successor.
9368bcb0991SDimitry Andric     Succ->replacePhiUsesWith(FromMBB, this);
9370b57cec5SDimitry Andric   }
9380b57cec5SDimitry Andric   normalizeSuccProbs();
9390b57cec5SDimitry Andric }
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
9420b57cec5SDimitry Andric   return is_contained(predecessors(), MBB);
9430b57cec5SDimitry Andric }
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
9460b57cec5SDimitry Andric   return is_contained(successors(), MBB);
9470b57cec5SDimitry Andric }
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
9500b57cec5SDimitry Andric   MachineFunction::const_iterator I(this);
9510b57cec5SDimitry Andric   return std::next(I) == MachineFunction::const_iterator(MBB);
9520b57cec5SDimitry Andric }
9530b57cec5SDimitry Andric 
95481ad6265SDimitry Andric const MachineBasicBlock *MachineBasicBlock::getSingleSuccessor() const {
95581ad6265SDimitry Andric   return Successors.size() == 1 ? Successors[0] : nullptr;
95681ad6265SDimitry Andric }
95781ad6265SDimitry Andric 
958bdd1243dSDimitry Andric MachineBasicBlock *MachineBasicBlock::getFallThrough(bool JumpToFallThrough) {
9590b57cec5SDimitry Andric   MachineFunction::iterator Fallthrough = getIterator();
9600b57cec5SDimitry Andric   ++Fallthrough;
9610b57cec5SDimitry Andric   // If FallthroughBlock is off the end of the function, it can't fall through.
9620b57cec5SDimitry Andric   if (Fallthrough == getParent()->end())
9630b57cec5SDimitry Andric     return nullptr;
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric   // If FallthroughBlock isn't a successor, no fallthrough is possible.
9660b57cec5SDimitry Andric   if (!isSuccessor(&*Fallthrough))
9670b57cec5SDimitry Andric     return nullptr;
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric   // Analyze the branches, if any, at the end of the block.
9700b57cec5SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
9710b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
9720b57cec5SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
9730b57cec5SDimitry Andric   if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
9740b57cec5SDimitry Andric     // If we couldn't analyze the branch, examine the last instruction.
9750b57cec5SDimitry Andric     // If the block doesn't end in a known control barrier, assume fallthrough
9760b57cec5SDimitry Andric     // is possible. The isPredicated check is needed because this code can be
9770b57cec5SDimitry Andric     // called during IfConversion, where an instruction which is normally a
9780b57cec5SDimitry Andric     // Barrier is predicated and thus no longer an actual control barrier.
9790b57cec5SDimitry Andric     return (empty() || !back().isBarrier() || TII->isPredicated(back()))
9800b57cec5SDimitry Andric                ? &*Fallthrough
9810b57cec5SDimitry Andric                : nullptr;
9820b57cec5SDimitry Andric   }
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric   // If there is no branch, control always falls through.
9850b57cec5SDimitry Andric   if (!TBB) return &*Fallthrough;
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   // If there is some explicit branch to the fallthrough block, it can obviously
9880b57cec5SDimitry Andric   // reach, even though the branch should get folded to fall through implicitly.
989*fe013be4SDimitry Andric   if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough ||
990bdd1243dSDimitry Andric                             MachineFunction::iterator(FBB) == Fallthrough))
9910b57cec5SDimitry Andric     return &*Fallthrough;
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric   // If it's an unconditional branch to some block not the fall through, it
9940b57cec5SDimitry Andric   // doesn't fall through.
9950b57cec5SDimitry Andric   if (Cond.empty()) return nullptr;
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric   // Otherwise, if it is conditional and has no explicit false block, it falls
9980b57cec5SDimitry Andric   // through.
9990b57cec5SDimitry Andric   return (FBB == nullptr) ? &*Fallthrough : nullptr;
10000b57cec5SDimitry Andric }
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric bool MachineBasicBlock::canFallThrough() {
10030b57cec5SDimitry Andric   return getFallThrough() != nullptr;
10040b57cec5SDimitry Andric }
10050b57cec5SDimitry Andric 
1006e8d8bef9SDimitry Andric MachineBasicBlock *MachineBasicBlock::splitAt(MachineInstr &MI,
1007e8d8bef9SDimitry Andric                                               bool UpdateLiveIns,
1008e8d8bef9SDimitry Andric                                               LiveIntervals *LIS) {
1009e8d8bef9SDimitry Andric   MachineBasicBlock::iterator SplitPoint(&MI);
1010e8d8bef9SDimitry Andric   ++SplitPoint;
1011e8d8bef9SDimitry Andric 
1012e8d8bef9SDimitry Andric   if (SplitPoint == end()) {
1013e8d8bef9SDimitry Andric     // Don't bother with a new block.
1014e8d8bef9SDimitry Andric     return this;
1015e8d8bef9SDimitry Andric   }
1016e8d8bef9SDimitry Andric 
1017e8d8bef9SDimitry Andric   MachineFunction *MF = getParent();
1018e8d8bef9SDimitry Andric 
1019e8d8bef9SDimitry Andric   LivePhysRegs LiveRegs;
1020e8d8bef9SDimitry Andric   if (UpdateLiveIns) {
1021e8d8bef9SDimitry Andric     // Make sure we add any physregs we define in the block as liveins to the
1022e8d8bef9SDimitry Andric     // new block.
1023e8d8bef9SDimitry Andric     MachineBasicBlock::iterator Prev(&MI);
1024e8d8bef9SDimitry Andric     LiveRegs.init(*MF->getSubtarget().getRegisterInfo());
1025e8d8bef9SDimitry Andric     LiveRegs.addLiveOuts(*this);
1026e8d8bef9SDimitry Andric     for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
1027e8d8bef9SDimitry Andric       LiveRegs.stepBackward(*I);
1028e8d8bef9SDimitry Andric   }
1029e8d8bef9SDimitry Andric 
1030e8d8bef9SDimitry Andric   MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(getBasicBlock());
1031e8d8bef9SDimitry Andric 
1032e8d8bef9SDimitry Andric   MF->insert(++MachineFunction::iterator(this), SplitBB);
1033e8d8bef9SDimitry Andric   SplitBB->splice(SplitBB->begin(), this, SplitPoint, end());
1034e8d8bef9SDimitry Andric 
1035e8d8bef9SDimitry Andric   SplitBB->transferSuccessorsAndUpdatePHIs(this);
1036e8d8bef9SDimitry Andric   addSuccessor(SplitBB);
1037e8d8bef9SDimitry Andric 
1038e8d8bef9SDimitry Andric   if (UpdateLiveIns)
1039e8d8bef9SDimitry Andric     addLiveIns(*SplitBB, LiveRegs);
1040e8d8bef9SDimitry Andric 
1041e8d8bef9SDimitry Andric   if (LIS)
1042e8d8bef9SDimitry Andric     LIS->insertMBBInMaps(SplitBB);
1043e8d8bef9SDimitry Andric 
1044e8d8bef9SDimitry Andric   return SplitBB;
1045e8d8bef9SDimitry Andric }
1046e8d8bef9SDimitry Andric 
1047*fe013be4SDimitry Andric // Returns `true` if there are possibly other users of the jump table at
1048*fe013be4SDimitry Andric // `JumpTableIndex` except for the ones in `IgnoreMBB`.
1049*fe013be4SDimitry Andric static bool jumpTableHasOtherUses(const MachineFunction &MF,
1050*fe013be4SDimitry Andric                                   const MachineBasicBlock &IgnoreMBB,
1051*fe013be4SDimitry Andric                                   int JumpTableIndex) {
1052*fe013be4SDimitry Andric   assert(JumpTableIndex >= 0 && "need valid index");
1053*fe013be4SDimitry Andric   const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo();
1054*fe013be4SDimitry Andric   const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex];
1055*fe013be4SDimitry Andric   // Take any basic block from the table; every user of the jump table must
1056*fe013be4SDimitry Andric   // show up in the predecessor list.
1057*fe013be4SDimitry Andric   const MachineBasicBlock *MBB = nullptr;
1058*fe013be4SDimitry Andric   for (MachineBasicBlock *B : MJTE.MBBs) {
1059*fe013be4SDimitry Andric     if (B != nullptr) {
1060*fe013be4SDimitry Andric       MBB = B;
1061*fe013be4SDimitry Andric       break;
1062*fe013be4SDimitry Andric     }
1063*fe013be4SDimitry Andric   }
1064*fe013be4SDimitry Andric   if (MBB == nullptr)
1065*fe013be4SDimitry Andric     return true; // can't rule out other users if there isn't any block.
1066*fe013be4SDimitry Andric   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1067*fe013be4SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
1068*fe013be4SDimitry Andric   for (MachineBasicBlock *Pred : MBB->predecessors()) {
1069*fe013be4SDimitry Andric     if (Pred == &IgnoreMBB)
1070*fe013be4SDimitry Andric       continue;
1071*fe013be4SDimitry Andric     MachineBasicBlock *DummyT = nullptr;
1072*fe013be4SDimitry Andric     MachineBasicBlock *DummyF = nullptr;
1073*fe013be4SDimitry Andric     Cond.clear();
1074*fe013be4SDimitry Andric     if (!TII.analyzeBranch(*Pred, DummyT, DummyF, Cond,
1075*fe013be4SDimitry Andric                            /*AllowModify=*/false)) {
1076*fe013be4SDimitry Andric       // analyzable direct jump
1077*fe013be4SDimitry Andric       continue;
1078*fe013be4SDimitry Andric     }
1079*fe013be4SDimitry Andric     int PredJTI = findJumpTableIndex(*Pred);
1080*fe013be4SDimitry Andric     if (PredJTI >= 0) {
1081*fe013be4SDimitry Andric       if (PredJTI == JumpTableIndex)
1082*fe013be4SDimitry Andric         return true;
1083*fe013be4SDimitry Andric       continue;
1084*fe013be4SDimitry Andric     }
1085*fe013be4SDimitry Andric     // Be conservative for unanalyzable jumps.
1086*fe013be4SDimitry Andric     return true;
1087*fe013be4SDimitry Andric   }
1088*fe013be4SDimitry Andric   return false;
1089*fe013be4SDimitry Andric }
1090*fe013be4SDimitry Andric 
10915ffd83dbSDimitry Andric MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
10925ffd83dbSDimitry Andric     MachineBasicBlock *Succ, Pass &P,
10935ffd83dbSDimitry Andric     std::vector<SparseBitVector<>> *LiveInSets) {
10940b57cec5SDimitry Andric   if (!canSplitCriticalEdge(Succ))
10950b57cec5SDimitry Andric     return nullptr;
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric   MachineFunction *MF = getParent();
10985ffd83dbSDimitry Andric   MachineBasicBlock *PrevFallthrough = getNextNode();
10990b57cec5SDimitry Andric   DebugLoc DL;  // FIXME: this is nowhere
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
1102*fe013be4SDimitry Andric 
1103*fe013be4SDimitry Andric   // Is there an indirect jump with jump table?
1104*fe013be4SDimitry Andric   bool ChangedIndirectJump = false;
1105*fe013be4SDimitry Andric   int JTI = findJumpTableIndex(*this);
1106*fe013be4SDimitry Andric   if (JTI >= 0) {
1107*fe013be4SDimitry Andric     MachineJumpTableInfo &MJTI = *MF->getJumpTableInfo();
1108*fe013be4SDimitry Andric     MJTI.ReplaceMBBInJumpTable(JTI, Succ, NMBB);
1109*fe013be4SDimitry Andric     ChangedIndirectJump = true;
1110*fe013be4SDimitry Andric   }
1111*fe013be4SDimitry Andric 
11120b57cec5SDimitry Andric   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
11130b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
11140b57cec5SDimitry Andric                     << " -- " << printMBBReference(*NMBB) << " -- "
11150b57cec5SDimitry Andric                     << printMBBReference(*Succ) << '\n');
11160b57cec5SDimitry Andric 
11170b57cec5SDimitry Andric   LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
11180b57cec5SDimitry Andric   SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
11190b57cec5SDimitry Andric   if (LIS)
11200b57cec5SDimitry Andric     LIS->insertMBBInMaps(NMBB);
11210b57cec5SDimitry Andric   else if (Indexes)
11220b57cec5SDimitry Andric     Indexes->insertMBBInMaps(NMBB);
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric   // On some targets like Mips, branches may kill virtual registers. Make sure
11250b57cec5SDimitry Andric   // that LiveVariables is properly updated after updateTerminator replaces the
11260b57cec5SDimitry Andric   // terminators.
11270b57cec5SDimitry Andric   LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric   // Collect a list of virtual registers killed by the terminators.
11305ffd83dbSDimitry Andric   SmallVector<Register, 4> KilledRegs;
11310b57cec5SDimitry Andric   if (LV)
11320eae32dcSDimitry Andric     for (MachineInstr &MI :
11330eae32dcSDimitry Andric          llvm::make_range(getFirstInstrTerminator(), instr_end())) {
1134*fe013be4SDimitry Andric       for (MachineOperand &MO : MI.all_uses()) {
1135*fe013be4SDimitry Andric         if (MO.getReg() == 0 || !MO.isKill() || MO.isUndef())
11360b57cec5SDimitry Andric           continue;
1137349cc55cSDimitry Andric         Register Reg = MO.getReg();
1138bdd1243dSDimitry Andric         if (Reg.isPhysical() || LV->getVarInfo(Reg).removeKill(MI)) {
11390b57cec5SDimitry Andric           KilledRegs.push_back(Reg);
1140349cc55cSDimitry Andric           LLVM_DEBUG(dbgs() << "Removing terminator kill: " << MI);
1141349cc55cSDimitry Andric           MO.setIsKill(false);
11420b57cec5SDimitry Andric         }
11430b57cec5SDimitry Andric       }
11440b57cec5SDimitry Andric     }
11450b57cec5SDimitry Andric 
11465ffd83dbSDimitry Andric   SmallVector<Register, 4> UsedRegs;
11470b57cec5SDimitry Andric   if (LIS) {
11480eae32dcSDimitry Andric     for (MachineInstr &MI :
11490eae32dcSDimitry Andric          llvm::make_range(getFirstInstrTerminator(), instr_end())) {
11500eae32dcSDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
1151349cc55cSDimitry Andric         if (!MO.isReg() || MO.getReg() == 0)
11520b57cec5SDimitry Andric           continue;
11530b57cec5SDimitry Andric 
1154349cc55cSDimitry Andric         Register Reg = MO.getReg();
11550b57cec5SDimitry Andric         if (!is_contained(UsedRegs, Reg))
11560b57cec5SDimitry Andric           UsedRegs.push_back(Reg);
11570b57cec5SDimitry Andric       }
11580b57cec5SDimitry Andric     }
11590b57cec5SDimitry Andric   }
11600b57cec5SDimitry Andric 
11610b57cec5SDimitry Andric   ReplaceUsesOfBlockWith(Succ, NMBB);
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric   // If updateTerminator() removes instructions, we need to remove them from
11640b57cec5SDimitry Andric   // SlotIndexes.
11650b57cec5SDimitry Andric   SmallVector<MachineInstr*, 4> Terminators;
11660b57cec5SDimitry Andric   if (Indexes) {
11670eae32dcSDimitry Andric     for (MachineInstr &MI :
11680eae32dcSDimitry Andric          llvm::make_range(getFirstInstrTerminator(), instr_end()))
11690eae32dcSDimitry Andric       Terminators.push_back(&MI);
11700b57cec5SDimitry Andric   }
11710b57cec5SDimitry Andric 
11725ffd83dbSDimitry Andric   // Since we replaced all uses of Succ with NMBB, that should also be treated
11735ffd83dbSDimitry Andric   // as the fallthrough successor
11745ffd83dbSDimitry Andric   if (Succ == PrevFallthrough)
11755ffd83dbSDimitry Andric     PrevFallthrough = NMBB;
1176*fe013be4SDimitry Andric 
1177*fe013be4SDimitry Andric   if (!ChangedIndirectJump)
11785ffd83dbSDimitry Andric     updateTerminator(PrevFallthrough);
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric   if (Indexes) {
11810b57cec5SDimitry Andric     SmallVector<MachineInstr*, 4> NewTerminators;
11820eae32dcSDimitry Andric     for (MachineInstr &MI :
11830eae32dcSDimitry Andric          llvm::make_range(getFirstInstrTerminator(), instr_end()))
11840eae32dcSDimitry Andric       NewTerminators.push_back(&MI);
11850b57cec5SDimitry Andric 
1186fe6060f1SDimitry Andric     for (MachineInstr *Terminator : Terminators) {
1187fe6060f1SDimitry Andric       if (!is_contained(NewTerminators, Terminator))
1188fe6060f1SDimitry Andric         Indexes->removeMachineInstrFromMaps(*Terminator);
11890b57cec5SDimitry Andric     }
11900b57cec5SDimitry Andric   }
11910b57cec5SDimitry Andric 
11920b57cec5SDimitry Andric   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
11930b57cec5SDimitry Andric   NMBB->addSuccessor(Succ);
11940b57cec5SDimitry Andric   if (!NMBB->isLayoutSuccessor(Succ)) {
11950b57cec5SDimitry Andric     SmallVector<MachineOperand, 4> Cond;
11960b57cec5SDimitry Andric     const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
11970b57cec5SDimitry Andric     TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
11980b57cec5SDimitry Andric 
11990b57cec5SDimitry Andric     if (Indexes) {
12000b57cec5SDimitry Andric       for (MachineInstr &MI : NMBB->instrs()) {
12010b57cec5SDimitry Andric         // Some instructions may have been moved to NMBB by updateTerminator(),
12020b57cec5SDimitry Andric         // so we first remove any instruction that already has an index.
12030b57cec5SDimitry Andric         if (Indexes->hasIndex(MI))
12040b57cec5SDimitry Andric           Indexes->removeMachineInstrFromMaps(MI);
12050b57cec5SDimitry Andric         Indexes->insertMachineInstrInMaps(MI);
12060b57cec5SDimitry Andric       }
12070b57cec5SDimitry Andric     }
12080b57cec5SDimitry Andric   }
12090b57cec5SDimitry Andric 
12108bcb0991SDimitry Andric   // Fix PHI nodes in Succ so they refer to NMBB instead of this.
12118bcb0991SDimitry Andric   Succ->replacePhiUsesWith(this, NMBB);
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric   // Inherit live-ins from the successor
12140b57cec5SDimitry Andric   for (const auto &LI : Succ->liveins())
12150b57cec5SDimitry Andric     NMBB->addLiveIn(LI);
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric   // Update LiveVariables.
12180b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
12190b57cec5SDimitry Andric   if (LV) {
12200b57cec5SDimitry Andric     // Restore kills of virtual registers that were killed by the terminators.
12210b57cec5SDimitry Andric     while (!KilledRegs.empty()) {
12225ffd83dbSDimitry Andric       Register Reg = KilledRegs.pop_back_val();
12230b57cec5SDimitry Andric       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
12240b57cec5SDimitry Andric         if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false))
12250b57cec5SDimitry Andric           continue;
1226bdd1243dSDimitry Andric         if (Reg.isVirtual())
12270b57cec5SDimitry Andric           LV->getVarInfo(Reg).Kills.push_back(&*I);
12280b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
12290b57cec5SDimitry Andric         break;
12300b57cec5SDimitry Andric       }
12310b57cec5SDimitry Andric     }
12320b57cec5SDimitry Andric     // Update relevant live-through information.
12335ffd83dbSDimitry Andric     if (LiveInSets != nullptr)
12345ffd83dbSDimitry Andric       LV->addNewBlock(NMBB, this, Succ, *LiveInSets);
12355ffd83dbSDimitry Andric     else
12360b57cec5SDimitry Andric       LV->addNewBlock(NMBB, this, Succ);
12370b57cec5SDimitry Andric   }
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric   if (LIS) {
12400b57cec5SDimitry Andric     // After splitting the edge and updating SlotIndexes, live intervals may be
12410b57cec5SDimitry Andric     // in one of two situations, depending on whether this block was the last in
12420b57cec5SDimitry Andric     // the function. If the original block was the last in the function, all
12430b57cec5SDimitry Andric     // live intervals will end prior to the beginning of the new split block. If
12440b57cec5SDimitry Andric     // the original block was not at the end of the function, all live intervals
12450b57cec5SDimitry Andric     // will extend to the end of the new split block.
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric     bool isLastMBB =
12480b57cec5SDimitry Andric       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
12510b57cec5SDimitry Andric     SlotIndex PrevIndex = StartIndex.getPrevSlot();
12520b57cec5SDimitry Andric     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric     // Find the registers used from NMBB in PHIs in Succ.
12555ffd83dbSDimitry Andric     SmallSet<Register, 8> PHISrcRegs;
12560b57cec5SDimitry Andric     for (MachineBasicBlock::instr_iterator
12570b57cec5SDimitry Andric          I = Succ->instr_begin(), E = Succ->instr_end();
12580b57cec5SDimitry Andric          I != E && I->isPHI(); ++I) {
12590b57cec5SDimitry Andric       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
12600b57cec5SDimitry Andric         if (I->getOperand(ni+1).getMBB() == NMBB) {
12610b57cec5SDimitry Andric           MachineOperand &MO = I->getOperand(ni);
12628bcb0991SDimitry Andric           Register Reg = MO.getReg();
12630b57cec5SDimitry Andric           PHISrcRegs.insert(Reg);
12640b57cec5SDimitry Andric           if (MO.isUndef())
12650b57cec5SDimitry Andric             continue;
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric           LiveInterval &LI = LIS->getInterval(Reg);
12680b57cec5SDimitry Andric           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
12690b57cec5SDimitry Andric           assert(VNI &&
12700b57cec5SDimitry Andric                  "PHI sources should be live out of their predecessors.");
12710b57cec5SDimitry Andric           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
12720b57cec5SDimitry Andric         }
12730b57cec5SDimitry Andric       }
12740b57cec5SDimitry Andric     }
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
12770b57cec5SDimitry Andric     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
12785ffd83dbSDimitry Andric       Register Reg = Register::index2VirtReg(i);
12790b57cec5SDimitry Andric       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
12800b57cec5SDimitry Andric         continue;
12810b57cec5SDimitry Andric 
12820b57cec5SDimitry Andric       LiveInterval &LI = LIS->getInterval(Reg);
12830b57cec5SDimitry Andric       if (!LI.liveAt(PrevIndex))
12840b57cec5SDimitry Andric         continue;
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
12870b57cec5SDimitry Andric       if (isLiveOut && isLastMBB) {
12880b57cec5SDimitry Andric         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
12890b57cec5SDimitry Andric         assert(VNI && "LiveInterval should have VNInfo where it is live.");
12900b57cec5SDimitry Andric         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
12910b57cec5SDimitry Andric       } else if (!isLiveOut && !isLastMBB) {
12920b57cec5SDimitry Andric         LI.removeSegment(StartIndex, EndIndex);
12930b57cec5SDimitry Andric       }
12940b57cec5SDimitry Andric     }
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric     // Update all intervals for registers whose uses may have been modified by
12970b57cec5SDimitry Andric     // updateTerminator().
12980b57cec5SDimitry Andric     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
12990b57cec5SDimitry Andric   }
13000b57cec5SDimitry Andric 
13010b57cec5SDimitry Andric   if (MachineDominatorTree *MDT =
13020b57cec5SDimitry Andric           P.getAnalysisIfAvailable<MachineDominatorTree>())
13030b57cec5SDimitry Andric     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
13060b57cec5SDimitry Andric     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
13070b57cec5SDimitry Andric       // If one or the other blocks were not in a loop, the new block is not
13080b57cec5SDimitry Andric       // either, and thus LI doesn't need to be updated.
13090b57cec5SDimitry Andric       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
13100b57cec5SDimitry Andric         if (TIL == DestLoop) {
13110b57cec5SDimitry Andric           // Both in the same loop, the NMBB joins loop.
13120b57cec5SDimitry Andric           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
13130b57cec5SDimitry Andric         } else if (TIL->contains(DestLoop)) {
13140b57cec5SDimitry Andric           // Edge from an outer loop to an inner loop.  Add to the outer loop.
13150b57cec5SDimitry Andric           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
13160b57cec5SDimitry Andric         } else if (DestLoop->contains(TIL)) {
13170b57cec5SDimitry Andric           // Edge from an inner loop to an outer loop.  Add to the outer loop.
13180b57cec5SDimitry Andric           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
13190b57cec5SDimitry Andric         } else {
13200b57cec5SDimitry Andric           // Edge from two loops with no containment relation.  Because these
13210b57cec5SDimitry Andric           // are natural loops, we know that the destination block must be the
13220b57cec5SDimitry Andric           // header of its loop (adding a branch into a loop elsewhere would
13230b57cec5SDimitry Andric           // create an irreducible loop).
13240b57cec5SDimitry Andric           assert(DestLoop->getHeader() == Succ &&
13250b57cec5SDimitry Andric                  "Should not create irreducible loops!");
13260b57cec5SDimitry Andric           if (MachineLoop *P = DestLoop->getParentLoop())
13270b57cec5SDimitry Andric             P->addBasicBlockToLoop(NMBB, MLI->getBase());
13280b57cec5SDimitry Andric         }
13290b57cec5SDimitry Andric       }
13300b57cec5SDimitry Andric     }
13310b57cec5SDimitry Andric 
13320b57cec5SDimitry Andric   return NMBB;
13330b57cec5SDimitry Andric }
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric bool MachineBasicBlock::canSplitCriticalEdge(
13360b57cec5SDimitry Andric     const MachineBasicBlock *Succ) const {
13370b57cec5SDimitry Andric   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
13380b57cec5SDimitry Andric   // it in this generic function.
13390b57cec5SDimitry Andric   if (Succ->isEHPad())
13400b57cec5SDimitry Andric     return false;
13410b57cec5SDimitry Andric 
13425ffd83dbSDimitry Andric   // Splitting the critical edge to a callbr's indirect block isn't advised.
13435ffd83dbSDimitry Andric   // Don't do it in this generic function.
13445ffd83dbSDimitry Andric   if (Succ->isInlineAsmBrIndirectTarget())
13455ffd83dbSDimitry Andric     return false;
13460b57cec5SDimitry Andric 
13475ffd83dbSDimitry Andric   const MachineFunction *MF = getParent();
13480b57cec5SDimitry Andric   // Performance might be harmed on HW that implements branching using exec mask
13490b57cec5SDimitry Andric   // where both sides of the branches are always executed.
13500b57cec5SDimitry Andric   if (MF->getTarget().requiresStructuredCFG())
13510b57cec5SDimitry Andric     return false;
13520b57cec5SDimitry Andric 
1353*fe013be4SDimitry Andric   // Do we have an Indirect jump with a jumptable that we can rewrite?
1354*fe013be4SDimitry Andric   int JTI = findJumpTableIndex(*this);
1355*fe013be4SDimitry Andric   if (JTI >= 0 && !jumpTableHasOtherUses(*MF, *this, JTI))
1356*fe013be4SDimitry Andric     return true;
1357*fe013be4SDimitry Andric 
13580b57cec5SDimitry Andric   // We may need to update this's terminator, but we can't do that if
1359*fe013be4SDimitry Andric   // analyzeBranch fails.
13600b57cec5SDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
13610b57cec5SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
13620b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
13630b57cec5SDimitry Andric   // AnalyzeBanch should modify this, since we did not allow modification.
13640b57cec5SDimitry Andric   if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
13650b57cec5SDimitry Andric                          /*AllowModify*/ false))
13660b57cec5SDimitry Andric     return false;
13670b57cec5SDimitry Andric 
13680b57cec5SDimitry Andric   // Avoid bugpoint weirdness: A block may end with a conditional branch but
13690b57cec5SDimitry Andric   // jumps to the same MBB is either case. We have duplicate CFG edges in that
13700b57cec5SDimitry Andric   // case that we can't handle. Since this never happens in properly optimized
13710b57cec5SDimitry Andric   // code, just skip those edges.
13720b57cec5SDimitry Andric   if (TBB && TBB == FBB) {
13730b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
13740b57cec5SDimitry Andric                       << printMBBReference(*this) << '\n');
13750b57cec5SDimitry Andric     return false;
13760b57cec5SDimitry Andric   }
13770b57cec5SDimitry Andric   return true;
13780b57cec5SDimitry Andric }
13790b57cec5SDimitry Andric 
13800b57cec5SDimitry Andric /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
13810b57cec5SDimitry Andric /// neighboring instructions so the bundle won't be broken by removing MI.
13820b57cec5SDimitry Andric static void unbundleSingleMI(MachineInstr *MI) {
13830b57cec5SDimitry Andric   // Removing the first instruction in a bundle.
13840b57cec5SDimitry Andric   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
13850b57cec5SDimitry Andric     MI->unbundleFromSucc();
13860b57cec5SDimitry Andric   // Removing the last instruction in a bundle.
13870b57cec5SDimitry Andric   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
13880b57cec5SDimitry Andric     MI->unbundleFromPred();
13890b57cec5SDimitry Andric   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
13900b57cec5SDimitry Andric   // are already fine.
13910b57cec5SDimitry Andric }
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric MachineBasicBlock::instr_iterator
13940b57cec5SDimitry Andric MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
13950b57cec5SDimitry Andric   unbundleSingleMI(&*I);
13960b57cec5SDimitry Andric   return Insts.erase(I);
13970b57cec5SDimitry Andric }
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
14000b57cec5SDimitry Andric   unbundleSingleMI(MI);
14010b57cec5SDimitry Andric   MI->clearFlag(MachineInstr::BundledPred);
14020b57cec5SDimitry Andric   MI->clearFlag(MachineInstr::BundledSucc);
14030b57cec5SDimitry Andric   return Insts.remove(MI);
14040b57cec5SDimitry Andric }
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric MachineBasicBlock::instr_iterator
14070b57cec5SDimitry Andric MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
14080b57cec5SDimitry Andric   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
14090b57cec5SDimitry Andric          "Cannot insert instruction with bundle flags");
14100b57cec5SDimitry Andric   // Set the bundle flags when inserting inside a bundle.
14110b57cec5SDimitry Andric   if (I != instr_end() && I->isBundledWithPred()) {
14120b57cec5SDimitry Andric     MI->setFlag(MachineInstr::BundledPred);
14130b57cec5SDimitry Andric     MI->setFlag(MachineInstr::BundledSucc);
14140b57cec5SDimitry Andric   }
14150b57cec5SDimitry Andric   return Insts.insert(I, MI);
14160b57cec5SDimitry Andric }
14170b57cec5SDimitry Andric 
14180b57cec5SDimitry Andric /// This method unlinks 'this' from the containing function, and returns it, but
14190b57cec5SDimitry Andric /// does not delete it.
14200b57cec5SDimitry Andric MachineBasicBlock *MachineBasicBlock::removeFromParent() {
14210b57cec5SDimitry Andric   assert(getParent() && "Not embedded in a function!");
14220b57cec5SDimitry Andric   getParent()->remove(this);
14230b57cec5SDimitry Andric   return this;
14240b57cec5SDimitry Andric }
14250b57cec5SDimitry Andric 
14260b57cec5SDimitry Andric /// This method unlinks 'this' from the containing function, and deletes it.
14270b57cec5SDimitry Andric void MachineBasicBlock::eraseFromParent() {
14280b57cec5SDimitry Andric   assert(getParent() && "Not embedded in a function!");
14290b57cec5SDimitry Andric   getParent()->erase(this);
14300b57cec5SDimitry Andric }
14310b57cec5SDimitry Andric 
14320b57cec5SDimitry Andric /// Given a machine basic block that branched to 'Old', change the code and CFG
14330b57cec5SDimitry Andric /// so that it branches to 'New' instead.
14340b57cec5SDimitry Andric void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
14350b57cec5SDimitry Andric                                                MachineBasicBlock *New) {
14360b57cec5SDimitry Andric   assert(Old != New && "Cannot replace self with self!");
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric   MachineBasicBlock::instr_iterator I = instr_end();
14390b57cec5SDimitry Andric   while (I != instr_begin()) {
14400b57cec5SDimitry Andric     --I;
14410b57cec5SDimitry Andric     if (!I->isTerminator()) break;
14420b57cec5SDimitry Andric 
14430b57cec5SDimitry Andric     // Scan the operands of this machine instruction, replacing any uses of Old
14440b57cec5SDimitry Andric     // with New.
14450b57cec5SDimitry Andric     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
14460b57cec5SDimitry Andric       if (I->getOperand(i).isMBB() &&
14470b57cec5SDimitry Andric           I->getOperand(i).getMBB() == Old)
14480b57cec5SDimitry Andric         I->getOperand(i).setMBB(New);
14490b57cec5SDimitry Andric   }
14500b57cec5SDimitry Andric 
14510b57cec5SDimitry Andric   // Update the successor information.
14520b57cec5SDimitry Andric   replaceSuccessor(Old, New);
14530b57cec5SDimitry Andric }
14540b57cec5SDimitry Andric 
14558bcb0991SDimitry Andric void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old,
14568bcb0991SDimitry Andric                                            MachineBasicBlock *New) {
14578bcb0991SDimitry Andric   for (MachineInstr &MI : phis())
14588bcb0991SDimitry Andric     for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
14598bcb0991SDimitry Andric       MachineOperand &MO = MI.getOperand(i);
14608bcb0991SDimitry Andric       if (MO.getMBB() == Old)
14618bcb0991SDimitry Andric         MO.setMBB(New);
14628bcb0991SDimitry Andric     }
14638bcb0991SDimitry Andric }
14648bcb0991SDimitry Andric 
1465*fe013be4SDimitry Andric /// Find the next valid DebugLoc starting at MBBI, skipping any debug
14660b57cec5SDimitry Andric /// instructions.  Return UnknownLoc if there is none.
14670b57cec5SDimitry Andric DebugLoc
14680b57cec5SDimitry Andric MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
14690b57cec5SDimitry Andric   // Skip debug declarations, we don't want a DebugLoc from them.
14700b57cec5SDimitry Andric   MBBI = skipDebugInstructionsForward(MBBI, instr_end());
14710b57cec5SDimitry Andric   if (MBBI != instr_end())
14720b57cec5SDimitry Andric     return MBBI->getDebugLoc();
14730b57cec5SDimitry Andric   return {};
14740b57cec5SDimitry Andric }
14750b57cec5SDimitry Andric 
1476fe6060f1SDimitry Andric DebugLoc MachineBasicBlock::rfindDebugLoc(reverse_instr_iterator MBBI) {
1477*fe013be4SDimitry Andric   if (MBBI == instr_rend())
1478*fe013be4SDimitry Andric     return findDebugLoc(instr_begin());
1479fe6060f1SDimitry Andric   // Skip debug declarations, we don't want a DebugLoc from them.
1480fe6060f1SDimitry Andric   MBBI = skipDebugInstructionsBackward(MBBI, instr_rbegin());
1481fe6060f1SDimitry Andric   if (!MBBI->isDebugInstr())
1482fe6060f1SDimitry Andric     return MBBI->getDebugLoc();
1483fe6060f1SDimitry Andric   return {};
1484fe6060f1SDimitry Andric }
1485fe6060f1SDimitry Andric 
1486*fe013be4SDimitry Andric /// Find the previous valid DebugLoc preceding MBBI, skipping any debug
14870b57cec5SDimitry Andric /// instructions.  Return UnknownLoc if there is none.
14880b57cec5SDimitry Andric DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) {
1489*fe013be4SDimitry Andric   if (MBBI == instr_begin())
1490*fe013be4SDimitry Andric     return {};
14915ffd83dbSDimitry Andric   // Skip debug instructions, we don't want a DebugLoc from them.
14925ffd83dbSDimitry Andric   MBBI = prev_nodbg(MBBI, instr_begin());
1493*fe013be4SDimitry Andric   if (!MBBI->isDebugInstr())
1494*fe013be4SDimitry Andric     return MBBI->getDebugLoc();
14950b57cec5SDimitry Andric   return {};
14960b57cec5SDimitry Andric }
14970b57cec5SDimitry Andric 
1498fe6060f1SDimitry Andric DebugLoc MachineBasicBlock::rfindPrevDebugLoc(reverse_instr_iterator MBBI) {
1499fe6060f1SDimitry Andric   if (MBBI == instr_rend())
1500fe6060f1SDimitry Andric     return {};
1501fe6060f1SDimitry Andric   // Skip debug declarations, we don't want a DebugLoc from them.
1502fe6060f1SDimitry Andric   MBBI = next_nodbg(MBBI, instr_rend());
1503fe6060f1SDimitry Andric   if (MBBI != instr_rend())
1504fe6060f1SDimitry Andric     return MBBI->getDebugLoc();
1505fe6060f1SDimitry Andric   return {};
1506fe6060f1SDimitry Andric }
1507fe6060f1SDimitry Andric 
15080b57cec5SDimitry Andric /// Find and return the merged DebugLoc of the branch instructions of the block.
15090b57cec5SDimitry Andric /// Return UnknownLoc if there is none.
15100b57cec5SDimitry Andric DebugLoc
15110b57cec5SDimitry Andric MachineBasicBlock::findBranchDebugLoc() {
15120b57cec5SDimitry Andric   DebugLoc DL;
15130b57cec5SDimitry Andric   auto TI = getFirstTerminator();
15140b57cec5SDimitry Andric   while (TI != end() && !TI->isBranch())
15150b57cec5SDimitry Andric     ++TI;
15160b57cec5SDimitry Andric 
15170b57cec5SDimitry Andric   if (TI != end()) {
15180b57cec5SDimitry Andric     DL = TI->getDebugLoc();
15190b57cec5SDimitry Andric     for (++TI ; TI != end() ; ++TI)
15200b57cec5SDimitry Andric       if (TI->isBranch())
15210b57cec5SDimitry Andric         DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
15220b57cec5SDimitry Andric   }
15230b57cec5SDimitry Andric   return DL;
15240b57cec5SDimitry Andric }
15250b57cec5SDimitry Andric 
15260b57cec5SDimitry Andric /// Return probability of the edge from this block to MBB.
15270b57cec5SDimitry Andric BranchProbability
15280b57cec5SDimitry Andric MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
15290b57cec5SDimitry Andric   if (Probs.empty())
15300b57cec5SDimitry Andric     return BranchProbability(1, succ_size());
15310b57cec5SDimitry Andric 
15320b57cec5SDimitry Andric   const auto &Prob = *getProbabilityIterator(Succ);
15330b57cec5SDimitry Andric   if (Prob.isUnknown()) {
15340b57cec5SDimitry Andric     // For unknown probabilities, collect the sum of all known ones, and evenly
15350b57cec5SDimitry Andric     // ditribute the complemental of the sum to each unknown probability.
15360b57cec5SDimitry Andric     unsigned KnownProbNum = 0;
15370b57cec5SDimitry Andric     auto Sum = BranchProbability::getZero();
1538fcaf7f86SDimitry Andric     for (const auto &P : Probs) {
15390b57cec5SDimitry Andric       if (!P.isUnknown()) {
15400b57cec5SDimitry Andric         Sum += P;
15410b57cec5SDimitry Andric         KnownProbNum++;
15420b57cec5SDimitry Andric       }
15430b57cec5SDimitry Andric     }
15440b57cec5SDimitry Andric     return Sum.getCompl() / (Probs.size() - KnownProbNum);
15450b57cec5SDimitry Andric   } else
15460b57cec5SDimitry Andric     return Prob;
15470b57cec5SDimitry Andric }
15480b57cec5SDimitry Andric 
15490b57cec5SDimitry Andric /// Set successor probability of a given iterator.
15500b57cec5SDimitry Andric void MachineBasicBlock::setSuccProbability(succ_iterator I,
15510b57cec5SDimitry Andric                                            BranchProbability Prob) {
15520b57cec5SDimitry Andric   assert(!Prob.isUnknown());
15530b57cec5SDimitry Andric   if (Probs.empty())
15540b57cec5SDimitry Andric     return;
15550b57cec5SDimitry Andric   *getProbabilityIterator(I) = Prob;
15560b57cec5SDimitry Andric }
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric /// Return probability iterator corresonding to the I successor iterator
15590b57cec5SDimitry Andric MachineBasicBlock::const_probability_iterator
15600b57cec5SDimitry Andric MachineBasicBlock::getProbabilityIterator(
15610b57cec5SDimitry Andric     MachineBasicBlock::const_succ_iterator I) const {
15620b57cec5SDimitry Andric   assert(Probs.size() == Successors.size() && "Async probability list!");
15630b57cec5SDimitry Andric   const size_t index = std::distance(Successors.begin(), I);
15640b57cec5SDimitry Andric   assert(index < Probs.size() && "Not a current successor!");
15650b57cec5SDimitry Andric   return Probs.begin() + index;
15660b57cec5SDimitry Andric }
15670b57cec5SDimitry Andric 
15680b57cec5SDimitry Andric /// Return probability iterator corresonding to the I successor iterator.
15690b57cec5SDimitry Andric MachineBasicBlock::probability_iterator
15700b57cec5SDimitry Andric MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
15710b57cec5SDimitry Andric   assert(Probs.size() == Successors.size() && "Async probability list!");
15720b57cec5SDimitry Andric   const size_t index = std::distance(Successors.begin(), I);
15730b57cec5SDimitry Andric   assert(index < Probs.size() && "Not a current successor!");
15740b57cec5SDimitry Andric   return Probs.begin() + index;
15750b57cec5SDimitry Andric }
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
15780b57cec5SDimitry Andric /// as of just before "MI".
15790b57cec5SDimitry Andric ///
15800b57cec5SDimitry Andric /// Search is localised to a neighborhood of
15810b57cec5SDimitry Andric /// Neighborhood instructions before (searching for defs or kills) and N
15820b57cec5SDimitry Andric /// instructions after (searching just for defs) MI.
15830b57cec5SDimitry Andric MachineBasicBlock::LivenessQueryResult
15840b57cec5SDimitry Andric MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
15855ffd83dbSDimitry Andric                                            MCRegister Reg, const_iterator Before,
15860b57cec5SDimitry Andric                                            unsigned Neighborhood) const {
15870b57cec5SDimitry Andric   unsigned N = Neighborhood;
15880b57cec5SDimitry Andric 
15890b57cec5SDimitry Andric   // Try searching forwards from Before, looking for reads or defs.
15900b57cec5SDimitry Andric   const_iterator I(Before);
15910b57cec5SDimitry Andric   for (; I != end() && N > 0; ++I) {
1592fe6060f1SDimitry Andric     if (I->isDebugOrPseudoInstr())
15930b57cec5SDimitry Andric       continue;
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric     --N;
15960b57cec5SDimitry Andric 
1597480093f4SDimitry Andric     PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric     // Register is live when we read it here.
16000b57cec5SDimitry Andric     if (Info.Read)
16010b57cec5SDimitry Andric       return LQR_Live;
16020b57cec5SDimitry Andric     // Register is dead if we can fully overwrite or clobber it here.
16030b57cec5SDimitry Andric     if (Info.FullyDefined || Info.Clobbered)
16040b57cec5SDimitry Andric       return LQR_Dead;
16050b57cec5SDimitry Andric   }
16060b57cec5SDimitry Andric 
16070b57cec5SDimitry Andric   // If we reached the end, it is safe to clobber Reg at the end of a block of
16080b57cec5SDimitry Andric   // no successor has it live in.
16090b57cec5SDimitry Andric   if (I == end()) {
16100b57cec5SDimitry Andric     for (MachineBasicBlock *S : successors()) {
16110b57cec5SDimitry Andric       for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
16120b57cec5SDimitry Andric         if (TRI->regsOverlap(LI.PhysReg, Reg))
16130b57cec5SDimitry Andric           return LQR_Live;
16140b57cec5SDimitry Andric       }
16150b57cec5SDimitry Andric     }
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric     return LQR_Dead;
16180b57cec5SDimitry Andric   }
16190b57cec5SDimitry Andric 
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric   N = Neighborhood;
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric   // Start by searching backwards from Before, looking for kills, reads or defs.
16240b57cec5SDimitry Andric   I = const_iterator(Before);
16250b57cec5SDimitry Andric   // If this is the first insn in the block, don't search backwards.
16260b57cec5SDimitry Andric   if (I != begin()) {
16270b57cec5SDimitry Andric     do {
16280b57cec5SDimitry Andric       --I;
16290b57cec5SDimitry Andric 
1630fe6060f1SDimitry Andric       if (I->isDebugOrPseudoInstr())
16310b57cec5SDimitry Andric         continue;
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric       --N;
16340b57cec5SDimitry Andric 
1635480093f4SDimitry Andric       PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric       // Defs happen after uses so they take precedence if both are present.
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric       // Register is dead after a dead def of the full register.
16400b57cec5SDimitry Andric       if (Info.DeadDef)
16410b57cec5SDimitry Andric         return LQR_Dead;
16420b57cec5SDimitry Andric       // Register is (at least partially) live after a def.
16430b57cec5SDimitry Andric       if (Info.Defined) {
16440b57cec5SDimitry Andric         if (!Info.PartialDeadDef)
16450b57cec5SDimitry Andric           return LQR_Live;
16460b57cec5SDimitry Andric         // As soon as we saw a partial definition (dead or not),
16470b57cec5SDimitry Andric         // we cannot tell if the value is partial live without
16480b57cec5SDimitry Andric         // tracking the lanemasks. We are not going to do this,
16490b57cec5SDimitry Andric         // so fall back on the remaining of the analysis.
16500b57cec5SDimitry Andric         break;
16510b57cec5SDimitry Andric       }
16520b57cec5SDimitry Andric       // Register is dead after a full kill or clobber and no def.
16530b57cec5SDimitry Andric       if (Info.Killed || Info.Clobbered)
16540b57cec5SDimitry Andric         return LQR_Dead;
16550b57cec5SDimitry Andric       // Register must be live if we read it.
16560b57cec5SDimitry Andric       if (Info.Read)
16570b57cec5SDimitry Andric         return LQR_Live;
16580b57cec5SDimitry Andric 
16590b57cec5SDimitry Andric     } while (I != begin() && N > 0);
16600b57cec5SDimitry Andric   }
16610b57cec5SDimitry Andric 
1662480093f4SDimitry Andric   // If all the instructions before this in the block are debug instructions,
1663480093f4SDimitry Andric   // skip over them.
1664fe6060f1SDimitry Andric   while (I != begin() && std::prev(I)->isDebugOrPseudoInstr())
1665480093f4SDimitry Andric     --I;
1666480093f4SDimitry Andric 
16670b57cec5SDimitry Andric   // Did we get to the start of the block?
16680b57cec5SDimitry Andric   if (I == begin()) {
16690b57cec5SDimitry Andric     // If so, the register's state is definitely defined by the live-in state.
16700b57cec5SDimitry Andric     for (const MachineBasicBlock::RegisterMaskPair &LI : liveins())
16710b57cec5SDimitry Andric       if (TRI->regsOverlap(LI.PhysReg, Reg))
16720b57cec5SDimitry Andric         return LQR_Live;
16730b57cec5SDimitry Andric 
16740b57cec5SDimitry Andric     return LQR_Dead;
16750b57cec5SDimitry Andric   }
16760b57cec5SDimitry Andric 
16770b57cec5SDimitry Andric   // At this point we have no idea of the liveness of the register.
16780b57cec5SDimitry Andric   return LQR_Unknown;
16790b57cec5SDimitry Andric }
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric const uint32_t *
16820b57cec5SDimitry Andric MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
16830b57cec5SDimitry Andric   // EH funclet entry does not preserve any registers.
16840b57cec5SDimitry Andric   return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
16850b57cec5SDimitry Andric }
16860b57cec5SDimitry Andric 
16870b57cec5SDimitry Andric const uint32_t *
16880b57cec5SDimitry Andric MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
16890b57cec5SDimitry Andric   // If we see a return block with successors, this must be a funclet return,
16900b57cec5SDimitry Andric   // which does not preserve any registers. If there are no successors, we don't
16910b57cec5SDimitry Andric   // care what kind of return it is, putting a mask after it is a no-op.
16920b57cec5SDimitry Andric   return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
16930b57cec5SDimitry Andric }
16940b57cec5SDimitry Andric 
16950b57cec5SDimitry Andric void MachineBasicBlock::clearLiveIns() {
16960b57cec5SDimitry Andric   LiveIns.clear();
16970b57cec5SDimitry Andric }
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
17000b57cec5SDimitry Andric   assert(getParent()->getProperties().hasProperty(
17010b57cec5SDimitry Andric       MachineFunctionProperties::Property::TracksLiveness) &&
17020b57cec5SDimitry Andric       "Liveness information is accurate");
17030b57cec5SDimitry Andric   return LiveIns.begin();
17040b57cec5SDimitry Andric }
17055ffd83dbSDimitry Andric 
1706fe6060f1SDimitry Andric MachineBasicBlock::liveout_iterator MachineBasicBlock::liveout_begin() const {
1707fe6060f1SDimitry Andric   const MachineFunction &MF = *getParent();
1708fe6060f1SDimitry Andric   assert(MF.getProperties().hasProperty(
1709fe6060f1SDimitry Andric       MachineFunctionProperties::Property::TracksLiveness) &&
1710fe6060f1SDimitry Andric       "Liveness information is accurate");
1711fe6060f1SDimitry Andric 
1712fe6060f1SDimitry Andric   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1713fe6060f1SDimitry Andric   MCPhysReg ExceptionPointer = 0, ExceptionSelector = 0;
1714fe6060f1SDimitry Andric   if (MF.getFunction().hasPersonalityFn()) {
1715fe6060f1SDimitry Andric     auto PersonalityFn = MF.getFunction().getPersonalityFn();
1716fe6060f1SDimitry Andric     ExceptionPointer = TLI.getExceptionPointerRegister(PersonalityFn);
1717fe6060f1SDimitry Andric     ExceptionSelector = TLI.getExceptionSelectorRegister(PersonalityFn);
1718fe6060f1SDimitry Andric   }
1719fe6060f1SDimitry Andric 
1720fe6060f1SDimitry Andric   return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false);
1721fe6060f1SDimitry Andric }
1722fe6060f1SDimitry Andric 
172381ad6265SDimitry Andric bool MachineBasicBlock::sizeWithoutDebugLargerThan(unsigned Limit) const {
172481ad6265SDimitry Andric   unsigned Cntr = 0;
172581ad6265SDimitry Andric   auto R = instructionsWithoutDebug(begin(), end());
172681ad6265SDimitry Andric   for (auto I = R.begin(), E = R.end(); I != E; ++I) {
172781ad6265SDimitry Andric     if (++Cntr > Limit)
172881ad6265SDimitry Andric       return true;
172981ad6265SDimitry Andric   }
173081ad6265SDimitry Andric   return false;
173181ad6265SDimitry Andric }
173281ad6265SDimitry Andric 
1733bdd1243dSDimitry Andric unsigned MachineBasicBlock::getBBIDOrNumber() const {
1734bdd1243dSDimitry Andric   uint8_t BBAddrMapVersion = getParent()->getContext().getBBAddrMapVersion();
1735bdd1243dSDimitry Andric   return BBAddrMapVersion < 2 ? getNumber() : *getBBID();
1736bdd1243dSDimitry Andric }
1737bdd1243dSDimitry Andric 
17385ffd83dbSDimitry Andric const MBBSectionID MBBSectionID::ColdSectionID(MBBSectionID::SectionType::Cold);
17395ffd83dbSDimitry Andric const MBBSectionID
17405ffd83dbSDimitry Andric     MBBSectionID::ExceptionSectionID(MBBSectionID::SectionType::Exception);
1741