LLVM 23.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;
45using namespace llvm::AMDGPU;
46
47#define DEBUG_TYPE "si-insert-waitcnts"
48
49DEBUG_COUNTER(ForceExpCounter, DEBUG_TYPE "-forceexp",
50 "Force emit s_waitcnt expcnt(0) instrs");
51DEBUG_COUNTER(ForceLgkmCounter, DEBUG_TYPE "-forcelgkm",
52 "Force emit s_waitcnt lgkmcnt(0) instrs");
53DEBUG_COUNTER(ForceVMCounter, DEBUG_TYPE "-forcevm",
54 "Force emit s_waitcnt vmcnt(0) instrs");
55
56static cl::opt<bool>
57 ForceEmitZeroFlag("amdgpu-waitcnt-forcezero",
58 cl::desc("Force all waitcnt instrs to be emitted as "
59 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
60 cl::init(false), cl::Hidden);
61
63 "amdgpu-waitcnt-load-forcezero",
64 cl::desc("Force all waitcnt load counters to wait until 0"),
65 cl::init(false), cl::Hidden);
66
68 "amdgpu-expert-scheduling-mode",
69 cl::desc("Enable expert scheduling mode 2 for all functions (GFX12+ only)"),
70 cl::init(false), cl::Hidden);
71
72namespace {
73// Get the maximum wait count value for a given counter type.
74static unsigned getWaitCountMax(const AMDGPU::HardwareLimits &Limits,
76 switch (T) {
77 case LOAD_CNT:
78 return Limits.LoadcntMax;
79 case DS_CNT:
80 return Limits.DscntMax;
81 case EXP_CNT:
82 return Limits.ExpcntMax;
83 case STORE_CNT:
84 return Limits.StorecntMax;
85 case SAMPLE_CNT:
86 return Limits.SamplecntMax;
87 case BVH_CNT:
88 return Limits.BvhcntMax;
89 case KM_CNT:
90 return Limits.KmcntMax;
91 case X_CNT:
92 return Limits.XcntMax;
93 case VA_VDST:
94 return Limits.VaVdstMax;
95 case VM_VSRC:
96 return Limits.VmVsrcMax;
97 default:
98 return 0;
99 }
100}
101
102/// Integer IDs used to track vector memory locations we may have to wait on.
103/// Encoded as u16 chunks:
104///
105/// [0, REGUNITS_END ): MCRegUnit
106/// [LDSDMA_BEGIN, LDSDMA_END ) : LDS DMA IDs
107///
108/// NOTE: The choice of encoding these as "u16 chunks" is arbitrary.
109/// It gives (2 << 16) - 1 entries per category which is more than enough
110/// for all register units. MCPhysReg is u16 so we don't even support >u16
111/// physical register numbers at this time, let alone >u16 register units.
112/// In any case, an assertion in "WaitcntBrackets" ensures REGUNITS_END
113/// is enough for all register units.
114using VMEMID = uint32_t;
115
116enum : VMEMID {
117 TRACKINGID_RANGE_LEN = (1 << 16),
118
119 // Important: MCRegUnits must always be tracked starting from 0, as we
120 // need to be able to convert between a MCRegUnit and a VMEMID freely.
121 REGUNITS_BEGIN = 0,
122 REGUNITS_END = REGUNITS_BEGIN + TRACKINGID_RANGE_LEN,
123
124 // Note for LDSDMA: LDSDMA_BEGIN corresponds to the "common"
125 // entry, which is updated for all LDS DMA operations encountered.
126 // Specific LDS DMA IDs start at LDSDMA_BEGIN + 1.
127 NUM_LDSDMA = TRACKINGID_RANGE_LEN,
128 LDSDMA_BEGIN = REGUNITS_END,
129 LDSDMA_END = LDSDMA_BEGIN + NUM_LDSDMA,
130};
131
132/// Convert a MCRegUnit to a VMEMID.
133static constexpr VMEMID toVMEMID(MCRegUnit RU) {
134 return static_cast<unsigned>(RU);
135}
136
137#define AMDGPU_DECLARE_WAIT_EVENTS(DECL) \
138 DECL(VMEM_ACCESS) /* vmem read & write (pre-gfx10), vmem read (gfx10+) */ \
139 DECL(VMEM_SAMPLER_READ_ACCESS) /* vmem SAMPLER read (gfx12+ only) */ \
140 DECL(VMEM_BVH_READ_ACCESS) /* vmem BVH read (gfx12+ only) */ \
141 DECL(GLOBAL_INV_ACCESS) /* GLOBAL_INV (gfx12+ only) */ \
142 DECL(VMEM_WRITE_ACCESS) /* vmem write that is not scratch */ \
143 DECL(SCRATCH_WRITE_ACCESS) /* vmem write that may be scratch */ \
144 DECL(VMEM_GROUP) /* vmem group */ \
145 DECL(LDS_ACCESS) /* lds read & write */ \
146 DECL(GDS_ACCESS) /* gds read & write */ \
147 DECL(SQ_MESSAGE) /* send message */ \
148 DECL(SCC_WRITE) /* write to SCC from barrier */ \
149 DECL(SMEM_ACCESS) /* scalar-memory read & write */ \
150 DECL(SMEM_GROUP) /* scalar-memory group */ \
151 DECL(EXP_GPR_LOCK) /* export holding on its data src */ \
152 DECL(GDS_GPR_LOCK) /* GDS holding on its data and addr src */ \
153 DECL(EXP_POS_ACCESS) /* write to export position */ \
154 DECL(EXP_PARAM_ACCESS) /* write to export parameter */ \
155 DECL(VMW_GPR_LOCK) /* vmem write holding on its data src */ \
156 DECL(EXP_LDS_ACCESS) /* read by ldsdir counting as export */ \
157 DECL(VGPR_CSMACC_WRITE) /* write VGPR dest in Core/Side-MACC VALU */ \
158 DECL(VGPR_DPMACC_WRITE) /* write VGPR dest in DPMACC VALU */ \
159 DECL(VGPR_TRANS_WRITE) /* write VGPR dest in TRANS VALU */ \
160 DECL(VGPR_XDL_WRITE) /* write VGPR dest in XDL VALU */ \
161 DECL(VGPR_LDS_READ) /* read VGPR source in LDS */ \
162 DECL(VGPR_FLAT_READ) /* read VGPR source in FLAT */ \
163 DECL(VGPR_VMEM_READ) /* read VGPR source in other VMEM */ \
164 DECL(ASYNC_ACCESS) /* access that uses ASYNC_CNT */
165
166// clang-format off
167#define AMDGPU_EVENT_ENUM(Name) Name,
168enum WaitEventType {
170 NUM_WAIT_EVENTS
171};
172#undef AMDGPU_EVENT_ENUM
173} // namespace
174
175namespace llvm {
176template <> struct enum_iteration_traits<WaitEventType> {
177 static constexpr bool is_iterable = true;
178};
179} // namespace llvm
180
181namespace {
182
183/// Return an iterator over all events between VMEM_ACCESS (the first event)
184/// and \c MaxEvent (exclusive, default value yields an enumeration over
185/// all counters).
186auto wait_events(WaitEventType MaxEvent = NUM_WAIT_EVENTS) {
187 return enum_seq(VMEM_ACCESS, MaxEvent);
188}
189
190#define AMDGPU_EVENT_NAME(Name) #Name,
191static constexpr StringLiteral WaitEventTypeName[] = {
193};
194#undef AMDGPU_EVENT_NAME
195static constexpr StringLiteral getWaitEventTypeName(WaitEventType Event) {
196 return WaitEventTypeName[Event];
197}
198// clang-format on
199
200// Enumerate different types of result-returning VMEM operations. Although
201// s_waitcnt orders them all with a single vmcnt counter, in the absence of
202// s_waitcnt only instructions of the same VmemType are guaranteed to write
203// their results in order -- so there is no need to insert an s_waitcnt between
204// two instructions of the same type that write the same vgpr.
205enum VmemType {
206 // BUF instructions and MIMG instructions without a sampler.
207 VMEM_NOSAMPLER,
208 // MIMG instructions with a sampler.
209 VMEM_SAMPLER,
210 // BVH instructions
211 VMEM_BVH,
212 NUM_VMEM_TYPES
213};
214
215// Maps values of InstCounterType to the instruction that waits on that
216// counter. Only used if GCNSubtarget::hasExtendedWaitCounts()
217// returns true, and does not cover VA_VDST or VM_VSRC.
218static const unsigned instrsForExtendedCounterTypes[NUM_EXTENDED_INST_CNTS] = {
219 AMDGPU::S_WAIT_LOADCNT, AMDGPU::S_WAIT_DSCNT, AMDGPU::S_WAIT_EXPCNT,
220 AMDGPU::S_WAIT_STORECNT, AMDGPU::S_WAIT_SAMPLECNT, AMDGPU::S_WAIT_BVHCNT,
221 AMDGPU::S_WAIT_KMCNT, AMDGPU::S_WAIT_XCNT, AMDGPU::S_WAIT_ASYNCCNT};
222
223static bool updateVMCntOnly(const MachineInstr &Inst) {
224 return (SIInstrInfo::isVMEM(Inst) && !SIInstrInfo::isFLAT(Inst)) ||
226}
227
228#ifndef NDEBUG
229static bool isNormalMode(InstCounterType MaxCounter) {
230 return MaxCounter == NUM_NORMAL_INST_CNTS;
231}
232#endif // NDEBUG
233
234VmemType getVmemType(const MachineInstr &Inst) {
235 assert(updateVMCntOnly(Inst));
236 if (!SIInstrInfo::isImage(Inst))
237 return VMEM_NOSAMPLER;
238 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Inst.getOpcode());
239 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
240 AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
241
242 if (BaseInfo->BVH)
243 return VMEM_BVH;
244
245 // We have to make an additional check for isVSAMPLE here since some
246 // instructions don't have a sampler, but are still classified as sampler
247 // instructions for the purposes of e.g. waitcnt.
248 if (BaseInfo->Sampler || BaseInfo->MSAA || SIInstrInfo::isVSAMPLE(Inst))
249 return VMEM_SAMPLER;
250
251 return VMEM_NOSAMPLER;
252}
253
254void addWait(AMDGPU::Waitcnt &Wait, InstCounterType T, unsigned Count) {
255 Wait.set(T, std::min(Wait.get(T), Count));
256}
257
258void setNoWait(AMDGPU::Waitcnt &Wait, InstCounterType T) { Wait.set(T, ~0u); }
259
260/// A small set of events.
261class WaitEventSet {
262 unsigned Mask = 0;
263
264public:
265 WaitEventSet() = default;
266 explicit constexpr WaitEventSet(WaitEventType Event) {
267 static_assert(NUM_WAIT_EVENTS <= sizeof(Mask) * 8,
268 "Not enough bits in Mask for all the events");
269 Mask |= 1 << Event;
270 }
271 constexpr WaitEventSet(std::initializer_list<WaitEventType> Events) {
272 for (auto &E : Events) {
273 Mask |= 1 << E;
274 }
275 }
276 void insert(const WaitEventType &Event) { Mask |= 1 << Event; }
277 void remove(const WaitEventType &Event) { Mask &= ~(1 << Event); }
278 void remove(const WaitEventSet &Other) { Mask &= ~Other.Mask; }
279 bool contains(const WaitEventType &Event) const {
280 return Mask & (1 << Event);
281 }
282 /// \Returns true if this set contains all elements of \p Other.
283 bool contains(const WaitEventSet &Other) const {
284 return (~Mask & Other.Mask) == 0;
285 }
286 /// \Returns the intersection of this and \p Other.
287 WaitEventSet operator&(const WaitEventSet &Other) const {
288 auto Copy = *this;
289 Copy.Mask &= Other.Mask;
290 return Copy;
291 }
292 /// \Returns the union of this and \p Other.
293 WaitEventSet operator|(const WaitEventSet &Other) const {
294 auto Copy = *this;
295 Copy.Mask |= Other.Mask;
296 return Copy;
297 }
298 /// This set becomes the union of this and \p Other.
299 WaitEventSet &operator|=(const WaitEventSet &Other) {
300 Mask |= Other.Mask;
301 return *this;
302 }
303 /// This set becomes the intersection of this and \p Other.
304 WaitEventSet &operator&=(const WaitEventSet &Other) {
305 Mask &= Other.Mask;
306 return *this;
307 }
308 bool operator==(const WaitEventSet &Other) const {
309 return Mask == Other.Mask;
310 }
311 bool operator!=(const WaitEventSet &Other) const { return !(*this == Other); }
312 bool empty() const { return Mask == 0; }
313 /// \Returns true if the set contains more than one element.
314 bool twoOrMore() const { return Mask & (Mask - 1); }
315 operator bool() const { return !empty(); }
316 void print(raw_ostream &OS) const {
317 ListSeparator LS(", ");
318 for (WaitEventType Event : wait_events()) {
319 if (contains(Event))
320 OS << LS << getWaitEventTypeName(Event);
321 }
322 }
323 LLVM_DUMP_METHOD void dump() const;
324};
325
326void WaitEventSet::dump() const {
327 print(dbgs());
328 dbgs() << "\n";
329}
330
331class WaitcntBrackets;
332
333// This abstracts the logic for generating and updating S_WAIT* instructions
334// away from the analysis that determines where they are needed. This was
335// done because the set of counters and instructions for waiting on them
336// underwent a major shift with gfx12, sufficiently so that having this
337// abstraction allows the main analysis logic to be simpler than it would
338// otherwise have had to become.
339class WaitcntGenerator {
340protected:
341 const GCNSubtarget &ST;
342 const SIInstrInfo &TII;
343 AMDGPU::IsaVersion IV;
344 InstCounterType MaxCounter;
345 bool OptNone;
346 bool ExpandWaitcntProfiling = false;
347 const AMDGPU::HardwareLimits &Limits;
348
349public:
350 WaitcntGenerator() = delete;
351 WaitcntGenerator(const WaitcntGenerator &) = delete;
352 WaitcntGenerator(const MachineFunction &MF, InstCounterType MaxCounter,
353 const AMDGPU::HardwareLimits &Limits)
354 : ST(MF.getSubtarget<GCNSubtarget>()), TII(*ST.getInstrInfo()),
355 IV(AMDGPU::getIsaVersion(ST.getCPU())), MaxCounter(MaxCounter),
356 OptNone(MF.getFunction().hasOptNone() ||
357 MF.getTarget().getOptLevel() == CodeGenOptLevel::None),
358 ExpandWaitcntProfiling(
359 MF.getFunction().hasFnAttribute("amdgpu-expand-waitcnt-profiling")),
360 Limits(Limits) {}
361
362 // Return true if the current function should be compiled with no
363 // optimization.
364 bool isOptNone() const { return OptNone; }
365
366 const AMDGPU::HardwareLimits &getLimits() const { return Limits; }
367
368 // Edits an existing sequence of wait count instructions according
369 // to an incoming Waitcnt value, which is itself updated to reflect
370 // any new wait count instructions which may need to be generated by
371 // WaitcntGenerator::createNewWaitcnt(). It will return true if any edits
372 // were made.
373 //
374 // This editing will usually be merely updated operands, but it may also
375 // delete instructions if the incoming Wait value indicates they are not
376 // needed. It may also remove existing instructions for which a wait
377 // is needed if it can be determined that it is better to generate new
378 // instructions later, as can happen on gfx12.
379 virtual bool
380 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
381 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
383
384 // Transform a soft waitcnt into a normal one.
385 bool promoteSoftWaitCnt(MachineInstr *Waitcnt) const;
386
387 // Generates new wait count instructions according to the value of
388 // Wait, returning true if any new instructions were created.
389 // ScoreBrackets is used for profiling expansion.
390 virtual bool createNewWaitcnt(MachineBasicBlock &Block,
392 AMDGPU::Waitcnt Wait,
393 const WaitcntBrackets &ScoreBrackets) = 0;
394
395 // Returns the WaitEventSet that corresponds to counter \p T.
396 virtual const WaitEventSet &getWaitEvents(InstCounterType T) const = 0;
397
398 /// \returns the counter that corresponds to event \p E.
399 InstCounterType getCounterFromEvent(WaitEventType E) const {
400 for (auto T : inst_counter_types()) {
401 if (getWaitEvents(T).contains(E))
402 return T;
403 }
404 llvm_unreachable("event type has no associated counter");
405 }
406
407 // Returns a new waitcnt with all counters except VScnt set to 0. If
408 // IncludeVSCnt is true, VScnt is set to 0, otherwise it is set to ~0u.
409 // AsyncCnt always defaults to ~0u (don't wait for it). It is only updated
410 // when a call to @llvm.amdgcn.wait.asyncmark() is processed.
411 virtual AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const = 0;
412
413 virtual ~WaitcntGenerator() = default;
414};
415
416class WaitcntGeneratorPreGFX12 final : public WaitcntGenerator {
417 static constexpr const WaitEventSet
418 WaitEventMaskForInstPreGFX12[NUM_INST_CNTS] = {
419 WaitEventSet(
420 {VMEM_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS}),
421 WaitEventSet({SMEM_ACCESS, LDS_ACCESS, GDS_ACCESS, SQ_MESSAGE}),
422 WaitEventSet({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK,
423 EXP_PARAM_ACCESS, EXP_POS_ACCESS, EXP_LDS_ACCESS}),
424 WaitEventSet({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
425 WaitEventSet(),
426 WaitEventSet(),
427 WaitEventSet(),
428 WaitEventSet(),
429 WaitEventSet(),
430 WaitEventSet()};
431
432public:
433 using WaitcntGenerator::WaitcntGenerator;
434 bool
435 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
436 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
437 MachineBasicBlock::instr_iterator It) const override;
438
439 bool createNewWaitcnt(MachineBasicBlock &Block,
441 AMDGPU::Waitcnt Wait,
442 const WaitcntBrackets &ScoreBrackets) override;
443
444 const WaitEventSet &getWaitEvents(InstCounterType T) const override {
445 return WaitEventMaskForInstPreGFX12[T];
446 }
447
448 AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const override;
449};
450
451class WaitcntGeneratorGFX12Plus final : public WaitcntGenerator {
452protected:
453 bool IsExpertMode;
454 static constexpr const WaitEventSet
455 WaitEventMaskForInstGFX12Plus[NUM_INST_CNTS] = {
456 WaitEventSet({VMEM_ACCESS, GLOBAL_INV_ACCESS}),
457 WaitEventSet({LDS_ACCESS, GDS_ACCESS}),
458 WaitEventSet({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK,
459 EXP_PARAM_ACCESS, EXP_POS_ACCESS, EXP_LDS_ACCESS}),
460 WaitEventSet({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
461 WaitEventSet({VMEM_SAMPLER_READ_ACCESS}),
462 WaitEventSet({VMEM_BVH_READ_ACCESS}),
463 WaitEventSet({SMEM_ACCESS, SQ_MESSAGE, SCC_WRITE}),
464 WaitEventSet({VMEM_GROUP, SMEM_GROUP}),
465 WaitEventSet({ASYNC_ACCESS}),
466 WaitEventSet({VGPR_CSMACC_WRITE, VGPR_DPMACC_WRITE, VGPR_TRANS_WRITE,
467 VGPR_XDL_WRITE}),
468 WaitEventSet({VGPR_LDS_READ, VGPR_FLAT_READ, VGPR_VMEM_READ})};
469
470public:
471 WaitcntGeneratorGFX12Plus() = delete;
472 WaitcntGeneratorGFX12Plus(const MachineFunction &MF,
473 InstCounterType MaxCounter,
474 const AMDGPU::HardwareLimits &Limits,
475 bool IsExpertMode)
476 : WaitcntGenerator(MF, MaxCounter, Limits), IsExpertMode(IsExpertMode) {}
477
478 bool
479 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
480 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
481 MachineBasicBlock::instr_iterator It) const override;
482
483 bool createNewWaitcnt(MachineBasicBlock &Block,
485 AMDGPU::Waitcnt Wait,
486 const WaitcntBrackets &ScoreBrackets) override;
487
488 const WaitEventSet &getWaitEvents(InstCounterType T) const override {
489 return WaitEventMaskForInstGFX12Plus[T];
490 }
491
492 AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const override;
493};
494
495// Flags indicating which counters should be flushed in a loop preheader.
496struct PreheaderFlushFlags {
497 bool FlushVmCnt = false;
498 bool FlushDsCnt = false;
499};
500
501class SIInsertWaitcnts {
502 DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
503 DenseMap<MachineBasicBlock *, PreheaderFlushFlags> PreheadersToFlush;
504 MachineLoopInfo &MLI;
505 MachinePostDominatorTree &PDT;
506 AliasAnalysis *AA = nullptr;
507 MachineFunction &MF;
508
509 struct BlockInfo {
510 std::unique_ptr<WaitcntBrackets> Incoming;
511 bool Dirty = true;
512 };
513
514 MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
515
516 bool ForceEmitWaitcnt[NUM_INST_CNTS] = {};
517
518 std::unique_ptr<WaitcntGenerator> WCG;
519
520 // Remember call and return instructions in the function.
521 DenseSet<MachineInstr *> CallInsts;
522 DenseSet<MachineInstr *> ReturnInsts;
523
524 // Remember all S_ENDPGM instructions. The boolean flag is true if there might
525 // be outstanding stores but definitely no outstanding scratch stores, to help
526 // with insertion of DEALLOC_VGPRS messages.
527 DenseMap<MachineInstr *, bool> EndPgmInsts;
528
529 AMDGPU::HardwareLimits Limits;
530
531public:
532 const GCNSubtarget &ST;
533 const SIInstrInfo &TII;
534 const SIRegisterInfo &TRI;
535 const MachineRegisterInfo &MRI;
536 InstCounterType SmemAccessCounter;
537 InstCounterType MaxCounter;
538 bool IsExpertMode = false;
539
540 SIInsertWaitcnts(MachineLoopInfo &MLI, MachinePostDominatorTree &PDT,
541 AliasAnalysis *AA, MachineFunction &MF)
542 : MLI(MLI), PDT(PDT), AA(AA), MF(MF), ST(MF.getSubtarget<GCNSubtarget>()),
543 TII(*ST.getInstrInfo()), TRI(TII.getRegisterInfo()),
544 MRI(MF.getRegInfo()) {
545 (void)ForceExpCounter;
546 (void)ForceLgkmCounter;
547 (void)ForceVMCounter;
548 }
549
550 const AMDGPU::HardwareLimits &getLimits() const { return Limits; }
551
552 PreheaderFlushFlags getPreheaderFlushFlags(MachineLoop *ML,
553 const WaitcntBrackets &Brackets);
554 PreheaderFlushFlags isPreheaderToFlush(MachineBasicBlock &MBB,
555 const WaitcntBrackets &ScoreBrackets);
556 bool isVMEMOrFlatVMEM(const MachineInstr &MI) const;
557 bool isDSRead(const MachineInstr &MI) const;
558 bool mayStoreIncrementingDSCNT(const MachineInstr &MI) const;
559 bool run();
560
561 void setForceEmitWaitcnt() {
562// For non-debug builds, ForceEmitWaitcnt has been initialized to false;
563// For debug builds, get the debug counter info and adjust if need be
564#ifndef NDEBUG
565 if (DebugCounter::isCounterSet(ForceExpCounter) &&
566 DebugCounter::shouldExecute(ForceExpCounter)) {
567 ForceEmitWaitcnt[EXP_CNT] = true;
568 } else {
569 ForceEmitWaitcnt[EXP_CNT] = false;
570 }
571
572 if (DebugCounter::isCounterSet(ForceLgkmCounter) &&
573 DebugCounter::shouldExecute(ForceLgkmCounter)) {
574 ForceEmitWaitcnt[DS_CNT] = true;
575 ForceEmitWaitcnt[KM_CNT] = true;
576 } else {
577 ForceEmitWaitcnt[DS_CNT] = false;
578 ForceEmitWaitcnt[KM_CNT] = false;
579 }
580
581 if (DebugCounter::isCounterSet(ForceVMCounter) &&
582 DebugCounter::shouldExecute(ForceVMCounter)) {
583 ForceEmitWaitcnt[LOAD_CNT] = true;
584 ForceEmitWaitcnt[SAMPLE_CNT] = true;
585 ForceEmitWaitcnt[BVH_CNT] = true;
586 } else {
587 ForceEmitWaitcnt[LOAD_CNT] = false;
588 ForceEmitWaitcnt[SAMPLE_CNT] = false;
589 ForceEmitWaitcnt[BVH_CNT] = false;
590 }
591
592 ForceEmitWaitcnt[VA_VDST] = false;
593 ForceEmitWaitcnt[VM_VSRC] = false;
594#endif // NDEBUG
595 }
596
597 // Return the appropriate VMEM_*_ACCESS type for Inst, which must be a VMEM
598 // instruction.
599 WaitEventType getVmemWaitEventType(const MachineInstr &Inst) const {
600 switch (Inst.getOpcode()) {
601 // FIXME: GLOBAL_INV needs to be tracked with xcnt too.
602 case AMDGPU::GLOBAL_INV:
603 return GLOBAL_INV_ACCESS; // tracked using loadcnt, but doesn't write
604 // VGPRs
605 case AMDGPU::GLOBAL_WB:
606 case AMDGPU::GLOBAL_WBINV:
607 return VMEM_WRITE_ACCESS; // tracked using storecnt
608 default:
609 break;
610 }
611
612 // Maps VMEM access types to their corresponding WaitEventType.
613 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
614 VMEM_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
615
617 // LDS DMA loads are also stores, but on the LDS side. On the VMEM side
618 // these should use VM_CNT.
619 if (!ST.hasVscnt() || SIInstrInfo::mayWriteLDSThroughDMA(Inst))
620 return VMEM_ACCESS;
621 if (Inst.mayStore() &&
622 (!Inst.mayLoad() || SIInstrInfo::isAtomicNoRet(Inst))) {
623 if (TII.mayAccessScratch(Inst))
624 return SCRATCH_WRITE_ACCESS;
625 return VMEM_WRITE_ACCESS;
626 }
627 if (!ST.hasExtendedWaitCounts() || SIInstrInfo::isFLAT(Inst))
628 return VMEM_ACCESS;
629 return VmemReadMapping[getVmemType(Inst)];
630 }
631
632 std::optional<WaitEventType>
633 getExpertSchedulingEventType(const MachineInstr &Inst) const;
634
635 bool isAsync(const MachineInstr &MI) const {
637 return false;
639 return true;
640 const MachineOperand *Async =
641 TII.getNamedOperand(MI, AMDGPU::OpName::IsAsync);
642 return Async && (Async->getImm());
643 }
644
645 bool isNonAsyncLdsDmaWrite(const MachineInstr &MI) const {
646 return SIInstrInfo::mayWriteLDSThroughDMA(MI) && !isAsync(MI);
647 }
648
649 bool isAsyncLdsDmaWrite(const MachineInstr &MI) const {
650 return SIInstrInfo::mayWriteLDSThroughDMA(MI) && isAsync(MI);
651 }
652
653 bool isVmemAccess(const MachineInstr &MI) const;
654 bool generateWaitcntInstBefore(MachineInstr &MI,
655 WaitcntBrackets &ScoreBrackets,
656 MachineInstr *OldWaitcntInstr,
657 PreheaderFlushFlags FlushFlags);
658 bool generateWaitcnt(AMDGPU::Waitcnt Wait,
660 MachineBasicBlock &Block, WaitcntBrackets &ScoreBrackets,
661 MachineInstr *OldWaitcntInstr);
662 /// \returns all events that correspond to \p Inst.
663 WaitEventSet getEventsFor(const MachineInstr &Inst) const;
664 void updateEventWaitcntAfter(MachineInstr &Inst,
665 WaitcntBrackets *ScoreBrackets);
666 bool isNextENDPGM(MachineBasicBlock::instr_iterator It,
667 MachineBasicBlock *Block) const;
668 bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &Block,
669 WaitcntBrackets &ScoreBrackets);
670 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block,
671 WaitcntBrackets &ScoreBrackets);
672 /// Removes redundant Soft Xcnt Waitcnts in \p Block emitted by the Memory
673 /// Legalizer. Returns true if block was modified.
674 bool removeRedundantSoftXcnts(MachineBasicBlock &Block);
675 void setSchedulingMode(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
676 bool ExpertMode) const;
677 const WaitEventSet &getWaitEvents(InstCounterType T) const {
678 return WCG->getWaitEvents(T);
679 }
680 InstCounterType getCounterFromEvent(WaitEventType E) const {
681 return WCG->getCounterFromEvent(E);
682 }
683};
684
685// This objects maintains the current score brackets of each wait counter, and
686// a per-register scoreboard for each wait counter.
687//
688// We also maintain the latest score for every event type that can change the
689// waitcnt in order to know if there are multiple types of events within
690// the brackets. When multiple types of event happen in the bracket,
691// wait count may get decreased out of order, therefore we need to put in
692// "s_waitcnt 0" before use.
693class WaitcntBrackets {
694public:
695 WaitcntBrackets(const SIInsertWaitcnts *Context) : Context(Context) {
696 assert(Context->TRI.getNumRegUnits() < REGUNITS_END);
697 }
698
699#ifndef NDEBUG
700 ~WaitcntBrackets() {
701 unsigned NumUnusedVmem = 0, NumUnusedSGPRs = 0;
702 for (auto &[ID, Val] : VMem) {
703 if (Val.empty())
704 ++NumUnusedVmem;
705 }
706 for (auto &[ID, Val] : SGPRs) {
707 if (Val.empty())
708 ++NumUnusedSGPRs;
709 }
710
711 if (NumUnusedVmem || NumUnusedSGPRs) {
712 errs() << "WaitcntBracket had unused entries at destruction time: "
713 << NumUnusedVmem << " VMem and " << NumUnusedSGPRs
714 << " SGPR unused entries\n";
715 std::abort();
716 }
717 }
718#endif
719
720 bool isSmemCounter(InstCounterType T) const {
721 return T == Context->SmemAccessCounter || T == X_CNT;
722 }
723
724 unsigned getOutstanding(InstCounterType T) const {
725 return ScoreUBs[T] - ScoreLBs[T];
726 }
727
728 bool hasPendingVMEM(VMEMID ID, InstCounterType T) const {
729 return getVMemScore(ID, T) > getScoreLB(T);
730 }
731
732 /// \Return true if we have no score entries for counter \p T.
733 bool empty(InstCounterType T) const { return getScoreRange(T) == 0; }
734
735private:
736 unsigned getScoreLB(InstCounterType T) const {
738 return ScoreLBs[T];
739 }
740
741 unsigned getScoreUB(InstCounterType T) const {
743 return ScoreUBs[T];
744 }
745
746 unsigned getScoreRange(InstCounterType T) const {
747 return getScoreUB(T) - getScoreLB(T);
748 }
749
750 unsigned getSGPRScore(MCRegUnit RU, InstCounterType T) const {
751 auto It = SGPRs.find(RU);
752 return It != SGPRs.end() ? It->second.get(T) : 0;
753 }
754
755 unsigned getVMemScore(VMEMID TID, InstCounterType T) const {
756 auto It = VMem.find(TID);
757 return It != VMem.end() ? It->second.Scores[T] : 0;
758 }
759
760public:
761 bool merge(const WaitcntBrackets &Other);
762
763 bool counterOutOfOrder(InstCounterType T) const;
764 void simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const {
765 simplifyWaitcnt(Wait, Wait);
766 }
767 void simplifyWaitcnt(const AMDGPU::Waitcnt &CheckWait,
768 AMDGPU::Waitcnt &UpdateWait) const;
769 void simplifyWaitcnt(InstCounterType T, unsigned &Count) const;
770 void simplifyWaitcnt(Waitcnt &Wait, InstCounterType T) const;
771 void simplifyXcnt(const AMDGPU::Waitcnt &CheckWait,
772 AMDGPU::Waitcnt &UpdateWait) const;
773 void simplifyVmVsrc(const AMDGPU::Waitcnt &CheckWait,
774 AMDGPU::Waitcnt &UpdateWait) const;
775
776 void determineWaitForPhysReg(InstCounterType T, MCPhysReg Reg,
777 AMDGPU::Waitcnt &Wait) const;
778 void determineWaitForLDSDMA(InstCounterType T, VMEMID TID,
779 AMDGPU::Waitcnt &Wait) const;
780 AMDGPU::Waitcnt determineAsyncWait(unsigned N);
781 void tryClearSCCWriteEvent(MachineInstr *Inst);
782
783 void applyWaitcnt(const AMDGPU::Waitcnt &Wait);
784 void applyWaitcnt(InstCounterType T, unsigned Count);
785 void applyWaitcnt(const AMDGPU::Waitcnt &Wait, InstCounterType T);
786 void updateByEvent(WaitEventType E, MachineInstr &MI);
787 void recordAsyncMark(MachineInstr &MI);
788
789 bool hasPendingEvent() const { return !PendingEvents.empty(); }
790 bool hasPendingEvent(WaitEventType E) const {
791 return PendingEvents.contains(E);
792 }
793 bool hasPendingEvent(InstCounterType T) const {
794 bool HasPending = PendingEvents & Context->getWaitEvents(T);
795 assert(HasPending == !empty(T) &&
796 "Expected pending events iff scoreboard is not empty");
797 return HasPending;
798 }
799
800 bool hasMixedPendingEvents(InstCounterType T) const {
801 WaitEventSet Events = PendingEvents & Context->getWaitEvents(T);
802 // Return true if more than one bit is set in Events.
803 return Events.twoOrMore();
804 }
805
806 bool hasPendingFlat() const {
807 return ((LastFlat[DS_CNT] > ScoreLBs[DS_CNT] &&
808 LastFlat[DS_CNT] <= ScoreUBs[DS_CNT]) ||
809 (LastFlat[LOAD_CNT] > ScoreLBs[LOAD_CNT] &&
810 LastFlat[LOAD_CNT] <= ScoreUBs[LOAD_CNT]));
811 }
812
813 void setPendingFlat() {
814 LastFlat[LOAD_CNT] = ScoreUBs[LOAD_CNT];
815 LastFlat[DS_CNT] = ScoreUBs[DS_CNT];
816 }
817
818 bool hasPendingGDS() const {
819 return LastGDS > ScoreLBs[DS_CNT] && LastGDS <= ScoreUBs[DS_CNT];
820 }
821
822 unsigned getPendingGDSWait() const {
823 return std::min(getScoreUB(DS_CNT) - LastGDS,
824 getWaitCountMax(Context->getLimits(), DS_CNT) - 1);
825 }
826
827 void setPendingGDS() { LastGDS = ScoreUBs[DS_CNT]; }
828
829 // Return true if there might be pending writes to the vgpr-interval by VMEM
830 // instructions with types different from V.
831 bool hasOtherPendingVmemTypes(MCPhysReg Reg, VmemType V) const {
832 for (MCRegUnit RU : regunits(Reg)) {
833 auto It = VMem.find(toVMEMID(RU));
834 if (It != VMem.end() && (It->second.VMEMTypes & ~(1 << V)))
835 return true;
836 }
837 return false;
838 }
839
840 void clearVgprVmemTypes(MCPhysReg Reg) {
841 for (MCRegUnit RU : regunits(Reg)) {
842 if (auto It = VMem.find(toVMEMID(RU)); It != VMem.end()) {
843 It->second.VMEMTypes = 0;
844 if (It->second.empty())
845 VMem.erase(It);
846 }
847 }
848 }
849
850 void setStateOnFunctionEntryOrReturn() {
851 setScoreUB(STORE_CNT, getScoreUB(STORE_CNT) +
852 getWaitCountMax(Context->getLimits(), STORE_CNT));
853 PendingEvents |= Context->getWaitEvents(STORE_CNT);
854 }
855
856 ArrayRef<const MachineInstr *> getLDSDMAStores() const {
857 return LDSDMAStores;
858 }
859
860 bool hasPointSampleAccel(const MachineInstr &MI) const;
861 bool hasPointSamplePendingVmemTypes(const MachineInstr &MI,
862 MCPhysReg RU) const;
863
864 void print(raw_ostream &) const;
865 void dump() const { print(dbgs()); }
866
867 // Free up memory by removing empty entries from the DenseMap that track event
868 // scores.
869 void purgeEmptyTrackingData();
870
871private:
872 struct MergeInfo {
873 unsigned OldLB;
874 unsigned OtherLB;
875 unsigned MyShift;
876 unsigned OtherShift;
877 };
878
879 using CounterValueArray = std::array<unsigned, NUM_INST_CNTS>;
880
881 void determineWaitForScore(InstCounterType T, unsigned Score,
882 AMDGPU::Waitcnt &Wait) const;
883
884 static bool mergeScore(const MergeInfo &M, unsigned &Score,
885 unsigned OtherScore);
886 bool mergeAsyncMarks(ArrayRef<MergeInfo> MergeInfos,
887 ArrayRef<CounterValueArray> OtherMarks);
888
890 assert(Reg != AMDGPU::SCC && "Shouldn't be used on SCC");
891 if (!Context->TRI.isInAllocatableClass(Reg))
892 return {{}, {}};
893 const TargetRegisterClass *RC = Context->TRI.getPhysRegBaseClass(Reg);
894 unsigned Size = Context->TRI.getRegSizeInBits(*RC);
895 if (Size == 16 && Context->ST.hasD16Writes32BitVgpr())
896 Reg = Context->TRI.get32BitRegister(Reg);
897 return Context->TRI.regunits(Reg);
898 }
899
900 void setScoreLB(InstCounterType T, unsigned Val) {
902 ScoreLBs[T] = Val;
903 }
904
905 void setScoreUB(InstCounterType T, unsigned Val) {
907 ScoreUBs[T] = Val;
908
909 if (T != EXP_CNT)
910 return;
911
912 if (getScoreRange(EXP_CNT) > getWaitCountMax(Context->getLimits(), EXP_CNT))
913 ScoreLBs[EXP_CNT] =
914 ScoreUBs[EXP_CNT] - getWaitCountMax(Context->getLimits(), EXP_CNT);
915 }
916
917 void setRegScore(MCPhysReg Reg, InstCounterType T, unsigned Val) {
918 const SIRegisterInfo &TRI = Context->TRI;
919 if (Reg == AMDGPU::SCC) {
920 SCCScore = Val;
921 } else if (TRI.isVectorRegister(Context->MRI, Reg)) {
922 for (MCRegUnit RU : regunits(Reg))
923 VMem[toVMEMID(RU)].Scores[T] = Val;
924 } else if (TRI.isSGPRReg(Context->MRI, Reg)) {
925 for (MCRegUnit RU : regunits(Reg))
926 SGPRs[RU].get(T) = Val;
927 } else {
928 llvm_unreachable("Register cannot be tracked/unknown register!");
929 }
930 }
931
932 void setVMemScore(VMEMID TID, InstCounterType T, unsigned Val) {
933 VMem[TID].Scores[T] = Val;
934 }
935
936 void setScoreByOperand(const MachineOperand &Op, InstCounterType CntTy,
937 unsigned Val);
938
939 const SIInsertWaitcnts *Context;
940
941 unsigned ScoreLBs[NUM_INST_CNTS] = {0};
942 unsigned ScoreUBs[NUM_INST_CNTS] = {0};
943 WaitEventSet PendingEvents;
944 // Remember the last flat memory operation.
945 unsigned LastFlat[NUM_INST_CNTS] = {0};
946 // Remember the last GDS operation.
947 unsigned LastGDS = 0;
948
949 // The score tracking logic is fragmented as follows:
950 // - VMem: VGPR RegUnits and LDS DMA IDs, see the VMEMID encoding.
951 // - SGPRs: SGPR RegUnits
952 // - SCC: Non-allocatable and not general purpose: not a SGPR.
953 //
954 // For the VMem case, if the key is within the range of LDS DMA IDs,
955 // then the corresponding index into the `LDSDMAStores` vector below is:
956 // Key - LDSDMA_BEGIN - 1
957 // This is because LDSDMA_BEGIN is a generic entry and does not have an
958 // associated MachineInstr.
959 //
960 // TODO: Could we track SCC alongside SGPRs so it's not longer a special case?
961
962 struct VMEMInfo {
963 // Scores for all instruction counters. Zero-initialized.
964 CounterValueArray Scores{};
965 // Bitmask of the VmemTypes of VMEM instructions for this VGPR.
966 unsigned VMEMTypes = 0;
967
968 bool empty() const { return all_of(Scores, equal_to(0)) && !VMEMTypes; }
969 };
970
971 /// Wait cnt scores for every sgpr, the DS_CNT (corresponding to LGKMcnt
972 /// pre-gfx12) or KM_CNT (gfx12+ only), and X_CNT (gfx1250) are relevant.
973 class SGPRInfo {
974 /// Either DS_CNT or KM_CNT score.
975 unsigned ScoreDsKmCnt = 0;
976 unsigned ScoreXCnt = 0;
977
978 public:
979 unsigned get(InstCounterType T) const {
980 assert((T == DS_CNT || T == KM_CNT || T == X_CNT) && "Invalid counter");
981 return T == X_CNT ? ScoreXCnt : ScoreDsKmCnt;
982 }
983 unsigned &get(InstCounterType T) {
984 assert((T == DS_CNT || T == KM_CNT || T == X_CNT) && "Invalid counter");
985 return T == X_CNT ? ScoreXCnt : ScoreDsKmCnt;
986 }
987
988 bool empty() const { return !ScoreDsKmCnt && !ScoreXCnt; }
989 };
990
991 DenseMap<VMEMID, VMEMInfo> VMem; // VGPR + LDS DMA
992 DenseMap<MCRegUnit, SGPRInfo> SGPRs;
993
994 // Reg score for SCC.
995 unsigned SCCScore = 0;
996 // The unique instruction that has an SCC write pending, if there is one.
997 const MachineInstr *PendingSCCWrite = nullptr;
998
999 // Store representative LDS DMA operations. The only useful info here is
1000 // alias info. One store is kept per unique AAInfo.
1001 SmallVector<const MachineInstr *> LDSDMAStores;
1002
1003 // State of all counters at each async mark encountered so far.
1005
1006 // But in the rare pathological case, a nest of loops that pushes marks
1007 // without waiting on any mark can cause AsyncMarks to grow very large. We cap
1008 // it to a reasonable limit. We can tune this later or potentially introduce a
1009 // user option to control the value.
1010 static constexpr unsigned MaxAsyncMarks = 16;
1011
1012 // Track the upper bound score for async operations that are not part of a
1013 // mark yet. Initialized to all zeros.
1014 CounterValueArray AsyncScore{};
1015};
1016
1017class SIInsertWaitcntsLegacy : public MachineFunctionPass {
1018public:
1019 static char ID;
1020 SIInsertWaitcntsLegacy() : MachineFunctionPass(ID) {}
1021
1022 bool runOnMachineFunction(MachineFunction &MF) override;
1023
1024 StringRef getPassName() const override {
1025 return "SI insert wait instructions";
1026 }
1027
1028 void getAnalysisUsage(AnalysisUsage &AU) const override {
1029 AU.setPreservesCFG();
1030 AU.addRequired<MachineLoopInfoWrapperPass>();
1031 AU.addRequired<MachinePostDominatorTreeWrapperPass>();
1032 AU.addUsedIfAvailable<AAResultsWrapperPass>();
1033 AU.addPreserved<AAResultsWrapperPass>();
1035 }
1036};
1037
1038} // end anonymous namespace
1039
1040void WaitcntBrackets::setScoreByOperand(const MachineOperand &Op,
1041 InstCounterType CntTy, unsigned Score) {
1042 setRegScore(Op.getReg().asMCReg(), CntTy, Score);
1043}
1044
1045// Return true if the subtarget is one that enables Point Sample Acceleration
1046// and the MachineInstr passed in is one to which it might be applied (the
1047// hardware makes this decision based on several factors, but we can't determine
1048// this at compile time, so we have to assume it might be applied if the
1049// instruction supports it).
1050bool WaitcntBrackets::hasPointSampleAccel(const MachineInstr &MI) const {
1051 if (!Context->ST.hasPointSampleAccel() || !SIInstrInfo::isMIMG(MI))
1052 return false;
1053
1054 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(MI.getOpcode());
1055 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
1057 return BaseInfo->PointSampleAccel;
1058}
1059
1060// Return true if the subtarget enables Point Sample Acceleration, the supplied
1061// MachineInstr is one to which it might be applied and the supplied interval is
1062// one that has outstanding writes to vmem-types different than VMEM_NOSAMPLER
1063// (this is the type that a point sample accelerated instruction effectively
1064// becomes)
1065bool WaitcntBrackets::hasPointSamplePendingVmemTypes(const MachineInstr &MI,
1066 MCPhysReg Reg) const {
1067 if (!hasPointSampleAccel(MI))
1068 return false;
1069
1070 return hasOtherPendingVmemTypes(Reg, VMEM_NOSAMPLER);
1071}
1072
1073void WaitcntBrackets::updateByEvent(WaitEventType E, MachineInstr &Inst) {
1074 InstCounterType T = Context->getCounterFromEvent(E);
1075 assert(T < Context->MaxCounter);
1076
1077 unsigned UB = getScoreUB(T);
1078 unsigned CurrScore = UB + 1;
1079 if (CurrScore == 0)
1080 report_fatal_error("InsertWaitcnt score wraparound");
1081 // PendingEvents and ScoreUB need to be update regardless if this event
1082 // changes the score of a register or not.
1083 // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
1084 PendingEvents.insert(E);
1085 setScoreUB(T, CurrScore);
1086
1087 const SIRegisterInfo &TRI = Context->TRI;
1088 const MachineRegisterInfo &MRI = Context->MRI;
1089 const SIInstrInfo &TII = Context->TII;
1090
1091 if (T == EXP_CNT) {
1092 // Put score on the source vgprs. If this is a store, just use those
1093 // specific register(s).
1094 if (TII.isDS(Inst) && Inst.mayLoadOrStore()) {
1095 // All GDS operations must protect their address register (same as
1096 // export.)
1097 if (const auto *AddrOp = TII.getNamedOperand(Inst, AMDGPU::OpName::addr))
1098 setScoreByOperand(*AddrOp, EXP_CNT, CurrScore);
1099
1100 if (Inst.mayStore()) {
1101 if (const auto *Data0 =
1102 TII.getNamedOperand(Inst, AMDGPU::OpName::data0))
1103 setScoreByOperand(*Data0, EXP_CNT, CurrScore);
1104 if (const auto *Data1 =
1105 TII.getNamedOperand(Inst, AMDGPU::OpName::data1))
1106 setScoreByOperand(*Data1, EXP_CNT, CurrScore);
1107 } else if (SIInstrInfo::isAtomicRet(Inst) && !SIInstrInfo::isGWS(Inst) &&
1108 Inst.getOpcode() != AMDGPU::DS_APPEND &&
1109 Inst.getOpcode() != AMDGPU::DS_CONSUME &&
1110 Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
1111 for (const MachineOperand &Op : Inst.all_uses()) {
1112 if (TRI.isVectorRegister(MRI, Op.getReg()))
1113 setScoreByOperand(Op, EXP_CNT, CurrScore);
1114 }
1115 }
1116 } else if (TII.isFLAT(Inst)) {
1117 if (Inst.mayStore()) {
1118 setScoreByOperand(*TII.getNamedOperand(Inst, AMDGPU::OpName::data),
1119 EXP_CNT, CurrScore);
1120 } else if (SIInstrInfo::isAtomicRet(Inst)) {
1121 setScoreByOperand(*TII.getNamedOperand(Inst, AMDGPU::OpName::data),
1122 EXP_CNT, CurrScore);
1123 }
1124 } else if (TII.isMIMG(Inst)) {
1125 if (Inst.mayStore()) {
1126 setScoreByOperand(Inst.getOperand(0), EXP_CNT, CurrScore);
1127 } else if (SIInstrInfo::isAtomicRet(Inst)) {
1128 setScoreByOperand(*TII.getNamedOperand(Inst, AMDGPU::OpName::data),
1129 EXP_CNT, CurrScore);
1130 }
1131 } else if (TII.isMTBUF(Inst)) {
1132 if (Inst.mayStore())
1133 setScoreByOperand(Inst.getOperand(0), EXP_CNT, CurrScore);
1134 } else if (TII.isMUBUF(Inst)) {
1135 if (Inst.mayStore()) {
1136 setScoreByOperand(Inst.getOperand(0), EXP_CNT, CurrScore);
1137 } else if (SIInstrInfo::isAtomicRet(Inst)) {
1138 setScoreByOperand(*TII.getNamedOperand(Inst, AMDGPU::OpName::data),
1139 EXP_CNT, CurrScore);
1140 }
1141 } else if (TII.isLDSDIR(Inst)) {
1142 // LDSDIR instructions attach the score to the destination.
1143 setScoreByOperand(*TII.getNamedOperand(Inst, AMDGPU::OpName::vdst),
1144 EXP_CNT, CurrScore);
1145 } else {
1146 if (TII.isEXP(Inst)) {
1147 // For export the destination registers are really temps that
1148 // can be used as the actual source after export patching, so
1149 // we need to treat them like sources and set the EXP_CNT
1150 // score.
1151 for (MachineOperand &DefMO : Inst.all_defs()) {
1152 if (TRI.isVGPR(MRI, DefMO.getReg())) {
1153 setScoreByOperand(DefMO, EXP_CNT, CurrScore);
1154 }
1155 }
1156 }
1157 for (const MachineOperand &Op : Inst.all_uses()) {
1158 if (TRI.isVectorRegister(MRI, Op.getReg()))
1159 setScoreByOperand(Op, EXP_CNT, CurrScore);
1160 }
1161 }
1162 } else if (T == X_CNT) {
1163 WaitEventType OtherEvent = E == SMEM_GROUP ? VMEM_GROUP : SMEM_GROUP;
1164 if (PendingEvents.contains(OtherEvent)) {
1165 // Hardware inserts an implicit xcnt between interleaved
1166 // SMEM and VMEM operations. So there will never be
1167 // outstanding address translations for both SMEM and
1168 // VMEM at the same time.
1169 setScoreLB(T, getScoreUB(T) - 1);
1170 PendingEvents.remove(OtherEvent);
1171 }
1172 for (const MachineOperand &Op : Inst.all_uses())
1173 setScoreByOperand(Op, T, CurrScore);
1174 } else if (T == VA_VDST || T == VM_VSRC) {
1175 // Match the score to the VGPR destination or source registers as
1176 // appropriate
1177 for (const MachineOperand &Op : Inst.operands()) {
1178 if (!Op.isReg() || (T == VA_VDST && Op.isUse()) ||
1179 (T == VM_VSRC && Op.isDef()))
1180 continue;
1181 if (TRI.isVectorRegister(Context->MRI, Op.getReg()))
1182 setScoreByOperand(Op, T, CurrScore);
1183 }
1184 } else /* LGKM_CNT || EXP_CNT || VS_CNT || NUM_INST_CNTS */ {
1185 // Match the score to the destination registers.
1186 //
1187 // Check only explicit operands. Stores, especially spill stores, include
1188 // implicit uses and defs of their super registers which would create an
1189 // artificial dependency, while these are there only for register liveness
1190 // accounting purposes.
1191 //
1192 // Special cases where implicit register defs exists, such as M0 or VCC,
1193 // but none with memory instructions.
1194 for (const MachineOperand &Op : Inst.defs()) {
1195 if (T == LOAD_CNT || T == SAMPLE_CNT || T == BVH_CNT) {
1196 if (!TRI.isVectorRegister(MRI, Op.getReg())) // TODO: add wrapper
1197 continue;
1198 if (updateVMCntOnly(Inst)) {
1199 // updateVMCntOnly should only leave us with VGPRs
1200 // MUBUF, MTBUF, MIMG, FlatGlobal, and FlatScratch only have VGPR/AGPR
1201 // defs. That's required for a sane index into `VgprMemTypes` below
1202 assert(TRI.isVectorRegister(MRI, Op.getReg()));
1203 VmemType V = getVmemType(Inst);
1204 unsigned char TypesMask = 1 << V;
1205 // If instruction can have Point Sample Accel applied, we have to flag
1206 // this with another potential dependency
1207 if (hasPointSampleAccel(Inst))
1208 TypesMask |= 1 << VMEM_NOSAMPLER;
1209 for (MCRegUnit RU : regunits(Op.getReg().asMCReg()))
1210 VMem[toVMEMID(RU)].VMEMTypes |= TypesMask;
1211 }
1212 }
1213 setScoreByOperand(Op, T, CurrScore);
1214 }
1215 if (Inst.mayStore() &&
1216 (TII.isDS(Inst) || Context->isNonAsyncLdsDmaWrite(Inst))) {
1217 // MUBUF and FLAT LDS DMA operations need a wait on vmcnt before LDS
1218 // written can be accessed. A load from LDS to VMEM does not need a wait.
1219 //
1220 // The "Slot" is the offset from LDSDMA_BEGIN. If it's non-zero, then
1221 // there is a MachineInstr in LDSDMAStores used to track this LDSDMA
1222 // store. The "Slot" is the index into LDSDMAStores + 1.
1223 unsigned Slot = 0;
1224 for (const auto *MemOp : Inst.memoperands()) {
1225 if (!MemOp->isStore() ||
1226 MemOp->getAddrSpace() != AMDGPUAS::LOCAL_ADDRESS)
1227 continue;
1228 // Comparing just AA info does not guarantee memoperands are equal
1229 // in general, but this is so for LDS DMA in practice.
1230 auto AAI = MemOp->getAAInfo();
1231 // Alias scope information gives a way to definitely identify an
1232 // original memory object and practically produced in the module LDS
1233 // lowering pass. If there is no scope available we will not be able
1234 // to disambiguate LDS aliasing as after the module lowering all LDS
1235 // is squashed into a single big object.
1236 if (!AAI || !AAI.Scope)
1237 break;
1238 for (unsigned I = 0, E = LDSDMAStores.size(); I != E && !Slot; ++I) {
1239 for (const auto *MemOp : LDSDMAStores[I]->memoperands()) {
1240 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1241 Slot = I + 1;
1242 break;
1243 }
1244 }
1245 }
1246 if (Slot)
1247 break;
1248 // The slot may not be valid because it can be >= NUM_LDSDMA which
1249 // means the scoreboard cannot track it. We still want to preserve the
1250 // MI in order to check alias information, though.
1251 LDSDMAStores.push_back(&Inst);
1252 Slot = LDSDMAStores.size();
1253 break;
1254 }
1255 setVMemScore(LDSDMA_BEGIN, T, CurrScore);
1256 if (Slot && Slot < NUM_LDSDMA)
1257 setVMemScore(LDSDMA_BEGIN + Slot, T, CurrScore);
1258 }
1259
1260 // FIXME: Not supported on GFX12 yet. Newer async operations use other
1261 // counters too, so will need a map from instruction or event types to
1262 // counter types.
1263 if (Context->isAsyncLdsDmaWrite(Inst) && T == LOAD_CNT) {
1265 "unexpected GFX1250 instruction");
1266 AsyncScore[T] = CurrScore;
1267 }
1268
1270 setRegScore(AMDGPU::SCC, T, CurrScore);
1271 PendingSCCWrite = &Inst;
1272 }
1273 }
1274}
1275
1276void WaitcntBrackets::recordAsyncMark(MachineInstr &Inst) {
1277 // In the absence of loops, AsyncMarks can grow linearly with the program
1278 // until we encounter an ASYNCMARK_WAIT. We could drop the oldest mark above a
1279 // limit every time we push a new mark, but that seems like unnecessary work
1280 // in practical cases. We do separately truncate the array when processing a
1281 // loop, which should be sufficient.
1282 AsyncMarks.push_back(AsyncScore);
1283 AsyncScore = {};
1284 LLVM_DEBUG({
1285 dbgs() << "recordAsyncMark:\n" << Inst;
1286 for (const auto &Mark : AsyncMarks) {
1287 llvm::interleaveComma(Mark, dbgs());
1288 dbgs() << '\n';
1289 }
1290 });
1291}
1292
1293void WaitcntBrackets::print(raw_ostream &OS) const {
1294 const GCNSubtarget &ST = Context->ST;
1295
1296 for (auto T : inst_counter_types(Context->MaxCounter)) {
1297 unsigned SR = getScoreRange(T);
1298 switch (T) {
1299 case LOAD_CNT:
1300 OS << " " << (ST.hasExtendedWaitCounts() ? "LOAD" : "VM") << "_CNT("
1301 << SR << "):";
1302 break;
1303 case DS_CNT:
1304 OS << " " << (ST.hasExtendedWaitCounts() ? "DS" : "LGKM") << "_CNT("
1305 << SR << "):";
1306 break;
1307 case EXP_CNT:
1308 OS << " EXP_CNT(" << SR << "):";
1309 break;
1310 case STORE_CNT:
1311 OS << " " << (ST.hasExtendedWaitCounts() ? "STORE" : "VS") << "_CNT("
1312 << SR << "):";
1313 break;
1314 case SAMPLE_CNT:
1315 OS << " SAMPLE_CNT(" << SR << "):";
1316 break;
1317 case BVH_CNT:
1318 OS << " BVH_CNT(" << SR << "):";
1319 break;
1320 case KM_CNT:
1321 OS << " KM_CNT(" << SR << "):";
1322 break;
1323 case X_CNT:
1324 OS << " X_CNT(" << SR << "):";
1325 break;
1326 case ASYNC_CNT:
1327 OS << " ASYNC_CNT(" << SR << "):";
1328 break;
1329 case VA_VDST:
1330 OS << " VA_VDST(" << SR << "): ";
1331 break;
1332 case VM_VSRC:
1333 OS << " VM_VSRC(" << SR << "): ";
1334 break;
1335 default:
1336 OS << " UNKNOWN(" << SR << "):";
1337 break;
1338 }
1339
1340 if (SR != 0) {
1341 // Print vgpr scores.
1342 unsigned LB = getScoreLB(T);
1343
1344 SmallVector<VMEMID> SortedVMEMIDs(VMem.keys());
1345 sort(SortedVMEMIDs);
1346
1347 for (auto ID : SortedVMEMIDs) {
1348 unsigned RegScore = VMem.at(ID).Scores[T];
1349 if (RegScore <= LB)
1350 continue;
1351 unsigned RelScore = RegScore - LB - 1;
1352 if (ID < REGUNITS_END) {
1353 OS << ' ' << RelScore << ":vRU" << ID;
1354 } else {
1355 assert(ID >= LDSDMA_BEGIN && ID < LDSDMA_END &&
1356 "Unhandled/unexpected ID value!");
1357 OS << ' ' << RelScore << ":LDSDMA" << ID;
1358 }
1359 }
1360
1361 // Also need to print sgpr scores for lgkm_cnt or xcnt.
1362 if (isSmemCounter(T)) {
1363 SmallVector<MCRegUnit> SortedSMEMIDs(SGPRs.keys());
1364 sort(SortedSMEMIDs);
1365 for (auto ID : SortedSMEMIDs) {
1366 unsigned RegScore = SGPRs.at(ID).get(T);
1367 if (RegScore <= LB)
1368 continue;
1369 unsigned RelScore = RegScore - LB - 1;
1370 OS << ' ' << RelScore << ":sRU" << static_cast<unsigned>(ID);
1371 }
1372 }
1373
1374 if (T == KM_CNT && SCCScore > 0)
1375 OS << ' ' << SCCScore << ":scc";
1376 }
1377 OS << '\n';
1378 }
1379
1380 OS << "Pending Events: ";
1381 if (hasPendingEvent()) {
1382 ListSeparator LS;
1383 for (unsigned I = 0; I != NUM_WAIT_EVENTS; ++I) {
1384 if (hasPendingEvent((WaitEventType)I)) {
1385 OS << LS << WaitEventTypeName[I];
1386 }
1387 }
1388 } else {
1389 OS << "none";
1390 }
1391 OS << '\n';
1392
1393 OS << "Async score: ";
1394 if (AsyncScore.empty())
1395 OS << "none";
1396 else
1397 llvm::interleaveComma(AsyncScore, OS);
1398 OS << '\n';
1399
1400 OS << "Async marks: " << AsyncMarks.size() << '\n';
1401
1402 for (const auto &Mark : AsyncMarks) {
1403 for (auto T : inst_counter_types()) {
1404 unsigned MarkedScore = Mark[T];
1405 switch (T) {
1406 case LOAD_CNT:
1407 OS << " " << (ST.hasExtendedWaitCounts() ? "LOAD" : "VM")
1408 << "_CNT: " << MarkedScore;
1409 break;
1410 case DS_CNT:
1411 OS << " " << (ST.hasExtendedWaitCounts() ? "DS" : "LGKM")
1412 << "_CNT: " << MarkedScore;
1413 break;
1414 case EXP_CNT:
1415 OS << " EXP_CNT: " << MarkedScore;
1416 break;
1417 case STORE_CNT:
1418 OS << " " << (ST.hasExtendedWaitCounts() ? "STORE" : "VS")
1419 << "_CNT: " << MarkedScore;
1420 break;
1421 case SAMPLE_CNT:
1422 OS << " SAMPLE_CNT: " << MarkedScore;
1423 break;
1424 case BVH_CNT:
1425 OS << " BVH_CNT: " << MarkedScore;
1426 break;
1427 case KM_CNT:
1428 OS << " KM_CNT: " << MarkedScore;
1429 break;
1430 case X_CNT:
1431 OS << " X_CNT: " << MarkedScore;
1432 break;
1433 case ASYNC_CNT:
1434 OS << " ASYNC_CNT: " << MarkedScore;
1435 break;
1436 default:
1437 OS << " UNKNOWN: " << MarkedScore;
1438 break;
1439 }
1440 }
1441 OS << '\n';
1442 }
1443 OS << '\n';
1444}
1445
1446/// Simplify \p UpdateWait by removing waits that are redundant based on the
1447/// current WaitcntBrackets and any other waits specified in \p CheckWait.
1448void WaitcntBrackets::simplifyWaitcnt(const AMDGPU::Waitcnt &CheckWait,
1449 AMDGPU::Waitcnt &UpdateWait) const {
1450 simplifyWaitcnt(UpdateWait, LOAD_CNT);
1451 simplifyWaitcnt(UpdateWait, EXP_CNT);
1452 simplifyWaitcnt(UpdateWait, DS_CNT);
1453 simplifyWaitcnt(UpdateWait, STORE_CNT);
1454 simplifyWaitcnt(UpdateWait, SAMPLE_CNT);
1455 simplifyWaitcnt(UpdateWait, BVH_CNT);
1456 simplifyWaitcnt(UpdateWait, KM_CNT);
1457 simplifyXcnt(CheckWait, UpdateWait);
1458 simplifyWaitcnt(UpdateWait, VA_VDST);
1459 simplifyVmVsrc(CheckWait, UpdateWait);
1460 simplifyWaitcnt(UpdateWait, ASYNC_CNT);
1461}
1462
1463void WaitcntBrackets::simplifyWaitcnt(InstCounterType T,
1464 unsigned &Count) const {
1465 // The number of outstanding events for this type, T, can be calculated
1466 // as (UB - LB). If the current Count is greater than or equal to the number
1467 // of outstanding events, then the wait for this counter is redundant.
1468 if (Count >= getScoreRange(T))
1469 Count = ~0u;
1470}
1471
1472void WaitcntBrackets::simplifyWaitcnt(Waitcnt &Wait, InstCounterType T) const {
1473 unsigned Cnt = Wait.get(T);
1474 simplifyWaitcnt(T, Cnt);
1475 Wait.set(T, Cnt);
1476}
1477
1478void WaitcntBrackets::simplifyXcnt(const AMDGPU::Waitcnt &CheckWait,
1479 AMDGPU::Waitcnt &UpdateWait) const {
1480 // Try to simplify xcnt further by checking for joint kmcnt and loadcnt
1481 // optimizations. On entry to a block with multiple predescessors, there may
1482 // be pending SMEM and VMEM events active at the same time.
1483 // In such cases, only clear one active event at a time.
1484 // TODO: Revisit xcnt optimizations for gfx1250.
1485 // Wait on XCNT is redundant if we are already waiting for a load to complete.
1486 // SMEM can return out of order, so only omit XCNT wait if we are waiting till
1487 // zero.
1488 if (CheckWait.get(KM_CNT) == 0 && hasPendingEvent(SMEM_GROUP))
1489 UpdateWait.set(X_CNT, ~0u);
1490 // If we have pending store we cannot optimize XCnt because we do not wait for
1491 // stores. VMEM loads retun in order, so if we only have loads XCnt is
1492 // decremented to the same number as LOADCnt.
1493 if (CheckWait.get(LOAD_CNT) != ~0u && hasPendingEvent(VMEM_GROUP) &&
1494 !hasPendingEvent(STORE_CNT) &&
1495 CheckWait.get(X_CNT) >= CheckWait.get(LOAD_CNT))
1496 UpdateWait.set(X_CNT, ~0u);
1497 simplifyWaitcnt(UpdateWait, X_CNT);
1498}
1499
1500void WaitcntBrackets::simplifyVmVsrc(const AMDGPU::Waitcnt &CheckWait,
1501 AMDGPU::Waitcnt &UpdateWait) const {
1502 // Waiting for some counters implies waiting for VM_VSRC, since an
1503 // instruction that decrements a counter on completion would have
1504 // decremented VM_VSRC once its VGPR operands had been read.
1505 if (CheckWait.get(VM_VSRC) >=
1506 std::min({CheckWait.get(LOAD_CNT), CheckWait.get(STORE_CNT),
1507 CheckWait.get(SAMPLE_CNT), CheckWait.get(BVH_CNT),
1508 CheckWait.get(DS_CNT)}))
1509 UpdateWait.set(VM_VSRC, ~0u);
1510 simplifyWaitcnt(UpdateWait, VM_VSRC);
1511}
1512
1513void WaitcntBrackets::purgeEmptyTrackingData() {
1514 for (auto &[K, V] : make_early_inc_range(VMem)) {
1515 if (V.empty())
1516 VMem.erase(K);
1517 }
1518 for (auto &[K, V] : make_early_inc_range(SGPRs)) {
1519 if (V.empty())
1520 SGPRs.erase(K);
1521 }
1522}
1523
1524void WaitcntBrackets::determineWaitForScore(InstCounterType T,
1525 unsigned ScoreToWait,
1526 AMDGPU::Waitcnt &Wait) const {
1527 const unsigned LB = getScoreLB(T);
1528 const unsigned UB = getScoreUB(T);
1529
1530 // If the score falls within the bracket, we need a waitcnt.
1531 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1532 if ((T == LOAD_CNT || T == DS_CNT) && hasPendingFlat() &&
1533 !Context->ST.hasFlatLgkmVMemCountInOrder()) {
1534 // If there is a pending FLAT operation, and this is a VMem or LGKM
1535 // waitcnt and the target can report early completion, then we need
1536 // to force a waitcnt 0.
1537 addWait(Wait, T, 0);
1538 } else if (counterOutOfOrder(T)) {
1539 // Counter can get decremented out-of-order when there
1540 // are multiple types event in the bracket. Also emit an s_wait counter
1541 // with a conservative value of 0 for the counter.
1542 addWait(Wait, T, 0);
1543 } else {
1544 // If a counter has been maxed out avoid overflow by waiting for
1545 // MAX(CounterType) - 1 instead.
1546 unsigned NeededWait = std::min(
1547 UB - ScoreToWait, getWaitCountMax(Context->getLimits(), T) - 1);
1548 addWait(Wait, T, NeededWait);
1549 }
1550 }
1551}
1552
1553AMDGPU::Waitcnt WaitcntBrackets::determineAsyncWait(unsigned N) {
1554 LLVM_DEBUG({
1555 dbgs() << "Need " << N << " async marks. Found " << AsyncMarks.size()
1556 << ":\n";
1557 for (const auto &Mark : AsyncMarks) {
1558 llvm::interleaveComma(Mark, dbgs());
1559 dbgs() << '\n';
1560 }
1561 });
1562
1563 if (AsyncMarks.size() == MaxAsyncMarks) {
1564 // Enforcing MaxAsyncMarks here is unnecessary work because the size of
1565 // MaxAsyncMarks is linear when traversing straightline code. But we do
1566 // need to check if truncation may have occured at a merge, and adjust N
1567 // to ensure that a wait is generated.
1568 LLVM_DEBUG(dbgs() << "Possible truncation. Ensuring a non-trivial wait.\n");
1569 N = std::min(N, (unsigned)MaxAsyncMarks - 1);
1570 }
1571
1572 AMDGPU::Waitcnt Wait;
1573 if (AsyncMarks.size() <= N) {
1574 LLVM_DEBUG(dbgs() << "No additional wait for async mark.\n");
1575 return Wait;
1576 }
1577
1578 size_t MarkIndex = AsyncMarks.size() - N - 1;
1579 const auto &RequiredMark = AsyncMarks[MarkIndex];
1581 determineWaitForScore(T, RequiredMark[T], Wait);
1582
1583 // Immediately remove the waited mark and all older ones
1584 // This happens BEFORE the wait is actually inserted, which is fine
1585 // because we've already extracted the wait requirements
1586 LLVM_DEBUG({
1587 dbgs() << "Removing " << (MarkIndex + 1)
1588 << " async marks after determining wait\n";
1589 });
1590 AsyncMarks.erase(AsyncMarks.begin(), AsyncMarks.begin() + MarkIndex + 1);
1591
1592 LLVM_DEBUG(dbgs() << "Waits to add: " << Wait);
1593 return Wait;
1594}
1595
1596void WaitcntBrackets::determineWaitForPhysReg(InstCounterType T, MCPhysReg Reg,
1597 AMDGPU::Waitcnt &Wait) const {
1598 if (Reg == AMDGPU::SCC) {
1599 determineWaitForScore(T, SCCScore, Wait);
1600 } else {
1601 bool IsVGPR = Context->TRI.isVectorRegister(Context->MRI, Reg);
1602 for (MCRegUnit RU : regunits(Reg))
1603 determineWaitForScore(
1604 T, IsVGPR ? getVMemScore(toVMEMID(RU), T) : getSGPRScore(RU, T),
1605 Wait);
1606 }
1607}
1608
1609void WaitcntBrackets::determineWaitForLDSDMA(InstCounterType T, VMEMID TID,
1610 AMDGPU::Waitcnt &Wait) const {
1611 assert(TID >= LDSDMA_BEGIN && TID < LDSDMA_END);
1612 determineWaitForScore(T, getVMemScore(TID, T), Wait);
1613}
1614
1615void WaitcntBrackets::tryClearSCCWriteEvent(MachineInstr *Inst) {
1616 // S_BARRIER_WAIT on the same barrier guarantees that the pending write to
1617 // SCC has landed
1618 if (PendingSCCWrite &&
1619 PendingSCCWrite->getOpcode() == AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM &&
1620 PendingSCCWrite->getOperand(0).getImm() == Inst->getOperand(0).getImm()) {
1621 WaitEventSet SCC_WRITE_PendingEvent(SCC_WRITE);
1622 // If this SCC_WRITE is the only pending KM_CNT event, clear counter.
1623 if ((PendingEvents & Context->getWaitEvents(KM_CNT)) ==
1624 SCC_WRITE_PendingEvent) {
1625 setScoreLB(KM_CNT, getScoreUB(KM_CNT));
1626 }
1627
1628 PendingEvents.remove(SCC_WRITE_PendingEvent);
1629 PendingSCCWrite = nullptr;
1630 }
1631}
1632
1633void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait) {
1635 applyWaitcnt(Wait, T);
1636}
1637
1638void WaitcntBrackets::applyWaitcnt(InstCounterType T, unsigned Count) {
1639 const unsigned UB = getScoreUB(T);
1640 if (Count >= UB)
1641 return;
1642 if (Count != 0) {
1643 if (counterOutOfOrder(T))
1644 return;
1645 setScoreLB(T, std::max(getScoreLB(T), UB - Count));
1646 } else {
1647 setScoreLB(T, UB);
1648 PendingEvents.remove(Context->getWaitEvents(T));
1649 }
1650
1651 if (T == KM_CNT && Count == 0 && hasPendingEvent(SMEM_GROUP)) {
1652 if (!hasMixedPendingEvents(X_CNT))
1653 applyWaitcnt(X_CNT, 0);
1654 else
1655 PendingEvents.remove(SMEM_GROUP);
1656 }
1657 if (T == LOAD_CNT && hasPendingEvent(VMEM_GROUP) &&
1658 !hasPendingEvent(STORE_CNT)) {
1659 if (!hasMixedPendingEvents(X_CNT))
1660 applyWaitcnt(X_CNT, Count);
1661 else if (Count == 0)
1662 PendingEvents.remove(VMEM_GROUP);
1663 }
1664}
1665
1666void WaitcntBrackets::applyWaitcnt(const Waitcnt &Wait, InstCounterType T) {
1667 unsigned Cnt = Wait.get(T);
1668 applyWaitcnt(T, Cnt);
1669}
1670
1671// Where there are multiple types of event in the bracket of a counter,
1672// the decrement may go out of order.
1673bool WaitcntBrackets::counterOutOfOrder(InstCounterType T) const {
1674 // Scalar memory read always can go out of order.
1675 if ((T == Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1676 (T == X_CNT && hasPendingEvent(SMEM_GROUP)))
1677 return true;
1678
1679 // GLOBAL_INV completes in-order with other LOAD_CNT events (VMEM_ACCESS),
1680 // so having GLOBAL_INV_ACCESS mixed with other LOAD_CNT events doesn't cause
1681 // out-of-order completion.
1682 if (T == LOAD_CNT) {
1683 unsigned Events = hasPendingEvent(T);
1684 // Remove GLOBAL_INV_ACCESS from the event mask before checking for mixed
1685 // events
1686 Events &= ~(1 << GLOBAL_INV_ACCESS);
1687 // Return true only if there are still multiple event types after removing
1688 // GLOBAL_INV
1689 return Events & (Events - 1);
1690 }
1691
1692 return hasMixedPendingEvents(T);
1693}
1694
1695INITIALIZE_PASS_BEGIN(SIInsertWaitcntsLegacy, DEBUG_TYPE, "SI Insert Waitcnts",
1696 false, false)
1699INITIALIZE_PASS_END(SIInsertWaitcntsLegacy, DEBUG_TYPE, "SI Insert Waitcnts",
1701
1702char SIInsertWaitcntsLegacy::ID = 0;
1703
1704char &llvm::SIInsertWaitcntsID = SIInsertWaitcntsLegacy::ID;
1705
1707 return new SIInsertWaitcntsLegacy();
1708}
1709
1710static bool updateOperandIfDifferent(MachineInstr &MI, AMDGPU::OpName OpName,
1711 unsigned NewEnc) {
1712 int OpIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpName);
1713 assert(OpIdx >= 0);
1714
1715 MachineOperand &MO = MI.getOperand(OpIdx);
1716
1717 if (NewEnc == MO.getImm())
1718 return false;
1719
1720 MO.setImm(NewEnc);
1721 return true;
1722}
1723
1724/// Determine if \p MI is a gfx12+ single-counter S_WAIT_*CNT instruction,
1725/// and if so, which counter it is waiting on.
1726static std::optional<InstCounterType> counterTypeForInstr(unsigned Opcode) {
1727 switch (Opcode) {
1728 case AMDGPU::S_WAIT_LOADCNT:
1729 return LOAD_CNT;
1730 case AMDGPU::S_WAIT_EXPCNT:
1731 return EXP_CNT;
1732 case AMDGPU::S_WAIT_STORECNT:
1733 return STORE_CNT;
1734 case AMDGPU::S_WAIT_SAMPLECNT:
1735 return SAMPLE_CNT;
1736 case AMDGPU::S_WAIT_BVHCNT:
1737 return BVH_CNT;
1738 case AMDGPU::S_WAIT_DSCNT:
1739 return DS_CNT;
1740 case AMDGPU::S_WAIT_KMCNT:
1741 return KM_CNT;
1742 case AMDGPU::S_WAIT_XCNT:
1743 return X_CNT;
1744 default:
1745 return {};
1746 }
1747}
1748
1749bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt) const {
1750 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(Waitcnt->getOpcode());
1751 if (Opcode == Waitcnt->getOpcode())
1752 return false;
1753
1754 Waitcnt->setDesc(TII.get(Opcode));
1755 return true;
1756}
1757
1758/// Combine consecutive S_WAITCNT and S_WAITCNT_VSCNT instructions that
1759/// precede \p It and follow \p OldWaitcntInstr and apply any extra waits
1760/// from \p Wait that were added by previous passes. Currently this pass
1761/// conservatively assumes that these preexisting waits are required for
1762/// correctness.
1763bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1764 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1765 AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
1766 assert(isNormalMode(MaxCounter));
1767
1768 bool Modified = false;
1769 MachineInstr *WaitcntInstr = nullptr;
1770 MachineInstr *WaitcntVsCntInstr = nullptr;
1771
1772 LLVM_DEBUG({
1773 dbgs() << "PreGFX12::applyPreexistingWaitcnt at: ";
1774 if (It.isEnd())
1775 dbgs() << "end of block\n";
1776 else
1777 dbgs() << *It;
1778 });
1779
1780 for (auto &II :
1781 make_early_inc_range(make_range(OldWaitcntInstr.getIterator(), It))) {
1782 LLVM_DEBUG(dbgs() << "pre-existing iter: " << II);
1783 if (II.isMetaInstruction()) {
1784 LLVM_DEBUG(dbgs() << "skipped meta instruction\n");
1785 continue;
1786 }
1787
1788 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
1789 bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
1790
1791 // Update required wait count. If this is a soft waitcnt (= it was added
1792 // by an earlier pass), it may be entirely removed.
1793 if (Opcode == AMDGPU::S_WAITCNT) {
1794 unsigned IEnc = II.getOperand(0).getImm();
1795 AMDGPU::Waitcnt OldWait = AMDGPU::decodeWaitcnt(IV, IEnc);
1796 if (TrySimplify)
1797 ScoreBrackets.simplifyWaitcnt(OldWait);
1798 Wait = Wait.combined(OldWait);
1799
1800 // Merge consecutive waitcnt of the same type by erasing multiples.
1801 if (WaitcntInstr || (!Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1802 II.eraseFromParent();
1803 Modified = true;
1804 } else
1805 WaitcntInstr = &II;
1806 } else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1807 assert(ST.hasVMemToLDSLoad());
1808 LLVM_DEBUG(dbgs() << "Processing S_WAITCNT_lds_direct: " << II
1809 << "Before: " << Wait << '\n';);
1810 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, LDSDMA_BEGIN, Wait);
1811 LLVM_DEBUG(dbgs() << "After: " << Wait << '\n';);
1812
1813 // It is possible (but unlikely) that this is the only wait instruction,
1814 // in which case, we exit this loop without a WaitcntInstr to consume
1815 // `Wait`. But that works because `Wait` was passed in by reference, and
1816 // the callee eventually calls createNewWaitcnt on it. We test this
1817 // possibility in an articial MIR test since such a situation cannot be
1818 // recreated by running the memory legalizer.
1819 II.eraseFromParent();
1820 } else if (Opcode == AMDGPU::WAIT_ASYNCMARK) {
1821 unsigned N = II.getOperand(0).getImm();
1822 LLVM_DEBUG(dbgs() << "Processing WAIT_ASYNCMARK: " << II << '\n';);
1823 AMDGPU::Waitcnt OldWait = ScoreBrackets.determineAsyncWait(N);
1824 Wait = Wait.combined(OldWait);
1825 } else {
1826 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1827 assert(II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1828
1829 unsigned OldVSCnt =
1830 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1831 if (TrySimplify)
1832 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1833 Wait.set(STORE_CNT, std::min(Wait.get(STORE_CNT), OldVSCnt));
1834
1835 if (WaitcntVsCntInstr || (!Wait.hasWaitStoreCnt() && TrySimplify)) {
1836 II.eraseFromParent();
1837 Modified = true;
1838 } else
1839 WaitcntVsCntInstr = &II;
1840 }
1841 }
1842
1843 if (WaitcntInstr) {
1844 Modified |= updateOperandIfDifferent(*WaitcntInstr, AMDGPU::OpName::simm16,
1846 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1847
1848 ScoreBrackets.applyWaitcnt(Wait, LOAD_CNT);
1849 ScoreBrackets.applyWaitcnt(Wait, EXP_CNT);
1850 ScoreBrackets.applyWaitcnt(Wait, DS_CNT);
1851 Wait.set(LOAD_CNT, ~0u);
1852 Wait.set(EXP_CNT, ~0u);
1853 Wait.set(DS_CNT, ~0u);
1854
1855 LLVM_DEBUG(It.isEnd() ? dbgs() << "applied pre-existing waitcnt\n"
1856 << "New Instr at block end: "
1857 << *WaitcntInstr << '\n'
1858 : dbgs() << "applied pre-existing waitcnt\n"
1859 << "Old Instr: " << *It
1860 << "New Instr: " << *WaitcntInstr << '\n');
1861 }
1862
1863 if (WaitcntVsCntInstr) {
1865 *WaitcntVsCntInstr, AMDGPU::OpName::simm16, Wait.get(STORE_CNT));
1866 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1867
1868 ScoreBrackets.applyWaitcnt(STORE_CNT, Wait.get(STORE_CNT));
1869 Wait.set(STORE_CNT, ~0u);
1870
1871 LLVM_DEBUG(It.isEnd()
1872 ? dbgs() << "applied pre-existing waitcnt\n"
1873 << "New Instr at block end: " << *WaitcntVsCntInstr
1874 << '\n'
1875 : dbgs() << "applied pre-existing waitcnt\n"
1876 << "Old Instr: " << *It
1877 << "New Instr: " << *WaitcntVsCntInstr << '\n');
1878 }
1879
1880 return Modified;
1881}
1882
1883/// Generate S_WAITCNT and/or S_WAITCNT_VSCNT instructions for any
1884/// required counters in \p Wait
1885bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1886 MachineBasicBlock &Block, MachineBasicBlock::instr_iterator It,
1887 AMDGPU::Waitcnt Wait, const WaitcntBrackets &ScoreBrackets) {
1888 assert(isNormalMode(MaxCounter));
1889
1890 bool Modified = false;
1891 const DebugLoc &DL = Block.findDebugLoc(It);
1892
1893 // Helper to emit expanded waitcnt sequence for profiling.
1894 // Emits waitcnts from (Outstanding-1) down to Target.
1895 // The EmitWaitcnt callback emits a single waitcnt.
1896 auto EmitExpandedWaitcnt = [&](unsigned Outstanding, unsigned Target,
1897 auto EmitWaitcnt) {
1898 do {
1899 EmitWaitcnt(--Outstanding);
1900 } while (Outstanding > Target);
1901 Modified = true;
1902 };
1903
1904 // Waits for VMcnt, LKGMcnt and/or EXPcnt are encoded together into a
1905 // single instruction while VScnt has its own instruction.
1906 if (Wait.hasWaitExceptStoreCnt()) {
1907 // If profiling expansion is enabled, emit an expanded sequence
1908 if (ExpandWaitcntProfiling) {
1909 // Check if any of the counters to be waited on are out-of-order.
1910 // If so, fall back to normal (non-expanded) behavior since expansion
1911 // would provide misleading profiling information.
1912 bool AnyOutOfOrder = false;
1913 for (auto CT : {LOAD_CNT, DS_CNT, EXP_CNT}) {
1914 unsigned WaitCnt = Wait.get(CT);
1915 if (WaitCnt != ~0u && ScoreBrackets.counterOutOfOrder(CT)) {
1916 AnyOutOfOrder = true;
1917 break;
1918 }
1919 }
1920
1921 if (AnyOutOfOrder) {
1922 // Fall back to non-expanded wait
1923 unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
1924 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT)).addImm(Enc);
1925 Modified = true;
1926 } else {
1927 // All counters are in-order, safe to expand
1928 for (auto CT : {LOAD_CNT, DS_CNT, EXP_CNT}) {
1929 unsigned WaitCnt = Wait.get(CT);
1930 if (WaitCnt == ~0u)
1931 continue;
1932
1933 unsigned Outstanding = std::min(ScoreBrackets.getOutstanding(CT),
1934 getWaitCountMax(getLimits(), CT) - 1);
1935 EmitExpandedWaitcnt(Outstanding, WaitCnt, [&](unsigned Count) {
1936 AMDGPU::Waitcnt W;
1937 W.set(CT, Count);
1938 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT))
1940 });
1941 }
1942 }
1943 } else {
1944 // Normal behavior: emit single combined waitcnt
1945 unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
1946 [[maybe_unused]] auto SWaitInst =
1947 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT)).addImm(Enc);
1948 Modified = true;
1949
1950 LLVM_DEBUG(dbgs() << "PreGFX12::createNewWaitcnt\n";
1951 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1952 dbgs() << "New Instr: " << *SWaitInst << '\n');
1953 }
1954 }
1955
1956 if (Wait.hasWaitStoreCnt()) {
1957 assert(ST.hasVscnt());
1958
1959 if (ExpandWaitcntProfiling && Wait.get(STORE_CNT) != ~0u &&
1960 !ScoreBrackets.counterOutOfOrder(STORE_CNT)) {
1961 // Only expand if counter is not out-of-order
1962 unsigned Outstanding =
1963 std::min(ScoreBrackets.getOutstanding(STORE_CNT),
1964 getWaitCountMax(getLimits(), STORE_CNT) - 1);
1965 EmitExpandedWaitcnt(
1966 Outstanding, Wait.get(STORE_CNT), [&](unsigned Count) {
1967 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT_VSCNT))
1968 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1969 .addImm(Count);
1970 });
1971 } else {
1972 [[maybe_unused]] auto SWaitInst =
1973 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT_VSCNT))
1974 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1975 .addImm(Wait.get(STORE_CNT));
1976 Modified = true;
1977
1978 LLVM_DEBUG(dbgs() << "PreGFX12::createNewWaitcnt\n";
1979 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1980 dbgs() << "New Instr: " << *SWaitInst << '\n');
1981 }
1982 }
1983
1984 return Modified;
1985}
1986
1987AMDGPU::Waitcnt
1988WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(bool IncludeVSCnt) const {
1989 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt && ST.hasVscnt() ? 0 : ~0u);
1990}
1991
1992AMDGPU::Waitcnt
1993WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(bool IncludeVSCnt) const {
1994 unsigned ExpertVal = IsExpertMode ? 0 : ~0u;
1995 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
1996 ~0u /* XCNT */, ~0u /* ASYNC_CNT */, ExpertVal,
1997 ExpertVal);
1998}
1999
2000/// Combine consecutive S_WAIT_*CNT instructions that precede \p It and
2001/// follow \p OldWaitcntInstr and apply any extra waits from \p Wait that
2002/// were added by previous passes. Currently this pass conservatively
2003/// assumes that these preexisting waits are required for correctness.
2004bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
2005 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
2006 AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
2007 assert(!isNormalMode(MaxCounter));
2008
2009 bool Modified = false;
2010 MachineInstr *CombinedLoadDsCntInstr = nullptr;
2011 MachineInstr *CombinedStoreDsCntInstr = nullptr;
2012 MachineInstr *WaitcntDepctrInstr = nullptr;
2013 MachineInstr *WaitInstrs[NUM_EXTENDED_INST_CNTS] = {};
2014
2015 LLVM_DEBUG({
2016 dbgs() << "GFX12Plus::applyPreexistingWaitcnt at: ";
2017 if (It.isEnd())
2018 dbgs() << "end of block\n";
2019 else
2020 dbgs() << *It;
2021 });
2022
2023 // Accumulate waits that should not be simplified.
2024 AMDGPU::Waitcnt RequiredWait;
2025
2026 for (auto &II :
2027 make_early_inc_range(make_range(OldWaitcntInstr.getIterator(), It))) {
2028 LLVM_DEBUG(dbgs() << "pre-existing iter: " << II);
2029 if (II.isMetaInstruction()) {
2030 LLVM_DEBUG(dbgs() << "skipped meta instruction\n");
2031 continue;
2032 }
2033
2034 // Update required wait count. If this is a soft waitcnt (= it was added
2035 // by an earlier pass), it may be entirely removed.
2036
2037 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
2038 bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
2039
2040 // Don't crash if the programmer used legacy waitcnt intrinsics, but don't
2041 // attempt to do more than that either.
2042 if (Opcode == AMDGPU::S_WAITCNT)
2043 continue;
2044
2045 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
2046 unsigned OldEnc =
2047 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
2048 AMDGPU::Waitcnt OldWait = AMDGPU::decodeLoadcntDscnt(IV, OldEnc);
2049 if (TrySimplify)
2050 Wait = Wait.combined(OldWait);
2051 else
2052 RequiredWait = RequiredWait.combined(OldWait);
2053 // Keep the first wait_loadcnt, erase the rest.
2054 if (CombinedLoadDsCntInstr == nullptr) {
2055 CombinedLoadDsCntInstr = &II;
2056 } else {
2057 II.eraseFromParent();
2058 Modified = true;
2059 }
2060 } else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
2061 unsigned OldEnc =
2062 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
2063 AMDGPU::Waitcnt OldWait = AMDGPU::decodeStorecntDscnt(IV, OldEnc);
2064 if (TrySimplify)
2065 Wait = Wait.combined(OldWait);
2066 else
2067 RequiredWait = RequiredWait.combined(OldWait);
2068 // Keep the first wait_storecnt, erase the rest.
2069 if (CombinedStoreDsCntInstr == nullptr) {
2070 CombinedStoreDsCntInstr = &II;
2071 } else {
2072 II.eraseFromParent();
2073 Modified = true;
2074 }
2075 } else if (Opcode == AMDGPU::S_WAITCNT_DEPCTR) {
2076 unsigned OldEnc =
2077 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
2078 AMDGPU::Waitcnt OldWait;
2081 if (TrySimplify)
2082 ScoreBrackets.simplifyWaitcnt(OldWait);
2083 Wait = Wait.combined(OldWait);
2084 if (WaitcntDepctrInstr == nullptr) {
2085 WaitcntDepctrInstr = &II;
2086 } else {
2087 // S_WAITCNT_DEPCTR requires special care. Don't remove a
2088 // duplicate if it is waiting on things other than VA_VDST or
2089 // VM_VSRC. If that is the case, just make sure the VA_VDST and
2090 // VM_VSRC subfields of the operand are set to the "no wait"
2091 // values.
2092
2093 unsigned Enc =
2094 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
2095 Enc = AMDGPU::DepCtr::encodeFieldVmVsrc(Enc, ~0u);
2096 Enc = AMDGPU::DepCtr::encodeFieldVaVdst(Enc, ~0u);
2097
2098 if (Enc != (unsigned)AMDGPU::DepCtr::getDefaultDepCtrEncoding(ST)) {
2099 Modified |= updateOperandIfDifferent(II, AMDGPU::OpName::simm16, Enc);
2100 Modified |= promoteSoftWaitCnt(&II);
2101 } else {
2102 II.eraseFromParent();
2103 Modified = true;
2104 }
2105 }
2106 } else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
2107 // Architectures higher than GFX10 do not have direct loads to
2108 // LDS, so no work required here yet.
2109 II.eraseFromParent();
2110 Modified = true;
2111 } else if (Opcode == AMDGPU::WAIT_ASYNCMARK) {
2112 reportFatalUsageError("WAIT_ASYNCMARK is not ready for GFX12 yet");
2113 } else {
2114 std::optional<InstCounterType> CT = counterTypeForInstr(Opcode);
2115 assert(CT.has_value());
2116 unsigned OldCnt =
2117 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
2118 if (TrySimplify)
2119 addWait(Wait, CT.value(), OldCnt);
2120 else
2121 addWait(RequiredWait, CT.value(), OldCnt);
2122 // Keep the first wait of its kind, erase the rest.
2123 if (WaitInstrs[CT.value()] == nullptr) {
2124 WaitInstrs[CT.value()] = &II;
2125 } else {
2126 II.eraseFromParent();
2127 Modified = true;
2128 }
2129 }
2130 }
2131
2132 ScoreBrackets.simplifyWaitcnt(Wait.combined(RequiredWait), Wait);
2133 Wait = Wait.combined(RequiredWait);
2134
2135 if (CombinedLoadDsCntInstr) {
2136 // Only keep an S_WAIT_LOADCNT_DSCNT if both counters actually need
2137 // to be waited for. Otherwise, let the instruction be deleted so
2138 // the appropriate single counter wait instruction can be inserted
2139 // instead, when new S_WAIT_*CNT instructions are inserted by
2140 // createNewWaitcnt(). As a side effect, resetting the wait counts will
2141 // cause any redundant S_WAIT_LOADCNT or S_WAIT_DSCNT to be removed by
2142 // the loop below that deals with single counter instructions.
2143 //
2144 // A wait for LOAD_CNT or DS_CNT implies a wait for VM_VSRC, since
2145 // instructions that have decremented LOAD_CNT or DS_CNT on completion
2146 // will have needed to wait for their register sources to be available
2147 // first.
2148 if (Wait.get(LOAD_CNT) != ~0u && Wait.get(DS_CNT) != ~0u) {
2149 unsigned NewEnc = AMDGPU::encodeLoadcntDscnt(IV, Wait);
2150 Modified |= updateOperandIfDifferent(*CombinedLoadDsCntInstr,
2151 AMDGPU::OpName::simm16, NewEnc);
2152 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
2153 ScoreBrackets.applyWaitcnt(LOAD_CNT, Wait.get(LOAD_CNT));
2154 ScoreBrackets.applyWaitcnt(DS_CNT, Wait.get(DS_CNT));
2155 Wait.set(LOAD_CNT, ~0u);
2156 Wait.set(DS_CNT, ~0u);
2157
2158 LLVM_DEBUG(It.isEnd() ? dbgs() << "applied pre-existing waitcnt\n"
2159 << "New Instr at block end: "
2160 << *CombinedLoadDsCntInstr << '\n'
2161 : dbgs() << "applied pre-existing waitcnt\n"
2162 << "Old Instr: " << *It << "New Instr: "
2163 << *CombinedLoadDsCntInstr << '\n');
2164 } else {
2165 CombinedLoadDsCntInstr->eraseFromParent();
2166 Modified = true;
2167 }
2168 }
2169
2170 if (CombinedStoreDsCntInstr) {
2171 // Similarly for S_WAIT_STORECNT_DSCNT.
2172 if (Wait.get(STORE_CNT) != ~0u && Wait.get(DS_CNT) != ~0u) {
2173 unsigned NewEnc = AMDGPU::encodeStorecntDscnt(IV, Wait);
2174 Modified |= updateOperandIfDifferent(*CombinedStoreDsCntInstr,
2175 AMDGPU::OpName::simm16, NewEnc);
2176 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
2177 ScoreBrackets.applyWaitcnt(Wait, STORE_CNT);
2178 ScoreBrackets.applyWaitcnt(Wait, DS_CNT);
2179 Wait.set(STORE_CNT, ~0u);
2180 Wait.set(DS_CNT, ~0u);
2181
2182 LLVM_DEBUG(It.isEnd() ? dbgs() << "applied pre-existing waitcnt\n"
2183 << "New Instr at block end: "
2184 << *CombinedStoreDsCntInstr << '\n'
2185 : dbgs() << "applied pre-existing waitcnt\n"
2186 << "Old Instr: " << *It << "New Instr: "
2187 << *CombinedStoreDsCntInstr << '\n');
2188 } else {
2189 CombinedStoreDsCntInstr->eraseFromParent();
2190 Modified = true;
2191 }
2192 }
2193
2194 // Look for an opportunity to convert existing S_WAIT_LOADCNT,
2195 // S_WAIT_STORECNT and S_WAIT_DSCNT into new S_WAIT_LOADCNT_DSCNT
2196 // or S_WAIT_STORECNT_DSCNT. This is achieved by selectively removing
2197 // instructions so that createNewWaitcnt() will create new combined
2198 // instructions to replace them.
2199
2200 if (Wait.get(DS_CNT) != ~0u) {
2201 // This is a vector of addresses in WaitInstrs pointing to instructions
2202 // that should be removed if they are present.
2204
2205 // If it's known that both DScnt and either LOADcnt or STOREcnt (but not
2206 // both) need to be waited for, ensure that there are no existing
2207 // individual wait count instructions for these.
2208
2209 if (Wait.get(LOAD_CNT) != ~0u) {
2210 WaitsToErase.push_back(&WaitInstrs[LOAD_CNT]);
2211 WaitsToErase.push_back(&WaitInstrs[DS_CNT]);
2212 } else if (Wait.get(STORE_CNT) != ~0u) {
2213 WaitsToErase.push_back(&WaitInstrs[STORE_CNT]);
2214 WaitsToErase.push_back(&WaitInstrs[DS_CNT]);
2215 }
2216
2217 for (MachineInstr **WI : WaitsToErase) {
2218 if (!*WI)
2219 continue;
2220
2221 (*WI)->eraseFromParent();
2222 *WI = nullptr;
2223 Modified = true;
2224 }
2225 }
2226
2228 if (!WaitInstrs[CT])
2229 continue;
2230
2231 unsigned NewCnt = Wait.get(CT);
2232 if (NewCnt != ~0u) {
2233 Modified |= updateOperandIfDifferent(*WaitInstrs[CT],
2234 AMDGPU::OpName::simm16, NewCnt);
2235 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
2236
2237 ScoreBrackets.applyWaitcnt(CT, NewCnt);
2238 setNoWait(Wait, CT);
2239
2240 LLVM_DEBUG(It.isEnd()
2241 ? dbgs() << "applied pre-existing waitcnt\n"
2242 << "New Instr at block end: " << *WaitInstrs[CT]
2243 << '\n'
2244 : dbgs() << "applied pre-existing waitcnt\n"
2245 << "Old Instr: " << *It
2246 << "New Instr: " << *WaitInstrs[CT] << '\n');
2247 } else {
2248 WaitInstrs[CT]->eraseFromParent();
2249 Modified = true;
2250 }
2251 }
2252
2253 if (WaitcntDepctrInstr) {
2254 // Get the encoded Depctr immediate and override the VA_VDST and VM_VSRC
2255 // subfields with the new required values.
2256 unsigned Enc =
2257 TII.getNamedOperand(*WaitcntDepctrInstr, AMDGPU::OpName::simm16)
2258 ->getImm();
2261
2262 ScoreBrackets.applyWaitcnt(VA_VDST, Wait.get(VA_VDST));
2263 ScoreBrackets.applyWaitcnt(VM_VSRC, Wait.get(VM_VSRC));
2264 Wait.set(VA_VDST, ~0u);
2265 Wait.set(VM_VSRC, ~0u);
2266
2267 // If that new encoded Depctr immediate would actually still wait
2268 // for anything, update the instruction's operand. Otherwise it can
2269 // just be deleted.
2270 if (Enc != (unsigned)AMDGPU::DepCtr::getDefaultDepCtrEncoding(ST)) {
2271 Modified |= updateOperandIfDifferent(*WaitcntDepctrInstr,
2272 AMDGPU::OpName::simm16, Enc);
2273 LLVM_DEBUG(It.isEnd() ? dbgs() << "applyPreexistingWaitcnt\n"
2274 << "New Instr at block end: "
2275 << *WaitcntDepctrInstr << '\n'
2276 : dbgs() << "applyPreexistingWaitcnt\n"
2277 << "Old Instr: " << *It << "New Instr: "
2278 << *WaitcntDepctrInstr << '\n');
2279 } else {
2280 WaitcntDepctrInstr->eraseFromParent();
2281 Modified = true;
2282 }
2283 }
2284
2285 return Modified;
2286}
2287
2288/// Generate S_WAIT_*CNT instructions for any required counters in \p Wait
2289bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
2290 MachineBasicBlock &Block, MachineBasicBlock::instr_iterator It,
2291 AMDGPU::Waitcnt Wait, const WaitcntBrackets &ScoreBrackets) {
2292 assert(!isNormalMode(MaxCounter));
2293
2294 bool Modified = false;
2295 const DebugLoc &DL = Block.findDebugLoc(It);
2296
2297 // Helper to emit expanded waitcnt sequence for profiling.
2298 auto EmitExpandedWaitcnt = [&](unsigned Outstanding, unsigned Target,
2299 auto EmitWaitcnt) {
2300 for (unsigned I = Outstanding - 1; I > Target && I != ~0u; --I)
2301 EmitWaitcnt(I);
2302 EmitWaitcnt(Target);
2303 Modified = true;
2304 };
2305
2306 // For GFX12+, we use separate wait instructions, which makes expansion
2307 // simpler
2308 if (ExpandWaitcntProfiling) {
2310 unsigned Count = Wait.get(CT);
2311 if (Count == ~0u)
2312 continue;
2313
2314 // Skip expansion for out-of-order counters - emit normal wait instead
2315 if (ScoreBrackets.counterOutOfOrder(CT)) {
2316 BuildMI(Block, It, DL, TII.get(instrsForExtendedCounterTypes[CT]))
2317 .addImm(Count);
2318 Modified = true;
2319 continue;
2320 }
2321
2322 unsigned Outstanding = std::min(ScoreBrackets.getOutstanding(CT),
2323 getWaitCountMax(getLimits(), CT) - 1);
2324 EmitExpandedWaitcnt(Outstanding, Count, [&](unsigned Val) {
2325 BuildMI(Block, It, DL, TII.get(instrsForExtendedCounterTypes[CT]))
2326 .addImm(Val);
2327 });
2328 }
2329 return Modified;
2330 }
2331
2332 // Normal behavior (no expansion)
2333 // Check for opportunities to use combined wait instructions.
2334 if (Wait.get(DS_CNT) != ~0u) {
2335 MachineInstr *SWaitInst = nullptr;
2336
2337 if (Wait.get(LOAD_CNT) != ~0u) {
2338 unsigned Enc = AMDGPU::encodeLoadcntDscnt(IV, Wait);
2339
2340 SWaitInst = BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAIT_LOADCNT_DSCNT))
2341 .addImm(Enc);
2342
2343 Wait.set(LOAD_CNT, ~0u);
2344 Wait.set(DS_CNT, ~0u);
2345 } else if (Wait.get(STORE_CNT) != ~0u) {
2346 unsigned Enc = AMDGPU::encodeStorecntDscnt(IV, Wait);
2347
2348 SWaitInst = BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAIT_STORECNT_DSCNT))
2349 .addImm(Enc);
2350
2351 Wait.set(STORE_CNT, ~0u);
2352 Wait.set(DS_CNT, ~0u);
2353 }
2354
2355 if (SWaitInst) {
2356 Modified = true;
2357
2358 LLVM_DEBUG(dbgs() << "GFX12Plus::createNewWaitcnt\n";
2359 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
2360 dbgs() << "New Instr: " << *SWaitInst << '\n');
2361 }
2362 }
2363
2364 // Generate an instruction for any remaining counter that needs
2365 // waiting for.
2366
2368 unsigned Count = Wait.get(CT);
2369 if (Count == ~0u)
2370 continue;
2371
2372 [[maybe_unused]] auto SWaitInst =
2373 BuildMI(Block, It, DL, TII.get(instrsForExtendedCounterTypes[CT]))
2374 .addImm(Count);
2375
2376 Modified = true;
2377
2378 LLVM_DEBUG(dbgs() << "GFX12Plus::createNewWaitcnt\n";
2379 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
2380 dbgs() << "New Instr: " << *SWaitInst << '\n');
2381 }
2382
2383 if (Wait.hasWaitDepctr()) {
2384 assert(IsExpertMode);
2385 unsigned Enc = AMDGPU::DepCtr::encodeFieldVmVsrc(Wait.get(VM_VSRC), ST);
2387
2388 [[maybe_unused]] auto SWaitInst =
2389 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT_DEPCTR)).addImm(Enc);
2390
2391 Modified = true;
2392
2393 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
2394 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
2395 dbgs() << "New Instr: " << *SWaitInst << '\n');
2396 }
2397
2398 return Modified;
2399}
2400
2401/// Generate s_waitcnt instruction to be placed before cur_Inst.
2402/// Instructions of a given type are returned in order,
2403/// but instructions of different types can complete out of order.
2404/// We rely on this in-order completion
2405/// and simply assign a score to the memory access instructions.
2406/// We keep track of the active "score bracket" to determine
2407/// if an access of a memory read requires an s_waitcnt
2408/// and if so what the value of each counter is.
2409/// The "score bracket" is bound by the lower bound and upper bound
2410/// scores (*_score_LB and *_score_ub respectively).
2411/// If FlushFlags.FlushVmCnt is true, we want to flush the vmcnt counter here.
2412/// If FlushFlags.FlushDsCnt is true, we want to flush the dscnt counter here
2413/// (GFX12+ only, where DS_CNT is a separate counter).
2414bool SIInsertWaitcnts::generateWaitcntInstBefore(
2415 MachineInstr &MI, WaitcntBrackets &ScoreBrackets,
2416 MachineInstr *OldWaitcntInstr, PreheaderFlushFlags FlushFlags) {
2417 LLVM_DEBUG(dbgs() << "\n*** GenerateWaitcntInstBefore: "; MI.print(dbgs()););
2418 setForceEmitWaitcnt();
2419
2420 assert(!MI.isMetaInstruction());
2421
2422 AMDGPU::Waitcnt Wait;
2423 const unsigned Opc = MI.getOpcode();
2424
2425 switch (Opc) {
2426 case AMDGPU::BUFFER_WBINVL1:
2427 case AMDGPU::BUFFER_WBINVL1_SC:
2428 case AMDGPU::BUFFER_WBINVL1_VOL:
2429 case AMDGPU::BUFFER_GL0_INV:
2430 case AMDGPU::BUFFER_GL1_INV: {
2431 // FIXME: This should have already been handled by the memory legalizer.
2432 // Removing this currently doesn't affect any lit tests, but we need to
2433 // verify that nothing was relying on this. The number of buffer invalidates
2434 // being handled here should not be expanded.
2435 Wait.set(LOAD_CNT, 0);
2436 break;
2437 }
2438 case AMDGPU::SI_RETURN_TO_EPILOG:
2439 case AMDGPU::SI_RETURN:
2440 case AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN:
2441 case AMDGPU::S_SETPC_B64_return: {
2442 // All waits must be resolved at call return.
2443 // NOTE: this could be improved with knowledge of all call sites or
2444 // with knowledge of the called routines.
2445 ReturnInsts.insert(&MI);
2446 AMDGPU::Waitcnt AllZeroWait =
2447 WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false);
2448 // On GFX12+, if LOAD_CNT is pending but no VGPRs are waiting for loads
2449 // (e.g., only GLOBAL_INV is pending), we can skip waiting on loadcnt.
2450 // GLOBAL_INV increments loadcnt but doesn't write to VGPRs, so there's
2451 // no need to wait for it at function boundaries.
2452 if (ST.hasExtendedWaitCounts() &&
2453 !ScoreBrackets.hasPendingEvent(VMEM_ACCESS))
2454 AllZeroWait.set(LOAD_CNT, ~0u);
2455 Wait = AllZeroWait;
2456 break;
2457 }
2458 case AMDGPU::S_ENDPGM:
2459 case AMDGPU::S_ENDPGM_SAVED: {
2460 // In dynamic VGPR mode, we want to release the VGPRs before the wave exits.
2461 // Technically the hardware will do this on its own if we don't, but that
2462 // might cost extra cycles compared to doing it explicitly.
2463 // When not in dynamic VGPR mode, identify S_ENDPGM instructions which may
2464 // have to wait for outstanding VMEM stores. In this case it can be useful
2465 // to send a message to explicitly release all VGPRs before the stores have
2466 // completed, but it is only safe to do this if there are no outstanding
2467 // scratch stores.
2468 EndPgmInsts[&MI] = !ScoreBrackets.empty(STORE_CNT) &&
2469 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS);
2470 break;
2471 }
2472 case AMDGPU::S_SENDMSG:
2473 case AMDGPU::S_SENDMSGHALT: {
2474 if (ST.hasLegacyGeometry() &&
2475 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_PreGFX11_) ==
2477 // Resolve vm waits before gs-done.
2478 Wait.set(LOAD_CNT, 0);
2479 break;
2480 }
2481 [[fallthrough]];
2482 }
2483 default: {
2484
2485 // Export & GDS instructions do not read the EXEC mask until after the
2486 // export is granted (which can occur well after the instruction is issued).
2487 // The shader program must flush all EXP operations on the export-count
2488 // before overwriting the EXEC mask.
2489 if (MI.modifiesRegister(AMDGPU::EXEC, &TRI)) {
2490 // Export and GDS are tracked individually, either may trigger a waitcnt
2491 // for EXEC.
2492 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
2493 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
2494 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
2495 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
2496 Wait.set(EXP_CNT, 0);
2497 }
2498 }
2499
2500 // Wait for any pending GDS instruction to complete before any
2501 // "Always GDS" instruction.
2502 if (TII.isAlwaysGDS(Opc) && ScoreBrackets.hasPendingGDS())
2503 addWait(Wait, DS_CNT, ScoreBrackets.getPendingGDSWait());
2504
2505 if (MI.isCall()) {
2506 // The function is going to insert a wait on everything in its prolog.
2507 // This still needs to be careful if the call target is a load (e.g. a GOT
2508 // load). We also need to check WAW dependency with saved PC.
2509 CallInsts.insert(&MI);
2510 Wait = AMDGPU::Waitcnt();
2511
2512 const MachineOperand &CallAddrOp = TII.getCalleeOperand(MI);
2513 if (CallAddrOp.isReg()) {
2514 ScoreBrackets.determineWaitForPhysReg(
2515 SmemAccessCounter, CallAddrOp.getReg().asMCReg(), Wait);
2516
2517 if (const auto *RtnAddrOp =
2518 TII.getNamedOperand(MI, AMDGPU::OpName::dst)) {
2519 ScoreBrackets.determineWaitForPhysReg(
2520 SmemAccessCounter, RtnAddrOp->getReg().asMCReg(), Wait);
2521 }
2522 }
2523 } else if (Opc == AMDGPU::S_BARRIER_WAIT) {
2524 ScoreBrackets.tryClearSCCWriteEvent(&MI);
2525 } else {
2526 // FIXME: Should not be relying on memoperands.
2527 // Look at the source operands of every instruction to see if
2528 // any of them results from a previous memory operation that affects
2529 // its current usage. If so, an s_waitcnt instruction needs to be
2530 // emitted.
2531 // If the source operand was defined by a load, add the s_waitcnt
2532 // instruction.
2533 //
2534 // Two cases are handled for destination operands:
2535 // 1) If the destination operand was defined by a load, add the s_waitcnt
2536 // instruction to guarantee the right WAW order.
2537 // 2) If a destination operand that was used by a recent export/store ins,
2538 // add s_waitcnt on exp_cnt to guarantee the WAR order.
2539
2540 for (const MachineMemOperand *Memop : MI.memoperands()) {
2541 const Value *Ptr = Memop->getValue();
2542 if (Memop->isStore()) {
2543 if (auto It = SLoadAddresses.find(Ptr); It != SLoadAddresses.end()) {
2544 addWait(Wait, SmemAccessCounter, 0);
2545 if (PDT.dominates(MI.getParent(), It->second))
2546 SLoadAddresses.erase(It);
2547 }
2548 }
2549 unsigned AS = Memop->getAddrSpace();
2551 continue;
2552 // No need to wait before load from VMEM to LDS.
2553 if (TII.mayWriteLDSThroughDMA(MI))
2554 continue;
2555
2556 // LOAD_CNT is only relevant to vgpr or LDS.
2557 unsigned TID = LDSDMA_BEGIN;
2558 if (Ptr && Memop->getAAInfo()) {
2559 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
2560 for (unsigned I = 0, E = LDSDMAStores.size(); I != E; ++I) {
2561 if (MI.mayAlias(AA, *LDSDMAStores[I], true)) {
2562 if ((I + 1) >= NUM_LDSDMA) {
2563 // We didn't have enough slot to track this LDS DMA store, it
2564 // has been tracked using the common RegNo (FIRST_LDS_VGPR).
2565 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID, Wait);
2566 break;
2567 }
2568
2569 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID + I + 1, Wait);
2570 }
2571 }
2572 } else {
2573 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID, Wait);
2574 }
2575 if (Memop->isStore()) {
2576 ScoreBrackets.determineWaitForLDSDMA(EXP_CNT, TID, Wait);
2577 }
2578 }
2579
2580 // Loop over use and def operands.
2581 for (const MachineOperand &Op : MI.operands()) {
2582 if (!Op.isReg())
2583 continue;
2584
2585 // If the instruction does not read tied source, skip the operand.
2586 if (Op.isTied() && Op.isUse() && TII.doesNotReadTiedSource(MI))
2587 continue;
2588
2589 MCPhysReg Reg = Op.getReg().asMCReg();
2590
2591 const bool IsVGPR = TRI.isVectorRegister(MRI, Op.getReg());
2592 if (IsVGPR) {
2593 // Implicit VGPR defs and uses are never a part of the memory
2594 // instructions description and usually present to account for
2595 // super-register liveness.
2596 // TODO: Most of the other instructions also have implicit uses
2597 // for the liveness accounting only.
2598 if (Op.isImplicit() && MI.mayLoadOrStore())
2599 continue;
2600
2601 ScoreBrackets.determineWaitForPhysReg(VA_VDST, Reg, Wait);
2602 if (Op.isDef())
2603 ScoreBrackets.determineWaitForPhysReg(VM_VSRC, Reg, Wait);
2604 // RAW always needs an s_waitcnt. WAW needs an s_waitcnt unless the
2605 // previous write and this write are the same type of VMEM
2606 // instruction, in which case they are (in some architectures)
2607 // guaranteed to write their results in order anyway.
2608 // Additionally check instructions where Point Sample Acceleration
2609 // might be applied.
2610 if (Op.isUse() || !updateVMCntOnly(MI) ||
2611 ScoreBrackets.hasOtherPendingVmemTypes(Reg, getVmemType(MI)) ||
2612 ScoreBrackets.hasPointSamplePendingVmemTypes(MI, Reg) ||
2613 !ST.hasVmemWriteVgprInOrder()) {
2614 ScoreBrackets.determineWaitForPhysReg(LOAD_CNT, Reg, Wait);
2615 ScoreBrackets.determineWaitForPhysReg(SAMPLE_CNT, Reg, Wait);
2616 ScoreBrackets.determineWaitForPhysReg(BVH_CNT, Reg, Wait);
2617 ScoreBrackets.clearVgprVmemTypes(Reg);
2618 }
2619
2620 if (Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2621 ScoreBrackets.determineWaitForPhysReg(EXP_CNT, Reg, Wait);
2622 }
2623 ScoreBrackets.determineWaitForPhysReg(DS_CNT, Reg, Wait);
2624 } else if (Op.getReg() == AMDGPU::SCC) {
2625 ScoreBrackets.determineWaitForPhysReg(KM_CNT, Reg, Wait);
2626 } else {
2627 ScoreBrackets.determineWaitForPhysReg(SmemAccessCounter, Reg, Wait);
2628 }
2629
2630 if (ST.hasWaitXcnt() && Op.isDef())
2631 ScoreBrackets.determineWaitForPhysReg(X_CNT, Reg, Wait);
2632 }
2633 }
2634 }
2635 }
2636
2637 // Ensure safety against exceptions from outstanding memory operations while
2638 // waiting for a barrier:
2639 //
2640 // * Some subtargets safely handle backing off the barrier in hardware
2641 // when an exception occurs.
2642 // * Some subtargets have an implicit S_WAITCNT 0 before barriers, so that
2643 // there can be no outstanding memory operations during the wait.
2644 // * Subtargets with split barriers don't need to back off the barrier; it
2645 // is up to the trap handler to preserve the user barrier state correctly.
2646 //
2647 // In all other cases, ensure safety by ensuring that there are no outstanding
2648 // memory operations.
2649 if (Opc == AMDGPU::S_BARRIER && !ST.hasAutoWaitcntBeforeBarrier() &&
2650 !ST.hasBackOffBarrier()) {
2651 Wait = Wait.combined(WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/true));
2652 }
2653
2654 // TODO: Remove this work-around, enable the assert for Bug 457939
2655 // after fixing the scheduler. Also, the Shader Compiler code is
2656 // independent of target.
2657 if (SIInstrInfo::isCBranchVCCZRead(MI) && ST.hasReadVCCZBug() &&
2658 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2659 Wait.set(DS_CNT, 0);
2660 }
2661
2662 // Verify that the wait is actually needed.
2663 ScoreBrackets.simplifyWaitcnt(Wait);
2664
2665 // It is only necessary to insert an S_WAITCNT_DEPCTR instruction that
2666 // waits on VA_VDST if the instruction it would precede is not a VALU
2667 // instruction, since hardware handles VALU->VGPR->VALU hazards in
2668 // expert scheduling mode.
2669 if (TII.isVALU(MI))
2670 Wait.set(VA_VDST, ~0u);
2671
2672 // Since the translation for VMEM addresses occur in-order, we can apply the
2673 // XCnt if the current instruction is of VMEM type and has a memory
2674 // dependency with another VMEM instruction in flight.
2675 if (Wait.get(X_CNT) != ~0u && isVmemAccess(MI)) {
2676 ScoreBrackets.applyWaitcnt(Wait, X_CNT);
2677 Wait.set(X_CNT, ~0u);
2678 }
2679
2680 // When forcing emit, we need to skip terminators because that would break the
2681 // terminators of the MBB if we emit a waitcnt between terminators.
2682 if (ForceEmitZeroFlag && !MI.isTerminator())
2683 Wait = WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false);
2684
2685 // If we force waitcnt then update Wait accordingly.
2687 if (!ForceEmitWaitcnt[T])
2688 continue;
2689 Wait.set(T, 0);
2690 }
2691
2692 if (FlushFlags.FlushVmCnt) {
2694 Wait.set(T, 0);
2695 }
2696
2697 if (FlushFlags.FlushDsCnt && ScoreBrackets.hasPendingEvent(DS_CNT))
2698 Wait.set(DS_CNT, 0);
2699
2700 if (ForceEmitZeroLoadFlag && Wait.get(LOAD_CNT) != ~0u)
2701 Wait.set(LOAD_CNT, 0);
2702
2703 return generateWaitcnt(Wait, MI.getIterator(), *MI.getParent(), ScoreBrackets,
2704 OldWaitcntInstr);
2705}
2706
2707bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt Wait,
2709 MachineBasicBlock &Block,
2710 WaitcntBrackets &ScoreBrackets,
2711 MachineInstr *OldWaitcntInstr) {
2712 bool Modified = false;
2713
2714 if (OldWaitcntInstr)
2715 // Try to merge the required wait with preexisting waitcnt instructions.
2716 // Also erase redundant waitcnt.
2717 Modified =
2718 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr, Wait, It);
2719
2720 // ExpCnt can be merged into VINTERP.
2721 if (Wait.get(EXP_CNT) != ~0u && It != Block.instr_end() &&
2723 MachineOperand *WaitExp = TII.getNamedOperand(*It, AMDGPU::OpName::waitexp);
2724 if (Wait.get(EXP_CNT) < WaitExp->getImm()) {
2725 WaitExp->setImm(Wait.get(EXP_CNT));
2726 Modified = true;
2727 }
2728 // Apply ExpCnt before resetting it, so applyWaitcnt below sees all counts.
2729 ScoreBrackets.applyWaitcnt(Wait, EXP_CNT);
2730 Wait.set(EXP_CNT, ~0u);
2731
2732 LLVM_DEBUG(dbgs() << "generateWaitcnt\n"
2733 << "Update Instr: " << *It);
2734 }
2735
2736 if (WCG->createNewWaitcnt(Block, It, Wait, ScoreBrackets))
2737 Modified = true;
2738
2739 // Any counts that could have been applied to any existing waitcnt
2740 // instructions will have been done so, now deal with any remaining.
2741 ScoreBrackets.applyWaitcnt(Wait);
2742
2743 return Modified;
2744}
2745
2746std::optional<WaitEventType>
2747SIInsertWaitcnts::getExpertSchedulingEventType(const MachineInstr &Inst) const {
2748 if (TII.isVALU(Inst)) {
2749 // Core/Side-, DP-, XDL- and TRANS-MACC VALU instructions complete
2750 // out-of-order with respect to each other, so each of these classes
2751 // has its own event.
2752
2753 if (TII.isXDL(Inst))
2754 return VGPR_XDL_WRITE;
2755
2756 if (TII.isTRANS(Inst))
2757 return VGPR_TRANS_WRITE;
2758
2760 return VGPR_DPMACC_WRITE;
2761
2762 return VGPR_CSMACC_WRITE;
2763 }
2764
2765 // FLAT and LDS instructions may read their VGPR sources out-of-order
2766 // with respect to each other and all other VMEM instructions, so
2767 // each of these also has a separate event.
2768
2769 if (TII.isFLAT(Inst))
2770 return VGPR_FLAT_READ;
2771
2772 if (TII.isDS(Inst))
2773 return VGPR_LDS_READ;
2774
2775 if (TII.isVMEM(Inst) || TII.isVIMAGE(Inst) || TII.isVSAMPLE(Inst))
2776 return VGPR_VMEM_READ;
2777
2778 // Otherwise, no hazard.
2779
2780 return {};
2781}
2782
2783bool SIInsertWaitcnts::isVmemAccess(const MachineInstr &MI) const {
2784 return (TII.isFLAT(MI) && TII.mayAccessVMEMThroughFlat(MI)) ||
2785 (TII.isVMEM(MI) && !AMDGPU::getMUBUFIsBufferInv(MI.getOpcode()));
2786}
2787
2788// Return true if the next instruction is S_ENDPGM, following fallthrough
2789// blocks if necessary.
2790bool SIInsertWaitcnts::isNextENDPGM(MachineBasicBlock::instr_iterator It,
2791 MachineBasicBlock *Block) const {
2792 auto BlockEnd = Block->getParent()->end();
2793 auto BlockIter = Block->getIterator();
2794
2795 while (true) {
2796 if (It.isEnd()) {
2797 if (++BlockIter != BlockEnd) {
2798 It = BlockIter->instr_begin();
2799 continue;
2800 }
2801
2802 return false;
2803 }
2804
2805 if (!It->isMetaInstruction())
2806 break;
2807
2808 It++;
2809 }
2810
2811 assert(!It.isEnd());
2812
2813 return It->getOpcode() == AMDGPU::S_ENDPGM;
2814}
2815
2816// Add a wait after an instruction if architecture requirements mandate one.
2817bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2818 MachineBasicBlock &Block,
2819 WaitcntBrackets &ScoreBrackets) {
2820 AMDGPU::Waitcnt Wait;
2821 bool NeedsEndPGMCheck = false;
2822
2823 if (ST.isPreciseMemoryEnabled() && Inst.mayLoadOrStore())
2824 Wait = WCG->getAllZeroWaitcnt(Inst.mayStore() &&
2826
2827 if (TII.isAlwaysGDS(Inst.getOpcode())) {
2828 Wait.set(DS_CNT, 0);
2829 NeedsEndPGMCheck = true;
2830 }
2831
2832 ScoreBrackets.simplifyWaitcnt(Wait);
2833
2834 auto SuccessorIt = std::next(Inst.getIterator());
2835 bool Result = generateWaitcnt(Wait, SuccessorIt, Block, ScoreBrackets,
2836 /*OldWaitcntInstr=*/nullptr);
2837
2838 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &Block)) {
2839 BuildMI(Block, SuccessorIt, Inst.getDebugLoc(), TII.get(AMDGPU::S_NOP))
2840 .addImm(0);
2841 }
2842
2843 return Result;
2844}
2845
2846WaitEventSet SIInsertWaitcnts::getEventsFor(const MachineInstr &Inst) const {
2847 WaitEventSet Events;
2848 if (IsExpertMode) {
2849 if (const auto ET = getExpertSchedulingEventType(Inst))
2850 Events.insert(*ET);
2851 }
2852
2853 if (TII.isDS(Inst) && TII.usesLGKM_CNT(Inst)) {
2854 if (TII.isAlwaysGDS(Inst.getOpcode()) ||
2855 TII.hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2856 Events.insert(GDS_ACCESS);
2857 Events.insert(GDS_GPR_LOCK);
2858 } else {
2859 Events.insert(LDS_ACCESS);
2860 }
2861 } else if (TII.isFLAT(Inst)) {
2863 Events.insert(getVmemWaitEventType(Inst));
2864 } else {
2865 assert(Inst.mayLoadOrStore());
2866 if (TII.mayAccessVMEMThroughFlat(Inst)) {
2867 if (ST.hasWaitXcnt())
2868 Events.insert(VMEM_GROUP);
2869 Events.insert(getVmemWaitEventType(Inst));
2870 }
2871 if (TII.mayAccessLDSThroughFlat(Inst))
2872 Events.insert(LDS_ACCESS);
2873 }
2874 } else if (SIInstrInfo::isVMEM(Inst) &&
2876 Inst.getOpcode() == AMDGPU::BUFFER_WBL2)) {
2877 // BUFFER_WBL2 is included here because unlike invalidates, has to be
2878 // followed "S_WAITCNT vmcnt(0)" is needed after to ensure the writeback has
2879 // completed.
2880 if (ST.hasWaitXcnt())
2881 Events.insert(VMEM_GROUP);
2882 Events.insert(getVmemWaitEventType(Inst));
2883 if (ST.vmemWriteNeedsExpWaitcnt() &&
2884 (Inst.mayStore() || SIInstrInfo::isAtomicRet(Inst))) {
2885 Events.insert(VMW_GPR_LOCK);
2886 }
2887 } else if (TII.isSMRD(Inst)) {
2888 if (ST.hasWaitXcnt())
2889 Events.insert(SMEM_GROUP);
2890 Events.insert(SMEM_ACCESS);
2891 } else if (SIInstrInfo::isLDSDIR(Inst)) {
2892 Events.insert(EXP_LDS_ACCESS);
2893 } else if (SIInstrInfo::isEXP(Inst)) {
2894 unsigned Imm = TII.getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2896 Events.insert(EXP_PARAM_ACCESS);
2898 Events.insert(EXP_POS_ACCESS);
2899 else
2900 Events.insert(EXP_GPR_LOCK);
2901 } else if (SIInstrInfo::isSBarrierSCCWrite(Inst.getOpcode())) {
2902 Events.insert(SCC_WRITE);
2903 } else {
2904 switch (Inst.getOpcode()) {
2905 case AMDGPU::S_SENDMSG:
2906 case AMDGPU::S_SENDMSG_RTN_B32:
2907 case AMDGPU::S_SENDMSG_RTN_B64:
2908 case AMDGPU::S_SENDMSGHALT:
2909 Events.insert(SQ_MESSAGE);
2910 break;
2911 case AMDGPU::S_MEMTIME:
2912 case AMDGPU::S_MEMREALTIME:
2913 case AMDGPU::S_GET_BARRIER_STATE_M0:
2914 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2915 Events.insert(SMEM_ACCESS);
2916 break;
2917 }
2918 }
2919 return Events;
2920}
2921
2922void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2923 WaitcntBrackets *ScoreBrackets) {
2924
2925 WaitEventSet InstEvents = getEventsFor(Inst);
2926 for (WaitEventType E : wait_events()) {
2927 if (InstEvents.contains(E))
2928 ScoreBrackets->updateByEvent(E, Inst);
2929 }
2930
2931 if (TII.isDS(Inst) && TII.usesLGKM_CNT(Inst)) {
2932 if (TII.isAlwaysGDS(Inst.getOpcode()) ||
2933 TII.hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2934 ScoreBrackets->setPendingGDS();
2935 }
2936 } else if (TII.isFLAT(Inst)) {
2937 if (Inst.mayLoadOrStore() && TII.mayAccessVMEMThroughFlat(Inst) &&
2938 TII.mayAccessLDSThroughFlat(Inst) && !SIInstrInfo::isLDSDMA(Inst)) {
2939 // Async/LDSDMA operations have FLAT encoding but do not actually use flat
2940 // pointers. They do have two operands that each access global and LDS,
2941 // thus making it appear at this point that they are using a flat pointer.
2942 // Filter them out, and for the rest, generate a dependency on flat
2943 // pointers so that both VM and LGKM counters are flushed.
2944 ScoreBrackets->setPendingFlat();
2945 }
2946 if (SIInstrInfo::usesASYNC_CNT(Inst)) {
2947 ScoreBrackets->updateByEvent(ASYNC_ACCESS, Inst);
2948 }
2949 } else if (Inst.isCall()) {
2950 // Act as a wait on everything, but AsyncCnt is never included in such
2951 // blanket waits.
2952 ScoreBrackets->applyWaitcnt(WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false));
2953 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2954 } else if (TII.isVINTERP(Inst)) {
2955 int64_t Imm = TII.getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2956 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2957 }
2958}
2959
2960bool WaitcntBrackets::mergeScore(const MergeInfo &M, unsigned &Score,
2961 unsigned OtherScore) {
2962 unsigned MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
2963 unsigned OtherShifted =
2964 OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
2965 Score = std::max(MyShifted, OtherShifted);
2966 return OtherShifted > MyShifted;
2967}
2968
2969bool WaitcntBrackets::mergeAsyncMarks(ArrayRef<MergeInfo> MergeInfos,
2970 ArrayRef<CounterValueArray> OtherMarks) {
2971 bool StrictDom = false;
2972
2973 LLVM_DEBUG(dbgs() << "Merging async marks ...");
2974 // Early exit: both empty
2975 if (AsyncMarks.empty() && OtherMarks.empty()) {
2976 LLVM_DEBUG(dbgs() << " nothing to merge\n");
2977 return false;
2978 }
2979 LLVM_DEBUG(dbgs() << '\n');
2980
2981 // Determine maximum length needed after merging
2982 auto MaxSize = (unsigned)std::max(AsyncMarks.size(), OtherMarks.size());
2983 MaxSize = std::min(MaxSize, MaxAsyncMarks);
2984
2985 // Keep only the most recent marks within our limit.
2986 if (AsyncMarks.size() > MaxSize)
2987 AsyncMarks.erase(AsyncMarks.begin(),
2988 AsyncMarks.begin() + (AsyncMarks.size() - MaxSize));
2989
2990 // Pad with zero-filled marks if our list is shorter. Zero represents "no
2991 // pending async operations at this checkpoint" and acts as the identity
2992 // element for max() during merging. We pad at the beginning since the marks
2993 // need to be aligned in most-recent order.
2994 constexpr CounterValueArray ZeroMark{};
2995 AsyncMarks.insert(AsyncMarks.begin(), MaxSize - AsyncMarks.size(), ZeroMark);
2996
2997 LLVM_DEBUG({
2998 dbgs() << "Before merge:\n";
2999 for (const auto &Mark : AsyncMarks) {
3000 llvm::interleaveComma(Mark, dbgs());
3001 dbgs() << '\n';
3002 }
3003 dbgs() << "Other marks:\n";
3004 for (const auto &Mark : OtherMarks) {
3005 llvm::interleaveComma(Mark, dbgs());
3006 dbgs() << '\n';
3007 }
3008 });
3009
3010 // Merge element-wise using the existing mergeScore function and the
3011 // appropriate MergeInfo for each counter type. Iterate only while we have
3012 // elements in both vectors.
3013 unsigned OtherSize = OtherMarks.size();
3014 unsigned OurSize = AsyncMarks.size();
3015 unsigned MergeCount = std::min(OtherSize, OurSize);
3016 for (auto Idx : seq_inclusive<unsigned>(1, MergeCount)) {
3017 for (auto T : inst_counter_types(Context->MaxCounter)) {
3018 StrictDom |= mergeScore(MergeInfos[T], AsyncMarks[OurSize - Idx][T],
3019 OtherMarks[OtherSize - Idx][T]);
3020 }
3021 }
3022
3023 LLVM_DEBUG({
3024 dbgs() << "After merge:\n";
3025 for (const auto &Mark : AsyncMarks) {
3026 llvm::interleaveComma(Mark, dbgs());
3027 dbgs() << '\n';
3028 }
3029 });
3030
3031 return StrictDom;
3032}
3033
3034/// Merge the pending events and associater score brackets of \p Other into
3035/// this brackets status.
3036///
3037/// Returns whether the merge resulted in a change that requires tighter waits
3038/// (i.e. the merged brackets strictly dominate the original brackets).
3039bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
3040 bool StrictDom = false;
3041
3042 // Check if "other" has keys we don't have, and create default entries for
3043 // those. If they remain empty after merging, we will clean it up after.
3044 for (auto K : Other.VMem.keys())
3045 VMem.try_emplace(K);
3046 for (auto K : Other.SGPRs.keys())
3047 SGPRs.try_emplace(K);
3048
3049 // Array to store MergeInfo for each counter type
3050 MergeInfo MergeInfos[NUM_INST_CNTS];
3051
3052 for (auto T : inst_counter_types(Context->MaxCounter)) {
3053 // Merge event flags for this counter
3054 const WaitEventSet &EventsForT = Context->getWaitEvents(T);
3055 const WaitEventSet OldEvents = PendingEvents & EventsForT;
3056 const WaitEventSet OtherEvents = Other.PendingEvents & EventsForT;
3057 if (!OldEvents.contains(OtherEvents))
3058 StrictDom = true;
3059 PendingEvents |= OtherEvents;
3060
3061 // Merge scores for this counter
3062 const unsigned MyPending = ScoreUBs[T] - ScoreLBs[T];
3063 const unsigned OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
3064 const unsigned NewUB = ScoreLBs[T] + std::max(MyPending, OtherPending);
3065 if (NewUB < ScoreLBs[T])
3066 report_fatal_error("waitcnt score overflow");
3067
3068 MergeInfo &M = MergeInfos[T];
3069 M.OldLB = ScoreLBs[T];
3070 M.OtherLB = Other.ScoreLBs[T];
3071 M.MyShift = NewUB - ScoreUBs[T];
3072 M.OtherShift = NewUB - Other.ScoreUBs[T];
3073
3074 ScoreUBs[T] = NewUB;
3075
3076 StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]);
3077
3078 if (T == DS_CNT)
3079 StrictDom |= mergeScore(M, LastGDS, Other.LastGDS);
3080
3081 if (T == KM_CNT) {
3082 StrictDom |= mergeScore(M, SCCScore, Other.SCCScore);
3083 if (Other.hasPendingEvent(SCC_WRITE)) {
3084 if (!OldEvents.contains(SCC_WRITE)) {
3085 PendingSCCWrite = Other.PendingSCCWrite;
3086 } else if (PendingSCCWrite != Other.PendingSCCWrite) {
3087 PendingSCCWrite = nullptr;
3088 }
3089 }
3090 }
3091
3092 for (auto &[RegID, Info] : VMem)
3093 StrictDom |= mergeScore(M, Info.Scores[T], Other.getVMemScore(RegID, T));
3094
3095 if (isSmemCounter(T)) {
3096 for (auto &[RegID, Info] : SGPRs) {
3097 auto It = Other.SGPRs.find(RegID);
3098 unsigned OtherScore = (It != Other.SGPRs.end()) ? It->second.get(T) : 0;
3099 StrictDom |= mergeScore(M, Info.get(T), OtherScore);
3100 }
3101 }
3102 }
3103
3104 for (auto &[TID, Info] : VMem) {
3105 if (auto It = Other.VMem.find(TID); It != Other.VMem.end()) {
3106 unsigned char NewVmemTypes = Info.VMEMTypes | It->second.VMEMTypes;
3107 StrictDom |= NewVmemTypes != Info.VMEMTypes;
3108 Info.VMEMTypes = NewVmemTypes;
3109 }
3110 }
3111
3112 StrictDom |= mergeAsyncMarks(MergeInfos, Other.AsyncMarks);
3113 for (auto T : inst_counter_types(Context->MaxCounter))
3114 StrictDom |= mergeScore(MergeInfos[T], AsyncScore[T], Other.AsyncScore[T]);
3115
3116 purgeEmptyTrackingData();
3117 return StrictDom;
3118}
3119
3120static bool isWaitInstr(MachineInstr &Inst) {
3121 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(Inst.getOpcode());
3122 return Opcode == AMDGPU::S_WAITCNT ||
3123 (Opcode == AMDGPU::S_WAITCNT_VSCNT && Inst.getOperand(0).isReg() &&
3124 Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL) ||
3125 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
3126 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
3127 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
3128 Opcode == AMDGPU::WAIT_ASYNCMARK ||
3129 counterTypeForInstr(Opcode).has_value();
3130}
3131
3132void SIInsertWaitcnts::setSchedulingMode(MachineBasicBlock &MBB,
3134 bool ExpertMode) const {
3135 const unsigned EncodedReg = AMDGPU::Hwreg::HwregEncoding::encode(
3137 BuildMI(MBB, I, DebugLoc(), TII.get(AMDGPU::S_SETREG_IMM32_B32))
3138 .addImm(ExpertMode ? 2 : 0)
3139 .addImm(EncodedReg);
3140}
3141
3142namespace {
3143// TODO: Remove this work-around after fixing the scheduler.
3144// There are two reasons why vccz might be incorrect; see ST.hasReadVCCZBug()
3145// and ST.partialVCCWritesUpdateVCCZ().
3146// i. VCCZBug: There is a hardware bug on CI/SI where SMRD instruction may
3147// corrupt vccz bit, so when we detect that an instruction may read from
3148// a corrupt vccz bit, we need to:
3149// 1. Insert s_waitcnt lgkm(0) to wait for all outstanding SMRD
3150// operations to complete.
3151// 2. Recompute the correct value of vccz by writing the current value
3152// of vcc back to vcc.
3153// ii. Partial writes to vcc don't update vccz, so we need to recompute the
3154// correct value of vccz by reading vcc and writing it back to vcc.
3155// No waitcnt is needed in this case.
3156class VCCZWorkaround {
3157 const WaitcntBrackets &ScoreBrackets;
3158 const GCNSubtarget &ST;
3159 const SIInstrInfo &TII;
3160 const SIRegisterInfo &TRI;
3161 bool VCCZCorruptionBug = false;
3162 bool VCCZNotUpdatedByPartialWrites = false;
3163 /// vccz could be incorrect at a basic block boundary if a predecessor wrote
3164 /// to vcc and then issued an smem load, so initialize to true.
3165 bool MustRecomputeVCCZ = true;
3166
3167public:
3168 VCCZWorkaround(const WaitcntBrackets &ScoreBrackets, const GCNSubtarget &ST,
3169 const SIInstrInfo &TII, const SIRegisterInfo &TRI)
3170 : ScoreBrackets(ScoreBrackets), ST(ST), TII(TII), TRI(TRI) {
3171 VCCZCorruptionBug = ST.hasReadVCCZBug();
3172 VCCZNotUpdatedByPartialWrites = !ST.partialVCCWritesUpdateVCCZ();
3173 }
3174 /// If \p MI reads vccz and we must recompute it based on MustRecomputeVCCZ,
3175 /// then emit a vccz recompute instruction before \p MI. This needs to be
3176 /// called on every instruction in the basic block because it also tracks the
3177 /// state and updates MustRecomputeVCCZ accordingly. Returns true if it
3178 /// modified the IR.
3179 bool tryRecomputeVCCZ(MachineInstr &MI) {
3180 // No need to run this if neither bug is present.
3181 if (!VCCZCorruptionBug && !VCCZNotUpdatedByPartialWrites)
3182 return false;
3183
3184 // If MI is an SMEM and it can corrupt vccz on this target, then we need
3185 // both to emit a waitcnt and to recompute vccz.
3186 // But we don't actually emit a waitcnt here. This is done in
3187 // generateWaitcntInstBefore() because it tracks all the necessary waitcnt
3188 // state, and can either skip emitting a waitcnt if there is already one in
3189 // the IR, or emit an "optimized" combined waitcnt.
3190 // If this is an smem read, it could complete and clobber vccz at any time.
3191 MustRecomputeVCCZ |= VCCZCorruptionBug && TII.isSMRD(MI);
3192
3193 // If the target partial vcc writes don't update vccz, and MI is such an
3194 // instruction then we must recompute vccz.
3195 // Note: We are using PartiallyWritesToVCCOpt optional to avoid calling
3196 // `definesRegister()` more than needed, because it's not very cheap.
3197 std::optional<bool> PartiallyWritesToVCCOpt;
3198 auto PartiallyWritesToVCC = [](MachineInstr &MI) {
3199 return MI.definesRegister(AMDGPU::VCC_LO, /*TRI=*/nullptr) ||
3200 MI.definesRegister(AMDGPU::VCC_HI, /*TRI=*/nullptr);
3201 };
3202 if (VCCZNotUpdatedByPartialWrites) {
3203 PartiallyWritesToVCCOpt = PartiallyWritesToVCC(MI);
3204 // If this is a partial VCC write but won't update vccz, then we must
3205 // recompute vccz.
3206 MustRecomputeVCCZ |= *PartiallyWritesToVCCOpt;
3207 }
3208
3209 // If MI is a vcc write with no pending smem, or there is a pending smem
3210 // but the target does not suffer from the vccz corruption bug, then we
3211 // don't need to recompute vccz as this write will recompute it anyway.
3212 if (!ScoreBrackets.hasPendingEvent(SMEM_ACCESS) || !VCCZCorruptionBug) {
3213 // Compute PartiallyWritesToVCCOpt if we haven't done so already.
3214 if (!PartiallyWritesToVCCOpt)
3215 PartiallyWritesToVCCOpt = PartiallyWritesToVCC(MI);
3216 bool FullyWritesToVCC = !*PartiallyWritesToVCCOpt &&
3217 MI.definesRegister(AMDGPU::VCC, /*TRI=*/nullptr);
3218 // If we write to the full vcc or we write partially and the target
3219 // updates vccz on partial writes, then vccz will be updated correctly.
3220 bool UpdatesVCCZ = FullyWritesToVCC || (!VCCZNotUpdatedByPartialWrites &&
3221 *PartiallyWritesToVCCOpt);
3222 if (UpdatesVCCZ)
3223 MustRecomputeVCCZ = false;
3224 }
3225
3226 // If MI is a branch that reads VCCZ then emit a waitcnt and a vccz
3227 // restore instruction if either is needed.
3228 if (SIInstrInfo::isCBranchVCCZRead(MI) && MustRecomputeVCCZ) {
3229 // Recompute the vccz bit. Any time a value is written to vcc, the vccz
3230 // bit is updated, so we can restore the bit by reading the value of vcc
3231 // and then writing it back to the register.
3232 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
3233 TII.get(ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
3234 TRI.getVCC())
3235 .addReg(TRI.getVCC());
3236 MustRecomputeVCCZ = false;
3237 return true;
3238 }
3239 return false;
3240 }
3241};
3242
3243} // namespace
3244
3245// Generate s_waitcnt instructions where needed.
3246bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
3247 MachineBasicBlock &Block,
3248 WaitcntBrackets &ScoreBrackets) {
3249 bool Modified = false;
3250
3251 LLVM_DEBUG({
3252 dbgs() << "*** Begin Block: ";
3253 Block.printName(dbgs());
3254 ScoreBrackets.dump();
3255 });
3256 VCCZWorkaround VCCZW(ScoreBrackets, ST, TII, TRI);
3257
3258 // Walk over the instructions.
3259 MachineInstr *OldWaitcntInstr = nullptr;
3260
3261 // NOTE: We may append instrs after Inst while iterating.
3262 for (MachineBasicBlock::instr_iterator Iter = Block.instr_begin(),
3263 E = Block.instr_end();
3264 Iter != E; ++Iter) {
3265 MachineInstr &Inst = *Iter;
3266 if (Inst.isMetaInstruction())
3267 continue;
3268 // Track pre-existing waitcnts that were added in earlier iterations or by
3269 // the memory legalizer.
3270 if (isWaitInstr(Inst) ||
3271 (IsExpertMode && Inst.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR)) {
3272 if (!OldWaitcntInstr)
3273 OldWaitcntInstr = &Inst;
3274 continue;
3275 }
3276
3277 PreheaderFlushFlags FlushFlags;
3278 if (Block.getFirstTerminator() == Inst)
3279 FlushFlags = isPreheaderToFlush(Block, ScoreBrackets);
3280
3281 // Generate an s_waitcnt instruction to be placed before Inst, if needed.
3282 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
3283 FlushFlags);
3284 OldWaitcntInstr = nullptr;
3285
3286 if (Inst.getOpcode() == AMDGPU::ASYNCMARK) {
3287 // Asyncmarks record the current wait state and so should not allow
3288 // waitcnts that occur after them to be merged into waitcnts that occur
3289 // before.
3290 ScoreBrackets.recordAsyncMark(Inst);
3291 continue;
3292 }
3293
3294 if (TII.isSMRD(Inst)) {
3295 for (const MachineMemOperand *Memop : Inst.memoperands()) {
3296 // No need to handle invariant loads when avoiding WAR conflicts, as
3297 // there cannot be a vector store to the same memory location.
3298 if (!Memop->isInvariant()) {
3299 const Value *Ptr = Memop->getValue();
3300 SLoadAddresses.insert(std::pair(Ptr, Inst.getParent()));
3301 }
3302 }
3303 }
3304
3305 updateEventWaitcntAfter(Inst, &ScoreBrackets);
3306
3307 // Note: insertForcedWaitAfter() may add instrs after Iter that need to be
3308 // visited by the loop.
3309 Modified |= insertForcedWaitAfter(Inst, Block, ScoreBrackets);
3310
3311 LLVM_DEBUG({
3312 Inst.print(dbgs());
3313 ScoreBrackets.dump();
3314 });
3315
3316 // If the target suffers from the vccz bugs, this may emit the necessary
3317 // vccz recompute instruction before \p Inst if needed.
3318 Modified |= VCCZW.tryRecomputeVCCZ(Inst);
3319 }
3320
3321 // Flush counters at the end of the block if needed (for preheaders with no
3322 // terminator).
3323 AMDGPU::Waitcnt Wait;
3324 if (Block.getFirstTerminator() == Block.end()) {
3325 PreheaderFlushFlags FlushFlags = isPreheaderToFlush(Block, ScoreBrackets);
3326 if (FlushFlags.FlushVmCnt) {
3327 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
3328 Wait.set(LOAD_CNT, 0);
3329 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
3330 Wait.set(SAMPLE_CNT, 0);
3331 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
3332 Wait.set(BVH_CNT, 0);
3333 }
3334 if (FlushFlags.FlushDsCnt && ScoreBrackets.hasPendingEvent(DS_CNT))
3335 Wait.set(DS_CNT, 0);
3336 }
3337
3338 // Combine or remove any redundant waitcnts at the end of the block.
3339 Modified |= generateWaitcnt(Wait, Block.instr_end(), Block, ScoreBrackets,
3340 OldWaitcntInstr);
3341
3342 LLVM_DEBUG({
3343 dbgs() << "*** End Block: ";
3344 Block.printName(dbgs());
3345 ScoreBrackets.dump();
3346 });
3347
3348 return Modified;
3349}
3350
3351bool SIInsertWaitcnts::removeRedundantSoftXcnts(MachineBasicBlock &Block) {
3352 if (Block.size() <= 1)
3353 return false;
3354 // The Memory Legalizer conservatively inserts a soft xcnt before each
3355 // atomic RMW operation. However, for sequences of back-to-back atomic
3356 // RMWs, only the first s_wait_xcnt insertion is necessary. Optimize away
3357 // the redundant soft xcnts.
3358 bool Modified = false;
3359 // Remember the last atomic with a soft xcnt right before it.
3360 MachineInstr *LastAtomicWithSoftXcnt = nullptr;
3361
3362 for (MachineInstr &MI : drop_begin(Block)) {
3363 // Ignore last atomic if non-LDS VMEM and SMEM.
3364 bool IsLDS =
3365 TII.isDS(MI) || (TII.isFLAT(MI) && TII.mayAccessLDSThroughFlat(MI));
3366 if (!IsLDS && (MI.mayLoad() ^ MI.mayStore()))
3367 LastAtomicWithSoftXcnt = nullptr;
3368
3369 bool IsAtomicRMW = (MI.getDesc().TSFlags & SIInstrFlags::maybeAtomic) &&
3370 MI.mayLoad() && MI.mayStore();
3371 MachineInstr &PrevMI = *MI.getPrevNode();
3372 // This is an atomic with a soft xcnt.
3373 if (PrevMI.getOpcode() == AMDGPU::S_WAIT_XCNT_soft && IsAtomicRMW) {
3374 // If we have already found an atomic with a soft xcnt, remove this soft
3375 // xcnt as it's redundant.
3376 if (LastAtomicWithSoftXcnt) {
3377 PrevMI.eraseFromParent();
3378 Modified = true;
3379 }
3380 LastAtomicWithSoftXcnt = &MI;
3381 }
3382 }
3383 return Modified;
3384}
3385
3386// Return flags indicating which counters should be flushed in the preheader.
3387PreheaderFlushFlags
3388SIInsertWaitcnts::isPreheaderToFlush(MachineBasicBlock &MBB,
3389 const WaitcntBrackets &ScoreBrackets) {
3390 auto [Iterator, IsInserted] =
3391 PreheadersToFlush.try_emplace(&MBB, PreheaderFlushFlags());
3392 if (!IsInserted)
3393 return Iterator->second;
3394
3395 MachineBasicBlock *Succ = MBB.getSingleSuccessor();
3396 if (!Succ)
3397 return PreheaderFlushFlags();
3398
3399 MachineLoop *Loop = MLI.getLoopFor(Succ);
3400 if (!Loop)
3401 return PreheaderFlushFlags();
3402
3403 if (Loop->getLoopPreheader() == &MBB) {
3404 Iterator->second = getPreheaderFlushFlags(Loop, ScoreBrackets);
3405 return Iterator->second;
3406 }
3407
3408 return PreheaderFlushFlags();
3409}
3410
3411bool SIInsertWaitcnts::isVMEMOrFlatVMEM(const MachineInstr &MI) const {
3413 return TII.mayAccessVMEMThroughFlat(MI);
3414 return SIInstrInfo::isVMEM(MI);
3415}
3416
3417bool SIInsertWaitcnts::isDSRead(const MachineInstr &MI) const {
3418 return SIInstrInfo::isDS(MI) && MI.mayLoad() && !MI.mayStore();
3419}
3420
3421// Check if instruction is a store to LDS that is counted via DSCNT
3422// (where that counter exists).
3423bool SIInsertWaitcnts::mayStoreIncrementingDSCNT(const MachineInstr &MI) const {
3424 return MI.mayStore() && SIInstrInfo::isDS(MI);
3425}
3426
3427// Return flags indicating which counters should be flushed in the preheader of
3428// the given loop. We currently decide to flush in the following situations:
3429// For VMEM (FlushVmCnt):
3430// 1. The loop contains vmem store(s), no vmem load and at least one use of a
3431// vgpr containing a value that is loaded outside of the loop. (Only on
3432// targets with no vscnt counter).
3433// 2. The loop contains vmem load(s), but the loaded values are not used in the
3434// loop, and at least one use of a vgpr containing a value that is loaded
3435// outside of the loop.
3436// For DS (FlushDsCnt, GFX12+ only):
3437// 3. The loop contains no DS reads, and at least one use of a vgpr containing
3438// a value that is DS read outside of the loop.
3439// 4. The loop contains DS read(s), loaded values are not used in the same
3440// iteration but in the next iteration (prefetch pattern), and at least one
3441// use of a vgpr containing a value that is DS read outside of the loop.
3442// Flushing in preheader reduces wait overhead if the wait requirement in
3443// iteration 1 would otherwise be more strict (but unfortunately preheader
3444// flush decision is taken before knowing that).
3445// 5. (Single-block loops only) The loop has DS prefetch reads with flush point
3446// tracking. Some DS reads may be used in the same iteration (creating
3447// "flush points"), but others remain unflushed at the backedge. When a DS
3448// read is consumed in the same iteration, it and all prior reads are
3449// "flushed" (FIFO order). No DS writes are allowed in the loop.
3450// TODO: Find a way to extend to multi-block loops.
3451PreheaderFlushFlags
3452SIInsertWaitcnts::getPreheaderFlushFlags(MachineLoop *ML,
3453 const WaitcntBrackets &Brackets) {
3454 PreheaderFlushFlags Flags;
3455 bool HasVMemLoad = false;
3456 bool HasVMemStore = false;
3457 bool UsesVgprVMEMLoadedOutside = false;
3458 bool UsesVgprDSReadOutside = false;
3459 bool VMemInvalidated = false;
3460 // DS optimization only applies to GFX12+ where DS_CNT is separate.
3461 // Tracking status for "no DS read in loop" or "pure DS prefetch
3462 // (use only in next iteration)".
3463 bool TrackSimpleDSOpt = ST.hasExtendedWaitCounts();
3464 DenseSet<MCRegUnit> VgprUse;
3465 DenseSet<MCRegUnit> VgprDefVMEM;
3466 DenseSet<MCRegUnit> VgprDefDS;
3467
3468 // Track DS reads for prefetch pattern with flush points (single-block only).
3469 // Keeps track of the last DS read (position counted from the top of the loop)
3470 // to each VGPR. Read is considered consumed (and thus needs flushing) if
3471 // the dest register has a use or is overwritten (by any later opertions).
3472 DenseMap<MCRegUnit, unsigned> LastDSReadPositionMap;
3473 unsigned DSReadPosition = 0;
3474 bool IsSingleBlock = ML->getNumBlocks() == 1;
3475 bool TrackDSFlushPoint = ST.hasExtendedWaitCounts() && IsSingleBlock;
3476 unsigned LastDSFlushPosition = 0;
3477
3478 for (MachineBasicBlock *MBB : ML->blocks()) {
3479 for (MachineInstr &MI : *MBB) {
3480 if (isVMEMOrFlatVMEM(MI)) {
3481 HasVMemLoad |= MI.mayLoad();
3482 HasVMemStore |= MI.mayStore();
3483 }
3484 // TODO: Can we relax DSStore check? There may be cases where
3485 // these DS stores are drained prior to the end of MBB (or loop).
3486 if (mayStoreIncrementingDSCNT(MI)) {
3487 // Early exit if none of the optimizations are feasible.
3488 // Otherwise, set tracking status appropriately and continue.
3489 if (VMemInvalidated)
3490 return Flags;
3491 TrackSimpleDSOpt = false;
3492 TrackDSFlushPoint = false;
3493 }
3494 bool IsDSRead = isDSRead(MI);
3495 if (IsDSRead)
3496 ++DSReadPosition;
3497
3498 // Helper: if RU has a pending DS read, update LastDSFlushPosition
3499 auto updateDSReadFlushTracking = [&](MCRegUnit RU) {
3500 if (!TrackDSFlushPoint)
3501 return;
3502 if (auto It = LastDSReadPositionMap.find(RU);
3503 It != LastDSReadPositionMap.end()) {
3504 // RU defined by DSRead is used or overwritten. Need to complete
3505 // the read, if not already implied by a later DSRead (to any RU)
3506 // needing to complete in FIFO order.
3507 LastDSFlushPosition = std::max(LastDSFlushPosition, It->second);
3508 }
3509 };
3510
3511 for (const MachineOperand &Op : MI.all_uses()) {
3512 if (Op.isDebug() || !TRI.isVectorRegister(MRI, Op.getReg()))
3513 continue;
3514 // Vgpr use
3515 for (MCRegUnit RU : TRI.regunits(Op.getReg().asMCReg())) {
3516 // If we find a register that is loaded inside the loop, 1. and 2.
3517 // are invalidated.
3518 if (VgprDefVMEM.contains(RU))
3519 VMemInvalidated = true;
3520
3521 // Check for DS reads used inside the loop
3522 if (VgprDefDS.contains(RU))
3523 TrackSimpleDSOpt = false;
3524
3525 // Early exit if all optimizations are invalidated
3526 if (VMemInvalidated && !TrackSimpleDSOpt && !TrackDSFlushPoint)
3527 return Flags;
3528
3529 // Check for flush points (DS read used in same iteration)
3530 updateDSReadFlushTracking(RU);
3531
3532 VgprUse.insert(RU);
3533 // Check if this register has a pending VMEM load from outside the
3534 // loop (value loaded outside and used inside).
3535 VMEMID ID = toVMEMID(RU);
3536 if (Brackets.hasPendingVMEM(ID, LOAD_CNT) ||
3537 Brackets.hasPendingVMEM(ID, SAMPLE_CNT) ||
3538 Brackets.hasPendingVMEM(ID, BVH_CNT))
3539 UsesVgprVMEMLoadedOutside = true;
3540 // Check if loaded outside the loop via DS (not VMEM/FLAT).
3541 // Only consider it a DS read if there's no pending VMEM load for
3542 // this register, since FLAT can set both counters.
3543 else if (Brackets.hasPendingVMEM(ID, DS_CNT))
3544 UsesVgprDSReadOutside = true;
3545 }
3546 }
3547
3548 // VMem load vgpr def
3549 if (isVMEMOrFlatVMEM(MI) && MI.mayLoad()) {
3550 for (const MachineOperand &Op : MI.all_defs()) {
3551 for (MCRegUnit RU : TRI.regunits(Op.getReg().asMCReg())) {
3552 // If we find a register that is loaded inside the loop, 1. and 2.
3553 // are invalidated.
3554 if (VgprUse.contains(RU))
3555 VMemInvalidated = true;
3556 VgprDefVMEM.insert(RU);
3557 }
3558 }
3559 // Early exit if all optimizations are invalidated
3560 if (VMemInvalidated && !TrackSimpleDSOpt && !TrackDSFlushPoint)
3561 return Flags;
3562 }
3563
3564 // DS read vgpr def
3565 // Note: Unlike VMEM, we DON'T invalidate when VgprUse.contains(RegNo).
3566 // If USE comes before DEF, it's the prefetch pattern (use value from
3567 // previous iteration, read for next iteration). We should still flush
3568 // in preheader so iteration 1 doesn't need to wait inside the loop.
3569 // Only invalidate when DEF comes before USE (same-iteration consumption,
3570 // checked above when processing uses).
3571 if (IsDSRead || TrackDSFlushPoint) {
3572 for (const MachineOperand &Op : MI.all_defs()) {
3573 if (!TRI.isVectorRegister(MRI, Op.getReg()))
3574 continue;
3575 for (MCRegUnit RU : TRI.regunits(Op.getReg().asMCReg())) {
3576 // Check for overwrite of pending DS read (flush point) by any
3577 // instruction
3578 updateDSReadFlushTracking(RU);
3579 if (IsDSRead) {
3580 VgprDefDS.insert(RU);
3581 if (TrackDSFlushPoint)
3582 LastDSReadPositionMap[RU] = DSReadPosition;
3583 }
3584 }
3585 }
3586 }
3587 }
3588 }
3589
3590 // VMEM flush decision
3591 if (!VMemInvalidated && UsesVgprVMEMLoadedOutside &&
3592 ((!ST.hasVscnt() && HasVMemStore && !HasVMemLoad) ||
3593 (HasVMemLoad && ST.hasVmemWriteVgprInOrder())))
3594 Flags.FlushVmCnt = true;
3595
3596 // DS flush decision:
3597 // Simple DS Opt: flush if loop uses DS read values from outside
3598 // and either has no DS reads in the loop, or DS reads whose results
3599 // are not used in the loop.
3600 bool SimpleDSOpt = TrackSimpleDSOpt && UsesVgprDSReadOutside;
3601 // Prefetch with flush points: some DS reads used in same iteration,
3602 // but unflushed reads remain at backedge
3603 bool HasUnflushedDSReads = DSReadPosition > LastDSFlushPosition;
3604 bool DSFlushPointPrefetch =
3605 TrackDSFlushPoint && UsesVgprDSReadOutside && HasUnflushedDSReads;
3606
3607 if (SimpleDSOpt || DSFlushPointPrefetch)
3608 Flags.FlushDsCnt = true;
3609
3610 return Flags;
3611}
3612
3613bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
3614 auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
3615 auto &PDT =
3616 getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
3617 AliasAnalysis *AA = nullptr;
3618 if (auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
3619 AA = &AAR->getAAResults();
3620
3621 return SIInsertWaitcnts(MLI, PDT, AA, MF).run();
3622}
3623
3624PreservedAnalyses
3627 auto &MLI = MFAM.getResult<MachineLoopAnalysis>(MF);
3628 auto &PDT = MFAM.getResult<MachinePostDominatorTreeAnalysis>(MF);
3630 .getManager()
3631 .getCachedResult<AAManager>(MF.getFunction());
3632
3633 if (!SIInsertWaitcnts(MLI, PDT, AA, MF).run())
3634 return PreservedAnalyses::all();
3635
3638 .preserve<AAManager>();
3639}
3640
3641bool SIInsertWaitcnts::run() {
3643
3645
3646 // Initialize hardware limits first, as they're needed by the generators.
3647 Limits = AMDGPU::HardwareLimits(IV);
3648
3649 if (ST.hasExtendedWaitCounts()) {
3650 IsExpertMode = ST.hasExpertSchedulingMode() &&
3651 (ExpertSchedulingModeFlag.getNumOccurrences()
3653 : MF.getFunction()
3654 .getFnAttribute("amdgpu-expert-scheduling-mode")
3655 .getValueAsBool());
3656 MaxCounter = IsExpertMode ? NUM_EXPERT_INST_CNTS : NUM_EXTENDED_INST_CNTS;
3657 // Initialize WCG per MF. It contains state that depends on MF attributes.
3658 WCG = std::make_unique<WaitcntGeneratorGFX12Plus>(MF, MaxCounter, Limits,
3659 IsExpertMode);
3660 } else {
3661 MaxCounter = NUM_NORMAL_INST_CNTS;
3662 // Initialize WCG per MF. It contains state that depends on MF attributes.
3663 WCG = std::make_unique<WaitcntGeneratorPreGFX12>(MF, NUM_NORMAL_INST_CNTS,
3664 Limits);
3665 }
3666
3667 SmemAccessCounter = getCounterFromEvent(SMEM_ACCESS);
3668
3669 bool Modified = false;
3670
3671 MachineBasicBlock &EntryBB = MF.front();
3672
3673 if (!MFI->isEntryFunction()) {
3674 // Wait for any outstanding memory operations that the input registers may
3675 // depend on. We can't track them and it's better to do the wait after the
3676 // costly call sequence.
3677
3678 // TODO: Could insert earlier and schedule more liberally with operations
3679 // that only use caller preserved registers.
3681 while (I != EntryBB.end() && I->isMetaInstruction())
3682 ++I;
3683
3684 if (ST.hasExtendedWaitCounts()) {
3685 BuildMI(EntryBB, I, DebugLoc(), TII.get(AMDGPU::S_WAIT_LOADCNT_DSCNT))
3686 .addImm(0);
3688 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT ||
3689 CT == ASYNC_CNT)
3690 continue;
3691
3692 if (!ST.hasImageInsts() &&
3693 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
3694 continue;
3695
3696 BuildMI(EntryBB, I, DebugLoc(),
3697 TII.get(instrsForExtendedCounterTypes[CT]))
3698 .addImm(0);
3699 }
3700 if (IsExpertMode) {
3701 unsigned Enc = AMDGPU::DepCtr::encodeFieldVaVdst(0, ST);
3703 BuildMI(EntryBB, I, DebugLoc(), TII.get(AMDGPU::S_WAITCNT_DEPCTR))
3704 .addImm(Enc);
3705 }
3706 } else {
3707 BuildMI(EntryBB, I, DebugLoc(), TII.get(AMDGPU::S_WAITCNT)).addImm(0);
3708 }
3709
3710 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(this);
3711 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
3712 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
3713
3714 Modified = true;
3715 }
3716
3717 // Keep iterating over the blocks in reverse post order, inserting and
3718 // updating s_waitcnt where needed, until a fix point is reached.
3719 for (auto *MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
3720 BlockInfos.try_emplace(MBB);
3721
3722 std::unique_ptr<WaitcntBrackets> Brackets;
3723 bool Repeat;
3724 do {
3725 Repeat = false;
3726
3727 for (auto BII = BlockInfos.begin(), BIE = BlockInfos.end(); BII != BIE;
3728 ++BII) {
3729 MachineBasicBlock *MBB = BII->first;
3730 BlockInfo &BI = BII->second;
3731 if (!BI.Dirty)
3732 continue;
3733
3734 if (BI.Incoming) {
3735 if (!Brackets)
3736 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
3737 else
3738 *Brackets = *BI.Incoming;
3739 } else {
3740 if (!Brackets) {
3741 Brackets = std::make_unique<WaitcntBrackets>(this);
3742 } else {
3743 // Reinitialize in-place. N.B. do not do this by assigning from a
3744 // temporary because the WaitcntBrackets class is large and it could
3745 // cause this function to use an unreasonable amount of stack space.
3746 Brackets->~WaitcntBrackets();
3747 new (Brackets.get()) WaitcntBrackets(this);
3748 }
3749 }
3750
3751 if (ST.hasWaitXcnt())
3752 Modified |= removeRedundantSoftXcnts(*MBB);
3753 Modified |= insertWaitcntInBlock(MF, *MBB, *Brackets);
3754 BI.Dirty = false;
3755
3756 if (Brackets->hasPendingEvent()) {
3757 BlockInfo *MoveBracketsToSucc = nullptr;
3758 for (MachineBasicBlock *Succ : MBB->successors()) {
3759 auto *SuccBII = BlockInfos.find(Succ);
3760 BlockInfo &SuccBI = SuccBII->second;
3761 if (!SuccBI.Incoming) {
3762 SuccBI.Dirty = true;
3763 if (SuccBII <= BII) {
3764 LLVM_DEBUG(dbgs() << "Repeat on backedge without merge\n");
3765 Repeat = true;
3766 }
3767 if (!MoveBracketsToSucc) {
3768 MoveBracketsToSucc = &SuccBI;
3769 } else {
3770 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
3771 }
3772 } else {
3773 LLVM_DEBUG({
3774 dbgs() << "Try to merge ";
3775 MBB->printName(dbgs());
3776 dbgs() << " into ";
3777 Succ->printName(dbgs());
3778 dbgs() << '\n';
3779 });
3780 if (SuccBI.Incoming->merge(*Brackets)) {
3781 SuccBI.Dirty = true;
3782 if (SuccBII <= BII) {
3783 LLVM_DEBUG(dbgs() << "Repeat on backedge with merge\n");
3784 Repeat = true;
3785 }
3786 }
3787 }
3788 }
3789 if (MoveBracketsToSucc)
3790 MoveBracketsToSucc->Incoming = std::move(Brackets);
3791 }
3792 }
3793 } while (Repeat);
3794
3795 if (ST.hasScalarStores()) {
3796 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
3797 bool HaveScalarStores = false;
3798
3799 for (MachineBasicBlock &MBB : MF) {
3800 for (MachineInstr &MI : MBB) {
3801 if (!HaveScalarStores && TII.isScalarStore(MI))
3802 HaveScalarStores = true;
3803
3804 if (MI.getOpcode() == AMDGPU::S_ENDPGM ||
3805 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
3806 EndPgmBlocks.push_back(&MBB);
3807 }
3808 }
3809
3810 if (HaveScalarStores) {
3811 // If scalar writes are used, the cache must be flushed or else the next
3812 // wave to reuse the same scratch memory can be clobbered.
3813 //
3814 // Insert s_dcache_wb at wave termination points if there were any scalar
3815 // stores, and only if the cache hasn't already been flushed. This could
3816 // be improved by looking across blocks for flushes in postdominating
3817 // blocks from the stores but an explicitly requested flush is probably
3818 // very rare.
3819 for (MachineBasicBlock *MBB : EndPgmBlocks) {
3820 bool SeenDCacheWB = false;
3821
3822 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
3823 I != E; ++I) {
3824 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
3825 SeenDCacheWB = true;
3826 else if (TII.isScalarStore(*I))
3827 SeenDCacheWB = false;
3828
3829 // FIXME: It would be better to insert this before a waitcnt if any.
3830 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
3831 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
3832 !SeenDCacheWB) {
3833 Modified = true;
3834 BuildMI(*MBB, I, I->getDebugLoc(), TII.get(AMDGPU::S_DCACHE_WB));
3835 }
3836 }
3837 }
3838 }
3839 }
3840
3841 if (IsExpertMode) {
3842 // Enable expert scheduling on function entry. To satisfy ABI requirements
3843 // and to allow calls between function with different expert scheduling
3844 // settings, disable it around calls and before returns.
3845
3847 while (I != EntryBB.end() && I->isMetaInstruction())
3848 ++I;
3849 setSchedulingMode(EntryBB, I, true);
3850
3851 for (MachineInstr *MI : CallInsts) {
3852 MachineBasicBlock &MBB = *MI->getParent();
3853 setSchedulingMode(MBB, MI, false);
3854 setSchedulingMode(MBB, std::next(MI->getIterator()), true);
3855 }
3856
3857 for (MachineInstr *MI : ReturnInsts)
3858 setSchedulingMode(*MI->getParent(), MI, false);
3859
3860 Modified = true;
3861 }
3862
3863 // Deallocate the VGPRs before previously identified S_ENDPGM instructions.
3864 // This is done in different ways depending on how the VGPRs were allocated
3865 // (i.e. whether we're in dynamic VGPR mode or not).
3866 // Skip deallocation if kernel is waveslot limited vs VGPR limited. A short
3867 // waveslot limited kernel runs slower with the deallocation.
3868 if (!WCG->isOptNone() && MFI->isDynamicVGPREnabled()) {
3869 for (auto [MI, _] : EndPgmInsts) {
3870 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
3871 TII.get(AMDGPU::S_ALLOC_VGPR))
3872 .addImm(0);
3873 Modified = true;
3874 }
3875 } else if (!WCG->isOptNone() &&
3876 ST.getGeneration() >= AMDGPUSubtarget::GFX11 &&
3877 (MF.getFrameInfo().hasCalls() ||
3878 ST.getOccupancyWithNumVGPRs(
3879 TRI.getNumUsedPhysRegs(MRI, AMDGPU::VGPR_32RegClass),
3880 /*IsDynamicVGPR=*/false) <
3882 for (auto [MI, Flag] : EndPgmInsts) {
3883 if (Flag) {
3884 if (ST.requiresNopBeforeDeallocVGPRs()) {
3885 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
3886 TII.get(AMDGPU::S_NOP))
3887 .addImm(0);
3888 }
3889 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
3890 TII.get(AMDGPU::S_SENDMSG))
3892 Modified = true;
3893 }
3894 }
3895 }
3896
3897 return Modified;
3898}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
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)
#define _
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)
#define AMDGPU_EVENT_NAME(Name)
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 > ExpertSchedulingModeFlag("amdgpu-expert-scheduling-mode", cl::desc("Enable expert scheduling mode 2 for all functions (GFX12+ only)"), cl::init(false), cl::Hidden)
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)
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:487
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.
Represents the counter values to wait for in an s_waitcnt instruction.
unsigned get(InstCounterType T) const
void set(InstCounterType T, unsigned Val)
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
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
LLVM_ABI bool getValueAsBool() const
Return the attribute's value as a boolean.
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
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:763
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()
LLVM_ABI void printName(raw_ostream &os, unsigned printNameFlags=PrintNameIr, ModuleSlotTracker *moduleSlotTracker=nullptr) const
Print the basic block's name as:
MachineInstrBundleIterator< MachineInstr > iterator
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
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 & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate 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.
mop_range operands()
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.
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
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
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
bool isReg() const
isReg - Tests if this is a MO_Register operand.
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
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition Pass.cpp:140
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
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static bool isCBranchVCCZRead(const MachineInstr &MI)
static bool isDS(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 usesASYNC_CNT(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:882
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 encodeFieldVaVdst(unsigned Encoded, unsigned VaVdst)
unsigned encodeFieldVmVsrc(unsigned Encoded, unsigned VmVsrc)
unsigned decodeFieldVaVdst(unsigned Encoded)
int getDefaultDepCtrEncoding(const MCSubtargetInfo &STI)
unsigned decodeFieldVmVsrc(unsigned Encoded)
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...
bool isDPMACCInstruction(unsigned Opc)
iota_range< InstCounterType > inst_counter_types(InstCounterType MaxCounter)
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.
Waitcnt decodeStorecntDscnt(const IsaVersion &Version, unsigned StorecntDscnt)
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)
static unsigned encodeLoadcntDscnt(const IsaVersion &Version, unsigned Loadcnt, unsigned Dscnt)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
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
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto seq_inclusive(T Begin, T End)
Iterate over an integral type from Begin to End inclusive.
Definition Sequence.h:325
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:1739
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.
APInt operator&(APInt a, const APInt &b)
Definition APInt.h:2138
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.
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2128
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2313
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2173
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
char & SIInsertWaitcntsID
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:157
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
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:163
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
bool operator&=(SparseBitVector< ElementSize > *LHS, const SparseBitVector< ElementSize > &RHS)
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
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool operator|=(SparseBitVector< ElementSize > &LHS, const SparseBitVector< ElementSize > *RHS)
APInt operator|(APInt a, const APInt &b)
Definition APInt.h:2158
FunctionPass * createSIInsertWaitcntsPass()
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
static constexpr ValueType Default
static constexpr uint64_t encode(Fields... Values)
Represents the hardware counter limits for different wait count types.
Instruction set architecture version.