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 for (const MachineOperand &Op : Inst.all_uses())
1017 setScoreByOperand(&Inst, Op, T, CurrScore);
1018 } else /* LGKM_CNT || EXP_CNT || VS_CNT || NUM_INST_CNTS */ {
1019 // Match the score to the destination registers.
1020 //
1021 // Check only explicit operands. Stores, especially spill stores, include
1022 // implicit uses and defs of their super registers which would create an
1023 // artificial dependency, while these are there only for register liveness
1024 // accounting purposes.
1025 //
1026 // Special cases where implicit register defs exists, such as M0 or VCC,
1027 // but none with memory instructions.
1028 for (const MachineOperand &Op : Inst.defs()) {
1029 RegInterval Interval = getRegInterval(&Inst, Op);
1030 if (T == LOAD_CNT || T == SAMPLE_CNT || T == BVH_CNT) {
1031 if (Interval.first >= NUM_ALL_VGPRS)
1032 continue;
1033 if (updateVMCntOnly(Inst)) {
1034 // updateVMCntOnly should only leave us with VGPRs
1035 // MUBUF, MTBUF, MIMG, FlatGlobal, and FlatScratch only have VGPR/AGPR
1036 // defs. That's required for a sane index into `VgprMemTypes` below
1037 assert(TRI->isVectorRegister(*MRI, Op.getReg()));
1038 VmemType V = getVmemType(Inst);
1039 unsigned char TypesMask = 1 << V;
1040 // If instruction can have Point Sample Accel applied, we have to flag
1041 // this with another potential dependency
1042 if (hasPointSampleAccel(Inst))
1043 TypesMask |= 1 << VMEM_NOSAMPLER;
1044 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo)
1045 VgprVmemTypes[RegNo] |= TypesMask;
1046 }
1047 }
1048 setScoreByInterval(Interval, T, CurrScore);
1049 }
1050 if (Inst.mayStore() &&
1051 (TII->isDS(Inst) || TII->mayWriteLDSThroughDMA(Inst))) {
1052 // MUBUF and FLAT LDS DMA operations need a wait on vmcnt before LDS
1053 // written can be accessed. A load from LDS to VMEM does not need a wait.
1054 unsigned Slot = 0;
1055 for (const auto *MemOp : Inst.memoperands()) {
1056 if (!MemOp->isStore() ||
1057 MemOp->getAddrSpace() != AMDGPUAS::LOCAL_ADDRESS)
1058 continue;
1059 // Comparing just AA info does not guarantee memoperands are equal
1060 // in general, but this is so for LDS DMA in practice.
1061 auto AAI = MemOp->getAAInfo();
1062 // Alias scope information gives a way to definitely identify an
1063 // original memory object and practically produced in the module LDS
1064 // lowering pass. If there is no scope available we will not be able
1065 // to disambiguate LDS aliasing as after the module lowering all LDS
1066 // is squashed into a single big object. Do not attempt to use one of
1067 // the limited LDSDMAStores for something we will not be able to use
1068 // anyway.
1069 if (!AAI || !AAI.Scope)
1070 break;
1071 for (unsigned I = 0, E = LDSDMAStores.size(); I != E && !Slot; ++I) {
1072 for (const auto *MemOp : LDSDMAStores[I]->memoperands()) {
1073 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1074 Slot = I + 1;
1075 break;
1076 }
1077 }
1078 }
1079 if (Slot || LDSDMAStores.size() == NUM_LDS_VGPRS - 1)
1080 break;
1081 LDSDMAStores.push_back(&Inst);
1082 Slot = LDSDMAStores.size();
1083 break;
1084 }
1085 setRegScore(FIRST_LDS_VGPR + Slot, T, CurrScore);
1086 if (Slot)
1087 setRegScore(FIRST_LDS_VGPR, T, CurrScore);
1088 }
1089
1091 setRegScore(SCC, T, CurrScore);
1092 PendingSCCWrite = &Inst;
1093 }
1094 }
1095}
1096
1097void WaitcntBrackets::print(raw_ostream &OS) const {
1098 const GCNSubtarget *ST = Context->ST;
1099
1100 OS << '\n';
1101 for (auto T : inst_counter_types(Context->MaxCounter)) {
1102 unsigned SR = getScoreRange(T);
1103
1104 switch (T) {
1105 case LOAD_CNT:
1106 OS << " " << (ST->hasExtendedWaitCounts() ? "LOAD" : "VM") << "_CNT("
1107 << SR << "): ";
1108 break;
1109 case DS_CNT:
1110 OS << " " << (ST->hasExtendedWaitCounts() ? "DS" : "LGKM") << "_CNT("
1111 << SR << "): ";
1112 break;
1113 case EXP_CNT:
1114 OS << " EXP_CNT(" << SR << "): ";
1115 break;
1116 case STORE_CNT:
1117 OS << " " << (ST->hasExtendedWaitCounts() ? "STORE" : "VS") << "_CNT("
1118 << SR << "): ";
1119 break;
1120 case SAMPLE_CNT:
1121 OS << " SAMPLE_CNT(" << SR << "): ";
1122 break;
1123 case BVH_CNT:
1124 OS << " BVH_CNT(" << SR << "): ";
1125 break;
1126 case KM_CNT:
1127 OS << " KM_CNT(" << SR << "): ";
1128 break;
1129 case X_CNT:
1130 OS << " X_CNT(" << SR << "): ";
1131 break;
1132 default:
1133 OS << " UNKNOWN(" << SR << "): ";
1134 break;
1135 }
1136
1137 if (SR != 0) {
1138 // Print vgpr scores.
1139 unsigned LB = getScoreLB(T);
1140
1141 for (int J = 0; J <= VgprUB; J++) {
1142 unsigned RegScore = getRegScore(J, T);
1143 if (RegScore <= LB)
1144 continue;
1145 unsigned RelScore = RegScore - LB - 1;
1146 if (J < FIRST_LDS_VGPR) {
1147 OS << RelScore << ":v" << J << " ";
1148 } else {
1149 OS << RelScore << ":ds ";
1150 }
1151 }
1152 // Also need to print sgpr scores for lgkm_cnt or xcnt.
1153 if (isSmemCounter(T)) {
1154 for (int J = 0; J <= SgprUB; J++) {
1155 unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS, T);
1156 if (RegScore <= LB)
1157 continue;
1158 unsigned RelScore = RegScore - LB - 1;
1159 OS << RelScore << ":s" << J << " ";
1160 }
1161 }
1162 if (T == KM_CNT && SCCScore > 0)
1163 OS << SCCScore << ":scc ";
1164 }
1165 OS << '\n';
1166 }
1167
1168 OS << "Pending Events: ";
1169 if (hasPendingEvent()) {
1170 ListSeparator LS;
1171 for (unsigned I = 0; I != NUM_WAIT_EVENTS; ++I) {
1172 if (hasPendingEvent((WaitEventType)I)) {
1173 OS << LS << WaitEventTypeName[I];
1174 }
1175 }
1176 } else {
1177 OS << "none";
1178 }
1179 OS << '\n';
1180
1181 OS << '\n';
1182}
1183
1184/// Simplify the waitcnt, in the sense of removing redundant counts, and return
1185/// whether a waitcnt instruction is needed at all.
1186void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const {
1187 simplifyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1188 simplifyWaitcnt(EXP_CNT, Wait.ExpCnt);
1189 simplifyWaitcnt(DS_CNT, Wait.DsCnt);
1190 simplifyWaitcnt(STORE_CNT, Wait.StoreCnt);
1191 simplifyWaitcnt(SAMPLE_CNT, Wait.SampleCnt);
1192 simplifyWaitcnt(BVH_CNT, Wait.BvhCnt);
1193 simplifyWaitcnt(KM_CNT, Wait.KmCnt);
1194 simplifyWaitcnt(X_CNT, Wait.XCnt);
1195}
1196
1197void WaitcntBrackets::simplifyWaitcnt(InstCounterType T,
1198 unsigned &Count) const {
1199 // The number of outstanding events for this type, T, can be calculated
1200 // as (UB - LB). If the current Count is greater than or equal to the number
1201 // of outstanding events, then the wait for this counter is redundant.
1202 if (Count >= getScoreRange(T))
1203 Count = ~0u;
1204}
1205
1206void WaitcntBrackets::determineWait(InstCounterType T, RegInterval Interval,
1207 AMDGPU::Waitcnt &Wait) const {
1208 const unsigned LB = getScoreLB(T);
1209 const unsigned UB = getScoreUB(T);
1210 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1211 unsigned ScoreToWait = getRegScore(RegNo, T);
1212
1213 // If the score of src_operand falls within the bracket, we need an
1214 // s_waitcnt instruction.
1215 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1216 if ((T == LOAD_CNT || T == DS_CNT) && hasPendingFlat() &&
1217 !Context->ST->hasFlatLgkmVMemCountInOrder()) {
1218 // If there is a pending FLAT operation, and this is a VMem or LGKM
1219 // waitcnt and the target can report early completion, then we need
1220 // to force a waitcnt 0.
1221 addWait(Wait, T, 0);
1222 } else if (counterOutOfOrder(T)) {
1223 // Counter can get decremented out-of-order when there
1224 // are multiple types event in the bracket. Also emit an s_wait counter
1225 // with a conservative value of 0 for the counter.
1226 addWait(Wait, T, 0);
1227 } else {
1228 // If a counter has been maxed out avoid overflow by waiting for
1229 // MAX(CounterType) - 1 instead.
1230 unsigned NeededWait =
1231 std::min(UB - ScoreToWait, Context->getWaitCountMax(T) - 1);
1232 addWait(Wait, T, NeededWait);
1233 }
1234 }
1235 }
1236}
1237
1238void WaitcntBrackets::tryClearSCCWriteEvent(MachineInstr *Inst) {
1239 // S_BARRIER_WAIT on the same barrier guarantees that the pending write to
1240 // SCC has landed
1241 if (PendingSCCWrite &&
1242 PendingSCCWrite->getOpcode() == AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM &&
1243 PendingSCCWrite->getOperand(0).getImm() == Inst->getOperand(0).getImm()) {
1244 unsigned SCC_WRITE_PendingEvent = 1 << SCC_WRITE;
1245 // If this SCC_WRITE is the only pending KM_CNT event, clear counter.
1246 if ((PendingEvents & Context->WaitEventMaskForInst[KM_CNT]) ==
1247 SCC_WRITE_PendingEvent) {
1248 setScoreLB(KM_CNT, getScoreUB(KM_CNT));
1249 }
1250
1251 PendingEvents &= ~SCC_WRITE_PendingEvent;
1252 PendingSCCWrite = nullptr;
1253 }
1254}
1255
1256void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait) {
1257 applyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1258 applyWaitcnt(EXP_CNT, Wait.ExpCnt);
1259 applyWaitcnt(DS_CNT, Wait.DsCnt);
1260 applyWaitcnt(STORE_CNT, Wait.StoreCnt);
1261 applyWaitcnt(SAMPLE_CNT, Wait.SampleCnt);
1262 applyWaitcnt(BVH_CNT, Wait.BvhCnt);
1263 applyWaitcnt(KM_CNT, Wait.KmCnt);
1264 applyXcnt(Wait);
1265}
1266
1267void WaitcntBrackets::applyWaitcnt(InstCounterType T, unsigned Count) {
1268 const unsigned UB = getScoreUB(T);
1269 if (Count >= UB)
1270 return;
1271 if (Count != 0) {
1272 if (counterOutOfOrder(T))
1273 return;
1274 setScoreLB(T, std::max(getScoreLB(T), UB - Count));
1275 } else {
1276 setScoreLB(T, UB);
1277 PendingEvents &= ~Context->WaitEventMaskForInst[T];
1278 }
1279}
1280
1281void WaitcntBrackets::applyXcnt(const AMDGPU::Waitcnt &Wait) {
1282 // Wait on XCNT is redundant if we are already waiting for a load to complete.
1283 // SMEM can return out of order, so only omit XCNT wait if we are waiting till
1284 // zero.
1285 if (Wait.KmCnt == 0 && hasPendingEvent(SMEM_GROUP))
1286 return applyWaitcnt(X_CNT, 0);
1287
1288 // If we have pending store we cannot optimize XCnt because we do not wait for
1289 // stores. VMEM loads retun in order, so if we only have loads XCnt is
1290 // decremented to the same number as LOADCnt.
1291 if (Wait.LoadCnt != ~0u && hasPendingEvent(VMEM_GROUP) &&
1292 !hasPendingEvent(STORE_CNT))
1293 return applyWaitcnt(X_CNT, std::min(Wait.XCnt, Wait.LoadCnt));
1294
1295 applyWaitcnt(X_CNT, Wait.XCnt);
1296}
1297
1298// Where there are multiple types of event in the bracket of a counter,
1299// the decrement may go out of order.
1300bool WaitcntBrackets::counterOutOfOrder(InstCounterType T) const {
1301 // Scalar memory read always can go out of order.
1302 if ((T == Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1303 (T == X_CNT && hasPendingEvent(SMEM_GROUP)))
1304 return true;
1305 return hasMixedPendingEvents(T);
1306}
1307
1308INITIALIZE_PASS_BEGIN(SIInsertWaitcntsLegacy, DEBUG_TYPE, "SI Insert Waitcnts",
1309 false, false)
1312INITIALIZE_PASS_END(SIInsertWaitcntsLegacy, DEBUG_TYPE, "SI Insert Waitcnts",
1314
1315char SIInsertWaitcntsLegacy::ID = 0;
1316
1317char &llvm::SIInsertWaitcntsID = SIInsertWaitcntsLegacy::ID;
1318
1320 return new SIInsertWaitcntsLegacy();
1321}
1322
1323static bool updateOperandIfDifferent(MachineInstr &MI, AMDGPU::OpName OpName,
1324 unsigned NewEnc) {
1325 int OpIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpName);
1326 assert(OpIdx >= 0);
1327
1328 MachineOperand &MO = MI.getOperand(OpIdx);
1329
1330 if (NewEnc == MO.getImm())
1331 return false;
1332
1333 MO.setImm(NewEnc);
1334 return true;
1335}
1336
1337/// Determine if \p MI is a gfx12+ single-counter S_WAIT_*CNT instruction,
1338/// and if so, which counter it is waiting on.
1339static std::optional<InstCounterType> counterTypeForInstr(unsigned Opcode) {
1340 switch (Opcode) {
1341 case AMDGPU::S_WAIT_LOADCNT:
1342 return LOAD_CNT;
1343 case AMDGPU::S_WAIT_EXPCNT:
1344 return EXP_CNT;
1345 case AMDGPU::S_WAIT_STORECNT:
1346 return STORE_CNT;
1347 case AMDGPU::S_WAIT_SAMPLECNT:
1348 return SAMPLE_CNT;
1349 case AMDGPU::S_WAIT_BVHCNT:
1350 return BVH_CNT;
1351 case AMDGPU::S_WAIT_DSCNT:
1352 return DS_CNT;
1353 case AMDGPU::S_WAIT_KMCNT:
1354 return KM_CNT;
1355 case AMDGPU::S_WAIT_XCNT:
1356 return X_CNT;
1357 default:
1358 return {};
1359 }
1360}
1361
1362bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt) const {
1363 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(Waitcnt->getOpcode());
1364 if (Opcode == Waitcnt->getOpcode())
1365 return false;
1366
1367 Waitcnt->setDesc(TII->get(Opcode));
1368 return true;
1369}
1370
1371/// Combine consecutive S_WAITCNT and S_WAITCNT_VSCNT instructions that
1372/// precede \p It and follow \p OldWaitcntInstr and apply any extra waits
1373/// from \p Wait that were added by previous passes. Currently this pass
1374/// conservatively assumes that these preexisting waits are required for
1375/// correctness.
1376bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1377 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1378 AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
1379 assert(ST);
1380 assert(isNormalMode(MaxCounter));
1381
1382 bool Modified = false;
1383 MachineInstr *WaitcntInstr = nullptr;
1384 MachineInstr *WaitcntVsCntInstr = nullptr;
1385
1386 LLVM_DEBUG({
1387 dbgs() << "PreGFX12::applyPreexistingWaitcnt at: ";
1388 if (It == OldWaitcntInstr.getParent()->instr_end())
1389 dbgs() << "end of block\n";
1390 else
1391 dbgs() << *It;
1392 });
1393
1394 for (auto &II :
1395 make_early_inc_range(make_range(OldWaitcntInstr.getIterator(), It))) {
1396 LLVM_DEBUG(dbgs() << "pre-existing iter: " << II);
1397 if (II.isMetaInstruction()) {
1398 LLVM_DEBUG(dbgs() << "skipped meta instruction\n");
1399 continue;
1400 }
1401
1402 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
1403 bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
1404
1405 // Update required wait count. If this is a soft waitcnt (= it was added
1406 // by an earlier pass), it may be entirely removed.
1407 if (Opcode == AMDGPU::S_WAITCNT) {
1408 unsigned IEnc = II.getOperand(0).getImm();
1409 AMDGPU::Waitcnt OldWait = AMDGPU::decodeWaitcnt(IV, IEnc);
1410 if (TrySimplify)
1411 ScoreBrackets.simplifyWaitcnt(OldWait);
1412 Wait = Wait.combined(OldWait);
1413
1414 // Merge consecutive waitcnt of the same type by erasing multiples.
1415 if (WaitcntInstr || (!Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1416 II.eraseFromParent();
1417 Modified = true;
1418 } else
1419 WaitcntInstr = &II;
1420 } else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1421 assert(ST->hasVMemToLDSLoad());
1422 LLVM_DEBUG(dbgs() << "Processing S_WAITCNT_lds_direct: " << II
1423 << "Before: " << Wait.LoadCnt << '\n';);
1424 ScoreBrackets.determineWait(LOAD_CNT, FIRST_LDS_VGPR, Wait);
1425 LLVM_DEBUG(dbgs() << "After: " << Wait.LoadCnt << '\n';);
1426
1427 // It is possible (but unlikely) that this is the only wait instruction,
1428 // in which case, we exit this loop without a WaitcntInstr to consume
1429 // `Wait`. But that works because `Wait` was passed in by reference, and
1430 // the callee eventually calls createNewWaitcnt on it. We test this
1431 // possibility in an articial MIR test since such a situation cannot be
1432 // recreated by running the memory legalizer.
1433 II.eraseFromParent();
1434 } else {
1435 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1436 assert(II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1437
1438 unsigned OldVSCnt =
1439 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1440 if (TrySimplify)
1441 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1442 Wait.StoreCnt = std::min(Wait.StoreCnt, OldVSCnt);
1443
1444 if (WaitcntVsCntInstr || (!Wait.hasWaitStoreCnt() && TrySimplify)) {
1445 II.eraseFromParent();
1446 Modified = true;
1447 } else
1448 WaitcntVsCntInstr = &II;
1449 }
1450 }
1451
1452 if (WaitcntInstr) {
1453 Modified |= updateOperandIfDifferent(*WaitcntInstr, AMDGPU::OpName::simm16,
1455 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1456
1457 ScoreBrackets.applyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1458 ScoreBrackets.applyWaitcnt(EXP_CNT, Wait.ExpCnt);
1459 ScoreBrackets.applyWaitcnt(DS_CNT, Wait.DsCnt);
1460 Wait.LoadCnt = ~0u;
1461 Wait.ExpCnt = ~0u;
1462 Wait.DsCnt = ~0u;
1463
1464 LLVM_DEBUG(It == WaitcntInstr->getParent()->end()
1465 ? dbgs()
1466 << "applied pre-existing waitcnt\n"
1467 << "New Instr at block end: " << *WaitcntInstr << '\n'
1468 : dbgs() << "applied pre-existing waitcnt\n"
1469 << "Old Instr: " << *It
1470 << "New Instr: " << *WaitcntInstr << '\n');
1471 }
1472
1473 if (WaitcntVsCntInstr) {
1474 Modified |= updateOperandIfDifferent(*WaitcntVsCntInstr,
1475 AMDGPU::OpName::simm16, Wait.StoreCnt);
1476 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1477
1478 ScoreBrackets.applyWaitcnt(STORE_CNT, Wait.StoreCnt);
1479 Wait.StoreCnt = ~0u;
1480
1481 LLVM_DEBUG(It == WaitcntVsCntInstr->getParent()->end()
1482 ? dbgs() << "applied pre-existing waitcnt\n"
1483 << "New Instr at block end: " << *WaitcntVsCntInstr
1484 << '\n'
1485 : dbgs() << "applied pre-existing waitcnt\n"
1486 << "Old Instr: " << *It
1487 << "New Instr: " << *WaitcntVsCntInstr << '\n');
1488 }
1489
1490 return Modified;
1491}
1492
1493/// Generate S_WAITCNT and/or S_WAITCNT_VSCNT instructions for any
1494/// required counters in \p Wait
1495bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1496 MachineBasicBlock &Block, MachineBasicBlock::instr_iterator It,
1497 AMDGPU::Waitcnt Wait) {
1498 assert(ST);
1499 assert(isNormalMode(MaxCounter));
1500
1501 bool Modified = false;
1502 const DebugLoc &DL = Block.findDebugLoc(It);
1503
1504 // Waits for VMcnt, LKGMcnt and/or EXPcnt are encoded together into a
1505 // single instruction while VScnt has its own instruction.
1506 if (Wait.hasWaitExceptStoreCnt()) {
1507 unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
1508 [[maybe_unused]] auto SWaitInst =
1509 BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAITCNT)).addImm(Enc);
1510 Modified = true;
1511
1512 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1513 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1514 dbgs() << "New Instr: " << *SWaitInst << '\n');
1515 }
1516
1517 if (Wait.hasWaitStoreCnt()) {
1518 assert(ST->hasVscnt());
1519
1520 [[maybe_unused]] auto SWaitInst =
1521 BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAITCNT_VSCNT))
1522 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1523 .addImm(Wait.StoreCnt);
1524 Modified = true;
1525
1526 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1527 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1528 dbgs() << "New Instr: " << *SWaitInst << '\n');
1529 }
1530
1531 return Modified;
1532}
1533
1534AMDGPU::Waitcnt
1535WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(bool IncludeVSCnt) const {
1536 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt && ST->hasVscnt() ? 0 : ~0u);
1537}
1538
1539AMDGPU::Waitcnt
1540WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(bool IncludeVSCnt) const {
1541 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
1542 ~0u /* XCNT */);
1543}
1544
1545/// Combine consecutive S_WAIT_*CNT instructions that precede \p It and
1546/// follow \p OldWaitcntInstr and apply any extra waits from \p Wait that
1547/// were added by previous passes. Currently this pass conservatively
1548/// assumes that these preexisting waits are required for correctness.
1549bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
1550 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1551 AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
1552 assert(ST);
1553 assert(!isNormalMode(MaxCounter));
1554
1555 bool Modified = false;
1556 MachineInstr *CombinedLoadDsCntInstr = nullptr;
1557 MachineInstr *CombinedStoreDsCntInstr = nullptr;
1558 MachineInstr *WaitInstrs[NUM_EXTENDED_INST_CNTS] = {};
1559
1560 LLVM_DEBUG({
1561 dbgs() << "GFX12Plus::applyPreexistingWaitcnt at: ";
1562 if (It == OldWaitcntInstr.getParent()->instr_end())
1563 dbgs() << "end of block\n";
1564 else
1565 dbgs() << *It;
1566 });
1567
1568 for (auto &II :
1569 make_early_inc_range(make_range(OldWaitcntInstr.getIterator(), It))) {
1570 LLVM_DEBUG(dbgs() << "pre-existing iter: " << II);
1571 if (II.isMetaInstruction()) {
1572 LLVM_DEBUG(dbgs() << "skipped meta instruction\n");
1573 continue;
1574 }
1575
1576 MachineInstr **UpdatableInstr;
1577
1578 // Update required wait count. If this is a soft waitcnt (= it was added
1579 // by an earlier pass), it may be entirely removed.
1580
1581 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
1582 bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
1583
1584 // Don't crash if the programmer used legacy waitcnt intrinsics, but don't
1585 // attempt to do more than that either.
1586 if (Opcode == AMDGPU::S_WAITCNT)
1587 continue;
1588
1589 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
1590 unsigned OldEnc =
1591 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1592 AMDGPU::Waitcnt OldWait = AMDGPU::decodeLoadcntDscnt(IV, OldEnc);
1593 if (TrySimplify)
1594 ScoreBrackets.simplifyWaitcnt(OldWait);
1595 Wait = Wait.combined(OldWait);
1596 UpdatableInstr = &CombinedLoadDsCntInstr;
1597 } else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
1598 unsigned OldEnc =
1599 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1600 AMDGPU::Waitcnt OldWait = AMDGPU::decodeStorecntDscnt(IV, OldEnc);
1601 if (TrySimplify)
1602 ScoreBrackets.simplifyWaitcnt(OldWait);
1603 Wait = Wait.combined(OldWait);
1604 UpdatableInstr = &CombinedStoreDsCntInstr;
1605 } else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1606 // Architectures higher than GFX10 do not have direct loads to
1607 // LDS, so no work required here yet.
1608 II.eraseFromParent();
1609 continue;
1610 } else {
1611 std::optional<InstCounterType> CT = counterTypeForInstr(Opcode);
1612 assert(CT.has_value());
1613 unsigned OldCnt =
1614 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1615 if (TrySimplify)
1616 ScoreBrackets.simplifyWaitcnt(CT.value(), OldCnt);
1617 addWait(Wait, CT.value(), OldCnt);
1618 UpdatableInstr = &WaitInstrs[CT.value()];
1619 }
1620
1621 // Merge consecutive waitcnt of the same type by erasing multiples.
1622 if (!*UpdatableInstr) {
1623 *UpdatableInstr = &II;
1624 } else {
1625 II.eraseFromParent();
1626 Modified = true;
1627 }
1628 }
1629
1630 if (CombinedLoadDsCntInstr) {
1631 // Only keep an S_WAIT_LOADCNT_DSCNT if both counters actually need
1632 // to be waited for. Otherwise, let the instruction be deleted so
1633 // the appropriate single counter wait instruction can be inserted
1634 // instead, when new S_WAIT_*CNT instructions are inserted by
1635 // createNewWaitcnt(). As a side effect, resetting the wait counts will
1636 // cause any redundant S_WAIT_LOADCNT or S_WAIT_DSCNT to be removed by
1637 // the loop below that deals with single counter instructions.
1638 if (Wait.LoadCnt != ~0u && Wait.DsCnt != ~0u) {
1639 unsigned NewEnc = AMDGPU::encodeLoadcntDscnt(IV, Wait);
1640 Modified |= updateOperandIfDifferent(*CombinedLoadDsCntInstr,
1641 AMDGPU::OpName::simm16, NewEnc);
1642 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
1643 ScoreBrackets.applyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1644 ScoreBrackets.applyWaitcnt(DS_CNT, Wait.DsCnt);
1645 Wait.LoadCnt = ~0u;
1646 Wait.DsCnt = ~0u;
1647
1648 LLVM_DEBUG(It == OldWaitcntInstr.getParent()->end()
1649 ? dbgs() << "applied pre-existing waitcnt\n"
1650 << "New Instr at block end: "
1651 << *CombinedLoadDsCntInstr << '\n'
1652 : dbgs() << "applied pre-existing waitcnt\n"
1653 << "Old Instr: " << *It << "New Instr: "
1654 << *CombinedLoadDsCntInstr << '\n');
1655 } else {
1656 CombinedLoadDsCntInstr->eraseFromParent();
1657 Modified = true;
1658 }
1659 }
1660
1661 if (CombinedStoreDsCntInstr) {
1662 // Similarly for S_WAIT_STORECNT_DSCNT.
1663 if (Wait.StoreCnt != ~0u && Wait.DsCnt != ~0u) {
1664 unsigned NewEnc = AMDGPU::encodeStorecntDscnt(IV, Wait);
1665 Modified |= updateOperandIfDifferent(*CombinedStoreDsCntInstr,
1666 AMDGPU::OpName::simm16, NewEnc);
1667 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
1668 ScoreBrackets.applyWaitcnt(STORE_CNT, Wait.StoreCnt);
1669 ScoreBrackets.applyWaitcnt(DS_CNT, Wait.DsCnt);
1670 Wait.StoreCnt = ~0u;
1671 Wait.DsCnt = ~0u;
1672
1673 LLVM_DEBUG(It == OldWaitcntInstr.getParent()->end()
1674 ? dbgs() << "applied pre-existing waitcnt\n"
1675 << "New Instr at block end: "
1676 << *CombinedStoreDsCntInstr << '\n'
1677 : dbgs() << "applied pre-existing waitcnt\n"
1678 << "Old Instr: " << *It << "New Instr: "
1679 << *CombinedStoreDsCntInstr << '\n');
1680 } else {
1681 CombinedStoreDsCntInstr->eraseFromParent();
1682 Modified = true;
1683 }
1684 }
1685
1686 // Look for an opportunity to convert existing S_WAIT_LOADCNT,
1687 // S_WAIT_STORECNT and S_WAIT_DSCNT into new S_WAIT_LOADCNT_DSCNT
1688 // or S_WAIT_STORECNT_DSCNT. This is achieved by selectively removing
1689 // instructions so that createNewWaitcnt() will create new combined
1690 // instructions to replace them.
1691
1692 if (Wait.DsCnt != ~0u) {
1693 // This is a vector of addresses in WaitInstrs pointing to instructions
1694 // that should be removed if they are present.
1696
1697 // If it's known that both DScnt and either LOADcnt or STOREcnt (but not
1698 // both) need to be waited for, ensure that there are no existing
1699 // individual wait count instructions for these.
1700
1701 if (Wait.LoadCnt != ~0u) {
1702 WaitsToErase.push_back(&WaitInstrs[LOAD_CNT]);
1703 WaitsToErase.push_back(&WaitInstrs[DS_CNT]);
1704 } else if (Wait.StoreCnt != ~0u) {
1705 WaitsToErase.push_back(&WaitInstrs[STORE_CNT]);
1706 WaitsToErase.push_back(&WaitInstrs[DS_CNT]);
1707 }
1708
1709 for (MachineInstr **WI : WaitsToErase) {
1710 if (!*WI)
1711 continue;
1712
1713 (*WI)->eraseFromParent();
1714 *WI = nullptr;
1715 Modified = true;
1716 }
1717 }
1718
1719 for (auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1720 if (!WaitInstrs[CT])
1721 continue;
1722
1723 unsigned NewCnt = getWait(Wait, CT);
1724 if (NewCnt != ~0u) {
1725 Modified |= updateOperandIfDifferent(*WaitInstrs[CT],
1726 AMDGPU::OpName::simm16, NewCnt);
1727 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
1728
1729 ScoreBrackets.applyWaitcnt(CT, NewCnt);
1730 setNoWait(Wait, CT);
1731
1732 LLVM_DEBUG(It == OldWaitcntInstr.getParent()->end()
1733 ? dbgs() << "applied pre-existing waitcnt\n"
1734 << "New Instr at block end: " << *WaitInstrs[CT]
1735 << '\n'
1736 : dbgs() << "applied pre-existing waitcnt\n"
1737 << "Old Instr: " << *It
1738 << "New Instr: " << *WaitInstrs[CT] << '\n');
1739 } else {
1740 WaitInstrs[CT]->eraseFromParent();
1741 Modified = true;
1742 }
1743 }
1744
1745 return Modified;
1746}
1747
1748/// Generate S_WAIT_*CNT instructions for any required counters in \p Wait
1749bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
1750 MachineBasicBlock &Block, MachineBasicBlock::instr_iterator It,
1751 AMDGPU::Waitcnt Wait) {
1752 assert(ST);
1753 assert(!isNormalMode(MaxCounter));
1754
1755 bool Modified = false;
1756 const DebugLoc &DL = Block.findDebugLoc(It);
1757
1758 // Check for opportunities to use combined wait instructions.
1759 if (Wait.DsCnt != ~0u) {
1760 MachineInstr *SWaitInst = nullptr;
1761
1762 if (Wait.LoadCnt != ~0u) {
1763 unsigned Enc = AMDGPU::encodeLoadcntDscnt(IV, Wait);
1764
1765 SWaitInst = BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAIT_LOADCNT_DSCNT))
1766 .addImm(Enc);
1767
1768 Wait.LoadCnt = ~0u;
1769 Wait.DsCnt = ~0u;
1770 } else if (Wait.StoreCnt != ~0u) {
1771 unsigned Enc = AMDGPU::encodeStorecntDscnt(IV, Wait);
1772
1773 SWaitInst =
1774 BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAIT_STORECNT_DSCNT))
1775 .addImm(Enc);
1776
1777 Wait.StoreCnt = ~0u;
1778 Wait.DsCnt = ~0u;
1779 }
1780
1781 if (SWaitInst) {
1782 Modified = true;
1783
1784 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1785 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1786 dbgs() << "New Instr: " << *SWaitInst << '\n');
1787 }
1788 }
1789
1790 // Generate an instruction for any remaining counter that needs
1791 // waiting for.
1792
1793 for (auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1794 unsigned Count = getWait(Wait, CT);
1795 if (Count == ~0u)
1796 continue;
1797
1798 [[maybe_unused]] auto SWaitInst =
1799 BuildMI(Block, It, DL, TII->get(instrsForExtendedCounterTypes[CT]))
1800 .addImm(Count);
1801
1802 Modified = true;
1803
1804 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1805 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1806 dbgs() << "New Instr: " << *SWaitInst << '\n');
1807 }
1808
1809 return Modified;
1810}
1811
1812/// \returns true if the callee inserts an s_waitcnt 0 on function entry.
1814 // Currently all conventions wait, but this may not always be the case.
1815 //
1816 // TODO: If IPRA is enabled, and the callee is isSafeForNoCSROpt, it may make
1817 // senses to omit the wait and do it in the caller.
1818 return true;
1819}
1820
1821/// \returns true if the callee is expected to wait for any outstanding waits
1822/// before returning.
1823static bool callWaitsOnFunctionReturn(const MachineInstr &MI) { return true; }
1824
1825/// Generate s_waitcnt instruction to be placed before cur_Inst.
1826/// Instructions of a given type are returned in order,
1827/// but instructions of different types can complete out of order.
1828/// We rely on this in-order completion
1829/// and simply assign a score to the memory access instructions.
1830/// We keep track of the active "score bracket" to determine
1831/// if an access of a memory read requires an s_waitcnt
1832/// and if so what the value of each counter is.
1833/// The "score bracket" is bound by the lower bound and upper bound
1834/// scores (*_score_LB and *_score_ub respectively).
1835/// If FlushVmCnt is true, that means that we want to generate a s_waitcnt to
1836/// flush the vmcnt counter here.
1837bool SIInsertWaitcnts::generateWaitcntInstBefore(MachineInstr &MI,
1838 WaitcntBrackets &ScoreBrackets,
1839 MachineInstr *OldWaitcntInstr,
1840 bool FlushVmCnt) {
1841 setForceEmitWaitcnt();
1842
1843 assert(!MI.isMetaInstruction());
1844
1845 AMDGPU::Waitcnt Wait;
1846 const unsigned Opc = MI.getOpcode();
1847
1848 // FIXME: This should have already been handled by the memory legalizer.
1849 // Removing this currently doesn't affect any lit tests, but we need to
1850 // verify that nothing was relying on this. The number of buffer invalidates
1851 // being handled here should not be expanded.
1852 if (Opc == AMDGPU::BUFFER_WBINVL1 || Opc == AMDGPU::BUFFER_WBINVL1_SC ||
1853 Opc == AMDGPU::BUFFER_WBINVL1_VOL || Opc == AMDGPU::BUFFER_GL0_INV ||
1854 Opc == AMDGPU::BUFFER_GL1_INV) {
1855 Wait.LoadCnt = 0;
1856 }
1857
1858 // All waits must be resolved at call return.
1859 // NOTE: this could be improved with knowledge of all call sites or
1860 // with knowledge of the called routines.
1861 if (Opc == AMDGPU::SI_RETURN_TO_EPILOG || Opc == AMDGPU::SI_RETURN ||
1862 Opc == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1863 Opc == AMDGPU::S_SETPC_B64_return ||
1864 (MI.isReturn() && MI.isCall() && !callWaitsOnFunctionEntry(MI))) {
1865 Wait = Wait.combined(WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false));
1866 }
1867 // In dynamic VGPR mode, we want to release the VGPRs before the wave exits.
1868 // Technically the hardware will do this on its own if we don't, but that
1869 // might cost extra cycles compared to doing it explicitly.
1870 // When not in dynamic VGPR mode, identify S_ENDPGM instructions which may
1871 // have to wait for outstanding VMEM stores. In this case it can be useful to
1872 // send a message to explicitly release all VGPRs before the stores have
1873 // completed, but it is only safe to do this if there are no outstanding
1874 // scratch stores.
1875 else if (Opc == AMDGPU::S_ENDPGM || Opc == AMDGPU::S_ENDPGM_SAVED) {
1876 if (!WCG->isOptNone() &&
1877 (MI.getMF()->getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() ||
1878 (ST->getGeneration() >= AMDGPUSubtarget::GFX11 &&
1879 ScoreBrackets.getScoreRange(STORE_CNT) != 0 &&
1880 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS))))
1881 ReleaseVGPRInsts.insert(&MI);
1882 }
1883 // Resolve vm waits before gs-done.
1884 else if ((Opc == AMDGPU::S_SENDMSG || Opc == AMDGPU::S_SENDMSGHALT) &&
1885 ST->hasLegacyGeometry() &&
1886 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_PreGFX11_) ==
1888 Wait.LoadCnt = 0;
1889 }
1890
1891 // Export & GDS instructions do not read the EXEC mask until after the export
1892 // is granted (which can occur well after the instruction is issued).
1893 // The shader program must flush all EXP operations on the export-count
1894 // before overwriting the EXEC mask.
1895 else {
1896 if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
1897 // Export and GDS are tracked individually, either may trigger a waitcnt
1898 // for EXEC.
1899 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1900 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1901 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1902 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1903 Wait.ExpCnt = 0;
1904 }
1905 }
1906
1907 // Wait for any pending GDS instruction to complete before any
1908 // "Always GDS" instruction.
1909 if (TII->isAlwaysGDS(Opc) && ScoreBrackets.hasPendingGDS())
1910 addWait(Wait, DS_CNT, ScoreBrackets.getPendingGDSWait());
1911
1912 if (MI.isCall() && callWaitsOnFunctionEntry(MI)) {
1913 // The function is going to insert a wait on everything in its prolog.
1914 // This still needs to be careful if the call target is a load (e.g. a GOT
1915 // load). We also need to check WAW dependency with saved PC.
1916 Wait = AMDGPU::Waitcnt();
1917
1918 const auto &CallAddrOp = *TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1919 if (CallAddrOp.isReg()) {
1920 RegInterval CallAddrOpInterval =
1921 ScoreBrackets.getRegInterval(&MI, CallAddrOp);
1922
1923 ScoreBrackets.determineWait(SmemAccessCounter, CallAddrOpInterval,
1924 Wait);
1925
1926 if (const auto *RtnAddrOp =
1927 TII->getNamedOperand(MI, AMDGPU::OpName::dst)) {
1928 RegInterval RtnAddrOpInterval =
1929 ScoreBrackets.getRegInterval(&MI, *RtnAddrOp);
1930
1931 ScoreBrackets.determineWait(SmemAccessCounter, RtnAddrOpInterval,
1932 Wait);
1933 }
1934 }
1935 } else if (Opc == AMDGPU::S_BARRIER_WAIT) {
1936 ScoreBrackets.tryClearSCCWriteEvent(&MI);
1937 } else {
1938 // FIXME: Should not be relying on memoperands.
1939 // Look at the source operands of every instruction to see if
1940 // any of them results from a previous memory operation that affects
1941 // its current usage. If so, an s_waitcnt instruction needs to be
1942 // emitted.
1943 // If the source operand was defined by a load, add the s_waitcnt
1944 // instruction.
1945 //
1946 // Two cases are handled for destination operands:
1947 // 1) If the destination operand was defined by a load, add the s_waitcnt
1948 // instruction to guarantee the right WAW order.
1949 // 2) If a destination operand that was used by a recent export/store ins,
1950 // add s_waitcnt on exp_cnt to guarantee the WAR order.
1951
1952 for (const MachineMemOperand *Memop : MI.memoperands()) {
1953 const Value *Ptr = Memop->getValue();
1954 if (Memop->isStore()) {
1955 if (auto It = SLoadAddresses.find(Ptr); It != SLoadAddresses.end()) {
1956 addWait(Wait, SmemAccessCounter, 0);
1957 if (PDT->dominates(MI.getParent(), It->second))
1958 SLoadAddresses.erase(It);
1959 }
1960 }
1961 unsigned AS = Memop->getAddrSpace();
1963 continue;
1964 // No need to wait before load from VMEM to LDS.
1965 if (TII->mayWriteLDSThroughDMA(MI))
1966 continue;
1967
1968 // LOAD_CNT is only relevant to vgpr or LDS.
1969 unsigned RegNo = FIRST_LDS_VGPR;
1970 if (Ptr && Memop->getAAInfo()) {
1971 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
1972 for (unsigned I = 0, E = LDSDMAStores.size(); I != E; ++I) {
1973 if (MI.mayAlias(AA, *LDSDMAStores[I], true))
1974 ScoreBrackets.determineWait(LOAD_CNT, RegNo + I + 1, Wait);
1975 }
1976 } else {
1977 ScoreBrackets.determineWait(LOAD_CNT, RegNo, Wait);
1978 }
1979 if (Memop->isStore()) {
1980 ScoreBrackets.determineWait(EXP_CNT, RegNo, Wait);
1981 }
1982 }
1983
1984 // Loop over use and def operands.
1985 for (const MachineOperand &Op : MI.operands()) {
1986 if (!Op.isReg())
1987 continue;
1988
1989 // If the instruction does not read tied source, skip the operand.
1990 if (Op.isTied() && Op.isUse() && TII->doesNotReadTiedSource(MI))
1991 continue;
1992
1993 RegInterval Interval = ScoreBrackets.getRegInterval(&MI, Op);
1994
1995 const bool IsVGPR = TRI->isVectorRegister(*MRI, Op.getReg());
1996 if (IsVGPR) {
1997 // Implicit VGPR defs and uses are never a part of the memory
1998 // instructions description and usually present to account for
1999 // super-register liveness.
2000 // TODO: Most of the other instructions also have implicit uses
2001 // for the liveness accounting only.
2002 if (Op.isImplicit() && MI.mayLoadOrStore())
2003 continue;
2004
2005 // RAW always needs an s_waitcnt. WAW needs an s_waitcnt unless the
2006 // previous write and this write are the same type of VMEM
2007 // instruction, in which case they are (in some architectures)
2008 // guaranteed to write their results in order anyway.
2009 // Additionally check instructions where Point Sample Acceleration
2010 // might be applied.
2011 if (Op.isUse() || !updateVMCntOnly(MI) ||
2012 ScoreBrackets.hasOtherPendingVmemTypes(Interval,
2013 getVmemType(MI)) ||
2014 ScoreBrackets.hasPointSamplePendingVmemTypes(MI, Interval) ||
2015 !ST->hasVmemWriteVgprInOrder()) {
2016 ScoreBrackets.determineWait(LOAD_CNT, Interval, Wait);
2017 ScoreBrackets.determineWait(SAMPLE_CNT, Interval, Wait);
2018 ScoreBrackets.determineWait(BVH_CNT, Interval, Wait);
2019 ScoreBrackets.clearVgprVmemTypes(Interval);
2020 }
2021
2022 if (Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2023 ScoreBrackets.determineWait(EXP_CNT, Interval, Wait);
2024 }
2025 ScoreBrackets.determineWait(DS_CNT, Interval, Wait);
2026 } else if (Op.getReg() == AMDGPU::SCC) {
2027 ScoreBrackets.determineWait(KM_CNT, Interval, Wait);
2028 } else {
2029 ScoreBrackets.determineWait(SmemAccessCounter, Interval, Wait);
2030 }
2031
2032 if (ST->hasWaitXCnt() && Op.isDef())
2033 ScoreBrackets.determineWait(X_CNT, Interval, Wait);
2034 }
2035 }
2036 }
2037
2038 // Ensure safety against exceptions from outstanding memory operations while
2039 // waiting for a barrier:
2040 //
2041 // * Some subtargets safely handle backing off the barrier in hardware
2042 // when an exception occurs.
2043 // * Some subtargets have an implicit S_WAITCNT 0 before barriers, so that
2044 // there can be no outstanding memory operations during the wait.
2045 // * Subtargets with split barriers don't need to back off the barrier; it
2046 // is up to the trap handler to preserve the user barrier state correctly.
2047 //
2048 // In all other cases, ensure safety by ensuring that there are no outstanding
2049 // memory operations.
2050 if (Opc == AMDGPU::S_BARRIER && !ST->hasAutoWaitcntBeforeBarrier() &&
2051 !ST->supportsBackOffBarrier()) {
2052 Wait = Wait.combined(WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/true));
2053 }
2054
2055 // TODO: Remove this work-around, enable the assert for Bug 457939
2056 // after fixing the scheduler. Also, the Shader Compiler code is
2057 // independent of target.
2058 if (SIInstrInfo::isCBranchVCCZRead(MI) && ST->hasReadVCCZBug() &&
2059 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2060 Wait.DsCnt = 0;
2061 }
2062
2063 // Verify that the wait is actually needed.
2064 ScoreBrackets.simplifyWaitcnt(Wait);
2065
2066 // When forcing emit, we need to skip terminators because that would break the
2067 // terminators of the MBB if we emit a waitcnt between terminators.
2068 if (ForceEmitZeroFlag && !MI.isTerminator())
2069 Wait = WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false);
2070
2071 if (ForceEmitWaitcnt[LOAD_CNT])
2072 Wait.LoadCnt = 0;
2073 if (ForceEmitWaitcnt[EXP_CNT])
2074 Wait.ExpCnt = 0;
2075 if (ForceEmitWaitcnt[DS_CNT])
2076 Wait.DsCnt = 0;
2077 if (ForceEmitWaitcnt[SAMPLE_CNT])
2078 Wait.SampleCnt = 0;
2079 if (ForceEmitWaitcnt[BVH_CNT])
2080 Wait.BvhCnt = 0;
2081 if (ForceEmitWaitcnt[KM_CNT])
2082 Wait.KmCnt = 0;
2083 if (ForceEmitWaitcnt[X_CNT])
2084 Wait.XCnt = 0;
2085
2086 if (FlushVmCnt) {
2087 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2088 Wait.LoadCnt = 0;
2089 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2090 Wait.SampleCnt = 0;
2091 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2092 Wait.BvhCnt = 0;
2093 }
2094
2095 if (ForceEmitZeroLoadFlag && Wait.LoadCnt != ~0u)
2096 Wait.LoadCnt = 0;
2097
2098 return generateWaitcnt(Wait, MI.getIterator(), *MI.getParent(), ScoreBrackets,
2099 OldWaitcntInstr);
2100}
2101
2102bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt Wait,
2104 MachineBasicBlock &Block,
2105 WaitcntBrackets &ScoreBrackets,
2106 MachineInstr *OldWaitcntInstr) {
2107 bool Modified = false;
2108
2109 if (OldWaitcntInstr)
2110 // Try to merge the required wait with preexisting waitcnt instructions.
2111 // Also erase redundant waitcnt.
2112 Modified =
2113 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr, Wait, It);
2114
2115 // Any counts that could have been applied to any existing waitcnt
2116 // instructions will have been done so, now deal with any remaining.
2117 ScoreBrackets.applyWaitcnt(Wait);
2118
2119 // ExpCnt can be merged into VINTERP.
2120 if (Wait.ExpCnt != ~0u && It != Block.instr_end() &&
2122 MachineOperand *WaitExp =
2123 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
2124 if (Wait.ExpCnt < WaitExp->getImm()) {
2125 WaitExp->setImm(Wait.ExpCnt);
2126 Modified = true;
2127 }
2128 Wait.ExpCnt = ~0u;
2129
2130 LLVM_DEBUG(dbgs() << "generateWaitcnt\n"
2131 << "Update Instr: " << *It);
2132 }
2133
2134 // XCnt may be already consumed by a load wait.
2135 if (Wait.XCnt != ~0u) {
2136 if (Wait.KmCnt == 0 && !ScoreBrackets.hasPendingEvent(SMEM_GROUP))
2137 Wait.XCnt = ~0u;
2138
2139 if (Wait.LoadCnt == 0 && !ScoreBrackets.hasPendingEvent(VMEM_GROUP))
2140 Wait.XCnt = ~0u;
2141
2142 // Since the translation for VMEM addresses occur in-order, we can skip the
2143 // XCnt if the current instruction is of VMEM type and has a memory
2144 // dependency with another VMEM instruction in flight.
2145 if (isVmemAccess(*It))
2146 Wait.XCnt = ~0u;
2147 }
2148
2149 if (WCG->createNewWaitcnt(Block, It, Wait))
2150 Modified = true;
2151
2152 return Modified;
2153}
2154
2155bool SIInsertWaitcnts::isVmemAccess(const MachineInstr &MI) const {
2156 return (TII->isFLAT(MI) && TII->mayAccessVMEMThroughFlat(MI)) ||
2157 (TII->isVMEM(MI) && !AMDGPU::getMUBUFIsBufferInv(MI.getOpcode()));
2158}
2159
2160// Return true if the next instruction is S_ENDPGM, following fallthrough
2161// blocks if necessary.
2162bool SIInsertWaitcnts::isNextENDPGM(MachineBasicBlock::instr_iterator It,
2163 MachineBasicBlock *Block) const {
2164 auto BlockEnd = Block->getParent()->end();
2165 auto BlockIter = Block->getIterator();
2166
2167 while (true) {
2168 if (It.isEnd()) {
2169 if (++BlockIter != BlockEnd) {
2170 It = BlockIter->instr_begin();
2171 continue;
2172 }
2173
2174 return false;
2175 }
2176
2177 if (!It->isMetaInstruction())
2178 break;
2179
2180 It++;
2181 }
2182
2183 assert(!It.isEnd());
2184
2185 return It->getOpcode() == AMDGPU::S_ENDPGM;
2186}
2187
2188// Add a wait after an instruction if architecture requirements mandate one.
2189bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2190 MachineBasicBlock &Block,
2191 WaitcntBrackets &ScoreBrackets) {
2192 AMDGPU::Waitcnt Wait;
2193 bool NeedsEndPGMCheck = false;
2194
2195 if (ST->isPreciseMemoryEnabled() && Inst.mayLoadOrStore())
2196 Wait = WCG->getAllZeroWaitcnt(Inst.mayStore() &&
2198
2199 if (TII->isAlwaysGDS(Inst.getOpcode())) {
2200 Wait.DsCnt = 0;
2201 NeedsEndPGMCheck = true;
2202 }
2203
2204 ScoreBrackets.simplifyWaitcnt(Wait);
2205
2206 auto SuccessorIt = std::next(Inst.getIterator());
2207 bool Result = generateWaitcnt(Wait, SuccessorIt, Block, ScoreBrackets,
2208 /*OldWaitcntInstr=*/nullptr);
2209
2210 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &Block)) {
2211 BuildMI(Block, SuccessorIt, Inst.getDebugLoc(), TII->get(AMDGPU::S_NOP))
2212 .addImm(0);
2213 }
2214
2215 return Result;
2216}
2217
2218void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2219 WaitcntBrackets *ScoreBrackets) {
2220 // Now look at the instruction opcode. If it is a memory access
2221 // instruction, update the upper-bound of the appropriate counter's
2222 // bracket and the destination operand scores.
2223 // TODO: Use the (TSFlags & SIInstrFlags::DS_CNT) property everywhere.
2224
2225 bool IsVMEMAccess = false;
2226 bool IsSMEMAccess = false;
2227 if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
2228 if (TII->isAlwaysGDS(Inst.getOpcode()) ||
2229 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2230 ScoreBrackets->updateByEvent(GDS_ACCESS, Inst);
2231 ScoreBrackets->updateByEvent(GDS_GPR_LOCK, Inst);
2232 ScoreBrackets->setPendingGDS();
2233 } else {
2234 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2235 }
2236 } else if (TII->isFLAT(Inst)) {
2238 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2239 return;
2240 }
2241
2242 assert(Inst.mayLoadOrStore());
2243
2244 int FlatASCount = 0;
2245
2246 if (TII->mayAccessVMEMThroughFlat(Inst)) {
2247 ++FlatASCount;
2248 IsVMEMAccess = true;
2249 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2250 }
2251
2252 if (TII->mayAccessLDSThroughFlat(Inst)) {
2253 ++FlatASCount;
2254 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2255 }
2256
2257 // This is a flat memory operation that access both VMEM and LDS, so note it
2258 // - it will require that both the VM and LGKM be flushed to zero if it is
2259 // pending when a VM or LGKM dependency occurs.
2260 if (FlatASCount > 1)
2261 ScoreBrackets->setPendingFlat();
2262 } else if (SIInstrInfo::isVMEM(Inst) &&
2264 IsVMEMAccess = true;
2265 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2266
2267 if (ST->vmemWriteNeedsExpWaitcnt() &&
2268 (Inst.mayStore() || SIInstrInfo::isAtomicRet(Inst))) {
2269 ScoreBrackets->updateByEvent(VMW_GPR_LOCK, Inst);
2270 }
2271 } else if (TII->isSMRD(Inst)) {
2272 IsSMEMAccess = true;
2273 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2274 } else if (Inst.isCall()) {
2275 if (callWaitsOnFunctionReturn(Inst)) {
2276 // Act as a wait on everything
2277 ScoreBrackets->applyWaitcnt(
2278 WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false));
2279 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2280 } else {
2281 // May need to way wait for anything.
2282 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
2283 }
2284 } else if (SIInstrInfo::isLDSDIR(Inst)) {
2285 ScoreBrackets->updateByEvent(EXP_LDS_ACCESS, Inst);
2286 } else if (TII->isVINTERP(Inst)) {
2287 int64_t Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2288 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2289 } else if (SIInstrInfo::isEXP(Inst)) {
2290 unsigned Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2292 ScoreBrackets->updateByEvent(EXP_PARAM_ACCESS, Inst);
2293 else if (Imm >= AMDGPU::Exp::ET_POS0 && Imm <= AMDGPU::Exp::ET_POS_LAST)
2294 ScoreBrackets->updateByEvent(EXP_POS_ACCESS, Inst);
2295 else
2296 ScoreBrackets->updateByEvent(EXP_GPR_LOCK, Inst);
2297 } else if (SIInstrInfo::isSBarrierSCCWrite(Inst.getOpcode())) {
2298 ScoreBrackets->updateByEvent(SCC_WRITE, Inst);
2299 } else {
2300 switch (Inst.getOpcode()) {
2301 case AMDGPU::S_SENDMSG:
2302 case AMDGPU::S_SENDMSG_RTN_B32:
2303 case AMDGPU::S_SENDMSG_RTN_B64:
2304 case AMDGPU::S_SENDMSGHALT:
2305 ScoreBrackets->updateByEvent(SQ_MESSAGE, Inst);
2306 break;
2307 case AMDGPU::S_MEMTIME:
2308 case AMDGPU::S_MEMREALTIME:
2309 case AMDGPU::S_GET_BARRIER_STATE_M0:
2310 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2311 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2312 break;
2313 }
2314 }
2315
2316 if (!ST->hasWaitXCnt())
2317 return;
2318
2319 if (IsVMEMAccess)
2320 ScoreBrackets->updateByEvent(VMEM_GROUP, Inst);
2321
2322 if (IsSMEMAccess)
2323 ScoreBrackets->updateByEvent(SMEM_GROUP, Inst);
2324}
2325
2326bool WaitcntBrackets::mergeScore(const MergeInfo &M, unsigned &Score,
2327 unsigned OtherScore) {
2328 unsigned MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
2329 unsigned OtherShifted =
2330 OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
2331 Score = std::max(MyShifted, OtherShifted);
2332 return OtherShifted > MyShifted;
2333}
2334
2335/// Merge the pending events and associater score brackets of \p Other into
2336/// this brackets status.
2337///
2338/// Returns whether the merge resulted in a change that requires tighter waits
2339/// (i.e. the merged brackets strictly dominate the original brackets).
2340bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
2341 bool StrictDom = false;
2342
2343 VgprUB = std::max(VgprUB, Other.VgprUB);
2344 SgprUB = std::max(SgprUB, Other.SgprUB);
2345
2346 for (auto T : inst_counter_types(Context->MaxCounter)) {
2347 // Merge event flags for this counter
2348 const unsigned *WaitEventMaskForInst = Context->WaitEventMaskForInst;
2349 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[T];
2350 const unsigned OtherEvents = Other.PendingEvents & WaitEventMaskForInst[T];
2351 if (OtherEvents & ~OldEvents)
2352 StrictDom = true;
2353 PendingEvents |= OtherEvents;
2354
2355 // Merge scores for this counter
2356 const unsigned MyPending = ScoreUBs[T] - ScoreLBs[T];
2357 const unsigned OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
2358 const unsigned NewUB = ScoreLBs[T] + std::max(MyPending, OtherPending);
2359 if (NewUB < ScoreLBs[T])
2360 report_fatal_error("waitcnt score overflow");
2361
2362 MergeInfo M;
2363 M.OldLB = ScoreLBs[T];
2364 M.OtherLB = Other.ScoreLBs[T];
2365 M.MyShift = NewUB - ScoreUBs[T];
2366 M.OtherShift = NewUB - Other.ScoreUBs[T];
2367
2368 ScoreUBs[T] = NewUB;
2369
2370 StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]);
2371
2372 if (T == DS_CNT)
2373 StrictDom |= mergeScore(M, LastGDS, Other.LastGDS);
2374
2375 if (T == KM_CNT) {
2376 StrictDom |= mergeScore(M, SCCScore, Other.SCCScore);
2377 if (Other.hasPendingEvent(SCC_WRITE)) {
2378 unsigned OldEventsHasSCCWrite = OldEvents & (1 << SCC_WRITE);
2379 if (!OldEventsHasSCCWrite) {
2380 PendingSCCWrite = Other.PendingSCCWrite;
2381 } else if (PendingSCCWrite != Other.PendingSCCWrite) {
2382 PendingSCCWrite = nullptr;
2383 }
2384 }
2385 }
2386
2387 for (int J = 0; J <= VgprUB; J++)
2388 StrictDom |= mergeScore(M, VgprScores[T][J], Other.VgprScores[T][J]);
2389
2390 if (isSmemCounter(T)) {
2391 unsigned Idx = getSgprScoresIdx(T);
2392 for (int J = 0; J <= SgprUB; J++)
2393 StrictDom |=
2394 mergeScore(M, SgprScores[Idx][J], Other.SgprScores[Idx][J]);
2395 }
2396 }
2397
2398 for (int J = 0; J <= VgprUB; J++) {
2399 unsigned char NewVmemTypes = VgprVmemTypes[J] | Other.VgprVmemTypes[J];
2400 StrictDom |= NewVmemTypes != VgprVmemTypes[J];
2401 VgprVmemTypes[J] = NewVmemTypes;
2402 }
2403
2404 return StrictDom;
2405}
2406
2407static bool isWaitInstr(MachineInstr &Inst) {
2408 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(Inst.getOpcode());
2409 return Opcode == AMDGPU::S_WAITCNT ||
2410 (Opcode == AMDGPU::S_WAITCNT_VSCNT && Inst.getOperand(0).isReg() &&
2411 Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL) ||
2412 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2413 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2414 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
2415 counterTypeForInstr(Opcode).has_value();
2416}
2417
2418// Generate s_waitcnt instructions where needed.
2419bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
2420 MachineBasicBlock &Block,
2421 WaitcntBrackets &ScoreBrackets) {
2422 bool Modified = false;
2423
2424 LLVM_DEBUG({
2425 dbgs() << "*** Begin Block: ";
2426 Block.printName(dbgs());
2427 ScoreBrackets.dump();
2428 });
2429
2430 // Track the correctness of vccz through this basic block. There are two
2431 // reasons why it might be incorrect; see ST->hasReadVCCZBug() and
2432 // ST->partialVCCWritesUpdateVCCZ().
2433 bool VCCZCorrect = true;
2434 if (ST->hasReadVCCZBug()) {
2435 // vccz could be incorrect at a basic block boundary if a predecessor wrote
2436 // to vcc and then issued an smem load.
2437 VCCZCorrect = false;
2438 } else if (!ST->partialVCCWritesUpdateVCCZ()) {
2439 // vccz could be incorrect at a basic block boundary if a predecessor wrote
2440 // to vcc_lo or vcc_hi.
2441 VCCZCorrect = false;
2442 }
2443
2444 // Walk over the instructions.
2445 MachineInstr *OldWaitcntInstr = nullptr;
2446
2447 for (MachineBasicBlock::instr_iterator Iter = Block.instr_begin(),
2448 E = Block.instr_end();
2449 Iter != E;) {
2450 MachineInstr &Inst = *Iter;
2451 if (Inst.isMetaInstruction()) {
2452 ++Iter;
2453 continue;
2454 }
2455
2456 // Track pre-existing waitcnts that were added in earlier iterations or by
2457 // the memory legalizer.
2458 if (isWaitInstr(Inst)) {
2459 if (!OldWaitcntInstr)
2460 OldWaitcntInstr = &Inst;
2461 ++Iter;
2462 continue;
2463 }
2464
2465 bool FlushVmCnt = Block.getFirstTerminator() == Inst &&
2466 isPreheaderToFlush(Block, ScoreBrackets);
2467
2468 // Generate an s_waitcnt instruction to be placed before Inst, if needed.
2469 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2470 FlushVmCnt);
2471 OldWaitcntInstr = nullptr;
2472
2473 // Restore vccz if it's not known to be correct already.
2474 bool RestoreVCCZ = !VCCZCorrect && SIInstrInfo::isCBranchVCCZRead(Inst);
2475
2476 // Don't examine operands unless we need to track vccz correctness.
2477 if (ST->hasReadVCCZBug() || !ST->partialVCCWritesUpdateVCCZ()) {
2478 if (Inst.definesRegister(AMDGPU::VCC_LO, /*TRI=*/nullptr) ||
2479 Inst.definesRegister(AMDGPU::VCC_HI, /*TRI=*/nullptr)) {
2480 // Up to gfx9, writes to vcc_lo and vcc_hi don't update vccz.
2481 if (!ST->partialVCCWritesUpdateVCCZ())
2482 VCCZCorrect = false;
2483 } else if (Inst.definesRegister(AMDGPU::VCC, /*TRI=*/nullptr)) {
2484 // There is a hardware bug on CI/SI where SMRD instruction may corrupt
2485 // vccz bit, so when we detect that an instruction may read from a
2486 // corrupt vccz bit, we need to:
2487 // 1. Insert s_waitcnt lgkm(0) to wait for all outstanding SMRD
2488 // operations to complete.
2489 // 2. Restore the correct value of vccz by writing the current value
2490 // of vcc back to vcc.
2491 if (ST->hasReadVCCZBug() &&
2492 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2493 // Writes to vcc while there's an outstanding smem read may get
2494 // clobbered as soon as any read completes.
2495 VCCZCorrect = false;
2496 } else {
2497 // Writes to vcc will fix any incorrect value in vccz.
2498 VCCZCorrect = true;
2499 }
2500 }
2501 }
2502
2503 if (TII->isSMRD(Inst)) {
2504 for (const MachineMemOperand *Memop : Inst.memoperands()) {
2505 // No need to handle invariant loads when avoiding WAR conflicts, as
2506 // there cannot be a vector store to the same memory location.
2507 if (!Memop->isInvariant()) {
2508 const Value *Ptr = Memop->getValue();
2509 SLoadAddresses.insert(std::pair(Ptr, Inst.getParent()));
2510 }
2511 }
2512 if (ST->hasReadVCCZBug()) {
2513 // This smem read could complete and clobber vccz at any time.
2514 VCCZCorrect = false;
2515 }
2516 }
2517
2518 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2519
2520 Modified |= insertForcedWaitAfter(Inst, Block, ScoreBrackets);
2521
2522 LLVM_DEBUG({
2523 Inst.print(dbgs());
2524 ScoreBrackets.dump();
2525 });
2526
2527 // TODO: Remove this work-around after fixing the scheduler and enable the
2528 // assert above.
2529 if (RestoreVCCZ) {
2530 // Restore the vccz bit. Any time a value is written to vcc, the vcc
2531 // bit is updated, so we can restore the bit by reading the value of
2532 // vcc and then writing it back to the register.
2533 BuildMI(Block, Inst, Inst.getDebugLoc(),
2534 TII->get(ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2535 TRI->getVCC())
2536 .addReg(TRI->getVCC());
2537 VCCZCorrect = true;
2538 Modified = true;
2539 }
2540
2541 ++Iter;
2542 }
2543
2544 // Flush the LOADcnt, SAMPLEcnt and BVHcnt counters at the end of the block if
2545 // needed.
2546 AMDGPU::Waitcnt Wait;
2547 if (Block.getFirstTerminator() == Block.end() &&
2548 isPreheaderToFlush(Block, ScoreBrackets)) {
2549 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2550 Wait.LoadCnt = 0;
2551 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2552 Wait.SampleCnt = 0;
2553 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2554 Wait.BvhCnt = 0;
2555 }
2556
2557 // Combine or remove any redundant waitcnts at the end of the block.
2558 Modified |= generateWaitcnt(Wait, Block.instr_end(), Block, ScoreBrackets,
2559 OldWaitcntInstr);
2560
2561 LLVM_DEBUG({
2562 dbgs() << "*** End Block: ";
2563 Block.printName(dbgs());
2564 ScoreBrackets.dump();
2565 });
2566
2567 return Modified;
2568}
2569
2570// Return true if the given machine basic block is a preheader of a loop in
2571// which we want to flush the vmcnt counter, and false otherwise.
2572bool SIInsertWaitcnts::isPreheaderToFlush(
2573 MachineBasicBlock &MBB, const WaitcntBrackets &ScoreBrackets) {
2574 auto [Iterator, IsInserted] = PreheadersToFlush.try_emplace(&MBB, false);
2575 if (!IsInserted)
2576 return Iterator->second;
2577
2578 MachineBasicBlock *Succ = MBB.getSingleSuccessor();
2579 if (!Succ)
2580 return false;
2581
2582 MachineLoop *Loop = MLI->getLoopFor(Succ);
2583 if (!Loop)
2584 return false;
2585
2586 if (Loop->getLoopPreheader() == &MBB &&
2587 shouldFlushVmCnt(Loop, ScoreBrackets)) {
2588 Iterator->second = true;
2589 return true;
2590 }
2591
2592 return false;
2593}
2594
2595bool SIInsertWaitcnts::isVMEMOrFlatVMEM(const MachineInstr &MI) const {
2597 return TII->mayAccessVMEMThroughFlat(MI);
2598 return SIInstrInfo::isVMEM(MI);
2599}
2600
2601// Return true if it is better to flush the vmcnt counter in the preheader of
2602// the given loop. We currently decide to flush in two situations:
2603// 1. The loop contains vmem store(s), no vmem load and at least one use of a
2604// vgpr containing a value that is loaded outside of the loop. (Only on
2605// targets with no vscnt counter).
2606// 2. The loop contains vmem load(s), but the loaded values are not used in the
2607// loop, and at least one use of a vgpr containing a value that is loaded
2608// outside of the loop.
2609bool SIInsertWaitcnts::shouldFlushVmCnt(MachineLoop *ML,
2610 const WaitcntBrackets &Brackets) {
2611 bool HasVMemLoad = false;
2612 bool HasVMemStore = false;
2613 bool UsesVgprLoadedOutside = false;
2614 DenseSet<Register> VgprUse;
2615 DenseSet<Register> VgprDef;
2616
2617 for (MachineBasicBlock *MBB : ML->blocks()) {
2618 for (MachineInstr &MI : *MBB) {
2619 if (isVMEMOrFlatVMEM(MI)) {
2620 HasVMemLoad |= MI.mayLoad();
2621 HasVMemStore |= MI.mayStore();
2622 }
2623
2624 for (const MachineOperand &Op : MI.all_uses()) {
2625 if (Op.isDebug() || !TRI->isVectorRegister(*MRI, Op.getReg()))
2626 continue;
2627 RegInterval Interval = Brackets.getRegInterval(&MI, Op);
2628 // Vgpr use
2629 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
2630 // If we find a register that is loaded inside the loop, 1. and 2.
2631 // are invalidated and we can exit.
2632 if (VgprDef.contains(RegNo))
2633 return false;
2634 VgprUse.insert(RegNo);
2635 // If at least one of Op's registers is in the score brackets, the
2636 // value is likely loaded outside of the loop.
2637 if (Brackets.getRegScore(RegNo, LOAD_CNT) >
2638 Brackets.getScoreLB(LOAD_CNT) ||
2639 Brackets.getRegScore(RegNo, SAMPLE_CNT) >
2640 Brackets.getScoreLB(SAMPLE_CNT) ||
2641 Brackets.getRegScore(RegNo, BVH_CNT) >
2642 Brackets.getScoreLB(BVH_CNT)) {
2643 UsesVgprLoadedOutside = true;
2644 break;
2645 }
2646 }
2647 }
2648
2649 // VMem load vgpr def
2650 if (isVMEMOrFlatVMEM(MI) && MI.mayLoad()) {
2651 for (const MachineOperand &Op : MI.all_defs()) {
2652 RegInterval Interval = Brackets.getRegInterval(&MI, Op);
2653 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
2654 // If we find a register that is loaded inside the loop, 1. and 2.
2655 // are invalidated and we can exit.
2656 if (VgprUse.contains(RegNo))
2657 return false;
2658 VgprDef.insert(RegNo);
2659 }
2660 }
2661 }
2662 }
2663 }
2664 if (!ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2665 return true;
2666 return HasVMemLoad && UsesVgprLoadedOutside && ST->hasVmemWriteVgprInOrder();
2667}
2668
2669bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
2670 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2671 auto *PDT =
2672 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2673 AliasAnalysis *AA = nullptr;
2674 if (auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2675 AA = &AAR->getAAResults();
2676
2677 return SIInsertWaitcnts(MLI, PDT, AA).run(MF);
2678}
2679
2680PreservedAnalyses
2683 auto *MLI = &MFAM.getResult<MachineLoopAnalysis>(MF);
2684 auto *PDT = &MFAM.getResult<MachinePostDominatorTreeAnalysis>(MF);
2686 .getManager()
2687 .getCachedResult<AAManager>(MF.getFunction());
2688
2689 if (!SIInsertWaitcnts(MLI, PDT, AA).run(MF))
2690 return PreservedAnalyses::all();
2691
2694 .preserve<AAManager>();
2695}
2696
2697bool SIInsertWaitcnts::run(MachineFunction &MF) {
2698 ST = &MF.getSubtarget<GCNSubtarget>();
2699 TII = ST->getInstrInfo();
2700 TRI = &TII->getRegisterInfo();
2701 MRI = &MF.getRegInfo();
2703
2705
2706 if (ST->hasExtendedWaitCounts()) {
2707 MaxCounter = NUM_EXTENDED_INST_CNTS;
2708 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2709 WCG = &WCGGFX12Plus;
2710 } else {
2711 MaxCounter = NUM_NORMAL_INST_CNTS;
2712 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF);
2713 WCG = &WCGPreGFX12;
2714 }
2715
2716 for (auto T : inst_counter_types())
2717 ForceEmitWaitcnt[T] = false;
2718
2719 WaitEventMaskForInst = WCG->getWaitEventMask();
2720
2721 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2722
2723 if (ST->hasExtendedWaitCounts()) {
2724 Limits.LoadcntMax = AMDGPU::getLoadcntBitMask(IV);
2725 Limits.DscntMax = AMDGPU::getDscntBitMask(IV);
2726 } else {
2727 Limits.LoadcntMax = AMDGPU::getVmcntBitMask(IV);
2728 Limits.DscntMax = AMDGPU::getLgkmcntBitMask(IV);
2729 }
2730 Limits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
2731 Limits.StorecntMax = AMDGPU::getStorecntBitMask(IV);
2732 Limits.SamplecntMax = AMDGPU::getSamplecntBitMask(IV);
2733 Limits.BvhcntMax = AMDGPU::getBvhcntBitMask(IV);
2734 Limits.KmcntMax = AMDGPU::getKmcntBitMask(IV);
2735 Limits.XcntMax = AMDGPU::getXcntBitMask(IV);
2736
2737 [[maybe_unused]] unsigned NumVGPRsMax =
2738 ST->getAddressableNumVGPRs(MFI->getDynamicVGPRBlockSize());
2739 [[maybe_unused]] unsigned NumSGPRsMax = ST->getAddressableNumSGPRs();
2740 assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
2741 assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
2742
2743 BlockInfos.clear();
2744 bool Modified = false;
2745
2746 MachineBasicBlock &EntryBB = MF.front();
2748
2749 if (!MFI->isEntryFunction()) {
2750 // Wait for any outstanding memory operations that the input registers may
2751 // depend on. We can't track them and it's better to do the wait after the
2752 // costly call sequence.
2753
2754 // TODO: Could insert earlier and schedule more liberally with operations
2755 // that only use caller preserved registers.
2756 for (MachineBasicBlock::iterator E = EntryBB.end();
2757 I != E && (I->isPHI() || I->isMetaInstruction()); ++I)
2758 ;
2759
2760 if (ST->hasExtendedWaitCounts()) {
2761 BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAIT_LOADCNT_DSCNT))
2762 .addImm(0);
2763 for (auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2764 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT)
2765 continue;
2766
2767 if (!ST->hasImageInsts() &&
2768 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
2769 continue;
2770
2771 BuildMI(EntryBB, I, DebugLoc(),
2772 TII->get(instrsForExtendedCounterTypes[CT]))
2773 .addImm(0);
2774 }
2775 } else {
2776 BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT)).addImm(0);
2777 }
2778
2779 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(this);
2780 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2781 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2782
2783 Modified = true;
2784 }
2785
2786 // Keep iterating over the blocks in reverse post order, inserting and
2787 // updating s_waitcnt where needed, until a fix point is reached.
2788 for (auto *MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
2789 BlockInfos.try_emplace(MBB);
2790
2791 std::unique_ptr<WaitcntBrackets> Brackets;
2792 bool Repeat;
2793 do {
2794 Repeat = false;
2795
2796 for (auto BII = BlockInfos.begin(), BIE = BlockInfos.end(); BII != BIE;
2797 ++BII) {
2798 MachineBasicBlock *MBB = BII->first;
2799 BlockInfo &BI = BII->second;
2800 if (!BI.Dirty)
2801 continue;
2802
2803 if (BI.Incoming) {
2804 if (!Brackets)
2805 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2806 else
2807 *Brackets = *BI.Incoming;
2808 } else {
2809 if (!Brackets) {
2810 Brackets = std::make_unique<WaitcntBrackets>(this);
2811 } else {
2812 // Reinitialize in-place. N.B. do not do this by assigning from a
2813 // temporary because the WaitcntBrackets class is large and it could
2814 // cause this function to use an unreasonable amount of stack space.
2815 Brackets->~WaitcntBrackets();
2816 new (Brackets.get()) WaitcntBrackets(this);
2817 }
2818 }
2819
2820 Modified |= insertWaitcntInBlock(MF, *MBB, *Brackets);
2821 BI.Dirty = false;
2822
2823 if (Brackets->hasPendingEvent()) {
2824 BlockInfo *MoveBracketsToSucc = nullptr;
2825 for (MachineBasicBlock *Succ : MBB->successors()) {
2826 auto *SuccBII = BlockInfos.find(Succ);
2827 BlockInfo &SuccBI = SuccBII->second;
2828 if (!SuccBI.Incoming) {
2829 SuccBI.Dirty = true;
2830 if (SuccBII <= BII) {
2831 LLVM_DEBUG(dbgs() << "repeat on backedge\n");
2832 Repeat = true;
2833 }
2834 if (!MoveBracketsToSucc) {
2835 MoveBracketsToSucc = &SuccBI;
2836 } else {
2837 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2838 }
2839 } else if (SuccBI.Incoming->merge(*Brackets)) {
2840 SuccBI.Dirty = true;
2841 if (SuccBII <= BII) {
2842 LLVM_DEBUG(dbgs() << "repeat on backedge\n");
2843 Repeat = true;
2844 }
2845 }
2846 }
2847 if (MoveBracketsToSucc)
2848 MoveBracketsToSucc->Incoming = std::move(Brackets);
2849 }
2850 }
2851 } while (Repeat);
2852
2853 if (ST->hasScalarStores()) {
2854 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
2855 bool HaveScalarStores = false;
2856
2857 for (MachineBasicBlock &MBB : MF) {
2858 for (MachineInstr &MI : MBB) {
2859 if (!HaveScalarStores && TII->isScalarStore(MI))
2860 HaveScalarStores = true;
2861
2862 if (MI.getOpcode() == AMDGPU::S_ENDPGM ||
2863 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2864 EndPgmBlocks.push_back(&MBB);
2865 }
2866 }
2867
2868 if (HaveScalarStores) {
2869 // If scalar writes are used, the cache must be flushed or else the next
2870 // wave to reuse the same scratch memory can be clobbered.
2871 //
2872 // Insert s_dcache_wb at wave termination points if there were any scalar
2873 // stores, and only if the cache hasn't already been flushed. This could
2874 // be improved by looking across blocks for flushes in postdominating
2875 // blocks from the stores but an explicitly requested flush is probably
2876 // very rare.
2877 for (MachineBasicBlock *MBB : EndPgmBlocks) {
2878 bool SeenDCacheWB = false;
2879
2880 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
2881 I != E; ++I) {
2882 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
2883 SeenDCacheWB = true;
2884 else if (TII->isScalarStore(*I))
2885 SeenDCacheWB = false;
2886
2887 // FIXME: It would be better to insert this before a waitcnt if any.
2888 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
2889 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
2890 !SeenDCacheWB) {
2891 Modified = true;
2892 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
2893 }
2894 }
2895 }
2896 }
2897 }
2898
2899 // Deallocate the VGPRs before previously identified S_ENDPGM instructions.
2900 // This is done in different ways depending on how the VGPRs were allocated
2901 // (i.e. whether we're in dynamic VGPR mode or not).
2902 // Skip deallocation if kernel is waveslot limited vs VGPR limited. A short
2903 // waveslot limited kernel runs slower with the deallocation.
2904 if (MFI->isDynamicVGPREnabled()) {
2905 for (MachineInstr *MI : ReleaseVGPRInsts) {
2906 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2907 TII->get(AMDGPU::S_ALLOC_VGPR))
2908 .addImm(0);
2909 Modified = true;
2910 }
2911 } else {
2912 if (!ReleaseVGPRInsts.empty() &&
2913 (MF.getFrameInfo().hasCalls() ||
2914 ST->getOccupancyWithNumVGPRs(
2915 TRI->getNumUsedPhysRegs(*MRI, AMDGPU::VGPR_32RegClass),
2916 /*IsDynamicVGPR=*/false) <
2918 for (MachineInstr *MI : ReleaseVGPRInsts) {
2919 if (ST->requiresNopBeforeDeallocVGPRs()) {
2920 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2921 TII->get(AMDGPU::S_NOP))
2922 .addImm(0);
2923 }
2924 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2925 TII->get(AMDGPU::S_SENDMSG))
2927 Modified = true;
2928 }
2929 }
2930 }
2931 ReleaseVGPRInsts.clear();
2932 PreheadersToFlush.clear();
2933 SLoadAddresses.clear();
2934
2935 return Modified;
2936}
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.