41#define DEBUG_TYPE "si-insert-waitcnts"
44 "Force emit s_waitcnt expcnt(0) instrs");
46 "Force emit s_waitcnt lgkmcnt(0) instrs");
48 "Force emit s_waitcnt vmcnt(0) instrs");
52 cl::desc(
"Force all waitcnt instrs to be emitted as "
53 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
67 SAMPLE_CNT = NUM_NORMAL_INST_CNTS,
70 NUM_EXTENDED_INST_CNTS,
71 NUM_INST_CNTS = NUM_EXTENDED_INST_CNTS
85auto inst_counter_types(InstCounterType MaxCounter = NUM_INST_CNTS) {
86 return enum_seq(LOAD_CNT, MaxCounter);
89using RegInterval = std::pair<int, int>;
91struct HardwareLimits {
96 unsigned SamplecntMax;
101struct RegisterEncoding {
111 VMEM_SAMPLER_READ_ACCESS,
112 VMEM_BVH_READ_ACCESS,
114 SCRATCH_WRITE_ACCESS,
134enum RegisterMapping {
135 SQ_MAX_PGM_VGPRS = 512,
137 SQ_MAX_PGM_SGPRS = 256,
145 NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_EXTRA_VGPRS,
166static const unsigned instrsForExtendedCounterTypes[NUM_EXTENDED_INST_CNTS] = {
167 AMDGPU::S_WAIT_LOADCNT, AMDGPU::S_WAIT_DSCNT, AMDGPU::S_WAIT_EXPCNT,
168 AMDGPU::S_WAIT_STORECNT, AMDGPU::S_WAIT_SAMPLECNT, AMDGPU::S_WAIT_BVHCNT,
169 AMDGPU::S_WAIT_KMCNT};
177static bool isNormalMode(InstCounterType MaxCounter) {
178 return MaxCounter == NUM_NORMAL_INST_CNTS;
183 assert(updateVMCntOnly(Inst));
186 return VMEM_NOSAMPLER;
193 return BaseInfo->
BVH ? VMEM_BVH
207 return Wait.StoreCnt;
209 return Wait.SampleCnt;
220 unsigned &WC = getCounterRef(
Wait,
T);
221 WC = std::min(WC, Count);
225 getCounterRef(
Wait,
T) = ~0
u;
229 return getCounterRef(
Wait,
T);
233InstCounterType eventCounter(
const unsigned *masks, WaitEventType E) {
234 for (
auto T : inst_counter_types()) {
235 if (masks[
T] & (1 << E))
249class WaitcntBrackets {
251 WaitcntBrackets(
const GCNSubtarget *SubTarget, InstCounterType MaxCounter,
252 HardwareLimits Limits, RegisterEncoding Encoding,
253 const unsigned *WaitEventMaskForInst,
254 InstCounterType SmemAccessCounter)
255 :
ST(SubTarget), MaxCounter(MaxCounter), Limits(Limits),
256 Encoding(Encoding), WaitEventMaskForInst(WaitEventMaskForInst),
257 SmemAccessCounter(SmemAccessCounter) {}
259 unsigned getWaitCountMax(InstCounterType
T)
const {
262 return Limits.LoadcntMax;
264 return Limits.DscntMax;
266 return Limits.ExpcntMax;
268 return Limits.StorecntMax;
270 return Limits.SamplecntMax;
272 return Limits.BvhcntMax;
274 return Limits.KmcntMax;
281 unsigned getScoreLB(InstCounterType
T)
const {
286 unsigned getScoreUB(InstCounterType
T)
const {
291 unsigned getScoreRange(InstCounterType
T)
const {
292 return getScoreUB(
T) - getScoreLB(
T);
295 unsigned getRegScore(
int GprNo, InstCounterType
T)
const {
296 if (GprNo < NUM_ALL_VGPRS) {
297 return VgprScores[
T][GprNo];
299 assert(
T == SmemAccessCounter);
300 return SgprScores[GprNo - NUM_ALL_VGPRS];
310 bool counterOutOfOrder(InstCounterType
T)
const;
312 void simplifyWaitcnt(InstCounterType
T,
unsigned &Count)
const;
314 void determineWait(InstCounterType
T, RegInterval
Interval,
316 void determineWait(InstCounterType
T,
int RegNo,
318 determineWait(
T, {RegNo, RegNo + 1},
Wait);
322 void applyWaitcnt(InstCounterType
T,
unsigned Count);
327 unsigned hasPendingEvent()
const {
return PendingEvents; }
328 unsigned hasPendingEvent(WaitEventType E)
const {
329 return PendingEvents & (1 << E);
331 unsigned hasPendingEvent(InstCounterType
T)
const {
332 unsigned HasPending = PendingEvents & WaitEventMaskForInst[
T];
333 assert((HasPending != 0) == (getScoreRange(
T) != 0));
337 bool hasMixedPendingEvents(InstCounterType
T)
const {
338 unsigned Events = hasPendingEvent(
T);
340 return Events & (Events - 1);
343 bool hasPendingFlat()
const {
344 return ((LastFlat[DS_CNT] > ScoreLBs[DS_CNT] &&
345 LastFlat[DS_CNT] <= ScoreUBs[DS_CNT]) ||
346 (LastFlat[LOAD_CNT] > ScoreLBs[LOAD_CNT] &&
347 LastFlat[LOAD_CNT] <= ScoreUBs[LOAD_CNT]));
350 void setPendingFlat() {
351 LastFlat[LOAD_CNT] = ScoreUBs[LOAD_CNT];
352 LastFlat[DS_CNT] = ScoreUBs[DS_CNT];
357 bool hasOtherPendingVmemTypes(RegInterval
Interval, VmemType V)
const {
359 assert(RegNo < NUM_ALL_VGPRS);
360 if (VgprVmemTypes[RegNo] & ~(1 << V))
366 void clearVgprVmemTypes(RegInterval
Interval) {
368 assert(RegNo < NUM_ALL_VGPRS);
369 VgprVmemTypes[RegNo] = 0;
373 void setStateOnFunctionEntryOrReturn() {
374 setScoreUB(STORE_CNT, getScoreUB(STORE_CNT) + getWaitCountMax(STORE_CNT));
375 PendingEvents |= WaitEventMaskForInst[STORE_CNT];
392 static bool mergeScore(
const MergeInfo &M,
unsigned &Score,
393 unsigned OtherScore);
395 void setScoreLB(InstCounterType
T,
unsigned Val) {
400 void setScoreUB(InstCounterType
T,
unsigned Val) {
407 if (getScoreRange(EXP_CNT) > getWaitCountMax(EXP_CNT))
411 void setRegScore(
int GprNo, InstCounterType
T,
unsigned Val) {
412 setScoreByInterval({GprNo, GprNo + 1},
T, Val);
415 void setScoreByInterval(RegInterval
Interval, InstCounterType CntTy,
424 InstCounterType MaxCounter = NUM_EXTENDED_INST_CNTS;
425 HardwareLimits Limits = {};
426 RegisterEncoding Encoding = {};
427 const unsigned *WaitEventMaskForInst;
428 InstCounterType SmemAccessCounter;
429 unsigned ScoreLBs[NUM_INST_CNTS] = {0};
430 unsigned ScoreUBs[NUM_INST_CNTS] = {0};
431 unsigned PendingEvents = 0;
433 unsigned LastFlat[NUM_INST_CNTS] = {0};
438 unsigned VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS] = {{0}};
441 unsigned SgprScores[SQ_MAX_PGM_SGPRS] = {0};
444 unsigned char VgprVmemTypes[NUM_ALL_VGPRS] = {0};
456class WaitcntGenerator {
461 InstCounterType MaxCounter;
465 WaitcntGenerator() =
default;
466 WaitcntGenerator(
const MachineFunction &MF, InstCounterType MaxCounter)
474 bool isOptNone()
const {
return OptNone; }
488 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
503 virtual const unsigned *getWaitEventMask()
const = 0;
507 virtual AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const = 0;
509 virtual ~WaitcntGenerator() =
default;
512 static constexpr unsigned
513 eventMask(std::initializer_list<WaitEventType> Events) {
515 for (
auto &E : Events)
522class WaitcntGeneratorPreGFX12 :
public WaitcntGenerator {
524 WaitcntGeneratorPreGFX12() =
default;
526 : WaitcntGenerator(MF, NUM_NORMAL_INST_CNTS) {}
529 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
537 const unsigned *getWaitEventMask()
const override {
540 static const unsigned WaitEventMaskForInstPreGFX12[NUM_INST_CNTS] = {
541 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS,
542 VMEM_BVH_READ_ACCESS}),
543 eventMask({SMEM_ACCESS, LDS_ACCESS, GDS_ACCESS, SQ_MESSAGE}),
544 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
545 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
546 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
551 return WaitEventMaskForInstPreGFX12;
557class WaitcntGeneratorGFX12Plus :
public WaitcntGenerator {
559 WaitcntGeneratorGFX12Plus() =
default;
561 InstCounterType MaxCounter)
562 : WaitcntGenerator(MF, MaxCounter) {}
565 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
573 const unsigned *getWaitEventMask()
const override {
576 static const unsigned WaitEventMaskForInstGFX12Plus[NUM_INST_CNTS] = {
577 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS}),
578 eventMask({LDS_ACCESS, GDS_ACCESS}),
579 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
580 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
581 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
582 eventMask({VMEM_SAMPLER_READ_ACCESS}),
583 eventMask({VMEM_BVH_READ_ACCESS}),
584 eventMask({SMEM_ACCESS, SQ_MESSAGE})};
586 return WaitEventMaskForInstGFX12Plus;
606 std::unique_ptr<WaitcntBrackets>
Incoming;
610 InstCounterType SmemAccessCounter;
614 bool ForceEmitWaitcnt[NUM_INST_CNTS];
619 WaitcntGeneratorPreGFX12 WCGPreGFX12;
620 WaitcntGeneratorGFX12Plus WCGGFX12Plus;
622 WaitcntGenerator *WCG =
nullptr;
628 InstCounterType MaxCounter = NUM_NORMAL_INST_CNTS;
634 (void)ForceExpCounter;
635 (void)ForceLgkmCounter;
636 (void)ForceVMCounter;
639 bool shouldFlushVmCnt(
MachineLoop *
ML, WaitcntBrackets &Brackets);
641 WaitcntBrackets &ScoreBrackets);
646 return "SI insert wait instructions";
658 bool isForceEmitWaitcnt()
const {
659 for (
auto T : inst_counter_types())
660 if (ForceEmitWaitcnt[
T])
665 void setForceEmitWaitcnt() {
671 ForceEmitWaitcnt[
EXP_CNT] =
true;
673 ForceEmitWaitcnt[
EXP_CNT] =
false;
678 ForceEmitWaitcnt[DS_CNT] =
true;
679 ForceEmitWaitcnt[KM_CNT] =
true;
681 ForceEmitWaitcnt[DS_CNT] =
false;
682 ForceEmitWaitcnt[KM_CNT] =
false;
687 ForceEmitWaitcnt[LOAD_CNT] =
true;
688 ForceEmitWaitcnt[SAMPLE_CNT] =
true;
689 ForceEmitWaitcnt[BVH_CNT] =
true;
691 ForceEmitWaitcnt[LOAD_CNT] =
false;
692 ForceEmitWaitcnt[SAMPLE_CNT] =
false;
693 ForceEmitWaitcnt[BVH_CNT] =
false;
700 WaitEventType getVmemWaitEventType(
const MachineInstr &Inst)
const {
702 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
703 VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
715 return SCRATCH_WRITE_ACCESS;
716 return VMEM_WRITE_ACCESS;
719 return VMEM_READ_ACCESS;
720 return VmemReadMapping[getVmemType(Inst)];
727 WaitcntBrackets &ScoreBrackets,
735 WaitcntBrackets *ScoreBrackets);
737 WaitcntBrackets &ScoreBrackets);
742RegInterval WaitcntBrackets::getRegInterval(
const MachineInstr *
MI,
746 if (!
TRI->isInAllocatableClass(
Op.getReg()))
758 if (
TRI->isVectorRegister(*
MRI,
Op.getReg())) {
759 assert(Reg >= Encoding.VGPR0 && Reg <= Encoding.VGPRL);
762 Result.first += AGPR_OFFSET;
764 }
else if (
TRI->isSGPRReg(*
MRI,
Op.getReg())) {
765 assert(Reg >= Encoding.SGPR0 && Reg < SQ_MAX_PGM_SGPRS);
766 Result.first =
Reg - Encoding.SGPR0 + NUM_ALL_VGPRS;
768 Result.first < SQ_MAX_PGM_SGPRS + NUM_ALL_VGPRS);
776 unsigned Size =
TRI->getRegSizeInBits(*RC);
782void WaitcntBrackets::setScoreByInterval(RegInterval
Interval,
783 InstCounterType CntTy,
786 if (RegNo < NUM_ALL_VGPRS) {
787 VgprUB = std::max(VgprUB, RegNo);
788 VgprScores[CntTy][RegNo] = Score;
790 assert(CntTy == SmemAccessCounter);
791 SgprUB = std::max(SgprUB, RegNo - NUM_ALL_VGPRS);
792 SgprScores[RegNo - NUM_ALL_VGPRS] = Score;
801 InstCounterType CntTy,
unsigned Score) {
803 setScoreByInterval(
Interval, CntTy, Score);
810 InstCounterType
T = eventCounter(WaitEventMaskForInst, E);
812 unsigned UB = getScoreUB(
T);
813 unsigned CurrScore = UB + 1;
819 PendingEvents |= 1 << E;
820 setScoreUB(
T, CurrScore);
828 if (
const auto *AddrOp =
TII->getNamedOperand(Inst, AMDGPU::OpName::addr))
829 setScoreByOperand(&Inst,
TRI,
MRI, *AddrOp, EXP_CNT, CurrScore);
832 if (
const auto *Data0 =
833 TII->getNamedOperand(Inst, AMDGPU::OpName::data0))
834 setScoreByOperand(&Inst,
TRI,
MRI, *Data0, EXP_CNT, CurrScore);
835 if (
const auto *Data1 =
836 TII->getNamedOperand(Inst, AMDGPU::OpName::data1))
837 setScoreByOperand(&Inst,
TRI,
MRI, *Data1, EXP_CNT, CurrScore);
840 Inst.
getOpcode() != AMDGPU::DS_CONSUME &&
841 Inst.
getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
843 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
844 setScoreByOperand(&Inst,
TRI,
MRI,
Op, EXP_CNT, CurrScore);
847 }
else if (
TII->isFLAT(Inst)) {
849 setScoreByOperand(&Inst,
TRI,
MRI,
850 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
853 setScoreByOperand(&Inst,
TRI,
MRI,
854 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
857 }
else if (
TII->isMIMG(Inst)) {
862 setScoreByOperand(&Inst,
TRI,
MRI,
863 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
866 }
else if (
TII->isMTBUF(Inst)) {
870 }
else if (
TII->isMUBUF(Inst)) {
875 setScoreByOperand(&Inst,
TRI,
MRI,
876 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
879 }
else if (
TII->isLDSDIR(Inst)) {
881 setScoreByOperand(&Inst,
TRI,
MRI,
882 *
TII->getNamedOperand(Inst, AMDGPU::OpName::vdst),
885 if (
TII->isEXP(Inst)) {
891 if (
TRI->isVGPR(*
MRI, DefMO.getReg())) {
892 setScoreByOperand(&Inst,
TRI,
MRI, DefMO, EXP_CNT, CurrScore);
897 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
898 setScoreByOperand(&Inst,
TRI,
MRI,
Op, EXP_CNT, CurrScore);
913 if (
T == LOAD_CNT ||
T == SAMPLE_CNT ||
T == BVH_CNT) {
914 if (
Interval.first >= NUM_ALL_VGPRS)
916 if (updateVMCntOnly(Inst)) {
921 VmemType
V = getVmemType(Inst);
923 VgprVmemTypes[RegNo] |= 1 <<
V;
926 setScoreByInterval(
Interval,
T, CurrScore);
929 (
TII->isDS(Inst) ||
TII->mayWriteLDSThroughDMA(Inst))) {
934 if (!
MemOp->isStore() ||
939 auto AAI =
MemOp->getAAInfo();
947 if (!AAI || !AAI.Scope)
949 for (
unsigned I = 0, E = LDSDMAStores.size();
I != E && !Slot; ++
I) {
950 for (
const auto *
MemOp : LDSDMAStores[
I]->memoperands()) {
951 if (
MemOp->isStore() && AAI ==
MemOp->getAAInfo()) {
957 if (Slot || LDSDMAStores.size() == NUM_EXTRA_VGPRS - 1)
959 LDSDMAStores.push_back(&Inst);
960 Slot = LDSDMAStores.size();
963 setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS + Slot,
T, CurrScore);
965 setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS,
T, CurrScore);
972 for (
auto T : inst_counter_types(MaxCounter)) {
973 unsigned SR = getScoreRange(
T);
977 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"LOAD" :
"VM") <<
"_CNT("
981 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"DS" :
"LGKM") <<
"_CNT("
985 OS <<
" EXP_CNT(" << SR <<
"): ";
988 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"STORE" :
"VS") <<
"_CNT("
992 OS <<
" SAMPLE_CNT(" << SR <<
"): ";
995 OS <<
" BVH_CNT(" << SR <<
"): ";
998 OS <<
" KM_CNT(" << SR <<
"): ";
1001 OS <<
" UNKNOWN(" << SR <<
"): ";
1007 unsigned LB = getScoreLB(
T);
1009 for (
int J = 0; J <= VgprUB; J++) {
1010 unsigned RegScore = getRegScore(J,
T);
1013 unsigned RelScore = RegScore - LB - 1;
1014 if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) {
1015 OS << RelScore <<
":v" << J <<
" ";
1017 OS << RelScore <<
":ds ";
1021 if (
T == SmemAccessCounter) {
1022 for (
int J = 0; J <= SgprUB; J++) {
1023 unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS,
T);
1026 unsigned RelScore = RegScore - LB - 1;
1027 OS << RelScore <<
":s" << J <<
" ";
1039 simplifyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1040 simplifyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1041 simplifyWaitcnt(DS_CNT,
Wait.DsCnt);
1042 simplifyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1043 simplifyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1044 simplifyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1045 simplifyWaitcnt(KM_CNT,
Wait.KmCnt);
1048void WaitcntBrackets::simplifyWaitcnt(InstCounterType
T,
1049 unsigned &Count)
const {
1053 if (Count >= getScoreRange(
T))
1057void WaitcntBrackets::determineWait(InstCounterType
T, RegInterval
Interval,
1059 const unsigned LB = getScoreLB(
T);
1060 const unsigned UB = getScoreUB(
T);
1062 unsigned ScoreToWait = getRegScore(RegNo,
T);
1066 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1067 if ((
T == LOAD_CNT ||
T == DS_CNT) && hasPendingFlat() &&
1068 !
ST->hasFlatLgkmVMemCountInOrder()) {
1072 addWait(
Wait,
T, 0);
1073 }
else if (counterOutOfOrder(
T)) {
1077 addWait(
Wait,
T, 0);
1081 unsigned NeededWait =
1082 std::min(UB - ScoreToWait, getWaitCountMax(
T) - 1);
1083 addWait(
Wait,
T, NeededWait);
1090 applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1091 applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1092 applyWaitcnt(DS_CNT,
Wait.DsCnt);
1093 applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1094 applyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1095 applyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1096 applyWaitcnt(KM_CNT,
Wait.KmCnt);
1099void WaitcntBrackets::applyWaitcnt(InstCounterType
T,
unsigned Count) {
1100 const unsigned UB = getScoreUB(
T);
1104 if (counterOutOfOrder(
T))
1106 setScoreLB(
T, std::max(getScoreLB(
T), UB - Count));
1109 PendingEvents &= ~WaitEventMaskForInst[
T];
1115bool WaitcntBrackets::counterOutOfOrder(InstCounterType
T)
const {
1117 if (
T == SmemAccessCounter && hasPendingEvent(SMEM_ACCESS))
1119 return hasMixedPendingEvents(
T);
1129char SIInsertWaitcnts::
ID = 0;
1134 return new SIInsertWaitcnts();
1144 if (NewEnc == MO.
getImm())
1155 case AMDGPU::S_WAIT_LOADCNT:
1157 case AMDGPU::S_WAIT_EXPCNT:
1159 case AMDGPU::S_WAIT_STORECNT:
1161 case AMDGPU::S_WAIT_SAMPLECNT:
1163 case AMDGPU::S_WAIT_BVHCNT:
1165 case AMDGPU::S_WAIT_DSCNT:
1167 case AMDGPU::S_WAIT_KMCNT:
1174bool WaitcntGenerator::promoteSoftWaitCnt(
MachineInstr *Waitcnt)
const {
1188bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1189 WaitcntBrackets &ScoreBrackets,
MachineInstr &OldWaitcntInstr,
1192 assert(isNormalMode(MaxCounter));
1200 if (
II.isMetaInstruction())
1204 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1208 if (Opcode == AMDGPU::S_WAITCNT) {
1209 unsigned IEnc =
II.getOperand(0).getImm();
1212 ScoreBrackets.simplifyWaitcnt(OldWait);
1216 if (WaitcntInstr || (!
Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1217 II.eraseFromParent();
1222 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1223 assert(
II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1226 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1228 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1229 Wait.StoreCnt = std::min(
Wait.StoreCnt, OldVSCnt);
1231 if (WaitcntVsCntInstr || (!
Wait.hasWaitStoreCnt() && TrySimplify)) {
1232 II.eraseFromParent();
1235 WaitcntVsCntInstr = &
II;
1242 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1244 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1245 ScoreBrackets.applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1246 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1253 <<
"applyPreexistingWaitcnt\n"
1254 <<
"New Instr at block end: " << *WaitcntInstr <<
'\n'
1255 :
dbgs() <<
"applyPreexistingWaitcnt\n"
1256 <<
"Old Instr: " << *It
1257 <<
"New Instr: " << *WaitcntInstr <<
'\n');
1260 if (WaitcntVsCntInstr) {
1262 AMDGPU::OpName::simm16,
Wait.StoreCnt);
1263 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1265 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1266 Wait.StoreCnt = ~0
u;
1269 ?
dbgs() <<
"applyPreexistingWaitcnt\n"
1270 <<
"New Instr at block end: " << *WaitcntVsCntInstr
1272 :
dbgs() <<
"applyPreexistingWaitcnt\n"
1273 <<
"Old Instr: " << *It
1274 <<
"New Instr: " << *WaitcntVsCntInstr <<
'\n');
1282bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1286 assert(isNormalMode(MaxCounter));
1293 if (
Wait.hasWaitExceptStoreCnt()) {
1295 [[maybe_unused]]
auto SWaitInst =
1300 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1301 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1304 if (
Wait.hasWaitStoreCnt()) {
1307 [[maybe_unused]]
auto SWaitInst =
1314 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1315 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1322WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1327WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1335bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
1336 WaitcntBrackets &ScoreBrackets,
MachineInstr &OldWaitcntInstr,
1339 assert(!isNormalMode(MaxCounter));
1348 if (
II.isMetaInstruction())
1357 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1361 if (Opcode == AMDGPU::S_WAITCNT)
1364 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
1366 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1369 ScoreBrackets.simplifyWaitcnt(OldWait);
1371 UpdatableInstr = &CombinedLoadDsCntInstr;
1372 }
else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
1374 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1377 ScoreBrackets.simplifyWaitcnt(OldWait);
1379 UpdatableInstr = &CombinedStoreDsCntInstr;
1384 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1386 ScoreBrackets.simplifyWaitcnt(CT.value(), OldCnt);
1387 addWait(
Wait, CT.value(), OldCnt);
1388 UpdatableInstr = &WaitInstrs[CT.value()];
1392 if (!*UpdatableInstr) {
1393 *UpdatableInstr = &
II;
1395 II.eraseFromParent();
1400 if (CombinedLoadDsCntInstr) {
1408 if (
Wait.LoadCnt != ~0u &&
Wait.DsCnt != ~0u) {
1411 AMDGPU::OpName::simm16, NewEnc);
1412 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
1413 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1414 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1419 ?
dbgs() <<
"applyPreexistingWaitcnt\n"
1420 <<
"New Instr at block end: "
1421 << *CombinedLoadDsCntInstr <<
'\n'
1422 :
dbgs() <<
"applyPreexistingWaitcnt\n"
1423 <<
"Old Instr: " << *It <<
"New Instr: "
1424 << *CombinedLoadDsCntInstr <<
'\n');
1431 if (CombinedStoreDsCntInstr) {
1433 if (
Wait.StoreCnt != ~0u &&
Wait.DsCnt != ~0u) {
1436 AMDGPU::OpName::simm16, NewEnc);
1437 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
1438 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1439 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1440 Wait.StoreCnt = ~0
u;
1444 ?
dbgs() <<
"applyPreexistingWaitcnt\n"
1445 <<
"New Instr at block end: "
1446 << *CombinedStoreDsCntInstr <<
'\n'
1447 :
dbgs() <<
"applyPreexistingWaitcnt\n"
1448 <<
"Old Instr: " << *It <<
"New Instr: "
1449 << *CombinedStoreDsCntInstr <<
'\n');
1462 if (
Wait.DsCnt != ~0u) {
1471 if (
Wait.LoadCnt != ~0u) {
1472 WaitsToErase.
push_back(&WaitInstrs[LOAD_CNT]);
1473 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1474 }
else if (
Wait.StoreCnt != ~0u) {
1475 WaitsToErase.
push_back(&WaitInstrs[STORE_CNT]);
1476 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1483 (*WI)->eraseFromParent();
1489 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1490 if (!WaitInstrs[CT])
1493 unsigned NewCnt = getWait(
Wait, CT);
1494 if (NewCnt != ~0u) {
1496 AMDGPU::OpName::simm16, NewCnt);
1497 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
1499 ScoreBrackets.applyWaitcnt(CT, NewCnt);
1500 setNoWait(
Wait, CT);
1503 ?
dbgs() <<
"applyPreexistingWaitcnt\n"
1504 <<
"New Instr at block end: " << *WaitInstrs[CT]
1506 :
dbgs() <<
"applyPreexistingWaitcnt\n"
1507 <<
"Old Instr: " << *It
1508 <<
"New Instr: " << *WaitInstrs[CT] <<
'\n');
1519bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
1523 assert(!isNormalMode(MaxCounter));
1529 if (
Wait.DsCnt != ~0u) {
1532 if (
Wait.LoadCnt != ~0u) {
1540 }
else if (
Wait.StoreCnt != ~0u) {
1547 Wait.StoreCnt = ~0
u;
1555 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1556 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1563 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1564 unsigned Count = getWait(
Wait, CT);
1568 [[maybe_unused]]
auto SWaitInst =
1575 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1576 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1583 unsigned Opc =
MI.getOpcode();
1584 return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
1585 !
MI.getOperand(1).isUndef();
1613bool SIInsertWaitcnts::generateWaitcntInstBefore(
MachineInstr &
MI,
1614 WaitcntBrackets &ScoreBrackets,
1617 setForceEmitWaitcnt();
1619 if (
MI.isMetaInstruction())
1628 if (
MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
1629 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
1630 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL ||
1631 MI.getOpcode() == AMDGPU::BUFFER_GL0_INV ||
1632 MI.getOpcode() == AMDGPU::BUFFER_GL1_INV) {
1639 if (
MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
1640 MI.getOpcode() == AMDGPU::SI_RETURN ||
1641 MI.getOpcode() == AMDGPU::S_SETPC_B64_return ||
1643 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
false));
1651 else if (
MI.getOpcode() == AMDGPU::S_ENDPGM ||
1652 MI.getOpcode() == AMDGPU::S_ENDPGM_SAVED) {
1654 ScoreBrackets.getScoreRange(STORE_CNT) != 0 &&
1655 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS))
1659 else if ((
MI.getOpcode() == AMDGPU::S_SENDMSG ||
1660 MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
1661 ST->hasLegacyGeometry() &&
1672 if (
MI.modifiesRegister(AMDGPU::EXEC,
TRI)) {
1675 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1676 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1677 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1678 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1689 const auto &CallAddrOp = *
TII->getNamedOperand(
MI, AMDGPU::OpName::src0);
1690 if (CallAddrOp.isReg()) {
1691 RegInterval CallAddrOpInterval =
1692 ScoreBrackets.getRegInterval(&
MI,
MRI,
TRI, CallAddrOp);
1694 ScoreBrackets.determineWait(SmemAccessCounter, CallAddrOpInterval,
1697 if (
const auto *RtnAddrOp =
1698 TII->getNamedOperand(
MI, AMDGPU::OpName::dst)) {
1699 RegInterval RtnAddrOpInterval =
1700 ScoreBrackets.getRegInterval(&
MI,
MRI,
TRI, *RtnAddrOp);
1702 ScoreBrackets.determineWait(SmemAccessCounter, RtnAddrOpInterval,
1722 const Value *
Ptr = Memop->getValue();
1723 if (Memop->isStore() && SLoadAddresses.
count(
Ptr)) {
1724 addWait(
Wait, SmemAccessCounter, 0);
1728 unsigned AS = Memop->getAddrSpace();
1732 if (
TII->mayWriteLDSThroughDMA(
MI))
1736 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
1737 bool FoundAliasingStore =
false;
1744 if (
Ptr && Memop->getAAInfo() && Memop->getAAInfo().Scope) {
1745 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
1746 for (
unsigned I = 0, E = LDSDMAStores.size();
I != E; ++
I) {
1747 if (
MI.mayAlias(AA, *LDSDMAStores[
I],
true)) {
1748 FoundAliasingStore =
true;
1749 ScoreBrackets.determineWait(LOAD_CNT, RegNo +
I + 1,
Wait);
1753 if (!FoundAliasingStore)
1754 ScoreBrackets.determineWait(LOAD_CNT, RegNo,
Wait);
1755 if (Memop->isStore()) {
1756 ScoreBrackets.determineWait(EXP_CNT, RegNo,
Wait);
1766 if (
Op.isTied() &&
Op.isUse() &&
TII->doesNotReadTiedSource(
MI))
1771 const bool IsVGPR =
TRI->isVectorRegister(*
MRI,
Op.getReg());
1778 if (
Op.isImplicit() &&
MI.mayLoadOrStore())
1785 if (
Op.isUse() || !updateVMCntOnly(
MI) ||
1786 ScoreBrackets.hasOtherPendingVmemTypes(
Interval,
1788 !
ST->hasVmemWriteVgprInOrder()) {
1790 ScoreBrackets.determineWait(SAMPLE_CNT,
Interval,
Wait);
1792 ScoreBrackets.clearVgprVmemTypes(
Interval);
1794 if (
Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
1799 ScoreBrackets.determineWait(SmemAccessCounter,
Interval,
Wait);
1809 if (
TII->isBarrierStart(
MI.getOpcode()) &&
1810 !
ST->hasAutoWaitcntBeforeBarrier() && !
ST->supportsBackOffBarrier()) {
1811 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
true));
1818 if (ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
1824 ScoreBrackets.simplifyWaitcnt(
Wait);
1829 Wait = WCG->getAllZeroWaitcnt(
false);
1831 if (ForceEmitWaitcnt[LOAD_CNT])
1833 if (ForceEmitWaitcnt[EXP_CNT])
1835 if (ForceEmitWaitcnt[DS_CNT])
1837 if (ForceEmitWaitcnt[SAMPLE_CNT])
1839 if (ForceEmitWaitcnt[BVH_CNT])
1841 if (ForceEmitWaitcnt[KM_CNT])
1845 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
1847 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
1849 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
1853 return generateWaitcnt(
Wait,
MI.getIterator(), *
MI.getParent(), ScoreBrackets,
1860 WaitcntBrackets &ScoreBrackets,
1864 if (OldWaitcntInstr)
1868 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr,
Wait, It);
1872 ScoreBrackets.applyWaitcnt(
Wait);
1875 if (
Wait.ExpCnt != ~0u && It !=
Block.instr_end() &&
1878 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
1886 <<
"Update Instr: " << *It);
1889 if (WCG->createNewWaitcnt(
Block, It,
Wait))
1898bool SIInsertWaitcnts::mayAccessVMEMThroughFlat(
const MachineInstr &
MI)
const {
1906 if (
MI.memoperands_empty())
1915 unsigned AS = Memop->getAddrSpace();
1926bool SIInsertWaitcnts::mayAccessLDSThroughFlat(
const MachineInstr &
MI)
const {
1930 if (!
TII->usesLGKM_CNT(
MI))
1934 if (
ST->isTgSplitEnabled())
1939 if (
MI.memoperands_empty())
1944 unsigned AS = Memop->getAddrSpace();
1954bool SIInsertWaitcnts::mayAccessScratchThroughFlat(
1959 if (
TII->isFLATScratch(
MI))
1963 if (
TII->isFLATGlobal(
MI))
1968 if (
MI.memoperands_empty())
1973 unsigned AS = Memop->getAddrSpace();
1974 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
1980 return Opc == AMDGPU::GLOBAL_INV || Opc == AMDGPU::GLOBAL_WB ||
1981 Opc == AMDGPU::GLOBAL_WBINV;
1984void SIInsertWaitcnts::updateEventWaitcntAfter(
MachineInstr &Inst,
1985 WaitcntBrackets *ScoreBrackets) {
1991 if (
TII->isDS(Inst) &&
TII->usesLGKM_CNT(Inst)) {
1993 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
1994 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, GDS_ACCESS, Inst);
1995 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, GDS_GPR_LOCK, Inst);
1997 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, LDS_ACCESS, Inst);
1999 }
else if (
TII->isFLAT(Inst)) {
2006 int FlatASCount = 0;
2008 if (mayAccessVMEMThroughFlat(Inst)) {
2010 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, getVmemWaitEventType(Inst),
2014 if (mayAccessLDSThroughFlat(Inst)) {
2016 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, LDS_ACCESS, Inst);
2025 if (FlatASCount > 1)
2026 ScoreBrackets->setPendingFlat();
2029 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, getVmemWaitEventType(Inst),
2032 if (
ST->vmemWriteNeedsExpWaitcnt() &&
2034 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, VMW_GPR_LOCK, Inst);
2036 }
else if (
TII->isSMRD(Inst)) {
2037 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, SMEM_ACCESS, Inst);
2038 }
else if (Inst.
isCall()) {
2041 ScoreBrackets->applyWaitcnt(
2042 WCG->getAllZeroWaitcnt(
false));
2043 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2049 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, EXP_LDS_ACCESS, Inst);
2050 }
else if (
TII->isVINTERP(Inst)) {
2051 int64_t
Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2052 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2054 unsigned Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2056 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, EXP_PARAM_ACCESS, Inst);
2058 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, EXP_POS_ACCESS, Inst);
2060 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, EXP_GPR_LOCK, Inst);
2063 case AMDGPU::S_SENDMSG:
2064 case AMDGPU::S_SENDMSG_RTN_B32:
2065 case AMDGPU::S_SENDMSG_RTN_B64:
2066 case AMDGPU::S_SENDMSGHALT:
2067 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, SQ_MESSAGE, Inst);
2069 case AMDGPU::S_MEMTIME:
2070 case AMDGPU::S_MEMREALTIME:
2071 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_M0:
2072 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM:
2073 case AMDGPU::S_BARRIER_LEAVE:
2074 case AMDGPU::S_GET_BARRIER_STATE_M0:
2075 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2076 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, SMEM_ACCESS, Inst);
2082bool WaitcntBrackets::mergeScore(
const MergeInfo &M,
unsigned &Score,
2083 unsigned OtherScore) {
2084 unsigned MyShifted = Score <=
M.OldLB ? 0 : Score +
M.MyShift;
2085 unsigned OtherShifted =
2086 OtherScore <=
M.OtherLB ? 0 : OtherScore +
M.OtherShift;
2087 Score = std::max(MyShifted, OtherShifted);
2088 return OtherShifted > MyShifted;
2096bool WaitcntBrackets::merge(
const WaitcntBrackets &
Other) {
2097 bool StrictDom =
false;
2099 VgprUB = std::max(VgprUB,
Other.VgprUB);
2100 SgprUB = std::max(SgprUB,
Other.SgprUB);
2102 for (
auto T : inst_counter_types(MaxCounter)) {
2104 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[
T];
2105 const unsigned OtherEvents =
Other.PendingEvents & WaitEventMaskForInst[
T];
2106 if (OtherEvents & ~OldEvents)
2108 PendingEvents |= OtherEvents;
2111 const unsigned MyPending = ScoreUBs[
T] - ScoreLBs[
T];
2112 const unsigned OtherPending =
Other.ScoreUBs[
T] -
Other.ScoreLBs[
T];
2113 const unsigned NewUB = ScoreLBs[
T] + std::max(MyPending, OtherPending);
2114 if (NewUB < ScoreLBs[
T])
2118 M.OldLB = ScoreLBs[
T];
2119 M.OtherLB =
Other.ScoreLBs[
T];
2120 M.MyShift = NewUB - ScoreUBs[
T];
2121 M.OtherShift = NewUB -
Other.ScoreUBs[
T];
2123 ScoreUBs[
T] = NewUB;
2125 StrictDom |= mergeScore(M, LastFlat[
T],
Other.LastFlat[
T]);
2127 for (
int J = 0; J <= VgprUB; J++)
2128 StrictDom |= mergeScore(M, VgprScores[
T][J],
Other.VgprScores[
T][J]);
2130 if (
T == SmemAccessCounter) {
2131 for (
int J = 0; J <= SgprUB; J++)
2132 StrictDom |= mergeScore(M, SgprScores[J],
Other.SgprScores[J]);
2136 for (
int J = 0; J <= VgprUB; J++) {
2137 unsigned char NewVmemTypes = VgprVmemTypes[J] |
Other.VgprVmemTypes[J];
2138 StrictDom |= NewVmemTypes != VgprVmemTypes[J];
2139 VgprVmemTypes[J] = NewVmemTypes;
2147 return Opcode == AMDGPU::S_WAITCNT ||
2150 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2151 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2158 WaitcntBrackets &ScoreBrackets) {
2162 dbgs() <<
"*** Block" <<
Block.getNumber() <<
" ***";
2163 ScoreBrackets.dump();
2169 bool VCCZCorrect =
true;
2170 if (
ST->hasReadVCCZBug()) {
2173 VCCZCorrect =
false;
2174 }
else if (!
ST->partialVCCWritesUpdateVCCZ()) {
2177 VCCZCorrect =
false;
2184 E =
Block.instr_end();
2191 if (!OldWaitcntInstr)
2192 OldWaitcntInstr = &Inst;
2197 bool FlushVmCnt =
Block.getFirstTerminator() == Inst &&
2198 isPreheaderToFlush(
Block, ScoreBrackets);
2201 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2203 OldWaitcntInstr =
nullptr;
2206 bool RestoreVCCZ = !VCCZCorrect &&
readsVCCZ(Inst);
2209 if (
ST->hasReadVCCZBug() || !
ST->partialVCCWritesUpdateVCCZ()) {
2213 if (!
ST->partialVCCWritesUpdateVCCZ())
2214 VCCZCorrect =
false;
2223 if (
ST->hasReadVCCZBug() &&
2224 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2227 VCCZCorrect =
false;
2235 if (
TII->isSMRD(Inst)) {
2239 if (!Memop->isInvariant()) {
2240 const Value *
Ptr = Memop->getValue();
2244 if (
ST->hasReadVCCZBug()) {
2246 VCCZCorrect =
false;
2250 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2255 ScoreBrackets.simplifyWaitcnt(
Wait);
2257 ScoreBrackets,
nullptr);
2262 ScoreBrackets.dump();
2272 TII->get(
ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2285 if (
Block.getFirstTerminator() ==
Block.end() &&
2286 isPreheaderToFlush(
Block, ScoreBrackets)) {
2287 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2289 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2291 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2305 WaitcntBrackets &ScoreBrackets) {
2306 auto [Iterator, IsInserted] = PreheadersToFlush.
try_emplace(&
MBB,
false);
2308 return Iterator->second;
2319 shouldFlushVmCnt(
Loop, ScoreBrackets)) {
2320 Iterator->second =
true;
2327bool SIInsertWaitcnts::isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const {
2341 WaitcntBrackets &Brackets) {
2342 bool HasVMemLoad =
false;
2343 bool HasVMemStore =
false;
2344 bool UsesVgprLoadedOutside =
false;
2350 if (isVMEMOrFlatVMEM(
MI)) {
2354 HasVMemStore =
true;
2357 if (!
TRI->isVectorRegister(*
MRI,
Op.getReg()))
2369 if (Brackets.getRegScore(RegNo, LOAD_CNT) >
2370 Brackets.getScoreLB(LOAD_CNT) ||
2371 Brackets.getRegScore(RegNo, SAMPLE_CNT) >
2372 Brackets.getScoreLB(SAMPLE_CNT) ||
2373 Brackets.getRegScore(RegNo, BVH_CNT) >
2374 Brackets.getScoreLB(BVH_CNT)) {
2375 UsesVgprLoadedOutside =
true;
2382 if (isVMEMOrFlatVMEM(
MI) &&
MI.mayLoad()) {
2396 if (!
ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2398 return HasVMemLoad && UsesVgprLoadedOutside &&
ST->hasVmemWriteVgprInOrder();
2403 TII =
ST->getInstrInfo();
2404 TRI = &
TII->getRegisterInfo();
2407 MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2408 PDT = &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2409 if (
auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2410 AA = &AAR->getAAResults();
2414 if (
ST->hasExtendedWaitCounts()) {
2415 MaxCounter = NUM_EXTENDED_INST_CNTS;
2416 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2417 WCG = &WCGGFX12Plus;
2419 MaxCounter = NUM_NORMAL_INST_CNTS;
2420 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF);
2424 for (
auto T : inst_counter_types())
2425 ForceEmitWaitcnt[
T] =
false;
2427 const unsigned *WaitEventMaskForInst = WCG->getWaitEventMask();
2429 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2431 HardwareLimits Limits = {};
2432 if (
ST->hasExtendedWaitCounts()) {
2445 unsigned NumVGPRsMax =
ST->getAddressableNumVGPRs();
2446 unsigned NumSGPRsMax =
ST->getAddressableNumSGPRs();
2447 assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
2448 assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
2450 RegisterEncoding Encoding = {};
2453 Encoding.VGPRL = Encoding.VGPR0 + NumVGPRsMax - 1;
2456 Encoding.SGPRL = Encoding.SGPR0 + NumSGPRsMax - 1;
2472 I != E && (
I->isPHI() ||
I->isMetaInstruction()); ++
I)
2475 if (
ST->hasExtendedWaitCounts()) {
2478 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2479 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT)
2483 TII->get(instrsForExtendedCounterTypes[CT]))
2490 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(
2491 ST, MaxCounter, Limits, Encoding, WaitEventMaskForInst,
2493 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2494 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2504 std::unique_ptr<WaitcntBrackets> Brackets;
2509 for (
auto BII = BlockInfos.
begin(), BIE = BlockInfos.
end(); BII != BIE;
2512 BlockInfo &BI = BII->second;
2518 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2520 *Brackets = *BI.Incoming;
2523 Brackets = std::make_unique<WaitcntBrackets>(
2524 ST, MaxCounter, Limits, Encoding, WaitEventMaskForInst,
2527 *Brackets = WaitcntBrackets(ST, MaxCounter, Limits, Encoding,
2528 WaitEventMaskForInst, SmemAccessCounter);
2531 Modified |= insertWaitcntInBlock(MF, *
MBB, *Brackets);
2534 if (Brackets->hasPendingEvent()) {
2535 BlockInfo *MoveBracketsToSucc =
nullptr;
2537 auto *SuccBII = BlockInfos.
find(Succ);
2538 BlockInfo &SuccBI = SuccBII->second;
2539 if (!SuccBI.Incoming) {
2540 SuccBI.Dirty =
true;
2543 if (!MoveBracketsToSucc) {
2544 MoveBracketsToSucc = &SuccBI;
2546 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2548 }
else if (SuccBI.Incoming->merge(*Brackets)) {
2549 SuccBI.Dirty =
true;
2554 if (MoveBracketsToSucc)
2555 MoveBracketsToSucc->Incoming = std::move(Brackets);
2560 if (
ST->hasScalarStores()) {
2562 bool HaveScalarStores =
false;
2566 if (!HaveScalarStores &&
TII->isScalarStore(
MI))
2567 HaveScalarStores =
true;
2569 if (
MI.getOpcode() == AMDGPU::S_ENDPGM ||
2570 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2575 if (HaveScalarStores) {
2585 bool SeenDCacheWB =
false;
2589 if (
I->getOpcode() == AMDGPU::S_DCACHE_WB)
2590 SeenDCacheWB =
true;
2591 else if (
TII->isScalarStore(*
I))
2592 SeenDCacheWB =
false;
2595 if ((
I->getOpcode() == AMDGPU::S_ENDPGM ||
2596 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
2610 if (!ReleaseVGPRInsts.
empty() &&
2611 (MF.getFrameInfo().hasCalls() ||
2612 ST->getOccupancyWithNumVGPRs(
2613 TRI->getNumUsedPhysRegs(*
MRI, AMDGPU::VGPR_32RegClass)) <
2616 if (
ST->requiresNopBeforeDeallocVGPRs()) {
2618 TII->get(AMDGPU::S_NOP))
2622 TII->get(AMDGPU::S_SENDMSG))
2627 ReleaseVGPRInsts.clear();
2628 PreheadersToFlush.
clear();
2629 SLoadAddresses.
clear();
unsigned const MachineRegisterInfo * MRI
Provides AMDGPU specific target descriptions.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Analysis containing CSE Info
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
std::optional< std::vector< StOtherPiece > > Other
static Function * getFunction(Constant *C)
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
static bool isOptNone(const MachineFunction &MF)
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
unsigned const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
std::pair< uint64_t, uint64_t > Interval
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 bool callWaitsOnFunctionReturn(const MachineInstr &MI)
static bool isCacheInvOrWBInst(MachineInstr &Inst)
static bool callWaitsOnFunctionEntry(const MachineInstr &MI)
static bool updateOperandIfDifferent(MachineInstr &MI, uint16_t 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 bool readsVCCZ(const MachineInstr &MI)
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)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Provides some synthesis utilities to produce sequences of values.
static const uint32_t IV[8]
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
bool isEntryFunction() const
Represent the analysis usage information of a pass.
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.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
This class represents an Operation in the Expression.
static bool isCounterSet(unsigned ID)
static bool shouldExecute(unsigned CounterName)
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
bool erase(const KeyT &Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
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.
Represents a single loop in the control flow graph.
const MachineBasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Instructions::iterator instr_iterator
iterator_range< succ_iterator > successors()
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.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
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.
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.
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
bool isCall(QueryType Type=AnyInBundle) const
iterator_range< filtered_mop_iterator > all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
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.
void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
iterator_range< mop_iterator > defs()
Returns a range over all explicit operands that are register definitions.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
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.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const MachineOperand & getOperand(unsigned i) const
iterator_range< filtered_mop_iterator > all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
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 isVIMAGE(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 unsigned getNonSoftWaitcntOpcode(unsigned Opcode)
static bool isVINTERP(const MachineInstr &MI)
static bool isMIMG(const MachineInstr &MI)
static bool isFLAT(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...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
LLVM Value Representation.
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()
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ 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.
LLVM_READONLY int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
unsigned getStorecntBitMask(const IsaVersion &Version)
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)
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.
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
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...
char & SIInsertWaitcntsID
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
CodeGenOptLevel
Code generation optimization level.
FunctionPass * createSIInsertWaitcntsPass()
Instruction set architecture version.
Represents the counter values to wait for in an s_waitcnt instruction.
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
static constexpr bool is_iterable