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