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