xref: /llvm-project/llvm/lib/CodeGen/MachineBasicBlock.cpp (revision 58d1eaa3b6ce4f7285c51f83faff7a3ac374c746)
1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Collect the sequence of machine instructions for a basic block.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/MachineBasicBlock.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/CodeGen/LiveIntervals.h"
17 #include "llvm/CodeGen/LivePhysRegs.h"
18 #include "llvm/CodeGen/LiveVariables.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SlotIndexes.h"
26 #include "llvm/CodeGen/TargetInstrInfo.h"
27 #include "llvm/CodeGen/TargetLowering.h"
28 #include "llvm/CodeGen/TargetRegisterInfo.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/Config/llvm-config.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/DebugInfoMetadata.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include <algorithm>
40 #include <cmath>
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "codegen"
44 
45 static cl::opt<bool> PrintSlotIndexes(
46     "print-slotindexes",
47     cl::desc("When printing machine IR, annotate instructions and blocks with "
48              "SlotIndexes when available"),
49     cl::init(true), cl::Hidden);
50 
51 MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
52     : BB(B), Number(-1), xParent(&MF) {
53   Insts.Parent = this;
54   if (B)
55     IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight();
56 }
57 
58 MachineBasicBlock::~MachineBasicBlock() = default;
59 
60 /// Return the MCSymbol for this basic block.
61 MCSymbol *MachineBasicBlock::getSymbol() const {
62   if (!CachedMCSymbol) {
63     const MachineFunction *MF = getParent();
64     MCContext &Ctx = MF->getContext();
65 
66     // We emit a non-temporary symbol -- with a descriptive name -- if it begins
67     // a section (with basic block sections). Otherwise we fall back to use temp
68     // label.
69     if (MF->hasBBSections() && isBeginSection()) {
70       SmallString<5> Suffix;
71       if (SectionID == MBBSectionID::ColdSectionID) {
72         Suffix += ".cold";
73       } else if (SectionID == MBBSectionID::ExceptionSectionID) {
74         Suffix += ".eh";
75       } else {
76         // For symbols that represent basic block sections, we add ".__part." to
77         // allow tools like symbolizers to know that this represents a part of
78         // the original function.
79         Suffix = (Suffix + Twine(".__part.") + Twine(SectionID.Number)).str();
80       }
81       CachedMCSymbol = Ctx.getOrCreateSymbol(MF->getName() + Suffix);
82     } else {
83       const StringRef Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
84       CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
85                                              Twine(MF->getFunctionNumber()) +
86                                              "_" + Twine(getNumber()));
87     }
88   }
89   return CachedMCSymbol;
90 }
91 
92 MCSymbol *MachineBasicBlock::getEHCatchretSymbol() const {
93   if (!CachedEHCatchretMCSymbol) {
94     const MachineFunction *MF = getParent();
95     SmallString<128> SymbolName;
96     raw_svector_ostream(SymbolName)
97         << "$ehgcr_" << MF->getFunctionNumber() << '_' << getNumber();
98     CachedEHCatchretMCSymbol = MF->getContext().getOrCreateSymbol(SymbolName);
99   }
100   return CachedEHCatchretMCSymbol;
101 }
102 
103 MCSymbol *MachineBasicBlock::getEndSymbol() const {
104   if (!CachedEndMCSymbol) {
105     const MachineFunction *MF = getParent();
106     MCContext &Ctx = MF->getContext();
107     auto Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
108     CachedEndMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB_END" +
109                                               Twine(MF->getFunctionNumber()) +
110                                               "_" + Twine(getNumber()));
111   }
112   return CachedEndMCSymbol;
113 }
114 
115 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
116   MBB.print(OS);
117   return OS;
118 }
119 
120 Printable llvm::printMBBReference(const MachineBasicBlock &MBB) {
121   return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
122 }
123 
124 /// When an MBB is added to an MF, we need to update the parent pointer of the
125 /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
126 /// operand list for registers.
127 ///
128 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
129 /// gets the next available unique MBB number. If it is removed from a
130 /// MachineFunction, it goes back to being #-1.
131 void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
132     MachineBasicBlock *N) {
133   MachineFunction &MF = *N->getParent();
134   N->Number = MF.addToMBBNumbering(N);
135 
136   // Make sure the instructions have their operands in the reginfo lists.
137   MachineRegisterInfo &RegInfo = MF.getRegInfo();
138   for (MachineInstr &MI : N->instrs())
139     MI.addRegOperandsToUseLists(RegInfo);
140 }
141 
142 void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
143     MachineBasicBlock *N) {
144   N->getParent()->removeFromMBBNumbering(N->Number);
145   N->Number = -1;
146 }
147 
148 /// When we add an instruction to a basic block list, we update its parent
149 /// pointer and add its operands from reg use/def lists if appropriate.
150 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
151   assert(!N->getParent() && "machine instruction already in a basic block");
152   N->setParent(Parent);
153 
154   // Add the instruction's register operands to their corresponding
155   // use/def lists.
156   MachineFunction *MF = Parent->getParent();
157   N->addRegOperandsToUseLists(MF->getRegInfo());
158   MF->handleInsertion(*N);
159 }
160 
161 /// When we remove an instruction from a basic block list, we update its parent
162 /// pointer and remove its operands from reg use/def lists if appropriate.
163 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
164   assert(N->getParent() && "machine instruction not in a basic block");
165 
166   // Remove from the use/def lists.
167   if (MachineFunction *MF = N->getMF()) {
168     MF->handleRemoval(*N);
169     N->removeRegOperandsFromUseLists(MF->getRegInfo());
170   }
171 
172   N->setParent(nullptr);
173 }
174 
175 /// When moving a range of instructions from one MBB list to another, we need to
176 /// update the parent pointers and the use/def lists.
177 void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
178                                                        instr_iterator First,
179                                                        instr_iterator Last) {
180   assert(Parent->getParent() == FromList.Parent->getParent() &&
181          "cannot transfer MachineInstrs between MachineFunctions");
182 
183   // If it's within the same BB, there's nothing to do.
184   if (this == &FromList)
185     return;
186 
187   assert(Parent != FromList.Parent && "Two lists have the same parent?");
188 
189   // If splicing between two blocks within the same function, just update the
190   // parent pointers.
191   for (; First != Last; ++First)
192     First->setParent(Parent);
193 }
194 
195 void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
196   assert(!MI->getParent() && "MI is still in a block!");
197   Parent->getParent()->deleteMachineInstr(MI);
198 }
199 
200 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
201   instr_iterator I = instr_begin(), E = instr_end();
202   while (I != E && I->isPHI())
203     ++I;
204   assert((I == E || !I->isInsideBundle()) &&
205          "First non-phi MI cannot be inside a bundle!");
206   return I;
207 }
208 
209 MachineBasicBlock::iterator
210 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
211   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
212 
213   iterator E = end();
214   while (I != E && (I->isPHI() || I->isPosition() ||
215                     TII->isBasicBlockPrologue(*I)))
216     ++I;
217   // FIXME: This needs to change if we wish to bundle labels
218   // inside the bundle.
219   assert((I == E || !I->isInsideBundle()) &&
220          "First non-phi / non-label instruction is inside a bundle!");
221   return I;
222 }
223 
224 MachineBasicBlock::iterator
225 MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I,
226                                           bool SkipPseudoOp) {
227   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
228 
229   iterator E = end();
230   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() ||
231                     (SkipPseudoOp && I->isPseudoProbe()) ||
232                     TII->isBasicBlockPrologue(*I)))
233     ++I;
234   // FIXME: This needs to change if we wish to bundle labels / dbg_values
235   // inside the bundle.
236   assert((I == E || !I->isInsideBundle()) &&
237          "First non-phi / non-label / non-debug "
238          "instruction is inside a bundle!");
239   return I;
240 }
241 
242 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
243   iterator B = begin(), E = end(), I = E;
244   while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
245     ; /*noop */
246   while (I != E && !I->isTerminator())
247     ++I;
248   return I;
249 }
250 
251 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
252   instr_iterator B = instr_begin(), E = instr_end(), I = E;
253   while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
254     ; /*noop */
255   while (I != E && !I->isTerminator())
256     ++I;
257   return I;
258 }
259 
260 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminatorForward() {
261   return find_if(instrs(), [](auto &II) { return II.isTerminator(); });
262 }
263 
264 MachineBasicBlock::iterator
265 MachineBasicBlock::getFirstNonDebugInstr(bool SkipPseudoOp) {
266   // Skip over begin-of-block dbg_value instructions.
267   return skipDebugInstructionsForward(begin(), end(), SkipPseudoOp);
268 }
269 
270 MachineBasicBlock::iterator
271 MachineBasicBlock::getLastNonDebugInstr(bool SkipPseudoOp) {
272   // Skip over end-of-block dbg_value instructions.
273   instr_iterator B = instr_begin(), I = instr_end();
274   while (I != B) {
275     --I;
276     // Return instruction that starts a bundle.
277     if (I->isDebugInstr() || I->isInsideBundle())
278       continue;
279     if (SkipPseudoOp && I->isPseudoProbe())
280       continue;
281     return I;
282   }
283   // The block is all debug values.
284   return end();
285 }
286 
287 bool MachineBasicBlock::hasEHPadSuccessor() const {
288   for (const MachineBasicBlock *Succ : successors())
289     if (Succ->isEHPad())
290       return true;
291   return false;
292 }
293 
294 bool MachineBasicBlock::isEntryBlock() const {
295   return getParent()->begin() == getIterator();
296 }
297 
298 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
299 LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
300   print(dbgs());
301 }
302 #endif
303 
304 bool MachineBasicBlock::mayHaveInlineAsmBr() const {
305   for (const MachineBasicBlock *Succ : successors()) {
306     if (Succ->isInlineAsmBrIndirectTarget())
307       return true;
308   }
309   return false;
310 }
311 
312 bool MachineBasicBlock::isLegalToHoistInto() const {
313   if (isReturnBlock() || hasEHPadSuccessor() || mayHaveInlineAsmBr())
314     return false;
315   return true;
316 }
317 
318 StringRef MachineBasicBlock::getName() const {
319   if (const BasicBlock *LBB = getBasicBlock())
320     return LBB->getName();
321   else
322     return StringRef("", 0);
323 }
324 
325 /// Return a hopefully unique identifier for this block.
326 std::string MachineBasicBlock::getFullName() const {
327   std::string Name;
328   if (getParent())
329     Name = (getParent()->getName() + ":").str();
330   if (getBasicBlock())
331     Name += getBasicBlock()->getName();
332   else
333     Name += ("BB" + Twine(getNumber())).str();
334   return Name;
335 }
336 
337 void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes,
338                               bool IsStandalone) const {
339   const MachineFunction *MF = getParent();
340   if (!MF) {
341     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
342        << " is null\n";
343     return;
344   }
345   const Function &F = MF->getFunction();
346   const Module *M = F.getParent();
347   ModuleSlotTracker MST(M);
348   MST.incorporateFunction(F);
349   print(OS, MST, Indexes, IsStandalone);
350 }
351 
352 void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
353                               const SlotIndexes *Indexes,
354                               bool IsStandalone) const {
355   const MachineFunction *MF = getParent();
356   if (!MF) {
357     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
358        << " is null\n";
359     return;
360   }
361 
362   if (Indexes && PrintSlotIndexes)
363     OS << Indexes->getMBBStartIdx(this) << '\t';
364 
365   printName(OS, PrintNameIr | PrintNameAttributes, &MST);
366   OS << ":\n";
367 
368   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
369   const MachineRegisterInfo &MRI = MF->getRegInfo();
370   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
371   bool HasLineAttributes = false;
372 
373   // Print the preds of this block according to the CFG.
374   if (!pred_empty() && IsStandalone) {
375     if (Indexes) OS << '\t';
376     // Don't indent(2), align with previous line attributes.
377     OS << "; predecessors: ";
378     ListSeparator LS;
379     for (auto *Pred : predecessors())
380       OS << LS << printMBBReference(*Pred);
381     OS << '\n';
382     HasLineAttributes = true;
383   }
384 
385   if (!succ_empty()) {
386     if (Indexes) OS << '\t';
387     // Print the successors
388     OS.indent(2) << "successors: ";
389     ListSeparator LS;
390     for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
391       OS << LS << printMBBReference(**I);
392       if (!Probs.empty())
393         OS << '('
394            << format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
395            << ')';
396     }
397     if (!Probs.empty() && IsStandalone) {
398       // Print human readable probabilities as comments.
399       OS << "; ";
400       ListSeparator LS;
401       for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
402         const BranchProbability &BP = getSuccProbability(I);
403         OS << LS << printMBBReference(**I) << '('
404            << format("%.2f%%",
405                      rint(((double)BP.getNumerator() / BP.getDenominator()) *
406                           100.0 * 100.0) /
407                          100.0)
408            << ')';
409       }
410     }
411 
412     OS << '\n';
413     HasLineAttributes = true;
414   }
415 
416   if (!livein_empty() && MRI.tracksLiveness()) {
417     if (Indexes) OS << '\t';
418     OS.indent(2) << "liveins: ";
419 
420     ListSeparator LS;
421     for (const auto &LI : liveins()) {
422       OS << LS << printReg(LI.PhysReg, TRI);
423       if (!LI.LaneMask.all())
424         OS << ":0x" << PrintLaneMask(LI.LaneMask);
425     }
426     HasLineAttributes = true;
427   }
428 
429   if (HasLineAttributes)
430     OS << '\n';
431 
432   bool IsInBundle = false;
433   for (const MachineInstr &MI : instrs()) {
434     if (Indexes && PrintSlotIndexes) {
435       if (Indexes->hasIndex(MI))
436         OS << Indexes->getInstructionIndex(MI);
437       OS << '\t';
438     }
439 
440     if (IsInBundle && !MI.isInsideBundle()) {
441       OS.indent(2) << "}\n";
442       IsInBundle = false;
443     }
444 
445     OS.indent(IsInBundle ? 4 : 2);
446     MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
447              /*AddNewLine=*/false, &TII);
448 
449     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
450       OS << " {";
451       IsInBundle = true;
452     }
453     OS << '\n';
454   }
455 
456   if (IsInBundle)
457     OS.indent(2) << "}\n";
458 
459   if (IrrLoopHeaderWeight && IsStandalone) {
460     if (Indexes) OS << '\t';
461     OS.indent(2) << "; Irreducible loop header weight: " << *IrrLoopHeaderWeight
462                  << '\n';
463   }
464 }
465 
466 /// Print the basic block's name as:
467 ///
468 ///    bb.{number}[.{ir-name}] [(attributes...)]
469 ///
470 /// The {ir-name} is only printed when the \ref PrintNameIr flag is passed
471 /// (which is the default). If the IR block has no name, it is identified
472 /// numerically using the attribute syntax as "(%ir-block.{ir-slot})".
473 ///
474 /// When the \ref PrintNameAttributes flag is passed, additional attributes
475 /// of the block are printed when set.
476 ///
477 /// \param printNameFlags Combination of \ref PrintNameFlag flags indicating
478 ///                       the parts to print.
479 /// \param moduleSlotTracker Optional ModuleSlotTracker. This method will
480 ///                          incorporate its own tracker when necessary to
481 ///                          determine the block's IR name.
482 void MachineBasicBlock::printName(raw_ostream &os, unsigned printNameFlags,
483                                   ModuleSlotTracker *moduleSlotTracker) const {
484   os << "bb." << getNumber();
485   bool hasAttributes = false;
486 
487   auto PrintBBRef = [&](const BasicBlock *bb) {
488     os << "%ir-block.";
489     if (bb->hasName()) {
490       os << bb->getName();
491     } else {
492       int slot = -1;
493 
494       if (moduleSlotTracker) {
495         slot = moduleSlotTracker->getLocalSlot(bb);
496       } else if (bb->getParent()) {
497         ModuleSlotTracker tmpTracker(bb->getModule(), false);
498         tmpTracker.incorporateFunction(*bb->getParent());
499         slot = tmpTracker.getLocalSlot(bb);
500       }
501 
502       if (slot == -1)
503         os << "<ir-block badref>";
504       else
505         os << slot;
506     }
507   };
508 
509   if (printNameFlags & PrintNameIr) {
510     if (const auto *bb = getBasicBlock()) {
511       if (bb->hasName()) {
512         os << '.' << bb->getName();
513       } else {
514         hasAttributes = true;
515         os << " (";
516         PrintBBRef(bb);
517       }
518     }
519   }
520 
521   if (printNameFlags & PrintNameAttributes) {
522     if (isMachineBlockAddressTaken()) {
523       os << (hasAttributes ? ", " : " (");
524       os << "machine-block-address-taken";
525       hasAttributes = true;
526     }
527     if (isIRBlockAddressTaken()) {
528       os << (hasAttributes ? ", " : " (");
529       os << "ir-block-address-taken ";
530       PrintBBRef(getAddressTakenIRBlock());
531       hasAttributes = true;
532     }
533     if (isEHPad()) {
534       os << (hasAttributes ? ", " : " (");
535       os << "landing-pad";
536       hasAttributes = true;
537     }
538     if (isInlineAsmBrIndirectTarget()) {
539       os << (hasAttributes ? ", " : " (");
540       os << "inlineasm-br-indirect-target";
541       hasAttributes = true;
542     }
543     if (isEHFuncletEntry()) {
544       os << (hasAttributes ? ", " : " (");
545       os << "ehfunclet-entry";
546       hasAttributes = true;
547     }
548     if (getAlignment() != Align(1)) {
549       os << (hasAttributes ? ", " : " (");
550       os << "align " << getAlignment().value();
551       hasAttributes = true;
552     }
553     if (getSectionID() != MBBSectionID(0)) {
554       os << (hasAttributes ? ", " : " (");
555       os << "bbsections ";
556       switch (getSectionID().Type) {
557       case MBBSectionID::SectionType::Exception:
558         os << "Exception";
559         break;
560       case MBBSectionID::SectionType::Cold:
561         os << "Cold";
562         break;
563       default:
564         os << getSectionID().Number;
565       }
566       hasAttributes = true;
567     }
568     if (getBBID().has_value()) {
569       os << (hasAttributes ? ", " : " (");
570       os << "bb_id " << *getBBID();
571       hasAttributes = true;
572     }
573     if (SPAdjustment != 0) {
574       os << (hasAttributes ? ", " : " (");
575       os << "sp-adjustment " << SPAdjustment;
576       hasAttributes = true;
577     }
578   }
579 
580   if (hasAttributes)
581     os << ')';
582 }
583 
584 void MachineBasicBlock::printAsOperand(raw_ostream &OS,
585                                        bool /*PrintType*/) const {
586   OS << '%';
587   printName(OS, 0);
588 }
589 
590 void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
591   LiveInVector::iterator I = find_if(
592       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
593   if (I == LiveIns.end())
594     return;
595 
596   I->LaneMask &= ~LaneMask;
597   if (I->LaneMask.none())
598     LiveIns.erase(I);
599 }
600 
601 MachineBasicBlock::livein_iterator
602 MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
603   // Get non-const version of iterator.
604   LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
605   return LiveIns.erase(LI);
606 }
607 
608 bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
609   livein_iterator I = find_if(
610       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
611   return I != livein_end() && (I->LaneMask & LaneMask).any();
612 }
613 
614 void MachineBasicBlock::sortUniqueLiveIns() {
615   llvm::sort(LiveIns,
616              [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
617                return LI0.PhysReg < LI1.PhysReg;
618              });
619   // Liveins are sorted by physreg now we can merge their lanemasks.
620   LiveInVector::const_iterator I = LiveIns.begin();
621   LiveInVector::const_iterator J;
622   LiveInVector::iterator Out = LiveIns.begin();
623   for (; I != LiveIns.end(); ++Out, I = J) {
624     MCRegister PhysReg = I->PhysReg;
625     LaneBitmask LaneMask = I->LaneMask;
626     for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
627       LaneMask |= J->LaneMask;
628     Out->PhysReg = PhysReg;
629     Out->LaneMask = LaneMask;
630   }
631   LiveIns.erase(Out, LiveIns.end());
632 }
633 
634 Register
635 MachineBasicBlock::addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC) {
636   assert(getParent() && "MBB must be inserted in function");
637   assert(Register::isPhysicalRegister(PhysReg) && "Expected physreg");
638   assert(RC && "Register class is required");
639   assert((isEHPad() || this == &getParent()->front()) &&
640          "Only the entry block and landing pads can have physreg live ins");
641 
642   bool LiveIn = isLiveIn(PhysReg);
643   iterator I = SkipPHIsAndLabels(begin()), E = end();
644   MachineRegisterInfo &MRI = getParent()->getRegInfo();
645   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
646 
647   // Look for an existing copy.
648   if (LiveIn)
649     for (;I != E && I->isCopy(); ++I)
650       if (I->getOperand(1).getReg() == PhysReg) {
651         Register VirtReg = I->getOperand(0).getReg();
652         if (!MRI.constrainRegClass(VirtReg, RC))
653           llvm_unreachable("Incompatible live-in register class.");
654         return VirtReg;
655       }
656 
657   // No luck, create a virtual register.
658   Register VirtReg = MRI.createVirtualRegister(RC);
659   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
660     .addReg(PhysReg, RegState::Kill);
661   if (!LiveIn)
662     addLiveIn(PhysReg);
663   return VirtReg;
664 }
665 
666 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
667   getParent()->splice(NewAfter->getIterator(), getIterator());
668 }
669 
670 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
671   getParent()->splice(++NewBefore->getIterator(), getIterator());
672 }
673 
674 static int findJumpTableIndex(const MachineBasicBlock &MBB) {
675   MachineBasicBlock::const_iterator TerminatorI = MBB.getFirstTerminator();
676   if (TerminatorI == MBB.end())
677     return -1;
678   const MachineInstr &Terminator = *TerminatorI;
679   const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
680   return TII->getJumpTableIndex(Terminator);
681 }
682 
683 void MachineBasicBlock::updateTerminator(
684     MachineBasicBlock *PreviousLayoutSuccessor) {
685   LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
686                     << "\n");
687 
688   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
689   // A block with no successors has no concerns with fall-through edges.
690   if (this->succ_empty())
691     return;
692 
693   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
694   SmallVector<MachineOperand, 4> Cond;
695   DebugLoc DL = findBranchDebugLoc();
696   bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
697   (void) B;
698   assert(!B && "UpdateTerminators requires analyzable predecessors!");
699   if (Cond.empty()) {
700     if (TBB) {
701       // The block has an unconditional branch. If its successor is now its
702       // layout successor, delete the branch.
703       if (isLayoutSuccessor(TBB))
704         TII->removeBranch(*this);
705     } else {
706       // The block has an unconditional fallthrough, or the end of the block is
707       // unreachable.
708 
709       // Unfortunately, whether the end of the block is unreachable is not
710       // immediately obvious; we must fall back to checking the successor list,
711       // and assuming that if the passed in block is in the succesor list and
712       // not an EHPad, it must be the intended target.
713       if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) ||
714           PreviousLayoutSuccessor->isEHPad())
715         return;
716 
717       // If the unconditional successor block is not the current layout
718       // successor, insert a branch to jump to it.
719       if (!isLayoutSuccessor(PreviousLayoutSuccessor))
720         TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
721     }
722     return;
723   }
724 
725   if (FBB) {
726     // The block has a non-fallthrough conditional branch. If one of its
727     // successors is its layout successor, rewrite it to a fallthrough
728     // conditional branch.
729     if (isLayoutSuccessor(TBB)) {
730       if (TII->reverseBranchCondition(Cond))
731         return;
732       TII->removeBranch(*this);
733       TII->insertBranch(*this, FBB, nullptr, Cond, DL);
734     } else if (isLayoutSuccessor(FBB)) {
735       TII->removeBranch(*this);
736       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
737     }
738     return;
739   }
740 
741   // We now know we're going to fallthrough to PreviousLayoutSuccessor.
742   assert(PreviousLayoutSuccessor);
743   assert(!PreviousLayoutSuccessor->isEHPad());
744   assert(isSuccessor(PreviousLayoutSuccessor));
745 
746   if (PreviousLayoutSuccessor == TBB) {
747     // We had a fallthrough to the same basic block as the conditional jump
748     // targets.  Remove the conditional jump, leaving an unconditional
749     // fallthrough or an unconditional jump.
750     TII->removeBranch(*this);
751     if (!isLayoutSuccessor(TBB)) {
752       Cond.clear();
753       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
754     }
755     return;
756   }
757 
758   // The block has a fallthrough conditional branch.
759   if (isLayoutSuccessor(TBB)) {
760     if (TII->reverseBranchCondition(Cond)) {
761       // We can't reverse the condition, add an unconditional branch.
762       Cond.clear();
763       TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
764       return;
765     }
766     TII->removeBranch(*this);
767     TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL);
768   } else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) {
769     TII->removeBranch(*this);
770     TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL);
771   }
772 }
773 
774 void MachineBasicBlock::validateSuccProbs() const {
775 #ifndef NDEBUG
776   int64_t Sum = 0;
777   for (auto Prob : Probs)
778     Sum += Prob.getNumerator();
779   // Due to precision issue, we assume that the sum of probabilities is one if
780   // the difference between the sum of their numerators and the denominator is
781   // no greater than the number of successors.
782   assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
783              Probs.size() &&
784          "The sum of successors's probabilities exceeds one.");
785 #endif // NDEBUG
786 }
787 
788 void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
789                                      BranchProbability Prob) {
790   // Probability list is either empty (if successor list isn't empty, this means
791   // disabled optimization) or has the same size as successor list.
792   if (!(Probs.empty() && !Successors.empty()))
793     Probs.push_back(Prob);
794   Successors.push_back(Succ);
795   Succ->addPredecessor(this);
796 }
797 
798 void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
799   // We need to make sure probability list is either empty or has the same size
800   // of successor list. When this function is called, we can safely delete all
801   // probability in the list.
802   Probs.clear();
803   Successors.push_back(Succ);
804   Succ->addPredecessor(this);
805 }
806 
807 void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
808                                        MachineBasicBlock *New,
809                                        bool NormalizeSuccProbs) {
810   succ_iterator OldI = llvm::find(successors(), Old);
811   assert(OldI != succ_end() && "Old is not a successor of this block!");
812   assert(!llvm::is_contained(successors(), New) &&
813          "New is already a successor of this block!");
814 
815   // Add a new successor with equal probability as the original one. Note
816   // that we directly copy the probability using the iterator rather than
817   // getting a potentially synthetic probability computed when unknown. This
818   // preserves the probabilities as-is and then we can renormalize them and
819   // query them effectively afterward.
820   addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
821                                   : *getProbabilityIterator(OldI));
822   if (NormalizeSuccProbs)
823     normalizeSuccProbs();
824 }
825 
826 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
827                                         bool NormalizeSuccProbs) {
828   succ_iterator I = find(Successors, Succ);
829   removeSuccessor(I, NormalizeSuccProbs);
830 }
831 
832 MachineBasicBlock::succ_iterator
833 MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
834   assert(I != Successors.end() && "Not a current successor!");
835 
836   // If probability list is empty it means we don't use it (disabled
837   // optimization).
838   if (!Probs.empty()) {
839     probability_iterator WI = getProbabilityIterator(I);
840     Probs.erase(WI);
841     if (NormalizeSuccProbs)
842       normalizeSuccProbs();
843   }
844 
845   (*I)->removePredecessor(this);
846   return Successors.erase(I);
847 }
848 
849 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
850                                          MachineBasicBlock *New) {
851   if (Old == New)
852     return;
853 
854   succ_iterator E = succ_end();
855   succ_iterator NewI = E;
856   succ_iterator OldI = E;
857   for (succ_iterator I = succ_begin(); I != E; ++I) {
858     if (*I == Old) {
859       OldI = I;
860       if (NewI != E)
861         break;
862     }
863     if (*I == New) {
864       NewI = I;
865       if (OldI != E)
866         break;
867     }
868   }
869   assert(OldI != E && "Old is not a successor of this block");
870 
871   // If New isn't already a successor, let it take Old's place.
872   if (NewI == E) {
873     Old->removePredecessor(this);
874     New->addPredecessor(this);
875     *OldI = New;
876     return;
877   }
878 
879   // New is already a successor.
880   // Update its probability instead of adding a duplicate edge.
881   if (!Probs.empty()) {
882     auto ProbIter = getProbabilityIterator(NewI);
883     if (!ProbIter->isUnknown())
884       *ProbIter += *getProbabilityIterator(OldI);
885   }
886   removeSuccessor(OldI);
887 }
888 
889 void MachineBasicBlock::copySuccessor(MachineBasicBlock *Orig,
890                                       succ_iterator I) {
891   if (!Orig->Probs.empty())
892     addSuccessor(*I, Orig->getSuccProbability(I));
893   else
894     addSuccessorWithoutProb(*I);
895 }
896 
897 void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
898   Predecessors.push_back(Pred);
899 }
900 
901 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
902   pred_iterator I = find(Predecessors, Pred);
903   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
904   Predecessors.erase(I);
905 }
906 
907 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
908   if (this == FromMBB)
909     return;
910 
911   while (!FromMBB->succ_empty()) {
912     MachineBasicBlock *Succ = *FromMBB->succ_begin();
913 
914     // If probability list is empty it means we don't use it (disabled
915     // optimization).
916     if (!FromMBB->Probs.empty()) {
917       auto Prob = *FromMBB->Probs.begin();
918       addSuccessor(Succ, Prob);
919     } else
920       addSuccessorWithoutProb(Succ);
921 
922     FromMBB->removeSuccessor(Succ);
923   }
924 }
925 
926 void
927 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
928   if (this == FromMBB)
929     return;
930 
931   while (!FromMBB->succ_empty()) {
932     MachineBasicBlock *Succ = *FromMBB->succ_begin();
933     if (!FromMBB->Probs.empty()) {
934       auto Prob = *FromMBB->Probs.begin();
935       addSuccessor(Succ, Prob);
936     } else
937       addSuccessorWithoutProb(Succ);
938     FromMBB->removeSuccessor(Succ);
939 
940     // Fix up any PHI nodes in the successor.
941     Succ->replacePhiUsesWith(FromMBB, this);
942   }
943   normalizeSuccProbs();
944 }
945 
946 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
947   return is_contained(predecessors(), MBB);
948 }
949 
950 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
951   return is_contained(successors(), MBB);
952 }
953 
954 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
955   MachineFunction::const_iterator I(this);
956   return std::next(I) == MachineFunction::const_iterator(MBB);
957 }
958 
959 const MachineBasicBlock *MachineBasicBlock::getSingleSuccessor() const {
960   return Successors.size() == 1 ? Successors[0] : nullptr;
961 }
962 
963 MachineBasicBlock *MachineBasicBlock::getFallThrough(bool JumpToFallThrough) {
964   MachineFunction::iterator Fallthrough = getIterator();
965   ++Fallthrough;
966   // If FallthroughBlock is off the end of the function, it can't fall through.
967   if (Fallthrough == getParent()->end())
968     return nullptr;
969 
970   // If FallthroughBlock isn't a successor, no fallthrough is possible.
971   if (!isSuccessor(&*Fallthrough))
972     return nullptr;
973 
974   // Analyze the branches, if any, at the end of the block.
975   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
976   SmallVector<MachineOperand, 4> Cond;
977   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
978   if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
979     // If we couldn't analyze the branch, examine the last instruction.
980     // If the block doesn't end in a known control barrier, assume fallthrough
981     // is possible. The isPredicated check is needed because this code can be
982     // called during IfConversion, where an instruction which is normally a
983     // Barrier is predicated and thus no longer an actual control barrier.
984     return (empty() || !back().isBarrier() || TII->isPredicated(back()))
985                ? &*Fallthrough
986                : nullptr;
987   }
988 
989   // If there is no branch, control always falls through.
990   if (!TBB) return &*Fallthrough;
991 
992   // If there is some explicit branch to the fallthrough block, it can obviously
993   // reach, even though the branch should get folded to fall through implicitly.
994   if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough ||
995                             MachineFunction::iterator(FBB) == Fallthrough))
996     return &*Fallthrough;
997 
998   // If it's an unconditional branch to some block not the fall through, it
999   // doesn't fall through.
1000   if (Cond.empty()) return nullptr;
1001 
1002   // Otherwise, if it is conditional and has no explicit false block, it falls
1003   // through.
1004   return (FBB == nullptr) ? &*Fallthrough : nullptr;
1005 }
1006 
1007 bool MachineBasicBlock::canFallThrough() {
1008   return getFallThrough() != nullptr;
1009 }
1010 
1011 MachineBasicBlock *MachineBasicBlock::splitAt(MachineInstr &MI,
1012                                               bool UpdateLiveIns,
1013                                               LiveIntervals *LIS) {
1014   MachineBasicBlock::iterator SplitPoint(&MI);
1015   ++SplitPoint;
1016 
1017   if (SplitPoint == end()) {
1018     // Don't bother with a new block.
1019     return this;
1020   }
1021 
1022   MachineFunction *MF = getParent();
1023 
1024   LivePhysRegs LiveRegs;
1025   if (UpdateLiveIns) {
1026     // Make sure we add any physregs we define in the block as liveins to the
1027     // new block.
1028     MachineBasicBlock::iterator Prev(&MI);
1029     LiveRegs.init(*MF->getSubtarget().getRegisterInfo());
1030     LiveRegs.addLiveOuts(*this);
1031     for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
1032       LiveRegs.stepBackward(*I);
1033   }
1034 
1035   MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(getBasicBlock());
1036 
1037   MF->insert(++MachineFunction::iterator(this), SplitBB);
1038   SplitBB->splice(SplitBB->begin(), this, SplitPoint, end());
1039 
1040   SplitBB->transferSuccessorsAndUpdatePHIs(this);
1041   addSuccessor(SplitBB);
1042 
1043   if (UpdateLiveIns)
1044     addLiveIns(*SplitBB, LiveRegs);
1045 
1046   if (LIS)
1047     LIS->insertMBBInMaps(SplitBB);
1048 
1049   return SplitBB;
1050 }
1051 
1052 // Returns `true` if there are possibly other users of the jump table at
1053 // `JumpTableIndex` except for the ones in `IgnoreMBB`.
1054 static bool jumpTableHasOtherUses(const MachineFunction &MF,
1055                                   const MachineBasicBlock &IgnoreMBB,
1056                                   int JumpTableIndex) {
1057   assert(JumpTableIndex >= 0 && "need valid index");
1058   const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo();
1059   const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex];
1060   // Take any basic block from the table; every user of the jump table must
1061   // show up in the predecessor list.
1062   const MachineBasicBlock *MBB = nullptr;
1063   for (MachineBasicBlock *B : MJTE.MBBs) {
1064     if (B != nullptr) {
1065       MBB = B;
1066       break;
1067     }
1068   }
1069   if (MBB == nullptr)
1070     return true; // can't rule out other users if there isn't any block.
1071   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1072   SmallVector<MachineOperand, 4> Cond;
1073   for (MachineBasicBlock *Pred : MBB->predecessors()) {
1074     if (Pred == &IgnoreMBB)
1075       continue;
1076     MachineBasicBlock *DummyT = nullptr;
1077     MachineBasicBlock *DummyF = nullptr;
1078     Cond.clear();
1079     if (!TII.analyzeBranch(*Pred, DummyT, DummyF, Cond,
1080                            /*AllowModify=*/false)) {
1081       // analyzable direct jump
1082       continue;
1083     }
1084     int PredJTI = findJumpTableIndex(*Pred);
1085     if (PredJTI >= 0) {
1086       if (PredJTI == JumpTableIndex)
1087         return true;
1088       continue;
1089     }
1090     // Be conservative for unanalyzable jumps.
1091     return true;
1092   }
1093   return false;
1094 }
1095 
1096 MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
1097     MachineBasicBlock *Succ, Pass &P,
1098     std::vector<SparseBitVector<>> *LiveInSets) {
1099   if (!canSplitCriticalEdge(Succ))
1100     return nullptr;
1101 
1102   MachineFunction *MF = getParent();
1103   MachineBasicBlock *PrevFallthrough = getNextNode();
1104   DebugLoc DL;  // FIXME: this is nowhere
1105 
1106   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
1107 
1108   // Is there an indirect jump with jump table?
1109   bool ChangedIndirectJump = false;
1110   int JTI = findJumpTableIndex(*this);
1111   if (JTI >= 0) {
1112     MachineJumpTableInfo &MJTI = *MF->getJumpTableInfo();
1113     MJTI.ReplaceMBBInJumpTable(JTI, Succ, NMBB);
1114     ChangedIndirectJump = true;
1115   }
1116 
1117   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
1118   LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
1119                     << " -- " << printMBBReference(*NMBB) << " -- "
1120                     << printMBBReference(*Succ) << '\n');
1121 
1122   LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
1123   SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
1124   if (LIS)
1125     LIS->insertMBBInMaps(NMBB);
1126   else if (Indexes)
1127     Indexes->insertMBBInMaps(NMBB);
1128 
1129   // On some targets like Mips, branches may kill virtual registers. Make sure
1130   // that LiveVariables is properly updated after updateTerminator replaces the
1131   // terminators.
1132   LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
1133 
1134   // Collect a list of virtual registers killed by the terminators.
1135   SmallVector<Register, 4> KilledRegs;
1136   if (LV)
1137     for (MachineInstr &MI :
1138          llvm::make_range(getFirstInstrTerminator(), instr_end())) {
1139       for (MachineOperand &MO : MI.all_uses()) {
1140         if (MO.getReg() == 0 || !MO.isKill() || MO.isUndef())
1141           continue;
1142         Register Reg = MO.getReg();
1143         if (Reg.isPhysical() || LV->getVarInfo(Reg).removeKill(MI)) {
1144           KilledRegs.push_back(Reg);
1145           LLVM_DEBUG(dbgs() << "Removing terminator kill: " << MI);
1146           MO.setIsKill(false);
1147         }
1148       }
1149     }
1150 
1151   SmallVector<Register, 4> UsedRegs;
1152   if (LIS) {
1153     for (MachineInstr &MI :
1154          llvm::make_range(getFirstInstrTerminator(), instr_end())) {
1155       for (const MachineOperand &MO : MI.operands()) {
1156         if (!MO.isReg() || MO.getReg() == 0)
1157           continue;
1158 
1159         Register Reg = MO.getReg();
1160         if (!is_contained(UsedRegs, Reg))
1161           UsedRegs.push_back(Reg);
1162       }
1163     }
1164   }
1165 
1166   ReplaceUsesOfBlockWith(Succ, NMBB);
1167 
1168   // If updateTerminator() removes instructions, we need to remove them from
1169   // SlotIndexes.
1170   SmallVector<MachineInstr*, 4> Terminators;
1171   if (Indexes) {
1172     for (MachineInstr &MI :
1173          llvm::make_range(getFirstInstrTerminator(), instr_end()))
1174       Terminators.push_back(&MI);
1175   }
1176 
1177   // Since we replaced all uses of Succ with NMBB, that should also be treated
1178   // as the fallthrough successor
1179   if (Succ == PrevFallthrough)
1180     PrevFallthrough = NMBB;
1181 
1182   if (!ChangedIndirectJump)
1183     updateTerminator(PrevFallthrough);
1184 
1185   if (Indexes) {
1186     SmallVector<MachineInstr*, 4> NewTerminators;
1187     for (MachineInstr &MI :
1188          llvm::make_range(getFirstInstrTerminator(), instr_end()))
1189       NewTerminators.push_back(&MI);
1190 
1191     for (MachineInstr *Terminator : Terminators) {
1192       if (!is_contained(NewTerminators, Terminator))
1193         Indexes->removeMachineInstrFromMaps(*Terminator);
1194     }
1195   }
1196 
1197   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
1198   NMBB->addSuccessor(Succ);
1199   if (!NMBB->isLayoutSuccessor(Succ)) {
1200     SmallVector<MachineOperand, 4> Cond;
1201     const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
1202     TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
1203 
1204     if (Indexes) {
1205       for (MachineInstr &MI : NMBB->instrs()) {
1206         // Some instructions may have been moved to NMBB by updateTerminator(),
1207         // so we first remove any instruction that already has an index.
1208         if (Indexes->hasIndex(MI))
1209           Indexes->removeMachineInstrFromMaps(MI);
1210         Indexes->insertMachineInstrInMaps(MI);
1211       }
1212     }
1213   }
1214 
1215   // Fix PHI nodes in Succ so they refer to NMBB instead of this.
1216   Succ->replacePhiUsesWith(this, NMBB);
1217 
1218   // Inherit live-ins from the successor
1219   for (const auto &LI : Succ->liveins())
1220     NMBB->addLiveIn(LI);
1221 
1222   // Update LiveVariables.
1223   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1224   if (LV) {
1225     // Restore kills of virtual registers that were killed by the terminators.
1226     while (!KilledRegs.empty()) {
1227       Register Reg = KilledRegs.pop_back_val();
1228       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
1229         if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false))
1230           continue;
1231         if (Reg.isVirtual())
1232           LV->getVarInfo(Reg).Kills.push_back(&*I);
1233         LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
1234         break;
1235       }
1236     }
1237     // Update relevant live-through information.
1238     if (LiveInSets != nullptr)
1239       LV->addNewBlock(NMBB, this, Succ, *LiveInSets);
1240     else
1241       LV->addNewBlock(NMBB, this, Succ);
1242   }
1243 
1244   if (LIS) {
1245     // After splitting the edge and updating SlotIndexes, live intervals may be
1246     // in one of two situations, depending on whether this block was the last in
1247     // the function. If the original block was the last in the function, all
1248     // live intervals will end prior to the beginning of the new split block. If
1249     // the original block was not at the end of the function, all live intervals
1250     // will extend to the end of the new split block.
1251 
1252     bool isLastMBB =
1253       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
1254 
1255     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
1256     SlotIndex PrevIndex = StartIndex.getPrevSlot();
1257     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
1258 
1259     // Find the registers used from NMBB in PHIs in Succ.
1260     SmallSet<Register, 8> PHISrcRegs;
1261     for (MachineBasicBlock::instr_iterator
1262          I = Succ->instr_begin(), E = Succ->instr_end();
1263          I != E && I->isPHI(); ++I) {
1264       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
1265         if (I->getOperand(ni+1).getMBB() == NMBB) {
1266           MachineOperand &MO = I->getOperand(ni);
1267           Register Reg = MO.getReg();
1268           PHISrcRegs.insert(Reg);
1269           if (MO.isUndef())
1270             continue;
1271 
1272           LiveInterval &LI = LIS->getInterval(Reg);
1273           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1274           assert(VNI &&
1275                  "PHI sources should be live out of their predecessors.");
1276           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1277         }
1278       }
1279     }
1280 
1281     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
1282     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1283       Register Reg = Register::index2VirtReg(i);
1284       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
1285         continue;
1286 
1287       LiveInterval &LI = LIS->getInterval(Reg);
1288       if (!LI.liveAt(PrevIndex))
1289         continue;
1290 
1291       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
1292       if (isLiveOut && isLastMBB) {
1293         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1294         assert(VNI && "LiveInterval should have VNInfo where it is live.");
1295         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
1296       } else if (!isLiveOut && !isLastMBB) {
1297         LI.removeSegment(StartIndex, EndIndex);
1298       }
1299     }
1300 
1301     // Update all intervals for registers whose uses may have been modified by
1302     // updateTerminator().
1303     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
1304   }
1305 
1306   if (MachineDominatorTree *MDT =
1307           P.getAnalysisIfAvailable<MachineDominatorTree>())
1308     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
1309 
1310   if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
1311     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
1312       // If one or the other blocks were not in a loop, the new block is not
1313       // either, and thus LI doesn't need to be updated.
1314       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
1315         if (TIL == DestLoop) {
1316           // Both in the same loop, the NMBB joins loop.
1317           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1318         } else if (TIL->contains(DestLoop)) {
1319           // Edge from an outer loop to an inner loop.  Add to the outer loop.
1320           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
1321         } else if (DestLoop->contains(TIL)) {
1322           // Edge from an inner loop to an outer loop.  Add to the outer loop.
1323           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1324         } else {
1325           // Edge from two loops with no containment relation.  Because these
1326           // are natural loops, we know that the destination block must be the
1327           // header of its loop (adding a branch into a loop elsewhere would
1328           // create an irreducible loop).
1329           assert(DestLoop->getHeader() == Succ &&
1330                  "Should not create irreducible loops!");
1331           if (MachineLoop *P = DestLoop->getParentLoop())
1332             P->addBasicBlockToLoop(NMBB, MLI->getBase());
1333         }
1334       }
1335     }
1336 
1337   return NMBB;
1338 }
1339 
1340 bool MachineBasicBlock::canSplitCriticalEdge(
1341     const MachineBasicBlock *Succ) const {
1342   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1343   // it in this generic function.
1344   if (Succ->isEHPad())
1345     return false;
1346 
1347   // Splitting the critical edge to a callbr's indirect block isn't advised.
1348   // Don't do it in this generic function.
1349   if (Succ->isInlineAsmBrIndirectTarget())
1350     return false;
1351 
1352   const MachineFunction *MF = getParent();
1353   // Performance might be harmed on HW that implements branching using exec mask
1354   // where both sides of the branches are always executed.
1355   if (MF->getTarget().requiresStructuredCFG())
1356     return false;
1357 
1358   // Do we have an Indirect jump with a jumptable that we can rewrite?
1359   int JTI = findJumpTableIndex(*this);
1360   if (JTI >= 0 && !jumpTableHasOtherUses(*MF, *this, JTI))
1361     return true;
1362 
1363   // We may need to update this's terminator, but we can't do that if
1364   // analyzeBranch fails.
1365   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1366   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1367   SmallVector<MachineOperand, 4> Cond;
1368   // AnalyzeBanch should modify this, since we did not allow modification.
1369   if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
1370                          /*AllowModify*/ false))
1371     return false;
1372 
1373   // Avoid bugpoint weirdness: A block may end with a conditional branch but
1374   // jumps to the same MBB is either case. We have duplicate CFG edges in that
1375   // case that we can't handle. Since this never happens in properly optimized
1376   // code, just skip those edges.
1377   if (TBB && TBB == FBB) {
1378     LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1379                       << printMBBReference(*this) << '\n');
1380     return false;
1381   }
1382   return true;
1383 }
1384 
1385 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1386 /// neighboring instructions so the bundle won't be broken by removing MI.
1387 static void unbundleSingleMI(MachineInstr *MI) {
1388   // Removing the first instruction in a bundle.
1389   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1390     MI->unbundleFromSucc();
1391   // Removing the last instruction in a bundle.
1392   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1393     MI->unbundleFromPred();
1394   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1395   // are already fine.
1396 }
1397 
1398 MachineBasicBlock::instr_iterator
1399 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
1400   unbundleSingleMI(&*I);
1401   return Insts.erase(I);
1402 }
1403 
1404 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1405   unbundleSingleMI(MI);
1406   MI->clearFlag(MachineInstr::BundledPred);
1407   MI->clearFlag(MachineInstr::BundledSucc);
1408   return Insts.remove(MI);
1409 }
1410 
1411 MachineBasicBlock::instr_iterator
1412 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1413   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1414          "Cannot insert instruction with bundle flags");
1415   // Set the bundle flags when inserting inside a bundle.
1416   if (I != instr_end() && I->isBundledWithPred()) {
1417     MI->setFlag(MachineInstr::BundledPred);
1418     MI->setFlag(MachineInstr::BundledSucc);
1419   }
1420   return Insts.insert(I, MI);
1421 }
1422 
1423 /// This method unlinks 'this' from the containing function, and returns it, but
1424 /// does not delete it.
1425 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1426   assert(getParent() && "Not embedded in a function!");
1427   getParent()->remove(this);
1428   return this;
1429 }
1430 
1431 /// This method unlinks 'this' from the containing function, and deletes it.
1432 void MachineBasicBlock::eraseFromParent() {
1433   assert(getParent() && "Not embedded in a function!");
1434   getParent()->erase(this);
1435 }
1436 
1437 /// Given a machine basic block that branched to 'Old', change the code and CFG
1438 /// so that it branches to 'New' instead.
1439 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1440                                                MachineBasicBlock *New) {
1441   assert(Old != New && "Cannot replace self with self!");
1442 
1443   MachineBasicBlock::instr_iterator I = instr_end();
1444   while (I != instr_begin()) {
1445     --I;
1446     if (!I->isTerminator()) break;
1447 
1448     // Scan the operands of this machine instruction, replacing any uses of Old
1449     // with New.
1450     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1451       if (I->getOperand(i).isMBB() &&
1452           I->getOperand(i).getMBB() == Old)
1453         I->getOperand(i).setMBB(New);
1454   }
1455 
1456   // Update the successor information.
1457   replaceSuccessor(Old, New);
1458 }
1459 
1460 void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old,
1461                                            MachineBasicBlock *New) {
1462   for (MachineInstr &MI : phis())
1463     for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
1464       MachineOperand &MO = MI.getOperand(i);
1465       if (MO.getMBB() == Old)
1466         MO.setMBB(New);
1467     }
1468 }
1469 
1470 /// Find the next valid DebugLoc starting at MBBI, skipping any debug
1471 /// instructions.  Return UnknownLoc if there is none.
1472 DebugLoc
1473 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1474   // Skip debug declarations, we don't want a DebugLoc from them.
1475   MBBI = skipDebugInstructionsForward(MBBI, instr_end());
1476   if (MBBI != instr_end())
1477     return MBBI->getDebugLoc();
1478   return {};
1479 }
1480 
1481 DebugLoc MachineBasicBlock::rfindDebugLoc(reverse_instr_iterator MBBI) {
1482   if (MBBI == instr_rend())
1483     return findDebugLoc(instr_begin());
1484   // Skip debug declarations, we don't want a DebugLoc from them.
1485   MBBI = skipDebugInstructionsBackward(MBBI, instr_rbegin());
1486   if (!MBBI->isDebugInstr())
1487     return MBBI->getDebugLoc();
1488   return {};
1489 }
1490 
1491 /// Find the previous valid DebugLoc preceding MBBI, skipping any debug
1492 /// instructions.  Return UnknownLoc if there is none.
1493 DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) {
1494   if (MBBI == instr_begin())
1495     return {};
1496   // Skip debug instructions, we don't want a DebugLoc from them.
1497   MBBI = prev_nodbg(MBBI, instr_begin());
1498   if (!MBBI->isDebugInstr())
1499     return MBBI->getDebugLoc();
1500   return {};
1501 }
1502 
1503 DebugLoc MachineBasicBlock::rfindPrevDebugLoc(reverse_instr_iterator MBBI) {
1504   if (MBBI == instr_rend())
1505     return {};
1506   // Skip debug declarations, we don't want a DebugLoc from them.
1507   MBBI = next_nodbg(MBBI, instr_rend());
1508   if (MBBI != instr_rend())
1509     return MBBI->getDebugLoc();
1510   return {};
1511 }
1512 
1513 /// Find and return the merged DebugLoc of the branch instructions of the block.
1514 /// Return UnknownLoc if there is none.
1515 DebugLoc
1516 MachineBasicBlock::findBranchDebugLoc() {
1517   DebugLoc DL;
1518   auto TI = getFirstTerminator();
1519   while (TI != end() && !TI->isBranch())
1520     ++TI;
1521 
1522   if (TI != end()) {
1523     DL = TI->getDebugLoc();
1524     for (++TI ; TI != end() ; ++TI)
1525       if (TI->isBranch())
1526         DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
1527   }
1528   return DL;
1529 }
1530 
1531 /// Return probability of the edge from this block to MBB.
1532 BranchProbability
1533 MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
1534   if (Probs.empty())
1535     return BranchProbability(1, succ_size());
1536 
1537   const auto &Prob = *getProbabilityIterator(Succ);
1538   if (Prob.isUnknown()) {
1539     // For unknown probabilities, collect the sum of all known ones, and evenly
1540     // ditribute the complemental of the sum to each unknown probability.
1541     unsigned KnownProbNum = 0;
1542     auto Sum = BranchProbability::getZero();
1543     for (const auto &P : Probs) {
1544       if (!P.isUnknown()) {
1545         Sum += P;
1546         KnownProbNum++;
1547       }
1548     }
1549     return Sum.getCompl() / (Probs.size() - KnownProbNum);
1550   } else
1551     return Prob;
1552 }
1553 
1554 /// Set successor probability of a given iterator.
1555 void MachineBasicBlock::setSuccProbability(succ_iterator I,
1556                                            BranchProbability Prob) {
1557   assert(!Prob.isUnknown());
1558   if (Probs.empty())
1559     return;
1560   *getProbabilityIterator(I) = Prob;
1561 }
1562 
1563 /// Return probability iterator corresonding to the I successor iterator
1564 MachineBasicBlock::const_probability_iterator
1565 MachineBasicBlock::getProbabilityIterator(
1566     MachineBasicBlock::const_succ_iterator I) const {
1567   assert(Probs.size() == Successors.size() && "Async probability list!");
1568   const size_t index = std::distance(Successors.begin(), I);
1569   assert(index < Probs.size() && "Not a current successor!");
1570   return Probs.begin() + index;
1571 }
1572 
1573 /// Return probability iterator corresonding to the I successor iterator.
1574 MachineBasicBlock::probability_iterator
1575 MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1576   assert(Probs.size() == Successors.size() && "Async probability list!");
1577   const size_t index = std::distance(Successors.begin(), I);
1578   assert(index < Probs.size() && "Not a current successor!");
1579   return Probs.begin() + index;
1580 }
1581 
1582 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1583 /// as of just before "MI".
1584 ///
1585 /// Search is localised to a neighborhood of
1586 /// Neighborhood instructions before (searching for defs or kills) and N
1587 /// instructions after (searching just for defs) MI.
1588 MachineBasicBlock::LivenessQueryResult
1589 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1590                                            MCRegister Reg, const_iterator Before,
1591                                            unsigned Neighborhood) const {
1592   unsigned N = Neighborhood;
1593 
1594   // Try searching forwards from Before, looking for reads or defs.
1595   const_iterator I(Before);
1596   for (; I != end() && N > 0; ++I) {
1597     if (I->isDebugOrPseudoInstr())
1598       continue;
1599 
1600     --N;
1601 
1602     PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1603 
1604     // Register is live when we read it here.
1605     if (Info.Read)
1606       return LQR_Live;
1607     // Register is dead if we can fully overwrite or clobber it here.
1608     if (Info.FullyDefined || Info.Clobbered)
1609       return LQR_Dead;
1610   }
1611 
1612   // If we reached the end, it is safe to clobber Reg at the end of a block of
1613   // no successor has it live in.
1614   if (I == end()) {
1615     for (MachineBasicBlock *S : successors()) {
1616       for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
1617         if (TRI->regsOverlap(LI.PhysReg, Reg))
1618           return LQR_Live;
1619       }
1620     }
1621 
1622     return LQR_Dead;
1623   }
1624 
1625 
1626   N = Neighborhood;
1627 
1628   // Start by searching backwards from Before, looking for kills, reads or defs.
1629   I = const_iterator(Before);
1630   // If this is the first insn in the block, don't search backwards.
1631   if (I != begin()) {
1632     do {
1633       --I;
1634 
1635       if (I->isDebugOrPseudoInstr())
1636         continue;
1637 
1638       --N;
1639 
1640       PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI);
1641 
1642       // Defs happen after uses so they take precedence if both are present.
1643 
1644       // Register is dead after a dead def of the full register.
1645       if (Info.DeadDef)
1646         return LQR_Dead;
1647       // Register is (at least partially) live after a def.
1648       if (Info.Defined) {
1649         if (!Info.PartialDeadDef)
1650           return LQR_Live;
1651         // As soon as we saw a partial definition (dead or not),
1652         // we cannot tell if the value is partial live without
1653         // tracking the lanemasks. We are not going to do this,
1654         // so fall back on the remaining of the analysis.
1655         break;
1656       }
1657       // Register is dead after a full kill or clobber and no def.
1658       if (Info.Killed || Info.Clobbered)
1659         return LQR_Dead;
1660       // Register must be live if we read it.
1661       if (Info.Read)
1662         return LQR_Live;
1663 
1664     } while (I != begin() && N > 0);
1665   }
1666 
1667   // If all the instructions before this in the block are debug instructions,
1668   // skip over them.
1669   while (I != begin() && std::prev(I)->isDebugOrPseudoInstr())
1670     --I;
1671 
1672   // Did we get to the start of the block?
1673   if (I == begin()) {
1674     // If so, the register's state is definitely defined by the live-in state.
1675     for (const MachineBasicBlock::RegisterMaskPair &LI : liveins())
1676       if (TRI->regsOverlap(LI.PhysReg, Reg))
1677         return LQR_Live;
1678 
1679     return LQR_Dead;
1680   }
1681 
1682   // At this point we have no idea of the liveness of the register.
1683   return LQR_Unknown;
1684 }
1685 
1686 const uint32_t *
1687 MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
1688   // EH funclet entry does not preserve any registers.
1689   return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1690 }
1691 
1692 const uint32_t *
1693 MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
1694   // If we see a return block with successors, this must be a funclet return,
1695   // which does not preserve any registers. If there are no successors, we don't
1696   // care what kind of return it is, putting a mask after it is a no-op.
1697   return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1698 }
1699 
1700 void MachineBasicBlock::clearLiveIns() {
1701   LiveIns.clear();
1702 }
1703 
1704 MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
1705   assert(getParent()->getProperties().hasProperty(
1706       MachineFunctionProperties::Property::TracksLiveness) &&
1707       "Liveness information is accurate");
1708   return LiveIns.begin();
1709 }
1710 
1711 MachineBasicBlock::liveout_iterator MachineBasicBlock::liveout_begin() const {
1712   const MachineFunction &MF = *getParent();
1713   assert(MF.getProperties().hasProperty(
1714       MachineFunctionProperties::Property::TracksLiveness) &&
1715       "Liveness information is accurate");
1716 
1717   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1718   MCPhysReg ExceptionPointer = 0, ExceptionSelector = 0;
1719   if (MF.getFunction().hasPersonalityFn()) {
1720     auto PersonalityFn = MF.getFunction().getPersonalityFn();
1721     ExceptionPointer = TLI.getExceptionPointerRegister(PersonalityFn);
1722     ExceptionSelector = TLI.getExceptionSelectorRegister(PersonalityFn);
1723   }
1724 
1725   return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false);
1726 }
1727 
1728 bool MachineBasicBlock::sizeWithoutDebugLargerThan(unsigned Limit) const {
1729   unsigned Cntr = 0;
1730   auto R = instructionsWithoutDebug(begin(), end());
1731   for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1732     if (++Cntr > Limit)
1733       return true;
1734   }
1735   return false;
1736 }
1737 
1738 unsigned MachineBasicBlock::getBBIDOrNumber() const {
1739   uint8_t BBAddrMapVersion = getParent()->getContext().getBBAddrMapVersion();
1740   return BBAddrMapVersion < 2 ? getNumber() : *getBBID();
1741 }
1742 
1743 const MBBSectionID MBBSectionID::ColdSectionID(MBBSectionID::SectionType::Cold);
1744 const MBBSectionID
1745     MBBSectionID::ExceptionSectionID(MBBSectionID::SectionType::Exception);
1746