LLVM 22.0.0git
SIInsertWaitcnts.cpp
Go to the documentation of this file.
1//===- SIInsertWaitcnts.cpp - Insert Wait Instructions --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Insert wait instructions for memory reads and writes.
11///
12/// Memory reads and writes are issued asynchronously, so we need to insert
13/// S_WAITCNT instructions when we want to access any of their results or
14/// overwrite any register that's used asynchronously.
15///
16/// TODO: This pass currently keeps one timeline per hardware counter. A more
17/// finely-grained approach that keeps one timeline per event type could
18/// sometimes get away with generating weaker s_waitcnt instructions. For
19/// example, when both SMEM and LDS are in flight and we need to wait for
20/// the i-th-last LDS instruction, then an lgkmcnt(i) is actually sufficient,
21/// but the pass will currently generate a conservative lgkmcnt(0) because
22/// multiple event types are in flight.
23//
24//===----------------------------------------------------------------------===//
25
26#include "AMDGPU.h"
27#include "GCNSubtarget.h"
31#include "llvm/ADT/MapVector.h"
33#include "llvm/ADT/Sequence.h"
39#include "llvm/IR/Dominators.h"
43
44using namespace llvm;
45
46#define DEBUG_TYPE "si-insert-waitcnts"
47
48DEBUG_COUNTER(ForceExpCounter, DEBUG_TYPE "-forceexp",
49 "Force emit s_waitcnt expcnt(0) instrs");
50DEBUG_COUNTER(ForceLgkmCounter, DEBUG_TYPE "-forcelgkm",
51 "Force emit s_waitcnt lgkmcnt(0) instrs");
52DEBUG_COUNTER(ForceVMCounter, DEBUG_TYPE "-forcevm",
53 "Force emit s_waitcnt vmcnt(0) instrs");
54
55static cl::opt<bool>
56 ForceEmitZeroFlag("amdgpu-waitcnt-forcezero",
57 cl::desc("Force all waitcnt instrs to be emitted as "
58 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
59 cl::init(false), cl::Hidden);
60
62 "amdgpu-waitcnt-load-forcezero",
63 cl::desc("Force all waitcnt load counters to wait until 0"),
64 cl::init(false), cl::Hidden);
65
66namespace {
67// Class of object that encapsulates latest instruction counter score
68// associated with the operand. Used for determining whether
69// s_waitcnt instruction needs to be emitted.
70
71enum InstCounterType {
72 LOAD_CNT = 0, // VMcnt prior to gfx12.
73 DS_CNT, // LKGMcnt prior to gfx12.
74 EXP_CNT, //
75 STORE_CNT, // VScnt in gfx10/gfx11.
76 NUM_NORMAL_INST_CNTS,
77 SAMPLE_CNT = NUM_NORMAL_INST_CNTS, // gfx12+ only.
78 BVH_CNT, // gfx12+ only.
79 KM_CNT, // gfx12+ only.
80 X_CNT, // gfx1250.
81 NUM_EXTENDED_INST_CNTS,
82 NUM_INST_CNTS = NUM_EXTENDED_INST_CNTS
83};
84} // namespace
85
86namespace llvm {
87template <> struct enum_iteration_traits<InstCounterType> {
88 static constexpr bool is_iterable = true;
89};
90} // namespace llvm
91
92namespace {
93// Return an iterator over all counters between LOAD_CNT (the first counter)
94// and \c MaxCounter (exclusive, default value yields an enumeration over
95// all counters).
96auto inst_counter_types(InstCounterType MaxCounter = NUM_INST_CNTS) {
97 return enum_seq(LOAD_CNT, MaxCounter);
98}
99
100using RegInterval = std::pair<int, int>;
101
102struct HardwareLimits {
103 unsigned LoadcntMax; // Corresponds to VMcnt prior to gfx12.
104 unsigned ExpcntMax;
105 unsigned DscntMax; // Corresponds to LGKMcnt prior to gfx12.
106 unsigned StorecntMax; // Corresponds to VScnt in gfx10/gfx11.
107 unsigned SamplecntMax; // gfx12+ only.
108 unsigned BvhcntMax; // gfx12+ only.
109 unsigned KmcntMax; // gfx12+ only.
110 unsigned XcntMax; // gfx1250.
111};
112
113#define AMDGPU_DECLARE_WAIT_EVENTS(DECL) \
114 DECL(VMEM_ACCESS) /* vmem read & write */ \
115 DECL(VMEM_READ_ACCESS) /* vmem read */ \
116 DECL(VMEM_SAMPLER_READ_ACCESS) /* vmem SAMPLER read (gfx12+ only) */ \
117 DECL(VMEM_BVH_READ_ACCESS) /* vmem BVH read (gfx12+ only) */ \
118 DECL(VMEM_WRITE_ACCESS) /* vmem write that is not scratch */ \
119 DECL(SCRATCH_WRITE_ACCESS) /* vmem write that may be scratch */ \
120 DECL(VMEM_GROUP) /* vmem group */ \
121 DECL(LDS_ACCESS) /* lds read & write */ \
122 DECL(GDS_ACCESS) /* gds read & write */ \
123 DECL(SQ_MESSAGE) /* send message */ \
124 DECL(SCC_WRITE) /* write to SCC from barrier */ \
125 DECL(SMEM_ACCESS) /* scalar-memory read & write */ \
126 DECL(SMEM_GROUP) /* scalar-memory group */ \
127 DECL(EXP_GPR_LOCK) /* export holding on its data src */ \
128 DECL(GDS_GPR_LOCK) /* GDS holding on its data and addr src */ \
129 DECL(EXP_POS_ACCESS) /* write to export position */ \
130 DECL(EXP_PARAM_ACCESS) /* write to export parameter */ \
131 DECL(VMW_GPR_LOCK) /* vmem write holding on its data src */ \
132 DECL(EXP_LDS_ACCESS) /* read by ldsdir counting as export */
133
134// clang-format off
135#define AMDGPU_EVENT_ENUM(Name) Name,
136enum WaitEventType {
138 NUM_WAIT_EVENTS
139};
140#undef AMDGPU_EVENT_ENUM
141
142#define AMDGPU_EVENT_NAME(Name) #Name,
143static constexpr StringLiteral WaitEventTypeName[] = {
145};
146#undef AMDGPU_EVENT_NAME
147// clang-format on
148
149// The mapping is:
150// 0 .. SQ_MAX_PGM_VGPRS-1 real VGPRs
151// SQ_MAX_PGM_VGPRS .. NUM_ALL_VGPRS-1 extra VGPR-like slots
152// NUM_ALL_VGPRS .. NUM_ALL_VGPRS+SQ_MAX_PGM_SGPRS-1 real SGPRs
153// NUM_ALL_VGPRS+SQ_MAX_PGM_SGPRS .. SCC
154// We reserve a fixed number of VGPR slots in the scoring tables for
155// special tokens like SCMEM_LDS (needed for buffer load to LDS).
156enum RegisterMapping {
157 SQ_MAX_PGM_VGPRS = 2048, // Maximum programmable VGPRs across all targets.
158 AGPR_OFFSET = 512, // Maximum programmable ArchVGPRs across all targets.
159 SQ_MAX_PGM_SGPRS = 128, // Maximum programmable SGPRs across all targets.
160 // Artificial register slots to track LDS writes into specific LDS locations
161 // if a location is known. When slots are exhausted or location is
162 // unknown use the first slot. The first slot is also always updated in
163 // addition to known location's slot to properly generate waits if dependent
164 // instruction's location is unknown.
165 FIRST_LDS_VGPR = SQ_MAX_PGM_VGPRS, // Extra slots for LDS stores.
166 NUM_LDS_VGPRS = 9, // One more than the stores we track.
167 NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_LDS_VGPRS, // Where SGPRs start.
168 NUM_ALL_ALLOCATABLE = NUM_ALL_VGPRS + SQ_MAX_PGM_SGPRS,
169 // Remaining non-allocatable registers
170 SCC = NUM_ALL_ALLOCATABLE
171};
172
173// Enumerate different types of result-returning VMEM operations. Although
174// s_waitcnt orders them all with a single vmcnt counter, in the absence of
175// s_waitcnt only instructions of the same VmemType are guaranteed to write
176// their results in order -- so there is no need to insert an s_waitcnt between
177// two instructions of the same type that write the same vgpr.
178enum VmemType {
179 // BUF instructions and MIMG instructions without a sampler.
180 VMEM_NOSAMPLER,
181 // MIMG instructions with a sampler.
182 VMEM_SAMPLER,
183 // BVH instructions
184 VMEM_BVH,
185 NUM_VMEM_TYPES
186};
187
188// Maps values of InstCounterType to the instruction that waits on that
189// counter. Only used if GCNSubtarget::hasExtendedWaitCounts()
190// returns true.
191static const unsigned instrsForExtendedCounterTypes[NUM_EXTENDED_INST_CNTS] = {
192 AMDGPU::S_WAIT_LOADCNT, AMDGPU::S_WAIT_DSCNT, AMDGPU::S_WAIT_EXPCNT,
193 AMDGPU::S_WAIT_STORECNT, AMDGPU::S_WAIT_SAMPLECNT, AMDGPU::S_WAIT_BVHCNT,
194 AMDGPU::S_WAIT_KMCNT, AMDGPU::S_WAIT_XCNT};
195
196static bool updateVMCntOnly(const MachineInstr &Inst) {
197 return (SIInstrInfo::isVMEM(Inst) && !SIInstrInfo::isFLAT(Inst)) ||
199}
200
201#ifndef NDEBUG
202static bool isNormalMode(InstCounterType MaxCounter) {
203 return MaxCounter == NUM_NORMAL_INST_CNTS;
204}
205#endif // NDEBUG
206
207VmemType getVmemType(const MachineInstr &Inst) {
208 assert(updateVMCntOnly(Inst));
209 if (!SIInstrInfo::isImage(Inst))
210 return VMEM_NOSAMPLER;
212 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
214
215 if (BaseInfo->BVH)
216 return VMEM_BVH;
217
218 // We have to make an additional check for isVSAMPLE here since some
219 // instructions don't have a sampler, but are still classified as sampler
220 // instructions for the purposes of e.g. waitcnt.
221 if (BaseInfo->Sampler || BaseInfo->MSAA || SIInstrInfo::isVSAMPLE(Inst))
222 return VMEM_SAMPLER;
223
224 return VMEM_NOSAMPLER;
225}
226
227unsigned &getCounterRef(AMDGPU::Waitcnt &Wait, InstCounterType T) {
228 switch (T) {
229 case LOAD_CNT:
230 return Wait.LoadCnt;
231 case EXP_CNT:
232 return Wait.ExpCnt;
233 case DS_CNT:
234 return Wait.DsCnt;
235 case STORE_CNT:
236 return Wait.StoreCnt;
237 case SAMPLE_CNT:
238 return Wait.SampleCnt;
239 case BVH_CNT:
240 return Wait.BvhCnt;
241 case KM_CNT:
242 return Wait.KmCnt;
243 case X_CNT:
244 return Wait.XCnt;
245 default:
246 llvm_unreachable("bad InstCounterType");
247 }
248}
249
250void addWait(AMDGPU::Waitcnt &Wait, InstCounterType T, unsigned Count) {
251 unsigned &WC = getCounterRef(Wait, T);
252 WC = std::min(WC, Count);
253}
254
255void setNoWait(AMDGPU::Waitcnt &Wait, InstCounterType T) {
256 getCounterRef(Wait, T) = ~0u;
257}
258
259unsigned getWait(AMDGPU::Waitcnt &Wait, InstCounterType T) {
260 return getCounterRef(Wait, T);
261}
262
263// Mapping from event to counter according to the table masks.
264InstCounterType eventCounter(const unsigned *masks, WaitEventType E) {
265 for (auto T : inst_counter_types()) {
266 if (masks[T] & (1 << E))
267 return T;
268 }
269 llvm_unreachable("event type has no associated counter");
270}
271
272class WaitcntBrackets;
273
274// This abstracts the logic for generating and updating S_WAIT* instructions
275// away from the analysis that determines where they are needed. This was
276// done because the set of counters and instructions for waiting on them
277// underwent a major shift with gfx12, sufficiently so that having this
278// abstraction allows the main analysis logic to be simpler than it would
279// otherwise have had to become.
280class WaitcntGenerator {
281protected:
282 const GCNSubtarget *ST = nullptr;
283 const SIInstrInfo *TII = nullptr;
284 AMDGPU::IsaVersion IV;
285 InstCounterType MaxCounter;
286 bool OptNone;
287
288public:
289 WaitcntGenerator() = default;
290 WaitcntGenerator(const MachineFunction &MF, InstCounterType MaxCounter)
291 : ST(&MF.getSubtarget<GCNSubtarget>()), TII(ST->getInstrInfo()),
292 IV(AMDGPU::getIsaVersion(ST->getCPU())), MaxCounter(MaxCounter),
293 OptNone(MF.getFunction().hasOptNone() ||
294 MF.getTarget().getOptLevel() == CodeGenOptLevel::None) {}
295
296 // Return true if the current function should be compiled with no
297 // optimization.
298 bool isOptNone() const { return OptNone; }
299
300 // Edits an existing sequence of wait count instructions according
301 // to an incoming Waitcnt value, which is itself updated to reflect
302 // any new wait count instructions which may need to be generated by
303 // WaitcntGenerator::createNewWaitcnt(). It will return true if any edits
304 // were made.
305 //
306 // This editing will usually be merely updated operands, but it may also
307 // delete instructions if the incoming Wait value indicates they are not
308 // needed. It may also remove existing instructions for which a wait
309 // is needed if it can be determined that it is better to generate new
310 // instructions later, as can happen on gfx12.
311 virtual bool
312 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
313 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
315
316 // Transform a soft waitcnt into a normal one.
317 bool promoteSoftWaitCnt(MachineInstr *Waitcnt) const;
318
319 // Generates new wait count instructions according to the value of
320 // Wait, returning true if any new instructions were created.
321 virtual bool createNewWaitcnt(MachineBasicBlock &Block,
323 AMDGPU::Waitcnt Wait) = 0;
324
325 // Returns an array of bit masks which can be used to map values in
326 // WaitEventType to corresponding counter values in InstCounterType.
327 virtual const unsigned *getWaitEventMask() const = 0;
328
329 // Returns a new waitcnt with all counters except VScnt set to 0. If
330 // IncludeVSCnt is true, VScnt is set to 0, otherwise it is set to ~0u.
331 virtual AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const = 0;
332
333 virtual ~WaitcntGenerator() = default;
334
335 // Create a mask value from the initializer list of wait event types.
336 static constexpr unsigned
337 eventMask(std::initializer_list<WaitEventType> Events) {
338 unsigned Mask = 0;
339 for (auto &E : Events)
340 Mask |= 1 << E;
341
342 return Mask;
343 }
344};
345
346class WaitcntGeneratorPreGFX12 : public WaitcntGenerator {
347public:
348 WaitcntGeneratorPreGFX12() = default;
349 WaitcntGeneratorPreGFX12(const MachineFunction &MF)
350 : WaitcntGenerator(MF, NUM_NORMAL_INST_CNTS) {}
351
352 bool
353 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
354 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
355 MachineBasicBlock::instr_iterator It) const override;
356
357 bool createNewWaitcnt(MachineBasicBlock &Block,
359 AMDGPU::Waitcnt Wait) override;
360
361 const unsigned *getWaitEventMask() const override {
362 assert(ST);
363
364 static const unsigned WaitEventMaskForInstPreGFX12[NUM_INST_CNTS] = {
365 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS,
366 VMEM_BVH_READ_ACCESS}),
367 eventMask({SMEM_ACCESS, LDS_ACCESS, GDS_ACCESS, SQ_MESSAGE}),
368 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
369 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
370 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
371 0,
372 0,
373 0,
374 0};
375
376 return WaitEventMaskForInstPreGFX12;
377 }
378
379 AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const override;
380};
381
382class WaitcntGeneratorGFX12Plus : public WaitcntGenerator {
383public:
384 WaitcntGeneratorGFX12Plus() = default;
385 WaitcntGeneratorGFX12Plus(const MachineFunction &MF,
386 InstCounterType MaxCounter)
387 : WaitcntGenerator(MF, MaxCounter) {}
388
389 bool
390 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
391 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
392 MachineBasicBlock::instr_iterator It) const override;
393
394 bool createNewWaitcnt(MachineBasicBlock &Block,
396 AMDGPU::Waitcnt Wait) override;
397
398 const unsigned *getWaitEventMask() const override {
399 assert(ST);
400
401 static const unsigned WaitEventMaskForInstGFX12Plus[NUM_INST_CNTS] = {
402 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS}),
403 eventMask({LDS_ACCESS, GDS_ACCESS}),
404 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
405 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
406 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
407 eventMask({VMEM_SAMPLER_READ_ACCESS}),
408 eventMask({VMEM_BVH_READ_ACCESS}),
409 eventMask({SMEM_ACCESS, SQ_MESSAGE, SCC_WRITE}),
410 eventMask({VMEM_GROUP, SMEM_GROUP})};
411
412 return WaitEventMaskForInstGFX12Plus;
413 }
414
415 AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const override;
416};
417
418class SIInsertWaitcnts {
419public:
420 const GCNSubtarget *ST;
421 const SIInstrInfo *TII = nullptr;
422 const SIRegisterInfo *TRI = nullptr;
423 const MachineRegisterInfo *MRI = nullptr;
424 InstCounterType SmemAccessCounter;
425 InstCounterType MaxCounter;
426 const unsigned *WaitEventMaskForInst;
427
428private:
429 DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
430 DenseMap<MachineBasicBlock *, bool> PreheadersToFlush;
431 MachineLoopInfo *MLI;
432 MachinePostDominatorTree *PDT;
433 AliasAnalysis *AA = nullptr;
434
435 struct BlockInfo {
436 std::unique_ptr<WaitcntBrackets> Incoming;
437 bool Dirty = true;
438 };
439
440 MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
441
442 bool ForceEmitWaitcnt[NUM_INST_CNTS];
443
444 // In any given run of this pass, WCG will point to one of these two
445 // generator objects, which must have been re-initialised before use
446 // from a value made using a subtarget constructor.
447 WaitcntGeneratorPreGFX12 WCGPreGFX12;
448 WaitcntGeneratorGFX12Plus WCGGFX12Plus;
449
450 WaitcntGenerator *WCG = nullptr;
451
452 // S_ENDPGM instructions before which we should insert a DEALLOC_VGPRS
453 // message.
454 DenseSet<MachineInstr *> ReleaseVGPRInsts;
455
456 HardwareLimits Limits;
457
458public:
459 SIInsertWaitcnts(MachineLoopInfo *MLI, MachinePostDominatorTree *PDT,
460 AliasAnalysis *AA)
461 : MLI(MLI), PDT(PDT), AA(AA) {
462 (void)ForceExpCounter;
463 (void)ForceLgkmCounter;
464 (void)ForceVMCounter;
465 }
466
467 unsigned getWaitCountMax(InstCounterType T) const {
468 switch (T) {
469 case LOAD_CNT:
470 return Limits.LoadcntMax;
471 case DS_CNT:
472 return Limits.DscntMax;
473 case EXP_CNT:
474 return Limits.ExpcntMax;
475 case STORE_CNT:
476 return Limits.StorecntMax;
477 case SAMPLE_CNT:
478 return Limits.SamplecntMax;
479 case BVH_CNT:
480 return Limits.BvhcntMax;
481 case KM_CNT:
482 return Limits.KmcntMax;
483 case X_CNT:
484 return Limits.XcntMax;
485 default:
486 break;
487 }
488 return 0;
489 }
490
491 bool shouldFlushVmCnt(MachineLoop *ML, const WaitcntBrackets &Brackets);
492 bool isPreheaderToFlush(MachineBasicBlock &MBB,
493 const WaitcntBrackets &ScoreBrackets);
494 bool isVMEMOrFlatVMEM(const MachineInstr &MI) const;
495 bool run(MachineFunction &MF);
496
497 void setForceEmitWaitcnt() {
498// For non-debug builds, ForceEmitWaitcnt has been initialized to false;
499// For debug builds, get the debug counter info and adjust if need be
500#ifndef NDEBUG
501 if (DebugCounter::isCounterSet(ForceExpCounter) &&
502 DebugCounter::shouldExecute(ForceExpCounter)) {
503 ForceEmitWaitcnt[EXP_CNT] = true;
504 } else {
505 ForceEmitWaitcnt[EXP_CNT] = false;
506 }
507
508 if (DebugCounter::isCounterSet(ForceLgkmCounter) &&
509 DebugCounter::shouldExecute(ForceLgkmCounter)) {
510 ForceEmitWaitcnt[DS_CNT] = true;
511 ForceEmitWaitcnt[KM_CNT] = true;
512 } else {
513 ForceEmitWaitcnt[DS_CNT] = false;
514 ForceEmitWaitcnt[KM_CNT] = false;
515 }
516
517 if (DebugCounter::isCounterSet(ForceVMCounter) &&
518 DebugCounter::shouldExecute(ForceVMCounter)) {
519 ForceEmitWaitcnt[LOAD_CNT] = true;
520 ForceEmitWaitcnt[SAMPLE_CNT] = true;
521 ForceEmitWaitcnt[BVH_CNT] = true;
522 } else {
523 ForceEmitWaitcnt[LOAD_CNT] = false;
524 ForceEmitWaitcnt[SAMPLE_CNT] = false;
525 ForceEmitWaitcnt[BVH_CNT] = false;
526 }
527#endif // NDEBUG
528 }
529
530 // Return the appropriate VMEM_*_ACCESS type for Inst, which must be a VMEM
531 // instruction.
532 WaitEventType getVmemWaitEventType(const MachineInstr &Inst) const {
533 switch (Inst.getOpcode()) {
534 case AMDGPU::GLOBAL_INV:
535 return VMEM_READ_ACCESS; // tracked using loadcnt
536 case AMDGPU::GLOBAL_WB:
537 case AMDGPU::GLOBAL_WBINV:
538 return VMEM_WRITE_ACCESS; // tracked using storecnt
539 default:
540 break;
541 }
542
543 // Maps VMEM access types to their corresponding WaitEventType.
544 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
545 VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
546
548 // LDS DMA loads are also stores, but on the LDS side. On the VMEM side
549 // these should use VM_CNT.
550 if (!ST->hasVscnt() || SIInstrInfo::mayWriteLDSThroughDMA(Inst))
551 return VMEM_ACCESS;
552 if (Inst.mayStore() &&
553 (!Inst.mayLoad() || SIInstrInfo::isAtomicNoRet(Inst))) {
554 // FLAT and SCRATCH instructions may access scratch. Other VMEM
555 // instructions do not.
556 if (TII->mayAccessScratchThroughFlat(Inst))
557 return SCRATCH_WRITE_ACCESS;
558 return VMEM_WRITE_ACCESS;
559 }
560 if (!ST->hasExtendedWaitCounts() || SIInstrInfo::isFLAT(Inst))
561 return VMEM_READ_ACCESS;
562 return VmemReadMapping[getVmemType(Inst)];
563 }
564
565 bool isVmemAccess(const MachineInstr &MI) const;
566 bool generateWaitcntInstBefore(MachineInstr &MI,
567 WaitcntBrackets &ScoreBrackets,
568 MachineInstr *OldWaitcntInstr,
569 bool FlushVmCnt);
570 bool generateWaitcnt(AMDGPU::Waitcnt Wait,
572 MachineBasicBlock &Block, WaitcntBrackets &ScoreBrackets,
573 MachineInstr *OldWaitcntInstr);
574 void updateEventWaitcntAfter(MachineInstr &Inst,
575 WaitcntBrackets *ScoreBrackets);
576 bool isNextENDPGM(MachineBasicBlock::instr_iterator It,
577 MachineBasicBlock *Block) const;
578 bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &Block,
579 WaitcntBrackets &ScoreBrackets);
580 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block,
581 WaitcntBrackets &ScoreBrackets);
582};
583
584// This objects maintains the current score brackets of each wait counter, and
585// a per-register scoreboard for each wait counter.
586//
587// We also maintain the latest score for every event type that can change the
588// waitcnt in order to know if there are multiple types of events within
589// the brackets. When multiple types of event happen in the bracket,
590// wait count may get decreased out of order, therefore we need to put in
591// "s_waitcnt 0" before use.
592class WaitcntBrackets {
593public:
594 WaitcntBrackets(const SIInsertWaitcnts *Context) : Context(Context) {}
595
596 bool isSmemCounter(InstCounterType T) const {
597 return T == Context->SmemAccessCounter || T == X_CNT;
598 }
599
600 unsigned getSgprScoresIdx(InstCounterType T) const {
601 assert(isSmemCounter(T) && "Invalid SMEM counter");
602 return T == X_CNT ? 1 : 0;
603 }
604
605 unsigned getScoreLB(InstCounterType T) const {
606 assert(T < NUM_INST_CNTS);
607 return ScoreLBs[T];
608 }
609
610 unsigned getScoreUB(InstCounterType T) const {
611 assert(T < NUM_INST_CNTS);
612 return ScoreUBs[T];
613 }
614
615 unsigned getScoreRange(InstCounterType T) const {
616 return getScoreUB(T) - getScoreLB(T);
617 }
618
619 unsigned getRegScore(int GprNo, InstCounterType T) const {
620 if (GprNo < NUM_ALL_VGPRS)
621 return VgprScores[T][GprNo];
622
623 if (GprNo < NUM_ALL_ALLOCATABLE)
624 return SgprScores[getSgprScoresIdx(T)][GprNo - NUM_ALL_VGPRS];
625
626 assert(GprNo == SCC);
627 return SCCScore;
628 }
629
630 bool merge(const WaitcntBrackets &Other);
631
632 RegInterval getRegInterval(const MachineInstr *MI,
633 const MachineOperand &Op) const;
634
635 bool counterOutOfOrder(InstCounterType T) const;
636 void simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const;
637 void simplifyWaitcnt(InstCounterType T, unsigned &Count) const;
638
639 void determineWait(InstCounterType T, RegInterval Interval,
640 AMDGPU::Waitcnt &Wait) const;
641 void determineWait(InstCounterType T, int RegNo,
642 AMDGPU::Waitcnt &Wait) const {
643 determineWait(T, {RegNo, RegNo + 1}, Wait);
644 }
645 void tryClearSCCWriteEvent(MachineInstr *Inst);
646
647 void applyWaitcnt(const AMDGPU::Waitcnt &Wait);
648 void applyWaitcnt(InstCounterType T, unsigned Count);
649 void applyXcnt(const AMDGPU::Waitcnt &Wait);
650 void updateByEvent(WaitEventType E, MachineInstr &MI);
651
652 unsigned hasPendingEvent() const { return PendingEvents; }
653 unsigned hasPendingEvent(WaitEventType E) const {
654 return PendingEvents & (1 << E);
655 }
656 unsigned hasPendingEvent(InstCounterType T) const {
657 unsigned HasPending = PendingEvents & Context->WaitEventMaskForInst[T];
658 assert((HasPending != 0) == (getScoreRange(T) != 0));
659 return HasPending;
660 }
661
662 bool hasMixedPendingEvents(InstCounterType T) const {
663 unsigned Events = hasPendingEvent(T);
664 // Return true if more than one bit is set in Events.
665 return Events & (Events - 1);
666 }
667
668 bool hasPendingFlat() const {
669 return ((LastFlat[DS_CNT] > ScoreLBs[DS_CNT] &&
670 LastFlat[DS_CNT] <= ScoreUBs[DS_CNT]) ||
671 (LastFlat[LOAD_CNT] > ScoreLBs[LOAD_CNT] &&
672 LastFlat[LOAD_CNT] <= ScoreUBs[LOAD_CNT]));
673 }
674
675 void setPendingFlat() {
676 LastFlat[LOAD_CNT] = ScoreUBs[LOAD_CNT];
677 LastFlat[DS_CNT] = ScoreUBs[DS_CNT];
678 }
679
680 bool hasPendingGDS() const {
681 return LastGDS > ScoreLBs[DS_CNT] && LastGDS <= ScoreUBs[DS_CNT];
682 }
683
684 unsigned getPendingGDSWait() const {
685 return std::min(getScoreUB(DS_CNT) - LastGDS,
686 Context->getWaitCountMax(DS_CNT) - 1);
687 }
688
689 void setPendingGDS() { LastGDS = ScoreUBs[DS_CNT]; }
690
691 // Return true if there might be pending writes to the vgpr-interval by VMEM
692 // instructions with types different from V.
693 bool hasOtherPendingVmemTypes(RegInterval Interval, VmemType V) const {
694 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
695 assert(RegNo < NUM_ALL_VGPRS);
696 if (VgprVmemTypes[RegNo] & ~(1 << V))
697 return true;
698 }
699 return false;
700 }
701
702 void clearVgprVmemTypes(RegInterval Interval) {
703 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
704 assert(RegNo < NUM_ALL_VGPRS);
705 VgprVmemTypes[RegNo] = 0;
706 }
707 }
708
709 void setStateOnFunctionEntryOrReturn() {
710 setScoreUB(STORE_CNT,
711 getScoreUB(STORE_CNT) + Context->getWaitCountMax(STORE_CNT));
712 PendingEvents |= Context->WaitEventMaskForInst[STORE_CNT];
713 }
714
715 ArrayRef<const MachineInstr *> getLDSDMAStores() const {
716 return LDSDMAStores;
717 }
718
719 bool hasPointSampleAccel(const MachineInstr &MI) const;
720 bool hasPointSamplePendingVmemTypes(const MachineInstr &MI,
721 RegInterval Interval) const;
722
723 void print(raw_ostream &) const;
724 void dump() const { print(dbgs()); }
725
726private:
727 struct MergeInfo {
728 unsigned OldLB;
729 unsigned OtherLB;
730 unsigned MyShift;
731 unsigned OtherShift;
732 };
733 static bool mergeScore(const MergeInfo &M, unsigned &Score,
734 unsigned OtherScore);
735
736 void setScoreLB(InstCounterType T, unsigned Val) {
737 assert(T < NUM_INST_CNTS);
738 ScoreLBs[T] = Val;
739 }
740
741 void setScoreUB(InstCounterType T, unsigned Val) {
742 assert(T < NUM_INST_CNTS);
743 ScoreUBs[T] = Val;
744
745 if (T != EXP_CNT)
746 return;
747
748 if (getScoreRange(EXP_CNT) > Context->getWaitCountMax(EXP_CNT))
749 ScoreLBs[EXP_CNT] = ScoreUBs[EXP_CNT] - Context->getWaitCountMax(EXP_CNT);
750 }
751
752 void setRegScore(int GprNo, InstCounterType T, unsigned Val) {
753 setScoreByInterval({GprNo, GprNo + 1}, T, Val);
754 }
755
756 void setScoreByInterval(RegInterval Interval, InstCounterType CntTy,
757 unsigned Score);
758
759 void setScoreByOperand(const MachineInstr *MI, const MachineOperand &Op,
760 InstCounterType CntTy, unsigned Val);
761
762 const SIInsertWaitcnts *Context;
763
764 unsigned ScoreLBs[NUM_INST_CNTS] = {0};
765 unsigned ScoreUBs[NUM_INST_CNTS] = {0};
766 unsigned PendingEvents = 0;
767 // Remember the last flat memory operation.
768 unsigned LastFlat[NUM_INST_CNTS] = {0};
769 // Remember the last GDS operation.
770 unsigned LastGDS = 0;
771 // wait_cnt scores for every vgpr.
772 // Keep track of the VgprUB and SgprUB to make merge at join efficient.
773 int VgprUB = -1;
774 int SgprUB = -1;
775 unsigned VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS] = {{0}};
776 // Wait cnt scores for every sgpr, the DS_CNT (corresponding to LGKMcnt
777 // pre-gfx12) or KM_CNT (gfx12+ only), and X_CNT (gfx1250) are relevant.
778 // Row 0 represents the score for either DS_CNT or KM_CNT and row 1 keeps the
779 // X_CNT score.
780 unsigned SgprScores[2][SQ_MAX_PGM_SGPRS] = {{0}};
781 // Reg score for SCC.
782 unsigned SCCScore = 0;
783 // The unique instruction that has an SCC write pending, if there is one.
784 const MachineInstr *PendingSCCWrite = nullptr;
785 // Bitmask of the VmemTypes of VMEM instructions that might have a pending
786 // write to each vgpr.
787 unsigned char VgprVmemTypes[NUM_ALL_VGPRS] = {0};
788 // Store representative LDS DMA operations. The only useful info here is
789 // alias info. One store is kept per unique AAInfo.
790 SmallVector<const MachineInstr *, NUM_LDS_VGPRS - 1> LDSDMAStores;
791};
792
793class SIInsertWaitcntsLegacy : public MachineFunctionPass {
794public:
795 static char ID;
796 SIInsertWaitcntsLegacy() : MachineFunctionPass(ID) {}
797
798 bool runOnMachineFunction(MachineFunction &MF) override;
799
800 StringRef getPassName() const override {
801 return "SI insert wait instructions";
802 }
803
804 void getAnalysisUsage(AnalysisUsage &AU) const override {
805 AU.setPreservesCFG();
806 AU.addRequired<MachineLoopInfoWrapperPass>();
807 AU.addRequired<MachinePostDominatorTreeWrapperPass>();
808 AU.addUsedIfAvailable<AAResultsWrapperPass>();
809 AU.addPreserved<AAResultsWrapperPass>();
811 }
812};
813
814} // end anonymous namespace
815
816RegInterval WaitcntBrackets::getRegInterval(const MachineInstr *MI,
817 const MachineOperand &Op) const {
818 if (Op.getReg() == AMDGPU::SCC)
819 return {SCC, SCC + 1};
820
821 const SIRegisterInfo *TRI = Context->TRI;
822 const MachineRegisterInfo *MRI = Context->MRI;
823
824 if (!TRI->isInAllocatableClass(Op.getReg()))
825 return {-1, -1};
826
827 // A use via a PW operand does not need a waitcnt.
828 // A partial write is not a WAW.
829 assert(!Op.getSubReg() || !Op.isUndef());
830
831 RegInterval Result;
832
833 MCRegister MCReg = AMDGPU::getMCReg(Op.getReg(), *Context->ST);
834 unsigned RegIdx = TRI->getHWRegIndex(MCReg);
835
836 const TargetRegisterClass *RC = TRI->getPhysRegBaseClass(Op.getReg());
837 unsigned Size = TRI->getRegSizeInBits(*RC);
838
839 // AGPRs/VGPRs are tracked every 16 bits, SGPRs by 32 bits
840 if (TRI->isVectorRegister(*MRI, Op.getReg())) {
841 unsigned Reg = RegIdx << 1 | (AMDGPU::isHi16Reg(MCReg, *TRI) ? 1 : 0);
842 assert(!Context->ST->hasMAIInsts() || Reg < AGPR_OFFSET);
843 Result.first = Reg;
844 if (TRI->isAGPR(*MRI, Op.getReg()))
845 Result.first += AGPR_OFFSET;
846 assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS);
847 assert(Size % 16 == 0);
848 Result.second = Result.first + (Size / 16);
849
850 if (Size == 16 && Context->ST->hasD16Writes32BitVgpr()) {
851 // Regardless of which lo16/hi16 is used, consider the full 32-bit
852 // register used.
853 if (AMDGPU::isHi16Reg(MCReg, *TRI))
854 Result.first -= 1;
855 else
856 Result.second += 1;
857 }
858 } else if (TRI->isSGPRReg(*MRI, Op.getReg()) && RegIdx < SQ_MAX_PGM_SGPRS) {
859 // SGPRs including VCC, TTMPs and EXEC but excluding read-only scalar
860 // sources like SRC_PRIVATE_BASE.
861 Result.first = RegIdx + NUM_ALL_VGPRS;
862 Result.second = Result.first + divideCeil(Size, 32);
863 } else {
864 return {-1, -1};
865 }
866
867 return Result;
868}
869
870void WaitcntBrackets::setScoreByInterval(RegInterval Interval,
871 InstCounterType CntTy,
872 unsigned Score) {
873 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
874 if (RegNo < NUM_ALL_VGPRS) {
875 VgprUB = std::max(VgprUB, RegNo);
876 VgprScores[CntTy][RegNo] = Score;
877 } else if (RegNo < NUM_ALL_ALLOCATABLE) {
878 SgprUB = std::max(SgprUB, RegNo - NUM_ALL_VGPRS);
879 SgprScores[getSgprScoresIdx(CntTy)][RegNo - NUM_ALL_VGPRS] = Score;
880 } else {
881 assert(RegNo == SCC);
882 SCCScore = Score;
883 }
884 }
885}
886
887void WaitcntBrackets::setScoreByOperand(const MachineInstr *MI,
888 const MachineOperand &Op,
889 InstCounterType CntTy, unsigned Score) {
890 RegInterval Interval = getRegInterval(MI, Op);
891 setScoreByInterval(Interval, CntTy, Score);
892}
893
894// Return true if the subtarget is one that enables Point Sample Acceleration
895// and the MachineInstr passed in is one to which it might be applied (the
896// hardware makes this decision based on several factors, but we can't determine
897// this at compile time, so we have to assume it might be applied if the
898// instruction supports it).
899bool WaitcntBrackets::hasPointSampleAccel(const MachineInstr &MI) const {
900 if (!Context->ST->hasPointSampleAccel() || !SIInstrInfo::isMIMG(MI))
901 return false;
902
903 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(MI.getOpcode());
904 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
906 return BaseInfo->PointSampleAccel;
907}
908
909// Return true if the subtarget enables Point Sample Acceleration, the supplied
910// MachineInstr is one to which it might be applied and the supplied interval is
911// one that has outstanding writes to vmem-types different than VMEM_NOSAMPLER
912// (this is the type that a point sample accelerated instruction effectively
913// becomes)
914bool WaitcntBrackets::hasPointSamplePendingVmemTypes(
915 const MachineInstr &MI, RegInterval Interval) const {
916 if (!hasPointSampleAccel(MI))
917 return false;
918
919 return hasOtherPendingVmemTypes(Interval, VMEM_NOSAMPLER);
920}
921
922void WaitcntBrackets::updateByEvent(WaitEventType E, MachineInstr &Inst) {
923 InstCounterType T = eventCounter(Context->WaitEventMaskForInst, E);
924
925 unsigned UB = getScoreUB(T);
926 unsigned CurrScore = UB + 1;
927 if (CurrScore == 0)
928 report_fatal_error("InsertWaitcnt score wraparound");
929 // PendingEvents and ScoreUB need to be update regardless if this event
930 // changes the score of a register or not.
931 // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
932 PendingEvents |= 1 << E;
933 setScoreUB(T, CurrScore);
934
935 const SIRegisterInfo *TRI = Context->TRI;
936 const MachineRegisterInfo *MRI = Context->MRI;
937 const SIInstrInfo *TII = Context->TII;
938
939 if (T == EXP_CNT) {
940 // Put score on the source vgprs. If this is a store, just use those
941 // specific register(s).
942 if (TII->isDS(Inst) && Inst.mayLoadOrStore()) {
943 // All GDS operations must protect their address register (same as
944 // export.)
945 if (const auto *AddrOp = TII->getNamedOperand(Inst, AMDGPU::OpName::addr))
946 setScoreByOperand(&Inst, *AddrOp, EXP_CNT, CurrScore);
947
948 if (Inst.mayStore()) {
949 if (const auto *Data0 =
950 TII->getNamedOperand(Inst, AMDGPU::OpName::data0))
951 setScoreByOperand(&Inst, *Data0, EXP_CNT, CurrScore);
952 if (const auto *Data1 =
953 TII->getNamedOperand(Inst, AMDGPU::OpName::data1))
954 setScoreByOperand(&Inst, *Data1, EXP_CNT, CurrScore);
955 } else if (SIInstrInfo::isAtomicRet(Inst) && !SIInstrInfo::isGWS(Inst) &&
956 Inst.getOpcode() != AMDGPU::DS_APPEND &&
957 Inst.getOpcode() != AMDGPU::DS_CONSUME &&
958 Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
959 for (const MachineOperand &Op : Inst.all_uses()) {
960 if (TRI->isVectorRegister(*MRI, Op.getReg()))
961 setScoreByOperand(&Inst, Op, EXP_CNT, CurrScore);
962 }
963 }
964 } else if (TII->isFLAT(Inst)) {
965 if (Inst.mayStore()) {
966 setScoreByOperand(&Inst,
967 *TII->getNamedOperand(Inst, AMDGPU::OpName::data),
968 EXP_CNT, CurrScore);
969 } else if (SIInstrInfo::isAtomicRet(Inst)) {
970 setScoreByOperand(&Inst,
971 *TII->getNamedOperand(Inst, AMDGPU::OpName::data),
972 EXP_CNT, CurrScore);
973 }
974 } else if (TII->isMIMG(Inst)) {
975 if (Inst.mayStore()) {
976 setScoreByOperand(&Inst, Inst.getOperand(0), EXP_CNT, CurrScore);
977 } else if (SIInstrInfo::isAtomicRet(Inst)) {
978 setScoreByOperand(&Inst,
979 *TII->getNamedOperand(Inst, AMDGPU::OpName::data),
980 EXP_CNT, CurrScore);
981 }
982 } else if (TII->isMTBUF(Inst)) {
983 if (Inst.mayStore())
984 setScoreByOperand(&Inst, Inst.getOperand(0), EXP_CNT, CurrScore);
985 } else if (TII->isMUBUF(Inst)) {
986 if (Inst.mayStore()) {
987 setScoreByOperand(&Inst, Inst.getOperand(0), EXP_CNT, CurrScore);
988 } else if (SIInstrInfo::isAtomicRet(Inst)) {
989 setScoreByOperand(&Inst,
990 *TII->getNamedOperand(Inst, AMDGPU::OpName::data),
991 EXP_CNT, CurrScore);
992 }
993 } else if (TII->isLDSDIR(Inst)) {
994 // LDSDIR instructions attach the score to the destination.
995 setScoreByOperand(&Inst,
996 *TII->getNamedOperand(Inst, AMDGPU::OpName::vdst),
997 EXP_CNT, CurrScore);
998 } else {
999 if (TII->isEXP(Inst)) {
1000 // For export the destination registers are really temps that
1001 // can be used as the actual source after export patching, so
1002 // we need to treat them like sources and set the EXP_CNT
1003 // score.
1004 for (MachineOperand &DefMO : Inst.all_defs()) {
1005 if (TRI->isVGPR(*MRI, DefMO.getReg())) {
1006 setScoreByOperand(&Inst, DefMO, EXP_CNT, CurrScore);
1007 }
1008 }
1009 }
1010 for (const MachineOperand &Op : Inst.all_uses()) {
1011 if (TRI->isVectorRegister(*MRI, Op.getReg()))
1012 setScoreByOperand(&Inst, Op, EXP_CNT, CurrScore);
1013 }
1014 }
1015 } else if (T == X_CNT) {
1016 WaitEventType OtherEvent = E == SMEM_GROUP ? VMEM_GROUP : SMEM_GROUP;
1017 if (PendingEvents & (1 << OtherEvent)) {
1018 // Hardware inserts an implicit xcnt between interleaved
1019 // SMEM and VMEM operations. So there will never be
1020 // outstanding address translations for both SMEM and
1021 // VMEM at the same time.
1022 setScoreLB(T, CurrScore - 1);
1023 PendingEvents &= ~(1 << OtherEvent);
1024 }
1025 for (const MachineOperand &Op : Inst.all_uses())
1026 setScoreByOperand(&Inst, Op, T, CurrScore);
1027 } else /* LGKM_CNT || EXP_CNT || VS_CNT || NUM_INST_CNTS */ {
1028 // Match the score to the destination registers.
1029 //
1030 // Check only explicit operands. Stores, especially spill stores, include
1031 // implicit uses and defs of their super registers which would create an
1032 // artificial dependency, while these are there only for register liveness
1033 // accounting purposes.
1034 //
1035 // Special cases where implicit register defs exists, such as M0 or VCC,
1036 // but none with memory instructions.
1037 for (const MachineOperand &Op : Inst.defs()) {
1038 RegInterval Interval = getRegInterval(&Inst, Op);
1039 if (T == LOAD_CNT || T == SAMPLE_CNT || T == BVH_CNT) {
1040 if (Interval.first >= NUM_ALL_VGPRS)
1041 continue;
1042 if (updateVMCntOnly(Inst)) {
1043 // updateVMCntOnly should only leave us with VGPRs
1044 // MUBUF, MTBUF, MIMG, FlatGlobal, and FlatScratch only have VGPR/AGPR
1045 // defs. That's required for a sane index into `VgprMemTypes` below
1046 assert(TRI->isVectorRegister(*MRI, Op.getReg()));
1047 VmemType V = getVmemType(Inst);
1048 unsigned char TypesMask = 1 << V;
1049 // If instruction can have Point Sample Accel applied, we have to flag
1050 // this with another potential dependency
1051 if (hasPointSampleAccel(Inst))
1052 TypesMask |= 1 << VMEM_NOSAMPLER;
1053 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo)
1054 VgprVmemTypes[RegNo] |= TypesMask;
1055 }
1056 }
1057 setScoreByInterval(Interval, T, CurrScore);
1058 }
1059 if (Inst.mayStore() &&
1060 (TII->isDS(Inst) || TII->mayWriteLDSThroughDMA(Inst))) {
1061 // MUBUF and FLAT LDS DMA operations need a wait on vmcnt before LDS
1062 // written can be accessed. A load from LDS to VMEM does not need a wait.
1063 unsigned Slot = 0;
1064 for (const auto *MemOp : Inst.memoperands()) {
1065 if (!MemOp->isStore() ||
1066 MemOp->getAddrSpace() != AMDGPUAS::LOCAL_ADDRESS)
1067 continue;
1068 // Comparing just AA info does not guarantee memoperands are equal
1069 // in general, but this is so for LDS DMA in practice.
1070 auto AAI = MemOp->getAAInfo();
1071 // Alias scope information gives a way to definitely identify an
1072 // original memory object and practically produced in the module LDS
1073 // lowering pass. If there is no scope available we will not be able
1074 // to disambiguate LDS aliasing as after the module lowering all LDS
1075 // is squashed into a single big object. Do not attempt to use one of
1076 // the limited LDSDMAStores for something we will not be able to use
1077 // anyway.
1078 if (!AAI || !AAI.Scope)
1079 break;
1080 for (unsigned I = 0, E = LDSDMAStores.size(); I != E && !Slot; ++I) {
1081 for (const auto *MemOp : LDSDMAStores[I]->memoperands()) {
1082 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1083 Slot = I + 1;
1084 break;
1085 }
1086 }
1087 }
1088 if (Slot || LDSDMAStores.size() == NUM_LDS_VGPRS - 1)
1089 break;
1090 LDSDMAStores.push_back(&Inst);
1091 Slot = LDSDMAStores.size();
1092 break;
1093 }
1094 setRegScore(FIRST_LDS_VGPR + Slot, T, CurrScore);
1095 if (Slot)
1096 setRegScore(FIRST_LDS_VGPR, T, CurrScore);
1097 }
1098
1100 setRegScore(SCC, T, CurrScore);
1101 PendingSCCWrite = &Inst;
1102 }
1103 }
1104}
1105
1106void WaitcntBrackets::print(raw_ostream &OS) const {
1107 const GCNSubtarget *ST = Context->ST;
1108
1109 OS << '\n';
1110 for (auto T : inst_counter_types(Context->MaxCounter)) {
1111 unsigned SR = getScoreRange(T);
1112
1113 switch (T) {
1114 case LOAD_CNT:
1115 OS << " " << (ST->hasExtendedWaitCounts() ? "LOAD" : "VM") << "_CNT("
1116 << SR << "): ";
1117 break;
1118 case DS_CNT:
1119 OS << " " << (ST->hasExtendedWaitCounts() ? "DS" : "LGKM") << "_CNT("
1120 << SR << "): ";
1121 break;
1122 case EXP_CNT:
1123 OS << " EXP_CNT(" << SR << "): ";
1124 break;
1125 case STORE_CNT:
1126 OS << " " << (ST->hasExtendedWaitCounts() ? "STORE" : "VS") << "_CNT("
1127 << SR << "): ";
1128 break;
1129 case SAMPLE_CNT:
1130 OS << " SAMPLE_CNT(" << SR << "): ";
1131 break;
1132 case BVH_CNT:
1133 OS << " BVH_CNT(" << SR << "): ";
1134 break;
1135 case KM_CNT:
1136 OS << " KM_CNT(" << SR << "): ";
1137 break;
1138 case X_CNT:
1139 OS << " X_CNT(" << SR << "): ";
1140 break;
1141 default:
1142 OS << " UNKNOWN(" << SR << "): ";
1143 break;
1144 }
1145
1146 if (SR != 0) {
1147 // Print vgpr scores.
1148 unsigned LB = getScoreLB(T);
1149
1150 for (int J = 0; J <= VgprUB; J++) {
1151 unsigned RegScore = getRegScore(J, T);
1152 if (RegScore <= LB)
1153 continue;
1154 unsigned RelScore = RegScore - LB - 1;
1155 if (J < FIRST_LDS_VGPR) {
1156 OS << RelScore << ":v" << J << " ";
1157 } else {
1158 OS << RelScore << ":ds ";
1159 }
1160 }
1161 // Also need to print sgpr scores for lgkm_cnt or xcnt.
1162 if (isSmemCounter(T)) {
1163 for (int J = 0; J <= SgprUB; J++) {
1164 unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS, T);
1165 if (RegScore <= LB)
1166 continue;
1167 unsigned RelScore = RegScore - LB - 1;
1168 OS << RelScore << ":s" << J << " ";
1169 }
1170 }
1171 if (T == KM_CNT && SCCScore > 0)
1172 OS << SCCScore << ":scc ";
1173 }
1174 OS << '\n';
1175 }
1176
1177 OS << "Pending Events: ";
1178 if (hasPendingEvent()) {
1179 ListSeparator LS;
1180 for (unsigned I = 0; I != NUM_WAIT_EVENTS; ++I) {
1181 if (hasPendingEvent((WaitEventType)I)) {
1182 OS << LS << WaitEventTypeName[I];
1183 }
1184 }
1185 } else {
1186 OS << "none";
1187 }
1188 OS << '\n';
1189
1190 OS << '\n';
1191}
1192
1193/// Simplify the waitcnt, in the sense of removing redundant counts, and return
1194/// whether a waitcnt instruction is needed at all.
1195void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const {
1196 simplifyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1197 simplifyWaitcnt(EXP_CNT, Wait.ExpCnt);
1198 simplifyWaitcnt(DS_CNT, Wait.DsCnt);
1199 simplifyWaitcnt(STORE_CNT, Wait.StoreCnt);
1200 simplifyWaitcnt(SAMPLE_CNT, Wait.SampleCnt);
1201 simplifyWaitcnt(BVH_CNT, Wait.BvhCnt);
1202 simplifyWaitcnt(KM_CNT, Wait.KmCnt);
1203 simplifyWaitcnt(X_CNT, Wait.XCnt);
1204}
1205
1206void WaitcntBrackets::simplifyWaitcnt(InstCounterType T,
1207 unsigned &Count) const {
1208 // The number of outstanding events for this type, T, can be calculated
1209 // as (UB - LB). If the current Count is greater than or equal to the number
1210 // of outstanding events, then the wait for this counter is redundant.
1211 if (Count >= getScoreRange(T))
1212 Count = ~0u;
1213}
1214
1215void WaitcntBrackets::determineWait(InstCounterType T, RegInterval Interval,
1216 AMDGPU::Waitcnt &Wait) const {
1217 const unsigned LB = getScoreLB(T);
1218 const unsigned UB = getScoreUB(T);
1219 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1220 unsigned ScoreToWait = getRegScore(RegNo, T);
1221
1222 // If the score of src_operand falls within the bracket, we need an
1223 // s_waitcnt instruction.
1224 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1225 if ((T == LOAD_CNT || T == DS_CNT) && hasPendingFlat() &&
1226 !Context->ST->hasFlatLgkmVMemCountInOrder()) {
1227 // If there is a pending FLAT operation, and this is a VMem or LGKM
1228 // waitcnt and the target can report early completion, then we need
1229 // to force a waitcnt 0.
1230 addWait(Wait, T, 0);
1231 } else if (counterOutOfOrder(T)) {
1232 // Counter can get decremented out-of-order when there
1233 // are multiple types event in the bracket. Also emit an s_wait counter
1234 // with a conservative value of 0 for the counter.
1235 addWait(Wait, T, 0);
1236 } else {
1237 // If a counter has been maxed out avoid overflow by waiting for
1238 // MAX(CounterType) - 1 instead.
1239 unsigned NeededWait =
1240 std::min(UB - ScoreToWait, Context->getWaitCountMax(T) - 1);
1241 addWait(Wait, T, NeededWait);
1242 }
1243 }
1244 }
1245}
1246
1247void WaitcntBrackets::tryClearSCCWriteEvent(MachineInstr *Inst) {
1248 // S_BARRIER_WAIT on the same barrier guarantees that the pending write to
1249 // SCC has landed
1250 if (PendingSCCWrite &&
1251 PendingSCCWrite->getOpcode() == AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM &&
1252 PendingSCCWrite->getOperand(0).getImm() == Inst->getOperand(0).getImm()) {
1253 unsigned SCC_WRITE_PendingEvent = 1 << SCC_WRITE;
1254 // If this SCC_WRITE is the only pending KM_CNT event, clear counter.
1255 if ((PendingEvents & Context->WaitEventMaskForInst[KM_CNT]) ==
1256 SCC_WRITE_PendingEvent) {
1257 setScoreLB(KM_CNT, getScoreUB(KM_CNT));
1258 }
1259
1260 PendingEvents &= ~SCC_WRITE_PendingEvent;
1261 PendingSCCWrite = nullptr;
1262 }
1263}
1264
1265void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait) {
1266 applyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1267 applyWaitcnt(EXP_CNT, Wait.ExpCnt);
1268 applyWaitcnt(DS_CNT, Wait.DsCnt);
1269 applyWaitcnt(STORE_CNT, Wait.StoreCnt);
1270 applyWaitcnt(SAMPLE_CNT, Wait.SampleCnt);
1271 applyWaitcnt(BVH_CNT, Wait.BvhCnt);
1272 applyWaitcnt(KM_CNT, Wait.KmCnt);
1273 applyXcnt(Wait);
1274}
1275
1276void WaitcntBrackets::applyWaitcnt(InstCounterType T, unsigned Count) {
1277 const unsigned UB = getScoreUB(T);
1278 if (Count >= UB)
1279 return;
1280 if (Count != 0) {
1281 if (counterOutOfOrder(T))
1282 return;
1283 setScoreLB(T, std::max(getScoreLB(T), UB - Count));
1284 } else {
1285 setScoreLB(T, UB);
1286 PendingEvents &= ~Context->WaitEventMaskForInst[T];
1287 }
1288}
1289
1290void WaitcntBrackets::applyXcnt(const AMDGPU::Waitcnt &Wait) {
1291 // Wait on XCNT is redundant if we are already waiting for a load to complete.
1292 // SMEM can return out of order, so only omit XCNT wait if we are waiting till
1293 // zero.
1294 if (Wait.KmCnt == 0 && hasPendingEvent(SMEM_GROUP))
1295 return applyWaitcnt(X_CNT, 0);
1296
1297 // If we have pending store we cannot optimize XCnt because we do not wait for
1298 // stores. VMEM loads retun in order, so if we only have loads XCnt is
1299 // decremented to the same number as LOADCnt.
1300 if (Wait.LoadCnt != ~0u && hasPendingEvent(VMEM_GROUP) &&
1301 !hasPendingEvent(STORE_CNT))
1302 return applyWaitcnt(X_CNT, std::min(Wait.XCnt, Wait.LoadCnt));
1303
1304 applyWaitcnt(X_CNT, Wait.XCnt);
1305}
1306
1307// Where there are multiple types of event in the bracket of a counter,
1308// the decrement may go out of order.
1309bool WaitcntBrackets::counterOutOfOrder(InstCounterType T) const {
1310 // Scalar memory read always can go out of order.
1311 if ((T == Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1312 (T == X_CNT && hasPendingEvent(SMEM_GROUP)))
1313 return true;
1314 return hasMixedPendingEvents(T);
1315}
1316
1317INITIALIZE_PASS_BEGIN(SIInsertWaitcntsLegacy, DEBUG_TYPE, "SI Insert Waitcnts",
1318 false, false)
1321INITIALIZE_PASS_END(SIInsertWaitcntsLegacy, DEBUG_TYPE, "SI Insert Waitcnts",
1323
1324char SIInsertWaitcntsLegacy::ID = 0;
1325
1326char &llvm::SIInsertWaitcntsID = SIInsertWaitcntsLegacy::ID;
1327
1329 return new SIInsertWaitcntsLegacy();
1330}
1331
1332static bool updateOperandIfDifferent(MachineInstr &MI, AMDGPU::OpName OpName,
1333 unsigned NewEnc) {
1334 int OpIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpName);
1335 assert(OpIdx >= 0);
1336
1337 MachineOperand &MO = MI.getOperand(OpIdx);
1338
1339 if (NewEnc == MO.getImm())
1340 return false;
1341
1342 MO.setImm(NewEnc);
1343 return true;
1344}
1345
1346/// Determine if \p MI is a gfx12+ single-counter S_WAIT_*CNT instruction,
1347/// and if so, which counter it is waiting on.
1348static std::optional<InstCounterType> counterTypeForInstr(unsigned Opcode) {
1349 switch (Opcode) {
1350 case AMDGPU::S_WAIT_LOADCNT:
1351 return LOAD_CNT;
1352 case AMDGPU::S_WAIT_EXPCNT:
1353 return EXP_CNT;
1354 case AMDGPU::S_WAIT_STORECNT:
1355 return STORE_CNT;
1356 case AMDGPU::S_WAIT_SAMPLECNT:
1357 return SAMPLE_CNT;
1358 case AMDGPU::S_WAIT_BVHCNT:
1359 return BVH_CNT;
1360 case AMDGPU::S_WAIT_DSCNT:
1361 return DS_CNT;
1362 case AMDGPU::S_WAIT_KMCNT:
1363 return KM_CNT;
1364 case AMDGPU::S_WAIT_XCNT:
1365 return X_CNT;
1366 default:
1367 return {};
1368 }
1369}
1370
1371bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt) const {
1372 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(Waitcnt->getOpcode());
1373 if (Opcode == Waitcnt->getOpcode())
1374 return false;
1375
1376 Waitcnt->setDesc(TII->get(Opcode));
1377 return true;
1378}
1379
1380/// Combine consecutive S_WAITCNT and S_WAITCNT_VSCNT instructions that
1381/// precede \p It and follow \p OldWaitcntInstr and apply any extra waits
1382/// from \p Wait that were added by previous passes. Currently this pass
1383/// conservatively assumes that these preexisting waits are required for
1384/// correctness.
1385bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1386 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1387 AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
1388 assert(ST);
1389 assert(isNormalMode(MaxCounter));
1390
1391 bool Modified = false;
1392 MachineInstr *WaitcntInstr = nullptr;
1393 MachineInstr *WaitcntVsCntInstr = nullptr;
1394
1395 LLVM_DEBUG({
1396 dbgs() << "PreGFX12::applyPreexistingWaitcnt at: ";
1397 if (It == OldWaitcntInstr.getParent()->instr_end())
1398 dbgs() << "end of block\n";
1399 else
1400 dbgs() << *It;
1401 });
1402
1403 for (auto &II :
1404 make_early_inc_range(make_range(OldWaitcntInstr.getIterator(), It))) {
1405 LLVM_DEBUG(dbgs() << "pre-existing iter: " << II);
1406 if (II.isMetaInstruction()) {
1407 LLVM_DEBUG(dbgs() << "skipped meta instruction\n");
1408 continue;
1409 }
1410
1411 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
1412 bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
1413
1414 // Update required wait count. If this is a soft waitcnt (= it was added
1415 // by an earlier pass), it may be entirely removed.
1416 if (Opcode == AMDGPU::S_WAITCNT) {
1417 unsigned IEnc = II.getOperand(0).getImm();
1418 AMDGPU::Waitcnt OldWait = AMDGPU::decodeWaitcnt(IV, IEnc);
1419 if (TrySimplify)
1420 ScoreBrackets.simplifyWaitcnt(OldWait);
1421 Wait = Wait.combined(OldWait);
1422
1423 // Merge consecutive waitcnt of the same type by erasing multiples.
1424 if (WaitcntInstr || (!Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1425 II.eraseFromParent();
1426 Modified = true;
1427 } else
1428 WaitcntInstr = &II;
1429 } else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1430 assert(ST->hasVMemToLDSLoad());
1431 LLVM_DEBUG(dbgs() << "Processing S_WAITCNT_lds_direct: " << II
1432 << "Before: " << Wait.LoadCnt << '\n';);
1433 ScoreBrackets.determineWait(LOAD_CNT, FIRST_LDS_VGPR, Wait);
1434 LLVM_DEBUG(dbgs() << "After: " << Wait.LoadCnt << '\n';);
1435
1436 // It is possible (but unlikely) that this is the only wait instruction,
1437 // in which case, we exit this loop without a WaitcntInstr to consume
1438 // `Wait`. But that works because `Wait` was passed in by reference, and
1439 // the callee eventually calls createNewWaitcnt on it. We test this
1440 // possibility in an articial MIR test since such a situation cannot be
1441 // recreated by running the memory legalizer.
1442 II.eraseFromParent();
1443 } else {
1444 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1445 assert(II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1446
1447 unsigned OldVSCnt =
1448 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1449 if (TrySimplify)
1450 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1451 Wait.StoreCnt = std::min(Wait.StoreCnt, OldVSCnt);
1452
1453 if (WaitcntVsCntInstr || (!Wait.hasWaitStoreCnt() && TrySimplify)) {
1454 II.eraseFromParent();
1455 Modified = true;
1456 } else
1457 WaitcntVsCntInstr = &II;
1458 }
1459 }
1460
1461 if (WaitcntInstr) {
1462 Modified |= updateOperandIfDifferent(*WaitcntInstr, AMDGPU::OpName::simm16,
1464 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1465
1466 ScoreBrackets.applyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1467 ScoreBrackets.applyWaitcnt(EXP_CNT, Wait.ExpCnt);
1468 ScoreBrackets.applyWaitcnt(DS_CNT, Wait.DsCnt);
1469 Wait.LoadCnt = ~0u;
1470 Wait.ExpCnt = ~0u;
1471 Wait.DsCnt = ~0u;
1472
1473 LLVM_DEBUG(It == WaitcntInstr->getParent()->end()
1474 ? dbgs()
1475 << "applied pre-existing waitcnt\n"
1476 << "New Instr at block end: " << *WaitcntInstr << '\n'
1477 : dbgs() << "applied pre-existing waitcnt\n"
1478 << "Old Instr: " << *It
1479 << "New Instr: " << *WaitcntInstr << '\n');
1480 }
1481
1482 if (WaitcntVsCntInstr) {
1483 Modified |= updateOperandIfDifferent(*WaitcntVsCntInstr,
1484 AMDGPU::OpName::simm16, Wait.StoreCnt);
1485 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1486
1487 ScoreBrackets.applyWaitcnt(STORE_CNT, Wait.StoreCnt);
1488 Wait.StoreCnt = ~0u;
1489
1490 LLVM_DEBUG(It == WaitcntVsCntInstr->getParent()->end()
1491 ? dbgs() << "applied pre-existing waitcnt\n"
1492 << "New Instr at block end: " << *WaitcntVsCntInstr
1493 << '\n'
1494 : dbgs() << "applied pre-existing waitcnt\n"
1495 << "Old Instr: " << *It
1496 << "New Instr: " << *WaitcntVsCntInstr << '\n');
1497 }
1498
1499 return Modified;
1500}
1501
1502/// Generate S_WAITCNT and/or S_WAITCNT_VSCNT instructions for any
1503/// required counters in \p Wait
1504bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1505 MachineBasicBlock &Block, MachineBasicBlock::instr_iterator It,
1506 AMDGPU::Waitcnt Wait) {
1507 assert(ST);
1508 assert(isNormalMode(MaxCounter));
1509
1510 bool Modified = false;
1511 const DebugLoc &DL = Block.findDebugLoc(It);
1512
1513 // Waits for VMcnt, LKGMcnt and/or EXPcnt are encoded together into a
1514 // single instruction while VScnt has its own instruction.
1515 if (Wait.hasWaitExceptStoreCnt()) {
1516 unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
1517 [[maybe_unused]] auto SWaitInst =
1518 BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAITCNT)).addImm(Enc);
1519 Modified = true;
1520
1521 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1522 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1523 dbgs() << "New Instr: " << *SWaitInst << '\n');
1524 }
1525
1526 if (Wait.hasWaitStoreCnt()) {
1527 assert(ST->hasVscnt());
1528
1529 [[maybe_unused]] auto SWaitInst =
1530 BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAITCNT_VSCNT))
1531 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1532 .addImm(Wait.StoreCnt);
1533 Modified = true;
1534
1535 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1536 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1537 dbgs() << "New Instr: " << *SWaitInst << '\n');
1538 }
1539
1540 return Modified;
1541}
1542
1543AMDGPU::Waitcnt
1544WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(bool IncludeVSCnt) const {
1545 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt && ST->hasVscnt() ? 0 : ~0u);
1546}
1547
1548AMDGPU::Waitcnt
1549WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(bool IncludeVSCnt) const {
1550 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
1551 ~0u /* XCNT */);
1552}
1553
1554/// Combine consecutive S_WAIT_*CNT instructions that precede \p It and
1555/// follow \p OldWaitcntInstr and apply any extra waits from \p Wait that
1556/// were added by previous passes. Currently this pass conservatively
1557/// assumes that these preexisting waits are required for correctness.
1558bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
1559 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1560 AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
1561 assert(ST);
1562 assert(!isNormalMode(MaxCounter));
1563
1564 bool Modified = false;
1565 MachineInstr *CombinedLoadDsCntInstr = nullptr;
1566 MachineInstr *CombinedStoreDsCntInstr = nullptr;
1567 MachineInstr *WaitInstrs[NUM_EXTENDED_INST_CNTS] = {};
1568
1569 LLVM_DEBUG({
1570 dbgs() << "GFX12Plus::applyPreexistingWaitcnt at: ";
1571 if (It == OldWaitcntInstr.getParent()->instr_end())
1572 dbgs() << "end of block\n";
1573 else
1574 dbgs() << *It;
1575 });
1576
1577 for (auto &II :
1578 make_early_inc_range(make_range(OldWaitcntInstr.getIterator(), It))) {
1579 LLVM_DEBUG(dbgs() << "pre-existing iter: " << II);
1580 if (II.isMetaInstruction()) {
1581 LLVM_DEBUG(dbgs() << "skipped meta instruction\n");
1582 continue;
1583 }
1584
1585 MachineInstr **UpdatableInstr;
1586
1587 // Update required wait count. If this is a soft waitcnt (= it was added
1588 // by an earlier pass), it may be entirely removed.
1589
1590 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
1591 bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
1592
1593 // Don't crash if the programmer used legacy waitcnt intrinsics, but don't
1594 // attempt to do more than that either.
1595 if (Opcode == AMDGPU::S_WAITCNT)
1596 continue;
1597
1598 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
1599 unsigned OldEnc =
1600 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1601 AMDGPU::Waitcnt OldWait = AMDGPU::decodeLoadcntDscnt(IV, OldEnc);
1602 if (TrySimplify)
1603 ScoreBrackets.simplifyWaitcnt(OldWait);
1604 Wait = Wait.combined(OldWait);
1605 UpdatableInstr = &CombinedLoadDsCntInstr;
1606 } else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
1607 unsigned OldEnc =
1608 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1609 AMDGPU::Waitcnt OldWait = AMDGPU::decodeStorecntDscnt(IV, OldEnc);
1610 if (TrySimplify)
1611 ScoreBrackets.simplifyWaitcnt(OldWait);
1612 Wait = Wait.combined(OldWait);
1613 UpdatableInstr = &CombinedStoreDsCntInstr;
1614 } else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1615 // Architectures higher than GFX10 do not have direct loads to
1616 // LDS, so no work required here yet.
1617 II.eraseFromParent();
1618 continue;
1619 } else {
1620 std::optional<InstCounterType> CT = counterTypeForInstr(Opcode);
1621 assert(CT.has_value());
1622 unsigned OldCnt =
1623 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1624 if (TrySimplify)
1625 ScoreBrackets.simplifyWaitcnt(CT.value(), OldCnt);
1626 addWait(Wait, CT.value(), OldCnt);
1627 UpdatableInstr = &WaitInstrs[CT.value()];
1628 }
1629
1630 // Merge consecutive waitcnt of the same type by erasing multiples.
1631 if (!*UpdatableInstr) {
1632 *UpdatableInstr = &II;
1633 } else {
1634 II.eraseFromParent();
1635 Modified = true;
1636 }
1637 }
1638
1639 if (CombinedLoadDsCntInstr) {
1640 // Only keep an S_WAIT_LOADCNT_DSCNT if both counters actually need
1641 // to be waited for. Otherwise, let the instruction be deleted so
1642 // the appropriate single counter wait instruction can be inserted
1643 // instead, when new S_WAIT_*CNT instructions are inserted by
1644 // createNewWaitcnt(). As a side effect, resetting the wait counts will
1645 // cause any redundant S_WAIT_LOADCNT or S_WAIT_DSCNT to be removed by
1646 // the loop below that deals with single counter instructions.
1647 if (Wait.LoadCnt != ~0u && Wait.DsCnt != ~0u) {
1648 unsigned NewEnc = AMDGPU::encodeLoadcntDscnt(IV, Wait);
1649 Modified |= updateOperandIfDifferent(*CombinedLoadDsCntInstr,
1650 AMDGPU::OpName::simm16, NewEnc);
1651 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
1652 ScoreBrackets.applyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1653 ScoreBrackets.applyWaitcnt(DS_CNT, Wait.DsCnt);
1654 Wait.LoadCnt = ~0u;
1655 Wait.DsCnt = ~0u;
1656
1657 LLVM_DEBUG(It == OldWaitcntInstr.getParent()->end()
1658 ? dbgs() << "applied pre-existing waitcnt\n"
1659 << "New Instr at block end: "
1660 << *CombinedLoadDsCntInstr << '\n'
1661 : dbgs() << "applied pre-existing waitcnt\n"
1662 << "Old Instr: " << *It << "New Instr: "
1663 << *CombinedLoadDsCntInstr << '\n');
1664 } else {
1665 CombinedLoadDsCntInstr->eraseFromParent();
1666 Modified = true;
1667 }
1668 }
1669
1670 if (CombinedStoreDsCntInstr) {
1671 // Similarly for S_WAIT_STORECNT_DSCNT.
1672 if (Wait.StoreCnt != ~0u && Wait.DsCnt != ~0u) {
1673 unsigned NewEnc = AMDGPU::encodeStorecntDscnt(IV, Wait);
1674 Modified |= updateOperandIfDifferent(*CombinedStoreDsCntInstr,
1675 AMDGPU::OpName::simm16, NewEnc);
1676 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
1677 ScoreBrackets.applyWaitcnt(STORE_CNT, Wait.StoreCnt);
1678 ScoreBrackets.applyWaitcnt(DS_CNT, Wait.DsCnt);
1679 Wait.StoreCnt = ~0u;
1680 Wait.DsCnt = ~0u;
1681
1682 LLVM_DEBUG(It == OldWaitcntInstr.getParent()->end()
1683 ? dbgs() << "applied pre-existing waitcnt\n"
1684 << "New Instr at block end: "
1685 << *CombinedStoreDsCntInstr << '\n'
1686 : dbgs() << "applied pre-existing waitcnt\n"
1687 << "Old Instr: " << *It << "New Instr: "
1688 << *CombinedStoreDsCntInstr << '\n');
1689 } else {
1690 CombinedStoreDsCntInstr->eraseFromParent();
1691 Modified = true;
1692 }
1693 }
1694
1695 // Look for an opportunity to convert existing S_WAIT_LOADCNT,
1696 // S_WAIT_STORECNT and S_WAIT_DSCNT into new S_WAIT_LOADCNT_DSCNT
1697 // or S_WAIT_STORECNT_DSCNT. This is achieved by selectively removing
1698 // instructions so that createNewWaitcnt() will create new combined
1699 // instructions to replace them.
1700
1701 if (Wait.DsCnt != ~0u) {
1702 // This is a vector of addresses in WaitInstrs pointing to instructions
1703 // that should be removed if they are present.
1705
1706 // If it's known that both DScnt and either LOADcnt or STOREcnt (but not
1707 // both) need to be waited for, ensure that there are no existing
1708 // individual wait count instructions for these.
1709
1710 if (Wait.LoadCnt != ~0u) {
1711 WaitsToErase.push_back(&WaitInstrs[LOAD_CNT]);
1712 WaitsToErase.push_back(&WaitInstrs[DS_CNT]);
1713 } else if (Wait.StoreCnt != ~0u) {
1714 WaitsToErase.push_back(&WaitInstrs[STORE_CNT]);
1715 WaitsToErase.push_back(&WaitInstrs[DS_CNT]);
1716 }
1717
1718 for (MachineInstr **WI : WaitsToErase) {
1719 if (!*WI)
1720 continue;
1721
1722 (*WI)->eraseFromParent();
1723 *WI = nullptr;
1724 Modified = true;
1725 }
1726 }
1727
1728 for (auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1729 if (!WaitInstrs[CT])
1730 continue;
1731
1732 unsigned NewCnt = getWait(Wait, CT);
1733 if (NewCnt != ~0u) {
1734 Modified |= updateOperandIfDifferent(*WaitInstrs[CT],
1735 AMDGPU::OpName::simm16, NewCnt);
1736 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
1737
1738 ScoreBrackets.applyWaitcnt(CT, NewCnt);
1739 setNoWait(Wait, CT);
1740
1741 LLVM_DEBUG(It == OldWaitcntInstr.getParent()->end()
1742 ? dbgs() << "applied pre-existing waitcnt\n"
1743 << "New Instr at block end: " << *WaitInstrs[CT]
1744 << '\n'
1745 : dbgs() << "applied pre-existing waitcnt\n"
1746 << "Old Instr: " << *It
1747 << "New Instr: " << *WaitInstrs[CT] << '\n');
1748 } else {
1749 WaitInstrs[CT]->eraseFromParent();
1750 Modified = true;
1751 }
1752 }
1753
1754 return Modified;
1755}
1756
1757/// Generate S_WAIT_*CNT instructions for any required counters in \p Wait
1758bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
1759 MachineBasicBlock &Block, MachineBasicBlock::instr_iterator It,
1760 AMDGPU::Waitcnt Wait) {
1761 assert(ST);
1762 assert(!isNormalMode(MaxCounter));
1763
1764 bool Modified = false;
1765 const DebugLoc &DL = Block.findDebugLoc(It);
1766
1767 // Check for opportunities to use combined wait instructions.
1768 if (Wait.DsCnt != ~0u) {
1769 MachineInstr *SWaitInst = nullptr;
1770
1771 if (Wait.LoadCnt != ~0u) {
1772 unsigned Enc = AMDGPU::encodeLoadcntDscnt(IV, Wait);
1773
1774 SWaitInst = BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAIT_LOADCNT_DSCNT))
1775 .addImm(Enc);
1776
1777 Wait.LoadCnt = ~0u;
1778 Wait.DsCnt = ~0u;
1779 } else if (Wait.StoreCnt != ~0u) {
1780 unsigned Enc = AMDGPU::encodeStorecntDscnt(IV, Wait);
1781
1782 SWaitInst =
1783 BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAIT_STORECNT_DSCNT))
1784 .addImm(Enc);
1785
1786 Wait.StoreCnt = ~0u;
1787 Wait.DsCnt = ~0u;
1788 }
1789
1790 if (SWaitInst) {
1791 Modified = true;
1792
1793 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1794 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1795 dbgs() << "New Instr: " << *SWaitInst << '\n');
1796 }
1797 }
1798
1799 // Generate an instruction for any remaining counter that needs
1800 // waiting for.
1801
1802 for (auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1803 unsigned Count = getWait(Wait, CT);
1804 if (Count == ~0u)
1805 continue;
1806
1807 [[maybe_unused]] auto SWaitInst =
1808 BuildMI(Block, It, DL, TII->get(instrsForExtendedCounterTypes[CT]))
1809 .addImm(Count);
1810
1811 Modified = true;
1812
1813 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1814 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1815 dbgs() << "New Instr: " << *SWaitInst << '\n');
1816 }
1817
1818 return Modified;
1819}
1820
1821/// \returns true if the callee inserts an s_waitcnt 0 on function entry.
1823 // Currently all conventions wait, but this may not always be the case.
1824 //
1825 // TODO: If IPRA is enabled, and the callee is isSafeForNoCSROpt, it may make
1826 // senses to omit the wait and do it in the caller.
1827 return true;
1828}
1829
1830/// \returns true if the callee is expected to wait for any outstanding waits
1831/// before returning.
1832static bool callWaitsOnFunctionReturn(const MachineInstr &MI) { return true; }
1833
1834/// Generate s_waitcnt instruction to be placed before cur_Inst.
1835/// Instructions of a given type are returned in order,
1836/// but instructions of different types can complete out of order.
1837/// We rely on this in-order completion
1838/// and simply assign a score to the memory access instructions.
1839/// We keep track of the active "score bracket" to determine
1840/// if an access of a memory read requires an s_waitcnt
1841/// and if so what the value of each counter is.
1842/// The "score bracket" is bound by the lower bound and upper bound
1843/// scores (*_score_LB and *_score_ub respectively).
1844/// If FlushVmCnt is true, that means that we want to generate a s_waitcnt to
1845/// flush the vmcnt counter here.
1846bool SIInsertWaitcnts::generateWaitcntInstBefore(MachineInstr &MI,
1847 WaitcntBrackets &ScoreBrackets,
1848 MachineInstr *OldWaitcntInstr,
1849 bool FlushVmCnt) {
1850 setForceEmitWaitcnt();
1851
1852 assert(!MI.isMetaInstruction());
1853
1854 AMDGPU::Waitcnt Wait;
1855 const unsigned Opc = MI.getOpcode();
1856
1857 // FIXME: This should have already been handled by the memory legalizer.
1858 // Removing this currently doesn't affect any lit tests, but we need to
1859 // verify that nothing was relying on this. The number of buffer invalidates
1860 // being handled here should not be expanded.
1861 if (Opc == AMDGPU::BUFFER_WBINVL1 || Opc == AMDGPU::BUFFER_WBINVL1_SC ||
1862 Opc == AMDGPU::BUFFER_WBINVL1_VOL || Opc == AMDGPU::BUFFER_GL0_INV ||
1863 Opc == AMDGPU::BUFFER_GL1_INV) {
1864 Wait.LoadCnt = 0;
1865 }
1866
1867 // All waits must be resolved at call return.
1868 // NOTE: this could be improved with knowledge of all call sites or
1869 // with knowledge of the called routines.
1870 if (Opc == AMDGPU::SI_RETURN_TO_EPILOG || Opc == AMDGPU::SI_RETURN ||
1871 Opc == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1872 Opc == AMDGPU::S_SETPC_B64_return ||
1873 (MI.isReturn() && MI.isCall() && !callWaitsOnFunctionEntry(MI))) {
1874 Wait = Wait.combined(WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false));
1875 }
1876 // In dynamic VGPR mode, we want to release the VGPRs before the wave exits.
1877 // Technically the hardware will do this on its own if we don't, but that
1878 // might cost extra cycles compared to doing it explicitly.
1879 // When not in dynamic VGPR mode, identify S_ENDPGM instructions which may
1880 // have to wait for outstanding VMEM stores. In this case it can be useful to
1881 // send a message to explicitly release all VGPRs before the stores have
1882 // completed, but it is only safe to do this if there are no outstanding
1883 // scratch stores.
1884 else if (Opc == AMDGPU::S_ENDPGM || Opc == AMDGPU::S_ENDPGM_SAVED) {
1885 if (!WCG->isOptNone() &&
1886 (MI.getMF()->getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() ||
1887 (ST->getGeneration() >= AMDGPUSubtarget::GFX11 &&
1888 ScoreBrackets.getScoreRange(STORE_CNT) != 0 &&
1889 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS))))
1890 ReleaseVGPRInsts.insert(&MI);
1891 }
1892 // Resolve vm waits before gs-done.
1893 else if ((Opc == AMDGPU::S_SENDMSG || Opc == AMDGPU::S_SENDMSGHALT) &&
1894 ST->hasLegacyGeometry() &&
1895 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_PreGFX11_) ==
1897 Wait.LoadCnt = 0;
1898 }
1899
1900 // Export & GDS instructions do not read the EXEC mask until after the export
1901 // is granted (which can occur well after the instruction is issued).
1902 // The shader program must flush all EXP operations on the export-count
1903 // before overwriting the EXEC mask.
1904 else {
1905 if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
1906 // Export and GDS are tracked individually, either may trigger a waitcnt
1907 // for EXEC.
1908 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1909 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1910 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1911 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1912 Wait.ExpCnt = 0;
1913 }
1914 }
1915
1916 // Wait for any pending GDS instruction to complete before any
1917 // "Always GDS" instruction.
1918 if (TII->isAlwaysGDS(Opc) && ScoreBrackets.hasPendingGDS())
1919 addWait(Wait, DS_CNT, ScoreBrackets.getPendingGDSWait());
1920
1921 if (MI.isCall() && callWaitsOnFunctionEntry(MI)) {
1922 // The function is going to insert a wait on everything in its prolog.
1923 // This still needs to be careful if the call target is a load (e.g. a GOT
1924 // load). We also need to check WAW dependency with saved PC.
1925 Wait = AMDGPU::Waitcnt();
1926
1927 const auto &CallAddrOp = *TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1928 if (CallAddrOp.isReg()) {
1929 RegInterval CallAddrOpInterval =
1930 ScoreBrackets.getRegInterval(&MI, CallAddrOp);
1931
1932 ScoreBrackets.determineWait(SmemAccessCounter, CallAddrOpInterval,
1933 Wait);
1934
1935 if (const auto *RtnAddrOp =
1936 TII->getNamedOperand(MI, AMDGPU::OpName::dst)) {
1937 RegInterval RtnAddrOpInterval =
1938 ScoreBrackets.getRegInterval(&MI, *RtnAddrOp);
1939
1940 ScoreBrackets.determineWait(SmemAccessCounter, RtnAddrOpInterval,
1941 Wait);
1942 }
1943 }
1944 } else if (Opc == AMDGPU::S_BARRIER_WAIT) {
1945 ScoreBrackets.tryClearSCCWriteEvent(&MI);
1946 } else {
1947 // FIXME: Should not be relying on memoperands.
1948 // Look at the source operands of every instruction to see if
1949 // any of them results from a previous memory operation that affects
1950 // its current usage. If so, an s_waitcnt instruction needs to be
1951 // emitted.
1952 // If the source operand was defined by a load, add the s_waitcnt
1953 // instruction.
1954 //
1955 // Two cases are handled for destination operands:
1956 // 1) If the destination operand was defined by a load, add the s_waitcnt
1957 // instruction to guarantee the right WAW order.
1958 // 2) If a destination operand that was used by a recent export/store ins,
1959 // add s_waitcnt on exp_cnt to guarantee the WAR order.
1960
1961 for (const MachineMemOperand *Memop : MI.memoperands()) {
1962 const Value *Ptr = Memop->getValue();
1963 if (Memop->isStore()) {
1964 if (auto It = SLoadAddresses.find(Ptr); It != SLoadAddresses.end()) {
1965 addWait(Wait, SmemAccessCounter, 0);
1966 if (PDT->dominates(MI.getParent(), It->second))
1967 SLoadAddresses.erase(It);
1968 }
1969 }
1970 unsigned AS = Memop->getAddrSpace();
1972 continue;
1973 // No need to wait before load from VMEM to LDS.
1974 if (TII->mayWriteLDSThroughDMA(MI))
1975 continue;
1976
1977 // LOAD_CNT is only relevant to vgpr or LDS.
1978 unsigned RegNo = FIRST_LDS_VGPR;
1979 if (Ptr && Memop->getAAInfo()) {
1980 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
1981 for (unsigned I = 0, E = LDSDMAStores.size(); I != E; ++I) {
1982 if (MI.mayAlias(AA, *LDSDMAStores[I], true))
1983 ScoreBrackets.determineWait(LOAD_CNT, RegNo + I + 1, Wait);
1984 }
1985 } else {
1986 ScoreBrackets.determineWait(LOAD_CNT, RegNo, Wait);
1987 }
1988 if (Memop->isStore()) {
1989 ScoreBrackets.determineWait(EXP_CNT, RegNo, Wait);
1990 }
1991 }
1992
1993 // Loop over use and def operands.
1994 for (const MachineOperand &Op : MI.operands()) {
1995 if (!Op.isReg())
1996 continue;
1997
1998 // If the instruction does not read tied source, skip the operand.
1999 if (Op.isTied() && Op.isUse() && TII->doesNotReadTiedSource(MI))
2000 continue;
2001
2002 RegInterval Interval = ScoreBrackets.getRegInterval(&MI, Op);
2003
2004 const bool IsVGPR = TRI->isVectorRegister(*MRI, Op.getReg());
2005 if (IsVGPR) {
2006 // Implicit VGPR defs and uses are never a part of the memory
2007 // instructions description and usually present to account for
2008 // super-register liveness.
2009 // TODO: Most of the other instructions also have implicit uses
2010 // for the liveness accounting only.
2011 if (Op.isImplicit() && MI.mayLoadOrStore())
2012 continue;
2013
2014 // RAW always needs an s_waitcnt. WAW needs an s_waitcnt unless the
2015 // previous write and this write are the same type of VMEM
2016 // instruction, in which case they are (in some architectures)
2017 // guaranteed to write their results in order anyway.
2018 // Additionally check instructions where Point Sample Acceleration
2019 // might be applied.
2020 if (Op.isUse() || !updateVMCntOnly(MI) ||
2021 ScoreBrackets.hasOtherPendingVmemTypes(Interval,
2022 getVmemType(MI)) ||
2023 ScoreBrackets.hasPointSamplePendingVmemTypes(MI, Interval) ||
2024 !ST->hasVmemWriteVgprInOrder()) {
2025 ScoreBrackets.determineWait(LOAD_CNT, Interval, Wait);
2026 ScoreBrackets.determineWait(SAMPLE_CNT, Interval, Wait);
2027 ScoreBrackets.determineWait(BVH_CNT, Interval, Wait);
2028 ScoreBrackets.clearVgprVmemTypes(Interval);
2029 }
2030
2031 if (Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2032 ScoreBrackets.determineWait(EXP_CNT, Interval, Wait);
2033 }
2034 ScoreBrackets.determineWait(DS_CNT, Interval, Wait);
2035 } else if (Op.getReg() == AMDGPU::SCC) {
2036 ScoreBrackets.determineWait(KM_CNT, Interval, Wait);
2037 } else {
2038 ScoreBrackets.determineWait(SmemAccessCounter, Interval, Wait);
2039 }
2040
2041 if (ST->hasWaitXCnt() && Op.isDef())
2042 ScoreBrackets.determineWait(X_CNT, Interval, Wait);
2043 }
2044 }
2045 }
2046
2047 // Ensure safety against exceptions from outstanding memory operations while
2048 // waiting for a barrier:
2049 //
2050 // * Some subtargets safely handle backing off the barrier in hardware
2051 // when an exception occurs.
2052 // * Some subtargets have an implicit S_WAITCNT 0 before barriers, so that
2053 // there can be no outstanding memory operations during the wait.
2054 // * Subtargets with split barriers don't need to back off the barrier; it
2055 // is up to the trap handler to preserve the user barrier state correctly.
2056 //
2057 // In all other cases, ensure safety by ensuring that there are no outstanding
2058 // memory operations.
2059 if (Opc == AMDGPU::S_BARRIER && !ST->hasAutoWaitcntBeforeBarrier() &&
2060 !ST->supportsBackOffBarrier()) {
2061 Wait = Wait.combined(WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/true));
2062 }
2063
2064 // TODO: Remove this work-around, enable the assert for Bug 457939
2065 // after fixing the scheduler. Also, the Shader Compiler code is
2066 // independent of target.
2067 if (SIInstrInfo::isCBranchVCCZRead(MI) && ST->hasReadVCCZBug() &&
2068 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2069 Wait.DsCnt = 0;
2070 }
2071
2072 // Verify that the wait is actually needed.
2073 ScoreBrackets.simplifyWaitcnt(Wait);
2074
2075 // When forcing emit, we need to skip terminators because that would break the
2076 // terminators of the MBB if we emit a waitcnt between terminators.
2077 if (ForceEmitZeroFlag && !MI.isTerminator())
2078 Wait = WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false);
2079
2080 if (ForceEmitWaitcnt[LOAD_CNT])
2081 Wait.LoadCnt = 0;
2082 if (ForceEmitWaitcnt[EXP_CNT])
2083 Wait.ExpCnt = 0;
2084 if (ForceEmitWaitcnt[DS_CNT])
2085 Wait.DsCnt = 0;
2086 if (ForceEmitWaitcnt[SAMPLE_CNT])
2087 Wait.SampleCnt = 0;
2088 if (ForceEmitWaitcnt[BVH_CNT])
2089 Wait.BvhCnt = 0;
2090 if (ForceEmitWaitcnt[KM_CNT])
2091 Wait.KmCnt = 0;
2092 if (ForceEmitWaitcnt[X_CNT])
2093 Wait.XCnt = 0;
2094
2095 if (FlushVmCnt) {
2096 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2097 Wait.LoadCnt = 0;
2098 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2099 Wait.SampleCnt = 0;
2100 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2101 Wait.BvhCnt = 0;
2102 }
2103
2104 if (ForceEmitZeroLoadFlag && Wait.LoadCnt != ~0u)
2105 Wait.LoadCnt = 0;
2106
2107 return generateWaitcnt(Wait, MI.getIterator(), *MI.getParent(), ScoreBrackets,
2108 OldWaitcntInstr);
2109}
2110
2111bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt Wait,
2113 MachineBasicBlock &Block,
2114 WaitcntBrackets &ScoreBrackets,
2115 MachineInstr *OldWaitcntInstr) {
2116 bool Modified = false;
2117
2118 if (OldWaitcntInstr)
2119 // Try to merge the required wait with preexisting waitcnt instructions.
2120 // Also erase redundant waitcnt.
2121 Modified =
2122 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr, Wait, It);
2123
2124 // Any counts that could have been applied to any existing waitcnt
2125 // instructions will have been done so, now deal with any remaining.
2126 ScoreBrackets.applyWaitcnt(Wait);
2127
2128 // ExpCnt can be merged into VINTERP.
2129 if (Wait.ExpCnt != ~0u && It != Block.instr_end() &&
2131 MachineOperand *WaitExp =
2132 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
2133 if (Wait.ExpCnt < WaitExp->getImm()) {
2134 WaitExp->setImm(Wait.ExpCnt);
2135 Modified = true;
2136 }
2137 Wait.ExpCnt = ~0u;
2138
2139 LLVM_DEBUG(dbgs() << "generateWaitcnt\n"
2140 << "Update Instr: " << *It);
2141 }
2142
2143 // XCnt may be already consumed by a load wait.
2144 if (Wait.XCnt != ~0u) {
2145 if (Wait.KmCnt == 0 && !ScoreBrackets.hasPendingEvent(SMEM_GROUP))
2146 Wait.XCnt = ~0u;
2147
2148 if (Wait.LoadCnt == 0 && !ScoreBrackets.hasPendingEvent(VMEM_GROUP))
2149 Wait.XCnt = ~0u;
2150
2151 // Since the translation for VMEM addresses occur in-order, we can skip the
2152 // XCnt if the current instruction is of VMEM type and has a memory
2153 // dependency with another VMEM instruction in flight.
2154 if (isVmemAccess(*It))
2155 Wait.XCnt = ~0u;
2156 }
2157
2158 if (WCG->createNewWaitcnt(Block, It, Wait))
2159 Modified = true;
2160
2161 return Modified;
2162}
2163
2164bool SIInsertWaitcnts::isVmemAccess(const MachineInstr &MI) const {
2165 return (TII->isFLAT(MI) && TII->mayAccessVMEMThroughFlat(MI)) ||
2166 (TII->isVMEM(MI) && !AMDGPU::getMUBUFIsBufferInv(MI.getOpcode()));
2167}
2168
2169// Return true if the next instruction is S_ENDPGM, following fallthrough
2170// blocks if necessary.
2171bool SIInsertWaitcnts::isNextENDPGM(MachineBasicBlock::instr_iterator It,
2172 MachineBasicBlock *Block) const {
2173 auto BlockEnd = Block->getParent()->end();
2174 auto BlockIter = Block->getIterator();
2175
2176 while (true) {
2177 if (It.isEnd()) {
2178 if (++BlockIter != BlockEnd) {
2179 It = BlockIter->instr_begin();
2180 continue;
2181 }
2182
2183 return false;
2184 }
2185
2186 if (!It->isMetaInstruction())
2187 break;
2188
2189 It++;
2190 }
2191
2192 assert(!It.isEnd());
2193
2194 return It->getOpcode() == AMDGPU::S_ENDPGM;
2195}
2196
2197// Add a wait after an instruction if architecture requirements mandate one.
2198bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2199 MachineBasicBlock &Block,
2200 WaitcntBrackets &ScoreBrackets) {
2201 AMDGPU::Waitcnt Wait;
2202 bool NeedsEndPGMCheck = false;
2203
2204 if (ST->isPreciseMemoryEnabled() && Inst.mayLoadOrStore())
2205 Wait = WCG->getAllZeroWaitcnt(Inst.mayStore() &&
2207
2208 if (TII->isAlwaysGDS(Inst.getOpcode())) {
2209 Wait.DsCnt = 0;
2210 NeedsEndPGMCheck = true;
2211 }
2212
2213 ScoreBrackets.simplifyWaitcnt(Wait);
2214
2215 auto SuccessorIt = std::next(Inst.getIterator());
2216 bool Result = generateWaitcnt(Wait, SuccessorIt, Block, ScoreBrackets,
2217 /*OldWaitcntInstr=*/nullptr);
2218
2219 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &Block)) {
2220 BuildMI(Block, SuccessorIt, Inst.getDebugLoc(), TII->get(AMDGPU::S_NOP))
2221 .addImm(0);
2222 }
2223
2224 return Result;
2225}
2226
2227void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2228 WaitcntBrackets *ScoreBrackets) {
2229 // Now look at the instruction opcode. If it is a memory access
2230 // instruction, update the upper-bound of the appropriate counter's
2231 // bracket and the destination operand scores.
2232 // For architectures with X_CNT, mark the source address operands
2233 // with the appropriate counter values.
2234 // TODO: Use the (TSFlags & SIInstrFlags::DS_CNT) property everywhere.
2235
2236 bool IsVMEMAccess = false;
2237 bool IsSMEMAccess = false;
2238 if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
2239 if (TII->isAlwaysGDS(Inst.getOpcode()) ||
2240 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2241 ScoreBrackets->updateByEvent(GDS_ACCESS, Inst);
2242 ScoreBrackets->updateByEvent(GDS_GPR_LOCK, Inst);
2243 ScoreBrackets->setPendingGDS();
2244 } else {
2245 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2246 }
2247 } else if (TII->isFLAT(Inst)) {
2249 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2250 return;
2251 }
2252
2253 assert(Inst.mayLoadOrStore());
2254
2255 int FlatASCount = 0;
2256
2257 if (TII->mayAccessVMEMThroughFlat(Inst)) {
2258 ++FlatASCount;
2259 IsVMEMAccess = true;
2260 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2261 }
2262
2263 if (TII->mayAccessLDSThroughFlat(Inst)) {
2264 ++FlatASCount;
2265 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2266 }
2267
2268 // This is a flat memory operation that access both VMEM and LDS, so note it
2269 // - it will require that both the VM and LGKM be flushed to zero if it is
2270 // pending when a VM or LGKM dependency occurs.
2271 if (FlatASCount > 1)
2272 ScoreBrackets->setPendingFlat();
2273 } else if (SIInstrInfo::isVMEM(Inst) &&
2275 IsVMEMAccess = true;
2276 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2277
2278 if (ST->vmemWriteNeedsExpWaitcnt() &&
2279 (Inst.mayStore() || SIInstrInfo::isAtomicRet(Inst))) {
2280 ScoreBrackets->updateByEvent(VMW_GPR_LOCK, Inst);
2281 }
2282 } else if (TII->isSMRD(Inst)) {
2283 IsSMEMAccess = true;
2284 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2285 } else if (Inst.isCall()) {
2286 if (callWaitsOnFunctionReturn(Inst)) {
2287 // Act as a wait on everything
2288 ScoreBrackets->applyWaitcnt(
2289 WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false));
2290 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2291 } else {
2292 // May need to way wait for anything.
2293 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
2294 }
2295 } else if (SIInstrInfo::isLDSDIR(Inst)) {
2296 ScoreBrackets->updateByEvent(EXP_LDS_ACCESS, Inst);
2297 } else if (TII->isVINTERP(Inst)) {
2298 int64_t Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2299 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2300 } else if (SIInstrInfo::isEXP(Inst)) {
2301 unsigned Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2303 ScoreBrackets->updateByEvent(EXP_PARAM_ACCESS, Inst);
2304 else if (Imm >= AMDGPU::Exp::ET_POS0 && Imm <= AMDGPU::Exp::ET_POS_LAST)
2305 ScoreBrackets->updateByEvent(EXP_POS_ACCESS, Inst);
2306 else
2307 ScoreBrackets->updateByEvent(EXP_GPR_LOCK, Inst);
2308 } else if (SIInstrInfo::isSBarrierSCCWrite(Inst.getOpcode())) {
2309 ScoreBrackets->updateByEvent(SCC_WRITE, Inst);
2310 } else {
2311 switch (Inst.getOpcode()) {
2312 case AMDGPU::S_SENDMSG:
2313 case AMDGPU::S_SENDMSG_RTN_B32:
2314 case AMDGPU::S_SENDMSG_RTN_B64:
2315 case AMDGPU::S_SENDMSGHALT:
2316 ScoreBrackets->updateByEvent(SQ_MESSAGE, Inst);
2317 break;
2318 case AMDGPU::S_MEMTIME:
2319 case AMDGPU::S_MEMREALTIME:
2320 case AMDGPU::S_GET_BARRIER_STATE_M0:
2321 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2322 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2323 break;
2324 }
2325 }
2326
2327 if (!ST->hasWaitXCnt())
2328 return;
2329
2330 if (IsVMEMAccess)
2331 ScoreBrackets->updateByEvent(VMEM_GROUP, Inst);
2332
2333 if (IsSMEMAccess)
2334 ScoreBrackets->updateByEvent(SMEM_GROUP, Inst);
2335}
2336
2337bool WaitcntBrackets::mergeScore(const MergeInfo &M, unsigned &Score,
2338 unsigned OtherScore) {
2339 unsigned MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
2340 unsigned OtherShifted =
2341 OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
2342 Score = std::max(MyShifted, OtherShifted);
2343 return OtherShifted > MyShifted;
2344}
2345
2346/// Merge the pending events and associater score brackets of \p Other into
2347/// this brackets status.
2348///
2349/// Returns whether the merge resulted in a change that requires tighter waits
2350/// (i.e. the merged brackets strictly dominate the original brackets).
2351bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
2352 bool StrictDom = false;
2353
2354 VgprUB = std::max(VgprUB, Other.VgprUB);
2355 SgprUB = std::max(SgprUB, Other.SgprUB);
2356
2357 for (auto T : inst_counter_types(Context->MaxCounter)) {
2358 // Merge event flags for this counter
2359 const unsigned *WaitEventMaskForInst = Context->WaitEventMaskForInst;
2360 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[T];
2361 const unsigned OtherEvents = Other.PendingEvents & WaitEventMaskForInst[T];
2362 if (OtherEvents & ~OldEvents)
2363 StrictDom = true;
2364 PendingEvents |= OtherEvents;
2365
2366 // Merge scores for this counter
2367 const unsigned MyPending = ScoreUBs[T] - ScoreLBs[T];
2368 const unsigned OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
2369 const unsigned NewUB = ScoreLBs[T] + std::max(MyPending, OtherPending);
2370 if (NewUB < ScoreLBs[T])
2371 report_fatal_error("waitcnt score overflow");
2372
2373 MergeInfo M;
2374 M.OldLB = ScoreLBs[T];
2375 M.OtherLB = Other.ScoreLBs[T];
2376 M.MyShift = NewUB - ScoreUBs[T];
2377 M.OtherShift = NewUB - Other.ScoreUBs[T];
2378
2379 ScoreUBs[T] = NewUB;
2380
2381 StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]);
2382
2383 if (T == DS_CNT)
2384 StrictDom |= mergeScore(M, LastGDS, Other.LastGDS);
2385
2386 if (T == KM_CNT) {
2387 StrictDom |= mergeScore(M, SCCScore, Other.SCCScore);
2388 if (Other.hasPendingEvent(SCC_WRITE)) {
2389 unsigned OldEventsHasSCCWrite = OldEvents & (1 << SCC_WRITE);
2390 if (!OldEventsHasSCCWrite) {
2391 PendingSCCWrite = Other.PendingSCCWrite;
2392 } else if (PendingSCCWrite != Other.PendingSCCWrite) {
2393 PendingSCCWrite = nullptr;
2394 }
2395 }
2396 }
2397
2398 for (int J = 0; J <= VgprUB; J++)
2399 StrictDom |= mergeScore(M, VgprScores[T][J], Other.VgprScores[T][J]);
2400
2401 if (isSmemCounter(T)) {
2402 unsigned Idx = getSgprScoresIdx(T);
2403 for (int J = 0; J <= SgprUB; J++)
2404 StrictDom |=
2405 mergeScore(M, SgprScores[Idx][J], Other.SgprScores[Idx][J]);
2406 }
2407 }
2408
2409 for (int J = 0; J <= VgprUB; J++) {
2410 unsigned char NewVmemTypes = VgprVmemTypes[J] | Other.VgprVmemTypes[J];
2411 StrictDom |= NewVmemTypes != VgprVmemTypes[J];
2412 VgprVmemTypes[J] = NewVmemTypes;
2413 }
2414
2415 return StrictDom;
2416}
2417
2418static bool isWaitInstr(MachineInstr &Inst) {
2419 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(Inst.getOpcode());
2420 return Opcode == AMDGPU::S_WAITCNT ||
2421 (Opcode == AMDGPU::S_WAITCNT_VSCNT && Inst.getOperand(0).isReg() &&
2422 Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL) ||
2423 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2424 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2425 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
2426 counterTypeForInstr(Opcode).has_value();
2427}
2428
2429// Generate s_waitcnt instructions where needed.
2430bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
2431 MachineBasicBlock &Block,
2432 WaitcntBrackets &ScoreBrackets) {
2433 bool Modified = false;
2434
2435 LLVM_DEBUG({
2436 dbgs() << "*** Begin Block: ";
2437 Block.printName(dbgs());
2438 ScoreBrackets.dump();
2439 });
2440
2441 // Track the correctness of vccz through this basic block. There are two
2442 // reasons why it might be incorrect; see ST->hasReadVCCZBug() and
2443 // ST->partialVCCWritesUpdateVCCZ().
2444 bool VCCZCorrect = true;
2445 if (ST->hasReadVCCZBug()) {
2446 // vccz could be incorrect at a basic block boundary if a predecessor wrote
2447 // to vcc and then issued an smem load.
2448 VCCZCorrect = false;
2449 } else if (!ST->partialVCCWritesUpdateVCCZ()) {
2450 // vccz could be incorrect at a basic block boundary if a predecessor wrote
2451 // to vcc_lo or vcc_hi.
2452 VCCZCorrect = false;
2453 }
2454
2455 // Walk over the instructions.
2456 MachineInstr *OldWaitcntInstr = nullptr;
2457
2458 for (MachineBasicBlock::instr_iterator Iter = Block.instr_begin(),
2459 E = Block.instr_end();
2460 Iter != E;) {
2461 MachineInstr &Inst = *Iter;
2462 if (Inst.isMetaInstruction()) {
2463 ++Iter;
2464 continue;
2465 }
2466
2467 // Track pre-existing waitcnts that were added in earlier iterations or by
2468 // the memory legalizer.
2469 if (isWaitInstr(Inst)) {
2470 if (!OldWaitcntInstr)
2471 OldWaitcntInstr = &Inst;
2472 ++Iter;
2473 continue;
2474 }
2475
2476 bool FlushVmCnt = Block.getFirstTerminator() == Inst &&
2477 isPreheaderToFlush(Block, ScoreBrackets);
2478
2479 // Generate an s_waitcnt instruction to be placed before Inst, if needed.
2480 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2481 FlushVmCnt);
2482 OldWaitcntInstr = nullptr;
2483
2484 // Restore vccz if it's not known to be correct already.
2485 bool RestoreVCCZ = !VCCZCorrect && SIInstrInfo::isCBranchVCCZRead(Inst);
2486
2487 // Don't examine operands unless we need to track vccz correctness.
2488 if (ST->hasReadVCCZBug() || !ST->partialVCCWritesUpdateVCCZ()) {
2489 if (Inst.definesRegister(AMDGPU::VCC_LO, /*TRI=*/nullptr) ||
2490 Inst.definesRegister(AMDGPU::VCC_HI, /*TRI=*/nullptr)) {
2491 // Up to gfx9, writes to vcc_lo and vcc_hi don't update vccz.
2492 if (!ST->partialVCCWritesUpdateVCCZ())
2493 VCCZCorrect = false;
2494 } else if (Inst.definesRegister(AMDGPU::VCC, /*TRI=*/nullptr)) {
2495 // There is a hardware bug on CI/SI where SMRD instruction may corrupt
2496 // vccz bit, so when we detect that an instruction may read from a
2497 // corrupt vccz bit, we need to:
2498 // 1. Insert s_waitcnt lgkm(0) to wait for all outstanding SMRD
2499 // operations to complete.
2500 // 2. Restore the correct value of vccz by writing the current value
2501 // of vcc back to vcc.
2502 if (ST->hasReadVCCZBug() &&
2503 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2504 // Writes to vcc while there's an outstanding smem read may get
2505 // clobbered as soon as any read completes.
2506 VCCZCorrect = false;
2507 } else {
2508 // Writes to vcc will fix any incorrect value in vccz.
2509 VCCZCorrect = true;
2510 }
2511 }
2512 }
2513
2514 if (TII->isSMRD(Inst)) {
2515 for (const MachineMemOperand *Memop : Inst.memoperands()) {
2516 // No need to handle invariant loads when avoiding WAR conflicts, as
2517 // there cannot be a vector store to the same memory location.
2518 if (!Memop->isInvariant()) {
2519 const Value *Ptr = Memop->getValue();
2520 SLoadAddresses.insert(std::pair(Ptr, Inst.getParent()));
2521 }
2522 }
2523 if (ST->hasReadVCCZBug()) {
2524 // This smem read could complete and clobber vccz at any time.
2525 VCCZCorrect = false;
2526 }
2527 }
2528
2529 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2530
2531 Modified |= insertForcedWaitAfter(Inst, Block, ScoreBrackets);
2532
2533 LLVM_DEBUG({
2534 Inst.print(dbgs());
2535 ScoreBrackets.dump();
2536 });
2537
2538 // TODO: Remove this work-around after fixing the scheduler and enable the
2539 // assert above.
2540 if (RestoreVCCZ) {
2541 // Restore the vccz bit. Any time a value is written to vcc, the vcc
2542 // bit is updated, so we can restore the bit by reading the value of
2543 // vcc and then writing it back to the register.
2544 BuildMI(Block, Inst, Inst.getDebugLoc(),
2545 TII->get(ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2546 TRI->getVCC())
2547 .addReg(TRI->getVCC());
2548 VCCZCorrect = true;
2549 Modified = true;
2550 }
2551
2552 ++Iter;
2553 }
2554
2555 // Flush the LOADcnt, SAMPLEcnt and BVHcnt counters at the end of the block if
2556 // needed.
2557 AMDGPU::Waitcnt Wait;
2558 if (Block.getFirstTerminator() == Block.end() &&
2559 isPreheaderToFlush(Block, ScoreBrackets)) {
2560 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2561 Wait.LoadCnt = 0;
2562 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2563 Wait.SampleCnt = 0;
2564 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2565 Wait.BvhCnt = 0;
2566 }
2567
2568 // Combine or remove any redundant waitcnts at the end of the block.
2569 Modified |= generateWaitcnt(Wait, Block.instr_end(), Block, ScoreBrackets,
2570 OldWaitcntInstr);
2571
2572 LLVM_DEBUG({
2573 dbgs() << "*** End Block: ";
2574 Block.printName(dbgs());
2575 ScoreBrackets.dump();
2576 });
2577
2578 return Modified;
2579}
2580
2581// Return true if the given machine basic block is a preheader of a loop in
2582// which we want to flush the vmcnt counter, and false otherwise.
2583bool SIInsertWaitcnts::isPreheaderToFlush(
2584 MachineBasicBlock &MBB, const WaitcntBrackets &ScoreBrackets) {
2585 auto [Iterator, IsInserted] = PreheadersToFlush.try_emplace(&MBB, false);
2586 if (!IsInserted)
2587 return Iterator->second;
2588
2589 MachineBasicBlock *Succ = MBB.getSingleSuccessor();
2590 if (!Succ)
2591 return false;
2592
2593 MachineLoop *Loop = MLI->getLoopFor(Succ);
2594 if (!Loop)
2595 return false;
2596
2597 if (Loop->getLoopPreheader() == &MBB &&
2598 shouldFlushVmCnt(Loop, ScoreBrackets)) {
2599 Iterator->second = true;
2600 return true;
2601 }
2602
2603 return false;
2604}
2605
2606bool SIInsertWaitcnts::isVMEMOrFlatVMEM(const MachineInstr &MI) const {
2608 return TII->mayAccessVMEMThroughFlat(MI);
2609 return SIInstrInfo::isVMEM(MI);
2610}
2611
2612// Return true if it is better to flush the vmcnt counter in the preheader of
2613// the given loop. We currently decide to flush in two situations:
2614// 1. The loop contains vmem store(s), no vmem load and at least one use of a
2615// vgpr containing a value that is loaded outside of the loop. (Only on
2616// targets with no vscnt counter).
2617// 2. The loop contains vmem load(s), but the loaded values are not used in the
2618// loop, and at least one use of a vgpr containing a value that is loaded
2619// outside of the loop.
2620bool SIInsertWaitcnts::shouldFlushVmCnt(MachineLoop *ML,
2621 const WaitcntBrackets &Brackets) {
2622 bool HasVMemLoad = false;
2623 bool HasVMemStore = false;
2624 bool UsesVgprLoadedOutside = false;
2625 DenseSet<Register> VgprUse;
2626 DenseSet<Register> VgprDef;
2627
2628 for (MachineBasicBlock *MBB : ML->blocks()) {
2629 for (MachineInstr &MI : *MBB) {
2630 if (isVMEMOrFlatVMEM(MI)) {
2631 HasVMemLoad |= MI.mayLoad();
2632 HasVMemStore |= MI.mayStore();
2633 }
2634
2635 for (const MachineOperand &Op : MI.all_uses()) {
2636 if (Op.isDebug() || !TRI->isVectorRegister(*MRI, Op.getReg()))
2637 continue;
2638 RegInterval Interval = Brackets.getRegInterval(&MI, Op);
2639 // Vgpr use
2640 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
2641 // If we find a register that is loaded inside the loop, 1. and 2.
2642 // are invalidated and we can exit.
2643 if (VgprDef.contains(RegNo))
2644 return false;
2645 VgprUse.insert(RegNo);
2646 // If at least one of Op's registers is in the score brackets, the
2647 // value is likely loaded outside of the loop.
2648 if (Brackets.getRegScore(RegNo, LOAD_CNT) >
2649 Brackets.getScoreLB(LOAD_CNT) ||
2650 Brackets.getRegScore(RegNo, SAMPLE_CNT) >
2651 Brackets.getScoreLB(SAMPLE_CNT) ||
2652 Brackets.getRegScore(RegNo, BVH_CNT) >
2653 Brackets.getScoreLB(BVH_CNT)) {
2654 UsesVgprLoadedOutside = true;
2655 break;
2656 }
2657 }
2658 }
2659
2660 // VMem load vgpr def
2661 if (isVMEMOrFlatVMEM(MI) && MI.mayLoad()) {
2662 for (const MachineOperand &Op : MI.all_defs()) {
2663 RegInterval Interval = Brackets.getRegInterval(&MI, Op);
2664 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
2665 // If we find a register that is loaded inside the loop, 1. and 2.
2666 // are invalidated and we can exit.
2667 if (VgprUse.contains(RegNo))
2668 return false;
2669 VgprDef.insert(RegNo);
2670 }
2671 }
2672 }
2673 }
2674 }
2675 if (!ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2676 return true;
2677 return HasVMemLoad && UsesVgprLoadedOutside && ST->hasVmemWriteVgprInOrder();
2678}
2679
2680bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
2681 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2682 auto *PDT =
2683 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2684 AliasAnalysis *AA = nullptr;
2685 if (auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2686 AA = &AAR->getAAResults();
2687
2688 return SIInsertWaitcnts(MLI, PDT, AA).run(MF);
2689}
2690
2691PreservedAnalyses
2694 auto *MLI = &MFAM.getResult<MachineLoopAnalysis>(MF);
2695 auto *PDT = &MFAM.getResult<MachinePostDominatorTreeAnalysis>(MF);
2697 .getManager()
2698 .getCachedResult<AAManager>(MF.getFunction());
2699
2700 if (!SIInsertWaitcnts(MLI, PDT, AA).run(MF))
2701 return PreservedAnalyses::all();
2702
2705 .preserve<AAManager>();
2706}
2707
2708bool SIInsertWaitcnts::run(MachineFunction &MF) {
2709 ST = &MF.getSubtarget<GCNSubtarget>();
2710 TII = ST->getInstrInfo();
2711 TRI = &TII->getRegisterInfo();
2712 MRI = &MF.getRegInfo();
2714
2716
2717 if (ST->hasExtendedWaitCounts()) {
2718 MaxCounter = NUM_EXTENDED_INST_CNTS;
2719 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2720 WCG = &WCGGFX12Plus;
2721 } else {
2722 MaxCounter = NUM_NORMAL_INST_CNTS;
2723 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF);
2724 WCG = &WCGPreGFX12;
2725 }
2726
2727 for (auto T : inst_counter_types())
2728 ForceEmitWaitcnt[T] = false;
2729
2730 WaitEventMaskForInst = WCG->getWaitEventMask();
2731
2732 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2733
2734 if (ST->hasExtendedWaitCounts()) {
2735 Limits.LoadcntMax = AMDGPU::getLoadcntBitMask(IV);
2736 Limits.DscntMax = AMDGPU::getDscntBitMask(IV);
2737 } else {
2738 Limits.LoadcntMax = AMDGPU::getVmcntBitMask(IV);
2739 Limits.DscntMax = AMDGPU::getLgkmcntBitMask(IV);
2740 }
2741 Limits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
2742 Limits.StorecntMax = AMDGPU::getStorecntBitMask(IV);
2743 Limits.SamplecntMax = AMDGPU::getSamplecntBitMask(IV);
2744 Limits.BvhcntMax = AMDGPU::getBvhcntBitMask(IV);
2745 Limits.KmcntMax = AMDGPU::getKmcntBitMask(IV);
2746 Limits.XcntMax = AMDGPU::getXcntBitMask(IV);
2747
2748 [[maybe_unused]] unsigned NumVGPRsMax =
2749 ST->getAddressableNumVGPRs(MFI->getDynamicVGPRBlockSize());
2750 [[maybe_unused]] unsigned NumSGPRsMax = ST->getAddressableNumSGPRs();
2751 assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
2752 assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
2753
2754 BlockInfos.clear();
2755 bool Modified = false;
2756
2757 MachineBasicBlock &EntryBB = MF.front();
2759
2760 if (!MFI->isEntryFunction()) {
2761 // Wait for any outstanding memory operations that the input registers may
2762 // depend on. We can't track them and it's better to do the wait after the
2763 // costly call sequence.
2764
2765 // TODO: Could insert earlier and schedule more liberally with operations
2766 // that only use caller preserved registers.
2767 for (MachineBasicBlock::iterator E = EntryBB.end();
2768 I != E && (I->isPHI() || I->isMetaInstruction()); ++I)
2769 ;
2770
2771 if (ST->hasExtendedWaitCounts()) {
2772 BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAIT_LOADCNT_DSCNT))
2773 .addImm(0);
2774 for (auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2775 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT)
2776 continue;
2777
2778 if (!ST->hasImageInsts() &&
2779 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
2780 continue;
2781
2782 BuildMI(EntryBB, I, DebugLoc(),
2783 TII->get(instrsForExtendedCounterTypes[CT]))
2784 .addImm(0);
2785 }
2786 } else {
2787 BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT)).addImm(0);
2788 }
2789
2790 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(this);
2791 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2792 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2793
2794 Modified = true;
2795 }
2796
2797 // Keep iterating over the blocks in reverse post order, inserting and
2798 // updating s_waitcnt where needed, until a fix point is reached.
2799 for (auto *MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
2800 BlockInfos.try_emplace(MBB);
2801
2802 std::unique_ptr<WaitcntBrackets> Brackets;
2803 bool Repeat;
2804 do {
2805 Repeat = false;
2806
2807 for (auto BII = BlockInfos.begin(), BIE = BlockInfos.end(); BII != BIE;
2808 ++BII) {
2809 MachineBasicBlock *MBB = BII->first;
2810 BlockInfo &BI = BII->second;
2811 if (!BI.Dirty)
2812 continue;
2813
2814 if (BI.Incoming) {
2815 if (!Brackets)
2816 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2817 else
2818 *Brackets = *BI.Incoming;
2819 } else {
2820 if (!Brackets) {
2821 Brackets = std::make_unique<WaitcntBrackets>(this);
2822 } else {
2823 // Reinitialize in-place. N.B. do not do this by assigning from a
2824 // temporary because the WaitcntBrackets class is large and it could
2825 // cause this function to use an unreasonable amount of stack space.
2826 Brackets->~WaitcntBrackets();
2827 new (Brackets.get()) WaitcntBrackets(this);
2828 }
2829 }
2830
2831 Modified |= insertWaitcntInBlock(MF, *MBB, *Brackets);
2832 BI.Dirty = false;
2833
2834 if (Brackets->hasPendingEvent()) {
2835 BlockInfo *MoveBracketsToSucc = nullptr;
2836 for (MachineBasicBlock *Succ : MBB->successors()) {
2837 auto *SuccBII = BlockInfos.find(Succ);
2838 BlockInfo &SuccBI = SuccBII->second;
2839 if (!SuccBI.Incoming) {
2840 SuccBI.Dirty = true;
2841 if (SuccBII <= BII) {
2842 LLVM_DEBUG(dbgs() << "repeat on backedge\n");
2843 Repeat = true;
2844 }
2845 if (!MoveBracketsToSucc) {
2846 MoveBracketsToSucc = &SuccBI;
2847 } else {
2848 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2849 }
2850 } else if (SuccBI.Incoming->merge(*Brackets)) {
2851 SuccBI.Dirty = true;
2852 if (SuccBII <= BII) {
2853 LLVM_DEBUG(dbgs() << "repeat on backedge\n");
2854 Repeat = true;
2855 }
2856 }
2857 }
2858 if (MoveBracketsToSucc)
2859 MoveBracketsToSucc->Incoming = std::move(Brackets);
2860 }
2861 }
2862 } while (Repeat);
2863
2864 if (ST->hasScalarStores()) {
2865 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
2866 bool HaveScalarStores = false;
2867
2868 for (MachineBasicBlock &MBB : MF) {
2869 for (MachineInstr &MI : MBB) {
2870 if (!HaveScalarStores && TII->isScalarStore(MI))
2871 HaveScalarStores = true;
2872
2873 if (MI.getOpcode() == AMDGPU::S_ENDPGM ||
2874 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2875 EndPgmBlocks.push_back(&MBB);
2876 }
2877 }
2878
2879 if (HaveScalarStores) {
2880 // If scalar writes are used, the cache must be flushed or else the next
2881 // wave to reuse the same scratch memory can be clobbered.
2882 //
2883 // Insert s_dcache_wb at wave termination points if there were any scalar
2884 // stores, and only if the cache hasn't already been flushed. This could
2885 // be improved by looking across blocks for flushes in postdominating
2886 // blocks from the stores but an explicitly requested flush is probably
2887 // very rare.
2888 for (MachineBasicBlock *MBB : EndPgmBlocks) {
2889 bool SeenDCacheWB = false;
2890
2891 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
2892 I != E; ++I) {
2893 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
2894 SeenDCacheWB = true;
2895 else if (TII->isScalarStore(*I))
2896 SeenDCacheWB = false;
2897
2898 // FIXME: It would be better to insert this before a waitcnt if any.
2899 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
2900 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
2901 !SeenDCacheWB) {
2902 Modified = true;
2903 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
2904 }
2905 }
2906 }
2907 }
2908 }
2909
2910 // Deallocate the VGPRs before previously identified S_ENDPGM instructions.
2911 // This is done in different ways depending on how the VGPRs were allocated
2912 // (i.e. whether we're in dynamic VGPR mode or not).
2913 // Skip deallocation if kernel is waveslot limited vs VGPR limited. A short
2914 // waveslot limited kernel runs slower with the deallocation.
2915 if (MFI->isDynamicVGPREnabled()) {
2916 for (MachineInstr *MI : ReleaseVGPRInsts) {
2917 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2918 TII->get(AMDGPU::S_ALLOC_VGPR))
2919 .addImm(0);
2920 Modified = true;
2921 }
2922 } else {
2923 if (!ReleaseVGPRInsts.empty() &&
2924 (MF.getFrameInfo().hasCalls() ||
2925 ST->getOccupancyWithNumVGPRs(
2926 TRI->getNumUsedPhysRegs(*MRI, AMDGPU::VGPR_32RegClass),
2927 /*IsDynamicVGPR=*/false) <
2929 for (MachineInstr *MI : ReleaseVGPRInsts) {
2930 if (ST->requiresNopBeforeDeallocVGPRs()) {
2931 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2932 TII->get(AMDGPU::S_NOP))
2933 .addImm(0);
2934 }
2935 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2936 TII->get(AMDGPU::S_SENDMSG))
2938 Modified = true;
2939 }
2940 }
2941 }
2942 ReleaseVGPRInsts.clear();
2943 PreheadersToFlush.clear();
2944 SLoadAddresses.clear();
2945
2946 return Modified;
2947}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
static bool isOptNone(const MachineFunction &MF)
IRTranslator LLVM IR MI
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
#define I(x, y, z)
Definition MD5.cpp:58
Register Reg
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
std::pair< uint64_t, uint64_t > Interval
#define T
static bool isReg(const MCInst &MI, unsigned OpNo)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static cl::opt< bool > ForceEmitZeroLoadFlag("amdgpu-waitcnt-load-forcezero", cl::desc("Force all waitcnt load counters to wait until 0"), cl::init(false), cl::Hidden)
static bool callWaitsOnFunctionReturn(const MachineInstr &MI)
#define AMDGPU_EVENT_NAME(Name)
static bool callWaitsOnFunctionEntry(const MachineInstr &MI)
static bool updateOperandIfDifferent(MachineInstr &MI, AMDGPU::OpName OpName, unsigned NewEnc)
static bool isWaitInstr(MachineInstr &Inst)
static std::optional< InstCounterType > counterTypeForInstr(unsigned Opcode)
Determine if MI is a gfx12+ single-counter S_WAIT_*CNT instruction, and if so, which counter it is wa...
static cl::opt< bool > ForceEmitZeroFlag("amdgpu-waitcnt-forcezero", cl::desc("Force all waitcnt instrs to be emitted as " "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"), cl::init(false), cl::Hidden)
#define AMDGPU_DECLARE_WAIT_EVENTS(DECL)
#define AMDGPU_EVENT_ENUM(Name)
Provides some synthesis utilities to produce sequences of values.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
static const uint32_t IV[8]
Definition blake3_impl.h:83
A manager for alias analyses.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static bool isCounterSet(unsigned ID)
static bool shouldExecute(unsigned CounterName)
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:167
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:237
bool erase(const KeyT &Val)
Definition DenseMap.h:311
iterator end()
Definition DenseMap.h:81
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:222
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI const MachineBasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
Instructions::iterator instr_iterator
iterator_range< succ_iterator > successors()
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
bool isCall(QueryType Type=AnyInBundle) const
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr fully defines the specified register.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
LLVM_ABI void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
const MachineOperand & getOperand(unsigned i) const
bool isMetaInstruction(QueryType Type=IgnoreBundle) const
Return true if this instruction doesn't produce any output in the form of executable instructions.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
int64_t getImm() const
Register getReg() const
getReg - Returns the register number.
iterator end()
Definition MapVector.h:67
iterator find(const KeyT &Key)
Definition MapVector.h:149
iterator begin()
Definition MapVector.h:65
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static bool isCBranchVCCZRead(const MachineInstr &MI)
static bool isVMEM(const MachineInstr &MI)
static bool isFLATScratch(const MachineInstr &MI)
static bool isEXP(const MachineInstr &MI)
static bool mayWriteLDSThroughDMA(const MachineInstr &MI)
static bool isLDSDIR(const MachineInstr &MI)
static bool isGWS(const MachineInstr &MI)
static bool isFLATGlobal(const MachineInstr &MI)
static bool isVSAMPLE(const MachineInstr &MI)
static bool isAtomicRet(const MachineInstr &MI)
static bool isImage(const MachineInstr &MI)
static unsigned getNonSoftWaitcntOpcode(unsigned Opcode)
static bool isVINTERP(const MachineInstr &MI)
static bool isGFX12CacheInvOrWBInst(unsigned Opc)
static bool isSBarrierSCCWrite(unsigned Opcode)
static bool isMIMG(const MachineInstr &MI)
static bool isFLAT(const MachineInstr &MI)
static bool isAtomicNoRet(const MachineInstr &MI)
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
void push_back(const T &Elt)
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:854
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
@ LOCAL_ADDRESS
Address space for local memory.
@ FLAT_ADDRESS
Address space for flat memory.
unsigned getMaxWavesPerEU(const MCSubtargetInfo *STI)
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
void decodeWaitcnt(const IsaVersion &Version, unsigned Waitcnt, unsigned &Vmcnt, unsigned &Expcnt, unsigned &Lgkmcnt)
Decodes Vmcnt, Expcnt and Lgkmcnt from given Waitcnt for given isa Version, and writes decoded values...
MCRegister getMCReg(MCRegister Reg, const MCSubtargetInfo &STI)
If Reg is a pseudo reg, return the correct hardware register given STI otherwise return Reg.
bool isHi16Reg(MCRegister Reg, const MCRegisterInfo &MRI)
unsigned getStorecntBitMask(const IsaVersion &Version)
LLVM_ABI IsaVersion getIsaVersion(StringRef GPU)
unsigned encodeWaitcnt(const IsaVersion &Version, unsigned Vmcnt, unsigned Expcnt, unsigned Lgkmcnt)
Encodes Vmcnt, Expcnt and Lgkmcnt into Waitcnt for given isa Version.
unsigned getSamplecntBitMask(const IsaVersion &Version)
unsigned getKmcntBitMask(const IsaVersion &Version)
unsigned getVmcntBitMask(const IsaVersion &Version)
unsigned getXcntBitMask(const IsaVersion &Version)
Waitcnt decodeStorecntDscnt(const IsaVersion &Version, unsigned StorecntDscnt)
unsigned getLgkmcntBitMask(const IsaVersion &Version)
unsigned getBvhcntBitMask(const IsaVersion &Version)
unsigned getExpcntBitMask(const IsaVersion &Version)
Waitcnt decodeLoadcntDscnt(const IsaVersion &Version, unsigned LoadcntDscnt)
static unsigned encodeStorecntDscnt(const IsaVersion &Version, unsigned Storecnt, unsigned Dscnt)
bool getMUBUFIsBufferInv(unsigned Opc)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
unsigned getLoadcntBitMask(const IsaVersion &Version)
static unsigned encodeLoadcntDscnt(const IsaVersion &Version, unsigned Loadcnt, unsigned Dscnt)
unsigned getDscntBitMask(const IsaVersion &Version)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Undef
Value of the register doesn't matter.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
auto enum_seq(EnumT Begin, EnumT End)
Iterate over an enum type from Begin up to - but not including - End.
Definition Sequence.h:337
@ Wait
Definition Threading.h:60
static StringRef getCPU(StringRef CPU)
Processes a CPU name.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
char & SIInsertWaitcntsID
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:405
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
FunctionPass * createSIInsertWaitcntsPass()
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
Instruction set architecture version.
Represents the counter values to wait for in an s_waitcnt instruction.