1 //===- SIInsertWaitcnts.cpp - Insert Wait Instructions --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// Insert wait instructions for memory reads and writes.
12 ///
13 /// Memory reads and writes are issued asynchronously, so we need to insert
14 /// S_WAITCNT instructions when we want to access any of their results or
15 /// overwrite any register that's used asynchronously.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "AMDGPU.h"
20 #include "AMDGPUSubtarget.h"
21 #include "SIDefines.h"
22 #include "SIInstrInfo.h"
23 #include "SIMachineFunctionInfo.h"
24 #include "SIRegisterInfo.h"
25 #include "Utils/AMDGPUBaseInfo.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/PostOrderIterator.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineLoopInfo.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/MachineOperand.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/IR/DebugLoc.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/DebugCounter.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include <algorithm>
47 #include <cassert>
48 #include <cstdint>
49 #include <cstring>
50 #include <memory>
51 #include <utility>
52 #include <vector>
53 
54 using namespace llvm;
55 
56 #define DEBUG_TYPE "si-insert-waitcnts"
57 
58 DEBUG_COUNTER(ForceExpCounter, DEBUG_TYPE"-forceexp",
59               "Force emit s_waitcnt expcnt(0) instrs");
60 DEBUG_COUNTER(ForceLgkmCounter, DEBUG_TYPE"-forcelgkm",
61               "Force emit s_waitcnt lgkmcnt(0) instrs");
62 DEBUG_COUNTER(ForceVMCounter, DEBUG_TYPE"-forcevm",
63               "Force emit s_waitcnt vmcnt(0) instrs");
64 
65 static cl::opt<unsigned> ForceEmitZeroFlag(
66   "amdgpu-waitcnt-forcezero",
67   cl::desc("Force all waitcnt instrs to be emitted as s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
68   cl::init(0), cl::Hidden);
69 
70 namespace {
71 
72 // Class of object that encapsulates latest instruction counter score
73 // associated with the operand.  Used for determining whether
74 // s_waitcnt instruction needs to be emited.
75 
76 #define CNT_MASK(t) (1u << (t))
77 
78 enum InstCounterType { VM_CNT = 0, LGKM_CNT, EXP_CNT, NUM_INST_CNTS };
79 
80 using RegInterval = std::pair<signed, signed>;
81 
82 struct {
83   int32_t VmcntMax;
84   int32_t ExpcntMax;
85   int32_t LgkmcntMax;
86   int32_t NumVGPRsMax;
87   int32_t NumSGPRsMax;
88 } HardwareLimits;
89 
90 struct {
91   unsigned VGPR0;
92   unsigned VGPRL;
93   unsigned SGPR0;
94   unsigned SGPRL;
95 } RegisterEncoding;
96 
97 enum WaitEventType {
98   VMEM_ACCESS,      // vector-memory read & write
99   LDS_ACCESS,       // lds read & write
100   GDS_ACCESS,       // gds read & write
101   SQ_MESSAGE,       // send message
102   SMEM_ACCESS,      // scalar-memory read & write
103   EXP_GPR_LOCK,     // export holding on its data src
104   GDS_GPR_LOCK,     // GDS holding on its data and addr src
105   EXP_POS_ACCESS,   // write to export position
106   EXP_PARAM_ACCESS, // write to export parameter
107   VMW_GPR_LOCK,     // vector-memory write holding on its data src
108   NUM_WAIT_EVENTS,
109 };
110 
111 // The mapping is:
112 //  0                .. SQ_MAX_PGM_VGPRS-1               real VGPRs
113 //  SQ_MAX_PGM_VGPRS .. NUM_ALL_VGPRS-1                  extra VGPR-like slots
114 //  NUM_ALL_VGPRS    .. NUM_ALL_VGPRS+SQ_MAX_PGM_SGPRS-1 real SGPRs
115 // We reserve a fixed number of VGPR slots in the scoring tables for
116 // special tokens like SCMEM_LDS (needed for buffer load to LDS).
117 enum RegisterMapping {
118   SQ_MAX_PGM_VGPRS = 256, // Maximum programmable VGPRs across all targets.
119   SQ_MAX_PGM_SGPRS = 256, // Maximum programmable SGPRs across all targets.
120   NUM_EXTRA_VGPRS = 1,    // A reserved slot for DS.
121   EXTRA_VGPR_LDS = 0,     // This is a placeholder the Shader algorithm uses.
122   NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_EXTRA_VGPRS, // Where SGPR starts.
123 };
124 
125 #define ForAllWaitEventType(w)                                                 \
126   for (enum WaitEventType w = (enum WaitEventType)0;                           \
127        (w) < (enum WaitEventType)NUM_WAIT_EVENTS;                              \
128        (w) = (enum WaitEventType)((w) + 1))
129 
130 // This is a per-basic-block object that maintains current score brackets
131 // of each wait counter, and a per-register scoreboard for each wait counter.
132 // We also maintain the latest score for every event type that can change the
133 // waitcnt in order to know if there are multiple types of events within
134 // the brackets. When multiple types of event happen in the bracket,
135 // wait count may get decreased out of order, therefore we need to put in
136 // "s_waitcnt 0" before use.
137 class BlockWaitcntBrackets {
138 public:
139   BlockWaitcntBrackets() {
140     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
141          T = (enum InstCounterType)(T + 1)) {
142       memset(VgprScores[T], 0, sizeof(VgprScores[T]));
143     }
144   }
145 
146   ~BlockWaitcntBrackets() = default;
147 
148   static int32_t getWaitCountMax(InstCounterType T) {
149     switch (T) {
150     case VM_CNT:
151       return HardwareLimits.VmcntMax;
152     case LGKM_CNT:
153       return HardwareLimits.LgkmcntMax;
154     case EXP_CNT:
155       return HardwareLimits.ExpcntMax;
156     default:
157       break;
158     }
159     return 0;
160   }
161 
162   void setScoreLB(InstCounterType T, int32_t Val) {
163     assert(T < NUM_INST_CNTS);
164     if (T >= NUM_INST_CNTS)
165       return;
166     ScoreLBs[T] = Val;
167   }
168 
169   void setScoreUB(InstCounterType T, int32_t Val) {
170     assert(T < NUM_INST_CNTS);
171     if (T >= NUM_INST_CNTS)
172       return;
173     ScoreUBs[T] = Val;
174     if (T == EXP_CNT) {
175       int32_t UB = (int)(ScoreUBs[T] - getWaitCountMax(EXP_CNT));
176       if (ScoreLBs[T] < UB)
177         ScoreLBs[T] = UB;
178     }
179   }
180 
181   int32_t getScoreLB(InstCounterType T) {
182     assert(T < NUM_INST_CNTS);
183     if (T >= NUM_INST_CNTS)
184       return 0;
185     return ScoreLBs[T];
186   }
187 
188   int32_t getScoreUB(InstCounterType T) {
189     assert(T < NUM_INST_CNTS);
190     if (T >= NUM_INST_CNTS)
191       return 0;
192     return ScoreUBs[T];
193   }
194 
195   // Mapping from event to counter.
196   InstCounterType eventCounter(WaitEventType E) {
197     switch (E) {
198     case VMEM_ACCESS:
199       return VM_CNT;
200     case LDS_ACCESS:
201     case GDS_ACCESS:
202     case SQ_MESSAGE:
203     case SMEM_ACCESS:
204       return LGKM_CNT;
205     case EXP_GPR_LOCK:
206     case GDS_GPR_LOCK:
207     case VMW_GPR_LOCK:
208     case EXP_POS_ACCESS:
209     case EXP_PARAM_ACCESS:
210       return EXP_CNT;
211     default:
212       llvm_unreachable("unhandled event type");
213     }
214     return NUM_INST_CNTS;
215   }
216 
217   void setRegScore(int GprNo, InstCounterType T, int32_t Val) {
218     if (GprNo < NUM_ALL_VGPRS) {
219       if (GprNo > VgprUB) {
220         VgprUB = GprNo;
221       }
222       VgprScores[T][GprNo] = Val;
223     } else {
224       assert(T == LGKM_CNT);
225       if (GprNo - NUM_ALL_VGPRS > SgprUB) {
226         SgprUB = GprNo - NUM_ALL_VGPRS;
227       }
228       SgprScores[GprNo - NUM_ALL_VGPRS] = Val;
229     }
230   }
231 
232   int32_t getRegScore(int GprNo, InstCounterType T) {
233     if (GprNo < NUM_ALL_VGPRS) {
234       return VgprScores[T][GprNo];
235     }
236     return SgprScores[GprNo - NUM_ALL_VGPRS];
237   }
238 
239   void clear() {
240     memset(ScoreLBs, 0, sizeof(ScoreLBs));
241     memset(ScoreUBs, 0, sizeof(ScoreUBs));
242     memset(EventUBs, 0, sizeof(EventUBs));
243     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
244          T = (enum InstCounterType)(T + 1)) {
245       memset(VgprScores[T], 0, sizeof(VgprScores[T]));
246     }
247     memset(SgprScores, 0, sizeof(SgprScores));
248   }
249 
250   RegInterval getRegInterval(const MachineInstr *MI, const SIInstrInfo *TII,
251                              const MachineRegisterInfo *MRI,
252                              const SIRegisterInfo *TRI, unsigned OpNo,
253                              bool Def) const;
254 
255   void setExpScore(const MachineInstr *MI, const SIInstrInfo *TII,
256                    const SIRegisterInfo *TRI, const MachineRegisterInfo *MRI,
257                    unsigned OpNo, int32_t Val);
258 
259   void setWaitAtBeginning() { WaitAtBeginning = true; }
260   void clearWaitAtBeginning() { WaitAtBeginning = false; }
261   bool getWaitAtBeginning() const { return WaitAtBeginning; }
262   void setEventUB(enum WaitEventType W, int32_t Val) { EventUBs[W] = Val; }
263   int32_t getMaxVGPR() const { return VgprUB; }
264   int32_t getMaxSGPR() const { return SgprUB; }
265 
266   int32_t getEventUB(enum WaitEventType W) const {
267     assert(W < NUM_WAIT_EVENTS);
268     return EventUBs[W];
269   }
270 
271   bool counterOutOfOrder(InstCounterType T);
272   unsigned int updateByWait(InstCounterType T, int ScoreToWait);
273   void updateByEvent(const SIInstrInfo *TII, const SIRegisterInfo *TRI,
274                      const MachineRegisterInfo *MRI, WaitEventType E,
275                      MachineInstr &MI);
276 
277   bool hasPendingSMEM() const {
278     return (EventUBs[SMEM_ACCESS] > ScoreLBs[LGKM_CNT] &&
279             EventUBs[SMEM_ACCESS] <= ScoreUBs[LGKM_CNT]);
280   }
281 
282   bool hasPendingFlat() const {
283     return ((LastFlat[LGKM_CNT] > ScoreLBs[LGKM_CNT] &&
284              LastFlat[LGKM_CNT] <= ScoreUBs[LGKM_CNT]) ||
285             (LastFlat[VM_CNT] > ScoreLBs[VM_CNT] &&
286              LastFlat[VM_CNT] <= ScoreUBs[VM_CNT]));
287   }
288 
289   void setPendingFlat() {
290     LastFlat[VM_CNT] = ScoreUBs[VM_CNT];
291     LastFlat[LGKM_CNT] = ScoreUBs[LGKM_CNT];
292   }
293 
294   int pendingFlat(InstCounterType Ct) const { return LastFlat[Ct]; }
295 
296   void setLastFlat(InstCounterType Ct, int Val) { LastFlat[Ct] = Val; }
297 
298   bool getRevisitLoop() const { return RevisitLoop; }
299   void setRevisitLoop(bool RevisitLoopIn) { RevisitLoop = RevisitLoopIn; }
300 
301   void setPostOrder(int32_t PostOrderIn) { PostOrder = PostOrderIn; }
302   int32_t getPostOrder() const { return PostOrder; }
303 
304   void setWaitcnt(MachineInstr *WaitcntIn) { Waitcnt = WaitcntIn; }
305   void clearWaitcnt() { Waitcnt = nullptr; }
306   MachineInstr *getWaitcnt() const { return Waitcnt; }
307 
308   bool mixedExpTypes() const { return MixedExpTypes; }
309   void setMixedExpTypes(bool MixedExpTypesIn) {
310     MixedExpTypes = MixedExpTypesIn;
311   }
312 
313   void print(raw_ostream &);
314   void dump() { print(dbgs()); }
315 
316 private:
317   bool WaitAtBeginning = false;
318   bool RevisitLoop = false;
319   bool MixedExpTypes = false;
320   int32_t PostOrder = 0;
321   MachineInstr *Waitcnt = nullptr;
322   int32_t ScoreLBs[NUM_INST_CNTS] = {0};
323   int32_t ScoreUBs[NUM_INST_CNTS] = {0};
324   int32_t EventUBs[NUM_WAIT_EVENTS] = {0};
325   // Remember the last flat memory operation.
326   int32_t LastFlat[NUM_INST_CNTS] = {0};
327   // wait_cnt scores for every vgpr.
328   // Keep track of the VgprUB and SgprUB to make merge at join efficient.
329   int32_t VgprUB = 0;
330   int32_t SgprUB = 0;
331   int32_t VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS];
332   // Wait cnt scores for every sgpr, only lgkmcnt is relevant.
333   int32_t SgprScores[SQ_MAX_PGM_SGPRS] = {0};
334 };
335 
336 // This is a per-loop-region object that records waitcnt status at the end of
337 // loop footer from the previous iteration. We also maintain an iteration
338 // count to track the number of times the loop has been visited. When it
339 // doesn't converge naturally, we force convergence by inserting s_waitcnt 0
340 // at the end of the loop footer.
341 class LoopWaitcntData {
342 public:
343   LoopWaitcntData() = default;
344   ~LoopWaitcntData() = default;
345 
346   void incIterCnt() { IterCnt++; }
347   void resetIterCnt() { IterCnt = 0; }
348   unsigned getIterCnt() { return IterCnt; }
349 
350   void setWaitcnt(MachineInstr *WaitcntIn) { LfWaitcnt = WaitcntIn; }
351   MachineInstr *getWaitcnt() const { return LfWaitcnt; }
352 
353   void print() { LLVM_DEBUG(dbgs() << "  iteration " << IterCnt << '\n';); }
354 
355 private:
356   // s_waitcnt added at the end of loop footer to stablize wait scores
357   // at the end of the loop footer.
358   MachineInstr *LfWaitcnt = nullptr;
359   // Number of iterations the loop has been visited, not including the initial
360   // walk over.
361   int32_t IterCnt = 0;
362 };
363 
364 class SIInsertWaitcnts : public MachineFunctionPass {
365 private:
366   const SISubtarget *ST = nullptr;
367   const SIInstrInfo *TII = nullptr;
368   const SIRegisterInfo *TRI = nullptr;
369   const MachineRegisterInfo *MRI = nullptr;
370   const MachineLoopInfo *MLI = nullptr;
371   AMDGPU::IsaInfo::IsaVersion IV;
372   AMDGPUAS AMDGPUASI;
373 
374   DenseSet<MachineBasicBlock *> BlockVisitedSet;
375   DenseSet<MachineInstr *> TrackedWaitcntSet;
376   DenseSet<MachineInstr *> VCCZBugHandledSet;
377 
378   DenseMap<MachineBasicBlock *, std::unique_ptr<BlockWaitcntBrackets>>
379       BlockWaitcntBracketsMap;
380 
381   std::vector<MachineBasicBlock *> BlockWaitcntProcessedSet;
382 
383   DenseMap<MachineLoop *, std::unique_ptr<LoopWaitcntData>> LoopWaitcntDataMap;
384 
385   std::vector<std::unique_ptr<BlockWaitcntBrackets>> KillWaitBrackets;
386 
387   // ForceEmitZeroWaitcnts: force all waitcnts insts to be s_waitcnt 0
388   // because of amdgpu-waitcnt-forcezero flag
389   bool ForceEmitZeroWaitcnts;
390   bool ForceEmitWaitcnt[NUM_INST_CNTS];
391 
392 public:
393   static char ID;
394 
395   SIInsertWaitcnts() : MachineFunctionPass(ID) {}
396 
397   bool runOnMachineFunction(MachineFunction &MF) override;
398 
399   StringRef getPassName() const override {
400     return "SI insert wait instructions";
401   }
402 
403   void getAnalysisUsage(AnalysisUsage &AU) const override {
404     AU.setPreservesCFG();
405     AU.addRequired<MachineLoopInfo>();
406     MachineFunctionPass::getAnalysisUsage(AU);
407   }
408 
409   void addKillWaitBracket(BlockWaitcntBrackets *Bracket) {
410     // The waitcnt information is copied because it changes as the block is
411     // traversed.
412     KillWaitBrackets.push_back(
413         llvm::make_unique<BlockWaitcntBrackets>(*Bracket));
414   }
415 
416   bool isForceEmitWaitcnt() const {
417     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
418          T = (enum InstCounterType)(T + 1))
419       if (ForceEmitWaitcnt[T])
420         return true;
421     return false;
422   }
423 
424   void setForceEmitWaitcnt() {
425 // For non-debug builds, ForceEmitWaitcnt has been initialized to false;
426 // For debug builds, get the debug counter info and adjust if need be
427 #ifndef NDEBUG
428     if (DebugCounter::isCounterSet(ForceExpCounter) &&
429         DebugCounter::shouldExecute(ForceExpCounter)) {
430       ForceEmitWaitcnt[EXP_CNT] = true;
431     } else {
432       ForceEmitWaitcnt[EXP_CNT] = false;
433     }
434 
435     if (DebugCounter::isCounterSet(ForceLgkmCounter) &&
436          DebugCounter::shouldExecute(ForceLgkmCounter)) {
437       ForceEmitWaitcnt[LGKM_CNT] = true;
438     } else {
439       ForceEmitWaitcnt[LGKM_CNT] = false;
440     }
441 
442     if (DebugCounter::isCounterSet(ForceVMCounter) &&
443         DebugCounter::shouldExecute(ForceVMCounter)) {
444       ForceEmitWaitcnt[VM_CNT] = true;
445     } else {
446       ForceEmitWaitcnt[VM_CNT] = false;
447     }
448 #endif // NDEBUG
449   }
450 
451   bool mayAccessLDSThroughFlat(const MachineInstr &MI) const;
452   void generateWaitcntInstBefore(MachineInstr &MI,
453                                   BlockWaitcntBrackets *ScoreBrackets);
454   void updateEventWaitcntAfter(MachineInstr &Inst,
455                                BlockWaitcntBrackets *ScoreBrackets);
456   void mergeInputScoreBrackets(MachineBasicBlock &Block);
457   bool isLoopBottom(const MachineLoop *Loop, const MachineBasicBlock *Block);
458   unsigned countNumBottomBlocks(const MachineLoop *Loop);
459   void insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block);
460   void insertWaitcntBeforeCF(MachineBasicBlock &Block, MachineInstr *Inst);
461   bool isWaitcntStronger(unsigned LHS, unsigned RHS);
462   unsigned combineWaitcnt(unsigned LHS, unsigned RHS);
463 };
464 
465 } // end anonymous namespace
466 
467 RegInterval BlockWaitcntBrackets::getRegInterval(const MachineInstr *MI,
468                                                  const SIInstrInfo *TII,
469                                                  const MachineRegisterInfo *MRI,
470                                                  const SIRegisterInfo *TRI,
471                                                  unsigned OpNo,
472                                                  bool Def) const {
473   const MachineOperand &Op = MI->getOperand(OpNo);
474   if (!Op.isReg() || !TRI->isInAllocatableClass(Op.getReg()) ||
475       (Def && !Op.isDef()))
476     return {-1, -1};
477 
478   // A use via a PW operand does not need a waitcnt.
479   // A partial write is not a WAW.
480   assert(!Op.getSubReg() || !Op.isUndef());
481 
482   RegInterval Result;
483   const MachineRegisterInfo &MRIA = *MRI;
484 
485   unsigned Reg = TRI->getEncodingValue(Op.getReg());
486 
487   if (TRI->isVGPR(MRIA, Op.getReg())) {
488     assert(Reg >= RegisterEncoding.VGPR0 && Reg <= RegisterEncoding.VGPRL);
489     Result.first = Reg - RegisterEncoding.VGPR0;
490     assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS);
491   } else if (TRI->isSGPRReg(MRIA, Op.getReg())) {
492     assert(Reg >= RegisterEncoding.SGPR0 && Reg < SQ_MAX_PGM_SGPRS);
493     Result.first = Reg - RegisterEncoding.SGPR0 + NUM_ALL_VGPRS;
494     assert(Result.first >= NUM_ALL_VGPRS &&
495            Result.first < SQ_MAX_PGM_SGPRS + NUM_ALL_VGPRS);
496   }
497   // TODO: Handle TTMP
498   // else if (TRI->isTTMP(MRIA, Reg.getReg())) ...
499   else
500     return {-1, -1};
501 
502   const MachineInstr &MIA = *MI;
503   const TargetRegisterClass *RC = TII->getOpRegClass(MIA, OpNo);
504   unsigned Size = TRI->getRegSizeInBits(*RC);
505   Result.second = Result.first + (Size / 32);
506 
507   return Result;
508 }
509 
510 void BlockWaitcntBrackets::setExpScore(const MachineInstr *MI,
511                                        const SIInstrInfo *TII,
512                                        const SIRegisterInfo *TRI,
513                                        const MachineRegisterInfo *MRI,
514                                        unsigned OpNo, int32_t Val) {
515   RegInterval Interval = getRegInterval(MI, TII, MRI, TRI, OpNo, false);
516   LLVM_DEBUG({
517     const MachineOperand &Opnd = MI->getOperand(OpNo);
518     assert(TRI->isVGPR(*MRI, Opnd.getReg()));
519   });
520   for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
521     setRegScore(RegNo, EXP_CNT, Val);
522   }
523 }
524 
525 void BlockWaitcntBrackets::updateByEvent(const SIInstrInfo *TII,
526                                          const SIRegisterInfo *TRI,
527                                          const MachineRegisterInfo *MRI,
528                                          WaitEventType E, MachineInstr &Inst) {
529   const MachineRegisterInfo &MRIA = *MRI;
530   InstCounterType T = eventCounter(E);
531   int32_t CurrScore = getScoreUB(T) + 1;
532   // EventUB and ScoreUB need to be update regardless if this event changes
533   // the score of a register or not.
534   // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
535   EventUBs[E] = CurrScore;
536   setScoreUB(T, CurrScore);
537 
538   if (T == EXP_CNT) {
539     // Check for mixed export types. If they are mixed, then a waitcnt exp(0)
540     // is required.
541     if (!MixedExpTypes) {
542       MixedExpTypes = counterOutOfOrder(EXP_CNT);
543     }
544 
545     // Put score on the source vgprs. If this is a store, just use those
546     // specific register(s).
547     if (TII->isDS(Inst) && (Inst.mayStore() || Inst.mayLoad())) {
548       // All GDS operations must protect their address register (same as
549       // export.)
550       if (Inst.getOpcode() != AMDGPU::DS_APPEND &&
551           Inst.getOpcode() != AMDGPU::DS_CONSUME) {
552         setExpScore(
553             &Inst, TII, TRI, MRI,
554             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::addr),
555             CurrScore);
556       }
557       if (Inst.mayStore()) {
558         setExpScore(
559             &Inst, TII, TRI, MRI,
560             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0),
561             CurrScore);
562         if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
563                                        AMDGPU::OpName::data1) != -1) {
564           setExpScore(&Inst, TII, TRI, MRI,
565                       AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
566                                                  AMDGPU::OpName::data1),
567                       CurrScore);
568         }
569       } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1 &&
570                  Inst.getOpcode() != AMDGPU::DS_GWS_INIT &&
571                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_V &&
572                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_BR &&
573                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_P &&
574                  Inst.getOpcode() != AMDGPU::DS_GWS_BARRIER &&
575                  Inst.getOpcode() != AMDGPU::DS_APPEND &&
576                  Inst.getOpcode() != AMDGPU::DS_CONSUME &&
577                  Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
578         for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
579           const MachineOperand &Op = Inst.getOperand(I);
580           if (Op.isReg() && !Op.isDef() && TRI->isVGPR(MRIA, Op.getReg())) {
581             setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
582           }
583         }
584       }
585     } else if (TII->isFLAT(Inst)) {
586       if (Inst.mayStore()) {
587         setExpScore(
588             &Inst, TII, TRI, MRI,
589             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
590             CurrScore);
591       } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
592         setExpScore(
593             &Inst, TII, TRI, MRI,
594             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
595             CurrScore);
596       }
597     } else if (TII->isMIMG(Inst)) {
598       if (Inst.mayStore()) {
599         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
600       } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
601         setExpScore(
602             &Inst, TII, TRI, MRI,
603             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
604             CurrScore);
605       }
606     } else if (TII->isMTBUF(Inst)) {
607       if (Inst.mayStore()) {
608         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
609       }
610     } else if (TII->isMUBUF(Inst)) {
611       if (Inst.mayStore()) {
612         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
613       } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
614         setExpScore(
615             &Inst, TII, TRI, MRI,
616             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
617             CurrScore);
618       }
619     } else {
620       if (TII->isEXP(Inst)) {
621         // For export the destination registers are really temps that
622         // can be used as the actual source after export patching, so
623         // we need to treat them like sources and set the EXP_CNT
624         // score.
625         for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
626           MachineOperand &DefMO = Inst.getOperand(I);
627           if (DefMO.isReg() && DefMO.isDef() &&
628               TRI->isVGPR(MRIA, DefMO.getReg())) {
629             setRegScore(TRI->getEncodingValue(DefMO.getReg()), EXP_CNT,
630                         CurrScore);
631           }
632         }
633       }
634       for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
635         MachineOperand &MO = Inst.getOperand(I);
636         if (MO.isReg() && !MO.isDef() && TRI->isVGPR(MRIA, MO.getReg())) {
637           setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
638         }
639       }
640     }
641 #if 0 // TODO: check if this is handled by MUBUF code above.
642   } else if (Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORD ||
643        Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX2 ||
644        Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX4) {
645     MachineOperand *MO = TII->getNamedOperand(Inst, AMDGPU::OpName::data);
646     unsigned OpNo;//TODO: find the OpNo for this operand;
647     RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, OpNo, false);
648     for (signed RegNo = Interval.first; RegNo < Interval.second;
649     ++RegNo) {
650       setRegScore(RegNo + NUM_ALL_VGPRS, t, CurrScore);
651     }
652 #endif
653   } else {
654     // Match the score to the destination registers.
655     for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
656       RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, I, true);
657       if (T == VM_CNT && Interval.first >= NUM_ALL_VGPRS)
658         continue;
659       for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
660         setRegScore(RegNo, T, CurrScore);
661       }
662     }
663     if (TII->isDS(Inst) && Inst.mayStore()) {
664       setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS, T, CurrScore);
665     }
666   }
667 }
668 
669 void BlockWaitcntBrackets::print(raw_ostream &OS) {
670   OS << '\n';
671   for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
672        T = (enum InstCounterType)(T + 1)) {
673     int LB = getScoreLB(T);
674     int UB = getScoreUB(T);
675 
676     switch (T) {
677     case VM_CNT:
678       OS << "    VM_CNT(" << UB - LB << "): ";
679       break;
680     case LGKM_CNT:
681       OS << "    LGKM_CNT(" << UB - LB << "): ";
682       break;
683     case EXP_CNT:
684       OS << "    EXP_CNT(" << UB - LB << "): ";
685       break;
686     default:
687       OS << "    UNKNOWN(" << UB - LB << "): ";
688       break;
689     }
690 
691     if (LB < UB) {
692       // Print vgpr scores.
693       for (int J = 0; J <= getMaxVGPR(); J++) {
694         int RegScore = getRegScore(J, T);
695         if (RegScore <= LB)
696           continue;
697         int RelScore = RegScore - LB - 1;
698         if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) {
699           OS << RelScore << ":v" << J << " ";
700         } else {
701           OS << RelScore << ":ds ";
702         }
703       }
704       // Also need to print sgpr scores for lgkm_cnt.
705       if (T == LGKM_CNT) {
706         for (int J = 0; J <= getMaxSGPR(); J++) {
707           int RegScore = getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
708           if (RegScore <= LB)
709             continue;
710           int RelScore = RegScore - LB - 1;
711           OS << RelScore << ":s" << J << " ";
712         }
713       }
714     }
715     OS << '\n';
716   }
717   OS << '\n';
718 }
719 
720 unsigned int BlockWaitcntBrackets::updateByWait(InstCounterType T,
721                                                 int ScoreToWait) {
722   unsigned int NeedWait = 0;
723   if (ScoreToWait == -1) {
724     // The score to wait is unknown. This implies that it was not encountered
725     // during the path of the CFG walk done during the current traversal but
726     // may be seen on a different path. Emit an s_wait counter with a
727     // conservative value of 0 for the counter.
728     NeedWait = CNT_MASK(T);
729     setScoreLB(T, getScoreUB(T));
730     return NeedWait;
731   }
732 
733   // If the score of src_operand falls within the bracket, we need an
734   // s_waitcnt instruction.
735   const int32_t LB = getScoreLB(T);
736   const int32_t UB = getScoreUB(T);
737   if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
738     if (T == VM_CNT && hasPendingFlat()) {
739       // If there is a pending FLAT operation, and this is a VM waitcnt,
740       // then we need to force a waitcnt 0 for VM.
741       NeedWait = CNT_MASK(T);
742       setScoreLB(T, getScoreUB(T));
743     } else if (counterOutOfOrder(T)) {
744       // Counter can get decremented out-of-order when there
745       // are multiple types event in the bracket. Also emit an s_wait counter
746       // with a conservative value of 0 for the counter.
747       NeedWait = CNT_MASK(T);
748       setScoreLB(T, getScoreUB(T));
749     } else {
750       NeedWait = CNT_MASK(T);
751       setScoreLB(T, ScoreToWait);
752     }
753   }
754 
755   return NeedWait;
756 }
757 
758 // Where there are multiple types of event in the bracket of a counter,
759 // the decrement may go out of order.
760 bool BlockWaitcntBrackets::counterOutOfOrder(InstCounterType T) {
761   switch (T) {
762   case VM_CNT:
763     return false;
764   case LGKM_CNT: {
765     if (EventUBs[SMEM_ACCESS] > ScoreLBs[LGKM_CNT] &&
766         EventUBs[SMEM_ACCESS] <= ScoreUBs[LGKM_CNT]) {
767       // Scalar memory read always can go out of order.
768       return true;
769     }
770     int NumEventTypes = 0;
771     if (EventUBs[LDS_ACCESS] > ScoreLBs[LGKM_CNT] &&
772         EventUBs[LDS_ACCESS] <= ScoreUBs[LGKM_CNT]) {
773       NumEventTypes++;
774     }
775     if (EventUBs[GDS_ACCESS] > ScoreLBs[LGKM_CNT] &&
776         EventUBs[GDS_ACCESS] <= ScoreUBs[LGKM_CNT]) {
777       NumEventTypes++;
778     }
779     if (EventUBs[SQ_MESSAGE] > ScoreLBs[LGKM_CNT] &&
780         EventUBs[SQ_MESSAGE] <= ScoreUBs[LGKM_CNT]) {
781       NumEventTypes++;
782     }
783     if (NumEventTypes <= 1) {
784       return false;
785     }
786     break;
787   }
788   case EXP_CNT: {
789     // If there has been a mixture of export types, then a waitcnt exp(0) is
790     // required.
791     if (MixedExpTypes)
792       return true;
793     int NumEventTypes = 0;
794     if (EventUBs[EXP_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
795         EventUBs[EXP_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
796       NumEventTypes++;
797     }
798     if (EventUBs[GDS_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
799         EventUBs[GDS_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
800       NumEventTypes++;
801     }
802     if (EventUBs[VMW_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
803         EventUBs[VMW_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
804       NumEventTypes++;
805     }
806     if (EventUBs[EXP_PARAM_ACCESS] > ScoreLBs[EXP_CNT] &&
807         EventUBs[EXP_PARAM_ACCESS] <= ScoreUBs[EXP_CNT]) {
808       NumEventTypes++;
809     }
810 
811     if (EventUBs[EXP_POS_ACCESS] > ScoreLBs[EXP_CNT] &&
812         EventUBs[EXP_POS_ACCESS] <= ScoreUBs[EXP_CNT]) {
813       NumEventTypes++;
814     }
815 
816     if (NumEventTypes <= 1) {
817       return false;
818     }
819     break;
820   }
821   default:
822     break;
823   }
824   return true;
825 }
826 
827 INITIALIZE_PASS_BEGIN(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
828                       false)
829 INITIALIZE_PASS_END(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
830                     false)
831 
832 char SIInsertWaitcnts::ID = 0;
833 
834 char &llvm::SIInsertWaitcntsID = SIInsertWaitcnts::ID;
835 
836 FunctionPass *llvm::createSIInsertWaitcntsPass() {
837   return new SIInsertWaitcnts();
838 }
839 
840 static bool readsVCCZ(const MachineInstr &MI) {
841   unsigned Opc = MI.getOpcode();
842   return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
843          !MI.getOperand(1).isUndef();
844 }
845 
846 /// Given wait count encodings checks if LHS is stronger than RHS.
847 bool SIInsertWaitcnts::isWaitcntStronger(unsigned LHS, unsigned RHS) {
848   if (AMDGPU::decodeVmcnt(IV, LHS) > AMDGPU::decodeVmcnt(IV, RHS))
849     return false;
850   if (AMDGPU::decodeLgkmcnt(IV, LHS) > AMDGPU::decodeLgkmcnt(IV, RHS))
851     return false;
852   if (AMDGPU::decodeExpcnt(IV, LHS) > AMDGPU::decodeExpcnt(IV, RHS))
853     return false;
854   return true;
855 }
856 
857 /// Given wait count encodings create a new encoding which is stronger
858 /// or equal to both.
859 unsigned SIInsertWaitcnts::combineWaitcnt(unsigned LHS, unsigned RHS) {
860   unsigned VmCnt = std::min(AMDGPU::decodeVmcnt(IV, LHS),
861                             AMDGPU::decodeVmcnt(IV, RHS));
862   unsigned LgkmCnt = std::min(AMDGPU::decodeLgkmcnt(IV, LHS),
863                               AMDGPU::decodeLgkmcnt(IV, RHS));
864   unsigned ExpCnt = std::min(AMDGPU::decodeExpcnt(IV, LHS),
865                              AMDGPU::decodeExpcnt(IV, RHS));
866   return AMDGPU::encodeWaitcnt(IV, VmCnt, ExpCnt, LgkmCnt);
867 }
868 
869 ///  Generate s_waitcnt instruction to be placed before cur_Inst.
870 ///  Instructions of a given type are returned in order,
871 ///  but instructions of different types can complete out of order.
872 ///  We rely on this in-order completion
873 ///  and simply assign a score to the memory access instructions.
874 ///  We keep track of the active "score bracket" to determine
875 ///  if an access of a memory read requires an s_waitcnt
876 ///  and if so what the value of each counter is.
877 ///  The "score bracket" is bound by the lower bound and upper bound
878 ///  scores (*_score_LB and *_score_ub respectively).
879 void SIInsertWaitcnts::generateWaitcntInstBefore(
880     MachineInstr &MI, BlockWaitcntBrackets *ScoreBrackets) {
881   // To emit, or not to emit - that's the question!
882   // Start with an assumption that there is no need to emit.
883   unsigned int EmitWaitcnt = 0;
884 
885   // No need to wait before phi. If a phi-move exists, then the wait should
886   // has been inserted before the move. If a phi-move does not exist, then
887   // wait should be inserted before the real use. The same is true for
888   // sc-merge. It is not a coincident that all these cases correspond to the
889   // instructions that are skipped in the assembling loop.
890   bool NeedLineMapping = false; // TODO: Check on this.
891 
892   // ForceEmitZeroWaitcnt: force a single s_waitcnt 0 due to hw bug
893   bool ForceEmitZeroWaitcnt = false;
894 
895   setForceEmitWaitcnt();
896   bool IsForceEmitWaitcnt = isForceEmitWaitcnt();
897 
898   if (MI.isDebugInstr() &&
899       // TODO: any other opcode?
900       !NeedLineMapping) {
901     return;
902   }
903 
904   // See if an s_waitcnt is forced at block entry, or is needed at
905   // program end.
906   if (ScoreBrackets->getWaitAtBeginning()) {
907     // Note that we have already cleared the state, so we don't need to update
908     // it.
909     ScoreBrackets->clearWaitAtBeginning();
910     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
911          T = (enum InstCounterType)(T + 1)) {
912       EmitWaitcnt |= CNT_MASK(T);
913       ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
914     }
915   }
916 
917   // See if this instruction has a forced S_WAITCNT VM.
918   // TODO: Handle other cases of NeedsWaitcntVmBefore()
919   else if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
920            MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
921            MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL) {
922     EmitWaitcnt |=
923         ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
924   }
925 
926   // All waits must be resolved at call return.
927   // NOTE: this could be improved with knowledge of all call sites or
928   //   with knowledge of the called routines.
929   if (MI.getOpcode() == AMDGPU::RETURN ||
930       MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
931       MI.getOpcode() == AMDGPU::S_SETPC_B64_return) {
932     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
933          T = (enum InstCounterType)(T + 1)) {
934       if (ScoreBrackets->getScoreUB(T) > ScoreBrackets->getScoreLB(T)) {
935         ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
936         EmitWaitcnt |= CNT_MASK(T);
937       }
938     }
939   }
940   // Resolve vm waits before gs-done.
941   else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
942             MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
943            ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_) ==
944             AMDGPU::SendMsg::ID_GS_DONE)) {
945     if (ScoreBrackets->getScoreUB(VM_CNT) > ScoreBrackets->getScoreLB(VM_CNT)) {
946       ScoreBrackets->setScoreLB(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
947       EmitWaitcnt |= CNT_MASK(VM_CNT);
948     }
949   }
950 #if 0 // TODO: the following blocks of logic when we have fence.
951   else if (MI.getOpcode() == SC_FENCE) {
952     const unsigned int group_size =
953       context->shader_info->GetMaxThreadGroupSize();
954     // group_size == 0 means thread group size is unknown at compile time
955     const bool group_is_multi_wave =
956       (group_size == 0 || group_size > target_info->GetWaveFrontSize());
957     const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence();
958 
959     for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) {
960       SCRegType src_type = Inst->GetSrcType(i);
961       switch (src_type) {
962         case SCMEM_LDS:
963           if (group_is_multi_wave ||
964             context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) {
965             EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
966                                ScoreBrackets->getScoreUB(LGKM_CNT));
967             // LDS may have to wait for VM_CNT after buffer load to LDS
968             if (target_info->HasBufferLoadToLDS()) {
969               EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
970                                  ScoreBrackets->getScoreUB(VM_CNT));
971             }
972           }
973           break;
974 
975         case SCMEM_GDS:
976           if (group_is_multi_wave || fence_is_global) {
977             EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
978               ScoreBrackets->getScoreUB(EXP_CNT));
979             EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
980               ScoreBrackets->getScoreUB(LGKM_CNT));
981           }
982           break;
983 
984         case SCMEM_UAV:
985         case SCMEM_TFBUF:
986         case SCMEM_RING:
987         case SCMEM_SCATTER:
988           if (group_is_multi_wave || fence_is_global) {
989             EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
990               ScoreBrackets->getScoreUB(EXP_CNT));
991             EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
992               ScoreBrackets->getScoreUB(VM_CNT));
993           }
994           break;
995 
996         case SCMEM_SCRATCH:
997         default:
998           break;
999       }
1000     }
1001   }
1002 #endif
1003 
1004   // Export & GDS instructions do not read the EXEC mask until after the export
1005   // is granted (which can occur well after the instruction is issued).
1006   // The shader program must flush all EXP operations on the export-count
1007   // before overwriting the EXEC mask.
1008   else {
1009     if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
1010       // Export and GDS are tracked individually, either may trigger a waitcnt
1011       // for EXEC.
1012       EmitWaitcnt |= ScoreBrackets->updateByWait(
1013           EXP_CNT, ScoreBrackets->getEventUB(EXP_GPR_LOCK));
1014       EmitWaitcnt |= ScoreBrackets->updateByWait(
1015           EXP_CNT, ScoreBrackets->getEventUB(EXP_PARAM_ACCESS));
1016       EmitWaitcnt |= ScoreBrackets->updateByWait(
1017           EXP_CNT, ScoreBrackets->getEventUB(EXP_POS_ACCESS));
1018       EmitWaitcnt |= ScoreBrackets->updateByWait(
1019           EXP_CNT, ScoreBrackets->getEventUB(GDS_GPR_LOCK));
1020     }
1021 
1022 #if 0 // TODO: the following code to handle CALL.
1023     // The argument passing for CALLs should suffice for VM_CNT and LGKM_CNT.
1024     // However, there is a problem with EXP_CNT, because the call cannot
1025     // easily tell if a register is used in the function, and if it did, then
1026     // the referring instruction would have to have an S_WAITCNT, which is
1027     // dependent on all call sites. So Instead, force S_WAITCNT for EXP_CNTs
1028     // before the call.
1029     if (MI.getOpcode() == SC_CALL) {
1030       if (ScoreBrackets->getScoreUB(EXP_CNT) >
1031         ScoreBrackets->getScoreLB(EXP_CNT)) {
1032         ScoreBrackets->setScoreLB(EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
1033         EmitWaitcnt |= CNT_MASK(EXP_CNT);
1034       }
1035     }
1036 #endif
1037 
1038     // FIXME: Should not be relying on memoperands.
1039     // Look at the source operands of every instruction to see if
1040     // any of them results from a previous memory operation that affects
1041     // its current usage. If so, an s_waitcnt instruction needs to be
1042     // emitted.
1043     // If the source operand was defined by a load, add the s_waitcnt
1044     // instruction.
1045     for (const MachineMemOperand *Memop : MI.memoperands()) {
1046       unsigned AS = Memop->getAddrSpace();
1047       if (AS != AMDGPUASI.LOCAL_ADDRESS)
1048         continue;
1049       unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
1050       // VM_CNT is only relevant to vgpr or LDS.
1051       EmitWaitcnt |= ScoreBrackets->updateByWait(
1052           VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1053     }
1054 
1055     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1056       const MachineOperand &Op = MI.getOperand(I);
1057       const MachineRegisterInfo &MRIA = *MRI;
1058       RegInterval Interval =
1059           ScoreBrackets->getRegInterval(&MI, TII, MRI, TRI, I, false);
1060       for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1061         if (TRI->isVGPR(MRIA, Op.getReg())) {
1062           // VM_CNT is only relevant to vgpr or LDS.
1063           EmitWaitcnt |= ScoreBrackets->updateByWait(
1064               VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1065         }
1066         EmitWaitcnt |= ScoreBrackets->updateByWait(
1067             LGKM_CNT, ScoreBrackets->getRegScore(RegNo, LGKM_CNT));
1068       }
1069     }
1070     // End of for loop that looks at all source operands to decide vm_wait_cnt
1071     // and lgk_wait_cnt.
1072 
1073     // Two cases are handled for destination operands:
1074     // 1) If the destination operand was defined by a load, add the s_waitcnt
1075     // instruction to guarantee the right WAW order.
1076     // 2) If a destination operand that was used by a recent export/store ins,
1077     // add s_waitcnt on exp_cnt to guarantee the WAR order.
1078     if (MI.mayStore()) {
1079       // FIXME: Should not be relying on memoperands.
1080       for (const MachineMemOperand *Memop : MI.memoperands()) {
1081         unsigned AS = Memop->getAddrSpace();
1082         if (AS != AMDGPUASI.LOCAL_ADDRESS)
1083           continue;
1084         unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
1085         EmitWaitcnt |= ScoreBrackets->updateByWait(
1086             VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1087         EmitWaitcnt |= ScoreBrackets->updateByWait(
1088             EXP_CNT, ScoreBrackets->getRegScore(RegNo, EXP_CNT));
1089       }
1090     }
1091     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1092       MachineOperand &Def = MI.getOperand(I);
1093       const MachineRegisterInfo &MRIA = *MRI;
1094       RegInterval Interval =
1095           ScoreBrackets->getRegInterval(&MI, TII, MRI, TRI, I, true);
1096       for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1097         if (TRI->isVGPR(MRIA, Def.getReg())) {
1098           EmitWaitcnt |= ScoreBrackets->updateByWait(
1099               VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1100           EmitWaitcnt |= ScoreBrackets->updateByWait(
1101               EXP_CNT, ScoreBrackets->getRegScore(RegNo, EXP_CNT));
1102         }
1103         EmitWaitcnt |= ScoreBrackets->updateByWait(
1104             LGKM_CNT, ScoreBrackets->getRegScore(RegNo, LGKM_CNT));
1105       }
1106     } // End of for loop that looks at all dest operands.
1107   }
1108 
1109   // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0
1110   // occurs before the instruction. Doing it here prevents any additional
1111   // S_WAITCNTs from being emitted if the instruction was marked as
1112   // requiring a WAITCNT beforehand.
1113   if (MI.getOpcode() == AMDGPU::S_BARRIER &&
1114       !ST->hasAutoWaitcntBeforeBarrier()) {
1115     EmitWaitcnt |=
1116         ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
1117     EmitWaitcnt |= ScoreBrackets->updateByWait(
1118         EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
1119     EmitWaitcnt |= ScoreBrackets->updateByWait(
1120         LGKM_CNT, ScoreBrackets->getScoreUB(LGKM_CNT));
1121   }
1122 
1123   // TODO: Remove this work-around, enable the assert for Bug 457939
1124   //       after fixing the scheduler. Also, the Shader Compiler code is
1125   //       independent of target.
1126   if (readsVCCZ(MI) && ST->getGeneration() <= SISubtarget::SEA_ISLANDS) {
1127     if (ScoreBrackets->getScoreLB(LGKM_CNT) <
1128             ScoreBrackets->getScoreUB(LGKM_CNT) &&
1129         ScoreBrackets->hasPendingSMEM()) {
1130       // Wait on everything, not just LGKM.  vccz reads usually come from
1131       // terminators, and we always wait on everything at the end of the
1132       // block, so if we only wait on LGKM here, we might end up with
1133       // another s_waitcnt inserted right after this if there are non-LGKM
1134       // instructions still outstanding.
1135       // FIXME: this is too conservative / the comment is wrong.
1136       // We don't wait on everything at the end of the block and we combine
1137       // waitcnts so we should never have back-to-back waitcnts.
1138       ForceEmitZeroWaitcnt = true;
1139       EmitWaitcnt = true;
1140     }
1141   }
1142 
1143   // Does this operand processing indicate s_wait counter update?
1144   if (EmitWaitcnt || IsForceEmitWaitcnt) {
1145     int CntVal[NUM_INST_CNTS];
1146 
1147     bool UseDefaultWaitcntStrategy = true;
1148     if (ForceEmitZeroWaitcnt || ForceEmitZeroWaitcnts) {
1149       // Force all waitcnts to 0.
1150       for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1151            T = (enum InstCounterType)(T + 1)) {
1152         ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
1153       }
1154       CntVal[VM_CNT] = 0;
1155       CntVal[EXP_CNT] = 0;
1156       CntVal[LGKM_CNT] = 0;
1157       UseDefaultWaitcntStrategy = false;
1158     }
1159 
1160     if (UseDefaultWaitcntStrategy) {
1161       for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1162            T = (enum InstCounterType)(T + 1)) {
1163         if (EmitWaitcnt & CNT_MASK(T)) {
1164           int Delta =
1165               ScoreBrackets->getScoreUB(T) - ScoreBrackets->getScoreLB(T);
1166           int MaxDelta = ScoreBrackets->getWaitCountMax(T);
1167           if (Delta >= MaxDelta) {
1168             Delta = -1;
1169             if (T != EXP_CNT) {
1170               ScoreBrackets->setScoreLB(
1171                   T, ScoreBrackets->getScoreUB(T) - MaxDelta);
1172             }
1173             EmitWaitcnt &= ~CNT_MASK(T);
1174           }
1175           CntVal[T] = Delta;
1176         } else {
1177           // If we are not waiting for a particular counter then encode
1178           // it as -1 which means "don't care."
1179           CntVal[T] = -1;
1180         }
1181       }
1182     }
1183 
1184     // If we are not waiting on any counter we can skip the wait altogether.
1185     if (EmitWaitcnt != 0 || IsForceEmitWaitcnt) {
1186       MachineInstr *OldWaitcnt = ScoreBrackets->getWaitcnt();
1187       int Imm = (!OldWaitcnt) ? 0 : OldWaitcnt->getOperand(0).getImm();
1188       if (!OldWaitcnt ||
1189           (AMDGPU::decodeVmcnt(IV, Imm) !=
1190                           (CntVal[VM_CNT] & AMDGPU::getVmcntBitMask(IV))) ||
1191           (AMDGPU::decodeExpcnt(IV, Imm) !=
1192            (CntVal[EXP_CNT] & AMDGPU::getExpcntBitMask(IV))) ||
1193           (AMDGPU::decodeLgkmcnt(IV, Imm) !=
1194            (CntVal[LGKM_CNT] & AMDGPU::getLgkmcntBitMask(IV)))) {
1195         MachineLoop *ContainingLoop = MLI->getLoopFor(MI.getParent());
1196         if (ContainingLoop) {
1197           MachineBasicBlock *TBB = ContainingLoop->getHeader();
1198           BlockWaitcntBrackets *ScoreBracket =
1199               BlockWaitcntBracketsMap[TBB].get();
1200           if (!ScoreBracket) {
1201             assert(!BlockVisitedSet.count(TBB));
1202             BlockWaitcntBracketsMap[TBB] =
1203                 llvm::make_unique<BlockWaitcntBrackets>();
1204             ScoreBracket = BlockWaitcntBracketsMap[TBB].get();
1205           }
1206           ScoreBracket->setRevisitLoop(true);
1207           LLVM_DEBUG(dbgs()
1208                          << "set-revisit2: Block"
1209                          << ContainingLoop->getHeader()->getNumber() << '\n';);
1210         }
1211       }
1212 
1213       // Update an existing waitcount, or make a new one.
1214       unsigned Enc = AMDGPU::encodeWaitcnt(IV,
1215                       ForceEmitWaitcnt[VM_CNT] ? 0 : CntVal[VM_CNT],
1216                       ForceEmitWaitcnt[EXP_CNT] ? 0 : CntVal[EXP_CNT],
1217                       ForceEmitWaitcnt[LGKM_CNT] ? 0 : CntVal[LGKM_CNT]);
1218       // We don't remove waitcnts that existed prior to the waitcnt
1219       // pass. Check if the waitcnt to-be-inserted can be avoided
1220       // or if the prev waitcnt can be updated.
1221       bool insertSWaitInst = true;
1222       for (MachineBasicBlock::iterator I = MI.getIterator(),
1223                                        B = MI.getParent()->begin();
1224            insertSWaitInst && I != B; --I) {
1225         if (I == MI.getIterator())
1226           continue;
1227 
1228         switch (I->getOpcode()) {
1229         case AMDGPU::S_WAITCNT:
1230           if (isWaitcntStronger(I->getOperand(0).getImm(), Enc))
1231             insertSWaitInst = false;
1232           else if (!OldWaitcnt) {
1233             OldWaitcnt = &*I;
1234             Enc = combineWaitcnt(I->getOperand(0).getImm(), Enc);
1235           }
1236           break;
1237         // TODO: skip over instructions which never require wait.
1238         }
1239         break;
1240       }
1241       if (insertSWaitInst) {
1242         if (OldWaitcnt && OldWaitcnt->getOpcode() == AMDGPU::S_WAITCNT) {
1243           if (ForceEmitZeroWaitcnts)
1244             LLVM_DEBUG(
1245                 dbgs()
1246                 << "Force emit s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)\n");
1247           if (IsForceEmitWaitcnt)
1248             LLVM_DEBUG(dbgs()
1249                        << "Force emit a s_waitcnt due to debug counter\n");
1250 
1251           OldWaitcnt->getOperand(0).setImm(Enc);
1252           if (!OldWaitcnt->getParent())
1253             MI.getParent()->insert(MI, OldWaitcnt);
1254 
1255           LLVM_DEBUG(dbgs() << "updateWaitcntInBlock\n"
1256                             << "Old Instr: " << MI << '\n'
1257                             << "New Instr: " << *OldWaitcnt << '\n');
1258         } else {
1259             auto SWaitInst = BuildMI(*MI.getParent(), MI.getIterator(),
1260                                MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1261                              .addImm(Enc);
1262             TrackedWaitcntSet.insert(SWaitInst);
1263 
1264             LLVM_DEBUG(dbgs() << "insertWaitcntInBlock\n"
1265                               << "Old Instr: " << MI << '\n'
1266                               << "New Instr: " << *SWaitInst << '\n');
1267         }
1268       }
1269 
1270       if (CntVal[EXP_CNT] == 0) {
1271         ScoreBrackets->setMixedExpTypes(false);
1272       }
1273     }
1274   }
1275 }
1276 
1277 void SIInsertWaitcnts::insertWaitcntBeforeCF(MachineBasicBlock &MBB,
1278                                              MachineInstr *Waitcnt) {
1279   if (MBB.empty()) {
1280     MBB.push_back(Waitcnt);
1281     return;
1282   }
1283 
1284   MachineBasicBlock::iterator It = MBB.end();
1285   MachineInstr *MI = &*(--It);
1286   if (MI->isBranch()) {
1287     MBB.insert(It, Waitcnt);
1288   } else {
1289     MBB.push_back(Waitcnt);
1290   }
1291 }
1292 
1293 // This is a flat memory operation. Check to see if it has memory
1294 // tokens for both LDS and Memory, and if so mark it as a flat.
1295 bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
1296   if (MI.memoperands_empty())
1297     return true;
1298 
1299   for (const MachineMemOperand *Memop : MI.memoperands()) {
1300     unsigned AS = Memop->getAddrSpace();
1301     if (AS == AMDGPUASI.LOCAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS)
1302       return true;
1303   }
1304 
1305   return false;
1306 }
1307 
1308 void SIInsertWaitcnts::updateEventWaitcntAfter(
1309     MachineInstr &Inst, BlockWaitcntBrackets *ScoreBrackets) {
1310   // Now look at the instruction opcode. If it is a memory access
1311   // instruction, update the upper-bound of the appropriate counter's
1312   // bracket and the destination operand scores.
1313   // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere.
1314   if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
1315     if (TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
1316       ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
1317       ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
1318     } else {
1319       ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1320     }
1321   } else if (TII->isFLAT(Inst)) {
1322     assert(Inst.mayLoad() || Inst.mayStore());
1323 
1324     if (TII->usesVM_CNT(Inst))
1325       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1326 
1327     if (TII->usesLGKM_CNT(Inst)) {
1328       ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1329 
1330       // This is a flat memory operation, so note it - it will require
1331       // that both the VM and LGKM be flushed to zero if it is pending when
1332       // a VM or LGKM dependency occurs.
1333       if (mayAccessLDSThroughFlat(Inst))
1334         ScoreBrackets->setPendingFlat();
1335     }
1336   } else if (SIInstrInfo::isVMEM(Inst) &&
1337              // TODO: get a better carve out.
1338              Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1 &&
1339              Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_SC &&
1340              Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_VOL) {
1341     ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1342     if (ST->vmemWriteNeedsExpWaitcnt() &&
1343         (Inst.mayStore() || AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1)) {
1344       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
1345     }
1346   } else if (TII->isSMRD(Inst)) {
1347     ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1348   } else {
1349     switch (Inst.getOpcode()) {
1350     case AMDGPU::S_SENDMSG:
1351     case AMDGPU::S_SENDMSGHALT:
1352       ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
1353       break;
1354     case AMDGPU::EXP:
1355     case AMDGPU::EXP_DONE: {
1356       int Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
1357       if (Imm >= 32 && Imm <= 63)
1358         ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
1359       else if (Imm >= 12 && Imm <= 15)
1360         ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
1361       else
1362         ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
1363       break;
1364     }
1365     case AMDGPU::S_MEMTIME:
1366     case AMDGPU::S_MEMREALTIME:
1367       ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1368       break;
1369     default:
1370       break;
1371     }
1372   }
1373 }
1374 
1375 // Merge the score brackets of the Block's predecessors;
1376 // this merged score bracket is used when adding waitcnts to the Block
1377 void SIInsertWaitcnts::mergeInputScoreBrackets(MachineBasicBlock &Block) {
1378   BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&Block].get();
1379   int32_t MaxPending[NUM_INST_CNTS] = {0};
1380   int32_t MaxFlat[NUM_INST_CNTS] = {0};
1381   bool MixedExpTypes = false;
1382 
1383   // For single basic block loops, we need to retain the Block's
1384   // score bracket to have accurate Pred info. So, make a copy of Block's
1385   // score bracket, clear() it (which retains several important bits of info),
1386   // populate, and then replace en masse. For non-single basic block loops,
1387   // just clear Block's current score bracket and repopulate in-place.
1388   bool IsSelfPred;
1389   std::unique_ptr<BlockWaitcntBrackets> S;
1390 
1391   IsSelfPred = (std::find(Block.pred_begin(), Block.pred_end(), &Block))
1392     != Block.pred_end();
1393   if (IsSelfPred) {
1394     S = llvm::make_unique<BlockWaitcntBrackets>(*ScoreBrackets);
1395     ScoreBrackets = S.get();
1396   }
1397 
1398   ScoreBrackets->clear();
1399 
1400   // See if there are any uninitialized predecessors. If so, emit an
1401   // s_waitcnt 0 at the beginning of the block.
1402   for (MachineBasicBlock *Pred : Block.predecessors()) {
1403     BlockWaitcntBrackets *PredScoreBrackets =
1404         BlockWaitcntBracketsMap[Pred].get();
1405     bool Visited = BlockVisitedSet.count(Pred);
1406     if (!Visited || PredScoreBrackets->getWaitAtBeginning()) {
1407       continue;
1408     }
1409     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1410          T = (enum InstCounterType)(T + 1)) {
1411       int span =
1412           PredScoreBrackets->getScoreUB(T) - PredScoreBrackets->getScoreLB(T);
1413       MaxPending[T] = std::max(MaxPending[T], span);
1414       span =
1415           PredScoreBrackets->pendingFlat(T) - PredScoreBrackets->getScoreLB(T);
1416       MaxFlat[T] = std::max(MaxFlat[T], span);
1417     }
1418 
1419     MixedExpTypes |= PredScoreBrackets->mixedExpTypes();
1420   }
1421 
1422   // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1423   // Also handle kills for exit block.
1424   if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1425     for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1426       for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1427            T = (enum InstCounterType)(T + 1)) {
1428         int Span = KillWaitBrackets[I]->getScoreUB(T) -
1429                    KillWaitBrackets[I]->getScoreLB(T);
1430         MaxPending[T] = std::max(MaxPending[T], Span);
1431         Span = KillWaitBrackets[I]->pendingFlat(T) -
1432                KillWaitBrackets[I]->getScoreLB(T);
1433         MaxFlat[T] = std::max(MaxFlat[T], Span);
1434       }
1435 
1436       MixedExpTypes |= KillWaitBrackets[I]->mixedExpTypes();
1437     }
1438   }
1439 
1440   // Special handling for GDS_GPR_LOCK and EXP_GPR_LOCK.
1441   for (MachineBasicBlock *Pred : Block.predecessors()) {
1442     BlockWaitcntBrackets *PredScoreBrackets =
1443         BlockWaitcntBracketsMap[Pred].get();
1444     bool Visited = BlockVisitedSet.count(Pred);
1445     if (!Visited || PredScoreBrackets->getWaitAtBeginning()) {
1446       continue;
1447     }
1448 
1449     int GDSSpan = PredScoreBrackets->getEventUB(GDS_GPR_LOCK) -
1450                   PredScoreBrackets->getScoreLB(EXP_CNT);
1451     MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], GDSSpan);
1452     int EXPSpan = PredScoreBrackets->getEventUB(EXP_GPR_LOCK) -
1453                   PredScoreBrackets->getScoreLB(EXP_CNT);
1454     MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], EXPSpan);
1455   }
1456 
1457   // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1458   if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1459     for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1460       int GDSSpan = KillWaitBrackets[I]->getEventUB(GDS_GPR_LOCK) -
1461                     KillWaitBrackets[I]->getScoreLB(EXP_CNT);
1462       MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], GDSSpan);
1463       int EXPSpan = KillWaitBrackets[I]->getEventUB(EXP_GPR_LOCK) -
1464                     KillWaitBrackets[I]->getScoreLB(EXP_CNT);
1465       MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], EXPSpan);
1466     }
1467   }
1468 
1469 #if 0
1470   // LC does not (unlike) add a waitcnt at beginning. Leaving it as marker.
1471   // TODO: how does LC distinguish between function entry and main entry?
1472   // If this is the entry to a function, force a wait.
1473   MachineBasicBlock &Entry = Block.getParent()->front();
1474   if (Entry.getNumber() == Block.getNumber()) {
1475     ScoreBrackets->setWaitAtBeginning();
1476     return;
1477   }
1478 #endif
1479 
1480   // Now set the current Block's brackets to the largest ending bracket.
1481   for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1482        T = (enum InstCounterType)(T + 1)) {
1483     ScoreBrackets->setScoreUB(T, MaxPending[T]);
1484     ScoreBrackets->setScoreLB(T, 0);
1485     ScoreBrackets->setLastFlat(T, MaxFlat[T]);
1486   }
1487 
1488   ScoreBrackets->setMixedExpTypes(MixedExpTypes);
1489 
1490   // Set the register scoreboard.
1491   for (MachineBasicBlock *Pred : Block.predecessors()) {
1492     if (!BlockVisitedSet.count(Pred)) {
1493       continue;
1494     }
1495 
1496     BlockWaitcntBrackets *PredScoreBrackets =
1497         BlockWaitcntBracketsMap[Pred].get();
1498 
1499     // Now merge the gpr_reg_score information
1500     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1501          T = (enum InstCounterType)(T + 1)) {
1502       int PredLB = PredScoreBrackets->getScoreLB(T);
1503       int PredUB = PredScoreBrackets->getScoreUB(T);
1504       if (PredLB < PredUB) {
1505         int PredScale = MaxPending[T] - PredUB;
1506         // Merge vgpr scores.
1507         for (int J = 0; J <= PredScoreBrackets->getMaxVGPR(); J++) {
1508           int PredRegScore = PredScoreBrackets->getRegScore(J, T);
1509           if (PredRegScore <= PredLB)
1510             continue;
1511           int NewRegScore = PredScale + PredRegScore;
1512           ScoreBrackets->setRegScore(
1513               J, T, std::max(ScoreBrackets->getRegScore(J, T), NewRegScore));
1514         }
1515         // Also need to merge sgpr scores for lgkm_cnt.
1516         if (T == LGKM_CNT) {
1517           for (int J = 0; J <= PredScoreBrackets->getMaxSGPR(); J++) {
1518             int PredRegScore =
1519                 PredScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
1520             if (PredRegScore <= PredLB)
1521               continue;
1522             int NewRegScore = PredScale + PredRegScore;
1523             ScoreBrackets->setRegScore(
1524                 J + NUM_ALL_VGPRS, LGKM_CNT,
1525                 std::max(
1526                     ScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT),
1527                     NewRegScore));
1528           }
1529         }
1530       }
1531     }
1532 
1533     // Also merge the WaitEvent information.
1534     ForAllWaitEventType(W) {
1535       enum InstCounterType T = PredScoreBrackets->eventCounter(W);
1536       int PredEventUB = PredScoreBrackets->getEventUB(W);
1537       if (PredEventUB > PredScoreBrackets->getScoreLB(T)) {
1538         int NewEventUB =
1539             MaxPending[T] + PredEventUB - PredScoreBrackets->getScoreUB(T);
1540         if (NewEventUB > 0) {
1541           ScoreBrackets->setEventUB(
1542               W, std::max(ScoreBrackets->getEventUB(W), NewEventUB));
1543         }
1544       }
1545     }
1546   }
1547 
1548   // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1549   // Set the register scoreboard.
1550   if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1551     for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1552       // Now merge the gpr_reg_score information.
1553       for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1554            T = (enum InstCounterType)(T + 1)) {
1555         int PredLB = KillWaitBrackets[I]->getScoreLB(T);
1556         int PredUB = KillWaitBrackets[I]->getScoreUB(T);
1557         if (PredLB < PredUB) {
1558           int PredScale = MaxPending[T] - PredUB;
1559           // Merge vgpr scores.
1560           for (int J = 0; J <= KillWaitBrackets[I]->getMaxVGPR(); J++) {
1561             int PredRegScore = KillWaitBrackets[I]->getRegScore(J, T);
1562             if (PredRegScore <= PredLB)
1563               continue;
1564             int NewRegScore = PredScale + PredRegScore;
1565             ScoreBrackets->setRegScore(
1566                 J, T, std::max(ScoreBrackets->getRegScore(J, T), NewRegScore));
1567           }
1568           // Also need to merge sgpr scores for lgkm_cnt.
1569           if (T == LGKM_CNT) {
1570             for (int J = 0; J <= KillWaitBrackets[I]->getMaxSGPR(); J++) {
1571               int PredRegScore =
1572                   KillWaitBrackets[I]->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
1573               if (PredRegScore <= PredLB)
1574                 continue;
1575               int NewRegScore = PredScale + PredRegScore;
1576               ScoreBrackets->setRegScore(
1577                   J + NUM_ALL_VGPRS, LGKM_CNT,
1578                   std::max(
1579                       ScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT),
1580                       NewRegScore));
1581             }
1582           }
1583         }
1584       }
1585 
1586       // Also merge the WaitEvent information.
1587       ForAllWaitEventType(W) {
1588         enum InstCounterType T = KillWaitBrackets[I]->eventCounter(W);
1589         int PredEventUB = KillWaitBrackets[I]->getEventUB(W);
1590         if (PredEventUB > KillWaitBrackets[I]->getScoreLB(T)) {
1591           int NewEventUB =
1592               MaxPending[T] + PredEventUB - KillWaitBrackets[I]->getScoreUB(T);
1593           if (NewEventUB > 0) {
1594             ScoreBrackets->setEventUB(
1595                 W, std::max(ScoreBrackets->getEventUB(W), NewEventUB));
1596           }
1597         }
1598       }
1599     }
1600   }
1601 
1602   // Special case handling of GDS_GPR_LOCK and EXP_GPR_LOCK. Merge this for the
1603   // sequencing predecessors, because changes to EXEC require waitcnts due to
1604   // the delayed nature of these operations.
1605   for (MachineBasicBlock *Pred : Block.predecessors()) {
1606     if (!BlockVisitedSet.count(Pred)) {
1607       continue;
1608     }
1609 
1610     BlockWaitcntBrackets *PredScoreBrackets =
1611         BlockWaitcntBracketsMap[Pred].get();
1612 
1613     int pred_gds_ub = PredScoreBrackets->getEventUB(GDS_GPR_LOCK);
1614     if (pred_gds_ub > PredScoreBrackets->getScoreLB(EXP_CNT)) {
1615       int new_gds_ub = MaxPending[EXP_CNT] + pred_gds_ub -
1616                        PredScoreBrackets->getScoreUB(EXP_CNT);
1617       if (new_gds_ub > 0) {
1618         ScoreBrackets->setEventUB(
1619             GDS_GPR_LOCK,
1620             std::max(ScoreBrackets->getEventUB(GDS_GPR_LOCK), new_gds_ub));
1621       }
1622     }
1623     int pred_exp_ub = PredScoreBrackets->getEventUB(EXP_GPR_LOCK);
1624     if (pred_exp_ub > PredScoreBrackets->getScoreLB(EXP_CNT)) {
1625       int new_exp_ub = MaxPending[EXP_CNT] + pred_exp_ub -
1626                        PredScoreBrackets->getScoreUB(EXP_CNT);
1627       if (new_exp_ub > 0) {
1628         ScoreBrackets->setEventUB(
1629             EXP_GPR_LOCK,
1630             std::max(ScoreBrackets->getEventUB(EXP_GPR_LOCK), new_exp_ub));
1631       }
1632     }
1633   }
1634 
1635   // if a single block loop, update the score brackets. Not needed for other
1636   // blocks, as we did this in-place
1637   if (IsSelfPred) {
1638     BlockWaitcntBracketsMap[&Block] = llvm::make_unique<BlockWaitcntBrackets>(*ScoreBrackets);
1639   }
1640 }
1641 
1642 /// Return true if the given basic block is a "bottom" block of a loop.
1643 /// This works even if the loop is discontiguous. This also handles
1644 /// multiple back-edges for the same "header" block of a loop.
1645 bool SIInsertWaitcnts::isLoopBottom(const MachineLoop *Loop,
1646                                     const MachineBasicBlock *Block) {
1647   for (MachineBasicBlock *MBB : Loop->blocks()) {
1648     if (MBB == Block && MBB->isSuccessor(Loop->getHeader())) {
1649       return true;
1650     }
1651   }
1652   return false;
1653 }
1654 
1655 /// Count the number of "bottom" basic blocks of a loop.
1656 unsigned SIInsertWaitcnts::countNumBottomBlocks(const MachineLoop *Loop) {
1657   unsigned Count = 0;
1658   for (MachineBasicBlock *MBB : Loop->blocks()) {
1659     if (MBB->isSuccessor(Loop->getHeader())) {
1660       Count++;
1661     }
1662   }
1663   return Count;
1664 }
1665 
1666 // Generate s_waitcnt instructions where needed.
1667 void SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
1668                                             MachineBasicBlock &Block) {
1669   // Initialize the state information.
1670   mergeInputScoreBrackets(Block);
1671 
1672   BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&Block].get();
1673 
1674   LLVM_DEBUG({
1675     dbgs() << "*** Block" << Block.getNumber() << " ***";
1676     ScoreBrackets->dump();
1677   });
1678 
1679   // Walk over the instructions.
1680   for (MachineBasicBlock::iterator Iter = Block.begin(), E = Block.end();
1681        Iter != E;) {
1682     MachineInstr &Inst = *Iter;
1683     // Remove any previously existing waitcnts.
1684     if (Inst.getOpcode() == AMDGPU::S_WAITCNT) {
1685       // Leave pre-existing waitcnts, but note their existence via setWaitcnt.
1686       // Remove the waitcnt-pass-generated waitcnts; the pass will add them back
1687       // as needed.
1688       if (!TrackedWaitcntSet.count(&Inst))
1689         ++Iter;
1690       else {
1691         ++Iter;
1692         Inst.removeFromParent();
1693       }
1694       ScoreBrackets->setWaitcnt(&Inst);
1695       continue;
1696     }
1697 
1698     // Kill instructions generate a conditional branch to the endmain block.
1699     // Merge the current waitcnt state into the endmain block information.
1700     // TODO: Are there other flavors of KILL instruction?
1701     if (Inst.getOpcode() == AMDGPU::KILL) {
1702       addKillWaitBracket(ScoreBrackets);
1703     }
1704 
1705     bool VCCZBugWorkAround = false;
1706     if (readsVCCZ(Inst) &&
1707         (!VCCZBugHandledSet.count(&Inst))) {
1708       if (ScoreBrackets->getScoreLB(LGKM_CNT) <
1709               ScoreBrackets->getScoreUB(LGKM_CNT) &&
1710           ScoreBrackets->hasPendingSMEM()) {
1711         if (ST->getGeneration() <= SISubtarget::SEA_ISLANDS)
1712           VCCZBugWorkAround = true;
1713       }
1714     }
1715 
1716     // Generate an s_waitcnt instruction to be placed before
1717     // cur_Inst, if needed.
1718     generateWaitcntInstBefore(Inst, ScoreBrackets);
1719 
1720     updateEventWaitcntAfter(Inst, ScoreBrackets);
1721 
1722 #if 0 // TODO: implement resource type check controlled by options with ub = LB.
1723     // If this instruction generates a S_SETVSKIP because it is an
1724     // indexed resource, and we are on Tahiti, then it will also force
1725     // an S_WAITCNT vmcnt(0)
1726     if (RequireCheckResourceType(Inst, context)) {
1727       // Force the score to as if an S_WAITCNT vmcnt(0) is emitted.
1728       ScoreBrackets->setScoreLB(VM_CNT,
1729       ScoreBrackets->getScoreUB(VM_CNT));
1730     }
1731 #endif
1732 
1733     ScoreBrackets->clearWaitcnt();
1734 
1735     LLVM_DEBUG({
1736       Inst.print(dbgs());
1737       ScoreBrackets->dump();
1738     });
1739 
1740     // Check to see if this is a GWS instruction. If so, and if this is CI or
1741     // VI, then the generated code sequence will include an S_WAITCNT 0.
1742     // TODO: Are these the only GWS instructions?
1743     if (Inst.getOpcode() == AMDGPU::DS_GWS_INIT ||
1744         Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_V ||
1745         Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_BR ||
1746         Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_P ||
1747         Inst.getOpcode() == AMDGPU::DS_GWS_BARRIER) {
1748       // TODO: && context->target_info->GwsRequiresMemViolTest() ) {
1749       ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
1750       ScoreBrackets->updateByWait(EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
1751       ScoreBrackets->updateByWait(LGKM_CNT,
1752                                   ScoreBrackets->getScoreUB(LGKM_CNT));
1753     }
1754 
1755     // TODO: Remove this work-around after fixing the scheduler and enable the
1756     // assert above.
1757     if (VCCZBugWorkAround) {
1758       // Restore the vccz bit.  Any time a value is written to vcc, the vcc
1759       // bit is updated, so we can restore the bit by reading the value of
1760       // vcc and then writing it back to the register.
1761       BuildMI(Block, Inst, Inst.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
1762               AMDGPU::VCC)
1763           .addReg(AMDGPU::VCC);
1764       VCCZBugHandledSet.insert(&Inst);
1765     }
1766 
1767     ++Iter;
1768   }
1769 
1770   // Check if we need to force convergence at loop footer.
1771   MachineLoop *ContainingLoop = MLI->getLoopFor(&Block);
1772   if (ContainingLoop && isLoopBottom(ContainingLoop, &Block)) {
1773     LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1774     WaitcntData->print();
1775     LLVM_DEBUG(dbgs() << '\n';);
1776 
1777     // The iterative waitcnt insertion algorithm aims for optimal waitcnt
1778     // placement, but doesn't guarantee convergence for a loop. Each
1779     // loop should take at most (n+1) iterations for it to converge naturally,
1780     // where n is the number of bottom blocks. If this threshold is reached and
1781     // the result hasn't converged, then we force convergence by inserting
1782     // a s_waitcnt at the end of loop footer.
1783     if (WaitcntData->getIterCnt() > (countNumBottomBlocks(ContainingLoop) + 1)) {
1784       // To ensure convergence, need to make wait events at loop footer be no
1785       // more than those from the previous iteration.
1786       // As a simplification, instead of tracking individual scores and
1787       // generating the precise wait count, just wait on 0.
1788       bool HasPending = false;
1789       MachineInstr *SWaitInst = WaitcntData->getWaitcnt();
1790       for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1791            T = (enum InstCounterType)(T + 1)) {
1792         if (ScoreBrackets->getScoreUB(T) > ScoreBrackets->getScoreLB(T)) {
1793           ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
1794           HasPending = true;
1795           break;
1796         }
1797       }
1798 
1799       if (HasPending) {
1800         if (!SWaitInst) {
1801           SWaitInst = BuildMI(Block, Block.getFirstNonPHI(),
1802                               DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1803                               .addImm(0);
1804           TrackedWaitcntSet.insert(SWaitInst);
1805 #if 0 // TODO: Format the debug output
1806           OutputTransformBanner("insertWaitcntInBlock",0,"Create:",context);
1807           OutputTransformAdd(SWaitInst, context);
1808 #endif
1809         }
1810 #if 0 // TODO: ??
1811         _DEV( REPORTED_STATS->force_waitcnt_converge = 1; )
1812 #endif
1813       }
1814 
1815       if (SWaitInst) {
1816         LLVM_DEBUG({
1817           SWaitInst->print(dbgs());
1818           dbgs() << "\nAdjusted score board:";
1819           ScoreBrackets->dump();
1820         });
1821 
1822         // Add this waitcnt to the block. It is either newly created or
1823         // created in previous iterations and added back since block traversal
1824         // always removes waitcnts.
1825         insertWaitcntBeforeCF(Block, SWaitInst);
1826         WaitcntData->setWaitcnt(SWaitInst);
1827       }
1828     }
1829   }
1830 }
1831 
1832 bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) {
1833   ST = &MF.getSubtarget<SISubtarget>();
1834   TII = ST->getInstrInfo();
1835   TRI = &TII->getRegisterInfo();
1836   MRI = &MF.getRegInfo();
1837   MLI = &getAnalysis<MachineLoopInfo>();
1838   IV = AMDGPU::IsaInfo::getIsaVersion(ST->getFeatureBits());
1839   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1840   AMDGPUASI = ST->getAMDGPUAS();
1841 
1842   ForceEmitZeroWaitcnts = ForceEmitZeroFlag;
1843   for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1844        T = (enum InstCounterType)(T + 1))
1845     ForceEmitWaitcnt[T] = false;
1846 
1847   HardwareLimits.VmcntMax = AMDGPU::getVmcntBitMask(IV);
1848   HardwareLimits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
1849   HardwareLimits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV);
1850 
1851   HardwareLimits.NumVGPRsMax = ST->getAddressableNumVGPRs();
1852   HardwareLimits.NumSGPRsMax = ST->getAddressableNumSGPRs();
1853   assert(HardwareLimits.NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
1854   assert(HardwareLimits.NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
1855 
1856   RegisterEncoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0);
1857   RegisterEncoding.VGPRL =
1858       RegisterEncoding.VGPR0 + HardwareLimits.NumVGPRsMax - 1;
1859   RegisterEncoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0);
1860   RegisterEncoding.SGPRL =
1861       RegisterEncoding.SGPR0 + HardwareLimits.NumSGPRsMax - 1;
1862 
1863   TrackedWaitcntSet.clear();
1864   BlockVisitedSet.clear();
1865   VCCZBugHandledSet.clear();
1866   LoopWaitcntDataMap.clear();
1867 
1868   // Walk over the blocks in reverse post-dominator order, inserting
1869   // s_waitcnt where needed.
1870   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1871   bool Modified = false;
1872   for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1873            I = RPOT.begin(),
1874            E = RPOT.end(), J = RPOT.begin();
1875        I != E;) {
1876     MachineBasicBlock &MBB = **I;
1877 
1878     BlockVisitedSet.insert(&MBB);
1879 
1880     BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&MBB].get();
1881     if (!ScoreBrackets) {
1882       BlockWaitcntBracketsMap[&MBB] = llvm::make_unique<BlockWaitcntBrackets>();
1883       ScoreBrackets = BlockWaitcntBracketsMap[&MBB].get();
1884     }
1885     ScoreBrackets->setPostOrder(MBB.getNumber());
1886     MachineLoop *ContainingLoop = MLI->getLoopFor(&MBB);
1887     if (ContainingLoop && LoopWaitcntDataMap[ContainingLoop] == nullptr)
1888       LoopWaitcntDataMap[ContainingLoop] = llvm::make_unique<LoopWaitcntData>();
1889 
1890     // If we are walking into the block from before the loop, then guarantee
1891     // at least 1 re-walk over the loop to propagate the information, even if
1892     // no S_WAITCNT instructions were generated.
1893     if (ContainingLoop && ContainingLoop->getHeader() == &MBB) {
1894       unsigned Count = countNumBottomBlocks(ContainingLoop);
1895 
1896       // If the loop has multiple back-edges, and so more than one "bottom"
1897       // basic block, we have to guarantee a re-walk over every blocks.
1898       if ((std::count(BlockWaitcntProcessedSet.begin(),
1899                       BlockWaitcntProcessedSet.end(), &MBB) < Count)) {
1900         BlockWaitcntBracketsMap[&MBB]->setRevisitLoop(true);
1901         LLVM_DEBUG(dbgs() << "set-revisit1: Block"
1902                           << ContainingLoop->getHeader()->getNumber() << '\n';);
1903       }
1904     }
1905 
1906     // Walk over the instructions.
1907     insertWaitcntInBlock(MF, MBB);
1908 
1909     // Record that waitcnts have been processed at least once for this block.
1910     BlockWaitcntProcessedSet.push_back(&MBB);
1911 
1912     // See if we want to revisit the loop. If a loop has multiple back-edges,
1913     // we shouldn't revisit the same "bottom" basic block.
1914     if (ContainingLoop && isLoopBottom(ContainingLoop, &MBB) &&
1915         std::count(BlockWaitcntProcessedSet.begin(),
1916                    BlockWaitcntProcessedSet.end(), &MBB) == 1) {
1917       MachineBasicBlock *EntryBB = ContainingLoop->getHeader();
1918       BlockWaitcntBrackets *EntrySB = BlockWaitcntBracketsMap[EntryBB].get();
1919       if (EntrySB && EntrySB->getRevisitLoop()) {
1920         EntrySB->setRevisitLoop(false);
1921         J = I;
1922         int32_t PostOrder = EntrySB->getPostOrder();
1923         // TODO: Avoid this loop. Find another way to set I.
1924         for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1925                  X = RPOT.begin(),
1926                  Y = RPOT.end();
1927              X != Y; ++X) {
1928           MachineBasicBlock &MBBX = **X;
1929           if (MBBX.getNumber() == PostOrder) {
1930             I = X;
1931             break;
1932           }
1933         }
1934         LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1935         WaitcntData->incIterCnt();
1936         LLVM_DEBUG(dbgs() << "revisit: Block" << EntryBB->getNumber() << '\n';);
1937         continue;
1938       } else {
1939         LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1940         // Loop converged, reset iteration count. If this loop gets revisited,
1941         // it must be from an outer loop, the counter will restart, this will
1942         // ensure we don't force convergence on such revisits.
1943         WaitcntData->resetIterCnt();
1944       }
1945     }
1946 
1947     J = I;
1948     ++I;
1949   }
1950 
1951   SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
1952 
1953   bool HaveScalarStores = false;
1954 
1955   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE;
1956        ++BI) {
1957     MachineBasicBlock &MBB = *BI;
1958 
1959     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1960          ++I) {
1961       if (!HaveScalarStores && TII->isScalarStore(*I))
1962         HaveScalarStores = true;
1963 
1964       if (I->getOpcode() == AMDGPU::S_ENDPGM ||
1965           I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
1966         EndPgmBlocks.push_back(&MBB);
1967     }
1968   }
1969 
1970   if (HaveScalarStores) {
1971     // If scalar writes are used, the cache must be flushed or else the next
1972     // wave to reuse the same scratch memory can be clobbered.
1973     //
1974     // Insert s_dcache_wb at wave termination points if there were any scalar
1975     // stores, and only if the cache hasn't already been flushed. This could be
1976     // improved by looking across blocks for flushes in postdominating blocks
1977     // from the stores but an explicitly requested flush is probably very rare.
1978     for (MachineBasicBlock *MBB : EndPgmBlocks) {
1979       bool SeenDCacheWB = false;
1980 
1981       for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
1982            ++I) {
1983         if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
1984           SeenDCacheWB = true;
1985         else if (TII->isScalarStore(*I))
1986           SeenDCacheWB = false;
1987 
1988         // FIXME: It would be better to insert this before a waitcnt if any.
1989         if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
1990              I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
1991             !SeenDCacheWB) {
1992           Modified = true;
1993           BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
1994         }
1995       }
1996     }
1997   }
1998 
1999   if (!MFI->isEntryFunction()) {
2000     // Wait for any outstanding memory operations that the input registers may
2001     // depend on. We can't track them and it's better to the wait after the
2002     // costly call sequence.
2003 
2004     // TODO: Could insert earlier and schedule more liberally with operations
2005     // that only use caller preserved registers.
2006     MachineBasicBlock &EntryBB = MF.front();
2007     BuildMI(EntryBB, EntryBB.getFirstNonPHI(), DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
2008       .addImm(0);
2009 
2010     Modified = true;
2011   }
2012 
2013   return Modified;
2014 }
2015