blob: 49e6afaece02684de0ba9abc7c1b4237e4da06e2 [file] [log] [blame]
Eugene Zelenko59e12822017-08-08 00:47:13 +00001//===- SIInsertWaitcnts.cpp - Insert Wait Instructions --------------------===//
Kannan Narayananacb089e2017-04-12 03:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// \brief Insert wait instructions for memory reads and writes.
12///
13/// Memory reads and writes are issued asynchronously, so we need to insert
14/// S_WAITCNT instructions when we want to access any of their results or
15/// overwrite any register that's used asynchronously.
16//
17//===----------------------------------------------------------------------===//
18
19#include "AMDGPU.h"
20#include "AMDGPUSubtarget.h"
21#include "SIDefines.h"
22#include "SIInstrInfo.h"
23#include "SIMachineFunctionInfo.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000024#include "SIRegisterInfo.h"
Kannan Narayananacb089e2017-04-12 03:25:12 +000025#include "Utils/AMDGPUBaseInfo.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/DenseSet.h"
Kannan Narayananacb089e2017-04-12 03:25:12 +000028#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000029#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/CodeGen/MachineBasicBlock.h"
Kannan Narayananacb089e2017-04-12 03:25:12 +000032#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000034#include "llvm/CodeGen/MachineInstr.h"
Kannan Narayananacb089e2017-04-12 03:25:12 +000035#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000036#include "llvm/CodeGen/MachineLoopInfo.h"
37#include "llvm/CodeGen/MachineMemOperand.h"
38#include "llvm/CodeGen/MachineOperand.h"
Kannan Narayananacb089e2017-04-12 03:25:12 +000039#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000040#include "llvm/IR/DebugLoc.h"
41#include "llvm/Pass.h"
42#include "llvm/Support/Debug.h"
Mark Searlesec581832018-04-25 19:21:26 +000043#include "llvm/Support/DebugCounter.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000044#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/raw_ostream.h"
46#include <algorithm>
47#include <cassert>
48#include <cstdint>
49#include <cstring>
50#include <memory>
51#include <utility>
52#include <vector>
Kannan Narayananacb089e2017-04-12 03:25:12 +000053
Mark Searlesec581832018-04-25 19:21:26 +000054using namespace llvm;
55
Kannan Narayananacb089e2017-04-12 03:25:12 +000056#define DEBUG_TYPE "si-insert-waitcnts"
57
Mark Searlesec581832018-04-25 19:21:26 +000058DEBUG_COUNTER(ForceExpCounter, DEBUG_TYPE"-forceexp",
59 "Force emit s_waitcnt expcnt(0) instrs");
60DEBUG_COUNTER(ForceLgkmCounter, DEBUG_TYPE"-forcelgkm",
61 "Force emit s_waitcnt lgkmcnt(0) instrs");
62DEBUG_COUNTER(ForceVMCounter, DEBUG_TYPE"-forcevm",
63 "Force emit s_waitcnt vmcnt(0) instrs");
64
65static cl::opt<unsigned> ForceEmitZeroFlag(
66 "amdgpu-waitcnt-forcezero",
67 cl::desc("Force all waitcnt instrs to be emitted as s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
68 cl::init(0), cl::Hidden);
Kannan Narayananacb089e2017-04-12 03:25:12 +000069
70namespace {
71
72// Class of object that encapsulates latest instruction counter score
73// associated with the operand. Used for determining whether
74// s_waitcnt instruction needs to be emited.
75
76#define CNT_MASK(t) (1u << (t))
77
78enum InstCounterType { VM_CNT = 0, LGKM_CNT, EXP_CNT, NUM_INST_CNTS };
79
Eugene Zelenko59e12822017-08-08 00:47:13 +000080using RegInterval = std::pair<signed, signed>;
Kannan Narayananacb089e2017-04-12 03:25:12 +000081
82struct {
83 int32_t VmcntMax;
84 int32_t ExpcntMax;
85 int32_t LgkmcntMax;
86 int32_t NumVGPRsMax;
87 int32_t NumSGPRsMax;
88} HardwareLimits;
89
90struct {
91 unsigned VGPR0;
92 unsigned VGPRL;
93 unsigned SGPR0;
94 unsigned SGPRL;
95} RegisterEncoding;
96
97enum WaitEventType {
98 VMEM_ACCESS, // vector-memory read & write
99 LDS_ACCESS, // lds read & write
100 GDS_ACCESS, // gds read & write
101 SQ_MESSAGE, // send message
102 SMEM_ACCESS, // scalar-memory read & write
103 EXP_GPR_LOCK, // export holding on its data src
104 GDS_GPR_LOCK, // GDS holding on its data and addr src
105 EXP_POS_ACCESS, // write to export position
106 EXP_PARAM_ACCESS, // write to export parameter
107 VMW_GPR_LOCK, // vector-memory write holding on its data src
108 NUM_WAIT_EVENTS,
109};
110
111// The mapping is:
112// 0 .. SQ_MAX_PGM_VGPRS-1 real VGPRs
113// SQ_MAX_PGM_VGPRS .. NUM_ALL_VGPRS-1 extra VGPR-like slots
114// NUM_ALL_VGPRS .. NUM_ALL_VGPRS+SQ_MAX_PGM_SGPRS-1 real SGPRs
115// We reserve a fixed number of VGPR slots in the scoring tables for
116// special tokens like SCMEM_LDS (needed for buffer load to LDS).
117enum RegisterMapping {
118 SQ_MAX_PGM_VGPRS = 256, // Maximum programmable VGPRs across all targets.
119 SQ_MAX_PGM_SGPRS = 256, // Maximum programmable SGPRs across all targets.
120 NUM_EXTRA_VGPRS = 1, // A reserved slot for DS.
121 EXTRA_VGPR_LDS = 0, // This is a placeholder the Shader algorithm uses.
122 NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_EXTRA_VGPRS, // Where SGPR starts.
123};
124
125#define ForAllWaitEventType(w) \
126 for (enum WaitEventType w = (enum WaitEventType)0; \
127 (w) < (enum WaitEventType)NUM_WAIT_EVENTS; \
128 (w) = (enum WaitEventType)((w) + 1))
129
130// This is a per-basic-block object that maintains current score brackets
Mark Searlesc3c02bd2018-03-14 22:04:32 +0000131// of each wait counter, and a per-register scoreboard for each wait counter.
Kannan Narayananacb089e2017-04-12 03:25:12 +0000132// We also maintain the latest score for every event type that can change the
133// waitcnt in order to know if there are multiple types of events within
134// the brackets. When multiple types of event happen in the bracket,
Mark Searlesc3c02bd2018-03-14 22:04:32 +0000135// wait count may get decreased out of order, therefore we need to put in
Kannan Narayananacb089e2017-04-12 03:25:12 +0000136// "s_waitcnt 0" before use.
137class BlockWaitcntBrackets {
138public:
Eugene Zelenko59e12822017-08-08 00:47:13 +0000139 BlockWaitcntBrackets() {
140 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
141 T = (enum InstCounterType)(T + 1)) {
142 memset(VgprScores[T], 0, sizeof(VgprScores[T]));
143 }
144 }
145
146 ~BlockWaitcntBrackets() = default;
147
Kannan Narayananacb089e2017-04-12 03:25:12 +0000148 static int32_t getWaitCountMax(InstCounterType T) {
149 switch (T) {
150 case VM_CNT:
151 return HardwareLimits.VmcntMax;
152 case LGKM_CNT:
153 return HardwareLimits.LgkmcntMax;
154 case EXP_CNT:
155 return HardwareLimits.ExpcntMax;
156 default:
157 break;
158 }
159 return 0;
Eugene Zelenko59e12822017-08-08 00:47:13 +0000160 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000161
162 void setScoreLB(InstCounterType T, int32_t Val) {
163 assert(T < NUM_INST_CNTS);
164 if (T >= NUM_INST_CNTS)
165 return;
166 ScoreLBs[T] = Val;
Eugene Zelenko59e12822017-08-08 00:47:13 +0000167 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000168
169 void setScoreUB(InstCounterType T, int32_t Val) {
170 assert(T < NUM_INST_CNTS);
171 if (T >= NUM_INST_CNTS)
172 return;
173 ScoreUBs[T] = Val;
174 if (T == EXP_CNT) {
175 int32_t UB = (int)(ScoreUBs[T] - getWaitCountMax(EXP_CNT));
176 if (ScoreLBs[T] < UB)
177 ScoreLBs[T] = UB;
178 }
Eugene Zelenko59e12822017-08-08 00:47:13 +0000179 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000180
181 int32_t getScoreLB(InstCounterType T) {
182 assert(T < NUM_INST_CNTS);
183 if (T >= NUM_INST_CNTS)
184 return 0;
185 return ScoreLBs[T];
Eugene Zelenko59e12822017-08-08 00:47:13 +0000186 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000187
188 int32_t getScoreUB(InstCounterType T) {
189 assert(T < NUM_INST_CNTS);
190 if (T >= NUM_INST_CNTS)
191 return 0;
192 return ScoreUBs[T];
Eugene Zelenko59e12822017-08-08 00:47:13 +0000193 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000194
195 // Mapping from event to counter.
196 InstCounterType eventCounter(WaitEventType E) {
197 switch (E) {
198 case VMEM_ACCESS:
199 return VM_CNT;
200 case LDS_ACCESS:
201 case GDS_ACCESS:
202 case SQ_MESSAGE:
203 case SMEM_ACCESS:
204 return LGKM_CNT;
205 case EXP_GPR_LOCK:
206 case GDS_GPR_LOCK:
207 case VMW_GPR_LOCK:
208 case EXP_POS_ACCESS:
209 case EXP_PARAM_ACCESS:
210 return EXP_CNT;
211 default:
212 llvm_unreachable("unhandled event type");
213 }
214 return NUM_INST_CNTS;
215 }
216
217 void setRegScore(int GprNo, InstCounterType T, int32_t Val) {
218 if (GprNo < NUM_ALL_VGPRS) {
219 if (GprNo > VgprUB) {
220 VgprUB = GprNo;
221 }
222 VgprScores[T][GprNo] = Val;
223 } else {
224 assert(T == LGKM_CNT);
225 if (GprNo - NUM_ALL_VGPRS > SgprUB) {
226 SgprUB = GprNo - NUM_ALL_VGPRS;
227 }
228 SgprScores[GprNo - NUM_ALL_VGPRS] = Val;
229 }
230 }
231
232 int32_t getRegScore(int GprNo, InstCounterType T) {
233 if (GprNo < NUM_ALL_VGPRS) {
234 return VgprScores[T][GprNo];
235 }
236 return SgprScores[GprNo - NUM_ALL_VGPRS];
237 }
238
239 void clear() {
240 memset(ScoreLBs, 0, sizeof(ScoreLBs));
241 memset(ScoreUBs, 0, sizeof(ScoreUBs));
242 memset(EventUBs, 0, sizeof(EventUBs));
243 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
244 T = (enum InstCounterType)(T + 1)) {
245 memset(VgprScores[T], 0, sizeof(VgprScores[T]));
246 }
247 memset(SgprScores, 0, sizeof(SgprScores));
248 }
249
250 RegInterval getRegInterval(const MachineInstr *MI, const SIInstrInfo *TII,
251 const MachineRegisterInfo *MRI,
252 const SIRegisterInfo *TRI, unsigned OpNo,
253 bool Def) const;
254
255 void setExpScore(const MachineInstr *MI, const SIInstrInfo *TII,
256 const SIRegisterInfo *TRI, const MachineRegisterInfo *MRI,
257 unsigned OpNo, int32_t Val);
258
259 void setWaitAtBeginning() { WaitAtBeginning = true; }
260 void clearWaitAtBeginning() { WaitAtBeginning = false; }
261 bool getWaitAtBeginning() const { return WaitAtBeginning; }
262 void setEventUB(enum WaitEventType W, int32_t Val) { EventUBs[W] = Val; }
263 int32_t getMaxVGPR() const { return VgprUB; }
264 int32_t getMaxSGPR() const { return SgprUB; }
Eugene Zelenko59e12822017-08-08 00:47:13 +0000265
Kannan Narayananacb089e2017-04-12 03:25:12 +0000266 int32_t getEventUB(enum WaitEventType W) const {
267 assert(W < NUM_WAIT_EVENTS);
268 return EventUBs[W];
269 }
Eugene Zelenko59e12822017-08-08 00:47:13 +0000270
Kannan Narayananacb089e2017-04-12 03:25:12 +0000271 bool counterOutOfOrder(InstCounterType T);
272 unsigned int updateByWait(InstCounterType T, int ScoreToWait);
273 void updateByEvent(const SIInstrInfo *TII, const SIRegisterInfo *TRI,
274 const MachineRegisterInfo *MRI, WaitEventType E,
275 MachineInstr &MI);
276
Kannan Narayananacb089e2017-04-12 03:25:12 +0000277 bool hasPendingSMEM() const {
278 return (EventUBs[SMEM_ACCESS] > ScoreLBs[LGKM_CNT] &&
279 EventUBs[SMEM_ACCESS] <= ScoreUBs[LGKM_CNT]);
280 }
281
282 bool hasPendingFlat() const {
283 return ((LastFlat[LGKM_CNT] > ScoreLBs[LGKM_CNT] &&
284 LastFlat[LGKM_CNT] <= ScoreUBs[LGKM_CNT]) ||
285 (LastFlat[VM_CNT] > ScoreLBs[VM_CNT] &&
286 LastFlat[VM_CNT] <= ScoreUBs[VM_CNT]));
287 }
288
289 void setPendingFlat() {
290 LastFlat[VM_CNT] = ScoreUBs[VM_CNT];
291 LastFlat[LGKM_CNT] = ScoreUBs[LGKM_CNT];
292 }
293
294 int pendingFlat(InstCounterType Ct) const { return LastFlat[Ct]; }
295
296 void setLastFlat(InstCounterType Ct, int Val) { LastFlat[Ct] = Val; }
297
298 bool getRevisitLoop() const { return RevisitLoop; }
299 void setRevisitLoop(bool RevisitLoopIn) { RevisitLoop = RevisitLoopIn; }
300
301 void setPostOrder(int32_t PostOrderIn) { PostOrder = PostOrderIn; }
302 int32_t getPostOrder() const { return PostOrder; }
303
304 void setWaitcnt(MachineInstr *WaitcntIn) { Waitcnt = WaitcntIn; }
Eugene Zelenko59e12822017-08-08 00:47:13 +0000305 void clearWaitcnt() { Waitcnt = nullptr; }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000306 MachineInstr *getWaitcnt() const { return Waitcnt; }
307
308 bool mixedExpTypes() const { return MixedExpTypes; }
309 void setMixedExpTypes(bool MixedExpTypesIn) {
310 MixedExpTypes = MixedExpTypesIn;
311 }
312
313 void print(raw_ostream &);
314 void dump() { print(dbgs()); }
315
316private:
Eugene Zelenko59e12822017-08-08 00:47:13 +0000317 bool WaitAtBeginning = false;
318 bool RevisitLoop = false;
Eugene Zelenko59e12822017-08-08 00:47:13 +0000319 bool MixedExpTypes = false;
Eugene Zelenko59e12822017-08-08 00:47:13 +0000320 int32_t PostOrder = 0;
321 MachineInstr *Waitcnt = nullptr;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000322 int32_t ScoreLBs[NUM_INST_CNTS] = {0};
323 int32_t ScoreUBs[NUM_INST_CNTS] = {0};
324 int32_t EventUBs[NUM_WAIT_EVENTS] = {0};
325 // Remember the last flat memory operation.
326 int32_t LastFlat[NUM_INST_CNTS] = {0};
327 // wait_cnt scores for every vgpr.
328 // Keep track of the VgprUB and SgprUB to make merge at join efficient.
Eugene Zelenko59e12822017-08-08 00:47:13 +0000329 int32_t VgprUB = 0;
330 int32_t SgprUB = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000331 int32_t VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS];
332 // Wait cnt scores for every sgpr, only lgkmcnt is relevant.
333 int32_t SgprScores[SQ_MAX_PGM_SGPRS] = {0};
334};
335
336// This is a per-loop-region object that records waitcnt status at the end of
337// loop footer from the previous iteration. We also maintain an iteration
338// count to track the number of times the loop has been visited. When it
339// doesn't converge naturally, we force convergence by inserting s_waitcnt 0
340// at the end of the loop footer.
341class LoopWaitcntData {
342public:
Eugene Zelenko59e12822017-08-08 00:47:13 +0000343 LoopWaitcntData() = default;
344 ~LoopWaitcntData() = default;
345
Kannan Narayananacb089e2017-04-12 03:25:12 +0000346 void incIterCnt() { IterCnt++; }
347 void resetIterCnt() { IterCnt = 0; }
348 int32_t getIterCnt() { return IterCnt; }
349
Kannan Narayananacb089e2017-04-12 03:25:12 +0000350 void setWaitcnt(MachineInstr *WaitcntIn) { LfWaitcnt = WaitcntIn; }
351 MachineInstr *getWaitcnt() const { return LfWaitcnt; }
352
353 void print() {
354 DEBUG(dbgs() << " iteration " << IterCnt << '\n';);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000355 }
356
357private:
358 // s_waitcnt added at the end of loop footer to stablize wait scores
359 // at the end of the loop footer.
Eugene Zelenko59e12822017-08-08 00:47:13 +0000360 MachineInstr *LfWaitcnt = nullptr;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000361 // Number of iterations the loop has been visited, not including the initial
362 // walk over.
Eugene Zelenko59e12822017-08-08 00:47:13 +0000363 int32_t IterCnt = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000364};
365
366class SIInsertWaitcnts : public MachineFunctionPass {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000367private:
Eugene Zelenko59e12822017-08-08 00:47:13 +0000368 const SISubtarget *ST = nullptr;
369 const SIInstrInfo *TII = nullptr;
370 const SIRegisterInfo *TRI = nullptr;
371 const MachineRegisterInfo *MRI = nullptr;
372 const MachineLoopInfo *MLI = nullptr;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000373 AMDGPU::IsaInfo::IsaVersion IV;
374 AMDGPUAS AMDGPUASI;
375
376 DenseSet<MachineBasicBlock *> BlockVisitedSet;
Mark Searles24c92ee2018-02-07 02:21:21 +0000377 DenseSet<MachineInstr *> TrackedWaitcntSet;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000378 DenseSet<MachineInstr *> VCCZBugHandledSet;
379
380 DenseMap<MachineBasicBlock *, std::unique_ptr<BlockWaitcntBrackets>>
381 BlockWaitcntBracketsMap;
382
Mark Searles1bc6e712018-04-19 15:42:30 +0000383 std::vector<MachineBasicBlock *> BlockWaitcntProcessedSet;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000384
385 DenseMap<MachineLoop *, std::unique_ptr<LoopWaitcntData>> LoopWaitcntDataMap;
386
387 std::vector<std::unique_ptr<BlockWaitcntBrackets>> KillWaitBrackets;
388
Mark Searlesec581832018-04-25 19:21:26 +0000389 bool ForceEmitZeroWaitcnt;
390 bool ForceEmitWaitcnt[NUM_INST_CNTS];
391
Kannan Narayananacb089e2017-04-12 03:25:12 +0000392public:
393 static char ID;
394
Eugene Zelenko59e12822017-08-08 00:47:13 +0000395 SIInsertWaitcnts() : MachineFunctionPass(ID) {}
Kannan Narayananacb089e2017-04-12 03:25:12 +0000396
397 bool runOnMachineFunction(MachineFunction &MF) override;
398
399 StringRef getPassName() const override {
400 return "SI insert wait instructions";
401 }
402
403 void getAnalysisUsage(AnalysisUsage &AU) const override {
404 AU.setPreservesCFG();
405 AU.addRequired<MachineLoopInfo>();
406 MachineFunctionPass::getAnalysisUsage(AU);
407 }
408
409 void addKillWaitBracket(BlockWaitcntBrackets *Bracket) {
410 // The waitcnt information is copied because it changes as the block is
411 // traversed.
Eugene Zelenko59e12822017-08-08 00:47:13 +0000412 KillWaitBrackets.push_back(
413 llvm::make_unique<BlockWaitcntBrackets>(*Bracket));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000414 }
415
Mark Searlesec581832018-04-25 19:21:26 +0000416 bool isForceEmitWaitcnt() const {
417 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
418 T = (enum InstCounterType)(T + 1))
419 if (ForceEmitWaitcnt[T])
420 return true;
421 return false;
422 }
423
424 void setForceEmitWaitcnt() {
425// For non-debug builds, ForceEmitWaitcnt has been initialized to false;
426// For debug builds, get the debug counter info and adjust if need be
427#ifndef NDEBUG
428 if (DebugCounter::isCounterSet(ForceExpCounter) &&
429 DebugCounter::shouldExecute(ForceExpCounter)) {
430 ForceEmitWaitcnt[EXP_CNT] = true;
431 } else {
432 ForceEmitWaitcnt[EXP_CNT] = false;
433 }
434
435 if (DebugCounter::isCounterSet(ForceLgkmCounter) &&
436 DebugCounter::shouldExecute(ForceLgkmCounter)) {
437 ForceEmitWaitcnt[LGKM_CNT] = true;
438 } else {
439 ForceEmitWaitcnt[LGKM_CNT] = false;
440 }
441
442 if (DebugCounter::isCounterSet(ForceVMCounter) &&
443 DebugCounter::shouldExecute(ForceVMCounter)) {
444 ForceEmitWaitcnt[VM_CNT] = true;
445 } else {
446 ForceEmitWaitcnt[VM_CNT] = false;
447 }
448#endif // NDEBUG
449 }
450
Matt Arsenault0ed39d32017-07-21 18:54:54 +0000451 bool mayAccessLDSThroughFlat(const MachineInstr &MI) const;
Mark Searles70901b92018-04-24 15:59:59 +0000452 void generateWaitcntInstBefore(MachineInstr &MI,
Stanislav Mekhanoshindb39b4b2018-02-08 00:18:35 +0000453 BlockWaitcntBrackets *ScoreBrackets);
Mark Searles70901b92018-04-24 15:59:59 +0000454 void updateEventWaitcntAfter(MachineInstr &Inst,
Kannan Narayananacb089e2017-04-12 03:25:12 +0000455 BlockWaitcntBrackets *ScoreBrackets);
456 void mergeInputScoreBrackets(MachineBasicBlock &Block);
Mark Searles1bc6e712018-04-19 15:42:30 +0000457 bool isLoopBottom(const MachineLoop *Loop, const MachineBasicBlock *Block);
458 unsigned countNumBottomBlocks(const MachineLoop *Loop);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000459 void insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block);
460 void insertWaitcntBeforeCF(MachineBasicBlock &Block, MachineInstr *Inst);
Stanislav Mekhanoshinff2763a2018-02-15 22:03:55 +0000461 bool isWaitcntStronger(unsigned LHS, unsigned RHS);
462 unsigned combineWaitcnt(unsigned LHS, unsigned RHS);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000463};
464
Eugene Zelenko59e12822017-08-08 00:47:13 +0000465} // end anonymous namespace
Kannan Narayananacb089e2017-04-12 03:25:12 +0000466
467RegInterval BlockWaitcntBrackets::getRegInterval(const MachineInstr *MI,
468 const SIInstrInfo *TII,
469 const MachineRegisterInfo *MRI,
470 const SIRegisterInfo *TRI,
471 unsigned OpNo,
472 bool Def) const {
473 const MachineOperand &Op = MI->getOperand(OpNo);
474 if (!Op.isReg() || !TRI->isInAllocatableClass(Op.getReg()) ||
475 (Def && !Op.isDef()))
476 return {-1, -1};
477
478 // A use via a PW operand does not need a waitcnt.
479 // A partial write is not a WAW.
480 assert(!Op.getSubReg() || !Op.isUndef());
481
482 RegInterval Result;
483 const MachineRegisterInfo &MRIA = *MRI;
484
485 unsigned Reg = TRI->getEncodingValue(Op.getReg());
486
487 if (TRI->isVGPR(MRIA, Op.getReg())) {
488 assert(Reg >= RegisterEncoding.VGPR0 && Reg <= RegisterEncoding.VGPRL);
489 Result.first = Reg - RegisterEncoding.VGPR0;
490 assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS);
491 } else if (TRI->isSGPRReg(MRIA, Op.getReg())) {
492 assert(Reg >= RegisterEncoding.SGPR0 && Reg < SQ_MAX_PGM_SGPRS);
493 Result.first = Reg - RegisterEncoding.SGPR0 + NUM_ALL_VGPRS;
494 assert(Result.first >= NUM_ALL_VGPRS &&
495 Result.first < SQ_MAX_PGM_SGPRS + NUM_ALL_VGPRS);
496 }
497 // TODO: Handle TTMP
498 // else if (TRI->isTTMP(MRIA, Reg.getReg())) ...
499 else
500 return {-1, -1};
501
502 const MachineInstr &MIA = *MI;
503 const TargetRegisterClass *RC = TII->getOpRegClass(MIA, OpNo);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +0000504 unsigned Size = TRI->getRegSizeInBits(*RC);
505 Result.second = Result.first + (Size / 32);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000506
507 return Result;
508}
509
510void BlockWaitcntBrackets::setExpScore(const MachineInstr *MI,
511 const SIInstrInfo *TII,
512 const SIRegisterInfo *TRI,
513 const MachineRegisterInfo *MRI,
514 unsigned OpNo, int32_t Val) {
515 RegInterval Interval = getRegInterval(MI, TII, MRI, TRI, OpNo, false);
516 DEBUG({
517 const MachineOperand &Opnd = MI->getOperand(OpNo);
518 assert(TRI->isVGPR(*MRI, Opnd.getReg()));
519 });
520 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
521 setRegScore(RegNo, EXP_CNT, Val);
522 }
523}
524
525void BlockWaitcntBrackets::updateByEvent(const SIInstrInfo *TII,
526 const SIRegisterInfo *TRI,
527 const MachineRegisterInfo *MRI,
528 WaitEventType E, MachineInstr &Inst) {
529 const MachineRegisterInfo &MRIA = *MRI;
530 InstCounterType T = eventCounter(E);
531 int32_t CurrScore = getScoreUB(T) + 1;
532 // EventUB and ScoreUB need to be update regardless if this event changes
533 // the score of a register or not.
534 // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
535 EventUBs[E] = CurrScore;
536 setScoreUB(T, CurrScore);
537
538 if (T == EXP_CNT) {
539 // Check for mixed export types. If they are mixed, then a waitcnt exp(0)
540 // is required.
541 if (!MixedExpTypes) {
542 MixedExpTypes = counterOutOfOrder(EXP_CNT);
543 }
544
545 // Put score on the source vgprs. If this is a store, just use those
546 // specific register(s).
547 if (TII->isDS(Inst) && (Inst.mayStore() || Inst.mayLoad())) {
548 // All GDS operations must protect their address register (same as
549 // export.)
550 if (Inst.getOpcode() != AMDGPU::DS_APPEND &&
551 Inst.getOpcode() != AMDGPU::DS_CONSUME) {
552 setExpScore(
553 &Inst, TII, TRI, MRI,
554 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::addr),
555 CurrScore);
556 }
557 if (Inst.mayStore()) {
558 setExpScore(
559 &Inst, TII, TRI, MRI,
560 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0),
561 CurrScore);
562 if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
563 AMDGPU::OpName::data1) != -1) {
564 setExpScore(&Inst, TII, TRI, MRI,
565 AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
566 AMDGPU::OpName::data1),
567 CurrScore);
568 }
569 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1 &&
570 Inst.getOpcode() != AMDGPU::DS_GWS_INIT &&
571 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_V &&
572 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_BR &&
573 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_P &&
574 Inst.getOpcode() != AMDGPU::DS_GWS_BARRIER &&
575 Inst.getOpcode() != AMDGPU::DS_APPEND &&
576 Inst.getOpcode() != AMDGPU::DS_CONSUME &&
577 Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
578 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
579 const MachineOperand &Op = Inst.getOperand(I);
580 if (Op.isReg() && !Op.isDef() && TRI->isVGPR(MRIA, Op.getReg())) {
581 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
582 }
583 }
584 }
585 } else if (TII->isFLAT(Inst)) {
586 if (Inst.mayStore()) {
587 setExpScore(
588 &Inst, TII, TRI, MRI,
589 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
590 CurrScore);
591 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
592 setExpScore(
593 &Inst, TII, TRI, MRI,
594 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
595 CurrScore);
596 }
597 } else if (TII->isMIMG(Inst)) {
598 if (Inst.mayStore()) {
599 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
600 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
601 setExpScore(
602 &Inst, TII, TRI, MRI,
603 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
604 CurrScore);
605 }
606 } else if (TII->isMTBUF(Inst)) {
607 if (Inst.mayStore()) {
608 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
609 }
610 } else if (TII->isMUBUF(Inst)) {
611 if (Inst.mayStore()) {
612 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
613 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
614 setExpScore(
615 &Inst, TII, TRI, MRI,
616 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
617 CurrScore);
618 }
619 } else {
620 if (TII->isEXP(Inst)) {
621 // For export the destination registers are really temps that
622 // can be used as the actual source after export patching, so
623 // we need to treat them like sources and set the EXP_CNT
624 // score.
625 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
626 MachineOperand &DefMO = Inst.getOperand(I);
627 if (DefMO.isReg() && DefMO.isDef() &&
628 TRI->isVGPR(MRIA, DefMO.getReg())) {
629 setRegScore(TRI->getEncodingValue(DefMO.getReg()), EXP_CNT,
630 CurrScore);
631 }
632 }
633 }
634 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
635 MachineOperand &MO = Inst.getOperand(I);
636 if (MO.isReg() && !MO.isDef() && TRI->isVGPR(MRIA, MO.getReg())) {
637 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
638 }
639 }
640 }
641#if 0 // TODO: check if this is handled by MUBUF code above.
642 } else if (Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORD ||
Evgeny Mankovbf975172017-08-16 16:47:29 +0000643 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX2 ||
644 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX4) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000645 MachineOperand *MO = TII->getNamedOperand(Inst, AMDGPU::OpName::data);
646 unsigned OpNo;//TODO: find the OpNo for this operand;
647 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, OpNo, false);
648 for (signed RegNo = Interval.first; RegNo < Interval.second;
Evgeny Mankovbf975172017-08-16 16:47:29 +0000649 ++RegNo) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000650 setRegScore(RegNo + NUM_ALL_VGPRS, t, CurrScore);
651 }
652#endif
653 } else {
654 // Match the score to the destination registers.
655 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
656 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, I, true);
657 if (T == VM_CNT && Interval.first >= NUM_ALL_VGPRS)
658 continue;
659 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
660 setRegScore(RegNo, T, CurrScore);
661 }
662 }
663 if (TII->isDS(Inst) && Inst.mayStore()) {
664 setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS, T, CurrScore);
665 }
666 }
667}
668
669void BlockWaitcntBrackets::print(raw_ostream &OS) {
670 OS << '\n';
671 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
672 T = (enum InstCounterType)(T + 1)) {
673 int LB = getScoreLB(T);
674 int UB = getScoreUB(T);
675
676 switch (T) {
677 case VM_CNT:
678 OS << " VM_CNT(" << UB - LB << "): ";
679 break;
680 case LGKM_CNT:
681 OS << " LGKM_CNT(" << UB - LB << "): ";
682 break;
683 case EXP_CNT:
684 OS << " EXP_CNT(" << UB - LB << "): ";
685 break;
686 default:
687 OS << " UNKNOWN(" << UB - LB << "): ";
688 break;
689 }
690
691 if (LB < UB) {
692 // Print vgpr scores.
693 for (int J = 0; J <= getMaxVGPR(); J++) {
694 int RegScore = getRegScore(J, T);
695 if (RegScore <= LB)
696 continue;
697 int RelScore = RegScore - LB - 1;
698 if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) {
699 OS << RelScore << ":v" << J << " ";
700 } else {
701 OS << RelScore << ":ds ";
702 }
703 }
704 // Also need to print sgpr scores for lgkm_cnt.
705 if (T == LGKM_CNT) {
706 for (int J = 0; J <= getMaxSGPR(); J++) {
707 int RegScore = getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
708 if (RegScore <= LB)
709 continue;
710 int RelScore = RegScore - LB - 1;
711 OS << RelScore << ":s" << J << " ";
712 }
713 }
714 }
715 OS << '\n';
716 }
717 OS << '\n';
Kannan Narayananacb089e2017-04-12 03:25:12 +0000718}
719
720unsigned int BlockWaitcntBrackets::updateByWait(InstCounterType T,
721 int ScoreToWait) {
722 unsigned int NeedWait = 0;
723 if (ScoreToWait == -1) {
724 // The score to wait is unknown. This implies that it was not encountered
725 // during the path of the CFG walk done during the current traversal but
726 // may be seen on a different path. Emit an s_wait counter with a
727 // conservative value of 0 for the counter.
728 NeedWait = CNT_MASK(T);
729 setScoreLB(T, getScoreUB(T));
730 return NeedWait;
731 }
732
733 // If the score of src_operand falls within the bracket, we need an
734 // s_waitcnt instruction.
735 const int32_t LB = getScoreLB(T);
736 const int32_t UB = getScoreUB(T);
737 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
738 if (T == VM_CNT && hasPendingFlat()) {
739 // If there is a pending FLAT operation, and this is a VM waitcnt,
740 // then we need to force a waitcnt 0 for VM.
741 NeedWait = CNT_MASK(T);
742 setScoreLB(T, getScoreUB(T));
743 } else if (counterOutOfOrder(T)) {
744 // Counter can get decremented out-of-order when there
Mark Searlesc3c02bd2018-03-14 22:04:32 +0000745 // are multiple types event in the bracket. Also emit an s_wait counter
Kannan Narayananacb089e2017-04-12 03:25:12 +0000746 // with a conservative value of 0 for the counter.
747 NeedWait = CNT_MASK(T);
748 setScoreLB(T, getScoreUB(T));
749 } else {
750 NeedWait = CNT_MASK(T);
751 setScoreLB(T, ScoreToWait);
752 }
753 }
754
755 return NeedWait;
756}
757
758// Where there are multiple types of event in the bracket of a counter,
759// the decrement may go out of order.
760bool BlockWaitcntBrackets::counterOutOfOrder(InstCounterType T) {
761 switch (T) {
762 case VM_CNT:
763 return false;
764 case LGKM_CNT: {
765 if (EventUBs[SMEM_ACCESS] > ScoreLBs[LGKM_CNT] &&
766 EventUBs[SMEM_ACCESS] <= ScoreUBs[LGKM_CNT]) {
767 // Scalar memory read always can go out of order.
768 return true;
769 }
770 int NumEventTypes = 0;
771 if (EventUBs[LDS_ACCESS] > ScoreLBs[LGKM_CNT] &&
772 EventUBs[LDS_ACCESS] <= ScoreUBs[LGKM_CNT]) {
773 NumEventTypes++;
774 }
775 if (EventUBs[GDS_ACCESS] > ScoreLBs[LGKM_CNT] &&
776 EventUBs[GDS_ACCESS] <= ScoreUBs[LGKM_CNT]) {
777 NumEventTypes++;
778 }
779 if (EventUBs[SQ_MESSAGE] > ScoreLBs[LGKM_CNT] &&
780 EventUBs[SQ_MESSAGE] <= ScoreUBs[LGKM_CNT]) {
781 NumEventTypes++;
782 }
783 if (NumEventTypes <= 1) {
784 return false;
785 }
786 break;
787 }
788 case EXP_CNT: {
789 // If there has been a mixture of export types, then a waitcnt exp(0) is
790 // required.
791 if (MixedExpTypes)
792 return true;
793 int NumEventTypes = 0;
794 if (EventUBs[EXP_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
795 EventUBs[EXP_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
796 NumEventTypes++;
797 }
798 if (EventUBs[GDS_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
799 EventUBs[GDS_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
800 NumEventTypes++;
801 }
802 if (EventUBs[VMW_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
803 EventUBs[VMW_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
804 NumEventTypes++;
805 }
806 if (EventUBs[EXP_PARAM_ACCESS] > ScoreLBs[EXP_CNT] &&
807 EventUBs[EXP_PARAM_ACCESS] <= ScoreUBs[EXP_CNT]) {
808 NumEventTypes++;
809 }
810
811 if (EventUBs[EXP_POS_ACCESS] > ScoreLBs[EXP_CNT] &&
812 EventUBs[EXP_POS_ACCESS] <= ScoreUBs[EXP_CNT]) {
813 NumEventTypes++;
814 }
815
816 if (NumEventTypes <= 1) {
817 return false;
818 }
819 break;
820 }
821 default:
822 break;
823 }
824 return true;
825}
826
827INITIALIZE_PASS_BEGIN(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
828 false)
829INITIALIZE_PASS_END(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
830 false)
831
832char SIInsertWaitcnts::ID = 0;
833
834char &llvm::SIInsertWaitcntsID = SIInsertWaitcnts::ID;
835
836FunctionPass *llvm::createSIInsertWaitcntsPass() {
837 return new SIInsertWaitcnts();
838}
839
840static bool readsVCCZ(const MachineInstr &MI) {
841 unsigned Opc = MI.getOpcode();
842 return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
843 !MI.getOperand(1).isUndef();
844}
845
Stanislav Mekhanoshinff2763a2018-02-15 22:03:55 +0000846/// \brief Given wait count encodings checks if LHS is stronger than RHS.
847bool SIInsertWaitcnts::isWaitcntStronger(unsigned LHS, unsigned RHS) {
848 if (AMDGPU::decodeVmcnt(IV, LHS) > AMDGPU::decodeVmcnt(IV, RHS))
849 return false;
850 if (AMDGPU::decodeLgkmcnt(IV, LHS) > AMDGPU::decodeLgkmcnt(IV, RHS))
851 return false;
852 if (AMDGPU::decodeExpcnt(IV, LHS) > AMDGPU::decodeExpcnt(IV, RHS))
853 return false;
854 return true;
855}
856
857/// \brief Given wait count encodings create a new encoding which is stronger
858/// or equal to both.
859unsigned SIInsertWaitcnts::combineWaitcnt(unsigned LHS, unsigned RHS) {
860 unsigned VmCnt = std::min(AMDGPU::decodeVmcnt(IV, LHS),
861 AMDGPU::decodeVmcnt(IV, RHS));
862 unsigned LgkmCnt = std::min(AMDGPU::decodeLgkmcnt(IV, LHS),
863 AMDGPU::decodeLgkmcnt(IV, RHS));
864 unsigned ExpCnt = std::min(AMDGPU::decodeExpcnt(IV, LHS),
865 AMDGPU::decodeExpcnt(IV, RHS));
866 return AMDGPU::encodeWaitcnt(IV, VmCnt, ExpCnt, LgkmCnt);
867}
868
Kannan Narayananacb089e2017-04-12 03:25:12 +0000869/// \brief Generate s_waitcnt instruction to be placed before cur_Inst.
870/// Instructions of a given type are returned in order,
871/// but instructions of different types can complete out of order.
872/// We rely on this in-order completion
873/// and simply assign a score to the memory access instructions.
874/// We keep track of the active "score bracket" to determine
875/// if an access of a memory read requires an s_waitcnt
876/// and if so what the value of each counter is.
877/// The "score bracket" is bound by the lower bound and upper bound
878/// scores (*_score_LB and *_score_ub respectively).
Mark Searles70901b92018-04-24 15:59:59 +0000879void SIInsertWaitcnts::generateWaitcntInstBefore(
Kannan Narayananacb089e2017-04-12 03:25:12 +0000880 MachineInstr &MI, BlockWaitcntBrackets *ScoreBrackets) {
881 // To emit, or not to emit - that's the question!
882 // Start with an assumption that there is no need to emit.
Mark Searles70901b92018-04-24 15:59:59 +0000883 unsigned int EmitWaitcnt = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000884 // No need to wait before phi. If a phi-move exists, then the wait should
885 // has been inserted before the move. If a phi-move does not exist, then
886 // wait should be inserted before the real use. The same is true for
887 // sc-merge. It is not a coincident that all these cases correspond to the
888 // instructions that are skipped in the assembling loop.
889 bool NeedLineMapping = false; // TODO: Check on this.
Mark Searlesec581832018-04-25 19:21:26 +0000890 setForceEmitWaitcnt();
891
892 bool IsForceEmitWaitcnt = isForceEmitWaitcnt();
893
Kannan Narayananacb089e2017-04-12 03:25:12 +0000894 if (MI.isDebugValue() &&
895 // TODO: any other opcode?
896 !NeedLineMapping) {
Stanislav Mekhanoshindb39b4b2018-02-08 00:18:35 +0000897 return;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000898 }
899
900 // See if an s_waitcnt is forced at block entry, or is needed at
901 // program end.
902 if (ScoreBrackets->getWaitAtBeginning()) {
903 // Note that we have already cleared the state, so we don't need to update
904 // it.
905 ScoreBrackets->clearWaitAtBeginning();
906 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
907 T = (enum InstCounterType)(T + 1)) {
Mark Searles70901b92018-04-24 15:59:59 +0000908 EmitWaitcnt |= CNT_MASK(T);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000909 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
910 }
911 }
912
913 // See if this instruction has a forced S_WAITCNT VM.
914 // TODO: Handle other cases of NeedsWaitcntVmBefore()
915 else if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
916 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
917 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL) {
Mark Searles70901b92018-04-24 15:59:59 +0000918 EmitWaitcnt |=
Kannan Narayananacb089e2017-04-12 03:25:12 +0000919 ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
920 }
921
922 // All waits must be resolved at call return.
923 // NOTE: this could be improved with knowledge of all call sites or
924 // with knowledge of the called routines.
925 if (MI.getOpcode() == AMDGPU::RETURN ||
Mark Searles11d0a042017-05-31 16:44:23 +0000926 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
927 MI.getOpcode() == AMDGPU::S_SETPC_B64_return) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000928 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
929 T = (enum InstCounterType)(T + 1)) {
930 if (ScoreBrackets->getScoreUB(T) > ScoreBrackets->getScoreLB(T)) {
931 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
Mark Searles70901b92018-04-24 15:59:59 +0000932 EmitWaitcnt |= CNT_MASK(T);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000933 }
934 }
935 }
936 // Resolve vm waits before gs-done.
937 else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
938 MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
939 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_) ==
940 AMDGPU::SendMsg::ID_GS_DONE)) {
941 if (ScoreBrackets->getScoreUB(VM_CNT) > ScoreBrackets->getScoreLB(VM_CNT)) {
942 ScoreBrackets->setScoreLB(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
Mark Searles70901b92018-04-24 15:59:59 +0000943 EmitWaitcnt |= CNT_MASK(VM_CNT);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000944 }
945 }
946#if 0 // TODO: the following blocks of logic when we have fence.
947 else if (MI.getOpcode() == SC_FENCE) {
948 const unsigned int group_size =
949 context->shader_info->GetMaxThreadGroupSize();
950 // group_size == 0 means thread group size is unknown at compile time
951 const bool group_is_multi_wave =
952 (group_size == 0 || group_size > target_info->GetWaveFrontSize());
953 const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence();
954
955 for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) {
956 SCRegType src_type = Inst->GetSrcType(i);
957 switch (src_type) {
958 case SCMEM_LDS:
959 if (group_is_multi_wave ||
Evgeny Mankovbf975172017-08-16 16:47:29 +0000960 context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) {
Mark Searles70901b92018-04-24 15:59:59 +0000961 EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
Kannan Narayananacb089e2017-04-12 03:25:12 +0000962 ScoreBrackets->getScoreUB(LGKM_CNT));
963 // LDS may have to wait for VM_CNT after buffer load to LDS
964 if (target_info->HasBufferLoadToLDS()) {
Mark Searles70901b92018-04-24 15:59:59 +0000965 EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
Kannan Narayananacb089e2017-04-12 03:25:12 +0000966 ScoreBrackets->getScoreUB(VM_CNT));
967 }
968 }
969 break;
970
971 case SCMEM_GDS:
972 if (group_is_multi_wave || fence_is_global) {
Mark Searles70901b92018-04-24 15:59:59 +0000973 EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000974 ScoreBrackets->getScoreUB(EXP_CNT));
Mark Searles70901b92018-04-24 15:59:59 +0000975 EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000976 ScoreBrackets->getScoreUB(LGKM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000977 }
978 break;
979
980 case SCMEM_UAV:
981 case SCMEM_TFBUF:
982 case SCMEM_RING:
983 case SCMEM_SCATTER:
984 if (group_is_multi_wave || fence_is_global) {
Mark Searles70901b92018-04-24 15:59:59 +0000985 EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000986 ScoreBrackets->getScoreUB(EXP_CNT));
Mark Searles70901b92018-04-24 15:59:59 +0000987 EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000988 ScoreBrackets->getScoreUB(VM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000989 }
990 break;
991
992 case SCMEM_SCRATCH:
993 default:
994 break;
995 }
996 }
997 }
998#endif
999
1000 // Export & GDS instructions do not read the EXEC mask until after the export
1001 // is granted (which can occur well after the instruction is issued).
1002 // The shader program must flush all EXP operations on the export-count
1003 // before overwriting the EXEC mask.
1004 else {
1005 if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
1006 // Export and GDS are tracked individually, either may trigger a waitcnt
1007 // for EXEC.
Mark Searles70901b92018-04-24 15:59:59 +00001008 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001009 EXP_CNT, ScoreBrackets->getEventUB(EXP_GPR_LOCK));
Mark Searles70901b92018-04-24 15:59:59 +00001010 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001011 EXP_CNT, ScoreBrackets->getEventUB(EXP_PARAM_ACCESS));
Mark Searles70901b92018-04-24 15:59:59 +00001012 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001013 EXP_CNT, ScoreBrackets->getEventUB(EXP_POS_ACCESS));
Mark Searles70901b92018-04-24 15:59:59 +00001014 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001015 EXP_CNT, ScoreBrackets->getEventUB(GDS_GPR_LOCK));
1016 }
1017
1018#if 0 // TODO: the following code to handle CALL.
1019 // The argument passing for CALLs should suffice for VM_CNT and LGKM_CNT.
1020 // However, there is a problem with EXP_CNT, because the call cannot
1021 // easily tell if a register is used in the function, and if it did, then
1022 // the referring instruction would have to have an S_WAITCNT, which is
1023 // dependent on all call sites. So Instead, force S_WAITCNT for EXP_CNTs
1024 // before the call.
1025 if (MI.getOpcode() == SC_CALL) {
1026 if (ScoreBrackets->getScoreUB(EXP_CNT) >
Evgeny Mankovbf975172017-08-16 16:47:29 +00001027 ScoreBrackets->getScoreLB(EXP_CNT)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001028 ScoreBrackets->setScoreLB(EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
Mark Searles70901b92018-04-24 15:59:59 +00001029 EmitWaitcnt |= CNT_MASK(EXP_CNT);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001030 }
1031 }
1032#endif
1033
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001034 // FIXME: Should not be relying on memoperands.
Kannan Narayananacb089e2017-04-12 03:25:12 +00001035 // Look at the source operands of every instruction to see if
1036 // any of them results from a previous memory operation that affects
1037 // its current usage. If so, an s_waitcnt instruction needs to be
1038 // emitted.
1039 // If the source operand was defined by a load, add the s_waitcnt
1040 // instruction.
1041 for (const MachineMemOperand *Memop : MI.memoperands()) {
1042 unsigned AS = Memop->getAddrSpace();
1043 if (AS != AMDGPUASI.LOCAL_ADDRESS)
1044 continue;
1045 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
1046 // VM_CNT is only relevant to vgpr or LDS.
Mark Searles70901b92018-04-24 15:59:59 +00001047 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001048 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1049 }
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001050
Kannan Narayananacb089e2017-04-12 03:25:12 +00001051 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1052 const MachineOperand &Op = MI.getOperand(I);
1053 const MachineRegisterInfo &MRIA = *MRI;
1054 RegInterval Interval =
1055 ScoreBrackets->getRegInterval(&MI, TII, MRI, TRI, I, false);
1056 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1057 if (TRI->isVGPR(MRIA, Op.getReg())) {
1058 // VM_CNT is only relevant to vgpr or LDS.
Mark Searles70901b92018-04-24 15:59:59 +00001059 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001060 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1061 }
Mark Searles70901b92018-04-24 15:59:59 +00001062 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001063 LGKM_CNT, ScoreBrackets->getRegScore(RegNo, LGKM_CNT));
1064 }
1065 }
1066 // End of for loop that looks at all source operands to decide vm_wait_cnt
1067 // and lgk_wait_cnt.
1068
1069 // Two cases are handled for destination operands:
1070 // 1) If the destination operand was defined by a load, add the s_waitcnt
1071 // instruction to guarantee the right WAW order.
1072 // 2) If a destination operand that was used by a recent export/store ins,
1073 // add s_waitcnt on exp_cnt to guarantee the WAR order.
1074 if (MI.mayStore()) {
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001075 // FIXME: Should not be relying on memoperands.
Kannan Narayananacb089e2017-04-12 03:25:12 +00001076 for (const MachineMemOperand *Memop : MI.memoperands()) {
1077 unsigned AS = Memop->getAddrSpace();
1078 if (AS != AMDGPUASI.LOCAL_ADDRESS)
1079 continue;
1080 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
Mark Searles70901b92018-04-24 15:59:59 +00001081 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001082 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
Mark Searles70901b92018-04-24 15:59:59 +00001083 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001084 EXP_CNT, ScoreBrackets->getRegScore(RegNo, EXP_CNT));
1085 }
1086 }
1087 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1088 MachineOperand &Def = MI.getOperand(I);
1089 const MachineRegisterInfo &MRIA = *MRI;
1090 RegInterval Interval =
1091 ScoreBrackets->getRegInterval(&MI, TII, MRI, TRI, I, true);
1092 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1093 if (TRI->isVGPR(MRIA, Def.getReg())) {
Mark Searles70901b92018-04-24 15:59:59 +00001094 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001095 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
Mark Searles70901b92018-04-24 15:59:59 +00001096 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001097 EXP_CNT, ScoreBrackets->getRegScore(RegNo, EXP_CNT));
1098 }
Mark Searles70901b92018-04-24 15:59:59 +00001099 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001100 LGKM_CNT, ScoreBrackets->getRegScore(RegNo, LGKM_CNT));
1101 }
1102 } // End of for loop that looks at all dest operands.
1103 }
1104
Kannan Narayananacb089e2017-04-12 03:25:12 +00001105 // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0
1106 // occurs before the instruction. Doing it here prevents any additional
1107 // S_WAITCNTs from being emitted if the instruction was marked as
1108 // requiring a WAITCNT beforehand.
Konstantin Zhuravlyovbe6c0ca2017-06-02 17:40:26 +00001109 if (MI.getOpcode() == AMDGPU::S_BARRIER &&
1110 !ST->hasAutoWaitcntBeforeBarrier()) {
Mark Searles70901b92018-04-24 15:59:59 +00001111 EmitWaitcnt |=
Kannan Narayananacb089e2017-04-12 03:25:12 +00001112 ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
Mark Searles70901b92018-04-24 15:59:59 +00001113 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001114 EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
Mark Searles70901b92018-04-24 15:59:59 +00001115 EmitWaitcnt |= ScoreBrackets->updateByWait(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001116 LGKM_CNT, ScoreBrackets->getScoreUB(LGKM_CNT));
1117 }
1118
1119 // TODO: Remove this work-around, enable the assert for Bug 457939
1120 // after fixing the scheduler. Also, the Shader Compiler code is
1121 // independent of target.
1122 if (readsVCCZ(MI) && ST->getGeneration() <= SISubtarget::SEA_ISLANDS) {
1123 if (ScoreBrackets->getScoreLB(LGKM_CNT) <
1124 ScoreBrackets->getScoreUB(LGKM_CNT) &&
1125 ScoreBrackets->hasPendingSMEM()) {
1126 // Wait on everything, not just LGKM. vccz reads usually come from
1127 // terminators, and we always wait on everything at the end of the
1128 // block, so if we only wait on LGKM here, we might end up with
1129 // another s_waitcnt inserted right after this if there are non-LGKM
1130 // instructions still outstanding.
Mark Searlesec581832018-04-25 19:21:26 +00001131 ForceEmitZeroWaitcnt = true;
Mark Searles70901b92018-04-24 15:59:59 +00001132 EmitWaitcnt = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001133 }
1134 }
1135
1136 // Does this operand processing indicate s_wait counter update?
Mark Searlesec581832018-04-25 19:21:26 +00001137 if (EmitWaitcnt || IsForceEmitWaitcnt) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001138 int CntVal[NUM_INST_CNTS];
1139
1140 bool UseDefaultWaitcntStrategy = true;
Mark Searlesec581832018-04-25 19:21:26 +00001141 if (ForceEmitZeroWaitcnt) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001142 // Force all waitcnts to 0.
1143 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1144 T = (enum InstCounterType)(T + 1)) {
1145 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
1146 }
1147 CntVal[VM_CNT] = 0;
1148 CntVal[EXP_CNT] = 0;
1149 CntVal[LGKM_CNT] = 0;
1150 UseDefaultWaitcntStrategy = false;
1151 }
1152
1153 if (UseDefaultWaitcntStrategy) {
1154 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1155 T = (enum InstCounterType)(T + 1)) {
Mark Searles70901b92018-04-24 15:59:59 +00001156 if (EmitWaitcnt & CNT_MASK(T)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001157 int Delta =
1158 ScoreBrackets->getScoreUB(T) - ScoreBrackets->getScoreLB(T);
1159 int MaxDelta = ScoreBrackets->getWaitCountMax(T);
1160 if (Delta >= MaxDelta) {
1161 Delta = -1;
1162 if (T != EXP_CNT) {
1163 ScoreBrackets->setScoreLB(
1164 T, ScoreBrackets->getScoreUB(T) - MaxDelta);
1165 }
Mark Searles70901b92018-04-24 15:59:59 +00001166 EmitWaitcnt &= ~CNT_MASK(T);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001167 }
1168 CntVal[T] = Delta;
1169 } else {
1170 // If we are not waiting for a particular counter then encode
1171 // it as -1 which means "don't care."
1172 CntVal[T] = -1;
1173 }
1174 }
1175 }
1176
1177 // If we are not waiting on any counter we can skip the wait altogether.
Mark Searlesec581832018-04-25 19:21:26 +00001178 if (EmitWaitcnt != 0 || IsForceEmitWaitcnt) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001179 MachineInstr *OldWaitcnt = ScoreBrackets->getWaitcnt();
1180 int Imm = (!OldWaitcnt) ? 0 : OldWaitcnt->getOperand(0).getImm();
Mark Searles65207922018-02-19 19:19:59 +00001181 if (!OldWaitcnt ||
1182 (AMDGPU::decodeVmcnt(IV, Imm) !=
Kannan Narayananacb089e2017-04-12 03:25:12 +00001183 (CntVal[VM_CNT] & AMDGPU::getVmcntBitMask(IV))) ||
1184 (AMDGPU::decodeExpcnt(IV, Imm) !=
1185 (CntVal[EXP_CNT] & AMDGPU::getExpcntBitMask(IV))) ||
1186 (AMDGPU::decodeLgkmcnt(IV, Imm) !=
1187 (CntVal[LGKM_CNT] & AMDGPU::getLgkmcntBitMask(IV)))) {
1188 MachineLoop *ContainingLoop = MLI->getLoopFor(MI.getParent());
1189 if (ContainingLoop) {
Kannan Narayanan5e73b042017-05-05 21:10:17 +00001190 MachineBasicBlock *TBB = ContainingLoop->getHeader();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001191 BlockWaitcntBrackets *ScoreBracket =
1192 BlockWaitcntBracketsMap[TBB].get();
1193 if (!ScoreBracket) {
Mark Searles24c92ee2018-02-07 02:21:21 +00001194 assert(!BlockVisitedSet.count(TBB));
Eugene Zelenko59e12822017-08-08 00:47:13 +00001195 BlockWaitcntBracketsMap[TBB] =
1196 llvm::make_unique<BlockWaitcntBrackets>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001197 ScoreBracket = BlockWaitcntBracketsMap[TBB].get();
1198 }
1199 ScoreBracket->setRevisitLoop(true);
Mark Searles65207922018-02-19 19:19:59 +00001200 DEBUG(dbgs() << "set-revisit: Block"
Kannan Narayanan5e73b042017-05-05 21:10:17 +00001201 << ContainingLoop->getHeader()->getNumber() << '\n';);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001202 }
1203 }
1204
1205 // Update an existing waitcount, or make a new one.
Mark Searlesec581832018-04-25 19:21:26 +00001206 unsigned Enc = AMDGPU::encodeWaitcnt(IV,
1207 ForceEmitWaitcnt[VM_CNT] ? 0 : CntVal[VM_CNT],
1208 ForceEmitWaitcnt[EXP_CNT] ? 0 : CntVal[EXP_CNT],
1209 ForceEmitWaitcnt[LGKM_CNT] ? 0 : CntVal[LGKM_CNT]);
Mark Searles65207922018-02-19 19:19:59 +00001210 // We don't remove waitcnts that existed prior to the waitcnt
1211 // pass. Check if the waitcnt to-be-inserted can be avoided
1212 // or if the prev waitcnt can be updated.
Stanislav Mekhanoshindb39b4b2018-02-08 00:18:35 +00001213 bool insertSWaitInst = true;
Stanislav Mekhanoshinff2763a2018-02-15 22:03:55 +00001214 for (MachineBasicBlock::iterator I = MI.getIterator(),
1215 B = MI.getParent()->begin();
1216 insertSWaitInst && I != B; --I) {
Mark Searles65207922018-02-19 19:19:59 +00001217 if (I == MI.getIterator())
Stanislav Mekhanoshinff2763a2018-02-15 22:03:55 +00001218 continue;
1219
1220 switch (I->getOpcode()) {
1221 case AMDGPU::S_WAITCNT:
1222 if (isWaitcntStronger(I->getOperand(0).getImm(), Enc))
1223 insertSWaitInst = false;
1224 else if (!OldWaitcnt) {
1225 OldWaitcnt = &*I;
1226 Enc = combineWaitcnt(I->getOperand(0).getImm(), Enc);
1227 }
1228 break;
1229 // TODO: skip over instructions which never require wait.
Stanislav Mekhanoshindb39b4b2018-02-08 00:18:35 +00001230 }
Stanislav Mekhanoshinff2763a2018-02-15 22:03:55 +00001231 break;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001232 }
Stanislav Mekhanoshindb39b4b2018-02-08 00:18:35 +00001233 if (insertSWaitInst) {
1234 if (OldWaitcnt && OldWaitcnt->getOpcode() == AMDGPU::S_WAITCNT) {
Mark Searlesec581832018-04-25 19:21:26 +00001235 if (ForceEmitZeroWaitcnt)
1236 DEBUG(dbgs() << "Force emit s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)\n");
1237 if (IsForceEmitWaitcnt)
1238 DEBUG(dbgs() << "Force emit a s_waitcnt due to debug counter\n");
1239
Stanislav Mekhanoshindb39b4b2018-02-08 00:18:35 +00001240 OldWaitcnt->getOperand(0).setImm(Enc);
Stanislav Mekhanoshinff2763a2018-02-15 22:03:55 +00001241 if (!OldWaitcnt->getParent())
1242 MI.getParent()->insert(MI, OldWaitcnt);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001243
Stanislav Mekhanoshindb39b4b2018-02-08 00:18:35 +00001244 DEBUG(dbgs() << "updateWaitcntInBlock\n"
1245 << "Old Instr: " << MI << '\n'
1246 << "New Instr: " << *OldWaitcnt << '\n');
1247 } else {
1248 auto SWaitInst = BuildMI(*MI.getParent(), MI.getIterator(),
1249 MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1250 .addImm(Enc);
1251 TrackedWaitcntSet.insert(SWaitInst);
1252
1253 DEBUG(dbgs() << "insertWaitcntInBlock\n"
1254 << "Old Instr: " << MI << '\n'
1255 << "New Instr: " << *SWaitInst << '\n');
1256 }
1257 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001258
1259 if (CntVal[EXP_CNT] == 0) {
1260 ScoreBrackets->setMixedExpTypes(false);
1261 }
1262 }
1263 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001264}
1265
1266void SIInsertWaitcnts::insertWaitcntBeforeCF(MachineBasicBlock &MBB,
1267 MachineInstr *Waitcnt) {
1268 if (MBB.empty()) {
1269 MBB.push_back(Waitcnt);
1270 return;
1271 }
1272
1273 MachineBasicBlock::iterator It = MBB.end();
1274 MachineInstr *MI = &*(--It);
1275 if (MI->isBranch()) {
1276 MBB.insert(It, Waitcnt);
1277 } else {
1278 MBB.push_back(Waitcnt);
1279 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001280}
1281
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001282// This is a flat memory operation. Check to see if it has memory
1283// tokens for both LDS and Memory, and if so mark it as a flat.
1284bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
1285 if (MI.memoperands_empty())
1286 return true;
1287
1288 for (const MachineMemOperand *Memop : MI.memoperands()) {
1289 unsigned AS = Memop->getAddrSpace();
1290 if (AS == AMDGPUASI.LOCAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS)
1291 return true;
1292 }
1293
1294 return false;
1295}
1296
Mark Searles70901b92018-04-24 15:59:59 +00001297void SIInsertWaitcnts::updateEventWaitcntAfter(
Kannan Narayananacb089e2017-04-12 03:25:12 +00001298 MachineInstr &Inst, BlockWaitcntBrackets *ScoreBrackets) {
1299 // Now look at the instruction opcode. If it is a memory access
1300 // instruction, update the upper-bound of the appropriate counter's
1301 // bracket and the destination operand scores.
1302 // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere.
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001303 if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001304 if (TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001305 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
1306 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
1307 } else {
1308 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1309 }
1310 } else if (TII->isFLAT(Inst)) {
1311 assert(Inst.mayLoad() || Inst.mayStore());
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001312
1313 if (TII->usesVM_CNT(Inst))
1314 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1315
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001316 if (TII->usesLGKM_CNT(Inst)) {
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001317 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001318
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001319 // This is a flat memory operation, so note it - it will require
1320 // that both the VM and LGKM be flushed to zero if it is pending when
1321 // a VM or LGKM dependency occurs.
1322 if (mayAccessLDSThroughFlat(Inst))
1323 ScoreBrackets->setPendingFlat();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001324 }
1325 } else if (SIInstrInfo::isVMEM(Inst) &&
1326 // TODO: get a better carve out.
1327 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1 &&
1328 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_SC &&
1329 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_VOL) {
1330 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1331 if ( // TODO: assumed yes -- target_info->MemWriteNeedsExpWait() &&
Mark Searles11d0a042017-05-31 16:44:23 +00001332 (Inst.mayStore() || AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001333 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
1334 }
1335 } else if (TII->isSMRD(Inst)) {
1336 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1337 } else {
1338 switch (Inst.getOpcode()) {
1339 case AMDGPU::S_SENDMSG:
1340 case AMDGPU::S_SENDMSGHALT:
1341 ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
1342 break;
1343 case AMDGPU::EXP:
1344 case AMDGPU::EXP_DONE: {
1345 int Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
1346 if (Imm >= 32 && Imm <= 63)
1347 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
1348 else if (Imm >= 12 && Imm <= 15)
1349 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
1350 else
1351 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
1352 break;
1353 }
1354 case AMDGPU::S_MEMTIME:
1355 case AMDGPU::S_MEMREALTIME:
1356 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1357 break;
1358 default:
1359 break;
1360 }
1361 }
1362}
1363
Mark Searlesc3c02bd2018-03-14 22:04:32 +00001364// Merge the score brackets of the Block's predecessors;
1365// this merged score bracket is used when adding waitcnts to the Block
Kannan Narayananacb089e2017-04-12 03:25:12 +00001366void SIInsertWaitcnts::mergeInputScoreBrackets(MachineBasicBlock &Block) {
1367 BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&Block].get();
1368 int32_t MaxPending[NUM_INST_CNTS] = {0};
1369 int32_t MaxFlat[NUM_INST_CNTS] = {0};
1370 bool MixedExpTypes = false;
1371
Mark Searlesc3c02bd2018-03-14 22:04:32 +00001372 // For single basic block loops, we need to retain the Block's
1373 // score bracket to have accurate Pred info. So, make a copy of Block's
1374 // score bracket, clear() it (which retains several important bits of info),
1375 // populate, and then replace en masse. For non-single basic block loops,
1376 // just clear Block's current score bracket and repopulate in-place.
1377 bool IsSelfPred;
1378 std::unique_ptr<BlockWaitcntBrackets> S;
1379
1380 IsSelfPred = (std::find(Block.pred_begin(), Block.pred_end(), &Block))
1381 != Block.pred_end();
1382 if (IsSelfPred) {
1383 S = llvm::make_unique<BlockWaitcntBrackets>(*ScoreBrackets);
1384 ScoreBrackets = S.get();
1385 }
1386
Kannan Narayananacb089e2017-04-12 03:25:12 +00001387 ScoreBrackets->clear();
1388
Kannan Narayananacb089e2017-04-12 03:25:12 +00001389 // See if there are any uninitialized predecessors. If so, emit an
1390 // s_waitcnt 0 at the beginning of the block.
Mark Searlesc3c02bd2018-03-14 22:04:32 +00001391 for (MachineBasicBlock *Pred : Block.predecessors()) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001392 BlockWaitcntBrackets *PredScoreBrackets =
Mark Searlesc3c02bd2018-03-14 22:04:32 +00001393 BlockWaitcntBracketsMap[Pred].get();
1394 bool Visited = BlockVisitedSet.count(Pred);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001395 if (!Visited || PredScoreBrackets->getWaitAtBeginning()) {
Tim Corringham6c6d5e22017-12-04 12:30:49 +00001396 continue;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001397 }
1398 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1399 T = (enum InstCounterType)(T + 1)) {
1400 int span =
1401 PredScoreBrackets->getScoreUB(T) - PredScoreBrackets->getScoreLB(T);
1402 MaxPending[T] = std::max(MaxPending[T], span);
1403 span =
1404 PredScoreBrackets->pendingFlat(T) - PredScoreBrackets->getScoreLB(T);
1405 MaxFlat[T] = std::max(MaxFlat[T], span);
1406 }
1407
1408 MixedExpTypes |= PredScoreBrackets->mixedExpTypes();
1409 }
1410
1411 // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1412 // Also handle kills for exit block.
1413 if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1414 for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1415 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1416 T = (enum InstCounterType)(T + 1)) {
1417 int Span = KillWaitBrackets[I]->getScoreUB(T) -
1418 KillWaitBrackets[I]->getScoreLB(T);
1419 MaxPending[T] = std::max(MaxPending[T], Span);
1420 Span = KillWaitBrackets[I]->pendingFlat(T) -
1421 KillWaitBrackets[I]->getScoreLB(T);
1422 MaxFlat[T] = std::max(MaxFlat[T], Span);
1423 }
1424
1425 MixedExpTypes |= KillWaitBrackets[I]->mixedExpTypes();
1426 }
1427 }
1428
1429 // Special handling for GDS_GPR_LOCK and EXP_GPR_LOCK.
1430 for (MachineBasicBlock *Pred : Block.predecessors()) {
1431 BlockWaitcntBrackets *PredScoreBrackets =
1432 BlockWaitcntBracketsMap[Pred].get();
Mark Searles24c92ee2018-02-07 02:21:21 +00001433 bool Visited = BlockVisitedSet.count(Pred);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001434 if (!Visited || PredScoreBrackets->getWaitAtBeginning()) {
Tim Corringham6c6d5e22017-12-04 12:30:49 +00001435 continue;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001436 }
1437
1438 int GDSSpan = PredScoreBrackets->getEventUB(GDS_GPR_LOCK) -
1439 PredScoreBrackets->getScoreLB(EXP_CNT);
1440 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], GDSSpan);
1441 int EXPSpan = PredScoreBrackets->getEventUB(EXP_GPR_LOCK) -
1442 PredScoreBrackets->getScoreLB(EXP_CNT);
1443 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], EXPSpan);
1444 }
1445
1446 // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1447 if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1448 for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1449 int GDSSpan = KillWaitBrackets[I]->getEventUB(GDS_GPR_LOCK) -
1450 KillWaitBrackets[I]->getScoreLB(EXP_CNT);
1451 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], GDSSpan);
1452 int EXPSpan = KillWaitBrackets[I]->getEventUB(EXP_GPR_LOCK) -
1453 KillWaitBrackets[I]->getScoreLB(EXP_CNT);
1454 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], EXPSpan);
1455 }
1456 }
1457
1458#if 0
1459 // LC does not (unlike) add a waitcnt at beginning. Leaving it as marker.
1460 // TODO: how does LC distinguish between function entry and main entry?
1461 // If this is the entry to a function, force a wait.
1462 MachineBasicBlock &Entry = Block.getParent()->front();
1463 if (Entry.getNumber() == Block.getNumber()) {
1464 ScoreBrackets->setWaitAtBeginning();
1465 return;
1466 }
1467#endif
1468
1469 // Now set the current Block's brackets to the largest ending bracket.
1470 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1471 T = (enum InstCounterType)(T + 1)) {
1472 ScoreBrackets->setScoreUB(T, MaxPending[T]);
1473 ScoreBrackets->setScoreLB(T, 0);
1474 ScoreBrackets->setLastFlat(T, MaxFlat[T]);
1475 }
1476
1477 ScoreBrackets->setMixedExpTypes(MixedExpTypes);
1478
1479 // Set the register scoreboard.
1480 for (MachineBasicBlock *Pred : Block.predecessors()) {
Mark Searles24c92ee2018-02-07 02:21:21 +00001481 if (!BlockVisitedSet.count(Pred)) {
Tim Corringham6c6d5e22017-12-04 12:30:49 +00001482 continue;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001483 }
1484
1485 BlockWaitcntBrackets *PredScoreBrackets =
1486 BlockWaitcntBracketsMap[Pred].get();
1487
1488 // Now merge the gpr_reg_score information
1489 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1490 T = (enum InstCounterType)(T + 1)) {
1491 int PredLB = PredScoreBrackets->getScoreLB(T);
1492 int PredUB = PredScoreBrackets->getScoreUB(T);
1493 if (PredLB < PredUB) {
1494 int PredScale = MaxPending[T] - PredUB;
1495 // Merge vgpr scores.
1496 for (int J = 0; J <= PredScoreBrackets->getMaxVGPR(); J++) {
1497 int PredRegScore = PredScoreBrackets->getRegScore(J, T);
1498 if (PredRegScore <= PredLB)
1499 continue;
1500 int NewRegScore = PredScale + PredRegScore;
1501 ScoreBrackets->setRegScore(
1502 J, T, std::max(ScoreBrackets->getRegScore(J, T), NewRegScore));
1503 }
1504 // Also need to merge sgpr scores for lgkm_cnt.
1505 if (T == LGKM_CNT) {
1506 for (int J = 0; J <= PredScoreBrackets->getMaxSGPR(); J++) {
1507 int PredRegScore =
1508 PredScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
1509 if (PredRegScore <= PredLB)
1510 continue;
1511 int NewRegScore = PredScale + PredRegScore;
1512 ScoreBrackets->setRegScore(
1513 J + NUM_ALL_VGPRS, LGKM_CNT,
1514 std::max(
1515 ScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT),
1516 NewRegScore));
1517 }
1518 }
1519 }
1520 }
1521
1522 // Also merge the WaitEvent information.
1523 ForAllWaitEventType(W) {
1524 enum InstCounterType T = PredScoreBrackets->eventCounter(W);
1525 int PredEventUB = PredScoreBrackets->getEventUB(W);
1526 if (PredEventUB > PredScoreBrackets->getScoreLB(T)) {
1527 int NewEventUB =
1528 MaxPending[T] + PredEventUB - PredScoreBrackets->getScoreUB(T);
1529 if (NewEventUB > 0) {
1530 ScoreBrackets->setEventUB(
1531 W, std::max(ScoreBrackets->getEventUB(W), NewEventUB));
1532 }
1533 }
1534 }
1535 }
1536
1537 // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1538 // Set the register scoreboard.
1539 if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1540 for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1541 // Now merge the gpr_reg_score information.
1542 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1543 T = (enum InstCounterType)(T + 1)) {
1544 int PredLB = KillWaitBrackets[I]->getScoreLB(T);
1545 int PredUB = KillWaitBrackets[I]->getScoreUB(T);
1546 if (PredLB < PredUB) {
1547 int PredScale = MaxPending[T] - PredUB;
1548 // Merge vgpr scores.
1549 for (int J = 0; J <= KillWaitBrackets[I]->getMaxVGPR(); J++) {
1550 int PredRegScore = KillWaitBrackets[I]->getRegScore(J, T);
1551 if (PredRegScore <= PredLB)
1552 continue;
1553 int NewRegScore = PredScale + PredRegScore;
1554 ScoreBrackets->setRegScore(
1555 J, T, std::max(ScoreBrackets->getRegScore(J, T), NewRegScore));
1556 }
1557 // Also need to merge sgpr scores for lgkm_cnt.
1558 if (T == LGKM_CNT) {
1559 for (int J = 0; J <= KillWaitBrackets[I]->getMaxSGPR(); J++) {
1560 int PredRegScore =
1561 KillWaitBrackets[I]->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
1562 if (PredRegScore <= PredLB)
1563 continue;
1564 int NewRegScore = PredScale + PredRegScore;
1565 ScoreBrackets->setRegScore(
1566 J + NUM_ALL_VGPRS, LGKM_CNT,
1567 std::max(
1568 ScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT),
1569 NewRegScore));
1570 }
1571 }
1572 }
1573 }
1574
1575 // Also merge the WaitEvent information.
1576 ForAllWaitEventType(W) {
1577 enum InstCounterType T = KillWaitBrackets[I]->eventCounter(W);
1578 int PredEventUB = KillWaitBrackets[I]->getEventUB(W);
1579 if (PredEventUB > KillWaitBrackets[I]->getScoreLB(T)) {
1580 int NewEventUB =
1581 MaxPending[T] + PredEventUB - KillWaitBrackets[I]->getScoreUB(T);
1582 if (NewEventUB > 0) {
1583 ScoreBrackets->setEventUB(
1584 W, std::max(ScoreBrackets->getEventUB(W), NewEventUB));
1585 }
1586 }
1587 }
1588 }
1589 }
1590
1591 // Special case handling of GDS_GPR_LOCK and EXP_GPR_LOCK. Merge this for the
1592 // sequencing predecessors, because changes to EXEC require waitcnts due to
1593 // the delayed nature of these operations.
1594 for (MachineBasicBlock *Pred : Block.predecessors()) {
Mark Searles24c92ee2018-02-07 02:21:21 +00001595 if (!BlockVisitedSet.count(Pred)) {
Tim Corringham6c6d5e22017-12-04 12:30:49 +00001596 continue;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001597 }
1598
1599 BlockWaitcntBrackets *PredScoreBrackets =
1600 BlockWaitcntBracketsMap[Pred].get();
1601
1602 int pred_gds_ub = PredScoreBrackets->getEventUB(GDS_GPR_LOCK);
1603 if (pred_gds_ub > PredScoreBrackets->getScoreLB(EXP_CNT)) {
1604 int new_gds_ub = MaxPending[EXP_CNT] + pred_gds_ub -
1605 PredScoreBrackets->getScoreUB(EXP_CNT);
1606 if (new_gds_ub > 0) {
1607 ScoreBrackets->setEventUB(
1608 GDS_GPR_LOCK,
1609 std::max(ScoreBrackets->getEventUB(GDS_GPR_LOCK), new_gds_ub));
1610 }
1611 }
1612 int pred_exp_ub = PredScoreBrackets->getEventUB(EXP_GPR_LOCK);
1613 if (pred_exp_ub > PredScoreBrackets->getScoreLB(EXP_CNT)) {
1614 int new_exp_ub = MaxPending[EXP_CNT] + pred_exp_ub -
1615 PredScoreBrackets->getScoreUB(EXP_CNT);
1616 if (new_exp_ub > 0) {
1617 ScoreBrackets->setEventUB(
1618 EXP_GPR_LOCK,
1619 std::max(ScoreBrackets->getEventUB(EXP_GPR_LOCK), new_exp_ub));
1620 }
1621 }
1622 }
Mark Searlesc3c02bd2018-03-14 22:04:32 +00001623
1624 // if a single block loop, update the score brackets. Not needed for other
1625 // blocks, as we did this in-place
1626 if (IsSelfPred) {
1627 BlockWaitcntBracketsMap[&Block] = llvm::make_unique<BlockWaitcntBrackets>(*ScoreBrackets);
1628 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001629}
1630
Mark Searles1bc6e712018-04-19 15:42:30 +00001631/// Return true if the given basic block is a "bottom" block of a loop. This
1632/// differs from MachineLoop::getBottomBlock in that it works even if the loop
1633/// is discontiguous. This also handles multiple back-edges for the same
1634/// "header" block of a loop.
1635bool SIInsertWaitcnts::isLoopBottom(const MachineLoop *Loop,
1636 const MachineBasicBlock *Block) {
1637 for (MachineBasicBlock *MBB : Loop->blocks()) {
1638 if (MBB == Block && MBB->isSuccessor(Loop->getHeader())) {
1639 return true;
1640 }
1641 }
1642 return false;
1643}
1644
1645/// Count the number of "bottom" basic blocks of a loop.
1646unsigned SIInsertWaitcnts::countNumBottomBlocks(const MachineLoop *Loop) {
1647 unsigned Count = 0;
1648 for (MachineBasicBlock *MBB : Loop->blocks()) {
1649 if (MBB->isSuccessor(Loop->getHeader())) {
1650 Count++;
1651 }
1652 }
1653 return Count;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001654}
1655
1656// Generate s_waitcnt instructions where needed.
1657void SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
1658 MachineBasicBlock &Block) {
1659 // Initialize the state information.
1660 mergeInputScoreBrackets(Block);
1661
1662 BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&Block].get();
1663
1664 DEBUG({
Mark Searlesec581832018-04-25 19:21:26 +00001665 dbgs() << "*** Block" << Block.getNumber() << " ***";
Kannan Narayananacb089e2017-04-12 03:25:12 +00001666 ScoreBrackets->dump();
1667 });
1668
Kannan Narayananacb089e2017-04-12 03:25:12 +00001669 // Walk over the instructions.
1670 for (MachineBasicBlock::iterator Iter = Block.begin(), E = Block.end();
1671 Iter != E;) {
1672 MachineInstr &Inst = *Iter;
1673 // Remove any previously existing waitcnts.
1674 if (Inst.getOpcode() == AMDGPU::S_WAITCNT) {
Mark Searles65207922018-02-19 19:19:59 +00001675 // Leave pre-existing waitcnts, but note their existence via setWaitcnt.
1676 // Remove the waitcnt-pass-generated waitcnts; the pass will add them back
1677 // as needed.
Mark Searles24c92ee2018-02-07 02:21:21 +00001678 if (!TrackedWaitcntSet.count(&Inst))
Kannan Narayananacb089e2017-04-12 03:25:12 +00001679 ++Iter;
1680 else {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001681 ++Iter;
1682 Inst.removeFromParent();
1683 }
Mark Searles65207922018-02-19 19:19:59 +00001684 ScoreBrackets->setWaitcnt(&Inst);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001685 continue;
1686 }
1687
1688 // Kill instructions generate a conditional branch to the endmain block.
1689 // Merge the current waitcnt state into the endmain block information.
1690 // TODO: Are there other flavors of KILL instruction?
1691 if (Inst.getOpcode() == AMDGPU::KILL) {
1692 addKillWaitBracket(ScoreBrackets);
1693 }
1694
1695 bool VCCZBugWorkAround = false;
1696 if (readsVCCZ(Inst) &&
Mark Searles24c92ee2018-02-07 02:21:21 +00001697 (!VCCZBugHandledSet.count(&Inst))) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001698 if (ScoreBrackets->getScoreLB(LGKM_CNT) <
1699 ScoreBrackets->getScoreUB(LGKM_CNT) &&
1700 ScoreBrackets->hasPendingSMEM()) {
1701 if (ST->getGeneration() <= SISubtarget::SEA_ISLANDS)
1702 VCCZBugWorkAround = true;
1703 }
1704 }
1705
1706 // Generate an s_waitcnt instruction to be placed before
1707 // cur_Inst, if needed.
Mark Searles70901b92018-04-24 15:59:59 +00001708 generateWaitcntInstBefore(Inst, ScoreBrackets);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001709
Mark Searles70901b92018-04-24 15:59:59 +00001710 updateEventWaitcntAfter(Inst, ScoreBrackets);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001711
1712#if 0 // TODO: implement resource type check controlled by options with ub = LB.
1713 // If this instruction generates a S_SETVSKIP because it is an
1714 // indexed resource, and we are on Tahiti, then it will also force
1715 // an S_WAITCNT vmcnt(0)
1716 if (RequireCheckResourceType(Inst, context)) {
1717 // Force the score to as if an S_WAITCNT vmcnt(0) is emitted.
1718 ScoreBrackets->setScoreLB(VM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +00001719 ScoreBrackets->getScoreUB(VM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +00001720 }
1721#endif
1722
1723 ScoreBrackets->clearWaitcnt();
1724
Kannan Narayananacb089e2017-04-12 03:25:12 +00001725 DEBUG({
Mark Searles94ae3b22018-01-30 17:17:06 +00001726 Inst.print(dbgs());
Kannan Narayananacb089e2017-04-12 03:25:12 +00001727 ScoreBrackets->dump();
1728 });
1729
1730 // Check to see if this is a GWS instruction. If so, and if this is CI or
1731 // VI, then the generated code sequence will include an S_WAITCNT 0.
1732 // TODO: Are these the only GWS instructions?
1733 if (Inst.getOpcode() == AMDGPU::DS_GWS_INIT ||
1734 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_V ||
1735 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_BR ||
1736 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_P ||
1737 Inst.getOpcode() == AMDGPU::DS_GWS_BARRIER) {
1738 // TODO: && context->target_info->GwsRequiresMemViolTest() ) {
1739 ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
1740 ScoreBrackets->updateByWait(EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
1741 ScoreBrackets->updateByWait(LGKM_CNT,
1742 ScoreBrackets->getScoreUB(LGKM_CNT));
1743 }
1744
1745 // TODO: Remove this work-around after fixing the scheduler and enable the
1746 // assert above.
1747 if (VCCZBugWorkAround) {
1748 // Restore the vccz bit. Any time a value is written to vcc, the vcc
1749 // bit is updated, so we can restore the bit by reading the value of
1750 // vcc and then writing it back to the register.
1751 BuildMI(Block, Inst, Inst.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
1752 AMDGPU::VCC)
1753 .addReg(AMDGPU::VCC);
1754 VCCZBugHandledSet.insert(&Inst);
1755 }
1756
Kannan Narayananacb089e2017-04-12 03:25:12 +00001757 ++Iter;
1758 }
1759
1760 // Check if we need to force convergence at loop footer.
1761 MachineLoop *ContainingLoop = MLI->getLoopFor(&Block);
Mark Searles1bc6e712018-04-19 15:42:30 +00001762 if (ContainingLoop && isLoopBottom(ContainingLoop, &Block)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001763 LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1764 WaitcntData->print();
1765 DEBUG(dbgs() << '\n';);
1766
1767 // The iterative waitcnt insertion algorithm aims for optimal waitcnt
1768 // placement and doesn't always guarantee convergence for a loop. Each
1769 // loop should take at most 2 iterations for it to converge naturally.
1770 // When this max is reached and result doesn't converge, we force
1771 // convergence by inserting a s_waitcnt at the end of loop footer.
1772 if (WaitcntData->getIterCnt() > 2) {
1773 // To ensure convergence, need to make wait events at loop footer be no
1774 // more than those from the previous iteration.
Mark Searles65207922018-02-19 19:19:59 +00001775 // As a simplification, instead of tracking individual scores and
1776 // generating the precise wait count, just wait on 0.
Kannan Narayananacb089e2017-04-12 03:25:12 +00001777 bool HasPending = false;
1778 MachineInstr *SWaitInst = WaitcntData->getWaitcnt();
1779 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1780 T = (enum InstCounterType)(T + 1)) {
1781 if (ScoreBrackets->getScoreUB(T) > ScoreBrackets->getScoreLB(T)) {
1782 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
1783 HasPending = true;
1784 }
1785 }
1786
1787 if (HasPending) {
1788 if (!SWaitInst) {
1789 SWaitInst = Block.getParent()->CreateMachineInstr(
1790 TII->get(AMDGPU::S_WAITCNT), DebugLoc());
Mark Searles24c92ee2018-02-07 02:21:21 +00001791 TrackedWaitcntSet.insert(SWaitInst);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001792 const MachineOperand &Op = MachineOperand::CreateImm(0);
1793 SWaitInst->addOperand(MF, Op);
1794#if 0 // TODO: Format the debug output
1795 OutputTransformBanner("insertWaitcntInBlock",0,"Create:",context);
1796 OutputTransformAdd(SWaitInst, context);
1797#endif
1798 }
1799#if 0 // TODO: ??
1800 _DEV( REPORTED_STATS->force_waitcnt_converge = 1; )
1801#endif
1802 }
1803
1804 if (SWaitInst) {
1805 DEBUG({
1806 SWaitInst->print(dbgs());
1807 dbgs() << "\nAdjusted score board:";
1808 ScoreBrackets->dump();
1809 });
1810
1811 // Add this waitcnt to the block. It is either newly created or
1812 // created in previous iterations and added back since block traversal
Mark Searles65207922018-02-19 19:19:59 +00001813 // always removes waitcnts.
Kannan Narayananacb089e2017-04-12 03:25:12 +00001814 insertWaitcntBeforeCF(Block, SWaitInst);
1815 WaitcntData->setWaitcnt(SWaitInst);
1816 }
1817 }
1818 }
1819}
1820
1821bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) {
1822 ST = &MF.getSubtarget<SISubtarget>();
1823 TII = ST->getInstrInfo();
1824 TRI = &TII->getRegisterInfo();
1825 MRI = &MF.getRegInfo();
1826 MLI = &getAnalysis<MachineLoopInfo>();
1827 IV = AMDGPU::IsaInfo::getIsaVersion(ST->getFeatureBits());
Mark Searles11d0a042017-05-31 16:44:23 +00001828 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001829 AMDGPUASI = ST->getAMDGPUAS();
1830
Mark Searlesec581832018-04-25 19:21:26 +00001831 ForceEmitZeroWaitcnt = ForceEmitZeroFlag;
1832 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1833 T = (enum InstCounterType)(T + 1))
1834 ForceEmitWaitcnt[T] = false;
1835
Kannan Narayananacb089e2017-04-12 03:25:12 +00001836 HardwareLimits.VmcntMax = AMDGPU::getVmcntBitMask(IV);
1837 HardwareLimits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
1838 HardwareLimits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV);
1839
1840 HardwareLimits.NumVGPRsMax = ST->getAddressableNumVGPRs();
1841 HardwareLimits.NumSGPRsMax = ST->getAddressableNumSGPRs();
1842 assert(HardwareLimits.NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
1843 assert(HardwareLimits.NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
1844
1845 RegisterEncoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0);
1846 RegisterEncoding.VGPRL =
1847 RegisterEncoding.VGPR0 + HardwareLimits.NumVGPRsMax - 1;
1848 RegisterEncoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0);
1849 RegisterEncoding.SGPRL =
1850 RegisterEncoding.SGPR0 + HardwareLimits.NumSGPRsMax - 1;
1851
Mark Searles24c92ee2018-02-07 02:21:21 +00001852 TrackedWaitcntSet.clear();
1853 BlockVisitedSet.clear();
1854 VCCZBugHandledSet.clear();
Mark Searles1bc6e712018-04-19 15:42:30 +00001855 LoopWaitcntDataMap.clear();
Mark Searles24c92ee2018-02-07 02:21:21 +00001856
Kannan Narayananacb089e2017-04-12 03:25:12 +00001857 // Walk over the blocks in reverse post-dominator order, inserting
1858 // s_waitcnt where needed.
1859 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1860 bool Modified = false;
1861 for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1862 I = RPOT.begin(),
1863 E = RPOT.end(), J = RPOT.begin();
1864 I != E;) {
1865 MachineBasicBlock &MBB = **I;
1866
1867 BlockVisitedSet.insert(&MBB);
1868
1869 BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&MBB].get();
1870 if (!ScoreBrackets) {
Eugene Zelenko59e12822017-08-08 00:47:13 +00001871 BlockWaitcntBracketsMap[&MBB] = llvm::make_unique<BlockWaitcntBrackets>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001872 ScoreBrackets = BlockWaitcntBracketsMap[&MBB].get();
1873 }
1874 ScoreBrackets->setPostOrder(MBB.getNumber());
1875 MachineLoop *ContainingLoop = MLI->getLoopFor(&MBB);
1876 if (ContainingLoop && LoopWaitcntDataMap[ContainingLoop] == nullptr)
Eugene Zelenko59e12822017-08-08 00:47:13 +00001877 LoopWaitcntDataMap[ContainingLoop] = llvm::make_unique<LoopWaitcntData>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001878
1879 // If we are walking into the block from before the loop, then guarantee
1880 // at least 1 re-walk over the loop to propagate the information, even if
1881 // no S_WAITCNT instructions were generated.
Mark Searles1bc6e712018-04-19 15:42:30 +00001882 if (ContainingLoop && ContainingLoop->getHeader() == &MBB) {
1883 unsigned Count = countNumBottomBlocks(ContainingLoop);
1884
1885 // If the loop has multiple back-edges, and so more than one "bottom"
1886 // basic block, we have to guarantee a re-walk over every blocks.
1887 if ((std::count(BlockWaitcntProcessedSet.begin(),
1888 BlockWaitcntProcessedSet.end(), &MBB) < Count)) {
1889 BlockWaitcntBracketsMap[&MBB]->setRevisitLoop(true);
1890 DEBUG(dbgs() << "set-revisit: Block"
1891 << ContainingLoop->getHeader()->getNumber() << '\n';);
1892 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001893 }
1894
1895 // Walk over the instructions.
1896 insertWaitcntInBlock(MF, MBB);
1897
1898 // Flag that waitcnts have been processed at least once.
Mark Searles1bc6e712018-04-19 15:42:30 +00001899 BlockWaitcntProcessedSet.push_back(&MBB);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001900
Mark Searles1bc6e712018-04-19 15:42:30 +00001901 // See if we want to revisit the loop. If a loop has multiple back-edges,
1902 // we shouldn't revisit the same "bottom" basic block.
1903 if (ContainingLoop && isLoopBottom(ContainingLoop, &MBB) &&
1904 std::count(BlockWaitcntProcessedSet.begin(),
1905 BlockWaitcntProcessedSet.end(), &MBB) == 1) {
Kannan Narayanan5e73b042017-05-05 21:10:17 +00001906 MachineBasicBlock *EntryBB = ContainingLoop->getHeader();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001907 BlockWaitcntBrackets *EntrySB = BlockWaitcntBracketsMap[EntryBB].get();
1908 if (EntrySB && EntrySB->getRevisitLoop()) {
1909 EntrySB->setRevisitLoop(false);
1910 J = I;
1911 int32_t PostOrder = EntrySB->getPostOrder();
1912 // TODO: Avoid this loop. Find another way to set I.
1913 for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1914 X = RPOT.begin(),
1915 Y = RPOT.end();
1916 X != Y; ++X) {
1917 MachineBasicBlock &MBBX = **X;
1918 if (MBBX.getNumber() == PostOrder) {
1919 I = X;
1920 break;
1921 }
1922 }
1923 LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1924 WaitcntData->incIterCnt();
Mark Searles65207922018-02-19 19:19:59 +00001925 DEBUG(dbgs() << "revisit: Block" << EntryBB->getNumber() << '\n';);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001926 continue;
1927 } else {
1928 LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1929 // Loop converged, reset iteration count. If this loop gets revisited,
1930 // it must be from an outer loop, the counter will restart, this will
1931 // ensure we don't force convergence on such revisits.
1932 WaitcntData->resetIterCnt();
1933 }
1934 }
1935
1936 J = I;
1937 ++I;
1938 }
1939
1940 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
1941
1942 bool HaveScalarStores = false;
1943
1944 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE;
1945 ++BI) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001946 MachineBasicBlock &MBB = *BI;
1947
1948 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1949 ++I) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001950 if (!HaveScalarStores && TII->isScalarStore(*I))
1951 HaveScalarStores = true;
1952
1953 if (I->getOpcode() == AMDGPU::S_ENDPGM ||
1954 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
1955 EndPgmBlocks.push_back(&MBB);
1956 }
1957 }
1958
1959 if (HaveScalarStores) {
1960 // If scalar writes are used, the cache must be flushed or else the next
1961 // wave to reuse the same scratch memory can be clobbered.
1962 //
1963 // Insert s_dcache_wb at wave termination points if there were any scalar
1964 // stores, and only if the cache hasn't already been flushed. This could be
1965 // improved by looking across blocks for flushes in postdominating blocks
1966 // from the stores but an explicitly requested flush is probably very rare.
1967 for (MachineBasicBlock *MBB : EndPgmBlocks) {
1968 bool SeenDCacheWB = false;
1969
1970 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
1971 ++I) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001972 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
1973 SeenDCacheWB = true;
1974 else if (TII->isScalarStore(*I))
1975 SeenDCacheWB = false;
1976
1977 // FIXME: It would be better to insert this before a waitcnt if any.
1978 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
1979 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
1980 !SeenDCacheWB) {
1981 Modified = true;
1982 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
1983 }
1984 }
1985 }
1986 }
1987
Mark Searles11d0a042017-05-31 16:44:23 +00001988 if (!MFI->isEntryFunction()) {
1989 // Wait for any outstanding memory operations that the input registers may
Hiroshi Inouec8e92452018-01-29 05:17:03 +00001990 // depend on. We can't track them and it's better to the wait after the
Mark Searles11d0a042017-05-31 16:44:23 +00001991 // costly call sequence.
1992
1993 // TODO: Could insert earlier and schedule more liberally with operations
1994 // that only use caller preserved registers.
1995 MachineBasicBlock &EntryBB = MF.front();
1996 BuildMI(EntryBB, EntryBB.getFirstNonPHI(), DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1997 .addImm(0);
1998
1999 Modified = true;
2000 }
2001
Kannan Narayananacb089e2017-04-12 03:25:12 +00002002 return Modified;
2003}