47#include "llvm/Config/llvm-config.h"
62#define DEBUG_TYPE "regalloc"
64STATISTIC(NumSpilledRanges,
"Number of spilled live ranges");
65STATISTIC(NumSnippets,
"Number of spilled snippets");
67STATISTIC(NumSpillsRemoved,
"Number of spills removed");
69STATISTIC(NumReloadsRemoved,
"Number of reloads removed");
70STATISTIC(NumFolded,
"Number of folded stack accesses");
72STATISTIC(NumRemats,
"Number of rematerialized defs for spilling");
77 cl::desc(
"Restrict remat for statepoint operands"));
102 using MergeableSpillsMap =
104 MergeableSpillsMap MergeableSpills;
114 void rmRedundantSpills(
134 : MF(mf), LIS(Analyses.LIS), LSS(Analyses.LSS), MDT(Analyses.MDT),
135 VRM(vrm),
MRI(mf.getRegInfo()),
TII(*mf.getSubtarget().getInstrInfo()),
136 MBFI(Analyses.MBFI),
Matrix(matrix), IPA(LIS, mf.getNumBlockIDs()) {}
138 void addToMergeableSpills(MachineInstr &Spill,
int StackSlot,
140 bool rmFromMergeableSpills(MachineInstr &Spill,
int StackSlot);
141 void hoistAllSpills();
142 void LRE_WillShrinkVirtReg(
Register)
override;
143 bool LRE_CanEraseVirtReg(
Register)
override;
149 DenseMap<Register, MCRegister> PendingReassignments;
152class InlineSpiller :
public Spiller {
157 MachineRegisterInfo &MRI;
158 const TargetInstrInfo &TII;
159 const TargetRegisterInfo &TRI;
160 LiveRegMatrix *Matrix =
nullptr;
163 LiveRangeEdit *Edit =
nullptr;
164 LiveInterval *StackInt =
nullptr;
167 AllocationOrder *Order =
nullptr;
179 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
182 SmallPtrSet<VNInfo*, 8> UsedValues;
185 SmallVector<MachineInstr*, 8> DeadDefs;
188 HoistSpillHelper HSpiller;
191 VirtRegAuxInfo &VRAI;
193 ~InlineSpiller()
override =
default;
196 InlineSpiller(
const Spiller::RequiredAnalyses &Analyses,
MachineFunction &MF,
197 VirtRegMap &VRM, VirtRegAuxInfo &VRAI, LiveRegMatrix *Matrix)
198 : MF(MF), LIS(Analyses.LIS), LSS(Analyses.LSS), VRM(VRM),
199 MRI(MF.getRegInfo()), TII(*MF.getSubtarget().getInstrInfo()),
200 TRI(*MF.getSubtarget().getRegisterInfo()), Matrix(Matrix),
201 HSpiller(Analyses, MF, VRM, Matrix), VRAI(VRAI) {}
203 void spill(LiveRangeEdit &, AllocationOrder *Order =
nullptr)
override;
206 void postOptimization()
override;
209 bool isSnippet(
const LiveInterval &SnipLI);
210 void collectRegsToSpill();
215 bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI);
216 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
218 void markValueUsed(LiveInterval *, VNInfo *);
219 bool hasPhysRegAvailable(
const MachineInstr &
MI);
220 bool reMaterializeFor(LiveInterval &, MachineInstr &
MI);
221 void reMaterializeAll();
224 bool foldMemoryOperand(
ArrayRef<std::pair<MachineInstr *, unsigned>>,
225 MachineInstr *LoadMI =
nullptr);
237void Spiller::anchor() {}
243 return new InlineSpiller(Analyses, MF, VRM, VRAI,
Matrix);
262 if (!
TII.isCopyInstr(
MI))
285 "expected to see first instruction in bundle");
289 while (
I->isBundledWithSucc()) {
291 auto CopyInst =
TII.isCopyInstr(
MI);
317 if (MO.getReg().isVirtual())
324bool InlineSpiller::isSnippet(
const LiveInterval &SnipLI) {
338 if (!LIS.intervalIsInOneMBB(SnipLI))
344 for (
auto *VNI : SnipLI.
vnis()) {
346 if (
MI->getOpcode() == TargetOpcode::STATEPOINT)
387void InlineSpiller::collectRegsToSpill() {
391 RegsToSpill.assign(1,
Reg);
392 SnippetCopies.clear();
393 RegsReplaced.clear();
402 if (!isSibling(SnipReg))
405 if (!isSnippet(SnipLI))
407 SnippetCopies.insert(&
MI);
408 if (isRegToSpill(SnipReg))
410 RegsToSpill.push_back(SnipReg);
439bool InlineSpiller::hoistSpillInsideBB(
LiveInterval &SpillLI,
444 assert(VNI && VNI->
def ==
Idx.getRegSlot() &&
"Not defined by copy");
461 assert(
DefMI &&
"Defining instruction disappeared");
475 ? LIS.getMBBEndIdx(
MBB)
476 : LIS.getInstructionIndex(*MII).getBaseIndex();
479 VRM.getPhys(SrcReg)))
486 assert(StackInt &&
"No stack slot assigned yet.");
489 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
491 << *StackInt <<
'\n');
495 eliminateRedundantSpills(SrcLI, SrcVNI);
501 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MII);
518 if (MIS.begin() == MII)
519 HSpiller.addToMergeableSpills(*MII, StackSlot, Original);
527 assert(VNI &&
"Missing value");
529 WorkList.
push_back(std::make_pair(&SLI, VNI));
530 assert(StackInt &&
"No stack slot assigned yet.");
537 << VNI->
def <<
" in " << *LI <<
'\n');
540 if (isRegToSpill(
Reg))
544 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
545 LLVM_DEBUG(
dbgs() <<
"Merged to stack int: " << *StackInt <<
'\n');
550 if (!
MI.mayStore() && !
TII.isCopyInstr(
MI))
558 if (isSibling(DstReg)) {
561 assert(DstVNI &&
"Missing defined value");
562 assert(DstVNI->
def ==
Idx.getRegSlot() &&
"Wrong copy def slot");
564 WorkList.
push_back(std::make_pair(&DstLI, DstVNI));
574 MI.setDesc(
TII.get(TargetOpcode::KILL));
575 DeadDefs.push_back(&
MI);
577 if (HSpiller.rmFromMergeableSpills(
MI, StackSlot))
581 }
while (!WorkList.
empty());
592 WorkList.
push_back(std::make_pair(LI, VNI));
595 if (!UsedValues.insert(VNI).second)
603 WorkList.
push_back(std::make_pair(LI, PVNI));
610 if (!SnippetCopies.count(
MI))
612 LiveInterval &SnipLI = LIS.getInterval(
MI->getOperand(1).getReg());
613 assert(isRegToSpill(SnipLI.
reg()) &&
"Unexpected register in copy");
615 assert(SnipVNI &&
"Snippet undefined before copy");
616 WorkList.
push_back(std::make_pair(&SnipLI, SnipVNI));
617 }
while (!WorkList.
empty());
639 if (
MI.getOpcode() != TargetOpcode::STATEPOINT)
645 EndIdx =
MI.getNumOperands();
646 Idx < EndIdx; ++Idx) {
664 if (!
Matrix->checkInterference(PrevIdx, UseIdx, PhysReg))
690 if (MO.getReg() == VirtReg.
reg())
698 if (SnippetCopies.count(&
MI)) {
699 LLVM_DEBUG(
dbgs() <<
"\tskipping remat snippet copy for " << UseIdx <<
'\t'
706 assert(OrigVNI &&
"corrupted sub-interval");
724 CurDef = LIS.getInstructionFromIndex(CurVNI->
def);
741 if (CurDef &&
TII.isReMaterializable(*CurDef)) {
743 LLVM_DEBUG(
dbgs() <<
"\tFound remat possibility through COPY chain: "
747 markValueUsed(&VirtReg, ParentVNI);
748 LLVM_DEBUG(
dbgs() <<
"\tcannot remat missing def for " << UseIdx <<
'\t'
756 if (!Edit->canRematerializeAt(RM, UseIdx)) {
757 markValueUsed(&VirtReg, ParentVNI);
765 markValueUsed(&VirtReg, ParentVNI);
772 if (
RM.OrigMI->canFoldAsLoad() &&
773 (
RM.OrigMI->mayLoad() || !hasPhysRegAvailable(
MI)) &&
774 foldMemoryOperand(
Ops,
RM.OrigMI)) {
775 Edit->markRematerialized(
RM.ParentVNI);
783 markValueUsed(&VirtReg, ParentVNI);
789 Register NewVReg = Edit->createFrom(Original);
799 if (SR.liveAt(UseIdx))
800 UsedLanes |= SR.LaneMask;
804 SlotIndex DefIdx = Edit->rematerializeAt(*
MI.getParent(),
MI, NewVReg, RM,
805 TRI,
false, 0,
nullptr, UsedLanes);
809 auto *NewMI = LIS.getInstructionFromIndex(DefIdx);
810 NewMI->setDebugLoc(
MI.getDebugLoc());
814 << *LIS.getInstructionFromIndex(DefIdx));
817 for (
const auto &OpPair :
Ops) {
830void InlineSpiller::reMaterializeAll() {
834 bool anyRemat =
false;
839 if (
MI.isDebugValue())
842 assert(!
MI.isDebugInstr() &&
"Did not expect to find a use in debug "
843 "instruction that isn't a DBG_VALUE");
845 anyRemat |= reMaterializeFor(LI,
MI);
859 if (!
MI->allDefsAreDead())
862 DeadDefs.push_back(
MI);
866 if (
MI->isBundledWithSucc() && !
MI->isBundledWithPred()) {
868 EndIt =
MI->getParent()->instr_end();
871 bool OnlyDeadCopies =
true;
873 It != EndIt && It->isBundledWithPred(); ++It) {
875 auto DestSrc =
TII.isCopyInstr(*It);
876 bool IsCopyToDeadReg =
877 DestSrc && DestSrc->Destination->getReg() ==
Reg;
878 if (!IsCopyToDeadReg) {
879 OnlyDeadCopies =
false;
883 if (OnlyDeadCopies) {
885 It != EndIt && It->isBundledWithPred(); ++It) {
886 It->addRegisterDead(
Reg, &
TRI);
888 DeadDefs.push_back(&*It);
897 if (DeadDefs.empty())
899 LLVM_DEBUG(
dbgs() <<
"Remat created " << DeadDefs.size() <<
" dead defs.\n");
900 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
908 unsigned ResultPos = 0;
911 Edit->eraseVirtReg(
Reg);
912 RegsReplaced.push_back(
Reg);
918 "Empty and not used live-range?!");
920 RegsToSpill[ResultPos++] =
Reg;
922 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
924 <<
" registers to spill after remat.\n");
935 bool IsLoad = InstrReg.
isValid();
940 if (InstrReg !=
Reg || FI != StackSlot)
944 HSpiller.rmFromMergeableSpills(*
MI, StackSlot);
947 LIS.RemoveMachineInstrFromMaps(*
MI);
948 MI->eraseFromParent();
961#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
967 const char *
const header,
969 char NextLine =
'\n';
970 char SlotIndent =
'\t';
972 if (std::next(
B) ==
E) {
977 dbgs() <<
'\t' << header <<
": " << NextLine;
988 Idx = Idx.getRegSlot(
true);
991 dbgs() << SlotIndent << Idx <<
'\t' << *
I;
1003foldMemoryOperand(
ArrayRef<std::pair<MachineInstr *, unsigned>>
Ops,
1009 if (
Ops.back().first !=
MI ||
MI->isBundled())
1012 bool WasCopy =
TII.isCopyInstr(*MI).has_value();
1021 bool UntieRegs =
MI->getOpcode() == TargetOpcode::STATEPOINT;
1025 bool SpillSubRegs =
TII.isSubregFoldable() ||
1026 MI->getOpcode() == TargetOpcode::STATEPOINT ||
1027 MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1028 MI->getOpcode() == TargetOpcode::STACKMAP;
1033 for (
const auto &OpPair :
Ops) {
1034 unsigned Idx = OpPair.second;
1035 assert(
MI == OpPair.first &&
"Instruction conflict during operand folding");
1052 if (LoadMI && MO.
isDef())
1055 if (UntieRegs || !
MI->isRegTiedToDefOperand(Idx))
1061 if (FoldOps.
empty())
1068 for (
unsigned Idx : FoldOps) {
1072 unsigned Tied =
MI->findTiedOperandIdx(Idx);
1079 MI->untieRegOperand(Idx);
1085 ?
TII.foldMemoryOperand(*
MI, FoldOps, *LoadMI, CopyMI, &LIS, &VRM)
1086 :
TII.foldMemoryOperand(*
MI, FoldOps, StackSlot, CopyMI, &LIS, &VRM);
1089 for (
auto Tied : TiedOps)
1090 MI->tieOperands(Tied.first, Tied.second);
1116 HSpiller.rmFromMergeableSpills(*
MI, FI))
1132 bool NeedMatrixReassign =
1135 if (NeedMatrixReassign) {
1136 PhysReg = VRM.getPhys(CopyDstReg);
1143 if (NeedMatrixReassign)
1144 Matrix->assign(LI, PhysReg);
1146 Register OrigReg = VRM.getOriginal(CopyDstReg);
1147 if (OrigReg != CopyDstReg) {
1159 "OrigLI should be live at FoldMI's def");
1168 if (
MI->isCandidateForAdditionalCallInfo())
1169 MI->getMF()->moveAdditionalCallInfo(
MI, FoldMI);
1176 if (
MI->peekDebugInstrNum() &&
Ops[0].second == 0) {
1178 auto MakeSubstitution = [
this,FoldMI,
MI,&
Ops]() {
1180 unsigned OldOperandNum =
Ops[0].second;
1182 unsigned OldNum =
MI->getDebugInstrNum();
1183 MF.makeDebugValueSubstitution({OldNum, OldOperandNum},
1188 if (
Ops.size() == 1 && Op0.
isDef()) {
1190 }
else if (
Ops.size() == 2 && Op0.
isDef() &&
MI->getOperand(1).isTied() &&
1191 Op0.
getReg() ==
MI->getOperand(1).getReg()) {
1194 }
else if (
MI->peekDebugInstrNum()) {
1200 MF.substituteDebugValuesForInst(*
MI, *FoldMI,
Ops[0].second);
1203 MI->eraseFromParent();
1206 assert(!MIS.empty() &&
"Unexpected empty span of instructions!");
1208 if (&
MI != FoldMI && &
MI != CopyMI)
1213 if (
R.isVirtual()) {
1228 if (MO.
getReg() == ImpReg)
1237 else if (
Ops.front().second == 0) {
1242 if (std::distance(MIS.begin(), MIS.end()) <= 1)
1243 HSpiller.addToMergeableSpills(*FoldMI, StackSlot, Original);
1249void InlineSpiller::insertReload(
Register NewVReg,
1269 if (!Def.isImplicitDef())
1275 return MO.getReg() == Reg && MO.readsReg();
1280void InlineSpiller::insertSpill(
Register NewVReg,
1284 assert(!
MI->isTerminator() &&
"Inserting a spill after a terminator");
1299 BuildMI(
MBB, SpillBefore,
MI->getDebugLoc(),
TII.get(TargetOpcode::KILL))
1313 if (IsRealSpill && std::distance(Spill, MIS.end()) <= 1)
1314 HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
1318void InlineSpiller::spillAroundUses(
Register Reg) {
1325 if (
MI.isDebugValue()) {
1334 assert(!
MI.isDebugInstr() &&
"Did not expect to find a use in debug "
1335 "instruction that isn't a DBG_VALUE");
1338 if (SnippetCopies.count(&
MI))
1342 if (coalesceStackAccess(&
MI,
Reg))
1358 if (SibReg && isSibling(SibReg)) {
1360 if (isRegToSpill(SibReg)) {
1362 SnippetCopies.insert(&
MI);
1366 if (hoistSpillInsideBB(OldLI,
MI)) {
1368 MI.getOperand(0).setIsDead();
1369 DeadDefs.push_back(&
MI);
1375 eliminateRedundantSpills(SibLI, SibLI.
getVNInfoAt(Idx));
1381 if (foldMemoryOperand(
Ops))
1389 insertReload(NewVReg, Idx, &
MI);
1392 bool hasLiveDef =
false;
1393 for (
const auto &OpPair :
Ops) {
1404 insertSpill(NewVReg, &
MI);
1409void InlineSpiller::spillAll() {
1412 StackSlot = VRM.assignVirt2StackSlot(Original);
1413 StackInt = &LSS.getOrCreateInterval(StackSlot,
MRI.
getRegClass(Original));
1414 StackInt->getNextValue(
SlotIndex(), LSS.getVNInfoAllocator());
1416 StackInt = &LSS.getInterval(StackSlot);
1418 if (Original != Edit->getReg())
1419 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1421 assert(StackInt->getNumValNums() == 1 &&
"Bad stack interval values");
1425 LLVM_DEBUG(
dbgs() <<
"Merged spilled regs: " << *StackInt <<
'\n');
1429 spillAroundUses(
Reg);
1433 VRM.assignVirt2StackSlot(
Reg, StackSlot);
1437 if (!DeadDefs.empty()) {
1438 LLVM_DEBUG(
dbgs() <<
"Eliminating " << DeadDefs.size() <<
" dead defs\n");
1439 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
1446 assert(SnippetCopies.count(&
MI) &&
"Remaining use wasn't a snippet copy");
1449 MI.eraseFromBundle();
1455 Edit->eraseVirtReg(
Reg);
1464 Original = VRM.getOriginal(edit.
getReg());
1465 StackSlot = VRM.getStackSlot(Original);
1470 <<
':' << edit.
getParent() <<
"\nFrom original "
1473 "Attempting to spill already spilled value.");
1474 assert(DeadDefs.empty() &&
"Previous spill didn't remove dead defs");
1476 collectRegsToSpill();
1480 if (!RegsToSpill.empty())
1483 Edit->calculateRegClassAndHint(MF, VRAI);
1487void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
1490void HoistSpillHelper::addToMergeableSpills(
MachineInstr &Spill,
int StackSlot,
1497 auto [Place,
Inserted] = StackSlotToOrigLI.try_emplace(StackSlot);
1499 auto LI = std::make_unique<LiveInterval>(OrigLI.
reg(), OrigLI.
weight());
1501 Place->second = std::move(LI);
1505 VNInfo *OrigVNI = Place->second->getVNInfoAt(
Idx.getRegSlot());
1513 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1514 MergeableSpills[MIdx].insert(&Spill);
1519bool HoistSpillHelper::rmFromMergeableSpills(
MachineInstr &Spill,
1521 auto It = StackSlotToOrigLI.find(StackSlot);
1522 if (It == StackSlotToOrigLI.end())
1525 VNInfo *OrigVNI = It->second->getVNInfoAt(
Idx.getRegSlot());
1526 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1527 return MergeableSpills[MIdx].erase(&Spill);
1537 if (Idx < OrigVNI.
def) {
1540 LLVM_DEBUG(
dbgs() <<
"can't spill in root block - def after LIP\n");
1547 for (
const Register &SibReg : Siblings) {
1555 return SR.getVNInfoAt(Idx) != nullptr;
1566void HoistSpillHelper::rmRedundantSpills(
1573 for (
auto *
const CurrentSpill : Spills) {
1580 MachineInstr *SpillToRm = (CIdx > PIdx) ? CurrentSpill : PrevSpill;
1581 MachineInstr *SpillToKeep = (CIdx > PIdx) ? PrevSpill : CurrentSpill;
1583 SpillBBToSpill[MDT.getNode(
Block)] = SpillToKeep;
1585 SpillBBToSpill[MDT.getNode(
Block)] = CurrentSpill;
1588 for (
auto *
const SpillToRm : SpillsToRm)
1589 Spills.erase(SpillToRm);
1598void HoistSpillHelper::getVisitOrders(
1622 for (
auto *
const Spill : Spills) {
1626 while (Node != RootIDomNode) {
1629 if (Node != MDT[
Block] && SpillBBToSpill[Node]) {
1630 SpillToRm = SpillBBToSpill[MDT[
Block]];
1635 }
else if (WorkSet.
count(Node)) {
1638 NodesOnPath.
insert(Node);
1653 NodesOnPath.
clear();
1663 if (WorkSet.
count(Child))
1666 }
while (idx != Orders.
size());
1668 "Orders have different size with WorkSet");
1673 for (; RIt != Orders.
rend(); RIt++)
1674 LLVM_DEBUG(
dbgs() <<
"BB" << (*RIt)->getBlock()->getNumber() <<
",");
1682void HoistSpillHelper::runHoistSpills(
1698 rmRedundantSpills(Spills, SpillsToRm, SpillBBToSpill);
1701 getVisitOrders(Root, Spills, Orders, SpillsToRm, SpillsToKeep,
1708 using NodesCostPair =
1709 std::pair<SmallPtrSet<MachineDomTreeNode *, 16>,
BlockFrequency>;
1717 for (; RIt != Orders.
rend(); RIt++) {
1721 if (
auto It = SpillsToKeep.
find(*RIt);
1722 It != SpillsToKeep.
end() && !It->second) {
1723 auto &SIt = SpillsInSubTreeMap[*RIt];
1726 SIt.second = MBFI.getBlockFreq(
Block);
1733 if (!SpillsInSubTreeMap.
contains(Child))
1741 auto &[SpillsInSubTree, SubTreeCost] = SpillsInSubTreeMap[*RIt];
1742 auto ChildIt = SpillsInSubTreeMap.
find(Child);
1743 SubTreeCost += ChildIt->second.second;
1744 auto BI = ChildIt->second.first.begin();
1745 auto EI = ChildIt->second.first.end();
1746 SpillsInSubTree.insert(BI, EI);
1747 SpillsInSubTreeMap.
erase(ChildIt);
1750 auto &[SpillsInSubTree, SubTreeCost] = SpillsInSubTreeMap[*RIt];
1752 if (SpillsInSubTree.empty())
1757 if (!isSpillCandBB(OrigLI, OrigVNI, *
Block, LiveReg))
1765 if (SubTreeCost > MBFI.getBlockFreq(
Block) * MarginProb) {
1767 for (auto *const SpillBB : SpillsInSubTree) {
1770 if (auto It = SpillsToKeep.find(SpillBB);
1771 It != SpillsToKeep.end() && !It->second) {
1772 MachineInstr *SpillToRm = SpillBBToSpill[SpillBB];
1773 SpillsToRm.push_back(SpillToRm);
1776 SpillsToKeep.erase(SpillBB);
1780 SpillsToKeep[*RIt] = LiveReg;
1782 dbgs() <<
"spills in BB: ";
1783 for (
const auto Rspill : SpillsInSubTree)
1784 dbgs() << Rspill->getBlock()->getNumber() <<
" ";
1785 dbgs() <<
"were promoted to BB" << (*RIt)->getBlock()->getNumber()
1788 SpillsInSubTree.clear();
1789 SpillsInSubTree.insert(*RIt);
1790 SubTreeCost = MBFI.getBlockFreq(
Block);
1795 for (
const auto &Ent : SpillsToKeep) {
1797 SpillsToIns[Ent.first->getBlock()] = Ent.second;
1817void HoistSpillHelper::hoistAllSpills() {
1825 Virt2SiblingsMap[Original].insert(
Reg);
1829 for (
auto &Ent : MergeableSpills) {
1830 int Slot = Ent.first.first;
1832 VNInfo *OrigVNI = Ent.first.second;
1834 if (Ent.second.empty())
1838 dbgs() <<
"\nFor Slot" <<
Slot <<
" and VN" << OrigVNI->
id <<
":\n"
1839 <<
"Equal spills in BB: ";
1840 for (
const auto spill : EqValSpills)
1841 dbgs() << spill->getParent()->getNumber() <<
" ";
1850 runHoistSpills(OrigLI, *OrigVNI, EqValSpills, SpillsToRm, SpillsToIns);
1853 dbgs() <<
"Finally inserted spills in BB: ";
1854 for (
const auto &Ispill : SpillsToIns)
1855 dbgs() << Ispill.first->getNumber() <<
" ";
1856 dbgs() <<
"\nFinally removed spills in BB: ";
1857 for (
const auto Rspill : SpillsToRm)
1858 dbgs() << Rspill->getParent()->getNumber() <<
" ";
1864 if (!SpillsToIns.empty() || !SpillsToRm.empty())
1866 StackIntvl.getValNumInfo(0));
1869 for (
auto const &Insert : SpillsToIns) {
1883 NumSpills -= SpillsToRm.size();
1884 for (
auto *
const RMEnt : SpillsToRm) {
1885 RMEnt->setDesc(
TII.get(TargetOpcode::KILL));
1886 for (
unsigned i = RMEnt->getNumOperands(); i; --i) {
1889 RMEnt->removeOperand(i - 1);
1892 Edit.eliminateDeadDefs(SpillsToRm, {});
1897 for (
auto &[VReg, PhysReg] : PendingReassignments) {
1899 "Pending reassignment without matrix or live interval");
1902 PendingReassignments.clear();
1909void HoistSpillHelper::LRE_WillShrinkVirtReg(
Register VirtReg) {
1915 Matrix->unassign(LI,
true);
1916 PendingReassignments[VirtReg] = PhysReg;
1922bool HoistSpillHelper::LRE_CanEraseVirtReg(
Register VirtReg) {
1923 PendingReassignments.erase(VirtReg);
1924 if (
Matrix && VRM.hasPhys(VirtReg)) {
1926 Matrix->unassign(LI,
true);
1938 auto PendingIt = PendingReassignments.find(Old);
1939 if (PendingIt != PendingReassignments.end()) {
1943 "Pending reassignment without matrix or live interval");
1945 PendingReassignments.erase(PendingIt);
1950 }
else if (VRM.hasPhys(Old)) {
1956 Matrix->unassign(LI,
true);
1957 Matrix->assign(LI, PhysReg);
1961 VRM.assignVirt2Phys(New, PhysReg);
1964 VRM.assignVirt2StackSlot(New, VRM.getStackSlot(Old));
1968 if (VRM.hasShape(Old))
1969 VRM.assignVirt2Shape(New, VRM.getShape(Old));
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
This file defines the DenseMap class.
const HexagonInstrInfo * TII
static LLVM_DUMP_METHOD void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E, LiveIntervals const &LIS, const char *const header, Register VReg=Register())
static Register isCopyOfBundle(const MachineInstr &FirstMI, Register Reg, const TargetInstrInfo &TII)
Check for a copy bundle as formed by SplitKit.
static bool isRealSpill(const MachineInstr &Def, Register Reg)
Check if Def defines Reg with an undefined value.
static cl::opt< bool > RestrictStatepointRemat("restrict-statepoint-remat", cl::init(false), cl::Hidden, cl::desc("Restrict remat for statepoint operands"))
static Register isCopyOf(const MachineInstr &MI, Register Reg, const TargetInstrInfo &TII)
isFullCopyOf - If MI is a COPY to or from Reg, return the other register, otherwise return 0.
static void getVDefInterval(const MachineInstr &MI, LiveIntervals &LIS)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
Promote Memory to Register
MachineRegisterInfo & MRI
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
Store the specified register of the given register class to the specified stack frame index.
Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const override
TargetInstrInfo overrides.
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
Load the specified register of the given register class from the specified stack frame index.
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
If the specified machine instruction is a direct store to a stack slot, return the virtual or physica...
Determines the latest safe point in a block in which we can insert a split, spill or other instructio...
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
bool isSpillable() const
isSpillable - Can this interval be spilled?
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
bool hasInterval(Register Reg) const
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
SlotIndexes * getSlotIndexes() const
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
VNInfo::Allocator & getVNInfoAllocator()
LiveInterval & getInterval(Register Reg)
void InsertMachineInstrRangeInMaps(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E)
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr, LaneBitmask SubRangeMask=LaneBitmask::getAll())
After removing some uses of a register, shrink its live range to just the remaining uses.
LLVM_ABI void removePhysRegDefAt(MCRegister Reg, SlotIndex Pos)
Remove value numbers and related live segments starting at position Pos that are part of any liverang...
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
Result of a LiveRange query.
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction,...
bool isKill() const
Return true if the live-in value is killed by this instruction.
Callback methods for LiveRangeEdit owners.
const LiveInterval & getParent() const
VNInfo * getValNumInfo(unsigned ValNo)
getValNumInfo - Returns pointer to the specified val#.
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
LLVM_ABI void MergeValueInAsValue(const LiveRange &RHS, const VNInfo *RHSValNo, VNInfo *LHSValNo)
MergeValueInAsValue - Merge all of the segments of a specific val# in RHS into this live range as the...
iterator_range< vni_iterator > vnis()
bool liveAt(SlotIndex index) const
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
LLVM_ABI std::pair< VNInfo *, bool > extendInBlock(ArrayRef< SlotIndex > Undefs, SlotIndex StartIdx, SlotIndex Kill)
Attempt to extend a value defined after StartIdx to include Use.
unsigned getNumValNums() const
VNInfo * getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
void assign(const LiveRange &Other, BumpPtrAllocator &Allocator)
Copies values numbers and live segments from Other into this range.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Wrapper class representing physical registers. Should be passed by value.
MIBundleOperands - Iterate over all operands in a bundle of machine instructions.
LLVM_ABI iterator SkipPHIsLabelsAndDebug(iterator I, Register Reg=Register(), bool SkipPseudoOp=true)
Return the first instruction in MBB after I that is not a PHI, label or debug.
Instructions::iterator instr_iterator
Instructions::const_iterator const_instr_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
static const unsigned int DebugOperandMemNumber
A reserved operand number representing the instructions memory operand, for instructions that have a ...
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
MachineInstrSpan provides an interface to get an iteration range containing the instruction it was in...
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
bool isBundledWithPred() const
Return true if this instruction is part of a bundle, and it is not the first instruction in the bundl...
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
LLVM_ABI unsigned getDebugInstrNum()
Fetch the instruction number of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
bool isBundled() const
Return true if this instruction part of a bundle.
LLVM_ABI bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI defined a register without a use.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< reg_bundle_iterator > reg_bundles(Register Reg) const
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
reg_bundle_nodbg_iterator reg_bundle_nodbg_begin(Register RegNo) const
defusechain_instr_iterator< true, true, true, false > reg_bundle_nodbg_iterator
reg_bundle_nodbg_iterator/reg_bundle_nodbg_begin/reg_bundle_nodbg_end - Walk all defs and uses of the...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
iterator_range< use_bundle_nodbg_iterator > use_nodbg_bundles(Register Reg) const
bool def_empty(Register RegNo) const
def_empty - Return true if there are no instructions defining the specified register (it may be live-...
bool reg_nodbg_empty(Register RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions.
static reg_bundle_nodbg_iterator reg_bundle_nodbg_end()
iterator_range< reg_instr_iterator > reg_instructions(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
This class implements a map that also provides access to all stored values in a deterministic order.
Wrapper class representing virtual and physical registers.
constexpr bool isStack() const
Return true if this is a stack slot.
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
constexpr bool isValid() const
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
SlotIndex - An opaque wrapper around machine indexes.
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
LLVM_ABI void removeSingleMachineInstrFromMaps(MachineInstr &MI)
Removes a single machine instruction MI from the mapping.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
reverse_iterator rbegin()
std::reverse_iterator< iterator > reverse_iterator
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
MI-level Statepoint operands.
LLVM_ABI bool isFoldableReg(Register Reg) const
Return true if Reg is used only in operands which can be folded to stack usage.
TargetInstrInfo - Interface to description of machine instruction set.
VNInfo - Value Number Information.
bool isUnused() const
Returns true if this value is unused.
unsigned id
The ID number of this value.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
Calculate auxiliary information for a virtual register such as its spill weight and allocation hint.
static constexpr int NO_STACK_SLOT
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
NodeAddr< NodeBase * > Node
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI PhysRegInfo AnalyzePhysRegInBundle(const MachineInstr &MI, Register Reg, const TargetRegisterInfo *TRI)
AnalyzePhysRegInBundle - Analyze how the current instruction or bundle uses a physical register.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI Spiller * createInlineSpiller(const Spiller::RequiredAnalyses &Analyses, MachineFunction &MF, VirtRegMap &VRM, VirtRegAuxInfo &VRAI, LiveRegMatrix *Matrix=nullptr)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI VirtRegInfo AnalyzeVirtRegInBundle(MachineInstr &MI, Register Reg, SmallVectorImpl< std::pair< MachineInstr *, unsigned > > *Ops=nullptr)
AnalyzeVirtRegInBundle - Analyze how the current instruction or bundle uses a virtual register.
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool canGuaranteeAssignmentAfterRemat(Register VReg, const MachineInstr &MI)
Return whether we can guarantee physical register assignment if VReg's value is rematerialized immedi...
LLVM_ABI MachineInstr * buildDbgValueForSpill(MachineBasicBlock &BB, MachineBasicBlock::iterator I, const MachineInstr &Orig, int FrameIndex, Register SpillReg)
Clone a DBG_VALUE whose value has been spilled to FrameIndex.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
static constexpr LaneBitmask getAll()
static constexpr LaneBitmask getNone()
Remat - Information needed to rematerialize at a specific location.
This represents a simple continuous liveness interval for a value.
Information about how a physical register Reg is used by a set of operands.
bool FullyDefined
Reg or a super-register is defined.
VirtRegInfo - Information about a virtual register used by a set of operands.
bool Reads
Reads - One of the operands read the virtual register.
bool Tied
Tied - Uses and defs must use the same register.
bool Writes
Writes - One of the operands writes the virtual register.