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