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