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