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);
100using RegInterval = std::pair<int, int>;
102struct HardwareLimits {
106 unsigned StorecntMax;
107 unsigned SamplecntMax;
113#define AMDGPU_DECLARE_WAIT_EVENTS(DECL) \
115 DECL(VMEM_READ_ACCESS) \
116 DECL(VMEM_SAMPLER_READ_ACCESS) \
117 DECL(VMEM_BVH_READ_ACCESS) \
118 DECL(VMEM_WRITE_ACCESS) \
119 DECL(SCRATCH_WRITE_ACCESS) \
129 DECL(EXP_POS_ACCESS) \
130 DECL(EXP_PARAM_ACCESS) \
135#define AMDGPU_EVENT_ENUM(Name) Name,
140#undef AMDGPU_EVENT_ENUM
142#define AMDGPU_EVENT_NAME(Name) #Name,
146#undef AMDGPU_EVENT_NAME
156enum RegisterMapping {
157 SQ_MAX_PGM_VGPRS = 2048,
159 SQ_MAX_PGM_SGPRS = 128,
165 FIRST_LDS_VGPR = SQ_MAX_PGM_VGPRS,
167 NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_LDS_VGPRS,
168 NUM_ALL_ALLOCATABLE = NUM_ALL_VGPRS + SQ_MAX_PGM_SGPRS,
170 SCC = NUM_ALL_ALLOCATABLE
191static const unsigned instrsForExtendedCounterTypes[NUM_EXTENDED_INST_CNTS] = {
192 AMDGPU::S_WAIT_LOADCNT, AMDGPU::S_WAIT_DSCNT, AMDGPU::S_WAIT_EXPCNT,
193 AMDGPU::S_WAIT_STORECNT, AMDGPU::S_WAIT_SAMPLECNT, AMDGPU::S_WAIT_BVHCNT,
194 AMDGPU::S_WAIT_KMCNT, AMDGPU::S_WAIT_XCNT};
202static bool isNormalMode(InstCounterType MaxCounter) {
203 return MaxCounter == NUM_NORMAL_INST_CNTS;
208 assert(updateVMCntOnly(Inst));
210 return VMEM_NOSAMPLER;
224 return VMEM_NOSAMPLER;
236 return Wait.StoreCnt;
238 return Wait.SampleCnt;
251 unsigned &WC = getCounterRef(
Wait,
T);
252 WC = std::min(WC,
Count);
256 getCounterRef(
Wait,
T) = ~0
u;
260 return getCounterRef(
Wait,
T);
264InstCounterType eventCounter(
const unsigned *masks, WaitEventType
E) {
265 for (
auto T : inst_counter_types()) {
266 if (masks[
T] & (1 <<
E))
272class WaitcntBrackets;
280class WaitcntGenerator {
282 const GCNSubtarget *ST =
nullptr;
283 const SIInstrInfo *TII =
nullptr;
284 AMDGPU::IsaVersion IV;
285 InstCounterType MaxCounter;
289 WaitcntGenerator() =
default;
290 WaitcntGenerator(
const MachineFunction &MF, InstCounterType MaxCounter)
291 : ST(&MF.getSubtarget<GCNSubtarget>()), TII(ST->getInstrInfo()),
298 bool isOptNone()
const {
return OptNone; }
312 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
313 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
317 bool promoteSoftWaitCnt(MachineInstr *Waitcnt)
const;
321 virtual bool createNewWaitcnt(MachineBasicBlock &
Block,
323 AMDGPU::Waitcnt
Wait) = 0;
327 virtual const unsigned *getWaitEventMask()
const = 0;
331 virtual AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const = 0;
333 virtual ~WaitcntGenerator() =
default;
336 static constexpr unsigned
337 eventMask(std::initializer_list<WaitEventType> Events) {
339 for (
auto &
E : Events)
346class WaitcntGeneratorPreGFX12 :
public WaitcntGenerator {
348 using WaitcntGenerator::WaitcntGenerator;
351 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
352 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
355 bool createNewWaitcnt(MachineBasicBlock &
Block,
357 AMDGPU::Waitcnt
Wait)
override;
359 const unsigned *getWaitEventMask()
const override {
362 static const unsigned WaitEventMaskForInstPreGFX12[NUM_INST_CNTS] = {
363 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS,
364 VMEM_BVH_READ_ACCESS}),
365 eventMask({SMEM_ACCESS, LDS_ACCESS, GDS_ACCESS, SQ_MESSAGE}),
366 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
367 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
368 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
374 return WaitEventMaskForInstPreGFX12;
377 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
380class WaitcntGeneratorGFX12Plus :
public WaitcntGenerator {
382 using WaitcntGenerator::WaitcntGenerator;
385 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
386 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
389 bool createNewWaitcnt(MachineBasicBlock &
Block,
391 AMDGPU::Waitcnt
Wait)
override;
393 const unsigned *getWaitEventMask()
const override {
396 static const unsigned WaitEventMaskForInstGFX12Plus[NUM_INST_CNTS] = {
397 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS}),
398 eventMask({LDS_ACCESS, GDS_ACCESS}),
399 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
400 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
401 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
402 eventMask({VMEM_SAMPLER_READ_ACCESS}),
403 eventMask({VMEM_BVH_READ_ACCESS}),
404 eventMask({SMEM_ACCESS, SQ_MESSAGE, SCC_WRITE}),
405 eventMask({VMEM_GROUP, SMEM_GROUP})};
407 return WaitEventMaskForInstGFX12Plus;
410 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
413class SIInsertWaitcnts {
415 const GCNSubtarget *ST;
416 const SIInstrInfo *TII =
nullptr;
417 const SIRegisterInfo *TRI =
nullptr;
418 const MachineRegisterInfo *MRI =
nullptr;
419 InstCounterType SmemAccessCounter;
420 InstCounterType MaxCounter;
421 const unsigned *WaitEventMaskForInst;
424 DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
425 DenseMap<MachineBasicBlock *, bool> PreheadersToFlush;
426 MachineLoopInfo *MLI;
427 MachinePostDominatorTree *PDT;
431 std::unique_ptr<WaitcntBrackets> Incoming;
435 MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
437 bool ForceEmitWaitcnt[NUM_INST_CNTS];
442 WaitcntGeneratorPreGFX12 WCGPreGFX12;
443 WaitcntGeneratorGFX12Plus WCGGFX12Plus;
445 WaitcntGenerator *WCG =
nullptr;
449 DenseSet<MachineInstr *> ReleaseVGPRInsts;
451 HardwareLimits Limits;
454 SIInsertWaitcnts(MachineLoopInfo *MLI, MachinePostDominatorTree *PDT,
456 : MLI(MLI), PDT(PDT), AA(AA) {
457 (void)ForceExpCounter;
458 (void)ForceLgkmCounter;
459 (void)ForceVMCounter;
462 unsigned getWaitCountMax(InstCounterType
T)
const {
465 return Limits.LoadcntMax;
467 return Limits.DscntMax;
469 return Limits.ExpcntMax;
471 return Limits.StorecntMax;
473 return Limits.SamplecntMax;
475 return Limits.BvhcntMax;
477 return Limits.KmcntMax;
479 return Limits.XcntMax;
486 bool shouldFlushVmCnt(MachineLoop *
ML,
const WaitcntBrackets &Brackets);
487 bool isPreheaderToFlush(MachineBasicBlock &
MBB,
488 const WaitcntBrackets &ScoreBrackets);
489 bool isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const;
490 bool run(MachineFunction &MF);
492 void setForceEmitWaitcnt() {
498 ForceEmitWaitcnt[
EXP_CNT] =
true;
500 ForceEmitWaitcnt[
EXP_CNT] =
false;
505 ForceEmitWaitcnt[DS_CNT] =
true;
506 ForceEmitWaitcnt[KM_CNT] =
true;
508 ForceEmitWaitcnt[DS_CNT] =
false;
509 ForceEmitWaitcnt[KM_CNT] =
false;
514 ForceEmitWaitcnt[LOAD_CNT] =
true;
515 ForceEmitWaitcnt[SAMPLE_CNT] =
true;
516 ForceEmitWaitcnt[BVH_CNT] =
true;
518 ForceEmitWaitcnt[LOAD_CNT] =
false;
519 ForceEmitWaitcnt[SAMPLE_CNT] =
false;
520 ForceEmitWaitcnt[BVH_CNT] =
false;
527 WaitEventType getVmemWaitEventType(
const MachineInstr &Inst)
const {
530 case AMDGPU::GLOBAL_INV:
531 return VMEM_READ_ACCESS;
532 case AMDGPU::GLOBAL_WB:
533 case AMDGPU::GLOBAL_WBINV:
534 return VMEM_WRITE_ACCESS;
540 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
541 VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
550 if (TII->mayAccessScratch(Inst))
551 return SCRATCH_WRITE_ACCESS;
552 return VMEM_WRITE_ACCESS;
555 return VMEM_READ_ACCESS;
556 return VmemReadMapping[getVmemType(Inst)];
559 bool isVmemAccess(
const MachineInstr &
MI)
const;
560 bool generateWaitcntInstBefore(MachineInstr &
MI,
561 WaitcntBrackets &ScoreBrackets,
562 MachineInstr *OldWaitcntInstr,
564 bool generateWaitcnt(AMDGPU::Waitcnt
Wait,
566 MachineBasicBlock &
Block, WaitcntBrackets &ScoreBrackets,
567 MachineInstr *OldWaitcntInstr);
568 void updateEventWaitcntAfter(MachineInstr &Inst,
569 WaitcntBrackets *ScoreBrackets);
571 MachineBasicBlock *
Block)
const;
572 bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &
Block,
573 WaitcntBrackets &ScoreBrackets);
574 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &
Block,
575 WaitcntBrackets &ScoreBrackets);
586class WaitcntBrackets {
588 WaitcntBrackets(
const SIInsertWaitcnts *Context) : Context(Context) {}
590 bool isSmemCounter(InstCounterType
T)
const {
591 return T == Context->SmemAccessCounter ||
T == X_CNT;
594 unsigned getSgprScoresIdx(InstCounterType
T)
const {
595 assert(isSmemCounter(
T) &&
"Invalid SMEM counter");
596 return T == X_CNT ? 1 : 0;
599 unsigned getScoreLB(InstCounterType
T)
const {
604 unsigned getScoreUB(InstCounterType
T)
const {
609 unsigned getScoreRange(InstCounterType
T)
const {
610 return getScoreUB(
T) - getScoreLB(
T);
613 unsigned getRegScore(
int GprNo, InstCounterType
T)
const {
614 if (GprNo < NUM_ALL_VGPRS)
615 return VgprScores[
T][GprNo];
617 if (GprNo < NUM_ALL_ALLOCATABLE)
618 return SgprScores[getSgprScoresIdx(
T)][GprNo - NUM_ALL_VGPRS];
626 RegInterval getRegInterval(
const MachineInstr *
MI,
627 const MachineOperand &
Op)
const;
629 bool counterOutOfOrder(InstCounterType
T)
const;
630 void simplifyWaitcnt(AMDGPU::Waitcnt &
Wait);
631 void simplifyWaitcnt(InstCounterType
T,
unsigned &
Count)
const;
632 bool hasRedundantXCntWithKmCnt(
const AMDGPU::Waitcnt &
Wait);
633 bool canOptimizeXCntWithLoadCnt(
const AMDGPU::Waitcnt &
Wait);
634 void simplifyXcnt(AMDGPU::Waitcnt &CheckWait, AMDGPU::Waitcnt &UpdateWait);
636 void determineWait(InstCounterType
T, RegInterval
Interval,
637 AMDGPU::Waitcnt &
Wait)
const;
638 void determineWait(InstCounterType
T,
int RegNo,
639 AMDGPU::Waitcnt &
Wait)
const {
640 determineWait(
T, {RegNo, RegNo + 1},
Wait);
642 void tryClearSCCWriteEvent(MachineInstr *Inst);
644 void applyWaitcnt(
const AMDGPU::Waitcnt &
Wait);
645 void applyWaitcnt(InstCounterType
T,
unsigned Count);
646 void updateByEvent(WaitEventType
E, MachineInstr &
MI);
648 unsigned hasPendingEvent()
const {
return PendingEvents; }
649 unsigned hasPendingEvent(WaitEventType
E)
const {
650 return PendingEvents & (1 <<
E);
652 unsigned hasPendingEvent(InstCounterType
T)
const {
653 unsigned HasPending = PendingEvents & Context->WaitEventMaskForInst[
T];
654 assert((HasPending != 0) == (getScoreRange(
T) != 0));
658 bool hasMixedPendingEvents(InstCounterType
T)
const {
659 unsigned Events = hasPendingEvent(
T);
661 return Events & (Events - 1);
664 bool hasPendingFlat()
const {
665 return ((LastFlat[DS_CNT] > ScoreLBs[DS_CNT] &&
666 LastFlat[DS_CNT] <= ScoreUBs[DS_CNT]) ||
667 (LastFlat[LOAD_CNT] > ScoreLBs[LOAD_CNT] &&
668 LastFlat[LOAD_CNT] <= ScoreUBs[LOAD_CNT]));
671 void setPendingFlat() {
672 LastFlat[LOAD_CNT] = ScoreUBs[LOAD_CNT];
673 LastFlat[DS_CNT] = ScoreUBs[DS_CNT];
676 bool hasPendingGDS()
const {
677 return LastGDS > ScoreLBs[DS_CNT] && LastGDS <= ScoreUBs[DS_CNT];
680 unsigned getPendingGDSWait()
const {
681 return std::min(getScoreUB(DS_CNT) - LastGDS,
682 Context->getWaitCountMax(DS_CNT) - 1);
685 void setPendingGDS() { LastGDS = ScoreUBs[DS_CNT]; }
689 bool hasOtherPendingVmemTypes(RegInterval
Interval, VmemType V)
const {
691 assert(RegNo < NUM_ALL_VGPRS);
692 if (VgprVmemTypes[RegNo] & ~(1 << V))
698 void clearVgprVmemTypes(RegInterval
Interval) {
700 assert(RegNo < NUM_ALL_VGPRS);
701 VgprVmemTypes[RegNo] = 0;
705 void setStateOnFunctionEntryOrReturn() {
706 setScoreUB(STORE_CNT,
707 getScoreUB(STORE_CNT) + Context->getWaitCountMax(STORE_CNT));
708 PendingEvents |= Context->WaitEventMaskForInst[STORE_CNT];
711 ArrayRef<const MachineInstr *> getLDSDMAStores()
const {
715 bool hasPointSampleAccel(
const MachineInstr &
MI)
const;
716 bool hasPointSamplePendingVmemTypes(
const MachineInstr &
MI,
719 void print(raw_ostream &)
const;
729 static bool mergeScore(
const MergeInfo &M,
unsigned &Score,
730 unsigned OtherScore);
732 void setScoreLB(InstCounterType
T,
unsigned Val) {
737 void setScoreUB(InstCounterType
T,
unsigned Val) {
744 if (getScoreRange(EXP_CNT) > Context->getWaitCountMax(EXP_CNT))
745 ScoreLBs[
EXP_CNT] = ScoreUBs[
EXP_CNT] - Context->getWaitCountMax(EXP_CNT);
748 void setRegScore(
int GprNo, InstCounterType
T,
unsigned Val) {
749 setScoreByInterval({GprNo, GprNo + 1},
T, Val);
752 void setScoreByInterval(RegInterval
Interval, InstCounterType CntTy,
755 void setScoreByOperand(
const MachineInstr *
MI,
const MachineOperand &
Op,
756 InstCounterType CntTy,
unsigned Val);
758 const SIInsertWaitcnts *Context;
760 unsigned ScoreLBs[NUM_INST_CNTS] = {0};
761 unsigned ScoreUBs[NUM_INST_CNTS] = {0};
762 unsigned PendingEvents = 0;
764 unsigned LastFlat[NUM_INST_CNTS] = {0};
766 unsigned LastGDS = 0;
771 unsigned VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS] = {{0}};
776 unsigned SgprScores[2][SQ_MAX_PGM_SGPRS] = {{0}};
778 unsigned SCCScore = 0;
780 const MachineInstr *PendingSCCWrite =
nullptr;
783 unsigned char VgprVmemTypes[NUM_ALL_VGPRS] = {0};
786 SmallVector<
const MachineInstr *, NUM_LDS_VGPRS - 1> LDSDMAStores;
792 SIInsertWaitcntsLegacy() : MachineFunctionPass(ID) {}
794 bool runOnMachineFunction(MachineFunction &MF)
override;
796 StringRef getPassName()
const override {
797 return "SI insert wait instructions";
800 void getAnalysisUsage(AnalysisUsage &AU)
const override {
803 AU.
addRequired<MachinePostDominatorTreeWrapperPass>();
812RegInterval WaitcntBrackets::getRegInterval(
const MachineInstr *
MI,
814 if (
Op.getReg() == AMDGPU::SCC)
818 const MachineRegisterInfo *
MRI =
Context->MRI;
820 if (!
TRI->isInAllocatableClass(
Op.getReg()))
830 unsigned RegIdx =
TRI->getHWRegIndex(MCReg);
832 const TargetRegisterClass *RC =
TRI->getPhysRegBaseClass(
Op.getReg());
833 unsigned Size =
TRI->getRegSizeInBits(*RC);
836 if (
TRI->isVectorRegister(*
MRI,
Op.getReg())) {
841 Result.first += AGPR_OFFSET;
846 if (
Size == 16 &&
Context->ST->hasD16Writes32BitVgpr()) {
854 }
else if (
TRI->isSGPRReg(*
MRI,
Op.getReg()) && RegIdx < SQ_MAX_PGM_SGPRS) {
857 Result.first = RegIdx + NUM_ALL_VGPRS;
866void WaitcntBrackets::setScoreByInterval(RegInterval
Interval,
867 InstCounterType CntTy,
870 if (RegNo < NUM_ALL_VGPRS) {
871 VgprUB = std::max(VgprUB, RegNo);
872 VgprScores[CntTy][RegNo] = Score;
873 }
else if (RegNo < NUM_ALL_ALLOCATABLE) {
874 SgprUB = std::max(SgprUB, RegNo - NUM_ALL_VGPRS);
875 SgprScores[getSgprScoresIdx(CntTy)][RegNo - NUM_ALL_VGPRS] = Score;
883void WaitcntBrackets::setScoreByOperand(
const MachineInstr *
MI,
884 const MachineOperand &
Op,
885 InstCounterType CntTy,
unsigned Score) {
887 setScoreByInterval(
Interval, CntTy, Score);
895bool WaitcntBrackets::hasPointSampleAccel(
const MachineInstr &
MI)
const {
900 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
910bool WaitcntBrackets::hasPointSamplePendingVmemTypes(
911 const MachineInstr &
MI, RegInterval
Interval)
const {
912 if (!hasPointSampleAccel(
MI))
915 return hasOtherPendingVmemTypes(
Interval, VMEM_NOSAMPLER);
918void WaitcntBrackets::updateByEvent(WaitEventType
E, MachineInstr &Inst) {
919 InstCounterType
T = eventCounter(
Context->WaitEventMaskForInst,
E);
922 unsigned UB = getScoreUB(
T);
923 unsigned CurrScore = UB + 1;
929 PendingEvents |= 1 <<
E;
930 setScoreUB(
T, CurrScore);
933 const MachineRegisterInfo *
MRI =
Context->MRI;
942 if (
const auto *AddrOp =
TII->getNamedOperand(Inst, AMDGPU::OpName::addr))
943 setScoreByOperand(&Inst, *AddrOp, EXP_CNT, CurrScore);
946 if (
const auto *Data0 =
947 TII->getNamedOperand(Inst, AMDGPU::OpName::data0))
948 setScoreByOperand(&Inst, *Data0, EXP_CNT, CurrScore);
949 if (
const auto *Data1 =
950 TII->getNamedOperand(Inst, AMDGPU::OpName::data1))
951 setScoreByOperand(&Inst, *Data1, EXP_CNT, CurrScore);
954 Inst.
getOpcode() != AMDGPU::DS_CONSUME &&
955 Inst.
getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
956 for (
const MachineOperand &
Op : Inst.
all_uses()) {
957 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
958 setScoreByOperand(&Inst,
Op, EXP_CNT, CurrScore);
961 }
else if (
TII->isFLAT(Inst)) {
963 setScoreByOperand(&Inst,
964 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
967 setScoreByOperand(&Inst,
968 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
971 }
else if (
TII->isMIMG(Inst)) {
973 setScoreByOperand(&Inst, Inst.
getOperand(0), EXP_CNT, CurrScore);
975 setScoreByOperand(&Inst,
976 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
979 }
else if (
TII->isMTBUF(Inst)) {
981 setScoreByOperand(&Inst, Inst.
getOperand(0), EXP_CNT, CurrScore);
982 }
else if (
TII->isMUBUF(Inst)) {
984 setScoreByOperand(&Inst, Inst.
getOperand(0), EXP_CNT, CurrScore);
986 setScoreByOperand(&Inst,
987 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
990 }
else if (
TII->isLDSDIR(Inst)) {
992 setScoreByOperand(&Inst,
993 *
TII->getNamedOperand(Inst, AMDGPU::OpName::vdst),
996 if (
TII->isEXP(Inst)) {
1001 for (MachineOperand &DefMO : Inst.
all_defs()) {
1002 if (
TRI->isVGPR(*
MRI, DefMO.getReg())) {
1003 setScoreByOperand(&Inst, DefMO, EXP_CNT, CurrScore);
1007 for (
const MachineOperand &
Op : Inst.
all_uses()) {
1008 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
1009 setScoreByOperand(&Inst,
Op, EXP_CNT, CurrScore);
1012 }
else if (
T == X_CNT) {
1013 WaitEventType OtherEvent =
E == SMEM_GROUP ? VMEM_GROUP : SMEM_GROUP;
1014 if (PendingEvents & (1 << OtherEvent)) {
1019 setScoreLB(
T, getScoreUB(
T) - 1);
1020 PendingEvents &= ~(1 << OtherEvent);
1022 for (
const MachineOperand &
Op : Inst.
all_uses())
1023 setScoreByOperand(&Inst,
Op,
T, CurrScore);
1034 for (
const MachineOperand &
Op : Inst.
defs()) {
1035 RegInterval
Interval = getRegInterval(&Inst,
Op);
1036 if (
T == LOAD_CNT ||
T == SAMPLE_CNT ||
T == BVH_CNT) {
1037 if (
Interval.first >= NUM_ALL_VGPRS)
1039 if (updateVMCntOnly(Inst)) {
1044 VmemType
V = getVmemType(Inst);
1045 unsigned char TypesMask = 1 <<
V;
1048 if (hasPointSampleAccel(Inst))
1049 TypesMask |= 1 << VMEM_NOSAMPLER;
1051 VgprVmemTypes[RegNo] |= TypesMask;
1054 setScoreByInterval(
Interval,
T, CurrScore);
1057 (
TII->isDS(Inst) ||
TII->mayWriteLDSThroughDMA(Inst))) {
1062 if (!MemOp->isStore() ||
1067 auto AAI = MemOp->getAAInfo();
1075 if (!AAI || !AAI.Scope)
1077 for (
unsigned I = 0,
E = LDSDMAStores.size();
I !=
E && !Slot; ++
I) {
1078 for (
const auto *MemOp : LDSDMAStores[
I]->memoperands()) {
1079 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1090 LDSDMAStores.push_back(&Inst);
1091 Slot = LDSDMAStores.size();
1094 if (Slot < NUM_LDS_VGPRS)
1095 setRegScore(FIRST_LDS_VGPR + Slot,
T, CurrScore);
1097 setRegScore(FIRST_LDS_VGPR,
T, CurrScore);
1101 setRegScore(SCC,
T, CurrScore);
1102 PendingSCCWrite = &Inst;
1107void WaitcntBrackets::print(raw_ostream &OS)
const {
1111 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
1112 unsigned SR = getScoreRange(
T);
1116 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"LOAD" :
"VM") <<
"_CNT("
1120 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"DS" :
"LGKM") <<
"_CNT("
1124 OS <<
" EXP_CNT(" << SR <<
"): ";
1127 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"STORE" :
"VS") <<
"_CNT("
1131 OS <<
" SAMPLE_CNT(" << SR <<
"): ";
1134 OS <<
" BVH_CNT(" << SR <<
"): ";
1137 OS <<
" KM_CNT(" << SR <<
"): ";
1140 OS <<
" X_CNT(" << SR <<
"): ";
1143 OS <<
" UNKNOWN(" << SR <<
"): ";
1149 unsigned LB = getScoreLB(
T);
1151 for (
int J = 0; J <= VgprUB; J++) {
1152 unsigned RegScore = getRegScore(J,
T);
1155 unsigned RelScore = RegScore - LB - 1;
1156 if (J < FIRST_LDS_VGPR) {
1157 OS << RelScore <<
":v" << J <<
" ";
1159 OS << RelScore <<
":ds ";
1163 if (isSmemCounter(
T)) {
1164 for (
int J = 0; J <= SgprUB; J++) {
1165 unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS,
T);
1168 unsigned RelScore = RegScore - LB - 1;
1169 OS << RelScore <<
":s" << J <<
" ";
1172 if (
T == KM_CNT && SCCScore > 0)
1173 OS << SCCScore <<
":scc ";
1178 OS <<
"Pending Events: ";
1179 if (hasPendingEvent()) {
1181 for (
unsigned I = 0;
I != NUM_WAIT_EVENTS; ++
I) {
1182 if (hasPendingEvent((WaitEventType)
I)) {
1183 OS <<
LS << WaitEventTypeName[
I];
1196void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &
Wait) {
1197 simplifyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1198 simplifyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1199 simplifyWaitcnt(DS_CNT,
Wait.DsCnt);
1200 simplifyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1201 simplifyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1202 simplifyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1203 simplifyWaitcnt(KM_CNT,
Wait.KmCnt);
1207void WaitcntBrackets::simplifyWaitcnt(InstCounterType
T,
1208 unsigned &
Count)
const {
1212 if (
Count >= getScoreRange(
T))
1216void WaitcntBrackets::determineWait(InstCounterType
T, RegInterval
Interval,
1217 AMDGPU::Waitcnt &
Wait)
const {
1218 const unsigned LB = getScoreLB(
T);
1219 const unsigned UB = getScoreUB(
T);
1221 unsigned ScoreToWait = getRegScore(RegNo,
T);
1225 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1226 if ((
T == LOAD_CNT ||
T == DS_CNT) && hasPendingFlat() &&
1227 !
Context->ST->hasFlatLgkmVMemCountInOrder()) {
1231 addWait(
Wait,
T, 0);
1232 }
else if (counterOutOfOrder(
T)) {
1236 addWait(
Wait,
T, 0);
1240 unsigned NeededWait =
1241 std::min(UB - ScoreToWait,
Context->getWaitCountMax(
T) - 1);
1242 addWait(
Wait,
T, NeededWait);
1248void WaitcntBrackets::tryClearSCCWriteEvent(MachineInstr *Inst) {
1251 if (PendingSCCWrite &&
1252 PendingSCCWrite->
getOpcode() == AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM &&
1254 unsigned SCC_WRITE_PendingEvent = 1 << SCC_WRITE;
1256 if ((PendingEvents &
Context->WaitEventMaskForInst[KM_CNT]) ==
1257 SCC_WRITE_PendingEvent) {
1258 setScoreLB(KM_CNT, getScoreUB(KM_CNT));
1261 PendingEvents &= ~SCC_WRITE_PendingEvent;
1262 PendingSCCWrite =
nullptr;
1266void WaitcntBrackets::applyWaitcnt(
const AMDGPU::Waitcnt &
Wait) {
1267 applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1268 applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1269 applyWaitcnt(DS_CNT,
Wait.DsCnt);
1270 applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1271 applyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1272 applyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1273 applyWaitcnt(KM_CNT,
Wait.KmCnt);
1274 applyWaitcnt(X_CNT,
Wait.XCnt);
1277void WaitcntBrackets::applyWaitcnt(InstCounterType
T,
unsigned Count) {
1278 const unsigned UB = getScoreUB(
T);
1282 if (counterOutOfOrder(
T))
1284 setScoreLB(
T, std::max(getScoreLB(
T), UB -
Count));
1287 PendingEvents &= ~Context->WaitEventMaskForInst[
T];
1291bool WaitcntBrackets::hasRedundantXCntWithKmCnt(
const AMDGPU::Waitcnt &
Wait) {
1295 return Wait.KmCnt == 0 && hasPendingEvent(SMEM_GROUP);
1298bool WaitcntBrackets::canOptimizeXCntWithLoadCnt(
const AMDGPU::Waitcnt &
Wait) {
1302 return Wait.LoadCnt != ~0
u && hasPendingEvent(VMEM_GROUP) &&
1303 !hasPendingEvent(STORE_CNT);
1306void WaitcntBrackets::simplifyXcnt(AMDGPU::Waitcnt &CheckWait,
1307 AMDGPU::Waitcnt &UpdateWait) {
1313 if (hasRedundantXCntWithKmCnt(CheckWait)) {
1314 if (!hasMixedPendingEvents(X_CNT)) {
1315 applyWaitcnt(X_CNT, 0);
1317 PendingEvents &= ~(1 << SMEM_GROUP);
1319 }
else if (canOptimizeXCntWithLoadCnt(CheckWait)) {
1320 if (!hasMixedPendingEvents(X_CNT)) {
1321 applyWaitcnt(X_CNT, std::min(CheckWait.
XCnt, CheckWait.
LoadCnt));
1322 }
else if (CheckWait.
LoadCnt == 0) {
1323 PendingEvents &= ~(1 << VMEM_GROUP);
1326 simplifyWaitcnt(X_CNT, UpdateWait.
XCnt);
1331bool WaitcntBrackets::counterOutOfOrder(InstCounterType
T)
const {
1333 if ((
T ==
Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1334 (
T == X_CNT && hasPendingEvent(SMEM_GROUP)))
1336 return hasMixedPendingEvents(
T);
1346char SIInsertWaitcntsLegacy::
ID = 0;
1351 return new SIInsertWaitcntsLegacy();
1356 int OpIdx = AMDGPU::getNamedOperandIdx(
MI.getOpcode(),
OpName);
1361 if (NewEnc == MO.
getImm())
1372 case AMDGPU::S_WAIT_LOADCNT:
1374 case AMDGPU::S_WAIT_EXPCNT:
1376 case AMDGPU::S_WAIT_STORECNT:
1378 case AMDGPU::S_WAIT_SAMPLECNT:
1380 case AMDGPU::S_WAIT_BVHCNT:
1382 case AMDGPU::S_WAIT_DSCNT:
1384 case AMDGPU::S_WAIT_KMCNT:
1386 case AMDGPU::S_WAIT_XCNT:
1393bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt)
const {
1407bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1408 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1411 assert(isNormalMode(MaxCounter));
1414 MachineInstr *WaitcntInstr =
nullptr;
1415 MachineInstr *WaitcntVsCntInstr =
nullptr;
1418 dbgs() <<
"PreGFX12::applyPreexistingWaitcnt at: ";
1420 dbgs() <<
"end of block\n";
1428 if (
II.isMetaInstruction()) {
1434 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1438 if (Opcode == AMDGPU::S_WAITCNT) {
1439 unsigned IEnc =
II.getOperand(0).getImm();
1442 ScoreBrackets.simplifyWaitcnt(OldWait);
1446 if (WaitcntInstr || (!
Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1447 II.eraseFromParent();
1451 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1454 <<
"Before: " <<
Wait.LoadCnt <<
'\n';);
1455 ScoreBrackets.determineWait(LOAD_CNT, FIRST_LDS_VGPR,
Wait);
1464 II.eraseFromParent();
1466 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1467 assert(
II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1470 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1472 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1473 Wait.StoreCnt = std::min(
Wait.StoreCnt, OldVSCnt);
1475 if (WaitcntVsCntInstr || (!
Wait.hasWaitStoreCnt() && TrySimplify)) {
1476 II.eraseFromParent();
1479 WaitcntVsCntInstr = &
II;
1486 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1488 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1489 ScoreBrackets.applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1490 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1497 <<
"applied pre-existing waitcnt\n"
1498 <<
"New Instr at block end: " << *WaitcntInstr <<
'\n'
1499 :
dbgs() <<
"applied pre-existing waitcnt\n"
1500 <<
"Old Instr: " << *It
1501 <<
"New Instr: " << *WaitcntInstr <<
'\n');
1504 if (WaitcntVsCntInstr) {
1506 AMDGPU::OpName::simm16,
Wait.StoreCnt);
1507 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1509 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1510 Wait.StoreCnt = ~0
u;
1513 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1514 <<
"New Instr at block end: " << *WaitcntVsCntInstr
1516 :
dbgs() <<
"applied pre-existing waitcnt\n"
1517 <<
"Old Instr: " << *It
1518 <<
"New Instr: " << *WaitcntVsCntInstr <<
'\n');
1526bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1528 AMDGPU::Waitcnt
Wait) {
1530 assert(isNormalMode(MaxCounter));
1537 if (
Wait.hasWaitExceptStoreCnt()) {
1539 [[maybe_unused]]
auto SWaitInst =
1544 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1545 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1548 if (
Wait.hasWaitStoreCnt()) {
1551 [[maybe_unused]]
auto SWaitInst =
1558 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1559 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1566WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1567 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt &&
ST->hasVscnt() ? 0 : ~0u);
1571WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1572 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
1580bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
1581 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1584 assert(!isNormalMode(MaxCounter));
1587 MachineInstr *CombinedLoadDsCntInstr =
nullptr;
1588 MachineInstr *CombinedStoreDsCntInstr =
nullptr;
1589 MachineInstr *WaitInstrs[NUM_EXTENDED_INST_CNTS] = {};
1592 dbgs() <<
"GFX12Plus::applyPreexistingWaitcnt at: ";
1594 dbgs() <<
"end of block\n";
1602 if (
II.isMetaInstruction()) {
1607 MachineInstr **UpdatableInstr;
1613 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1617 if (Opcode == AMDGPU::S_WAITCNT)
1620 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
1622 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1625 ScoreBrackets.simplifyWaitcnt(OldWait);
1627 UpdatableInstr = &CombinedLoadDsCntInstr;
1628 }
else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
1630 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1633 ScoreBrackets.simplifyWaitcnt(OldWait);
1635 UpdatableInstr = &CombinedStoreDsCntInstr;
1636 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1639 II.eraseFromParent();
1645 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1647 ScoreBrackets.simplifyWaitcnt(CT.value(), OldCnt);
1648 addWait(
Wait, CT.value(), OldCnt);
1649 UpdatableInstr = &WaitInstrs[CT.value()];
1653 if (!*UpdatableInstr) {
1654 *UpdatableInstr = &
II;
1656 II.eraseFromParent();
1662 AMDGPU::Waitcnt PreCombine =
Wait;
1663 if (CombinedLoadDsCntInstr) {
1671 if (
Wait.LoadCnt != ~0u &&
Wait.DsCnt != ~0u) {
1674 AMDGPU::OpName::simm16, NewEnc);
1675 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
1676 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1677 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1682 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1683 <<
"New Instr at block end: "
1684 << *CombinedLoadDsCntInstr <<
'\n'
1685 :
dbgs() <<
"applied pre-existing waitcnt\n"
1686 <<
"Old Instr: " << *It <<
"New Instr: "
1687 << *CombinedLoadDsCntInstr <<
'\n');
1694 if (CombinedStoreDsCntInstr) {
1696 if (
Wait.StoreCnt != ~0u &&
Wait.DsCnt != ~0u) {
1699 AMDGPU::OpName::simm16, NewEnc);
1700 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
1701 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1702 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1703 Wait.StoreCnt = ~0
u;
1707 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1708 <<
"New Instr at block end: "
1709 << *CombinedStoreDsCntInstr <<
'\n'
1710 :
dbgs() <<
"applied pre-existing waitcnt\n"
1711 <<
"Old Instr: " << *It <<
"New Instr: "
1712 << *CombinedStoreDsCntInstr <<
'\n');
1725 if (
Wait.DsCnt != ~0u) {
1734 if (
Wait.LoadCnt != ~0u) {
1735 WaitsToErase.
push_back(&WaitInstrs[LOAD_CNT]);
1736 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1737 }
else if (
Wait.StoreCnt != ~0u) {
1738 WaitsToErase.
push_back(&WaitInstrs[STORE_CNT]);
1739 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1742 for (MachineInstr **WI : WaitsToErase) {
1746 (*WI)->eraseFromParent();
1752 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1753 if ((CT == KM_CNT && ScoreBrackets.hasRedundantXCntWithKmCnt(PreCombine)) ||
1755 ScoreBrackets.canOptimizeXCntWithLoadCnt(PreCombine))) {
1758 ScoreBrackets.simplifyXcnt(PreCombine,
Wait);
1760 if (!WaitInstrs[CT])
1763 unsigned NewCnt = getWait(
Wait, CT);
1764 if (NewCnt != ~0u) {
1766 AMDGPU::OpName::simm16, NewCnt);
1767 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
1769 ScoreBrackets.applyWaitcnt(CT, NewCnt);
1770 setNoWait(
Wait, CT);
1773 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1774 <<
"New Instr at block end: " << *WaitInstrs[CT]
1776 :
dbgs() <<
"applied pre-existing waitcnt\n"
1777 <<
"Old Instr: " << *It
1778 <<
"New Instr: " << *WaitInstrs[CT] <<
'\n');
1789bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
1791 AMDGPU::Waitcnt
Wait) {
1793 assert(!isNormalMode(MaxCounter));
1799 if (
Wait.DsCnt != ~0u) {
1800 MachineInstr *SWaitInst =
nullptr;
1802 if (
Wait.LoadCnt != ~0u) {
1810 }
else if (
Wait.StoreCnt != ~0u) {
1817 Wait.StoreCnt = ~0
u;
1825 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1826 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1833 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1838 [[maybe_unused]]
auto SWaitInst =
1845 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1846 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1877bool SIInsertWaitcnts::generateWaitcntInstBefore(MachineInstr &
MI,
1878 WaitcntBrackets &ScoreBrackets,
1879 MachineInstr *OldWaitcntInstr,
1881 setForceEmitWaitcnt();
1885 AMDGPU::Waitcnt
Wait;
1886 const unsigned Opc =
MI.getOpcode();
1892 if (
Opc == AMDGPU::BUFFER_WBINVL1 ||
Opc == AMDGPU::BUFFER_WBINVL1_SC ||
1893 Opc == AMDGPU::BUFFER_WBINVL1_VOL ||
Opc == AMDGPU::BUFFER_GL0_INV ||
1894 Opc == AMDGPU::BUFFER_GL1_INV) {
1901 if (
Opc == AMDGPU::SI_RETURN_TO_EPILOG ||
Opc == AMDGPU::SI_RETURN ||
1902 Opc == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1903 Opc == AMDGPU::S_SETPC_B64_return ||
1905 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
false));
1915 else if (
Opc == AMDGPU::S_ENDPGM ||
Opc == AMDGPU::S_ENDPGM_SAVED) {
1916 if (!WCG->isOptNone() &&
1917 (
MI.getMF()->getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() ||
1918 (
ST->getGeneration() >= AMDGPUSubtarget::GFX11 &&
1919 ScoreBrackets.getScoreRange(STORE_CNT) != 0 &&
1920 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS))))
1924 else if ((
Opc == AMDGPU::S_SENDMSG ||
Opc == AMDGPU::S_SENDMSGHALT) &&
1925 ST->hasLegacyGeometry() &&
1936 if (
MI.modifiesRegister(AMDGPU::EXEC,
TRI)) {
1939 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1940 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1941 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1942 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1949 if (
TII->isAlwaysGDS(
Opc) && ScoreBrackets.hasPendingGDS())
1950 addWait(
Wait, DS_CNT, ScoreBrackets.getPendingGDSWait());
1956 Wait = AMDGPU::Waitcnt();
1958 const auto &CallAddrOp = *
TII->getNamedOperand(
MI, AMDGPU::OpName::src0);
1959 if (CallAddrOp.isReg()) {
1960 RegInterval CallAddrOpInterval =
1961 ScoreBrackets.getRegInterval(&
MI, CallAddrOp);
1963 ScoreBrackets.determineWait(SmemAccessCounter, CallAddrOpInterval,
1966 if (
const auto *RtnAddrOp =
1967 TII->getNamedOperand(
MI, AMDGPU::OpName::dst)) {
1968 RegInterval RtnAddrOpInterval =
1969 ScoreBrackets.getRegInterval(&
MI, *RtnAddrOp);
1971 ScoreBrackets.determineWait(SmemAccessCounter, RtnAddrOpInterval,
1975 }
else if (
Opc == AMDGPU::S_BARRIER_WAIT) {
1976 ScoreBrackets.tryClearSCCWriteEvent(&
MI);
1992 for (
const MachineMemOperand *Memop :
MI.memoperands()) {
1993 const Value *Ptr = Memop->getValue();
1994 if (Memop->isStore()) {
1995 if (
auto It = SLoadAddresses.
find(Ptr); It != SLoadAddresses.
end()) {
1996 addWait(
Wait, SmemAccessCounter, 0);
1998 SLoadAddresses.
erase(It);
2001 unsigned AS = Memop->getAddrSpace();
2005 if (
TII->mayWriteLDSThroughDMA(
MI))
2009 unsigned RegNo = FIRST_LDS_VGPR;
2010 if (Ptr && Memop->getAAInfo()) {
2011 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
2012 for (
unsigned I = 0,
E = LDSDMAStores.size();
I !=
E; ++
I) {
2013 if (
MI.mayAlias(AA, *LDSDMAStores[
I],
true)) {
2014 if ((
I + 1) >= NUM_LDS_VGPRS) {
2017 ScoreBrackets.determineWait(LOAD_CNT, RegNo,
Wait);
2021 ScoreBrackets.determineWait(LOAD_CNT, RegNo +
I + 1,
Wait);
2025 ScoreBrackets.determineWait(LOAD_CNT, RegNo,
Wait);
2028 if (Memop->isStore())
2029 ScoreBrackets.determineWait(EXP_CNT, RegNo,
Wait);
2033 for (
const MachineOperand &
Op :
MI.operands()) {
2038 if (
Op.isTied() &&
Op.isUse() &&
TII->doesNotReadTiedSource(
MI))
2041 RegInterval
Interval = ScoreBrackets.getRegInterval(&
MI,
Op);
2043 const bool IsVGPR =
TRI->isVectorRegister(*
MRI,
Op.getReg());
2050 if (
Op.isImplicit() &&
MI.mayLoadOrStore())
2059 if (
Op.isUse() || !updateVMCntOnly(
MI) ||
2060 ScoreBrackets.hasOtherPendingVmemTypes(
Interval,
2062 ScoreBrackets.hasPointSamplePendingVmemTypes(
MI,
Interval) ||
2063 !
ST->hasVmemWriteVgprInOrder()) {
2065 ScoreBrackets.determineWait(SAMPLE_CNT,
Interval,
Wait);
2067 ScoreBrackets.clearVgprVmemTypes(
Interval);
2070 if (
Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2074 }
else if (
Op.getReg() == AMDGPU::SCC) {
2077 ScoreBrackets.determineWait(SmemAccessCounter,
Interval,
Wait);
2080 if (
ST->hasWaitXCnt() &&
Op.isDef())
2098 if (
Opc == AMDGPU::S_BARRIER && !
ST->hasAutoWaitcntBeforeBarrier() &&
2099 !
ST->supportsBackOffBarrier()) {
2100 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
true));
2107 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2112 ScoreBrackets.simplifyWaitcnt(
Wait);
2117 if (
Wait.XCnt != ~0u && isVmemAccess(
MI)) {
2118 ScoreBrackets.applyWaitcnt(X_CNT,
Wait.XCnt);
2125 Wait = WCG->getAllZeroWaitcnt(
false);
2127 if (ForceEmitWaitcnt[LOAD_CNT])
2129 if (ForceEmitWaitcnt[EXP_CNT])
2131 if (ForceEmitWaitcnt[DS_CNT])
2133 if (ForceEmitWaitcnt[SAMPLE_CNT])
2135 if (ForceEmitWaitcnt[BVH_CNT])
2137 if (ForceEmitWaitcnt[KM_CNT])
2139 if (ForceEmitWaitcnt[X_CNT])
2143 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2145 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2147 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2154 return generateWaitcnt(
Wait,
MI.getIterator(), *
MI.getParent(), ScoreBrackets,
2158bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt
Wait,
2160 MachineBasicBlock &
Block,
2161 WaitcntBrackets &ScoreBrackets,
2162 MachineInstr *OldWaitcntInstr) {
2165 if (OldWaitcntInstr)
2169 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr,
Wait, It);
2173 ScoreBrackets.applyWaitcnt(
Wait);
2176 if (
Wait.ExpCnt != ~0u && It !=
Block.instr_end() &&
2178 MachineOperand *WaitExp =
2179 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
2187 <<
"Update Instr: " << *It);
2190 if (WCG->createNewWaitcnt(
Block, It,
Wait))
2196bool SIInsertWaitcnts::isVmemAccess(
const MachineInstr &
MI)
const {
2197 return (
TII->isFLAT(
MI) &&
TII->mayAccessVMEMThroughFlat(
MI)) ||
2204 MachineBasicBlock *
Block)
const {
2205 auto BlockEnd =
Block->getParent()->end();
2206 auto BlockIter =
Block->getIterator();
2210 if (++BlockIter != BlockEnd) {
2211 It = BlockIter->instr_begin();
2218 if (!It->isMetaInstruction())
2226 return It->getOpcode() == AMDGPU::S_ENDPGM;
2230bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2231 MachineBasicBlock &
Block,
2232 WaitcntBrackets &ScoreBrackets) {
2233 AMDGPU::Waitcnt
Wait;
2234 bool NeedsEndPGMCheck =
false;
2242 NeedsEndPGMCheck =
true;
2245 ScoreBrackets.simplifyWaitcnt(
Wait);
2248 bool Result = generateWaitcnt(
Wait, SuccessorIt,
Block, ScoreBrackets,
2251 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &
Block)) {
2259void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2260 WaitcntBrackets *ScoreBrackets) {
2268 bool IsVMEMAccess =
false;
2269 bool IsSMEMAccess =
false;
2270 if (
TII->isDS(Inst) &&
TII->usesLGKM_CNT(Inst)) {
2272 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2273 ScoreBrackets->updateByEvent(GDS_ACCESS, Inst);
2274 ScoreBrackets->updateByEvent(GDS_GPR_LOCK, Inst);
2275 ScoreBrackets->setPendingGDS();
2277 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2279 }
else if (
TII->isFLAT(Inst)) {
2281 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2287 int FlatASCount = 0;
2289 if (
TII->mayAccessVMEMThroughFlat(Inst)) {
2291 IsVMEMAccess =
true;
2292 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2295 if (
TII->mayAccessLDSThroughFlat(Inst)) {
2297 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2306 ScoreBrackets->setPendingFlat();
2309 IsVMEMAccess =
true;
2310 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2312 if (
ST->vmemWriteNeedsExpWaitcnt() &&
2314 ScoreBrackets->updateByEvent(VMW_GPR_LOCK, Inst);
2316 }
else if (
TII->isSMRD(Inst)) {
2317 IsSMEMAccess =
true;
2318 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2319 }
else if (Inst.
isCall()) {
2322 ScoreBrackets->applyWaitcnt(
2323 WCG->getAllZeroWaitcnt(
false));
2324 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2327 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
2330 ScoreBrackets->updateByEvent(EXP_LDS_ACCESS, Inst);
2331 }
else if (
TII->isVINTERP(Inst)) {
2332 int64_t
Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2333 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2335 unsigned Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2337 ScoreBrackets->updateByEvent(EXP_PARAM_ACCESS, Inst);
2339 ScoreBrackets->updateByEvent(EXP_POS_ACCESS, Inst);
2341 ScoreBrackets->updateByEvent(EXP_GPR_LOCK, Inst);
2343 ScoreBrackets->updateByEvent(SCC_WRITE, Inst);
2346 case AMDGPU::S_SENDMSG:
2347 case AMDGPU::S_SENDMSG_RTN_B32:
2348 case AMDGPU::S_SENDMSG_RTN_B64:
2349 case AMDGPU::S_SENDMSGHALT:
2350 ScoreBrackets->updateByEvent(SQ_MESSAGE, Inst);
2352 case AMDGPU::S_MEMTIME:
2353 case AMDGPU::S_MEMREALTIME:
2354 case AMDGPU::S_GET_BARRIER_STATE_M0:
2355 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2356 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2361 if (!
ST->hasWaitXCnt())
2365 ScoreBrackets->updateByEvent(VMEM_GROUP, Inst);
2368 ScoreBrackets->updateByEvent(SMEM_GROUP, Inst);
2371bool WaitcntBrackets::mergeScore(
const MergeInfo &M,
unsigned &Score,
2372 unsigned OtherScore) {
2373 unsigned MyShifted = Score <=
M.OldLB ? 0 : Score +
M.MyShift;
2374 unsigned OtherShifted =
2375 OtherScore <=
M.OtherLB ? 0 : OtherScore +
M.OtherShift;
2376 Score = std::max(MyShifted, OtherShifted);
2377 return OtherShifted > MyShifted;
2385bool WaitcntBrackets::merge(
const WaitcntBrackets &
Other) {
2386 bool StrictDom =
false;
2388 VgprUB = std::max(VgprUB,
Other.VgprUB);
2389 SgprUB = std::max(SgprUB,
Other.SgprUB);
2391 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
2393 const unsigned *WaitEventMaskForInst =
Context->WaitEventMaskForInst;
2394 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[
T];
2395 const unsigned OtherEvents =
Other.PendingEvents & WaitEventMaskForInst[
T];
2396 if (OtherEvents & ~OldEvents)
2398 PendingEvents |= OtherEvents;
2401 const unsigned MyPending = ScoreUBs[
T] - ScoreLBs[
T];
2402 const unsigned OtherPending =
Other.ScoreUBs[
T] -
Other.ScoreLBs[
T];
2403 const unsigned NewUB = ScoreLBs[
T] + std::max(MyPending, OtherPending);
2404 if (NewUB < ScoreLBs[
T])
2408 M.OldLB = ScoreLBs[
T];
2409 M.OtherLB =
Other.ScoreLBs[
T];
2410 M.MyShift = NewUB - ScoreUBs[
T];
2411 M.OtherShift = NewUB -
Other.ScoreUBs[
T];
2413 ScoreUBs[
T] = NewUB;
2415 StrictDom |= mergeScore(M, LastFlat[
T],
Other.LastFlat[
T]);
2418 StrictDom |= mergeScore(M, LastGDS,
Other.LastGDS);
2421 StrictDom |= mergeScore(M, SCCScore,
Other.SCCScore);
2422 if (
Other.hasPendingEvent(SCC_WRITE)) {
2423 unsigned OldEventsHasSCCWrite = OldEvents & (1 << SCC_WRITE);
2424 if (!OldEventsHasSCCWrite) {
2425 PendingSCCWrite =
Other.PendingSCCWrite;
2426 }
else if (PendingSCCWrite !=
Other.PendingSCCWrite) {
2427 PendingSCCWrite =
nullptr;
2432 for (
int J = 0; J <= VgprUB; J++)
2433 StrictDom |= mergeScore(M, VgprScores[
T][J],
Other.VgprScores[
T][J]);
2435 if (isSmemCounter(
T)) {
2436 unsigned Idx = getSgprScoresIdx(
T);
2437 for (
int J = 0; J <= SgprUB; J++)
2439 mergeScore(M, SgprScores[Idx][J],
Other.SgprScores[Idx][J]);
2443 for (
int J = 0; J <= VgprUB; J++) {
2444 unsigned char NewVmemTypes = VgprVmemTypes[J] |
Other.VgprVmemTypes[J];
2445 StrictDom |= NewVmemTypes != VgprVmemTypes[J];
2446 VgprVmemTypes[J] = NewVmemTypes;
2454 return Opcode == AMDGPU::S_WAITCNT ||
2457 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2458 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2459 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
2464bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
2465 MachineBasicBlock &
Block,
2466 WaitcntBrackets &ScoreBrackets) {
2470 dbgs() <<
"*** Begin Block: ";
2472 ScoreBrackets.dump();
2478 bool VCCZCorrect =
true;
2479 if (
ST->hasReadVCCZBug()) {
2482 VCCZCorrect =
false;
2483 }
else if (!
ST->partialVCCWritesUpdateVCCZ()) {
2486 VCCZCorrect =
false;
2490 MachineInstr *OldWaitcntInstr =
nullptr;
2495 MachineInstr &Inst = *Iter;
2504 if (!OldWaitcntInstr)
2505 OldWaitcntInstr = &Inst;
2510 bool FlushVmCnt =
Block.getFirstTerminator() == Inst &&
2511 isPreheaderToFlush(
Block, ScoreBrackets);
2514 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2516 OldWaitcntInstr =
nullptr;
2522 if (
ST->hasReadVCCZBug() || !
ST->partialVCCWritesUpdateVCCZ()) {
2526 if (!
ST->partialVCCWritesUpdateVCCZ())
2527 VCCZCorrect =
false;
2536 if (
ST->hasReadVCCZBug() &&
2537 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2540 VCCZCorrect =
false;
2548 if (
TII->isSMRD(Inst)) {
2549 for (
const MachineMemOperand *Memop : Inst.
memoperands()) {
2552 if (!Memop->isInvariant()) {
2553 const Value *Ptr = Memop->getValue();
2557 if (
ST->hasReadVCCZBug()) {
2559 VCCZCorrect =
false;
2563 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2565 Modified |= insertForcedWaitAfter(Inst,
Block, ScoreBrackets);
2569 ScoreBrackets.dump();
2579 TII->
get(
ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2591 AMDGPU::Waitcnt
Wait;
2592 if (
Block.getFirstTerminator() ==
Block.end() &&
2593 isPreheaderToFlush(
Block, ScoreBrackets)) {
2594 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2596 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2598 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2607 dbgs() <<
"*** End Block: ";
2609 ScoreBrackets.dump();
2617bool SIInsertWaitcnts::isPreheaderToFlush(
2618 MachineBasicBlock &
MBB,
const WaitcntBrackets &ScoreBrackets) {
2619 auto [Iterator, IsInserted] = PreheadersToFlush.
try_emplace(&
MBB,
false);
2621 return Iterator->second;
2632 shouldFlushVmCnt(Loop, ScoreBrackets)) {
2633 Iterator->second =
true;
2640bool SIInsertWaitcnts::isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const {
2642 return TII->mayAccessVMEMThroughFlat(
MI);
2654bool SIInsertWaitcnts::shouldFlushVmCnt(MachineLoop *
ML,
2655 const WaitcntBrackets &Brackets) {
2656 bool HasVMemLoad =
false;
2657 bool HasVMemStore =
false;
2658 bool UsesVgprLoadedOutside =
false;
2659 DenseSet<Register> VgprUse;
2660 DenseSet<Register> VgprDef;
2662 for (MachineBasicBlock *
MBB :
ML->blocks()) {
2663 for (MachineInstr &
MI : *
MBB) {
2664 if (isVMEMOrFlatVMEM(
MI)) {
2665 HasVMemLoad |=
MI.mayLoad();
2666 HasVMemStore |=
MI.mayStore();
2669 for (
const MachineOperand &
Op :
MI.all_uses()) {
2670 if (
Op.isDebug() || !
TRI->isVectorRegister(*
MRI,
Op.getReg()))
2672 RegInterval
Interval = Brackets.getRegInterval(&
MI,
Op);
2682 if (Brackets.getRegScore(RegNo, LOAD_CNT) >
2683 Brackets.getScoreLB(LOAD_CNT) ||
2684 Brackets.getRegScore(RegNo, SAMPLE_CNT) >
2685 Brackets.getScoreLB(SAMPLE_CNT) ||
2686 Brackets.getRegScore(RegNo, BVH_CNT) >
2687 Brackets.getScoreLB(BVH_CNT)) {
2688 UsesVgprLoadedOutside =
true;
2695 if (isVMEMOrFlatVMEM(
MI) &&
MI.mayLoad()) {
2696 for (
const MachineOperand &
Op :
MI.all_defs()) {
2697 RegInterval
Interval = Brackets.getRegInterval(&
MI,
Op);
2709 if (!
ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2711 return HasVMemLoad && UsesVgprLoadedOutside &&
ST->hasVmemWriteVgprInOrder();
2714bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
2715 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2717 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2719 if (
auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2720 AA = &AAR->getAAResults();
2722 return SIInsertWaitcnts(MLI, PDT, AA).run(MF);
2734 if (!SIInsertWaitcnts(MLI, PDT,
AA).
run(MF))
2739 .preserve<AAManager>();
2744 TII = ST->getInstrInfo();
2745 TRI = &
TII->getRegisterInfo();
2751 if (ST->hasExtendedWaitCounts()) {
2752 MaxCounter = NUM_EXTENDED_INST_CNTS;
2753 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2754 WCG = &WCGGFX12Plus;
2756 MaxCounter = NUM_NORMAL_INST_CNTS;
2757 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF, MaxCounter);
2761 for (
auto T : inst_counter_types())
2762 ForceEmitWaitcnt[
T] =
false;
2764 WaitEventMaskForInst = WCG->getWaitEventMask();
2766 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2768 if (
ST->hasExtendedWaitCounts()) {
2782 [[maybe_unused]]
unsigned NumVGPRsMax =
2784 [[maybe_unused]]
unsigned NumSGPRsMax =
ST->getAddressableNumSGPRs();
2785 assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
2786 assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
2791 MachineBasicBlock &EntryBB = MF.
front();
2802 I !=
E && (
I->isPHI() ||
I->isMetaInstruction()); ++
I)
2805 if (
ST->hasExtendedWaitCounts()) {
2808 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2809 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT)
2812 if (!
ST->hasImageInsts() &&
2813 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
2817 TII->
get(instrsForExtendedCounterTypes[CT]))
2824 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(
this);
2825 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2826 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2833 for (
auto *
MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
2836 std::unique_ptr<WaitcntBrackets> Brackets;
2841 for (
auto BII = BlockInfos.
begin(), BIE = BlockInfos.
end(); BII != BIE;
2843 MachineBasicBlock *
MBB = BII->first;
2844 BlockInfo &BI = BII->second;
2850 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2852 *Brackets = *BI.Incoming;
2855 Brackets = std::make_unique<WaitcntBrackets>(
this);
2860 Brackets->~WaitcntBrackets();
2861 new (Brackets.get()) WaitcntBrackets(
this);
2865 Modified |= insertWaitcntInBlock(MF, *
MBB, *Brackets);
2868 if (Brackets->hasPendingEvent()) {
2869 BlockInfo *MoveBracketsToSucc =
nullptr;
2871 auto *SuccBII = BlockInfos.
find(Succ);
2872 BlockInfo &SuccBI = SuccBII->second;
2873 if (!SuccBI.Incoming) {
2874 SuccBI.Dirty =
true;
2875 if (SuccBII <= BII) {
2879 if (!MoveBracketsToSucc) {
2880 MoveBracketsToSucc = &SuccBI;
2882 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2884 }
else if (SuccBI.Incoming->merge(*Brackets)) {
2885 SuccBI.Dirty =
true;
2886 if (SuccBII <= BII) {
2892 if (MoveBracketsToSucc)
2893 MoveBracketsToSucc->Incoming = std::move(Brackets);
2898 if (
ST->hasScalarStores()) {
2899 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
2900 bool HaveScalarStores =
false;
2902 for (MachineBasicBlock &
MBB : MF) {
2903 for (MachineInstr &
MI :
MBB) {
2904 if (!HaveScalarStores &&
TII->isScalarStore(
MI))
2905 HaveScalarStores =
true;
2907 if (
MI.getOpcode() == AMDGPU::S_ENDPGM ||
2908 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2913 if (HaveScalarStores) {
2922 for (MachineBasicBlock *
MBB : EndPgmBlocks) {
2923 bool SeenDCacheWB =
false;
2927 if (
I->getOpcode() == AMDGPU::S_DCACHE_WB)
2928 SeenDCacheWB =
true;
2929 else if (
TII->isScalarStore(*
I))
2930 SeenDCacheWB =
false;
2933 if ((
I->getOpcode() == AMDGPU::S_ENDPGM ||
2934 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
2950 for (MachineInstr *
MI : ReleaseVGPRInsts) {
2952 TII->
get(AMDGPU::S_ALLOC_VGPR))
2957 if (!ReleaseVGPRInsts.empty() &&
2958 (MF.getFrameInfo().hasCalls() ||
2959 ST->getOccupancyWithNumVGPRs(
2960 TRI->getNumUsedPhysRegs(*
MRI, AMDGPU::VGPR_32RegClass),
2963 for (MachineInstr *
MI : ReleaseVGPRInsts) {
2964 if (
ST->requiresNopBeforeDeallocVGPRs()) {
2970 TII->
get(AMDGPU::S_SENDMSG))
2976 ReleaseVGPRInsts.clear();
2977 PreheadersToFlush.
clear();
2978 SLoadAddresses.
clear();
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const TargetInstrInfo & TII
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.
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.
std::pair< uint64_t, uint64_t > Interval
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.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
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...
unsigned getDynamicVGPRBlockSize() const
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...
MCRegister getMCReg(MCRegister Reg, const MCSubtargetInfo &STI)
If Reg is a pseudo reg, return the correct hardware register given STI otherwise return Reg.
bool isHi16Reg(MCRegister Reg, const MCRegisterInfo &MRI)
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
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
char & SIInsertWaitcntsID
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...
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
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