aco: fix typo in insert_waitcnt's kill()
[mesa.git] / src / amd / compiler / aco_insert_waitcnt.cpp
1 /*
2 * Copyright © 2018 Valve Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 */
24
25 #include <algorithm>
26 #include <map>
27 #include <stack>
28 #include <math.h>
29
30 #include "aco_ir.h"
31 #include "vulkan/radv_shader.h"
32
33 namespace aco {
34
35 namespace {
36
37 /**
38 * The general idea of this pass is:
39 * The CFG is traversed in reverse postorder (forward) and loops are processed
40 * several times until no progress is made.
41 * Per BB two wait_ctx is maintained: an in-context and out-context.
42 * The in-context is the joined out-contexts of the predecessors.
43 * The context contains a map: gpr -> wait_entry
44 * consisting of the information about the cnt values to be waited for.
45 * Note: After merge-nodes, it might occur that for the same register
46 * multiple cnt values are to be waited for.
47 *
48 * The values are updated according to the encountered instructions:
49 * - additional events increment the counter of waits of the same type
50 * - or erase gprs with counters higher than to be waited for.
51 */
52
53 // TODO: do a more clever insertion of wait_cnt (lgkm_cnt) when there is a load followed by a use of a previous load
54
55 /* Instructions of the same event will finish in-order except for smem
56 * and maybe flat. Instructions of different events may not finish in-order. */
57 enum wait_event : uint16_t {
58 event_smem = 1 << 0,
59 event_lds = 1 << 1,
60 event_gds = 1 << 2,
61 event_vmem = 1 << 3,
62 event_vmem_store = 1 << 4, /* GFX10+ */
63 event_flat = 1 << 5,
64 event_exp_pos = 1 << 6,
65 event_exp_param = 1 << 7,
66 event_exp_mrt_null = 1 << 8,
67 event_gds_gpr_lock = 1 << 9,
68 event_vmem_gpr_lock = 1 << 10,
69 event_sendmsg = 1 << 11,
70 num_events = 12,
71 };
72
73 enum counter_type : uint8_t {
74 counter_exp = 1 << 0,
75 counter_lgkm = 1 << 1,
76 counter_vm = 1 << 2,
77 counter_vs = 1 << 3,
78 num_counters = 4,
79 };
80
81 static const uint16_t exp_events = event_exp_pos | event_exp_param | event_exp_mrt_null | event_gds_gpr_lock | event_vmem_gpr_lock;
82 static const uint16_t lgkm_events = event_smem | event_lds | event_gds | event_flat | event_sendmsg;
83 static const uint16_t vm_events = event_vmem | event_flat;
84 static const uint16_t vs_events = event_vmem_store;
85
86 uint8_t get_counters_for_event(wait_event ev)
87 {
88 switch (ev) {
89 case event_smem:
90 case event_lds:
91 case event_gds:
92 case event_sendmsg:
93 return counter_lgkm;
94 case event_vmem:
95 return counter_vm;
96 case event_vmem_store:
97 return counter_vs;
98 case event_flat:
99 return counter_vm | counter_lgkm;
100 case event_exp_pos:
101 case event_exp_param:
102 case event_exp_mrt_null:
103 case event_gds_gpr_lock:
104 case event_vmem_gpr_lock:
105 return counter_exp;
106 default:
107 return 0;
108 }
109 }
110
111 uint16_t get_events_for_counter(counter_type ctr)
112 {
113 switch (ctr) {
114 case counter_exp:
115 return exp_events;
116 case counter_lgkm:
117 return lgkm_events;
118 case counter_vm:
119 return vm_events;
120 case counter_vs:
121 return vs_events;
122 }
123 return 0;
124 }
125
126 struct wait_imm {
127 static const uint8_t unset_counter = 0xff;
128
129 uint8_t vm;
130 uint8_t exp;
131 uint8_t lgkm;
132 uint8_t vs;
133
134 wait_imm() :
135 vm(unset_counter), exp(unset_counter), lgkm(unset_counter), vs(unset_counter) {}
136 wait_imm(uint16_t vm_, uint16_t exp_, uint16_t lgkm_, uint16_t vs_) :
137 vm(vm_), exp(exp_), lgkm(lgkm_), vs(vs_) {}
138
139 wait_imm(enum chip_class chip, uint16_t packed) : vs(unset_counter)
140 {
141 vm = packed & 0xf;
142 if (chip >= GFX9)
143 vm |= (packed >> 10) & 0x30;
144
145 exp = (packed >> 4) & 0x7;
146
147 lgkm = (packed >> 8) & 0xf;
148 if (chip >= GFX10)
149 lgkm |= (packed >> 8) & 0x30;
150 }
151
152 uint16_t pack(enum chip_class chip) const
153 {
154 uint16_t imm = 0;
155 assert(exp == unset_counter || exp <= 0x7);
156 switch (chip) {
157 case GFX10:
158 assert(lgkm == unset_counter || lgkm <= 0x3f);
159 assert(vm == unset_counter || vm <= 0x3f);
160 imm = ((vm & 0x30) << 10) | ((lgkm & 0x3f) << 8) | ((exp & 0x7) << 4) | (vm & 0xf);
161 break;
162 case GFX9:
163 assert(lgkm == unset_counter || lgkm <= 0xf);
164 assert(vm == unset_counter || vm <= 0x3f);
165 imm = ((vm & 0x30) << 10) | ((lgkm & 0xf) << 8) | ((exp & 0x7) << 4) | (vm & 0xf);
166 break;
167 default:
168 assert(lgkm == unset_counter || lgkm <= 0xf);
169 assert(vm == unset_counter || vm <= 0xf);
170 imm = ((lgkm & 0xf) << 8) | ((exp & 0x7) << 4) | (vm & 0xf);
171 break;
172 }
173 if (chip < GFX9 && vm == wait_imm::unset_counter)
174 imm |= 0xc000; /* should have no effect on pre-GFX9 and now we won't have to worry about the architecture when interpreting the immediate */
175 if (chip < GFX10 && lgkm == wait_imm::unset_counter)
176 imm |= 0x3000; /* should have no effect on pre-GFX10 and now we won't have to worry about the architecture when interpreting the immediate */
177 return imm;
178 }
179
180 bool combine(const wait_imm& other)
181 {
182 bool changed = other.vm < vm || other.exp < exp || other.lgkm < lgkm || other.vs < vs;
183 vm = std::min(vm, other.vm);
184 exp = std::min(exp, other.exp);
185 lgkm = std::min(lgkm, other.lgkm);
186 vs = std::min(vs, other.vs);
187 return changed;
188 }
189
190 bool empty() const
191 {
192 return vm == unset_counter && exp == unset_counter &&
193 lgkm == unset_counter && vs == unset_counter;
194 }
195 };
196
197 struct wait_entry {
198 wait_imm imm;
199 uint16_t events; /* use wait_event notion */
200 uint8_t counters; /* use counter_type notion */
201 bool wait_on_read:1;
202 bool logical:1;
203 bool has_vmem_nosampler:1;
204 bool has_vmem_sampler:1;
205
206 wait_entry(wait_event event, wait_imm imm, bool logical, bool wait_on_read)
207 : imm(imm), events(event), counters(get_counters_for_event(event)),
208 wait_on_read(wait_on_read), logical(logical),
209 has_vmem_nosampler(false), has_vmem_sampler(false) {}
210
211 bool join(const wait_entry& other)
212 {
213 bool changed = (other.events & ~events) ||
214 (other.counters & ~counters) ||
215 (other.wait_on_read && !wait_on_read) ||
216 (other.has_vmem_nosampler && !has_vmem_nosampler) ||
217 (other.has_vmem_sampler && !has_vmem_sampler);
218 events |= other.events;
219 counters |= other.counters;
220 changed |= imm.combine(other.imm);
221 wait_on_read |= other.wait_on_read;
222 has_vmem_nosampler |= other.has_vmem_nosampler;
223 has_vmem_sampler |= other.has_vmem_sampler;
224 assert(logical == other.logical);
225 return changed;
226 }
227
228 void remove_counter(counter_type counter)
229 {
230 counters &= ~counter;
231
232 if (counter == counter_lgkm) {
233 imm.lgkm = wait_imm::unset_counter;
234 events &= ~(event_smem | event_lds | event_gds | event_sendmsg);
235 }
236
237 if (counter == counter_vm) {
238 imm.vm = wait_imm::unset_counter;
239 events &= ~event_vmem;
240 has_vmem_nosampler = false;
241 has_vmem_sampler = false;
242 }
243
244 if (counter == counter_exp) {
245 imm.exp = wait_imm::unset_counter;
246 events &= ~(event_exp_pos | event_exp_param | event_exp_mrt_null | event_gds_gpr_lock | event_vmem_gpr_lock);
247 }
248
249 if (counter == counter_vs) {
250 imm.vs = wait_imm::unset_counter;
251 events &= ~event_vmem_store;
252 }
253
254 if (!(counters & counter_lgkm) && !(counters & counter_vm))
255 events &= ~event_flat;
256 }
257 };
258
259 struct wait_ctx {
260 Program *program;
261 enum chip_class chip_class;
262 uint16_t max_vm_cnt;
263 uint16_t max_exp_cnt;
264 uint16_t max_lgkm_cnt;
265 uint16_t max_vs_cnt;
266 uint16_t unordered_events = event_smem | event_flat;
267
268 uint8_t vm_cnt = 0;
269 uint8_t exp_cnt = 0;
270 uint8_t lgkm_cnt = 0;
271 uint8_t vs_cnt = 0;
272 bool pending_flat_lgkm = false;
273 bool pending_flat_vm = false;
274 bool pending_s_buffer_store = false; /* GFX10 workaround */
275
276 wait_imm barrier_imm[barrier_count];
277 uint16_t barrier_events[barrier_count] = {}; /* use wait_event notion */
278
279 std::map<PhysReg,wait_entry> gpr_map;
280
281 /* used for vmem/smem scores */
282 bool collect_statistics;
283 Instruction *gen_instr;
284 std::map<Instruction *, unsigned> unwaited_instrs[num_counters];
285 std::map<PhysReg,std::set<Instruction *>> reg_instrs[num_counters];
286 std::vector<unsigned> wait_distances[num_events];
287
288 wait_ctx() {}
289 wait_ctx(Program *program_)
290 : program(program_),
291 chip_class(program_->chip_class),
292 max_vm_cnt(program_->chip_class >= GFX9 ? 62 : 14),
293 max_exp_cnt(6),
294 max_lgkm_cnt(program_->chip_class >= GFX10 ? 62 : 14),
295 max_vs_cnt(program_->chip_class >= GFX10 ? 62 : 0),
296 unordered_events(event_smem | (program_->chip_class < GFX10 ? event_flat : 0)) {}
297
298 bool join(const wait_ctx* other, bool logical)
299 {
300 bool changed = other->exp_cnt > exp_cnt ||
301 other->vm_cnt > vm_cnt ||
302 other->lgkm_cnt > lgkm_cnt ||
303 other->vs_cnt > vs_cnt ||
304 (other->pending_flat_lgkm && !pending_flat_lgkm) ||
305 (other->pending_flat_vm && !pending_flat_vm);
306
307 exp_cnt = std::max(exp_cnt, other->exp_cnt);
308 vm_cnt = std::max(vm_cnt, other->vm_cnt);
309 lgkm_cnt = std::max(lgkm_cnt, other->lgkm_cnt);
310 vs_cnt = std::max(vs_cnt, other->vs_cnt);
311 pending_flat_lgkm |= other->pending_flat_lgkm;
312 pending_flat_vm |= other->pending_flat_vm;
313 pending_s_buffer_store |= other->pending_s_buffer_store;
314
315 for (std::pair<PhysReg,wait_entry> entry : other->gpr_map)
316 {
317 std::map<PhysReg,wait_entry>::iterator it = gpr_map.find(entry.first);
318 if (entry.second.logical != logical)
319 continue;
320
321 if (it != gpr_map.end()) {
322 changed |= it->second.join(entry.second);
323 } else {
324 gpr_map.insert(entry);
325 changed = true;
326 }
327 }
328
329 for (unsigned i = 0; i < barrier_count; i++) {
330 changed |= barrier_imm[i].combine(other->barrier_imm[i]);
331 changed |= other->barrier_events[i] & ~barrier_events[i];
332 barrier_events[i] |= other->barrier_events[i];
333 }
334
335 /* these are used for statistics, so don't update "changed" */
336 for (unsigned i = 0; i < num_counters; i++) {
337 for (std::pair<Instruction *, unsigned> instr : other->unwaited_instrs[i]) {
338 auto pos = unwaited_instrs[i].find(instr.first);
339 if (pos == unwaited_instrs[i].end())
340 unwaited_instrs[i].insert(instr);
341 else
342 pos->second = std::min(pos->second, instr.second);
343 }
344 /* don't use a foreach loop to avoid copies */
345 for (auto it = other->reg_instrs[i].begin(); it != other->reg_instrs[i].end(); ++it)
346 reg_instrs[i][it->first].insert(it->second.begin(), it->second.end());
347 }
348
349 return changed;
350 }
351
352 void wait_and_remove_from_entry(PhysReg reg, wait_entry& entry, counter_type counter) {
353 if (collect_statistics && (entry.counters & counter)) {
354 unsigned counter_idx = ffs(counter) - 1;
355 for (Instruction *instr : reg_instrs[counter_idx][reg]) {
356 auto pos = unwaited_instrs[counter_idx].find(instr);
357 if (pos == unwaited_instrs[counter_idx].end())
358 continue;
359
360 unsigned distance = pos->second;
361 unsigned events = entry.events & get_events_for_counter(counter);
362 while (events) {
363 unsigned event_idx = u_bit_scan(&events);
364 wait_distances[event_idx].push_back(distance);
365 }
366
367 unwaited_instrs[counter_idx].erase(instr);
368 }
369 reg_instrs[counter_idx][reg].clear();
370 }
371
372 entry.remove_counter(counter);
373 }
374
375 void advance_unwaited_instrs()
376 {
377 for (unsigned i = 0; i < num_counters; i++) {
378 for (auto it = unwaited_instrs[i].begin(); it != unwaited_instrs[i].end(); ++it)
379 it->second++;
380 }
381 }
382 };
383
384 wait_imm check_instr(Instruction* instr, wait_ctx& ctx)
385 {
386 wait_imm wait;
387
388 for (const Operand op : instr->operands) {
389 if (op.isConstant() || op.isUndefined())
390 continue;
391
392 /* check consecutively read gprs */
393 for (unsigned j = 0; j < op.size(); j++) {
394 PhysReg reg{op.physReg() + j};
395 std::map<PhysReg,wait_entry>::iterator it = ctx.gpr_map.find(reg);
396 if (it == ctx.gpr_map.end() || !it->second.wait_on_read)
397 continue;
398
399 wait.combine(it->second.imm);
400 }
401 }
402
403 for (const Definition& def : instr->definitions) {
404 /* check consecutively written gprs */
405 for (unsigned j = 0; j < def.getTemp().size(); j++)
406 {
407 PhysReg reg{def.physReg() + j};
408
409 std::map<PhysReg,wait_entry>::iterator it = ctx.gpr_map.find(reg);
410 if (it == ctx.gpr_map.end())
411 continue;
412
413 /* Vector Memory reads and writes return in the order they were issued */
414 bool has_sampler = instr->format == Format::MIMG && !instr->operands[1].isUndefined() && instr->operands[1].regClass() == s4;
415 if (instr->isVMEM() && ((it->second.events & vm_events) == event_vmem) &&
416 it->second.has_vmem_nosampler == !has_sampler && it->second.has_vmem_sampler == has_sampler)
417 continue;
418
419 /* LDS reads and writes return in the order they were issued. same for GDS */
420 if (instr->format == Format::DS) {
421 bool gds = static_cast<DS_instruction*>(instr)->gds;
422 if ((it->second.events & lgkm_events) == (gds ? event_gds : event_lds))
423 continue;
424 }
425
426 wait.combine(it->second.imm);
427 }
428 }
429
430 return wait;
431 }
432
433 wait_imm parse_wait_instr(wait_ctx& ctx, Instruction *instr)
434 {
435 if (instr->opcode == aco_opcode::s_waitcnt_vscnt &&
436 instr->definitions[0].physReg() == sgpr_null) {
437 wait_imm imm;
438 imm.vs = std::min<uint8_t>(imm.vs, static_cast<SOPK_instruction*>(instr)->imm);
439 return imm;
440 } else if (instr->opcode == aco_opcode::s_waitcnt) {
441 return wait_imm(ctx.chip_class, static_cast<SOPP_instruction*>(instr)->imm);
442 }
443 return wait_imm();
444 }
445
446 wait_imm kill(Instruction* instr, wait_ctx& ctx)
447 {
448 wait_imm imm;
449 if (ctx.exp_cnt || ctx.vm_cnt || ctx.lgkm_cnt)
450 imm.combine(check_instr(instr, ctx));
451
452 imm.combine(parse_wait_instr(ctx, instr));
453
454
455 /* It's required to wait for scalar stores before "writing back" data.
456 * It shouldn't cost anything anyways since we're about to do s_endpgm.
457 */
458 if (ctx.lgkm_cnt && instr->opcode == aco_opcode::s_dcache_wb) {
459 assert(ctx.chip_class >= GFX8);
460 imm.lgkm = 0;
461 }
462
463 if (ctx.chip_class >= GFX10) {
464 /* GFX10: A store followed by a load at the same address causes a problem because
465 * the load doesn't load the correct values unless we wait for the store first.
466 * This is NOT mitigated by an s_nop.
467 *
468 * TODO: Refine this when we have proper alias analysis.
469 */
470 SMEM_instruction *smem = static_cast<SMEM_instruction *>(instr);
471 if (ctx.pending_s_buffer_store &&
472 !smem->definitions.empty() &&
473 !smem->can_reorder && smem->barrier == barrier_buffer) {
474 imm.lgkm = 0;
475 }
476 }
477
478 if (instr->format == Format::PSEUDO_BARRIER) {
479 switch (instr->opcode) {
480 case aco_opcode::p_memory_barrier_common:
481 imm.combine(ctx.barrier_imm[ffs(barrier_atomic) - 1]);
482 imm.combine(ctx.barrier_imm[ffs(barrier_buffer) - 1]);
483 imm.combine(ctx.barrier_imm[ffs(barrier_image) - 1]);
484 if (ctx.program->workgroup_size > ctx.program->wave_size)
485 imm.combine(ctx.barrier_imm[ffs(barrier_shared) - 1]);
486 break;
487 case aco_opcode::p_memory_barrier_atomic:
488 imm.combine(ctx.barrier_imm[ffs(barrier_atomic) - 1]);
489 break;
490 /* see comment in aco_scheduler.cpp's can_move_instr() on why these barriers are merged */
491 case aco_opcode::p_memory_barrier_buffer:
492 case aco_opcode::p_memory_barrier_image:
493 imm.combine(ctx.barrier_imm[ffs(barrier_buffer) - 1]);
494 imm.combine(ctx.barrier_imm[ffs(barrier_image) - 1]);
495 break;
496 case aco_opcode::p_memory_barrier_shared:
497 if (ctx.program->workgroup_size > ctx.program->wave_size)
498 imm.combine(ctx.barrier_imm[ffs(barrier_shared) - 1]);
499 break;
500 case aco_opcode::p_memory_barrier_gs_data:
501 imm.combine(ctx.barrier_imm[ffs(barrier_gs_data) - 1]);
502 break;
503 case aco_opcode::p_memory_barrier_gs_sendmsg:
504 imm.combine(ctx.barrier_imm[ffs(barrier_gs_sendmsg) - 1]);
505 break;
506 default:
507 assert(false);
508 break;
509 }
510 }
511
512 if (!imm.empty()) {
513 if (ctx.pending_flat_vm && imm.vm != wait_imm::unset_counter)
514 imm.vm = 0;
515 if (ctx.pending_flat_lgkm && imm.lgkm != wait_imm::unset_counter)
516 imm.lgkm = 0;
517
518 /* reset counters */
519 ctx.exp_cnt = std::min(ctx.exp_cnt, imm.exp);
520 ctx.vm_cnt = std::min(ctx.vm_cnt, imm.vm);
521 ctx.lgkm_cnt = std::min(ctx.lgkm_cnt, imm.lgkm);
522 ctx.vs_cnt = std::min(ctx.vs_cnt, imm.vs);
523
524 /* update barrier wait imms */
525 for (unsigned i = 0; i < barrier_count; i++) {
526 wait_imm& bar = ctx.barrier_imm[i];
527 uint16_t& bar_ev = ctx.barrier_events[i];
528 if (bar.exp != wait_imm::unset_counter && imm.exp <= bar.exp) {
529 bar.exp = wait_imm::unset_counter;
530 bar_ev &= ~exp_events;
531 }
532 if (bar.vm != wait_imm::unset_counter && imm.vm <= bar.vm) {
533 bar.vm = wait_imm::unset_counter;
534 bar_ev &= ~(vm_events & ~event_flat);
535 }
536 if (bar.lgkm != wait_imm::unset_counter && imm.lgkm <= bar.lgkm) {
537 bar.lgkm = wait_imm::unset_counter;
538 bar_ev &= ~(lgkm_events & ~event_flat);
539 }
540 if (bar.vs != wait_imm::unset_counter && imm.vs <= bar.vs) {
541 bar.vs = wait_imm::unset_counter;
542 bar_ev &= ~vs_events;
543 }
544 if (bar.vm == wait_imm::unset_counter && bar.lgkm == wait_imm::unset_counter)
545 bar_ev &= ~event_flat;
546 }
547
548 /* remove all gprs with higher counter from map */
549 std::map<PhysReg,wait_entry>::iterator it = ctx.gpr_map.begin();
550 while (it != ctx.gpr_map.end())
551 {
552 if (imm.exp != wait_imm::unset_counter && imm.exp <= it->second.imm.exp)
553 ctx.wait_and_remove_from_entry(it->first, it->second, counter_exp);
554 if (imm.vm != wait_imm::unset_counter && imm.vm <= it->second.imm.vm)
555 ctx.wait_and_remove_from_entry(it->first, it->second, counter_vm);
556 if (imm.lgkm != wait_imm::unset_counter && imm.lgkm <= it->second.imm.lgkm)
557 ctx.wait_and_remove_from_entry(it->first, it->second, counter_lgkm);
558 if (imm.vs != wait_imm::unset_counter && imm.vs <= it->second.imm.vs)
559 ctx.wait_and_remove_from_entry(it->first, it->second, counter_vs);
560 if (!it->second.counters)
561 it = ctx.gpr_map.erase(it);
562 else
563 it++;
564 }
565 }
566
567 if (imm.vm == 0)
568 ctx.pending_flat_vm = false;
569 if (imm.lgkm == 0) {
570 ctx.pending_flat_lgkm = false;
571 ctx.pending_s_buffer_store = false;
572 }
573
574 return imm;
575 }
576
577 void update_barrier_counter(uint8_t *ctr, unsigned max)
578 {
579 if (*ctr != wait_imm::unset_counter && *ctr < max)
580 (*ctr)++;
581 }
582
583 void update_barrier_imm(wait_ctx& ctx, uint8_t counters, wait_event event, barrier_interaction barrier)
584 {
585 for (unsigned i = 0; i < barrier_count; i++) {
586 wait_imm& bar = ctx.barrier_imm[i];
587 uint16_t& bar_ev = ctx.barrier_events[i];
588 if (barrier & (1 << i)) {
589 bar_ev |= event;
590 if (counters & counter_lgkm)
591 bar.lgkm = 0;
592 if (counters & counter_vm)
593 bar.vm = 0;
594 if (counters & counter_exp)
595 bar.exp = 0;
596 if (counters & counter_vs)
597 bar.vs = 0;
598 } else if (!(bar_ev & ctx.unordered_events) && !(ctx.unordered_events & event)) {
599 if (counters & counter_lgkm && (bar_ev & lgkm_events) == event)
600 update_barrier_counter(&bar.lgkm, ctx.max_lgkm_cnt);
601 if (counters & counter_vm && (bar_ev & vm_events) == event)
602 update_barrier_counter(&bar.vm, ctx.max_vm_cnt);
603 if (counters & counter_exp && (bar_ev & exp_events) == event)
604 update_barrier_counter(&bar.exp, ctx.max_exp_cnt);
605 if (counters & counter_vs && (bar_ev & vs_events) == event)
606 update_barrier_counter(&bar.vs, ctx.max_vs_cnt);
607 }
608 }
609 }
610
611 void update_counters(wait_ctx& ctx, wait_event event, barrier_interaction barrier=barrier_none)
612 {
613 uint8_t counters = get_counters_for_event(event);
614
615 if (counters & counter_lgkm && ctx.lgkm_cnt <= ctx.max_lgkm_cnt)
616 ctx.lgkm_cnt++;
617 if (counters & counter_vm && ctx.vm_cnt <= ctx.max_vm_cnt)
618 ctx.vm_cnt++;
619 if (counters & counter_exp && ctx.exp_cnt <= ctx.max_exp_cnt)
620 ctx.exp_cnt++;
621 if (counters & counter_vs && ctx.vs_cnt <= ctx.max_vs_cnt)
622 ctx.vs_cnt++;
623
624 update_barrier_imm(ctx, counters, event, barrier);
625
626 if (ctx.unordered_events & event)
627 return;
628
629 if (ctx.pending_flat_lgkm)
630 counters &= ~counter_lgkm;
631 if (ctx.pending_flat_vm)
632 counters &= ~counter_vm;
633
634 for (std::pair<const PhysReg,wait_entry>& e : ctx.gpr_map) {
635 wait_entry& entry = e.second;
636
637 if (entry.events & ctx.unordered_events)
638 continue;
639
640 assert(entry.events);
641
642 if ((counters & counter_exp) && (entry.events & exp_events) == event && entry.imm.exp < ctx.max_exp_cnt)
643 entry.imm.exp++;
644 if ((counters & counter_lgkm) && (entry.events & lgkm_events) == event && entry.imm.lgkm < ctx.max_lgkm_cnt)
645 entry.imm.lgkm++;
646 if ((counters & counter_vm) && (entry.events & vm_events) == event && entry.imm.vm < ctx.max_vm_cnt)
647 entry.imm.vm++;
648 if ((counters & counter_vs) && (entry.events & vs_events) == event && entry.imm.vs < ctx.max_vs_cnt)
649 entry.imm.vs++;
650 }
651 }
652
653 void update_counters_for_flat_load(wait_ctx& ctx, barrier_interaction barrier=barrier_none)
654 {
655 assert(ctx.chip_class < GFX10);
656
657 if (ctx.lgkm_cnt <= ctx.max_lgkm_cnt)
658 ctx.lgkm_cnt++;
659 if (ctx.vm_cnt <= ctx.max_vm_cnt)
660 ctx.vm_cnt++;
661
662 update_barrier_imm(ctx, counter_vm | counter_lgkm, event_flat, barrier);
663
664 for (std::pair<PhysReg,wait_entry> e : ctx.gpr_map)
665 {
666 if (e.second.counters & counter_vm)
667 e.second.imm.vm = 0;
668 if (e.second.counters & counter_lgkm)
669 e.second.imm.lgkm = 0;
670 }
671 ctx.pending_flat_lgkm = true;
672 ctx.pending_flat_vm = true;
673 }
674
675 void insert_wait_entry(wait_ctx& ctx, PhysReg reg, RegClass rc, wait_event event, bool wait_on_read,
676 bool has_sampler=false)
677 {
678 uint16_t counters = get_counters_for_event(event);
679 wait_imm imm;
680 if (counters & counter_lgkm)
681 imm.lgkm = 0;
682 if (counters & counter_vm)
683 imm.vm = 0;
684 if (counters & counter_exp)
685 imm.exp = 0;
686 if (counters & counter_vs)
687 imm.vs = 0;
688
689 wait_entry new_entry(event, imm, !rc.is_linear(), wait_on_read);
690 new_entry.has_vmem_nosampler = (event & event_vmem) && !has_sampler;
691 new_entry.has_vmem_sampler = (event & event_vmem) && has_sampler;
692
693 for (unsigned i = 0; i < rc.size(); i++) {
694 auto it = ctx.gpr_map.emplace(PhysReg{reg.reg()+i}, new_entry);
695 if (!it.second)
696 it.first->second.join(new_entry);
697 }
698
699 if (ctx.collect_statistics) {
700 unsigned counters_todo = counters;
701 while (counters_todo) {
702 unsigned i = u_bit_scan(&counters_todo);
703 ctx.unwaited_instrs[i].insert(std::make_pair(ctx.gen_instr, 0u));
704 for (unsigned j = 0; j < rc.size(); j++)
705 ctx.reg_instrs[i][PhysReg{reg.reg()+j}].insert(ctx.gen_instr);
706 }
707 }
708 }
709
710 void insert_wait_entry(wait_ctx& ctx, Operand op, wait_event event, bool has_sampler=false)
711 {
712 if (!op.isConstant() && !op.isUndefined())
713 insert_wait_entry(ctx, op.physReg(), op.regClass(), event, false, has_sampler);
714 }
715
716 void insert_wait_entry(wait_ctx& ctx, Definition def, wait_event event, bool has_sampler=false)
717 {
718 insert_wait_entry(ctx, def.physReg(), def.regClass(), event, true, has_sampler);
719 }
720
721 void gen(Instruction* instr, wait_ctx& ctx)
722 {
723 switch (instr->format) {
724 case Format::EXP: {
725 Export_instruction* exp_instr = static_cast<Export_instruction*>(instr);
726
727 wait_event ev;
728 if (exp_instr->dest <= 9)
729 ev = event_exp_mrt_null;
730 else if (exp_instr->dest <= 15)
731 ev = event_exp_pos;
732 else
733 ev = event_exp_param;
734 update_counters(ctx, ev);
735
736 /* insert new entries for exported vgprs */
737 for (unsigned i = 0; i < 4; i++)
738 {
739 if (exp_instr->enabled_mask & (1 << i)) {
740 unsigned idx = exp_instr->compressed ? i >> 1 : i;
741 assert(idx < exp_instr->operands.size());
742 insert_wait_entry(ctx, exp_instr->operands[idx], ev);
743
744 }
745 }
746 insert_wait_entry(ctx, exec, s2, ev, false);
747 break;
748 }
749 case Format::FLAT: {
750 if (ctx.chip_class < GFX10 && !instr->definitions.empty())
751 update_counters_for_flat_load(ctx, barrier_buffer);
752 else
753 update_counters(ctx, event_flat, barrier_buffer);
754
755 if (!instr->definitions.empty())
756 insert_wait_entry(ctx, instr->definitions[0], event_flat);
757 break;
758 }
759 case Format::SMEM: {
760 SMEM_instruction *smem = static_cast<SMEM_instruction*>(instr);
761 update_counters(ctx, event_smem, static_cast<SMEM_instruction*>(instr)->barrier);
762
763 if (!instr->definitions.empty())
764 insert_wait_entry(ctx, instr->definitions[0], event_smem);
765 else if (ctx.chip_class >= GFX10 &&
766 !smem->can_reorder &&
767 smem->barrier == barrier_buffer)
768 ctx.pending_s_buffer_store = true;
769
770 break;
771 }
772 case Format::DS: {
773 bool gds = static_cast<DS_instruction*>(instr)->gds;
774 update_counters(ctx, gds ? event_gds : event_lds, gds ? barrier_none : barrier_shared);
775 if (gds)
776 update_counters(ctx, event_gds_gpr_lock);
777
778 if (!instr->definitions.empty())
779 insert_wait_entry(ctx, instr->definitions[0], gds ? event_gds : event_lds);
780
781 if (gds) {
782 for (const Operand& op : instr->operands)
783 insert_wait_entry(ctx, op, event_gds_gpr_lock);
784 insert_wait_entry(ctx, exec, s2, event_gds_gpr_lock, false);
785 }
786 break;
787 }
788 case Format::MUBUF:
789 case Format::MTBUF:
790 case Format::MIMG:
791 case Format::GLOBAL: {
792 wait_event ev = !instr->definitions.empty() || ctx.chip_class < GFX10 ? event_vmem : event_vmem_store;
793 update_counters(ctx, ev, get_barrier_interaction(instr));
794
795 bool has_sampler = instr->format == Format::MIMG && !instr->operands[1].isUndefined() && instr->operands[1].regClass() == s4;
796
797 if (!instr->definitions.empty())
798 insert_wait_entry(ctx, instr->definitions[0], ev, has_sampler);
799
800 if (ctx.chip_class == GFX6 &&
801 instr->format != Format::MIMG &&
802 instr->operands.size() == 4) {
803 ctx.exp_cnt++;
804 update_counters(ctx, event_vmem_gpr_lock);
805 insert_wait_entry(ctx, instr->operands[3], event_vmem_gpr_lock);
806 } else if (ctx.chip_class == GFX6 &&
807 instr->format == Format::MIMG &&
808 instr->operands[1].regClass().type() == RegType::vgpr) {
809 ctx.exp_cnt++;
810 update_counters(ctx, event_vmem_gpr_lock);
811 insert_wait_entry(ctx, instr->operands[1], event_vmem_gpr_lock);
812 }
813
814 break;
815 }
816 case Format::SOPP: {
817 if (instr->opcode == aco_opcode::s_sendmsg ||
818 instr->opcode == aco_opcode::s_sendmsghalt)
819 update_counters(ctx, event_sendmsg, get_barrier_interaction(instr));
820 }
821 default:
822 break;
823 }
824 }
825
826 void emit_waitcnt(wait_ctx& ctx, std::vector<aco_ptr<Instruction>>& instructions, wait_imm imm)
827 {
828 if (imm.vs != wait_imm::unset_counter) {
829 assert(ctx.chip_class >= GFX10);
830 SOPK_instruction* waitcnt_vs = create_instruction<SOPK_instruction>(aco_opcode::s_waitcnt_vscnt, Format::SOPK, 0, 1);
831 waitcnt_vs->definitions[0] = Definition(sgpr_null, s1);
832 waitcnt_vs->imm = imm.vs;
833 instructions.emplace_back(waitcnt_vs);
834 imm.vs = wait_imm::unset_counter;
835 }
836 if (!imm.empty()) {
837 SOPP_instruction* waitcnt = create_instruction<SOPP_instruction>(aco_opcode::s_waitcnt, Format::SOPP, 0, 0);
838 waitcnt->imm = imm.pack(ctx.chip_class);
839 waitcnt->block = -1;
840 instructions.emplace_back(waitcnt);
841 }
842 }
843
844 void handle_block(Program *program, Block& block, wait_ctx& ctx)
845 {
846 std::vector<aco_ptr<Instruction>> new_instructions;
847
848 wait_imm queued_imm;
849
850 ctx.collect_statistics = program->collect_statistics;
851
852 for (aco_ptr<Instruction>& instr : block.instructions) {
853 bool is_wait = !parse_wait_instr(ctx, instr.get()).empty();
854
855 queued_imm.combine(kill(instr.get(), ctx));
856
857 ctx.gen_instr = instr.get();
858 gen(instr.get(), ctx);
859
860 if (instr->format != Format::PSEUDO_BARRIER && !is_wait) {
861 if (!queued_imm.empty()) {
862 emit_waitcnt(ctx, new_instructions, queued_imm);
863 queued_imm = wait_imm();
864 }
865 new_instructions.emplace_back(std::move(instr));
866
867 if (ctx.collect_statistics)
868 ctx.advance_unwaited_instrs();
869 }
870 }
871
872 if (!queued_imm.empty())
873 emit_waitcnt(ctx, new_instructions, queued_imm);
874
875 block.instructions.swap(new_instructions);
876 }
877
878 } /* end namespace */
879
880 static uint32_t calculate_score(std::vector<wait_ctx> &ctx_vec, uint32_t event_mask)
881 {
882 double result = 0.0;
883 unsigned num_waits = 0;
884 while (event_mask) {
885 unsigned event_index = u_bit_scan(&event_mask);
886 for (const wait_ctx &ctx : ctx_vec) {
887 for (unsigned dist : ctx.wait_distances[event_index]) {
888 double score = dist;
889 /* for many events, excessive distances provide little benefit, so
890 * decrease the score in that case. */
891 double threshold = INFINITY;
892 double inv_strength = 0.000001;
893 switch (1 << event_index) {
894 case event_smem:
895 threshold = 70.0;
896 inv_strength = 75.0;
897 break;
898 case event_vmem:
899 case event_vmem_store:
900 case event_flat:
901 threshold = 230.0;
902 inv_strength = 150.0;
903 break;
904 case event_lds:
905 threshold = 16.0;
906 break;
907 default:
908 break;
909 }
910 if (score > threshold) {
911 score -= threshold;
912 score = threshold + score / (1.0 + score / inv_strength);
913 }
914
915 /* we don't want increases in high scores to hide decreases in low scores,
916 * so raise to the power of 0.1 before averaging. */
917 result += pow(score, 0.1);
918 num_waits++;
919 }
920 }
921 }
922 return round(pow(result / num_waits, 10.0) * 10.0);
923 }
924
925 void insert_wait_states(Program* program)
926 {
927 /* per BB ctx */
928 std::vector<bool> done(program->blocks.size());
929 std::vector<wait_ctx> in_ctx(program->blocks.size(), wait_ctx(program));
930 std::vector<wait_ctx> out_ctx(program->blocks.size(), wait_ctx(program));
931
932 std::stack<unsigned> loop_header_indices;
933 unsigned loop_progress = 0;
934
935 for (unsigned i = 0; i < program->blocks.size();) {
936 Block& current = program->blocks[i++];
937 wait_ctx ctx = in_ctx[current.index];
938
939 if (current.kind & block_kind_loop_header) {
940 loop_header_indices.push(current.index);
941 } else if (current.kind & block_kind_loop_exit) {
942 bool repeat = false;
943 if (loop_progress == loop_header_indices.size()) {
944 i = loop_header_indices.top();
945 repeat = true;
946 }
947 loop_header_indices.pop();
948 loop_progress = std::min<unsigned>(loop_progress, loop_header_indices.size());
949 if (repeat)
950 continue;
951 }
952
953 bool changed = false;
954 for (unsigned b : current.linear_preds)
955 changed |= ctx.join(&out_ctx[b], false);
956 for (unsigned b : current.logical_preds)
957 changed |= ctx.join(&out_ctx[b], true);
958
959 if (done[current.index] && !changed) {
960 in_ctx[current.index] = std::move(ctx);
961 continue;
962 } else {
963 in_ctx[current.index] = ctx;
964 }
965
966 if (current.instructions.empty()) {
967 out_ctx[current.index] = std::move(ctx);
968 continue;
969 }
970
971 loop_progress = std::max<unsigned>(loop_progress, current.loop_nest_depth);
972 done[current.index] = true;
973
974 handle_block(program, current, ctx);
975
976 out_ctx[current.index] = std::move(ctx);
977 }
978
979 if (program->collect_statistics) {
980 program->statistics[statistic_vmem_score] =
981 calculate_score(out_ctx, event_vmem | event_flat | event_vmem_store);
982 program->statistics[statistic_smem_score] =
983 calculate_score(out_ctx, event_smem);
984 }
985 }
986
987 }
988