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