1 //===-- SIInsertWaitcnts.cpp - Insert Wait Instructions --------------------===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Insert wait instructions for memory reads and writes.
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.
17 //===----------------------------------------------------------------------===//
20 #include "AMDGPUSubtarget.h"
21 #include "SIDefines.h"
22 #include "SIInstrInfo.h"
23 #include "SIMachineFunctionInfo.h"
24 #include "Utils/AMDGPUBaseInfo.h"
25 #include "llvm/ADT/PostOrderIterator.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #define DEBUG_TYPE "si-insert-waitcnts"
37 // Class of object that encapsulates latest instruction counter score
38 // associated with the operand. Used for determining whether
39 // s_waitcnt instruction needs to be emited.
41 #define CNT_MASK(t) (1u << (t))
43 enum InstCounterType { VM_CNT = 0, LGKM_CNT, EXP_CNT, NUM_INST_CNTS };
45 typedef std::pair<signed, signed> RegInterval;
63 VMEM_ACCESS, // vector-memory read & write
64 LDS_ACCESS, // lds read & write
65 GDS_ACCESS, // gds read & write
66 SQ_MESSAGE, // send message
67 SMEM_ACCESS, // scalar-memory read & write
68 EXP_GPR_LOCK, // export holding on its data src
69 GDS_GPR_LOCK, // GDS holding on its data and addr src
70 EXP_POS_ACCESS, // write to export position
71 EXP_PARAM_ACCESS, // write to export parameter
72 VMW_GPR_LOCK, // vector-memory write holding on its data src
77 // 0 .. SQ_MAX_PGM_VGPRS-1 real VGPRs
78 // SQ_MAX_PGM_VGPRS .. NUM_ALL_VGPRS-1 extra VGPR-like slots
79 // NUM_ALL_VGPRS .. NUM_ALL_VGPRS+SQ_MAX_PGM_SGPRS-1 real SGPRs
80 // We reserve a fixed number of VGPR slots in the scoring tables for
81 // special tokens like SCMEM_LDS (needed for buffer load to LDS).
82 enum RegisterMapping {
83 SQ_MAX_PGM_VGPRS = 256, // Maximum programmable VGPRs across all targets.
84 SQ_MAX_PGM_SGPRS = 256, // Maximum programmable SGPRs across all targets.
85 NUM_EXTRA_VGPRS = 1, // A reserved slot for DS.
86 EXTRA_VGPR_LDS = 0, // This is a placeholder the Shader algorithm uses.
87 NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_EXTRA_VGPRS, // Where SGPR starts.
90 #define ForAllWaitEventType(w) \
91 for (enum WaitEventType w = (enum WaitEventType)0; \
92 (w) < (enum WaitEventType)NUM_WAIT_EVENTS; \
93 (w) = (enum WaitEventType)((w) + 1))
95 // This is a per-basic-block object that maintains current score brackets
96 // of each wait-counter, and a per-register scoreboard for each wait-couner.
97 // We also maintain the latest score for every event type that can change the
98 // waitcnt in order to know if there are multiple types of events within
99 // the brackets. When multiple types of event happen in the bracket,
100 // wait-count may get decreased out of order, therefore we need to put in
101 // "s_waitcnt 0" before use.
102 class BlockWaitcntBrackets {
104 static int32_t getWaitCountMax(InstCounterType T) {
107 return HardwareLimits.VmcntMax;
109 return HardwareLimits.LgkmcntMax;
111 return HardwareLimits.ExpcntMax;
118 void setScoreLB(InstCounterType T, int32_t Val) {
119 assert(T < NUM_INST_CNTS);
120 if (T >= NUM_INST_CNTS)
125 void setScoreUB(InstCounterType T, int32_t Val) {
126 assert(T < NUM_INST_CNTS);
127 if (T >= NUM_INST_CNTS)
131 int32_t UB = (int)(ScoreUBs[T] - getWaitCountMax(EXP_CNT));
132 if (ScoreLBs[T] < UB)
137 int32_t getScoreLB(InstCounterType T) {
138 assert(T < NUM_INST_CNTS);
139 if (T >= NUM_INST_CNTS)
144 int32_t getScoreUB(InstCounterType T) {
145 assert(T < NUM_INST_CNTS);
146 if (T >= NUM_INST_CNTS)
151 // Mapping from event to counter.
152 InstCounterType eventCounter(WaitEventType E) {
165 case EXP_PARAM_ACCESS:
168 llvm_unreachable("unhandled event type");
170 return NUM_INST_CNTS;
173 void setRegScore(int GprNo, InstCounterType T, int32_t Val) {
174 if (GprNo < NUM_ALL_VGPRS) {
175 if (GprNo > VgprUB) {
178 VgprScores[T][GprNo] = Val;
180 assert(T == LGKM_CNT);
181 if (GprNo - NUM_ALL_VGPRS > SgprUB) {
182 SgprUB = GprNo - NUM_ALL_VGPRS;
184 SgprScores[GprNo - NUM_ALL_VGPRS] = Val;
188 int32_t getRegScore(int GprNo, InstCounterType T) {
189 if (GprNo < NUM_ALL_VGPRS) {
190 return VgprScores[T][GprNo];
192 return SgprScores[GprNo - NUM_ALL_VGPRS];
196 memset(ScoreLBs, 0, sizeof(ScoreLBs));
197 memset(ScoreUBs, 0, sizeof(ScoreUBs));
198 memset(EventUBs, 0, sizeof(EventUBs));
199 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
200 T = (enum InstCounterType)(T + 1)) {
201 memset(VgprScores[T], 0, sizeof(VgprScores[T]));
203 memset(SgprScores, 0, sizeof(SgprScores));
206 RegInterval getRegInterval(const MachineInstr *MI, const SIInstrInfo *TII,
207 const MachineRegisterInfo *MRI,
208 const SIRegisterInfo *TRI, unsigned OpNo,
211 void setExpScore(const MachineInstr *MI, const SIInstrInfo *TII,
212 const SIRegisterInfo *TRI, const MachineRegisterInfo *MRI,
213 unsigned OpNo, int32_t Val);
215 void setWaitAtBeginning() { WaitAtBeginning = true; }
216 void clearWaitAtBeginning() { WaitAtBeginning = false; }
217 bool getWaitAtBeginning() const { return WaitAtBeginning; }
218 void setEventUB(enum WaitEventType W, int32_t Val) { EventUBs[W] = Val; }
219 int32_t getMaxVGPR() const { return VgprUB; }
220 int32_t getMaxSGPR() const { return SgprUB; }
221 int32_t getEventUB(enum WaitEventType W) const {
222 assert(W < NUM_WAIT_EVENTS);
225 bool counterOutOfOrder(InstCounterType T);
226 unsigned int updateByWait(InstCounterType T, int ScoreToWait);
227 void updateByEvent(const SIInstrInfo *TII, const SIRegisterInfo *TRI,
228 const MachineRegisterInfo *MRI, WaitEventType E,
231 BlockWaitcntBrackets()
232 : WaitAtBeginning(false), ValidLoop(false), MixedExpTypes(false),
233 LoopRegion(NULL), PostOrder(0), Waitcnt(NULL), VgprUB(0), SgprUB(0) {
234 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
235 T = (enum InstCounterType)(T + 1)) {
236 memset(VgprScores[T], 0, sizeof(VgprScores[T]));
239 ~BlockWaitcntBrackets(){};
241 bool hasPendingSMEM() const {
242 return (EventUBs[SMEM_ACCESS] > ScoreLBs[LGKM_CNT] &&
243 EventUBs[SMEM_ACCESS] <= ScoreUBs[LGKM_CNT]);
246 bool hasPendingFlat() const {
247 return ((LastFlat[LGKM_CNT] > ScoreLBs[LGKM_CNT] &&
248 LastFlat[LGKM_CNT] <= ScoreUBs[LGKM_CNT]) ||
249 (LastFlat[VM_CNT] > ScoreLBs[VM_CNT] &&
250 LastFlat[VM_CNT] <= ScoreUBs[VM_CNT]));
253 void setPendingFlat() {
254 LastFlat[VM_CNT] = ScoreUBs[VM_CNT];
255 LastFlat[LGKM_CNT] = ScoreUBs[LGKM_CNT];
258 int pendingFlat(InstCounterType Ct) const { return LastFlat[Ct]; }
260 void setLastFlat(InstCounterType Ct, int Val) { LastFlat[Ct] = Val; }
262 bool getRevisitLoop() const { return RevisitLoop; }
263 void setRevisitLoop(bool RevisitLoopIn) { RevisitLoop = RevisitLoopIn; }
265 void setPostOrder(int32_t PostOrderIn) { PostOrder = PostOrderIn; }
266 int32_t getPostOrder() const { return PostOrder; }
268 void setWaitcnt(MachineInstr *WaitcntIn) { Waitcnt = WaitcntIn; }
269 void clearWaitcnt() { Waitcnt = NULL; }
270 MachineInstr *getWaitcnt() const { return Waitcnt; }
272 bool mixedExpTypes() const { return MixedExpTypes; }
273 void setMixedExpTypes(bool MixedExpTypesIn) {
274 MixedExpTypes = MixedExpTypesIn;
277 void print(raw_ostream &);
278 void dump() { print(dbgs()); }
281 bool WaitAtBeginning;
285 MachineLoop *LoopRegion;
287 MachineInstr *Waitcnt;
288 int32_t ScoreLBs[NUM_INST_CNTS] = {0};
289 int32_t ScoreUBs[NUM_INST_CNTS] = {0};
290 int32_t EventUBs[NUM_WAIT_EVENTS] = {0};
291 // Remember the last flat memory operation.
292 int32_t LastFlat[NUM_INST_CNTS] = {0};
293 // wait_cnt scores for every vgpr.
294 // Keep track of the VgprUB and SgprUB to make merge at join efficient.
297 int32_t VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS];
298 // Wait cnt scores for every sgpr, only lgkmcnt is relevant.
299 int32_t SgprScores[SQ_MAX_PGM_SGPRS] = {0};
302 // This is a per-loop-region object that records waitcnt status at the end of
303 // loop footer from the previous iteration. We also maintain an iteration
304 // count to track the number of times the loop has been visited. When it
305 // doesn't converge naturally, we force convergence by inserting s_waitcnt 0
306 // at the end of the loop footer.
307 class LoopWaitcntData {
309 void incIterCnt() { IterCnt++; }
310 void resetIterCnt() { IterCnt = 0; }
311 int32_t getIterCnt() { return IterCnt; }
313 LoopWaitcntData() : LfWaitcnt(NULL), IterCnt(0) {}
314 ~LoopWaitcntData(){};
316 void setWaitcnt(MachineInstr *WaitcntIn) { LfWaitcnt = WaitcntIn; }
317 MachineInstr *getWaitcnt() const { return LfWaitcnt; }
320 DEBUG(dbgs() << " iteration " << IterCnt << '\n';);
325 // s_waitcnt added at the end of loop footer to stablize wait scores
326 // at the end of the loop footer.
327 MachineInstr *LfWaitcnt;
328 // Number of iterations the loop has been visited, not including the initial
333 class SIInsertWaitcnts : public MachineFunctionPass {
336 const SISubtarget *ST;
337 const SIInstrInfo *TII;
338 const SIRegisterInfo *TRI;
339 const MachineRegisterInfo *MRI;
340 const MachineLoopInfo *MLI;
341 AMDGPU::IsaInfo::IsaVersion IV;
344 DenseSet<MachineBasicBlock *> BlockVisitedSet;
345 DenseSet<MachineInstr *> CompilerGeneratedWaitcntSet;
346 DenseSet<MachineInstr *> VCCZBugHandledSet;
348 DenseMap<MachineBasicBlock *, std::unique_ptr<BlockWaitcntBrackets>>
349 BlockWaitcntBracketsMap;
351 DenseSet<MachineBasicBlock *> BlockWaitcntProcessedSet;
353 DenseMap<MachineLoop *, std::unique_ptr<LoopWaitcntData>> LoopWaitcntDataMap;
355 std::vector<std::unique_ptr<BlockWaitcntBrackets>> KillWaitBrackets;
361 : MachineFunctionPass(ID), ST(nullptr), TII(nullptr), TRI(nullptr),
362 MRI(nullptr), MLI(nullptr) {}
364 bool runOnMachineFunction(MachineFunction &MF) override;
366 StringRef getPassName() const override {
367 return "SI insert wait instructions";
370 void getAnalysisUsage(AnalysisUsage &AU) const override {
371 AU.setPreservesCFG();
372 AU.addRequired<MachineLoopInfo>();
373 MachineFunctionPass::getAnalysisUsage(AU);
376 void addKillWaitBracket(BlockWaitcntBrackets *Bracket) {
377 // The waitcnt information is copied because it changes as the block is
379 KillWaitBrackets.push_back(make_unique<BlockWaitcntBrackets>(*Bracket));
382 MachineInstr *generateSWaitCntInstBefore(MachineInstr &MI,
383 BlockWaitcntBrackets *ScoreBrackets);
384 void updateEventWaitCntAfter(MachineInstr &Inst,
385 BlockWaitcntBrackets *ScoreBrackets);
386 void mergeInputScoreBrackets(MachineBasicBlock &Block);
387 MachineBasicBlock *loopBottom(const MachineLoop *Loop);
388 void insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block);
389 void insertWaitcntBeforeCF(MachineBasicBlock &Block, MachineInstr *Inst);
392 } // End anonymous namespace.
394 RegInterval BlockWaitcntBrackets::getRegInterval(const MachineInstr *MI,
395 const SIInstrInfo *TII,
396 const MachineRegisterInfo *MRI,
397 const SIRegisterInfo *TRI,
400 const MachineOperand &Op = MI->getOperand(OpNo);
401 if (!Op.isReg() || !TRI->isInAllocatableClass(Op.getReg()) ||
402 (Def && !Op.isDef()))
405 // A use via a PW operand does not need a waitcnt.
406 // A partial write is not a WAW.
407 assert(!Op.getSubReg() || !Op.isUndef());
410 const MachineRegisterInfo &MRIA = *MRI;
412 unsigned Reg = TRI->getEncodingValue(Op.getReg());
414 if (TRI->isVGPR(MRIA, Op.getReg())) {
415 assert(Reg >= RegisterEncoding.VGPR0 && Reg <= RegisterEncoding.VGPRL);
416 Result.first = Reg - RegisterEncoding.VGPR0;
417 assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS);
418 } else if (TRI->isSGPRReg(MRIA, Op.getReg())) {
419 assert(Reg >= RegisterEncoding.SGPR0 && Reg < SQ_MAX_PGM_SGPRS);
420 Result.first = Reg - RegisterEncoding.SGPR0 + NUM_ALL_VGPRS;
421 assert(Result.first >= NUM_ALL_VGPRS &&
422 Result.first < SQ_MAX_PGM_SGPRS + NUM_ALL_VGPRS);
425 // else if (TRI->isTTMP(MRIA, Reg.getReg())) ...
429 const MachineInstr &MIA = *MI;
430 const TargetRegisterClass *RC = TII->getOpRegClass(MIA, OpNo);
431 unsigned Size = TRI->getRegSizeInBits(*RC);
432 Result.second = Result.first + (Size / 32);
437 void BlockWaitcntBrackets::setExpScore(const MachineInstr *MI,
438 const SIInstrInfo *TII,
439 const SIRegisterInfo *TRI,
440 const MachineRegisterInfo *MRI,
441 unsigned OpNo, int32_t Val) {
442 RegInterval Interval = getRegInterval(MI, TII, MRI, TRI, OpNo, false);
444 const MachineOperand &Opnd = MI->getOperand(OpNo);
445 assert(TRI->isVGPR(*MRI, Opnd.getReg()));
447 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
448 setRegScore(RegNo, EXP_CNT, Val);
452 void BlockWaitcntBrackets::updateByEvent(const SIInstrInfo *TII,
453 const SIRegisterInfo *TRI,
454 const MachineRegisterInfo *MRI,
455 WaitEventType E, MachineInstr &Inst) {
456 const MachineRegisterInfo &MRIA = *MRI;
457 InstCounterType T = eventCounter(E);
458 int32_t CurrScore = getScoreUB(T) + 1;
459 // EventUB and ScoreUB need to be update regardless if this event changes
460 // the score of a register or not.
461 // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
462 EventUBs[E] = CurrScore;
463 setScoreUB(T, CurrScore);
466 // Check for mixed export types. If they are mixed, then a waitcnt exp(0)
468 if (!MixedExpTypes) {
469 MixedExpTypes = counterOutOfOrder(EXP_CNT);
472 // Put score on the source vgprs. If this is a store, just use those
473 // specific register(s).
474 if (TII->isDS(Inst) && (Inst.mayStore() || Inst.mayLoad())) {
475 // All GDS operations must protect their address register (same as
477 if (Inst.getOpcode() != AMDGPU::DS_APPEND &&
478 Inst.getOpcode() != AMDGPU::DS_CONSUME) {
480 &Inst, TII, TRI, MRI,
481 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::addr),
484 if (Inst.mayStore()) {
486 &Inst, TII, TRI, MRI,
487 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0),
489 if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
490 AMDGPU::OpName::data1) != -1) {
491 setExpScore(&Inst, TII, TRI, MRI,
492 AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
493 AMDGPU::OpName::data1),
496 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1 &&
497 Inst.getOpcode() != AMDGPU::DS_GWS_INIT &&
498 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_V &&
499 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_BR &&
500 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_P &&
501 Inst.getOpcode() != AMDGPU::DS_GWS_BARRIER &&
502 Inst.getOpcode() != AMDGPU::DS_APPEND &&
503 Inst.getOpcode() != AMDGPU::DS_CONSUME &&
504 Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
505 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
506 const MachineOperand &Op = Inst.getOperand(I);
507 if (Op.isReg() && !Op.isDef() && TRI->isVGPR(MRIA, Op.getReg())) {
508 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
512 } else if (TII->isFLAT(Inst)) {
513 if (Inst.mayStore()) {
515 &Inst, TII, TRI, MRI,
516 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
518 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
520 &Inst, TII, TRI, MRI,
521 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
524 } else if (TII->isMIMG(Inst)) {
525 if (Inst.mayStore()) {
526 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
527 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
529 &Inst, TII, TRI, MRI,
530 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
533 } else if (TII->isMTBUF(Inst)) {
534 if (Inst.mayStore()) {
535 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
537 } else if (TII->isMUBUF(Inst)) {
538 if (Inst.mayStore()) {
539 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
540 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
542 &Inst, TII, TRI, MRI,
543 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
547 if (TII->isEXP(Inst)) {
548 // For export the destination registers are really temps that
549 // can be used as the actual source after export patching, so
550 // we need to treat them like sources and set the EXP_CNT
552 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
553 MachineOperand &DefMO = Inst.getOperand(I);
554 if (DefMO.isReg() && DefMO.isDef() &&
555 TRI->isVGPR(MRIA, DefMO.getReg())) {
556 setRegScore(TRI->getEncodingValue(DefMO.getReg()), EXP_CNT,
561 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
562 MachineOperand &MO = Inst.getOperand(I);
563 if (MO.isReg() && !MO.isDef() && TRI->isVGPR(MRIA, MO.getReg())) {
564 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
568 #if 0 // TODO: check if this is handled by MUBUF code above.
569 } else if (Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORD ||
570 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX2 ||
571 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX4) {
572 MachineOperand *MO = TII->getNamedOperand(Inst, AMDGPU::OpName::data);
573 unsigned OpNo;//TODO: find the OpNo for this operand;
574 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, OpNo, false);
575 for (signed RegNo = Interval.first; RegNo < Interval.second;
577 setRegScore(RegNo + NUM_ALL_VGPRS, t, CurrScore);
581 // Match the score to the destination registers.
582 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
583 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, I, true);
584 if (T == VM_CNT && Interval.first >= NUM_ALL_VGPRS)
586 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
587 setRegScore(RegNo, T, CurrScore);
590 if (TII->isDS(Inst) && Inst.mayStore()) {
591 setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS, T, CurrScore);
596 void BlockWaitcntBrackets::print(raw_ostream &OS) {
598 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
599 T = (enum InstCounterType)(T + 1)) {
600 int LB = getScoreLB(T);
601 int UB = getScoreUB(T);
605 OS << " VM_CNT(" << UB - LB << "): ";
608 OS << " LGKM_CNT(" << UB - LB << "): ";
611 OS << " EXP_CNT(" << UB - LB << "): ";
614 OS << " UNKNOWN(" << UB - LB << "): ";
619 // Print vgpr scores.
620 for (int J = 0; J <= getMaxVGPR(); J++) {
621 int RegScore = getRegScore(J, T);
624 int RelScore = RegScore - LB - 1;
625 if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) {
626 OS << RelScore << ":v" << J << " ";
628 OS << RelScore << ":ds ";
631 // Also need to print sgpr scores for lgkm_cnt.
633 for (int J = 0; J <= getMaxSGPR(); J++) {
634 int RegScore = getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
637 int RelScore = RegScore - LB - 1;
638 OS << RelScore << ":s" << J << " ";
648 unsigned int BlockWaitcntBrackets::updateByWait(InstCounterType T,
650 unsigned int NeedWait = 0;
651 if (ScoreToWait == -1) {
652 // The score to wait is unknown. This implies that it was not encountered
653 // during the path of the CFG walk done during the current traversal but
654 // may be seen on a different path. Emit an s_wait counter with a
655 // conservative value of 0 for the counter.
656 NeedWait = CNT_MASK(T);
657 setScoreLB(T, getScoreUB(T));
661 // If the score of src_operand falls within the bracket, we need an
662 // s_waitcnt instruction.
663 const int32_t LB = getScoreLB(T);
664 const int32_t UB = getScoreUB(T);
665 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
666 if (T == VM_CNT && hasPendingFlat()) {
667 // If there is a pending FLAT operation, and this is a VM waitcnt,
668 // then we need to force a waitcnt 0 for VM.
669 NeedWait = CNT_MASK(T);
670 setScoreLB(T, getScoreUB(T));
671 } else if (counterOutOfOrder(T)) {
672 // Counter can get decremented out-of-order when there
673 // are multiple types event in the brack. Also emit an s_wait counter
674 // with a conservative value of 0 for the counter.
675 NeedWait = CNT_MASK(T);
676 setScoreLB(T, getScoreUB(T));
678 NeedWait = CNT_MASK(T);
679 setScoreLB(T, ScoreToWait);
686 // Where there are multiple types of event in the bracket of a counter,
687 // the decrement may go out of order.
688 bool BlockWaitcntBrackets::counterOutOfOrder(InstCounterType T) {
693 if (EventUBs[SMEM_ACCESS] > ScoreLBs[LGKM_CNT] &&
694 EventUBs[SMEM_ACCESS] <= ScoreUBs[LGKM_CNT]) {
695 // Scalar memory read always can go out of order.
698 int NumEventTypes = 0;
699 if (EventUBs[LDS_ACCESS] > ScoreLBs[LGKM_CNT] &&
700 EventUBs[LDS_ACCESS] <= ScoreUBs[LGKM_CNT]) {
703 if (EventUBs[GDS_ACCESS] > ScoreLBs[LGKM_CNT] &&
704 EventUBs[GDS_ACCESS] <= ScoreUBs[LGKM_CNT]) {
707 if (EventUBs[SQ_MESSAGE] > ScoreLBs[LGKM_CNT] &&
708 EventUBs[SQ_MESSAGE] <= ScoreUBs[LGKM_CNT]) {
711 if (NumEventTypes <= 1) {
717 // If there has been a mixture of export types, then a waitcnt exp(0) is
721 int NumEventTypes = 0;
722 if (EventUBs[EXP_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
723 EventUBs[EXP_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
726 if (EventUBs[GDS_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
727 EventUBs[GDS_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
730 if (EventUBs[VMW_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
731 EventUBs[VMW_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
734 if (EventUBs[EXP_PARAM_ACCESS] > ScoreLBs[EXP_CNT] &&
735 EventUBs[EXP_PARAM_ACCESS] <= ScoreUBs[EXP_CNT]) {
739 if (EventUBs[EXP_POS_ACCESS] > ScoreLBs[EXP_CNT] &&
740 EventUBs[EXP_POS_ACCESS] <= ScoreUBs[EXP_CNT]) {
744 if (NumEventTypes <= 1) {
755 INITIALIZE_PASS_BEGIN(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
757 INITIALIZE_PASS_END(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
760 char SIInsertWaitcnts::ID = 0;
762 char &llvm::SIInsertWaitcntsID = SIInsertWaitcnts::ID;
764 FunctionPass *llvm::createSIInsertWaitcntsPass() {
765 return new SIInsertWaitcnts();
768 static bool readsVCCZ(const MachineInstr &MI) {
769 unsigned Opc = MI.getOpcode();
770 return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
771 !MI.getOperand(1).isUndef();
774 /// \brief Generate s_waitcnt instruction to be placed before cur_Inst.
775 /// Instructions of a given type are returned in order,
776 /// but instructions of different types can complete out of order.
777 /// We rely on this in-order completion
778 /// and simply assign a score to the memory access instructions.
779 /// We keep track of the active "score bracket" to determine
780 /// if an access of a memory read requires an s_waitcnt
781 /// and if so what the value of each counter is.
782 /// The "score bracket" is bound by the lower bound and upper bound
783 /// scores (*_score_LB and *_score_ub respectively).
784 MachineInstr *SIInsertWaitcnts::generateSWaitCntInstBefore(
785 MachineInstr &MI, BlockWaitcntBrackets *ScoreBrackets) {
786 // To emit, or not to emit - that's the question!
787 // Start with an assumption that there is no need to emit.
788 unsigned int EmitSwaitcnt = 0;
789 // s_waitcnt instruction to return; default is NULL.
790 MachineInstr *SWaitInst = nullptr;
791 // No need to wait before phi. If a phi-move exists, then the wait should
792 // has been inserted before the move. If a phi-move does not exist, then
793 // wait should be inserted before the real use. The same is true for
794 // sc-merge. It is not a coincident that all these cases correspond to the
795 // instructions that are skipped in the assembling loop.
796 bool NeedLineMapping = false; // TODO: Check on this.
797 if (MI.isDebugValue() &&
798 // TODO: any other opcode?
803 // See if an s_waitcnt is forced at block entry, or is needed at
805 if (ScoreBrackets->getWaitAtBeginning()) {
806 // Note that we have already cleared the state, so we don't need to update
808 ScoreBrackets->clearWaitAtBeginning();
809 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
810 T = (enum InstCounterType)(T + 1)) {
811 EmitSwaitcnt |= CNT_MASK(T);
812 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
816 // See if this instruction has a forced S_WAITCNT VM.
817 // TODO: Handle other cases of NeedsWaitcntVmBefore()
818 else if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
819 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
820 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL) {
822 ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
825 // All waits must be resolved at call return.
826 // NOTE: this could be improved with knowledge of all call sites or
827 // with knowledge of the called routines.
828 if (MI.getOpcode() == AMDGPU::RETURN ||
829 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) {
830 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
831 T = (enum InstCounterType)(T + 1)) {
832 if (ScoreBrackets->getScoreUB(T) > ScoreBrackets->getScoreLB(T)) {
833 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
834 EmitSwaitcnt |= CNT_MASK(T);
838 // Resolve vm waits before gs-done.
839 else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
840 MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
841 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_) ==
842 AMDGPU::SendMsg::ID_GS_DONE)) {
843 if (ScoreBrackets->getScoreUB(VM_CNT) > ScoreBrackets->getScoreLB(VM_CNT)) {
844 ScoreBrackets->setScoreLB(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
845 EmitSwaitcnt |= CNT_MASK(VM_CNT);
848 #if 0 // TODO: the following blocks of logic when we have fence.
849 else if (MI.getOpcode() == SC_FENCE) {
850 const unsigned int group_size =
851 context->shader_info->GetMaxThreadGroupSize();
852 // group_size == 0 means thread group size is unknown at compile time
853 const bool group_is_multi_wave =
854 (group_size == 0 || group_size > target_info->GetWaveFrontSize());
855 const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence();
857 for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) {
858 SCRegType src_type = Inst->GetSrcType(i);
861 if (group_is_multi_wave ||
862 context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) {
863 EmitSwaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
864 ScoreBrackets->getScoreUB(LGKM_CNT));
865 // LDS may have to wait for VM_CNT after buffer load to LDS
866 if (target_info->HasBufferLoadToLDS()) {
867 EmitSwaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
868 ScoreBrackets->getScoreUB(VM_CNT));
874 if (group_is_multi_wave || fence_is_global) {
875 EmitSwaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
876 ScoreBrackets->getScoreUB(EXP_CNT));
877 EmitSwaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
878 ScoreBrackets->getScoreUB(LGKM_CNT));
886 if (group_is_multi_wave || fence_is_global) {
887 EmitSwaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
888 ScoreBrackets->getScoreUB(EXP_CNT));
889 EmitSwaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
890 ScoreBrackets->getScoreUB(VM_CNT));
902 // Export & GDS instructions do not read the EXEC mask until after the export
903 // is granted (which can occur well after the instruction is issued).
904 // The shader program must flush all EXP operations on the export-count
905 // before overwriting the EXEC mask.
907 if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
908 // Export and GDS are tracked individually, either may trigger a waitcnt
910 EmitSwaitcnt |= ScoreBrackets->updateByWait(
911 EXP_CNT, ScoreBrackets->getEventUB(EXP_GPR_LOCK));
912 EmitSwaitcnt |= ScoreBrackets->updateByWait(
913 EXP_CNT, ScoreBrackets->getEventUB(EXP_PARAM_ACCESS));
914 EmitSwaitcnt |= ScoreBrackets->updateByWait(
915 EXP_CNT, ScoreBrackets->getEventUB(EXP_POS_ACCESS));
916 EmitSwaitcnt |= ScoreBrackets->updateByWait(
917 EXP_CNT, ScoreBrackets->getEventUB(GDS_GPR_LOCK));
920 #if 0 // TODO: the following code to handle CALL.
921 // The argument passing for CALLs should suffice for VM_CNT and LGKM_CNT.
922 // However, there is a problem with EXP_CNT, because the call cannot
923 // easily tell if a register is used in the function, and if it did, then
924 // the referring instruction would have to have an S_WAITCNT, which is
925 // dependent on all call sites. So Instead, force S_WAITCNT for EXP_CNTs
927 if (MI.getOpcode() == SC_CALL) {
928 if (ScoreBrackets->getScoreUB(EXP_CNT) >
929 ScoreBrackets->getScoreLB(EXP_CNT)) {
930 ScoreBrackets->setScoreLB(EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
931 EmitSwaitcnt |= CNT_MASK(EXP_CNT);
936 // Look at the source operands of every instruction to see if
937 // any of them results from a previous memory operation that affects
938 // its current usage. If so, an s_waitcnt instruction needs to be
940 // If the source operand was defined by a load, add the s_waitcnt
942 for (const MachineMemOperand *Memop : MI.memoperands()) {
943 unsigned AS = Memop->getAddrSpace();
944 if (AS != AMDGPUASI.LOCAL_ADDRESS)
946 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
947 // VM_CNT is only relevant to vgpr or LDS.
948 EmitSwaitcnt |= ScoreBrackets->updateByWait(
949 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
951 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
952 const MachineOperand &Op = MI.getOperand(I);
953 const MachineRegisterInfo &MRIA = *MRI;
954 RegInterval Interval =
955 ScoreBrackets->getRegInterval(&MI, TII, MRI, TRI, I, false);
956 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
957 if (TRI->isVGPR(MRIA, Op.getReg())) {
958 // VM_CNT is only relevant to vgpr or LDS.
959 EmitSwaitcnt |= ScoreBrackets->updateByWait(
960 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
962 EmitSwaitcnt |= ScoreBrackets->updateByWait(
963 LGKM_CNT, ScoreBrackets->getRegScore(RegNo, LGKM_CNT));
966 // End of for loop that looks at all source operands to decide vm_wait_cnt
969 // Two cases are handled for destination operands:
970 // 1) If the destination operand was defined by a load, add the s_waitcnt
971 // instruction to guarantee the right WAW order.
972 // 2) If a destination operand that was used by a recent export/store ins,
973 // add s_waitcnt on exp_cnt to guarantee the WAR order.
975 for (const MachineMemOperand *Memop : MI.memoperands()) {
976 unsigned AS = Memop->getAddrSpace();
977 if (AS != AMDGPUASI.LOCAL_ADDRESS)
979 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
980 EmitSwaitcnt |= ScoreBrackets->updateByWait(
981 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
982 EmitSwaitcnt |= ScoreBrackets->updateByWait(
983 EXP_CNT, ScoreBrackets->getRegScore(RegNo, EXP_CNT));
986 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
987 MachineOperand &Def = MI.getOperand(I);
988 const MachineRegisterInfo &MRIA = *MRI;
989 RegInterval Interval =
990 ScoreBrackets->getRegInterval(&MI, TII, MRI, TRI, I, true);
991 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
992 if (TRI->isVGPR(MRIA, Def.getReg())) {
993 EmitSwaitcnt |= ScoreBrackets->updateByWait(
994 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
995 EmitSwaitcnt |= ScoreBrackets->updateByWait(
996 EXP_CNT, ScoreBrackets->getRegScore(RegNo, EXP_CNT));
998 EmitSwaitcnt |= ScoreBrackets->updateByWait(
999 LGKM_CNT, ScoreBrackets->getRegScore(RegNo, LGKM_CNT));
1001 } // End of for loop that looks at all dest operands.
1004 // TODO: Tie force zero to a compiler triage option.
1005 bool ForceZero = false;
1007 // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0
1008 // occurs before the instruction. Doing it here prevents any additional
1009 // S_WAITCNTs from being emitted if the instruction was marked as
1010 // requiring a WAITCNT beforehand.
1011 if (MI.getOpcode() == AMDGPU::S_BARRIER && ST->needWaitcntBeforeBarrier()) {
1013 ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
1014 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1015 EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
1016 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1017 LGKM_CNT, ScoreBrackets->getScoreUB(LGKM_CNT));
1020 // TODO: Remove this work-around, enable the assert for Bug 457939
1021 // after fixing the scheduler. Also, the Shader Compiler code is
1022 // independent of target.
1023 if (readsVCCZ(MI) && ST->getGeneration() <= SISubtarget::SEA_ISLANDS) {
1024 if (ScoreBrackets->getScoreLB(LGKM_CNT) <
1025 ScoreBrackets->getScoreUB(LGKM_CNT) &&
1026 ScoreBrackets->hasPendingSMEM()) {
1027 // Wait on everything, not just LGKM. vccz reads usually come from
1028 // terminators, and we always wait on everything at the end of the
1029 // block, so if we only wait on LGKM here, we might end up with
1030 // another s_waitcnt inserted right after this if there are non-LGKM
1031 // instructions still outstanding.
1033 EmitSwaitcnt = true;
1037 // Does this operand processing indicate s_wait counter update?
1039 int CntVal[NUM_INST_CNTS];
1041 bool UseDefaultWaitcntStrategy = true;
1043 // Force all waitcnts to 0.
1044 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1045 T = (enum InstCounterType)(T + 1)) {
1046 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
1049 CntVal[EXP_CNT] = 0;
1050 CntVal[LGKM_CNT] = 0;
1051 UseDefaultWaitcntStrategy = false;
1054 if (UseDefaultWaitcntStrategy) {
1055 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1056 T = (enum InstCounterType)(T + 1)) {
1057 if (EmitSwaitcnt & CNT_MASK(T)) {
1059 ScoreBrackets->getScoreUB(T) - ScoreBrackets->getScoreLB(T);
1060 int MaxDelta = ScoreBrackets->getWaitCountMax(T);
1061 if (Delta >= MaxDelta) {
1064 ScoreBrackets->setScoreLB(
1065 T, ScoreBrackets->getScoreUB(T) - MaxDelta);
1067 EmitSwaitcnt &= ~CNT_MASK(T);
1071 // If we are not waiting for a particular counter then encode
1072 // it as -1 which means "don't care."
1078 // If we are not waiting on any counter we can skip the wait altogether.
1079 if (EmitSwaitcnt != 0) {
1080 MachineInstr *OldWaitcnt = ScoreBrackets->getWaitcnt();
1081 int Imm = (!OldWaitcnt) ? 0 : OldWaitcnt->getOperand(0).getImm();
1082 if (!OldWaitcnt || (AMDGPU::decodeVmcnt(IV, Imm) !=
1083 (CntVal[VM_CNT] & AMDGPU::getVmcntBitMask(IV))) ||
1084 (AMDGPU::decodeExpcnt(IV, Imm) !=
1085 (CntVal[EXP_CNT] & AMDGPU::getExpcntBitMask(IV))) ||
1086 (AMDGPU::decodeLgkmcnt(IV, Imm) !=
1087 (CntVal[LGKM_CNT] & AMDGPU::getLgkmcntBitMask(IV)))) {
1088 MachineLoop *ContainingLoop = MLI->getLoopFor(MI.getParent());
1089 if (ContainingLoop) {
1090 MachineBasicBlock *TBB = ContainingLoop->getTopBlock();
1091 BlockWaitcntBrackets *ScoreBracket =
1092 BlockWaitcntBracketsMap[TBB].get();
1093 if (!ScoreBracket) {
1094 assert(BlockVisitedSet.find(TBB) == BlockVisitedSet.end());
1095 BlockWaitcntBracketsMap[TBB] = make_unique<BlockWaitcntBrackets>();
1096 ScoreBracket = BlockWaitcntBracketsMap[TBB].get();
1098 ScoreBracket->setRevisitLoop(true);
1099 DEBUG(dbgs() << "set-revisit: block"
1100 << ContainingLoop->getTopBlock()->getNumber() << '\n';);
1104 // Update an existing waitcount, or make a new one.
1105 MachineFunction &MF = *MI.getParent()->getParent();
1106 if (OldWaitcnt && OldWaitcnt->getOpcode() != AMDGPU::S_WAITCNT) {
1107 SWaitInst = OldWaitcnt;
1109 SWaitInst = MF.CreateMachineInstr(TII->get(AMDGPU::S_WAITCNT),
1111 CompilerGeneratedWaitcntSet.insert(SWaitInst);
1114 const MachineOperand &Op =
1115 MachineOperand::CreateImm(AMDGPU::encodeWaitcnt(
1116 IV, CntVal[VM_CNT], CntVal[EXP_CNT], CntVal[LGKM_CNT]));
1117 SWaitInst->addOperand(MF, Op);
1119 if (CntVal[EXP_CNT] == 0) {
1120 ScoreBrackets->setMixedExpTypes(false);
1128 void SIInsertWaitcnts::insertWaitcntBeforeCF(MachineBasicBlock &MBB,
1129 MachineInstr *Waitcnt) {
1131 MBB.push_back(Waitcnt);
1135 MachineBasicBlock::iterator It = MBB.end();
1136 MachineInstr *MI = &*(--It);
1137 if (MI->isBranch()) {
1138 MBB.insert(It, Waitcnt);
1140 MBB.push_back(Waitcnt);
1146 void SIInsertWaitcnts::updateEventWaitCntAfter(
1147 MachineInstr &Inst, BlockWaitcntBrackets *ScoreBrackets) {
1148 // Now look at the instruction opcode. If it is a memory access
1149 // instruction, update the upper-bound of the appropriate counter's
1150 // bracket and the destination operand scores.
1151 // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere.
1152 if (TII->isDS(Inst) && (Inst.mayLoad() || Inst.mayStore())) {
1153 if (TII->getNamedOperand(Inst, AMDGPU::OpName::gds)->getImm() != 0) {
1154 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
1155 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
1157 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1159 } else if (TII->isFLAT(Inst)) {
1160 assert(Inst.mayLoad() || Inst.mayStore());
1161 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1162 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1164 // This is a flat memory operation. Check to see if it has memory
1165 // tokens for both LDS and Memory, and if so mark it as a flat.
1166 bool FoundLDSMem = false;
1167 for (const MachineMemOperand *Memop : Inst.memoperands()) {
1168 unsigned AS = Memop->getAddrSpace();
1169 if (AS == AMDGPUASI.LOCAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS)
1173 // This is a flat memory operation, so note it - it will require
1174 // that both the VM and LGKM be flushed to zero if it is pending when
1175 // a VM or LGKM dependency occurs.
1177 ScoreBrackets->setPendingFlat();
1179 } else if (SIInstrInfo::isVMEM(Inst) &&
1180 // TODO: get a better carve out.
1181 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1 &&
1182 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_SC &&
1183 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_VOL) {
1184 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1185 if ( // TODO: assumed yes -- target_info->MemWriteNeedsExpWait() &&
1186 (Inst.mayStore() || AMDGPU::getAtomicNoRetOp(Inst.getOpcode()))) {
1187 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
1189 } else if (TII->isSMRD(Inst)) {
1190 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1192 switch (Inst.getOpcode()) {
1193 case AMDGPU::S_SENDMSG:
1194 case AMDGPU::S_SENDMSGHALT:
1195 ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
1198 case AMDGPU::EXP_DONE: {
1199 int Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
1200 if (Imm >= 32 && Imm <= 63)
1201 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
1202 else if (Imm >= 12 && Imm <= 15)
1203 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
1205 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
1208 case AMDGPU::S_MEMTIME:
1209 case AMDGPU::S_MEMREALTIME:
1210 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1218 void SIInsertWaitcnts::mergeInputScoreBrackets(MachineBasicBlock &Block) {
1219 BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&Block].get();
1220 int32_t MaxPending[NUM_INST_CNTS] = {0};
1221 int32_t MaxFlat[NUM_INST_CNTS] = {0};
1222 bool MixedExpTypes = false;
1224 // Clear the score bracket state.
1225 ScoreBrackets->clear();
1227 // Compute the number of pending elements on block entry.
1229 // IMPORTANT NOTE: If iterative handling of loops is added, the code will
1230 // need to handle single BBs with backedges to themselves. This means that
1231 // they will need to retain and not clear their initial state.
1233 // See if there are any uninitialized predecessors. If so, emit an
1234 // s_waitcnt 0 at the beginning of the block.
1235 for (MachineBasicBlock *pred : Block.predecessors()) {
1236 BlockWaitcntBrackets *PredScoreBrackets =
1237 BlockWaitcntBracketsMap[pred].get();
1238 bool Visited = BlockVisitedSet.find(pred) != BlockVisitedSet.end();
1239 if (!Visited || PredScoreBrackets->getWaitAtBeginning()) {
1242 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1243 T = (enum InstCounterType)(T + 1)) {
1245 PredScoreBrackets->getScoreUB(T) - PredScoreBrackets->getScoreLB(T);
1246 MaxPending[T] = std::max(MaxPending[T], span);
1248 PredScoreBrackets->pendingFlat(T) - PredScoreBrackets->getScoreLB(T);
1249 MaxFlat[T] = std::max(MaxFlat[T], span);
1252 MixedExpTypes |= PredScoreBrackets->mixedExpTypes();
1255 // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1256 // Also handle kills for exit block.
1257 if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1258 for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1259 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1260 T = (enum InstCounterType)(T + 1)) {
1261 int Span = KillWaitBrackets[I]->getScoreUB(T) -
1262 KillWaitBrackets[I]->getScoreLB(T);
1263 MaxPending[T] = std::max(MaxPending[T], Span);
1264 Span = KillWaitBrackets[I]->pendingFlat(T) -
1265 KillWaitBrackets[I]->getScoreLB(T);
1266 MaxFlat[T] = std::max(MaxFlat[T], Span);
1269 MixedExpTypes |= KillWaitBrackets[I]->mixedExpTypes();
1273 // Special handling for GDS_GPR_LOCK and EXP_GPR_LOCK.
1274 for (MachineBasicBlock *Pred : Block.predecessors()) {
1275 BlockWaitcntBrackets *PredScoreBrackets =
1276 BlockWaitcntBracketsMap[Pred].get();
1277 bool Visited = BlockVisitedSet.find(Pred) != BlockVisitedSet.end();
1278 if (!Visited || PredScoreBrackets->getWaitAtBeginning()) {
1282 int GDSSpan = PredScoreBrackets->getEventUB(GDS_GPR_LOCK) -
1283 PredScoreBrackets->getScoreLB(EXP_CNT);
1284 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], GDSSpan);
1285 int EXPSpan = PredScoreBrackets->getEventUB(EXP_GPR_LOCK) -
1286 PredScoreBrackets->getScoreLB(EXP_CNT);
1287 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], EXPSpan);
1290 // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1291 if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1292 for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1293 int GDSSpan = KillWaitBrackets[I]->getEventUB(GDS_GPR_LOCK) -
1294 KillWaitBrackets[I]->getScoreLB(EXP_CNT);
1295 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], GDSSpan);
1296 int EXPSpan = KillWaitBrackets[I]->getEventUB(EXP_GPR_LOCK) -
1297 KillWaitBrackets[I]->getScoreLB(EXP_CNT);
1298 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], EXPSpan);
1303 // LC does not (unlike) add a waitcnt at beginning. Leaving it as marker.
1304 // TODO: how does LC distinguish between function entry and main entry?
1305 // If this is the entry to a function, force a wait.
1306 MachineBasicBlock &Entry = Block.getParent()->front();
1307 if (Entry.getNumber() == Block.getNumber()) {
1308 ScoreBrackets->setWaitAtBeginning();
1313 // Now set the current Block's brackets to the largest ending bracket.
1314 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1315 T = (enum InstCounterType)(T + 1)) {
1316 ScoreBrackets->setScoreUB(T, MaxPending[T]);
1317 ScoreBrackets->setScoreLB(T, 0);
1318 ScoreBrackets->setLastFlat(T, MaxFlat[T]);
1321 ScoreBrackets->setMixedExpTypes(MixedExpTypes);
1323 // Set the register scoreboard.
1324 for (MachineBasicBlock *Pred : Block.predecessors()) {
1325 if (BlockVisitedSet.find(Pred) == BlockVisitedSet.end()) {
1329 BlockWaitcntBrackets *PredScoreBrackets =
1330 BlockWaitcntBracketsMap[Pred].get();
1332 // Now merge the gpr_reg_score information
1333 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1334 T = (enum InstCounterType)(T + 1)) {
1335 int PredLB = PredScoreBrackets->getScoreLB(T);
1336 int PredUB = PredScoreBrackets->getScoreUB(T);
1337 if (PredLB < PredUB) {
1338 int PredScale = MaxPending[T] - PredUB;
1339 // Merge vgpr scores.
1340 for (int J = 0; J <= PredScoreBrackets->getMaxVGPR(); J++) {
1341 int PredRegScore = PredScoreBrackets->getRegScore(J, T);
1342 if (PredRegScore <= PredLB)
1344 int NewRegScore = PredScale + PredRegScore;
1345 ScoreBrackets->setRegScore(
1346 J, T, std::max(ScoreBrackets->getRegScore(J, T), NewRegScore));
1348 // Also need to merge sgpr scores for lgkm_cnt.
1349 if (T == LGKM_CNT) {
1350 for (int J = 0; J <= PredScoreBrackets->getMaxSGPR(); J++) {
1352 PredScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
1353 if (PredRegScore <= PredLB)
1355 int NewRegScore = PredScale + PredRegScore;
1356 ScoreBrackets->setRegScore(
1357 J + NUM_ALL_VGPRS, LGKM_CNT,
1359 ScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT),
1366 // Also merge the WaitEvent information.
1367 ForAllWaitEventType(W) {
1368 enum InstCounterType T = PredScoreBrackets->eventCounter(W);
1369 int PredEventUB = PredScoreBrackets->getEventUB(W);
1370 if (PredEventUB > PredScoreBrackets->getScoreLB(T)) {
1372 MaxPending[T] + PredEventUB - PredScoreBrackets->getScoreUB(T);
1373 if (NewEventUB > 0) {
1374 ScoreBrackets->setEventUB(
1375 W, std::max(ScoreBrackets->getEventUB(W), NewEventUB));
1381 // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1382 // Set the register scoreboard.
1383 if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1384 for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1385 // Now merge the gpr_reg_score information.
1386 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1387 T = (enum InstCounterType)(T + 1)) {
1388 int PredLB = KillWaitBrackets[I]->getScoreLB(T);
1389 int PredUB = KillWaitBrackets[I]->getScoreUB(T);
1390 if (PredLB < PredUB) {
1391 int PredScale = MaxPending[T] - PredUB;
1392 // Merge vgpr scores.
1393 for (int J = 0; J <= KillWaitBrackets[I]->getMaxVGPR(); J++) {
1394 int PredRegScore = KillWaitBrackets[I]->getRegScore(J, T);
1395 if (PredRegScore <= PredLB)
1397 int NewRegScore = PredScale + PredRegScore;
1398 ScoreBrackets->setRegScore(
1399 J, T, std::max(ScoreBrackets->getRegScore(J, T), NewRegScore));
1401 // Also need to merge sgpr scores for lgkm_cnt.
1402 if (T == LGKM_CNT) {
1403 for (int J = 0; J <= KillWaitBrackets[I]->getMaxSGPR(); J++) {
1405 KillWaitBrackets[I]->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
1406 if (PredRegScore <= PredLB)
1408 int NewRegScore = PredScale + PredRegScore;
1409 ScoreBrackets->setRegScore(
1410 J + NUM_ALL_VGPRS, LGKM_CNT,
1412 ScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT),
1419 // Also merge the WaitEvent information.
1420 ForAllWaitEventType(W) {
1421 enum InstCounterType T = KillWaitBrackets[I]->eventCounter(W);
1422 int PredEventUB = KillWaitBrackets[I]->getEventUB(W);
1423 if (PredEventUB > KillWaitBrackets[I]->getScoreLB(T)) {
1425 MaxPending[T] + PredEventUB - KillWaitBrackets[I]->getScoreUB(T);
1426 if (NewEventUB > 0) {
1427 ScoreBrackets->setEventUB(
1428 W, std::max(ScoreBrackets->getEventUB(W), NewEventUB));
1435 // Special case handling of GDS_GPR_LOCK and EXP_GPR_LOCK. Merge this for the
1436 // sequencing predecessors, because changes to EXEC require waitcnts due to
1437 // the delayed nature of these operations.
1438 for (MachineBasicBlock *Pred : Block.predecessors()) {
1439 if (BlockVisitedSet.find(Pred) == BlockVisitedSet.end()) {
1443 BlockWaitcntBrackets *PredScoreBrackets =
1444 BlockWaitcntBracketsMap[Pred].get();
1446 int pred_gds_ub = PredScoreBrackets->getEventUB(GDS_GPR_LOCK);
1447 if (pred_gds_ub > PredScoreBrackets->getScoreLB(EXP_CNT)) {
1448 int new_gds_ub = MaxPending[EXP_CNT] + pred_gds_ub -
1449 PredScoreBrackets->getScoreUB(EXP_CNT);
1450 if (new_gds_ub > 0) {
1451 ScoreBrackets->setEventUB(
1453 std::max(ScoreBrackets->getEventUB(GDS_GPR_LOCK), new_gds_ub));
1456 int pred_exp_ub = PredScoreBrackets->getEventUB(EXP_GPR_LOCK);
1457 if (pred_exp_ub > PredScoreBrackets->getScoreLB(EXP_CNT)) {
1458 int new_exp_ub = MaxPending[EXP_CNT] + pred_exp_ub -
1459 PredScoreBrackets->getScoreUB(EXP_CNT);
1460 if (new_exp_ub > 0) {
1461 ScoreBrackets->setEventUB(
1463 std::max(ScoreBrackets->getEventUB(EXP_GPR_LOCK), new_exp_ub));
1469 /// Return the "bottom" block of a loop. This differs from
1470 /// MachineLoop::getBottomBlock in that it works even if the loop is
1472 MachineBasicBlock *SIInsertWaitcnts::loopBottom(const MachineLoop *Loop) {
1473 MachineBasicBlock *Bottom = Loop->getHeader();
1474 for (MachineBasicBlock *MBB : Loop->blocks())
1475 if (MBB->getNumber() > Bottom->getNumber())
1480 // Generate s_waitcnt instructions where needed.
1481 void SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
1482 MachineBasicBlock &Block) {
1483 // Initialize the state information.
1484 mergeInputScoreBrackets(Block);
1486 BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&Block].get();
1489 dbgs() << "Block" << Block.getNumber();
1490 ScoreBrackets->dump();
1493 bool InsertNOP = false;
1495 // Walk over the instructions.
1496 for (MachineBasicBlock::iterator Iter = Block.begin(), E = Block.end();
1498 MachineInstr &Inst = *Iter;
1499 // Remove any previously existing waitcnts.
1500 if (Inst.getOpcode() == AMDGPU::S_WAITCNT) {
1501 // TODO: Register the old waitcnt and optimize the following waitcnts.
1502 // Leaving the previously existing waitcnts is conservatively correct.
1503 if (CompilerGeneratedWaitcntSet.find(&Inst) ==
1504 CompilerGeneratedWaitcntSet.end())
1507 ScoreBrackets->setWaitcnt(&Inst);
1509 Inst.removeFromParent();
1514 // Kill instructions generate a conditional branch to the endmain block.
1515 // Merge the current waitcnt state into the endmain block information.
1516 // TODO: Are there other flavors of KILL instruction?
1517 if (Inst.getOpcode() == AMDGPU::KILL) {
1518 addKillWaitBracket(ScoreBrackets);
1521 bool VCCZBugWorkAround = false;
1522 if (readsVCCZ(Inst) &&
1523 (VCCZBugHandledSet.find(&Inst) == VCCZBugHandledSet.end())) {
1524 if (ScoreBrackets->getScoreLB(LGKM_CNT) <
1525 ScoreBrackets->getScoreUB(LGKM_CNT) &&
1526 ScoreBrackets->hasPendingSMEM()) {
1527 if (ST->getGeneration() <= SISubtarget::SEA_ISLANDS)
1528 VCCZBugWorkAround = true;
1532 // Generate an s_waitcnt instruction to be placed before
1533 // cur_Inst, if needed.
1534 MachineInstr *SWaitInst = generateSWaitCntInstBefore(Inst, ScoreBrackets);
1537 Block.insert(Inst, SWaitInst);
1538 if (ScoreBrackets->getWaitcnt() != SWaitInst) {
1539 DEBUG(dbgs() << "insertWaitcntInBlock\n"
1540 << "Old Instr: " << Inst << '\n'
1541 << "New Instr: " << *SWaitInst << '\n';);
1545 updateEventWaitCntAfter(Inst, ScoreBrackets);
1547 #if 0 // TODO: implement resource type check controlled by options with ub = LB.
1548 // If this instruction generates a S_SETVSKIP because it is an
1549 // indexed resource, and we are on Tahiti, then it will also force
1550 // an S_WAITCNT vmcnt(0)
1551 if (RequireCheckResourceType(Inst, context)) {
1552 // Force the score to as if an S_WAITCNT vmcnt(0) is emitted.
1553 ScoreBrackets->setScoreLB(VM_CNT,
1554 ScoreBrackets->getScoreUB(VM_CNT));
1558 ScoreBrackets->clearWaitcnt();
1561 DEBUG({ SWaitInst->print(dbgs() << '\n'); });
1565 ScoreBrackets->dump();
1568 // Check to see if this is a GWS instruction. If so, and if this is CI or
1569 // VI, then the generated code sequence will include an S_WAITCNT 0.
1570 // TODO: Are these the only GWS instructions?
1571 if (Inst.getOpcode() == AMDGPU::DS_GWS_INIT ||
1572 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_V ||
1573 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_BR ||
1574 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_P ||
1575 Inst.getOpcode() == AMDGPU::DS_GWS_BARRIER) {
1576 // TODO: && context->target_info->GwsRequiresMemViolTest() ) {
1577 ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
1578 ScoreBrackets->updateByWait(EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
1579 ScoreBrackets->updateByWait(LGKM_CNT,
1580 ScoreBrackets->getScoreUB(LGKM_CNT));
1583 // TODO: Remove this work-around after fixing the scheduler and enable the
1585 if (VCCZBugWorkAround) {
1586 // Restore the vccz bit. Any time a value is written to vcc, the vcc
1587 // bit is updated, so we can restore the bit by reading the value of
1588 // vcc and then writing it back to the register.
1589 BuildMI(Block, Inst, Inst.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
1591 .addReg(AMDGPU::VCC);
1592 VCCZBugHandledSet.insert(&Inst);
1595 if (ST->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
1597 // This avoids a s_nop after a waitcnt has just been inserted.
1598 if (!SWaitInst && InsertNOP) {
1599 BuildMI(Block, Inst, DebugLoc(), TII->get(AMDGPU::S_NOP)).addImm(0);
1603 // Any occurrence of consecutive VMEM or SMEM instructions forms a VMEM
1604 // or SMEM clause, respectively.
1606 // The temporary workaround is to break the clauses with S_NOP.
1608 // The proper solution would be to allocate registers such that all source
1609 // and destination registers don't overlap, e.g. this is illegal:
1612 bool IsSMEM = false;
1613 bool IsVMEM = false;
1614 if (TII->isSMRD(Inst))
1616 else if (TII->usesVM_CNT(Inst))
1623 MachineInstr &Next = *Iter;
1625 // TODO: How about consecutive SMEM instructions?
1626 // The comments above says break the clause but the code does not.
1627 // if ((TII->isSMRD(next) && isSMEM) ||
1628 if (!IsSMEM && TII->usesVM_CNT(Next) && IsVMEM &&
1629 // TODO: Enable this check when hasSoftClause is upstreamed.
1630 // ST->hasSoftClauses() &&
1631 ST->isXNACKEnabled()) {
1632 // Insert a NOP to break the clause.
1637 // There must be "S_NOP 0" between an instruction writing M0 and
1639 if ((Next.getOpcode() == AMDGPU::S_SENDMSG ||
1640 Next.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
1641 Inst.definesRegister(AMDGPU::M0))
1650 // Check if we need to force convergence at loop footer.
1651 MachineLoop *ContainingLoop = MLI->getLoopFor(&Block);
1652 if (ContainingLoop && loopBottom(ContainingLoop) == &Block) {
1653 LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1654 WaitcntData->print();
1655 DEBUG(dbgs() << '\n';);
1657 // The iterative waitcnt insertion algorithm aims for optimal waitcnt
1658 // placement and doesn't always guarantee convergence for a loop. Each
1659 // loop should take at most 2 iterations for it to converge naturally.
1660 // When this max is reached and result doesn't converge, we force
1661 // convergence by inserting a s_waitcnt at the end of loop footer.
1662 if (WaitcntData->getIterCnt() > 2) {
1663 // To ensure convergence, need to make wait events at loop footer be no
1664 // more than those from the previous iteration.
1665 // As a simplification, Instead of tracking individual scores and
1666 // generate the precise wait count, just wait on 0.
1667 bool HasPending = false;
1668 MachineInstr *SWaitInst = WaitcntData->getWaitcnt();
1669 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1670 T = (enum InstCounterType)(T + 1)) {
1671 if (ScoreBrackets->getScoreUB(T) > ScoreBrackets->getScoreLB(T)) {
1672 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
1679 SWaitInst = Block.getParent()->CreateMachineInstr(
1680 TII->get(AMDGPU::S_WAITCNT), DebugLoc());
1681 CompilerGeneratedWaitcntSet.insert(SWaitInst);
1682 const MachineOperand &Op = MachineOperand::CreateImm(0);
1683 SWaitInst->addOperand(MF, Op);
1684 #if 0 // TODO: Format the debug output
1685 OutputTransformBanner("insertWaitcntInBlock",0,"Create:",context);
1686 OutputTransformAdd(SWaitInst, context);
1690 _DEV( REPORTED_STATS->force_waitcnt_converge = 1; )
1696 SWaitInst->print(dbgs());
1697 dbgs() << "\nAdjusted score board:";
1698 ScoreBrackets->dump();
1701 // Add this waitcnt to the block. It is either newly created or
1702 // created in previous iterations and added back since block traversal
1703 // always remove waitcnt.
1704 insertWaitcntBeforeCF(Block, SWaitInst);
1705 WaitcntData->setWaitcnt(SWaitInst);
1711 bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) {
1712 ST = &MF.getSubtarget<SISubtarget>();
1713 TII = ST->getInstrInfo();
1714 TRI = &TII->getRegisterInfo();
1715 MRI = &MF.getRegInfo();
1716 MLI = &getAnalysis<MachineLoopInfo>();
1717 IV = AMDGPU::IsaInfo::getIsaVersion(ST->getFeatureBits());
1718 AMDGPUASI = ST->getAMDGPUAS();
1720 HardwareLimits.VmcntMax = AMDGPU::getVmcntBitMask(IV);
1721 HardwareLimits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
1722 HardwareLimits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV);
1724 HardwareLimits.NumVGPRsMax = ST->getAddressableNumVGPRs();
1725 HardwareLimits.NumSGPRsMax = ST->getAddressableNumSGPRs();
1726 assert(HardwareLimits.NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
1727 assert(HardwareLimits.NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
1729 RegisterEncoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0);
1730 RegisterEncoding.VGPRL =
1731 RegisterEncoding.VGPR0 + HardwareLimits.NumVGPRsMax - 1;
1732 RegisterEncoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0);
1733 RegisterEncoding.SGPRL =
1734 RegisterEncoding.SGPR0 + HardwareLimits.NumSGPRsMax - 1;
1736 // Walk over the blocks in reverse post-dominator order, inserting
1737 // s_waitcnt where needed.
1738 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1739 bool Modified = false;
1740 for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1742 E = RPOT.end(), J = RPOT.begin();
1744 MachineBasicBlock &MBB = **I;
1746 BlockVisitedSet.insert(&MBB);
1748 BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&MBB].get();
1749 if (!ScoreBrackets) {
1750 BlockWaitcntBracketsMap[&MBB] = make_unique<BlockWaitcntBrackets>();
1751 ScoreBrackets = BlockWaitcntBracketsMap[&MBB].get();
1753 ScoreBrackets->setPostOrder(MBB.getNumber());
1754 MachineLoop *ContainingLoop = MLI->getLoopFor(&MBB);
1755 if (ContainingLoop && LoopWaitcntDataMap[ContainingLoop] == nullptr)
1756 LoopWaitcntDataMap[ContainingLoop] = make_unique<LoopWaitcntData>();
1758 // If we are walking into the block from before the loop, then guarantee
1759 // at least 1 re-walk over the loop to propagate the information, even if
1760 // no S_WAITCNT instructions were generated.
1761 if (ContainingLoop && ContainingLoop->getTopBlock() == &MBB && J < I &&
1762 (BlockWaitcntProcessedSet.find(&MBB) ==
1763 BlockWaitcntProcessedSet.end())) {
1764 BlockWaitcntBracketsMap[&MBB]->setRevisitLoop(true);
1765 DEBUG(dbgs() << "set-revisit: block"
1766 << ContainingLoop->getTopBlock()->getNumber() << '\n';);
1769 // Walk over the instructions.
1770 insertWaitcntInBlock(MF, MBB);
1772 // Flag that waitcnts have been processed at least once.
1773 BlockWaitcntProcessedSet.insert(&MBB);
1775 // See if we want to revisit the loop.
1776 if (ContainingLoop && loopBottom(ContainingLoop) == &MBB) {
1777 MachineBasicBlock *EntryBB = ContainingLoop->getTopBlock();
1778 BlockWaitcntBrackets *EntrySB = BlockWaitcntBracketsMap[EntryBB].get();
1779 if (EntrySB && EntrySB->getRevisitLoop()) {
1780 EntrySB->setRevisitLoop(false);
1782 int32_t PostOrder = EntrySB->getPostOrder();
1783 // TODO: Avoid this loop. Find another way to set I.
1784 for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1788 MachineBasicBlock &MBBX = **X;
1789 if (MBBX.getNumber() == PostOrder) {
1794 LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1795 WaitcntData->incIterCnt();
1796 DEBUG(dbgs() << "revisit: block" << EntryBB->getNumber() << '\n';);
1799 LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1800 // Loop converged, reset iteration count. If this loop gets revisited,
1801 // it must be from an outer loop, the counter will restart, this will
1802 // ensure we don't force convergence on such revisits.
1803 WaitcntData->resetIterCnt();
1811 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
1813 bool HaveScalarStores = false;
1815 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE;
1818 MachineBasicBlock &MBB = *BI;
1820 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1823 if (!HaveScalarStores && TII->isScalarStore(*I))
1824 HaveScalarStores = true;
1826 if (I->getOpcode() == AMDGPU::S_ENDPGM ||
1827 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
1828 EndPgmBlocks.push_back(&MBB);
1832 if (HaveScalarStores) {
1833 // If scalar writes are used, the cache must be flushed or else the next
1834 // wave to reuse the same scratch memory can be clobbered.
1836 // Insert s_dcache_wb at wave termination points if there were any scalar
1837 // stores, and only if the cache hasn't already been flushed. This could be
1838 // improved by looking across blocks for flushes in postdominating blocks
1839 // from the stores but an explicitly requested flush is probably very rare.
1840 for (MachineBasicBlock *MBB : EndPgmBlocks) {
1841 bool SeenDCacheWB = false;
1843 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
1846 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
1847 SeenDCacheWB = true;
1848 else if (TII->isScalarStore(*I))
1849 SeenDCacheWB = false;
1851 // FIXME: It would be better to insert this before a waitcnt if any.
1852 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
1853 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
1856 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));