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