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"
15fe013be4SDimitry 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"
22fe013be4SDimitry 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 
MachineBasicBlock(MachineFunction & MF,const BasicBlock * B)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.
getSymbol() const610b57cec5SDimitry 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 
getEHCatchretSymbol() const92fe6060f1SDimitry 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 
getEndSymbol() const103e8d8bef9SDimitry 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 
operator <<(raw_ostream & OS,const MachineBasicBlock & MBB)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 
printMBBReference(const MachineBasicBlock & MBB)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.
addNodeToList(MachineBasicBlock * N)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 
removeNodeFromList(MachineBasicBlock * N)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.
addNodeToList(MachineInstr * N)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.
removeNodeFromList(MachineInstr * N)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.
transferNodesFromList(ilist_traits & FromList,instr_iterator First,instr_iterator Last)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 
deleteNode(MachineInstr * MI)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 
getFirstNonPHI()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
SkipPHIsAndLabels(MachineBasicBlock::iterator I)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
SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I,Register Reg,bool SkipPseudoOp)225fe6060f1SDimitry Andric MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I,
226*c9157d92SDimitry Andric                                           Register Reg, 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()) ||
232*c9157d92SDimitry Andric                     TII->isBasicBlockPrologue(*I, Reg)))
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 
getFirstTerminator()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 
getFirstInstrTerminator()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 
getFirstTerminatorForward()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
getFirstNonDebugInstr(bool SkipPseudoOp)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
getLastNonDebugInstr(bool SkipPseudoOp)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 
hasEHPadSuccessor() const2870b57cec5SDimitry 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 
isEntryBlock() const294e8d8bef9SDimitry Andric bool MachineBasicBlock::isEntryBlock() const {
295e8d8bef9SDimitry Andric   return getParent()->begin() == getIterator();
296e8d8bef9SDimitry Andric }
297e8d8bef9SDimitry Andric 
2980b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const2990b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
3000b57cec5SDimitry Andric   print(dbgs());
3010b57cec5SDimitry Andric }
3020b57cec5SDimitry Andric #endif
3030b57cec5SDimitry Andric 
mayHaveInlineAsmBr() const3045ffd83dbSDimitry 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 
isLegalToHoistInto() const3120b57cec5SDimitry Andric bool MachineBasicBlock::isLegalToHoistInto() const {
3135ffd83dbSDimitry Andric   if (isReturnBlock() || hasEHPadSuccessor() || mayHaveInlineAsmBr())
3140b57cec5SDimitry Andric     return false;
3150b57cec5SDimitry Andric   return true;
3160b57cec5SDimitry Andric }
3170b57cec5SDimitry Andric 
getName() const3180b57cec5SDimitry 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.
getFullName() const3260b57cec5SDimitry 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 
print(raw_ostream & OS,const SlotIndexes * Indexes,bool IsStandalone) const3370b57cec5SDimitry 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 
print(raw_ostream & OS,ModuleSlotTracker & MST,const SlotIndexes * Indexes,bool IsStandalone) const3520b57cec5SDimitry 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.
printName(raw_ostream & os,unsigned printNameFlags,ModuleSlotTracker * moduleSlotTracker) const482e8d8bef9SDimitry 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 ? ", " : " (");
570*c9157d92SDimitry Andric       os << "bb_id " << getBBID()->BaseID;
571*c9157d92SDimitry Andric       if (getBBID()->CloneID != 0)
572*c9157d92SDimitry Andric         os << " " << getBBID()->CloneID;
573*c9157d92SDimitry Andric       hasAttributes = true;
574*c9157d92SDimitry Andric     }
575*c9157d92SDimitry Andric     if (CallFrameSize != 0) {
576*c9157d92SDimitry Andric       os << (hasAttributes ? ", " : " (");
577*c9157d92SDimitry Andric       os << "call-frame-size " << CallFrameSize;
578bdd1243dSDimitry Andric       hasAttributes = true;
579bdd1243dSDimitry Andric     }
580e8d8bef9SDimitry Andric   }
581e8d8bef9SDimitry Andric 
582e8d8bef9SDimitry Andric   if (hasAttributes)
583e8d8bef9SDimitry Andric     os << ')';
584e8d8bef9SDimitry Andric }
585e8d8bef9SDimitry Andric 
printAsOperand(raw_ostream & OS,bool) const5860b57cec5SDimitry Andric void MachineBasicBlock::printAsOperand(raw_ostream &OS,
5870b57cec5SDimitry Andric                                        bool /*PrintType*/) const {
588e8d8bef9SDimitry Andric   OS << '%';
589e8d8bef9SDimitry Andric   printName(OS, 0);
5900b57cec5SDimitry Andric }
5910b57cec5SDimitry Andric 
removeLiveIn(MCPhysReg Reg,LaneBitmask LaneMask)5920b57cec5SDimitry Andric void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
5930b57cec5SDimitry Andric   LiveInVector::iterator I = find_if(
5940b57cec5SDimitry Andric       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
5950b57cec5SDimitry Andric   if (I == LiveIns.end())
5960b57cec5SDimitry Andric     return;
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric   I->LaneMask &= ~LaneMask;
5990b57cec5SDimitry Andric   if (I->LaneMask.none())
6000b57cec5SDimitry Andric     LiveIns.erase(I);
6010b57cec5SDimitry Andric }
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric MachineBasicBlock::livein_iterator
removeLiveIn(MachineBasicBlock::livein_iterator I)6040b57cec5SDimitry Andric MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
6050b57cec5SDimitry Andric   // Get non-const version of iterator.
6060b57cec5SDimitry Andric   LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
6070b57cec5SDimitry Andric   return LiveIns.erase(LI);
6080b57cec5SDimitry Andric }
6090b57cec5SDimitry Andric 
isLiveIn(MCPhysReg Reg,LaneBitmask LaneMask) const6100b57cec5SDimitry Andric bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
6110b57cec5SDimitry Andric   livein_iterator I = find_if(
6120b57cec5SDimitry Andric       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
6130b57cec5SDimitry Andric   return I != livein_end() && (I->LaneMask & LaneMask).any();
6140b57cec5SDimitry Andric }
6150b57cec5SDimitry Andric 
sortUniqueLiveIns()6160b57cec5SDimitry Andric void MachineBasicBlock::sortUniqueLiveIns() {
6170b57cec5SDimitry Andric   llvm::sort(LiveIns,
6180b57cec5SDimitry Andric              [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
6190b57cec5SDimitry Andric                return LI0.PhysReg < LI1.PhysReg;
6200b57cec5SDimitry Andric              });
6210b57cec5SDimitry Andric   // Liveins are sorted by physreg now we can merge their lanemasks.
6220b57cec5SDimitry Andric   LiveInVector::const_iterator I = LiveIns.begin();
6230b57cec5SDimitry Andric   LiveInVector::const_iterator J;
6240b57cec5SDimitry Andric   LiveInVector::iterator Out = LiveIns.begin();
6250b57cec5SDimitry Andric   for (; I != LiveIns.end(); ++Out, I = J) {
6265ffd83dbSDimitry Andric     MCRegister PhysReg = I->PhysReg;
6270b57cec5SDimitry Andric     LaneBitmask LaneMask = I->LaneMask;
6280b57cec5SDimitry Andric     for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
6290b57cec5SDimitry Andric       LaneMask |= J->LaneMask;
6300b57cec5SDimitry Andric     Out->PhysReg = PhysReg;
6310b57cec5SDimitry Andric     Out->LaneMask = LaneMask;
6320b57cec5SDimitry Andric   }
6330b57cec5SDimitry Andric   LiveIns.erase(Out, LiveIns.end());
6340b57cec5SDimitry Andric }
6350b57cec5SDimitry Andric 
6365ffd83dbSDimitry Andric Register
addLiveIn(MCRegister PhysReg,const TargetRegisterClass * RC)6378bcb0991SDimitry Andric MachineBasicBlock::addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC) {
6380b57cec5SDimitry Andric   assert(getParent() && "MBB must be inserted in function");
639e8d8bef9SDimitry Andric   assert(Register::isPhysicalRegister(PhysReg) && "Expected physreg");
6400b57cec5SDimitry Andric   assert(RC && "Register class is required");
6410b57cec5SDimitry Andric   assert((isEHPad() || this == &getParent()->front()) &&
6420b57cec5SDimitry Andric          "Only the entry block and landing pads can have physreg live ins");
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric   bool LiveIn = isLiveIn(PhysReg);
6450b57cec5SDimitry Andric   iterator I = SkipPHIsAndLabels(begin()), E = end();
6460b57cec5SDimitry Andric   MachineRegisterInfo &MRI = getParent()->getRegInfo();
6470b57cec5SDimitry Andric   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric   // Look for an existing copy.
6500b57cec5SDimitry Andric   if (LiveIn)
6510b57cec5SDimitry Andric     for (;I != E && I->isCopy(); ++I)
6520b57cec5SDimitry Andric       if (I->getOperand(1).getReg() == PhysReg) {
6538bcb0991SDimitry Andric         Register VirtReg = I->getOperand(0).getReg();
6540b57cec5SDimitry Andric         if (!MRI.constrainRegClass(VirtReg, RC))
6550b57cec5SDimitry Andric           llvm_unreachable("Incompatible live-in register class.");
6560b57cec5SDimitry Andric         return VirtReg;
6570b57cec5SDimitry Andric       }
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric   // No luck, create a virtual register.
6608bcb0991SDimitry Andric   Register VirtReg = MRI.createVirtualRegister(RC);
6610b57cec5SDimitry Andric   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
6620b57cec5SDimitry Andric     .addReg(PhysReg, RegState::Kill);
6630b57cec5SDimitry Andric   if (!LiveIn)
6640b57cec5SDimitry Andric     addLiveIn(PhysReg);
6650b57cec5SDimitry Andric   return VirtReg;
6660b57cec5SDimitry Andric }
6670b57cec5SDimitry Andric 
moveBefore(MachineBasicBlock * NewAfter)6680b57cec5SDimitry Andric void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
6690b57cec5SDimitry Andric   getParent()->splice(NewAfter->getIterator(), getIterator());
6700b57cec5SDimitry Andric }
6710b57cec5SDimitry Andric 
moveAfter(MachineBasicBlock * NewBefore)6720b57cec5SDimitry Andric void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
6730b57cec5SDimitry Andric   getParent()->splice(++NewBefore->getIterator(), getIterator());
6740b57cec5SDimitry Andric }
6750b57cec5SDimitry Andric 
findJumpTableIndex(const MachineBasicBlock & MBB)676fe013be4SDimitry Andric static int findJumpTableIndex(const MachineBasicBlock &MBB) {
677fe013be4SDimitry Andric   MachineBasicBlock::const_iterator TerminatorI = MBB.getFirstTerminator();
678fe013be4SDimitry Andric   if (TerminatorI == MBB.end())
679fe013be4SDimitry Andric     return -1;
680fe013be4SDimitry Andric   const MachineInstr &Terminator = *TerminatorI;
681fe013be4SDimitry Andric   const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
682fe013be4SDimitry Andric   return TII->getJumpTableIndex(Terminator);
683fe013be4SDimitry Andric }
684fe013be4SDimitry Andric 
updateTerminator(MachineBasicBlock * PreviousLayoutSuccessor)6855ffd83dbSDimitry Andric void MachineBasicBlock::updateTerminator(
6865ffd83dbSDimitry Andric     MachineBasicBlock *PreviousLayoutSuccessor) {
6875ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
6885ffd83dbSDimitry Andric                     << "\n");
6895ffd83dbSDimitry Andric 
6900b57cec5SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
6910b57cec5SDimitry Andric   // A block with no successors has no concerns with fall-through edges.
6920b57cec5SDimitry Andric   if (this->succ_empty())
6930b57cec5SDimitry Andric     return;
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
6960b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
6970b57cec5SDimitry Andric   DebugLoc DL = findBranchDebugLoc();
6980b57cec5SDimitry Andric   bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
6990b57cec5SDimitry Andric   (void) B;
7000b57cec5SDimitry Andric   assert(!B && "UpdateTerminators requires analyzable predecessors!");
7010b57cec5SDimitry Andric   if (Cond.empty()) {
7020b57cec5SDimitry Andric     if (TBB) {
7030b57cec5SDimitry Andric       // The block has an unconditional branch. If its successor is now its
7040b57cec5SDimitry Andric       // layout successor, delete the branch.
7050b57cec5SDimitry Andric       if (isLayoutSuccessor(TBB))
7060b57cec5SDimitry Andric         TII->removeBranch(*this);
7070b57cec5SDimitry Andric     } else {
7085ffd83dbSDimitry Andric       // The block has an unconditional fallthrough, or the end of the block is
7095ffd83dbSDimitry Andric       // unreachable.
7100b57cec5SDimitry Andric 
7115ffd83dbSDimitry Andric       // Unfortunately, whether the end of the block is unreachable is not
7125ffd83dbSDimitry Andric       // immediately obvious; we must fall back to checking the successor list,
7135ffd83dbSDimitry Andric       // and assuming that if the passed in block is in the succesor list and
7145ffd83dbSDimitry Andric       // not an EHPad, it must be the intended target.
7155ffd83dbSDimitry Andric       if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) ||
7165ffd83dbSDimitry Andric           PreviousLayoutSuccessor->isEHPad())
7170b57cec5SDimitry Andric         return;
7180b57cec5SDimitry Andric 
7195ffd83dbSDimitry Andric       // If the unconditional successor block is not the current layout
7205ffd83dbSDimitry Andric       // successor, insert a branch to jump to it.
7215ffd83dbSDimitry Andric       if (!isLayoutSuccessor(PreviousLayoutSuccessor))
7225ffd83dbSDimitry Andric         TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
7230b57cec5SDimitry Andric     }
7240b57cec5SDimitry Andric     return;
7250b57cec5SDimitry Andric   }
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric   if (FBB) {
7280b57cec5SDimitry Andric     // The block has a non-fallthrough conditional branch. If one of its
7290b57cec5SDimitry Andric     // successors is its layout successor, rewrite it to a fallthrough
7300b57cec5SDimitry Andric     // conditional branch.
7310b57cec5SDimitry Andric     if (isLayoutSuccessor(TBB)) {
7320b57cec5SDimitry Andric       if (TII->reverseBranchCondition(Cond))
7330b57cec5SDimitry Andric         return;
7340b57cec5SDimitry Andric       TII->removeBranch(*this);
7350b57cec5SDimitry Andric       TII->insertBranch(*this, FBB, nullptr, Cond, DL);
7360b57cec5SDimitry Andric     } else if (isLayoutSuccessor(FBB)) {
7370b57cec5SDimitry Andric       TII->removeBranch(*this);
7380b57cec5SDimitry Andric       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
7390b57cec5SDimitry Andric     }
7400b57cec5SDimitry Andric     return;
7410b57cec5SDimitry Andric   }
7420b57cec5SDimitry Andric 
7435ffd83dbSDimitry Andric   // We now know we're going to fallthrough to PreviousLayoutSuccessor.
7445ffd83dbSDimitry Andric   assert(PreviousLayoutSuccessor);
7455ffd83dbSDimitry Andric   assert(!PreviousLayoutSuccessor->isEHPad());
7465ffd83dbSDimitry Andric   assert(isSuccessor(PreviousLayoutSuccessor));
7470b57cec5SDimitry Andric 
7485ffd83dbSDimitry Andric   if (PreviousLayoutSuccessor == TBB) {
7495ffd83dbSDimitry Andric     // We had a fallthrough to the same basic block as the conditional jump
7505ffd83dbSDimitry Andric     // targets.  Remove the conditional jump, leaving an unconditional
7515ffd83dbSDimitry Andric     // fallthrough or an unconditional jump.
7520b57cec5SDimitry Andric     TII->removeBranch(*this);
7535ffd83dbSDimitry Andric     if (!isLayoutSuccessor(TBB)) {
7540b57cec5SDimitry Andric       Cond.clear();
7550b57cec5SDimitry Andric       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
7565ffd83dbSDimitry Andric     }
7570b57cec5SDimitry Andric     return;
7580b57cec5SDimitry Andric   }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   // The block has a fallthrough conditional branch.
7610b57cec5SDimitry Andric   if (isLayoutSuccessor(TBB)) {
7620b57cec5SDimitry Andric     if (TII->reverseBranchCondition(Cond)) {
7630b57cec5SDimitry Andric       // We can't reverse the condition, add an unconditional branch.
7640b57cec5SDimitry Andric       Cond.clear();
7655ffd83dbSDimitry Andric       TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
7660b57cec5SDimitry Andric       return;
7670b57cec5SDimitry Andric     }
7680b57cec5SDimitry Andric     TII->removeBranch(*this);
7695ffd83dbSDimitry Andric     TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
7705ffd83dbSDimitry Andric   } else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) {
7710b57cec5SDimitry Andric     TII->removeBranch(*this);
7725ffd83dbSDimitry Andric     TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL);
7730b57cec5SDimitry Andric   }
7740b57cec5SDimitry Andric }
7750b57cec5SDimitry Andric 
validateSuccProbs() const7760b57cec5SDimitry Andric void MachineBasicBlock::validateSuccProbs() const {
7770b57cec5SDimitry Andric #ifndef NDEBUG
7780b57cec5SDimitry Andric   int64_t Sum = 0;
7790b57cec5SDimitry Andric   for (auto Prob : Probs)
7800b57cec5SDimitry Andric     Sum += Prob.getNumerator();
7810b57cec5SDimitry Andric   // Due to precision issue, we assume that the sum of probabilities is one if
7820b57cec5SDimitry Andric   // the difference between the sum of their numerators and the denominator is
7830b57cec5SDimitry Andric   // no greater than the number of successors.
7840b57cec5SDimitry Andric   assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
7850b57cec5SDimitry Andric              Probs.size() &&
7860b57cec5SDimitry Andric          "The sum of successors's probabilities exceeds one.");
7870b57cec5SDimitry Andric #endif // NDEBUG
7880b57cec5SDimitry Andric }
7890b57cec5SDimitry Andric 
addSuccessor(MachineBasicBlock * Succ,BranchProbability Prob)7900b57cec5SDimitry Andric void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
7910b57cec5SDimitry Andric                                      BranchProbability Prob) {
7920b57cec5SDimitry Andric   // Probability list is either empty (if successor list isn't empty, this means
7930b57cec5SDimitry Andric   // disabled optimization) or has the same size as successor list.
7940b57cec5SDimitry Andric   if (!(Probs.empty() && !Successors.empty()))
7950b57cec5SDimitry Andric     Probs.push_back(Prob);
7960b57cec5SDimitry Andric   Successors.push_back(Succ);
7970b57cec5SDimitry Andric   Succ->addPredecessor(this);
7980b57cec5SDimitry Andric }
7990b57cec5SDimitry Andric 
addSuccessorWithoutProb(MachineBasicBlock * Succ)8000b57cec5SDimitry Andric void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
8010b57cec5SDimitry Andric   // We need to make sure probability list is either empty or has the same size
8020b57cec5SDimitry Andric   // of successor list. When this function is called, we can safely delete all
8030b57cec5SDimitry Andric   // probability in the list.
8040b57cec5SDimitry Andric   Probs.clear();
8050b57cec5SDimitry Andric   Successors.push_back(Succ);
8060b57cec5SDimitry Andric   Succ->addPredecessor(this);
8070b57cec5SDimitry Andric }
8080b57cec5SDimitry Andric 
splitSuccessor(MachineBasicBlock * Old,MachineBasicBlock * New,bool NormalizeSuccProbs)8090b57cec5SDimitry Andric void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
8100b57cec5SDimitry Andric                                        MachineBasicBlock *New,
8110b57cec5SDimitry Andric                                        bool NormalizeSuccProbs) {
8120b57cec5SDimitry Andric   succ_iterator OldI = llvm::find(successors(), Old);
8130b57cec5SDimitry Andric   assert(OldI != succ_end() && "Old is not a successor of this block!");
814e8d8bef9SDimitry Andric   assert(!llvm::is_contained(successors(), New) &&
8150b57cec5SDimitry Andric          "New is already a successor of this block!");
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric   // Add a new successor with equal probability as the original one. Note
8180b57cec5SDimitry Andric   // that we directly copy the probability using the iterator rather than
8190b57cec5SDimitry Andric   // getting a potentially synthetic probability computed when unknown. This
8200b57cec5SDimitry Andric   // preserves the probabilities as-is and then we can renormalize them and
8210b57cec5SDimitry Andric   // query them effectively afterward.
8220b57cec5SDimitry Andric   addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
8230b57cec5SDimitry Andric                                   : *getProbabilityIterator(OldI));
8240b57cec5SDimitry Andric   if (NormalizeSuccProbs)
8250b57cec5SDimitry Andric     normalizeSuccProbs();
8260b57cec5SDimitry Andric }
8270b57cec5SDimitry Andric 
removeSuccessor(MachineBasicBlock * Succ,bool NormalizeSuccProbs)8280b57cec5SDimitry Andric void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
8290b57cec5SDimitry Andric                                         bool NormalizeSuccProbs) {
8300b57cec5SDimitry Andric   succ_iterator I = find(Successors, Succ);
8310b57cec5SDimitry Andric   removeSuccessor(I, NormalizeSuccProbs);
8320b57cec5SDimitry Andric }
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric MachineBasicBlock::succ_iterator
removeSuccessor(succ_iterator I,bool NormalizeSuccProbs)8350b57cec5SDimitry Andric MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
8360b57cec5SDimitry Andric   assert(I != Successors.end() && "Not a current successor!");
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric   // If probability list is empty it means we don't use it (disabled
8390b57cec5SDimitry Andric   // optimization).
8400b57cec5SDimitry Andric   if (!Probs.empty()) {
8410b57cec5SDimitry Andric     probability_iterator WI = getProbabilityIterator(I);
8420b57cec5SDimitry Andric     Probs.erase(WI);
8430b57cec5SDimitry Andric     if (NormalizeSuccProbs)
8440b57cec5SDimitry Andric       normalizeSuccProbs();
8450b57cec5SDimitry Andric   }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric   (*I)->removePredecessor(this);
8480b57cec5SDimitry Andric   return Successors.erase(I);
8490b57cec5SDimitry Andric }
8500b57cec5SDimitry Andric 
replaceSuccessor(MachineBasicBlock * Old,MachineBasicBlock * New)8510b57cec5SDimitry Andric void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
8520b57cec5SDimitry Andric                                          MachineBasicBlock *New) {
8530b57cec5SDimitry Andric   if (Old == New)
8540b57cec5SDimitry Andric     return;
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric   succ_iterator E = succ_end();
8570b57cec5SDimitry Andric   succ_iterator NewI = E;
8580b57cec5SDimitry Andric   succ_iterator OldI = E;
8590b57cec5SDimitry Andric   for (succ_iterator I = succ_begin(); I != E; ++I) {
8600b57cec5SDimitry Andric     if (*I == Old) {
8610b57cec5SDimitry Andric       OldI = I;
8620b57cec5SDimitry Andric       if (NewI != E)
8630b57cec5SDimitry Andric         break;
8640b57cec5SDimitry Andric     }
8650b57cec5SDimitry Andric     if (*I == New) {
8660b57cec5SDimitry Andric       NewI = I;
8670b57cec5SDimitry Andric       if (OldI != E)
8680b57cec5SDimitry Andric         break;
8690b57cec5SDimitry Andric     }
8700b57cec5SDimitry Andric   }
8710b57cec5SDimitry Andric   assert(OldI != E && "Old is not a successor of this block");
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric   // If New isn't already a successor, let it take Old's place.
8740b57cec5SDimitry Andric   if (NewI == E) {
8750b57cec5SDimitry Andric     Old->removePredecessor(this);
8760b57cec5SDimitry Andric     New->addPredecessor(this);
8770b57cec5SDimitry Andric     *OldI = New;
8780b57cec5SDimitry Andric     return;
8790b57cec5SDimitry Andric   }
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric   // New is already a successor.
8820b57cec5SDimitry Andric   // Update its probability instead of adding a duplicate edge.
8830b57cec5SDimitry Andric   if (!Probs.empty()) {
8840b57cec5SDimitry Andric     auto ProbIter = getProbabilityIterator(NewI);
8850b57cec5SDimitry Andric     if (!ProbIter->isUnknown())
8860b57cec5SDimitry Andric       *ProbIter += *getProbabilityIterator(OldI);
8870b57cec5SDimitry Andric   }
8880b57cec5SDimitry Andric   removeSuccessor(OldI);
8890b57cec5SDimitry Andric }
8900b57cec5SDimitry Andric 
copySuccessor(const MachineBasicBlock * Orig,succ_iterator I)891*c9157d92SDimitry Andric void MachineBasicBlock::copySuccessor(const MachineBasicBlock *Orig,
8920b57cec5SDimitry Andric                                       succ_iterator I) {
893e8d8bef9SDimitry Andric   if (!Orig->Probs.empty())
8940b57cec5SDimitry Andric     addSuccessor(*I, Orig->getSuccProbability(I));
8950b57cec5SDimitry Andric   else
8960b57cec5SDimitry Andric     addSuccessorWithoutProb(*I);
8970b57cec5SDimitry Andric }
8980b57cec5SDimitry Andric 
addPredecessor(MachineBasicBlock * Pred)8990b57cec5SDimitry Andric void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
9000b57cec5SDimitry Andric   Predecessors.push_back(Pred);
9010b57cec5SDimitry Andric }
9020b57cec5SDimitry Andric 
removePredecessor(MachineBasicBlock * Pred)9030b57cec5SDimitry Andric void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
9040b57cec5SDimitry Andric   pred_iterator I = find(Predecessors, Pred);
9050b57cec5SDimitry Andric   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
9060b57cec5SDimitry Andric   Predecessors.erase(I);
9070b57cec5SDimitry Andric }
9080b57cec5SDimitry Andric 
transferSuccessors(MachineBasicBlock * FromMBB)9090b57cec5SDimitry Andric void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
9100b57cec5SDimitry Andric   if (this == FromMBB)
9110b57cec5SDimitry Andric     return;
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric   while (!FromMBB->succ_empty()) {
9140b57cec5SDimitry Andric     MachineBasicBlock *Succ = *FromMBB->succ_begin();
9150b57cec5SDimitry Andric 
9168bcb0991SDimitry Andric     // If probability list is empty it means we don't use it (disabled
9178bcb0991SDimitry Andric     // optimization).
9180b57cec5SDimitry Andric     if (!FromMBB->Probs.empty()) {
9190b57cec5SDimitry Andric       auto Prob = *FromMBB->Probs.begin();
9200b57cec5SDimitry Andric       addSuccessor(Succ, Prob);
9210b57cec5SDimitry Andric     } else
9220b57cec5SDimitry Andric       addSuccessorWithoutProb(Succ);
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric     FromMBB->removeSuccessor(Succ);
9250b57cec5SDimitry Andric   }
9260b57cec5SDimitry Andric }
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric void
transferSuccessorsAndUpdatePHIs(MachineBasicBlock * FromMBB)9290b57cec5SDimitry Andric MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
9300b57cec5SDimitry Andric   if (this == FromMBB)
9310b57cec5SDimitry Andric     return;
9320b57cec5SDimitry Andric 
9330b57cec5SDimitry Andric   while (!FromMBB->succ_empty()) {
9340b57cec5SDimitry Andric     MachineBasicBlock *Succ = *FromMBB->succ_begin();
9350b57cec5SDimitry Andric     if (!FromMBB->Probs.empty()) {
9360b57cec5SDimitry Andric       auto Prob = *FromMBB->Probs.begin();
9370b57cec5SDimitry Andric       addSuccessor(Succ, Prob);
9380b57cec5SDimitry Andric     } else
9390b57cec5SDimitry Andric       addSuccessorWithoutProb(Succ);
9400b57cec5SDimitry Andric     FromMBB->removeSuccessor(Succ);
9410b57cec5SDimitry Andric 
9420b57cec5SDimitry Andric     // Fix up any PHI nodes in the successor.
9438bcb0991SDimitry Andric     Succ->replacePhiUsesWith(FromMBB, this);
9440b57cec5SDimitry Andric   }
9450b57cec5SDimitry Andric   normalizeSuccProbs();
9460b57cec5SDimitry Andric }
9470b57cec5SDimitry Andric 
isPredecessor(const MachineBasicBlock * MBB) const9480b57cec5SDimitry Andric bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
9490b57cec5SDimitry Andric   return is_contained(predecessors(), MBB);
9500b57cec5SDimitry Andric }
9510b57cec5SDimitry Andric 
isSuccessor(const MachineBasicBlock * MBB) const9520b57cec5SDimitry Andric bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
9530b57cec5SDimitry Andric   return is_contained(successors(), MBB);
9540b57cec5SDimitry Andric }
9550b57cec5SDimitry Andric 
isLayoutSuccessor(const MachineBasicBlock * MBB) const9560b57cec5SDimitry Andric bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
9570b57cec5SDimitry Andric   MachineFunction::const_iterator I(this);
9580b57cec5SDimitry Andric   return std::next(I) == MachineFunction::const_iterator(MBB);
9590b57cec5SDimitry Andric }
9600b57cec5SDimitry Andric 
getSingleSuccessor() const96181ad6265SDimitry Andric const MachineBasicBlock *MachineBasicBlock::getSingleSuccessor() const {
96281ad6265SDimitry Andric   return Successors.size() == 1 ? Successors[0] : nullptr;
96381ad6265SDimitry Andric }
96481ad6265SDimitry Andric 
getSinglePredecessor() const965*c9157d92SDimitry Andric const MachineBasicBlock *MachineBasicBlock::getSinglePredecessor() const {
966*c9157d92SDimitry Andric   return Predecessors.size() == 1 ? Predecessors[0] : nullptr;
967*c9157d92SDimitry Andric }
968*c9157d92SDimitry Andric 
getFallThrough(bool JumpToFallThrough)969bdd1243dSDimitry Andric MachineBasicBlock *MachineBasicBlock::getFallThrough(bool JumpToFallThrough) {
9700b57cec5SDimitry Andric   MachineFunction::iterator Fallthrough = getIterator();
9710b57cec5SDimitry Andric   ++Fallthrough;
9720b57cec5SDimitry Andric   // If FallthroughBlock is off the end of the function, it can't fall through.
9730b57cec5SDimitry Andric   if (Fallthrough == getParent()->end())
9740b57cec5SDimitry Andric     return nullptr;
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   // If FallthroughBlock isn't a successor, no fallthrough is possible.
9770b57cec5SDimitry Andric   if (!isSuccessor(&*Fallthrough))
9780b57cec5SDimitry Andric     return nullptr;
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   // Analyze the branches, if any, at the end of the block.
9810b57cec5SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
9820b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
9830b57cec5SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
9840b57cec5SDimitry Andric   if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
9850b57cec5SDimitry Andric     // If we couldn't analyze the branch, examine the last instruction.
9860b57cec5SDimitry Andric     // If the block doesn't end in a known control barrier, assume fallthrough
9870b57cec5SDimitry Andric     // is possible. The isPredicated check is needed because this code can be
9880b57cec5SDimitry Andric     // called during IfConversion, where an instruction which is normally a
9890b57cec5SDimitry Andric     // Barrier is predicated and thus no longer an actual control barrier.
9900b57cec5SDimitry Andric     return (empty() || !back().isBarrier() || TII->isPredicated(back()))
9910b57cec5SDimitry Andric                ? &*Fallthrough
9920b57cec5SDimitry Andric                : nullptr;
9930b57cec5SDimitry Andric   }
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric   // If there is no branch, control always falls through.
9960b57cec5SDimitry Andric   if (!TBB) return &*Fallthrough;
9970b57cec5SDimitry Andric 
9980b57cec5SDimitry Andric   // If there is some explicit branch to the fallthrough block, it can obviously
9990b57cec5SDimitry Andric   // reach, even though the branch should get folded to fall through implicitly.
1000fe013be4SDimitry Andric   if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough ||
1001bdd1243dSDimitry Andric                             MachineFunction::iterator(FBB) == Fallthrough))
10020b57cec5SDimitry Andric     return &*Fallthrough;
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   // If it's an unconditional branch to some block not the fall through, it
10050b57cec5SDimitry Andric   // doesn't fall through.
10060b57cec5SDimitry Andric   if (Cond.empty()) return nullptr;
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric   // Otherwise, if it is conditional and has no explicit false block, it falls
10090b57cec5SDimitry Andric   // through.
10100b57cec5SDimitry Andric   return (FBB == nullptr) ? &*Fallthrough : nullptr;
10110b57cec5SDimitry Andric }
10120b57cec5SDimitry Andric 
canFallThrough()10130b57cec5SDimitry Andric bool MachineBasicBlock::canFallThrough() {
10140b57cec5SDimitry Andric   return getFallThrough() != nullptr;
10150b57cec5SDimitry Andric }
10160b57cec5SDimitry Andric 
splitAt(MachineInstr & MI,bool UpdateLiveIns,LiveIntervals * LIS)1017e8d8bef9SDimitry Andric MachineBasicBlock *MachineBasicBlock::splitAt(MachineInstr &MI,
1018e8d8bef9SDimitry Andric                                               bool UpdateLiveIns,
1019e8d8bef9SDimitry Andric                                               LiveIntervals *LIS) {
1020e8d8bef9SDimitry Andric   MachineBasicBlock::iterator SplitPoint(&MI);
1021e8d8bef9SDimitry Andric   ++SplitPoint;
1022e8d8bef9SDimitry Andric 
1023e8d8bef9SDimitry Andric   if (SplitPoint == end()) {
1024e8d8bef9SDimitry Andric     // Don't bother with a new block.
1025e8d8bef9SDimitry Andric     return this;
1026e8d8bef9SDimitry Andric   }
1027e8d8bef9SDimitry Andric 
1028e8d8bef9SDimitry Andric   MachineFunction *MF = getParent();
1029e8d8bef9SDimitry Andric 
1030e8d8bef9SDimitry Andric   LivePhysRegs LiveRegs;
1031e8d8bef9SDimitry Andric   if (UpdateLiveIns) {
1032e8d8bef9SDimitry Andric     // Make sure we add any physregs we define in the block as liveins to the
1033e8d8bef9SDimitry Andric     // new block.
1034e8d8bef9SDimitry Andric     MachineBasicBlock::iterator Prev(&MI);
1035e8d8bef9SDimitry Andric     LiveRegs.init(*MF->getSubtarget().getRegisterInfo());
1036e8d8bef9SDimitry Andric     LiveRegs.addLiveOuts(*this);
1037e8d8bef9SDimitry Andric     for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
1038e8d8bef9SDimitry Andric       LiveRegs.stepBackward(*I);
1039e8d8bef9SDimitry Andric   }
1040e8d8bef9SDimitry Andric 
1041e8d8bef9SDimitry Andric   MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(getBasicBlock());
1042e8d8bef9SDimitry Andric 
1043e8d8bef9SDimitry Andric   MF->insert(++MachineFunction::iterator(this), SplitBB);
1044e8d8bef9SDimitry Andric   SplitBB->splice(SplitBB->begin(), this, SplitPoint, end());
1045e8d8bef9SDimitry Andric 
1046e8d8bef9SDimitry Andric   SplitBB->transferSuccessorsAndUpdatePHIs(this);
1047e8d8bef9SDimitry Andric   addSuccessor(SplitBB);
1048e8d8bef9SDimitry Andric 
1049e8d8bef9SDimitry Andric   if (UpdateLiveIns)
1050e8d8bef9SDimitry Andric     addLiveIns(*SplitBB, LiveRegs);
1051e8d8bef9SDimitry Andric 
1052e8d8bef9SDimitry Andric   if (LIS)
1053e8d8bef9SDimitry Andric     LIS->insertMBBInMaps(SplitBB);
1054e8d8bef9SDimitry Andric 
1055e8d8bef9SDimitry Andric   return SplitBB;
1056e8d8bef9SDimitry Andric }
1057e8d8bef9SDimitry Andric 
1058fe013be4SDimitry Andric // Returns `true` if there are possibly other users of the jump table at
1059fe013be4SDimitry Andric // `JumpTableIndex` except for the ones in `IgnoreMBB`.
jumpTableHasOtherUses(const MachineFunction & MF,const MachineBasicBlock & IgnoreMBB,int JumpTableIndex)1060fe013be4SDimitry Andric static bool jumpTableHasOtherUses(const MachineFunction &MF,
1061fe013be4SDimitry Andric                                   const MachineBasicBlock &IgnoreMBB,
1062fe013be4SDimitry Andric                                   int JumpTableIndex) {
1063fe013be4SDimitry Andric   assert(JumpTableIndex >= 0 && "need valid index");
1064fe013be4SDimitry Andric   const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo();
1065fe013be4SDimitry Andric   const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex];
1066fe013be4SDimitry Andric   // Take any basic block from the table; every user of the jump table must
1067fe013be4SDimitry Andric   // show up in the predecessor list.
1068fe013be4SDimitry Andric   const MachineBasicBlock *MBB = nullptr;
1069fe013be4SDimitry Andric   for (MachineBasicBlock *B : MJTE.MBBs) {
1070fe013be4SDimitry Andric     if (B != nullptr) {
1071fe013be4SDimitry Andric       MBB = B;
1072fe013be4SDimitry Andric       break;
1073fe013be4SDimitry Andric     }
1074fe013be4SDimitry Andric   }
1075fe013be4SDimitry Andric   if (MBB == nullptr)
1076fe013be4SDimitry Andric     return true; // can't rule out other users if there isn't any block.
1077fe013be4SDimitry Andric   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1078fe013be4SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
1079fe013be4SDimitry Andric   for (MachineBasicBlock *Pred : MBB->predecessors()) {
1080fe013be4SDimitry Andric     if (Pred == &IgnoreMBB)
1081fe013be4SDimitry Andric       continue;
1082fe013be4SDimitry Andric     MachineBasicBlock *DummyT = nullptr;
1083fe013be4SDimitry Andric     MachineBasicBlock *DummyF = nullptr;
1084fe013be4SDimitry Andric     Cond.clear();
1085fe013be4SDimitry Andric     if (!TII.analyzeBranch(*Pred, DummyT, DummyF, Cond,
1086fe013be4SDimitry Andric                            /*AllowModify=*/false)) {
1087fe013be4SDimitry Andric       // analyzable direct jump
1088fe013be4SDimitry Andric       continue;
1089fe013be4SDimitry Andric     }
1090fe013be4SDimitry Andric     int PredJTI = findJumpTableIndex(*Pred);
1091fe013be4SDimitry Andric     if (PredJTI >= 0) {
1092fe013be4SDimitry Andric       if (PredJTI == JumpTableIndex)
1093fe013be4SDimitry Andric         return true;
1094fe013be4SDimitry Andric       continue;
1095fe013be4SDimitry Andric     }
1096fe013be4SDimitry Andric     // Be conservative for unanalyzable jumps.
1097fe013be4SDimitry Andric     return true;
1098fe013be4SDimitry Andric   }
1099fe013be4SDimitry Andric   return false;
1100fe013be4SDimitry Andric }
1101fe013be4SDimitry Andric 
1102*c9157d92SDimitry Andric class SlotIndexUpdateDelegate : public MachineFunction::Delegate {
1103*c9157d92SDimitry Andric private:
1104*c9157d92SDimitry Andric   MachineFunction &MF;
1105*c9157d92SDimitry Andric   SlotIndexes *Indexes;
1106*c9157d92SDimitry Andric   SmallSetVector<MachineInstr *, 2> Insertions;
1107*c9157d92SDimitry Andric 
1108*c9157d92SDimitry Andric public:
SlotIndexUpdateDelegate(MachineFunction & MF,SlotIndexes * Indexes)1109*c9157d92SDimitry Andric   SlotIndexUpdateDelegate(MachineFunction &MF, SlotIndexes *Indexes)
1110*c9157d92SDimitry Andric       : MF(MF), Indexes(Indexes) {
1111*c9157d92SDimitry Andric     MF.setDelegate(this);
1112*c9157d92SDimitry Andric   }
1113*c9157d92SDimitry Andric 
~SlotIndexUpdateDelegate()1114*c9157d92SDimitry Andric   ~SlotIndexUpdateDelegate() {
1115*c9157d92SDimitry Andric     MF.resetDelegate(this);
1116*c9157d92SDimitry Andric     for (auto MI : Insertions)
1117*c9157d92SDimitry Andric       Indexes->insertMachineInstrInMaps(*MI);
1118*c9157d92SDimitry Andric   }
1119*c9157d92SDimitry Andric 
MF_HandleInsertion(MachineInstr & MI)1120*c9157d92SDimitry Andric   void MF_HandleInsertion(MachineInstr &MI) override {
1121*c9157d92SDimitry Andric     // This is called before MI is inserted into block so defer index update.
1122*c9157d92SDimitry Andric     if (Indexes)
1123*c9157d92SDimitry Andric       Insertions.insert(&MI);
1124*c9157d92SDimitry Andric   }
1125*c9157d92SDimitry Andric 
MF_HandleRemoval(MachineInstr & MI)1126*c9157d92SDimitry Andric   void MF_HandleRemoval(MachineInstr &MI) override {
1127*c9157d92SDimitry Andric     if (Indexes && !Insertions.remove(&MI))
1128*c9157d92SDimitry Andric       Indexes->removeMachineInstrFromMaps(MI);
1129*c9157d92SDimitry Andric   }
1130*c9157d92SDimitry Andric };
1131*c9157d92SDimitry Andric 
SplitCriticalEdge(MachineBasicBlock * Succ,Pass & P,std::vector<SparseBitVector<>> * LiveInSets)11325ffd83dbSDimitry Andric MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
11335ffd83dbSDimitry Andric     MachineBasicBlock *Succ, Pass &P,
11345ffd83dbSDimitry Andric     std::vector<SparseBitVector<>> *LiveInSets) {
11350b57cec5SDimitry Andric   if (!canSplitCriticalEdge(Succ))
11360b57cec5SDimitry Andric     return nullptr;
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric   MachineFunction *MF = getParent();
11395ffd83dbSDimitry Andric   MachineBasicBlock *PrevFallthrough = getNextNode();
11400b57cec5SDimitry Andric   DebugLoc DL;  // FIXME: this is nowhere
11410b57cec5SDimitry Andric 
11420b57cec5SDimitry Andric   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
1143*c9157d92SDimitry Andric   NMBB->setCallFrameSize(Succ->getCallFrameSize());
1144fe013be4SDimitry Andric 
1145fe013be4SDimitry Andric   // Is there an indirect jump with jump table?
1146fe013be4SDimitry Andric   bool ChangedIndirectJump = false;
1147fe013be4SDimitry Andric   int JTI = findJumpTableIndex(*this);
1148fe013be4SDimitry Andric   if (JTI >= 0) {
1149fe013be4SDimitry Andric     MachineJumpTableInfo &MJTI = *MF->getJumpTableInfo();
1150fe013be4SDimitry Andric     MJTI.ReplaceMBBInJumpTable(JTI, Succ, NMBB);
1151fe013be4SDimitry Andric     ChangedIndirectJump = true;
1152fe013be4SDimitry Andric   }
1153fe013be4SDimitry Andric 
11540b57cec5SDimitry Andric   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
11550b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
11560b57cec5SDimitry Andric                     << " -- " << printMBBReference(*NMBB) << " -- "
11570b57cec5SDimitry Andric                     << printMBBReference(*Succ) << '\n');
11580b57cec5SDimitry Andric 
11590b57cec5SDimitry Andric   LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
11600b57cec5SDimitry Andric   SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
11610b57cec5SDimitry Andric   if (LIS)
11620b57cec5SDimitry Andric     LIS->insertMBBInMaps(NMBB);
11630b57cec5SDimitry Andric   else if (Indexes)
11640b57cec5SDimitry Andric     Indexes->insertMBBInMaps(NMBB);
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric   // On some targets like Mips, branches may kill virtual registers. Make sure
11670b57cec5SDimitry Andric   // that LiveVariables is properly updated after updateTerminator replaces the
11680b57cec5SDimitry Andric   // terminators.
11690b57cec5SDimitry Andric   LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
11700b57cec5SDimitry Andric 
11710b57cec5SDimitry Andric   // Collect a list of virtual registers killed by the terminators.
11725ffd83dbSDimitry Andric   SmallVector<Register, 4> KilledRegs;
11730b57cec5SDimitry Andric   if (LV)
11740eae32dcSDimitry Andric     for (MachineInstr &MI :
11750eae32dcSDimitry Andric          llvm::make_range(getFirstInstrTerminator(), instr_end())) {
1176fe013be4SDimitry Andric       for (MachineOperand &MO : MI.all_uses()) {
1177fe013be4SDimitry Andric         if (MO.getReg() == 0 || !MO.isKill() || MO.isUndef())
11780b57cec5SDimitry Andric           continue;
1179349cc55cSDimitry Andric         Register Reg = MO.getReg();
1180bdd1243dSDimitry Andric         if (Reg.isPhysical() || LV->getVarInfo(Reg).removeKill(MI)) {
11810b57cec5SDimitry Andric           KilledRegs.push_back(Reg);
1182349cc55cSDimitry Andric           LLVM_DEBUG(dbgs() << "Removing terminator kill: " << MI);
1183349cc55cSDimitry Andric           MO.setIsKill(false);
11840b57cec5SDimitry Andric         }
11850b57cec5SDimitry Andric       }
11860b57cec5SDimitry Andric     }
11870b57cec5SDimitry Andric 
11885ffd83dbSDimitry Andric   SmallVector<Register, 4> UsedRegs;
11890b57cec5SDimitry Andric   if (LIS) {
11900eae32dcSDimitry Andric     for (MachineInstr &MI :
11910eae32dcSDimitry Andric          llvm::make_range(getFirstInstrTerminator(), instr_end())) {
11920eae32dcSDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
1193349cc55cSDimitry Andric         if (!MO.isReg() || MO.getReg() == 0)
11940b57cec5SDimitry Andric           continue;
11950b57cec5SDimitry Andric 
1196349cc55cSDimitry Andric         Register Reg = MO.getReg();
11970b57cec5SDimitry Andric         if (!is_contained(UsedRegs, Reg))
11980b57cec5SDimitry Andric           UsedRegs.push_back(Reg);
11990b57cec5SDimitry Andric       }
12000b57cec5SDimitry Andric     }
12010b57cec5SDimitry Andric   }
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   ReplaceUsesOfBlockWith(Succ, NMBB);
12040b57cec5SDimitry Andric 
12055ffd83dbSDimitry Andric   // Since we replaced all uses of Succ with NMBB, that should also be treated
12065ffd83dbSDimitry Andric   // as the fallthrough successor
12075ffd83dbSDimitry Andric   if (Succ == PrevFallthrough)
12085ffd83dbSDimitry Andric     PrevFallthrough = NMBB;
1209fe013be4SDimitry Andric 
1210*c9157d92SDimitry Andric   if (!ChangedIndirectJump) {
1211*c9157d92SDimitry Andric     SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
12125ffd83dbSDimitry Andric     updateTerminator(PrevFallthrough);
12130b57cec5SDimitry Andric   }
12140b57cec5SDimitry Andric 
12150b57cec5SDimitry Andric   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
12160b57cec5SDimitry Andric   NMBB->addSuccessor(Succ);
12170b57cec5SDimitry Andric   if (!NMBB->isLayoutSuccessor(Succ)) {
1218*c9157d92SDimitry Andric     SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
12190b57cec5SDimitry Andric     SmallVector<MachineOperand, 4> Cond;
12200b57cec5SDimitry Andric     const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
12210b57cec5SDimitry Andric     TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
12220b57cec5SDimitry Andric   }
12230b57cec5SDimitry Andric 
12248bcb0991SDimitry Andric   // Fix PHI nodes in Succ so they refer to NMBB instead of this.
12258bcb0991SDimitry Andric   Succ->replacePhiUsesWith(this, NMBB);
12260b57cec5SDimitry Andric 
12270b57cec5SDimitry Andric   // Inherit live-ins from the successor
12280b57cec5SDimitry Andric   for (const auto &LI : Succ->liveins())
12290b57cec5SDimitry Andric     NMBB->addLiveIn(LI);
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric   // Update LiveVariables.
12320b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
12330b57cec5SDimitry Andric   if (LV) {
12340b57cec5SDimitry Andric     // Restore kills of virtual registers that were killed by the terminators.
12350b57cec5SDimitry Andric     while (!KilledRegs.empty()) {
12365ffd83dbSDimitry Andric       Register Reg = KilledRegs.pop_back_val();
12370b57cec5SDimitry Andric       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
12380b57cec5SDimitry Andric         if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false))
12390b57cec5SDimitry Andric           continue;
1240bdd1243dSDimitry Andric         if (Reg.isVirtual())
12410b57cec5SDimitry Andric           LV->getVarInfo(Reg).Kills.push_back(&*I);
12420b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
12430b57cec5SDimitry Andric         break;
12440b57cec5SDimitry Andric       }
12450b57cec5SDimitry Andric     }
12460b57cec5SDimitry Andric     // Update relevant live-through information.
12475ffd83dbSDimitry Andric     if (LiveInSets != nullptr)
12485ffd83dbSDimitry Andric       LV->addNewBlock(NMBB, this, Succ, *LiveInSets);
12495ffd83dbSDimitry Andric     else
12500b57cec5SDimitry Andric       LV->addNewBlock(NMBB, this, Succ);
12510b57cec5SDimitry Andric   }
12520b57cec5SDimitry Andric 
12530b57cec5SDimitry Andric   if (LIS) {
12540b57cec5SDimitry Andric     // After splitting the edge and updating SlotIndexes, live intervals may be
12550b57cec5SDimitry Andric     // in one of two situations, depending on whether this block was the last in
12560b57cec5SDimitry Andric     // the function. If the original block was the last in the function, all
12570b57cec5SDimitry Andric     // live intervals will end prior to the beginning of the new split block. If
12580b57cec5SDimitry Andric     // the original block was not at the end of the function, all live intervals
12590b57cec5SDimitry Andric     // will extend to the end of the new split block.
12600b57cec5SDimitry Andric 
12610b57cec5SDimitry Andric     bool isLastMBB =
12620b57cec5SDimitry Andric       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
12630b57cec5SDimitry Andric 
12640b57cec5SDimitry Andric     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
12650b57cec5SDimitry Andric     SlotIndex PrevIndex = StartIndex.getPrevSlot();
12660b57cec5SDimitry Andric     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric     // Find the registers used from NMBB in PHIs in Succ.
12695ffd83dbSDimitry Andric     SmallSet<Register, 8> PHISrcRegs;
12700b57cec5SDimitry Andric     for (MachineBasicBlock::instr_iterator
12710b57cec5SDimitry Andric          I = Succ->instr_begin(), E = Succ->instr_end();
12720b57cec5SDimitry Andric          I != E && I->isPHI(); ++I) {
12730b57cec5SDimitry Andric       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
12740b57cec5SDimitry Andric         if (I->getOperand(ni+1).getMBB() == NMBB) {
12750b57cec5SDimitry Andric           MachineOperand &MO = I->getOperand(ni);
12768bcb0991SDimitry Andric           Register Reg = MO.getReg();
12770b57cec5SDimitry Andric           PHISrcRegs.insert(Reg);
12780b57cec5SDimitry Andric           if (MO.isUndef())
12790b57cec5SDimitry Andric             continue;
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric           LiveInterval &LI = LIS->getInterval(Reg);
12820b57cec5SDimitry Andric           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
12830b57cec5SDimitry Andric           assert(VNI &&
12840b57cec5SDimitry Andric                  "PHI sources should be live out of their predecessors.");
12850b57cec5SDimitry Andric           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1286*c9157d92SDimitry Andric           for (auto &SR : LI.subranges())
1287*c9157d92SDimitry Andric             SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
12880b57cec5SDimitry Andric         }
12890b57cec5SDimitry Andric       }
12900b57cec5SDimitry Andric     }
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
12930b57cec5SDimitry Andric     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
12945ffd83dbSDimitry Andric       Register Reg = Register::index2VirtReg(i);
12950b57cec5SDimitry Andric       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
12960b57cec5SDimitry Andric         continue;
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric       LiveInterval &LI = LIS->getInterval(Reg);
12990b57cec5SDimitry Andric       if (!LI.liveAt(PrevIndex))
13000b57cec5SDimitry Andric         continue;
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
13030b57cec5SDimitry Andric       if (isLiveOut && isLastMBB) {
13040b57cec5SDimitry Andric         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
13050b57cec5SDimitry Andric         assert(VNI && "LiveInterval should have VNInfo where it is live.");
13060b57cec5SDimitry Andric         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1307*c9157d92SDimitry Andric         // Update subranges with live values
1308*c9157d92SDimitry Andric         for (auto &SR : LI.subranges()) {
1309*c9157d92SDimitry Andric           VNInfo *VNI = SR.getVNInfoAt(PrevIndex);
1310*c9157d92SDimitry Andric           if (VNI)
1311*c9157d92SDimitry Andric             SR.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1312*c9157d92SDimitry Andric         }
13130b57cec5SDimitry Andric       } else if (!isLiveOut && !isLastMBB) {
13140b57cec5SDimitry Andric         LI.removeSegment(StartIndex, EndIndex);
1315*c9157d92SDimitry Andric         for (auto &SR : LI.subranges())
1316*c9157d92SDimitry Andric           SR.removeSegment(StartIndex, EndIndex);
13170b57cec5SDimitry Andric       }
13180b57cec5SDimitry Andric     }
13190b57cec5SDimitry Andric 
13200b57cec5SDimitry Andric     // Update all intervals for registers whose uses may have been modified by
13210b57cec5SDimitry Andric     // updateTerminator().
13220b57cec5SDimitry Andric     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
13230b57cec5SDimitry Andric   }
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   if (MachineDominatorTree *MDT =
13260b57cec5SDimitry Andric           P.getAnalysisIfAvailable<MachineDominatorTree>())
13270b57cec5SDimitry Andric     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric   if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
13300b57cec5SDimitry Andric     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
13310b57cec5SDimitry Andric       // If one or the other blocks were not in a loop, the new block is not
13320b57cec5SDimitry Andric       // either, and thus LI doesn't need to be updated.
13330b57cec5SDimitry Andric       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
13340b57cec5SDimitry Andric         if (TIL == DestLoop) {
13350b57cec5SDimitry Andric           // Both in the same loop, the NMBB joins loop.
13360b57cec5SDimitry Andric           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
13370b57cec5SDimitry Andric         } else if (TIL->contains(DestLoop)) {
13380b57cec5SDimitry Andric           // Edge from an outer loop to an inner loop.  Add to the outer loop.
13390b57cec5SDimitry Andric           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
13400b57cec5SDimitry Andric         } else if (DestLoop->contains(TIL)) {
13410b57cec5SDimitry Andric           // Edge from an inner loop to an outer loop.  Add to the outer loop.
13420b57cec5SDimitry Andric           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
13430b57cec5SDimitry Andric         } else {
13440b57cec5SDimitry Andric           // Edge from two loops with no containment relation.  Because these
13450b57cec5SDimitry Andric           // are natural loops, we know that the destination block must be the
13460b57cec5SDimitry Andric           // header of its loop (adding a branch into a loop elsewhere would
13470b57cec5SDimitry Andric           // create an irreducible loop).
13480b57cec5SDimitry Andric           assert(DestLoop->getHeader() == Succ &&
13490b57cec5SDimitry Andric                  "Should not create irreducible loops!");
13500b57cec5SDimitry Andric           if (MachineLoop *P = DestLoop->getParentLoop())
13510b57cec5SDimitry Andric             P->addBasicBlockToLoop(NMBB, MLI->getBase());
13520b57cec5SDimitry Andric         }
13530b57cec5SDimitry Andric       }
13540b57cec5SDimitry Andric     }
13550b57cec5SDimitry Andric 
13560b57cec5SDimitry Andric   return NMBB;
13570b57cec5SDimitry Andric }
13580b57cec5SDimitry Andric 
canSplitCriticalEdge(const MachineBasicBlock * Succ) const13590b57cec5SDimitry Andric bool MachineBasicBlock::canSplitCriticalEdge(
13600b57cec5SDimitry Andric     const MachineBasicBlock *Succ) const {
13610b57cec5SDimitry Andric   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
13620b57cec5SDimitry Andric   // it in this generic function.
13630b57cec5SDimitry Andric   if (Succ->isEHPad())
13640b57cec5SDimitry Andric     return false;
13650b57cec5SDimitry Andric 
13665ffd83dbSDimitry Andric   // Splitting the critical edge to a callbr's indirect block isn't advised.
13675ffd83dbSDimitry Andric   // Don't do it in this generic function.
13685ffd83dbSDimitry Andric   if (Succ->isInlineAsmBrIndirectTarget())
13695ffd83dbSDimitry Andric     return false;
13700b57cec5SDimitry Andric 
13715ffd83dbSDimitry Andric   const MachineFunction *MF = getParent();
13720b57cec5SDimitry Andric   // Performance might be harmed on HW that implements branching using exec mask
13730b57cec5SDimitry Andric   // where both sides of the branches are always executed.
13740b57cec5SDimitry Andric   if (MF->getTarget().requiresStructuredCFG())
13750b57cec5SDimitry Andric     return false;
13760b57cec5SDimitry Andric 
1377fe013be4SDimitry Andric   // Do we have an Indirect jump with a jumptable that we can rewrite?
1378fe013be4SDimitry Andric   int JTI = findJumpTableIndex(*this);
1379fe013be4SDimitry Andric   if (JTI >= 0 && !jumpTableHasOtherUses(*MF, *this, JTI))
1380fe013be4SDimitry Andric     return true;
1381fe013be4SDimitry Andric 
13820b57cec5SDimitry Andric   // We may need to update this's terminator, but we can't do that if
1383fe013be4SDimitry Andric   // analyzeBranch fails.
13840b57cec5SDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
13850b57cec5SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
13860b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
13870b57cec5SDimitry Andric   // AnalyzeBanch should modify this, since we did not allow modification.
13880b57cec5SDimitry Andric   if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
13890b57cec5SDimitry Andric                          /*AllowModify*/ false))
13900b57cec5SDimitry Andric     return false;
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric   // Avoid bugpoint weirdness: A block may end with a conditional branch but
13930b57cec5SDimitry Andric   // jumps to the same MBB is either case. We have duplicate CFG edges in that
13940b57cec5SDimitry Andric   // case that we can't handle. Since this never happens in properly optimized
13950b57cec5SDimitry Andric   // code, just skip those edges.
13960b57cec5SDimitry Andric   if (TBB && TBB == FBB) {
13970b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
13980b57cec5SDimitry Andric                       << printMBBReference(*this) << '\n');
13990b57cec5SDimitry Andric     return false;
14000b57cec5SDimitry Andric   }
14010b57cec5SDimitry Andric   return true;
14020b57cec5SDimitry Andric }
14030b57cec5SDimitry Andric 
14040b57cec5SDimitry Andric /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
14050b57cec5SDimitry Andric /// neighboring instructions so the bundle won't be broken by removing MI.
unbundleSingleMI(MachineInstr * MI)14060b57cec5SDimitry Andric static void unbundleSingleMI(MachineInstr *MI) {
14070b57cec5SDimitry Andric   // Removing the first instruction in a bundle.
14080b57cec5SDimitry Andric   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
14090b57cec5SDimitry Andric     MI->unbundleFromSucc();
14100b57cec5SDimitry Andric   // Removing the last instruction in a bundle.
14110b57cec5SDimitry Andric   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
14120b57cec5SDimitry Andric     MI->unbundleFromPred();
14130b57cec5SDimitry Andric   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
14140b57cec5SDimitry Andric   // are already fine.
14150b57cec5SDimitry Andric }
14160b57cec5SDimitry Andric 
14170b57cec5SDimitry Andric MachineBasicBlock::instr_iterator
erase(MachineBasicBlock::instr_iterator I)14180b57cec5SDimitry Andric MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
14190b57cec5SDimitry Andric   unbundleSingleMI(&*I);
14200b57cec5SDimitry Andric   return Insts.erase(I);
14210b57cec5SDimitry Andric }
14220b57cec5SDimitry Andric 
remove_instr(MachineInstr * MI)14230b57cec5SDimitry Andric MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
14240b57cec5SDimitry Andric   unbundleSingleMI(MI);
14250b57cec5SDimitry Andric   MI->clearFlag(MachineInstr::BundledPred);
14260b57cec5SDimitry Andric   MI->clearFlag(MachineInstr::BundledSucc);
14270b57cec5SDimitry Andric   return Insts.remove(MI);
14280b57cec5SDimitry Andric }
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric MachineBasicBlock::instr_iterator
insert(instr_iterator I,MachineInstr * MI)14310b57cec5SDimitry Andric MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
14320b57cec5SDimitry Andric   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
14330b57cec5SDimitry Andric          "Cannot insert instruction with bundle flags");
14340b57cec5SDimitry Andric   // Set the bundle flags when inserting inside a bundle.
14350b57cec5SDimitry Andric   if (I != instr_end() && I->isBundledWithPred()) {
14360b57cec5SDimitry Andric     MI->setFlag(MachineInstr::BundledPred);
14370b57cec5SDimitry Andric     MI->setFlag(MachineInstr::BundledSucc);
14380b57cec5SDimitry Andric   }
14390b57cec5SDimitry Andric   return Insts.insert(I, MI);
14400b57cec5SDimitry Andric }
14410b57cec5SDimitry Andric 
14420b57cec5SDimitry Andric /// This method unlinks 'this' from the containing function, and returns it, but
14430b57cec5SDimitry Andric /// does not delete it.
removeFromParent()14440b57cec5SDimitry Andric MachineBasicBlock *MachineBasicBlock::removeFromParent() {
14450b57cec5SDimitry Andric   assert(getParent() && "Not embedded in a function!");
14460b57cec5SDimitry Andric   getParent()->remove(this);
14470b57cec5SDimitry Andric   return this;
14480b57cec5SDimitry Andric }
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric /// This method unlinks 'this' from the containing function, and deletes it.
eraseFromParent()14510b57cec5SDimitry Andric void MachineBasicBlock::eraseFromParent() {
14520b57cec5SDimitry Andric   assert(getParent() && "Not embedded in a function!");
14530b57cec5SDimitry Andric   getParent()->erase(this);
14540b57cec5SDimitry Andric }
14550b57cec5SDimitry Andric 
14560b57cec5SDimitry Andric /// Given a machine basic block that branched to 'Old', change the code and CFG
14570b57cec5SDimitry Andric /// so that it branches to 'New' instead.
ReplaceUsesOfBlockWith(MachineBasicBlock * Old,MachineBasicBlock * New)14580b57cec5SDimitry Andric void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
14590b57cec5SDimitry Andric                                                MachineBasicBlock *New) {
14600b57cec5SDimitry Andric   assert(Old != New && "Cannot replace self with self!");
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric   MachineBasicBlock::instr_iterator I = instr_end();
14630b57cec5SDimitry Andric   while (I != instr_begin()) {
14640b57cec5SDimitry Andric     --I;
14650b57cec5SDimitry Andric     if (!I->isTerminator()) break;
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric     // Scan the operands of this machine instruction, replacing any uses of Old
14680b57cec5SDimitry Andric     // with New.
14690b57cec5SDimitry Andric     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
14700b57cec5SDimitry Andric       if (I->getOperand(i).isMBB() &&
14710b57cec5SDimitry Andric           I->getOperand(i).getMBB() == Old)
14720b57cec5SDimitry Andric         I->getOperand(i).setMBB(New);
14730b57cec5SDimitry Andric   }
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric   // Update the successor information.
14760b57cec5SDimitry Andric   replaceSuccessor(Old, New);
14770b57cec5SDimitry Andric }
14780b57cec5SDimitry Andric 
replacePhiUsesWith(MachineBasicBlock * Old,MachineBasicBlock * New)14798bcb0991SDimitry Andric void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old,
14808bcb0991SDimitry Andric                                            MachineBasicBlock *New) {
14818bcb0991SDimitry Andric   for (MachineInstr &MI : phis())
14828bcb0991SDimitry Andric     for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
14838bcb0991SDimitry Andric       MachineOperand &MO = MI.getOperand(i);
14848bcb0991SDimitry Andric       if (MO.getMBB() == Old)
14858bcb0991SDimitry Andric         MO.setMBB(New);
14868bcb0991SDimitry Andric     }
14878bcb0991SDimitry Andric }
14888bcb0991SDimitry Andric 
1489fe013be4SDimitry Andric /// Find the next valid DebugLoc starting at MBBI, skipping any debug
14900b57cec5SDimitry Andric /// instructions.  Return UnknownLoc if there is none.
14910b57cec5SDimitry Andric DebugLoc
findDebugLoc(instr_iterator MBBI)14920b57cec5SDimitry Andric MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
14930b57cec5SDimitry Andric   // Skip debug declarations, we don't want a DebugLoc from them.
14940b57cec5SDimitry Andric   MBBI = skipDebugInstructionsForward(MBBI, instr_end());
14950b57cec5SDimitry Andric   if (MBBI != instr_end())
14960b57cec5SDimitry Andric     return MBBI->getDebugLoc();
14970b57cec5SDimitry Andric   return {};
14980b57cec5SDimitry Andric }
14990b57cec5SDimitry Andric 
rfindDebugLoc(reverse_instr_iterator MBBI)1500fe6060f1SDimitry Andric DebugLoc MachineBasicBlock::rfindDebugLoc(reverse_instr_iterator MBBI) {
1501fe013be4SDimitry Andric   if (MBBI == instr_rend())
1502fe013be4SDimitry Andric     return findDebugLoc(instr_begin());
1503fe6060f1SDimitry Andric   // Skip debug declarations, we don't want a DebugLoc from them.
1504fe6060f1SDimitry Andric   MBBI = skipDebugInstructionsBackward(MBBI, instr_rbegin());
1505fe6060f1SDimitry Andric   if (!MBBI->isDebugInstr())
1506fe6060f1SDimitry Andric     return MBBI->getDebugLoc();
1507fe6060f1SDimitry Andric   return {};
1508fe6060f1SDimitry Andric }
1509fe6060f1SDimitry Andric 
1510fe013be4SDimitry Andric /// Find the previous valid DebugLoc preceding MBBI, skipping any debug
15110b57cec5SDimitry Andric /// instructions.  Return UnknownLoc if there is none.
findPrevDebugLoc(instr_iterator MBBI)15120b57cec5SDimitry Andric DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) {
1513fe013be4SDimitry Andric   if (MBBI == instr_begin())
1514fe013be4SDimitry Andric     return {};
15155ffd83dbSDimitry Andric   // Skip debug instructions, we don't want a DebugLoc from them.
15165ffd83dbSDimitry Andric   MBBI = prev_nodbg(MBBI, instr_begin());
1517fe013be4SDimitry Andric   if (!MBBI->isDebugInstr())
1518fe013be4SDimitry Andric     return MBBI->getDebugLoc();
15190b57cec5SDimitry Andric   return {};
15200b57cec5SDimitry Andric }
15210b57cec5SDimitry Andric 
rfindPrevDebugLoc(reverse_instr_iterator MBBI)1522fe6060f1SDimitry Andric DebugLoc MachineBasicBlock::rfindPrevDebugLoc(reverse_instr_iterator MBBI) {
1523fe6060f1SDimitry Andric   if (MBBI == instr_rend())
1524fe6060f1SDimitry Andric     return {};
1525fe6060f1SDimitry Andric   // Skip debug declarations, we don't want a DebugLoc from them.
1526fe6060f1SDimitry Andric   MBBI = next_nodbg(MBBI, instr_rend());
1527fe6060f1SDimitry Andric   if (MBBI != instr_rend())
1528fe6060f1SDimitry Andric     return MBBI->getDebugLoc();
1529fe6060f1SDimitry Andric   return {};
1530fe6060f1SDimitry Andric }
1531fe6060f1SDimitry Andric 
15320b57cec5SDimitry Andric /// Find and return the merged DebugLoc of the branch instructions of the block.
15330b57cec5SDimitry Andric /// Return UnknownLoc if there is none.
15340b57cec5SDimitry Andric DebugLoc
findBranchDebugLoc()15350b57cec5SDimitry Andric MachineBasicBlock::findBranchDebugLoc() {
15360b57cec5SDimitry Andric   DebugLoc DL;
15370b57cec5SDimitry Andric   auto TI = getFirstTerminator();
15380b57cec5SDimitry Andric   while (TI != end() && !TI->isBranch())
15390b57cec5SDimitry Andric     ++TI;
15400b57cec5SDimitry Andric 
15410b57cec5SDimitry Andric   if (TI != end()) {
15420b57cec5SDimitry Andric     DL = TI->getDebugLoc();
15430b57cec5SDimitry Andric     for (++TI ; TI != end() ; ++TI)
15440b57cec5SDimitry Andric       if (TI->isBranch())
15450b57cec5SDimitry Andric         DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
15460b57cec5SDimitry Andric   }
15470b57cec5SDimitry Andric   return DL;
15480b57cec5SDimitry Andric }
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric /// Return probability of the edge from this block to MBB.
15510b57cec5SDimitry Andric BranchProbability
getSuccProbability(const_succ_iterator Succ) const15520b57cec5SDimitry Andric MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
15530b57cec5SDimitry Andric   if (Probs.empty())
15540b57cec5SDimitry Andric     return BranchProbability(1, succ_size());
15550b57cec5SDimitry Andric 
15560b57cec5SDimitry Andric   const auto &Prob = *getProbabilityIterator(Succ);
15570b57cec5SDimitry Andric   if (Prob.isUnknown()) {
15580b57cec5SDimitry Andric     // For unknown probabilities, collect the sum of all known ones, and evenly
15590b57cec5SDimitry Andric     // ditribute the complemental of the sum to each unknown probability.
15600b57cec5SDimitry Andric     unsigned KnownProbNum = 0;
15610b57cec5SDimitry Andric     auto Sum = BranchProbability::getZero();
1562fcaf7f86SDimitry Andric     for (const auto &P : Probs) {
15630b57cec5SDimitry Andric       if (!P.isUnknown()) {
15640b57cec5SDimitry Andric         Sum += P;
15650b57cec5SDimitry Andric         KnownProbNum++;
15660b57cec5SDimitry Andric       }
15670b57cec5SDimitry Andric     }
15680b57cec5SDimitry Andric     return Sum.getCompl() / (Probs.size() - KnownProbNum);
15690b57cec5SDimitry Andric   } else
15700b57cec5SDimitry Andric     return Prob;
15710b57cec5SDimitry Andric }
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric /// Set successor probability of a given iterator.
setSuccProbability(succ_iterator I,BranchProbability Prob)15740b57cec5SDimitry Andric void MachineBasicBlock::setSuccProbability(succ_iterator I,
15750b57cec5SDimitry Andric                                            BranchProbability Prob) {
15760b57cec5SDimitry Andric   assert(!Prob.isUnknown());
15770b57cec5SDimitry Andric   if (Probs.empty())
15780b57cec5SDimitry Andric     return;
15790b57cec5SDimitry Andric   *getProbabilityIterator(I) = Prob;
15800b57cec5SDimitry Andric }
15810b57cec5SDimitry Andric 
15820b57cec5SDimitry Andric /// Return probability iterator corresonding to the I successor iterator
15830b57cec5SDimitry Andric MachineBasicBlock::const_probability_iterator
getProbabilityIterator(MachineBasicBlock::const_succ_iterator I) const15840b57cec5SDimitry Andric MachineBasicBlock::getProbabilityIterator(
15850b57cec5SDimitry Andric     MachineBasicBlock::const_succ_iterator I) const {
15860b57cec5SDimitry Andric   assert(Probs.size() == Successors.size() && "Async probability list!");
15870b57cec5SDimitry Andric   const size_t index = std::distance(Successors.begin(), I);
15880b57cec5SDimitry Andric   assert(index < Probs.size() && "Not a current successor!");
15890b57cec5SDimitry Andric   return Probs.begin() + index;
15900b57cec5SDimitry Andric }
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric /// Return probability iterator corresonding to the I successor iterator.
15930b57cec5SDimitry Andric MachineBasicBlock::probability_iterator
getProbabilityIterator(MachineBasicBlock::succ_iterator I)15940b57cec5SDimitry Andric MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
15950b57cec5SDimitry Andric   assert(Probs.size() == Successors.size() && "Async probability list!");
15960b57cec5SDimitry Andric   const size_t index = std::distance(Successors.begin(), I);
15970b57cec5SDimitry Andric   assert(index < Probs.size() && "Not a current successor!");
15980b57cec5SDimitry Andric   return Probs.begin() + index;
15990b57cec5SDimitry Andric }
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
16020b57cec5SDimitry Andric /// as of just before "MI".
16030b57cec5SDimitry Andric ///
16040b57cec5SDimitry Andric /// Search is localised to a neighborhood of
16050b57cec5SDimitry Andric /// Neighborhood instructions before (searching for defs or kills) and N
16060b57cec5SDimitry Andric /// instructions after (searching just for defs) MI.
16070b57cec5SDimitry Andric MachineBasicBlock::LivenessQueryResult
computeRegisterLiveness(const TargetRegisterInfo * TRI,MCRegister Reg,const_iterator Before,unsigned Neighborhood) const16080b57cec5SDimitry Andric MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
16095ffd83dbSDimitry Andric                                            MCRegister Reg, const_iterator Before,
16100b57cec5SDimitry Andric                                            unsigned Neighborhood) const {
16110b57cec5SDimitry Andric   unsigned N = Neighborhood;
16120b57cec5SDimitry Andric 
16130b57cec5SDimitry Andric   // Try searching forwards from Before, looking for reads or defs.
16140b57cec5SDimitry Andric   const_iterator I(Before);
16150b57cec5SDimitry Andric   for (; I != end() && N > 0; ++I) {
1616fe6060f1SDimitry Andric     if (I->isDebugOrPseudoInstr())
16170b57cec5SDimitry Andric       continue;
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric     --N;
16200b57cec5SDimitry Andric 
1621480093f4SDimitry Andric     PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric     // Register is live when we read it here.
16240b57cec5SDimitry Andric     if (Info.Read)
16250b57cec5SDimitry Andric       return LQR_Live;
16260b57cec5SDimitry Andric     // Register is dead if we can fully overwrite or clobber it here.
16270b57cec5SDimitry Andric     if (Info.FullyDefined || Info.Clobbered)
16280b57cec5SDimitry Andric       return LQR_Dead;
16290b57cec5SDimitry Andric   }
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric   // If we reached the end, it is safe to clobber Reg at the end of a block of
16320b57cec5SDimitry Andric   // no successor has it live in.
16330b57cec5SDimitry Andric   if (I == end()) {
16340b57cec5SDimitry Andric     for (MachineBasicBlock *S : successors()) {
16350b57cec5SDimitry Andric       for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
16360b57cec5SDimitry Andric         if (TRI->regsOverlap(LI.PhysReg, Reg))
16370b57cec5SDimitry Andric           return LQR_Live;
16380b57cec5SDimitry Andric       }
16390b57cec5SDimitry Andric     }
16400b57cec5SDimitry Andric 
16410b57cec5SDimitry Andric     return LQR_Dead;
16420b57cec5SDimitry Andric   }
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric   N = Neighborhood;
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric   // Start by searching backwards from Before, looking for kills, reads or defs.
16480b57cec5SDimitry Andric   I = const_iterator(Before);
16490b57cec5SDimitry Andric   // If this is the first insn in the block, don't search backwards.
16500b57cec5SDimitry Andric   if (I != begin()) {
16510b57cec5SDimitry Andric     do {
16520b57cec5SDimitry Andric       --I;
16530b57cec5SDimitry Andric 
1654fe6060f1SDimitry Andric       if (I->isDebugOrPseudoInstr())
16550b57cec5SDimitry Andric         continue;
16560b57cec5SDimitry Andric 
16570b57cec5SDimitry Andric       --N;
16580b57cec5SDimitry Andric 
1659480093f4SDimitry Andric       PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric       // Defs happen after uses so they take precedence if both are present.
16620b57cec5SDimitry Andric 
16630b57cec5SDimitry Andric       // Register is dead after a dead def of the full register.
16640b57cec5SDimitry Andric       if (Info.DeadDef)
16650b57cec5SDimitry Andric         return LQR_Dead;
16660b57cec5SDimitry Andric       // Register is (at least partially) live after a def.
16670b57cec5SDimitry Andric       if (Info.Defined) {
16680b57cec5SDimitry Andric         if (!Info.PartialDeadDef)
16690b57cec5SDimitry Andric           return LQR_Live;
16700b57cec5SDimitry Andric         // As soon as we saw a partial definition (dead or not),
16710b57cec5SDimitry Andric         // we cannot tell if the value is partial live without
16720b57cec5SDimitry Andric         // tracking the lanemasks. We are not going to do this,
16730b57cec5SDimitry Andric         // so fall back on the remaining of the analysis.
16740b57cec5SDimitry Andric         break;
16750b57cec5SDimitry Andric       }
16760b57cec5SDimitry Andric       // Register is dead after a full kill or clobber and no def.
16770b57cec5SDimitry Andric       if (Info.Killed || Info.Clobbered)
16780b57cec5SDimitry Andric         return LQR_Dead;
16790b57cec5SDimitry Andric       // Register must be live if we read it.
16800b57cec5SDimitry Andric       if (Info.Read)
16810b57cec5SDimitry Andric         return LQR_Live;
16820b57cec5SDimitry Andric 
16830b57cec5SDimitry Andric     } while (I != begin() && N > 0);
16840b57cec5SDimitry Andric   }
16850b57cec5SDimitry Andric 
1686480093f4SDimitry Andric   // If all the instructions before this in the block are debug instructions,
1687480093f4SDimitry Andric   // skip over them.
1688fe6060f1SDimitry Andric   while (I != begin() && std::prev(I)->isDebugOrPseudoInstr())
1689480093f4SDimitry Andric     --I;
1690480093f4SDimitry Andric 
16910b57cec5SDimitry Andric   // Did we get to the start of the block?
16920b57cec5SDimitry Andric   if (I == begin()) {
16930b57cec5SDimitry Andric     // If so, the register's state is definitely defined by the live-in state.
16940b57cec5SDimitry Andric     for (const MachineBasicBlock::RegisterMaskPair &LI : liveins())
16950b57cec5SDimitry Andric       if (TRI->regsOverlap(LI.PhysReg, Reg))
16960b57cec5SDimitry Andric         return LQR_Live;
16970b57cec5SDimitry Andric 
16980b57cec5SDimitry Andric     return LQR_Dead;
16990b57cec5SDimitry Andric   }
17000b57cec5SDimitry Andric 
17010b57cec5SDimitry Andric   // At this point we have no idea of the liveness of the register.
17020b57cec5SDimitry Andric   return LQR_Unknown;
17030b57cec5SDimitry Andric }
17040b57cec5SDimitry Andric 
17050b57cec5SDimitry Andric const uint32_t *
getBeginClobberMask(const TargetRegisterInfo * TRI) const17060b57cec5SDimitry Andric MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
17070b57cec5SDimitry Andric   // EH funclet entry does not preserve any registers.
17080b57cec5SDimitry Andric   return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
17090b57cec5SDimitry Andric }
17100b57cec5SDimitry Andric 
17110b57cec5SDimitry Andric const uint32_t *
getEndClobberMask(const TargetRegisterInfo * TRI) const17120b57cec5SDimitry Andric MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
17130b57cec5SDimitry Andric   // If we see a return block with successors, this must be a funclet return,
17140b57cec5SDimitry Andric   // which does not preserve any registers. If there are no successors, we don't
17150b57cec5SDimitry Andric   // care what kind of return it is, putting a mask after it is a no-op.
17160b57cec5SDimitry Andric   return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
17170b57cec5SDimitry Andric }
17180b57cec5SDimitry Andric 
clearLiveIns()17190b57cec5SDimitry Andric void MachineBasicBlock::clearLiveIns() {
17200b57cec5SDimitry Andric   LiveIns.clear();
17210b57cec5SDimitry Andric }
17220b57cec5SDimitry Andric 
livein_begin() const17230b57cec5SDimitry Andric MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
17240b57cec5SDimitry Andric   assert(getParent()->getProperties().hasProperty(
17250b57cec5SDimitry Andric       MachineFunctionProperties::Property::TracksLiveness) &&
17260b57cec5SDimitry Andric       "Liveness information is accurate");
17270b57cec5SDimitry Andric   return LiveIns.begin();
17280b57cec5SDimitry Andric }
17295ffd83dbSDimitry Andric 
liveout_begin() const1730fe6060f1SDimitry Andric MachineBasicBlock::liveout_iterator MachineBasicBlock::liveout_begin() const {
1731fe6060f1SDimitry Andric   const MachineFunction &MF = *getParent();
1732fe6060f1SDimitry Andric   assert(MF.getProperties().hasProperty(
1733fe6060f1SDimitry Andric       MachineFunctionProperties::Property::TracksLiveness) &&
1734fe6060f1SDimitry Andric       "Liveness information is accurate");
1735fe6060f1SDimitry Andric 
1736fe6060f1SDimitry Andric   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1737fe6060f1SDimitry Andric   MCPhysReg ExceptionPointer = 0, ExceptionSelector = 0;
1738fe6060f1SDimitry Andric   if (MF.getFunction().hasPersonalityFn()) {
1739fe6060f1SDimitry Andric     auto PersonalityFn = MF.getFunction().getPersonalityFn();
1740fe6060f1SDimitry Andric     ExceptionPointer = TLI.getExceptionPointerRegister(PersonalityFn);
1741fe6060f1SDimitry Andric     ExceptionSelector = TLI.getExceptionSelectorRegister(PersonalityFn);
1742fe6060f1SDimitry Andric   }
1743fe6060f1SDimitry Andric 
1744fe6060f1SDimitry Andric   return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false);
1745fe6060f1SDimitry Andric }
1746fe6060f1SDimitry Andric 
sizeWithoutDebugLargerThan(unsigned Limit) const174781ad6265SDimitry Andric bool MachineBasicBlock::sizeWithoutDebugLargerThan(unsigned Limit) const {
174881ad6265SDimitry Andric   unsigned Cntr = 0;
174981ad6265SDimitry Andric   auto R = instructionsWithoutDebug(begin(), end());
175081ad6265SDimitry Andric   for (auto I = R.begin(), E = R.end(); I != E; ++I) {
175181ad6265SDimitry Andric     if (++Cntr > Limit)
175281ad6265SDimitry Andric       return true;
175381ad6265SDimitry Andric   }
175481ad6265SDimitry Andric   return false;
175581ad6265SDimitry Andric }
175681ad6265SDimitry Andric 
17575ffd83dbSDimitry Andric const MBBSectionID MBBSectionID::ColdSectionID(MBBSectionID::SectionType::Cold);
17585ffd83dbSDimitry Andric const MBBSectionID
17595ffd83dbSDimitry Andric     MBBSectionID::ExceptionSectionID(MBBSectionID::SectionType::Exception);
1760