1f22ef01cSRoman Divacky //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // Collect the sequence of machine instructions for a basic block.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineBasicBlock.h"
15139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
16139f7f9bSDimitry Andric #include "llvm/CodeGen/LiveIntervalAnalysis.h"
17ffd1746dSEd Schouten #include "llvm/CodeGen/LiveVariables.h"
18ffd1746dSEd Schouten #include "llvm/CodeGen/MachineDominators.h"
19f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineFunction.h"
20*6beeb091SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
21ffd1746dSEd Schouten #include "llvm/CodeGen/MachineLoopInfo.h"
22139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
232754fe60SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
24139f7f9bSDimitry Andric #include "llvm/IR/BasicBlock.h"
25139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
267a7e6055SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
273dac3a9bSDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
28f22ef01cSRoman Divacky #include "llvm/MC/MCAsmInfo.h"
29f22ef01cSRoman Divacky #include "llvm/MC/MCContext.h"
307d523365SDimitry Andric #include "llvm/Support/DataTypes.h"
31f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
32f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
33139f7f9bSDimitry Andric #include "llvm/Target/TargetInstrInfo.h"
34139f7f9bSDimitry Andric #include "llvm/Target/TargetMachine.h"
35139f7f9bSDimitry Andric #include "llvm/Target/TargetRegisterInfo.h"
3639d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
37f22ef01cSRoman Divacky #include <algorithm>
38f22ef01cSRoman Divacky using namespace llvm;
39f22ef01cSRoman Divacky 
4091bc56edSDimitry Andric #define DEBUG_TYPE "codegen"
4191bc56edSDimitry Andric 
427d523365SDimitry Andric MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
437d523365SDimitry Andric     : BB(B), Number(-1), xParent(&MF) {
44f22ef01cSRoman Divacky   Insts.Parent = this;
45f22ef01cSRoman Divacky }
46f22ef01cSRoman Divacky 
47f22ef01cSRoman Divacky MachineBasicBlock::~MachineBasicBlock() {
48f22ef01cSRoman Divacky }
49f22ef01cSRoman Divacky 
507d523365SDimitry Andric /// Return the MCSymbol for this basic block.
51f22ef01cSRoman Divacky MCSymbol *MachineBasicBlock::getSymbol() const {
52284c1978SDimitry Andric   if (!CachedMCSymbol) {
53f22ef01cSRoman Divacky     const MachineFunction *MF = getParent();
54f22ef01cSRoman Divacky     MCContext &Ctx = MF->getContext();
55d88c1a5aSDimitry Andric     auto Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
567d523365SDimitry Andric     assert(getNumber() >= 0 && "cannot get label for unreachable MBB");
57ff0cc061SDimitry Andric     CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
58284c1978SDimitry Andric                                            Twine(MF->getFunctionNumber()) +
59284c1978SDimitry Andric                                            "_" + Twine(getNumber()));
60284c1978SDimitry Andric   }
61284c1978SDimitry Andric 
62284c1978SDimitry Andric   return CachedMCSymbol;
63f22ef01cSRoman Divacky }
64f22ef01cSRoman Divacky 
65f22ef01cSRoman Divacky 
66f22ef01cSRoman Divacky raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
67f22ef01cSRoman Divacky   MBB.print(OS);
68f22ef01cSRoman Divacky   return OS;
69f22ef01cSRoman Divacky }
70f22ef01cSRoman Divacky 
717d523365SDimitry Andric /// When an MBB is added to an MF, we need to update the parent pointer of the
727d523365SDimitry Andric /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
737d523365SDimitry Andric /// operand list for registers.
74f22ef01cSRoman Divacky ///
75f22ef01cSRoman Divacky /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
76f22ef01cSRoman Divacky /// gets the next available unique MBB number. If it is removed from a
77f22ef01cSRoman Divacky /// MachineFunction, it goes back to being #-1.
78d88c1a5aSDimitry Andric void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
79d88c1a5aSDimitry Andric     MachineBasicBlock *N) {
80f22ef01cSRoman Divacky   MachineFunction &MF = *N->getParent();
81f22ef01cSRoman Divacky   N->Number = MF.addToMBBNumbering(N);
82f22ef01cSRoman Divacky 
83f22ef01cSRoman Divacky   // Make sure the instructions have their operands in the reginfo lists.
84f22ef01cSRoman Divacky   MachineRegisterInfo &RegInfo = MF.getRegInfo();
85dff0c46cSDimitry Andric   for (MachineBasicBlock::instr_iterator
86dff0c46cSDimitry Andric          I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
87f22ef01cSRoman Divacky     I->AddRegOperandsToUseLists(RegInfo);
88f22ef01cSRoman Divacky }
89f22ef01cSRoman Divacky 
90d88c1a5aSDimitry Andric void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
91d88c1a5aSDimitry Andric     MachineBasicBlock *N) {
92f22ef01cSRoman Divacky   N->getParent()->removeFromMBBNumbering(N->Number);
93f22ef01cSRoman Divacky   N->Number = -1;
94f22ef01cSRoman Divacky }
95f22ef01cSRoman Divacky 
967d523365SDimitry Andric /// When we add an instruction to a basic block list, we update its parent
977d523365SDimitry Andric /// pointer and add its operands from reg use/def lists if appropriate.
98f22ef01cSRoman Divacky void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
9991bc56edSDimitry Andric   assert(!N->getParent() && "machine instruction already in a basic block");
100f22ef01cSRoman Divacky   N->setParent(Parent);
101f22ef01cSRoman Divacky 
102f22ef01cSRoman Divacky   // Add the instruction's register operands to their corresponding
103f22ef01cSRoman Divacky   // use/def lists.
104f22ef01cSRoman Divacky   MachineFunction *MF = Parent->getParent();
105f22ef01cSRoman Divacky   N->AddRegOperandsToUseLists(MF->getRegInfo());
106f22ef01cSRoman Divacky }
107f22ef01cSRoman Divacky 
1087d523365SDimitry Andric /// When we remove an instruction from a basic block list, we update its parent
1097d523365SDimitry Andric /// pointer and remove its operands from reg use/def lists if appropriate.
110f22ef01cSRoman Divacky void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
11191bc56edSDimitry Andric   assert(N->getParent() && "machine instruction not in a basic block");
112f22ef01cSRoman Divacky 
113f22ef01cSRoman Divacky   // Remove from the use/def lists.
1147ae0e2c9SDimitry Andric   if (MachineFunction *MF = N->getParent()->getParent())
1157ae0e2c9SDimitry Andric     N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
116f22ef01cSRoman Divacky 
11791bc56edSDimitry Andric   N->setParent(nullptr);
118f22ef01cSRoman Divacky }
119f22ef01cSRoman Divacky 
1207d523365SDimitry Andric /// When moving a range of instructions from one MBB list to another, we need to
1217d523365SDimitry Andric /// update the parent pointers and the use/def lists.
122d88c1a5aSDimitry Andric void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
123d88c1a5aSDimitry Andric                                                        instr_iterator First,
124d88c1a5aSDimitry Andric                                                        instr_iterator Last) {
1257d523365SDimitry Andric   assert(Parent->getParent() == FromList.Parent->getParent() &&
126f22ef01cSRoman Divacky         "MachineInstr parent mismatch!");
127d88c1a5aSDimitry Andric   assert(this != &FromList && "Called without a real transfer...");
128d88c1a5aSDimitry Andric   assert(Parent != FromList.Parent && "Two lists have the same parent?");
129f22ef01cSRoman Divacky 
130f22ef01cSRoman Divacky   // If splicing between two blocks within the same function, just update the
131f22ef01cSRoman Divacky   // parent pointers.
1327d523365SDimitry Andric   for (; First != Last; ++First)
1337d523365SDimitry Andric     First->setParent(Parent);
134f22ef01cSRoman Divacky }
135f22ef01cSRoman Divacky 
136f22ef01cSRoman Divacky void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
137f22ef01cSRoman Divacky   assert(!MI->getParent() && "MI is still in a block!");
138f22ef01cSRoman Divacky   Parent->getParent()->DeleteMachineInstr(MI);
139f22ef01cSRoman Divacky }
140f22ef01cSRoman Divacky 
141ffd1746dSEd Schouten MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
142dff0c46cSDimitry Andric   instr_iterator I = instr_begin(), E = instr_end();
143dff0c46cSDimitry Andric   while (I != E && I->isPHI())
144ffd1746dSEd Schouten     ++I;
1453861d79fSDimitry Andric   assert((I == E || !I->isInsideBundle()) &&
1463861d79fSDimitry Andric          "First non-phi MI cannot be inside a bundle!");
147ffd1746dSEd Schouten   return I;
148ffd1746dSEd Schouten }
149ffd1746dSEd Schouten 
1502754fe60SDimitry Andric MachineBasicBlock::iterator
1512754fe60SDimitry Andric MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
1527a7e6055SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
1537a7e6055SDimitry Andric 
154dff0c46cSDimitry Andric   iterator E = end();
1557a7e6055SDimitry Andric   while (I != E && (I->isPHI() || I->isPosition() ||
1567a7e6055SDimitry Andric                     TII->isBasicBlockPrologue(*I)))
157d88c1a5aSDimitry Andric     ++I;
158d88c1a5aSDimitry Andric   // FIXME: This needs to change if we wish to bundle labels
159d88c1a5aSDimitry Andric   // inside the bundle.
160d88c1a5aSDimitry Andric   assert((I == E || !I->isInsideBundle()) &&
161d88c1a5aSDimitry Andric          "First non-phi / non-label instruction is inside a bundle!");
162d88c1a5aSDimitry Andric   return I;
163d88c1a5aSDimitry Andric }
164d88c1a5aSDimitry Andric 
165d88c1a5aSDimitry Andric MachineBasicBlock::iterator
166d88c1a5aSDimitry Andric MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I) {
1677a7e6055SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
1687a7e6055SDimitry Andric 
169d88c1a5aSDimitry Andric   iterator E = end();
1707a7e6055SDimitry Andric   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue() ||
1717a7e6055SDimitry Andric                     TII->isBasicBlockPrologue(*I)))
1722754fe60SDimitry Andric     ++I;
173dff0c46cSDimitry Andric   // FIXME: This needs to change if we wish to bundle labels / dbg_values
174dff0c46cSDimitry Andric   // inside the bundle.
1753861d79fSDimitry Andric   assert((I == E || !I->isInsideBundle()) &&
176d88c1a5aSDimitry Andric          "First non-phi / non-label / non-debug "
177d88c1a5aSDimitry Andric          "instruction is inside a bundle!");
1782754fe60SDimitry Andric   return I;
1792754fe60SDimitry Andric }
1802754fe60SDimitry Andric 
181f22ef01cSRoman Divacky MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
182dff0c46cSDimitry Andric   iterator B = begin(), E = end(), I = E;
183dff0c46cSDimitry Andric   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
184f22ef01cSRoman Divacky     ; /*noop */
185dff0c46cSDimitry Andric   while (I != E && !I->isTerminator())
186dff0c46cSDimitry Andric     ++I;
187dff0c46cSDimitry Andric   return I;
188dff0c46cSDimitry Andric }
189dff0c46cSDimitry Andric 
190dff0c46cSDimitry Andric MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
191dff0c46cSDimitry Andric   instr_iterator B = instr_begin(), E = instr_end(), I = E;
192dff0c46cSDimitry Andric   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
193dff0c46cSDimitry Andric     ; /*noop */
194dff0c46cSDimitry Andric   while (I != E && !I->isTerminator())
1952754fe60SDimitry Andric     ++I;
196f22ef01cSRoman Divacky   return I;
197f22ef01cSRoman Divacky }
198f22ef01cSRoman Divacky 
1993dac3a9bSDimitry Andric MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() {
2003dac3a9bSDimitry Andric   // Skip over begin-of-block dbg_value instructions.
201d88c1a5aSDimitry Andric   return skipDebugInstructionsForward(begin(), end());
2023dac3a9bSDimitry Andric }
2033dac3a9bSDimitry Andric 
2042754fe60SDimitry Andric MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
205dff0c46cSDimitry Andric   // Skip over end-of-block dbg_value instructions.
206dff0c46cSDimitry Andric   instr_iterator B = instr_begin(), I = instr_end();
2072754fe60SDimitry Andric   while (I != B) {
2082754fe60SDimitry Andric     --I;
209dff0c46cSDimitry Andric     // Return instruction that starts a bundle.
210dff0c46cSDimitry Andric     if (I->isDebugValue() || I->isInsideBundle())
211dff0c46cSDimitry Andric       continue;
212dff0c46cSDimitry Andric     return I;
213dff0c46cSDimitry Andric   }
214dff0c46cSDimitry Andric   // The block is all debug values.
215dff0c46cSDimitry Andric   return end();
216dff0c46cSDimitry Andric }
217dff0c46cSDimitry Andric 
2187d523365SDimitry Andric bool MachineBasicBlock::hasEHPadSuccessor() const {
2197d523365SDimitry Andric   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
2207d523365SDimitry Andric     if ((*I)->isEHPad())
2217d523365SDimitry Andric       return true;
2227d523365SDimitry Andric   return false;
2237d523365SDimitry Andric }
2247d523365SDimitry Andric 
2253861d79fSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2263ca95b02SDimitry Andric LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
227f22ef01cSRoman Divacky   print(dbgs());
228f22ef01cSRoman Divacky }
2293861d79fSDimitry Andric #endif
230f22ef01cSRoman Divacky 
231f22ef01cSRoman Divacky StringRef MachineBasicBlock::getName() const {
232f22ef01cSRoman Divacky   if (const BasicBlock *LBB = getBasicBlock())
233f22ef01cSRoman Divacky     return LBB->getName();
234f22ef01cSRoman Divacky   else
2357a7e6055SDimitry Andric     return StringRef("", 0);
236f22ef01cSRoman Divacky }
237f22ef01cSRoman Divacky 
238dff0c46cSDimitry Andric /// Return a hopefully unique identifier for this block.
239dff0c46cSDimitry Andric std::string MachineBasicBlock::getFullName() const {
240dff0c46cSDimitry Andric   std::string Name;
241dff0c46cSDimitry Andric   if (getParent())
2423861d79fSDimitry Andric     Name = (getParent()->getName() + ":").str();
243dff0c46cSDimitry Andric   if (getBasicBlock())
244dff0c46cSDimitry Andric     Name += getBasicBlock()->getName();
245dff0c46cSDimitry Andric   else
246ff0cc061SDimitry Andric     Name += ("BB" + Twine(getNumber())).str();
247dff0c46cSDimitry Andric   return Name;
248dff0c46cSDimitry Andric }
249dff0c46cSDimitry Andric 
2503ca95b02SDimitry Andric void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes)
2513ca95b02SDimitry Andric     const {
252f22ef01cSRoman Divacky   const MachineFunction *MF = getParent();
253f22ef01cSRoman Divacky   if (!MF) {
254f22ef01cSRoman Divacky     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
255f22ef01cSRoman Divacky        << " is null\n";
256f22ef01cSRoman Divacky     return;
257f22ef01cSRoman Divacky   }
2583dac3a9bSDimitry Andric   const Function *F = MF->getFunction();
2593dac3a9bSDimitry Andric   const Module *M = F ? F->getParent() : nullptr;
2603dac3a9bSDimitry Andric   ModuleSlotTracker MST(M);
2613dac3a9bSDimitry Andric   print(OS, MST, Indexes);
2623dac3a9bSDimitry Andric }
2633dac3a9bSDimitry Andric 
2643dac3a9bSDimitry Andric void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
2653ca95b02SDimitry Andric                               const SlotIndexes *Indexes) const {
2663dac3a9bSDimitry Andric   const MachineFunction *MF = getParent();
2673dac3a9bSDimitry Andric   if (!MF) {
2683dac3a9bSDimitry Andric     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
2693dac3a9bSDimitry Andric        << " is null\n";
2703dac3a9bSDimitry Andric     return;
2713dac3a9bSDimitry Andric   }
272f22ef01cSRoman Divacky 
2732754fe60SDimitry Andric   if (Indexes)
2742754fe60SDimitry Andric     OS << Indexes->getMBBStartIdx(this) << '\t';
2752754fe60SDimitry Andric 
276f22ef01cSRoman Divacky   OS << "BB#" << getNumber() << ": ";
277f22ef01cSRoman Divacky 
278f22ef01cSRoman Divacky   const char *Comma = "";
279f22ef01cSRoman Divacky   if (const BasicBlock *LBB = getBasicBlock()) {
280f22ef01cSRoman Divacky     OS << Comma << "derived from LLVM BB ";
2813dac3a9bSDimitry Andric     LBB->printAsOperand(OS, /*PrintType=*/false, MST);
282f22ef01cSRoman Divacky     Comma = ", ";
283f22ef01cSRoman Divacky   }
2847d523365SDimitry Andric   if (isEHPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
285f22ef01cSRoman Divacky   if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
2867ae0e2c9SDimitry Andric   if (Alignment)
287dff0c46cSDimitry Andric     OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
288dff0c46cSDimitry Andric        << " bytes)";
289dff0c46cSDimitry Andric 
290f22ef01cSRoman Divacky   OS << '\n';
291f22ef01cSRoman Divacky 
29239d628a0SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
293f22ef01cSRoman Divacky   if (!livein_empty()) {
2942754fe60SDimitry Andric     if (Indexes) OS << '\t';
295f22ef01cSRoman Divacky     OS << "    Live Ins:";
29695ec533aSDimitry Andric     for (const auto &LI : LiveIns) {
2977d523365SDimitry Andric       OS << ' ' << PrintReg(LI.PhysReg, TRI);
298d88c1a5aSDimitry Andric       if (!LI.LaneMask.all())
2997d523365SDimitry Andric         OS << ':' << PrintLaneMask(LI.LaneMask);
3007d523365SDimitry Andric     }
301f22ef01cSRoman Divacky     OS << '\n';
302f22ef01cSRoman Divacky   }
303f22ef01cSRoman Divacky   // Print the preds of this block according to the CFG.
304f22ef01cSRoman Divacky   if (!pred_empty()) {
3052754fe60SDimitry Andric     if (Indexes) OS << '\t';
306f22ef01cSRoman Divacky     OS << "    Predecessors according to CFG:";
307f22ef01cSRoman Divacky     for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
308f22ef01cSRoman Divacky       OS << " BB#" << (*PI)->getNumber();
309f22ef01cSRoman Divacky     OS << '\n';
310f22ef01cSRoman Divacky   }
311f22ef01cSRoman Divacky 
3123ca95b02SDimitry Andric   for (auto &I : instrs()) {
3132754fe60SDimitry Andric     if (Indexes) {
3143ca95b02SDimitry Andric       if (Indexes->hasIndex(I))
3153ca95b02SDimitry Andric         OS << Indexes->getInstructionIndex(I);
3162754fe60SDimitry Andric       OS << '\t';
3172754fe60SDimitry Andric     }
318f22ef01cSRoman Divacky     OS << '\t';
3193ca95b02SDimitry Andric     if (I.isInsideBundle())
320dff0c46cSDimitry Andric       OS << "  * ";
3213ca95b02SDimitry Andric     I.print(OS, MST);
322f22ef01cSRoman Divacky   }
323f22ef01cSRoman Divacky 
324f22ef01cSRoman Divacky   // Print the successors of this block according to the CFG.
325f22ef01cSRoman Divacky   if (!succ_empty()) {
3262754fe60SDimitry Andric     if (Indexes) OS << '\t';
327f22ef01cSRoman Divacky     OS << "    Successors according to CFG:";
3287ae0e2c9SDimitry Andric     for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
329f22ef01cSRoman Divacky       OS << " BB#" << (*SI)->getNumber();
3307d523365SDimitry Andric       if (!Probs.empty())
3317d523365SDimitry Andric         OS << '(' << *getProbabilityIterator(SI) << ')';
3327ae0e2c9SDimitry Andric     }
333f22ef01cSRoman Divacky     OS << '\n';
334f22ef01cSRoman Divacky   }
335f22ef01cSRoman Divacky }
336f22ef01cSRoman Divacky 
3377d523365SDimitry Andric void MachineBasicBlock::printAsOperand(raw_ostream &OS,
3387d523365SDimitry Andric                                        bool /*PrintType*/) const {
33991bc56edSDimitry Andric   OS << "BB#" << getNumber();
34091bc56edSDimitry Andric }
34191bc56edSDimitry Andric 
3427d523365SDimitry Andric void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
343d88c1a5aSDimitry Andric   LiveInVector::iterator I = find_if(
344d88c1a5aSDimitry Andric       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
3457d523365SDimitry Andric   if (I == LiveIns.end())
3467d523365SDimitry Andric     return;
3477d523365SDimitry Andric 
3487d523365SDimitry Andric   I->LaneMask &= ~LaneMask;
349d88c1a5aSDimitry Andric   if (I->LaneMask.none())
350f22ef01cSRoman Divacky     LiveIns.erase(I);
351f22ef01cSRoman Divacky }
352f22ef01cSRoman Divacky 
3537d523365SDimitry Andric bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
354d88c1a5aSDimitry Andric   livein_iterator I = find_if(
355d88c1a5aSDimitry Andric       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
356d88c1a5aSDimitry Andric   return I != livein_end() && (I->LaneMask & LaneMask).any();
3577d523365SDimitry Andric }
3587d523365SDimitry Andric 
3597d523365SDimitry Andric void MachineBasicBlock::sortUniqueLiveIns() {
3607d523365SDimitry Andric   std::sort(LiveIns.begin(), LiveIns.end(),
3617d523365SDimitry Andric             [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
3627d523365SDimitry Andric               return LI0.PhysReg < LI1.PhysReg;
3637d523365SDimitry Andric             });
3647d523365SDimitry Andric   // Liveins are sorted by physreg now we can merge their lanemasks.
3657d523365SDimitry Andric   LiveInVector::const_iterator I = LiveIns.begin();
3667d523365SDimitry Andric   LiveInVector::const_iterator J;
3677d523365SDimitry Andric   LiveInVector::iterator Out = LiveIns.begin();
3687d523365SDimitry Andric   for (; I != LiveIns.end(); ++Out, I = J) {
3697d523365SDimitry Andric     unsigned PhysReg = I->PhysReg;
3707d523365SDimitry Andric     LaneBitmask LaneMask = I->LaneMask;
3717d523365SDimitry Andric     for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
3727d523365SDimitry Andric       LaneMask |= J->LaneMask;
3737d523365SDimitry Andric     Out->PhysReg = PhysReg;
3747d523365SDimitry Andric     Out->LaneMask = LaneMask;
3757d523365SDimitry Andric   }
3767d523365SDimitry Andric   LiveIns.erase(Out, LiveIns.end());
377f22ef01cSRoman Divacky }
378f22ef01cSRoman Divacky 
379*6beeb091SDimitry Andric unsigned
3807d523365SDimitry Andric MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) {
381*6beeb091SDimitry Andric   assert(getParent() && "MBB must be inserted in function");
382*6beeb091SDimitry Andric   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
383*6beeb091SDimitry Andric   assert(RC && "Register class is required");
3847d523365SDimitry Andric   assert((isEHPad() || this == &getParent()->front()) &&
385*6beeb091SDimitry Andric          "Only the entry block and landing pads can have physreg live ins");
386*6beeb091SDimitry Andric 
387*6beeb091SDimitry Andric   bool LiveIn = isLiveIn(PhysReg);
388*6beeb091SDimitry Andric   iterator I = SkipPHIsAndLabels(begin()), E = end();
389*6beeb091SDimitry Andric   MachineRegisterInfo &MRI = getParent()->getRegInfo();
39039d628a0SDimitry Andric   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
391*6beeb091SDimitry Andric 
392*6beeb091SDimitry Andric   // Look for an existing copy.
393*6beeb091SDimitry Andric   if (LiveIn)
394*6beeb091SDimitry Andric     for (;I != E && I->isCopy(); ++I)
395*6beeb091SDimitry Andric       if (I->getOperand(1).getReg() == PhysReg) {
396*6beeb091SDimitry Andric         unsigned VirtReg = I->getOperand(0).getReg();
397*6beeb091SDimitry Andric         if (!MRI.constrainRegClass(VirtReg, RC))
398*6beeb091SDimitry Andric           llvm_unreachable("Incompatible live-in register class.");
399*6beeb091SDimitry Andric         return VirtReg;
400*6beeb091SDimitry Andric       }
401*6beeb091SDimitry Andric 
402*6beeb091SDimitry Andric   // No luck, create a virtual register.
403*6beeb091SDimitry Andric   unsigned VirtReg = MRI.createVirtualRegister(RC);
404*6beeb091SDimitry Andric   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
405*6beeb091SDimitry Andric     .addReg(PhysReg, RegState::Kill);
406*6beeb091SDimitry Andric   if (!LiveIn)
407*6beeb091SDimitry Andric     addLiveIn(PhysReg);
408*6beeb091SDimitry Andric   return VirtReg;
409*6beeb091SDimitry Andric }
410*6beeb091SDimitry Andric 
411f22ef01cSRoman Divacky void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
4127d523365SDimitry Andric   getParent()->splice(NewAfter->getIterator(), getIterator());
413f22ef01cSRoman Divacky }
414f22ef01cSRoman Divacky 
415f22ef01cSRoman Divacky void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
4167d523365SDimitry Andric   getParent()->splice(++NewBefore->getIterator(), getIterator());
417f22ef01cSRoman Divacky }
418f22ef01cSRoman Divacky 
419f22ef01cSRoman Divacky void MachineBasicBlock::updateTerminator() {
42039d628a0SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
421f22ef01cSRoman Divacky   // A block with no successors has no concerns with fall-through edges.
4223ca95b02SDimitry Andric   if (this->succ_empty())
4233ca95b02SDimitry Andric     return;
424f22ef01cSRoman Divacky 
42591bc56edSDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
426f22ef01cSRoman Divacky   SmallVector<MachineOperand, 4> Cond;
4277a7e6055SDimitry Andric   DebugLoc DL = findBranchDebugLoc();
4283ca95b02SDimitry Andric   bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
429f22ef01cSRoman Divacky   (void) B;
430f22ef01cSRoman Divacky   assert(!B && "UpdateTerminators requires analyzable predecessors!");
431f22ef01cSRoman Divacky   if (Cond.empty()) {
432f22ef01cSRoman Divacky     if (TBB) {
4333ca95b02SDimitry Andric       // The block has an unconditional branch. If its successor is now its
4343ca95b02SDimitry Andric       // layout successor, delete the branch.
435f22ef01cSRoman Divacky       if (isLayoutSuccessor(TBB))
436d88c1a5aSDimitry Andric         TII->removeBranch(*this);
437f22ef01cSRoman Divacky     } else {
4383ca95b02SDimitry Andric       // The block has an unconditional fallthrough. If its successor is not its
4393ca95b02SDimitry Andric       // layout successor, insert a branch. First we have to locate the only
4403ca95b02SDimitry Andric       // non-landing-pad successor, as that is the fallthrough block.
441dff0c46cSDimitry Andric       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
4427d523365SDimitry Andric         if ((*SI)->isEHPad())
443dff0c46cSDimitry Andric           continue;
444dff0c46cSDimitry Andric         assert(!TBB && "Found more than one non-landing-pad successor!");
445dff0c46cSDimitry Andric         TBB = *SI;
446dff0c46cSDimitry Andric       }
447dff0c46cSDimitry Andric 
4483ca95b02SDimitry Andric       // If there is no non-landing-pad successor, the block has no fall-through
4493ca95b02SDimitry Andric       // edges to be concerned with.
450dff0c46cSDimitry Andric       if (!TBB)
451dff0c46cSDimitry Andric         return;
452dff0c46cSDimitry Andric 
453dff0c46cSDimitry Andric       // Finally update the unconditional successor to be reached via a branch
454dff0c46cSDimitry Andric       // if it would not be reached by fallthrough.
455f22ef01cSRoman Divacky       if (!isLayoutSuccessor(TBB))
456d88c1a5aSDimitry Andric         TII->insertBranch(*this, TBB, nullptr, Cond, DL);
457f22ef01cSRoman Divacky     }
4583ca95b02SDimitry Andric     return;
4593ca95b02SDimitry Andric   }
4603ca95b02SDimitry Andric 
461f22ef01cSRoman Divacky   if (FBB) {
462f22ef01cSRoman Divacky     // The block has a non-fallthrough conditional branch. If one of its
463f22ef01cSRoman Divacky     // successors is its layout successor, rewrite it to a fallthrough
464f22ef01cSRoman Divacky     // conditional branch.
465f22ef01cSRoman Divacky     if (isLayoutSuccessor(TBB)) {
466d88c1a5aSDimitry Andric       if (TII->reverseBranchCondition(Cond))
467f22ef01cSRoman Divacky         return;
468d88c1a5aSDimitry Andric       TII->removeBranch(*this);
469d88c1a5aSDimitry Andric       TII->insertBranch(*this, FBB, nullptr, Cond, DL);
470f22ef01cSRoman Divacky     } else if (isLayoutSuccessor(FBB)) {
471d88c1a5aSDimitry Andric       TII->removeBranch(*this);
472d88c1a5aSDimitry Andric       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
473f22ef01cSRoman Divacky     }
4743ca95b02SDimitry Andric     return;
4753ca95b02SDimitry Andric   }
4763ca95b02SDimitry Andric 
4773ca95b02SDimitry Andric   // Walk through the successors and find the successor which is not a landing
4783ca95b02SDimitry Andric   // pad and is not the conditional branch destination (in TBB) as the
4793ca95b02SDimitry Andric   // fallthrough successor.
48091bc56edSDimitry Andric   MachineBasicBlock *FallthroughBB = nullptr;
481cb4dff85SDimitry Andric   for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
4827d523365SDimitry Andric     if ((*SI)->isEHPad() || *SI == TBB)
483cb4dff85SDimitry Andric       continue;
484cb4dff85SDimitry Andric     assert(!FallthroughBB && "Found more than one fallthrough successor.");
485cb4dff85SDimitry Andric     FallthroughBB = *SI;
486cb4dff85SDimitry Andric   }
4873ca95b02SDimitry Andric 
4883ca95b02SDimitry Andric   if (!FallthroughBB) {
4893ca95b02SDimitry Andric     if (canFallThrough()) {
4903ca95b02SDimitry Andric       // We fallthrough to the same basic block as the conditional jump targets.
4913ca95b02SDimitry Andric       // Remove the conditional jump, leaving unconditional fallthrough.
4923ca95b02SDimitry Andric       // FIXME: This does not seem like a reasonable pattern to support, but it
4933ca95b02SDimitry Andric       // has been seen in the wild coming out of degenerate ARM test cases.
494d88c1a5aSDimitry Andric       TII->removeBranch(*this);
495cb4dff85SDimitry Andric 
4963ca95b02SDimitry Andric       // Finally update the unconditional successor to be reached via a branch if
4973ca95b02SDimitry Andric       // it would not be reached by fallthrough.
498cb4dff85SDimitry Andric       if (!isLayoutSuccessor(TBB))
499d88c1a5aSDimitry Andric         TII->insertBranch(*this, TBB, nullptr, Cond, DL);
500cb4dff85SDimitry Andric       return;
501cb4dff85SDimitry Andric     }
502cb4dff85SDimitry Andric 
5033ca95b02SDimitry Andric     // We enter here iff exactly one successor is TBB which cannot fallthrough
5043ca95b02SDimitry Andric     // and the rest successors if any are EHPads.  In this case, we need to
5053ca95b02SDimitry Andric     // change the conditional branch into unconditional branch.
506d88c1a5aSDimitry Andric     TII->removeBranch(*this);
5073ca95b02SDimitry Andric     Cond.clear();
508d88c1a5aSDimitry Andric     TII->insertBranch(*this, TBB, nullptr, Cond, DL);
5093ca95b02SDimitry Andric     return;
5103ca95b02SDimitry Andric   }
5113ca95b02SDimitry Andric 
512f22ef01cSRoman Divacky   // The block has a fallthrough conditional branch.
513f22ef01cSRoman Divacky   if (isLayoutSuccessor(TBB)) {
514d88c1a5aSDimitry Andric     if (TII->reverseBranchCondition(Cond)) {
515f22ef01cSRoman Divacky       // We can't reverse the condition, add an unconditional branch.
516f22ef01cSRoman Divacky       Cond.clear();
517d88c1a5aSDimitry Andric       TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
518f22ef01cSRoman Divacky       return;
519f22ef01cSRoman Divacky     }
520d88c1a5aSDimitry Andric     TII->removeBranch(*this);
521d88c1a5aSDimitry Andric     TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
522cb4dff85SDimitry Andric   } else if (!isLayoutSuccessor(FallthroughBB)) {
523d88c1a5aSDimitry Andric     TII->removeBranch(*this);
524d88c1a5aSDimitry Andric     TII->insertBranch(*this, TBB, FallthroughBB, Cond, DL);
525f22ef01cSRoman Divacky   }
526f22ef01cSRoman Divacky }
527f22ef01cSRoman Divacky 
5287d523365SDimitry Andric void MachineBasicBlock::validateSuccProbs() const {
5297d523365SDimitry Andric #ifndef NDEBUG
5307d523365SDimitry Andric   int64_t Sum = 0;
5317d523365SDimitry Andric   for (auto Prob : Probs)
5327d523365SDimitry Andric     Sum += Prob.getNumerator();
5337d523365SDimitry Andric   // Due to precision issue, we assume that the sum of probabilities is one if
5347d523365SDimitry Andric   // the difference between the sum of their numerators and the denominator is
5357d523365SDimitry Andric   // no greater than the number of successors.
5367d523365SDimitry Andric   assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
5377d523365SDimitry Andric              Probs.size() &&
5387d523365SDimitry Andric          "The sum of successors's probabilities exceeds one.");
5397d523365SDimitry Andric #endif // NDEBUG
540f22ef01cSRoman Divacky }
541f22ef01cSRoman Divacky 
5427d523365SDimitry Andric void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
5437d523365SDimitry Andric                                      BranchProbability Prob) {
5447d523365SDimitry Andric   // Probability list is either empty (if successor list isn't empty, this means
5457d523365SDimitry Andric   // disabled optimization) or has the same size as successor list.
5467d523365SDimitry Andric   if (!(Probs.empty() && !Successors.empty()))
5477d523365SDimitry Andric     Probs.push_back(Prob);
5487d523365SDimitry Andric   Successors.push_back(Succ);
5497d523365SDimitry Andric   Succ->addPredecessor(this);
55017a519f9SDimitry Andric }
55117a519f9SDimitry Andric 
5527d523365SDimitry Andric void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
5537d523365SDimitry Andric   // We need to make sure probability list is either empty or has the same size
5547d523365SDimitry Andric   // of successor list. When this function is called, we can safely delete all
5557d523365SDimitry Andric   // probability in the list.
5567d523365SDimitry Andric   Probs.clear();
5577d523365SDimitry Andric   Successors.push_back(Succ);
5587d523365SDimitry Andric   Succ->addPredecessor(this);
5597d523365SDimitry Andric }
5607d523365SDimitry Andric 
5617d523365SDimitry Andric void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
5627d523365SDimitry Andric                                         bool NormalizeSuccProbs) {
563d88c1a5aSDimitry Andric   succ_iterator I = find(Successors, Succ);
5647d523365SDimitry Andric   removeSuccessor(I, NormalizeSuccProbs);
565f22ef01cSRoman Divacky }
566f22ef01cSRoman Divacky 
567f22ef01cSRoman Divacky MachineBasicBlock::succ_iterator
5687d523365SDimitry Andric MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
569f22ef01cSRoman Divacky   assert(I != Successors.end() && "Not a current successor!");
57017a519f9SDimitry Andric 
5717d523365SDimitry Andric   // If probability list is empty it means we don't use it (disabled
5727d523365SDimitry Andric   // optimization).
5737d523365SDimitry Andric   if (!Probs.empty()) {
5747d523365SDimitry Andric     probability_iterator WI = getProbabilityIterator(I);
5757d523365SDimitry Andric     Probs.erase(WI);
5767d523365SDimitry Andric     if (NormalizeSuccProbs)
5777d523365SDimitry Andric       normalizeSuccProbs();
57817a519f9SDimitry Andric   }
57917a519f9SDimitry Andric 
580f22ef01cSRoman Divacky   (*I)->removePredecessor(this);
581f22ef01cSRoman Divacky   return Successors.erase(I);
582f22ef01cSRoman Divacky }
583f22ef01cSRoman Divacky 
58417a519f9SDimitry Andric void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
58517a519f9SDimitry Andric                                          MachineBasicBlock *New) {
5867ae0e2c9SDimitry Andric   if (Old == New)
5877ae0e2c9SDimitry Andric     return;
58817a519f9SDimitry Andric 
5897ae0e2c9SDimitry Andric   succ_iterator E = succ_end();
5907ae0e2c9SDimitry Andric   succ_iterator NewI = E;
5917ae0e2c9SDimitry Andric   succ_iterator OldI = E;
5927ae0e2c9SDimitry Andric   for (succ_iterator I = succ_begin(); I != E; ++I) {
5937ae0e2c9SDimitry Andric     if (*I == Old) {
5947ae0e2c9SDimitry Andric       OldI = I;
5957ae0e2c9SDimitry Andric       if (NewI != E)
5967ae0e2c9SDimitry Andric         break;
5977ae0e2c9SDimitry Andric     }
5987ae0e2c9SDimitry Andric     if (*I == New) {
5997ae0e2c9SDimitry Andric       NewI = I;
6007ae0e2c9SDimitry Andric       if (OldI != E)
6017ae0e2c9SDimitry Andric         break;
6027ae0e2c9SDimitry Andric     }
6037ae0e2c9SDimitry Andric   }
6047ae0e2c9SDimitry Andric   assert(OldI != E && "Old is not a successor of this block");
6057ae0e2c9SDimitry Andric 
6067ae0e2c9SDimitry Andric   // If New isn't already a successor, let it take Old's place.
6077ae0e2c9SDimitry Andric   if (NewI == E) {
6087d523365SDimitry Andric     Old->removePredecessor(this);
6097ae0e2c9SDimitry Andric     New->addPredecessor(this);
6107ae0e2c9SDimitry Andric     *OldI = New;
6117ae0e2c9SDimitry Andric     return;
61217a519f9SDimitry Andric   }
61317a519f9SDimitry Andric 
6147ae0e2c9SDimitry Andric   // New is already a successor.
6157d523365SDimitry Andric   // Update its probability instead of adding a duplicate edge.
6167d523365SDimitry Andric   if (!Probs.empty()) {
6177d523365SDimitry Andric     auto ProbIter = getProbabilityIterator(NewI);
6187d523365SDimitry Andric     if (!ProbIter->isUnknown())
6197d523365SDimitry Andric       *ProbIter += *getProbabilityIterator(OldI);
6207ae0e2c9SDimitry Andric   }
6217d523365SDimitry Andric   removeSuccessor(OldI);
62217a519f9SDimitry Andric }
62317a519f9SDimitry Andric 
6247d523365SDimitry Andric void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
6257d523365SDimitry Andric   Predecessors.push_back(Pred);
626f22ef01cSRoman Divacky }
627f22ef01cSRoman Divacky 
6287d523365SDimitry Andric void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
629d88c1a5aSDimitry Andric   pred_iterator I = find(Predecessors, Pred);
630f22ef01cSRoman Divacky   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
631f22ef01cSRoman Divacky   Predecessors.erase(I);
632f22ef01cSRoman Divacky }
633f22ef01cSRoman Divacky 
6347d523365SDimitry Andric void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
6357d523365SDimitry Andric   if (this == FromMBB)
636f22ef01cSRoman Divacky     return;
637f22ef01cSRoman Divacky 
6387d523365SDimitry Andric   while (!FromMBB->succ_empty()) {
6397d523365SDimitry Andric     MachineBasicBlock *Succ = *FromMBB->succ_begin();
64017a519f9SDimitry Andric 
6417d523365SDimitry Andric     // If probability list is empty it means we don't use it (disabled optimization).
6427d523365SDimitry Andric     if (!FromMBB->Probs.empty()) {
6437d523365SDimitry Andric       auto Prob = *FromMBB->Probs.begin();
6447d523365SDimitry Andric       addSuccessor(Succ, Prob);
6457d523365SDimitry Andric     } else
6467d523365SDimitry Andric       addSuccessorWithoutProb(Succ);
64717a519f9SDimitry Andric 
6487d523365SDimitry Andric     FromMBB->removeSuccessor(Succ);
649ffd1746dSEd Schouten   }
650ffd1746dSEd Schouten }
651f22ef01cSRoman Divacky 
652ffd1746dSEd Schouten void
6537d523365SDimitry Andric MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
6547d523365SDimitry Andric   if (this == FromMBB)
655ffd1746dSEd Schouten     return;
656ffd1746dSEd Schouten 
6577d523365SDimitry Andric   while (!FromMBB->succ_empty()) {
6587d523365SDimitry Andric     MachineBasicBlock *Succ = *FromMBB->succ_begin();
6597d523365SDimitry Andric     if (!FromMBB->Probs.empty()) {
6607d523365SDimitry Andric       auto Prob = *FromMBB->Probs.begin();
6617d523365SDimitry Andric       addSuccessor(Succ, Prob);
6627d523365SDimitry Andric     } else
6637d523365SDimitry Andric       addSuccessorWithoutProb(Succ);
6647d523365SDimitry Andric     FromMBB->removeSuccessor(Succ);
665ffd1746dSEd Schouten 
666ffd1746dSEd Schouten     // Fix up any PHI nodes in the successor.
667dff0c46cSDimitry Andric     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
668dff0c46cSDimitry Andric            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
669ffd1746dSEd Schouten       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
670ffd1746dSEd Schouten         MachineOperand &MO = MI->getOperand(i);
6717d523365SDimitry Andric         if (MO.getMBB() == FromMBB)
672ffd1746dSEd Schouten           MO.setMBB(this);
673ffd1746dSEd Schouten       }
674ffd1746dSEd Schouten   }
6757d523365SDimitry Andric   normalizeSuccProbs();
676f22ef01cSRoman Divacky }
677f22ef01cSRoman Divacky 
6787ae0e2c9SDimitry Andric bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
679d88c1a5aSDimitry Andric   return is_contained(predecessors(), MBB);
6807ae0e2c9SDimitry Andric }
6817ae0e2c9SDimitry Andric 
682f22ef01cSRoman Divacky bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
683d88c1a5aSDimitry Andric   return is_contained(successors(), MBB);
684f22ef01cSRoman Divacky }
685f22ef01cSRoman Divacky 
686f22ef01cSRoman Divacky bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
687f22ef01cSRoman Divacky   MachineFunction::const_iterator I(this);
68891bc56edSDimitry Andric   return std::next(I) == MachineFunction::const_iterator(MBB);
689f22ef01cSRoman Divacky }
690f22ef01cSRoman Divacky 
6917a7e6055SDimitry Andric MachineBasicBlock *MachineBasicBlock::getFallThrough() {
6927d523365SDimitry Andric   MachineFunction::iterator Fallthrough = getIterator();
693f22ef01cSRoman Divacky   ++Fallthrough;
694f22ef01cSRoman Divacky   // If FallthroughBlock is off the end of the function, it can't fall through.
695f22ef01cSRoman Divacky   if (Fallthrough == getParent()->end())
6967a7e6055SDimitry Andric     return nullptr;
697f22ef01cSRoman Divacky 
698f22ef01cSRoman Divacky   // If FallthroughBlock isn't a successor, no fallthrough is possible.
6997d523365SDimitry Andric   if (!isSuccessor(&*Fallthrough))
7007a7e6055SDimitry Andric     return nullptr;
701f22ef01cSRoman Divacky 
702f22ef01cSRoman Divacky   // Analyze the branches, if any, at the end of the block.
70391bc56edSDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
704f22ef01cSRoman Divacky   SmallVector<MachineOperand, 4> Cond;
70539d628a0SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
7063ca95b02SDimitry Andric   if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
707f22ef01cSRoman Divacky     // If we couldn't analyze the branch, examine the last instruction.
708f22ef01cSRoman Divacky     // If the block doesn't end in a known control barrier, assume fallthrough
709dff0c46cSDimitry Andric     // is possible. The isPredicated check is needed because this code can be
710f22ef01cSRoman Divacky     // called during IfConversion, where an instruction which is normally a
711dff0c46cSDimitry Andric     // Barrier is predicated and thus no longer an actual control barrier.
7127a7e6055SDimitry Andric     return (empty() || !back().isBarrier() || TII->isPredicated(back()))
7137a7e6055SDimitry Andric                ? &*Fallthrough
7147a7e6055SDimitry Andric                : nullptr;
715f22ef01cSRoman Divacky   }
716f22ef01cSRoman Divacky 
717f22ef01cSRoman Divacky   // If there is no branch, control always falls through.
7187a7e6055SDimitry Andric   if (!TBB) return &*Fallthrough;
719f22ef01cSRoman Divacky 
720f22ef01cSRoman Divacky   // If there is some explicit branch to the fallthrough block, it can obviously
721f22ef01cSRoman Divacky   // reach, even though the branch should get folded to fall through implicitly.
722f22ef01cSRoman Divacky   if (MachineFunction::iterator(TBB) == Fallthrough ||
723f22ef01cSRoman Divacky       MachineFunction::iterator(FBB) == Fallthrough)
7247a7e6055SDimitry Andric     return &*Fallthrough;
725f22ef01cSRoman Divacky 
726f22ef01cSRoman Divacky   // If it's an unconditional branch to some block not the fall through, it
727f22ef01cSRoman Divacky   // doesn't fall through.
7287a7e6055SDimitry Andric   if (Cond.empty()) return nullptr;
729f22ef01cSRoman Divacky 
730f22ef01cSRoman Divacky   // Otherwise, if it is conditional and has no explicit false block, it falls
731f22ef01cSRoman Divacky   // through.
7327a7e6055SDimitry Andric   return (FBB == nullptr) ? &*Fallthrough : nullptr;
7337a7e6055SDimitry Andric }
7347a7e6055SDimitry Andric 
7357a7e6055SDimitry Andric bool MachineBasicBlock::canFallThrough() {
7367a7e6055SDimitry Andric   return getFallThrough() != nullptr;
737f22ef01cSRoman Divacky }
738f22ef01cSRoman Divacky 
7393ca95b02SDimitry Andric MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ,
7403ca95b02SDimitry Andric                                                         Pass &P) {
7413ca95b02SDimitry Andric   if (!canSplitCriticalEdge(Succ))
74291bc56edSDimitry Andric     return nullptr;
7437ae0e2c9SDimitry Andric 
744ffd1746dSEd Schouten   MachineFunction *MF = getParent();
7457d523365SDimitry Andric   DebugLoc DL;  // FIXME: this is nowhere
746ffd1746dSEd Schouten 
747ffd1746dSEd Schouten   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
74891bc56edSDimitry Andric   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
749e580952dSDimitry Andric   DEBUG(dbgs() << "Splitting critical edge:"
750ffd1746dSEd Schouten         " BB#" << getNumber()
751ffd1746dSEd Schouten         << " -- BB#" << NMBB->getNumber()
752ffd1746dSEd Schouten         << " -- BB#" << Succ->getNumber() << '\n');
753ffd1746dSEd Schouten 
7543ca95b02SDimitry Andric   LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
7553ca95b02SDimitry Andric   SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
756139f7f9bSDimitry Andric   if (LIS)
757139f7f9bSDimitry Andric     LIS->insertMBBInMaps(NMBB);
758139f7f9bSDimitry Andric   else if (Indexes)
759139f7f9bSDimitry Andric     Indexes->insertMBBInMaps(NMBB);
760139f7f9bSDimitry Andric 
761bd5abe19SDimitry Andric   // On some targets like Mips, branches may kill virtual registers. Make sure
762bd5abe19SDimitry Andric   // that LiveVariables is properly updated after updateTerminator replaces the
763bd5abe19SDimitry Andric   // terminators.
7643ca95b02SDimitry Andric   LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
765bd5abe19SDimitry Andric 
766bd5abe19SDimitry Andric   // Collect a list of virtual registers killed by the terminators.
767bd5abe19SDimitry Andric   SmallVector<unsigned, 4> KilledRegs;
768bd5abe19SDimitry Andric   if (LV)
769dff0c46cSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
770dff0c46cSDimitry Andric          I != E; ++I) {
7717d523365SDimitry Andric       MachineInstr *MI = &*I;
772bd5abe19SDimitry Andric       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
773bd5abe19SDimitry Andric            OE = MI->operands_end(); OI != OE; ++OI) {
774dff0c46cSDimitry Andric         if (!OI->isReg() || OI->getReg() == 0 ||
775dff0c46cSDimitry Andric             !OI->isUse() || !OI->isKill() || OI->isUndef())
776bd5abe19SDimitry Andric           continue;
777bd5abe19SDimitry Andric         unsigned Reg = OI->getReg();
778dff0c46cSDimitry Andric         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
7793ca95b02SDimitry Andric             LV->getVarInfo(Reg).removeKill(*MI)) {
780bd5abe19SDimitry Andric           KilledRegs.push_back(Reg);
781bd5abe19SDimitry Andric           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
782bd5abe19SDimitry Andric           OI->setIsKill(false);
783bd5abe19SDimitry Andric         }
784bd5abe19SDimitry Andric       }
785bd5abe19SDimitry Andric     }
786bd5abe19SDimitry Andric 
787139f7f9bSDimitry Andric   SmallVector<unsigned, 4> UsedRegs;
788139f7f9bSDimitry Andric   if (LIS) {
789139f7f9bSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
790139f7f9bSDimitry Andric          I != E; ++I) {
7917d523365SDimitry Andric       MachineInstr *MI = &*I;
792139f7f9bSDimitry Andric 
793139f7f9bSDimitry Andric       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
794139f7f9bSDimitry Andric            OE = MI->operands_end(); OI != OE; ++OI) {
795139f7f9bSDimitry Andric         if (!OI->isReg() || OI->getReg() == 0)
796139f7f9bSDimitry Andric           continue;
797139f7f9bSDimitry Andric 
798139f7f9bSDimitry Andric         unsigned Reg = OI->getReg();
799d88c1a5aSDimitry Andric         if (!is_contained(UsedRegs, Reg))
800139f7f9bSDimitry Andric           UsedRegs.push_back(Reg);
801139f7f9bSDimitry Andric       }
802139f7f9bSDimitry Andric     }
803139f7f9bSDimitry Andric   }
804139f7f9bSDimitry Andric 
805ffd1746dSEd Schouten   ReplaceUsesOfBlockWith(Succ, NMBB);
806139f7f9bSDimitry Andric 
807139f7f9bSDimitry Andric   // If updateTerminator() removes instructions, we need to remove them from
808139f7f9bSDimitry Andric   // SlotIndexes.
809139f7f9bSDimitry Andric   SmallVector<MachineInstr*, 4> Terminators;
810139f7f9bSDimitry Andric   if (Indexes) {
811139f7f9bSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
812139f7f9bSDimitry Andric          I != E; ++I)
8137d523365SDimitry Andric       Terminators.push_back(&*I);
814139f7f9bSDimitry Andric   }
815139f7f9bSDimitry Andric 
816ffd1746dSEd Schouten   updateTerminator();
817ffd1746dSEd Schouten 
818139f7f9bSDimitry Andric   if (Indexes) {
819139f7f9bSDimitry Andric     SmallVector<MachineInstr*, 4> NewTerminators;
820139f7f9bSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
821139f7f9bSDimitry Andric          I != E; ++I)
8227d523365SDimitry Andric       NewTerminators.push_back(&*I);
823139f7f9bSDimitry Andric 
824139f7f9bSDimitry Andric     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
825139f7f9bSDimitry Andric         E = Terminators.end(); I != E; ++I) {
826d88c1a5aSDimitry Andric       if (!is_contained(NewTerminators, *I))
8273ca95b02SDimitry Andric         Indexes->removeMachineInstrFromMaps(**I);
828139f7f9bSDimitry Andric     }
829139f7f9bSDimitry Andric   }
830139f7f9bSDimitry Andric 
831ffd1746dSEd Schouten   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
832ffd1746dSEd Schouten   NMBB->addSuccessor(Succ);
833ffd1746dSEd Schouten   if (!NMBB->isLayoutSuccessor(Succ)) {
8343ca95b02SDimitry Andric     SmallVector<MachineOperand, 4> Cond;
8353ca95b02SDimitry Andric     const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
836d88c1a5aSDimitry Andric     TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
837139f7f9bSDimitry Andric 
838139f7f9bSDimitry Andric     if (Indexes) {
8393ca95b02SDimitry Andric       for (MachineInstr &MI : NMBB->instrs()) {
840139f7f9bSDimitry Andric         // Some instructions may have been moved to NMBB by updateTerminator(),
841139f7f9bSDimitry Andric         // so we first remove any instruction that already has an index.
8423ca95b02SDimitry Andric         if (Indexes->hasIndex(MI))
8433ca95b02SDimitry Andric           Indexes->removeMachineInstrFromMaps(MI);
8443ca95b02SDimitry Andric         Indexes->insertMachineInstrInMaps(MI);
845139f7f9bSDimitry Andric       }
846139f7f9bSDimitry Andric     }
847ffd1746dSEd Schouten   }
848ffd1746dSEd Schouten 
849ffd1746dSEd Schouten   // Fix PHI nodes in Succ so they refer to NMBB instead of this
850dff0c46cSDimitry Andric   for (MachineBasicBlock::instr_iterator
851dff0c46cSDimitry Andric          i = Succ->instr_begin(),e = Succ->instr_end();
852ffd1746dSEd Schouten        i != e && i->isPHI(); ++i)
853ffd1746dSEd Schouten     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
854ffd1746dSEd Schouten       if (i->getOperand(ni+1).getMBB() == this)
855ffd1746dSEd Schouten         i->getOperand(ni+1).setMBB(NMBB);
856ffd1746dSEd Schouten 
8576122f3e6SDimitry Andric   // Inherit live-ins from the successor
8587d523365SDimitry Andric   for (const auto &LI : Succ->liveins())
8597d523365SDimitry Andric     NMBB->addLiveIn(LI);
8606122f3e6SDimitry Andric 
861bd5abe19SDimitry Andric   // Update LiveVariables.
86239d628a0SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
863bd5abe19SDimitry Andric   if (LV) {
864bd5abe19SDimitry Andric     // Restore kills of virtual registers that were killed by the terminators.
865bd5abe19SDimitry Andric     while (!KilledRegs.empty()) {
866bd5abe19SDimitry Andric       unsigned Reg = KilledRegs.pop_back_val();
867dff0c46cSDimitry Andric       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
868dff0c46cSDimitry Andric         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
869bd5abe19SDimitry Andric           continue;
870dff0c46cSDimitry Andric         if (TargetRegisterInfo::isVirtualRegister(Reg))
8717d523365SDimitry Andric           LV->getVarInfo(Reg).Kills.push_back(&*I);
872bd5abe19SDimitry Andric         DEBUG(dbgs() << "Restored terminator kill: " << *I);
873bd5abe19SDimitry Andric         break;
874bd5abe19SDimitry Andric       }
875bd5abe19SDimitry Andric     }
876bd5abe19SDimitry Andric     // Update relevant live-through information.
877ffd1746dSEd Schouten     LV->addNewBlock(NMBB, this, Succ);
878bd5abe19SDimitry Andric   }
879ffd1746dSEd Schouten 
880139f7f9bSDimitry Andric   if (LIS) {
881139f7f9bSDimitry Andric     // After splitting the edge and updating SlotIndexes, live intervals may be
882139f7f9bSDimitry Andric     // in one of two situations, depending on whether this block was the last in
8837d523365SDimitry Andric     // the function. If the original block was the last in the function, all
8847d523365SDimitry Andric     // live intervals will end prior to the beginning of the new split block. If
8857d523365SDimitry Andric     // the original block was not at the end of the function, all live intervals
8867d523365SDimitry Andric     // will extend to the end of the new split block.
887139f7f9bSDimitry Andric 
888139f7f9bSDimitry Andric     bool isLastMBB =
88991bc56edSDimitry Andric       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
890139f7f9bSDimitry Andric 
891139f7f9bSDimitry Andric     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
892139f7f9bSDimitry Andric     SlotIndex PrevIndex = StartIndex.getPrevSlot();
893139f7f9bSDimitry Andric     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
894139f7f9bSDimitry Andric 
895139f7f9bSDimitry Andric     // Find the registers used from NMBB in PHIs in Succ.
896139f7f9bSDimitry Andric     SmallSet<unsigned, 8> PHISrcRegs;
897139f7f9bSDimitry Andric     for (MachineBasicBlock::instr_iterator
898139f7f9bSDimitry Andric          I = Succ->instr_begin(), E = Succ->instr_end();
899139f7f9bSDimitry Andric          I != E && I->isPHI(); ++I) {
900139f7f9bSDimitry Andric       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
901139f7f9bSDimitry Andric         if (I->getOperand(ni+1).getMBB() == NMBB) {
902139f7f9bSDimitry Andric           MachineOperand &MO = I->getOperand(ni);
903139f7f9bSDimitry Andric           unsigned Reg = MO.getReg();
904139f7f9bSDimitry Andric           PHISrcRegs.insert(Reg);
905139f7f9bSDimitry Andric           if (MO.isUndef())
906139f7f9bSDimitry Andric             continue;
907139f7f9bSDimitry Andric 
908139f7f9bSDimitry Andric           LiveInterval &LI = LIS->getInterval(Reg);
909139f7f9bSDimitry Andric           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
9107d523365SDimitry Andric           assert(VNI &&
9117d523365SDimitry Andric                  "PHI sources should be live out of their predecessors.");
912f785676fSDimitry Andric           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
913139f7f9bSDimitry Andric         }
914139f7f9bSDimitry Andric       }
915139f7f9bSDimitry Andric     }
916139f7f9bSDimitry Andric 
917139f7f9bSDimitry Andric     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
918139f7f9bSDimitry Andric     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
919139f7f9bSDimitry Andric       unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
920139f7f9bSDimitry Andric       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
921139f7f9bSDimitry Andric         continue;
922139f7f9bSDimitry Andric 
923139f7f9bSDimitry Andric       LiveInterval &LI = LIS->getInterval(Reg);
924139f7f9bSDimitry Andric       if (!LI.liveAt(PrevIndex))
925139f7f9bSDimitry Andric         continue;
926139f7f9bSDimitry Andric 
927139f7f9bSDimitry Andric       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
928139f7f9bSDimitry Andric       if (isLiveOut && isLastMBB) {
929139f7f9bSDimitry Andric         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
930139f7f9bSDimitry Andric         assert(VNI && "LiveInterval should have VNInfo where it is live.");
931f785676fSDimitry Andric         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
932139f7f9bSDimitry Andric       } else if (!isLiveOut && !isLastMBB) {
933f785676fSDimitry Andric         LI.removeSegment(StartIndex, EndIndex);
934139f7f9bSDimitry Andric       }
935139f7f9bSDimitry Andric     }
936139f7f9bSDimitry Andric 
937139f7f9bSDimitry Andric     // Update all intervals for registers whose uses may have been modified by
938139f7f9bSDimitry Andric     // updateTerminator().
939139f7f9bSDimitry Andric     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
940139f7f9bSDimitry Andric   }
941139f7f9bSDimitry Andric 
942ffd1746dSEd Schouten   if (MachineDominatorTree *MDT =
9433ca95b02SDimitry Andric           P.getAnalysisIfAvailable<MachineDominatorTree>())
94439d628a0SDimitry Andric     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
945e580952dSDimitry Andric 
9463ca95b02SDimitry Andric   if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
947ffd1746dSEd Schouten     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
948ffd1746dSEd Schouten       // If one or the other blocks were not in a loop, the new block is not
949ffd1746dSEd Schouten       // either, and thus LI doesn't need to be updated.
950ffd1746dSEd Schouten       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
951ffd1746dSEd Schouten         if (TIL == DestLoop) {
952ffd1746dSEd Schouten           // Both in the same loop, the NMBB joins loop.
953ffd1746dSEd Schouten           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
954ffd1746dSEd Schouten         } else if (TIL->contains(DestLoop)) {
955ffd1746dSEd Schouten           // Edge from an outer loop to an inner loop.  Add to the outer loop.
956ffd1746dSEd Schouten           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
957ffd1746dSEd Schouten         } else if (DestLoop->contains(TIL)) {
958ffd1746dSEd Schouten           // Edge from an inner loop to an outer loop.  Add to the outer loop.
959ffd1746dSEd Schouten           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
960ffd1746dSEd Schouten         } else {
961ffd1746dSEd Schouten           // Edge from two loops with no containment relation.  Because these
962ffd1746dSEd Schouten           // are natural loops, we know that the destination block must be the
963ffd1746dSEd Schouten           // header of its loop (adding a branch into a loop elsewhere would
964ffd1746dSEd Schouten           // create an irreducible loop).
965ffd1746dSEd Schouten           assert(DestLoop->getHeader() == Succ &&
966ffd1746dSEd Schouten                  "Should not create irreducible loops!");
967ffd1746dSEd Schouten           if (MachineLoop *P = DestLoop->getParentLoop())
968ffd1746dSEd Schouten             P->addBasicBlockToLoop(NMBB, MLI->getBase());
969ffd1746dSEd Schouten         }
970ffd1746dSEd Schouten       }
971ffd1746dSEd Schouten     }
972ffd1746dSEd Schouten 
973ffd1746dSEd Schouten   return NMBB;
974ffd1746dSEd Schouten }
975ffd1746dSEd Schouten 
9763ca95b02SDimitry Andric bool MachineBasicBlock::canSplitCriticalEdge(
9773ca95b02SDimitry Andric     const MachineBasicBlock *Succ) const {
9783ca95b02SDimitry Andric   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
9793ca95b02SDimitry Andric   // it in this generic function.
9803ca95b02SDimitry Andric   if (Succ->isEHPad())
9813ca95b02SDimitry Andric     return false;
9823ca95b02SDimitry Andric 
9833ca95b02SDimitry Andric   const MachineFunction *MF = getParent();
9843ca95b02SDimitry Andric 
9853ca95b02SDimitry Andric   // Performance might be harmed on HW that implements branching using exec mask
9863ca95b02SDimitry Andric   // where both sides of the branches are always executed.
9873ca95b02SDimitry Andric   if (MF->getTarget().requiresStructuredCFG())
9883ca95b02SDimitry Andric     return false;
9893ca95b02SDimitry Andric 
9903ca95b02SDimitry Andric   // We may need to update this's terminator, but we can't do that if
9913ca95b02SDimitry Andric   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
9923ca95b02SDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
9933ca95b02SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
9943ca95b02SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
9953ca95b02SDimitry Andric   // AnalyzeBanch should modify this, since we did not allow modification.
9963ca95b02SDimitry Andric   if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
9973ca95b02SDimitry Andric                          /*AllowModify*/ false))
9983ca95b02SDimitry Andric     return false;
9993ca95b02SDimitry Andric 
10003ca95b02SDimitry Andric   // Avoid bugpoint weirdness: A block may end with a conditional branch but
10013ca95b02SDimitry Andric   // jumps to the same MBB is either case. We have duplicate CFG edges in that
10023ca95b02SDimitry Andric   // case that we can't handle. Since this never happens in properly optimized
10033ca95b02SDimitry Andric   // code, just skip those edges.
10043ca95b02SDimitry Andric   if (TBB && TBB == FBB) {
10053ca95b02SDimitry Andric     DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
10063ca95b02SDimitry Andric                  << getNumber() << '\n');
10073ca95b02SDimitry Andric     return false;
10083ca95b02SDimitry Andric   }
10093ca95b02SDimitry Andric   return true;
10103ca95b02SDimitry Andric }
10113ca95b02SDimitry Andric 
1012139f7f9bSDimitry Andric /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1013139f7f9bSDimitry Andric /// neighboring instructions so the bundle won't be broken by removing MI.
1014139f7f9bSDimitry Andric static void unbundleSingleMI(MachineInstr *MI) {
1015139f7f9bSDimitry Andric   // Removing the first instruction in a bundle.
1016139f7f9bSDimitry Andric   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1017139f7f9bSDimitry Andric     MI->unbundleFromSucc();
1018139f7f9bSDimitry Andric   // Removing the last instruction in a bundle.
1019139f7f9bSDimitry Andric   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1020139f7f9bSDimitry Andric     MI->unbundleFromPred();
1021139f7f9bSDimitry Andric   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1022139f7f9bSDimitry Andric   // are already fine.
1023dff0c46cSDimitry Andric }
1024dff0c46cSDimitry Andric 
1025139f7f9bSDimitry Andric MachineBasicBlock::instr_iterator
1026139f7f9bSDimitry Andric MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
10277d523365SDimitry Andric   unbundleSingleMI(&*I);
1028139f7f9bSDimitry Andric   return Insts.erase(I);
1029dff0c46cSDimitry Andric }
1030dff0c46cSDimitry Andric 
1031139f7f9bSDimitry Andric MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1032139f7f9bSDimitry Andric   unbundleSingleMI(MI);
1033139f7f9bSDimitry Andric   MI->clearFlag(MachineInstr::BundledPred);
1034139f7f9bSDimitry Andric   MI->clearFlag(MachineInstr::BundledSucc);
1035139f7f9bSDimitry Andric   return Insts.remove(MI);
1036dff0c46cSDimitry Andric }
1037dff0c46cSDimitry Andric 
1038139f7f9bSDimitry Andric MachineBasicBlock::instr_iterator
1039139f7f9bSDimitry Andric MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1040139f7f9bSDimitry Andric   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1041139f7f9bSDimitry Andric          "Cannot insert instruction with bundle flags");
1042139f7f9bSDimitry Andric   // Set the bundle flags when inserting inside a bundle.
1043139f7f9bSDimitry Andric   if (I != instr_end() && I->isBundledWithPred()) {
1044139f7f9bSDimitry Andric     MI->setFlag(MachineInstr::BundledPred);
1045139f7f9bSDimitry Andric     MI->setFlag(MachineInstr::BundledSucc);
1046dff0c46cSDimitry Andric   }
1047139f7f9bSDimitry Andric   return Insts.insert(I, MI);
1048dff0c46cSDimitry Andric }
1049dff0c46cSDimitry Andric 
10507d523365SDimitry Andric /// This method unlinks 'this' from the containing function, and returns it, but
10517d523365SDimitry Andric /// does not delete it.
1052f22ef01cSRoman Divacky MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1053f22ef01cSRoman Divacky   assert(getParent() && "Not embedded in a function!");
1054f22ef01cSRoman Divacky   getParent()->remove(this);
1055f22ef01cSRoman Divacky   return this;
1056f22ef01cSRoman Divacky }
1057f22ef01cSRoman Divacky 
10587d523365SDimitry Andric /// This method unlinks 'this' from the containing function, and deletes it.
1059f22ef01cSRoman Divacky void MachineBasicBlock::eraseFromParent() {
1060f22ef01cSRoman Divacky   assert(getParent() && "Not embedded in a function!");
1061f22ef01cSRoman Divacky   getParent()->erase(this);
1062f22ef01cSRoman Divacky }
1063f22ef01cSRoman Divacky 
10647d523365SDimitry Andric /// Given a machine basic block that branched to 'Old', change the code and CFG
10657d523365SDimitry Andric /// so that it branches to 'New' instead.
1066f22ef01cSRoman Divacky void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1067f22ef01cSRoman Divacky                                                MachineBasicBlock *New) {
1068f22ef01cSRoman Divacky   assert(Old != New && "Cannot replace self with self!");
1069f22ef01cSRoman Divacky 
1070dff0c46cSDimitry Andric   MachineBasicBlock::instr_iterator I = instr_end();
1071dff0c46cSDimitry Andric   while (I != instr_begin()) {
1072f22ef01cSRoman Divacky     --I;
1073dff0c46cSDimitry Andric     if (!I->isTerminator()) break;
1074f22ef01cSRoman Divacky 
1075f22ef01cSRoman Divacky     // Scan the operands of this machine instruction, replacing any uses of Old
1076f22ef01cSRoman Divacky     // with New.
1077f22ef01cSRoman Divacky     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1078f22ef01cSRoman Divacky       if (I->getOperand(i).isMBB() &&
1079f22ef01cSRoman Divacky           I->getOperand(i).getMBB() == Old)
1080f22ef01cSRoman Divacky         I->getOperand(i).setMBB(New);
1081f22ef01cSRoman Divacky   }
1082f22ef01cSRoman Divacky 
1083f22ef01cSRoman Divacky   // Update the successor information.
108417a519f9SDimitry Andric   replaceSuccessor(Old, New);
1085f22ef01cSRoman Divacky }
1086f22ef01cSRoman Divacky 
10877d523365SDimitry Andric /// Various pieces of code can cause excess edges in the CFG to be inserted.  If
10887d523365SDimitry Andric /// we have proven that MBB can only branch to DestA and DestB, remove any other
10897d523365SDimitry Andric /// MBB successors from the CFG.  DestA and DestB can be null.
1090f22ef01cSRoman Divacky ///
1091f22ef01cSRoman Divacky /// Besides DestA and DestB, retain other edges leading to LandingPads
1092f22ef01cSRoman Divacky /// (currently there can be only one; we don't check or require that here).
1093f22ef01cSRoman Divacky /// Note it is possible that DestA and/or DestB are LandingPads.
1094f22ef01cSRoman Divacky bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1095f22ef01cSRoman Divacky                                              MachineBasicBlock *DestB,
10967d523365SDimitry Andric                                              bool IsCond) {
1097f22ef01cSRoman Divacky   // The values of DestA and DestB frequently come from a call to the
1098f22ef01cSRoman Divacky   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1099f22ef01cSRoman Divacky   // values from there.
1100f22ef01cSRoman Divacky   //
1101f22ef01cSRoman Divacky   // 1. If both DestA and DestB are null, then the block ends with no branches
1102f22ef01cSRoman Divacky   //    (it falls through to its successor).
11037d523365SDimitry Andric   // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends
1104f22ef01cSRoman Divacky   //    with only an unconditional branch.
11057d523365SDimitry Andric   // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends
1106f22ef01cSRoman Divacky   //    with a conditional branch that falls through to a successor (DestB).
11077d523365SDimitry Andric   // 4. If DestA and DestB is set and IsCond is true, then the block ends with a
1108f22ef01cSRoman Divacky   //    conditional branch followed by an unconditional branch. DestA is the
1109f22ef01cSRoman Divacky   //    'true' destination and DestB is the 'false' destination.
1110f22ef01cSRoman Divacky 
1111f22ef01cSRoman Divacky   bool Changed = false;
1112f22ef01cSRoman Divacky 
1113d88c1a5aSDimitry Andric   MachineBasicBlock *FallThru = getNextNode();
1114f22ef01cSRoman Divacky 
111591bc56edSDimitry Andric   if (!DestA && !DestB) {
1116f22ef01cSRoman Divacky     // Block falls through to successor.
1117d88c1a5aSDimitry Andric     DestA = FallThru;
1118d88c1a5aSDimitry Andric     DestB = FallThru;
111991bc56edSDimitry Andric   } else if (DestA && !DestB) {
11207d523365SDimitry Andric     if (IsCond)
1121f22ef01cSRoman Divacky       // Block ends in conditional jump that falls through to successor.
1122d88c1a5aSDimitry Andric       DestB = FallThru;
1123f22ef01cSRoman Divacky   } else {
11247d523365SDimitry Andric     assert(DestA && DestB && IsCond &&
1125f22ef01cSRoman Divacky            "CFG in a bad state. Cannot correct CFG edges");
1126f22ef01cSRoman Divacky   }
1127f22ef01cSRoman Divacky 
1128f22ef01cSRoman Divacky   // Remove superfluous edges. I.e., those which aren't destinations of this
1129f22ef01cSRoman Divacky   // basic block, duplicate edges, or landing pads.
1130f22ef01cSRoman Divacky   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1131f22ef01cSRoman Divacky   MachineBasicBlock::succ_iterator SI = succ_begin();
1132f22ef01cSRoman Divacky   while (SI != succ_end()) {
1133f22ef01cSRoman Divacky     const MachineBasicBlock *MBB = *SI;
113439d628a0SDimitry Andric     if (!SeenMBBs.insert(MBB).second ||
11357d523365SDimitry Andric         (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
1136f22ef01cSRoman Divacky       // This is a superfluous edge, remove it.
1137f22ef01cSRoman Divacky       SI = removeSuccessor(SI);
1138f22ef01cSRoman Divacky       Changed = true;
1139f22ef01cSRoman Divacky     } else {
1140f22ef01cSRoman Divacky       ++SI;
1141f22ef01cSRoman Divacky     }
1142f22ef01cSRoman Divacky   }
1143f22ef01cSRoman Divacky 
11447d523365SDimitry Andric   if (Changed)
11457d523365SDimitry Andric     normalizeSuccProbs();
1146f22ef01cSRoman Divacky   return Changed;
1147f22ef01cSRoman Divacky }
1148f22ef01cSRoman Divacky 
11497d523365SDimitry Andric /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
11507d523365SDimitry Andric /// instructions.  Return UnknownLoc if there is none.
1151f22ef01cSRoman Divacky DebugLoc
1152dff0c46cSDimitry Andric MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1153f22ef01cSRoman Divacky   // Skip debug declarations, we don't want a DebugLoc from them.
1154d88c1a5aSDimitry Andric   MBBI = skipDebugInstructionsForward(MBBI, instr_end());
1155d88c1a5aSDimitry Andric   if (MBBI != instr_end())
1156d88c1a5aSDimitry Andric     return MBBI->getDebugLoc();
1157d88c1a5aSDimitry Andric   return {};
1158f22ef01cSRoman Divacky }
1159f22ef01cSRoman Divacky 
11607a7e6055SDimitry Andric /// Find and return the merged DebugLoc of the branch instructions of the block.
11617a7e6055SDimitry Andric /// Return UnknownLoc if there is none.
11627a7e6055SDimitry Andric DebugLoc
11637a7e6055SDimitry Andric MachineBasicBlock::findBranchDebugLoc() {
11647a7e6055SDimitry Andric   DebugLoc DL;
11657a7e6055SDimitry Andric   auto TI = getFirstTerminator();
11667a7e6055SDimitry Andric   while (TI != end() && !TI->isBranch())
11677a7e6055SDimitry Andric     ++TI;
11687a7e6055SDimitry Andric 
11697a7e6055SDimitry Andric   if (TI != end()) {
11707a7e6055SDimitry Andric     DL = TI->getDebugLoc();
11717a7e6055SDimitry Andric     for (++TI ; TI != end() ; ++TI)
11727a7e6055SDimitry Andric       if (TI->isBranch())
11737a7e6055SDimitry Andric         DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
11747a7e6055SDimitry Andric   }
11757a7e6055SDimitry Andric   return DL;
11767a7e6055SDimitry Andric }
11777a7e6055SDimitry Andric 
11787d523365SDimitry Andric /// Return probability of the edge from this block to MBB.
11797d523365SDimitry Andric BranchProbability
11807d523365SDimitry Andric MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
11817d523365SDimitry Andric   if (Probs.empty())
11827d523365SDimitry Andric     return BranchProbability(1, succ_size());
118317a519f9SDimitry Andric 
11847d523365SDimitry Andric   const auto &Prob = *getProbabilityIterator(Succ);
11857d523365SDimitry Andric   if (Prob.isUnknown()) {
11867d523365SDimitry Andric     // For unknown probabilities, collect the sum of all known ones, and evenly
11877d523365SDimitry Andric     // ditribute the complemental of the sum to each unknown probability.
11887d523365SDimitry Andric     unsigned KnownProbNum = 0;
11897d523365SDimitry Andric     auto Sum = BranchProbability::getZero();
11907d523365SDimitry Andric     for (auto &P : Probs) {
11917d523365SDimitry Andric       if (!P.isUnknown()) {
11927d523365SDimitry Andric         Sum += P;
11937d523365SDimitry Andric         KnownProbNum++;
11947d523365SDimitry Andric       }
11957d523365SDimitry Andric     }
11967d523365SDimitry Andric     return Sum.getCompl() / (Probs.size() - KnownProbNum);
11977d523365SDimitry Andric   } else
11987d523365SDimitry Andric     return Prob;
119917a519f9SDimitry Andric }
120017a519f9SDimitry Andric 
12017d523365SDimitry Andric /// Set successor probability of a given iterator.
12027d523365SDimitry Andric void MachineBasicBlock::setSuccProbability(succ_iterator I,
12037d523365SDimitry Andric                                            BranchProbability Prob) {
12047d523365SDimitry Andric   assert(!Prob.isUnknown());
12057d523365SDimitry Andric   if (Probs.empty())
120691bc56edSDimitry Andric     return;
12077d523365SDimitry Andric   *getProbabilityIterator(I) = Prob;
120891bc56edSDimitry Andric }
120991bc56edSDimitry Andric 
12107d523365SDimitry Andric /// Return probability iterator corresonding to the I successor iterator
12117d523365SDimitry Andric MachineBasicBlock::const_probability_iterator
12127d523365SDimitry Andric MachineBasicBlock::getProbabilityIterator(
12137d523365SDimitry Andric     MachineBasicBlock::const_succ_iterator I) const {
12147d523365SDimitry Andric   assert(Probs.size() == Successors.size() && "Async probability list!");
1215dff0c46cSDimitry Andric   const size_t index = std::distance(Successors.begin(), I);
12167d523365SDimitry Andric   assert(index < Probs.size() && "Not a current successor!");
12177d523365SDimitry Andric   return Probs.begin() + index;
12187d523365SDimitry Andric }
12197d523365SDimitry Andric 
12207d523365SDimitry Andric /// Return probability iterator corresonding to the I successor iterator.
12217d523365SDimitry Andric MachineBasicBlock::probability_iterator
12227d523365SDimitry Andric MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
12237d523365SDimitry Andric   assert(Probs.size() == Successors.size() && "Async probability list!");
12247d523365SDimitry Andric   const size_t index = std::distance(Successors.begin(), I);
12257d523365SDimitry Andric   assert(index < Probs.size() && "Not a current successor!");
12267d523365SDimitry Andric   return Probs.begin() + index;
1227dff0c46cSDimitry Andric }
1228dff0c46cSDimitry Andric 
12293861d79fSDimitry Andric /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
12303861d79fSDimitry Andric /// as of just before "MI".
12313861d79fSDimitry Andric ///
12323861d79fSDimitry Andric /// Search is localised to a neighborhood of
12333861d79fSDimitry Andric /// Neighborhood instructions before (searching for defs or kills) and N
12343861d79fSDimitry Andric /// instructions after (searching just for defs) MI.
12353861d79fSDimitry Andric MachineBasicBlock::LivenessQueryResult
12363861d79fSDimitry Andric MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1237ff0cc061SDimitry Andric                                            unsigned Reg, const_iterator Before,
1238ff0cc061SDimitry Andric                                            unsigned Neighborhood) const {
12393861d79fSDimitry Andric   unsigned N = Neighborhood;
12403861d79fSDimitry Andric 
1241ff0cc061SDimitry Andric   // Start by searching backwards from Before, looking for kills, reads or defs.
1242ff0cc061SDimitry Andric   const_iterator I(Before);
12433861d79fSDimitry Andric   // If this is the first insn in the block, don't search backwards.
1244ff0cc061SDimitry Andric   if (I != begin()) {
12453861d79fSDimitry Andric     do {
12463861d79fSDimitry Andric       --I;
12473861d79fSDimitry Andric 
12487d523365SDimitry Andric       MachineOperandIteratorBase::PhysRegInfo Info =
12493ca95b02SDimitry Andric           ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
12503861d79fSDimitry Andric 
12517d523365SDimitry Andric       // Defs happen after uses so they take precedence if both are present.
1252139f7f9bSDimitry Andric 
12537d523365SDimitry Andric       // Register is dead after a dead def of the full register.
12547d523365SDimitry Andric       if (Info.DeadDef)
12553861d79fSDimitry Andric         return LQR_Dead;
12567d523365SDimitry Andric       // Register is (at least partially) live after a def.
12573ca95b02SDimitry Andric       if (Info.Defined) {
12583ca95b02SDimitry Andric         if (!Info.PartialDeadDef)
12597d523365SDimitry Andric           return LQR_Live;
12603ca95b02SDimitry Andric         // As soon as we saw a partial definition (dead or not),
12613ca95b02SDimitry Andric         // we cannot tell if the value is partial live without
12623ca95b02SDimitry Andric         // tracking the lanemasks. We are not going to do this,
12633ca95b02SDimitry Andric         // so fall back on the remaining of the analysis.
12643ca95b02SDimitry Andric         break;
12653ca95b02SDimitry Andric       }
12667d523365SDimitry Andric       // Register is dead after a full kill or clobber and no def.
12677d523365SDimitry Andric       if (Info.Killed || Info.Clobbered)
12687d523365SDimitry Andric         return LQR_Dead;
12697d523365SDimitry Andric       // Register must be live if we read it.
12707d523365SDimitry Andric       if (Info.Read)
12717d523365SDimitry Andric         return LQR_Live;
1272ff0cc061SDimitry Andric     } while (I != begin() && --N > 0);
12733861d79fSDimitry Andric   }
12743861d79fSDimitry Andric 
12753861d79fSDimitry Andric   // Did we get to the start of the block?
1276ff0cc061SDimitry Andric   if (I == begin()) {
12773861d79fSDimitry Andric     // If so, the register's state is definitely defined by the live-in state.
12787d523365SDimitry Andric     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true); RAI.isValid();
12797d523365SDimitry Andric          ++RAI)
1280ff0cc061SDimitry Andric       if (isLiveIn(*RAI))
12817d523365SDimitry Andric         return LQR_Live;
12823861d79fSDimitry Andric 
12833861d79fSDimitry Andric     return LQR_Dead;
12843861d79fSDimitry Andric   }
12853861d79fSDimitry Andric 
12863861d79fSDimitry Andric   N = Neighborhood;
12873861d79fSDimitry Andric 
1288ff0cc061SDimitry Andric   // Try searching forwards from Before, looking for reads or defs.
1289ff0cc061SDimitry Andric   I = const_iterator(Before);
12903861d79fSDimitry Andric   // If this is the last insn in the block, don't search forwards.
1291ff0cc061SDimitry Andric   if (I != end()) {
1292ff0cc061SDimitry Andric     for (++I; I != end() && N > 0; ++I, --N) {
12937d523365SDimitry Andric       MachineOperandIteratorBase::PhysRegInfo Info =
12943ca95b02SDimitry Andric           ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
12953861d79fSDimitry Andric 
12967d523365SDimitry Andric       // Register is live when we read it here.
12977d523365SDimitry Andric       if (Info.Read)
12987d523365SDimitry Andric         return LQR_Live;
12997d523365SDimitry Andric       // Register is dead if we can fully overwrite or clobber it here.
13007d523365SDimitry Andric       if (Info.FullyDefined || Info.Clobbered)
13013861d79fSDimitry Andric         return LQR_Dead;
13023861d79fSDimitry Andric     }
13033861d79fSDimitry Andric   }
13043861d79fSDimitry Andric 
13053861d79fSDimitry Andric   // At this point we have no idea of the liveness of the register.
13063861d79fSDimitry Andric   return LQR_Unknown;
13073861d79fSDimitry Andric }
13087d523365SDimitry Andric 
13097d523365SDimitry Andric const uint32_t *
13107d523365SDimitry Andric MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
13117d523365SDimitry Andric   // EH funclet entry does not preserve any registers.
13127d523365SDimitry Andric   return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
13137d523365SDimitry Andric }
13147d523365SDimitry Andric 
13157d523365SDimitry Andric const uint32_t *
13167d523365SDimitry Andric MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
13177d523365SDimitry Andric   // If we see a return block with successors, this must be a funclet return,
13187d523365SDimitry Andric   // which does not preserve any registers. If there are no successors, we don't
13197d523365SDimitry Andric   // care what kind of return it is, putting a mask after it is a no-op.
13207d523365SDimitry Andric   return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
13217d523365SDimitry Andric }
1322d88c1a5aSDimitry Andric 
1323d88c1a5aSDimitry Andric void MachineBasicBlock::clearLiveIns() {
1324d88c1a5aSDimitry Andric   LiveIns.clear();
1325d88c1a5aSDimitry Andric }
132695ec533aSDimitry Andric 
132795ec533aSDimitry Andric MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
132895ec533aSDimitry Andric   assert(getParent()->getProperties().hasProperty(
132995ec533aSDimitry Andric       MachineFunctionProperties::Property::TracksLiveness) &&
133095ec533aSDimitry Andric       "Liveness information is accurate");
133195ec533aSDimitry Andric   return LiveIns.begin();
133295ec533aSDimitry Andric }
1333