1 //===- SIInsertWaitcnts.cpp - Insert Wait Instructions --------------------===//
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 /// \file
10 /// Insert wait instructions for memory reads and writes.
11 ///
12 /// Memory reads and writes are issued asynchronously, so we need to insert
13 /// S_WAITCNT instructions when we want to access any of their results or
14 /// overwrite any register that's used asynchronously.
15 ///
16 /// TODO: This pass currently keeps one timeline per hardware counter. A more
17 /// finely-grained approach that keeps one timeline per event type could
18 /// sometimes get away with generating weaker s_waitcnt instructions. For
19 /// example, when both SMEM and LDS are in flight and we need to wait for
20 /// the i-th-last LDS instruction, then an lgkmcnt(i) is actually sufficient,
21 /// but the pass will currently generate a conservative lgkmcnt(0) because
22 /// multiple event types are in flight.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "AMDGPU.h"
27 #include "GCNSubtarget.h"
28 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
29 #include "SIMachineFunctionInfo.h"
30 #include "Utils/AMDGPUBaseInfo.h"
31 #include "llvm/ADT/MapVector.h"
32 #include "llvm/ADT/PostOrderIterator.h"
33 #include "llvm/ADT/Sequence.h"
34 #include "llvm/CodeGen/MachinePostDominators.h"
35 #include "llvm/InitializePasses.h"
36 #include "llvm/Support/DebugCounter.h"
37 #include "llvm/Support/TargetParser.h"
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "si-insert-waitcnts"
41 
42 DEBUG_COUNTER(ForceExpCounter, DEBUG_TYPE"-forceexp",
43               "Force emit s_waitcnt expcnt(0) instrs");
44 DEBUG_COUNTER(ForceLgkmCounter, DEBUG_TYPE"-forcelgkm",
45               "Force emit s_waitcnt lgkmcnt(0) instrs");
46 DEBUG_COUNTER(ForceVMCounter, DEBUG_TYPE"-forcevm",
47               "Force emit s_waitcnt vmcnt(0) instrs");
48 
49 static cl::opt<bool> ForceEmitZeroFlag(
50   "amdgpu-waitcnt-forcezero",
51   cl::desc("Force all waitcnt instrs to be emitted as s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
52   cl::init(false), cl::Hidden);
53 
54 namespace {
55 // Class of object that encapsulates latest instruction counter score
56 // associated with the operand.  Used for determining whether
57 // s_waitcnt instruction needs to be emitted.
58 
59 #define CNT_MASK(t) (1u << (t))
60 
61 enum InstCounterType { VM_CNT = 0, LGKM_CNT, EXP_CNT, VS_CNT, NUM_INST_CNTS };
62 } // namespace
63 
64 namespace llvm {
65 template <> struct enum_iteration_traits<InstCounterType> {
66   static constexpr bool is_iterable = true;
67 };
68 } // namespace llvm
69 
70 namespace {
71 auto inst_counter_types() { return enum_seq(VM_CNT, NUM_INST_CNTS); }
72 
73 using RegInterval = std::pair<int, int>;
74 
75 struct HardwareLimits {
76   unsigned VmcntMax;
77   unsigned ExpcntMax;
78   unsigned LgkmcntMax;
79   unsigned VscntMax;
80 };
81 
82 struct RegisterEncoding {
83   unsigned VGPR0;
84   unsigned VGPRL;
85   unsigned SGPR0;
86   unsigned SGPRL;
87 };
88 
89 enum WaitEventType {
90   VMEM_ACCESS,      // vector-memory read & write
91   VMEM_READ_ACCESS, // vector-memory read
92   VMEM_WRITE_ACCESS,// vector-memory write
93   LDS_ACCESS,       // lds read & write
94   GDS_ACCESS,       // gds read & write
95   SQ_MESSAGE,       // send message
96   SMEM_ACCESS,      // scalar-memory read & write
97   EXP_GPR_LOCK,     // export holding on its data src
98   GDS_GPR_LOCK,     // GDS holding on its data and addr src
99   EXP_POS_ACCESS,   // write to export position
100   EXP_PARAM_ACCESS, // write to export parameter
101   VMW_GPR_LOCK,     // vector-memory write holding on its data src
102   NUM_WAIT_EVENTS,
103 };
104 
105 static const unsigned WaitEventMaskForInst[NUM_INST_CNTS] = {
106   (1 << VMEM_ACCESS) | (1 << VMEM_READ_ACCESS),
107   (1 << SMEM_ACCESS) | (1 << LDS_ACCESS) | (1 << GDS_ACCESS) |
108       (1 << SQ_MESSAGE),
109   (1 << EXP_GPR_LOCK) | (1 << GDS_GPR_LOCK) | (1 << VMW_GPR_LOCK) |
110       (1 << EXP_PARAM_ACCESS) | (1 << EXP_POS_ACCESS),
111   (1 << VMEM_WRITE_ACCESS)
112 };
113 
114 // The mapping is:
115 //  0                .. SQ_MAX_PGM_VGPRS-1               real VGPRs
116 //  SQ_MAX_PGM_VGPRS .. NUM_ALL_VGPRS-1                  extra VGPR-like slots
117 //  NUM_ALL_VGPRS    .. NUM_ALL_VGPRS+SQ_MAX_PGM_SGPRS-1 real SGPRs
118 // We reserve a fixed number of VGPR slots in the scoring tables for
119 // special tokens like SCMEM_LDS (needed for buffer load to LDS).
120 enum RegisterMapping {
121   SQ_MAX_PGM_VGPRS = 512, // Maximum programmable VGPRs across all targets.
122   AGPR_OFFSET = 256,      // Maximum programmable ArchVGPRs across all targets.
123   SQ_MAX_PGM_SGPRS = 256, // Maximum programmable SGPRs across all targets.
124   NUM_EXTRA_VGPRS = 1,    // A reserved slot for DS.
125   EXTRA_VGPR_LDS = 0,     // An artificial register to track LDS writes.
126   NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_EXTRA_VGPRS, // Where SGPR starts.
127 };
128 
129 // Enumerate different types of result-returning VMEM operations. Although
130 // s_waitcnt orders them all with a single vmcnt counter, in the absence of
131 // s_waitcnt only instructions of the same VmemType are guaranteed to write
132 // their results in order -- so there is no need to insert an s_waitcnt between
133 // two instructions of the same type that write the same vgpr.
134 enum VmemType {
135   // BUF instructions and MIMG instructions without a sampler.
136   VMEM_NOSAMPLER,
137   // MIMG instructions with a sampler.
138   VMEM_SAMPLER,
139   // BVH instructions
140   VMEM_BVH
141 };
142 
143 VmemType getVmemType(const MachineInstr &Inst) {
144   assert(SIInstrInfo::isVMEM(Inst));
145   if (!SIInstrInfo::isMIMG(Inst))
146     return VMEM_NOSAMPLER;
147   const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Inst.getOpcode());
148   const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
149       AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
150   return BaseInfo->BVH ? VMEM_BVH
151                        : BaseInfo->Sampler ? VMEM_SAMPLER : VMEM_NOSAMPLER;
152 }
153 
154 void addWait(AMDGPU::Waitcnt &Wait, InstCounterType T, unsigned Count) {
155   switch (T) {
156   case VM_CNT:
157     Wait.VmCnt = std::min(Wait.VmCnt, Count);
158     break;
159   case EXP_CNT:
160     Wait.ExpCnt = std::min(Wait.ExpCnt, Count);
161     break;
162   case LGKM_CNT:
163     Wait.LgkmCnt = std::min(Wait.LgkmCnt, Count);
164     break;
165   case VS_CNT:
166     Wait.VsCnt = std::min(Wait.VsCnt, Count);
167     break;
168   default:
169     llvm_unreachable("bad InstCounterType");
170   }
171 }
172 
173 // This objects maintains the current score brackets of each wait counter, and
174 // a per-register scoreboard for each wait counter.
175 //
176 // We also maintain the latest score for every event type that can change the
177 // waitcnt in order to know if there are multiple types of events within
178 // the brackets. When multiple types of event happen in the bracket,
179 // wait count may get decreased out of order, therefore we need to put in
180 // "s_waitcnt 0" before use.
181 class WaitcntBrackets {
182 public:
183   WaitcntBrackets(const GCNSubtarget *SubTarget, HardwareLimits Limits,
184                   RegisterEncoding Encoding)
185       : ST(SubTarget), Limits(Limits), Encoding(Encoding) {}
186 
187   unsigned getWaitCountMax(InstCounterType T) const {
188     switch (T) {
189     case VM_CNT:
190       return Limits.VmcntMax;
191     case LGKM_CNT:
192       return Limits.LgkmcntMax;
193     case EXP_CNT:
194       return Limits.ExpcntMax;
195     case VS_CNT:
196       return Limits.VscntMax;
197     default:
198       break;
199     }
200     return 0;
201   }
202 
203   unsigned getScoreLB(InstCounterType T) const {
204     assert(T < NUM_INST_CNTS);
205     return ScoreLBs[T];
206   }
207 
208   unsigned getScoreUB(InstCounterType T) const {
209     assert(T < NUM_INST_CNTS);
210     return ScoreUBs[T];
211   }
212 
213   // Mapping from event to counter.
214   InstCounterType eventCounter(WaitEventType E) {
215     if (WaitEventMaskForInst[VM_CNT] & (1 << E))
216       return VM_CNT;
217     if (WaitEventMaskForInst[LGKM_CNT] & (1 << E))
218       return LGKM_CNT;
219     if (WaitEventMaskForInst[VS_CNT] & (1 << E))
220       return VS_CNT;
221     assert(WaitEventMaskForInst[EXP_CNT] & (1 << E));
222     return EXP_CNT;
223   }
224 
225   unsigned getRegScore(int GprNo, InstCounterType T) {
226     if (GprNo < NUM_ALL_VGPRS) {
227       return VgprScores[T][GprNo];
228     }
229     assert(T == LGKM_CNT);
230     return SgprScores[GprNo - NUM_ALL_VGPRS];
231   }
232 
233   bool merge(const WaitcntBrackets &Other);
234 
235   RegInterval getRegInterval(const MachineInstr *MI, const SIInstrInfo *TII,
236                              const MachineRegisterInfo *MRI,
237                              const SIRegisterInfo *TRI, unsigned OpNo) const;
238 
239   bool counterOutOfOrder(InstCounterType T) const;
240   void simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const;
241   void simplifyWaitcnt(InstCounterType T, unsigned &Count) const;
242   void determineWait(InstCounterType T, unsigned ScoreToWait,
243                      AMDGPU::Waitcnt &Wait) const;
244   void applyWaitcnt(const AMDGPU::Waitcnt &Wait);
245   void applyWaitcnt(InstCounterType T, unsigned Count);
246   void updateByEvent(const SIInstrInfo *TII, const SIRegisterInfo *TRI,
247                      const MachineRegisterInfo *MRI, WaitEventType E,
248                      MachineInstr &MI);
249 
250   bool hasPending() const { return PendingEvents != 0; }
251   bool hasPendingEvent(WaitEventType E) const {
252     return PendingEvents & (1 << E);
253   }
254 
255   bool hasMixedPendingEvents(InstCounterType T) const {
256     unsigned Events = PendingEvents & WaitEventMaskForInst[T];
257     // Return true if more than one bit is set in Events.
258     return Events & (Events - 1);
259   }
260 
261   bool hasPendingFlat() const {
262     return ((LastFlat[LGKM_CNT] > ScoreLBs[LGKM_CNT] &&
263              LastFlat[LGKM_CNT] <= ScoreUBs[LGKM_CNT]) ||
264             (LastFlat[VM_CNT] > ScoreLBs[VM_CNT] &&
265              LastFlat[VM_CNT] <= ScoreUBs[VM_CNT]));
266   }
267 
268   void setPendingFlat() {
269     LastFlat[VM_CNT] = ScoreUBs[VM_CNT];
270     LastFlat[LGKM_CNT] = ScoreUBs[LGKM_CNT];
271   }
272 
273   // Return true if there might be pending writes to the specified vgpr by VMEM
274   // instructions with types different from V.
275   bool hasOtherPendingVmemTypes(int GprNo, VmemType V) const {
276     assert(GprNo < NUM_ALL_VGPRS);
277     return VgprVmemTypes[GprNo] & ~(1 << V);
278   }
279 
280   void clearVgprVmemTypes(int GprNo) {
281     assert(GprNo < NUM_ALL_VGPRS);
282     VgprVmemTypes[GprNo] = 0;
283   }
284 
285   void print(raw_ostream &);
286   void dump() { print(dbgs()); }
287 
288 private:
289   struct MergeInfo {
290     unsigned OldLB;
291     unsigned OtherLB;
292     unsigned MyShift;
293     unsigned OtherShift;
294   };
295   static bool mergeScore(const MergeInfo &M, unsigned &Score,
296                          unsigned OtherScore);
297 
298   void setScoreLB(InstCounterType T, unsigned Val) {
299     assert(T < NUM_INST_CNTS);
300     ScoreLBs[T] = Val;
301   }
302 
303   void setScoreUB(InstCounterType T, unsigned Val) {
304     assert(T < NUM_INST_CNTS);
305     ScoreUBs[T] = Val;
306     if (T == EXP_CNT) {
307       unsigned UB = ScoreUBs[T] - getWaitCountMax(EXP_CNT);
308       if (ScoreLBs[T] < UB && UB < ScoreUBs[T])
309         ScoreLBs[T] = UB;
310     }
311   }
312 
313   void setRegScore(int GprNo, InstCounterType T, unsigned Val) {
314     if (GprNo < NUM_ALL_VGPRS) {
315       VgprUB = std::max(VgprUB, GprNo);
316       VgprScores[T][GprNo] = Val;
317     } else {
318       assert(T == LGKM_CNT);
319       SgprUB = std::max(SgprUB, GprNo - NUM_ALL_VGPRS);
320       SgprScores[GprNo - NUM_ALL_VGPRS] = Val;
321     }
322   }
323 
324   void setExpScore(const MachineInstr *MI, const SIInstrInfo *TII,
325                    const SIRegisterInfo *TRI, const MachineRegisterInfo *MRI,
326                    unsigned OpNo, unsigned Val);
327 
328   const GCNSubtarget *ST = nullptr;
329   HardwareLimits Limits = {};
330   RegisterEncoding Encoding = {};
331   unsigned ScoreLBs[NUM_INST_CNTS] = {0};
332   unsigned ScoreUBs[NUM_INST_CNTS] = {0};
333   unsigned PendingEvents = 0;
334   // Remember the last flat memory operation.
335   unsigned LastFlat[NUM_INST_CNTS] = {0};
336   // wait_cnt scores for every vgpr.
337   // Keep track of the VgprUB and SgprUB to make merge at join efficient.
338   int VgprUB = -1;
339   int SgprUB = -1;
340   unsigned VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS] = {{0}};
341   // Wait cnt scores for every sgpr, only lgkmcnt is relevant.
342   unsigned SgprScores[SQ_MAX_PGM_SGPRS] = {0};
343   // Bitmask of the VmemTypes of VMEM instructions that might have a pending
344   // write to each vgpr.
345   unsigned char VgprVmemTypes[NUM_ALL_VGPRS] = {0};
346 };
347 
348 class SIInsertWaitcnts : public MachineFunctionPass {
349 private:
350   const GCNSubtarget *ST = nullptr;
351   const SIInstrInfo *TII = nullptr;
352   const SIRegisterInfo *TRI = nullptr;
353   const MachineRegisterInfo *MRI = nullptr;
354   AMDGPU::IsaVersion IV;
355 
356   DenseSet<MachineInstr *> TrackedWaitcntSet;
357   DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
358   MachinePostDominatorTree *PDT;
359 
360   struct BlockInfo {
361     MachineBasicBlock *MBB;
362     std::unique_ptr<WaitcntBrackets> Incoming;
363     bool Dirty = true;
364 
365     explicit BlockInfo(MachineBasicBlock *MBB) : MBB(MBB) {}
366   };
367 
368   MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
369 
370   // ForceEmitZeroWaitcnts: force all waitcnts insts to be s_waitcnt 0
371   // because of amdgpu-waitcnt-forcezero flag
372   bool ForceEmitZeroWaitcnts;
373   bool ForceEmitWaitcnt[NUM_INST_CNTS];
374 
375 public:
376   static char ID;
377 
378   SIInsertWaitcnts() : MachineFunctionPass(ID) {
379     (void)ForceExpCounter;
380     (void)ForceLgkmCounter;
381     (void)ForceVMCounter;
382   }
383 
384   bool runOnMachineFunction(MachineFunction &MF) override;
385 
386   StringRef getPassName() const override {
387     return "SI insert wait instructions";
388   }
389 
390   void getAnalysisUsage(AnalysisUsage &AU) const override {
391     AU.setPreservesCFG();
392     AU.addRequired<MachinePostDominatorTree>();
393     MachineFunctionPass::getAnalysisUsage(AU);
394   }
395 
396   bool isForceEmitWaitcnt() const {
397     for (auto T : inst_counter_types())
398       if (ForceEmitWaitcnt[T])
399         return true;
400     return false;
401   }
402 
403   void setForceEmitWaitcnt() {
404 // For non-debug builds, ForceEmitWaitcnt has been initialized to false;
405 // For debug builds, get the debug counter info and adjust if need be
406 #ifndef NDEBUG
407     if (DebugCounter::isCounterSet(ForceExpCounter) &&
408         DebugCounter::shouldExecute(ForceExpCounter)) {
409       ForceEmitWaitcnt[EXP_CNT] = true;
410     } else {
411       ForceEmitWaitcnt[EXP_CNT] = false;
412     }
413 
414     if (DebugCounter::isCounterSet(ForceLgkmCounter) &&
415         DebugCounter::shouldExecute(ForceLgkmCounter)) {
416       ForceEmitWaitcnt[LGKM_CNT] = true;
417     } else {
418       ForceEmitWaitcnt[LGKM_CNT] = false;
419     }
420 
421     if (DebugCounter::isCounterSet(ForceVMCounter) &&
422         DebugCounter::shouldExecute(ForceVMCounter)) {
423       ForceEmitWaitcnt[VM_CNT] = true;
424     } else {
425       ForceEmitWaitcnt[VM_CNT] = false;
426     }
427 #endif // NDEBUG
428   }
429 
430   bool mayAccessVMEMThroughFlat(const MachineInstr &MI) const;
431   bool mayAccessLDSThroughFlat(const MachineInstr &MI) const;
432   bool generateWaitcntInstBefore(MachineInstr &MI,
433                                  WaitcntBrackets &ScoreBrackets,
434                                  MachineInstr *OldWaitcntInstr);
435   void updateEventWaitcntAfter(MachineInstr &Inst,
436                                WaitcntBrackets *ScoreBrackets);
437   bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block,
438                             WaitcntBrackets &ScoreBrackets);
439   bool applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
440                                MachineInstr &OldWaitcntInstr,
441                                AMDGPU::Waitcnt &Wait, const MachineInstr *MI);
442 };
443 
444 } // end anonymous namespace
445 
446 RegInterval WaitcntBrackets::getRegInterval(const MachineInstr *MI,
447                                             const SIInstrInfo *TII,
448                                             const MachineRegisterInfo *MRI,
449                                             const SIRegisterInfo *TRI,
450                                             unsigned OpNo) const {
451   const MachineOperand &Op = MI->getOperand(OpNo);
452   if (!TRI->isInAllocatableClass(Op.getReg()))
453     return {-1, -1};
454 
455   // A use via a PW operand does not need a waitcnt.
456   // A partial write is not a WAW.
457   assert(!Op.getSubReg() || !Op.isUndef());
458 
459   RegInterval Result;
460 
461   unsigned Reg = TRI->getEncodingValue(AMDGPU::getMCReg(Op.getReg(), *ST));
462 
463   if (TRI->isVectorRegister(*MRI, Op.getReg())) {
464     assert(Reg >= Encoding.VGPR0 && Reg <= Encoding.VGPRL);
465     Result.first = Reg - Encoding.VGPR0;
466     if (TRI->isAGPR(*MRI, Op.getReg()))
467       Result.first += AGPR_OFFSET;
468     assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS);
469   } else if (TRI->isSGPRReg(*MRI, Op.getReg())) {
470     assert(Reg >= Encoding.SGPR0 && Reg < SQ_MAX_PGM_SGPRS);
471     Result.first = Reg - Encoding.SGPR0 + NUM_ALL_VGPRS;
472     assert(Result.first >= NUM_ALL_VGPRS &&
473            Result.first < SQ_MAX_PGM_SGPRS + NUM_ALL_VGPRS);
474   }
475   // TODO: Handle TTMP
476   // else if (TRI->isTTMP(*MRI, Reg.getReg())) ...
477   else
478     return {-1, -1};
479 
480   const TargetRegisterClass *RC = TII->getOpRegClass(*MI, OpNo);
481   unsigned Size = TRI->getRegSizeInBits(*RC);
482   Result.second = Result.first + ((Size + 16) / 32);
483 
484   return Result;
485 }
486 
487 void WaitcntBrackets::setExpScore(const MachineInstr *MI,
488                                   const SIInstrInfo *TII,
489                                   const SIRegisterInfo *TRI,
490                                   const MachineRegisterInfo *MRI, unsigned OpNo,
491                                   unsigned Val) {
492   RegInterval Interval = getRegInterval(MI, TII, MRI, TRI, OpNo);
493   assert(TRI->isVectorRegister(*MRI, MI->getOperand(OpNo).getReg()));
494   for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
495     setRegScore(RegNo, EXP_CNT, Val);
496   }
497 }
498 
499 // MUBUF and FLAT LDS DMA operations need a wait on vmcnt before LDS written
500 // can be accessed. A load from LDS to VMEM does not need a wait.
501 static bool mayWriteLDSThroughDMA(const MachineInstr &MI) {
502   return SIInstrInfo::isVALU(MI) &&
503          (SIInstrInfo::isMUBUF(MI) || SIInstrInfo::isFLAT(MI)) &&
504          MI.getOpcode() != AMDGPU::BUFFER_STORE_LDS_DWORD;
505 }
506 
507 void WaitcntBrackets::updateByEvent(const SIInstrInfo *TII,
508                                     const SIRegisterInfo *TRI,
509                                     const MachineRegisterInfo *MRI,
510                                     WaitEventType E, MachineInstr &Inst) {
511   InstCounterType T = eventCounter(E);
512   unsigned CurrScore = getScoreUB(T) + 1;
513   if (CurrScore == 0)
514     report_fatal_error("InsertWaitcnt score wraparound");
515   // PendingEvents and ScoreUB need to be update regardless if this event
516   // changes the score of a register or not.
517   // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
518   PendingEvents |= 1 << E;
519   setScoreUB(T, CurrScore);
520 
521   if (T == EXP_CNT) {
522     // Put score on the source vgprs. If this is a store, just use those
523     // specific register(s).
524     if (TII->isDS(Inst) && (Inst.mayStore() || Inst.mayLoad())) {
525       int AddrOpIdx =
526           AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::addr);
527       // All GDS operations must protect their address register (same as
528       // export.)
529       if (AddrOpIdx != -1) {
530         setExpScore(&Inst, TII, TRI, MRI, AddrOpIdx, CurrScore);
531       }
532 
533       if (Inst.mayStore()) {
534         if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
535                                        AMDGPU::OpName::data0) != -1) {
536           setExpScore(
537               &Inst, TII, TRI, MRI,
538               AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0),
539               CurrScore);
540         }
541         if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
542                                        AMDGPU::OpName::data1) != -1) {
543           setExpScore(&Inst, TII, TRI, MRI,
544                       AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
545                                                  AMDGPU::OpName::data1),
546                       CurrScore);
547         }
548       } else if (SIInstrInfo::isAtomicRet(Inst) &&
549                  Inst.getOpcode() != AMDGPU::DS_GWS_INIT &&
550                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_V &&
551                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_BR &&
552                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_P &&
553                  Inst.getOpcode() != AMDGPU::DS_GWS_BARRIER &&
554                  Inst.getOpcode() != AMDGPU::DS_APPEND &&
555                  Inst.getOpcode() != AMDGPU::DS_CONSUME &&
556                  Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
557         for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
558           const MachineOperand &Op = Inst.getOperand(I);
559           if (Op.isReg() && !Op.isDef() &&
560               TRI->isVectorRegister(*MRI, Op.getReg())) {
561             setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
562           }
563         }
564       }
565     } else if (TII->isFLAT(Inst)) {
566       if (Inst.mayStore()) {
567         setExpScore(
568             &Inst, TII, TRI, MRI,
569             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
570             CurrScore);
571       } else if (SIInstrInfo::isAtomicRet(Inst)) {
572         setExpScore(
573             &Inst, TII, TRI, MRI,
574             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
575             CurrScore);
576       }
577     } else if (TII->isMIMG(Inst)) {
578       if (Inst.mayStore()) {
579         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
580       } else if (SIInstrInfo::isAtomicRet(Inst)) {
581         setExpScore(
582             &Inst, TII, TRI, MRI,
583             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
584             CurrScore);
585       }
586     } else if (TII->isMTBUF(Inst)) {
587       if (Inst.mayStore()) {
588         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
589       }
590     } else if (TII->isMUBUF(Inst)) {
591       if (Inst.mayStore()) {
592         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
593       } else if (SIInstrInfo::isAtomicRet(Inst)) {
594         setExpScore(
595             &Inst, TII, TRI, MRI,
596             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
597             CurrScore);
598       }
599     } else {
600       if (TII->isEXP(Inst)) {
601         // For export the destination registers are really temps that
602         // can be used as the actual source after export patching, so
603         // we need to treat them like sources and set the EXP_CNT
604         // score.
605         for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
606           MachineOperand &DefMO = Inst.getOperand(I);
607           if (DefMO.isReg() && DefMO.isDef() &&
608               TRI->isVGPR(*MRI, DefMO.getReg())) {
609             setRegScore(
610                 TRI->getEncodingValue(AMDGPU::getMCReg(DefMO.getReg(), *ST)),
611                 EXP_CNT, CurrScore);
612           }
613         }
614       }
615       for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
616         MachineOperand &MO = Inst.getOperand(I);
617         if (MO.isReg() && !MO.isDef() &&
618             TRI->isVectorRegister(*MRI, MO.getReg())) {
619           setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
620         }
621       }
622     }
623 #if 0 // TODO: check if this is handled by MUBUF code above.
624   } else if (Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORD ||
625        Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX2 ||
626        Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX4) {
627     MachineOperand *MO = TII->getNamedOperand(Inst, AMDGPU::OpName::data);
628     unsigned OpNo;//TODO: find the OpNo for this operand;
629     RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, OpNo);
630     for (int RegNo = Interval.first; RegNo < Interval.second;
631     ++RegNo) {
632       setRegScore(RegNo + NUM_ALL_VGPRS, t, CurrScore);
633     }
634 #endif
635   } else {
636     // Match the score to the destination registers.
637     for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
638       auto &Op = Inst.getOperand(I);
639       if (!Op.isReg() || !Op.isDef())
640         continue;
641       RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, I);
642       if (T == VM_CNT) {
643         if (Interval.first >= NUM_ALL_VGPRS)
644           continue;
645         if (SIInstrInfo::isVMEM(Inst)) {
646           VmemType V = getVmemType(Inst);
647           for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo)
648             VgprVmemTypes[RegNo] |= 1 << V;
649         }
650       }
651       for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
652         setRegScore(RegNo, T, CurrScore);
653       }
654     }
655     if (Inst.mayStore() && (TII->isDS(Inst) || mayWriteLDSThroughDMA(Inst))) {
656       setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS, T, CurrScore);
657     }
658   }
659 }
660 
661 void WaitcntBrackets::print(raw_ostream &OS) {
662   OS << '\n';
663   for (auto T : inst_counter_types()) {
664     unsigned LB = getScoreLB(T);
665     unsigned UB = getScoreUB(T);
666 
667     switch (T) {
668     case VM_CNT:
669       OS << "    VM_CNT(" << UB - LB << "): ";
670       break;
671     case LGKM_CNT:
672       OS << "    LGKM_CNT(" << UB - LB << "): ";
673       break;
674     case EXP_CNT:
675       OS << "    EXP_CNT(" << UB - LB << "): ";
676       break;
677     case VS_CNT:
678       OS << "    VS_CNT(" << UB - LB << "): ";
679       break;
680     default:
681       OS << "    UNKNOWN(" << UB - LB << "): ";
682       break;
683     }
684 
685     if (LB < UB) {
686       // Print vgpr scores.
687       for (int J = 0; J <= VgprUB; J++) {
688         unsigned RegScore = getRegScore(J, T);
689         if (RegScore <= LB)
690           continue;
691         unsigned RelScore = RegScore - LB - 1;
692         if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) {
693           OS << RelScore << ":v" << J << " ";
694         } else {
695           OS << RelScore << ":ds ";
696         }
697       }
698       // Also need to print sgpr scores for lgkm_cnt.
699       if (T == LGKM_CNT) {
700         for (int J = 0; J <= SgprUB; J++) {
701           unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
702           if (RegScore <= LB)
703             continue;
704           unsigned RelScore = RegScore - LB - 1;
705           OS << RelScore << ":s" << J << " ";
706         }
707       }
708     }
709     OS << '\n';
710   }
711   OS << '\n';
712 }
713 
714 /// Simplify the waitcnt, in the sense of removing redundant counts, and return
715 /// whether a waitcnt instruction is needed at all.
716 void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const {
717   simplifyWaitcnt(VM_CNT, Wait.VmCnt);
718   simplifyWaitcnt(EXP_CNT, Wait.ExpCnt);
719   simplifyWaitcnt(LGKM_CNT, Wait.LgkmCnt);
720   simplifyWaitcnt(VS_CNT, Wait.VsCnt);
721 }
722 
723 void WaitcntBrackets::simplifyWaitcnt(InstCounterType T,
724                                       unsigned &Count) const {
725   const unsigned LB = getScoreLB(T);
726   const unsigned UB = getScoreUB(T);
727 
728   // The number of outstanding events for this type, T, can be calculated
729   // as (UB - LB). If the current Count is greater than or equal to the number
730   // of outstanding events, then the wait for this counter is redundant.
731   if (Count >= UB - LB)
732     Count = ~0u;
733 }
734 
735 void WaitcntBrackets::determineWait(InstCounterType T, unsigned ScoreToWait,
736                                     AMDGPU::Waitcnt &Wait) const {
737   // If the score of src_operand falls within the bracket, we need an
738   // s_waitcnt instruction.
739   const unsigned LB = getScoreLB(T);
740   const unsigned UB = getScoreUB(T);
741   if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
742     if ((T == VM_CNT || T == LGKM_CNT) &&
743         hasPendingFlat() &&
744         !ST->hasFlatLgkmVMemCountInOrder()) {
745       // If there is a pending FLAT operation, and this is a VMem or LGKM
746       // waitcnt and the target can report early completion, then we need
747       // to force a waitcnt 0.
748       addWait(Wait, T, 0);
749     } else if (counterOutOfOrder(T)) {
750       // Counter can get decremented out-of-order when there
751       // are multiple types event in the bracket. Also emit an s_wait counter
752       // with a conservative value of 0 for the counter.
753       addWait(Wait, T, 0);
754     } else {
755       // If a counter has been maxed out avoid overflow by waiting for
756       // MAX(CounterType) - 1 instead.
757       unsigned NeededWait = std::min(UB - ScoreToWait, getWaitCountMax(T) - 1);
758       addWait(Wait, T, NeededWait);
759     }
760   }
761 }
762 
763 void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait) {
764   applyWaitcnt(VM_CNT, Wait.VmCnt);
765   applyWaitcnt(EXP_CNT, Wait.ExpCnt);
766   applyWaitcnt(LGKM_CNT, Wait.LgkmCnt);
767   applyWaitcnt(VS_CNT, Wait.VsCnt);
768 }
769 
770 void WaitcntBrackets::applyWaitcnt(InstCounterType T, unsigned Count) {
771   const unsigned UB = getScoreUB(T);
772   if (Count >= UB)
773     return;
774   if (Count != 0) {
775     if (counterOutOfOrder(T))
776       return;
777     setScoreLB(T, std::max(getScoreLB(T), UB - Count));
778   } else {
779     setScoreLB(T, UB);
780     PendingEvents &= ~WaitEventMaskForInst[T];
781   }
782 }
783 
784 // Where there are multiple types of event in the bracket of a counter,
785 // the decrement may go out of order.
786 bool WaitcntBrackets::counterOutOfOrder(InstCounterType T) const {
787   // Scalar memory read always can go out of order.
788   if (T == LGKM_CNT && hasPendingEvent(SMEM_ACCESS))
789     return true;
790   return hasMixedPendingEvents(T);
791 }
792 
793 INITIALIZE_PASS_BEGIN(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
794                       false)
795 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
796 INITIALIZE_PASS_END(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
797                     false)
798 
799 char SIInsertWaitcnts::ID = 0;
800 
801 char &llvm::SIInsertWaitcntsID = SIInsertWaitcnts::ID;
802 
803 FunctionPass *llvm::createSIInsertWaitcntsPass() {
804   return new SIInsertWaitcnts();
805 }
806 
807 /// Combine consecutive waitcnt instructions that precede \p MI and follow
808 /// \p OldWaitcntInstr and apply any extra wait from waitcnt that were added
809 /// by previous passes. Currently this pass conservatively assumes that these
810 /// preexisting waitcnt are required for correctness.
811 bool SIInsertWaitcnts::applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
812                                                MachineInstr &OldWaitcntInstr,
813                                                AMDGPU::Waitcnt &Wait,
814                                                const MachineInstr *MI) {
815   bool Modified = false;
816   MachineInstr *WaitcntInstr = nullptr;
817   MachineInstr *WaitcntVsCntInstr = nullptr;
818   for (auto II = OldWaitcntInstr.getIterator(), NextI = std::next(II);
819        &*II != MI; II = NextI, ++NextI) {
820     if (II->isMetaInstruction())
821       continue;
822 
823     if (II->getOpcode() == AMDGPU::S_WAITCNT) {
824       // Conservatively update required wait if this waitcnt was added in an
825       // earlier pass. In this case it will not exist in the tracked waitcnt
826       // set.
827       if (!TrackedWaitcntSet.count(&*II)) {
828         unsigned IEnc = II->getOperand(0).getImm();
829         AMDGPU::Waitcnt OldWait = AMDGPU::decodeWaitcnt(IV, IEnc);
830         Wait = Wait.combined(OldWait);
831       }
832 
833       // Merge consecutive waitcnt of the same type by erasing multiples.
834       if (!WaitcntInstr) {
835         WaitcntInstr = &*II;
836       } else {
837         II->eraseFromParent();
838         Modified = true;
839       }
840 
841     } else {
842       assert(II->getOpcode() == AMDGPU::S_WAITCNT_VSCNT);
843       assert(II->getOperand(0).getReg() == AMDGPU::SGPR_NULL);
844       if (!TrackedWaitcntSet.count(&*II)) {
845         unsigned OldVSCnt =
846             TII->getNamedOperand(*II, AMDGPU::OpName::simm16)->getImm();
847         Wait.VsCnt = std::min(Wait.VsCnt, OldVSCnt);
848       }
849 
850       if (!WaitcntVsCntInstr) {
851         WaitcntVsCntInstr = &*II;
852       } else {
853         II->eraseFromParent();
854         Modified = true;
855       }
856     }
857   }
858 
859   // Updated encoding of merged waitcnt with the required wait.
860   if (WaitcntInstr) {
861     if (Wait.hasWaitExceptVsCnt()) {
862       unsigned NewEnc = AMDGPU::encodeWaitcnt(IV, Wait);
863       unsigned OldEnc = WaitcntInstr->getOperand(0).getImm();
864       if (OldEnc != NewEnc) {
865         WaitcntInstr->getOperand(0).setImm(NewEnc);
866         Modified = true;
867       }
868       ScoreBrackets.applyWaitcnt(Wait);
869       Wait.VmCnt = ~0u;
870       Wait.LgkmCnt = ~0u;
871       Wait.ExpCnt = ~0u;
872 
873       LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
874                         << "Old Instr: " << *MI << "New Instr: " << *WaitcntInstr
875                         << '\n');
876     } else {
877       WaitcntInstr->eraseFromParent();
878       Modified = true;
879     }
880   }
881 
882   if (WaitcntVsCntInstr) {
883     if (Wait.hasWaitVsCnt()) {
884       assert(ST->hasVscnt());
885       unsigned OldVSCnt =
886           TII->getNamedOperand(*WaitcntVsCntInstr, AMDGPU::OpName::simm16)
887               ->getImm();
888       if (Wait.VsCnt != OldVSCnt) {
889         TII->getNamedOperand(*WaitcntVsCntInstr, AMDGPU::OpName::simm16)
890             ->setImm(Wait.VsCnt);
891         Modified = true;
892       }
893       ScoreBrackets.applyWaitcnt(Wait);
894       Wait.VsCnt = ~0u;
895 
896       LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
897                         << "Old Instr: " << *MI
898                         << "New Instr: " << *WaitcntVsCntInstr << '\n');
899     } else {
900       WaitcntVsCntInstr->eraseFromParent();
901       Modified = true;
902     }
903   }
904 
905   return Modified;
906 }
907 
908 static bool readsVCCZ(const MachineInstr &MI) {
909   unsigned Opc = MI.getOpcode();
910   return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
911          !MI.getOperand(1).isUndef();
912 }
913 
914 /// \returns true if the callee inserts an s_waitcnt 0 on function entry.
915 static bool callWaitsOnFunctionEntry(const MachineInstr &MI) {
916   // Currently all conventions wait, but this may not always be the case.
917   //
918   // TODO: If IPRA is enabled, and the callee is isSafeForNoCSROpt, it may make
919   // senses to omit the wait and do it in the caller.
920   return true;
921 }
922 
923 /// \returns true if the callee is expected to wait for any outstanding waits
924 /// before returning.
925 static bool callWaitsOnFunctionReturn(const MachineInstr &MI) {
926   return true;
927 }
928 
929 ///  Generate s_waitcnt instruction to be placed before cur_Inst.
930 ///  Instructions of a given type are returned in order,
931 ///  but instructions of different types can complete out of order.
932 ///  We rely on this in-order completion
933 ///  and simply assign a score to the memory access instructions.
934 ///  We keep track of the active "score bracket" to determine
935 ///  if an access of a memory read requires an s_waitcnt
936 ///  and if so what the value of each counter is.
937 ///  The "score bracket" is bound by the lower bound and upper bound
938 ///  scores (*_score_LB and *_score_ub respectively).
939 bool SIInsertWaitcnts::generateWaitcntInstBefore(
940     MachineInstr &MI, WaitcntBrackets &ScoreBrackets,
941     MachineInstr *OldWaitcntInstr) {
942   setForceEmitWaitcnt();
943 
944   if (MI.isMetaInstruction())
945     return false;
946 
947   AMDGPU::Waitcnt Wait;
948   bool Modified = false;
949 
950   // FIXME: This should have already been handled by the memory legalizer.
951   // Removing this currently doesn't affect any lit tests, but we need to
952   // verify that nothing was relying on this. The number of buffer invalidates
953   // being handled here should not be expanded.
954   if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
955       MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
956       MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL ||
957       MI.getOpcode() == AMDGPU::BUFFER_GL0_INV ||
958       MI.getOpcode() == AMDGPU::BUFFER_GL1_INV) {
959     Wait.VmCnt = 0;
960   }
961 
962   // All waits must be resolved at call return.
963   // NOTE: this could be improved with knowledge of all call sites or
964   //   with knowledge of the called routines.
965   if (MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
966       MI.getOpcode() == AMDGPU::SI_RETURN ||
967       MI.getOpcode() == AMDGPU::S_SETPC_B64_return ||
968       (MI.isReturn() && MI.isCall() && !callWaitsOnFunctionEntry(MI))) {
969     Wait = Wait.combined(AMDGPU::Waitcnt::allZero(ST->hasVscnt()));
970   }
971   // Resolve vm waits before gs-done.
972   else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
973             MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
974            ST->hasLegacyGeometry() &&
975            ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_PreGFX11_) ==
976             AMDGPU::SendMsg::ID_GS_DONE_PreGFX11)) {
977     Wait.VmCnt = 0;
978   }
979 #if 0 // TODO: the following blocks of logic when we have fence.
980   else if (MI.getOpcode() == SC_FENCE) {
981     const unsigned int group_size =
982       context->shader_info->GetMaxThreadGroupSize();
983     // group_size == 0 means thread group size is unknown at compile time
984     const bool group_is_multi_wave =
985       (group_size == 0 || group_size > target_info->GetWaveFrontSize());
986     const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence();
987 
988     for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) {
989       SCRegType src_type = Inst->GetSrcType(i);
990       switch (src_type) {
991         case SCMEM_LDS:
992           if (group_is_multi_wave ||
993             context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) {
994             EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
995                                ScoreBrackets->getScoreUB(LGKM_CNT));
996             // LDS may have to wait for VM_CNT after buffer load to LDS
997             if (target_info->HasBufferLoadToLDS()) {
998               EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
999                                  ScoreBrackets->getScoreUB(VM_CNT));
1000             }
1001           }
1002           break;
1003 
1004         case SCMEM_GDS:
1005           if (group_is_multi_wave || fence_is_global) {
1006             EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
1007               ScoreBrackets->getScoreUB(EXP_CNT));
1008             EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
1009               ScoreBrackets->getScoreUB(LGKM_CNT));
1010           }
1011           break;
1012 
1013         case SCMEM_UAV:
1014         case SCMEM_TFBUF:
1015         case SCMEM_RING:
1016         case SCMEM_SCATTER:
1017           if (group_is_multi_wave || fence_is_global) {
1018             EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
1019               ScoreBrackets->getScoreUB(EXP_CNT));
1020             EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
1021               ScoreBrackets->getScoreUB(VM_CNT));
1022           }
1023           break;
1024 
1025         case SCMEM_SCRATCH:
1026         default:
1027           break;
1028       }
1029     }
1030   }
1031 #endif
1032 
1033   // Export & GDS instructions do not read the EXEC mask until after the export
1034   // is granted (which can occur well after the instruction is issued).
1035   // The shader program must flush all EXP operations on the export-count
1036   // before overwriting the EXEC mask.
1037   else {
1038     if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
1039       // Export and GDS are tracked individually, either may trigger a waitcnt
1040       // for EXEC.
1041       if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1042           ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1043           ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1044           ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1045         Wait.ExpCnt = 0;
1046       }
1047     }
1048 
1049     if (MI.isCall() && callWaitsOnFunctionEntry(MI)) {
1050       // The function is going to insert a wait on everything in its prolog.
1051       // This still needs to be careful if the call target is a load (e.g. a GOT
1052       // load). We also need to check WAW dependency with saved PC.
1053       Wait = AMDGPU::Waitcnt();
1054 
1055       int CallAddrOpIdx =
1056           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
1057 
1058       if (MI.getOperand(CallAddrOpIdx).isReg()) {
1059         RegInterval CallAddrOpInterval =
1060           ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, CallAddrOpIdx);
1061 
1062         for (int RegNo = CallAddrOpInterval.first;
1063              RegNo < CallAddrOpInterval.second; ++RegNo)
1064           ScoreBrackets.determineWait(
1065             LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
1066 
1067         int RtnAddrOpIdx =
1068           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::dst);
1069         if (RtnAddrOpIdx != -1) {
1070           RegInterval RtnAddrOpInterval =
1071             ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, RtnAddrOpIdx);
1072 
1073           for (int RegNo = RtnAddrOpInterval.first;
1074                RegNo < RtnAddrOpInterval.second; ++RegNo)
1075             ScoreBrackets.determineWait(
1076               LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
1077         }
1078       }
1079     } else {
1080       // FIXME: Should not be relying on memoperands.
1081       // Look at the source operands of every instruction to see if
1082       // any of them results from a previous memory operation that affects
1083       // its current usage. If so, an s_waitcnt instruction needs to be
1084       // emitted.
1085       // If the source operand was defined by a load, add the s_waitcnt
1086       // instruction.
1087       //
1088       // Two cases are handled for destination operands:
1089       // 1) If the destination operand was defined by a load, add the s_waitcnt
1090       // instruction to guarantee the right WAW order.
1091       // 2) If a destination operand that was used by a recent export/store ins,
1092       // add s_waitcnt on exp_cnt to guarantee the WAR order.
1093       for (const MachineMemOperand *Memop : MI.memoperands()) {
1094         const Value *Ptr = Memop->getValue();
1095         if (Memop->isStore() && SLoadAddresses.count(Ptr)) {
1096           addWait(Wait, LGKM_CNT, 0);
1097           if (PDT->dominates(MI.getParent(), SLoadAddresses.find(Ptr)->second))
1098             SLoadAddresses.erase(Ptr);
1099         }
1100         unsigned AS = Memop->getAddrSpace();
1101         if (AS != AMDGPUAS::LOCAL_ADDRESS && AS != AMDGPUAS::FLAT_ADDRESS)
1102           continue;
1103         // No need to wait before load from VMEM to LDS.
1104         if (mayWriteLDSThroughDMA(MI))
1105           continue;
1106         unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
1107         // VM_CNT is only relevant to vgpr or LDS.
1108         ScoreBrackets.determineWait(
1109             VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
1110         if (Memop->isStore()) {
1111           ScoreBrackets.determineWait(
1112               EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
1113         }
1114       }
1115 
1116       // Loop over use and def operands.
1117       for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1118         MachineOperand &Op = MI.getOperand(I);
1119         if (!Op.isReg())
1120           continue;
1121         RegInterval Interval =
1122             ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, I);
1123 
1124         const bool IsVGPR = TRI->isVectorRegister(*MRI, Op.getReg());
1125         for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1126           if (IsVGPR) {
1127             // RAW always needs an s_waitcnt. WAW needs an s_waitcnt unless the
1128             // previous write and this write are the same type of VMEM
1129             // instruction, in which case they're guaranteed to write their
1130             // results in order anyway.
1131             if (Op.isUse() || !SIInstrInfo::isVMEM(MI) ||
1132                 ScoreBrackets.hasOtherPendingVmemTypes(RegNo,
1133                                                        getVmemType(MI))) {
1134               ScoreBrackets.determineWait(
1135                   VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
1136               ScoreBrackets.clearVgprVmemTypes(RegNo);
1137             }
1138             if (Op.isDef()) {
1139               ScoreBrackets.determineWait(
1140                   EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
1141             }
1142           }
1143           ScoreBrackets.determineWait(
1144               LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
1145         }
1146       }
1147     }
1148   }
1149 
1150   // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0
1151   // occurs before the instruction. Doing it here prevents any additional
1152   // S_WAITCNTs from being emitted if the instruction was marked as
1153   // requiring a WAITCNT beforehand.
1154   if (MI.getOpcode() == AMDGPU::S_BARRIER &&
1155       !ST->hasAutoWaitcntBeforeBarrier()) {
1156     Wait = Wait.combined(AMDGPU::Waitcnt::allZero(ST->hasVscnt()));
1157   }
1158 
1159   // TODO: Remove this work-around, enable the assert for Bug 457939
1160   //       after fixing the scheduler. Also, the Shader Compiler code is
1161   //       independent of target.
1162   if (readsVCCZ(MI) && ST->hasReadVCCZBug()) {
1163     if (ScoreBrackets.getScoreLB(LGKM_CNT) <
1164             ScoreBrackets.getScoreUB(LGKM_CNT) &&
1165         ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
1166       Wait.LgkmCnt = 0;
1167     }
1168   }
1169 
1170   // Verify that the wait is actually needed.
1171   ScoreBrackets.simplifyWaitcnt(Wait);
1172 
1173   if (ForceEmitZeroWaitcnts)
1174     Wait = AMDGPU::Waitcnt::allZero(ST->hasVscnt());
1175 
1176   if (ForceEmitWaitcnt[VM_CNT])
1177     Wait.VmCnt = 0;
1178   if (ForceEmitWaitcnt[EXP_CNT])
1179     Wait.ExpCnt = 0;
1180   if (ForceEmitWaitcnt[LGKM_CNT])
1181     Wait.LgkmCnt = 0;
1182   if (ForceEmitWaitcnt[VS_CNT])
1183     Wait.VsCnt = 0;
1184 
1185   if (OldWaitcntInstr) {
1186     // Try to merge the required wait with preexisting waitcnt instructions.
1187     // Also erase redundant waitcnt.
1188     Modified =
1189         applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr, Wait, &MI);
1190   } else {
1191     // Update waitcnt brackets after determining the required wait.
1192     ScoreBrackets.applyWaitcnt(Wait);
1193   }
1194 
1195   // Build new waitcnt instructions unless no wait is needed or the old waitcnt
1196   // instruction was modified to handle the required wait.
1197   if (Wait.hasWaitExceptVsCnt()) {
1198     unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
1199     auto SWaitInst = BuildMI(*MI.getParent(), MI.getIterator(),
1200                              MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1201                          .addImm(Enc);
1202     TrackedWaitcntSet.insert(SWaitInst);
1203     Modified = true;
1204 
1205     LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
1206                       << "Old Instr: " << MI
1207                       << "New Instr: " << *SWaitInst << '\n');
1208   }
1209 
1210   if (Wait.hasWaitVsCnt()) {
1211     assert(ST->hasVscnt());
1212 
1213     auto SWaitInst =
1214         BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
1215                 TII->get(AMDGPU::S_WAITCNT_VSCNT))
1216             .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1217             .addImm(Wait.VsCnt);
1218     TrackedWaitcntSet.insert(SWaitInst);
1219     Modified = true;
1220 
1221     LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
1222                       << "Old Instr: " << MI
1223                       << "New Instr: " << *SWaitInst << '\n');
1224   }
1225 
1226   return Modified;
1227 }
1228 
1229 // This is a flat memory operation. Check to see if it has memory tokens other
1230 // than LDS. Other address spaces supported by flat memory operations involve
1231 // global memory.
1232 bool SIInsertWaitcnts::mayAccessVMEMThroughFlat(const MachineInstr &MI) const {
1233   assert(TII->isFLAT(MI));
1234 
1235   // All flat instructions use the VMEM counter.
1236   assert(TII->usesVM_CNT(MI));
1237 
1238   // If there are no memory operands then conservatively assume the flat
1239   // operation may access VMEM.
1240   if (MI.memoperands_empty())
1241     return true;
1242 
1243   // See if any memory operand specifies an address space that involves VMEM.
1244   // Flat operations only supported FLAT, LOCAL (LDS), or address spaces
1245   // involving VMEM such as GLOBAL, CONSTANT, PRIVATE (SCRATCH), etc. The REGION
1246   // (GDS) address space is not supported by flat operations. Therefore, simply
1247   // return true unless only the LDS address space is found.
1248   for (const MachineMemOperand *Memop : MI.memoperands()) {
1249     unsigned AS = Memop->getAddrSpace();
1250     assert(AS != AMDGPUAS::REGION_ADDRESS);
1251     if (AS != AMDGPUAS::LOCAL_ADDRESS)
1252       return true;
1253   }
1254 
1255   return false;
1256 }
1257 
1258 // This is a flat memory operation. Check to see if it has memory tokens for
1259 // either LDS or FLAT.
1260 bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
1261   assert(TII->isFLAT(MI));
1262 
1263   // Flat instruction such as SCRATCH and GLOBAL do not use the lgkm counter.
1264   if (!TII->usesLGKM_CNT(MI))
1265     return false;
1266 
1267   // If in tgsplit mode then there can be no use of LDS.
1268   if (ST->isTgSplitEnabled())
1269     return false;
1270 
1271   // If there are no memory operands then conservatively assume the flat
1272   // operation may access LDS.
1273   if (MI.memoperands_empty())
1274     return true;
1275 
1276   // See if any memory operand specifies an address space that involves LDS.
1277   for (const MachineMemOperand *Memop : MI.memoperands()) {
1278     unsigned AS = Memop->getAddrSpace();
1279     if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS)
1280       return true;
1281   }
1282 
1283   return false;
1284 }
1285 
1286 void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
1287                                                WaitcntBrackets *ScoreBrackets) {
1288   // Now look at the instruction opcode. If it is a memory access
1289   // instruction, update the upper-bound of the appropriate counter's
1290   // bracket and the destination operand scores.
1291   // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere.
1292   if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
1293     if (TII->isAlwaysGDS(Inst.getOpcode()) ||
1294         TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
1295       ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
1296       ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
1297     } else {
1298       ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1299     }
1300   } else if (TII->isFLAT(Inst)) {
1301     assert(Inst.mayLoadOrStore());
1302 
1303     int FlatASCount = 0;
1304 
1305     if (mayAccessVMEMThroughFlat(Inst)) {
1306       ++FlatASCount;
1307       if (!ST->hasVscnt())
1308         ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1309       else if (Inst.mayLoad() && !SIInstrInfo::isAtomicNoRet(Inst))
1310         ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1311       else
1312         ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1313     }
1314 
1315     if (mayAccessLDSThroughFlat(Inst)) {
1316       ++FlatASCount;
1317       ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1318     }
1319 
1320     // A Flat memory operation must access at least one address space.
1321     assert(FlatASCount);
1322 
1323     // This is a flat memory operation that access both VMEM and LDS, so note it
1324     // - it will require that both the VM and LGKM be flushed to zero if it is
1325     // pending when a VM or LGKM dependency occurs.
1326     if (FlatASCount > 1)
1327       ScoreBrackets->setPendingFlat();
1328   } else if (SIInstrInfo::isVMEM(Inst) &&
1329              !llvm::AMDGPU::getMUBUFIsBufferInv(Inst.getOpcode())) {
1330     if (!ST->hasVscnt())
1331       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1332     else if ((Inst.mayLoad() && !SIInstrInfo::isAtomicNoRet(Inst)) ||
1333              /* IMAGE_GET_RESINFO / IMAGE_GET_LOD */
1334              (TII->isMIMG(Inst) && !Inst.mayLoad() && !Inst.mayStore()))
1335       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1336     else if (Inst.mayStore())
1337       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1338 
1339     if (ST->vmemWriteNeedsExpWaitcnt() &&
1340         (Inst.mayStore() || SIInstrInfo::isAtomicRet(Inst))) {
1341       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
1342     }
1343   } else if (TII->isSMRD(Inst)) {
1344     ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1345   } else if (Inst.isCall()) {
1346     if (callWaitsOnFunctionReturn(Inst)) {
1347       // Act as a wait on everything
1348       ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt::allZero(ST->hasVscnt()));
1349     } else {
1350       // May need to way wait for anything.
1351       ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
1352     }
1353   } else if (SIInstrInfo::isEXP(Inst)) {
1354     unsigned Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
1355     if (Imm >= AMDGPU::Exp::ET_PARAM0 && Imm <= AMDGPU::Exp::ET_PARAM31)
1356       ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
1357     else if (Imm >= AMDGPU::Exp::ET_POS0 && Imm <= AMDGPU::Exp::ET_POS_LAST)
1358       ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
1359     else
1360       ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
1361   } else {
1362     switch (Inst.getOpcode()) {
1363     case AMDGPU::S_SENDMSG:
1364     case AMDGPU::S_SENDMSGHALT:
1365       ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
1366       break;
1367     case AMDGPU::S_MEMTIME:
1368     case AMDGPU::S_MEMREALTIME:
1369       ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1370       break;
1371     }
1372   }
1373 }
1374 
1375 bool WaitcntBrackets::mergeScore(const MergeInfo &M, unsigned &Score,
1376                                  unsigned OtherScore) {
1377   unsigned MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
1378   unsigned OtherShifted =
1379       OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
1380   Score = std::max(MyShifted, OtherShifted);
1381   return OtherShifted > MyShifted;
1382 }
1383 
1384 /// Merge the pending events and associater score brackets of \p Other into
1385 /// this brackets status.
1386 ///
1387 /// Returns whether the merge resulted in a change that requires tighter waits
1388 /// (i.e. the merged brackets strictly dominate the original brackets).
1389 bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
1390   bool StrictDom = false;
1391 
1392   VgprUB = std::max(VgprUB, Other.VgprUB);
1393   SgprUB = std::max(SgprUB, Other.SgprUB);
1394 
1395   for (auto T : inst_counter_types()) {
1396     // Merge event flags for this counter
1397     const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[T];
1398     const unsigned OtherEvents = Other.PendingEvents & WaitEventMaskForInst[T];
1399     if (OtherEvents & ~OldEvents)
1400       StrictDom = true;
1401     PendingEvents |= OtherEvents;
1402 
1403     // Merge scores for this counter
1404     const unsigned MyPending = ScoreUBs[T] - ScoreLBs[T];
1405     const unsigned OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
1406     const unsigned NewUB = ScoreLBs[T] + std::max(MyPending, OtherPending);
1407     if (NewUB < ScoreLBs[T])
1408       report_fatal_error("waitcnt score overflow");
1409 
1410     MergeInfo M;
1411     M.OldLB = ScoreLBs[T];
1412     M.OtherLB = Other.ScoreLBs[T];
1413     M.MyShift = NewUB - ScoreUBs[T];
1414     M.OtherShift = NewUB - Other.ScoreUBs[T];
1415 
1416     ScoreUBs[T] = NewUB;
1417 
1418     StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]);
1419 
1420     bool RegStrictDom = false;
1421     for (int J = 0; J <= VgprUB; J++) {
1422       RegStrictDom |= mergeScore(M, VgprScores[T][J], Other.VgprScores[T][J]);
1423     }
1424 
1425     if (T == VM_CNT) {
1426       for (int J = 0; J <= VgprUB; J++) {
1427         unsigned char NewVmemTypes = VgprVmemTypes[J] | Other.VgprVmemTypes[J];
1428         RegStrictDom |= NewVmemTypes != VgprVmemTypes[J];
1429         VgprVmemTypes[J] = NewVmemTypes;
1430       }
1431     }
1432 
1433     if (T == LGKM_CNT) {
1434       for (int J = 0; J <= SgprUB; J++) {
1435         RegStrictDom |= mergeScore(M, SgprScores[J], Other.SgprScores[J]);
1436       }
1437     }
1438 
1439     if (RegStrictDom)
1440       StrictDom = true;
1441   }
1442 
1443   return StrictDom;
1444 }
1445 
1446 // Generate s_waitcnt instructions where needed.
1447 bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
1448                                             MachineBasicBlock &Block,
1449                                             WaitcntBrackets &ScoreBrackets) {
1450   bool Modified = false;
1451 
1452   LLVM_DEBUG({
1453     dbgs() << "*** Block" << Block.getNumber() << " ***";
1454     ScoreBrackets.dump();
1455   });
1456 
1457   // Track the correctness of vccz through this basic block. There are two
1458   // reasons why it might be incorrect; see ST->hasReadVCCZBug() and
1459   // ST->partialVCCWritesUpdateVCCZ().
1460   bool VCCZCorrect = true;
1461   if (ST->hasReadVCCZBug()) {
1462     // vccz could be incorrect at a basic block boundary if a predecessor wrote
1463     // to vcc and then issued an smem load.
1464     VCCZCorrect = false;
1465   } else if (!ST->partialVCCWritesUpdateVCCZ()) {
1466     // vccz could be incorrect at a basic block boundary if a predecessor wrote
1467     // to vcc_lo or vcc_hi.
1468     VCCZCorrect = false;
1469   }
1470 
1471   // Walk over the instructions.
1472   MachineInstr *OldWaitcntInstr = nullptr;
1473 
1474   for (MachineBasicBlock::instr_iterator Iter = Block.instr_begin(),
1475                                          E = Block.instr_end();
1476        Iter != E;) {
1477     MachineInstr &Inst = *Iter;
1478 
1479     // Track pre-existing waitcnts that were added in earlier iterations or by
1480     // the memory legalizer.
1481     if (Inst.getOpcode() == AMDGPU::S_WAITCNT ||
1482         (Inst.getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1483          Inst.getOperand(0).isReg() &&
1484          Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL)) {
1485       if (!OldWaitcntInstr)
1486         OldWaitcntInstr = &Inst;
1487       ++Iter;
1488       continue;
1489     }
1490 
1491     // Generate an s_waitcnt instruction to be placed before Inst, if needed.
1492     Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr);
1493     OldWaitcntInstr = nullptr;
1494 
1495     // Restore vccz if it's not known to be correct already.
1496     bool RestoreVCCZ = !VCCZCorrect && readsVCCZ(Inst);
1497 
1498     // Don't examine operands unless we need to track vccz correctness.
1499     if (ST->hasReadVCCZBug() || !ST->partialVCCWritesUpdateVCCZ()) {
1500       if (Inst.definesRegister(AMDGPU::VCC_LO) ||
1501           Inst.definesRegister(AMDGPU::VCC_HI)) {
1502         // Up to gfx9, writes to vcc_lo and vcc_hi don't update vccz.
1503         if (!ST->partialVCCWritesUpdateVCCZ())
1504           VCCZCorrect = false;
1505       } else if (Inst.definesRegister(AMDGPU::VCC)) {
1506         // There is a hardware bug on CI/SI where SMRD instruction may corrupt
1507         // vccz bit, so when we detect that an instruction may read from a
1508         // corrupt vccz bit, we need to:
1509         // 1. Insert s_waitcnt lgkm(0) to wait for all outstanding SMRD
1510         //    operations to complete.
1511         // 2. Restore the correct value of vccz by writing the current value
1512         //    of vcc back to vcc.
1513         if (ST->hasReadVCCZBug() &&
1514             ScoreBrackets.getScoreLB(LGKM_CNT) <
1515                 ScoreBrackets.getScoreUB(LGKM_CNT) &&
1516             ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
1517           // Writes to vcc while there's an outstanding smem read may get
1518           // clobbered as soon as any read completes.
1519           VCCZCorrect = false;
1520         } else {
1521           // Writes to vcc will fix any incorrect value in vccz.
1522           VCCZCorrect = true;
1523         }
1524       }
1525     }
1526 
1527     if (TII->isSMRD(Inst)) {
1528       for (const MachineMemOperand *Memop : Inst.memoperands()) {
1529         // No need to handle invariant loads when avoiding WAR conflicts, as
1530         // there cannot be a vector store to the same memory location.
1531         if (!Memop->isInvariant()) {
1532           const Value *Ptr = Memop->getValue();
1533           SLoadAddresses.insert(std::make_pair(Ptr, Inst.getParent()));
1534         }
1535       }
1536       if (ST->hasReadVCCZBug()) {
1537         // This smem read could complete and clobber vccz at any time.
1538         VCCZCorrect = false;
1539       }
1540     }
1541 
1542     updateEventWaitcntAfter(Inst, &ScoreBrackets);
1543 
1544 #if 0 // TODO: implement resource type check controlled by options with ub = LB.
1545     // If this instruction generates a S_SETVSKIP because it is an
1546     // indexed resource, and we are on Tahiti, then it will also force
1547     // an S_WAITCNT vmcnt(0)
1548     if (RequireCheckResourceType(Inst, context)) {
1549       // Force the score to as if an S_WAITCNT vmcnt(0) is emitted.
1550       ScoreBrackets->setScoreLB(VM_CNT,
1551       ScoreBrackets->getScoreUB(VM_CNT));
1552     }
1553 #endif
1554 
1555     LLVM_DEBUG({
1556       Inst.print(dbgs());
1557       ScoreBrackets.dump();
1558     });
1559 
1560     // TODO: Remove this work-around after fixing the scheduler and enable the
1561     // assert above.
1562     if (RestoreVCCZ) {
1563       // Restore the vccz bit.  Any time a value is written to vcc, the vcc
1564       // bit is updated, so we can restore the bit by reading the value of
1565       // vcc and then writing it back to the register.
1566       BuildMI(Block, Inst, Inst.getDebugLoc(),
1567               TII->get(ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
1568               TRI->getVCC())
1569           .addReg(TRI->getVCC());
1570       VCCZCorrect = true;
1571       Modified = true;
1572     }
1573 
1574     ++Iter;
1575   }
1576 
1577   return Modified;
1578 }
1579 
1580 bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) {
1581   ST = &MF.getSubtarget<GCNSubtarget>();
1582   TII = ST->getInstrInfo();
1583   TRI = &TII->getRegisterInfo();
1584   MRI = &MF.getRegInfo();
1585   IV = AMDGPU::getIsaVersion(ST->getCPU());
1586   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1587   PDT = &getAnalysis<MachinePostDominatorTree>();
1588 
1589   ForceEmitZeroWaitcnts = ForceEmitZeroFlag;
1590   for (auto T : inst_counter_types())
1591     ForceEmitWaitcnt[T] = false;
1592 
1593   HardwareLimits Limits = {};
1594   Limits.VmcntMax = AMDGPU::getVmcntBitMask(IV);
1595   Limits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
1596   Limits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV);
1597   Limits.VscntMax = ST->hasVscnt() ? 63 : 0;
1598 
1599   unsigned NumVGPRsMax = ST->getAddressableNumVGPRs();
1600   unsigned NumSGPRsMax = ST->getAddressableNumSGPRs();
1601   assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
1602   assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
1603 
1604   RegisterEncoding Encoding = {};
1605   Encoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0);
1606   Encoding.VGPRL = Encoding.VGPR0 + NumVGPRsMax - 1;
1607   Encoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0);
1608   Encoding.SGPRL = Encoding.SGPR0 + NumSGPRsMax - 1;
1609 
1610   TrackedWaitcntSet.clear();
1611   BlockInfos.clear();
1612   bool Modified = false;
1613 
1614   if (!MFI->isEntryFunction()) {
1615     // Wait for any outstanding memory operations that the input registers may
1616     // depend on. We can't track them and it's better to do the wait after the
1617     // costly call sequence.
1618 
1619     // TODO: Could insert earlier and schedule more liberally with operations
1620     // that only use caller preserved registers.
1621     MachineBasicBlock &EntryBB = MF.front();
1622     MachineBasicBlock::iterator I = EntryBB.begin();
1623     for (MachineBasicBlock::iterator E = EntryBB.end();
1624          I != E && (I->isPHI() || I->isMetaInstruction()); ++I)
1625       ;
1626     BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT)).addImm(0);
1627     if (ST->hasVscnt())
1628       BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT_VSCNT))
1629           .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1630           .addImm(0);
1631 
1632     Modified = true;
1633   }
1634 
1635   // Keep iterating over the blocks in reverse post order, inserting and
1636   // updating s_waitcnt where needed, until a fix point is reached.
1637   for (auto *MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
1638     BlockInfos.insert({MBB, BlockInfo(MBB)});
1639 
1640   std::unique_ptr<WaitcntBrackets> Brackets;
1641   bool Repeat;
1642   do {
1643     Repeat = false;
1644 
1645     for (auto BII = BlockInfos.begin(), BIE = BlockInfos.end(); BII != BIE;
1646          ++BII) {
1647       BlockInfo &BI = BII->second;
1648       if (!BI.Dirty)
1649         continue;
1650 
1651       if (BI.Incoming) {
1652         if (!Brackets)
1653           Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
1654         else
1655           *Brackets = *BI.Incoming;
1656       } else {
1657         if (!Brackets)
1658           Brackets = std::make_unique<WaitcntBrackets>(ST, Limits, Encoding);
1659         else
1660           *Brackets = WaitcntBrackets(ST, Limits, Encoding);
1661       }
1662 
1663       Modified |= insertWaitcntInBlock(MF, *BI.MBB, *Brackets);
1664       BI.Dirty = false;
1665 
1666       if (Brackets->hasPending()) {
1667         BlockInfo *MoveBracketsToSucc = nullptr;
1668         for (MachineBasicBlock *Succ : BI.MBB->successors()) {
1669           auto SuccBII = BlockInfos.find(Succ);
1670           BlockInfo &SuccBI = SuccBII->second;
1671           if (!SuccBI.Incoming) {
1672             SuccBI.Dirty = true;
1673             if (SuccBII <= BII)
1674               Repeat = true;
1675             if (!MoveBracketsToSucc) {
1676               MoveBracketsToSucc = &SuccBI;
1677             } else {
1678               SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
1679             }
1680           } else if (SuccBI.Incoming->merge(*Brackets)) {
1681             SuccBI.Dirty = true;
1682             if (SuccBII <= BII)
1683               Repeat = true;
1684           }
1685         }
1686         if (MoveBracketsToSucc)
1687           MoveBracketsToSucc->Incoming = std::move(Brackets);
1688       }
1689     }
1690   } while (Repeat);
1691 
1692   if (ST->hasScalarStores()) {
1693     SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
1694     bool HaveScalarStores = false;
1695 
1696     for (MachineBasicBlock &MBB : MF) {
1697       for (MachineInstr &MI : MBB) {
1698         if (!HaveScalarStores && TII->isScalarStore(MI))
1699           HaveScalarStores = true;
1700 
1701         if (MI.getOpcode() == AMDGPU::S_ENDPGM ||
1702             MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
1703           EndPgmBlocks.push_back(&MBB);
1704       }
1705     }
1706 
1707     if (HaveScalarStores) {
1708       // If scalar writes are used, the cache must be flushed or else the next
1709       // wave to reuse the same scratch memory can be clobbered.
1710       //
1711       // Insert s_dcache_wb at wave termination points if there were any scalar
1712       // stores, and only if the cache hasn't already been flushed. This could
1713       // be improved by looking across blocks for flushes in postdominating
1714       // blocks from the stores but an explicitly requested flush is probably
1715       // very rare.
1716       for (MachineBasicBlock *MBB : EndPgmBlocks) {
1717         bool SeenDCacheWB = false;
1718 
1719         for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
1720              I != E; ++I) {
1721           if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
1722             SeenDCacheWB = true;
1723           else if (TII->isScalarStore(*I))
1724             SeenDCacheWB = false;
1725 
1726           // FIXME: It would be better to insert this before a waitcnt if any.
1727           if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
1728                I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
1729               !SeenDCacheWB) {
1730             Modified = true;
1731             BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
1732           }
1733         }
1734       }
1735     }
1736   }
1737 
1738   return Modified;
1739 }
1740