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 WaitcntGeneratorPreGFX12() =
default;
349 WaitcntGeneratorPreGFX12(
const MachineFunction &MF)
350 : WaitcntGenerator(MF, NUM_NORMAL_INST_CNTS) {}
353 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
354 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
357 bool createNewWaitcnt(MachineBasicBlock &
Block,
359 AMDGPU::Waitcnt
Wait)
override;
361 const unsigned *getWaitEventMask()
const override {
364 static const unsigned WaitEventMaskForInstPreGFX12[NUM_INST_CNTS] = {
365 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS,
366 VMEM_BVH_READ_ACCESS}),
367 eventMask({SMEM_ACCESS, LDS_ACCESS, GDS_ACCESS, SQ_MESSAGE}),
368 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
369 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
370 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
376 return WaitEventMaskForInstPreGFX12;
379 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
382class WaitcntGeneratorGFX12Plus :
public WaitcntGenerator {
384 WaitcntGeneratorGFX12Plus() =
default;
385 WaitcntGeneratorGFX12Plus(
const MachineFunction &MF,
386 InstCounterType MaxCounter)
387 : WaitcntGenerator(MF, MaxCounter) {}
390 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
391 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
394 bool createNewWaitcnt(MachineBasicBlock &
Block,
396 AMDGPU::Waitcnt
Wait)
override;
398 const unsigned *getWaitEventMask()
const override {
401 static const unsigned WaitEventMaskForInstGFX12Plus[NUM_INST_CNTS] = {
402 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS}),
403 eventMask({LDS_ACCESS, GDS_ACCESS}),
404 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
405 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
406 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
407 eventMask({VMEM_SAMPLER_READ_ACCESS}),
408 eventMask({VMEM_BVH_READ_ACCESS}),
409 eventMask({SMEM_ACCESS, SQ_MESSAGE, SCC_WRITE}),
410 eventMask({VMEM_GROUP, SMEM_GROUP})};
412 return WaitEventMaskForInstGFX12Plus;
415 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
418class SIInsertWaitcnts {
420 const GCNSubtarget *ST;
421 const SIInstrInfo *TII =
nullptr;
422 const SIRegisterInfo *TRI =
nullptr;
423 const MachineRegisterInfo *MRI =
nullptr;
424 InstCounterType SmemAccessCounter;
425 InstCounterType MaxCounter;
426 const unsigned *WaitEventMaskForInst;
429 DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
430 DenseMap<MachineBasicBlock *, bool> PreheadersToFlush;
431 MachineLoopInfo *MLI;
432 MachinePostDominatorTree *PDT;
436 std::unique_ptr<WaitcntBrackets> Incoming;
440 MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
442 bool ForceEmitWaitcnt[NUM_INST_CNTS];
447 WaitcntGeneratorPreGFX12 WCGPreGFX12;
448 WaitcntGeneratorGFX12Plus WCGGFX12Plus;
450 WaitcntGenerator *WCG =
nullptr;
454 DenseSet<MachineInstr *> ReleaseVGPRInsts;
456 HardwareLimits Limits;
459 SIInsertWaitcnts(MachineLoopInfo *MLI, MachinePostDominatorTree *PDT,
461 : MLI(MLI), PDT(PDT), AA(AA) {
462 (void)ForceExpCounter;
463 (void)ForceLgkmCounter;
464 (void)ForceVMCounter;
467 unsigned getWaitCountMax(InstCounterType
T)
const {
470 return Limits.LoadcntMax;
472 return Limits.DscntMax;
474 return Limits.ExpcntMax;
476 return Limits.StorecntMax;
478 return Limits.SamplecntMax;
480 return Limits.BvhcntMax;
482 return Limits.KmcntMax;
484 return Limits.XcntMax;
491 bool shouldFlushVmCnt(MachineLoop *
ML,
const WaitcntBrackets &Brackets);
492 bool isPreheaderToFlush(MachineBasicBlock &
MBB,
493 const WaitcntBrackets &ScoreBrackets);
494 bool isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const;
495 bool run(MachineFunction &MF);
497 void setForceEmitWaitcnt() {
503 ForceEmitWaitcnt[
EXP_CNT] =
true;
505 ForceEmitWaitcnt[
EXP_CNT] =
false;
510 ForceEmitWaitcnt[DS_CNT] =
true;
511 ForceEmitWaitcnt[KM_CNT] =
true;
513 ForceEmitWaitcnt[DS_CNT] =
false;
514 ForceEmitWaitcnt[KM_CNT] =
false;
519 ForceEmitWaitcnt[LOAD_CNT] =
true;
520 ForceEmitWaitcnt[SAMPLE_CNT] =
true;
521 ForceEmitWaitcnt[BVH_CNT] =
true;
523 ForceEmitWaitcnt[LOAD_CNT] =
false;
524 ForceEmitWaitcnt[SAMPLE_CNT] =
false;
525 ForceEmitWaitcnt[BVH_CNT] =
false;
532 WaitEventType getVmemWaitEventType(
const MachineInstr &Inst)
const {
534 case AMDGPU::GLOBAL_INV:
535 return VMEM_READ_ACCESS;
536 case AMDGPU::GLOBAL_WB:
537 case AMDGPU::GLOBAL_WBINV:
538 return VMEM_WRITE_ACCESS;
544 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
545 VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
556 if (TII->mayAccessScratchThroughFlat(Inst))
557 return SCRATCH_WRITE_ACCESS;
558 return VMEM_WRITE_ACCESS;
561 return VMEM_READ_ACCESS;
562 return VmemReadMapping[getVmemType(Inst)];
565 bool isVmemAccess(
const MachineInstr &
MI)
const;
566 bool generateWaitcntInstBefore(MachineInstr &
MI,
567 WaitcntBrackets &ScoreBrackets,
568 MachineInstr *OldWaitcntInstr,
570 bool generateWaitcnt(AMDGPU::Waitcnt
Wait,
572 MachineBasicBlock &
Block, WaitcntBrackets &ScoreBrackets,
573 MachineInstr *OldWaitcntInstr);
574 void updateEventWaitcntAfter(MachineInstr &Inst,
575 WaitcntBrackets *ScoreBrackets);
577 MachineBasicBlock *
Block)
const;
578 bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &
Block,
579 WaitcntBrackets &ScoreBrackets);
580 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &
Block,
581 WaitcntBrackets &ScoreBrackets);
592class WaitcntBrackets {
594 WaitcntBrackets(
const SIInsertWaitcnts *Context) : Context(Context) {}
596 bool isSmemCounter(InstCounterType
T)
const {
597 return T == Context->SmemAccessCounter ||
T == X_CNT;
600 unsigned getSgprScoresIdx(InstCounterType
T)
const {
601 assert(isSmemCounter(
T) &&
"Invalid SMEM counter");
602 return T == X_CNT ? 1 : 0;
605 unsigned getScoreLB(InstCounterType
T)
const {
610 unsigned getScoreUB(InstCounterType
T)
const {
615 unsigned getScoreRange(InstCounterType
T)
const {
616 return getScoreUB(
T) - getScoreLB(
T);
619 unsigned getRegScore(
int GprNo, InstCounterType
T)
const {
620 if (GprNo < NUM_ALL_VGPRS)
621 return VgprScores[
T][GprNo];
623 if (GprNo < NUM_ALL_ALLOCATABLE)
624 return SgprScores[getSgprScoresIdx(
T)][GprNo - NUM_ALL_VGPRS];
632 RegInterval getRegInterval(
const MachineInstr *
MI,
633 const MachineOperand &
Op)
const;
635 bool counterOutOfOrder(InstCounterType
T)
const;
636 void simplifyWaitcnt(AMDGPU::Waitcnt &
Wait)
const;
637 void simplifyWaitcnt(InstCounterType
T,
unsigned &
Count)
const;
639 void determineWait(InstCounterType
T, RegInterval
Interval,
640 AMDGPU::Waitcnt &
Wait)
const;
641 void determineWait(InstCounterType
T,
int RegNo,
642 AMDGPU::Waitcnt &
Wait)
const {
643 determineWait(
T, {RegNo, RegNo + 1},
Wait);
645 void tryClearSCCWriteEvent(MachineInstr *Inst);
647 void applyWaitcnt(
const AMDGPU::Waitcnt &
Wait);
648 void applyWaitcnt(InstCounterType
T,
unsigned Count);
649 void applyXcnt(
const AMDGPU::Waitcnt &
Wait);
650 void updateByEvent(WaitEventType
E, MachineInstr &
MI);
652 unsigned hasPendingEvent()
const {
return PendingEvents; }
653 unsigned hasPendingEvent(WaitEventType
E)
const {
654 return PendingEvents & (1 <<
E);
656 unsigned hasPendingEvent(InstCounterType
T)
const {
657 unsigned HasPending = PendingEvents & Context->WaitEventMaskForInst[
T];
658 assert((HasPending != 0) == (getScoreRange(
T) != 0));
662 bool hasMixedPendingEvents(InstCounterType
T)
const {
663 unsigned Events = hasPendingEvent(
T);
665 return Events & (Events - 1);
668 bool hasPendingFlat()
const {
669 return ((LastFlat[DS_CNT] > ScoreLBs[DS_CNT] &&
670 LastFlat[DS_CNT] <= ScoreUBs[DS_CNT]) ||
671 (LastFlat[LOAD_CNT] > ScoreLBs[LOAD_CNT] &&
672 LastFlat[LOAD_CNT] <= ScoreUBs[LOAD_CNT]));
675 void setPendingFlat() {
676 LastFlat[LOAD_CNT] = ScoreUBs[LOAD_CNT];
677 LastFlat[DS_CNT] = ScoreUBs[DS_CNT];
680 bool hasPendingGDS()
const {
681 return LastGDS > ScoreLBs[DS_CNT] && LastGDS <= ScoreUBs[DS_CNT];
684 unsigned getPendingGDSWait()
const {
685 return std::min(getScoreUB(DS_CNT) - LastGDS,
686 Context->getWaitCountMax(DS_CNT) - 1);
689 void setPendingGDS() { LastGDS = ScoreUBs[DS_CNT]; }
693 bool hasOtherPendingVmemTypes(RegInterval
Interval, VmemType V)
const {
695 assert(RegNo < NUM_ALL_VGPRS);
696 if (VgprVmemTypes[RegNo] & ~(1 << V))
702 void clearVgprVmemTypes(RegInterval
Interval) {
704 assert(RegNo < NUM_ALL_VGPRS);
705 VgprVmemTypes[RegNo] = 0;
709 void setStateOnFunctionEntryOrReturn() {
710 setScoreUB(STORE_CNT,
711 getScoreUB(STORE_CNT) + Context->getWaitCountMax(STORE_CNT));
712 PendingEvents |= Context->WaitEventMaskForInst[STORE_CNT];
715 ArrayRef<const MachineInstr *> getLDSDMAStores()
const {
719 bool hasPointSampleAccel(
const MachineInstr &
MI)
const;
720 bool hasPointSamplePendingVmemTypes(
const MachineInstr &
MI,
723 void print(raw_ostream &)
const;
733 static bool mergeScore(
const MergeInfo &M,
unsigned &Score,
734 unsigned OtherScore);
736 void setScoreLB(InstCounterType
T,
unsigned Val) {
741 void setScoreUB(InstCounterType
T,
unsigned Val) {
748 if (getScoreRange(EXP_CNT) > Context->getWaitCountMax(EXP_CNT))
749 ScoreLBs[
EXP_CNT] = ScoreUBs[
EXP_CNT] - Context->getWaitCountMax(EXP_CNT);
752 void setRegScore(
int GprNo, InstCounterType
T,
unsigned Val) {
753 setScoreByInterval({GprNo, GprNo + 1},
T, Val);
756 void setScoreByInterval(RegInterval
Interval, InstCounterType CntTy,
759 void setScoreByOperand(
const MachineInstr *
MI,
const MachineOperand &
Op,
760 InstCounterType CntTy,
unsigned Val);
762 const SIInsertWaitcnts *Context;
764 unsigned ScoreLBs[NUM_INST_CNTS] = {0};
765 unsigned ScoreUBs[NUM_INST_CNTS] = {0};
766 unsigned PendingEvents = 0;
768 unsigned LastFlat[NUM_INST_CNTS] = {0};
770 unsigned LastGDS = 0;
775 unsigned VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS] = {{0}};
780 unsigned SgprScores[2][SQ_MAX_PGM_SGPRS] = {{0}};
782 unsigned SCCScore = 0;
784 const MachineInstr *PendingSCCWrite =
nullptr;
787 unsigned char VgprVmemTypes[NUM_ALL_VGPRS] = {0};
790 SmallVector<
const MachineInstr *, NUM_LDS_VGPRS - 1> LDSDMAStores;
796 SIInsertWaitcntsLegacy() : MachineFunctionPass(ID) {}
798 bool runOnMachineFunction(MachineFunction &MF)
override;
800 StringRef getPassName()
const override {
801 return "SI insert wait instructions";
804 void getAnalysisUsage(AnalysisUsage &AU)
const override {
807 AU.
addRequired<MachinePostDominatorTreeWrapperPass>();
816RegInterval WaitcntBrackets::getRegInterval(
const MachineInstr *
MI,
818 if (
Op.getReg() == AMDGPU::SCC)
822 const MachineRegisterInfo *
MRI =
Context->MRI;
824 if (!
TRI->isInAllocatableClass(
Op.getReg()))
834 unsigned RegIdx =
TRI->getHWRegIndex(MCReg);
836 const TargetRegisterClass *RC =
TRI->getPhysRegBaseClass(
Op.getReg());
837 unsigned Size =
TRI->getRegSizeInBits(*RC);
840 if (
TRI->isVectorRegister(*
MRI,
Op.getReg())) {
845 Result.first += AGPR_OFFSET;
850 if (
Size == 16 &&
Context->ST->hasD16Writes32BitVgpr()) {
858 }
else if (
TRI->isSGPRReg(*
MRI,
Op.getReg()) && RegIdx < SQ_MAX_PGM_SGPRS) {
861 Result.first = RegIdx + NUM_ALL_VGPRS;
870void WaitcntBrackets::setScoreByInterval(RegInterval
Interval,
871 InstCounterType CntTy,
874 if (RegNo < NUM_ALL_VGPRS) {
875 VgprUB = std::max(VgprUB, RegNo);
876 VgprScores[CntTy][RegNo] = Score;
877 }
else if (RegNo < NUM_ALL_ALLOCATABLE) {
878 SgprUB = std::max(SgprUB, RegNo - NUM_ALL_VGPRS);
879 SgprScores[getSgprScoresIdx(CntTy)][RegNo - NUM_ALL_VGPRS] = Score;
887void WaitcntBrackets::setScoreByOperand(
const MachineInstr *
MI,
888 const MachineOperand &
Op,
889 InstCounterType CntTy,
unsigned Score) {
891 setScoreByInterval(
Interval, CntTy, Score);
899bool WaitcntBrackets::hasPointSampleAccel(
const MachineInstr &
MI)
const {
904 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
914bool WaitcntBrackets::hasPointSamplePendingVmemTypes(
915 const MachineInstr &
MI, RegInterval
Interval)
const {
916 if (!hasPointSampleAccel(
MI))
919 return hasOtherPendingVmemTypes(
Interval, VMEM_NOSAMPLER);
922void WaitcntBrackets::updateByEvent(WaitEventType
E, MachineInstr &Inst) {
923 InstCounterType
T = eventCounter(
Context->WaitEventMaskForInst,
E);
925 unsigned UB = getScoreUB(
T);
926 unsigned CurrScore = UB + 1;
932 PendingEvents |= 1 <<
E;
933 setScoreUB(
T, CurrScore);
936 const MachineRegisterInfo *
MRI =
Context->MRI;
945 if (
const auto *AddrOp =
TII->getNamedOperand(Inst, AMDGPU::OpName::addr))
946 setScoreByOperand(&Inst, *AddrOp, EXP_CNT, CurrScore);
949 if (
const auto *Data0 =
950 TII->getNamedOperand(Inst, AMDGPU::OpName::data0))
951 setScoreByOperand(&Inst, *Data0, EXP_CNT, CurrScore);
952 if (
const auto *Data1 =
953 TII->getNamedOperand(Inst, AMDGPU::OpName::data1))
954 setScoreByOperand(&Inst, *Data1, EXP_CNT, CurrScore);
957 Inst.
getOpcode() != AMDGPU::DS_CONSUME &&
958 Inst.
getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
959 for (
const MachineOperand &
Op : Inst.
all_uses()) {
960 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
961 setScoreByOperand(&Inst,
Op, EXP_CNT, CurrScore);
964 }
else if (
TII->isFLAT(Inst)) {
966 setScoreByOperand(&Inst,
967 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
970 setScoreByOperand(&Inst,
971 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
974 }
else if (
TII->isMIMG(Inst)) {
976 setScoreByOperand(&Inst, Inst.
getOperand(0), EXP_CNT, CurrScore);
978 setScoreByOperand(&Inst,
979 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
982 }
else if (
TII->isMTBUF(Inst)) {
984 setScoreByOperand(&Inst, Inst.
getOperand(0), EXP_CNT, CurrScore);
985 }
else if (
TII->isMUBUF(Inst)) {
987 setScoreByOperand(&Inst, Inst.
getOperand(0), EXP_CNT, CurrScore);
989 setScoreByOperand(&Inst,
990 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
993 }
else if (
TII->isLDSDIR(Inst)) {
995 setScoreByOperand(&Inst,
996 *
TII->getNamedOperand(Inst, AMDGPU::OpName::vdst),
999 if (
TII->isEXP(Inst)) {
1004 for (MachineOperand &DefMO : Inst.
all_defs()) {
1005 if (
TRI->isVGPR(*
MRI, DefMO.getReg())) {
1006 setScoreByOperand(&Inst, DefMO, EXP_CNT, CurrScore);
1010 for (
const MachineOperand &
Op : Inst.
all_uses()) {
1011 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
1012 setScoreByOperand(&Inst,
Op, EXP_CNT, CurrScore);
1015 }
else if (
T == X_CNT) {
1016 for (
const MachineOperand &
Op : Inst.
all_uses())
1017 setScoreByOperand(&Inst,
Op,
T, CurrScore);
1028 for (
const MachineOperand &
Op : Inst.
defs()) {
1029 RegInterval
Interval = getRegInterval(&Inst,
Op);
1030 if (
T == LOAD_CNT ||
T == SAMPLE_CNT ||
T == BVH_CNT) {
1031 if (
Interval.first >= NUM_ALL_VGPRS)
1033 if (updateVMCntOnly(Inst)) {
1038 VmemType
V = getVmemType(Inst);
1039 unsigned char TypesMask = 1 <<
V;
1042 if (hasPointSampleAccel(Inst))
1043 TypesMask |= 1 << VMEM_NOSAMPLER;
1045 VgprVmemTypes[RegNo] |= TypesMask;
1048 setScoreByInterval(
Interval,
T, CurrScore);
1051 (
TII->isDS(Inst) ||
TII->mayWriteLDSThroughDMA(Inst))) {
1056 if (!MemOp->isStore() ||
1061 auto AAI = MemOp->getAAInfo();
1069 if (!AAI || !AAI.Scope)
1071 for (
unsigned I = 0,
E = LDSDMAStores.size();
I !=
E && !Slot; ++
I) {
1072 for (
const auto *MemOp : LDSDMAStores[
I]->memoperands()) {
1073 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1079 if (Slot || LDSDMAStores.size() == NUM_LDS_VGPRS - 1)
1081 LDSDMAStores.push_back(&Inst);
1082 Slot = LDSDMAStores.size();
1085 setRegScore(FIRST_LDS_VGPR + Slot,
T, CurrScore);
1087 setRegScore(FIRST_LDS_VGPR,
T, CurrScore);
1091 setRegScore(SCC,
T, CurrScore);
1092 PendingSCCWrite = &Inst;
1097void WaitcntBrackets::print(raw_ostream &OS)
const {
1101 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
1102 unsigned SR = getScoreRange(
T);
1106 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"LOAD" :
"VM") <<
"_CNT("
1110 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"DS" :
"LGKM") <<
"_CNT("
1114 OS <<
" EXP_CNT(" << SR <<
"): ";
1117 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"STORE" :
"VS") <<
"_CNT("
1121 OS <<
" SAMPLE_CNT(" << SR <<
"): ";
1124 OS <<
" BVH_CNT(" << SR <<
"): ";
1127 OS <<
" KM_CNT(" << SR <<
"): ";
1130 OS <<
" X_CNT(" << SR <<
"): ";
1133 OS <<
" UNKNOWN(" << SR <<
"): ";
1139 unsigned LB = getScoreLB(
T);
1141 for (
int J = 0; J <= VgprUB; J++) {
1142 unsigned RegScore = getRegScore(J,
T);
1145 unsigned RelScore = RegScore - LB - 1;
1146 if (J < FIRST_LDS_VGPR) {
1147 OS << RelScore <<
":v" << J <<
" ";
1149 OS << RelScore <<
":ds ";
1153 if (isSmemCounter(
T)) {
1154 for (
int J = 0; J <= SgprUB; J++) {
1155 unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS,
T);
1158 unsigned RelScore = RegScore - LB - 1;
1159 OS << RelScore <<
":s" << J <<
" ";
1162 if (
T == KM_CNT && SCCScore > 0)
1163 OS << SCCScore <<
":scc ";
1168 OS <<
"Pending Events: ";
1169 if (hasPendingEvent()) {
1171 for (
unsigned I = 0;
I != NUM_WAIT_EVENTS; ++
I) {
1172 if (hasPendingEvent((WaitEventType)
I)) {
1173 OS <<
LS << WaitEventTypeName[
I];
1186void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &
Wait)
const {
1187 simplifyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1188 simplifyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1189 simplifyWaitcnt(DS_CNT,
Wait.DsCnt);
1190 simplifyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1191 simplifyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1192 simplifyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1193 simplifyWaitcnt(KM_CNT,
Wait.KmCnt);
1194 simplifyWaitcnt(X_CNT,
Wait.XCnt);
1197void WaitcntBrackets::simplifyWaitcnt(InstCounterType
T,
1198 unsigned &
Count)
const {
1202 if (
Count >= getScoreRange(
T))
1206void WaitcntBrackets::determineWait(InstCounterType
T, RegInterval
Interval,
1207 AMDGPU::Waitcnt &
Wait)
const {
1208 const unsigned LB = getScoreLB(
T);
1209 const unsigned UB = getScoreUB(
T);
1211 unsigned ScoreToWait = getRegScore(RegNo,
T);
1215 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1216 if ((
T == LOAD_CNT ||
T == DS_CNT) && hasPendingFlat() &&
1217 !
Context->ST->hasFlatLgkmVMemCountInOrder()) {
1221 addWait(
Wait,
T, 0);
1222 }
else if (counterOutOfOrder(
T)) {
1226 addWait(
Wait,
T, 0);
1230 unsigned NeededWait =
1231 std::min(UB - ScoreToWait,
Context->getWaitCountMax(
T) - 1);
1232 addWait(
Wait,
T, NeededWait);
1238void WaitcntBrackets::tryClearSCCWriteEvent(MachineInstr *Inst) {
1241 if (PendingSCCWrite &&
1242 PendingSCCWrite->
getOpcode() == AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM &&
1244 unsigned SCC_WRITE_PendingEvent = 1 << SCC_WRITE;
1246 if ((PendingEvents &
Context->WaitEventMaskForInst[KM_CNT]) ==
1247 SCC_WRITE_PendingEvent) {
1248 setScoreLB(KM_CNT, getScoreUB(KM_CNT));
1251 PendingEvents &= ~SCC_WRITE_PendingEvent;
1252 PendingSCCWrite =
nullptr;
1256void WaitcntBrackets::applyWaitcnt(
const AMDGPU::Waitcnt &
Wait) {
1257 applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1258 applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1259 applyWaitcnt(DS_CNT,
Wait.DsCnt);
1260 applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1261 applyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1262 applyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1263 applyWaitcnt(KM_CNT,
Wait.KmCnt);
1267void WaitcntBrackets::applyWaitcnt(InstCounterType
T,
unsigned Count) {
1268 const unsigned UB = getScoreUB(
T);
1272 if (counterOutOfOrder(
T))
1274 setScoreLB(
T, std::max(getScoreLB(
T), UB -
Count));
1277 PendingEvents &= ~Context->WaitEventMaskForInst[
T];
1281void WaitcntBrackets::applyXcnt(
const AMDGPU::Waitcnt &
Wait) {
1285 if (
Wait.KmCnt == 0 && hasPendingEvent(SMEM_GROUP))
1286 return applyWaitcnt(X_CNT, 0);
1291 if (
Wait.LoadCnt != ~0u && hasPendingEvent(VMEM_GROUP) &&
1292 !hasPendingEvent(STORE_CNT))
1293 return applyWaitcnt(X_CNT, std::min(
Wait.XCnt,
Wait.LoadCnt));
1295 applyWaitcnt(X_CNT,
Wait.XCnt);
1300bool WaitcntBrackets::counterOutOfOrder(InstCounterType
T)
const {
1302 if ((
T ==
Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1303 (
T == X_CNT && hasPendingEvent(SMEM_GROUP)))
1305 return hasMixedPendingEvents(
T);
1315char SIInsertWaitcntsLegacy::
ID = 0;
1320 return new SIInsertWaitcntsLegacy();
1325 int OpIdx = AMDGPU::getNamedOperandIdx(
MI.getOpcode(),
OpName);
1330 if (NewEnc == MO.
getImm())
1341 case AMDGPU::S_WAIT_LOADCNT:
1343 case AMDGPU::S_WAIT_EXPCNT:
1345 case AMDGPU::S_WAIT_STORECNT:
1347 case AMDGPU::S_WAIT_SAMPLECNT:
1349 case AMDGPU::S_WAIT_BVHCNT:
1351 case AMDGPU::S_WAIT_DSCNT:
1353 case AMDGPU::S_WAIT_KMCNT:
1355 case AMDGPU::S_WAIT_XCNT:
1362bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt)
const {
1376bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1377 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1380 assert(isNormalMode(MaxCounter));
1383 MachineInstr *WaitcntInstr =
nullptr;
1384 MachineInstr *WaitcntVsCntInstr =
nullptr;
1387 dbgs() <<
"PreGFX12::applyPreexistingWaitcnt at: ";
1389 dbgs() <<
"end of block\n";
1397 if (
II.isMetaInstruction()) {
1403 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1407 if (Opcode == AMDGPU::S_WAITCNT) {
1408 unsigned IEnc =
II.getOperand(0).getImm();
1411 ScoreBrackets.simplifyWaitcnt(OldWait);
1415 if (WaitcntInstr || (!
Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1416 II.eraseFromParent();
1420 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1423 <<
"Before: " <<
Wait.LoadCnt <<
'\n';);
1424 ScoreBrackets.determineWait(LOAD_CNT, FIRST_LDS_VGPR,
Wait);
1433 II.eraseFromParent();
1435 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1436 assert(
II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1439 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1441 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1442 Wait.StoreCnt = std::min(
Wait.StoreCnt, OldVSCnt);
1444 if (WaitcntVsCntInstr || (!
Wait.hasWaitStoreCnt() && TrySimplify)) {
1445 II.eraseFromParent();
1448 WaitcntVsCntInstr = &
II;
1455 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1457 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1458 ScoreBrackets.applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1459 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1466 <<
"applied pre-existing waitcnt\n"
1467 <<
"New Instr at block end: " << *WaitcntInstr <<
'\n'
1468 :
dbgs() <<
"applied pre-existing waitcnt\n"
1469 <<
"Old Instr: " << *It
1470 <<
"New Instr: " << *WaitcntInstr <<
'\n');
1473 if (WaitcntVsCntInstr) {
1475 AMDGPU::OpName::simm16,
Wait.StoreCnt);
1476 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1478 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1479 Wait.StoreCnt = ~0
u;
1482 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1483 <<
"New Instr at block end: " << *WaitcntVsCntInstr
1485 :
dbgs() <<
"applied pre-existing waitcnt\n"
1486 <<
"Old Instr: " << *It
1487 <<
"New Instr: " << *WaitcntVsCntInstr <<
'\n');
1495bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1497 AMDGPU::Waitcnt
Wait) {
1499 assert(isNormalMode(MaxCounter));
1506 if (
Wait.hasWaitExceptStoreCnt()) {
1508 [[maybe_unused]]
auto SWaitInst =
1513 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1514 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1517 if (
Wait.hasWaitStoreCnt()) {
1520 [[maybe_unused]]
auto SWaitInst =
1527 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1528 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1535WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1536 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt &&
ST->hasVscnt() ? 0 : ~0u);
1540WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1541 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
1549bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
1550 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1553 assert(!isNormalMode(MaxCounter));
1556 MachineInstr *CombinedLoadDsCntInstr =
nullptr;
1557 MachineInstr *CombinedStoreDsCntInstr =
nullptr;
1558 MachineInstr *WaitInstrs[NUM_EXTENDED_INST_CNTS] = {};
1561 dbgs() <<
"GFX12Plus::applyPreexistingWaitcnt at: ";
1563 dbgs() <<
"end of block\n";
1571 if (
II.isMetaInstruction()) {
1576 MachineInstr **UpdatableInstr;
1582 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1586 if (Opcode == AMDGPU::S_WAITCNT)
1589 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
1591 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1594 ScoreBrackets.simplifyWaitcnt(OldWait);
1596 UpdatableInstr = &CombinedLoadDsCntInstr;
1597 }
else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
1599 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1602 ScoreBrackets.simplifyWaitcnt(OldWait);
1604 UpdatableInstr = &CombinedStoreDsCntInstr;
1605 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1608 II.eraseFromParent();
1614 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1616 ScoreBrackets.simplifyWaitcnt(CT.value(), OldCnt);
1617 addWait(
Wait, CT.value(), OldCnt);
1618 UpdatableInstr = &WaitInstrs[CT.value()];
1622 if (!*UpdatableInstr) {
1623 *UpdatableInstr = &
II;
1625 II.eraseFromParent();
1630 if (CombinedLoadDsCntInstr) {
1638 if (
Wait.LoadCnt != ~0u &&
Wait.DsCnt != ~0u) {
1641 AMDGPU::OpName::simm16, NewEnc);
1642 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
1643 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1644 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1649 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1650 <<
"New Instr at block end: "
1651 << *CombinedLoadDsCntInstr <<
'\n'
1652 :
dbgs() <<
"applied pre-existing waitcnt\n"
1653 <<
"Old Instr: " << *It <<
"New Instr: "
1654 << *CombinedLoadDsCntInstr <<
'\n');
1661 if (CombinedStoreDsCntInstr) {
1663 if (
Wait.StoreCnt != ~0u &&
Wait.DsCnt != ~0u) {
1666 AMDGPU::OpName::simm16, NewEnc);
1667 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
1668 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1669 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1670 Wait.StoreCnt = ~0
u;
1674 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1675 <<
"New Instr at block end: "
1676 << *CombinedStoreDsCntInstr <<
'\n'
1677 :
dbgs() <<
"applied pre-existing waitcnt\n"
1678 <<
"Old Instr: " << *It <<
"New Instr: "
1679 << *CombinedStoreDsCntInstr <<
'\n');
1692 if (
Wait.DsCnt != ~0u) {
1701 if (
Wait.LoadCnt != ~0u) {
1702 WaitsToErase.
push_back(&WaitInstrs[LOAD_CNT]);
1703 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1704 }
else if (
Wait.StoreCnt != ~0u) {
1705 WaitsToErase.
push_back(&WaitInstrs[STORE_CNT]);
1706 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1709 for (MachineInstr **WI : WaitsToErase) {
1713 (*WI)->eraseFromParent();
1719 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1720 if (!WaitInstrs[CT])
1723 unsigned NewCnt = getWait(
Wait, CT);
1724 if (NewCnt != ~0u) {
1726 AMDGPU::OpName::simm16, NewCnt);
1727 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
1729 ScoreBrackets.applyWaitcnt(CT, NewCnt);
1730 setNoWait(
Wait, CT);
1733 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1734 <<
"New Instr at block end: " << *WaitInstrs[CT]
1736 :
dbgs() <<
"applied pre-existing waitcnt\n"
1737 <<
"Old Instr: " << *It
1738 <<
"New Instr: " << *WaitInstrs[CT] <<
'\n');
1749bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
1751 AMDGPU::Waitcnt
Wait) {
1753 assert(!isNormalMode(MaxCounter));
1759 if (
Wait.DsCnt != ~0u) {
1760 MachineInstr *SWaitInst =
nullptr;
1762 if (
Wait.LoadCnt != ~0u) {
1770 }
else if (
Wait.StoreCnt != ~0u) {
1777 Wait.StoreCnt = ~0
u;
1785 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1786 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1793 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1798 [[maybe_unused]]
auto SWaitInst =
1805 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1806 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1837bool SIInsertWaitcnts::generateWaitcntInstBefore(MachineInstr &
MI,
1838 WaitcntBrackets &ScoreBrackets,
1839 MachineInstr *OldWaitcntInstr,
1841 setForceEmitWaitcnt();
1845 AMDGPU::Waitcnt
Wait;
1846 const unsigned Opc =
MI.getOpcode();
1852 if (
Opc == AMDGPU::BUFFER_WBINVL1 ||
Opc == AMDGPU::BUFFER_WBINVL1_SC ||
1853 Opc == AMDGPU::BUFFER_WBINVL1_VOL ||
Opc == AMDGPU::BUFFER_GL0_INV ||
1854 Opc == AMDGPU::BUFFER_GL1_INV) {
1861 if (
Opc == AMDGPU::SI_RETURN_TO_EPILOG ||
Opc == AMDGPU::SI_RETURN ||
1862 Opc == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1863 Opc == AMDGPU::S_SETPC_B64_return ||
1865 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
false));
1875 else if (
Opc == AMDGPU::S_ENDPGM ||
Opc == AMDGPU::S_ENDPGM_SAVED) {
1876 if (!WCG->isOptNone() &&
1877 (
MI.getMF()->getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() ||
1878 (
ST->getGeneration() >= AMDGPUSubtarget::GFX11 &&
1879 ScoreBrackets.getScoreRange(STORE_CNT) != 0 &&
1880 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS))))
1884 else if ((
Opc == AMDGPU::S_SENDMSG ||
Opc == AMDGPU::S_SENDMSGHALT) &&
1885 ST->hasLegacyGeometry() &&
1896 if (
MI.modifiesRegister(AMDGPU::EXEC,
TRI)) {
1899 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1900 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1901 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1902 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1909 if (
TII->isAlwaysGDS(
Opc) && ScoreBrackets.hasPendingGDS())
1910 addWait(
Wait, DS_CNT, ScoreBrackets.getPendingGDSWait());
1916 Wait = AMDGPU::Waitcnt();
1918 const auto &CallAddrOp = *
TII->getNamedOperand(
MI, AMDGPU::OpName::src0);
1919 if (CallAddrOp.isReg()) {
1920 RegInterval CallAddrOpInterval =
1921 ScoreBrackets.getRegInterval(&
MI, CallAddrOp);
1923 ScoreBrackets.determineWait(SmemAccessCounter, CallAddrOpInterval,
1926 if (
const auto *RtnAddrOp =
1927 TII->getNamedOperand(
MI, AMDGPU::OpName::dst)) {
1928 RegInterval RtnAddrOpInterval =
1929 ScoreBrackets.getRegInterval(&
MI, *RtnAddrOp);
1931 ScoreBrackets.determineWait(SmemAccessCounter, RtnAddrOpInterval,
1935 }
else if (
Opc == AMDGPU::S_BARRIER_WAIT) {
1936 ScoreBrackets.tryClearSCCWriteEvent(&
MI);
1952 for (
const MachineMemOperand *Memop :
MI.memoperands()) {
1953 const Value *
Ptr = Memop->getValue();
1954 if (Memop->isStore()) {
1955 if (
auto It = SLoadAddresses.
find(
Ptr); It != SLoadAddresses.
end()) {
1956 addWait(
Wait, SmemAccessCounter, 0);
1958 SLoadAddresses.
erase(It);
1961 unsigned AS = Memop->getAddrSpace();
1965 if (
TII->mayWriteLDSThroughDMA(
MI))
1969 unsigned RegNo = FIRST_LDS_VGPR;
1970 if (
Ptr && Memop->getAAInfo()) {
1971 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
1972 for (
unsigned I = 0,
E = LDSDMAStores.size();
I !=
E; ++
I) {
1973 if (
MI.mayAlias(AA, *LDSDMAStores[
I],
true))
1974 ScoreBrackets.determineWait(LOAD_CNT, RegNo +
I + 1,
Wait);
1977 ScoreBrackets.determineWait(LOAD_CNT, RegNo,
Wait);
1979 if (Memop->isStore()) {
1980 ScoreBrackets.determineWait(EXP_CNT, RegNo,
Wait);
1985 for (
const MachineOperand &
Op :
MI.operands()) {
1990 if (
Op.isTied() &&
Op.isUse() &&
TII->doesNotReadTiedSource(
MI))
1993 RegInterval
Interval = ScoreBrackets.getRegInterval(&
MI,
Op);
1995 const bool IsVGPR =
TRI->isVectorRegister(*
MRI,
Op.getReg());
2002 if (
Op.isImplicit() &&
MI.mayLoadOrStore())
2011 if (
Op.isUse() || !updateVMCntOnly(
MI) ||
2012 ScoreBrackets.hasOtherPendingVmemTypes(
Interval,
2014 ScoreBrackets.hasPointSamplePendingVmemTypes(
MI,
Interval) ||
2015 !
ST->hasVmemWriteVgprInOrder()) {
2017 ScoreBrackets.determineWait(SAMPLE_CNT,
Interval,
Wait);
2019 ScoreBrackets.clearVgprVmemTypes(
Interval);
2022 if (
Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2026 }
else if (
Op.getReg() == AMDGPU::SCC) {
2029 ScoreBrackets.determineWait(SmemAccessCounter,
Interval,
Wait);
2032 if (
ST->hasWaitXCnt() &&
Op.isDef())
2050 if (
Opc == AMDGPU::S_BARRIER && !
ST->hasAutoWaitcntBeforeBarrier() &&
2051 !
ST->supportsBackOffBarrier()) {
2052 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
true));
2059 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2064 ScoreBrackets.simplifyWaitcnt(
Wait);
2069 Wait = WCG->getAllZeroWaitcnt(
false);
2071 if (ForceEmitWaitcnt[LOAD_CNT])
2073 if (ForceEmitWaitcnt[EXP_CNT])
2075 if (ForceEmitWaitcnt[DS_CNT])
2077 if (ForceEmitWaitcnt[SAMPLE_CNT])
2079 if (ForceEmitWaitcnt[BVH_CNT])
2081 if (ForceEmitWaitcnt[KM_CNT])
2083 if (ForceEmitWaitcnt[X_CNT])
2087 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2089 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2091 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2098 return generateWaitcnt(
Wait,
MI.getIterator(), *
MI.getParent(), ScoreBrackets,
2102bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt
Wait,
2104 MachineBasicBlock &
Block,
2105 WaitcntBrackets &ScoreBrackets,
2106 MachineInstr *OldWaitcntInstr) {
2109 if (OldWaitcntInstr)
2113 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr,
Wait, It);
2117 ScoreBrackets.applyWaitcnt(
Wait);
2120 if (
Wait.ExpCnt != ~0u && It !=
Block.instr_end() &&
2122 MachineOperand *WaitExp =
2123 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
2131 <<
"Update Instr: " << *It);
2135 if (
Wait.XCnt != ~0u) {
2136 if (
Wait.KmCnt == 0 && !ScoreBrackets.hasPendingEvent(SMEM_GROUP))
2139 if (
Wait.LoadCnt == 0 && !ScoreBrackets.hasPendingEvent(VMEM_GROUP))
2145 if (isVmemAccess(*It))
2149 if (WCG->createNewWaitcnt(
Block, It,
Wait))
2155bool SIInsertWaitcnts::isVmemAccess(
const MachineInstr &
MI)
const {
2156 return (
TII->isFLAT(
MI) &&
TII->mayAccessVMEMThroughFlat(
MI)) ||
2163 MachineBasicBlock *
Block)
const {
2164 auto BlockEnd =
Block->getParent()->end();
2165 auto BlockIter =
Block->getIterator();
2169 if (++BlockIter != BlockEnd) {
2170 It = BlockIter->instr_begin();
2177 if (!It->isMetaInstruction())
2185 return It->getOpcode() == AMDGPU::S_ENDPGM;
2189bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2190 MachineBasicBlock &
Block,
2191 WaitcntBrackets &ScoreBrackets) {
2192 AMDGPU::Waitcnt
Wait;
2193 bool NeedsEndPGMCheck =
false;
2201 NeedsEndPGMCheck =
true;
2204 ScoreBrackets.simplifyWaitcnt(
Wait);
2207 bool Result = generateWaitcnt(
Wait, SuccessorIt,
Block, ScoreBrackets,
2210 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &
Block)) {
2218void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2219 WaitcntBrackets *ScoreBrackets) {
2225 bool IsVMEMAccess =
false;
2226 bool IsSMEMAccess =
false;
2227 if (
TII->isDS(Inst) &&
TII->usesLGKM_CNT(Inst)) {
2229 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2230 ScoreBrackets->updateByEvent(GDS_ACCESS, Inst);
2231 ScoreBrackets->updateByEvent(GDS_GPR_LOCK, Inst);
2232 ScoreBrackets->setPendingGDS();
2234 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2236 }
else if (
TII->isFLAT(Inst)) {
2238 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2244 int FlatASCount = 0;
2246 if (
TII->mayAccessVMEMThroughFlat(Inst)) {
2248 IsVMEMAccess =
true;
2249 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2252 if (
TII->mayAccessLDSThroughFlat(Inst)) {
2254 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2260 if (FlatASCount > 1)
2261 ScoreBrackets->setPendingFlat();
2264 IsVMEMAccess =
true;
2265 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2267 if (
ST->vmemWriteNeedsExpWaitcnt() &&
2269 ScoreBrackets->updateByEvent(VMW_GPR_LOCK, Inst);
2271 }
else if (
TII->isSMRD(Inst)) {
2272 IsSMEMAccess =
true;
2273 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2274 }
else if (Inst.
isCall()) {
2277 ScoreBrackets->applyWaitcnt(
2278 WCG->getAllZeroWaitcnt(
false));
2279 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2282 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
2285 ScoreBrackets->updateByEvent(EXP_LDS_ACCESS, Inst);
2286 }
else if (
TII->isVINTERP(Inst)) {
2287 int64_t
Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2288 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2290 unsigned Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2292 ScoreBrackets->updateByEvent(EXP_PARAM_ACCESS, Inst);
2294 ScoreBrackets->updateByEvent(EXP_POS_ACCESS, Inst);
2296 ScoreBrackets->updateByEvent(EXP_GPR_LOCK, Inst);
2298 ScoreBrackets->updateByEvent(SCC_WRITE, Inst);
2301 case AMDGPU::S_SENDMSG:
2302 case AMDGPU::S_SENDMSG_RTN_B32:
2303 case AMDGPU::S_SENDMSG_RTN_B64:
2304 case AMDGPU::S_SENDMSGHALT:
2305 ScoreBrackets->updateByEvent(SQ_MESSAGE, Inst);
2307 case AMDGPU::S_MEMTIME:
2308 case AMDGPU::S_MEMREALTIME:
2309 case AMDGPU::S_GET_BARRIER_STATE_M0:
2310 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2311 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2316 if (!
ST->hasWaitXCnt())
2320 ScoreBrackets->updateByEvent(VMEM_GROUP, Inst);
2323 ScoreBrackets->updateByEvent(SMEM_GROUP, Inst);
2326bool WaitcntBrackets::mergeScore(
const MergeInfo &M,
unsigned &Score,
2327 unsigned OtherScore) {
2328 unsigned MyShifted = Score <=
M.OldLB ? 0 : Score +
M.MyShift;
2329 unsigned OtherShifted =
2330 OtherScore <=
M.OtherLB ? 0 : OtherScore +
M.OtherShift;
2331 Score = std::max(MyShifted, OtherShifted);
2332 return OtherShifted > MyShifted;
2340bool WaitcntBrackets::merge(
const WaitcntBrackets &
Other) {
2341 bool StrictDom =
false;
2343 VgprUB = std::max(VgprUB,
Other.VgprUB);
2344 SgprUB = std::max(SgprUB,
Other.SgprUB);
2346 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
2348 const unsigned *WaitEventMaskForInst =
Context->WaitEventMaskForInst;
2349 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[
T];
2350 const unsigned OtherEvents =
Other.PendingEvents & WaitEventMaskForInst[
T];
2351 if (OtherEvents & ~OldEvents)
2353 PendingEvents |= OtherEvents;
2356 const unsigned MyPending = ScoreUBs[
T] - ScoreLBs[
T];
2357 const unsigned OtherPending =
Other.ScoreUBs[
T] -
Other.ScoreLBs[
T];
2358 const unsigned NewUB = ScoreLBs[
T] + std::max(MyPending, OtherPending);
2359 if (NewUB < ScoreLBs[
T])
2363 M.OldLB = ScoreLBs[
T];
2364 M.OtherLB =
Other.ScoreLBs[
T];
2365 M.MyShift = NewUB - ScoreUBs[
T];
2366 M.OtherShift = NewUB -
Other.ScoreUBs[
T];
2368 ScoreUBs[
T] = NewUB;
2370 StrictDom |= mergeScore(M, LastFlat[
T],
Other.LastFlat[
T]);
2373 StrictDom |= mergeScore(M, LastGDS,
Other.LastGDS);
2376 StrictDom |= mergeScore(M, SCCScore,
Other.SCCScore);
2377 if (
Other.hasPendingEvent(SCC_WRITE)) {
2378 unsigned OldEventsHasSCCWrite = OldEvents & (1 << SCC_WRITE);
2379 if (!OldEventsHasSCCWrite) {
2380 PendingSCCWrite =
Other.PendingSCCWrite;
2381 }
else if (PendingSCCWrite !=
Other.PendingSCCWrite) {
2382 PendingSCCWrite =
nullptr;
2387 for (
int J = 0; J <= VgprUB; J++)
2388 StrictDom |= mergeScore(M, VgprScores[
T][J],
Other.VgprScores[
T][J]);
2390 if (isSmemCounter(
T)) {
2391 unsigned Idx = getSgprScoresIdx(
T);
2392 for (
int J = 0; J <= SgprUB; J++)
2394 mergeScore(M, SgprScores[Idx][J],
Other.SgprScores[Idx][J]);
2398 for (
int J = 0; J <= VgprUB; J++) {
2399 unsigned char NewVmemTypes = VgprVmemTypes[J] |
Other.VgprVmemTypes[J];
2400 StrictDom |= NewVmemTypes != VgprVmemTypes[J];
2401 VgprVmemTypes[J] = NewVmemTypes;
2409 return Opcode == AMDGPU::S_WAITCNT ||
2412 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2413 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2414 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
2419bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
2420 MachineBasicBlock &
Block,
2421 WaitcntBrackets &ScoreBrackets) {
2425 dbgs() <<
"*** Begin Block: ";
2427 ScoreBrackets.dump();
2433 bool VCCZCorrect =
true;
2434 if (
ST->hasReadVCCZBug()) {
2437 VCCZCorrect =
false;
2438 }
else if (!
ST->partialVCCWritesUpdateVCCZ()) {
2441 VCCZCorrect =
false;
2445 MachineInstr *OldWaitcntInstr =
nullptr;
2450 MachineInstr &Inst = *Iter;
2459 if (!OldWaitcntInstr)
2460 OldWaitcntInstr = &Inst;
2465 bool FlushVmCnt =
Block.getFirstTerminator() == Inst &&
2466 isPreheaderToFlush(
Block, ScoreBrackets);
2469 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2471 OldWaitcntInstr =
nullptr;
2477 if (
ST->hasReadVCCZBug() || !
ST->partialVCCWritesUpdateVCCZ()) {
2481 if (!
ST->partialVCCWritesUpdateVCCZ())
2482 VCCZCorrect =
false;
2491 if (
ST->hasReadVCCZBug() &&
2492 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2495 VCCZCorrect =
false;
2503 if (
TII->isSMRD(Inst)) {
2504 for (
const MachineMemOperand *Memop : Inst.
memoperands()) {
2507 if (!Memop->isInvariant()) {
2508 const Value *
Ptr = Memop->getValue();
2512 if (
ST->hasReadVCCZBug()) {
2514 VCCZCorrect =
false;
2518 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2520 Modified |= insertForcedWaitAfter(Inst,
Block, ScoreBrackets);
2524 ScoreBrackets.dump();
2534 TII->get(
ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2546 AMDGPU::Waitcnt
Wait;
2547 if (
Block.getFirstTerminator() ==
Block.end() &&
2548 isPreheaderToFlush(
Block, ScoreBrackets)) {
2549 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2551 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2553 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2562 dbgs() <<
"*** End Block: ";
2564 ScoreBrackets.dump();
2572bool SIInsertWaitcnts::isPreheaderToFlush(
2573 MachineBasicBlock &
MBB,
const WaitcntBrackets &ScoreBrackets) {
2574 auto [Iterator, IsInserted] = PreheadersToFlush.
try_emplace(&
MBB,
false);
2576 return Iterator->second;
2587 shouldFlushVmCnt(Loop, ScoreBrackets)) {
2588 Iterator->second =
true;
2595bool SIInsertWaitcnts::isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const {
2597 return TII->mayAccessVMEMThroughFlat(
MI);
2609bool SIInsertWaitcnts::shouldFlushVmCnt(MachineLoop *
ML,
2610 const WaitcntBrackets &Brackets) {
2611 bool HasVMemLoad =
false;
2612 bool HasVMemStore =
false;
2613 bool UsesVgprLoadedOutside =
false;
2614 DenseSet<Register> VgprUse;
2615 DenseSet<Register> VgprDef;
2617 for (MachineBasicBlock *
MBB :
ML->blocks()) {
2618 for (MachineInstr &
MI : *
MBB) {
2619 if (isVMEMOrFlatVMEM(
MI)) {
2620 HasVMemLoad |=
MI.mayLoad();
2621 HasVMemStore |=
MI.mayStore();
2624 for (
const MachineOperand &
Op :
MI.all_uses()) {
2625 if (
Op.isDebug() || !
TRI->isVectorRegister(*
MRI,
Op.getReg()))
2627 RegInterval
Interval = Brackets.getRegInterval(&
MI,
Op);
2637 if (Brackets.getRegScore(RegNo, LOAD_CNT) >
2638 Brackets.getScoreLB(LOAD_CNT) ||
2639 Brackets.getRegScore(RegNo, SAMPLE_CNT) >
2640 Brackets.getScoreLB(SAMPLE_CNT) ||
2641 Brackets.getRegScore(RegNo, BVH_CNT) >
2642 Brackets.getScoreLB(BVH_CNT)) {
2643 UsesVgprLoadedOutside =
true;
2650 if (isVMEMOrFlatVMEM(
MI) &&
MI.mayLoad()) {
2651 for (
const MachineOperand &
Op :
MI.all_defs()) {
2652 RegInterval
Interval = Brackets.getRegInterval(&
MI,
Op);
2664 if (!
ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2666 return HasVMemLoad && UsesVgprLoadedOutside &&
ST->hasVmemWriteVgprInOrder();
2669bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
2670 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2672 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2674 if (
auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2675 AA = &AAR->getAAResults();
2677 return SIInsertWaitcnts(MLI, PDT, AA).run(MF);
2689 if (!SIInsertWaitcnts(MLI, PDT,
AA).
run(MF))
2694 .preserve<AAManager>();
2699 TII = ST->getInstrInfo();
2700 TRI = &
TII->getRegisterInfo();
2706 if (ST->hasExtendedWaitCounts()) {
2707 MaxCounter = NUM_EXTENDED_INST_CNTS;
2708 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2709 WCG = &WCGGFX12Plus;
2711 MaxCounter = NUM_NORMAL_INST_CNTS;
2712 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF);
2716 for (
auto T : inst_counter_types())
2717 ForceEmitWaitcnt[
T] =
false;
2719 WaitEventMaskForInst = WCG->getWaitEventMask();
2721 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2723 if (
ST->hasExtendedWaitCounts()) {
2737 [[maybe_unused]]
unsigned NumVGPRsMax =
2739 [[maybe_unused]]
unsigned NumSGPRsMax =
ST->getAddressableNumSGPRs();
2740 assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
2741 assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
2746 MachineBasicBlock &EntryBB = MF.
front();
2757 I !=
E && (
I->isPHI() ||
I->isMetaInstruction()); ++
I)
2760 if (
ST->hasExtendedWaitCounts()) {
2763 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2764 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT)
2767 if (!
ST->hasImageInsts() &&
2768 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
2772 TII->get(instrsForExtendedCounterTypes[CT]))
2779 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(
this);
2780 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2781 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2788 for (
auto *
MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
2791 std::unique_ptr<WaitcntBrackets> Brackets;
2796 for (
auto BII = BlockInfos.
begin(), BIE = BlockInfos.
end(); BII != BIE;
2798 MachineBasicBlock *
MBB = BII->first;
2799 BlockInfo &BI = BII->second;
2805 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2807 *Brackets = *BI.Incoming;
2810 Brackets = std::make_unique<WaitcntBrackets>(
this);
2815 Brackets->~WaitcntBrackets();
2816 new (Brackets.get()) WaitcntBrackets(
this);
2820 Modified |= insertWaitcntInBlock(MF, *
MBB, *Brackets);
2823 if (Brackets->hasPendingEvent()) {
2824 BlockInfo *MoveBracketsToSucc =
nullptr;
2826 auto *SuccBII = BlockInfos.
find(Succ);
2827 BlockInfo &SuccBI = SuccBII->second;
2828 if (!SuccBI.Incoming) {
2829 SuccBI.Dirty =
true;
2830 if (SuccBII <= BII) {
2834 if (!MoveBracketsToSucc) {
2835 MoveBracketsToSucc = &SuccBI;
2837 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2839 }
else if (SuccBI.Incoming->merge(*Brackets)) {
2840 SuccBI.Dirty =
true;
2841 if (SuccBII <= BII) {
2847 if (MoveBracketsToSucc)
2848 MoveBracketsToSucc->Incoming = std::move(Brackets);
2853 if (
ST->hasScalarStores()) {
2854 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
2855 bool HaveScalarStores =
false;
2857 for (MachineBasicBlock &
MBB : MF) {
2858 for (MachineInstr &
MI :
MBB) {
2859 if (!HaveScalarStores &&
TII->isScalarStore(
MI))
2860 HaveScalarStores =
true;
2862 if (
MI.getOpcode() == AMDGPU::S_ENDPGM ||
2863 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2868 if (HaveScalarStores) {
2877 for (MachineBasicBlock *
MBB : EndPgmBlocks) {
2878 bool SeenDCacheWB =
false;
2882 if (
I->getOpcode() == AMDGPU::S_DCACHE_WB)
2883 SeenDCacheWB =
true;
2884 else if (
TII->isScalarStore(*
I))
2885 SeenDCacheWB =
false;
2888 if ((
I->getOpcode() == AMDGPU::S_ENDPGM ||
2889 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
2905 for (MachineInstr *
MI : ReleaseVGPRInsts) {
2907 TII->get(AMDGPU::S_ALLOC_VGPR))
2912 if (!ReleaseVGPRInsts.empty() &&
2913 (MF.getFrameInfo().hasCalls() ||
2914 ST->getOccupancyWithNumVGPRs(
2915 TRI->getNumUsedPhysRegs(*
MRI, AMDGPU::VGPR_32RegClass),
2918 for (MachineInstr *
MI : ReleaseVGPRInsts) {
2919 if (
ST->requiresNopBeforeDeallocVGPRs()) {
2921 TII->get(AMDGPU::S_NOP))
2925 TII->get(AMDGPU::S_SENDMSG))
2931 ReleaseVGPRInsts.clear();
2932 PreheadersToFlush.
clear();
2933 SLoadAddresses.
clear();
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
static bool isOptNone(const MachineFunction &MF)
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
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 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)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
FunctionPass class - This class is used to implement most global optimizations.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI const MachineBasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
Instructions::iterator instr_iterator
instr_iterator instr_end()
iterator_range< succ_iterator > successors()
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
bool isCall(QueryType Type=AnyInBundle) const
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr fully defines the specified register.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
LLVM_ABI void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
const MachineOperand & getOperand(unsigned i) const
bool isMetaInstruction(QueryType Type=IgnoreBundle) const
Return true if this instruction doesn't produce any output in the form of executable instructions.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
Register getReg() const
getReg - Returns the register number.
iterator find(const KeyT &Key)
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static bool isCBranchVCCZRead(const MachineInstr &MI)
static bool isVMEM(const MachineInstr &MI)
static bool isFLATScratch(const MachineInstr &MI)
static bool isEXP(const MachineInstr &MI)
static bool mayWriteLDSThroughDMA(const MachineInstr &MI)
static bool isLDSDIR(const MachineInstr &MI)
static bool isGWS(const MachineInstr &MI)
static bool isFLATGlobal(const MachineInstr &MI)
static bool isVSAMPLE(const MachineInstr &MI)
static bool isAtomicRet(const MachineInstr &MI)
static bool isImage(const MachineInstr &MI)
static unsigned getNonSoftWaitcntOpcode(unsigned Opcode)
static bool isVINTERP(const MachineInstr &MI)
static bool isGFX12CacheInvOrWBInst(unsigned Opc)
static bool isSBarrierSCCWrite(unsigned Opcode)
static bool isMIMG(const MachineInstr &MI)
static bool isFLAT(const MachineInstr &MI)
static bool 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