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_READ_ACCESS) \
149 DECL(VMEM_SAMPLER_READ_ACCESS) \
150 DECL(VMEM_BVH_READ_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] = {
372 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS,
373 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, VMEM_READ_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 VMEM_READ_ACCESS;
541 case AMDGPU::GLOBAL_WB:
542 case AMDGPU::GLOBAL_WBINV:
543 return VMEM_WRITE_ACCESS;
549 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
550 VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
559 if (TII->mayAccessScratch(Inst))
560 return SCRATCH_WRITE_ACCESS;
561 return VMEM_WRITE_ACCESS;
564 return VMEM_READ_ACCESS;
565 return VmemReadMapping[getVmemType(Inst)];
568 bool isVmemAccess(
const MachineInstr &
MI)
const;
569 bool generateWaitcntInstBefore(MachineInstr &
MI,
570 WaitcntBrackets &ScoreBrackets,
571 MachineInstr *OldWaitcntInstr,
573 bool generateWaitcnt(AMDGPU::Waitcnt
Wait,
575 MachineBasicBlock &
Block, WaitcntBrackets &ScoreBrackets,
576 MachineInstr *OldWaitcntInstr);
577 void updateEventWaitcntAfter(MachineInstr &Inst,
578 WaitcntBrackets *ScoreBrackets);
580 MachineBasicBlock *
Block)
const;
581 bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &
Block,
582 WaitcntBrackets &ScoreBrackets);
583 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &
Block,
584 WaitcntBrackets &ScoreBrackets);
595class WaitcntBrackets {
597 WaitcntBrackets(
const SIInsertWaitcnts *Context) : Context(Context) {
598 assert(Context->TRI->getNumRegUnits() < REGUNITS_END);
603 unsigned NumUnusedVmem = 0, NumUnusedSGPRs = 0;
604 for (
auto &[
ID, Val] : VMem) {
608 for (
auto &[
ID, Val] : SGPRs) {
613 if (NumUnusedVmem || NumUnusedSGPRs) {
614 errs() <<
"WaitcntBracket had unused entries at destruction time: "
615 << NumUnusedVmem <<
" VMem and " << NumUnusedSGPRs
616 <<
" SGPR unused entries\n";
622 bool isSmemCounter(InstCounterType
T)
const {
623 return T == Context->SmemAccessCounter ||
T == X_CNT;
626 unsigned getSgprScoresIdx(InstCounterType
T)
const {
627 assert(isSmemCounter(
T) &&
"Invalid SMEM counter");
628 return T == X_CNT ? 1 : 0;
631 unsigned getScoreLB(InstCounterType
T)
const {
636 unsigned getScoreUB(InstCounterType
T)
const {
641 unsigned getScoreRange(InstCounterType
T)
const {
642 return getScoreUB(
T) - getScoreLB(
T);
645 unsigned getSGPRScore(MCRegUnit RU, InstCounterType
T)
const {
646 auto It = SGPRs.find(RU);
647 return It != SGPRs.end() ? It->second.Scores[getSgprScoresIdx(
T)] : 0;
650 unsigned getVMemScore(VMEMID TID, InstCounterType
T)
const {
651 auto It = VMem.find(TID);
652 return It != VMem.end() ? It->second.Scores[
T] : 0;
657 bool counterOutOfOrder(InstCounterType
T)
const;
658 void simplifyWaitcnt(AMDGPU::Waitcnt &
Wait);
659 void simplifyWaitcnt(InstCounterType
T,
unsigned &
Count)
const;
660 bool hasRedundantXCntWithKmCnt(
const AMDGPU::Waitcnt &
Wait);
661 bool canOptimizeXCntWithLoadCnt(
const AMDGPU::Waitcnt &
Wait);
662 void simplifyXcnt(AMDGPU::Waitcnt &CheckWait, AMDGPU::Waitcnt &UpdateWait);
664 void determineWaitForPhysReg(InstCounterType
T,
MCPhysReg Reg,
665 AMDGPU::Waitcnt &
Wait)
const;
666 void determineWaitForLDSDMA(InstCounterType
T, VMEMID TID,
667 AMDGPU::Waitcnt &
Wait)
const;
668 void tryClearSCCWriteEvent(MachineInstr *Inst);
670 void applyWaitcnt(
const AMDGPU::Waitcnt &
Wait);
671 void applyWaitcnt(InstCounterType
T,
unsigned Count);
672 void updateByEvent(WaitEventType
E, MachineInstr &
MI);
674 unsigned hasPendingEvent()
const {
return PendingEvents; }
675 unsigned hasPendingEvent(WaitEventType
E)
const {
676 return PendingEvents & (1 <<
E);
678 unsigned hasPendingEvent(InstCounterType
T)
const {
679 unsigned HasPending = PendingEvents & Context->WaitEventMaskForInst[
T];
680 assert((HasPending != 0) == (getScoreRange(
T) != 0));
684 bool hasMixedPendingEvents(InstCounterType
T)
const {
685 unsigned Events = hasPendingEvent(
T);
687 return Events & (Events - 1);
690 bool hasPendingFlat()
const {
691 return ((LastFlat[DS_CNT] > ScoreLBs[DS_CNT] &&
692 LastFlat[DS_CNT] <= ScoreUBs[DS_CNT]) ||
693 (LastFlat[LOAD_CNT] > ScoreLBs[LOAD_CNT] &&
694 LastFlat[LOAD_CNT] <= ScoreUBs[LOAD_CNT]));
697 void setPendingFlat() {
698 LastFlat[LOAD_CNT] = ScoreUBs[LOAD_CNT];
699 LastFlat[DS_CNT] = ScoreUBs[DS_CNT];
702 bool hasPendingGDS()
const {
703 return LastGDS > ScoreLBs[DS_CNT] && LastGDS <= ScoreUBs[DS_CNT];
706 unsigned getPendingGDSWait()
const {
707 return std::min(getScoreUB(DS_CNT) - LastGDS,
708 Context->getWaitCountMax(DS_CNT) - 1);
711 void setPendingGDS() { LastGDS = ScoreUBs[DS_CNT]; }
715 bool hasOtherPendingVmemTypes(
MCPhysReg Reg, VmemType V)
const {
716 for (MCRegUnit RU : regunits(
Reg)) {
717 auto It = VMem.find(toVMEMID(RU));
718 if (It != VMem.end() && (It->second.VMEMTypes & ~(1 << V)))
725 for (MCRegUnit RU : regunits(
Reg)) {
726 if (
auto It = VMem.find(toVMEMID(RU)); It != VMem.end()) {
727 It->second.VMEMTypes = 0;
728 if (It->second.empty())
734 void setStateOnFunctionEntryOrReturn() {
735 setScoreUB(STORE_CNT,
736 getScoreUB(STORE_CNT) + Context->getWaitCountMax(STORE_CNT));
737 PendingEvents |= Context->WaitEventMaskForInst[STORE_CNT];
740 ArrayRef<const MachineInstr *> getLDSDMAStores()
const {
744 bool hasPointSampleAccel(
const MachineInstr &
MI)
const;
745 bool hasPointSamplePendingVmemTypes(
const MachineInstr &
MI,
748 void print(raw_ostream &)
const;
753 void purgeEmptyTrackingData();
763 void determineWaitForScore(InstCounterType
T,
unsigned Score,
764 AMDGPU::Waitcnt &
Wait)
const;
766 static bool mergeScore(
const MergeInfo &M,
unsigned &Score,
767 unsigned OtherScore);
770 assert(
Reg != AMDGPU::SCC &&
"Shouldn't be used on SCC");
771 if (!Context->TRI->isInAllocatableClass(
Reg))
773 const TargetRegisterClass *RC = Context->TRI->getPhysRegBaseClass(
Reg);
774 unsigned Size = Context->TRI->getRegSizeInBits(*RC);
775 if (
Size == 16 && Context->ST->hasD16Writes32BitVgpr())
776 Reg = Context->TRI->get32BitRegister(
Reg);
777 return Context->TRI->regunits(
Reg);
780 void setScoreLB(InstCounterType
T,
unsigned Val) {
785 void setScoreUB(InstCounterType
T,
unsigned Val) {
792 if (getScoreRange(EXP_CNT) > Context->getWaitCountMax(EXP_CNT))
793 ScoreLBs[
EXP_CNT] = ScoreUBs[
EXP_CNT] - Context->getWaitCountMax(EXP_CNT);
796 void setRegScore(
MCPhysReg Reg, InstCounterType
T,
unsigned Val) {
797 const SIRegisterInfo *
TRI = Context->TRI;
798 if (
Reg == AMDGPU::SCC) {
800 }
else if (
TRI->isVectorRegister(*Context->MRI,
Reg)) {
801 for (MCRegUnit RU : regunits(
Reg))
802 VMem[toVMEMID(RU)].Scores[
T] = Val;
803 }
else if (
TRI->isSGPRReg(*Context->MRI,
Reg)) {
804 auto STy = getSgprScoresIdx(
T);
805 for (MCRegUnit RU : regunits(
Reg))
806 SGPRs[RU].Scores[STy] = Val;
812 void setVMemScore(VMEMID TID, InstCounterType
T,
unsigned Val) {
813 VMem[TID].Scores[
T] = Val;
816 void setScoreByOperand(
const MachineOperand &
Op, InstCounterType CntTy,
819 const SIInsertWaitcnts *Context;
821 unsigned ScoreLBs[NUM_INST_CNTS] = {0};
822 unsigned ScoreUBs[NUM_INST_CNTS] = {0};
823 unsigned PendingEvents = 0;
825 unsigned LastFlat[NUM_INST_CNTS] = {0};
827 unsigned LastGDS = 0;
844 std::array<unsigned, NUM_INST_CNTS> Scores = {0};
846 unsigned VMEMTypes = 0;
849 return all_of(Scores, [](
unsigned K) {
return K == 0; }) && !VMEMTypes;
858 std::array<unsigned, 2> Scores = {0};
860 bool empty()
const {
return !Scores[0] && !Scores[1]; }
863 DenseMap<VMEMID, VMEMInfo> VMem;
864 DenseMap<MCRegUnit, SGPRInfo> SGPRs;
867 unsigned SCCScore = 0;
869 const MachineInstr *PendingSCCWrite =
nullptr;
873 SmallVector<const MachineInstr *> LDSDMAStores;
879 SIInsertWaitcntsLegacy() : MachineFunctionPass(ID) {}
881 bool runOnMachineFunction(MachineFunction &MF)
override;
883 StringRef getPassName()
const override {
884 return "SI insert wait instructions";
887 void getAnalysisUsage(AnalysisUsage &AU)
const override {
890 AU.
addRequired<MachinePostDominatorTreeWrapperPass>();
900 InstCounterType CntTy,
unsigned Score) {
901 setRegScore(
Op.getReg().asMCReg(), CntTy, Score);
909bool WaitcntBrackets::hasPointSampleAccel(
const MachineInstr &
MI)
const {
914 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
924bool WaitcntBrackets::hasPointSamplePendingVmemTypes(
const MachineInstr &
MI,
926 if (!hasPointSampleAccel(
MI))
929 return hasOtherPendingVmemTypes(
Reg, VMEM_NOSAMPLER);
932void WaitcntBrackets::updateByEvent(WaitEventType
E, MachineInstr &Inst) {
933 InstCounterType
T = eventCounter(
Context->WaitEventMaskForInst,
E);
936 unsigned UB = getScoreUB(
T);
937 unsigned CurrScore = UB + 1;
943 PendingEvents |= 1 <<
E;
944 setScoreUB(
T, CurrScore);
947 const MachineRegisterInfo *
MRI =
Context->MRI;
956 if (
const auto *AddrOp =
TII->getNamedOperand(Inst, AMDGPU::OpName::addr))
957 setScoreByOperand(*AddrOp, EXP_CNT, CurrScore);
960 if (
const auto *Data0 =
961 TII->getNamedOperand(Inst, AMDGPU::OpName::data0))
962 setScoreByOperand(*Data0, EXP_CNT, CurrScore);
963 if (
const auto *Data1 =
964 TII->getNamedOperand(Inst, AMDGPU::OpName::data1))
965 setScoreByOperand(*Data1, EXP_CNT, CurrScore);
968 Inst.
getOpcode() != AMDGPU::DS_CONSUME &&
969 Inst.
getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
970 for (
const MachineOperand &
Op : Inst.
all_uses()) {
971 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
972 setScoreByOperand(
Op, EXP_CNT, CurrScore);
975 }
else if (
TII->isFLAT(Inst)) {
977 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
980 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
983 }
else if (
TII->isMIMG(Inst)) {
985 setScoreByOperand(Inst.
getOperand(0), EXP_CNT, CurrScore);
987 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
990 }
else if (
TII->isMTBUF(Inst)) {
992 setScoreByOperand(Inst.
getOperand(0), EXP_CNT, CurrScore);
993 }
else if (
TII->isMUBUF(Inst)) {
995 setScoreByOperand(Inst.
getOperand(0), EXP_CNT, CurrScore);
997 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
1000 }
else if (
TII->isLDSDIR(Inst)) {
1002 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::vdst),
1003 EXP_CNT, CurrScore);
1005 if (
TII->isEXP(Inst)) {
1010 for (MachineOperand &DefMO : Inst.
all_defs()) {
1011 if (
TRI->isVGPR(*
MRI, DefMO.getReg())) {
1012 setScoreByOperand(DefMO, EXP_CNT, CurrScore);
1016 for (
const MachineOperand &
Op : Inst.
all_uses()) {
1017 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
1018 setScoreByOperand(
Op, EXP_CNT, CurrScore);
1021 }
else if (
T == X_CNT) {
1022 WaitEventType OtherEvent =
E == SMEM_GROUP ? VMEM_GROUP : SMEM_GROUP;
1023 if (PendingEvents & (1 << OtherEvent)) {
1028 setScoreLB(
T, getScoreUB(
T) - 1);
1029 PendingEvents &= ~(1 << OtherEvent);
1031 for (
const MachineOperand &
Op : Inst.
all_uses())
1032 setScoreByOperand(
Op,
T, CurrScore);
1043 for (
const MachineOperand &
Op : Inst.
defs()) {
1044 if (
T == LOAD_CNT ||
T == SAMPLE_CNT ||
T == BVH_CNT) {
1045 if (!
TRI->isVectorRegister(*
MRI,
Op.getReg()))
1047 if (updateVMCntOnly(Inst)) {
1052 VmemType
V = getVmemType(Inst);
1053 unsigned char TypesMask = 1 <<
V;
1056 if (hasPointSampleAccel(Inst))
1057 TypesMask |= 1 << VMEM_NOSAMPLER;
1058 for (MCRegUnit RU : regunits(
Op.getReg().asMCReg()))
1059 VMem[toVMEMID(RU)].VMEMTypes |= TypesMask;
1062 setScoreByOperand(
Op,
T, CurrScore);
1065 (
TII->isDS(Inst) ||
TII->mayWriteLDSThroughDMA(Inst))) {
1074 if (!MemOp->isStore() ||
1079 auto AAI = MemOp->getAAInfo();
1085 if (!AAI || !AAI.Scope)
1087 for (
unsigned I = 0,
E = LDSDMAStores.
size();
I !=
E && !Slot; ++
I) {
1088 for (
const auto *MemOp : LDSDMAStores[
I]->memoperands()) {
1089 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1104 setVMemScore(LDSDMA_BEGIN,
T, CurrScore);
1105 if (Slot && Slot < NUM_LDSDMA)
1106 setVMemScore(LDSDMA_BEGIN + Slot,
T, CurrScore);
1110 setRegScore(AMDGPU::SCC,
T, CurrScore);
1111 PendingSCCWrite = &Inst;
1116void WaitcntBrackets::print(raw_ostream &OS)
const {
1120 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
1121 unsigned SR = getScoreRange(
T);
1125 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"LOAD" :
"VM") <<
"_CNT("
1129 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"DS" :
"LGKM") <<
"_CNT("
1133 OS <<
" EXP_CNT(" << SR <<
"):";
1136 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"STORE" :
"VS") <<
"_CNT("
1140 OS <<
" SAMPLE_CNT(" << SR <<
"):";
1143 OS <<
" BVH_CNT(" << SR <<
"):";
1146 OS <<
" KM_CNT(" << SR <<
"):";
1149 OS <<
" X_CNT(" << SR <<
"):";
1152 OS <<
" UNKNOWN(" << SR <<
"):";
1158 unsigned LB = getScoreLB(
T);
1161 sort(SortedVMEMIDs);
1163 for (
auto ID : SortedVMEMIDs) {
1164 unsigned RegScore = VMem.at(
ID).Scores[
T];
1167 unsigned RelScore = RegScore - LB - 1;
1168 if (
ID < REGUNITS_END) {
1169 OS <<
' ' << RelScore <<
":vRU" <<
ID;
1171 assert(
ID >= LDSDMA_BEGIN &&
ID < LDSDMA_END &&
1172 "Unhandled/unexpected ID value!");
1173 OS <<
' ' << RelScore <<
":LDSDMA" <<
ID;
1178 if (isSmemCounter(
T)) {
1180 sort(SortedSMEMIDs);
1181 for (
auto ID : SortedSMEMIDs) {
1182 unsigned RegScore = SGPRs.at(
ID).Scores[getSgprScoresIdx(
T)];
1185 unsigned RelScore = RegScore - LB - 1;
1186 OS <<
' ' << RelScore <<
":sRU" <<
static_cast<unsigned>(
ID);
1190 if (
T == KM_CNT && SCCScore > 0)
1191 OS <<
' ' << SCCScore <<
":scc";
1196 OS <<
"Pending Events: ";
1197 if (hasPendingEvent()) {
1199 for (
unsigned I = 0;
I != NUM_WAIT_EVENTS; ++
I) {
1200 if (hasPendingEvent((WaitEventType)
I)) {
1201 OS <<
LS << WaitEventTypeName[
I];
1214void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &
Wait) {
1215 simplifyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1216 simplifyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1217 simplifyWaitcnt(DS_CNT,
Wait.DsCnt);
1218 simplifyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1219 simplifyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1220 simplifyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1221 simplifyWaitcnt(KM_CNT,
Wait.KmCnt);
1225void WaitcntBrackets::simplifyWaitcnt(InstCounterType
T,
1226 unsigned &
Count)
const {
1230 if (
Count >= getScoreRange(
T))
1234void WaitcntBrackets::purgeEmptyTrackingData() {
1245void WaitcntBrackets::determineWaitForScore(InstCounterType
T,
1246 unsigned ScoreToWait,
1247 AMDGPU::Waitcnt &
Wait)
const {
1248 const unsigned LB = getScoreLB(
T);
1249 const unsigned UB = getScoreUB(
T);
1252 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1253 if ((
T == LOAD_CNT ||
T == DS_CNT) && hasPendingFlat() &&
1254 !
Context->ST->hasFlatLgkmVMemCountInOrder()) {
1258 addWait(
Wait,
T, 0);
1259 }
else if (counterOutOfOrder(
T)) {
1263 addWait(
Wait,
T, 0);
1267 unsigned NeededWait =
1268 std::min(UB - ScoreToWait,
Context->getWaitCountMax(
T) - 1);
1269 addWait(
Wait,
T, NeededWait);
1274void WaitcntBrackets::determineWaitForPhysReg(InstCounterType
T,
MCPhysReg Reg,
1275 AMDGPU::Waitcnt &
Wait)
const {
1276 if (
Reg == AMDGPU::SCC) {
1277 determineWaitForScore(
T, SCCScore,
Wait);
1280 for (MCRegUnit RU : regunits(
Reg))
1281 determineWaitForScore(
1282 T, IsVGPR ? getVMemScore(toVMEMID(RU),
T) : getSGPRScore(RU,
T),
1287void WaitcntBrackets::determineWaitForLDSDMA(InstCounterType
T, VMEMID TID,
1288 AMDGPU::Waitcnt &
Wait)
const {
1289 assert(TID >= LDSDMA_BEGIN && TID < LDSDMA_END);
1290 determineWaitForScore(
T, getVMemScore(TID,
T),
Wait);
1293void WaitcntBrackets::tryClearSCCWriteEvent(MachineInstr *Inst) {
1296 if (PendingSCCWrite &&
1297 PendingSCCWrite->
getOpcode() == AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM &&
1299 unsigned SCC_WRITE_PendingEvent = 1 << SCC_WRITE;
1301 if ((PendingEvents &
Context->WaitEventMaskForInst[KM_CNT]) ==
1302 SCC_WRITE_PendingEvent) {
1303 setScoreLB(KM_CNT, getScoreUB(KM_CNT));
1306 PendingEvents &= ~SCC_WRITE_PendingEvent;
1307 PendingSCCWrite =
nullptr;
1311void WaitcntBrackets::applyWaitcnt(
const AMDGPU::Waitcnt &
Wait) {
1312 applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1313 applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1314 applyWaitcnt(DS_CNT,
Wait.DsCnt);
1315 applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1316 applyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1317 applyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1318 applyWaitcnt(KM_CNT,
Wait.KmCnt);
1319 applyWaitcnt(X_CNT,
Wait.XCnt);
1322void WaitcntBrackets::applyWaitcnt(InstCounterType
T,
unsigned Count) {
1323 const unsigned UB = getScoreUB(
T);
1327 if (counterOutOfOrder(
T))
1329 setScoreLB(
T, std::max(getScoreLB(
T), UB -
Count));
1332 PendingEvents &= ~Context->WaitEventMaskForInst[
T];
1336bool WaitcntBrackets::hasRedundantXCntWithKmCnt(
const AMDGPU::Waitcnt &
Wait) {
1340 return Wait.KmCnt == 0 && hasPendingEvent(SMEM_GROUP);
1343bool WaitcntBrackets::canOptimizeXCntWithLoadCnt(
const AMDGPU::Waitcnt &
Wait) {
1347 return Wait.LoadCnt != ~0
u && hasPendingEvent(VMEM_GROUP) &&
1348 !hasPendingEvent(STORE_CNT);
1351void WaitcntBrackets::simplifyXcnt(AMDGPU::Waitcnt &CheckWait,
1352 AMDGPU::Waitcnt &UpdateWait) {
1358 if (hasRedundantXCntWithKmCnt(CheckWait)) {
1359 if (!hasMixedPendingEvents(X_CNT)) {
1360 applyWaitcnt(X_CNT, 0);
1362 PendingEvents &= ~(1 << SMEM_GROUP);
1364 }
else if (canOptimizeXCntWithLoadCnt(CheckWait)) {
1365 if (!hasMixedPendingEvents(X_CNT)) {
1366 applyWaitcnt(X_CNT, std::min(CheckWait.
XCnt, CheckWait.
LoadCnt));
1367 }
else if (CheckWait.
LoadCnt == 0) {
1368 PendingEvents &= ~(1 << VMEM_GROUP);
1371 simplifyWaitcnt(X_CNT, UpdateWait.
XCnt);
1376bool WaitcntBrackets::counterOutOfOrder(InstCounterType
T)
const {
1378 if ((
T ==
Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1379 (
T == X_CNT && hasPendingEvent(SMEM_GROUP)))
1381 return hasMixedPendingEvents(
T);
1391char SIInsertWaitcntsLegacy::
ID = 0;
1396 return new SIInsertWaitcntsLegacy();
1401 int OpIdx = AMDGPU::getNamedOperandIdx(
MI.getOpcode(),
OpName);
1406 if (NewEnc == MO.
getImm())
1417 case AMDGPU::S_WAIT_LOADCNT:
1419 case AMDGPU::S_WAIT_EXPCNT:
1421 case AMDGPU::S_WAIT_STORECNT:
1423 case AMDGPU::S_WAIT_SAMPLECNT:
1425 case AMDGPU::S_WAIT_BVHCNT:
1427 case AMDGPU::S_WAIT_DSCNT:
1429 case AMDGPU::S_WAIT_KMCNT:
1431 case AMDGPU::S_WAIT_XCNT:
1438bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt)
const {
1452bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1453 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1456 assert(isNormalMode(MaxCounter));
1459 MachineInstr *WaitcntInstr =
nullptr;
1460 MachineInstr *WaitcntVsCntInstr =
nullptr;
1463 dbgs() <<
"PreGFX12::applyPreexistingWaitcnt at: ";
1465 dbgs() <<
"end of block\n";
1473 if (
II.isMetaInstruction()) {
1479 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1483 if (Opcode == AMDGPU::S_WAITCNT) {
1484 unsigned IEnc =
II.getOperand(0).getImm();
1487 ScoreBrackets.simplifyWaitcnt(OldWait);
1491 if (WaitcntInstr || (!
Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1492 II.eraseFromParent();
1496 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1499 <<
"Before: " <<
Wait <<
'\n';);
1500 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, LDSDMA_BEGIN,
Wait);
1509 II.eraseFromParent();
1511 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1512 assert(
II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1515 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1517 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1518 Wait.StoreCnt = std::min(
Wait.StoreCnt, OldVSCnt);
1520 if (WaitcntVsCntInstr || (!
Wait.hasWaitStoreCnt() && TrySimplify)) {
1521 II.eraseFromParent();
1524 WaitcntVsCntInstr = &
II;
1531 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1533 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1534 ScoreBrackets.applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1535 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1542 <<
"applied pre-existing waitcnt\n"
1543 <<
"New Instr at block end: " << *WaitcntInstr <<
'\n'
1544 :
dbgs() <<
"applied pre-existing waitcnt\n"
1545 <<
"Old Instr: " << *It
1546 <<
"New Instr: " << *WaitcntInstr <<
'\n');
1549 if (WaitcntVsCntInstr) {
1551 AMDGPU::OpName::simm16,
Wait.StoreCnt);
1552 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1554 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1555 Wait.StoreCnt = ~0
u;
1558 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1559 <<
"New Instr at block end: " << *WaitcntVsCntInstr
1561 :
dbgs() <<
"applied pre-existing waitcnt\n"
1562 <<
"Old Instr: " << *It
1563 <<
"New Instr: " << *WaitcntVsCntInstr <<
'\n');
1571bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1573 AMDGPU::Waitcnt
Wait) {
1575 assert(isNormalMode(MaxCounter));
1582 if (
Wait.hasWaitExceptStoreCnt()) {
1584 [[maybe_unused]]
auto SWaitInst =
1589 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1590 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1593 if (
Wait.hasWaitStoreCnt()) {
1596 [[maybe_unused]]
auto SWaitInst =
1603 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1604 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1611WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1612 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt &&
ST->hasVscnt() ? 0 : ~0u);
1616WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1617 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
1625bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
1626 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1629 assert(!isNormalMode(MaxCounter));
1632 MachineInstr *CombinedLoadDsCntInstr =
nullptr;
1633 MachineInstr *CombinedStoreDsCntInstr =
nullptr;
1634 MachineInstr *WaitInstrs[NUM_EXTENDED_INST_CNTS] = {};
1637 dbgs() <<
"GFX12Plus::applyPreexistingWaitcnt at: ";
1639 dbgs() <<
"end of block\n";
1647 if (
II.isMetaInstruction()) {
1652 MachineInstr **UpdatableInstr;
1658 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1662 if (Opcode == AMDGPU::S_WAITCNT)
1665 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
1667 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1670 ScoreBrackets.simplifyWaitcnt(OldWait);
1672 UpdatableInstr = &CombinedLoadDsCntInstr;
1673 }
else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
1675 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1678 ScoreBrackets.simplifyWaitcnt(OldWait);
1680 UpdatableInstr = &CombinedStoreDsCntInstr;
1681 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1684 II.eraseFromParent();
1690 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1692 ScoreBrackets.simplifyWaitcnt(CT.value(), OldCnt);
1693 addWait(
Wait, CT.value(), OldCnt);
1694 UpdatableInstr = &WaitInstrs[CT.value()];
1698 if (!*UpdatableInstr) {
1699 *UpdatableInstr = &
II;
1701 II.eraseFromParent();
1707 AMDGPU::Waitcnt PreCombine =
Wait;
1708 if (CombinedLoadDsCntInstr) {
1716 if (
Wait.LoadCnt != ~0u &&
Wait.DsCnt != ~0u) {
1719 AMDGPU::OpName::simm16, NewEnc);
1720 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
1721 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1722 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1727 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1728 <<
"New Instr at block end: "
1729 << *CombinedLoadDsCntInstr <<
'\n'
1730 :
dbgs() <<
"applied pre-existing waitcnt\n"
1731 <<
"Old Instr: " << *It <<
"New Instr: "
1732 << *CombinedLoadDsCntInstr <<
'\n');
1739 if (CombinedStoreDsCntInstr) {
1741 if (
Wait.StoreCnt != ~0u &&
Wait.DsCnt != ~0u) {
1744 AMDGPU::OpName::simm16, NewEnc);
1745 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
1746 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1747 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1748 Wait.StoreCnt = ~0
u;
1752 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1753 <<
"New Instr at block end: "
1754 << *CombinedStoreDsCntInstr <<
'\n'
1755 :
dbgs() <<
"applied pre-existing waitcnt\n"
1756 <<
"Old Instr: " << *It <<
"New Instr: "
1757 << *CombinedStoreDsCntInstr <<
'\n');
1770 if (
Wait.DsCnt != ~0u) {
1779 if (
Wait.LoadCnt != ~0u) {
1780 WaitsToErase.
push_back(&WaitInstrs[LOAD_CNT]);
1781 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1782 }
else if (
Wait.StoreCnt != ~0u) {
1783 WaitsToErase.
push_back(&WaitInstrs[STORE_CNT]);
1784 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1787 for (MachineInstr **WI : WaitsToErase) {
1791 (*WI)->eraseFromParent();
1797 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1798 if ((CT == KM_CNT && ScoreBrackets.hasRedundantXCntWithKmCnt(PreCombine)) ||
1800 ScoreBrackets.canOptimizeXCntWithLoadCnt(PreCombine))) {
1803 ScoreBrackets.simplifyXcnt(PreCombine,
Wait);
1805 if (!WaitInstrs[CT])
1808 unsigned NewCnt = getWait(
Wait, CT);
1809 if (NewCnt != ~0u) {
1811 AMDGPU::OpName::simm16, NewCnt);
1812 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
1814 ScoreBrackets.applyWaitcnt(CT, NewCnt);
1815 setNoWait(
Wait, CT);
1818 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1819 <<
"New Instr at block end: " << *WaitInstrs[CT]
1821 :
dbgs() <<
"applied pre-existing waitcnt\n"
1822 <<
"Old Instr: " << *It
1823 <<
"New Instr: " << *WaitInstrs[CT] <<
'\n');
1834bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
1836 AMDGPU::Waitcnt
Wait) {
1838 assert(!isNormalMode(MaxCounter));
1844 if (
Wait.DsCnt != ~0u) {
1845 MachineInstr *SWaitInst =
nullptr;
1847 if (
Wait.LoadCnt != ~0u) {
1855 }
else if (
Wait.StoreCnt != ~0u) {
1862 Wait.StoreCnt = ~0
u;
1870 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1871 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1878 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1883 [[maybe_unused]]
auto SWaitInst =
1890 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1891 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1922bool SIInsertWaitcnts::generateWaitcntInstBefore(MachineInstr &
MI,
1923 WaitcntBrackets &ScoreBrackets,
1924 MachineInstr *OldWaitcntInstr,
1926 setForceEmitWaitcnt();
1930 AMDGPU::Waitcnt
Wait;
1931 const unsigned Opc =
MI.getOpcode();
1937 if (
Opc == AMDGPU::BUFFER_WBINVL1 ||
Opc == AMDGPU::BUFFER_WBINVL1_SC ||
1938 Opc == AMDGPU::BUFFER_WBINVL1_VOL ||
Opc == AMDGPU::BUFFER_GL0_INV ||
1939 Opc == AMDGPU::BUFFER_GL1_INV) {
1946 if (
Opc == AMDGPU::SI_RETURN_TO_EPILOG ||
Opc == AMDGPU::SI_RETURN ||
1947 Opc == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1948 Opc == AMDGPU::S_SETPC_B64_return ||
1950 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
false));
1960 else if (
Opc == AMDGPU::S_ENDPGM ||
Opc == AMDGPU::S_ENDPGM_SAVED) {
1961 if (!WCG->isOptNone() &&
1962 (
MI.getMF()->getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() ||
1963 (
ST->getGeneration() >= AMDGPUSubtarget::GFX11 &&
1964 ScoreBrackets.getScoreRange(STORE_CNT) != 0 &&
1965 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS))))
1969 else if ((
Opc == AMDGPU::S_SENDMSG ||
Opc == AMDGPU::S_SENDMSGHALT) &&
1970 ST->hasLegacyGeometry() &&
1981 if (
MI.modifiesRegister(AMDGPU::EXEC,
TRI)) {
1984 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1985 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1986 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1987 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1994 if (
TII->isAlwaysGDS(
Opc) && ScoreBrackets.hasPendingGDS())
1995 addWait(
Wait, DS_CNT, ScoreBrackets.getPendingGDSWait());
2001 Wait = AMDGPU::Waitcnt();
2003 const auto &CallAddrOp = *
TII->getNamedOperand(
MI, AMDGPU::OpName::src0);
2004 if (CallAddrOp.isReg()) {
2005 ScoreBrackets.determineWaitForPhysReg(
2006 SmemAccessCounter, CallAddrOp.getReg().asMCReg(),
Wait);
2008 if (
const auto *RtnAddrOp =
2009 TII->getNamedOperand(
MI, AMDGPU::OpName::dst)) {
2010 ScoreBrackets.determineWaitForPhysReg(
2011 SmemAccessCounter, RtnAddrOp->getReg().asMCReg(),
Wait);
2014 }
else if (
Opc == AMDGPU::S_BARRIER_WAIT) {
2015 ScoreBrackets.tryClearSCCWriteEvent(&
MI);
2031 for (
const MachineMemOperand *Memop :
MI.memoperands()) {
2032 const Value *Ptr = Memop->getValue();
2033 if (Memop->isStore()) {
2034 if (
auto It = SLoadAddresses.
find(Ptr); It != SLoadAddresses.
end()) {
2035 addWait(
Wait, SmemAccessCounter, 0);
2037 SLoadAddresses.
erase(It);
2040 unsigned AS = Memop->getAddrSpace();
2044 if (
TII->mayWriteLDSThroughDMA(
MI))
2048 unsigned TID = LDSDMA_BEGIN;
2049 if (Ptr && Memop->getAAInfo()) {
2050 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
2051 for (
unsigned I = 0,
E = LDSDMAStores.size();
I !=
E; ++
I) {
2052 if (
MI.mayAlias(AA, *LDSDMAStores[
I],
true)) {
2053 if ((
I + 1) >= NUM_LDSDMA) {
2056 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID,
Wait);
2060 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID +
I + 1,
Wait);
2064 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID,
Wait);
2066 if (Memop->isStore()) {
2067 ScoreBrackets.determineWaitForLDSDMA(EXP_CNT, TID,
Wait);
2072 for (
const MachineOperand &
Op :
MI.operands()) {
2077 if (
Op.isTied() &&
Op.isUse() &&
TII->doesNotReadTiedSource(
MI))
2082 const bool IsVGPR =
TRI->isVectorRegister(*
MRI,
Op.getReg());
2089 if (
Op.isImplicit() &&
MI.mayLoadOrStore())
2098 if (
Op.isUse() || !updateVMCntOnly(
MI) ||
2099 ScoreBrackets.hasOtherPendingVmemTypes(
Reg, getVmemType(
MI)) ||
2100 ScoreBrackets.hasPointSamplePendingVmemTypes(
MI,
Reg) ||
2101 !
ST->hasVmemWriteVgprInOrder()) {
2102 ScoreBrackets.determineWaitForPhysReg(LOAD_CNT,
Reg,
Wait);
2103 ScoreBrackets.determineWaitForPhysReg(SAMPLE_CNT,
Reg,
Wait);
2104 ScoreBrackets.determineWaitForPhysReg(BVH_CNT,
Reg,
Wait);
2105 ScoreBrackets.clearVgprVmemTypes(
Reg);
2108 if (
Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2109 ScoreBrackets.determineWaitForPhysReg(EXP_CNT,
Reg,
Wait);
2111 ScoreBrackets.determineWaitForPhysReg(DS_CNT,
Reg,
Wait);
2112 }
else if (
Op.getReg() == AMDGPU::SCC) {
2113 ScoreBrackets.determineWaitForPhysReg(KM_CNT,
Reg,
Wait);
2115 ScoreBrackets.determineWaitForPhysReg(SmemAccessCounter,
Reg,
Wait);
2118 if (
ST->hasWaitXCnt() &&
Op.isDef())
2119 ScoreBrackets.determineWaitForPhysReg(X_CNT,
Reg,
Wait);
2136 if (
Opc == AMDGPU::S_BARRIER && !
ST->hasAutoWaitcntBeforeBarrier() &&
2137 !
ST->supportsBackOffBarrier()) {
2138 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
true));
2145 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2150 ScoreBrackets.simplifyWaitcnt(
Wait);
2155 if (
Wait.XCnt != ~0u && isVmemAccess(
MI)) {
2156 ScoreBrackets.applyWaitcnt(X_CNT,
Wait.XCnt);
2163 Wait = WCG->getAllZeroWaitcnt(
false);
2165 if (ForceEmitWaitcnt[LOAD_CNT])
2167 if (ForceEmitWaitcnt[EXP_CNT])
2169 if (ForceEmitWaitcnt[DS_CNT])
2171 if (ForceEmitWaitcnt[SAMPLE_CNT])
2173 if (ForceEmitWaitcnt[BVH_CNT])
2175 if (ForceEmitWaitcnt[KM_CNT])
2177 if (ForceEmitWaitcnt[X_CNT])
2181 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2183 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2185 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2192 return generateWaitcnt(
Wait,
MI.getIterator(), *
MI.getParent(), ScoreBrackets,
2196bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt
Wait,
2198 MachineBasicBlock &
Block,
2199 WaitcntBrackets &ScoreBrackets,
2200 MachineInstr *OldWaitcntInstr) {
2203 if (OldWaitcntInstr)
2207 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr,
Wait, It);
2211 ScoreBrackets.applyWaitcnt(
Wait);
2214 if (
Wait.ExpCnt != ~0u && It !=
Block.instr_end() &&
2216 MachineOperand *WaitExp =
2217 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
2225 <<
"Update Instr: " << *It);
2228 if (WCG->createNewWaitcnt(
Block, It,
Wait))
2234bool SIInsertWaitcnts::isVmemAccess(
const MachineInstr &
MI)
const {
2235 return (
TII->isFLAT(
MI) &&
TII->mayAccessVMEMThroughFlat(
MI)) ||
2242 MachineBasicBlock *
Block)
const {
2243 auto BlockEnd =
Block->getParent()->end();
2244 auto BlockIter =
Block->getIterator();
2248 if (++BlockIter != BlockEnd) {
2249 It = BlockIter->instr_begin();
2256 if (!It->isMetaInstruction())
2264 return It->getOpcode() == AMDGPU::S_ENDPGM;
2268bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2269 MachineBasicBlock &
Block,
2270 WaitcntBrackets &ScoreBrackets) {
2271 AMDGPU::Waitcnt
Wait;
2272 bool NeedsEndPGMCheck =
false;
2280 NeedsEndPGMCheck =
true;
2283 ScoreBrackets.simplifyWaitcnt(
Wait);
2286 bool Result = generateWaitcnt(
Wait, SuccessorIt,
Block, ScoreBrackets,
2289 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &
Block)) {
2297void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2298 WaitcntBrackets *ScoreBrackets) {
2306 bool IsVMEMAccess =
false;
2307 bool IsSMEMAccess =
false;
2308 if (
TII->isDS(Inst) &&
TII->usesLGKM_CNT(Inst)) {
2310 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2311 ScoreBrackets->updateByEvent(GDS_ACCESS, Inst);
2312 ScoreBrackets->updateByEvent(GDS_GPR_LOCK, Inst);
2313 ScoreBrackets->setPendingGDS();
2315 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2317 }
else if (
TII->isFLAT(Inst)) {
2319 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2325 int FlatASCount = 0;
2327 if (
TII->mayAccessVMEMThroughFlat(Inst)) {
2329 IsVMEMAccess =
true;
2330 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2333 if (
TII->mayAccessLDSThroughFlat(Inst)) {
2335 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2344 ScoreBrackets->setPendingFlat();
2347 IsVMEMAccess =
true;
2348 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2350 if (
ST->vmemWriteNeedsExpWaitcnt() &&
2352 ScoreBrackets->updateByEvent(VMW_GPR_LOCK, Inst);
2354 }
else if (
TII->isSMRD(Inst)) {
2355 IsSMEMAccess =
true;
2356 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2357 }
else if (Inst.
isCall()) {
2360 ScoreBrackets->applyWaitcnt(
2361 WCG->getAllZeroWaitcnt(
false));
2362 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2365 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
2368 ScoreBrackets->updateByEvent(EXP_LDS_ACCESS, Inst);
2369 }
else if (
TII->isVINTERP(Inst)) {
2370 int64_t
Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2371 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2373 unsigned Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2375 ScoreBrackets->updateByEvent(EXP_PARAM_ACCESS, Inst);
2377 ScoreBrackets->updateByEvent(EXP_POS_ACCESS, Inst);
2379 ScoreBrackets->updateByEvent(EXP_GPR_LOCK, Inst);
2381 ScoreBrackets->updateByEvent(SCC_WRITE, Inst);
2384 case AMDGPU::S_SENDMSG:
2385 case AMDGPU::S_SENDMSG_RTN_B32:
2386 case AMDGPU::S_SENDMSG_RTN_B64:
2387 case AMDGPU::S_SENDMSGHALT:
2388 ScoreBrackets->updateByEvent(SQ_MESSAGE, Inst);
2390 case AMDGPU::S_MEMTIME:
2391 case AMDGPU::S_MEMREALTIME:
2392 case AMDGPU::S_GET_BARRIER_STATE_M0:
2393 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2394 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2399 if (!
ST->hasWaitXCnt())
2403 ScoreBrackets->updateByEvent(VMEM_GROUP, Inst);
2406 ScoreBrackets->updateByEvent(SMEM_GROUP, Inst);
2409bool WaitcntBrackets::mergeScore(
const MergeInfo &M,
unsigned &Score,
2410 unsigned OtherScore) {
2411 unsigned MyShifted = Score <=
M.OldLB ? 0 : Score +
M.MyShift;
2412 unsigned OtherShifted =
2413 OtherScore <=
M.OtherLB ? 0 : OtherScore +
M.OtherShift;
2414 Score = std::max(MyShifted, OtherShifted);
2415 return OtherShifted > MyShifted;
2423bool WaitcntBrackets::merge(
const WaitcntBrackets &
Other) {
2424 bool StrictDom =
false;
2428 for (
auto K :
Other.VMem.keys())
2429 VMem.try_emplace(K);
2430 for (
auto K :
Other.SGPRs.keys())
2431 SGPRs.try_emplace(K);
2433 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
2435 const unsigned *WaitEventMaskForInst =
Context->WaitEventMaskForInst;
2436 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[
T];
2437 const unsigned OtherEvents =
Other.PendingEvents & WaitEventMaskForInst[
T];
2438 if (OtherEvents & ~OldEvents)
2440 PendingEvents |= OtherEvents;
2443 const unsigned MyPending = ScoreUBs[
T] - ScoreLBs[
T];
2444 const unsigned OtherPending =
Other.ScoreUBs[
T] -
Other.ScoreLBs[
T];
2445 const unsigned NewUB = ScoreLBs[
T] + std::max(MyPending, OtherPending);
2446 if (NewUB < ScoreLBs[
T])
2450 M.OldLB = ScoreLBs[
T];
2451 M.OtherLB =
Other.ScoreLBs[
T];
2452 M.MyShift = NewUB - ScoreUBs[
T];
2453 M.OtherShift = NewUB -
Other.ScoreUBs[
T];
2455 ScoreUBs[
T] = NewUB;
2457 StrictDom |= mergeScore(M, LastFlat[
T],
Other.LastFlat[
T]);
2460 StrictDom |= mergeScore(M, LastGDS,
Other.LastGDS);
2463 StrictDom |= mergeScore(M, SCCScore,
Other.SCCScore);
2464 if (
Other.hasPendingEvent(SCC_WRITE)) {
2465 unsigned OldEventsHasSCCWrite = OldEvents & (1 << SCC_WRITE);
2466 if (!OldEventsHasSCCWrite) {
2467 PendingSCCWrite =
Other.PendingSCCWrite;
2468 }
else if (PendingSCCWrite !=
Other.PendingSCCWrite) {
2469 PendingSCCWrite =
nullptr;
2474 for (
auto &[RegID,
Info] : VMem)
2475 StrictDom |= mergeScore(M,
Info.Scores[
T],
Other.getVMemScore(RegID,
T));
2477 if (isSmemCounter(
T)) {
2478 unsigned Idx = getSgprScoresIdx(
T);
2479 for (
auto &[RegID,
Info] : SGPRs) {
2480 auto It =
Other.SGPRs.find(RegID);
2481 unsigned OtherScore =
2482 (It !=
Other.SGPRs.end()) ? It->second.Scores[Idx] : 0;
2483 StrictDom |= mergeScore(M,
Info.Scores[Idx], OtherScore);
2488 for (
auto &[TID,
Info] : VMem) {
2489 if (
auto It =
Other.VMem.find(TID); It !=
Other.VMem.end()) {
2490 unsigned char NewVmemTypes =
Info.VMEMTypes | It->second.VMEMTypes;
2491 StrictDom |= NewVmemTypes !=
Info.VMEMTypes;
2492 Info.VMEMTypes = NewVmemTypes;
2496 purgeEmptyTrackingData();
2502 return Opcode == AMDGPU::S_WAITCNT ||
2505 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2506 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2507 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
2512bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
2513 MachineBasicBlock &
Block,
2514 WaitcntBrackets &ScoreBrackets) {
2518 dbgs() <<
"*** Begin Block: ";
2520 ScoreBrackets.dump();
2526 bool VCCZCorrect =
true;
2527 if (
ST->hasReadVCCZBug()) {
2530 VCCZCorrect =
false;
2531 }
else if (!
ST->partialVCCWritesUpdateVCCZ()) {
2534 VCCZCorrect =
false;
2538 MachineInstr *OldWaitcntInstr =
nullptr;
2543 MachineInstr &Inst = *Iter;
2552 if (!OldWaitcntInstr)
2553 OldWaitcntInstr = &Inst;
2558 bool FlushVmCnt =
Block.getFirstTerminator() == Inst &&
2559 isPreheaderToFlush(
Block, ScoreBrackets);
2562 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2564 OldWaitcntInstr =
nullptr;
2570 if (
ST->hasReadVCCZBug() || !
ST->partialVCCWritesUpdateVCCZ()) {
2574 if (!
ST->partialVCCWritesUpdateVCCZ())
2575 VCCZCorrect =
false;
2584 if (
ST->hasReadVCCZBug() &&
2585 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2588 VCCZCorrect =
false;
2596 if (
TII->isSMRD(Inst)) {
2597 for (
const MachineMemOperand *Memop : Inst.
memoperands()) {
2600 if (!Memop->isInvariant()) {
2601 const Value *Ptr = Memop->getValue();
2605 if (
ST->hasReadVCCZBug()) {
2607 VCCZCorrect =
false;
2611 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2613 Modified |= insertForcedWaitAfter(Inst,
Block, ScoreBrackets);
2617 ScoreBrackets.dump();
2627 TII->get(
ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2639 AMDGPU::Waitcnt
Wait;
2640 if (
Block.getFirstTerminator() ==
Block.end() &&
2641 isPreheaderToFlush(
Block, ScoreBrackets)) {
2642 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2644 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2646 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2655 dbgs() <<
"*** End Block: ";
2657 ScoreBrackets.dump();
2665bool SIInsertWaitcnts::isPreheaderToFlush(
2666 MachineBasicBlock &
MBB,
const WaitcntBrackets &ScoreBrackets) {
2667 auto [Iterator, IsInserted] = PreheadersToFlush.
try_emplace(&
MBB,
false);
2669 return Iterator->second;
2680 shouldFlushVmCnt(Loop, ScoreBrackets)) {
2681 Iterator->second =
true;
2688bool SIInsertWaitcnts::isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const {
2690 return TII->mayAccessVMEMThroughFlat(
MI);
2702bool SIInsertWaitcnts::shouldFlushVmCnt(MachineLoop *
ML,
2703 const WaitcntBrackets &Brackets) {
2704 bool HasVMemLoad =
false;
2705 bool HasVMemStore =
false;
2706 bool UsesVgprLoadedOutside =
false;
2707 DenseSet<MCRegUnit> VgprUse;
2708 DenseSet<MCRegUnit> VgprDef;
2710 for (MachineBasicBlock *
MBB :
ML->blocks()) {
2711 for (MachineInstr &
MI : *
MBB) {
2712 if (isVMEMOrFlatVMEM(
MI)) {
2713 HasVMemLoad |=
MI.mayLoad();
2714 HasVMemStore |=
MI.mayStore();
2717 for (
const MachineOperand &
Op :
MI.all_uses()) {
2718 if (
Op.isDebug() || !
TRI->isVectorRegister(*
MRI,
Op.getReg()))
2721 for (MCRegUnit RU :
TRI->regunits(
Op.getReg().asMCReg())) {
2729 VMEMID
ID = toVMEMID(RU);
2730 if (Brackets.getVMemScore(
ID, LOAD_CNT) >
2731 Brackets.getScoreLB(LOAD_CNT) ||
2732 Brackets.getVMemScore(
ID, SAMPLE_CNT) >
2733 Brackets.getScoreLB(SAMPLE_CNT) ||
2734 Brackets.getVMemScore(
ID, BVH_CNT) >
2735 Brackets.getScoreLB(BVH_CNT)) {
2736 UsesVgprLoadedOutside =
true;
2743 if (isVMEMOrFlatVMEM(
MI) &&
MI.mayLoad()) {
2744 for (
const MachineOperand &
Op :
MI.all_defs()) {
2745 for (MCRegUnit RU :
TRI->regunits(
Op.getReg().asMCReg())) {
2756 if (!
ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2758 return HasVMemLoad && UsesVgprLoadedOutside &&
ST->hasVmemWriteVgprInOrder();
2761bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
2762 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2764 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2766 if (
auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2767 AA = &AAR->getAAResults();
2769 return SIInsertWaitcnts(MLI, PDT, AA).run(MF);
2781 if (!SIInsertWaitcnts(MLI, PDT,
AA).
run(MF))
2786 .preserve<AAManager>();
2791 TII = ST->getInstrInfo();
2792 TRI = &
TII->getRegisterInfo();
2798 if (ST->hasExtendedWaitCounts()) {
2799 MaxCounter = NUM_EXTENDED_INST_CNTS;
2800 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2801 WCG = &WCGGFX12Plus;
2803 MaxCounter = NUM_NORMAL_INST_CNTS;
2804 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF, MaxCounter);
2808 for (
auto T : inst_counter_types())
2809 ForceEmitWaitcnt[
T] =
false;
2811 WaitEventMaskForInst = WCG->getWaitEventMask();
2813 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2815 if (
ST->hasExtendedWaitCounts()) {
2832 MachineBasicBlock &EntryBB = MF.
front();
2843 I !=
E && (
I->isPHI() ||
I->isMetaInstruction()); ++
I)
2846 if (
ST->hasExtendedWaitCounts()) {
2849 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2850 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT)
2853 if (!
ST->hasImageInsts() &&
2854 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
2858 TII->get(instrsForExtendedCounterTypes[CT]))
2865 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(
this);
2866 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2867 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2874 for (
auto *
MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
2877 std::unique_ptr<WaitcntBrackets> Brackets;
2882 for (
auto BII = BlockInfos.
begin(), BIE = BlockInfos.
end(); BII != BIE;
2884 MachineBasicBlock *
MBB = BII->first;
2885 BlockInfo &BI = BII->second;
2891 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2893 *Brackets = *BI.Incoming;
2896 Brackets = std::make_unique<WaitcntBrackets>(
this);
2901 Brackets->~WaitcntBrackets();
2902 new (Brackets.get()) WaitcntBrackets(
this);
2906 Modified |= insertWaitcntInBlock(MF, *
MBB, *Brackets);
2909 if (Brackets->hasPendingEvent()) {
2910 BlockInfo *MoveBracketsToSucc =
nullptr;
2912 auto *SuccBII = BlockInfos.
find(Succ);
2913 BlockInfo &SuccBI = SuccBII->second;
2914 if (!SuccBI.Incoming) {
2915 SuccBI.Dirty =
true;
2916 if (SuccBII <= BII) {
2920 if (!MoveBracketsToSucc) {
2921 MoveBracketsToSucc = &SuccBI;
2923 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2925 }
else if (SuccBI.Incoming->merge(*Brackets)) {
2926 SuccBI.Dirty =
true;
2927 if (SuccBII <= BII) {
2933 if (MoveBracketsToSucc)
2934 MoveBracketsToSucc->Incoming = std::move(Brackets);
2939 if (
ST->hasScalarStores()) {
2940 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
2941 bool HaveScalarStores =
false;
2943 for (MachineBasicBlock &
MBB : MF) {
2944 for (MachineInstr &
MI :
MBB) {
2945 if (!HaveScalarStores &&
TII->isScalarStore(
MI))
2946 HaveScalarStores =
true;
2948 if (
MI.getOpcode() == AMDGPU::S_ENDPGM ||
2949 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2954 if (HaveScalarStores) {
2963 for (MachineBasicBlock *
MBB : EndPgmBlocks) {
2964 bool SeenDCacheWB =
false;
2968 if (
I->getOpcode() == AMDGPU::S_DCACHE_WB)
2969 SeenDCacheWB =
true;
2970 else if (
TII->isScalarStore(*
I))
2971 SeenDCacheWB =
false;
2974 if ((
I->getOpcode() == AMDGPU::S_ENDPGM ||
2975 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
2991 for (MachineInstr *
MI : ReleaseVGPRInsts) {
2993 TII->get(AMDGPU::S_ALLOC_VGPR))
2998 if (!ReleaseVGPRInsts.empty() &&
2999 (MF.getFrameInfo().hasCalls() ||
3000 ST->getOccupancyWithNumVGPRs(
3001 TRI->getNumUsedPhysRegs(*
MRI, AMDGPU::VGPR_32RegClass),
3004 for (MachineInstr *
MI : ReleaseVGPRInsts) {
3005 if (
ST->requiresNopBeforeDeallocVGPRs()) {
3007 TII->get(AMDGPU::S_NOP))
3011 TII->get(AMDGPU::S_SENDMSG))
3017 ReleaseVGPRInsts.clear();
3018 PreheadersToFlush.
clear();
3019 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
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
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
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