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