46#define DEBUG_TYPE "si-insert-waitcnts"
49 "Force emit s_waitcnt expcnt(0) instrs");
51 "Force emit s_waitcnt lgkmcnt(0) instrs");
53 "Force emit s_waitcnt vmcnt(0) instrs");
57 cl::desc(
"Force all waitcnt instrs to be emitted as "
58 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
62 "amdgpu-waitcnt-load-forcezero",
63 cl::desc(
"Force all waitcnt load counters to wait until 0"),
77 SAMPLE_CNT = NUM_NORMAL_INST_CNTS,
81 NUM_EXTENDED_INST_CNTS,
82 NUM_INST_CNTS = NUM_EXTENDED_INST_CNTS
96auto inst_counter_types(InstCounterType MaxCounter = NUM_INST_CNTS) {
97 return enum_seq(LOAD_CNT, MaxCounter);
115 TRACKINGID_RANGE_LEN = (1 << 16),
120 REGUNITS_END = REGUNITS_BEGIN + TRACKINGID_RANGE_LEN,
125 NUM_LDSDMA = TRACKINGID_RANGE_LEN,
126 LDSDMA_BEGIN = REGUNITS_END,
127 LDSDMA_END = LDSDMA_BEGIN + NUM_LDSDMA,
131static constexpr VMEMID toVMEMID(MCRegUnit RU) {
132 return static_cast<unsigned>(RU);
135struct HardwareLimits {
139 unsigned StorecntMax;
140 unsigned SamplecntMax;
146#define AMDGPU_DECLARE_WAIT_EVENTS(DECL) \
148 DECL(VMEM_SAMPLER_READ_ACCESS) \
149 DECL(VMEM_BVH_READ_ACCESS) \
150 DECL(GLOBAL_INV_ACCESS) \
151 DECL(VMEM_WRITE_ACCESS) \
152 DECL(SCRATCH_WRITE_ACCESS) \
162 DECL(EXP_POS_ACCESS) \
163 DECL(EXP_PARAM_ACCESS) \
168#define AMDGPU_EVENT_ENUM(Name) Name,
173#undef AMDGPU_EVENT_ENUM
175#define AMDGPU_EVENT_NAME(Name) #Name,
179#undef AMDGPU_EVENT_NAME
200static const unsigned instrsForExtendedCounterTypes[NUM_EXTENDED_INST_CNTS] = {
201 AMDGPU::S_WAIT_LOADCNT, AMDGPU::S_WAIT_DSCNT, AMDGPU::S_WAIT_EXPCNT,
202 AMDGPU::S_WAIT_STORECNT, AMDGPU::S_WAIT_SAMPLECNT, AMDGPU::S_WAIT_BVHCNT,
203 AMDGPU::S_WAIT_KMCNT, AMDGPU::S_WAIT_XCNT};
211static bool isNormalMode(InstCounterType MaxCounter) {
212 return MaxCounter == NUM_NORMAL_INST_CNTS;
217 assert(updateVMCntOnly(Inst));
219 return VMEM_NOSAMPLER;
233 return VMEM_NOSAMPLER;
245 return Wait.StoreCnt;
247 return Wait.SampleCnt;
260 unsigned &WC = getCounterRef(
Wait,
T);
261 WC = std::min(WC,
Count);
265 getCounterRef(
Wait,
T) = ~0
u;
269 return getCounterRef(
Wait,
T);
273InstCounterType eventCounter(
const unsigned *masks, WaitEventType
E) {
274 for (
auto T : inst_counter_types()) {
275 if (masks[
T] & (1 <<
E))
281class WaitcntBrackets;
289class WaitcntGenerator {
291 const GCNSubtarget *ST =
nullptr;
292 const SIInstrInfo *TII =
nullptr;
293 AMDGPU::IsaVersion IV;
294 InstCounterType MaxCounter;
298 WaitcntGenerator() =
default;
299 WaitcntGenerator(
const MachineFunction &MF, InstCounterType MaxCounter)
300 : ST(&MF.getSubtarget<GCNSubtarget>()), TII(ST->getInstrInfo()),
307 bool isOptNone()
const {
return OptNone; }
321 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
322 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
326 bool promoteSoftWaitCnt(MachineInstr *Waitcnt)
const;
330 virtual bool createNewWaitcnt(MachineBasicBlock &
Block,
332 AMDGPU::Waitcnt
Wait) = 0;
336 virtual const unsigned *getWaitEventMask()
const = 0;
340 virtual AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const = 0;
342 virtual ~WaitcntGenerator() =
default;
345 static constexpr unsigned
346 eventMask(std::initializer_list<WaitEventType> Events) {
348 for (
auto &
E : Events)
355class WaitcntGeneratorPreGFX12 :
public WaitcntGenerator {
357 using WaitcntGenerator::WaitcntGenerator;
360 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
361 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
364 bool createNewWaitcnt(MachineBasicBlock &
Block,
366 AMDGPU::Waitcnt
Wait)
override;
368 const unsigned *getWaitEventMask()
const override {
371 static const unsigned WaitEventMaskForInstPreGFX12[NUM_INST_CNTS] = {
373 {VMEM_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS}),
374 eventMask({SMEM_ACCESS, LDS_ACCESS, GDS_ACCESS, SQ_MESSAGE}),
375 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
376 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
377 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
383 return WaitEventMaskForInstPreGFX12;
386 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
389class WaitcntGeneratorGFX12Plus :
public WaitcntGenerator {
391 using WaitcntGenerator::WaitcntGenerator;
394 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
395 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
398 bool createNewWaitcnt(MachineBasicBlock &
Block,
400 AMDGPU::Waitcnt
Wait)
override;
402 const unsigned *getWaitEventMask()
const override {
405 static const unsigned WaitEventMaskForInstGFX12Plus[NUM_INST_CNTS] = {
406 eventMask({VMEM_ACCESS, GLOBAL_INV_ACCESS}),
407 eventMask({LDS_ACCESS, GDS_ACCESS}),
408 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
409 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
410 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
411 eventMask({VMEM_SAMPLER_READ_ACCESS}),
412 eventMask({VMEM_BVH_READ_ACCESS}),
413 eventMask({SMEM_ACCESS, SQ_MESSAGE, SCC_WRITE}),
414 eventMask({VMEM_GROUP, SMEM_GROUP})};
416 return WaitEventMaskForInstGFX12Plus;
419 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
422class SIInsertWaitcnts {
424 const GCNSubtarget *ST;
425 const SIInstrInfo *TII =
nullptr;
426 const SIRegisterInfo *TRI =
nullptr;
427 const MachineRegisterInfo *MRI =
nullptr;
428 InstCounterType SmemAccessCounter;
429 InstCounterType MaxCounter;
430 const unsigned *WaitEventMaskForInst;
433 DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
434 DenseMap<MachineBasicBlock *, bool> PreheadersToFlush;
435 MachineLoopInfo *MLI;
436 MachinePostDominatorTree *PDT;
440 std::unique_ptr<WaitcntBrackets> Incoming;
444 MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
446 bool ForceEmitWaitcnt[NUM_INST_CNTS];
451 WaitcntGeneratorPreGFX12 WCGPreGFX12;
452 WaitcntGeneratorGFX12Plus WCGGFX12Plus;
454 WaitcntGenerator *WCG =
nullptr;
458 DenseSet<MachineInstr *> ReleaseVGPRInsts;
460 HardwareLimits Limits;
463 SIInsertWaitcnts(MachineLoopInfo *MLI, MachinePostDominatorTree *PDT,
465 : MLI(MLI), PDT(PDT), AA(AA) {
466 (void)ForceExpCounter;
467 (void)ForceLgkmCounter;
468 (void)ForceVMCounter;
471 unsigned getWaitCountMax(InstCounterType
T)
const {
474 return Limits.LoadcntMax;
476 return Limits.DscntMax;
478 return Limits.ExpcntMax;
480 return Limits.StorecntMax;
482 return Limits.SamplecntMax;
484 return Limits.BvhcntMax;
486 return Limits.KmcntMax;
488 return Limits.XcntMax;
495 bool shouldFlushVmCnt(MachineLoop *
ML,
const WaitcntBrackets &Brackets);
496 bool isPreheaderToFlush(MachineBasicBlock &
MBB,
497 const WaitcntBrackets &ScoreBrackets);
498 bool isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const;
499 bool run(MachineFunction &MF);
501 void setForceEmitWaitcnt() {
507 ForceEmitWaitcnt[
EXP_CNT] =
true;
509 ForceEmitWaitcnt[
EXP_CNT] =
false;
514 ForceEmitWaitcnt[DS_CNT] =
true;
515 ForceEmitWaitcnt[KM_CNT] =
true;
517 ForceEmitWaitcnt[DS_CNT] =
false;
518 ForceEmitWaitcnt[KM_CNT] =
false;
523 ForceEmitWaitcnt[LOAD_CNT] =
true;
524 ForceEmitWaitcnt[SAMPLE_CNT] =
true;
525 ForceEmitWaitcnt[BVH_CNT] =
true;
527 ForceEmitWaitcnt[LOAD_CNT] =
false;
528 ForceEmitWaitcnt[SAMPLE_CNT] =
false;
529 ForceEmitWaitcnt[BVH_CNT] =
false;
536 WaitEventType getVmemWaitEventType(
const MachineInstr &Inst)
const {
539 case AMDGPU::GLOBAL_INV:
540 return GLOBAL_INV_ACCESS;
542 case AMDGPU::GLOBAL_WB:
543 case AMDGPU::GLOBAL_WBINV:
544 return VMEM_WRITE_ACCESS;
550 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
551 VMEM_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
560 if (TII->mayAccessScratch(Inst))
561 return SCRATCH_WRITE_ACCESS;
562 return VMEM_WRITE_ACCESS;
566 return VmemReadMapping[getVmemType(Inst)];
569 bool isVmemAccess(
const MachineInstr &
MI)
const;
570 bool generateWaitcntInstBefore(MachineInstr &
MI,
571 WaitcntBrackets &ScoreBrackets,
572 MachineInstr *OldWaitcntInstr,
574 bool generateWaitcnt(AMDGPU::Waitcnt
Wait,
576 MachineBasicBlock &
Block, WaitcntBrackets &ScoreBrackets,
577 MachineInstr *OldWaitcntInstr);
578 void updateEventWaitcntAfter(MachineInstr &Inst,
579 WaitcntBrackets *ScoreBrackets);
581 MachineBasicBlock *
Block)
const;
582 bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &
Block,
583 WaitcntBrackets &ScoreBrackets);
584 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &
Block,
585 WaitcntBrackets &ScoreBrackets);
596class WaitcntBrackets {
598 WaitcntBrackets(
const SIInsertWaitcnts *Context) : Context(Context) {
599 assert(Context->TRI->getNumRegUnits() < REGUNITS_END);
604 unsigned NumUnusedVmem = 0, NumUnusedSGPRs = 0;
605 for (
auto &[
ID, Val] : VMem) {
609 for (
auto &[
ID, Val] : SGPRs) {
614 if (NumUnusedVmem || NumUnusedSGPRs) {
615 errs() <<
"WaitcntBracket had unused entries at destruction time: "
616 << NumUnusedVmem <<
" VMem and " << NumUnusedSGPRs
617 <<
" SGPR unused entries\n";
623 bool isSmemCounter(InstCounterType
T)
const {
624 return T == Context->SmemAccessCounter ||
T == X_CNT;
627 unsigned getSgprScoresIdx(InstCounterType
T)
const {
628 assert(isSmemCounter(
T) &&
"Invalid SMEM counter");
629 return T == X_CNT ? 1 : 0;
632 unsigned getScoreLB(InstCounterType
T)
const {
637 unsigned getScoreUB(InstCounterType
T)
const {
642 unsigned getScoreRange(InstCounterType
T)
const {
643 return getScoreUB(
T) - getScoreLB(
T);
646 unsigned getSGPRScore(MCRegUnit RU, InstCounterType
T)
const {
647 auto It = SGPRs.find(RU);
648 return It != SGPRs.end() ? It->second.Scores[getSgprScoresIdx(
T)] : 0;
651 unsigned getVMemScore(VMEMID TID, InstCounterType
T)
const {
652 auto It = VMem.find(TID);
653 return It != VMem.end() ? It->second.Scores[
T] : 0;
658 bool counterOutOfOrder(InstCounterType
T)
const;
659 void simplifyWaitcnt(AMDGPU::Waitcnt &
Wait);
660 void simplifyWaitcnt(InstCounterType
T,
unsigned &
Count)
const;
661 bool hasRedundantXCntWithKmCnt(
const AMDGPU::Waitcnt &
Wait);
662 bool canOptimizeXCntWithLoadCnt(
const AMDGPU::Waitcnt &
Wait);
663 void simplifyXcnt(AMDGPU::Waitcnt &CheckWait, AMDGPU::Waitcnt &UpdateWait);
665 void determineWaitForPhysReg(InstCounterType
T,
MCPhysReg Reg,
666 AMDGPU::Waitcnt &
Wait)
const;
667 void determineWaitForLDSDMA(InstCounterType
T, VMEMID TID,
668 AMDGPU::Waitcnt &
Wait)
const;
669 void tryClearSCCWriteEvent(MachineInstr *Inst);
671 void applyWaitcnt(
const AMDGPU::Waitcnt &
Wait);
672 void applyWaitcnt(InstCounterType
T,
unsigned Count);
673 void updateByEvent(WaitEventType
E, MachineInstr &
MI);
675 unsigned hasPendingEvent()
const {
return PendingEvents; }
676 unsigned hasPendingEvent(WaitEventType
E)
const {
677 return PendingEvents & (1 <<
E);
679 unsigned hasPendingEvent(InstCounterType
T)
const {
680 unsigned HasPending = PendingEvents & Context->WaitEventMaskForInst[
T];
681 assert((HasPending != 0) == (getScoreRange(
T) != 0));
685 bool hasMixedPendingEvents(InstCounterType
T)
const {
686 unsigned Events = hasPendingEvent(
T);
688 return Events & (Events - 1);
691 bool hasPendingFlat()
const {
692 return ((LastFlat[DS_CNT] > ScoreLBs[DS_CNT] &&
693 LastFlat[DS_CNT] <= ScoreUBs[DS_CNT]) ||
694 (LastFlat[LOAD_CNT] > ScoreLBs[LOAD_CNT] &&
695 LastFlat[LOAD_CNT] <= ScoreUBs[LOAD_CNT]));
698 void setPendingFlat() {
699 LastFlat[LOAD_CNT] = ScoreUBs[LOAD_CNT];
700 LastFlat[DS_CNT] = ScoreUBs[DS_CNT];
703 bool hasPendingGDS()
const {
704 return LastGDS > ScoreLBs[DS_CNT] && LastGDS <= ScoreUBs[DS_CNT];
707 unsigned getPendingGDSWait()
const {
708 return std::min(getScoreUB(DS_CNT) - LastGDS,
709 Context->getWaitCountMax(DS_CNT) - 1);
712 void setPendingGDS() { LastGDS = ScoreUBs[DS_CNT]; }
716 bool hasOtherPendingVmemTypes(
MCPhysReg Reg, VmemType V)
const {
717 for (MCRegUnit RU : regunits(
Reg)) {
718 auto It = VMem.find(toVMEMID(RU));
719 if (It != VMem.end() && (It->second.VMEMTypes & ~(1 << V)))
726 for (MCRegUnit RU : regunits(
Reg)) {
727 if (
auto It = VMem.find(toVMEMID(RU)); It != VMem.end()) {
728 It->second.VMEMTypes = 0;
729 if (It->second.empty())
735 void setStateOnFunctionEntryOrReturn() {
736 setScoreUB(STORE_CNT,
737 getScoreUB(STORE_CNT) + Context->getWaitCountMax(STORE_CNT));
738 PendingEvents |= Context->WaitEventMaskForInst[STORE_CNT];
741 ArrayRef<const MachineInstr *> getLDSDMAStores()
const {
745 bool hasPointSampleAccel(
const MachineInstr &
MI)
const;
746 bool hasPointSamplePendingVmemTypes(
const MachineInstr &
MI,
749 void print(raw_ostream &)
const;
754 void purgeEmptyTrackingData();
764 void determineWaitForScore(InstCounterType
T,
unsigned Score,
765 AMDGPU::Waitcnt &
Wait)
const;
767 static bool mergeScore(
const MergeInfo &M,
unsigned &Score,
768 unsigned OtherScore);
771 assert(
Reg != AMDGPU::SCC &&
"Shouldn't be used on SCC");
772 if (!Context->TRI->isInAllocatableClass(
Reg))
774 const TargetRegisterClass *RC = Context->TRI->getPhysRegBaseClass(
Reg);
775 unsigned Size = Context->TRI->getRegSizeInBits(*RC);
776 if (
Size == 16 && Context->ST->hasD16Writes32BitVgpr())
777 Reg = Context->TRI->get32BitRegister(
Reg);
778 return Context->TRI->regunits(
Reg);
781 void setScoreLB(InstCounterType
T,
unsigned Val) {
786 void setScoreUB(InstCounterType
T,
unsigned Val) {
793 if (getScoreRange(EXP_CNT) > Context->getWaitCountMax(EXP_CNT))
794 ScoreLBs[
EXP_CNT] = ScoreUBs[
EXP_CNT] - Context->getWaitCountMax(EXP_CNT);
797 void setRegScore(
MCPhysReg Reg, InstCounterType
T,
unsigned Val) {
798 const SIRegisterInfo *
TRI = Context->TRI;
799 if (
Reg == AMDGPU::SCC) {
801 }
else if (
TRI->isVectorRegister(*Context->MRI,
Reg)) {
802 for (MCRegUnit RU : regunits(
Reg))
803 VMem[toVMEMID(RU)].Scores[
T] = Val;
804 }
else if (
TRI->isSGPRReg(*Context->MRI,
Reg)) {
805 auto STy = getSgprScoresIdx(
T);
806 for (MCRegUnit RU : regunits(
Reg))
807 SGPRs[RU].Scores[STy] = Val;
813 void setVMemScore(VMEMID TID, InstCounterType
T,
unsigned Val) {
814 VMem[TID].Scores[
T] = Val;
817 void setScoreByOperand(
const MachineOperand &
Op, InstCounterType CntTy,
820 const SIInsertWaitcnts *Context;
822 unsigned ScoreLBs[NUM_INST_CNTS] = {0};
823 unsigned ScoreUBs[NUM_INST_CNTS] = {0};
824 unsigned PendingEvents = 0;
826 unsigned LastFlat[NUM_INST_CNTS] = {0};
828 unsigned LastGDS = 0;
845 std::array<unsigned, NUM_INST_CNTS> Scores = {0};
847 unsigned VMEMTypes = 0;
850 return all_of(Scores, [](
unsigned K) {
return K == 0; }) && !VMEMTypes;
859 std::array<unsigned, 2> Scores = {0};
861 bool empty()
const {
return !Scores[0] && !Scores[1]; }
864 DenseMap<VMEMID, VMEMInfo> VMem;
865 DenseMap<MCRegUnit, SGPRInfo> SGPRs;
868 unsigned SCCScore = 0;
870 const MachineInstr *PendingSCCWrite =
nullptr;
874 SmallVector<const MachineInstr *> LDSDMAStores;
880 SIInsertWaitcntsLegacy() : MachineFunctionPass(ID) {}
882 bool runOnMachineFunction(MachineFunction &MF)
override;
884 StringRef getPassName()
const override {
885 return "SI insert wait instructions";
888 void getAnalysisUsage(AnalysisUsage &AU)
const override {
891 AU.
addRequired<MachinePostDominatorTreeWrapperPass>();
901 InstCounterType CntTy,
unsigned Score) {
902 setRegScore(
Op.getReg().asMCReg(), CntTy, Score);
910bool WaitcntBrackets::hasPointSampleAccel(
const MachineInstr &
MI)
const {
915 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
925bool WaitcntBrackets::hasPointSamplePendingVmemTypes(
const MachineInstr &
MI,
927 if (!hasPointSampleAccel(
MI))
930 return hasOtherPendingVmemTypes(
Reg, VMEM_NOSAMPLER);
933void WaitcntBrackets::updateByEvent(WaitEventType
E, MachineInstr &Inst) {
934 InstCounterType
T = eventCounter(
Context->WaitEventMaskForInst,
E);
937 unsigned UB = getScoreUB(
T);
938 unsigned CurrScore = UB + 1;
944 PendingEvents |= 1 <<
E;
945 setScoreUB(
T, CurrScore);
948 const MachineRegisterInfo *
MRI =
Context->MRI;
957 if (
const auto *AddrOp =
TII->getNamedOperand(Inst, AMDGPU::OpName::addr))
958 setScoreByOperand(*AddrOp, EXP_CNT, CurrScore);
961 if (
const auto *Data0 =
962 TII->getNamedOperand(Inst, AMDGPU::OpName::data0))
963 setScoreByOperand(*Data0, EXP_CNT, CurrScore);
964 if (
const auto *Data1 =
965 TII->getNamedOperand(Inst, AMDGPU::OpName::data1))
966 setScoreByOperand(*Data1, EXP_CNT, CurrScore);
969 Inst.
getOpcode() != AMDGPU::DS_CONSUME &&
970 Inst.
getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
971 for (
const MachineOperand &
Op : Inst.
all_uses()) {
972 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
973 setScoreByOperand(
Op, EXP_CNT, CurrScore);
976 }
else if (
TII->isFLAT(Inst)) {
978 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
981 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
984 }
else if (
TII->isMIMG(Inst)) {
986 setScoreByOperand(Inst.
getOperand(0), EXP_CNT, CurrScore);
988 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
991 }
else if (
TII->isMTBUF(Inst)) {
993 setScoreByOperand(Inst.
getOperand(0), EXP_CNT, CurrScore);
994 }
else if (
TII->isMUBUF(Inst)) {
996 setScoreByOperand(Inst.
getOperand(0), EXP_CNT, CurrScore);
998 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
1001 }
else if (
TII->isLDSDIR(Inst)) {
1003 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::vdst),
1004 EXP_CNT, CurrScore);
1006 if (
TII->isEXP(Inst)) {
1011 for (MachineOperand &DefMO : Inst.
all_defs()) {
1012 if (
TRI->isVGPR(*
MRI, DefMO.getReg())) {
1013 setScoreByOperand(DefMO, EXP_CNT, CurrScore);
1017 for (
const MachineOperand &
Op : Inst.
all_uses()) {
1018 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
1019 setScoreByOperand(
Op, EXP_CNT, CurrScore);
1022 }
else if (
T == X_CNT) {
1023 WaitEventType OtherEvent =
E == SMEM_GROUP ? VMEM_GROUP : SMEM_GROUP;
1024 if (PendingEvents & (1 << OtherEvent)) {
1029 setScoreLB(
T, getScoreUB(
T) - 1);
1030 PendingEvents &= ~(1 << OtherEvent);
1032 for (
const MachineOperand &
Op : Inst.
all_uses())
1033 setScoreByOperand(
Op,
T, CurrScore);
1044 for (
const MachineOperand &
Op : Inst.
defs()) {
1045 if (
T == LOAD_CNT ||
T == SAMPLE_CNT ||
T == BVH_CNT) {
1046 if (!
TRI->isVectorRegister(*
MRI,
Op.getReg()))
1048 if (updateVMCntOnly(Inst)) {
1053 VmemType
V = getVmemType(Inst);
1054 unsigned char TypesMask = 1 <<
V;
1057 if (hasPointSampleAccel(Inst))
1058 TypesMask |= 1 << VMEM_NOSAMPLER;
1059 for (MCRegUnit RU : regunits(
Op.getReg().asMCReg()))
1060 VMem[toVMEMID(RU)].VMEMTypes |= TypesMask;
1063 setScoreByOperand(
Op,
T, CurrScore);
1066 (
TII->isDS(Inst) ||
TII->mayWriteLDSThroughDMA(Inst))) {
1075 if (!MemOp->isStore() ||
1080 auto AAI = MemOp->getAAInfo();
1086 if (!AAI || !AAI.Scope)
1088 for (
unsigned I = 0,
E = LDSDMAStores.
size();
I !=
E && !Slot; ++
I) {
1089 for (
const auto *MemOp : LDSDMAStores[
I]->memoperands()) {
1090 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1105 setVMemScore(LDSDMA_BEGIN,
T, CurrScore);
1106 if (Slot && Slot < NUM_LDSDMA)
1107 setVMemScore(LDSDMA_BEGIN + Slot,
T, CurrScore);
1111 setRegScore(AMDGPU::SCC,
T, CurrScore);
1112 PendingSCCWrite = &Inst;
1117void WaitcntBrackets::print(raw_ostream &OS)
const {
1121 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
1122 unsigned SR = getScoreRange(
T);
1126 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"LOAD" :
"VM") <<
"_CNT("
1130 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"DS" :
"LGKM") <<
"_CNT("
1134 OS <<
" EXP_CNT(" << SR <<
"):";
1137 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"STORE" :
"VS") <<
"_CNT("
1141 OS <<
" SAMPLE_CNT(" << SR <<
"):";
1144 OS <<
" BVH_CNT(" << SR <<
"):";
1147 OS <<
" KM_CNT(" << SR <<
"):";
1150 OS <<
" X_CNT(" << SR <<
"):";
1153 OS <<
" UNKNOWN(" << SR <<
"):";
1159 unsigned LB = getScoreLB(
T);
1162 sort(SortedVMEMIDs);
1164 for (
auto ID : SortedVMEMIDs) {
1165 unsigned RegScore = VMem.at(
ID).Scores[
T];
1168 unsigned RelScore = RegScore - LB - 1;
1169 if (
ID < REGUNITS_END) {
1170 OS <<
' ' << RelScore <<
":vRU" <<
ID;
1172 assert(
ID >= LDSDMA_BEGIN &&
ID < LDSDMA_END &&
1173 "Unhandled/unexpected ID value!");
1174 OS <<
' ' << RelScore <<
":LDSDMA" <<
ID;
1179 if (isSmemCounter(
T)) {
1181 sort(SortedSMEMIDs);
1182 for (
auto ID : SortedSMEMIDs) {
1183 unsigned RegScore = SGPRs.at(
ID).Scores[getSgprScoresIdx(
T)];
1186 unsigned RelScore = RegScore - LB - 1;
1187 OS <<
' ' << RelScore <<
":sRU" <<
static_cast<unsigned>(
ID);
1191 if (
T == KM_CNT && SCCScore > 0)
1192 OS <<
' ' << SCCScore <<
":scc";
1197 OS <<
"Pending Events: ";
1198 if (hasPendingEvent()) {
1200 for (
unsigned I = 0;
I != NUM_WAIT_EVENTS; ++
I) {
1201 if (hasPendingEvent((WaitEventType)
I)) {
1202 OS <<
LS << WaitEventTypeName[
I];
1215void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &
Wait) {
1216 simplifyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1217 simplifyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1218 simplifyWaitcnt(DS_CNT,
Wait.DsCnt);
1219 simplifyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1220 simplifyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1221 simplifyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1222 simplifyWaitcnt(KM_CNT,
Wait.KmCnt);
1226void WaitcntBrackets::simplifyWaitcnt(InstCounterType
T,
1227 unsigned &
Count)
const {
1231 if (
Count >= getScoreRange(
T))
1235void WaitcntBrackets::purgeEmptyTrackingData() {
1246void WaitcntBrackets::determineWaitForScore(InstCounterType
T,
1247 unsigned ScoreToWait,
1248 AMDGPU::Waitcnt &
Wait)
const {
1249 const unsigned LB = getScoreLB(
T);
1250 const unsigned UB = getScoreUB(
T);
1253 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1254 if ((
T == LOAD_CNT ||
T == DS_CNT) && hasPendingFlat() &&
1255 !
Context->ST->hasFlatLgkmVMemCountInOrder()) {
1259 addWait(
Wait,
T, 0);
1260 }
else if (counterOutOfOrder(
T)) {
1264 addWait(
Wait,
T, 0);
1268 unsigned NeededWait =
1269 std::min(UB - ScoreToWait,
Context->getWaitCountMax(
T) - 1);
1270 addWait(
Wait,
T, NeededWait);
1275void WaitcntBrackets::determineWaitForPhysReg(InstCounterType
T,
MCPhysReg Reg,
1276 AMDGPU::Waitcnt &
Wait)
const {
1277 if (
Reg == AMDGPU::SCC) {
1278 determineWaitForScore(
T, SCCScore,
Wait);
1281 for (MCRegUnit RU : regunits(
Reg))
1282 determineWaitForScore(
1283 T, IsVGPR ? getVMemScore(toVMEMID(RU),
T) : getSGPRScore(RU,
T),
1288void WaitcntBrackets::determineWaitForLDSDMA(InstCounterType
T, VMEMID TID,
1289 AMDGPU::Waitcnt &
Wait)
const {
1290 assert(TID >= LDSDMA_BEGIN && TID < LDSDMA_END);
1291 determineWaitForScore(
T, getVMemScore(TID,
T),
Wait);
1294void WaitcntBrackets::tryClearSCCWriteEvent(MachineInstr *Inst) {
1297 if (PendingSCCWrite &&
1298 PendingSCCWrite->
getOpcode() == AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM &&
1300 unsigned SCC_WRITE_PendingEvent = 1 << SCC_WRITE;
1302 if ((PendingEvents &
Context->WaitEventMaskForInst[KM_CNT]) ==
1303 SCC_WRITE_PendingEvent) {
1304 setScoreLB(KM_CNT, getScoreUB(KM_CNT));
1307 PendingEvents &= ~SCC_WRITE_PendingEvent;
1308 PendingSCCWrite =
nullptr;
1312void WaitcntBrackets::applyWaitcnt(
const AMDGPU::Waitcnt &
Wait) {
1313 applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1314 applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1315 applyWaitcnt(DS_CNT,
Wait.DsCnt);
1316 applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1317 applyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1318 applyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1319 applyWaitcnt(KM_CNT,
Wait.KmCnt);
1320 applyWaitcnt(X_CNT,
Wait.XCnt);
1323void WaitcntBrackets::applyWaitcnt(InstCounterType
T,
unsigned Count) {
1324 const unsigned UB = getScoreUB(
T);
1328 if (counterOutOfOrder(
T))
1330 setScoreLB(
T, std::max(getScoreLB(
T), UB -
Count));
1333 PendingEvents &= ~Context->WaitEventMaskForInst[
T];
1337bool WaitcntBrackets::hasRedundantXCntWithKmCnt(
const AMDGPU::Waitcnt &
Wait) {
1341 return Wait.KmCnt == 0 && hasPendingEvent(SMEM_GROUP);
1344bool WaitcntBrackets::canOptimizeXCntWithLoadCnt(
const AMDGPU::Waitcnt &
Wait) {
1348 return Wait.LoadCnt != ~0
u && hasPendingEvent(VMEM_GROUP) &&
1349 !hasPendingEvent(STORE_CNT);
1352void WaitcntBrackets::simplifyXcnt(AMDGPU::Waitcnt &CheckWait,
1353 AMDGPU::Waitcnt &UpdateWait) {
1359 if (hasRedundantXCntWithKmCnt(CheckWait)) {
1360 if (!hasMixedPendingEvents(X_CNT)) {
1361 applyWaitcnt(X_CNT, 0);
1363 PendingEvents &= ~(1 << SMEM_GROUP);
1365 }
else if (canOptimizeXCntWithLoadCnt(CheckWait)) {
1366 if (!hasMixedPendingEvents(X_CNT)) {
1367 applyWaitcnt(X_CNT, std::min(CheckWait.
XCnt, CheckWait.
LoadCnt));
1368 }
else if (CheckWait.
LoadCnt == 0) {
1369 PendingEvents &= ~(1 << VMEM_GROUP);
1372 simplifyWaitcnt(X_CNT, UpdateWait.
XCnt);
1377bool WaitcntBrackets::counterOutOfOrder(InstCounterType
T)
const {
1379 if ((
T ==
Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1380 (
T == X_CNT && hasPendingEvent(SMEM_GROUP)))
1386 if (
T == LOAD_CNT) {
1387 unsigned Events = hasPendingEvent(
T);
1390 Events &= ~(1 << GLOBAL_INV_ACCESS);
1393 return Events & (Events - 1);
1396 return hasMixedPendingEvents(
T);
1406char SIInsertWaitcntsLegacy::
ID = 0;
1411 return new SIInsertWaitcntsLegacy();
1416 int OpIdx = AMDGPU::getNamedOperandIdx(
MI.getOpcode(),
OpName);
1421 if (NewEnc == MO.
getImm())
1432 case AMDGPU::S_WAIT_LOADCNT:
1434 case AMDGPU::S_WAIT_EXPCNT:
1436 case AMDGPU::S_WAIT_STORECNT:
1438 case AMDGPU::S_WAIT_SAMPLECNT:
1440 case AMDGPU::S_WAIT_BVHCNT:
1442 case AMDGPU::S_WAIT_DSCNT:
1444 case AMDGPU::S_WAIT_KMCNT:
1446 case AMDGPU::S_WAIT_XCNT:
1453bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt)
const {
1467bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1468 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1471 assert(isNormalMode(MaxCounter));
1474 MachineInstr *WaitcntInstr =
nullptr;
1475 MachineInstr *WaitcntVsCntInstr =
nullptr;
1478 dbgs() <<
"PreGFX12::applyPreexistingWaitcnt at: ";
1480 dbgs() <<
"end of block\n";
1488 if (
II.isMetaInstruction()) {
1494 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1498 if (Opcode == AMDGPU::S_WAITCNT) {
1499 unsigned IEnc =
II.getOperand(0).getImm();
1502 ScoreBrackets.simplifyWaitcnt(OldWait);
1506 if (WaitcntInstr || (!
Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1507 II.eraseFromParent();
1511 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1514 <<
"Before: " <<
Wait <<
'\n';);
1515 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, LDSDMA_BEGIN,
Wait);
1524 II.eraseFromParent();
1526 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1527 assert(
II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1530 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1532 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1533 Wait.StoreCnt = std::min(
Wait.StoreCnt, OldVSCnt);
1535 if (WaitcntVsCntInstr || (!
Wait.hasWaitStoreCnt() && TrySimplify)) {
1536 II.eraseFromParent();
1539 WaitcntVsCntInstr = &
II;
1546 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1548 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1549 ScoreBrackets.applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1550 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1557 <<
"applied pre-existing waitcnt\n"
1558 <<
"New Instr at block end: " << *WaitcntInstr <<
'\n'
1559 :
dbgs() <<
"applied pre-existing waitcnt\n"
1560 <<
"Old Instr: " << *It
1561 <<
"New Instr: " << *WaitcntInstr <<
'\n');
1564 if (WaitcntVsCntInstr) {
1566 AMDGPU::OpName::simm16,
Wait.StoreCnt);
1567 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1569 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1570 Wait.StoreCnt = ~0
u;
1573 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1574 <<
"New Instr at block end: " << *WaitcntVsCntInstr
1576 :
dbgs() <<
"applied pre-existing waitcnt\n"
1577 <<
"Old Instr: " << *It
1578 <<
"New Instr: " << *WaitcntVsCntInstr <<
'\n');
1586bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1588 AMDGPU::Waitcnt
Wait) {
1590 assert(isNormalMode(MaxCounter));
1597 if (
Wait.hasWaitExceptStoreCnt()) {
1599 [[maybe_unused]]
auto SWaitInst =
1604 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1605 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1608 if (
Wait.hasWaitStoreCnt()) {
1611 [[maybe_unused]]
auto SWaitInst =
1618 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1619 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1626WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1627 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt &&
ST->hasVscnt() ? 0 : ~0u);
1631WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1632 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
1640bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
1641 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1644 assert(!isNormalMode(MaxCounter));
1647 MachineInstr *CombinedLoadDsCntInstr =
nullptr;
1648 MachineInstr *CombinedStoreDsCntInstr =
nullptr;
1649 MachineInstr *WaitInstrs[NUM_EXTENDED_INST_CNTS] = {};
1652 dbgs() <<
"GFX12Plus::applyPreexistingWaitcnt at: ";
1654 dbgs() <<
"end of block\n";
1662 if (
II.isMetaInstruction()) {
1667 MachineInstr **UpdatableInstr;
1673 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1677 if (Opcode == AMDGPU::S_WAITCNT)
1680 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
1682 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1685 ScoreBrackets.simplifyWaitcnt(OldWait);
1687 UpdatableInstr = &CombinedLoadDsCntInstr;
1688 }
else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
1690 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1693 ScoreBrackets.simplifyWaitcnt(OldWait);
1695 UpdatableInstr = &CombinedStoreDsCntInstr;
1696 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1699 II.eraseFromParent();
1705 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1707 ScoreBrackets.simplifyWaitcnt(CT.value(), OldCnt);
1708 addWait(
Wait, CT.value(), OldCnt);
1709 UpdatableInstr = &WaitInstrs[CT.value()];
1713 if (!*UpdatableInstr) {
1714 *UpdatableInstr = &
II;
1716 II.eraseFromParent();
1722 AMDGPU::Waitcnt PreCombine =
Wait;
1723 if (CombinedLoadDsCntInstr) {
1731 if (
Wait.LoadCnt != ~0u &&
Wait.DsCnt != ~0u) {
1734 AMDGPU::OpName::simm16, NewEnc);
1735 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
1736 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1737 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1742 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1743 <<
"New Instr at block end: "
1744 << *CombinedLoadDsCntInstr <<
'\n'
1745 :
dbgs() <<
"applied pre-existing waitcnt\n"
1746 <<
"Old Instr: " << *It <<
"New Instr: "
1747 << *CombinedLoadDsCntInstr <<
'\n');
1754 if (CombinedStoreDsCntInstr) {
1756 if (
Wait.StoreCnt != ~0u &&
Wait.DsCnt != ~0u) {
1759 AMDGPU::OpName::simm16, NewEnc);
1760 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
1761 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1762 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1763 Wait.StoreCnt = ~0
u;
1767 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1768 <<
"New Instr at block end: "
1769 << *CombinedStoreDsCntInstr <<
'\n'
1770 :
dbgs() <<
"applied pre-existing waitcnt\n"
1771 <<
"Old Instr: " << *It <<
"New Instr: "
1772 << *CombinedStoreDsCntInstr <<
'\n');
1785 if (
Wait.DsCnt != ~0u) {
1794 if (
Wait.LoadCnt != ~0u) {
1795 WaitsToErase.
push_back(&WaitInstrs[LOAD_CNT]);
1796 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1797 }
else if (
Wait.StoreCnt != ~0u) {
1798 WaitsToErase.
push_back(&WaitInstrs[STORE_CNT]);
1799 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1802 for (MachineInstr **WI : WaitsToErase) {
1806 (*WI)->eraseFromParent();
1812 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1813 if ((CT == KM_CNT && ScoreBrackets.hasRedundantXCntWithKmCnt(PreCombine)) ||
1815 ScoreBrackets.canOptimizeXCntWithLoadCnt(PreCombine))) {
1818 ScoreBrackets.simplifyXcnt(PreCombine,
Wait);
1820 if (!WaitInstrs[CT])
1823 unsigned NewCnt = getWait(
Wait, CT);
1824 if (NewCnt != ~0u) {
1826 AMDGPU::OpName::simm16, NewCnt);
1827 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
1829 ScoreBrackets.applyWaitcnt(CT, NewCnt);
1830 setNoWait(
Wait, CT);
1833 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1834 <<
"New Instr at block end: " << *WaitInstrs[CT]
1836 :
dbgs() <<
"applied pre-existing waitcnt\n"
1837 <<
"Old Instr: " << *It
1838 <<
"New Instr: " << *WaitInstrs[CT] <<
'\n');
1849bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
1851 AMDGPU::Waitcnt
Wait) {
1853 assert(!isNormalMode(MaxCounter));
1859 if (
Wait.DsCnt != ~0u) {
1860 MachineInstr *SWaitInst =
nullptr;
1862 if (
Wait.LoadCnt != ~0u) {
1870 }
else if (
Wait.StoreCnt != ~0u) {
1877 Wait.StoreCnt = ~0
u;
1885 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1886 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1893 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1898 [[maybe_unused]]
auto SWaitInst =
1905 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1906 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1937bool SIInsertWaitcnts::generateWaitcntInstBefore(MachineInstr &
MI,
1938 WaitcntBrackets &ScoreBrackets,
1939 MachineInstr *OldWaitcntInstr,
1941 setForceEmitWaitcnt();
1945 AMDGPU::Waitcnt
Wait;
1946 const unsigned Opc =
MI.getOpcode();
1952 if (
Opc == AMDGPU::BUFFER_WBINVL1 ||
Opc == AMDGPU::BUFFER_WBINVL1_SC ||
1953 Opc == AMDGPU::BUFFER_WBINVL1_VOL ||
Opc == AMDGPU::BUFFER_GL0_INV ||
1954 Opc == AMDGPU::BUFFER_GL1_INV) {
1961 if (
Opc == AMDGPU::SI_RETURN_TO_EPILOG ||
Opc == AMDGPU::SI_RETURN ||
1962 Opc == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1963 Opc == AMDGPU::S_SETPC_B64_return ||
1965 AMDGPU::Waitcnt AllZeroWait =
1966 WCG->getAllZeroWaitcnt(
false);
1971 if (
ST->hasExtendedWaitCounts() &&
1972 !ScoreBrackets.hasPendingEvent(VMEM_ACCESS))
1984 else if (
Opc == AMDGPU::S_ENDPGM ||
Opc == AMDGPU::S_ENDPGM_SAVED) {
1985 if (!WCG->isOptNone() &&
1986 (
MI.getMF()->getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() ||
1987 (
ST->getGeneration() >= AMDGPUSubtarget::GFX11 &&
1988 ScoreBrackets.getScoreRange(STORE_CNT) != 0 &&
1989 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS))))
1993 else if ((
Opc == AMDGPU::S_SENDMSG ||
Opc == AMDGPU::S_SENDMSGHALT) &&
1994 ST->hasLegacyGeometry() &&
2005 if (
MI.modifiesRegister(AMDGPU::EXEC,
TRI)) {
2008 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
2009 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
2010 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
2011 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
2018 if (
TII->isAlwaysGDS(
Opc) && ScoreBrackets.hasPendingGDS())
2019 addWait(
Wait, DS_CNT, ScoreBrackets.getPendingGDSWait());
2025 Wait = AMDGPU::Waitcnt();
2027 const auto &CallAddrOp = *
TII->getNamedOperand(
MI, AMDGPU::OpName::src0);
2028 if (CallAddrOp.isReg()) {
2029 ScoreBrackets.determineWaitForPhysReg(
2030 SmemAccessCounter, CallAddrOp.getReg().asMCReg(),
Wait);
2032 if (
const auto *RtnAddrOp =
2033 TII->getNamedOperand(
MI, AMDGPU::OpName::dst)) {
2034 ScoreBrackets.determineWaitForPhysReg(
2035 SmemAccessCounter, RtnAddrOp->getReg().asMCReg(),
Wait);
2038 }
else if (
Opc == AMDGPU::S_BARRIER_WAIT) {
2039 ScoreBrackets.tryClearSCCWriteEvent(&
MI);
2055 for (
const MachineMemOperand *Memop :
MI.memoperands()) {
2056 const Value *Ptr = Memop->getValue();
2057 if (Memop->isStore()) {
2058 if (
auto It = SLoadAddresses.
find(Ptr); It != SLoadAddresses.
end()) {
2059 addWait(
Wait, SmemAccessCounter, 0);
2061 SLoadAddresses.
erase(It);
2064 unsigned AS = Memop->getAddrSpace();
2068 if (
TII->mayWriteLDSThroughDMA(
MI))
2072 unsigned TID = LDSDMA_BEGIN;
2073 if (Ptr && Memop->getAAInfo()) {
2074 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
2075 for (
unsigned I = 0,
E = LDSDMAStores.size();
I !=
E; ++
I) {
2076 if (
MI.mayAlias(AA, *LDSDMAStores[
I],
true)) {
2077 if ((
I + 1) >= NUM_LDSDMA) {
2080 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID,
Wait);
2084 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID +
I + 1,
Wait);
2088 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID,
Wait);
2090 if (Memop->isStore()) {
2091 ScoreBrackets.determineWaitForLDSDMA(EXP_CNT, TID,
Wait);
2096 for (
const MachineOperand &
Op :
MI.operands()) {
2101 if (
Op.isTied() &&
Op.isUse() &&
TII->doesNotReadTiedSource(
MI))
2106 const bool IsVGPR =
TRI->isVectorRegister(*
MRI,
Op.getReg());
2113 if (
Op.isImplicit() &&
MI.mayLoadOrStore())
2122 if (
Op.isUse() || !updateVMCntOnly(
MI) ||
2123 ScoreBrackets.hasOtherPendingVmemTypes(
Reg, getVmemType(
MI)) ||
2124 ScoreBrackets.hasPointSamplePendingVmemTypes(
MI,
Reg) ||
2125 !
ST->hasVmemWriteVgprInOrder()) {
2126 ScoreBrackets.determineWaitForPhysReg(LOAD_CNT,
Reg,
Wait);
2127 ScoreBrackets.determineWaitForPhysReg(SAMPLE_CNT,
Reg,
Wait);
2128 ScoreBrackets.determineWaitForPhysReg(BVH_CNT,
Reg,
Wait);
2129 ScoreBrackets.clearVgprVmemTypes(
Reg);
2132 if (
Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2133 ScoreBrackets.determineWaitForPhysReg(EXP_CNT,
Reg,
Wait);
2135 ScoreBrackets.determineWaitForPhysReg(DS_CNT,
Reg,
Wait);
2136 }
else if (
Op.getReg() == AMDGPU::SCC) {
2137 ScoreBrackets.determineWaitForPhysReg(KM_CNT,
Reg,
Wait);
2139 ScoreBrackets.determineWaitForPhysReg(SmemAccessCounter,
Reg,
Wait);
2142 if (
ST->hasWaitXCnt() &&
Op.isDef())
2143 ScoreBrackets.determineWaitForPhysReg(X_CNT,
Reg,
Wait);
2160 if (
Opc == AMDGPU::S_BARRIER && !
ST->hasAutoWaitcntBeforeBarrier() &&
2161 !
ST->supportsBackOffBarrier()) {
2162 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
true));
2169 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2174 ScoreBrackets.simplifyWaitcnt(
Wait);
2179 if (
Wait.XCnt != ~0u && isVmemAccess(
MI)) {
2180 ScoreBrackets.applyWaitcnt(X_CNT,
Wait.XCnt);
2187 Wait = WCG->getAllZeroWaitcnt(
false);
2189 if (ForceEmitWaitcnt[LOAD_CNT])
2191 if (ForceEmitWaitcnt[EXP_CNT])
2193 if (ForceEmitWaitcnt[DS_CNT])
2195 if (ForceEmitWaitcnt[SAMPLE_CNT])
2197 if (ForceEmitWaitcnt[BVH_CNT])
2199 if (ForceEmitWaitcnt[KM_CNT])
2201 if (ForceEmitWaitcnt[X_CNT])
2205 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2207 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2209 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2216 return generateWaitcnt(
Wait,
MI.getIterator(), *
MI.getParent(), ScoreBrackets,
2220bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt
Wait,
2222 MachineBasicBlock &
Block,
2223 WaitcntBrackets &ScoreBrackets,
2224 MachineInstr *OldWaitcntInstr) {
2227 if (OldWaitcntInstr)
2231 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr,
Wait, It);
2235 ScoreBrackets.applyWaitcnt(
Wait);
2238 if (
Wait.ExpCnt != ~0u && It !=
Block.instr_end() &&
2240 MachineOperand *WaitExp =
2241 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
2249 <<
"Update Instr: " << *It);
2252 if (WCG->createNewWaitcnt(
Block, It,
Wait))
2258bool SIInsertWaitcnts::isVmemAccess(
const MachineInstr &
MI)
const {
2259 return (
TII->isFLAT(
MI) &&
TII->mayAccessVMEMThroughFlat(
MI)) ||
2266 MachineBasicBlock *
Block)
const {
2267 auto BlockEnd =
Block->getParent()->end();
2268 auto BlockIter =
Block->getIterator();
2272 if (++BlockIter != BlockEnd) {
2273 It = BlockIter->instr_begin();
2280 if (!It->isMetaInstruction())
2288 return It->getOpcode() == AMDGPU::S_ENDPGM;
2292bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2293 MachineBasicBlock &
Block,
2294 WaitcntBrackets &ScoreBrackets) {
2295 AMDGPU::Waitcnt
Wait;
2296 bool NeedsEndPGMCheck =
false;
2304 NeedsEndPGMCheck =
true;
2307 ScoreBrackets.simplifyWaitcnt(
Wait);
2310 bool Result = generateWaitcnt(
Wait, SuccessorIt,
Block, ScoreBrackets,
2313 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &
Block)) {
2321void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2322 WaitcntBrackets *ScoreBrackets) {
2330 bool IsVMEMAccess =
false;
2331 bool IsSMEMAccess =
false;
2332 if (
TII->isDS(Inst) &&
TII->usesLGKM_CNT(Inst)) {
2334 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2335 ScoreBrackets->updateByEvent(GDS_ACCESS, Inst);
2336 ScoreBrackets->updateByEvent(GDS_GPR_LOCK, Inst);
2337 ScoreBrackets->setPendingGDS();
2339 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2341 }
else if (
TII->isFLAT(Inst)) {
2343 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2349 int FlatASCount = 0;
2351 if (
TII->mayAccessVMEMThroughFlat(Inst)) {
2353 IsVMEMAccess =
true;
2354 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2357 if (
TII->mayAccessLDSThroughFlat(Inst)) {
2359 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2368 ScoreBrackets->setPendingFlat();
2371 IsVMEMAccess =
true;
2372 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2374 if (
ST->vmemWriteNeedsExpWaitcnt() &&
2376 ScoreBrackets->updateByEvent(VMW_GPR_LOCK, Inst);
2378 }
else if (
TII->isSMRD(Inst)) {
2379 IsSMEMAccess =
true;
2380 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2381 }
else if (Inst.
isCall()) {
2384 ScoreBrackets->applyWaitcnt(
2385 WCG->getAllZeroWaitcnt(
false));
2386 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2389 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
2392 ScoreBrackets->updateByEvent(EXP_LDS_ACCESS, Inst);
2393 }
else if (
TII->isVINTERP(Inst)) {
2394 int64_t
Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2395 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2397 unsigned Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2399 ScoreBrackets->updateByEvent(EXP_PARAM_ACCESS, Inst);
2401 ScoreBrackets->updateByEvent(EXP_POS_ACCESS, Inst);
2403 ScoreBrackets->updateByEvent(EXP_GPR_LOCK, Inst);
2405 ScoreBrackets->updateByEvent(SCC_WRITE, Inst);
2408 case AMDGPU::S_SENDMSG:
2409 case AMDGPU::S_SENDMSG_RTN_B32:
2410 case AMDGPU::S_SENDMSG_RTN_B64:
2411 case AMDGPU::S_SENDMSGHALT:
2412 ScoreBrackets->updateByEvent(SQ_MESSAGE, Inst);
2414 case AMDGPU::S_MEMTIME:
2415 case AMDGPU::S_MEMREALTIME:
2416 case AMDGPU::S_GET_BARRIER_STATE_M0:
2417 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2418 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2423 if (!
ST->hasWaitXCnt())
2427 ScoreBrackets->updateByEvent(VMEM_GROUP, Inst);
2430 ScoreBrackets->updateByEvent(SMEM_GROUP, Inst);
2433bool WaitcntBrackets::mergeScore(
const MergeInfo &M,
unsigned &Score,
2434 unsigned OtherScore) {
2435 unsigned MyShifted = Score <=
M.OldLB ? 0 : Score +
M.MyShift;
2436 unsigned OtherShifted =
2437 OtherScore <=
M.OtherLB ? 0 : OtherScore +
M.OtherShift;
2438 Score = std::max(MyShifted, OtherShifted);
2439 return OtherShifted > MyShifted;
2447bool WaitcntBrackets::merge(
const WaitcntBrackets &
Other) {
2448 bool StrictDom =
false;
2452 for (
auto K :
Other.VMem.keys())
2453 VMem.try_emplace(K);
2454 for (
auto K :
Other.SGPRs.keys())
2455 SGPRs.try_emplace(K);
2457 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
2459 const unsigned *WaitEventMaskForInst =
Context->WaitEventMaskForInst;
2460 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[
T];
2461 const unsigned OtherEvents =
Other.PendingEvents & WaitEventMaskForInst[
T];
2462 if (OtherEvents & ~OldEvents)
2464 PendingEvents |= OtherEvents;
2467 const unsigned MyPending = ScoreUBs[
T] - ScoreLBs[
T];
2468 const unsigned OtherPending =
Other.ScoreUBs[
T] -
Other.ScoreLBs[
T];
2469 const unsigned NewUB = ScoreLBs[
T] + std::max(MyPending, OtherPending);
2470 if (NewUB < ScoreLBs[
T])
2474 M.OldLB = ScoreLBs[
T];
2475 M.OtherLB =
Other.ScoreLBs[
T];
2476 M.MyShift = NewUB - ScoreUBs[
T];
2477 M.OtherShift = NewUB -
Other.ScoreUBs[
T];
2479 ScoreUBs[
T] = NewUB;
2481 StrictDom |= mergeScore(M, LastFlat[
T],
Other.LastFlat[
T]);
2484 StrictDom |= mergeScore(M, LastGDS,
Other.LastGDS);
2487 StrictDom |= mergeScore(M, SCCScore,
Other.SCCScore);
2488 if (
Other.hasPendingEvent(SCC_WRITE)) {
2489 unsigned OldEventsHasSCCWrite = OldEvents & (1 << SCC_WRITE);
2490 if (!OldEventsHasSCCWrite) {
2491 PendingSCCWrite =
Other.PendingSCCWrite;
2492 }
else if (PendingSCCWrite !=
Other.PendingSCCWrite) {
2493 PendingSCCWrite =
nullptr;
2498 for (
auto &[RegID,
Info] : VMem)
2499 StrictDom |= mergeScore(M,
Info.Scores[
T],
Other.getVMemScore(RegID,
T));
2501 if (isSmemCounter(
T)) {
2502 unsigned Idx = getSgprScoresIdx(
T);
2503 for (
auto &[RegID,
Info] : SGPRs) {
2504 auto It =
Other.SGPRs.find(RegID);
2505 unsigned OtherScore =
2506 (It !=
Other.SGPRs.end()) ? It->second.Scores[Idx] : 0;
2507 StrictDom |= mergeScore(M,
Info.Scores[Idx], OtherScore);
2512 for (
auto &[TID,
Info] : VMem) {
2513 if (
auto It =
Other.VMem.find(TID); It !=
Other.VMem.end()) {
2514 unsigned char NewVmemTypes =
Info.VMEMTypes | It->second.VMEMTypes;
2515 StrictDom |= NewVmemTypes !=
Info.VMEMTypes;
2516 Info.VMEMTypes = NewVmemTypes;
2520 purgeEmptyTrackingData();
2526 return Opcode == AMDGPU::S_WAITCNT ||
2529 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2530 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2531 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
2536bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
2537 MachineBasicBlock &
Block,
2538 WaitcntBrackets &ScoreBrackets) {
2542 dbgs() <<
"*** Begin Block: ";
2544 ScoreBrackets.dump();
2550 bool VCCZCorrect =
true;
2551 if (
ST->hasReadVCCZBug()) {
2554 VCCZCorrect =
false;
2555 }
else if (!
ST->partialVCCWritesUpdateVCCZ()) {
2558 VCCZCorrect =
false;
2562 MachineInstr *OldWaitcntInstr =
nullptr;
2567 MachineInstr &Inst = *Iter;
2576 if (!OldWaitcntInstr)
2577 OldWaitcntInstr = &Inst;
2582 bool FlushVmCnt =
Block.getFirstTerminator() == Inst &&
2583 isPreheaderToFlush(
Block, ScoreBrackets);
2586 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2588 OldWaitcntInstr =
nullptr;
2594 if (
ST->hasReadVCCZBug() || !
ST->partialVCCWritesUpdateVCCZ()) {
2598 if (!
ST->partialVCCWritesUpdateVCCZ())
2599 VCCZCorrect =
false;
2608 if (
ST->hasReadVCCZBug() &&
2609 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2612 VCCZCorrect =
false;
2620 if (
TII->isSMRD(Inst)) {
2621 for (
const MachineMemOperand *Memop : Inst.
memoperands()) {
2624 if (!Memop->isInvariant()) {
2625 const Value *Ptr = Memop->getValue();
2629 if (
ST->hasReadVCCZBug()) {
2631 VCCZCorrect =
false;
2635 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2637 Modified |= insertForcedWaitAfter(Inst,
Block, ScoreBrackets);
2641 ScoreBrackets.dump();
2651 TII->get(
ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2663 AMDGPU::Waitcnt
Wait;
2664 if (
Block.getFirstTerminator() ==
Block.end() &&
2665 isPreheaderToFlush(
Block, ScoreBrackets)) {
2666 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2668 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2670 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2679 dbgs() <<
"*** End Block: ";
2681 ScoreBrackets.dump();
2689bool SIInsertWaitcnts::isPreheaderToFlush(
2690 MachineBasicBlock &
MBB,
const WaitcntBrackets &ScoreBrackets) {
2691 auto [Iterator, IsInserted] = PreheadersToFlush.
try_emplace(&
MBB,
false);
2693 return Iterator->second;
2704 shouldFlushVmCnt(Loop, ScoreBrackets)) {
2705 Iterator->second =
true;
2712bool SIInsertWaitcnts::isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const {
2714 return TII->mayAccessVMEMThroughFlat(
MI);
2726bool SIInsertWaitcnts::shouldFlushVmCnt(MachineLoop *
ML,
2727 const WaitcntBrackets &Brackets) {
2728 bool HasVMemLoad =
false;
2729 bool HasVMemStore =
false;
2730 bool UsesVgprLoadedOutside =
false;
2731 DenseSet<MCRegUnit> VgprUse;
2732 DenseSet<MCRegUnit> VgprDef;
2734 for (MachineBasicBlock *
MBB :
ML->blocks()) {
2735 for (MachineInstr &
MI : *
MBB) {
2736 if (isVMEMOrFlatVMEM(
MI)) {
2737 HasVMemLoad |=
MI.mayLoad();
2738 HasVMemStore |=
MI.mayStore();
2741 for (
const MachineOperand &
Op :
MI.all_uses()) {
2742 if (
Op.isDebug() || !
TRI->isVectorRegister(*
MRI,
Op.getReg()))
2745 for (MCRegUnit RU :
TRI->regunits(
Op.getReg().asMCReg())) {
2753 VMEMID
ID = toVMEMID(RU);
2754 if (Brackets.getVMemScore(
ID, LOAD_CNT) >
2755 Brackets.getScoreLB(LOAD_CNT) ||
2756 Brackets.getVMemScore(
ID, SAMPLE_CNT) >
2757 Brackets.getScoreLB(SAMPLE_CNT) ||
2758 Brackets.getVMemScore(
ID, BVH_CNT) >
2759 Brackets.getScoreLB(BVH_CNT)) {
2760 UsesVgprLoadedOutside =
true;
2767 if (isVMEMOrFlatVMEM(
MI) &&
MI.mayLoad()) {
2768 for (
const MachineOperand &
Op :
MI.all_defs()) {
2769 for (MCRegUnit RU :
TRI->regunits(
Op.getReg().asMCReg())) {
2780 if (!
ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2782 return HasVMemLoad && UsesVgprLoadedOutside &&
ST->hasVmemWriteVgprInOrder();
2785bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
2786 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2788 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2790 if (
auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2791 AA = &AAR->getAAResults();
2793 return SIInsertWaitcnts(MLI, PDT, AA).run(MF);
2805 if (!SIInsertWaitcnts(MLI, PDT,
AA).
run(MF))
2810 .preserve<AAManager>();
2815 TII = ST->getInstrInfo();
2816 TRI = &
TII->getRegisterInfo();
2822 if (ST->hasExtendedWaitCounts()) {
2823 MaxCounter = NUM_EXTENDED_INST_CNTS;
2824 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2825 WCG = &WCGGFX12Plus;
2827 MaxCounter = NUM_NORMAL_INST_CNTS;
2828 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF, MaxCounter);
2832 for (
auto T : inst_counter_types())
2833 ForceEmitWaitcnt[
T] =
false;
2835 WaitEventMaskForInst = WCG->getWaitEventMask();
2837 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2839 if (
ST->hasExtendedWaitCounts()) {
2856 MachineBasicBlock &EntryBB = MF.
front();
2866 while (
I != EntryBB.
end() &&
I->isMetaInstruction())
2869 if (
ST->hasExtendedWaitCounts()) {
2872 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2873 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT)
2876 if (!
ST->hasImageInsts() &&
2877 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
2881 TII->get(instrsForExtendedCounterTypes[CT]))
2888 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(
this);
2889 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2890 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2897 for (
auto *
MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
2900 std::unique_ptr<WaitcntBrackets> Brackets;
2905 for (
auto BII = BlockInfos.
begin(), BIE = BlockInfos.
end(); BII != BIE;
2907 MachineBasicBlock *
MBB = BII->first;
2908 BlockInfo &BI = BII->second;
2914 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2916 *Brackets = *BI.Incoming;
2919 Brackets = std::make_unique<WaitcntBrackets>(
this);
2924 Brackets->~WaitcntBrackets();
2925 new (Brackets.get()) WaitcntBrackets(
this);
2929 Modified |= insertWaitcntInBlock(MF, *
MBB, *Brackets);
2932 if (Brackets->hasPendingEvent()) {
2933 BlockInfo *MoveBracketsToSucc =
nullptr;
2935 auto *SuccBII = BlockInfos.
find(Succ);
2936 BlockInfo &SuccBI = SuccBII->second;
2937 if (!SuccBI.Incoming) {
2938 SuccBI.Dirty =
true;
2939 if (SuccBII <= BII) {
2943 if (!MoveBracketsToSucc) {
2944 MoveBracketsToSucc = &SuccBI;
2946 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2948 }
else if (SuccBI.Incoming->merge(*Brackets)) {
2949 SuccBI.Dirty =
true;
2950 if (SuccBII <= BII) {
2956 if (MoveBracketsToSucc)
2957 MoveBracketsToSucc->Incoming = std::move(Brackets);
2962 if (
ST->hasScalarStores()) {
2963 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
2964 bool HaveScalarStores =
false;
2966 for (MachineBasicBlock &
MBB : MF) {
2967 for (MachineInstr &
MI :
MBB) {
2968 if (!HaveScalarStores &&
TII->isScalarStore(
MI))
2969 HaveScalarStores =
true;
2971 if (
MI.getOpcode() == AMDGPU::S_ENDPGM ||
2972 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2977 if (HaveScalarStores) {
2986 for (MachineBasicBlock *
MBB : EndPgmBlocks) {
2987 bool SeenDCacheWB =
false;
2991 if (
I->getOpcode() == AMDGPU::S_DCACHE_WB)
2992 SeenDCacheWB =
true;
2993 else if (
TII->isScalarStore(*
I))
2994 SeenDCacheWB =
false;
2997 if ((
I->getOpcode() == AMDGPU::S_ENDPGM ||
2998 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
3014 for (MachineInstr *
MI : ReleaseVGPRInsts) {
3016 TII->get(AMDGPU::S_ALLOC_VGPR))
3021 if (!ReleaseVGPRInsts.empty() &&
3022 (MF.getFrameInfo().hasCalls() ||
3023 ST->getOccupancyWithNumVGPRs(
3024 TRI->getNumUsedPhysRegs(*
MRI, AMDGPU::VGPR_32RegClass),
3027 for (MachineInstr *
MI : ReleaseVGPRInsts) {
3028 if (
ST->requiresNopBeforeDeallocVGPRs()) {
3030 TII->get(AMDGPU::S_NOP))
3034 TII->get(AMDGPU::S_SENDMSG))
3040 ReleaseVGPRInsts.clear();
3041 PreheadersToFlush.
clear();
3042 SLoadAddresses.
clear();
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
static bool isOptNone(const MachineFunction &MF)
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
static bool isReg(const MCInst &MI, unsigned OpNo)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static cl::opt< bool > ForceEmitZeroLoadFlag("amdgpu-waitcnt-load-forcezero", cl::desc("Force all waitcnt load counters to wait until 0"), cl::init(false), cl::Hidden)
static bool callWaitsOnFunctionReturn(const MachineInstr &MI)
#define AMDGPU_EVENT_NAME(Name)
static bool callWaitsOnFunctionEntry(const MachineInstr &MI)
static bool updateOperandIfDifferent(MachineInstr &MI, AMDGPU::OpName OpName, unsigned NewEnc)
static bool isWaitInstr(MachineInstr &Inst)
static std::optional< InstCounterType > counterTypeForInstr(unsigned Opcode)
Determine if MI is a gfx12+ single-counter S_WAIT_*CNT instruction, and if so, which counter it is wa...
static cl::opt< bool > ForceEmitZeroFlag("amdgpu-waitcnt-forcezero", cl::desc("Force all waitcnt instrs to be emitted as " "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"), cl::init(false), cl::Hidden)
#define AMDGPU_DECLARE_WAIT_EVENTS(DECL)
#define AMDGPU_EVENT_ENUM(Name)
Provides some synthesis utilities to produce sequences of values.
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
static const uint32_t IV[8]
A manager for alias analyses.
bool isEntryFunction() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
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.
static bool shouldExecute(CounterInfo &Counter)
static bool isCounterSet(CounterInfo &Info)
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
bool erase(const KeyT &Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
FunctionPass class - This class is used to implement most global optimizations.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI const MachineBasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
Instructions::iterator instr_iterator
instr_iterator instr_end()
iterator_range< succ_iterator > successors()
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.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
bool isCall(QueryType Type=AnyInBundle) const
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr fully defines the specified register.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
LLVM_ABI void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
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.
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
const MachineOperand & getOperand(unsigned i) const
bool isMetaInstruction(QueryType Type=IgnoreBundle) const
Return true if this instruction doesn't produce any output in the form of executable instructions.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
Register getReg() const
getReg - Returns the register number.
iterator find(const KeyT &Key)
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static bool isCBranchVCCZRead(const MachineInstr &MI)
static bool isVMEM(const MachineInstr &MI)
static bool isFLATScratch(const MachineInstr &MI)
static bool isEXP(const MachineInstr &MI)
static bool mayWriteLDSThroughDMA(const MachineInstr &MI)
static bool isLDSDIR(const MachineInstr &MI)
static bool isGWS(const MachineInstr &MI)
static bool isFLATGlobal(const MachineInstr &MI)
static bool isVSAMPLE(const MachineInstr &MI)
static bool isAtomicRet(const MachineInstr &MI)
static bool isImage(const MachineInstr &MI)
static unsigned getNonSoftWaitcntOpcode(unsigned Opcode)
static bool isVINTERP(const MachineInstr &MI)
static bool isGFX12CacheInvOrWBInst(unsigned Opc)
static bool isSBarrierSCCWrite(unsigned Opcode)
static bool isMIMG(const MachineInstr &MI)
static bool isFLAT(const MachineInstr &MI)
static bool isLDSDMA(const MachineInstr &MI)
static bool isAtomicNoRet(const MachineInstr &MI)
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
bool isDynamicVGPREnabled() const
void push_back(const T &Elt)
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
@ LOCAL_ADDRESS
Address space for local memory.
@ FLAT_ADDRESS
Address space for flat memory.
unsigned getMaxWavesPerEU(const MCSubtargetInfo *STI)
@ ID_DEALLOC_VGPRS_GFX11Plus
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
void decodeWaitcnt(const IsaVersion &Version, unsigned Waitcnt, unsigned &Vmcnt, unsigned &Expcnt, unsigned &Lgkmcnt)
Decodes Vmcnt, Expcnt and Lgkmcnt from given Waitcnt for given isa Version, and writes decoded values...
unsigned getStorecntBitMask(const IsaVersion &Version)
LLVM_ABI IsaVersion getIsaVersion(StringRef GPU)
unsigned encodeWaitcnt(const IsaVersion &Version, unsigned Vmcnt, unsigned Expcnt, unsigned Lgkmcnt)
Encodes Vmcnt, Expcnt and Lgkmcnt into Waitcnt for given isa Version.
unsigned getSamplecntBitMask(const IsaVersion &Version)
unsigned getKmcntBitMask(const IsaVersion &Version)
unsigned getVmcntBitMask(const IsaVersion &Version)
unsigned getXcntBitMask(const IsaVersion &Version)
Waitcnt decodeStorecntDscnt(const IsaVersion &Version, unsigned StorecntDscnt)
unsigned getLgkmcntBitMask(const IsaVersion &Version)
unsigned getBvhcntBitMask(const IsaVersion &Version)
unsigned getExpcntBitMask(const IsaVersion &Version)
Waitcnt decodeLoadcntDscnt(const IsaVersion &Version, unsigned LoadcntDscnt)
static unsigned encodeStorecntDscnt(const IsaVersion &Version, unsigned Storecnt, unsigned Dscnt)
bool getMUBUFIsBufferInv(unsigned Opc)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
unsigned getLoadcntBitMask(const IsaVersion &Version)
static unsigned encodeLoadcntDscnt(const IsaVersion &Version, unsigned Loadcnt, unsigned Dscnt)
unsigned getDscntBitMask(const IsaVersion &Version)
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ Undef
Value of the register doesn't matter.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
FunctionAddr VTableAddr Value
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
auto enum_seq(EnumT Begin, EnumT End)
Iterate over an enum type from Begin up to - but not including - End.
static StringRef getCPU(StringRef CPU)
Processes a CPU name.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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...
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
char & SIInsertWaitcntsID
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
FunctionAddr VTableAddr Count
CodeGenOptLevel
Code generation optimization level.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
DWARFExpression::Operation Op
FunctionPass * createSIInsertWaitcntsPass()
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
Instruction set architecture version.
Represents the counter values to wait for in an s_waitcnt instruction.
static constexpr bool is_iterable