45#define DEBUG_TYPE "amdgpu-rewrite-agpr-copy-mfma"
48 "Controls which MFMA chains are rewritten to AGPR form");
53 "Number of MFMA instructions rewritten to use AGPR form");
58class AMDGPURewriteAGPRCopyMFMAImpl {
81 TRI(*ST.getRegisterInfo()),
MRI(MF.getRegInfo()), VRM(VRM), LRM(LRM),
82 LIS(LIS), LSS(LSS), RegClassInfo(RegClassInfo), MDT(MDT) {}
84 bool isRewriteCandidate(
const MachineInstr &
MI)
const {
93 MCRegister getAssignedAGPR(
Register VReg)
const {
94 MCRegister PhysReg = VRM.getPhys(VReg);
101 return TRI.isAGPRClass(AssignedRC) ? PhysReg : MCRegister();
104 bool tryReassigningMFMAChain(MachineInstr &
MFMA,
Register MFMAHintReg,
117 bool recomputeRegClassExceptRewritable(
118 Register Reg, SmallVectorImpl<MachineInstr *> &RewriteCandidates,
119 SmallSetVector<Register, 4> &RewriteRegs)
const;
121 bool tryFoldCopiesToAGPR(
Register VReg, MCRegister AssignedAGPR)
const;
122 bool tryFoldCopiesFromAGPR(
Register VReg, MCRegister AssignedAGPR)
const;
126 void replaceSpillWithCopyToVReg(MachineInstr &SpillMI,
int SpillFI,
133 SpillReferenceMap &Map)
const;
140 bool isLoadJointlyDominatedByStores(
141 const MachineInstr &LoadMI,
const LiveInterval &SlotLI,
142 const SmallPtrSetImpl<MachineBasicBlock *> &StoreFreeReachable)
const;
146 void eliminateSpillsOfReassignedVGPRs()
const;
151bool AMDGPURewriteAGPRCopyMFMAImpl::recomputeRegClassExceptRewritable(
157 while (!Worklist.
empty()) {
169 MachineInstr *
MI = MO.getParent();
175 if (isRewriteCandidate(*
MI)) {
177 const MCInstrDesc &AGPRDesc =
TII.get(AGPROp);
179 TII.getRegClass(AGPRDesc, MO.getOperandNo());
180 if (!
TRI.hasAGPRs(NewRC))
183 const MachineOperand *VDst =
184 TII.getNamedOperand(*
MI, AMDGPU::OpName::vdst);
185 const MachineOperand *
Src2 =
186 TII.getNamedOperand(*
MI, AMDGPU::OpName::src2);
187 for (
const MachineOperand *
Op : {VDst,
Src2}) {
195 if (OtherReg !=
Reg && RewriteRegs.
insert(OtherReg))
202 dbgs() <<
"Attempting to replace VGPR MFMA with AGPR version:"
221 unsigned OpNo = &MO - &
MI->getOperand(0);
222 NewRC =
MI->getRegClassConstraintEffect(OpNo, NewRC, &
TII, &
TRI);
223 if (!NewRC || NewRC == OldRC) {
225 <<
" cannot be reassigned to "
226 << (NewRC ?
TRI.getRegClassName(NewRC) :
"NULL")
236bool AMDGPURewriteAGPRCopyMFMAImpl::tryReassigningMFMAChain(
240 SmallVector<MachineInstr *, 4> RewriteCandidates = {&
MFMA};
241 SmallSetVector<Register, 4> RewriteRegs;
245 RewriteRegs.
insert(MFMAHintReg);
256 if (!recomputeRegClassExceptRewritable(MFMAHintReg, RewriteCandidates,
258 LLVM_DEBUG(
dbgs() <<
"Could not recompute the regclass of dst reg "
279 using RecoloringStack =
281 RecoloringStack TentativeReassignments;
283 for (
Register RewriteReg : RewriteRegs) {
285 TentativeReassignments.push_back({&LI, VRM.
getPhys(RewriteReg)});
290 !attemptReassignmentsToAGPR(RewriteRegs, PhysRegHint)) {
292 for (
auto [LI, OldAssign] : TentativeReassignments) {
295 LRM.
assign(*LI, OldAssign);
303 for (
Register InterferingReg : RewriteRegs) {
309 for (MachineInstr *RewriteCandidate : RewriteCandidates) {
311 RewriteCandidate->setDesc(
TII.get(NewMFMAOp));
312 ++NumMFMAsRewrittenToAGPR;
321bool AMDGPURewriteAGPRCopyMFMAImpl::attemptReassignmentsToAGPR(
322 SmallSetVector<Register, 4> &InterferingRegs,
MCPhysReg PrefPhysReg)
const {
327 for (
Register InterferingReg : InterferingRegs) {
328 LiveInterval &ReassignLI = LIS.
getInterval(InterferingReg);
332 MCPhysReg Assignable = AMDGPU::NoRegister;
333 if (EquivalentAGPRRegClass->
contains(PrefPhysReg) &&
343 Assignable = PrefPhysReg;
346 RegClassInfo.
getOrder(EquivalentAGPRRegClass);
358 <<
" to a free AGPR\n");
364 LRM.
assign(ReassignLI, Assignable);
376bool AMDGPURewriteAGPRCopyMFMAImpl::tryFoldCopiesToAGPR(
377 Register VReg, MCRegister AssignedAGPR)
const {
378 bool MadeChange =
false;
401 if (isRewriteCandidate(CopySrcDefMI) &&
402 tryReassigningMFMAChain(
403 CopySrcDefMI, CopySrcDefMI.getOperand(0).getReg(), AssignedAGPR))
418bool AMDGPURewriteAGPRCopyMFMAImpl::tryFoldCopiesFromAGPR(
419 Register VReg, MCRegister AssignedAGPR)
const {
420 bool MadeChange =
false;
429 if (!CopyUseMO.readsReg())
432 MachineInstr &CopyUseMI = *CopyUseMO.getParent();
433 if (isRewriteCandidate(CopyUseMI)) {
434 if (tryReassigningMFMAChain(CopyUseMI, CopyDstReg,
444void AMDGPURewriteAGPRCopyMFMAImpl::replaceSpillWithCopyToVReg(
445 MachineInstr &SpillMI,
int SpillFI,
Register VReg)
const {
448 MachineInstr *NewCopy;
462void AMDGPURewriteAGPRCopyMFMAImpl::collectSpillIndexUses(
465 SmallSet<int, 4> NeededFrameIndexes;
466 for (
const LiveInterval *LI : StackIntervals)
469 for (MachineBasicBlock &
MBB : MF) {
470 for (MachineInstr &
MI :
MBB) {
471 for (MachineOperand &MO :
MI.operands()) {
472 if (!MO.isFI() || !NeededFrameIndexes.
count(MO.getIndex()))
475 if (
TII.isVGPRSpill(
MI)) {
476 SmallVector<MachineInstr *, 4> &References =
Map[MO.getIndex()];
485 NeededFrameIndexes.
erase(MO.getIndex());
486 Map.erase(MO.getIndex());
492bool AMDGPURewriteAGPRCopyMFMAImpl::isLoadJointlyDominatedByStores(
493 const MachineInstr &LoadMI,
const LiveInterval &SlotLI,
494 const SmallPtrSetImpl<MachineBasicBlock *> &StoreFreeReachable)
const {
495 const MachineBasicBlock *LoadMBB = LoadMI.
getParent();
500 if (!StoreFreeReachable.
contains(LoadMBB))
513void AMDGPURewriteAGPRCopyMFMAImpl::eliminateSpillsOfReassignedVGPRs()
const {
518 MachineFrameInfo &MFI = MF.getFrameInfo();
521 StackIntervals.
reserve(NumSlots);
523 for (
auto &[Slot, LI] : LSS) {
528 if (
TRI.hasVGPRs(RC))
532 sort(StackIntervals, [](
const LiveInterval *
A,
const LiveInterval *
B) {
535 if (
A->weight() !=
B->weight())
536 return A->weight() >
B->weight();
538 if (
A->getSize() !=
B->getSize())
539 return A->getSize() >
B->getSize();
542 return A->reg().stackSlotIndex() <
B->reg().stackSlotIndex();
557 DenseMap<int, SmallVector<MachineInstr *, 4>> SpillSlotReferences;
558 collectSpillIndexUses(StackIntervals, SpillSlotReferences);
560 for (LiveInterval *LI : StackIntervals) {
562 auto SpillReferences = SpillSlotReferences.find(Slot);
563 if (SpillReferences == SpillSlotReferences.end())
568 SmallPtrSet<MachineBasicBlock *, 4> StoreBlocks;
569 for (MachineInstr *
MI : SpillReferences->second) {
571 StoreBlocks.
insert(
MI->getParent());
574 if (StoreBlocks.
empty()) {
576 <<
": no reachable stores\n");
582 MachineBasicBlock &EntryMBB = MF.front();
583 SmallPtrSet<MachineBasicBlock *, 16> StoreFreeReachable = {&EntryMBB};
586 while (!Worklist.
empty()) {
592 if (StoreFreeReachable.
insert(Succ).second)
598 if (!
llvm::all_of(SpillReferences->second, [&](
const MachineInstr *
MI) {
599 return !MI->mayLoad() ||
600 isLoadJointlyDominatedByStores(*MI, *LI, StoreFreeReachable);
604 <<
": some reachable load not jointly dominated by stores\n");
611 <<
" by reassigning\n");
633 for (MachineInstr *SpillMI : SpillReferences->second)
634 replaceSpillWithCopyToVReg(*SpillMI, Slot, NewVReg);
649 if (!SplitLIs.
empty()) {
650 dbgs() <<
"Split unspilled interval into " << (SplitLIs.
size() + 1)
655 LRM.
assign(NewLI, PhysReg);
656 for (LiveInterval *SplitLI : SplitLIs) {
658 LRM.
assign(*SplitLI, PhysReg);
669 "RegisterClassInfo misses a change to the reserved registers");
673 if (!
ST.hasGFX90AInsts())
679 [&](
MCPhysReg Reg) { return LRM.isPhysRegUsed(Reg); })) {
680 LLVM_DEBUG(
dbgs() <<
"skipping function that did not allocate AGPRs\n");
684 bool MadeChange =
false;
687 Register VReg = Register::index2VirtReg(
I);
688 MCRegister AssignedAGPR = getAssignedAGPR(VReg);
692 if (tryFoldCopiesToAGPR(VReg, AssignedAGPR))
694 if (tryFoldCopiesFromAGPR(VReg, AssignedAGPR))
702 eliminateSpillsOfReassignedVGPRs();
707class AMDGPURewriteAGPRCopyMFMALegacy :
public MachineFunctionPass {
711 AMDGPURewriteAGPRCopyMFMALegacy() : MachineFunctionPass(
ID) {}
715 StringRef getPassName()
const override {
716 return "AMDGPU Rewrite AGPR-Copy-MFMA";
719 void getAnalysisUsage(AnalysisUsage &AU)
const override {
724 AU.
addRequired<MachineRegisterClassInfoWrapperPass>();
742 "AMDGPU Rewrite AGPR-Copy-MFMA",
false,
false)
752char AMDGPURewriteAGPRCopyMFMALegacy::ID = 0;
755 AMDGPURewriteAGPRCopyMFMALegacy::ID;
757bool AMDGPURewriteAGPRCopyMFMALegacy::runOnMachineFunction(
759 if (skipFunction(MF.getFunction()))
762 auto &VRM = getAnalysis<VirtRegMapWrapperLegacy>().getVRM();
763 auto &LRM = getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM();
764 auto &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
765 auto &LSS = getAnalysis<LiveStacksWrapperLegacy>().getLS();
766 auto &RCI = getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
767 auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
768 AMDGPURewriteAGPRCopyMFMAImpl Impl(MF, VRM, LRM, LIS, LSS, RCI, MDT);
782 AMDGPURewriteAGPRCopyMFMAImpl Impl(MF, VRM, LRM, LIS, LSS, RCI, MDT);
787 .preserve<LiveStacksAnalysis>()
789 .preserve<SlotIndexesAnalysis>()
791 .preserve<LiveRegMatrixAnalysis>()
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
AMDGPU Rewrite AGPR Copy MFMA
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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")
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
AMD GCN specific subclass of TargetSubtarget.
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
MachineRegisterInfo & MRI
Interface definition for SIRegisterInfo.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represents analyses that only rely on functions' control flow.
static bool shouldExecute(CounterInfo &Counter)
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
LiveInterval & getInterval(Register Reg)
LLVM_ABI void splitSeparateComponents(LiveInterval &LI, SmallVectorImpl< LiveInterval * > &SplitLIs)
Split separate components in LiveInterval LI into separate intervals.
bool isLiveInToMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
bool liveAt(SlotIndex index) const
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
LLVM_ABI void unassign(const LiveInterval &VirtReg, bool ClearAllReferencingSegments=false)
Unassign VirtReg from its PhysReg.
@ IK_Free
No interference, go ahead and assign.
LLVM_ABI void assign(const LiveInterval &VirtReg, MCRegister PhysReg)
Assign VirtReg to PhysReg.
LLVM_ABI InterferenceKind checkInterference(const LiveInterval &VirtReg, MCRegister PhysReg)
Check for interference before assigning VirtReg to PhysReg.
unsigned getNumIntervals() const
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
iterator_range< succ_iterator > successors()
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
void RemoveStackObject(int ObjectIdx)
Remove or mark dead a statically sized stack object.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineBasicBlock * getParent() const
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< def_instr_iterator > def_instructions(Register Reg) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
iterator_range< reg_nodbg_iterator > reg_nodbg_operands(Register Reg) const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
LLVM_ABI bool hasCurrentReservedRegs() const
Whether the cached information was filtered by MRI's frozen reserved registers, i....
ArrayRef< MCPhysReg > getOrder(const TargetRegisterClass *RC) const
getOrder - Returns the preferred allocation order for RC.
Wrapper class representing virtual and physical registers.
int stackSlotIndex() const
Compute the frame index from a register value representing a stack slot.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
bool insert(const value_type &X)
Insert a new element into the SetVector.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
A SetVector that performs no allocations if smaller than a certain size.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void push_back(const T &Elt)
MCRegister getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
LLVM_READONLY int32_t getAGPRFormOp(uint32_t Opcode)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
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.
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.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
char & AMDGPURewriteAGPRCopyMFMALegacyID
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.
MCRegisterClass TargetRegisterClass