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