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