xref: /llvm-project/llvm/lib/Target/AMDGPU/GCNHazardRecognizer.cpp (revision 97747467f1320b6e80495c5961a0176e0738863b)
1 //===-- GCNHazardRecognizers.cpp - GCN Hazard Recognizer Impls ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements hazard recognizers for scheduling on GCN processors.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "GCNHazardRecognizer.h"
14 #include "GCNSubtarget.h"
15 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
16 #include "SIMachineFunctionInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/TargetParser/TargetParser.h"
20 
21 using namespace llvm;
22 
23 namespace {
24 
25 struct MFMAPaddingRatioParser : public cl::parser<unsigned> {
26   MFMAPaddingRatioParser(cl::Option &O) : cl::parser<unsigned>(O) {}
27 
28   bool parse(cl::Option &O, StringRef ArgName, StringRef Arg, unsigned &Value) {
29     if (Arg.getAsInteger(0, Value))
30       return O.error("'" + Arg + "' value invalid for uint argument!");
31 
32     if (Value > 100)
33       return O.error("'" + Arg + "' value must be in the range [0, 100]!");
34 
35     return false;
36   }
37 };
38 
39 } // end anonymous namespace
40 
41 static cl::opt<unsigned, false, MFMAPaddingRatioParser>
42     MFMAPaddingRatio("amdgpu-mfma-padding-ratio", cl::init(0), cl::Hidden,
43                      cl::desc("Fill a percentage of the latency between "
44                               "neighboring MFMA with s_nops."));
45 
46 //===----------------------------------------------------------------------===//
47 // Hazard Recognizer Implementation
48 //===----------------------------------------------------------------------===//
49 
50 static bool shouldRunLdsBranchVmemWARHazardFixup(const MachineFunction &MF,
51                                                  const GCNSubtarget &ST);
52 
53 GCNHazardRecognizer::GCNHazardRecognizer(const MachineFunction &MF) :
54   IsHazardRecognizerMode(false),
55   CurrCycleInstr(nullptr),
56   MF(MF),
57   ST(MF.getSubtarget<GCNSubtarget>()),
58   TII(*ST.getInstrInfo()),
59   TRI(TII.getRegisterInfo()),
60   ClauseUses(TRI.getNumRegUnits()),
61   ClauseDefs(TRI.getNumRegUnits()) {
62   MaxLookAhead = MF.getRegInfo().isPhysRegUsed(AMDGPU::AGPR0) ? 19 : 5;
63   TSchedModel.init(&ST);
64   RunLdsBranchVmemWARHazardFixup = shouldRunLdsBranchVmemWARHazardFixup(MF, ST);
65 }
66 
67 void GCNHazardRecognizer::Reset() {
68   EmittedInstrs.clear();
69 }
70 
71 void GCNHazardRecognizer::EmitInstruction(SUnit *SU) {
72   EmitInstruction(SU->getInstr());
73 }
74 
75 void GCNHazardRecognizer::EmitInstruction(MachineInstr *MI) {
76   CurrCycleInstr = MI;
77 }
78 
79 static bool isDivFMas(unsigned Opcode) {
80   return Opcode == AMDGPU::V_DIV_FMAS_F32_e64 || Opcode == AMDGPU::V_DIV_FMAS_F64_e64;
81 }
82 
83 static bool isSGetReg(unsigned Opcode) {
84   return Opcode == AMDGPU::S_GETREG_B32;
85 }
86 
87 static bool isSSetReg(unsigned Opcode) {
88   switch (Opcode) {
89   case AMDGPU::S_SETREG_B32:
90   case AMDGPU::S_SETREG_B32_mode:
91   case AMDGPU::S_SETREG_IMM32_B32:
92   case AMDGPU::S_SETREG_IMM32_B32_mode:
93     return true;
94   }
95   return false;
96 }
97 
98 static bool isRWLane(unsigned Opcode) {
99   return Opcode == AMDGPU::V_READLANE_B32 || Opcode == AMDGPU::V_WRITELANE_B32;
100 }
101 
102 static bool isRFE(unsigned Opcode) {
103   return Opcode == AMDGPU::S_RFE_B64;
104 }
105 
106 static bool isSMovRel(unsigned Opcode) {
107   switch (Opcode) {
108   case AMDGPU::S_MOVRELS_B32:
109   case AMDGPU::S_MOVRELS_B64:
110   case AMDGPU::S_MOVRELD_B32:
111   case AMDGPU::S_MOVRELD_B64:
112     return true;
113   default:
114     return false;
115   }
116 }
117 
118 static bool isDGEMM(unsigned Opcode) {
119   return AMDGPU::getMAIIsDGEMM(Opcode);
120 }
121 
122 static bool isXDL(const GCNSubtarget &ST, const MachineInstr &MI) {
123   unsigned Opcode = MI.getOpcode();
124 
125   if (!SIInstrInfo::isMAI(MI) ||
126       isDGEMM(Opcode) ||
127       Opcode == AMDGPU::V_ACCVGPR_WRITE_B32_e64 ||
128       Opcode == AMDGPU::V_ACCVGPR_READ_B32_e64)
129     return false;
130 
131   if (!ST.hasGFX940Insts())
132     return true;
133 
134   return AMDGPU::getMAIIsGFX940XDL(Opcode);
135 }
136 
137 static bool isSendMsgTraceDataOrGDS(const SIInstrInfo &TII,
138                                     const MachineInstr &MI) {
139   if (TII.isAlwaysGDS(MI.getOpcode()))
140     return true;
141 
142   switch (MI.getOpcode()) {
143   case AMDGPU::S_SENDMSG:
144   case AMDGPU::S_SENDMSGHALT:
145   case AMDGPU::S_TTRACEDATA:
146     return true;
147   // These DS opcodes don't support GDS.
148   case AMDGPU::DS_NOP:
149   case AMDGPU::DS_PERMUTE_B32:
150   case AMDGPU::DS_BPERMUTE_B32:
151     return false;
152   default:
153     if (TII.isDS(MI.getOpcode())) {
154       int GDS = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
155                                            AMDGPU::OpName::gds);
156       if (MI.getOperand(GDS).getImm())
157         return true;
158     }
159     return false;
160   }
161 }
162 
163 static bool isPermlane(const MachineInstr &MI) {
164   unsigned Opcode = MI.getOpcode();
165   return Opcode == AMDGPU::V_PERMLANE16_B32_e64 ||
166          Opcode == AMDGPU::V_PERMLANEX16_B32_e64 ||
167          Opcode == AMDGPU::V_PERMLANE16_VAR_B32_e64 ||
168          Opcode == AMDGPU::V_PERMLANEX16_VAR_B32_e64;
169 }
170 
171 static bool isLdsDma(const MachineInstr &MI) {
172   return SIInstrInfo::isVALU(MI) &&
173          (SIInstrInfo::isMUBUF(MI) || SIInstrInfo::isFLAT(MI));
174 }
175 
176 static unsigned getHWReg(const SIInstrInfo *TII, const MachineInstr &RegInstr) {
177   const MachineOperand *RegOp = TII->getNamedOperand(RegInstr,
178                                                      AMDGPU::OpName::simm16);
179   return RegOp->getImm() & AMDGPU::Hwreg::ID_MASK_;
180 }
181 
182 ScheduleHazardRecognizer::HazardType
183 GCNHazardRecognizer::getHazardType(SUnit *SU, int Stalls) {
184   MachineInstr *MI = SU->getInstr();
185   // If we are not in "HazardRecognizerMode" and therefore not being run from
186   // the scheduler, track possible stalls from hazards but don't insert noops.
187   auto HazardType = IsHazardRecognizerMode ? NoopHazard : Hazard;
188 
189   if (MI->isBundle())
190    return NoHazard;
191 
192   if (SIInstrInfo::isSMRD(*MI) && checkSMRDHazards(MI) > 0)
193     return HazardType;
194 
195   if (ST.hasNSAtoVMEMBug() && checkNSAtoVMEMHazard(MI) > 0)
196     return HazardType;
197 
198   if (checkFPAtomicToDenormModeHazard(MI) > 0)
199     return HazardType;
200 
201   if (ST.hasNoDataDepHazard())
202     return NoHazard;
203 
204   // FIXME: Should flat be considered vmem?
205   if ((SIInstrInfo::isVMEM(*MI) ||
206        SIInstrInfo::isFLAT(*MI))
207       && checkVMEMHazards(MI) > 0)
208     return HazardType;
209 
210   if (SIInstrInfo::isVALU(*MI) && checkVALUHazards(MI) > 0)
211     return HazardType;
212 
213   if (SIInstrInfo::isDPP(*MI) && checkDPPHazards(MI) > 0)
214     return HazardType;
215 
216   if (isDivFMas(MI->getOpcode()) && checkDivFMasHazards(MI) > 0)
217     return HazardType;
218 
219   if (isRWLane(MI->getOpcode()) && checkRWLaneHazards(MI) > 0)
220     return HazardType;
221 
222   if ((SIInstrInfo::isVALU(*MI) || SIInstrInfo::isVMEM(*MI) ||
223        SIInstrInfo::isFLAT(*MI) || SIInstrInfo::isDS(*MI) ||
224        SIInstrInfo::isEXP(*MI)) && checkMAIVALUHazards(MI) > 0)
225     return HazardType;
226 
227   if (isSGetReg(MI->getOpcode()) && checkGetRegHazards(MI) > 0)
228     return HazardType;
229 
230   if (isSSetReg(MI->getOpcode()) && checkSetRegHazards(MI) > 0)
231     return HazardType;
232 
233   if (isRFE(MI->getOpcode()) && checkRFEHazards(MI) > 0)
234     return HazardType;
235 
236   if (((ST.hasReadM0MovRelInterpHazard() &&
237         (TII.isVINTRP(*MI) || isSMovRel(MI->getOpcode()) ||
238          MI->getOpcode() == AMDGPU::DS_WRITE_ADDTID_B32 ||
239          MI->getOpcode() == AMDGPU::DS_READ_ADDTID_B32)) ||
240        (ST.hasReadM0SendMsgHazard() && isSendMsgTraceDataOrGDS(TII, *MI)) ||
241        (ST.hasReadM0LdsDmaHazard() && isLdsDma(*MI)) ||
242        (ST.hasReadM0LdsDirectHazard() &&
243         MI->readsRegister(AMDGPU::LDS_DIRECT))) &&
244       checkReadM0Hazards(MI) > 0)
245     return HazardType;
246 
247   if (SIInstrInfo::isMAI(*MI) && checkMAIHazards(MI) > 0)
248     return HazardType;
249 
250   if ((SIInstrInfo::isVMEM(*MI) ||
251        SIInstrInfo::isFLAT(*MI) ||
252        SIInstrInfo::isDS(*MI)) && checkMAILdStHazards(MI) > 0)
253     return HazardType;
254 
255   if (MI->isInlineAsm() && checkInlineAsmHazards(MI) > 0)
256     return HazardType;
257 
258   return NoHazard;
259 }
260 
261 static void insertNoopsInBundle(MachineInstr *MI, const SIInstrInfo &TII,
262                                 unsigned Quantity) {
263   while (Quantity > 0) {
264     unsigned Arg = std::min(Quantity, 8u);
265     Quantity -= Arg;
266     BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII.get(AMDGPU::S_NOP))
267         .addImm(Arg - 1);
268   }
269 }
270 
271 unsigned
272 GCNHazardRecognizer::getMFMAPipelineWaitStates(const MachineInstr &MI) const {
273   const MCSchedClassDesc *SC = TSchedModel.resolveSchedClass(&MI);
274   assert(TSchedModel.getWriteProcResBegin(SC) !=
275          TSchedModel.getWriteProcResEnd(SC));
276   return TSchedModel.getWriteProcResBegin(SC)->ReleaseAtCycle;
277 }
278 
279 void GCNHazardRecognizer::processBundle() {
280   MachineBasicBlock::instr_iterator MI = std::next(CurrCycleInstr->getIterator());
281   MachineBasicBlock::instr_iterator E = CurrCycleInstr->getParent()->instr_end();
282   // Check bundled MachineInstr's for hazards.
283   for (; MI != E && MI->isInsideBundle(); ++MI) {
284     CurrCycleInstr = &*MI;
285     unsigned WaitStates = PreEmitNoopsCommon(CurrCycleInstr);
286 
287     if (IsHazardRecognizerMode) {
288       fixHazards(CurrCycleInstr);
289 
290       insertNoopsInBundle(CurrCycleInstr, TII, WaitStates);
291     }
292 
293     // It’s unnecessary to track more than MaxLookAhead instructions. Since we
294     // include the bundled MI directly after, only add a maximum of
295     // (MaxLookAhead - 1) noops to EmittedInstrs.
296     for (unsigned i = 0, e = std::min(WaitStates, MaxLookAhead - 1); i < e; ++i)
297       EmittedInstrs.push_front(nullptr);
298 
299     EmittedInstrs.push_front(CurrCycleInstr);
300     EmittedInstrs.resize(MaxLookAhead);
301   }
302   CurrCycleInstr = nullptr;
303 }
304 
305 void GCNHazardRecognizer::runOnInstruction(MachineInstr *MI) {
306   assert(IsHazardRecognizerMode);
307 
308   unsigned NumPreNoops = PreEmitNoops(MI);
309   EmitNoops(NumPreNoops);
310   if (MI->isInsideBundle())
311     insertNoopsInBundle(MI, TII, NumPreNoops);
312   else
313     TII.insertNoops(*MI->getParent(), MachineBasicBlock::iterator(MI),
314                     NumPreNoops);
315   EmitInstruction(MI);
316   AdvanceCycle();
317 }
318 
319 unsigned GCNHazardRecognizer::PreEmitNoops(MachineInstr *MI) {
320   IsHazardRecognizerMode = true;
321   CurrCycleInstr = MI;
322   unsigned W = PreEmitNoopsCommon(MI);
323   fixHazards(MI);
324   CurrCycleInstr = nullptr;
325   return W;
326 }
327 
328 unsigned GCNHazardRecognizer::PreEmitNoopsCommon(MachineInstr *MI) {
329   if (MI->isBundle())
330     return 0;
331 
332   int WaitStates = 0;
333 
334   if (SIInstrInfo::isSMRD(*MI))
335     return std::max(WaitStates, checkSMRDHazards(MI));
336 
337   if (ST.hasNSAtoVMEMBug())
338     WaitStates = std::max(WaitStates, checkNSAtoVMEMHazard(MI));
339 
340   WaitStates = std::max(WaitStates, checkFPAtomicToDenormModeHazard(MI));
341 
342   if (ST.hasNoDataDepHazard())
343     return WaitStates;
344 
345   if (SIInstrInfo::isVMEM(*MI) || SIInstrInfo::isFLAT(*MI))
346     WaitStates = std::max(WaitStates, checkVMEMHazards(MI));
347 
348   if (SIInstrInfo::isVALU(*MI))
349     WaitStates = std::max(WaitStates, checkVALUHazards(MI));
350 
351   if (SIInstrInfo::isDPP(*MI))
352     WaitStates = std::max(WaitStates, checkDPPHazards(MI));
353 
354   if (isDivFMas(MI->getOpcode()))
355     WaitStates = std::max(WaitStates, checkDivFMasHazards(MI));
356 
357   if (isRWLane(MI->getOpcode()))
358     WaitStates = std::max(WaitStates, checkRWLaneHazards(MI));
359 
360   if ((SIInstrInfo::isVALU(*MI) || SIInstrInfo::isVMEM(*MI) ||
361        SIInstrInfo::isFLAT(*MI) || SIInstrInfo::isDS(*MI) ||
362        SIInstrInfo::isEXP(*MI)) && checkMAIVALUHazards(MI) > 0)
363     WaitStates = std::max(WaitStates, checkMAIVALUHazards(MI));
364 
365   if (MI->isInlineAsm())
366     return std::max(WaitStates, checkInlineAsmHazards(MI));
367 
368   if (isSGetReg(MI->getOpcode()))
369     return std::max(WaitStates, checkGetRegHazards(MI));
370 
371   if (isSSetReg(MI->getOpcode()))
372     return std::max(WaitStates, checkSetRegHazards(MI));
373 
374   if (isRFE(MI->getOpcode()))
375     return std::max(WaitStates, checkRFEHazards(MI));
376 
377   if ((ST.hasReadM0MovRelInterpHazard() &&
378        (TII.isVINTRP(*MI) || isSMovRel(MI->getOpcode()) ||
379         MI->getOpcode() == AMDGPU::DS_WRITE_ADDTID_B32 ||
380         MI->getOpcode() == AMDGPU::DS_READ_ADDTID_B32)) ||
381       (ST.hasReadM0SendMsgHazard() && isSendMsgTraceDataOrGDS(TII, *MI)) ||
382       (ST.hasReadM0LdsDmaHazard() && isLdsDma(*MI)) ||
383       (ST.hasReadM0LdsDirectHazard() && MI->readsRegister(AMDGPU::LDS_DIRECT)))
384     return std::max(WaitStates, checkReadM0Hazards(MI));
385 
386   if (SIInstrInfo::isMAI(*MI))
387     return std::max(WaitStates, checkMAIHazards(MI));
388 
389   if (SIInstrInfo::isVMEM(*MI) ||
390       SIInstrInfo::isFLAT(*MI) ||
391       SIInstrInfo::isDS(*MI))
392     return std::max(WaitStates, checkMAILdStHazards(MI));
393 
394   return WaitStates;
395 }
396 
397 void GCNHazardRecognizer::EmitNoop() {
398   EmittedInstrs.push_front(nullptr);
399 }
400 
401 void GCNHazardRecognizer::AdvanceCycle() {
402   // When the scheduler detects a stall, it will call AdvanceCycle() without
403   // emitting any instructions.
404   if (!CurrCycleInstr) {
405     EmittedInstrs.push_front(nullptr);
406     return;
407   }
408 
409   if (CurrCycleInstr->isBundle()) {
410     processBundle();
411     return;
412   }
413 
414   unsigned NumWaitStates = TII.getNumWaitStates(*CurrCycleInstr);
415   if (!NumWaitStates) {
416     CurrCycleInstr = nullptr;
417     return;
418   }
419 
420   // Keep track of emitted instructions
421   EmittedInstrs.push_front(CurrCycleInstr);
422 
423   // Add a nullptr for each additional wait state after the first.  Make sure
424   // not to add more than getMaxLookAhead() items to the list, since we
425   // truncate the list to that size right after this loop.
426   for (unsigned i = 1, e = std::min(NumWaitStates, getMaxLookAhead());
427        i < e; ++i) {
428     EmittedInstrs.push_front(nullptr);
429   }
430 
431   // getMaxLookahead() is the largest number of wait states we will ever need
432   // to insert, so there is no point in keeping track of more than that many
433   // wait states.
434   EmittedInstrs.resize(getMaxLookAhead());
435 
436   CurrCycleInstr = nullptr;
437 }
438 
439 void GCNHazardRecognizer::RecedeCycle() {
440   llvm_unreachable("hazard recognizer does not support bottom-up scheduling.");
441 }
442 
443 //===----------------------------------------------------------------------===//
444 // Helper Functions
445 //===----------------------------------------------------------------------===//
446 
447 typedef enum { HazardFound, HazardExpired, NoHazardFound } HazardFnResult;
448 
449 typedef function_ref<bool(const MachineInstr &, int WaitStates)> IsExpiredFn;
450 typedef function_ref<unsigned int(const MachineInstr &)> GetNumWaitStatesFn;
451 
452 // Search for a hazard in a block and its predecessors.
453 template <typename StateT>
454 static bool
455 hasHazard(StateT State,
456           function_ref<HazardFnResult(StateT &, const MachineInstr &)> IsHazard,
457           function_ref<void(StateT &, const MachineInstr &)> UpdateState,
458           const MachineBasicBlock *MBB,
459           MachineBasicBlock::const_reverse_instr_iterator I,
460           DenseSet<const MachineBasicBlock *> &Visited) {
461   for (auto E = MBB->instr_rend(); I != E; ++I) {
462     // No need to look at parent BUNDLE instructions.
463     if (I->isBundle())
464       continue;
465 
466     switch (IsHazard(State, *I)) {
467     case HazardFound:
468       return true;
469     case HazardExpired:
470       return false;
471     default:
472       // Continue search
473       break;
474     }
475 
476     if (I->isInlineAsm() || I->isMetaInstruction())
477       continue;
478 
479     UpdateState(State, *I);
480   }
481 
482   for (MachineBasicBlock *Pred : MBB->predecessors()) {
483     if (!Visited.insert(Pred).second)
484       continue;
485 
486     if (hasHazard(State, IsHazard, UpdateState, Pred, Pred->instr_rbegin(),
487                   Visited))
488       return true;
489   }
490 
491   return false;
492 }
493 
494 // Returns a minimum wait states since \p I walking all predecessors.
495 // Only scans until \p IsExpired does not return true.
496 // Can only be run in a hazard recognizer mode.
497 static int getWaitStatesSince(
498     GCNHazardRecognizer::IsHazardFn IsHazard, const MachineBasicBlock *MBB,
499     MachineBasicBlock::const_reverse_instr_iterator I, int WaitStates,
500     IsExpiredFn IsExpired, DenseSet<const MachineBasicBlock *> &Visited,
501     GetNumWaitStatesFn GetNumWaitStates = SIInstrInfo::getNumWaitStates) {
502   for (auto E = MBB->instr_rend(); I != E; ++I) {
503     // Don't add WaitStates for parent BUNDLE instructions.
504     if (I->isBundle())
505       continue;
506 
507     if (IsHazard(*I))
508       return WaitStates;
509 
510     if (I->isInlineAsm())
511       continue;
512 
513     WaitStates += GetNumWaitStates(*I);
514 
515     if (IsExpired(*I, WaitStates))
516       return std::numeric_limits<int>::max();
517   }
518 
519   int MinWaitStates = std::numeric_limits<int>::max();
520   for (MachineBasicBlock *Pred : MBB->predecessors()) {
521     if (!Visited.insert(Pred).second)
522       continue;
523 
524     int W = getWaitStatesSince(IsHazard, Pred, Pred->instr_rbegin(), WaitStates,
525                                IsExpired, Visited, GetNumWaitStates);
526 
527     MinWaitStates = std::min(MinWaitStates, W);
528   }
529 
530   return MinWaitStates;
531 }
532 
533 static int getWaitStatesSince(GCNHazardRecognizer::IsHazardFn IsHazard,
534                               const MachineInstr *MI, IsExpiredFn IsExpired) {
535   DenseSet<const MachineBasicBlock *> Visited;
536   return getWaitStatesSince(IsHazard, MI->getParent(),
537                             std::next(MI->getReverseIterator()),
538                             0, IsExpired, Visited);
539 }
540 
541 int GCNHazardRecognizer::getWaitStatesSince(IsHazardFn IsHazard, int Limit) {
542   if (IsHazardRecognizerMode) {
543     auto IsExpiredFn = [Limit](const MachineInstr &, int WaitStates) {
544       return WaitStates >= Limit;
545     };
546     return ::getWaitStatesSince(IsHazard, CurrCycleInstr, IsExpiredFn);
547   }
548 
549   int WaitStates = 0;
550   for (MachineInstr *MI : EmittedInstrs) {
551     if (MI) {
552       if (IsHazard(*MI))
553         return WaitStates;
554 
555       if (MI->isInlineAsm())
556         continue;
557     }
558     ++WaitStates;
559 
560     if (WaitStates >= Limit)
561       break;
562   }
563   return std::numeric_limits<int>::max();
564 }
565 
566 int GCNHazardRecognizer::getWaitStatesSinceDef(unsigned Reg,
567                                                IsHazardFn IsHazardDef,
568                                                int Limit) {
569   const SIRegisterInfo *TRI = ST.getRegisterInfo();
570 
571   auto IsHazardFn = [IsHazardDef, TRI, Reg](const MachineInstr &MI) {
572     return IsHazardDef(MI) && MI.modifiesRegister(Reg, TRI);
573   };
574 
575   return getWaitStatesSince(IsHazardFn, Limit);
576 }
577 
578 int GCNHazardRecognizer::getWaitStatesSinceSetReg(IsHazardFn IsHazard,
579                                                   int Limit) {
580   auto IsHazardFn = [IsHazard](const MachineInstr &MI) {
581     return isSSetReg(MI.getOpcode()) && IsHazard(MI);
582   };
583 
584   return getWaitStatesSince(IsHazardFn, Limit);
585 }
586 
587 //===----------------------------------------------------------------------===//
588 // No-op Hazard Detection
589 //===----------------------------------------------------------------------===//
590 
591 static void addRegUnits(const SIRegisterInfo &TRI, BitVector &BV,
592                         MCRegister Reg) {
593   for (MCRegUnit Unit : TRI.regunits(Reg))
594     BV.set(Unit);
595 }
596 
597 static void addRegsToSet(const SIRegisterInfo &TRI,
598                          iterator_range<MachineInstr::const_mop_iterator> Ops,
599                          BitVector &DefSet, BitVector &UseSet) {
600   for (const MachineOperand &Op : Ops) {
601     if (Op.isReg())
602       addRegUnits(TRI, Op.isDef() ? DefSet : UseSet, Op.getReg().asMCReg());
603   }
604 }
605 
606 void GCNHazardRecognizer::addClauseInst(const MachineInstr &MI) {
607   addRegsToSet(TRI, MI.operands(), ClauseDefs, ClauseUses);
608 }
609 
610 static bool breaksSMEMSoftClause(MachineInstr *MI) {
611   return !SIInstrInfo::isSMRD(*MI);
612 }
613 
614 static bool breaksVMEMSoftClause(MachineInstr *MI) {
615   return !SIInstrInfo::isVMEM(*MI) && !SIInstrInfo::isFLAT(*MI);
616 }
617 
618 int GCNHazardRecognizer::checkSoftClauseHazards(MachineInstr *MEM) {
619   // SMEM soft clause are only present on VI+, and only matter if xnack is
620   // enabled.
621   if (!ST.isXNACKEnabled())
622     return 0;
623 
624   bool IsSMRD = TII.isSMRD(*MEM);
625 
626   resetClause();
627 
628   // A soft-clause is any group of consecutive SMEM instructions.  The
629   // instructions in this group may return out of order and/or may be
630   // replayed (i.e. the same instruction issued more than once).
631   //
632   // In order to handle these situations correctly we need to make sure that
633   // when a clause has more than one instruction, no instruction in the clause
634   // writes to a register that is read by another instruction in the clause
635   // (including itself). If we encounter this situation, we need to break the
636   // clause by inserting a non SMEM instruction.
637 
638   for (MachineInstr *MI : EmittedInstrs) {
639     // When we hit a non-SMEM instruction then we have passed the start of the
640     // clause and we can stop.
641     if (!MI)
642       break;
643 
644     if (IsSMRD ? breaksSMEMSoftClause(MI) : breaksVMEMSoftClause(MI))
645       break;
646 
647     addClauseInst(*MI);
648   }
649 
650   if (ClauseDefs.none())
651     return 0;
652 
653   // We need to make sure not to put loads and stores in the same clause if they
654   // use the same address. For now, just start a new clause whenever we see a
655   // store.
656   if (MEM->mayStore())
657     return 1;
658 
659   addClauseInst(*MEM);
660 
661   // If the set of defs and uses intersect then we cannot add this instruction
662   // to the clause, so we have a hazard.
663   return ClauseDefs.anyCommon(ClauseUses) ? 1 : 0;
664 }
665 
666 int GCNHazardRecognizer::checkSMRDHazards(MachineInstr *SMRD) {
667   int WaitStatesNeeded = 0;
668 
669   WaitStatesNeeded = checkSoftClauseHazards(SMRD);
670 
671   // This SMRD hazard only affects SI.
672   if (!ST.hasSMRDReadVALUDefHazard())
673     return WaitStatesNeeded;
674 
675   // A read of an SGPR by SMRD instruction requires 4 wait states when the
676   // SGPR was written by a VALU instruction.
677   int SmrdSgprWaitStates = 4;
678   auto IsHazardDefFn = [this](const MachineInstr &MI) {
679     return TII.isVALU(MI);
680   };
681   auto IsBufferHazardDefFn = [this](const MachineInstr &MI) {
682     return TII.isSALU(MI);
683   };
684 
685   bool IsBufferSMRD = TII.isBufferSMRD(*SMRD);
686 
687   for (const MachineOperand &Use : SMRD->uses()) {
688     if (!Use.isReg())
689       continue;
690     int WaitStatesNeededForUse =
691         SmrdSgprWaitStates - getWaitStatesSinceDef(Use.getReg(), IsHazardDefFn,
692                                                    SmrdSgprWaitStates);
693     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
694 
695     // This fixes what appears to be undocumented hardware behavior in SI where
696     // s_mov writing a descriptor and s_buffer_load_dword reading the descriptor
697     // needs some number of nops in between. We don't know how many we need, but
698     // let's use 4. This wasn't discovered before probably because the only
699     // case when this happens is when we expand a 64-bit pointer into a full
700     // descriptor and use s_buffer_load_dword instead of s_load_dword, which was
701     // probably never encountered in the closed-source land.
702     if (IsBufferSMRD) {
703       int WaitStatesNeededForUse =
704         SmrdSgprWaitStates - getWaitStatesSinceDef(Use.getReg(),
705                                                    IsBufferHazardDefFn,
706                                                    SmrdSgprWaitStates);
707       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
708     }
709   }
710 
711   return WaitStatesNeeded;
712 }
713 
714 int GCNHazardRecognizer::checkVMEMHazards(MachineInstr* VMEM) {
715   if (!ST.hasVMEMReadSGPRVALUDefHazard())
716     return 0;
717 
718   int WaitStatesNeeded = checkSoftClauseHazards(VMEM);
719 
720   // A read of an SGPR by a VMEM instruction requires 5 wait states when the
721   // SGPR was written by a VALU Instruction.
722   const int VmemSgprWaitStates = 5;
723   auto IsHazardDefFn = [this](const MachineInstr &MI) {
724     return TII.isVALU(MI);
725   };
726   for (const MachineOperand &Use : VMEM->uses()) {
727     if (!Use.isReg() || TRI.isVectorRegister(MF.getRegInfo(), Use.getReg()))
728       continue;
729 
730     int WaitStatesNeededForUse =
731         VmemSgprWaitStates - getWaitStatesSinceDef(Use.getReg(), IsHazardDefFn,
732                                                    VmemSgprWaitStates);
733     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
734   }
735   return WaitStatesNeeded;
736 }
737 
738 int GCNHazardRecognizer::checkDPPHazards(MachineInstr *DPP) {
739   const SIRegisterInfo *TRI = ST.getRegisterInfo();
740   const SIInstrInfo *TII = ST.getInstrInfo();
741 
742   // Check for DPP VGPR read after VALU VGPR write and EXEC write.
743   int DppVgprWaitStates = 2;
744   int DppExecWaitStates = 5;
745   int WaitStatesNeeded = 0;
746   auto IsHazardDefFn = [TII](const MachineInstr &MI) {
747     return TII->isVALU(MI);
748   };
749 
750   for (const MachineOperand &Use : DPP->uses()) {
751     if (!Use.isReg() || !TRI->isVGPR(MF.getRegInfo(), Use.getReg()))
752       continue;
753     int WaitStatesNeededForUse =
754         DppVgprWaitStates - getWaitStatesSinceDef(
755                                 Use.getReg(),
756                                 [](const MachineInstr &) { return true; },
757                                 DppVgprWaitStates);
758     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
759   }
760 
761   WaitStatesNeeded = std::max(
762       WaitStatesNeeded,
763       DppExecWaitStates - getWaitStatesSinceDef(AMDGPU::EXEC, IsHazardDefFn,
764                                                 DppExecWaitStates));
765 
766   return WaitStatesNeeded;
767 }
768 
769 int GCNHazardRecognizer::checkDivFMasHazards(MachineInstr *DivFMas) {
770   const SIInstrInfo *TII = ST.getInstrInfo();
771 
772   // v_div_fmas requires 4 wait states after a write to vcc from a VALU
773   // instruction.
774   const int DivFMasWaitStates = 4;
775   auto IsHazardDefFn = [TII](const MachineInstr &MI) {
776     return TII->isVALU(MI);
777   };
778   int WaitStatesNeeded = getWaitStatesSinceDef(AMDGPU::VCC, IsHazardDefFn,
779                                                DivFMasWaitStates);
780 
781   return DivFMasWaitStates - WaitStatesNeeded;
782 }
783 
784 int GCNHazardRecognizer::checkGetRegHazards(MachineInstr *GetRegInstr) {
785   const SIInstrInfo *TII = ST.getInstrInfo();
786   unsigned GetRegHWReg = getHWReg(TII, *GetRegInstr);
787 
788   const int GetRegWaitStates = 2;
789   auto IsHazardFn = [TII, GetRegHWReg](const MachineInstr &MI) {
790     return GetRegHWReg == getHWReg(TII, MI);
791   };
792   int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, GetRegWaitStates);
793 
794   return GetRegWaitStates - WaitStatesNeeded;
795 }
796 
797 int GCNHazardRecognizer::checkSetRegHazards(MachineInstr *SetRegInstr) {
798   const SIInstrInfo *TII = ST.getInstrInfo();
799   unsigned HWReg = getHWReg(TII, *SetRegInstr);
800 
801   const int SetRegWaitStates = ST.getSetRegWaitStates();
802   auto IsHazardFn = [TII, HWReg](const MachineInstr &MI) {
803     return HWReg == getHWReg(TII, MI);
804   };
805   int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, SetRegWaitStates);
806   return SetRegWaitStates - WaitStatesNeeded;
807 }
808 
809 int GCNHazardRecognizer::createsVALUHazard(const MachineInstr &MI) {
810   if (!MI.mayStore())
811     return -1;
812 
813   const SIInstrInfo *TII = ST.getInstrInfo();
814   unsigned Opcode = MI.getOpcode();
815   const MCInstrDesc &Desc = MI.getDesc();
816 
817   int VDataIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdata);
818   int VDataRCID = -1;
819   if (VDataIdx != -1)
820     VDataRCID = Desc.operands()[VDataIdx].RegClass;
821 
822   if (TII->isMUBUF(MI) || TII->isMTBUF(MI)) {
823     // There is no hazard if the instruction does not use vector regs
824     // (like wbinvl1)
825     if (VDataIdx == -1)
826       return -1;
827     // For MUBUF/MTBUF instructions this hazard only exists if the
828     // instruction is not using a register in the soffset field.
829     const MachineOperand *SOffset =
830         TII->getNamedOperand(MI, AMDGPU::OpName::soffset);
831     // If we have no soffset operand, then assume this field has been
832     // hardcoded to zero.
833     if (AMDGPU::getRegBitWidth(VDataRCID) > 64 &&
834         (!SOffset || !SOffset->isReg()))
835       return VDataIdx;
836   }
837 
838   // MIMG instructions create a hazard if they don't use a 256-bit T# and
839   // the store size is greater than 8 bytes and they have more than two bits
840   // of their dmask set.
841   // All our MIMG definitions use a 256-bit T#, so we can skip checking for them.
842   if (TII->isMIMG(MI)) {
843     int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::srsrc);
844     assert(SRsrcIdx != -1 &&
845            AMDGPU::getRegBitWidth(Desc.operands()[SRsrcIdx].RegClass) == 256);
846     (void)SRsrcIdx;
847   }
848 
849   if (TII->isFLAT(MI)) {
850     int DataIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdata);
851     if (AMDGPU::getRegBitWidth(Desc.operands()[DataIdx].RegClass) > 64)
852       return DataIdx;
853   }
854 
855   return -1;
856 }
857 
858 int
859 GCNHazardRecognizer::checkVALUHazardsHelper(const MachineOperand &Def,
860                                             const MachineRegisterInfo &MRI) {
861   // Helper to check for the hazard where VMEM instructions that store more than
862   // 8 bytes can have there store data over written by the next instruction.
863   const SIRegisterInfo *TRI = ST.getRegisterInfo();
864 
865   const int VALUWaitStates = ST.hasGFX940Insts() ? 2 : 1;
866   int WaitStatesNeeded = 0;
867 
868   if (!TRI->isVectorRegister(MRI, Def.getReg()))
869     return WaitStatesNeeded;
870   Register Reg = Def.getReg();
871   auto IsHazardFn = [this, Reg, TRI](const MachineInstr &MI) {
872     int DataIdx = createsVALUHazard(MI);
873     return DataIdx >= 0 &&
874            TRI->regsOverlap(MI.getOperand(DataIdx).getReg(), Reg);
875   };
876   int WaitStatesNeededForDef =
877     VALUWaitStates - getWaitStatesSince(IsHazardFn, VALUWaitStates);
878   WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
879 
880   return WaitStatesNeeded;
881 }
882 
883 int GCNHazardRecognizer::checkVALUHazards(MachineInstr *VALU) {
884   int WaitStatesNeeded = 0;
885 
886   if (ST.hasTransForwardingHazard() && !SIInstrInfo::isTRANS(*VALU)) {
887     const int TransDefWaitstates = 1;
888 
889     auto IsTransDefFn = [this, VALU](const MachineInstr &MI) {
890       if (!SIInstrInfo::isTRANS(MI))
891         return false;
892       const SIRegisterInfo *TRI = ST.getRegisterInfo();
893       const SIInstrInfo *TII = ST.getInstrInfo();
894       Register Def = TII->getNamedOperand(MI, AMDGPU::OpName::vdst)->getReg();
895 
896       for (const MachineOperand &Use : VALU->explicit_uses()) {
897         if (Use.isReg() && TRI->regsOverlap(Def, Use.getReg()))
898           return true;
899       }
900 
901       return false;
902     };
903 
904     int WaitStatesNeededForDef =
905         TransDefWaitstates -
906         getWaitStatesSince(IsTransDefFn, TransDefWaitstates);
907     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
908   }
909 
910   if (ST.hasDstSelForwardingHazard()) {
911     const int Shift16DefWaitstates = 1;
912 
913     auto IsShift16BitDefFn = [this, VALU](const MachineInstr &MI) {
914       if (!SIInstrInfo::isVALU(MI))
915         return false;
916       const SIInstrInfo *TII = ST.getInstrInfo();
917       if (SIInstrInfo::isSDWA(MI)) {
918         if (auto *DstSel = TII->getNamedOperand(MI, AMDGPU::OpName::dst_sel))
919           if (DstSel->getImm() == AMDGPU::SDWA::DWORD)
920             return false;
921       } else {
922         if (!AMDGPU::hasNamedOperand(MI.getOpcode(), AMDGPU::OpName::op_sel) ||
923             !(TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)
924                   ->getImm() &
925               SISrcMods::DST_OP_SEL))
926           return false;
927       }
928       const SIRegisterInfo *TRI = ST.getRegisterInfo();
929       if (auto *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::vdst)) {
930         Register Def = Dst->getReg();
931 
932         for (const MachineOperand &Use : VALU->explicit_uses()) {
933           if (Use.isReg() && TRI->regsOverlap(Def, Use.getReg()))
934             return true;
935         }
936       }
937 
938       return false;
939     };
940 
941     int WaitStatesNeededForDef =
942         Shift16DefWaitstates -
943         getWaitStatesSince(IsShift16BitDefFn, Shift16DefWaitstates);
944     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
945   }
946 
947   if (ST.hasVDecCoExecHazard()) {
948     const int VALUWriteSGPRVALUReadWaitstates = 2;
949     const int VALUWriteEXECRWLane = 4;
950     const int VALUWriteVGPRReadlaneRead = 1;
951 
952     const SIRegisterInfo *TRI = ST.getRegisterInfo();
953     const MachineRegisterInfo &MRI = MF.getRegInfo();
954     Register UseReg;
955     auto IsVALUDefSGPRFn = [&UseReg, TRI](const MachineInstr &MI) {
956       if (!SIInstrInfo::isVALU(MI))
957         return false;
958       return MI.modifiesRegister(UseReg, TRI);
959     };
960 
961     for (const MachineOperand &Use : VALU->explicit_uses()) {
962       if (!Use.isReg())
963         continue;
964 
965       UseReg = Use.getReg();
966       if (TRI->isSGPRReg(MRI, UseReg)) {
967         int WaitStatesNeededForDef =
968             VALUWriteSGPRVALUReadWaitstates -
969             getWaitStatesSince(IsVALUDefSGPRFn,
970                                VALUWriteSGPRVALUReadWaitstates);
971         WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
972       }
973     }
974 
975     if (VALU->readsRegister(AMDGPU::VCC, TRI)) {
976       UseReg = AMDGPU::VCC;
977       int WaitStatesNeededForDef =
978           VALUWriteSGPRVALUReadWaitstates -
979           getWaitStatesSince(IsVALUDefSGPRFn, VALUWriteSGPRVALUReadWaitstates);
980       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
981     }
982 
983     switch (VALU->getOpcode()) {
984     case AMDGPU::V_READLANE_B32:
985     case AMDGPU::V_READFIRSTLANE_B32: {
986       MachineOperand *Src = TII.getNamedOperand(*VALU, AMDGPU::OpName::src0);
987       UseReg = Src->getReg();
988       int WaitStatesNeededForDef =
989           VALUWriteVGPRReadlaneRead -
990           getWaitStatesSince(IsVALUDefSGPRFn, VALUWriteVGPRReadlaneRead);
991       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
992     }
993       [[fallthrough]];
994     case AMDGPU::V_WRITELANE_B32: {
995       UseReg = AMDGPU::EXEC;
996       int WaitStatesNeededForDef =
997           VALUWriteEXECRWLane -
998           getWaitStatesSince(IsVALUDefSGPRFn, VALUWriteEXECRWLane);
999       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
1000       break;
1001     }
1002     default:
1003       break;
1004     }
1005   }
1006 
1007   // This checks for the hazard where VMEM instructions that store more than
1008   // 8 bytes can have there store data over written by the next instruction.
1009   if (!ST.has12DWordStoreHazard())
1010     return WaitStatesNeeded;
1011 
1012   const MachineRegisterInfo &MRI = MF.getRegInfo();
1013 
1014   for (const MachineOperand &Def : VALU->defs()) {
1015     WaitStatesNeeded = std::max(WaitStatesNeeded, checkVALUHazardsHelper(Def, MRI));
1016   }
1017 
1018   return WaitStatesNeeded;
1019 }
1020 
1021 int GCNHazardRecognizer::checkInlineAsmHazards(MachineInstr *IA) {
1022   // This checks for hazards associated with inline asm statements.
1023   // Since inline asms can contain just about anything, we use this
1024   // to call/leverage other check*Hazard routines. Note that
1025   // this function doesn't attempt to address all possible inline asm
1026   // hazards (good luck), but is a collection of what has been
1027   // problematic thus far.
1028 
1029   // see checkVALUHazards()
1030   if (!ST.has12DWordStoreHazard())
1031     return 0;
1032 
1033   const MachineRegisterInfo &MRI = MF.getRegInfo();
1034   int WaitStatesNeeded = 0;
1035 
1036   for (const MachineOperand &Op :
1037        llvm::drop_begin(IA->operands(), InlineAsm::MIOp_FirstOperand)) {
1038     if (Op.isReg() && Op.isDef()) {
1039       WaitStatesNeeded =
1040           std::max(WaitStatesNeeded, checkVALUHazardsHelper(Op, MRI));
1041     }
1042   }
1043 
1044   return WaitStatesNeeded;
1045 }
1046 
1047 int GCNHazardRecognizer::checkRWLaneHazards(MachineInstr *RWLane) {
1048   const SIInstrInfo *TII = ST.getInstrInfo();
1049   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1050   const MachineRegisterInfo &MRI = MF.getRegInfo();
1051 
1052   const MachineOperand *LaneSelectOp =
1053       TII->getNamedOperand(*RWLane, AMDGPU::OpName::src1);
1054 
1055   if (!LaneSelectOp->isReg() || !TRI->isSGPRReg(MRI, LaneSelectOp->getReg()))
1056     return 0;
1057 
1058   Register LaneSelectReg = LaneSelectOp->getReg();
1059   auto IsHazardFn = [TII](const MachineInstr &MI) { return TII->isVALU(MI); };
1060 
1061   const int RWLaneWaitStates = 4;
1062   int WaitStatesSince = getWaitStatesSinceDef(LaneSelectReg, IsHazardFn,
1063                                               RWLaneWaitStates);
1064   return RWLaneWaitStates - WaitStatesSince;
1065 }
1066 
1067 int GCNHazardRecognizer::checkRFEHazards(MachineInstr *RFE) {
1068   if (!ST.hasRFEHazards())
1069     return 0;
1070 
1071   const SIInstrInfo *TII = ST.getInstrInfo();
1072 
1073   const int RFEWaitStates = 1;
1074 
1075   auto IsHazardFn = [TII](const MachineInstr &MI) {
1076     return getHWReg(TII, MI) == AMDGPU::Hwreg::ID_TRAPSTS;
1077   };
1078   int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, RFEWaitStates);
1079   return RFEWaitStates - WaitStatesNeeded;
1080 }
1081 
1082 int GCNHazardRecognizer::checkReadM0Hazards(MachineInstr *MI) {
1083   const SIInstrInfo *TII = ST.getInstrInfo();
1084   const int ReadM0WaitStates = 1;
1085   auto IsHazardFn = [TII](const MachineInstr &MI) { return TII->isSALU(MI); };
1086   return ReadM0WaitStates -
1087          getWaitStatesSinceDef(AMDGPU::M0, IsHazardFn, ReadM0WaitStates);
1088 }
1089 
1090 void GCNHazardRecognizer::fixHazards(MachineInstr *MI) {
1091   fixVMEMtoScalarWriteHazards(MI);
1092   fixVcmpxPermlaneHazards(MI);
1093   fixSMEMtoVectorWriteHazards(MI);
1094   fixVcmpxExecWARHazard(MI);
1095   fixLdsBranchVmemWARHazard(MI);
1096   if (ST.hasLdsDirect()) {
1097     fixLdsDirectVALUHazard(MI);
1098     fixLdsDirectVMEMHazard(MI);
1099   }
1100   fixVALUPartialForwardingHazard(MI);
1101   fixVALUTransUseHazard(MI);
1102   fixWMMAHazards(MI);
1103   fixShift64HighRegBug(MI);
1104   fixVALUMaskWriteHazard(MI);
1105 }
1106 
1107 bool GCNHazardRecognizer::fixVcmpxPermlaneHazards(MachineInstr *MI) {
1108   if (!ST.hasVcmpxPermlaneHazard() || !isPermlane(*MI))
1109     return false;
1110 
1111   const SIInstrInfo *TII = ST.getInstrInfo();
1112   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1113   auto IsHazardFn = [TII, TRI](const MachineInstr &MI) {
1114     return (TII->isVOPC(MI) ||
1115             ((TII->isVOP3(MI) || TII->isSDWA(MI)) && MI.isCompare())) &&
1116            MI.modifiesRegister(AMDGPU::EXEC, TRI);
1117   };
1118 
1119   auto IsExpiredFn = [](const MachineInstr &MI, int) {
1120     unsigned Opc = MI.getOpcode();
1121     return SIInstrInfo::isVALU(MI) && Opc != AMDGPU::V_NOP_e32 &&
1122            Opc != AMDGPU::V_NOP_e64 && Opc != AMDGPU::V_NOP_sdwa;
1123   };
1124 
1125   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1126       std::numeric_limits<int>::max())
1127     return false;
1128 
1129   // V_NOP will be discarded by SQ.
1130   // Use V_MOV_B32 v?, v?. Register must be alive so use src0 of V_PERMLANE*
1131   // which is always a VGPR and available.
1132   auto *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
1133   Register Reg = Src0->getReg();
1134   bool IsUndef = Src0->isUndef();
1135   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1136           TII->get(AMDGPU::V_MOV_B32_e32))
1137     .addReg(Reg, RegState::Define | (IsUndef ? RegState::Dead : 0))
1138     .addReg(Reg, IsUndef ? RegState::Undef : RegState::Kill);
1139 
1140   return true;
1141 }
1142 
1143 bool GCNHazardRecognizer::fixVMEMtoScalarWriteHazards(MachineInstr *MI) {
1144   if (!ST.hasVMEMtoScalarWriteHazard())
1145     return false;
1146   assert(!ST.hasExtendedWaitCounts());
1147 
1148   if (!SIInstrInfo::isSALU(*MI) && !SIInstrInfo::isSMRD(*MI))
1149     return false;
1150 
1151   if (MI->getNumDefs() == 0)
1152     return false;
1153 
1154   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1155 
1156   auto IsHazardFn = [TRI, MI](const MachineInstr &I) {
1157     if (!SIInstrInfo::isVMEM(I) && !SIInstrInfo::isDS(I) &&
1158         !SIInstrInfo::isFLAT(I))
1159       return false;
1160 
1161     for (const MachineOperand &Def : MI->defs()) {
1162       const MachineOperand *Op =
1163           I.findRegisterUseOperand(Def.getReg(), false, TRI);
1164       if (!Op)
1165         continue;
1166       return true;
1167     }
1168     return false;
1169   };
1170 
1171   auto IsExpiredFn = [](const MachineInstr &MI, int) {
1172     return SIInstrInfo::isVALU(MI) ||
1173            (MI.getOpcode() == AMDGPU::S_WAITCNT &&
1174             !MI.getOperand(0).getImm()) ||
1175            (MI.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1176             AMDGPU::DepCtr::decodeFieldVmVsrc(MI.getOperand(0).getImm()) == 0);
1177   };
1178 
1179   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1180       std::numeric_limits<int>::max())
1181     return false;
1182 
1183   const SIInstrInfo *TII = ST.getInstrInfo();
1184   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1185           TII->get(AMDGPU::S_WAITCNT_DEPCTR))
1186       .addImm(AMDGPU::DepCtr::encodeFieldVmVsrc(0));
1187   return true;
1188 }
1189 
1190 bool GCNHazardRecognizer::fixSMEMtoVectorWriteHazards(MachineInstr *MI) {
1191   if (!ST.hasSMEMtoVectorWriteHazard())
1192     return false;
1193   assert(!ST.hasExtendedWaitCounts());
1194 
1195   if (!SIInstrInfo::isVALU(*MI))
1196     return false;
1197 
1198   unsigned SDSTName;
1199   switch (MI->getOpcode()) {
1200   case AMDGPU::V_READLANE_B32:
1201   case AMDGPU::V_READFIRSTLANE_B32:
1202     SDSTName = AMDGPU::OpName::vdst;
1203     break;
1204   default:
1205     SDSTName = AMDGPU::OpName::sdst;
1206     break;
1207   }
1208 
1209   const SIInstrInfo *TII = ST.getInstrInfo();
1210   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1211   const AMDGPU::IsaVersion IV = AMDGPU::getIsaVersion(ST.getCPU());
1212   const MachineOperand *SDST = TII->getNamedOperand(*MI, SDSTName);
1213   if (!SDST) {
1214     for (const auto &MO : MI->implicit_operands()) {
1215       if (MO.isDef() && TRI->isSGPRClass(TRI->getPhysRegBaseClass(MO.getReg()))) {
1216         SDST = &MO;
1217         break;
1218       }
1219     }
1220   }
1221 
1222   if (!SDST)
1223     return false;
1224 
1225   const Register SDSTReg = SDST->getReg();
1226   auto IsHazardFn = [SDSTReg, TRI](const MachineInstr &I) {
1227     return SIInstrInfo::isSMRD(I) && I.readsRegister(SDSTReg, TRI);
1228   };
1229 
1230   auto IsExpiredFn = [TII, IV](const MachineInstr &MI, int) {
1231     if (TII->isSALU(MI)) {
1232       switch (MI.getOpcode()) {
1233       case AMDGPU::S_SETVSKIP:
1234       case AMDGPU::S_VERSION:
1235       case AMDGPU::S_WAITCNT_VSCNT:
1236       case AMDGPU::S_WAITCNT_VMCNT:
1237       case AMDGPU::S_WAITCNT_EXPCNT:
1238         // These instructions cannot not mitigate the hazard.
1239         return false;
1240       case AMDGPU::S_WAITCNT_LGKMCNT:
1241         // Reducing lgkmcnt count to 0 always mitigates the hazard.
1242         return (MI.getOperand(1).getImm() == 0) &&
1243                (MI.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1244       case AMDGPU::S_WAITCNT: {
1245         const int64_t Imm = MI.getOperand(0).getImm();
1246         AMDGPU::Waitcnt Decoded = AMDGPU::decodeWaitcnt(IV, Imm);
1247         // DsCnt corresponds to LGKMCnt here.
1248         return (Decoded.DsCnt == 0);
1249       }
1250       default:
1251         // SOPP instructions cannot mitigate the hazard.
1252         if (TII->isSOPP(MI))
1253           return false;
1254         // At this point the SALU can be assumed to mitigate the hazard
1255         // because either:
1256         // (a) it is independent of the at risk SMEM (breaking chain),
1257         // or
1258         // (b) it is dependent on the SMEM, in which case an appropriate
1259         //     s_waitcnt lgkmcnt _must_ exist between it and the at risk
1260         //     SMEM instruction.
1261         return true;
1262       }
1263     }
1264     return false;
1265   };
1266 
1267   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1268       std::numeric_limits<int>::max())
1269     return false;
1270 
1271   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1272           TII->get(AMDGPU::S_MOV_B32), AMDGPU::SGPR_NULL)
1273       .addImm(0);
1274   return true;
1275 }
1276 
1277 bool GCNHazardRecognizer::fixVcmpxExecWARHazard(MachineInstr *MI) {
1278   if (!ST.hasVcmpxExecWARHazard())
1279     return false;
1280   assert(!ST.hasExtendedWaitCounts());
1281 
1282   if (!SIInstrInfo::isVALU(*MI))
1283     return false;
1284 
1285   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1286   if (!MI->modifiesRegister(AMDGPU::EXEC, TRI))
1287     return false;
1288 
1289   auto IsHazardFn = [TRI](const MachineInstr &I) {
1290     if (SIInstrInfo::isVALU(I))
1291       return false;
1292     return I.readsRegister(AMDGPU::EXEC, TRI);
1293   };
1294 
1295   const SIInstrInfo *TII = ST.getInstrInfo();
1296   auto IsExpiredFn = [TII, TRI](const MachineInstr &MI, int) {
1297     if (SIInstrInfo::isVALU(MI)) {
1298       if (TII->getNamedOperand(MI, AMDGPU::OpName::sdst))
1299         return true;
1300       for (auto MO : MI.implicit_operands())
1301         if (MO.isDef() && TRI->isSGPRClass(TRI->getPhysRegBaseClass(MO.getReg())))
1302           return true;
1303     }
1304     if (MI.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1305         AMDGPU::DepCtr::decodeFieldSaSdst(MI.getOperand(0).getImm()) == 0)
1306       return true;
1307     return false;
1308   };
1309 
1310   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1311       std::numeric_limits<int>::max())
1312     return false;
1313 
1314   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1315           TII->get(AMDGPU::S_WAITCNT_DEPCTR))
1316       .addImm(AMDGPU::DepCtr::encodeFieldSaSdst(0));
1317   return true;
1318 }
1319 
1320 static bool shouldRunLdsBranchVmemWARHazardFixup(const MachineFunction &MF,
1321                                                  const GCNSubtarget &ST) {
1322   if (!ST.hasLdsBranchVmemWARHazard())
1323     return false;
1324 
1325   // Check if the necessary condition for the hazard is met: both LDS and VMEM
1326   // instructions need to appear in the same function.
1327   bool HasLds = false;
1328   bool HasVmem = false;
1329   for (auto &MBB : MF) {
1330     for (auto &MI : MBB) {
1331       HasLds |= SIInstrInfo::isDS(MI);
1332       HasVmem |=
1333           SIInstrInfo::isVMEM(MI) || SIInstrInfo::isSegmentSpecificFLAT(MI);
1334       if (HasLds && HasVmem)
1335         return true;
1336     }
1337   }
1338   return false;
1339 }
1340 
1341 static bool isStoreCountWaitZero(const MachineInstr &I) {
1342   return I.getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1343          I.getOperand(0).getReg() == AMDGPU::SGPR_NULL &&
1344          !I.getOperand(1).getImm();
1345 }
1346 
1347 bool GCNHazardRecognizer::fixLdsBranchVmemWARHazard(MachineInstr *MI) {
1348   if (!RunLdsBranchVmemWARHazardFixup)
1349     return false;
1350 
1351   assert(ST.hasLdsBranchVmemWARHazard());
1352   assert(!ST.hasExtendedWaitCounts());
1353 
1354   auto IsHazardInst = [](const MachineInstr &MI) {
1355     if (SIInstrInfo::isDS(MI))
1356       return 1;
1357     if (SIInstrInfo::isVMEM(MI) || SIInstrInfo::isSegmentSpecificFLAT(MI))
1358       return 2;
1359     return 0;
1360   };
1361 
1362   auto InstType = IsHazardInst(*MI);
1363   if (!InstType)
1364     return false;
1365 
1366   auto IsExpiredFn = [&IsHazardInst](const MachineInstr &I, int) {
1367     return IsHazardInst(I) || isStoreCountWaitZero(I);
1368   };
1369 
1370   auto IsHazardFn = [InstType, &IsHazardInst](const MachineInstr &I) {
1371     if (!I.isBranch())
1372       return false;
1373 
1374     auto IsHazardFn = [InstType, IsHazardInst](const MachineInstr &I) {
1375       auto InstType2 = IsHazardInst(I);
1376       return InstType2 && InstType != InstType2;
1377     };
1378 
1379     auto IsExpiredFn = [InstType, &IsHazardInst](const MachineInstr &I, int) {
1380       auto InstType2 = IsHazardInst(I);
1381       if (InstType == InstType2)
1382         return true;
1383 
1384       return isStoreCountWaitZero(I);
1385     };
1386 
1387     return ::getWaitStatesSince(IsHazardFn, &I, IsExpiredFn) !=
1388            std::numeric_limits<int>::max();
1389   };
1390 
1391   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1392       std::numeric_limits<int>::max())
1393     return false;
1394 
1395   const SIInstrInfo *TII = ST.getInstrInfo();
1396   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1397           TII->get(AMDGPU::S_WAITCNT_VSCNT))
1398     .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1399     .addImm(0);
1400 
1401   return true;
1402 }
1403 
1404 bool GCNHazardRecognizer::fixLdsDirectVALUHazard(MachineInstr *MI) {
1405   if (!SIInstrInfo::isLDSDIR(*MI))
1406     return false;
1407 
1408   const int NoHazardWaitStates = 15;
1409   const MachineOperand *VDST = TII.getNamedOperand(*MI, AMDGPU::OpName::vdst);
1410   const Register VDSTReg = VDST->getReg();
1411 
1412   bool VisitedTrans = false;
1413   auto IsHazardFn = [this, VDSTReg, &VisitedTrans](const MachineInstr &I) {
1414     if (!SIInstrInfo::isVALU(I))
1415       return false;
1416     VisitedTrans = VisitedTrans || SIInstrInfo::isTRANS(I);
1417     // Cover both WAR and WAW
1418     return I.readsRegister(VDSTReg, &TRI) || I.modifiesRegister(VDSTReg, &TRI);
1419   };
1420   auto IsExpiredFn = [&](const MachineInstr &I, int WaitStates) {
1421     if (WaitStates >= NoHazardWaitStates)
1422       return true;
1423     // Instructions which cause va_vdst==0 expire hazard
1424     return SIInstrInfo::isVMEM(I) || SIInstrInfo::isFLAT(I) ||
1425            SIInstrInfo::isDS(I) || SIInstrInfo::isEXP(I);
1426   };
1427   auto GetWaitStatesFn = [](const MachineInstr &MI) {
1428     return SIInstrInfo::isVALU(MI) ? 1 : 0;
1429   };
1430 
1431   DenseSet<const MachineBasicBlock *> Visited;
1432   auto Count = ::getWaitStatesSince(IsHazardFn, MI->getParent(),
1433                                     std::next(MI->getReverseIterator()), 0,
1434                                     IsExpiredFn, Visited, GetWaitStatesFn);
1435 
1436   // Transcendentals can execute in parallel to other VALUs.
1437   // This makes va_vdst count unusable with a mixture of VALU and TRANS.
1438   if (VisitedTrans)
1439     Count = 0;
1440 
1441   MachineOperand *WaitVdstOp =
1442       TII.getNamedOperand(*MI, AMDGPU::OpName::waitvdst);
1443   WaitVdstOp->setImm(std::min(Count, NoHazardWaitStates));
1444 
1445   return true;
1446 }
1447 
1448 bool GCNHazardRecognizer::fixLdsDirectVMEMHazard(MachineInstr *MI) {
1449   if (!SIInstrInfo::isLDSDIR(*MI))
1450     return false;
1451 
1452   const MachineOperand *VDST = TII.getNamedOperand(*MI, AMDGPU::OpName::vdst);
1453   const Register VDSTReg = VDST->getReg();
1454 
1455   auto IsHazardFn = [this, VDSTReg](const MachineInstr &I) {
1456     if (!SIInstrInfo::isVMEM(I) && !SIInstrInfo::isFLAT(I) &&
1457         !SIInstrInfo::isDS(I))
1458       return false;
1459     return I.readsRegister(VDSTReg, &TRI) || I.modifiesRegister(VDSTReg, &TRI);
1460   };
1461   bool LdsdirCanWait = ST.hasLdsWaitVMSRC();
1462   // TODO: On GFX12 the hazard should expire on S_WAIT_LOADCNT/SAMPLECNT/BVHCNT
1463   // according to the type of VMEM instruction.
1464   auto IsExpiredFn = [this, LdsdirCanWait](const MachineInstr &I, int) {
1465     return SIInstrInfo::isVALU(I) || SIInstrInfo::isEXP(I) ||
1466            (I.getOpcode() == AMDGPU::S_WAITCNT && !I.getOperand(0).getImm()) ||
1467            (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1468             AMDGPU::DepCtr::decodeFieldVmVsrc(I.getOperand(0).getImm()) == 0) ||
1469            (LdsdirCanWait && SIInstrInfo::isLDSDIR(I) &&
1470             !TII.getNamedOperand(I, AMDGPU::OpName::waitvsrc)->getImm());
1471   };
1472 
1473   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1474       std::numeric_limits<int>::max())
1475     return false;
1476 
1477   if (LdsdirCanWait) {
1478     TII.getNamedOperand(*MI, AMDGPU::OpName::waitvsrc)->setImm(0);
1479   } else {
1480     BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1481             TII.get(AMDGPU::S_WAITCNT_DEPCTR))
1482         .addImm(AMDGPU::DepCtr::encodeFieldVmVsrc(0));
1483   }
1484 
1485   return true;
1486 }
1487 
1488 bool GCNHazardRecognizer::fixVALUPartialForwardingHazard(MachineInstr *MI) {
1489   if (!ST.hasVALUPartialForwardingHazard())
1490     return false;
1491   assert(!ST.hasExtendedWaitCounts());
1492 
1493   if (!ST.isWave64() || !SIInstrInfo::isVALU(*MI))
1494     return false;
1495 
1496   SmallSetVector<Register, 4> SrcVGPRs;
1497 
1498   for (const MachineOperand &Use : MI->explicit_uses()) {
1499     if (Use.isReg() && TRI.isVGPR(MF.getRegInfo(), Use.getReg()))
1500       SrcVGPRs.insert(Use.getReg());
1501   }
1502 
1503   // Only applies with >= 2 unique VGPR sources
1504   if (SrcVGPRs.size() <= 1)
1505     return false;
1506 
1507   // Look for the following pattern:
1508   //   Va <- VALU [PreExecPos]
1509   //   intv1
1510   //   Exec <- SALU [ExecPos]
1511   //   intv2
1512   //   Vb <- VALU [PostExecPos]
1513   //   intv3
1514   //   MI Va, Vb (WaitState = 0)
1515   //
1516   // Where:
1517   // intv1 + intv2 <= 2 VALUs
1518   // intv3 <= 4 VALUs
1519   //
1520   // If found, insert an appropriate S_WAITCNT_DEPCTR before MI.
1521 
1522   const int Intv1plus2MaxVALUs = 2;
1523   const int Intv3MaxVALUs = 4;
1524   const int IntvMaxVALUs = 6;
1525   const int NoHazardVALUWaitStates = IntvMaxVALUs + 2;
1526 
1527   struct StateType {
1528     SmallDenseMap<Register, int, 4> DefPos;
1529     int ExecPos = std::numeric_limits<int>::max();
1530     int VALUs = 0;
1531   };
1532 
1533   StateType State;
1534 
1535   // This overloads expiry testing with all the hazard detection
1536   auto IsHazardFn = [&, this](StateType &State, const MachineInstr &I) {
1537     // Too many VALU states have passed
1538     if (State.VALUs > NoHazardVALUWaitStates)
1539       return HazardExpired;
1540 
1541     // Instructions which cause va_vdst==0 expire hazard
1542     if (SIInstrInfo::isVMEM(I) || SIInstrInfo::isFLAT(I) ||
1543         SIInstrInfo::isDS(I) || SIInstrInfo::isEXP(I) ||
1544         (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1545          AMDGPU::DepCtr::decodeFieldVaVdst(I.getOperand(0).getImm()) == 0))
1546       return HazardExpired;
1547 
1548     // Track registers writes
1549     bool Changed = false;
1550     if (SIInstrInfo::isVALU(I)) {
1551       for (Register Src : SrcVGPRs) {
1552         if (!State.DefPos.count(Src) && I.modifiesRegister(Src, &TRI)) {
1553           State.DefPos[Src] = State.VALUs;
1554           Changed = true;
1555         }
1556       }
1557     } else if (SIInstrInfo::isSALU(I)) {
1558       if (State.ExecPos == std::numeric_limits<int>::max()) {
1559         if (!State.DefPos.empty() && I.modifiesRegister(AMDGPU::EXEC, &TRI)) {
1560           State.ExecPos = State.VALUs;
1561           Changed = true;
1562         }
1563       }
1564     }
1565 
1566     // Early expiration: too many VALUs in intv3
1567     if (State.VALUs > Intv3MaxVALUs && State.DefPos.empty())
1568       return HazardExpired;
1569 
1570     // Only evaluate state if something changed
1571     if (!Changed)
1572       return NoHazardFound;
1573 
1574     // Determine positions of VALUs pre/post exec change
1575     if (State.ExecPos == std::numeric_limits<int>::max())
1576       return NoHazardFound;
1577 
1578     int PreExecPos = std::numeric_limits<int>::max();
1579     int PostExecPos = std::numeric_limits<int>::max();
1580 
1581     for (auto Entry : State.DefPos) {
1582       int DefVALUs = Entry.second;
1583       if (DefVALUs != std::numeric_limits<int>::max()) {
1584         if (DefVALUs >= State.ExecPos)
1585           PreExecPos = std::min(PreExecPos, DefVALUs);
1586         else if (DefVALUs < State.ExecPos)
1587           PostExecPos = std::min(PostExecPos, DefVALUs);
1588       }
1589     }
1590 
1591     // Need a VALUs post exec change
1592     if (PostExecPos == std::numeric_limits<int>::max())
1593       return NoHazardFound;
1594 
1595     // Too many VALUs in intv3?
1596     int Intv3VALUs = PostExecPos;
1597     if (Intv3VALUs > Intv3MaxVALUs)
1598       return HazardExpired;
1599 
1600     // Too many VALUs in intv2?
1601     int Intv2VALUs = (State.ExecPos - PostExecPos) - 1;
1602     if (Intv2VALUs > Intv1plus2MaxVALUs)
1603       return HazardExpired;
1604 
1605     // Need a VALUs pre exec change
1606     if (PreExecPos == std::numeric_limits<int>::max())
1607       return NoHazardFound;
1608 
1609     // Too many VALUs in intv1?
1610     int Intv1VALUs = PreExecPos - State.ExecPos;
1611     if (Intv1VALUs > Intv1plus2MaxVALUs)
1612       return HazardExpired;
1613 
1614     // Too many VALUs in intv1 + intv2
1615     if (Intv1VALUs + Intv2VALUs > Intv1plus2MaxVALUs)
1616       return HazardExpired;
1617 
1618     return HazardFound;
1619   };
1620   auto UpdateStateFn = [](StateType &State, const MachineInstr &MI) {
1621     if (SIInstrInfo::isVALU(MI))
1622       State.VALUs += 1;
1623   };
1624 
1625   DenseSet<const MachineBasicBlock *> Visited;
1626   if (!hasHazard<StateType>(State, IsHazardFn, UpdateStateFn, MI->getParent(),
1627                             std::next(MI->getReverseIterator()), Visited))
1628     return false;
1629 
1630   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1631           TII.get(AMDGPU::S_WAITCNT_DEPCTR))
1632       .addImm(0x0fff);
1633 
1634   return true;
1635 }
1636 
1637 bool GCNHazardRecognizer::fixVALUTransUseHazard(MachineInstr *MI) {
1638   if (!ST.hasVALUTransUseHazard())
1639     return false;
1640   assert(!ST.hasExtendedWaitCounts());
1641 
1642   if (!SIInstrInfo::isVALU(*MI))
1643     return false;
1644 
1645   SmallSet<Register, 4> SrcVGPRs;
1646 
1647   for (const MachineOperand &Use : MI->explicit_uses()) {
1648     if (Use.isReg() && TRI.isVGPR(MF.getRegInfo(), Use.getReg()))
1649       SrcVGPRs.insert(Use.getReg());
1650   }
1651 
1652   // Look for the following pattern:
1653   //   Va <- TRANS VALU
1654   //   intv
1655   //   MI Va (WaitState = 0)
1656   //
1657   // Where:
1658   // intv <= 5 VALUs / 1 TRANS
1659   //
1660   // If found, insert an appropriate S_WAITCNT_DEPCTR before MI.
1661 
1662   const int IntvMaxVALUs = 5;
1663   const int IntvMaxTRANS = 1;
1664 
1665   struct StateType {
1666     int VALUs = 0;
1667     int TRANS = 0;
1668   };
1669 
1670   StateType State;
1671 
1672   // This overloads expiry testing with all the hazard detection
1673   auto IsHazardFn = [&, this](StateType &State, const MachineInstr &I) {
1674     // Too many VALU states have passed
1675     if (State.VALUs > IntvMaxVALUs || State.TRANS > IntvMaxTRANS)
1676       return HazardExpired;
1677 
1678     // Instructions which cause va_vdst==0 expire hazard
1679     if (SIInstrInfo::isVMEM(I) || SIInstrInfo::isFLAT(I) ||
1680         SIInstrInfo::isDS(I) || SIInstrInfo::isEXP(I) ||
1681         (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1682          I.getOperand(0).getImm() == 0x0fff))
1683       return HazardExpired;
1684 
1685     // Track registers writes
1686     if (SIInstrInfo::isTRANS(I)) {
1687       for (Register Src : SrcVGPRs) {
1688         if (I.modifiesRegister(Src, &TRI)) {
1689           return HazardFound;
1690         }
1691       }
1692     }
1693 
1694     return NoHazardFound;
1695   };
1696   auto UpdateStateFn = [](StateType &State, const MachineInstr &MI) {
1697     if (SIInstrInfo::isVALU(MI))
1698       State.VALUs += 1;
1699     if (SIInstrInfo::isTRANS(MI))
1700       State.TRANS += 1;
1701   };
1702 
1703   DenseSet<const MachineBasicBlock *> Visited;
1704   if (!hasHazard<StateType>(State, IsHazardFn, UpdateStateFn, MI->getParent(),
1705                             std::next(MI->getReverseIterator()), Visited))
1706     return false;
1707 
1708   // Hazard is observed - insert a wait on va_dst counter to ensure hazard is
1709   // avoided.
1710   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1711           TII.get(AMDGPU::S_WAITCNT_DEPCTR))
1712       .addImm(AMDGPU::DepCtr::encodeFieldVaVdst(0));
1713 
1714   return true;
1715 }
1716 
1717 bool GCNHazardRecognizer::fixWMMAHazards(MachineInstr *MI) {
1718   if (!SIInstrInfo::isWMMA(*MI))
1719     return false;
1720 
1721   const SIInstrInfo *TII = ST.getInstrInfo();
1722   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1723 
1724   auto IsHazardFn = [MI, TII, TRI](const MachineInstr &I) {
1725     if (!SIInstrInfo::isWMMA(I))
1726       return false;
1727 
1728     // Src0 or Src1 of the current wmma instruction overlaps with the dest of
1729     // the previous wmma.
1730     const Register CurSrc0Reg =
1731         TII->getNamedOperand(*MI, AMDGPU::OpName::src0)->getReg();
1732     const Register CurSrc1Reg =
1733         TII->getNamedOperand(*MI, AMDGPU::OpName::src1)->getReg();
1734 
1735     const Register PrevDstReg =
1736         TII->getNamedOperand(I, AMDGPU::OpName::vdst)->getReg();
1737 
1738     if (TRI->regsOverlap(PrevDstReg, CurSrc0Reg) ||
1739         TRI->regsOverlap(PrevDstReg, CurSrc1Reg)) {
1740       return true;
1741     }
1742 
1743     // Src2 of the current wmma instruction overlaps with the dest of the
1744     // previous wmma.
1745     const MachineOperand *Src2 =
1746         TII->getNamedOperand(*MI, AMDGPU::OpName::src2);
1747     const Register CurSrc2Reg = Src2->isReg() ? Src2->getReg() : Register();
1748 
1749     if (CurSrc2Reg != AMDGPU::NoRegister &&
1750         TRI->regsOverlap(PrevDstReg, CurSrc2Reg)) {
1751 
1752       const MachineOperand *Src2Mods =
1753           TII->getNamedOperand(*MI, AMDGPU::OpName::src2_modifiers);
1754       const bool NoSrc2Mods =
1755           (Src2Mods->getImm() & (SISrcMods::NEG | SISrcMods::NEG_HI)) == 0;
1756       // Exception: there is no hazard if the wmma instructions are of the same
1757       // type and there is no input modifier on src2 of the current instruction.
1758       return !(NoSrc2Mods && (TII->pseudoToMCOpcode(I.getOpcode()) ==
1759                               TII->pseudoToMCOpcode(MI->getOpcode())));
1760     }
1761 
1762     return false;
1763   };
1764 
1765   auto IsExpiredFn = [](const MachineInstr &I, int) {
1766     return SIInstrInfo::isVALU(I);
1767   };
1768 
1769   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1770       std::numeric_limits<int>::max())
1771     return false;
1772 
1773   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(AMDGPU::V_NOP_e32));
1774 
1775   return true;
1776 }
1777 
1778 bool GCNHazardRecognizer::fixShift64HighRegBug(MachineInstr *MI) {
1779   if (!ST.hasShift64HighRegBug())
1780     return false;
1781   assert(!ST.hasExtendedWaitCounts());
1782 
1783   switch (MI->getOpcode()) {
1784   default:
1785     return false;
1786   case AMDGPU::V_LSHLREV_B64_e64:
1787   case AMDGPU::V_LSHRREV_B64_e64:
1788   case AMDGPU::V_ASHRREV_I64_e64:
1789     break;
1790   }
1791 
1792   MachineOperand *Amt = TII.getNamedOperand(*MI, AMDGPU::OpName::src0);
1793   if (!Amt->isReg())
1794     return false;
1795 
1796   Register AmtReg = Amt->getReg();
1797   const MachineRegisterInfo &MRI = MF.getRegInfo();
1798   // Check if this is a last VGPR in the allocation block.
1799   if (!TRI.isVGPR(MRI, AmtReg) || ((AmtReg - AMDGPU::VGPR0) & 7) != 7)
1800     return false;
1801 
1802   if (AmtReg != AMDGPU::VGPR255 && MRI.isPhysRegUsed(AmtReg + 1))
1803     return false;
1804 
1805   MachineOperand *Src1 = TII.getNamedOperand(*MI, AMDGPU::OpName::src1);
1806   bool OverlappedSrc = Src1->isReg() && TRI.regsOverlap(Src1->getReg(), AmtReg);
1807   bool OverlappedDst = MI->modifiesRegister(AmtReg, &TRI);
1808   bool Overlapped = OverlappedSrc || OverlappedDst;
1809 
1810   assert(!OverlappedDst || !OverlappedSrc ||
1811          Src1->getReg() == MI->getOperand(0).getReg());
1812   assert(ST.needsAlignedVGPRs());
1813   static_assert(AMDGPU::VGPR0 + 1 == AMDGPU::VGPR1);
1814 
1815   Register NewReg;
1816   for (MCRegister Reg : Overlapped ? AMDGPU::VReg_64_Align2RegClass
1817                                    : AMDGPU::VGPR_32RegClass) {
1818     if (!MI->modifiesRegister(Reg, &TRI) && !MI->readsRegister(Reg, &TRI)) {
1819       NewReg = Reg;
1820       break;
1821     }
1822   }
1823 
1824   Register NewAmt = Overlapped ? (Register)TRI.getSubReg(NewReg, AMDGPU::sub1)
1825                                : NewReg;
1826   Register NewAmtLo;
1827 
1828   if (Overlapped)
1829     NewAmtLo = TRI.getSubReg(NewReg, AMDGPU::sub0);
1830 
1831   DebugLoc DL = MI->getDebugLoc();
1832   MachineBasicBlock *MBB = MI->getParent();
1833   // Insert a full wait count because found register might be pending a wait.
1834   BuildMI(*MBB, MI, DL, TII.get(AMDGPU::S_WAITCNT))
1835       .addImm(0);
1836 
1837   // Insert V_SWAP_B32 instruction(s) and run hazard recognizer on them.
1838   if (Overlapped)
1839     runOnInstruction(
1840         BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_SWAP_B32), NewAmtLo)
1841             .addDef(AmtReg - 1)
1842             .addReg(AmtReg - 1, RegState::Undef)
1843             .addReg(NewAmtLo, RegState::Undef));
1844   runOnInstruction(BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_SWAP_B32), NewAmt)
1845                        .addDef(AmtReg)
1846                        .addReg(AmtReg, RegState::Undef)
1847                        .addReg(NewAmt, RegState::Undef));
1848 
1849   // Instructions emitted after the current instruction will be processed by the
1850   // parent loop of the hazard recognizer in a natural way.
1851   BuildMI(*MBB, std::next(MI->getIterator()), DL, TII.get(AMDGPU::V_SWAP_B32),
1852           AmtReg)
1853       .addDef(NewAmt)
1854       .addReg(NewAmt)
1855       .addReg(AmtReg);
1856   if (Overlapped)
1857     BuildMI(*MBB, std::next(MI->getIterator()), DL, TII.get(AMDGPU::V_SWAP_B32),
1858             AmtReg - 1)
1859         .addDef(NewAmtLo)
1860         .addReg(NewAmtLo)
1861         .addReg(AmtReg - 1);
1862 
1863   // Re-running hazard recognizer on the modified instruction is not necessary,
1864   // inserted V_SWAP_B32 has already both read and write new registers so
1865   // hazards related to these register has already been handled.
1866   Amt->setReg(NewAmt);
1867   Amt->setIsKill(false);
1868   // We do not update liveness, so verifier may see it as undef.
1869   Amt->setIsUndef();
1870   if (OverlappedDst)
1871     MI->getOperand(0).setReg(NewReg);
1872   if (OverlappedSrc) {
1873     Src1->setReg(NewReg);
1874     Src1->setIsKill(false);
1875     Src1->setIsUndef();
1876   }
1877 
1878   return true;
1879 }
1880 
1881 int GCNHazardRecognizer::checkNSAtoVMEMHazard(MachineInstr *MI) {
1882   int NSAtoVMEMWaitStates = 1;
1883 
1884   if (!ST.hasNSAtoVMEMBug())
1885     return 0;
1886 
1887   if (!SIInstrInfo::isMUBUF(*MI) && !SIInstrInfo::isMTBUF(*MI))
1888     return 0;
1889 
1890   const SIInstrInfo *TII = ST.getInstrInfo();
1891   const auto *Offset = TII->getNamedOperand(*MI, AMDGPU::OpName::offset);
1892   if (!Offset || (Offset->getImm() & 6) == 0)
1893     return 0;
1894 
1895   auto IsHazardFn = [TII](const MachineInstr &I) {
1896     if (!SIInstrInfo::isMIMG(I))
1897       return false;
1898     const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(I.getOpcode());
1899     return Info->MIMGEncoding == AMDGPU::MIMGEncGfx10NSA &&
1900            TII->getInstSizeInBytes(I) >= 16;
1901   };
1902 
1903   return NSAtoVMEMWaitStates - getWaitStatesSince(IsHazardFn, 1);
1904 }
1905 
1906 int GCNHazardRecognizer::checkFPAtomicToDenormModeHazard(MachineInstr *MI) {
1907   int FPAtomicToDenormModeWaitStates = 3;
1908 
1909   if (!ST.hasFPAtomicToDenormModeHazard())
1910     return 0;
1911   assert(!ST.hasExtendedWaitCounts());
1912 
1913   if (MI->getOpcode() != AMDGPU::S_DENORM_MODE)
1914     return 0;
1915 
1916   auto IsHazardFn = [](const MachineInstr &I) {
1917     if (!SIInstrInfo::isVMEM(I) && !SIInstrInfo::isFLAT(I))
1918       return false;
1919     return SIInstrInfo::isFPAtomic(I);
1920   };
1921 
1922   auto IsExpiredFn = [](const MachineInstr &MI, int WaitStates) {
1923     if (WaitStates >= 3 || SIInstrInfo::isVALU(MI))
1924       return true;
1925 
1926     switch (MI.getOpcode()) {
1927     case AMDGPU::S_WAITCNT:
1928     case AMDGPU::S_WAITCNT_VSCNT:
1929     case AMDGPU::S_WAITCNT_VMCNT:
1930     case AMDGPU::S_WAITCNT_EXPCNT:
1931     case AMDGPU::S_WAITCNT_LGKMCNT:
1932     case AMDGPU::S_WAIT_IDLE:
1933       return true;
1934     default:
1935       break;
1936     }
1937 
1938     return false;
1939   };
1940 
1941   return FPAtomicToDenormModeWaitStates -
1942          ::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn);
1943 }
1944 
1945 int GCNHazardRecognizer::checkMAIHazards(MachineInstr *MI) {
1946   assert(SIInstrInfo::isMAI(*MI));
1947 
1948   return ST.hasGFX90AInsts() ? checkMAIHazards90A(MI) : checkMAIHazards908(MI);
1949 }
1950 
1951 int GCNHazardRecognizer::checkMFMAPadding(MachineInstr *MI) {
1952   // Early exit if no padding is requested.
1953   if (MFMAPaddingRatio == 0)
1954     return 0;
1955 
1956   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1957   if (!SIInstrInfo::isMFMA(*MI) || MFI->getOccupancy() < 2)
1958     return 0;
1959 
1960   int NeighborMFMALatency = 0;
1961   auto IsNeighboringMFMA = [&NeighborMFMALatency,
1962                             this](const MachineInstr &MI) {
1963     if (!SIInstrInfo::isMFMA(MI))
1964       return false;
1965 
1966     NeighborMFMALatency = this->getMFMAPipelineWaitStates(MI);
1967     return true;
1968   };
1969 
1970   const int MaxMFMAPipelineWaitStates = 16;
1971   int WaitStatesSinceNeighborMFMA =
1972       getWaitStatesSince(IsNeighboringMFMA, MaxMFMAPipelineWaitStates);
1973 
1974   int NeighborMFMAPaddingNeeded =
1975       (NeighborMFMALatency * MFMAPaddingRatio / 100) -
1976       WaitStatesSinceNeighborMFMA;
1977 
1978   return std::max(0, NeighborMFMAPaddingNeeded);
1979 }
1980 
1981 int GCNHazardRecognizer::checkMAIHazards908(MachineInstr *MI) {
1982   int WaitStatesNeeded = 0;
1983   unsigned Opc = MI->getOpcode();
1984 
1985   auto IsVALUFn = [](const MachineInstr &MI) {
1986     return SIInstrInfo::isVALU(MI) || MI.isInlineAsm();
1987   };
1988 
1989   if (Opc != AMDGPU::V_ACCVGPR_READ_B32_e64) { // MFMA or v_accvgpr_write
1990     const int LegacyVALUWritesVGPRWaitStates = 2;
1991     const int VALUWritesExecWaitStates = 4;
1992     const int MaxWaitStates = 4;
1993 
1994     int WaitStatesNeededForUse = VALUWritesExecWaitStates -
1995       getWaitStatesSinceDef(AMDGPU::EXEC, IsVALUFn, MaxWaitStates);
1996     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
1997 
1998     if (WaitStatesNeeded < MaxWaitStates) {
1999       for (const MachineOperand &Use : MI->explicit_uses()) {
2000         const int MaxWaitStates = 2;
2001 
2002         if (!Use.isReg() || !TRI.isVGPR(MF.getRegInfo(), Use.getReg()))
2003           continue;
2004 
2005         int WaitStatesNeededForUse = LegacyVALUWritesVGPRWaitStates -
2006           getWaitStatesSinceDef(Use.getReg(), IsVALUFn, MaxWaitStates);
2007         WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2008 
2009         if (WaitStatesNeeded == MaxWaitStates)
2010           break;
2011       }
2012     }
2013   }
2014 
2015   for (const MachineOperand &Op : MI->explicit_operands()) {
2016     if (!Op.isReg() || !TRI.isAGPR(MF.getRegInfo(), Op.getReg()))
2017       continue;
2018 
2019     if (Op.isDef() && Opc != AMDGPU::V_ACCVGPR_WRITE_B32_e64)
2020       continue;
2021 
2022     const int MFMAWritesAGPROverlappedSrcABWaitStates = 4;
2023     const int MFMAWritesAGPROverlappedSrcCWaitStates = 2;
2024     const int MFMA4x4WritesAGPRAccVgprReadWaitStates = 4;
2025     const int MFMA16x16WritesAGPRAccVgprReadWaitStates = 10;
2026     const int MFMA32x32WritesAGPRAccVgprReadWaitStates = 18;
2027     const int MFMA4x4WritesAGPRAccVgprWriteWaitStates = 1;
2028     const int MFMA16x16WritesAGPRAccVgprWriteWaitStates = 7;
2029     const int MFMA32x32WritesAGPRAccVgprWriteWaitStates = 15;
2030     const int MaxWaitStates = 18;
2031     Register Reg = Op.getReg();
2032     unsigned HazardDefLatency = 0;
2033 
2034     auto IsOverlappedMFMAFn = [Reg, &HazardDefLatency,
2035                                this](const MachineInstr &MI) {
2036       if (!SIInstrInfo::isMFMA(MI))
2037         return false;
2038       Register DstReg = MI.getOperand(0).getReg();
2039       if (DstReg == Reg)
2040         return false;
2041       HazardDefLatency =
2042           std::max(HazardDefLatency, TSchedModel.computeInstrLatency(&MI));
2043       return TRI.regsOverlap(DstReg, Reg);
2044     };
2045 
2046     int WaitStatesSinceDef = getWaitStatesSinceDef(Reg, IsOverlappedMFMAFn,
2047                                                    MaxWaitStates);
2048     int NeedWaitStates = MFMAWritesAGPROverlappedSrcABWaitStates;
2049     int SrcCIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
2050     int OpNo = Op.getOperandNo();
2051     if (OpNo == SrcCIdx) {
2052       NeedWaitStates = MFMAWritesAGPROverlappedSrcCWaitStates;
2053     } else if (Opc == AMDGPU::V_ACCVGPR_READ_B32_e64) {
2054       switch (HazardDefLatency) {
2055       case 2:  NeedWaitStates = MFMA4x4WritesAGPRAccVgprReadWaitStates;
2056                break;
2057       case 8:  NeedWaitStates = MFMA16x16WritesAGPRAccVgprReadWaitStates;
2058                break;
2059       case 16: [[fallthrough]];
2060       default: NeedWaitStates = MFMA32x32WritesAGPRAccVgprReadWaitStates;
2061                break;
2062       }
2063     } else if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64) {
2064       switch (HazardDefLatency) {
2065       case 2:  NeedWaitStates = MFMA4x4WritesAGPRAccVgprWriteWaitStates;
2066                break;
2067       case 8:  NeedWaitStates = MFMA16x16WritesAGPRAccVgprWriteWaitStates;
2068                break;
2069       case 16: [[fallthrough]];
2070       default: NeedWaitStates = MFMA32x32WritesAGPRAccVgprWriteWaitStates;
2071                break;
2072       }
2073     }
2074 
2075     int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceDef;
2076     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2077 
2078     if (WaitStatesNeeded == MaxWaitStates)
2079       return WaitStatesNeeded; // Early exit.
2080 
2081     auto IsAccVgprWriteFn = [Reg, this](const MachineInstr &MI) {
2082       if (MI.getOpcode() != AMDGPU::V_ACCVGPR_WRITE_B32_e64)
2083         return false;
2084       Register DstReg = MI.getOperand(0).getReg();
2085       return TRI.regsOverlap(Reg, DstReg);
2086     };
2087 
2088     const int AccVGPRWriteMFMAReadSrcCWaitStates = 1;
2089     const int AccVGPRWriteMFMAReadSrcABWaitStates = 3;
2090     const int AccVGPRWriteAccVgprReadWaitStates = 3;
2091     NeedWaitStates = AccVGPRWriteMFMAReadSrcABWaitStates;
2092     if (OpNo == SrcCIdx)
2093       NeedWaitStates = AccVGPRWriteMFMAReadSrcCWaitStates;
2094     else if (Opc == AMDGPU::V_ACCVGPR_READ_B32_e64)
2095       NeedWaitStates = AccVGPRWriteAccVgprReadWaitStates;
2096 
2097     WaitStatesNeededForUse = NeedWaitStates -
2098       getWaitStatesSinceDef(Reg, IsAccVgprWriteFn, MaxWaitStates);
2099     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2100 
2101     if (WaitStatesNeeded == MaxWaitStates)
2102       return WaitStatesNeeded; // Early exit.
2103   }
2104 
2105   if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64) {
2106     const int MFMA4x4ReadSrcCAccVgprWriteWaitStates = 0;
2107     const int MFMA16x16ReadSrcCAccVgprWriteWaitStates = 5;
2108     const int MFMA32x32ReadSrcCAccVgprWriteWaitStates = 13;
2109     const int MaxWaitStates = 13;
2110     Register DstReg = MI->getOperand(0).getReg();
2111     unsigned HazardDefLatency = 0;
2112 
2113     auto IsSrcCMFMAFn = [DstReg, &HazardDefLatency,
2114                          this](const MachineInstr &MI) {
2115       if (!SIInstrInfo::isMFMA(MI))
2116         return false;
2117       Register Reg = TII.getNamedOperand(MI, AMDGPU::OpName::src2)->getReg();
2118       HazardDefLatency =
2119           std::max(HazardDefLatency, TSchedModel.computeInstrLatency(&MI));
2120       return TRI.regsOverlap(Reg, DstReg);
2121     };
2122 
2123     int WaitStatesSince = getWaitStatesSince(IsSrcCMFMAFn, MaxWaitStates);
2124     int NeedWaitStates;
2125     switch (HazardDefLatency) {
2126     case 2:  NeedWaitStates = MFMA4x4ReadSrcCAccVgprWriteWaitStates;
2127              break;
2128     case 8:  NeedWaitStates = MFMA16x16ReadSrcCAccVgprWriteWaitStates;
2129              break;
2130     case 16: [[fallthrough]];
2131     default: NeedWaitStates = MFMA32x32ReadSrcCAccVgprWriteWaitStates;
2132              break;
2133     }
2134 
2135     int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSince;
2136     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2137   }
2138 
2139   // Pad neighboring MFMA with noops for better inter-wave performance.
2140   WaitStatesNeeded = std::max(WaitStatesNeeded, checkMFMAPadding(MI));
2141 
2142   return WaitStatesNeeded;
2143 }
2144 
2145 int GCNHazardRecognizer::checkMAIHazards90A(MachineInstr *MI) {
2146   int WaitStatesNeeded = 0;
2147   unsigned Opc = MI->getOpcode();
2148 
2149   auto IsLegacyVALUFn = [](const MachineInstr &MI) {
2150     return SIInstrInfo::isVALU(MI) && !SIInstrInfo::isMFMA(MI);
2151   };
2152 
2153   auto IsLegacyVALUNotDotFn = [](const MachineInstr &MI) {
2154     return SIInstrInfo::isVALU(MI) && !SIInstrInfo::isMFMA(MI) &&
2155            !SIInstrInfo::isDOT(MI);
2156   };
2157 
2158   if (!SIInstrInfo::isMFMA(*MI))
2159     return WaitStatesNeeded;
2160 
2161   const int VALUWritesExecWaitStates = 4;
2162   int WaitStatesNeededForUse = VALUWritesExecWaitStates -
2163     getWaitStatesSinceDef(AMDGPU::EXEC, IsLegacyVALUFn,
2164                           VALUWritesExecWaitStates);
2165   WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2166 
2167   int SrcCIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
2168 
2169   // Loop for both DGEMM and S/HGEMM 2nd instruction.
2170   for (const MachineOperand &Use : MI->explicit_uses()) {
2171     const int LegacyVALUNotDotWritesVGPRWaitStates = 2;
2172     const int SMFMA4x4WritesVGPROverlappedSMFMASrcCWaitStates = 2;
2173     const int GFX940_XDL2PassWritesVGPROverlappedSMFMASrcCWaitStates = 3;
2174     const int GFX940_XDL4PassWritesVGPROverlappedSMFMASrcCWaitStates = 5;
2175     const int GFX940_SMFMA4PassWritesVGPROverlappedSMFMASrcCWaitStates = 4;
2176     const int GFX940_XDL8PassWritesVGPROverlappedSMFMASrcCWaitStates = 9;
2177     const int GFX940_SMFMA8PassWritesVGPROverlappedSMFMASrcCWaitStates = 8;
2178     const int GFX940_XDL16PassWritesVGPROverlappedSMFMASrcCWaitStates = 17;
2179     const int GFX940_SMFMA16PassWritesVGPROverlappedSMFMASrcCWaitStates = 16;
2180     const int SMFMA16x16WritesVGPROverlappedSMFMASrcCWaitStates = 8;
2181     const int SMFMA32x32WritesVGPROverlappedSMFMASrcCWaitStates = 16;
2182     const int SMFMA4x4WritesVGPROverlappedDMFMASrcCWaitStates = 3;
2183     const int SMFMA16x16WritesVGPROverlappedDMFMASrcCWaitStates = 9;
2184     const int SMFMA32x32WritesVGPROverlappedDMFMASrcCWaitStates = 17;
2185     const int DMFMA16x16WritesVGPROverlappedSrcCWaitStates = 9;
2186     const int DMFMA4x4WritesVGPROverlappedSrcCWaitStates = 4;
2187     const int SMFMA4x4WritesVGPROverlappedSrcABWaitStates = 5;
2188     const int SMFMA16x16WritesVGPROverlappedSrcABWaitStates = 11;
2189     const int SMFMA32x32WritesVGPROverlappedSrcABWaitStates = 19;
2190     const int GFX940_SMFMA2PassWritesVGPROverlappedSrcABWaitStates = 4;
2191     const int GFX940_SMFMA4PassWritesVGPROverlappedSrcABWaitStates = 6;
2192     const int GFX940_SMFMA8PassWritesVGPROverlappedSrcABWaitStates = 10;
2193     const int GFX940_SMFMA16PassWritesVGPROverlappedSrcABWaitStates = 18;
2194     const int GFX940_XDL2PassWritesVGPROverlappedSrcABWaitStates = 5;
2195     const int GFX940_XDL4PassWritesVGPROverlappedSrcABWaitStates = 7;
2196     const int GFX940_XDL8PassWritesVGPROverlappedSrcABWaitStates = 11;
2197     const int GFX940_XDL16PassWritesVGPROverlappedSrcABWaitStates = 19;
2198     const int DMFMA4x4WritesVGPROverlappedMFMASrcABWaitStates = 6;
2199     const int DMFMA16x16WritesVGPROverlappedMFMASrcABWaitStates = 11;
2200     const int DMFMA4x4WritesVGPRFullSrcCWaitStates = 4;
2201     const int GFX940_SMFMA4x4WritesVGPRFullSrcCWaitStates = 2;
2202     const int MaxWaitStates = 19;
2203 
2204     if (!Use.isReg())
2205       continue;
2206     Register Reg = Use.getReg();
2207     bool FullReg;
2208     const MachineInstr *MI1;
2209 
2210     auto IsOverlappedMFMAFn = [Reg, &FullReg, &MI1,
2211                                this](const MachineInstr &MI) {
2212       if (!SIInstrInfo::isMFMA(MI))
2213         return false;
2214       Register DstReg = MI.getOperand(0).getReg();
2215       FullReg = (DstReg == Reg);
2216       MI1 = &MI;
2217       return TRI.regsOverlap(DstReg, Reg);
2218     };
2219 
2220     WaitStatesNeededForUse = LegacyVALUNotDotWritesVGPRWaitStates -
2221       getWaitStatesSinceDef(Reg, IsLegacyVALUNotDotFn, MaxWaitStates);
2222     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2223 
2224     int NumWaitStates =
2225         getWaitStatesSinceDef(Reg, IsOverlappedMFMAFn, MaxWaitStates);
2226     if (NumWaitStates == std::numeric_limits<int>::max())
2227       continue;
2228 
2229     int OpNo = Use.getOperandNo();
2230     unsigned Opc1 = MI1->getOpcode();
2231     int NeedWaitStates = 0;
2232     if (OpNo == SrcCIdx) {
2233       if (!isDGEMM(Opc) && (!ST.hasGFX940Insts() && isDGEMM(Opc1))) {
2234         NeedWaitStates = 0;
2235       } else if (FullReg) {
2236         if ((Opc == AMDGPU::V_MFMA_F64_4X4X4F64_e64 ||
2237              Opc == AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64) &&
2238             (Opc1 == AMDGPU::V_MFMA_F64_4X4X4F64_e64 ||
2239              Opc1 == AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64))
2240           NeedWaitStates = DMFMA4x4WritesVGPRFullSrcCWaitStates;
2241         else if (ST.hasGFX940Insts() &&
2242                  TSchedModel.computeInstrLatency(MI1) == 2)
2243           NeedWaitStates = GFX940_SMFMA4x4WritesVGPRFullSrcCWaitStates;
2244       } else {
2245         switch (Opc1) {
2246         case AMDGPU::V_MFMA_F64_16X16X4F64_e64:
2247         case AMDGPU::V_MFMA_F64_16X16X4F64_vgprcd_e64:
2248         case AMDGPU::V_MFMA_F64_16X16X4F64_mac_e64:
2249         case AMDGPU::V_MFMA_F64_16X16X4F64_mac_vgprcd_e64:
2250           if (!isXDL(ST, *MI))
2251             NeedWaitStates = DMFMA16x16WritesVGPROverlappedSrcCWaitStates;
2252           break;
2253         case AMDGPU::V_MFMA_F64_4X4X4F64_e64:
2254         case AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64:
2255           if (!isXDL(ST, *MI))
2256             NeedWaitStates = DMFMA4x4WritesVGPROverlappedSrcCWaitStates;
2257           break;
2258         default:
2259           if (ST.hasGFX940Insts() && isXDL(ST, *MI) && !isXDL(ST, *MI1))
2260             break;
2261           switch (TSchedModel.computeInstrLatency(MI1)) {
2262           case 2:
2263             NeedWaitStates = ST.hasGFX940Insts()
2264               ? isXDL(ST, *MI1)
2265                 ? GFX940_XDL2PassWritesVGPROverlappedSMFMASrcCWaitStates
2266                 : SMFMA4x4WritesVGPROverlappedSMFMASrcCWaitStates
2267               : isDGEMM(Opc)
2268                 ? SMFMA4x4WritesVGPROverlappedDMFMASrcCWaitStates
2269                 : SMFMA4x4WritesVGPROverlappedSMFMASrcCWaitStates;
2270             break;
2271           case 4:
2272             assert(ST.hasGFX940Insts());
2273             NeedWaitStates = isXDL(ST, *MI1)
2274               ? GFX940_XDL4PassWritesVGPROverlappedSMFMASrcCWaitStates
2275               : GFX940_SMFMA4PassWritesVGPROverlappedSMFMASrcCWaitStates;
2276             break;
2277           case 8:
2278             NeedWaitStates = ST.hasGFX940Insts()
2279               ? isXDL(ST, *MI1)
2280                 ? GFX940_XDL8PassWritesVGPROverlappedSMFMASrcCWaitStates
2281                 : GFX940_SMFMA8PassWritesVGPROverlappedSMFMASrcCWaitStates
2282               : isDGEMM(Opc)
2283                 ? SMFMA16x16WritesVGPROverlappedDMFMASrcCWaitStates
2284                 : SMFMA16x16WritesVGPROverlappedSMFMASrcCWaitStates;
2285             break;
2286           case 16: [[fallthrough]];
2287           default:
2288             NeedWaitStates = ST.hasGFX940Insts()
2289               ? isXDL(ST, *MI1)
2290                 ? GFX940_XDL16PassWritesVGPROverlappedSMFMASrcCWaitStates
2291                 : GFX940_SMFMA16PassWritesVGPROverlappedSMFMASrcCWaitStates
2292               : isDGEMM(Opc)
2293                 ? SMFMA32x32WritesVGPROverlappedDMFMASrcCWaitStates
2294                 : SMFMA32x32WritesVGPROverlappedSMFMASrcCWaitStates;
2295           }
2296         }
2297       }
2298     } else {
2299       switch (Opc1) {
2300       case AMDGPU::V_MFMA_F64_16X16X4F64_e64:
2301       case AMDGPU::V_MFMA_F64_16X16X4F64_vgprcd_e64:
2302       case AMDGPU::V_MFMA_F64_16X16X4F64_mac_e64:
2303       case AMDGPU::V_MFMA_F64_16X16X4F64_mac_vgprcd_e64:
2304         NeedWaitStates = DMFMA16x16WritesVGPROverlappedMFMASrcABWaitStates;
2305         break;
2306       case AMDGPU::V_MFMA_F64_4X4X4F64_e64:
2307       case AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64:
2308         NeedWaitStates = DMFMA4x4WritesVGPROverlappedMFMASrcABWaitStates;
2309         break;
2310       default:
2311         switch (TSchedModel.computeInstrLatency(MI1)) {
2312         case 2:
2313           NeedWaitStates = ST.hasGFX940Insts()
2314             ? isXDL(ST, *MI1)
2315               ? GFX940_XDL2PassWritesVGPROverlappedSrcABWaitStates
2316               : GFX940_SMFMA2PassWritesVGPROverlappedSrcABWaitStates
2317             : SMFMA4x4WritesVGPROverlappedSrcABWaitStates;
2318           break;
2319         case 4:
2320           assert(ST.hasGFX940Insts());
2321           NeedWaitStates = isXDL(ST, *MI1)
2322             ? GFX940_XDL4PassWritesVGPROverlappedSrcABWaitStates
2323             : GFX940_SMFMA4PassWritesVGPROverlappedSrcABWaitStates;
2324           break;
2325         case 8:
2326           NeedWaitStates = ST.hasGFX940Insts()
2327             ? isXDL(ST, *MI1)
2328               ? GFX940_XDL8PassWritesVGPROverlappedSrcABWaitStates
2329               : GFX940_SMFMA8PassWritesVGPROverlappedSrcABWaitStates
2330             : SMFMA16x16WritesVGPROverlappedSrcABWaitStates;
2331           break;
2332         case 16: [[fallthrough]];
2333         default:
2334           NeedWaitStates = ST.hasGFX940Insts()
2335             ? isXDL(ST, *MI1)
2336               ? GFX940_XDL16PassWritesVGPROverlappedSrcABWaitStates
2337               : GFX940_SMFMA16PassWritesVGPROverlappedSrcABWaitStates
2338             : SMFMA32x32WritesVGPROverlappedSrcABWaitStates;
2339         }
2340       }
2341     }
2342     if (WaitStatesNeeded >= NeedWaitStates)
2343       continue;
2344 
2345     WaitStatesNeededForUse = NeedWaitStates - NumWaitStates;
2346     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2347 
2348     if (WaitStatesNeeded == MaxWaitStates)
2349       break;
2350   }
2351 
2352   return WaitStatesNeeded;
2353 }
2354 
2355 int GCNHazardRecognizer::checkMAILdStHazards(MachineInstr *MI) {
2356   // On gfx90a+ relevant hazards are checked in checkMAIVALUHazards()
2357   if (!ST.hasMAIInsts() || ST.hasGFX90AInsts())
2358     return 0;
2359 
2360   int WaitStatesNeeded = 0;
2361 
2362   auto IsAccVgprReadFn = [](const MachineInstr &MI) {
2363     return MI.getOpcode() == AMDGPU::V_ACCVGPR_READ_B32_e64;
2364   };
2365 
2366   for (const MachineOperand &Op : MI->explicit_uses()) {
2367     if (!Op.isReg() || !TRI.isVGPR(MF.getRegInfo(), Op.getReg()))
2368       continue;
2369 
2370     Register Reg = Op.getReg();
2371 
2372     const int AccVgprReadLdStWaitStates = 2;
2373     const int VALUWriteAccVgprRdWrLdStDepVALUWaitStates = 1;
2374     const int MaxWaitStates = 2;
2375 
2376     int WaitStatesNeededForUse = AccVgprReadLdStWaitStates -
2377       getWaitStatesSinceDef(Reg, IsAccVgprReadFn, MaxWaitStates);
2378     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2379 
2380     if (WaitStatesNeeded == MaxWaitStates)
2381       return WaitStatesNeeded; // Early exit.
2382 
2383     auto IsVALUAccVgprRdWrCheckFn = [Reg, this](const MachineInstr &MI) {
2384       if (MI.getOpcode() != AMDGPU::V_ACCVGPR_READ_B32_e64 &&
2385           MI.getOpcode() != AMDGPU::V_ACCVGPR_WRITE_B32_e64)
2386         return false;
2387       auto IsVALUFn = [](const MachineInstr &MI) {
2388         return SIInstrInfo::isVALU(MI) && !SIInstrInfo::isMAI(MI);
2389       };
2390       return getWaitStatesSinceDef(Reg, IsVALUFn, 2 /*MaxWaitStates*/) <
2391              std::numeric_limits<int>::max();
2392     };
2393 
2394     WaitStatesNeededForUse = VALUWriteAccVgprRdWrLdStDepVALUWaitStates -
2395       getWaitStatesSince(IsVALUAccVgprRdWrCheckFn, MaxWaitStates);
2396     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2397   }
2398 
2399   return WaitStatesNeeded;
2400 }
2401 
2402 int GCNHazardRecognizer::checkMAIVALUHazards(MachineInstr *MI) {
2403   if (!ST.hasGFX90AInsts())
2404     return 0;
2405 
2406   auto IsDGEMMFn = [](const MachineInstr &MI) -> bool {
2407     return isDGEMM(MI.getOpcode());
2408   };
2409 
2410   // This is checked in checkMAIHazards90A()
2411   if (SIInstrInfo::isMFMA(*MI))
2412     return 0;
2413 
2414   const MachineRegisterInfo &MRI = MF.getRegInfo();
2415 
2416   int WaitStatesNeeded = 0;
2417 
2418   bool IsMem = SIInstrInfo::isVMEM(*MI) ||
2419                SIInstrInfo::isFLAT(*MI) ||
2420                SIInstrInfo::isDS(*MI);
2421   bool IsMemOrExport = IsMem || SIInstrInfo::isEXP(*MI);
2422   bool IsVALU = SIInstrInfo::isVALU(*MI);
2423 
2424   const MachineInstr *MFMA = nullptr;
2425   unsigned Reg;
2426   auto IsMFMAWriteFn = [&Reg, &MFMA, this](const MachineInstr &MI) {
2427     if (!SIInstrInfo::isMFMA(MI) ||
2428         !TRI.regsOverlap(MI.getOperand(0).getReg(), Reg))
2429       return false;
2430     MFMA = &MI;
2431     return true;
2432   };
2433 
2434   const MachineInstr *DOT = nullptr;
2435   auto IsDotWriteFn = [&Reg, &DOT, this](const MachineInstr &MI) {
2436     if (!SIInstrInfo::isDOT(MI) ||
2437         !TRI.regsOverlap(MI.getOperand(0).getReg(), Reg))
2438       return false;
2439     DOT = &MI;
2440     return true;
2441   };
2442 
2443   bool DGEMMAfterVALUWrite = false;
2444   auto IsDGEMMHazard = [&DGEMMAfterVALUWrite, this](const MachineInstr &MI) {
2445     // Found DGEMM on reverse traversal to def.
2446     if (isDGEMM(MI.getOpcode()))
2447       DGEMMAfterVALUWrite = true;
2448 
2449     // Only hazard if register is defined by a VALU and a DGEMM is found after
2450     // after the def.
2451     if (!TII.isVALU(MI) || !DGEMMAfterVALUWrite)
2452       return false;
2453 
2454     return true;
2455   };
2456 
2457   int SrcCIdx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
2458                                            AMDGPU::OpName::src2);
2459 
2460   if (IsMemOrExport || IsVALU) {
2461     const int SMFMA4x4WriteVgprVALUMemExpReadWaitStates = 5;
2462     const int SMFMA16x16WriteVgprVALUMemExpReadWaitStates = 11;
2463     const int SMFMA32x32WriteVgprVALUMemExpReadWaitStates = 19;
2464     const int GFX940_SMFMA2PassWriteVgprVALUMemExpReadWaitStates = 4;
2465     const int GFX940_SMFMA4PassWriteVgprVALUMemExpReadWaitStates = 6;
2466     const int GFX940_SMFMA8PassWriteVgprVALUMemExpReadWaitStates = 10;
2467     const int GFX940_SMFMA16PassWriteVgprVALUMemExpReadWaitStates = 18;
2468     const int GFX940_XDL2PassWriteVgprVALUMemExpReadWaitStates = 5;
2469     const int GFX940_XDL4PassWriteVgprVALUMemExpReadWaitStates = 7;
2470     const int GFX940_XDL8PassWriteVgprVALUMemExpReadWaitStates = 11;
2471     const int GFX940_XDL16PassWriteVgprVALUMemExpReadWaitStates = 19;
2472     const int DMFMA4x4WriteVgprMemExpReadWaitStates = 9;
2473     const int DMFMA16x16WriteVgprMemExpReadWaitStates = 18;
2474     const int DMFMA4x4WriteVgprVALUReadWaitStates = 6;
2475     const int DMFMA16x16WriteVgprVALUReadWaitStates = 11;
2476     const int DotWriteSameDotReadSrcAB = 3;
2477     const int DotWriteDifferentVALURead = 3;
2478     const int DMFMABetweenVALUWriteVMEMRead = 2;
2479     const int MaxWaitStates = 19;
2480 
2481     for (const MachineOperand &Use : MI->explicit_uses()) {
2482       if (!Use.isReg())
2483         continue;
2484       Reg = Use.getReg();
2485 
2486       DOT = nullptr;
2487       int WaitStatesSinceDef = getWaitStatesSinceDef(Reg, IsDotWriteFn,
2488                                                      MaxWaitStates);
2489       if (DOT) {
2490         int NeedWaitStates = 0;
2491         if (DOT->getOpcode() == MI->getOpcode()) {
2492           if (&Use - &MI->getOperand(0) != SrcCIdx)
2493             NeedWaitStates = DotWriteSameDotReadSrcAB;
2494         } else {
2495           NeedWaitStates = DotWriteDifferentVALURead;
2496         }
2497 
2498         int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceDef;
2499         WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2500       }
2501 
2502       // Workaround for HW data hazard bug observed only in GFX90A. When there
2503       // is a DGEMM instruction in-between a VALU and a VMEM instruction it
2504       // causes the SQ to incorrectly not insert two wait states between the two
2505       // instructions needed to avoid data hazard.
2506       if (IsMem && ST.hasGFX90AInsts() && !ST.hasGFX940Insts()) {
2507         DGEMMAfterVALUWrite = false;
2508         if (TRI.isVectorRegister(MRI, Reg)) {
2509           int WaitStatesNeededForUse =
2510                 DMFMABetweenVALUWriteVMEMRead -
2511                 getWaitStatesSinceDef(Reg, IsDGEMMHazard,
2512                                       DMFMABetweenVALUWriteVMEMRead);
2513 
2514           WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2515         }
2516       }
2517 
2518       MFMA = nullptr;
2519       WaitStatesSinceDef =
2520           getWaitStatesSinceDef(Reg, IsMFMAWriteFn, MaxWaitStates);
2521       if (!MFMA)
2522         continue;
2523 
2524       unsigned HazardDefLatency = TSchedModel.computeInstrLatency(MFMA);
2525       int NeedWaitStates = MaxWaitStates;
2526       switch (HazardDefLatency) {
2527       case 2:
2528         NeedWaitStates =
2529           ST.hasGFX940Insts()
2530             ? isXDL(ST, *MFMA)
2531               ? GFX940_XDL2PassWriteVgprVALUMemExpReadWaitStates
2532               : GFX940_SMFMA2PassWriteVgprVALUMemExpReadWaitStates
2533             : SMFMA4x4WriteVgprVALUMemExpReadWaitStates;
2534         break;
2535       case 4:
2536         assert(isDGEMM(MFMA->getOpcode()) || ST.hasGFX940Insts());
2537         NeedWaitStates =
2538           isDGEMM(MFMA->getOpcode())
2539             ? IsMemOrExport ? DMFMA4x4WriteVgprMemExpReadWaitStates
2540                             : DMFMA4x4WriteVgprVALUReadWaitStates
2541             : isXDL(ST, *MFMA)
2542               ? GFX940_XDL4PassWriteVgprVALUMemExpReadWaitStates
2543               : GFX940_SMFMA4PassWriteVgprVALUMemExpReadWaitStates;
2544         break;
2545       case 8:
2546         NeedWaitStates =
2547           ST.hasGFX940Insts()
2548             ? isXDL(ST, *MFMA)
2549               ? GFX940_XDL8PassWriteVgprVALUMemExpReadWaitStates
2550               : GFX940_SMFMA8PassWriteVgprVALUMemExpReadWaitStates
2551             : SMFMA16x16WriteVgprVALUMemExpReadWaitStates;
2552         break;
2553       case 16: [[fallthrough]];
2554       default:
2555         NeedWaitStates =
2556           isDGEMM(MFMA->getOpcode())
2557             ? IsMemOrExport ? DMFMA16x16WriteVgprMemExpReadWaitStates
2558                             : DMFMA16x16WriteVgprVALUReadWaitStates
2559             : ST.hasGFX940Insts()
2560               ? isXDL(ST, *MFMA)
2561                 ? GFX940_XDL16PassWriteVgprVALUMemExpReadWaitStates
2562                 : GFX940_SMFMA16PassWriteVgprVALUMemExpReadWaitStates
2563               : SMFMA32x32WriteVgprVALUMemExpReadWaitStates;
2564         break;
2565       }
2566 
2567       int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceDef;
2568       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2569 
2570       if (WaitStatesNeeded == MaxWaitStates)
2571         break;
2572     }
2573   }
2574 
2575   unsigned Opc = MI->getOpcode();
2576   const int DMFMAToFMA64WaitStates = 2;
2577   if ((Opc == AMDGPU::V_FMA_F64_e64 ||
2578        Opc == AMDGPU::V_FMAC_F64_e32 || Opc == AMDGPU::V_FMAC_F64_e64 ||
2579        Opc == AMDGPU::V_FMAC_F64_dpp) &&
2580       WaitStatesNeeded < DMFMAToFMA64WaitStates) {
2581     int WaitStatesNeededForUse = DMFMAToFMA64WaitStates -
2582       getWaitStatesSince(IsDGEMMFn, DMFMAToFMA64WaitStates);
2583     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2584   }
2585 
2586   if (!IsVALU && !IsMemOrExport)
2587     return WaitStatesNeeded;
2588 
2589   for (const MachineOperand &Def : MI->defs()) {
2590     const int SMFMA4x4WriteVgprVALUWawWaitStates = 5;
2591     const int SMFMA16x16WriteVgprVALUWawWaitStates = 11;
2592     const int SMFMA32x32WriteVgprVALUWawWaitStates = 19;
2593     const int GFX940_SMFMA2PassWriteVgprVALUWawWaitStates = 4;
2594     const int GFX940_SMFMA4PassWriteVgprVALUWawWaitStates = 6;
2595     const int GFX940_SMFMA8PassWriteVgprVALUWawWaitStates = 10;
2596     const int GFX940_SMFMA16PassWriteVgprVALUWawWaitStates = 18;
2597     const int GFX940_XDL2PassWriteVgprVALUWawWaitStates = 5;
2598     const int GFX940_XDL4PassWriteVgprVALUWawWaitStates = 7;
2599     const int GFX940_XDL8PassWriteVgprVALUWawWaitStates = 11;
2600     const int GFX940_XDL16PassWriteVgprVALUWawWaitStates = 19;
2601     const int SMFMA4x4ReadVgprVALUWarWaitStates = 1;
2602     const int GFX940_XDL4PassReadVgprVALUWarWaitStates = 3;
2603     const int SMFMA16x16ReadVgprVALUWarWaitStates = 7;
2604     const int SMFMA32x32ReadVgprVALUWarWaitStates = 15;
2605     const int DMFMA4x4WriteVgprVALUWriteWaitStates = 6;
2606     const int DMFMA16x16WriteVgprVALUWriteWaitStates = 11;
2607     const int DotWriteDifferentVALUWrite = 3;
2608     const int MaxWaitStates = 19;
2609     const int MaxWarWaitStates = 15;
2610 
2611     Reg = Def.getReg();
2612 
2613     DOT = nullptr;
2614     int WaitStatesSinceDef = getWaitStatesSinceDef(Reg, IsDotWriteFn,
2615                                                    MaxWaitStates);
2616     if (DOT && DOT->getOpcode() != MI->getOpcode())
2617       WaitStatesNeeded = std::max(WaitStatesNeeded, DotWriteDifferentVALUWrite -
2618                                                     WaitStatesSinceDef);
2619 
2620     MFMA = nullptr;
2621     WaitStatesSinceDef =
2622         getWaitStatesSinceDef(Reg, IsMFMAWriteFn, MaxWaitStates);
2623     if (MFMA) {
2624       int NeedWaitStates = MaxWaitStates;
2625       switch (TSchedModel.computeInstrLatency(MFMA)) {
2626       case 2:
2627         NeedWaitStates = ST.hasGFX940Insts()
2628           ? isXDL(ST, *MFMA)
2629             ? GFX940_XDL2PassWriteVgprVALUWawWaitStates
2630             : GFX940_SMFMA2PassWriteVgprVALUWawWaitStates
2631           : SMFMA4x4WriteVgprVALUWawWaitStates;
2632         break;
2633       case 4:
2634         assert(isDGEMM(MFMA->getOpcode()) || ST.hasGFX940Insts());
2635         NeedWaitStates = isDGEMM(MFMA->getOpcode())
2636             ? DMFMA4x4WriteVgprVALUWriteWaitStates
2637             : isXDL(ST, *MFMA)
2638               ? GFX940_XDL4PassWriteVgprVALUWawWaitStates
2639               : GFX940_SMFMA4PassWriteVgprVALUWawWaitStates;
2640         break;
2641       case 8:
2642         NeedWaitStates = ST.hasGFX940Insts()
2643           ? isXDL(ST, *MFMA)
2644             ? GFX940_XDL8PassWriteVgprVALUWawWaitStates
2645             : GFX940_SMFMA8PassWriteVgprVALUWawWaitStates
2646           : SMFMA16x16WriteVgprVALUWawWaitStates;
2647         break;
2648       case 16: [[fallthrough]];
2649       default:
2650         NeedWaitStates = isDGEMM(MFMA->getOpcode())
2651                    ? DMFMA16x16WriteVgprVALUWriteWaitStates
2652                    : ST.hasGFX940Insts()
2653                      ? isXDL(ST, *MFMA)
2654                        ? GFX940_XDL16PassWriteVgprVALUWawWaitStates
2655                        : GFX940_SMFMA16PassWriteVgprVALUWawWaitStates
2656                    : SMFMA32x32WriteVgprVALUWawWaitStates;
2657         break;
2658       }
2659 
2660       int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceDef;
2661       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2662 
2663       if (WaitStatesNeeded == MaxWaitStates)
2664         break;
2665     }
2666 
2667     auto IsSMFMAReadAsCFn = [&Reg, &MFMA, this](const MachineInstr &MI) {
2668       if (!SIInstrInfo::isMFMA(MI) || isDGEMM(MI.getOpcode()) ||
2669           !MI.readsRegister(Reg, &TRI))
2670         return false;
2671 
2672       if (ST.hasGFX940Insts() && !isXDL(ST, MI))
2673         return false;
2674 
2675       const MachineOperand *SrcC =
2676           TII.getNamedOperand(MI, AMDGPU::OpName::src2);
2677       assert(SrcC);
2678       if (!SrcC->isReg() || !TRI.regsOverlap(SrcC->getReg(), Reg))
2679         return false;
2680 
2681       MFMA = &MI;
2682       return true;
2683     };
2684 
2685     MFMA = nullptr;
2686     int WaitStatesSinceUse = getWaitStatesSince(IsSMFMAReadAsCFn,
2687                                                 MaxWarWaitStates);
2688     if (!MFMA)
2689       continue;
2690 
2691     unsigned HazardDefLatency = TSchedModel.computeInstrLatency(MFMA);
2692     int NeedWaitStates = MaxWaitStates;
2693     switch (HazardDefLatency) {
2694     case 2:  NeedWaitStates = SMFMA4x4ReadVgprVALUWarWaitStates;
2695              break;
2696     case 4:  assert(ST.hasGFX940Insts());
2697              NeedWaitStates = GFX940_XDL4PassReadVgprVALUWarWaitStates;
2698              break;
2699     case 8:  NeedWaitStates = SMFMA16x16ReadVgprVALUWarWaitStates;
2700              break;
2701     case 16: [[fallthrough]];
2702     default: NeedWaitStates = SMFMA32x32ReadVgprVALUWarWaitStates;
2703              break;
2704     }
2705 
2706     int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceUse;
2707     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2708   }
2709 
2710   return WaitStatesNeeded;
2711 }
2712 
2713 bool GCNHazardRecognizer::ShouldPreferAnother(SUnit *SU) {
2714   if (!SU->isInstr())
2715     return false;
2716 
2717   const MachineInstr *MAI = nullptr;
2718 
2719   auto IsMFMAFn = [&MAI](const MachineInstr &MI) {
2720     MAI = nullptr;
2721     if (SIInstrInfo::isMFMA(MI))
2722       MAI = &MI;
2723     return MAI != nullptr;
2724   };
2725 
2726   MachineInstr *MI = SU->getInstr();
2727   if (IsMFMAFn(*MI)) {
2728     int W = getWaitStatesSince(IsMFMAFn, 16);
2729     if (MAI)
2730       return W < (int)TSchedModel.computeInstrLatency(MAI);
2731   }
2732 
2733   return false;
2734 }
2735 
2736 bool GCNHazardRecognizer::fixVALUMaskWriteHazard(MachineInstr *MI) {
2737   if (!ST.hasVALUMaskWriteHazard())
2738     return false;
2739   assert(!ST.hasExtendedWaitCounts());
2740 
2741   if (!ST.isWave64() || !SIInstrInfo::isSALU(*MI))
2742     return false;
2743 
2744   // The hazard sequence is three instructions:
2745   //   1. VALU reads SGPR as mask
2746   //   2. SALU writes SGPR
2747   //   3. SALU reads SGPR
2748   // The hazard can expire if the distance between 2 and 3 is sufficient.
2749   // In practice this happens <10% of the time, hence this always assumes
2750   // the hazard exists if 1 and 2 are present to avoid searching.
2751 
2752   const MachineOperand *SDSTOp = TII.getNamedOperand(*MI, AMDGPU::OpName::sdst);
2753   if (!SDSTOp || !SDSTOp->isReg())
2754     return false;
2755 
2756   const Register HazardReg = SDSTOp->getReg();
2757   if (HazardReg == AMDGPU::EXEC ||
2758       HazardReg == AMDGPU::EXEC_LO ||
2759       HazardReg == AMDGPU::EXEC_HI ||
2760       HazardReg == AMDGPU::M0)
2761     return false;
2762 
2763   auto IsHazardFn = [HazardReg, this](const MachineInstr &I) {
2764     switch (I.getOpcode()) {
2765     case AMDGPU::V_ADDC_U32_e32:
2766     case AMDGPU::V_ADDC_U32_dpp:
2767     case AMDGPU::V_CNDMASK_B16_e32:
2768     case AMDGPU::V_CNDMASK_B16_dpp:
2769     case AMDGPU::V_CNDMASK_B32_e32:
2770     case AMDGPU::V_CNDMASK_B32_dpp:
2771     case AMDGPU::V_DIV_FMAS_F32_e64:
2772     case AMDGPU::V_DIV_FMAS_F64_e64:
2773     case AMDGPU::V_SUBB_U32_e32:
2774     case AMDGPU::V_SUBB_U32_dpp:
2775     case AMDGPU::V_SUBBREV_U32_e32:
2776     case AMDGPU::V_SUBBREV_U32_dpp:
2777       // These implicitly read VCC as mask source.
2778       return HazardReg == AMDGPU::VCC ||
2779              HazardReg == AMDGPU::VCC_LO ||
2780              HazardReg == AMDGPU::VCC_HI;
2781     case AMDGPU::V_ADDC_U32_e64:
2782     case AMDGPU::V_ADDC_U32_e64_dpp:
2783     case AMDGPU::V_CNDMASK_B16_e64:
2784     case AMDGPU::V_CNDMASK_B16_e64_dpp:
2785     case AMDGPU::V_CNDMASK_B32_e64:
2786     case AMDGPU::V_CNDMASK_B32_e64_dpp:
2787     case AMDGPU::V_SUBB_U32_e64:
2788     case AMDGPU::V_SUBB_U32_e64_dpp:
2789     case AMDGPU::V_SUBBREV_U32_e64:
2790     case AMDGPU::V_SUBBREV_U32_e64_dpp: {
2791       // Only check mask register overlaps.
2792       const MachineOperand *SSRCOp = TII.getNamedOperand(I, AMDGPU::OpName::src2);
2793       assert(SSRCOp);
2794       return TRI.regsOverlap(SSRCOp->getReg(), HazardReg);
2795     }
2796     default:
2797       return false;
2798     }
2799   };
2800 
2801   const MachineRegisterInfo &MRI = MF.getRegInfo();
2802   auto IsExpiredFn = [&MRI, this](const MachineInstr &I, int) {
2803     // s_waitcnt_depctr sa_sdst(0) mitigates hazard.
2804     if (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
2805         AMDGPU::DepCtr::decodeFieldSaSdst(I.getOperand(0).getImm()) == 0)
2806       return true;
2807 
2808     // VALU access to any SGPR or literal constant other than HazardReg
2809     // mitigates hazard. No need to check HazardReg here as this will
2810     // only be called when !IsHazardFn.
2811     if (!SIInstrInfo::isVALU(I))
2812       return false;
2813     for (int OpNo = 0, End = I.getNumOperands(); OpNo < End; ++OpNo) {
2814       const MachineOperand &Op = I.getOperand(OpNo);
2815       if (Op.isReg()) {
2816         Register OpReg = Op.getReg();
2817         // Only consider uses
2818         if (!Op.isUse())
2819           continue;
2820         // Ignore EXEC
2821         if (OpReg == AMDGPU::EXEC ||
2822             OpReg == AMDGPU::EXEC_LO ||
2823             OpReg == AMDGPU::EXEC_HI)
2824           continue;
2825         // Ignore all implicit uses except VCC
2826         if (Op.isImplicit()) {
2827           if (OpReg == AMDGPU::VCC ||
2828               OpReg == AMDGPU::VCC_LO ||
2829               OpReg == AMDGPU::VCC_HI)
2830             return true;
2831           continue;
2832         }
2833         if (TRI.isSGPRReg(MRI, OpReg))
2834           return true;
2835       } else {
2836         const MCInstrDesc &InstDesc = I.getDesc();
2837         const MCOperandInfo &OpInfo = InstDesc.operands()[OpNo];
2838         if (!TII.isInlineConstant(Op, OpInfo))
2839           return true;
2840       }
2841     }
2842     return false;
2843   };
2844 
2845   // Check for hazard
2846   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
2847       std::numeric_limits<int>::max())
2848     return false;
2849 
2850   auto NextMI = std::next(MI->getIterator());
2851 
2852   // Add s_waitcnt_depctr sa_sdst(0) after SALU write.
2853   BuildMI(*MI->getParent(), NextMI, MI->getDebugLoc(),
2854           TII.get(AMDGPU::S_WAITCNT_DEPCTR))
2855       .addImm(AMDGPU::DepCtr::encodeFieldSaSdst(0));
2856 
2857   // SALU write may be s_getpc in a bundle.
2858   if (MI->getOpcode() == AMDGPU::S_GETPC_B64) {
2859     // Update offsets of any references in the bundle.
2860     while (NextMI != MI->getParent()->end() &&
2861            NextMI->isBundledWithPred()) {
2862       for (auto &Operand : NextMI->operands()) {
2863         if (Operand.isGlobal())
2864           Operand.setOffset(Operand.getOffset() + 4);
2865       }
2866       NextMI++;
2867     }
2868   }
2869 
2870   return true;
2871 }
2872