37#define DEBUG_TYPE "fixup-statepoint-caller-saved"
38STATISTIC(NumSpilledRegisters,
"Number of spilled register");
39STATISTIC(NumSpillSlotsAllocated,
"Number of spill slots allocated");
40STATISTIC(NumSpillSlotsExtended,
"Number of spill slots extended");
44struct FixupStatepointCallerSavedImpl {
52 FixupStatepointCallerSavedLegacy() : MachineFunctionPass(ID) {}
53 void getAnalysisUsage(AnalysisUsage &AU)
const override {
58 StringRef getPassName()
const override {
59 return "Fixup Statepoint Caller Saved";
67char FixupStatepointCallerSavedLegacy::ID = 0;
71 "Fixup Statepoint Caller Saved",
false,
false)
78 return TRI.getSpillSize(*RC);
99 int Idx = RI->findRegisterUseOperandIdx(
Reg, &
TRI,
false);
100 if (Idx >= 0 && (
unsigned)Idx <
StatepointOpers(&*RI).getNumDeoptArgsIdx()) {
105 if (!Opts.fixup_scs_enable_copy_propagation)
111 for (
auto It = ++(RI.
getReverse()); It !=
E; ++It) {
112 if (It->readsRegister(
Reg, &
TRI) && !
Use)
114 if (It->modifiesRegister(
Reg, &
TRI)) {
123 auto DestSrc =
TII.isCopyInstr(*Def);
124 if (!DestSrc || DestSrc->Destination->getReg() !=
Reg)
127 Register SrcReg = DestSrc->Source->getReg();
138 IsKill = DestSrc->Source->isKill();
143 LLVM_DEBUG(
dbgs() <<
"spillRegisters: removing dead copy " << *Def);
144 Def->eraseFromParent();
156using RegSlotPair = std::pair<Register, int>;
159class RegReloadCache {
160 using ReloadSet = SmallSet<RegSlotPair, 8>;
161 DenseMap<const MachineBasicBlock *, ReloadSet> Reloads;
164 RegReloadCache() =
default;
168 bool tryRecordReload(
Register Reg,
int FI,
const MachineBasicBlock *
MBB) {
169 RegSlotPair RSP(
Reg, FI);
170 return Reloads[
MBB].insert(RSP).second;
179class FrameIndexesCache {
181 struct FrameIndexesPerSize {
183 SmallVector<int, 8> Slots;
187 const CodeGenOptions &Opts;
188 MachineFrameInfo &MFI;
189 const TargetRegisterInfo &TRI;
194 DenseMap<unsigned, FrameIndexesPerSize> Cache;
198 SmallSet<int, 8> ReservedSlots;
203 DenseMap<const MachineBasicBlock *, SmallVector<RegSlotPair, 8>>
206 FrameIndexesPerSize &getCacheBucket(
unsigned Size) {
209 return Cache[Opts.fixup_scs_extend_slot_size ? 0 :
Size];
213 FrameIndexesCache(
const CodeGenOptions &Opts, MachineFrameInfo &MFI,
214 const TargetRegisterInfo &TRI)
215 : Opts(Opts), MFI(MFI), TRI(TRI) {}
219 void reset(
const MachineBasicBlock *EHPad) {
220 for (
auto &It : Cache)
223 ReservedSlots.clear();
225 if (
auto It = GlobalIndices.find(EHPad); It != GlobalIndices.end())
230 int getFrameIndex(
Register Reg, MachineBasicBlock *EHPad) {
232 auto It = GlobalIndices.find(EHPad);
233 if (It != GlobalIndices.end()) {
234 auto &Vec = It->second;
236 Vec, [
Reg](RegSlotPair &RSP) {
return Reg == RSP.first; });
237 if (Idx != Vec.end()) {
238 int FI =
Idx->second;
242 assert(ReservedSlots.count(FI) &&
"using unreserved slot");
248 FrameIndexesPerSize &
Line = getCacheBucket(
Size);
249 while (
Line.Index <
Line.Slots.size()) {
251 if (ReservedSlots.count(FI))
255 if (MFI.getObjectSize(FI) <
Size) {
256 MFI.setObjectSize(FI,
Size);
258 NumSpillSlotsExtended++;
263 NumSpillSlotsAllocated++;
264 Line.Slots.push_back(FI);
269 GlobalIndices[EHPad].push_back(std::make_pair(
Reg, FI));
281 void sortRegisters(SmallVectorImpl<Register> &Regs) {
282 if (!Opts.fixup_scs_extend_slot_size)
291class StatepointState {
293 const CodeGenOptions &Opts;
298 MachineBasicBlock *EHPad;
299 const TargetRegisterInfo &TRI;
300 const TargetInstrInfo &TII;
301 MachineFrameInfo &MFI;
303 const uint32_t *Mask;
305 FrameIndexesCache &CacheFI;
306 bool AllowGCPtrInCSR;
308 SmallVector<unsigned, 8> OpsToSpill;
314 DenseMap<Register, int> RegToSlotIdx;
317 StatepointState(
const CodeGenOptions &Opts, MachineInstr &MI,
318 const uint32_t *Mask, FrameIndexesCache &CacheFI,
319 bool AllowGCPtrInCSR)
320 : Opts(Opts), MI(MI), MF(*MI.getMF()),
321 TRI(*MF.getSubtarget().getRegisterInfo()),
322 TII(*MF.getSubtarget().getInstrInfo()), MFI(MF.getFrameInfo()),
323 Mask(Mask), CacheFI(CacheFI), AllowGCPtrInCSR(AllowGCPtrInCSR) {
330 [](MachineInstr &
I) {
331 return I.getOpcode() == TargetOpcode::STATEPOINT;
337 auto IsEHPad = [](MachineBasicBlock *
B) {
return B->isEHPad(); };
346 MachineBasicBlock *getEHPad()
const {
return EHPad; }
350 return (Mask[
Reg.
id() / 32] >> (
Reg.
id() % 32)) & 1;
356 bool findRegistersToSpill() {
357 SmallSet<Register, 8> GCRegs;
360 for (
const auto &Def : MI.defs())
363 SmallSet<Register, 8> VisitedRegs;
364 for (
unsigned Idx = StatepointOpers(&MI).getVarIdx(),
365 EndIdx = MI.getNumOperands();
366 Idx < EndIdx; ++Idx) {
367 MachineOperand &MO = MI.getOperand(Idx);
373 if (isCalleeSaved(
Reg) && (AllowGCPtrInCSR || !GCRegs.
contains(
Reg)))
380 RegsToSpill.push_back(
Reg);
381 OpsToSpill.push_back(Idx);
383 CacheFI.sortRegisters(RegsToSpill);
384 return !RegsToSpill.empty();
389 void spillRegisters() {
391 int FI = CacheFI.getFrameIndex(
Reg, EHPad);
393 NumSpilledRegisters++;
394 RegToSlotIdx[
Reg] = FI;
406 TII.storeRegToStackSlot(*MI.getParent(), InsertBefore,
Reg, IsKill, FI,
412 MachineBasicBlock *
MBB) {
414 int FI = RegToSlotIdx[
Reg];
425 MachineInstr *Reload = It->getPrevNode();
428 assert(TII.isLoadFromStackSlot(*Reload, Dummy) ==
Reg);
435 void insertReloads(MachineInstr *NewStatepoint, RegReloadCache &RC) {
437 auto InsertPoint = std::next(NewStatepoint->
getIterator());
439 for (
auto Reg : RegsToReload) {
440 insertReloadBefore(
Reg, InsertPoint,
MBB);
442 << RegToSlotIdx[
Reg] <<
" after statepoint\n");
444 if (EHPad && RC.tryRecordReload(
Reg, RegToSlotIdx[
Reg], EHPad)) {
445 auto EHPadInsertPoint =
446 EHPad->SkipPHIsLabelsAndDebug(EHPad->begin(),
Reg);
447 insertReloadBefore(
Reg, EHPadInsertPoint, EHPad);
456 MachineInstr *rewriteStatepoint() {
457 MachineInstr *NewMI =
458 MF.CreateMachineInstr(TII.get(MI.getOpcode()), MI.getDebugLoc(),
true);
459 MachineInstrBuilder MIB(MF, NewMI);
461 unsigned NumOps = MI.getNumOperands();
464 SmallVector<unsigned, 8> NewIndices;
465 unsigned NumDefs = MI.getNumDefs();
466 for (
unsigned I = 0;
I < NumDefs; ++
I) {
467 MachineOperand &DefMO = MI.getOperand(
I);
473 if (MI.getOperand(MI.findTiedOperandIdx(
I)).isUndef()) {
474 if (AllowGCPtrInCSR) {
476 MIB.addReg(
Reg, RegState::Define);
480 if (!AllowGCPtrInCSR) {
482 RegsToReload.push_back(
Reg);
484 if (isCalleeSaved(
Reg)) {
486 MIB.addReg(
Reg, RegState::Define);
489 RegsToReload.push_back(
Reg);
495 OpsToSpill.push_back(MI.getNumOperands());
496 unsigned CurOpIdx = 0;
498 for (
unsigned I = NumDefs;
I < MI.getNumOperands(); ++
I) {
499 MachineOperand &MO = MI.getOperand(
I);
500 if (
I == OpsToSpill[CurOpIdx]) {
501 int FI = RegToSlotIdx[MO.
getReg()];
502 MIB.addImm(StackMaps::IndirectMemRefOp);
506 MIB.addFrameIndex(FI);
512 if (AllowGCPtrInCSR && MI.isRegTiedToDefOperand(
I, &OldDef)) {
515 MIB->tieOperands(NewIndices[OldDef], MIB->getNumOperands() - 1);
519 assert(CurOpIdx == (OpsToSpill.size() - 1) &&
"Not all operands processed");
522 for (
auto It : RegToSlotIdx) {
531 MFI.getObjectAlign(FrameIndex));
536 MI.getParent()->insert(MI, NewMI);
538 LLVM_DEBUG(
dbgs() <<
"rewritten statepoint to : " << *NewMI <<
"\n");
539 MI.eraseFromParent();
544class StatepointProcessor {
546 const CodeGenOptions &Opts;
548 const TargetRegisterInfo &TRI;
549 FrameIndexesCache CacheFI;
550 RegReloadCache ReloadCache;
554 : Opts(Opts), MF(MF), TRI(*MF.getSubtarget().getRegisterInfo()),
555 CacheFI(Opts, MF.getFrameInfo(), TRI) {}
557 bool process(MachineInstr &
MI,
bool AllowGCPtrInCSR) {
558 StatepointOpers SO(&
MI);
561 if (Flags & (
uint64_t)StatepointFlags::DeoptLiveIn)
564 <<
MI.getParent()->getName() <<
" : process statepoint "
566 CallingConv::ID
CC = SO.getCallingConv();
567 const uint32_t *
Mask = TRI.getCallPreservedMask(MF,
CC);
568 StatepointState
SS(Opts,
MI, Mask, CacheFI, AllowGCPtrInCSR);
569 CacheFI.reset(
SS.getEHPad());
571 if (!
SS.findRegistersToSpill())
575 auto *NewStatepoint =
SS.rewriteStatepoint();
576 SS.insertReloads(NewStatepoint, ReloadCache);
588 for (MachineBasicBlock &BB : MF)
589 for (MachineInstr &
I : BB)
590 if (
I.getOpcode() == TargetOpcode::STATEPOINT)
593 if (Statepoints.
empty())
598 StatepointProcessor SPP(Opts, MF);
599 unsigned NumStatepoints = 0;
600 bool AllowGCPtrInCSR = Opts.fixup_allow_gcptr_in_csr;
601 for (MachineInstr *
I : Statepoints) {
603 if (Opts.fixup_max_csr_statepoints &&
604 NumStatepoints >= *Opts.fixup_max_csr_statepoints)
605 AllowGCPtrInCSR =
false;
606 Changed |= SPP.process(*
I, AllowGCPtrInCSR);
611bool FixupStatepointCallerSavedLegacy::runOnMachineFunction(
616 return FixupStatepointCallerSavedImpl().run(MF);
623 if (!FixupStatepointCallerSavedImpl().
run(MF))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Fixup Statepoint Caller static false unsigned getRegisterSize(const TargetRegisterInfo &TRI, Register Reg)
static Register performCopyPropagation(const CodeGenOptions &Opts, Register Reg, MachineBasicBlock::iterator &RI, bool &IsKill, const TargetInstrInfo &TII, const TargetRegisterInfo &TRI)
const HexagonInstrInfo * TII
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Represents analyses that only rely on functions' control flow.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
MachineInstr * remove(MachineInstr *I)
Remove the unbundled instruction from the instruction list without deleting it.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Function & getFunction()
Return the LLVM function that this machine code represents.
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
instr_iterator getInstrIterator() const
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI void setMemRefs(MachineFunction &MF, ArrayRef< MachineMemOperand * > MemRefs)
Assign this MachineInstr's memory reference descriptor list.
LLVM_ABI void addMemOperand(MachineFunction &MF, MachineMemOperand *MO)
Add a MachineMemOperand to the machine instruction.
Flags
Flags values. These may be or'd together.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Wrapper class representing virtual and physical registers.
constexpr unsigned id() const
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
bool contains(const T &V) const
Check if the SmallSet contains the given element.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
void push_back(const T &Elt)
MI-level Statepoint operands.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
A Use represents the edge between a Value definition and its users.
self_iterator getIterator()
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
NodeAddr< DefNode * > Def
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI char & FixupStatepointCallerSavedID
The pass fixups statepoint machine instruction to replace usage of caller saved registers with stack ...
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
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.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
MCRegisterClass TargetRegisterClass
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.