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